From a25f60970d1f2114effdca1a8d1275591d2597d0 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:09:30 +0200 Subject: [PATCH 01/15] Prove per Windows con WebView2 vero, e la prova che riproduce l'avvio mancato MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- Febe.slnx | 1 + src/Febe.Desktop/Febe.Desktop.csproj | 4 + .../Febe.Tests.Windows.csproj | 31 ++++++ tests/Febe.Tests.Windows/MSTestSettings.cs | 2 + .../Febe.Tests.Windows/Support/BrowserBed.cs | 100 ++++++++++++++++++ tests/Febe.Tests.Windows/Support/LogLines.cs | 54 ++++++++++ .../Febe.Tests.Windows/Support/TestFolder.cs | 39 +++++++ tests/Febe.Tests.Windows/Support/UiThread.cs | 55 ++++++++++ .../Support/WebView2Runtime.cs | 39 +++++++ .../WebView2BrowserStartTests.cs | 50 +++++++++ 10 files changed, 375 insertions(+) create mode 100644 tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj create mode 100644 tests/Febe.Tests.Windows/MSTestSettings.cs create mode 100644 tests/Febe.Tests.Windows/Support/BrowserBed.cs create mode 100644 tests/Febe.Tests.Windows/Support/LogLines.cs create mode 100644 tests/Febe.Tests.Windows/Support/TestFolder.cs create mode 100644 tests/Febe.Tests.Windows/Support/UiThread.cs create mode 100644 tests/Febe.Tests.Windows/Support/WebView2Runtime.cs create mode 100644 tests/Febe.Tests.Windows/WebView2BrowserStartTests.cs diff --git a/Febe.slnx b/Febe.slnx index 62cccd4..38a7235 100644 --- a/Febe.slnx +++ b/Febe.slnx @@ -11,6 +11,7 @@ + diff --git a/src/Febe.Desktop/Febe.Desktop.csproj b/src/Febe.Desktop/Febe.Desktop.csproj index d66b943..4e44622 100644 --- a/src/Febe.Desktop/Febe.Desktop.csproj +++ b/src/Febe.Desktop/Febe.Desktop.csproj @@ -38,6 +38,10 @@ + + + + diff --git a/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj b/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj new file mode 100644 index 0000000..404c8cf --- /dev/null +++ b/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj @@ -0,0 +1,31 @@ + + + + net10.0-windows + true + true + false + true + + + + + + + + + + + + + + + + + + + diff --git a/tests/Febe.Tests.Windows/MSTestSettings.cs b/tests/Febe.Tests.Windows/MSTestSettings.cs new file mode 100644 index 0000000..2900593 --- /dev/null +++ b/tests/Febe.Tests.Windows/MSTestSettings.cs @@ -0,0 +1,2 @@ +// One WebView2 at a time: every test starts its own browser process, window and UI thread. +[assembly: DoNotParallelize] diff --git a/tests/Febe.Tests.Windows/Support/BrowserBed.cs b/tests/Febe.Tests.Windows/Support/BrowserBed.cs new file mode 100644 index 0000000..5315764 --- /dev/null +++ b/tests/Febe.Tests.Windows/Support/BrowserBed.cs @@ -0,0 +1,100 @@ +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; + +/// +/// The browser of Febe for Windows on its own, as the composition builds it ( through +/// DesktopShell): a 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. +/// +internal sealed class BrowserBed : IAsyncDisposable +{ + private BrowserBed(TestFolder folder, UiThread ui, LogLines lines, FebeLog log, FebeDatabase database, WebView2Browser browser) + { + Folder = folder; + Ui = ui; + Lines = lines; + Log = log; + Database = database; + Browser = browser; + } + + public TestFolder Folder { get; } + + public UiThread Ui { get; } + + /// What Febe wrote in its log. + public LogLines Lines { get; } + + public FebeLog Log { get; } + + public FebeDatabase Database { get; } + + public WebView2Browser Browser { get; } + + public static async Task 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 context = new FebePlatformContext(options, data, database, clock, log, new BrowserUseTracker()); + 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, browser); + } + + /// + /// Starts the browser from a thread-pool thread, like FebeApp.BringUpBrowserAsync, and waits until + /// returns. Fails at once when the log reports a failed start: the loop of + /// retries would otherwise go on for ever. + /// + 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(); + } + } +} diff --git a/tests/Febe.Tests.Windows/Support/LogLines.cs b/tests/Febe.Tests.Windows/Support/LogLines.cs new file mode 100644 index 0000000..4354225 --- /dev/null +++ b/tests/Febe.Tests.Windows/Support/LogLines.cs @@ -0,0 +1,54 @@ +using System.Text; + +namespace Febe.Tests.Windows.Support; + +/// The «console» of in a test: the lines Alberto would find in his log. +internal sealed class LogLines : TextWriter +{ + private readonly Lock _gate = new(); + private readonly List _lines = []; + private readonly StringBuilder _current = new(); + + public override Encoding Encoding => Encoding.UTF8; + + public IReadOnlyList 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(); + } + } +} diff --git a/tests/Febe.Tests.Windows/Support/TestFolder.cs b/tests/Febe.Tests.Windows/Support/TestFolder.cs new file mode 100644 index 0000000..d121231 --- /dev/null +++ b/tests/Febe.Tests.Windows/Support/TestFolder.cs @@ -0,0 +1,39 @@ +namespace Febe.Tests.Windows.Support; + +/// +/// A temporary folder under (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. +/// +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); + } + } + } +} diff --git a/tests/Febe.Tests.Windows/Support/UiThread.cs b/tests/Febe.Tests.Windows/Support/UiThread.cs new file mode 100644 index 0000000..441b7c1 --- /dev/null +++ b/tests/Febe.Tests.Windows/Support/UiThread.cs @@ -0,0 +1,55 @@ +using System.Windows.Threading; + +namespace Febe.Tests.Windows.Support; + +/// +/// A UI thread like the one of Febe.exe: an STA thread running a WPF +/// (its message pump and its ). The browser of Febe is created on it, +/// while the test itself — like the engine of Febe — runs on thread-pool threads. +/// +internal sealed class UiThread : IAsyncDisposable +{ + private readonly Thread _thread; + + private UiThread(Thread thread, Dispatcher dispatcher) + { + _thread = thread; + Dispatcher = dispatcher; + } + + public Dispatcher Dispatcher { get; } + + /// The managed id of the UI thread (to tell where code ran). + public int ThreadId => _thread.ManagedThreadId; + + public static async Task StartAsync() + { + var ready = new TaskCompletionSource(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); + } + + /// Runs on the UI thread and waits for it. + public Task InvokeAsync(Func 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); + } +} diff --git a/tests/Febe.Tests.Windows/Support/WebView2Runtime.cs b/tests/Febe.Tests.Windows/Support/WebView2Runtime.cs new file mode 100644 index 0000000..b9a52c6 --- /dev/null +++ b/tests/Febe.Tests.Windows/Support/WebView2Runtime.cs @@ -0,0 +1,39 @@ +using System.Runtime.CompilerServices; +using Microsoft.Web.WebView2.Core; + +namespace Febe.Tests.Windows.Support; + +/// Whether these tests can run here: Windows with the WebView2 runtime (the tests are inconclusive otherwise). +internal static class WebView2Runtime +{ + /// Null when WebView2 can run; otherwise why not, in Italian (the text of the inconclusive result). + 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})."; + } + } + + /// The version of the installed WebView2 runtime, e.g. «141.0.3537.71». + [MethodImpl(MethodImplOptions.NoInlining)] + public static string? InstalledVersion() => CoreWebView2Environment.GetAvailableBrowserVersionString(); + + /// Marks the test inconclusive where WebView2 cannot run. + public static void Require() + { + if (UnavailableReason() is { } reason) + { + Assert.Inconclusive(reason); + } + } +} diff --git a/tests/Febe.Tests.Windows/WebView2BrowserStartTests.cs b/tests/Febe.Tests.Windows/WebView2BrowserStartTests.cs new file mode 100644 index 0000000..1d00073 --- /dev/null +++ b/tests/Febe.Tests.Windows/WebView2BrowserStartTests.cs @@ -0,0 +1,50 @@ +using System.Text.RegularExpressions; +using Febe.Browser.Cdp; +using Febe.Tests.Windows.Support; + +namespace Febe.Tests.Windows; + +/// +/// 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. +/// +[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(); +} From a6623e57368f1828aebcd6b9470319cdee97b519 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:10:41 +0200 Subject: [PATCH 02/15] Correzione: il browser di Febe per Windows parte al primo tentativo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/Febe.Desktop/Browser/WebView2Browser.cs | 13 +++++++++---- src/Febe.Desktop/Browser/WebView2Host.cs | 14 ++++++++++++-- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/Febe.Desktop/Browser/WebView2Browser.cs b/src/Febe.Desktop/Browser/WebView2Browser.cs index f717b11..a68effc 100644 --- a/src/Febe.Desktop/Browser/WebView2Browser.cs +++ b/src/Febe.Desktop/Browser/WebView2Browser.cs @@ -68,10 +68,6 @@ internal sealed class WebView2Browser : IFebeBrowser 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) { @@ -91,7 +87,16 @@ internal sealed class WebView2Browser : IFebeBrowser { return; } + + continue; } + + // Outside the retries: what follows a start that worked never undoes it. This runs on a thread of the + // composition, so it reads only plain values of the host (the version was read on the UI thread). + _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; } } diff --git a/src/Febe.Desktop/Browser/WebView2Host.cs b/src/Febe.Desktop/Browser/WebView2Host.cs index 22d4b95..8fe5919 100644 --- a/src/Febe.Desktop/Browser/WebView2Host.cs +++ b/src/Febe.Desktop/Browser/WebView2Host.cs @@ -57,6 +57,9 @@ internal sealed class WebView2Host : IBrowserHost private bool _closing; private bool _restarting; + // Read on the UI thread during the start: a plain value that any thread may read. + private volatile string? _version; + public WebView2Host(Dispatcher ui, WebView2HostOptions settings, FebeLog log) { _ui = ui ?? throw new ArgumentNullException(nameof(ui)); @@ -79,8 +82,11 @@ internal sealed class WebView2Host : IBrowserHost /// True while a WebView is attached (commands can be sent). public bool IsAttached => _session.IsAttached; - /// The version of the WebView2 runtime in use (for the log). - public string? Version => _environment?.BrowserVersionString; + /// + /// 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. + /// + public string? Version => _version; /// Raised on the UI thread when the browser process of WebView2 went away by itself (the owner restarts). public event EventHandler? BrowserProcessFailed; @@ -200,6 +206,10 @@ internal sealed class WebView2Host : IBrowserHost _exited = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _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; if (_settings.Hosting == BrowserHosting.Composition) { From ccfd8b5c08a60ee9e594af656e86e027abf0fab9 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:29:59 +0200 Subject: [PATCH 03/15] Browser di Febe per Windows: ripartenze robuste, WebView2 toccato solo dal suo thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/Febe.Desktop/Browser/WebView2Browser.cs | 256 ++++++++++++---- src/Febe.Desktop/Browser/WebView2Host.cs | 287 ++++++++++++++---- .../Febe.Tests.Windows/Support/BrowserBed.cs | 29 +- .../WebView2LifecycleTests.cs | 191 ++++++++++++ 4 files changed, 649 insertions(+), 114 deletions(-) create mode 100644 tests/Febe.Tests.Windows/WebView2LifecycleTests.cs diff --git a/src/Febe.Desktop/Browser/WebView2Browser.cs b/src/Febe.Desktop/Browser/WebView2Browser.cs index a68effc..96a8be2 100644 --- a/src/Febe.Desktop/Browser/WebView2Browser.cs +++ b/src/Febe.Desktop/Browser/WebView2Browser.cs @@ -12,8 +12,15 @@ namespace Febe.Desktop.Browser; /// /// The browser of Instagram on Windows as the shared composition sees it (): a /// started with retries like 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. /// +/// +/// 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). +/// 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)]; @@ -22,6 +29,11 @@ internal sealed class WebView2Browser : IFebeBrowser 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 +51,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); } /// The host: window «Browser di Febe», WebView2, CDP. @@ -63,40 +75,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); - } - 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; - } - - continue; - } - - // Outside the retries: what follows a start that worked never undoes it. This runs on a thread of the - // composition, so it reads only plain values of the host (the version was read on the UI thread). - _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; + _context.Log.Info("browser", ReadyMessage("Browser di Febe pronto")); } } @@ -106,56 +88,214 @@ internal sealed class WebView2Browser : IFebeBrowser public Task HideFromUserAsync(CancellationToken ct) => Host.HideFromUserAsync(); - /// «Scollega»: WebView2 closes and its process exits, Dati\browser is deleted, the browser starts empty. + /// + /// «Scollega»: WebView2 closes and its process exits, Dati\browser is deleted, the browser starts empty. When + /// the profile cannot be deleted completely an 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). + /// public async Task RestartWithEmptyProfileAsync(CancellationToken ct) { - try + Exception? deletion = null; + async Task DeleteProfileQuietlyAsync() { - await Host.RestartAsync(DeleteProfileAsync, ct).ConfigureAwait(false); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - 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); + try + { + await DeleteProfileAsync().ConfigureAwait(true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + deletion = ex; + } } - _context.Log.Info("browser", "Profilo del browser cancellato; il browser è ripartito vuoto."); + var restarted = false; + try + { + await Host.RestartAsync(DeleteProfileQuietlyAsync, ct).ConfigureAwait(false); + MarkStarted(); + restarted = true; + } + catch (Exception ex) when (ex is not (OutOfMemoryException or ObjectDisposedException)) + { + // The start that follows the deletion failed: never a dead browser after «Scollega». + RequestRestart(ex); + } + + 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(); - - /// The browser process of WebView2 went away by itself: it starts again with the same profile. - private async Task RecoverAsync() + /// + /// 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. + /// + public async ValueTask DisposeAsync() { + await _lifetime.CancelAsync().ConfigureAwait(false); + Task? restarting; + lock (_gate) + { + restarting = _restartLoop; + } + + if (restarting is not null) + { + await restarting.ConfigureAwait(false); + } + + await Host.DisposeAsync().ConfigureAwait(false); + } + + /// + /// Runs until it works (true) or is cancelled (false), waiting + /// between attempts. With the first attempt already failed with it. + /// Only an exception of the start itself is a failed start; this method never throws. + /// + private async Task StartWithRetriesAsync(Func 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; + } + + /// A start failed: it is said, what it left is closed, and the next attempt waits. False when cancelled. + private async Task 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 Host.ResetAsync().ConfigureAwait(false); } catch (Exception ex) when (ex is not OutOfMemoryException) { - _started = false; - _lastError = $"WebView2 non riparte ({ex.GetType().Name})."; - _context.Log.Error("browser", _lastError); + _context.Log.Warn("browser", "WebView2: quello che l'avvio non riuscito ha lasciato aperto non si è chiuso del tutto.", ex); + } + + try + { + await _wallClock.Delay(wait, ct).ConfigureAwait(false); + return true; + } + catch (OperationCanceledException) + { + return false; } } - /// Deletes the profile; a process of WebView2 may still hold a file for a moment. + private void MarkStarted() + { + _started = true; + _lastError = null; + } + + /// + /// The browser must start again (its process went away by itself, or the start after «Scollega» failed with + /// ): one loop at a time restarts 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. + /// + 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.RestartAsync(null, token), _lifetime.Token, failure).ConfigureAwait(false)) + { + _context.Log.Info("browser", ReadyMessage("Browser di Febe ripartito")); + } + } + } + + /// Plain values only (the version was read on the UI thread during the start). + 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."; + + /// + /// Deletes the profile — off the UI thread, it can be large — retrying while a process of WebView2 still holds a + /// file for a moment. + /// 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); } } } diff --git a/src/Febe.Desktop/Browser/WebView2Host.cs b/src/Febe.Desktop/Browser/WebView2Host.cs index 8fe5919..13ed81c 100644 --- a/src/Febe.Desktop/Browser/WebView2Host.cs +++ b/src/Febe.Desktop/Browser/WebView2Host.cs @@ -1,3 +1,4 @@ +using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Windows.Media; using System.Windows.Threading; @@ -35,30 +36,47 @@ internal sealed record WebView2HostOptions(BrowserHosting Hosting, string Additi /// «Ho finito»; using and closing it marks the browser as used for «Riprendi». /// Stopping closes the WebView and waits for its browser process to exit, so the session is on disk (S3); /// («Scollega») does the same before deleting the profile. -/// Every WebView2 call runs on the UI thread through its dispatcher. +/// Threads: every WebView2 object (environment, controller, CoreWebView2, 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 (, ), the CDP session, and tasks. Start, +/// restart, reset and stop run one at a time. /// /// internal sealed class WebView2Host : IBrowserHost { private static readonly TimeSpan ExitWait = TimeSpan.FromSeconds(15); + /// How long stopping waits for a start or restart in progress before closing what there is. + 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, reset 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; - // Read on the UI thread during the start: a plain value that any thread may read. + // 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) { @@ -88,7 +106,16 @@ internal sealed class WebView2Host : IBrowserHost /// public string? Version => _version; - /// Raised on the UI thread when the browser process of WebView2 went away by itself (the owner restarts). + /// The browser process of WebView2 when it last started (0 before the first start). Any thread. + public int BrowserProcessId => Volatile.Read(ref _browserProcessId); + + /// The window «Browser di Febe» (null before the first start). UI thread only, like every WPF object. + internal BrowserWindow? Window => _window; + + /// + /// 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. + /// public event EventHandler? BrowserProcessFailed; /// Creates the window (once), the environment and the controller, and attaches the CDP session. @@ -96,7 +123,7 @@ internal sealed class WebView2Host : IBrowserHost { ArgumentNullException.ThrowIfNull(options); _options = options; - return OnUiAsync(StartCoreAsync); + return OnUiAsync(() => ExclusiveAsync(StartCoreAsync)); } public Task ShowToUserAsync() => OnUiAsync(() => @@ -110,8 +137,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; }); @@ -125,55 +162,61 @@ internal sealed class WebView2Host : IBrowserHost /// /// Closes the WebView, waits for its browser process to exit (the profile is free and written), runs /// — «Scollega» deletes the profile there — and starts it again. - /// stays the same object. The browser starts again even when fails; its error is - /// thrown afterwards. + /// 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, as after a failed , the caller closes what it left with + /// before trying again. /// - public Task RestartAsync(Func? whileStopped, CancellationToken ct) => OnUiAsync(async () => + public Task RestartAsync(Func? whileStopped, CancellationToken ct) => OnUiAsync(() => ExclusiveAsync(async () => { + ObjectDisposedException.ThrowIf(_closing, this); + Exception? failure = null; _restarting = true; try { await CloseWebViewAsync().ConfigureAwait(true); - Exception? failure = null; - try + if (whileStopped is not null) { - if (whileStopped is not null) + try { await whileStopped().ConfigureAwait(true); } - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - failure = ex; + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + failure = ex; + } } await StartCoreAsync().ConfigureAwait(true); - if (failure is not null) - { - throw failure; - } } finally { _restarting = false; } - }); + + if (failure is not null) + { + ExceptionDispatchInfo.Throw(failure); + } + })); /// Closes what a failed start left, so that the next start begins clean. - public Task ResetAsync() => OnUiAsync(CloseWebViewAsync); + public Task ResetAsync() => OnUiAsync(() => ExclusiveAsync(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) { @@ -183,9 +226,32 @@ internal sealed class WebView2Host : IBrowserHost await _session.DisposeAsync().ConfigureAwait(false); } + /// UI thread, one at a time (). private async Task StartCoreAsync() { + _ui.VerifyAccess(); + ObjectDisposedException.ThrowIf(_closing, this); var options = _options ?? throw new InvalidOperationException("Opzioni del browser mancanti."); + _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."); + } + } + finally + { + _starting = false; + } + } + + private async Task CreateWebViewAsync(BrowserOptions options) + { if (_window is null) { var window = new BrowserWindow(options.WindowWidth, options.WindowHeight, _settings.Icon); @@ -202,28 +268,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; + _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; @@ -231,6 +300,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; @@ -238,11 +309,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); @@ -253,16 +327,30 @@ internal sealed class WebView2Host : IBrowserHost /// Closes the controller and waits for the browser process to exit (the profile is written). UI thread. private async Task CloseWebViewAsync() { + _ui.VerifyAccess(); _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) @@ -270,7 +358,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); @@ -286,24 +373,48 @@ 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 closed or replaced WebView is not ours any more. + if (_closing || generation != _generation) { return; } - if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.BrowserProcessExited) + // During a start the failure is the start's own error (the caller retries); while a restart closes the old + // WebView the failure changes nothing. + 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 (_restarting) + { + return; + } + + 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. + } } } @@ -341,19 +452,40 @@ internal sealed class WebView2Host : IBrowserHost private void UserNavigation(Action action, Func 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() @@ -378,5 +510,54 @@ internal sealed class WebView2Host : IBrowserHost } } - private Task OnUiAsync(Func action) => _ui.CheckAccess() ? action() : _ui.InvokeAsync(action).Task.Unwrap(); + /// + /// Runs one step of the life of the WebView (start, restart, reset, stop) after the others. UI thread. With + /// the step runs anyway once that time has passed (stopping must not hang behind a start + /// that WebView2 never completes). + /// + private async Task ExclusiveAsync(Func 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(); + } + } + } + + /// + /// 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. + /// + private Task OnUiAsync(Func 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); + } + } } diff --git a/tests/Febe.Tests.Windows/Support/BrowserBed.cs b/tests/Febe.Tests.Windows/Support/BrowserBed.cs index 5315764..c09263b 100644 --- a/tests/Febe.Tests.Windows/Support/BrowserBed.cs +++ b/tests/Febe.Tests.Windows/Support/BrowserBed.cs @@ -15,13 +15,14 @@ namespace Febe.Tests.Windows.Support; /// internal sealed class BrowserBed : IAsyncDisposable { - private BrowserBed(TestFolder folder, UiThread ui, LogLines lines, FebeLog log, FebeDatabase database, WebView2Browser browser) + 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; } @@ -36,6 +37,9 @@ internal sealed class BrowserBed : IAsyncDisposable public FebeDatabase Database { get; } + /// When Alberto last used the browser («Riprendi» after a verification). + public BrowserUseTracker Tracker { get; } + public WebView2Browser Browser { get; } public static async Task CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window) @@ -48,14 +52,33 @@ internal sealed class BrowserBed : IAsyncDisposable 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 context = new FebePlatformContext(options, data, database, clock, log, new BrowserUseTracker()); + 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, browser); + return new BrowserBed(folder, ui, lines, log, database, tracker, browser); } + /// Waits (real time) until holds; fails with and the log otherwise. + public async Task WaitUntilAsync(Func 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); + } + } + + /// Reads a value of the UI thread (the window, its position) through the dispatcher. + public Task OnUiAsync(Func read) => Ui.InvokeAsync(read); + /// /// Starts the browser from a thread-pool thread, like FebeApp.BringUpBrowserAsync, and waits until /// returns. Fails at once when the log reports a failed start: the loop of diff --git a/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs b/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs new file mode 100644 index 0000000..31f79f1 --- /dev/null +++ b/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs @@ -0,0 +1,191 @@ +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; + +/// +/// 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. +/// +/// Two tests bring the window «Browser di Febe» on screen for a moment, as «Accedi a Instagram» does. +[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); + } + + [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"); + } +} From 3f222448eeb6880c982c0fe683836b6a40e03b59 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:30:11 +0200 Subject: [PATCH 04/15] Sessione CDP di WebView2: un errore di chi ascolta la ripartenza non disfa l'avvio MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../WebView2/WebView2CdpSession.cs | 27 ++++++++- .../WebView2CdpSessionAttachTests.cs | 55 +++++++++++++++++++ 2 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 tests/Febe.Tests.Windows/WebView2CdpSessionAttachTests.cs diff --git a/src/Febe.Browser/WebView2/WebView2CdpSession.cs b/src/Febe.Browser/WebView2/WebView2CdpSession.cs index 5f641ed..80f3fd2 100644 --- a/src/Febe.Browser/WebView2/WebView2CdpSession.cs +++ b/src/Febe.Browser/WebView2/WebView2CdpSession.cs @@ -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); } + /// + /// , on the thread of (WebView2's UI thread), one handler at a time: an + /// error of a handler is logged and never reaches , 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). + /// + private void RaiseReconnected() + { + if (Reconnected is not { } handlers) + { + return; + } + + foreach (var handler in handlers.GetInvocationList().Cast()) + { + 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))); diff --git a/tests/Febe.Tests.Windows/WebView2CdpSessionAttachTests.cs b/tests/Febe.Tests.Windows/WebView2CdpSessionAttachTests.cs new file mode 100644 index 0000000..349508a --- /dev/null +++ b/tests/Febe.Tests.Windows/WebView2CdpSessionAttachTests.cs @@ -0,0 +1,55 @@ +using System.Collections.Concurrent; +using Febe.Browser.Diagnostics; +using Febe.Browser.WebView2; + +namespace Febe.Tests.Windows; + +/// +/// The attach of a new WebView to the session (after a crash or «Scollega»), without WebView2: an error of whoever +/// listens to must not undo a start that worked. +/// +[TestClass] +public sealed class WebView2CdpSessionAttachTests +{ + [TestMethod] + public async Task AFailingReconnectionHandlerDoesNotUndoTheAttach() + { + var log = new ListLog(); + 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 SilentDevTools()); + session.Attach(new SilentDevTools()); + + 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)), string.Join('\n', log.Lines)); + Assert.AreEqual("{}", (await session.SendAsync("Page.enable", ct: CancellationToken.None)).GetRawText()); + } + + private sealed class SilentDevTools : IWebView2DevTools + { + public Task CallMethodAsync(string methodName, string parametersAsJson) => Task.FromResult("{}"); + + public IDisposable Subscribe(string eventName, Action onEvent) => new Nothing(); + + private sealed class Nothing : IDisposable + { + public void Dispose() + { + } + } + } + + private sealed class ListLog : IBrowserLog + { + private readonly ConcurrentQueue _lines = new(); + + public IReadOnlyList Lines => [.. _lines]; + + public void Write(BrowserLogLevel level, string message, Exception? exception = null) => + _lines.Enqueue($"{level} {message} {exception?.GetType().Name}"); + } +} From 2ef098226b56316fa29aa42db4d30d683e209973 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:30:20 +0200 Subject: [PATCH 05/15] Finestra di Febe: gli indirizzi esterni si aprono dopo il gestore di WebView2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/Febe.Desktop/MainWindow.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/Febe.Desktop/MainWindow.cs b/src/Febe.Desktop/MainWindow.cs index cf395fd..8dfb6ab 100644 --- a/src/Febe.Desktop/MainWindow.cs +++ b/src/Febe.Desktop/MainWindow.cs @@ -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); } } + + /// + /// Opens 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). + /// + private void OpenOutsideLater(Uri uri) => Dispatcher.InvokeAsync(() => _openOutside(uri), DispatcherPriority.Background); } From a305a9ed2a00a6f2f8bede137503436176ea4daf Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:30:33 +0200 Subject: [PATCH 06/15] Prova di S1 su WebView2 vero contro il sito di prova MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- tests/Febe.Tests.Windows/WebView2CdpTests.cs | 197 +++++++++++++++++++ 1 file changed, 197 insertions(+) create mode 100644 tests/Febe.Tests.Windows/WebView2CdpTests.cs diff --git a/tests/Febe.Tests.Windows/WebView2CdpTests.cs b/tests/Febe.Tests.Windows/WebView2CdpTests.cs new file mode 100644 index 0000000..a75bd47 --- /dev/null +++ b/tests/Febe.Tests.Windows/WebView2CdpTests.cs @@ -0,0 +1,197 @@ +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; + +/// +/// S1 on a real Windows (docs/prove-dal-vivo.md, C3): the DevTools protocol of WebView2 through the real +/// 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. +/// +[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(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(() => cdp.SendAsync("Emulation.setTimezoneOverride", new JsonObject { ["timezoneId"] = "America/New_York" }, ct)); + await Assert.ThrowsExactlyAsync(() => cdp.SendAsync("Network.setUserAgentOverride", new JsonObject { ["userAgent"] = "Febe" }, ct)); + await Assert.ThrowsExactlyAsync(() => cdp.SendAsync("Page.addScriptToEvaluateOnNewDocument", new JsonObject { ["source"] = "1" }, ct)); + await Assert.ThrowsExactlyAsync(() => cdp.SendAsync("Fetch.enable", null, ct)); + await Assert.ThrowsExactlyAsync(() => cdp.SendAsync("Target.createTarget", new JsonObject { ["url"] = "about:blank" }, ct)); + await Assert.ThrowsExactlyAsync(() => cdp.EvaluateAsync("window.scrollBy(0, 500)", ct)); + Assert.AreEqual(scrolled, (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble(), "the refused script did not run"); + 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 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); + } + } + + /// The JSON bodies the page received, by path. + private sealed class BodyCollector : IResponseConsumer + { + private readonly ConcurrentDictionary _bodies = new(StringComparer.Ordinal); + + public ICollection 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; + } + } +} From cf618d898627f315b52556d79653e6cfdaa55aa8 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:30:51 +0200 Subject: [PATCH 07/15] Una sessione di raccolta vera della composizione condivisa su WebView2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../Support/CompositionSupport.cs | 78 ++++++++ .../WebView2CollectionTests.cs | 168 ++++++++++++++++++ 2 files changed, 246 insertions(+) create mode 100644 tests/Febe.Tests.Windows/Support/CompositionSupport.cs create mode 100644 tests/Febe.Tests.Windows/WebView2CollectionTests.cs diff --git a/tests/Febe.Tests.Windows/Support/CompositionSupport.cs b/tests/Febe.Tests.Windows/Support/CompositionSupport.cs new file mode 100644 index 0000000..54f2c73 --- /dev/null +++ b/tests/Febe.Tests.Windows/Support/CompositionSupport.cs @@ -0,0 +1,78 @@ +using Febe.Core.Abstractions; +using Febe.Desktop.Core; + +namespace Febe.Tests.Windows.Support; + +/// +/// A clock that compresses time, like the one of the Linux suite: waits for real only a fraction +/// of the requested time and moves on by the whole of it, so the engine keeps its order of events +/// while a session lasts minutes instead of hours. +/// +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 +{ + /// + /// 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. + /// + public static TimeZoneInfo Noon() + { + var offset = 12 - DateTimeOffset.UtcNow.Hour; + return TimeZoneInfo.CreateCustomTimeZone("Febe/Mezzogiorno", TimeSpan.FromHours(offset), "Mezzogiorno di prova", "Mezzogiorno di prova"); + } +} + +/// The registry values «CartellaDati» and «NuovaCartellaDati», in memory. +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; +} diff --git a/tests/Febe.Tests.Windows/WebView2CollectionTests.cs b/tests/Febe.Tests.Windows/WebView2CollectionTests.cs new file mode 100644 index 0000000..1a98f5c --- /dev/null +++ b/tests/Febe.Tests.Windows/WebView2CollectionTests.cs @@ -0,0 +1,168 @@ +using System.Net; +using System.Net.Http; +using System.Text; +using System.Text.Json; +using Febe.App; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Desktop; +using Febe.Desktop.Browser; +using Febe.Desktop.Core; +using Febe.SitoDiProva; +using Febe.Tests.Windows.Support; +using Febe.Web.Connection; +using Febe.Web.Native; + +namespace Febe.Tests.Windows; + +/// +/// One real collection session of the shared composition () running on WebView2, as Febe.exe +/// composes it — , DesktopShell, the window «Browser di Febe» on a WPF UI thread — +/// 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. +/// +[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 site = await TestSite.StartAsync(new TestSiteOptions(), ct); + using var folder = new TestFolder("raccolta"); + await using var ui = await UiThread.StartAsync(); + var lines = new LogLines(); + var data = folder.Combine("dati"); + string[] arguments = + [ + "--dati", data, "--libreria", folder.Combine("libreria"), + "--sito-di-prova", site.SiteUrl, "--cdn-di-prova", site.CdnUrl, "--accesso-di-prova", "--prima-sessione", "1", + ]; + Assert.IsTrue(DesktopCommandLine.TryParse(arguments, out var options, out var problem), problem); + + // Febe.exe's composition, on a clock ten times faster and in a zone where it is noon. + 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) }; + await using var app = await FebeApp.StartAsync(appOptions, platform, hooks, ct); + Assert.IsEmpty(app.Problems, string.Join("; ", app.Problems.Select(p => p.Title))); + + // The browser starts from a thread of the composition, the pipeline and the engine follow. + await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct); + Assert.IsInstanceOfType(app.Browser); + Assert.IsTrue(lines.Any("Browser di Febe pronto: WebView2 "), lines.Text); + Assert.IsFalse(lines.Any("non parte"), lines.Text); + var connection = app.Connection!; + Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State, "the test site's automatic login"); + + // Accounts and «Controlla ora» through the interface, with the token of this start, as the main window does. + using var client = new HttpClient(new HttpClientHandler { UseCookies = false, AllowAutoRedirect = false, UseProxy = false }) + { + BaseAddress = app.Address, + Timeout = TimeSpan.FromSeconds(30), + }; + var origin = $"{app.Address.Scheme}://{app.Address.Authority}"; + async Task JsonAsync(HttpMethod method, string path, string? json = null) + { + using var request = new HttpRequestMessage(method, path); + request.Headers.TryAddWithoutValidation(Febe.Web.Security.AccessToken.HeaderName, platform.AccessToken); + request.Headers.TryAddWithoutValidation("Origin", origin); + 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(); + } + + var added = await JsonAsync(HttpMethod.Post, "/api/accounts", """{"usernames":["marta.prova","luca.prova"],"start":"everything"}"""); + 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 JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now"); + if (check.GetProperty("status").GetString() == "needsConfirmation") + { + check = await JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", $$"""{"token":"{{check.GetProperty("token").GetString()}}"}"""); + } + + 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 WaitUntilAsync( + async () => (await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, 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", + lines, + 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 stored = []; + await WaitUntilAsync( + async () => + { + stored = await StoredAsync(app, marta.Id, ct); + return stored.Count >= 3; + }, + TimeSpan.FromSeconds(180), + "tre file di marta.prova nella libreria", + lines, + 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, folder.Path, "inside the temporary library"); + } + + var actions = await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, 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: {site.Control.CdnFilesServed} file serviti."); + TestContext.WriteLine(lines.Text); + Assert.IsFalse(lines.Any("non parte"), "the browser never failed to start"); + Assert.IsFalse(lines.Any("firma="), "no signed address in the log"); + } + + private static async Task> StoredAsync(FebeApp app, long accountId, CancellationToken ct) + { + var list = new List(); + 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; + } + + private static async Task WaitUntilAsync(Func> condition, TimeSpan timeout, string what, LogLines lines, 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); + } + } +} From 7b0b0339f75d7a5823a9f6cc77eb1057854733d8 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:45:13 +0200 Subject: [PATCH 08/15] Documenti: stato di Febe per Windows dopo la correzione, prove su Windows e decisioni MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/decisioni.md | 8 +++++ docs/windows.md | 58 +++++++++++++++++++++++++++++++++---- src/Febe.Desktop/LEGGIMI.md | 18 +++++++++--- 3 files changed, 75 insertions(+), 9 deletions(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index be3e037..9fc6ca2 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -226,3 +226,11 @@ 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 | 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, chiusura dopo un avvio fallito 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 | diff --git a/docs/windows.md b/docs/windows.md index c02a64f..5530ec4 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -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,16 @@ 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. + 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 +227,39 @@ 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, come +«Accedi a Instagram». 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»; 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 | +| `WebView2CdpSessionAttachTests` | Senza WebView2: un errore di chi ascolta la ripartenza non disfa l'avvio | + ## 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 | diff --git a/src/Febe.Desktop/LEGGIMI.md b/src/Febe.Desktop/LEGGIMI.md index 881169a..cea03f8 100644 --- a/src/Febe.Desktop/LEGGIMI.md +++ b/src/Febe.Desktop/LEGGIMI.md @@ -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,18 @@ 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. +- 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 From e5e2b6864fac6ea958d8616a1c160731ec0db132 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:46:58 +0200 Subject: [PATCH 09/15] 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 --- tests/Febe.Tests.Windows/WebView2CdpTests.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/Febe.Tests.Windows/WebView2CdpTests.cs b/tests/Febe.Tests.Windows/WebView2CdpTests.cs index a75bd47..920b1d4 100644 --- a/tests/Febe.Tests.Windows/WebView2CdpTests.cs +++ b/tests/Febe.Tests.Windows/WebView2CdpTests.cs @@ -112,8 +112,11 @@ public sealed class WebView2CdpTests await Assert.ThrowsExactlyAsync(() => cdp.SendAsync("Page.addScriptToEvaluateOnNewDocument", new JsonObject { ["source"] = "1" }, ct)); await Assert.ThrowsExactlyAsync(() => cdp.SendAsync("Fetch.enable", null, ct)); await Assert.ThrowsExactlyAsync(() => cdp.SendAsync("Target.createTarget", new JsonObject { ["url"] = "about:blank" }, ct)); + var before = (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble(); await Assert.ThrowsExactlyAsync(() => cdp.EvaluateAsync("window.scrollBy(0, 500)", ct)); - Assert.AreEqual(scrolled, (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble(), "the refused script did not run"); + 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); From 66a3fc7db6b12a1290c79b33ea81f1c1863eac83 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:53:48 +0200 Subject: [PATCH 10/15] Prove per Windows: la composizione di Febe.exe preparata in un posto solo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../Febe.Tests.Windows/Support/DesktopBed.cs | 150 ++++++++++++++++++ .../WebView2CollectionTests.cs | 110 +++---------- 2 files changed, 172 insertions(+), 88 deletions(-) create mode 100644 tests/Febe.Tests.Windows/Support/DesktopBed.cs diff --git a/tests/Febe.Tests.Windows/Support/DesktopBed.cs b/tests/Febe.Tests.Windows/Support/DesktopBed.cs new file mode 100644 index 0000000..8a1e1af --- /dev/null +++ b/tests/Febe.Tests.Windows/Support/DesktopBed.cs @@ -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; + +/// +/// The shared composition () as Febe.exe composes it — , +/// DesktopShell, 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. +/// +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; } + + /// What Febe wrote in its log. + public LogLines Lines { get; } + + public CompressedClock Clock { get; } + + public DesktopPlatform Platform { get; } + + public FebeApp App { get; } + + /// The browser of Febe: WebView2 (Febe.exe never uses another one unless asked with --browser edge). + public WebView2Browser Browser => App.Browser as WebView2Browser ?? throw new AssertFailedException("Il browser della composizione non è WebView2."); + + /// Prefix of the temporary folder. + /// --accesso-di-prova: the composition opens the test site once at start-up. + public static async Task 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 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; + } + } + + /// A request as the main window sends it; the answer must be 200 with JSON. + public async Task 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(); + } + + /// Waits (real time) until holds; fails with and the log otherwise. + public async Task WaitUntilAsync(Func> 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); + } + } + + /// Stops the composition (the browser of Febe closes on its UI thread), then the UI thread, folders, site. + public async ValueTask DisposeAsync() + { + _client.Dispose(); + try + { + await App.DisposeAsync(); + } + finally + { + await Ui.DisposeAsync(); + Folder.Dispose(); + await Site.DisposeAsync(); + } + } +} diff --git a/tests/Febe.Tests.Windows/WebView2CollectionTests.cs b/tests/Febe.Tests.Windows/WebView2CollectionTests.cs index 1a98f5c..d645996 100644 --- a/tests/Febe.Tests.Windows/WebView2CollectionTests.cs +++ b/tests/Febe.Tests.Windows/WebView2CollectionTests.cs @@ -1,25 +1,15 @@ -using System.Net; using System.Net.Http; -using System.Text; -using System.Text.Json; using Febe.App; -using Febe.Core.Abstractions; using Febe.Core.Domain; -using Febe.Desktop; using Febe.Desktop.Browser; -using Febe.Desktop.Core; -using Febe.SitoDiProva; using Febe.Tests.Windows.Support; -using Febe.Web.Connection; -using Febe.Web.Native; namespace Febe.Tests.Windows; /// /// One real collection session of the shared composition () running on WebView2, as Febe.exe -/// composes it — , DesktopShell, the window «Browser di Febe» on a WPF UI thread — -/// 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. +/// 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. /// [TestClass] public sealed class WebView2CollectionTests @@ -34,82 +24,41 @@ public sealed class WebView2CollectionTests public async Task ARealSessionOfTheCompositionRunsOnWebView2AndTheFilesArriveInTheLibrary() { var ct = TestContext.CancellationToken; - await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct); - using var folder = new TestFolder("raccolta"); - await using var ui = await UiThread.StartAsync(); - var lines = new LogLines(); - var data = folder.Combine("dati"); - string[] arguments = - [ - "--dati", data, "--libreria", folder.Combine("libreria"), - "--sito-di-prova", site.SiteUrl, "--cdn-di-prova", site.CdnUrl, "--accesso-di-prova", "--prima-sessione", "1", - ]; - Assert.IsTrue(DesktopCommandLine.TryParse(arguments, out var options, out var problem), problem); - - // Febe.exe's composition, on a clock ten times faster and in a zone where it is noon. - 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) }; - await using var app = await FebeApp.StartAsync(appOptions, platform, hooks, ct); + 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 pipeline and the engine follow. + // 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(app.Browser); - Assert.IsTrue(lines.Any("Browser di Febe pronto: WebView2 "), lines.Text); - Assert.IsFalse(lines.Any("non parte"), lines.Text); - var connection = app.Connection!; - Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State, "the test site's automatic login"); + 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, with the token of this start, as the main window does. - using var client = new HttpClient(new HttpClientHandler { UseCookies = false, AllowAutoRedirect = false, UseProxy = false }) - { - BaseAddress = app.Address, - Timeout = TimeSpan.FromSeconds(30), - }; - var origin = $"{app.Address.Scheme}://{app.Address.Authority}"; - async Task JsonAsync(HttpMethod method, string path, string? json = null) - { - using var request = new HttpRequestMessage(method, path); - request.Headers.TryAddWithoutValidation(Febe.Web.Security.AccessToken.HeaderName, platform.AccessToken); - request.Headers.TryAddWithoutValidation("Origin", origin); - 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(); - } - - var added = await JsonAsync(HttpMethod.Post, "/api/accounts", """{"usernames":["marta.prova","luca.prova"],"start":"everything"}"""); + // 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 JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now"); + var check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", null, ct); if (check.GetProperty("status").GetString() == "needsConfirmation") { - check = await JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", $$"""{"token":"{{check.GetProperty("token").GetString()}}"}"""); + 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 WaitUntilAsync( - async () => (await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, clock.Now.AddDays(1), ct)).Any(a => a.AccountId == marta.Id), + 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", - lines, 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 stored = []; - await WaitUntilAsync( + await bed.WaitUntilAsync( async () => { stored = await StoredAsync(app, marta.Id, ct); @@ -117,22 +66,21 @@ public sealed class WebView2CollectionTests }, TimeSpan.FromSeconds(180), "tre file di marta.prova nella libreria", - lines, 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, folder.Path, "inside the temporary library"); + StringAssert.StartsWith(path, bed.Folder.Path, "inside the temporary library"); } - var actions = await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, clock.Now.AddDays(1), ct); + 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: {site.Control.CdnFilesServed} file serviti."); - TestContext.WriteLine(lines.Text); - Assert.IsFalse(lines.Any("non parte"), "the browser never failed to start"); - Assert.IsFalse(lines.Any("firma="), "no signed address in the log"); + 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> StoredAsync(FebeApp app, long accountId, CancellationToken ct) @@ -151,18 +99,4 @@ public sealed class WebView2CollectionTests return list; } - - private static async Task WaitUntilAsync(Func> condition, TimeSpan timeout, string what, LogLines lines, 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); - } - } } From 7fffa53c9001da6f8586115126ee7e1cd97da894 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:53:48 +0200 Subject: [PATCH 11/15] Prova del collegamento su Windows: Accedi, Ho finito e Scollega con WebView2 vero MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/windows.md | 5 +- .../WebView2ConnectionTests.cs | 67 +++++++++++++++++++ 2 files changed, 70 insertions(+), 2 deletions(-) create mode 100644 tests/Febe.Tests.Windows/WebView2ConnectionTests.cs diff --git a/docs/windows.md b/docs/windows.md index 5530ec4..c04796a 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -241,8 +241,8 @@ dotnet test tests/Febe.Tests.Windows --filter "FullyQualifiedName~WebView2CdpTes 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, come -«Accedi a Instagram». Una prova chiude, con il suo numero di processo, il processo del browser che lei stessa ha +«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. @@ -252,6 +252,7 @@ raccolta. | `WebView2LifecycleTests` | Un avvio che fallisce davvero si riprova e poi va; primo piano e fuori vista con il permesso di guida; «Scollega»; 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 | | `WebView2CdpSessionAttachTests` | Senza WebView2: un errore di chi ascolta la ripartenza non disfa l'avvio | ## Problemi comuni diff --git a/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs b/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs new file mode 100644 index 0000000..8dd5722 --- /dev/null +++ b/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs @@ -0,0 +1,67 @@ +using Febe.Core.Storage; +using Febe.Tests.Windows.Support; +using Febe.Web.Connection; + +namespace Febe.Tests.Windows; + +/// +/// 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. +/// +[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); + } +} From a144d611ac762ec8c7b60da1e176f8af76c2b54b Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:23:19 +0200 Subject: [PATCH 12/15] Browser di Febe per Windows: un solo WebView nella finestra, chiunque lo avvii MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/decisioni.md | 3 +- docs/windows.md | 4 +- src/Febe.Desktop/Browser/WebView2Browser.cs | 22 ++-- src/Febe.Desktop/Browser/WebView2Host.cs | 102 +++++++++++------- src/Febe.Desktop/LEGGIMI.md | 4 + .../Febe.Tests.Windows/Support/BrowserBed.cs | 4 + .../Support/ChildWindows.cs | 31 ++++++ .../WebView2LifecycleTests.cs | 54 ++++++++++ 8 files changed, 171 insertions(+), 53 deletions(-) create mode 100644 tests/Febe.Tests.Windows/Support/ChildWindows.cs diff --git a/docs/decisioni.md b/docs/decisioni.md index 9fc6ca2..e1b0270 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -229,8 +229,9 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 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, chiusura dopo un avvio fallito 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 | 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 | diff --git a/docs/windows.md b/docs/windows.md index c04796a..1e4c9ea 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -191,6 +191,8 @@ dell'interfaccia: Febe li tocca solo da lì (i comandi del motore arrivano da al 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: @@ -249,7 +251,7 @@ 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»; ripartenza dopo l'arresto del processo; «composizione» di S2 | +| `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); 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 | diff --git a/src/Febe.Desktop/Browser/WebView2Browser.cs b/src/Febe.Desktop/Browser/WebView2Browser.cs index 96a8be2..14e1631 100644 --- a/src/Febe.Desktop/Browser/WebView2Browser.cs +++ b/src/Febe.Desktop/Browser/WebView2Browser.cs @@ -193,21 +193,15 @@ internal sealed class WebView2Browser : IFebeBrowser return false; } - /// A start failed: it is said, what it left is closed, and the next attempt waits. False when cancelled. + /// + /// 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. + /// private async Task 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.ResetAsync().ConfigureAwait(false); - } - catch (Exception ex) when (ex is not OutOfMemoryException) - { - _context.Log.Warn("browser", "WebView2: quello che l'avvio non riuscito ha lasciato aperto non si è chiuso del tutto.", ex); - } - try { await _wallClock.Delay(wait, ct).ConfigureAwait(false); @@ -227,8 +221,10 @@ internal sealed class WebView2Browser : IFebeBrowser /// /// The browser must start again (its process went away by itself, or the start after «Scollega» failed with - /// ): one loop at a time restarts 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. + /// ): 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. /// private void RequestRestart(Exception? failure) { @@ -263,7 +259,7 @@ internal sealed class WebView2Browser : IFebeBrowser _restartFailure = null; } - if (await StartWithRetriesAsync(token => Host.RestartAsync(null, token), _lifetime.Token, failure).ConfigureAwait(false)) + if (await StartWithRetriesAsync(token => Host.StartAsync(_options, token), _lifetime.Token, failure).ConfigureAwait(false)) { _context.Log.Info("browser", ReadyMessage("Browser di Febe ripartito")); } diff --git a/src/Febe.Desktop/Browser/WebView2Host.cs b/src/Febe.Desktop/Browser/WebView2Host.cs index 13ed81c..3cdffad 100644 --- a/src/Febe.Desktop/Browser/WebView2Host.cs +++ b/src/Febe.Desktop/Browser/WebView2Host.cs @@ -40,7 +40,10 @@ internal sealed record WebView2HostOptions(BrowserHosting Hosting, string Additi /// 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 (, ), the CDP session, and tasks. Start, -/// restart, reset and stop run one at a time. +/// restart and stop run one at a time. +/// 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. /// /// internal sealed class WebView2Host : IBrowserHost @@ -55,7 +58,7 @@ internal sealed class WebView2Host : IBrowserHost private readonly FebeLog _log; private readonly WebView2CdpSession _session; - // Start, restart, reset and dispose each await WebView2 on the UI thread: without this they could interleave there. + // 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. @@ -72,7 +75,6 @@ internal sealed class WebView2Host : IBrowserHost 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; @@ -118,7 +120,11 @@ internal sealed class WebView2Host : IBrowserHost /// public event EventHandler? BrowserProcessFailed; - /// Creates the window (once), the environment and the controller, and attaches the CDP session. + /// + /// 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. + /// public Task StartAsync(BrowserOptions options, CancellationToken ct) { ArgumentNullException.ThrowIfNull(options); @@ -164,45 +170,32 @@ 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, as after a failed , the caller closes what it left with - /// before trying again. + /// start throws its own error and, like a failed , leaves nothing open. /// public Task RestartAsync(Func? whileStopped, CancellationToken ct) => OnUiAsync(() => ExclusiveAsync(async () => { ObjectDisposedException.ThrowIf(_closing, this); Exception? failure = null; - _restarting = true; - try + await CloseWebViewAsync().ConfigureAwait(true); + if (whileStopped is not null) { - await CloseWebViewAsync().ConfigureAwait(true); - if (whileStopped is not null) + try { - try - { - await whileStopped().ConfigureAwait(true); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - failure = ex; - } + await whileStopped().ConfigureAwait(true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + failure = ex; } - - await StartCoreAsync().ConfigureAwait(true); - } - finally - { - _restarting = false; } + await StartCoreAsync().ConfigureAwait(true); if (failure is not null) { ExceptionDispatchInfo.Throw(failure); } })); - /// Closes what a failed start left, so that the next start begins clean. - public Task ResetAsync() => OnUiAsync(() => ExclusiveAsync(CloseWebViewAsync)); - public async ValueTask DisposeAsync() { try @@ -226,12 +219,29 @@ internal sealed class WebView2Host : IBrowserHost await _session.DisposeAsync().ConfigureAwait(false); } - /// UI thread, one at a time (). + /// True while a WebView is in the window and attached to the session (its browser process did not die). + private bool IsRunning => _controller is not null && _session.IsAttached; + + /// + /// UI thread, one at a time (): 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. + /// 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 @@ -244,12 +254,30 @@ internal sealed class WebView2Host : IBrowserHost throw new InvalidOperationException("Il processo del browser WebView2 si è chiuso durante l'avvio."); } } + 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) @@ -324,10 +352,14 @@ internal sealed class WebView2Host : IBrowserHost await _session.SendAsync("Page.enable", null, CancellationToken.None).ConfigureAwait(true); } - /// Closes the controller and waits for the browser process to exit (the profile is written). UI thread. + /// + /// 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. + /// private async Task CloseWebViewAsync() { _ui.VerifyAccess(); + _generation++; _session.Detach(); _devTools?.Close(); _devTools = null; @@ -378,25 +410,19 @@ internal sealed class WebView2Host : IBrowserHost var kind = e.ProcessFailedKind; _log.Warn("browser", $"WebView2: processo terminato ({kind})."); - // A closed or replaced WebView is not ours any more. + // A WebView that is closing, closed or replaced is not ours any more (a restart, «Scollega», a failed start). if (_closing || generation != _generation) { return; } - // During a start the failure is the start's own error (the caller retries); while a restart closes the old - // WebView the failure changes nothing. + // During a start the failure is the start's own error: the start closes what it created and the caller retries. if (_starting) { _crashedWhileStarting |= kind == CoreWebView2ProcessFailedKind.BrowserProcessExited; return; } - if (_restarting) - { - return; - } - if (kind == CoreWebView2ProcessFailedKind.BrowserProcessExited) { // The whole browser is gone: commands fail from now on, and the owner starts it again (same profile), as @@ -511,7 +537,7 @@ internal sealed class WebView2Host : IBrowserHost } /// - /// Runs one step of the life of the WebView (start, restart, reset, stop) after the others. UI thread. With + /// Runs one step of the life of the WebView (start, restart, stop) after the others. UI thread. With /// the step runs anyway once that time has passed (stopping must not hang behind a start /// that WebView2 never completes). /// diff --git a/src/Febe.Desktop/LEGGIMI.md b/src/Febe.Desktop/LEGGIMI.md index cea03f8..7868c2f 100644 --- a/src/Febe.Desktop/LEGGIMI.md +++ b/src/Febe.Desktop/LEGGIMI.md @@ -34,6 +34,10 @@ Regole che valgono anche qui: - 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). diff --git a/tests/Febe.Tests.Windows/Support/BrowserBed.cs b/tests/Febe.Tests.Windows/Support/BrowserBed.cs index c09263b..4861f03 100644 --- a/tests/Febe.Tests.Windows/Support/BrowserBed.cs +++ b/tests/Febe.Tests.Windows/Support/BrowserBed.cs @@ -79,6 +79,10 @@ internal sealed class BrowserBed : IAsyncDisposable /// Reads a value of the UI thread (the window, its position) through the dispatcher. public Task OnUiAsync(Func read) => Ui.InvokeAsync(read); + /// The class names of the child windows of «Browser di Febe»: one per WebView hosted in it. + public Task> ChildWindowsAsync() => + OnUiAsync(() => Browser.Host.Window is { } window ? ChildWindows.Of(window.Handle) : (IReadOnlyList)[]); + /// /// Starts the browser from a thread-pool thread, like FebeApp.BringUpBrowserAsync, and waits until /// returns. Fails at once when the log reports a failed start: the loop of diff --git a/tests/Febe.Tests.Windows/Support/ChildWindows.cs b/tests/Febe.Tests.Windows/Support/ChildWindows.cs new file mode 100644 index 0000000..4d85210 --- /dev/null +++ b/tests/Febe.Tests.Windows/Support/ChildWindows.cs @@ -0,0 +1,31 @@ +using System.Runtime.InteropServices; + +namespace Febe.Tests.Windows.Support; + +/// +/// 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. +/// +internal static class ChildWindows +{ + /// The class names of the direct children of , in Z order. + public static IReadOnlyList Of(IntPtr parent) + { + var names = new List(); + 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); +} diff --git a/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs b/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs index 31f79f1..5b09e71 100644 --- a/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs +++ b/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs @@ -132,6 +132,60 @@ public sealed class WebView2LifecycleTests Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text); } + /// + /// 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. + /// + [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); + } + [TestMethod] [Timeout(180_000, CooperativeCancellation = true)] public async Task WhenItsBrowserProcessDiesTheBrowserStartsAgainByItself() From 7aaa93fe3b7505485aeb5ec713730ecb02d5b0a5 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:27:22 +0200 Subject: [PATCH 13/15] 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() From f48b6abac4dd43075085ae73dc37160f1dcad784 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:29:48 +0200 Subject: [PATCH 14/15] Prove: l'errore di chi ascolta la ripartenza si prova sulla CI per Linux MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/windows.md | 16 +++--- .../WebView2CdpSessionAttachTests.cs | 55 ------------------- .../Desktop/WebView2CdpSessionTests.cs | 20 +++++++ 3 files changed, 29 insertions(+), 62 deletions(-) delete mode 100644 tests/Febe.Tests.Windows/WebView2CdpSessionAttachTests.cs diff --git a/docs/windows.md b/docs/windows.md index 1e4c9ea..a850571 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -242,20 +242,22 @@ dotnet test tests/Febe.Tests.Windows --filter "FullyQualifiedName~WebView2CdpTes 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. +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); ripartenza dopo l'arresto del processo; «composizione» di S2 | +| `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 | -| `WebView2CdpSessionAttachTests` | Senza WebView2: un errore di chi ascolta la ripartenza non disfa l'avvio | + +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 diff --git a/tests/Febe.Tests.Windows/WebView2CdpSessionAttachTests.cs b/tests/Febe.Tests.Windows/WebView2CdpSessionAttachTests.cs deleted file mode 100644 index 349508a..0000000 --- a/tests/Febe.Tests.Windows/WebView2CdpSessionAttachTests.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Collections.Concurrent; -using Febe.Browser.Diagnostics; -using Febe.Browser.WebView2; - -namespace Febe.Tests.Windows; - -/// -/// The attach of a new WebView to the session (after a crash or «Scollega»), without WebView2: an error of whoever -/// listens to must not undo a start that worked. -/// -[TestClass] -public sealed class WebView2CdpSessionAttachTests -{ - [TestMethod] - public async Task AFailingReconnectionHandlerDoesNotUndoTheAttach() - { - var log = new ListLog(); - 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 SilentDevTools()); - session.Attach(new SilentDevTools()); - - 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)), string.Join('\n', log.Lines)); - Assert.AreEqual("{}", (await session.SendAsync("Page.enable", ct: CancellationToken.None)).GetRawText()); - } - - private sealed class SilentDevTools : IWebView2DevTools - { - public Task CallMethodAsync(string methodName, string parametersAsJson) => Task.FromResult("{}"); - - public IDisposable Subscribe(string eventName, Action onEvent) => new Nothing(); - - private sealed class Nothing : IDisposable - { - public void Dispose() - { - } - } - } - - private sealed class ListLog : IBrowserLog - { - private readonly ConcurrentQueue _lines = new(); - - public IReadOnlyList Lines => [.. _lines]; - - public void Write(BrowserLogLevel level, string message, Exception? exception = null) => - _lines.Enqueue($"{level} {message} {exception?.GetType().Name}"); - } -} diff --git a/tests/Febe.Tests/Desktop/WebView2CdpSessionTests.cs b/tests/Febe.Tests/Desktop/WebView2CdpSessionTests.cs index f8635f1..1e85dee 100644 --- a/tests/Febe.Tests/Desktop/WebView2CdpSessionTests.cs +++ b/tests/Febe.Tests/Desktop/WebView2CdpSessionTests.cs @@ -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() { From f09ce4f2d5f591109498b0d1567d4240df1dff74 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 13:52:07 +0200 Subject: [PATCH 15/15] =?UTF-8?q?Collegamento:=20senza=20il=20nome=20dell'?= =?UTF-8?q?account=20il=20pannello=20dice=20=C2=ABCollegato=C2=BB,=20non?= =?UTF-8?q?=20=C2=ABCollegato=20come=20@=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/decisioni.md | 1 + src/Febe.Web/wwwroot/js/pages/connection.js | 7 +++++-- tests/Febe.Tests/Web/InterfaceTests.cs | 15 +++++++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index d2301f8..2013a3d 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -236,3 +236,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 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 | diff --git a/src/Febe.Web/wwwroot/js/pages/connection.js b/src/Febe.Web/wwwroot/js/pages/connection.js index 3959399..752312d 100644 --- a/src/Febe.Web/wwwroot/js/pages/connection.js +++ b/src/Febe.Web/wwwroot/js/pages/connection.js @@ -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')), diff --git a/tests/Febe.Tests/Web/InterfaceTests.cs b/tests/Febe.Tests/Web/InterfaceTests.cs index a32bfe4..52fce79 100644 --- a/tests/Febe.Tests/Web/InterfaceTests.cs +++ b/tests/Febe.Tests/Web/InterfaceTests.cs @@ -112,6 +112,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() {