From a25f60970d1f2114effdca1a8d1275591d2597d0 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:09:30 +0200 Subject: [PATCH 01/44] 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(); +} -- 2.54.1 From a6623e57368f1828aebcd6b9470319cdee97b519 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:10:41 +0200 Subject: [PATCH 02/44] 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) { -- 2.54.1 From ccfd8b5c08a60ee9e594af656e86e027abf0fab9 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:29:59 +0200 Subject: [PATCH 03/44] 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"); + } +} -- 2.54.1 From 3f222448eeb6880c982c0fe683836b6a40e03b59 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:30:11 +0200 Subject: [PATCH 04/44] 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}"); + } +} -- 2.54.1 From 2ef098226b56316fa29aa42db4d30d683e209973 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:30:20 +0200 Subject: [PATCH 05/44] 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); } -- 2.54.1 From a305a9ed2a00a6f2f8bede137503436176ea4daf Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:30:33 +0200 Subject: [PATCH 06/44] 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; + } + } +} -- 2.54.1 From cf618d898627f315b52556d79653e6cfdaa55aa8 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:30:51 +0200 Subject: [PATCH 07/44] 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); + } + } +} -- 2.54.1 From 7b0b0339f75d7a5823a9f6cc77eb1057854733d8 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:45:13 +0200 Subject: [PATCH 08/44] 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 -- 2.54.1 From e5e2b6864fac6ea958d8616a1c160731ec0db132 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:46:58 +0200 Subject: [PATCH 09/44] 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); -- 2.54.1 From 66a3fc7db6b12a1290c79b33ea81f1c1863eac83 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:53:48 +0200 Subject: [PATCH 10/44] 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); - } - } } -- 2.54.1 From 7fffa53c9001da6f8586115126ee7e1cd97da894 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:53:48 +0200 Subject: [PATCH 11/44] 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); + } +} -- 2.54.1 From 02e5cfe79c81ee40ae0632075cd6a87dd60901fc Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:10:02 +0200 Subject: [PATCH 12/44] Un solo blocco per .vscode in .gitignore Le regole per .vscode comparivano due volte, dal modello di Visual Studio e da quello di VS Code. Resta il blocco di VS Code, che ora ignora anche i file *.code-workspace: della cartella .vscode entrano nel repository solo settings.json, tasks.json, launch.json, extensions.json e gli snippet. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/.gitignore b/.gitignore index b0ddd2f..f1391fe 100644 --- a/.gitignore +++ b/.gitignore @@ -379,17 +379,6 @@ MigrationBackup/ # Fody - auto-generated XML schema FodyWeavers.xsd -# VS Code files for those working on multiple tools -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json -*.code-workspace - -# Local History for Visual Studio Code -.history/ - # Windows Installer files from build outputs *.cab *.msi @@ -401,12 +390,14 @@ FodyWeavers.xsd *.sln.iml # ---> VisualStudioCode +# Della cartella .vscode entra nel repository solo la configurazione condivisa (guida: Sviluppo, «Da VS Code»). .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json !.vscode/*.code-snippets +*.code-workspace # Local History for Visual Studio Code .history/ -- 2.54.1 From 4a4e85cc7f50fc676da089baefdfd631e6029a2e Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:10:10 +0200 Subject: [PATCH 13/44] =?UTF-8?q?Attivit=C3=A0=20di=20VS=20Code=20per=20co?= =?UTF-8?q?mpilare,=20provare,=20avviare=20il=20sito=20di=20prova=20e=20pu?= =?UTF-8?q?bblicare?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Da VS Code si compila con l'attività predefinita «compila» (dotnet build Febe.slnx -warnaserror, errori nel pannello Problemi), si prova con «prove» e «prove con filtro», si avvia il sito di prova in sfondo (pronto alla sua riga «Sito di prova: http://…») e si pubblica Febe.exe in un file solo come fa installer/costruisci.sh; l'immagine Docker c'è, segnata come bisognosa di Docker Desktop. Tutte le attività sono processi e non shell: il profilo di PowerShell di questo PC attiva l'ambiente conda di Pinokio, che mette davanti un .NET senza SDK. Le attività nascoste servono alle configurazioni di debug: compilare e avviare il sito, fermarlo a fine debug, fermare con un messaggio le configurazioni lanciate sul sistema sbagliato. Estensioni consigliate C# Dev Kit e C#; soluzione predefinita Febe.slnx. Co-Authored-By: Claude Opus 5.5 --- .vscode/extensions.json | 4 + .vscode/settings.json | 4 + .vscode/tasks.json | 200 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 208 insertions(+) create mode 100644 .vscode/extensions.json create mode 100644 .vscode/settings.json create mode 100644 .vscode/tasks.json diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..8682b19 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,4 @@ +// Estensioni consigliate per Febe: C# Dev Kit (soluzione, prove) e C# (linguaggio e debugger «coreclr» di launch.json). +{ + "recommendations": ["ms-dotnettools.csdevkit", "ms-dotnettools.csharp"] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..a309826 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +// Impostazioni di VS Code condivise per Febe: solo ciò che vale per tutti (guida: docs/guida/Sviluppo.md). +{ + "dotnet.defaultSolution": "Febe.slnx" +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..ecdff2a --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,200 @@ +// Attività di VS Code per Febe (guida: docs/guida/Sviluppo.md, «Da VS Code»). +// Sono i comandi della guida. Le due opzioni in più di compilazione e prove (-tl:off, -clp:ForceNoAlign) danno il +// registro classico, come nella CI: ogni errore su una riga sola, che $msCompile porta nel pannello Problemi. +// Tutte sono di tipo «process»: nessuna shell, quindi nessun profilo di PowerShell che metta davanti un altro .NET. +// Nessuna attività contatta Instagram: il sito di prova è locale (regola 1). +{ + "version": "2.0.0", + "tasks": [ + { + "label": "compila", + "detail": "dotnet build Febe.slnx -warnaserror: tutta la soluzione, gli avvisi sono errori", + "type": "process", + "command": "dotnet", + "args": [ + "build", + "${workspaceFolder}/Febe.slnx", + "-warnaserror", + "-nologo", + "-tl:off", + "-clp:ForceNoAlign" + ], + "group": { "kind": "build", "isDefault": true }, + "problemMatcher": "$msCompile", + "presentation": { "clear": true } + }, + { + "label": "prove", + "detail": "dotnet test tests/Febe.Tests: tutte le prove (senza Chromium e Xvfb quelle con il browser vero risultano saltate)", + "type": "process", + "command": "dotnet", + "args": [ + "test", + "${workspaceFolder}/tests/Febe.Tests", + "-nologo", + "-tl:off", + "-clp:ForceNoAlign" + ], + "group": { "kind": "test", "isDefault": true }, + "problemMatcher": "$msCompile", + "presentation": { "clear": true } + }, + { + "label": "prove con filtro", + "detail": "dotnet test tests/Febe.Tests --filter …: una prova o un gruppo, per nome", + "type": "process", + "command": "dotnet", + "args": [ + "test", + "${workspaceFolder}/tests/Febe.Tests", + "--filter", + "${input:filtroDelleProve}", + "-nologo", + "-tl:off", + "-clp:ForceNoAlign" + ], + "group": "test", + "problemMatcher": "$msCompile", + "presentation": { "clear": true } + }, + { + // In sfondo: VS Code lo considera pronto quando il sito scrive «Sito di prova: http://…». Il «CDN» ascolta su + // 127.0.0.2:8482, l'indirizzo che Febe si aspetta con --sito-di-prova http://127.0.0.1:8481. + "label": "sito di prova", + "detail": "dotnet run --project tools/Febe.SitoDiProva: http://127.0.0.1:8481, CDN su 127.0.0.2:8482, dati sintetici del seme 13", + "type": "process", + "command": "dotnet", + "args": [ + "run", + "--project", + "${workspaceFolder}/tools/Febe.SitoDiProva", + "--", + "--porta", + "8481", + "--porta-cdn", + "8482" + ], + "isBackground": true, + "problemMatcher": { + "base": "$msCompile", + "owner": "sito-di-prova", + "background": { + // Al lavoro dall'avvio (activeOnStart) fino alla riga di endsPattern, poi pronto per sempre: «(?!)» non trova + // mai nulla, quindi nessuna riga successiva lo rimette «al lavoro». + "activeOnStart": true, + "beginsPattern": "(?!)", + "endsPattern": "^Sito di prova: http://" + } + }, + "presentation": { "panel": "dedicated", "clear": true } + }, + { + "label": "pubblica Febe.exe", + "detail": "dotnet publish di Febe.Desktop in un file solo, come installer/costruisci.sh: out/pubblicazione/Febe.exe (Release, win-x64)", + "type": "process", + "command": "dotnet", + "args": [ + "publish", + "${workspaceFolder}/src/Febe.Desktop/Febe.Desktop.csproj", + "-c", + "Release", + "-r", + "win-x64", + "--self-contained", + "true", + "-p:PublishSingleFile=true", + "-p:IncludeNativeLibrariesForSelfExtract=true", + "-p:EnableCompressionInSingleFile=true", + "-nologo", + "-o", + "${workspaceFolder}/out/pubblicazione", + "-tl:off", + "-clp:ForceNoAlign" + ], + "group": "build", + "problemMatcher": "$msCompile", + "presentation": { "clear": true } + }, + { + "label": "immagine Docker (serve Docker Desktop)", + "detail": "docker build -f docker/Dockerfile -t febe .: compilazione e prove dentro l'immagine; serve un demone Docker avviato", + "type": "process", + "command": "docker", + "args": ["build", "-f", "docker/Dockerfile", "-t", "febe", "."], + "group": "build", + "problemMatcher": [], + "presentation": { "clear": true } + }, + + // Attività di servizio delle configurazioni di debug (.vscode/launch.json): non compaiono nell'elenco. + { + "label": "compila e avvia il sito di prova", + "detail": "Prima del debug contro il sito di prova: compila, poi avvia il sito (se è già aperto, lo usa così com'è)", + "dependsOrder": "sequence", + "dependsOn": ["compila", "sito di prova"], + "hide": true, + "problemMatcher": [] + }, + { + // VS Code non ha un'attività che ne chiuda un'altra: lo fa l'input «fermaIlSitoDiProva», che esegue il comando + // workbench.action.tasks.terminate mentre VS Code prepara questa attività. Il comando non restituisce un testo, + // quindi l'argomento resta com'è e «echo» lo stampa e basta. Un processo e non una shell: niente profilo da caricare. + "label": "ferma il sito di prova", + "detail": "A fine debug: chiude l'attività «sito di prova»", + "type": "process", + "command": "echo", + "args": ["${input:fermaIlSitoDiProva}"], + "windows": { "command": "cmd.exe", "args": ["/d", "/c", "echo", "${input:fermaIlSitoDiProva}"] }, + "hide": true, + "problemMatcher": [], + "presentation": { "reveal": "never", "echo": false, "close": true } + }, + { + "label": "solo su Linux", + "detail": "Ferma una configurazione che gira solo su Linux", + "type": "process", + "command": "sh", + "args": [ + "-c", + "echo 'Questa configurazione gira solo su Linux: il browser di Febe Server è Chromium su Xvfb.' >&2; exit 1" + ], + "windows": { + "command": "powershell.exe", + "args": [ + "-NoProfile", + "-NonInteractive", + "-Command", + "Write-Host 'Questa configurazione gira solo su Linux: il browser di Febe Server è Chromium su Xvfb. Su Windows usa «Febe per Windows · sito di prova».'; exit 1" + ] + }, + "hide": true, + "problemMatcher": [] + }, + { + "label": "solo su Windows", + "detail": "Ferma una configurazione che gira solo su Windows", + "type": "process", + "command": "sh", + "args": [ + "-c", + "echo 'Questa configurazione gira solo su Windows: Febe per Windows è WPF e WebView2. Su Linux usa «Febe Server · sito di prova (solo Linux)».' >&2; exit 1" + ], + "hide": true, + "problemMatcher": [] + } + ], + "inputs": [ + { + "id": "filtroDelleProve", + "type": "promptString", + "description": "Filtro di dotnet test, per esempio FullyQualifiedName~Febe.Tests.Docs (oppure solo una parte del nome: IconTests)", + "default": "FullyQualifiedName~Febe.Tests.Docs" + }, + { + "id": "fermaIlSitoDiProva", + "type": "command", + "command": "workbench.action.tasks.terminate", + "args": "sito di prova" + } + ] +} -- 2.54.1 From f324105371897293ae5300b4baee1e6a9cd4b266 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:10:11 +0200 Subject: [PATCH 14/44] Configurazioni di debug di Febe per VS Code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit F5 avvia Febe per Windows contro il sito di prova, che parte prima e si ferma dopo, con dati e libreria in %USERPROFILE%\FebeSviluppo e mai nella cartella vera. Ci sono anche il sito di prova nel debugger che avvia Febe quando è pronto, la dimostrazione con l'interfaccia servita dai sorgenti, il sito di prova da solo, la simulazione di 30 giorni e il server contro il sito di prova, che serve Chromium su Xvfb e quindi gira solo su Linux: altrove si ferma con un messaggio. Ultima e separata, Febe per Windows con Instagram e i dati veri, per le prove dal vivo di Alberto: prima di compilare chiede conferma, Esc annulla. Tutte scrivono nella Console di debug e non nel terminale integrato, che caricando il profilo di PowerShell trovava un .NET 8 e Febe non partiva. Co-Authored-By: Claude Opus 5.5 --- .vscode/launch.json | 204 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 204 insertions(+) create mode 100644 .vscode/launch.json diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..2490e2a --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,204 @@ +// Configurazioni di debug di Febe (guida: docs/guida/Sviluppo.md, «Da VS Code»). Tipo «coreclr» dell'estensione C#. +// - Prima di partire compilano tutta la soluzione con l'attività «compila» (.vscode/tasks.json). +// - Febe per Windows di sviluppo tiene dati e libreria in %USERPROFILE%\FebeSviluppo: mai in %LOCALAPPDATA%\Febe. +// - Nessuna configurazione contatta Instagram tranne l'ultima, «⚠ Febe per Windows · Instagram vero (dati veri)»: +// è per le prove dal vivo di Alberto (regola 1) e chiede conferma prima di partire. +// - VS Code non sa nascondere una configurazione per sistema operativo: quelle che non possono girare su un sistema +// lì si fermano subito con un messaggio (attività «solo su Windows» e «solo su Linux»). +// - Tutte usano la Console di debug («internalConsole»), mai il terminale integrato: il terminale carica il profilo di +// PowerShell, che può mettere davanti un altro .NET (per esempio quello di un ambiente conda, con il solo .NET 8, e +// il programma non parte). La Console di debug usa l'ambiente di VS Code. +{ + "version": "0.2.0", + "configurations": [ + { + // Il sito di prova parte come attività di sfondo (porte 8481 e 8482) e a fine debug si ferma. + "name": "Febe per Windows · sito di prova", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "compila e avvia il sito di prova", + "postDebugTask": "ferma il sito di prova", + "program": "${workspaceFolder}/src/Febe.Desktop/bin/Debug/net10.0-windows/Febe.exe", + "args": [ + "--dati", + "${env:USERPROFILE}\\FebeSviluppo\\dati", + "--libreria", + "${env:USERPROFILE}\\FebeSviluppo\\libreria", + "--sito-di-prova", + "http://127.0.0.1:8481", + "--accesso-di-prova", + "--prima-sessione", + "30", + "--sviluppo" + ], + "cwd": "${workspaceFolder}", + "console": "internalConsole", + "logging": { "moduleLoad": false }, + "linux": { "preLaunchTask": "solo su Windows" }, + "osx": { "preLaunchTask": "solo su Windows" }, + "presentation": { "group": "1-windows", "order": 1 } + }, + { + // Il sito di prova nel debugger; quando scrive «Sito di prova: http://…» parte anche Febe per Windows + // (configurazione nascosta qui sotto), che si ferma insieme al sito. + "name": "Sito di prova + Febe per Windows", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "compila", + "program": "${workspaceFolder}/tools/Febe.SitoDiProva/bin/Debug/net10.0/febe-sito-di-prova.dll", + "args": ["--porta", "8481", "--porta-cdn", "8482"], + "cwd": "${workspaceFolder}", + "console": "internalConsole", + "serverReadyAction": { + "action": "startDebugging", + "pattern": "Sito di prova: http://", + "name": "Febe per Windows · contro il sito già avviato", + "killOnServerStop": true + }, + "checkForDevCert": false, + "logging": { "moduleLoad": false }, + "linux": { "preLaunchTask": "solo su Windows" }, + "osx": { "preLaunchTask": "solo su Windows" }, + "presentation": { "group": "1-windows", "order": 2 } + }, + { + "name": "Febe per Windows · contro il sito già avviato", + "type": "coreclr", + "request": "launch", + "program": "${workspaceFolder}/src/Febe.Desktop/bin/Debug/net10.0-windows/Febe.exe", + "args": [ + "--dati", + "${env:USERPROFILE}\\FebeSviluppo\\dati", + "--libreria", + "${env:USERPROFILE}\\FebeSviluppo\\libreria", + "--sito-di-prova", + "http://127.0.0.1:8481", + "--accesso-di-prova", + "--prima-sessione", + "30", + "--sviluppo" + ], + "cwd": "${workspaceFolder}", + "console": "internalConsole", + "logging": { "moduleLoad": false }, + "presentation": { "hidden": true } + }, + { + // L'interfaccia viene da src/Febe.Web/wwwroot (FEBE_INTERFACCIA): modifichi un file e ricarichi la pagina. + // Fermata dal debugger, la dimostrazione non cancella la sua cartella temporanea: su Windows finisce in + // %USERPROFILE%\FebeSviluppo\temporanei, che si svuota quando vuoi. + "name": "Febe Server · dimostrazione (--demo)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "compila", + "program": "${workspaceFolder}/src/Febe.Server/bin/Debug/net10.0/febe.dll", + "args": ["--demo"], + "env": { "FEBE_INTERFACCIA": "${workspaceFolder}/src/Febe.Web/wwwroot" }, + "windows": { + "env": { + "FEBE_INTERFACCIA": "${workspaceFolder}/src/Febe.Web/wwwroot", + "TEMP": "${env:USERPROFILE}\\FebeSviluppo\\temporanei", + "TMP": "${env:USERPROFILE}\\FebeSviluppo\\temporanei" + } + }, + "cwd": "${workspaceFolder}", + "console": "internalConsole", + "serverReadyAction": { "action": "openExternally", "pattern": "Apri (https?://\\S+)" }, + "checkForDevCert": false, + "logging": { "moduleLoad": false }, + "presentation": { "group": "2-strumenti", "order": 1 } + }, + { + "name": "Sito di prova", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "compila", + "program": "${workspaceFolder}/tools/Febe.SitoDiProva/bin/Debug/net10.0/febe-sito-di-prova.dll", + "args": ["--porta", "8481", "--porta-cdn", "8482"], + "cwd": "${workspaceFolder}", + "console": "internalConsole", + "logging": { "moduleLoad": false }, + "presentation": { "group": "2-strumenti", "order": 2 } + }, + { + "name": "Simulazione 30 giorni (prudente)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "compila", + "program": "${workspaceFolder}/src/Febe.Server/bin/Debug/net10.0/febe.dll", + "args": ["--simula", "30g", "--profilo", "prudente"], + "cwd": "${workspaceFolder}", + "console": "internalConsole", + "logging": { "moduleLoad": false }, + "presentation": { "group": "2-strumenti", "order": 3 } + }, + { + // Il server vero contro il sito di prova, con Chromium su Xvfb (specifica §11): solo su Linux. Come root serve + // anche --senza-sandbox; se Chromium non è nel PATH, FEBE_CHROMIUM. Interfaccia su 127.0.0.1:8480, password «prova». + "name": "Febe Server · sito di prova (solo Linux)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "compila e avvia il sito di prova", + "postDebugTask": "ferma il sito di prova", + "program": "${workspaceFolder}/src/Febe.Server/bin/Debug/net10.0/febe.dll", + "args": [ + "--dati", + "${env:HOME}/FebeSviluppo/dati", + "--libreria", + "${env:HOME}/FebeSviluppo/libreria", + "--importa", + "${env:HOME}/FebeSviluppo/importa", + "--ascolta", + "127.0.0.1", + "--sito-di-prova", + "http://127.0.0.1:8481", + "--accesso-di-prova", + "--prima-sessione", + "30" + ], + "env": { + "FEBE_PASSWORD": "prova", + "FEBE_INTERFACCIA": "${workspaceFolder}/src/Febe.Web/wwwroot" + }, + "cwd": "${workspaceFolder}", + "console": "internalConsole", + "terminateChildProcesses": true, + "serverReadyAction": { + "action": "openExternally", + "pattern": "Interfaccia sulla porta (\\d+)", + "uriFormat": "http://127.0.0.1:%s/" + }, + "checkForDevCert": false, + "logging": { "moduleLoad": false }, + // Su Windows e macOS si ferma con un messaggio; anche con «Esegui comunque il debug» stampa solo l'aiuto. + "windows": { "preLaunchTask": "solo su Linux", "postDebugTask": "", "args": ["--aiuto"] }, + "osx": { "preLaunchTask": "solo su Linux", "postDebugTask": "", "args": ["--aiuto"] }, + "presentation": { "group": "3-linux", "order": 1 } + }, + { + // Instagram vero, con l'account e i dati veri (%LOCALAPPDATA%\Febe, Immagini\Febe): solo per le prove dal vivo di + // Alberto. Chiede conferma (Esc annulla). Una versione di sviluppo può aggiornare il database vero. Se Febe + // installato è aperto, prima esci da lui (menu dell'icona ▸ Esci): un solo Febe per cartella dei dati. + "name": "⚠ Febe per Windows · Instagram vero (dati veri)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "${input:confermaInstagramVero}", + "program": "${workspaceFolder}/src/Febe.Desktop/bin/Debug/net10.0-windows/Febe.exe", + "args": [], + "cwd": "${workspaceFolder}", + "console": "internalConsole", + "logging": { "moduleLoad": false }, + "linux": { "preLaunchTask": "solo su Windows" }, + "osx": { "preLaunchTask": "solo su Windows" }, + "presentation": { "group": "9-instagram-vero", "order": 1 } + } + ], + "inputs": [ + { + "id": "confermaInstagramVero", + "type": "pickString", + "description": "INSTAGRAM VERO con l'account e i dati veri di Alberto. Invio avvia, Esc annulla.", + "options": [{ "label": "Sì, avvia Febe con Instagram vero", "value": "compila" }] + } + ] +} -- 2.54.1 From 7a54eceaaf3a7641711fb59b0e0cf0ea24b29cc4 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:10:12 +0200 Subject: [PATCH 15/44] Guida: come si lavora con Febe da VS Code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La pagina Sviluppo ha una sezione «Da VS Code»: che cosa fa ogni configurazione di debug, dove vanno i dati di sviluppo, perché i programmi scrivono nella Console di debug, come si chiude Febe in debug e che cosa resta della dimostrazione fermata dal debugger. CLAUDE.md la richiama fra i comandi, con la cartella dei dati di sviluppo. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 1 + docs/guida/Sviluppo.md | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index 0dc4bf7..468fbdd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,6 +10,7 @@ All'inizio di ogni sessione leggi docs/stato.md. - Avviare in modalità dimostrativa: `dotnet run --project src/Febe.Server -- --demo` - Simulare il motore: `dotnet run --project src/Febe.Server -- --simula 30g --profilo prudente` - Immagine Docker: `docker build -f docker/Dockerfile -t febe .` +- Da VS Code: attività e configurazioni di debug in `.vscode/` (guida: `docs/guida/Sviluppo.md`, «Da VS Code»); Febe per Windows di sviluppo tiene i dati in `%USERPROFILE%\FebeSviluppo`, mai in `%LOCALAPPDATA%\Febe`. ## Regole che non si discutono (specifica §2) 1. IMPORTANTE: non contattare mai Instagram da prove, script o verifiche tue. Si usa solo tools/Febe.SitoDiProva. Le prove dal vivo le lancia Alberto. diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index 045686d..44ddb15 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -46,6 +46,41 @@ dotnet test tests/Febe.Tests --filter "FullyQualifiedName~Febe.Tests.Alerts" - La prova `Febe.Tests.Docs` controlla che questa guida dica tutto ciò che la specifica chiede (§15) e che ogni collegamento fra le pagine porti a una pagina che esiste. +## Da VS Code + +La cartella `.vscode/` prepara VS Code per Febe: estensioni consigliate (C# Dev Kit e C#), soluzione predefinita +`Febe.slnx`, attività e configurazioni di debug. Ogni configurazione compila prima con l'attività `compila` +(`dotnet build Febe.slnx -warnaserror`); gli errori del compilatore finiscono nel pannello Problemi. + +| Configurazione (Esegui e debug, F5) | Che cosa fa | +|---|---| +| Febe per Windows · sito di prova | Avvia il sito di prova come attività di sfondo (porte 8481 e 8482), poi Febe per Windows con `--sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30 --sviluppo`; a fine debug ferma il sito | +| Sito di prova + Febe per Windows | Il sito di prova nel debugger; quando è pronto parte anche Febe per Windows, che si ferma insieme al sito | +| Febe Server · dimostrazione (--demo) | La dimostrazione su `http://127.0.0.1:8480`, che si apre da sola nel browser; l'interfaccia viene da `src/Febe.Web/wwwroot` (`FEBE_INTERFACCIA`): modifichi un file e ricarichi la pagina | +| Sito di prova | Solo il sito di prova, nel debugger | +| Simulazione 30 giorni (prudente) | `--simula 30g --profilo prudente`, con il resoconto nella Console di debug | +| Febe Server · sito di prova (solo Linux) | Il server vero, con Chromium su Xvfb, contro il sito di prova: interfaccia su `127.0.0.1:8480`, password `prova` (come root serve anche `--senza-sandbox`). Su Windows e macOS si ferma con un messaggio | +| ⚠ Febe per Windows · Instagram vero (dati veri) | Febe senza opzioni: Instagram vero, `%LOCALAPPDATA%\Febe` e `Immagini\Febe`. Solo per le prove dal vivo di Alberto: chiede conferma, e una versione di sviluppo può aggiornare il database vero | + +- **Dati di sviluppo.** Febe per Windows di sviluppo tiene dati e libreria in `%USERPROFILE%\FebeSviluppo\dati` e + `%USERPROFILE%\FebeSviluppo\libreria` (il server su Linux in `~/FebeSviluppo`): fuori dal repository e mai nella + cartella vera. Con Febe chiuso si possono cancellare quando vuoi. +- Chiudendo la finestra Febe resta nell'area di notifica e il debug continua: per finire, menu dell'icona ▸ Esci oppure + Maiusc+F5. Finché Febe gira, `compila` non può sovrascrivere `Febe.exe`. +- Il sito di prova usa sempre le porte 8481 e 8482, come attività e come configurazione: uno alla volta. +- I programmi scrivono nella Console di debug e le attività partono senza shell: il terminale integrato carica il + profilo di PowerShell, che può mettere davanti un altro .NET (per esempio quello di un ambiente conda), e allora + `dotnet` non trova l'SDK 10 o Febe non parte («You must install or update .NET»). Se nel terminale + `dotnet --list-sdks` non mostra il 10, usa le attività, Git Bash oppure `conda deactivate`. +- Fermata dal debugger, la dimostrazione non cancella la sua cartella temporanea (`febe-dimostrazione-…`, una trentina + di MB): da VS Code su Windows finisce in `%USERPROFILE%\FebeSviluppo\temporanei`, che si svuota quando vuoi. Con + `dotnet run --project src/Febe.Server -- --demo` in un terminale, Ctrl+C la chiude in ordine e la cancella. +- Le configurazioni automatiche del C# Dev Kit («C#: …») avviano un progetto senza opzioni: per Febe per Windows vuol + dire Instagram vero e dati veri. Usa quelle dell'elenco qui sopra. +- Attività (Terminale ▸ Esegui attività): `compila`, `prove` (`dotnet test tests/Febe.Tests`), `prove con filtro` + (chiede il filtro, per esempio `FullyQualifiedName~Febe.Tests.Docs`), `sito di prova`, `pubblica Febe.exe` (un file + solo in `out/pubblicazione/`, come `installer/costruisci.sh`) e `immagine Docker (serve Docker Desktop)`. + ## Dimostrazione ```sh -- 2.54.1 From 1b5a8d4dcdbd4ed46cd2d02fe55c6cf469ca6dcc Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:10:12 +0200 Subject: [PATCH 16/44] Decisioni sulla configurazione di VS Code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Le scelte fatte per .vscode, ognuna con il suo motivo: debug coreclr senza launchSettings.json, dati di sviluppo fuori dal repository, registro classico per il pannello Problemi, sito di prova in sfondo fermato a fine debug, avvio in catena al posto di un compound, configurazioni legate a un sistema, conferma per Instagram vero, Console di debug e attività senza shell, cartella temporanea della dimostrazione. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/decisioni.md b/docs/decisioni.md index be3e037..b264c27 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -226,3 +226,12 @@ 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 | VS Code: configurazione condivisa in `.vscode/` (`launch.json`, `tasks.json`, `extensions.json`, `settings.json` con la sola `dotnet.defaultSolution`); debug con il tipo `coreclr` dell'estensione C#, senza file `launchSettings.json` | Il tipo `dotnet` del C# Dev Kit accetta solo il progetto e un profilo di `launchSettings.json`: niente argomenti, variabili d'ambiente, attività prima e dopo, `serverReadyAction`. Con `coreclr` tutto sta in un file solo | +| 2026-10-20 | Febe per Windows di sviluppo da VS Code con `--dati %USERPROFILE%\FebeSviluppo\dati` e `--libreria %USERPROFILE%\FebeSviluppo\libreria`; il debug avvia `Febe.exe`, non `dotnet Febe.dll` | Mai la cartella vera `%LOCALAPPDATA%\Febe`; fuori dal repository perché profilo del browser e libreria crescono e non devono finire in un commit. Con `Febe.exe` il percorso del processo è quello di Febe e non di `dotnet.exe` (lo usa l'avvio con il computer) | +| 2026-10-20 | Attività di compilazione, prove e pubblicazione con `-tl:off -clp:ForceNoAlign` oltre al comando della guida | Registro classico, come nella CI: ogni errore su una riga sola, senza le righe che il terminal logger ridisegna nel terminale; `$msCompile` lo porta nel pannello Problemi (provato con un errore voluto) | +| 2026-10-20 | Il sito di prova è un'attività di sfondo, pronta alla riga «Sito di prova: http://»; a fine debug la ferma un input che esegue `workbench.action.tasks.terminate` | VS Code non ha un'attività che ne chiuda un'altra: un input di tipo `command` è l'unico modo per farlo da `postDebugTask` | +| 2026-10-20 | «Sito di prova + Febe per Windows» non è un compound: la configurazione del sito avvia Febe con `serverReadyAction` (`startDebugging`, `killOnServerStop`) quando il sito scrive di essere pronto | Un compound avvia tutto insieme e senza ordine: Febe con `--accesso-di-prova` poteva cercare il sito prima che ascoltasse | +| 2026-10-20 | Le configurazioni legate a un sistema (Febe per Windows; Febe Server con il sito di prova, cioè Chromium su Xvfb) sugli altri sistemi si fermano con un messaggio (attività «solo su Windows» e «solo su Linux»; il server riceve anche solo `--aiuto`) | VS Code non sa nascondere una configurazione per sistema operativo: le proprietà `windows`, `linux` e `osx` contano solo all'avvio | +| 2026-10-20 | «⚠ Febe per Windows · Instagram vero (dati veri)» chiede conferma prima di compilare e partire (una scelta sola, Esc annulla) | Regola 1: le prove dal vivo le lancia Alberto; un F5 distratto non deve aprire Instagram con l'account e il database veri | +| 2026-10-20 | Tutte le configurazioni di debug scrivono nella Console di debug (`internalConsole`), mai nel terminale integrato; le attività sono di tipo `process`, senza shell | Il terminale integrato e le attività `shell` caricano il profilo di PowerShell: su questo PC il profilo attiva l'ambiente conda di Pinokio, che mette in testa al `PATH` e in `DOTNET_ROOT` un .NET senza SDK e con il solo runtime 8. Lì `dotnet build` non trova l'SDK e Febe (net10.0) non parte («You must install or update .NET»), né come `febe.dll` né come `febe.exe`. Console di debug e attività `process` usano l'ambiente di VS Code | +| 2026-10-20 | La dimostrazione da VS Code serve l'interfaccia dai sorgenti (`FEBE_INTERFACCIA`), apre da sola il browser (`serverReadyAction`) e su Windows tiene la cartella temporanea in `%USERPROFILE%\FebeSviluppo\temporanei` (`TEMP`, `TMP`) | Si modifica `wwwroot` e si ricarica senza ricompilare. Fermata dal debugger, la dimostrazione non può cancellare la sua cartella (una trentina di MB): così resta fra i dati di sviluppo invece di accumularsi in `%TEMP%` | -- 2.54.1 From a144d611ac762ec8c7b60da1e176f8af76c2b54b Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:23:19 +0200 Subject: [PATCH 17/44] 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() -- 2.54.1 From 7aaa93fe3b7505485aeb5ec713730ecb02d5b0a5 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:27:22 +0200 Subject: [PATCH 18/44] 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() -- 2.54.1 From f48b6abac4dd43075085ae73dc37160f1dcad784 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:29:48 +0200 Subject: [PATCH 19/44] 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() { -- 2.54.1 From 7bcb9f5f5a66936fafc694799d1f950c011e0c86 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:45:12 +0200 Subject: [PATCH 20/44] .vscode in JSON rigido: senza commenti, le spiegazioni nella guida MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Il controllo «File JSON» della CI legge ogni *.json tracciato con JSON.parse: con i commenti // dei quattro file di .vscode il lavoro «controlli» sarebbe fallito a ogni push dopo l'unione con il ramo della CI, e con lui tutta la verifica. VS Code legge anche il JSON rigido, quindi i commenti si tolgono e le spiegazioni passano nella guida («Da VS Code»), nei campi detail delle attività e in docs/decisioni.md. Co-Authored-By: Claude Opus 5.5 --- .vscode/extensions.json | 1 - .vscode/launch.json | 22 ---------------------- .vscode/settings.json | 1 - .vscode/tasks.json | 20 +++----------------- docs/decisioni.md | 3 ++- docs/guida/Sviluppo.md | 6 ++++-- 6 files changed, 9 insertions(+), 44 deletions(-) diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 8682b19..d19cdaa 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,4 +1,3 @@ -// Estensioni consigliate per Febe: C# Dev Kit (soluzione, prove) e C# (linguaggio e debugger «coreclr» di launch.json). { "recommendations": ["ms-dotnettools.csdevkit", "ms-dotnettools.csharp"] } diff --git a/.vscode/launch.json b/.vscode/launch.json index 2490e2a..5b44080 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,18 +1,7 @@ -// Configurazioni di debug di Febe (guida: docs/guida/Sviluppo.md, «Da VS Code»). Tipo «coreclr» dell'estensione C#. -// - Prima di partire compilano tutta la soluzione con l'attività «compila» (.vscode/tasks.json). -// - Febe per Windows di sviluppo tiene dati e libreria in %USERPROFILE%\FebeSviluppo: mai in %LOCALAPPDATA%\Febe. -// - Nessuna configurazione contatta Instagram tranne l'ultima, «⚠ Febe per Windows · Instagram vero (dati veri)»: -// è per le prove dal vivo di Alberto (regola 1) e chiede conferma prima di partire. -// - VS Code non sa nascondere una configurazione per sistema operativo: quelle che non possono girare su un sistema -// lì si fermano subito con un messaggio (attività «solo su Windows» e «solo su Linux»). -// - Tutte usano la Console di debug («internalConsole»), mai il terminale integrato: il terminale carica il profilo di -// PowerShell, che può mettere davanti un altro .NET (per esempio quello di un ambiente conda, con il solo .NET 8, e -// il programma non parte). La Console di debug usa l'ambiente di VS Code. { "version": "0.2.0", "configurations": [ { - // Il sito di prova parte come attività di sfondo (porte 8481 e 8482) e a fine debug si ferma. "name": "Febe per Windows · sito di prova", "type": "coreclr", "request": "launch", @@ -39,8 +28,6 @@ "presentation": { "group": "1-windows", "order": 1 } }, { - // Il sito di prova nel debugger; quando scrive «Sito di prova: http://…» parte anche Febe per Windows - // (configurazione nascosta qui sotto), che si ferma insieme al sito. "name": "Sito di prova + Febe per Windows", "type": "coreclr", "request": "launch", @@ -84,9 +71,6 @@ "presentation": { "hidden": true } }, { - // L'interfaccia viene da src/Febe.Web/wwwroot (FEBE_INTERFACCIA): modifichi un file e ricarichi la pagina. - // Fermata dal debugger, la dimostrazione non cancella la sua cartella temporanea: su Windows finisce in - // %USERPROFILE%\FebeSviluppo\temporanei, che si svuota quando vuoi. "name": "Febe Server · dimostrazione (--demo)", "type": "coreclr", "request": "launch", @@ -133,8 +117,6 @@ "presentation": { "group": "2-strumenti", "order": 3 } }, { - // Il server vero contro il sito di prova, con Chromium su Xvfb (specifica §11): solo su Linux. Come root serve - // anche --senza-sandbox; se Chromium non è nel PATH, FEBE_CHROMIUM. Interfaccia su 127.0.0.1:8480, password «prova». "name": "Febe Server · sito di prova (solo Linux)", "type": "coreclr", "request": "launch", @@ -170,15 +152,11 @@ }, "checkForDevCert": false, "logging": { "moduleLoad": false }, - // Su Windows e macOS si ferma con un messaggio; anche con «Esegui comunque il debug» stampa solo l'aiuto. "windows": { "preLaunchTask": "solo su Linux", "postDebugTask": "", "args": ["--aiuto"] }, "osx": { "preLaunchTask": "solo su Linux", "postDebugTask": "", "args": ["--aiuto"] }, "presentation": { "group": "3-linux", "order": 1 } }, { - // Instagram vero, con l'account e i dati veri (%LOCALAPPDATA%\Febe, Immagini\Febe): solo per le prove dal vivo di - // Alberto. Chiede conferma (Esc annulla). Una versione di sviluppo può aggiornare il database vero. Se Febe - // installato è aperto, prima esci da lui (menu dell'icona ▸ Esci): un solo Febe per cartella dei dati. "name": "⚠ Febe per Windows · Instagram vero (dati veri)", "type": "coreclr", "request": "launch", diff --git a/.vscode/settings.json b/.vscode/settings.json index a309826..70cf8cc 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,4 +1,3 @@ -// Impostazioni di VS Code condivise per Febe: solo ciò che vale per tutti (guida: docs/guida/Sviluppo.md). { "dotnet.defaultSolution": "Febe.slnx" } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index ecdff2a..1599c2b 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,14 +1,9 @@ -// Attività di VS Code per Febe (guida: docs/guida/Sviluppo.md, «Da VS Code»). -// Sono i comandi della guida. Le due opzioni in più di compilazione e prove (-tl:off, -clp:ForceNoAlign) danno il -// registro classico, come nella CI: ogni errore su una riga sola, che $msCompile porta nel pannello Problemi. -// Tutte sono di tipo «process»: nessuna shell, quindi nessun profilo di PowerShell che metta davanti un altro .NET. -// Nessuna attività contatta Instagram: il sito di prova è locale (regola 1). { "version": "2.0.0", "tasks": [ { "label": "compila", - "detail": "dotnet build Febe.slnx -warnaserror: tutta la soluzione, gli avvisi sono errori", + "detail": "dotnet build Febe.slnx -warnaserror: tutta la soluzione, gli avvisi sono errori; con -tl:off -clp:ForceNoAlign ogni errore sta su una riga e finisce nel pannello Problemi", "type": "process", "command": "dotnet", "args": [ @@ -58,10 +53,8 @@ "presentation": { "clear": true } }, { - // In sfondo: VS Code lo considera pronto quando il sito scrive «Sito di prova: http://…». Il «CDN» ascolta su - // 127.0.0.2:8482, l'indirizzo che Febe si aspetta con --sito-di-prova http://127.0.0.1:8481. "label": "sito di prova", - "detail": "dotnet run --project tools/Febe.SitoDiProva: http://127.0.0.1:8481, CDN su 127.0.0.2:8482, dati sintetici del seme 13", + "detail": "dotnet run --project tools/Febe.SitoDiProva: http://127.0.0.1:8481, CDN su 127.0.0.2:8482 (dove Febe lo cerca), dati sintetici del seme 13; in sfondo, pronto alla riga «Sito di prova: http://…»", "type": "process", "command": "dotnet", "args": [ @@ -79,8 +72,6 @@ "base": "$msCompile", "owner": "sito-di-prova", "background": { - // Al lavoro dall'avvio (activeOnStart) fino alla riga di endsPattern, poi pronto per sempre: «(?!)» non trova - // mai nulla, quindi nessuna riga successiva lo rimette «al lavoro». "activeOnStart": true, "beginsPattern": "(?!)", "endsPattern": "^Sito di prova: http://" @@ -125,8 +116,6 @@ "problemMatcher": [], "presentation": { "clear": true } }, - - // Attività di servizio delle configurazioni di debug (.vscode/launch.json): non compaiono nell'elenco. { "label": "compila e avvia il sito di prova", "detail": "Prima del debug contro il sito di prova: compila, poi avvia il sito (se è già aperto, lo usa così com'è)", @@ -136,11 +125,8 @@ "problemMatcher": [] }, { - // VS Code non ha un'attività che ne chiuda un'altra: lo fa l'input «fermaIlSitoDiProva», che esegue il comando - // workbench.action.tasks.terminate mentre VS Code prepara questa attività. Il comando non restituisce un testo, - // quindi l'argomento resta com'è e «echo» lo stampa e basta. Un processo e non una shell: niente profilo da caricare. "label": "ferma il sito di prova", - "detail": "A fine debug: chiude l'attività «sito di prova»", + "detail": "A fine debug: chiude l'attività «sito di prova» con l'input fermaIlSitoDiProva (comando workbench.action.tasks.terminate); echo stampa solo il suo argomento", "type": "process", "command": "echo", "args": ["${input:fermaIlSitoDiProva}"], diff --git a/docs/decisioni.md b/docs/decisioni.md index b264c27..90a590f 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -229,9 +229,10 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-10-20 | VS Code: configurazione condivisa in `.vscode/` (`launch.json`, `tasks.json`, `extensions.json`, `settings.json` con la sola `dotnet.defaultSolution`); debug con il tipo `coreclr` dell'estensione C#, senza file `launchSettings.json` | Il tipo `dotnet` del C# Dev Kit accetta solo il progetto e un profilo di `launchSettings.json`: niente argomenti, variabili d'ambiente, attività prima e dopo, `serverReadyAction`. Con `coreclr` tutto sta in un file solo | | 2026-10-20 | Febe per Windows di sviluppo da VS Code con `--dati %USERPROFILE%\FebeSviluppo\dati` e `--libreria %USERPROFILE%\FebeSviluppo\libreria`; il debug avvia `Febe.exe`, non `dotnet Febe.dll` | Mai la cartella vera `%LOCALAPPDATA%\Febe`; fuori dal repository perché profilo del browser e libreria crescono e non devono finire in un commit. Con `Febe.exe` il percorso del processo è quello di Febe e non di `dotnet.exe` (lo usa l'avvio con il computer) | | 2026-10-20 | Attività di compilazione, prove e pubblicazione con `-tl:off -clp:ForceNoAlign` oltre al comando della guida | Registro classico, come nella CI: ogni errore su una riga sola, senza le righe che il terminal logger ridisegna nel terminale; `$msCompile` lo porta nel pannello Problemi (provato con un errore voluto) | -| 2026-10-20 | Il sito di prova è un'attività di sfondo, pronta alla riga «Sito di prova: http://»; a fine debug la ferma un input che esegue `workbench.action.tasks.terminate` | VS Code non ha un'attività che ne chiuda un'altra: un input di tipo `command` è l'unico modo per farlo da `postDebugTask` | +| 2026-10-20 | Il sito di prova è un'attività di sfondo, pronta alla riga «Sito di prova: http://» (`activeOnStart`, con `beginsPattern` «(?!)», che non trova mai nulla); a fine debug la ferma un input che esegue `workbench.action.tasks.terminate` | VS Code legge `activeOnStart`, non `activeBegins`: senza, il debug aspettava il sito per sempre. Con «(?!)» nessuna riga successiva rimette l'attività «al lavoro». VS Code non ha un'attività che ne chiuda un'altra: un input di tipo `command` è l'unico modo per farlo da `postDebugTask` | | 2026-10-20 | «Sito di prova + Febe per Windows» non è un compound: la configurazione del sito avvia Febe con `serverReadyAction` (`startDebugging`, `killOnServerStop`) quando il sito scrive di essere pronto | Un compound avvia tutto insieme e senza ordine: Febe con `--accesso-di-prova` poteva cercare il sito prima che ascoltasse | | 2026-10-20 | Le configurazioni legate a un sistema (Febe per Windows; Febe Server con il sito di prova, cioè Chromium su Xvfb) sugli altri sistemi si fermano con un messaggio (attività «solo su Windows» e «solo su Linux»; il server riceve anche solo `--aiuto`) | VS Code non sa nascondere una configurazione per sistema operativo: le proprietà `windows`, `linux` e `osx` contano solo all'avvio | | 2026-10-20 | «⚠ Febe per Windows · Instagram vero (dati veri)» chiede conferma prima di compilare e partire (una scelta sola, Esc annulla) | Regola 1: le prove dal vivo le lancia Alberto; un F5 distratto non deve aprire Instagram con l'account e il database veri | | 2026-10-20 | Tutte le configurazioni di debug scrivono nella Console di debug (`internalConsole`), mai nel terminale integrato; le attività sono di tipo `process`, senza shell | Il terminale integrato e le attività `shell` caricano il profilo di PowerShell: su questo PC il profilo attiva l'ambiente conda di Pinokio, che mette in testa al `PATH` e in `DOTNET_ROOT` un .NET senza SDK e con il solo runtime 8. Lì `dotnet build` non trova l'SDK e Febe (net10.0) non parte («You must install or update .NET»), né come `febe.dll` né come `febe.exe`. Console di debug e attività `process` usano l'ambiente di VS Code | | 2026-10-20 | La dimostrazione da VS Code serve l'interfaccia dai sorgenti (`FEBE_INTERFACCIA`), apre da sola il browser (`serverReadyAction`) e su Windows tiene la cartella temporanea in `%USERPROFILE%\FebeSviluppo\temporanei` (`TEMP`, `TMP`) | Si modifica `wwwroot` e si ricarica senza ricompilare. Fermata dal debugger, la dimostrazione non può cancellare la sua cartella (una trentina di MB): così resta fra i dati di sviluppo invece di accumularsi in `%TEMP%` | +| 2026-10-20 | I file di `.vscode/` sono JSON rigido, senza commenti: le spiegazioni stanno nella guida (pagina «Sviluppo», «Da VS Code»), nei campi `detail` delle attività e in queste righe | Il controllo «File JSON» della CI legge ogni `*.json` tracciato con `JSON.parse`, e con i commenti `//` il lavoro «controlli» falliva a ogni push dopo l'unione. VS Code legge anche il JSON rigido, così il ramo non dipende da come la CI tratta i commenti | diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index 44ddb15..3c8c7c7 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -59,8 +59,8 @@ La cartella `.vscode/` prepara VS Code per Febe: estensioni consigliate (C# Dev | Febe Server · dimostrazione (--demo) | La dimostrazione su `http://127.0.0.1:8480`, che si apre da sola nel browser; l'interfaccia viene da `src/Febe.Web/wwwroot` (`FEBE_INTERFACCIA`): modifichi un file e ricarichi la pagina | | Sito di prova | Solo il sito di prova, nel debugger | | Simulazione 30 giorni (prudente) | `--simula 30g --profilo prudente`, con il resoconto nella Console di debug | -| Febe Server · sito di prova (solo Linux) | Il server vero, con Chromium su Xvfb, contro il sito di prova: interfaccia su `127.0.0.1:8480`, password `prova` (come root serve anche `--senza-sandbox`). Su Windows e macOS si ferma con un messaggio | -| ⚠ Febe per Windows · Instagram vero (dati veri) | Febe senza opzioni: Instagram vero, `%LOCALAPPDATA%\Febe` e `Immagini\Febe`. Solo per le prove dal vivo di Alberto: chiede conferma, e una versione di sviluppo può aggiornare il database vero | +| Febe Server · sito di prova (solo Linux) | Il server vero, con Chromium su Xvfb, contro il sito di prova: interfaccia su `127.0.0.1:8480`, password `prova` (come root serve anche `--senza-sandbox`, e `FEBE_CHROMIUM` se Chromium non è nel `PATH`). Su Windows e macOS si ferma con un messaggio; anche con «Esegui comunque il debug» stampa solo l'aiuto | +| ⚠ Febe per Windows · Instagram vero (dati veri) | Febe senza opzioni: Instagram vero, `%LOCALAPPDATA%\Febe` e `Immagini\Febe`. Solo per le prove dal vivo di Alberto: chiede conferma, e una versione di sviluppo può aggiornare il database vero. Se Febe installato è aperto, prima esci da lui (menu dell'icona ▸ Esci): un solo Febe per cartella dei dati | - **Dati di sviluppo.** Febe per Windows di sviluppo tiene dati e libreria in `%USERPROFILE%\FebeSviluppo\dati` e `%USERPROFILE%\FebeSviluppo\libreria` (il server su Linux in `~/FebeSviluppo`): fuori dal repository e mai nella @@ -80,6 +80,8 @@ La cartella `.vscode/` prepara VS Code per Febe: estensioni consigliate (C# Dev - Attività (Terminale ▸ Esegui attività): `compila`, `prove` (`dotnet test tests/Febe.Tests`), `prove con filtro` (chiede il filtro, per esempio `FullyQualifiedName~Febe.Tests.Docs`), `sito di prova`, `pubblica Febe.exe` (un file solo in `out/pubblicazione/`, come `installer/costruisci.sh`) e `immagine Docker (serve Docker Desktop)`. +- I file di `.vscode/` sono JSON senza commenti, così li legge anche un lettore rigido come quello dei controlli della + CI: le spiegazioni stanno in questa sezione, nei campi `detail` delle attività e in `docs/decisioni.md`. ## Dimostrazione -- 2.54.1 From a48899f522be28ef0b818ec180e73fb24e58fba3 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:46:36 +0200 Subject: [PATCH 21/44] Dati di sviluppo da VS Code in una cartella per checkout MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Il blocco contro le istanze doppie di Febe dipende dalla cartella dei dati: con una sola %USERPROFILE%\FebeSviluppo per tutti i checkout, F5 in un secondo worktree trovava il Febe del primo, gli chiedeva di mostrarsi e finiva subito, e un database migrato da un ramo più nuovo non si apriva più da main. Ora dati, libreria e cartella temporanea della dimostrazione stanno sotto FebeSviluppo\ (${workspaceFolderBasename}), e così il server su Linux. Co-Authored-By: Claude Opus 5.5 --- .vscode/launch.json | 18 +++++++++--------- CLAUDE.md | 2 +- docs/decisioni.md | 4 ++-- docs/guida/Sviluppo.md | 13 ++++++++----- 4 files changed, 20 insertions(+), 17 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 5b44080..c42e597 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -10,9 +10,9 @@ "program": "${workspaceFolder}/src/Febe.Desktop/bin/Debug/net10.0-windows/Febe.exe", "args": [ "--dati", - "${env:USERPROFILE}\\FebeSviluppo\\dati", + "${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\dati", "--libreria", - "${env:USERPROFILE}\\FebeSviluppo\\libreria", + "${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\libreria", "--sito-di-prova", "http://127.0.0.1:8481", "--accesso-di-prova", @@ -55,9 +55,9 @@ "program": "${workspaceFolder}/src/Febe.Desktop/bin/Debug/net10.0-windows/Febe.exe", "args": [ "--dati", - "${env:USERPROFILE}\\FebeSviluppo\\dati", + "${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\dati", "--libreria", - "${env:USERPROFILE}\\FebeSviluppo\\libreria", + "${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\libreria", "--sito-di-prova", "http://127.0.0.1:8481", "--accesso-di-prova", @@ -81,8 +81,8 @@ "windows": { "env": { "FEBE_INTERFACCIA": "${workspaceFolder}/src/Febe.Web/wwwroot", - "TEMP": "${env:USERPROFILE}\\FebeSviluppo\\temporanei", - "TMP": "${env:USERPROFILE}\\FebeSviluppo\\temporanei" + "TEMP": "${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\temporanei", + "TMP": "${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\temporanei" } }, "cwd": "${workspaceFolder}", @@ -125,11 +125,11 @@ "program": "${workspaceFolder}/src/Febe.Server/bin/Debug/net10.0/febe.dll", "args": [ "--dati", - "${env:HOME}/FebeSviluppo/dati", + "${env:HOME}/FebeSviluppo/${workspaceFolderBasename}/dati", "--libreria", - "${env:HOME}/FebeSviluppo/libreria", + "${env:HOME}/FebeSviluppo/${workspaceFolderBasename}/libreria", "--importa", - "${env:HOME}/FebeSviluppo/importa", + "${env:HOME}/FebeSviluppo/${workspaceFolderBasename}/importa", "--ascolta", "127.0.0.1", "--sito-di-prova", diff --git a/CLAUDE.md b/CLAUDE.md index 468fbdd..68eaf70 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,7 +10,7 @@ All'inizio di ogni sessione leggi docs/stato.md. - Avviare in modalità dimostrativa: `dotnet run --project src/Febe.Server -- --demo` - Simulare il motore: `dotnet run --project src/Febe.Server -- --simula 30g --profilo prudente` - Immagine Docker: `docker build -f docker/Dockerfile -t febe .` -- Da VS Code: attività e configurazioni di debug in `.vscode/` (guida: `docs/guida/Sviluppo.md`, «Da VS Code»); Febe per Windows di sviluppo tiene i dati in `%USERPROFILE%\FebeSviluppo`, mai in `%LOCALAPPDATA%\Febe`. +- Da VS Code: attività e configurazioni di debug in `.vscode/` (guida: `docs/guida/Sviluppo.md`, «Da VS Code»); Febe per Windows di sviluppo tiene i dati in `%USERPROFILE%\FebeSviluppo\`, mai in `%LOCALAPPDATA%\Febe`. ## Regole che non si discutono (specifica §2) 1. IMPORTANTE: non contattare mai Instagram da prove, script o verifiche tue. Si usa solo tools/Febe.SitoDiProva. Le prove dal vivo le lancia Alberto. diff --git a/docs/decisioni.md b/docs/decisioni.md index 90a590f..0f18c66 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -227,12 +227,12 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 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 | VS Code: configurazione condivisa in `.vscode/` (`launch.json`, `tasks.json`, `extensions.json`, `settings.json` con la sola `dotnet.defaultSolution`); debug con il tipo `coreclr` dell'estensione C#, senza file `launchSettings.json` | Il tipo `dotnet` del C# Dev Kit accetta solo il progetto e un profilo di `launchSettings.json`: niente argomenti, variabili d'ambiente, attività prima e dopo, `serverReadyAction`. Con `coreclr` tutto sta in un file solo | -| 2026-10-20 | Febe per Windows di sviluppo da VS Code con `--dati %USERPROFILE%\FebeSviluppo\dati` e `--libreria %USERPROFILE%\FebeSviluppo\libreria`; il debug avvia `Febe.exe`, non `dotnet Febe.dll` | Mai la cartella vera `%LOCALAPPDATA%\Febe`; fuori dal repository perché profilo del browser e libreria crescono e non devono finire in un commit. Con `Febe.exe` il percorso del processo è quello di Febe e non di `dotnet.exe` (lo usa l'avvio con il computer) | +| 2026-10-20 | Febe per Windows di sviluppo da VS Code con `--dati %USERPROFILE%\FebeSviluppo\\dati` e `--libreria %USERPROFILE%\FebeSviluppo\\libreria` (`${workspaceFolderBasename}`: una cartella per checkout); il debug avvia `Febe.exe`, non `dotnet Febe.dll` | Mai la cartella vera `%LOCALAPPDATA%\Febe`; fuori dal repository perché profilo del browser e libreria crescono e non devono finire in un commit. Una per checkout perché il blocco contro le istanze doppie dipende dalla cartella dei dati (F5 in un secondo worktree mostrava il Febe del primo e finiva subito) e un database migrato da un ramo più nuovo non si apre con una versione più vecchia. Con `Febe.exe` il percorso del processo è quello di Febe e non di `dotnet.exe` (lo usa l'avvio con il computer) | | 2026-10-20 | Attività di compilazione, prove e pubblicazione con `-tl:off -clp:ForceNoAlign` oltre al comando della guida | Registro classico, come nella CI: ogni errore su una riga sola, senza le righe che il terminal logger ridisegna nel terminale; `$msCompile` lo porta nel pannello Problemi (provato con un errore voluto) | | 2026-10-20 | Il sito di prova è un'attività di sfondo, pronta alla riga «Sito di prova: http://» (`activeOnStart`, con `beginsPattern` «(?!)», che non trova mai nulla); a fine debug la ferma un input che esegue `workbench.action.tasks.terminate` | VS Code legge `activeOnStart`, non `activeBegins`: senza, il debug aspettava il sito per sempre. Con «(?!)» nessuna riga successiva rimette l'attività «al lavoro». VS Code non ha un'attività che ne chiuda un'altra: un input di tipo `command` è l'unico modo per farlo da `postDebugTask` | | 2026-10-20 | «Sito di prova + Febe per Windows» non è un compound: la configurazione del sito avvia Febe con `serverReadyAction` (`startDebugging`, `killOnServerStop`) quando il sito scrive di essere pronto | Un compound avvia tutto insieme e senza ordine: Febe con `--accesso-di-prova` poteva cercare il sito prima che ascoltasse | | 2026-10-20 | Le configurazioni legate a un sistema (Febe per Windows; Febe Server con il sito di prova, cioè Chromium su Xvfb) sugli altri sistemi si fermano con un messaggio (attività «solo su Windows» e «solo su Linux»; il server riceve anche solo `--aiuto`) | VS Code non sa nascondere una configurazione per sistema operativo: le proprietà `windows`, `linux` e `osx` contano solo all'avvio | | 2026-10-20 | «⚠ Febe per Windows · Instagram vero (dati veri)» chiede conferma prima di compilare e partire (una scelta sola, Esc annulla) | Regola 1: le prove dal vivo le lancia Alberto; un F5 distratto non deve aprire Instagram con l'account e il database veri | | 2026-10-20 | Tutte le configurazioni di debug scrivono nella Console di debug (`internalConsole`), mai nel terminale integrato; le attività sono di tipo `process`, senza shell | Il terminale integrato e le attività `shell` caricano il profilo di PowerShell: su questo PC il profilo attiva l'ambiente conda di Pinokio, che mette in testa al `PATH` e in `DOTNET_ROOT` un .NET senza SDK e con il solo runtime 8. Lì `dotnet build` non trova l'SDK e Febe (net10.0) non parte («You must install or update .NET»), né come `febe.dll` né come `febe.exe`. Console di debug e attività `process` usano l'ambiente di VS Code | -| 2026-10-20 | La dimostrazione da VS Code serve l'interfaccia dai sorgenti (`FEBE_INTERFACCIA`), apre da sola il browser (`serverReadyAction`) e su Windows tiene la cartella temporanea in `%USERPROFILE%\FebeSviluppo\temporanei` (`TEMP`, `TMP`) | Si modifica `wwwroot` e si ricarica senza ricompilare. Fermata dal debugger, la dimostrazione non può cancellare la sua cartella (una trentina di MB): così resta fra i dati di sviluppo invece di accumularsi in `%TEMP%` | +| 2026-10-20 | La dimostrazione da VS Code serve l'interfaccia dai sorgenti (`FEBE_INTERFACCIA`), apre da sola il browser (`serverReadyAction`) e su Windows tiene la cartella temporanea in `%USERPROFILE%\FebeSviluppo\\temporanei` (`TEMP`, `TMP`) | Si modifica `wwwroot` e si ricarica senza ricompilare. Fermata dal debugger, la dimostrazione non può cancellare la sua cartella (una trentina di MB): così resta fra i dati di sviluppo invece di accumularsi in `%TEMP%` | | 2026-10-20 | I file di `.vscode/` sono JSON rigido, senza commenti: le spiegazioni stanno nella guida (pagina «Sviluppo», «Da VS Code»), nei campi `detail` delle attività e in queste righe | Il controllo «File JSON» della CI legge ogni `*.json` tracciato con `JSON.parse`, e con i commenti `//` il lavoro «controlli» falliva a ogni push dopo l'unione. VS Code legge anche il JSON rigido, così il ramo non dipende da come la CI tratta i commenti | diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index 3c8c7c7..fce5df8 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -62,9 +62,12 @@ La cartella `.vscode/` prepara VS Code per Febe: estensioni consigliate (C# Dev | Febe Server · sito di prova (solo Linux) | Il server vero, con Chromium su Xvfb, contro il sito di prova: interfaccia su `127.0.0.1:8480`, password `prova` (come root serve anche `--senza-sandbox`, e `FEBE_CHROMIUM` se Chromium non è nel `PATH`). Su Windows e macOS si ferma con un messaggio; anche con «Esegui comunque il debug» stampa solo l'aiuto | | ⚠ Febe per Windows · Instagram vero (dati veri) | Febe senza opzioni: Instagram vero, `%LOCALAPPDATA%\Febe` e `Immagini\Febe`. Solo per le prove dal vivo di Alberto: chiede conferma, e una versione di sviluppo può aggiornare il database vero. Se Febe installato è aperto, prima esci da lui (menu dell'icona ▸ Esci): un solo Febe per cartella dei dati | -- **Dati di sviluppo.** Febe per Windows di sviluppo tiene dati e libreria in `%USERPROFILE%\FebeSviluppo\dati` e - `%USERPROFILE%\FebeSviluppo\libreria` (il server su Linux in `~/FebeSviluppo`): fuori dal repository e mai nella - cartella vera. Con Febe chiuso si possono cancellare quando vuoi. +- **Dati di sviluppo.** Febe per Windows di sviluppo tiene dati e libreria in + `%USERPROFILE%\FebeSviluppo\\dati` e `%USERPROFILE%\FebeSviluppo\\libreria`, dove `` è + il nome della cartella aperta in VS Code (per esempio `Febe`; il server su Linux in `~/FebeSviluppo/`): + fuori dal repository e mai nella cartella vera. Una cartella per checkout perché su una cartella dei dati gira un + Febe solo (un secondo avvio mostra il primo ed esce) e un database scritto da un ramo più nuovo non si apre con una + versione più vecchia. Con Febe chiuso si possono cancellare quando vuoi. - Chiudendo la finestra Febe resta nell'area di notifica e il debug continua: per finire, menu dell'icona ▸ Esci oppure Maiusc+F5. Finché Febe gira, `compila` non può sovrascrivere `Febe.exe`. - Il sito di prova usa sempre le porte 8481 e 8482, come attività e come configurazione: uno alla volta. @@ -73,8 +76,8 @@ La cartella `.vscode/` prepara VS Code per Febe: estensioni consigliate (C# Dev `dotnet` non trova l'SDK 10 o Febe non parte («You must install or update .NET»). Se nel terminale `dotnet --list-sdks` non mostra il 10, usa le attività, Git Bash oppure `conda deactivate`. - Fermata dal debugger, la dimostrazione non cancella la sua cartella temporanea (`febe-dimostrazione-…`, una trentina - di MB): da VS Code su Windows finisce in `%USERPROFILE%\FebeSviluppo\temporanei`, che si svuota quando vuoi. Con - `dotnet run --project src/Febe.Server -- --demo` in un terminale, Ctrl+C la chiude in ordine e la cancella. + di MB): da VS Code su Windows finisce in `%USERPROFILE%\FebeSviluppo\\temporanei`, che si svuota quando + vuoi. Con `dotnet run --project src/Febe.Server -- --demo` in un terminale, Ctrl+C la chiude in ordine e la cancella. - Le configurazioni automatiche del C# Dev Kit («C#: …») avviano un progetto senza opzioni: per Febe per Windows vuol dire Instagram vero e dati veri. Usa quelle dell'elenco qui sopra. - Attività (Terminale ▸ Esegui attività): `compila`, `prove` (`dotnet test tests/Febe.Tests`), `prove con filtro` -- 2.54.1 From 3170fbd8b63d85502bca1e6442618ac1ff007197 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:54:13 +0200 Subject: [PATCH 22/44] Febe per Windows avviato fuori da launch.json va sul sito di prova MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Il pulsante ▷ «Debug project associated with this file» e «Start New Instance» del C# Dev Kit, consigliato dal ramo, e così dotnet run --project src/Febe.Desktop, avviavano Febe senza opzioni: Instagram vero, dati e libreria veri, senza la conferma della configurazione ⚠. Un launchSettings.json di Febe.Desktop con un solo profilo chiude la strada: sito di prova e dati in %USERPROFILE%\FebeSviluppo\comune. Provato che dotnet run e il Dev Kit leggono il profilo ed espandono %USERPROFILE%; le configurazioni coreclr di launch.json non lo leggono, perché lo cercano nella radice. Instagram vero dal terminale resta possibile con --no-launch-profile. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 3 ++- docs/guida/Sviluppo.md | 9 +++++++-- src/Febe.Desktop/Properties/launchSettings.json | 8 ++++++++ 3 files changed, 17 insertions(+), 3 deletions(-) create mode 100644 src/Febe.Desktop/Properties/launchSettings.json diff --git a/docs/decisioni.md b/docs/decisioni.md index 0f18c66..cde7593 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -226,7 +226,7 @@ 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 | VS Code: configurazione condivisa in `.vscode/` (`launch.json`, `tasks.json`, `extensions.json`, `settings.json` con la sola `dotnet.defaultSolution`); debug con il tipo `coreclr` dell'estensione C#, senza file `launchSettings.json` | Il tipo `dotnet` del C# Dev Kit accetta solo il progetto e un profilo di `launchSettings.json`: niente argomenti, variabili d'ambiente, attività prima e dopo, `serverReadyAction`. Con `coreclr` tutto sta in un file solo | +| 2026-10-20 | VS Code: configurazione condivisa in `.vscode/` (`launch.json`, `tasks.json`, `extensions.json`, `settings.json` con la sola `dotnet.defaultSolution`); debug con il tipo `coreclr` dell'estensione C#, che non legge `launchSettings.json` (lo cerca in `{cwd}/Properties`, e `cwd` è la radice del repository) | Il tipo `dotnet` del C# Dev Kit accetta solo il progetto e un profilo di `launchSettings.json`: niente argomenti, variabili d'ambiente, attività prima e dopo, `serverReadyAction`. Con `coreclr` tutto sta in un file solo | | 2026-10-20 | Febe per Windows di sviluppo da VS Code con `--dati %USERPROFILE%\FebeSviluppo\\dati` e `--libreria %USERPROFILE%\FebeSviluppo\\libreria` (`${workspaceFolderBasename}`: una cartella per checkout); il debug avvia `Febe.exe`, non `dotnet Febe.dll` | Mai la cartella vera `%LOCALAPPDATA%\Febe`; fuori dal repository perché profilo del browser e libreria crescono e non devono finire in un commit. Una per checkout perché il blocco contro le istanze doppie dipende dalla cartella dei dati (F5 in un secondo worktree mostrava il Febe del primo e finiva subito) e un database migrato da un ramo più nuovo non si apre con una versione più vecchia. Con `Febe.exe` il percorso del processo è quello di Febe e non di `dotnet.exe` (lo usa l'avvio con il computer) | | 2026-10-20 | Attività di compilazione, prove e pubblicazione con `-tl:off -clp:ForceNoAlign` oltre al comando della guida | Registro classico, come nella CI: ogni errore su una riga sola, senza le righe che il terminal logger ridisegna nel terminale; `$msCompile` lo porta nel pannello Problemi (provato con un errore voluto) | | 2026-10-20 | Il sito di prova è un'attività di sfondo, pronta alla riga «Sito di prova: http://» (`activeOnStart`, con `beginsPattern` «(?!)», che non trova mai nulla); a fine debug la ferma un input che esegue `workbench.action.tasks.terminate` | VS Code legge `activeOnStart`, non `activeBegins`: senza, il debug aspettava il sito per sempre. Con «(?!)» nessuna riga successiva rimette l'attività «al lavoro». VS Code non ha un'attività che ne chiuda un'altra: un input di tipo `command` è l'unico modo per farlo da `postDebugTask` | @@ -236,3 +236,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-10-20 | Tutte le configurazioni di debug scrivono nella Console di debug (`internalConsole`), mai nel terminale integrato; le attività sono di tipo `process`, senza shell | Il terminale integrato e le attività `shell` caricano il profilo di PowerShell: su questo PC il profilo attiva l'ambiente conda di Pinokio, che mette in testa al `PATH` e in `DOTNET_ROOT` un .NET senza SDK e con il solo runtime 8. Lì `dotnet build` non trova l'SDK e Febe (net10.0) non parte («You must install or update .NET»), né come `febe.dll` né come `febe.exe`. Console di debug e attività `process` usano l'ambiente di VS Code | | 2026-10-20 | La dimostrazione da VS Code serve l'interfaccia dai sorgenti (`FEBE_INTERFACCIA`), apre da sola il browser (`serverReadyAction`) e su Windows tiene la cartella temporanea in `%USERPROFILE%\FebeSviluppo\\temporanei` (`TEMP`, `TMP`) | Si modifica `wwwroot` e si ricarica senza ricompilare. Fermata dal debugger, la dimostrazione non può cancellare la sua cartella (una trentina di MB): così resta fra i dati di sviluppo invece di accumularsi in `%TEMP%` | | 2026-10-20 | I file di `.vscode/` sono JSON rigido, senza commenti: le spiegazioni stanno nella guida (pagina «Sviluppo», «Da VS Code»), nei campi `detail` delle attività e in queste righe | Il controllo «File JSON» della CI legge ogni `*.json` tracciato con `JSON.parse`, e con i commenti `//` il lavoro «controlli» falliva a ogni push dopo l'unione. VS Code legge anche il JSON rigido, così il ramo non dipende da come la CI tratta i commenti | +| 2026-10-20 | `src/Febe.Desktop/Properties/launchSettings.json` con un solo profilo, «Sito di prova»: `--dati` e `--libreria` in `%USERPROFILE%\FebeSviluppo\comune`, `--sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30 --sviluppo` | `dotnet run --project src/Febe.Desktop` e i comandi del C# Dev Kit (▷ «Debug project associated with this file», «Start New Instance», «C#: …») avviavano Febe senza opzioni: Instagram vero e dati veri, senza la conferma della configurazione ⚠. `dotnet run` e il Dev Kit leggono quel profilo ed espandono `%USERPROFILE%` (provato); se un altro strumento non lo facesse, Febe rifiuta il percorso non completo e non parte. Una cartella comune perché il file non conosce il checkout. Instagram vero dal terminale: `dotnet run --project src/Febe.Desktop --no-launch-profile` | diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index fce5df8..ef08910 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -78,8 +78,13 @@ La cartella `.vscode/` prepara VS Code per Febe: estensioni consigliate (C# Dev - Fermata dal debugger, la dimostrazione non cancella la sua cartella temporanea (`febe-dimostrazione-…`, una trentina di MB): da VS Code su Windows finisce in `%USERPROFILE%\FebeSviluppo\\temporanei`, che si svuota quando vuoi. Con `dotnet run --project src/Febe.Server -- --demo` in un terminale, Ctrl+C la chiude in ordine e la cancella. -- Le configurazioni automatiche del C# Dev Kit («C#: …») avviano un progetto senza opzioni: per Febe per Windows vuol - dire Instagram vero e dati veri. Usa quelle dell'elenco qui sopra. +- Fuori da queste configurazioni (`dotnet run --project src/Febe.Desktop`, il pulsante ▷ «Debug project associated + with this file» e «Start New Instance» del C# Dev Kit, le sue configurazioni automatiche «C#: …») Febe per Windows + prende l'unico profilo di `src/Febe.Desktop/Properties/launchSettings.json`: sito di prova su `http://127.0.0.1:8481` + (da avviare a parte, per esempio con l'attività `sito di prova`) e dati in `%USERPROFILE%\FebeSviluppo\comune`, la + stessa cartella per tutti i checkout. Instagram vero da un terminale solo con + `dotnet run --project src/Febe.Desktop --no-launch-profile`: come la configurazione ⚠, è per le prove dal vivo di + Alberto. - Attività (Terminale ▸ Esegui attività): `compila`, `prove` (`dotnet test tests/Febe.Tests`), `prove con filtro` (chiede il filtro, per esempio `FullyQualifiedName~Febe.Tests.Docs`), `sito di prova`, `pubblica Febe.exe` (un file solo in `out/pubblicazione/`, come `installer/costruisci.sh`) e `immagine Docker (serve Docker Desktop)`. diff --git a/src/Febe.Desktop/Properties/launchSettings.json b/src/Febe.Desktop/Properties/launchSettings.json new file mode 100644 index 0000000..c092d15 --- /dev/null +++ b/src/Febe.Desktop/Properties/launchSettings.json @@ -0,0 +1,8 @@ +{ + "profiles": { + "Sito di prova": { + "commandName": "Project", + "commandLineArgs": "--dati \"%USERPROFILE%\\FebeSviluppo\\comune\\dati\" --libreria \"%USERPROFILE%\\FebeSviluppo\\comune\\libreria\" --sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30 --sviluppo" + } + } +} -- 2.54.1 From af5383a3eabe586abc507b0cb186bd9d97780352 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:54:42 +0200 Subject: [PATCH 23/44] Guida: il registro di Febe per Windows sta nella cartella dei dati MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La guida diceva che i programmi scrivono nella Console di debug, ma Febe per Windows non ha una console: lì compaiono solo i messaggi del debugger, mentre «Interfaccia sulla porta N», lo stato del browser e gli errori finiscono in FebeSviluppo\\dati\registro. Chi aspettava quelle righe nella Console di debug non le avrebbe mai viste. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 2 +- docs/guida/Sviluppo.md | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index cde7593..96d1f42 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -233,7 +233,7 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-10-20 | «Sito di prova + Febe per Windows» non è un compound: la configurazione del sito avvia Febe con `serverReadyAction` (`startDebugging`, `killOnServerStop`) quando il sito scrive di essere pronto | Un compound avvia tutto insieme e senza ordine: Febe con `--accesso-di-prova` poteva cercare il sito prima che ascoltasse | | 2026-10-20 | Le configurazioni legate a un sistema (Febe per Windows; Febe Server con il sito di prova, cioè Chromium su Xvfb) sugli altri sistemi si fermano con un messaggio (attività «solo su Windows» e «solo su Linux»; il server riceve anche solo `--aiuto`) | VS Code non sa nascondere una configurazione per sistema operativo: le proprietà `windows`, `linux` e `osx` contano solo all'avvio | | 2026-10-20 | «⚠ Febe per Windows · Instagram vero (dati veri)» chiede conferma prima di compilare e partire (una scelta sola, Esc annulla) | Regola 1: le prove dal vivo le lancia Alberto; un F5 distratto non deve aprire Instagram con l'account e il database veri | -| 2026-10-20 | Tutte le configurazioni di debug scrivono nella Console di debug (`internalConsole`), mai nel terminale integrato; le attività sono di tipo `process`, senza shell | Il terminale integrato e le attività `shell` caricano il profilo di PowerShell: su questo PC il profilo attiva l'ambiente conda di Pinokio, che mette in testa al `PATH` e in `DOTNET_ROOT` un .NET senza SDK e con il solo runtime 8. Lì `dotnet build` non trova l'SDK e Febe (net10.0) non parte («You must install or update .NET»), né come `febe.dll` né come `febe.exe`. Console di debug e attività `process` usano l'ambiente di VS Code | +| 2026-10-20 | Tutte le configurazioni di debug usano la Console di debug (`internalConsole`), mai il terminale integrato (Febe per Windows non ha una console: il suo registro resta nella cartella dei dati, `registro`); le attività sono di tipo `process`, senza shell | Il terminale integrato e le attività `shell` caricano il profilo di PowerShell: su questo PC il profilo attiva l'ambiente conda di Pinokio, che mette in testa al `PATH` e in `DOTNET_ROOT` un .NET senza SDK e con il solo runtime 8. Lì `dotnet build` non trova l'SDK e Febe (net10.0) non parte («You must install or update .NET»), né come `febe.dll` né come `febe.exe`. Console di debug e attività `process` usano l'ambiente di VS Code | | 2026-10-20 | La dimostrazione da VS Code serve l'interfaccia dai sorgenti (`FEBE_INTERFACCIA`), apre da sola il browser (`serverReadyAction`) e su Windows tiene la cartella temporanea in `%USERPROFILE%\FebeSviluppo\\temporanei` (`TEMP`, `TMP`) | Si modifica `wwwroot` e si ricarica senza ricompilare. Fermata dal debugger, la dimostrazione non può cancellare la sua cartella (una trentina di MB): così resta fra i dati di sviluppo invece di accumularsi in `%TEMP%` | | 2026-10-20 | I file di `.vscode/` sono JSON rigido, senza commenti: le spiegazioni stanno nella guida (pagina «Sviluppo», «Da VS Code»), nei campi `detail` delle attività e in queste righe | Il controllo «File JSON» della CI legge ogni `*.json` tracciato con `JSON.parse`, e con i commenti `//` il lavoro «controlli» falliva a ogni push dopo l'unione. VS Code legge anche il JSON rigido, così il ramo non dipende da come la CI tratta i commenti | | 2026-10-20 | `src/Febe.Desktop/Properties/launchSettings.json` con un solo profilo, «Sito di prova»: `--dati` e `--libreria` in `%USERPROFILE%\FebeSviluppo\comune`, `--sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30 --sviluppo` | `dotnet run --project src/Febe.Desktop` e i comandi del C# Dev Kit (▷ «Debug project associated with this file», «Start New Instance», «C#: …») avviavano Febe senza opzioni: Instagram vero e dati veri, senza la conferma della configurazione ⚠. `dotnet run` e il Dev Kit leggono quel profilo ed espandono `%USERPROFILE%` (provato); se un altro strumento non lo facesse, Febe rifiuta il percorso non completo e non parte. Una cartella comune perché il file non conosce il checkout. Instagram vero dal terminale: `dotnet run --project src/Febe.Desktop --no-launch-profile` | diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index ef08910..ac22bd8 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -71,7 +71,12 @@ La cartella `.vscode/` prepara VS Code per Febe: estensioni consigliate (C# Dev - Chiudendo la finestra Febe resta nell'area di notifica e il debug continua: per finire, menu dell'icona ▸ Esci oppure Maiusc+F5. Finché Febe gira, `compila` non può sovrascrivere `Febe.exe`. - Il sito di prova usa sempre le porte 8481 e 8482, come attività e come configurazione: uno alla volta. -- I programmi scrivono nella Console di debug e le attività partono senza shell: il terminale integrato carica il +- **Registro.** Nella Console di debug compaiono le righe del sito di prova, della dimostrazione, della simulazione e + del server. Febe per Windows non ha una console: lì mostra solo i messaggi del debugger, e il suo registro sta nella + cartella dei dati, `%USERPROFILE%\FebeSviluppo\\dati\registro\febe-AAAA-MM-GG.log` (con il profilo di + `launchSettings.json`, in `FebeSviluppo\comune\dati\registro`). Lì si leggono «Interfaccia sulla porta N», lo stato + del browser di Febe e gli errori. +- Le configurazioni usano la Console di debug e le attività partono senza shell: il terminale integrato carica il profilo di PowerShell, che può mettere davanti un altro .NET (per esempio quello di un ambiente conda), e allora `dotnet` non trova l'SDK 10 o Febe non parte («You must install or update .NET»). Se nel terminale `dotnet --list-sdks` non mostra il 10, usa le attività, Git Bash oppure `conda deactivate`. -- 2.54.1 From d56c24f900cbf4d93668166f8060c5a84f9fb5ce Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:55:06 +0200 Subject: [PATCH 24/44] =?UTF-8?q?Guida:=20che=20cosa=20fare=20se=20a=20fin?= =?UTF-8?q?e=20debug=20compare=20l'elenco=20delle=20attivit=C3=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit «ferma il sito di prova» chiude l'attività con workbench.action.tasks.terminate; se il sito si è già fermato da solo, VS Code non trova l'attività e apre l'elenco di quelle da terminare, con «Termina tutte». Non c'è un modo di farlo solo se l'attività è in corso: la guida dice di premere Esc e ricorda che «Sito di prova + Febe per Windows» non ha il problema. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 2 +- docs/guida/Sviluppo.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index 96d1f42..3baea0f 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -229,7 +229,7 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-10-20 | VS Code: configurazione condivisa in `.vscode/` (`launch.json`, `tasks.json`, `extensions.json`, `settings.json` con la sola `dotnet.defaultSolution`); debug con il tipo `coreclr` dell'estensione C#, che non legge `launchSettings.json` (lo cerca in `{cwd}/Properties`, e `cwd` è la radice del repository) | Il tipo `dotnet` del C# Dev Kit accetta solo il progetto e un profilo di `launchSettings.json`: niente argomenti, variabili d'ambiente, attività prima e dopo, `serverReadyAction`. Con `coreclr` tutto sta in un file solo | | 2026-10-20 | Febe per Windows di sviluppo da VS Code con `--dati %USERPROFILE%\FebeSviluppo\\dati` e `--libreria %USERPROFILE%\FebeSviluppo\\libreria` (`${workspaceFolderBasename}`: una cartella per checkout); il debug avvia `Febe.exe`, non `dotnet Febe.dll` | Mai la cartella vera `%LOCALAPPDATA%\Febe`; fuori dal repository perché profilo del browser e libreria crescono e non devono finire in un commit. Una per checkout perché il blocco contro le istanze doppie dipende dalla cartella dei dati (F5 in un secondo worktree mostrava il Febe del primo e finiva subito) e un database migrato da un ramo più nuovo non si apre con una versione più vecchia. Con `Febe.exe` il percorso del processo è quello di Febe e non di `dotnet.exe` (lo usa l'avvio con il computer) | | 2026-10-20 | Attività di compilazione, prove e pubblicazione con `-tl:off -clp:ForceNoAlign` oltre al comando della guida | Registro classico, come nella CI: ogni errore su una riga sola, senza le righe che il terminal logger ridisegna nel terminale; `$msCompile` lo porta nel pannello Problemi (provato con un errore voluto) | -| 2026-10-20 | Il sito di prova è un'attività di sfondo, pronta alla riga «Sito di prova: http://» (`activeOnStart`, con `beginsPattern` «(?!)», che non trova mai nulla); a fine debug la ferma un input che esegue `workbench.action.tasks.terminate` | VS Code legge `activeOnStart`, non `activeBegins`: senza, il debug aspettava il sito per sempre. Con «(?!)» nessuna riga successiva rimette l'attività «al lavoro». VS Code non ha un'attività che ne chiuda un'altra: un input di tipo `command` è l'unico modo per farlo da `postDebugTask` | +| 2026-10-20 | Il sito di prova è un'attività di sfondo, pronta alla riga «Sito di prova: http://» (`activeOnStart`, con `beginsPattern` «(?!)», che non trova mai nulla); a fine debug la ferma un input che esegue `workbench.action.tasks.terminate` | VS Code legge `activeOnStart`, non `activeBegins`: senza, il debug aspettava il sito per sempre. Con «(?!)» nessuna riga successiva rimette l'attività «al lavoro». VS Code non ha un'attività che ne chiuda un'altra: un input di tipo `command` è l'unico modo per farlo da `postDebugTask`. Limite noto: se il sito non è più in corso, il comando apre l'elenco delle attività da terminare (la guida dice di premere Esc) | | 2026-10-20 | «Sito di prova + Febe per Windows» non è un compound: la configurazione del sito avvia Febe con `serverReadyAction` (`startDebugging`, `killOnServerStop`) quando il sito scrive di essere pronto | Un compound avvia tutto insieme e senza ordine: Febe con `--accesso-di-prova` poteva cercare il sito prima che ascoltasse | | 2026-10-20 | Le configurazioni legate a un sistema (Febe per Windows; Febe Server con il sito di prova, cioè Chromium su Xvfb) sugli altri sistemi si fermano con un messaggio (attività «solo su Windows» e «solo su Linux»; il server riceve anche solo `--aiuto`) | VS Code non sa nascondere una configurazione per sistema operativo: le proprietà `windows`, `linux` e `osx` contano solo all'avvio | | 2026-10-20 | «⚠ Febe per Windows · Instagram vero (dati veri)» chiede conferma prima di compilare e partire (una scelta sola, Esc annulla) | Regola 1: le prove dal vivo le lancia Alberto; un F5 distratto non deve aprire Instagram con l'account e il database veri | diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index ac22bd8..7167f00 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -71,6 +71,10 @@ La cartella `.vscode/` prepara VS Code per Febe: estensioni consigliate (C# Dev - Chiudendo la finestra Febe resta nell'area di notifica e il debug continua: per finire, menu dell'icona ▸ Esci oppure Maiusc+F5. Finché Febe gira, `compila` non può sovrascrivere `Febe.exe`. - Il sito di prova usa sempre le porte 8481 e 8482, come attività e come configurazione: uno alla volta. +- Se il sito di prova si ferma prima di Febe (terminale chiuso a mano, un guasto, oppure porta occupata e «Esegui + comunque il debug»), a fine debug VS Code apre l'elenco delle attività da terminare, con «Termina tutte»: premi Esc. + Con «Sito di prova + Febe per Windows» non succede, perché lì il sito sta nel debugger e non c'è un'attività da + chiudere. - **Registro.** Nella Console di debug compaiono le righe del sito di prova, della dimostrazione, della simulazione e del server. Febe per Windows non ha una console: lì mostra solo i messaggi del debugger, e il suo registro sta nella cartella dei dati, `%USERPROFILE%\FebeSviluppo\\dati\registro\febe-AAAA-MM-GG.log` (con il profilo di -- 2.54.1 From d9d8a296b1066449cd6139645c62ab74c260ae61 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 13:08:58 +0200 Subject: [PATCH 25/44] Prove dei percorsi uguali su Linux e su Windows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tre prove scrivevano i percorsi attesi alla Linux («/tmp/febe-profilo», «/importa», la radice seguita da «/») e fallivano su Windows, dove il prodotto dà giustamente il percorso completo sull'unità corrente o il percorso scritto con «/». Ora l'atteso si calcola come lo calcola il sistema: su Linux il testo resta identico a prima, su Windows le prove passano dove gira Febe per Windows. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 1 + tests/Febe.Tests/Browser/HostingTests.cs | 4 +++- tests/Febe.Tests/Import/ImportSourcesTests.cs | 3 ++- tests/Febe.Tests/Web/ImportApiTests.cs | 6 ++++-- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index be3e037..40d1f10 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -226,3 +226,4 @@ 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 | Prove portabili fra Linux e Windows: i percorsi attesi si calcolano come li calcola il sistema (`Path.GetFullPath` per il profilo del browser e per `/importa`, `LibraryLayout.ToStored` per il percorso mostrato in Docker) invece di essere scritti alla Linux | Febe per Windows gira su Windows e le prove devono passare dove gira il prodotto; su Linux il testo atteso è identico a prima, quindi lì non cambia nulla | diff --git a/tests/Febe.Tests/Browser/HostingTests.cs b/tests/Febe.Tests/Browser/HostingTests.cs index a44cc66..76d663f 100644 --- a/tests/Febe.Tests/Browser/HostingTests.cs +++ b/tests/Febe.Tests/Browser/HostingTests.cs @@ -15,7 +15,9 @@ public sealed class HostingTests var args = ChromiumCommandLine.Build(Options, new ChromiumLaunchOptions()); CollectionAssert.Contains(args.ToList(), "--remote-debugging-port=9333"); - CollectionAssert.Contains(args.ToList(), "--user-data-dir=/tmp/febe-profilo"); + + // The profile reaches Chromium as a full path: «/tmp/febe-profilo» on Linux, rooted on the current drive on Windows. + CollectionAssert.Contains(args.ToList(), $"--user-data-dir={Path.GetFullPath(Options.ProfileDirectory)}"); CollectionAssert.Contains(args.ToList(), "--no-first-run"); CollectionAssert.Contains(args.ToList(), "--no-default-browser-check"); CollectionAssert.Contains(args.ToList(), "--window-size=1280,900"); diff --git a/tests/Febe.Tests/Import/ImportSourcesTests.cs b/tests/Febe.Tests/Import/ImportSourcesTests.cs index 24353b8..9d95e72 100644 --- a/tests/Febe.Tests/Import/ImportSourcesTests.cs +++ b/tests/Febe.Tests/Import/ImportSourcesTests.cs @@ -27,7 +27,8 @@ public sealed class ImportSourcesTests Assert.AreEqual(Path.Combine(root, "4K Stogram"), info.FullPath); Assert.IsTrue(info.ReadOnly, "Il volume /importa è in sola lettura."); Assert.IsFalse(info.CanMove); - Assert.AreEqual(root + "/4K Stogram", info.DisplayPath); + // Shown as in the container, with «/»: the same text as the root on Linux; on Windows the separators change too. + Assert.AreEqual(LibraryLayout.ToStored(root) + "/4K Stogram", info.DisplayPath); var outside = Assert.ThrowsExactly(() => sources.Inspect(temp.Combine("fuori"))); StringAssert.Contains(outside.Message, "sottocartella"); diff --git a/tests/Febe.Tests/Web/ImportApiTests.cs b/tests/Febe.Tests/Web/ImportApiTests.cs index 7908a86..ea99530 100644 --- a/tests/Febe.Tests/Web/ImportApiTests.cs +++ b/tests/Febe.Tests/Web/ImportApiTests.cs @@ -163,10 +163,12 @@ public sealed class ImportApiTests Assert.AreEqual(HttpStatusCode.BadRequest, sources, "desktop: the native picker, no listing"); } - // Docker: the sources live under /importa (absent on this machine: the listing says so). + // Docker: the sources live under /importa (absent on this machine: the listing says so). The root is reported as + // a full path: «/importa» in the container, rooted on the current drive where the edition runs for development + // on Windows. await using var docker = await Part2.StartAsync(); var overview = await docker.GetJsonAsync("/api/import"); - Assert.AreEqual("/importa", overview.Str("sourceRoot")); + Assert.AreEqual(Path.GetFullPath("/importa"), overview.Str("sourceRoot")); Assert.IsFalse(overview.Bool("pickFolder")); var (pick, _) = await docker.SendJsonAsync(HttpMethod.Post, "/api/import/pick-folder"); Assert.AreEqual(HttpStatusCode.BadRequest, pick); -- 2.54.1 From e035cfd20adb1861f5733ad1006cf3301fe34d85 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 13:09:07 +0200 Subject: [PATCH 26/44] Cartella dei dati in rete: la prova vale anche su Windows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La prova iniettava una tabella dei montaggi di Linux (cifs), che su Windows non esiste: lì il controllo riconosce la rete dai percorsi UNC e dalle unità di rete, quindi il server partiva normalmente e la prova falliva. Ora su Windows la cartella dei dati è un percorso UNC verso un nome .invalid, riconosciuto dalla sola forma senza interrogare la rete; su Linux la prova è quella di prima. Il prodotto era già giusto: cambia solo la prova. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 1 + tests/Febe.Tests/Server/StartupProblemTests.cs | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index 40d1f10..5521fb2 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -227,3 +227,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 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 | Prove portabili fra Linux e Windows: i percorsi attesi si calcolano come li calcola il sistema (`Path.GetFullPath` per il profilo del browser e per `/importa`, `LibraryLayout.ToStored` per il percorso mostrato in Docker) invece di essere scritti alla Linux | Febe per Windows gira su Windows e le prove devono passare dove gira il prodotto; su Linux il testo atteso è identico a prima, quindi lì non cambia nulla | +| 2026-10-20 | Prova della cartella dei dati su una condivisione: su Linux il montaggio cifs iniettato come prima, su Windows un percorso UNC verso `febe-prova.invalid`, riconosciuto dalla sola forma; il controllo «niente scritto nella cartella dei dati» resta solo su Linux | Stesso comportamento sui due sistemi, ognuno con il suo modo di riconoscere la rete (su Windows non c'è tabella dei montaggi); guardare dentro un UNC vorrebbe dire interrogare la rete, e un nome `.invalid` (RFC 6761) non risponde mai | diff --git a/tests/Febe.Tests/Server/StartupProblemTests.cs b/tests/Febe.Tests/Server/StartupProblemTests.cs index d0c74b6..382ae45 100644 --- a/tests/Febe.Tests/Server/StartupProblemTests.cs +++ b/tests/Febe.Tests/Server/StartupProblemTests.cs @@ -99,14 +99,23 @@ public sealed class StartupProblemTests [TestMethod] public async Task ADataFolderOnANetworkShareIsRefused() { + // A share shows itself differently on the two systems: on Linux as a cifs mount in the mount table (injected + // here), on Windows as a UNC path, recognised from its form before anything touches it. The Windows server name + // ends in .invalid (RFC 6761): no machine answers to it, and nothing here looks it up. using var temp = new TempFolder("server-problemi"); - var data = temp.Combine("dati"); + var windows = OperatingSystem.IsWindows(); + var data = windows ? @"\\febe-prova.invalid\condivisa\dati" : temp.Combine("dati"); var mounts = $"/dev/sda1 / ext4 rw 0 0\n//nas/condivisa {temp.Path} cifs rw 0 0\n"; - await using var server = await FebeServer.StartAsync(Options(temp), Hooks() with { DataFolderCheck = new DataFolderCheck(() => mounts) }); + await using var server = await FebeServer.StartAsync(Options(temp) with { DataFolder = data }, Hooks() with { DataFolderCheck = new DataFolderCheck(() => mounts) }); var problem = server.Problems.Single(); Assert.AreEqual(StartupChecks.DataOnNetwork, problem.Code); - StringAssert.Contains(problem.Message, "cifs"); - Assert.IsFalse(Directory.Exists(Path.Combine(data, "registro"))); + StringAssert.Contains(problem.Message, windows ? "condivisione di rete" : "cifs"); + if (!windows) + { + // Nothing written in the Data folder (on Windows the share does not exist: looking would mean asking the network). + Assert.IsFalse(Directory.Exists(Path.Combine(data, "registro"))); + } + using var client = Client(server); await AssertHealthAsync(client, HttpStatusCode.ServiceUnavailable, """{"stato":"problema"}"""); } -- 2.54.1 From f7de7f5642acb8acee9921cb2761846de3a11534 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 13:09:19 +0200 Subject: [PATCH 27/44] Ricostruzione: la prova aspetta il database tenuto per un attimo su Windows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TestLibrary.LoseDatabaseAsync elimina febe.sqlite appena chiuso. Su Windows un file aperto da un altro programma non si elimina, e con Defender attivo succedeva circa 3 volte su 40 esecuzioni delle prove di libreria: il file era libero dopo 6-17 ms e nessun processo risultava tenerlo, quindi non è un collegamento di Febe rimasto aperto. Su Windows l'eliminazione che trova il file in uso si ripete ogni 50 ms per al più 5 s; su Linux, dove eliminare un file aperto riesce sempre, non cambia nulla. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 1 + tests/Febe.Tests/Support/TestLibrary.cs | 25 ++++++++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index 5521fb2..2b32652 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -228,3 +228,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 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 | Prove portabili fra Linux e Windows: i percorsi attesi si calcolano come li calcola il sistema (`Path.GetFullPath` per il profilo del browser e per `/importa`, `LibraryLayout.ToStored` per il percorso mostrato in Docker) invece di essere scritti alla Linux | Febe per Windows gira su Windows e le prove devono passare dove gira il prodotto; su Linux il testo atteso è identico a prima, quindi lì non cambia nulla | | 2026-10-20 | Prova della cartella dei dati su una condivisione: su Linux il montaggio cifs iniettato come prima, su Windows un percorso UNC verso `febe-prova.invalid`, riconosciuto dalla sola forma; il controllo «niente scritto nella cartella dei dati» resta solo su Linux | Stesso comportamento sui due sistemi, ognuno con il suo modo di riconoscere la rete (su Windows non c'è tabella dei montaggi); guardare dentro un UNC vorrebbe dire interrogare la rete, e un nome `.invalid` (RFC 6761) non risponde mai | +| 2026-10-20 | `TestLibrary.LoseDatabaseAsync`: su Windows un'eliminazione che trova il file in uso da un altro programma (`0x80070020`) si ripete ogni 50 ms, per al più 5 s | Su Windows un file aperto da un altro programma non si elimina. Su questo PC, con Defender attivo, succedeva circa 3 volte su 40 esecuzioni di `Febe.Tests.Library`: il file era libero dopo 6–17 ms e il Restart Manager non vedeva nessun processo che lo tenesse, quindi non è un collegamento di Febe rimasto aperto. Su Linux eliminare un file aperto riesce sempre e non si ripete nulla | diff --git a/tests/Febe.Tests/Support/TestLibrary.cs b/tests/Febe.Tests/Support/TestLibrary.cs index 572685e..9763bd0 100644 --- a/tests/Febe.Tests/Support/TestLibrary.cs +++ b/tests/Febe.Tests/Support/TestLibrary.cs @@ -63,13 +63,36 @@ internal sealed class TestLibrary : IAsyncDisposable await Db.DisposeAsync(); foreach (var suffix in new[] { string.Empty, "-wal", "-shm" }) { - File.Delete(Data.Database + suffix); + await DeleteClosedFileAsync(Data.Database + suffix); } Db = await FebeDatabase.OpenAsync(Data.Root); Ingest = new LibraryIngest(Db, Layout, LibraryNaming.Default, Journal, Clock, Thumbnails, Index); } + /// + /// Deletes a file Febe has already closed. On Windows a file that another program holds open cannot be deleted, and a + /// database just written is sometimes held for a few milliseconds by a program that scans new files (the real-time + /// antivirus): that sharing violation is waited out (at most 5 s). On Linux a delete never meets one, so the first + /// attempt is the only one. + /// + private static async Task DeleteClosedFileAsync(string path) + { + const int SharingViolation = unchecked((int)0x80070020); + for (var attempt = 1; ; attempt++) + { + try + { + File.Delete(path); + return; + } + catch (IOException ex) when (OperatingSystem.IsWindows() && ex.HResult == SharingViolation && attempt < 100) + { + await Task.Delay(50); + } + } + } + public ValueTask DisposeAsync() => Db.DisposeAsync(); } -- 2.54.1 From 815bd44a62e4324c70531cccfdba227d2689fdfe Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 13:09:27 +0200 Subject: [PATCH 28/44] Prova di costruisci.sh con Git Bash su Windows, mai col lanciatore di WSL MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dal PATH di PowerShell il primo bash è C:\Windows\System32\bash.exe, il lanciatore di WSL: senza distribuzione fallisce («execvpe(/bin/bash) failed») e la prova falliva con lui. Su Windows ora si cerca prima Git Bash (accanto a git sul PATH, poi nelle cartelle del suo installatore), poi un bash sul PATH che non stia nella cartella di Windows né fra gli alias di WindowsApps; senza bash la prova è inconcludente invece di passare in silenzio. Su Linux si usa come prima il primo bash sul PATH. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 1 + tests/Febe.Tests/Desktop/InstallerTests.cs | 62 +++++++++++++++++++--- 2 files changed, 56 insertions(+), 7 deletions(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index 2b32652..3622f7f 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -229,3 +229,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-10-20 | Prove portabili fra Linux e Windows: i percorsi attesi si calcolano come li calcola il sistema (`Path.GetFullPath` per il profilo del browser e per `/importa`, `LibraryLayout.ToStored` per il percorso mostrato in Docker) invece di essere scritti alla Linux | Febe per Windows gira su Windows e le prove devono passare dove gira il prodotto; su Linux il testo atteso è identico a prima, quindi lì non cambia nulla | | 2026-10-20 | Prova della cartella dei dati su una condivisione: su Linux il montaggio cifs iniettato come prima, su Windows un percorso UNC verso `febe-prova.invalid`, riconosciuto dalla sola forma; il controllo «niente scritto nella cartella dei dati» resta solo su Linux | Stesso comportamento sui due sistemi, ognuno con il suo modo di riconoscere la rete (su Windows non c'è tabella dei montaggi); guardare dentro un UNC vorrebbe dire interrogare la rete, e un nome `.invalid` (RFC 6761) non risponde mai | | 2026-10-20 | `TestLibrary.LoseDatabaseAsync`: su Windows un'eliminazione che trova il file in uso da un altro programma (`0x80070020`) si ripete ogni 50 ms, per al più 5 s | Su Windows un file aperto da un altro programma non si elimina. Su questo PC, con Defender attivo, succedeva circa 3 volte su 40 esecuzioni di `Febe.Tests.Library`: il file era libero dopo 6–17 ms e il Restart Manager non vedeva nessun processo che lo tenesse, quindi non è un collegamento di Febe rimasto aperto. Su Linux eliminare un file aperto riesce sempre e non si ripete nulla | +| 2026-10-20 | Prova di `costruisci.sh`: su Windows prima Git Bash (accanto a git sul PATH, poi nelle cartelle del suo installatore), altrimenti un bash sul PATH che non sia il lanciatore di WSL (`System32\bash.exe`, alias in `WindowsApps`); senza bash la prova è inconcludente invece di passare in silenzio | Dal PATH di PowerShell il primo bash è il lanciatore di WSL, che senza distribuzione fallisce («execvpe(/bin/bash) failed») e non vede lo script col percorso di Windows; su Linux si usa come prima il primo bash sul PATH | diff --git a/tests/Febe.Tests/Desktop/InstallerTests.cs b/tests/Febe.Tests/Desktop/InstallerTests.cs index 899e519..f884dea 100644 --- a/tests/Febe.Tests/Desktop/InstallerTests.cs +++ b/tests/Febe.Tests/Desktop/InstallerTests.cs @@ -112,10 +112,10 @@ public sealed partial class InstallerTests StringAssert.Contains(text, "100 * 1024 * 1024"); Assert.DoesNotContain("\r\n", text, "Unix line ends: bash would choke on CR"); - var bash = FindOnPath("bash"); + var bash = FindBash(); if (bash is null) { - return; + Assert.Inconclusive("Manca bash (su Windows: Git Bash): la prova della sintassi di costruisci.sh si salta."); } using var process = Process.Start(new ProcessStartInfo(bash, ["-n", script]) { RedirectStandardError = true })!; @@ -124,21 +124,69 @@ public sealed partial class InstallerTests Assert.AreEqual(0, process.ExitCode, errors); } - private static string? FindOnPath(string name) + private static string? FindOnPath(string name) => OnPath(name).FirstOrDefault(); + + /// + /// A bash that checks the script on this system. Elsewhere than Windows, the first on PATH. On Windows Git Bash + /// first (next to git on PATH, then where its installer puts it), else any bash on PATH except the WSL launcher: + /// System32\bash.exe and the WindowsApps alias start a Linux distribution, which may be missing + /// («execvpe(/bin/bash) failed») and does not see the script by its Windows path. + /// + private static string? FindBash() { + if (!OperatingSystem.IsWindows()) + { + return FindOnPath("bash"); + } + + var roots = new List(); + if (FindOnPath("git") is { } git) + { + // git.exe sits in \cmd, \bin or \mingw64\bin. + for (var folder = Path.GetDirectoryName(git); folder is not null && roots.Count < 3; folder = Path.GetDirectoryName(folder)) + { + roots.Add(folder); + } + } + + foreach (var variable in new[] { "ProgramW6432", "ProgramFiles", "ProgramFiles(x86)" }) + { + if (Environment.GetEnvironmentVariable(variable) is { Length: > 0 } programs) + { + roots.Add(Path.Combine(programs, "Git")); + } + } + + roots.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Git")); + var gitBash = roots + .SelectMany(root => new[] { Path.Combine(root, "bin", "bash.exe"), Path.Combine(root, "usr", "bin", "bash.exe") }) + .FirstOrDefault(path => File.Exists(path) && !IsWslLauncher(path)); + return gitBash ?? OnPath("bash").FirstOrDefault(path => !IsWslLauncher(path)); + } + + private static bool IsWslLauncher(string path) + { + var full = Path.GetFullPath(path); + var windows = Environment.GetFolderPath(Environment.SpecialFolder.Windows); + return (windows.Length > 0 && full.StartsWith(Path.TrimEndingDirectorySeparator(windows) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + || full.Contains(@"\Microsoft\WindowsApps\", StringComparison.OrdinalIgnoreCase); + } + + /// Every file called on PATH, in order (on Windows only .exe: the others do not start). + private static IEnumerable OnPath(string name) + { + var candidates = OperatingSystem.IsWindows() ? new[] { name + ".exe" } : new[] { name, name + ".exe" }; foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) { - foreach (var candidate in new[] { name, name + ".exe" }) + foreach (var candidate in candidates) { var path = Path.Combine(folder, candidate); if (File.Exists(path)) { - return path; + yield return path; } } } - - return null; } [GeneratedRegex(@"^\s*(?:Delete|RMDir)(?:\s+/\w+)*\s+""(?[^""]+)""", RegexOptions.Multiline)] -- 2.54.1 From 198e48d4f8fef79fb40d7bb16ed31fffb05f4d20 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 13:39:18 +0200 Subject: [PATCH 29/44] =?UTF-8?q?Prove:=20il=20commento=20dell'attesa=20su?= =?UTF-8?q?l=20database=20dice=20ci=C3=B2=20che=20si=20=C3=A8=20visto,=20n?= =?UTF-8?q?on=20una=20causa?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Il commento di TestLibrary.DeleteClosedFileAsync dava per certo che il file appena chiuso fosse tenuto dall'antivirus. È solo una deduzione: su un PC il file restava in uso per pochi millisecondi, il Restart Manager non elencava alcun processo e Defender era attivo, ma la causa non è stata dimostrata (la revisione non ha riprodotto il caso). Il commento ora lo dice, così nessuno smette di cercare né copia l'attesa nel prodotto per una causa mai vista. Il codice non cambia. Co-Authored-By: Claude Opus 5.5 --- tests/Febe.Tests/Support/TestLibrary.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/Febe.Tests/Support/TestLibrary.cs b/tests/Febe.Tests/Support/TestLibrary.cs index 9763bd0..c549819 100644 --- a/tests/Febe.Tests/Support/TestLibrary.cs +++ b/tests/Febe.Tests/Support/TestLibrary.cs @@ -71,10 +71,10 @@ internal sealed class TestLibrary : IAsyncDisposable } /// - /// Deletes a file Febe has already closed. On Windows a file that another program holds open cannot be deleted, and a - /// database just written is sometimes held for a few milliseconds by a program that scans new files (the real-time - /// antivirus): that sharing violation is waited out (at most 5 s). On Linux a delete never meets one, so the first - /// attempt is the only one. + /// Deletes a file Febe has already closed. On Windows a file still held open elsewhere cannot be deleted, and on one PC a + /// database just closed was now and then held for a few milliseconds by something outside Febe (Restart Manager listed + /// no process; probably the real-time antivirus, which was active, but the cause was never shown): that sharing + /// violation is waited out (at most 5 s). On Linux a delete never meets one, so the first attempt is the only one. /// private static async Task DeleteClosedFileAsync(string path) { -- 2.54.1 From f09ce4f2d5f591109498b0d1567d4240df1dff74 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 13:52:07 +0200 Subject: [PATCH 30/44] =?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() { -- 2.54.1 From f86c794fa4d9ac7229125c281900e012d4c6c2c9 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 15:23:55 +0200 Subject: [PATCH 31/44] Il motore chiude lo storico anche se la corsa finisce con un segnale MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Quando il cammino dello Storico arriva in fondo, la ricetta segna lo storico come completato e lo dice al motore (BackfillFinished). Il motore però chiudeva lo storico (stato «Aggiornato» o «In pausa» e riga «Storico completato») solo se la corsa finiva «Completata»: un segnale o un'interruzione arrivati subito dopo l'ultima pagina lasciavano l'account «Storico in corso» per sempre, senza che nessuno lo riprendesse. Ora la chiusura sta in un solo punto (FinishBackfillAsync) e scatta ogni volta che il cammino è arrivato in fondo, comunque sia finita la corsa. Prova nuova per il segnale e per l'interruzione. Co-Authored-By: Claude Opus 5.5 --- src/Febe.Core/Engine/SessionComposer.cs | 55 ++++++++++------- .../Engine/BackfillCompletedTests.cs | 59 +++++++++++++++++++ 2 files changed, 93 insertions(+), 21 deletions(-) create mode 100644 tests/Febe.Tests/Engine/BackfillCompletedTests.cs diff --git a/src/Febe.Core/Engine/SessionComposer.cs b/src/Febe.Core/Engine/SessionComposer.cs index df2017e..9d62a89 100644 --- a/src/Febe.Core/Engine/SessionComposer.cs +++ b/src/Febe.Core/Engine/SessionComposer.cs @@ -771,6 +771,14 @@ internal sealed class SessionComposer var now = Clock.Now; var kind = request.Kind; var writes = new List(); + + // The walk reached the beginning of the profile: the history is complete however the run ended (a signal or a + // cancellation can come right after the last page was stored, and that account would not be walked again). + if (kind == RecipeKind.Backfill && outcome.BackfillFinished && account is not null) + { + await FinishBackfillAsync(account, state, now, ct).ConfigureAwait(false); + } + switch (outcome.Status) { case RecipeStatus.Completed: @@ -947,27 +955,8 @@ internal sealed class SessionComposer break; } - case RecipeKind.Backfill when outcome.BackfillFinished: - { - var fresh = await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account; - await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false); - var newState = fresh.KeepUpdated ? AccountState.UpToDate : AccountState.Paused; - await Store.Accounts.SetStateAsync(account.Id, newState, now, null, ct).ConfigureAwait(false); - var total = await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false); - var tail = fresh.KeepUpdated - ? " Da ora lo tengo aggiornato." - : " «Tieni aggiornato» è spento: l'account resta in pausa."; - await _s.Events.WriteAsync( - EventSeverity.Success, - EngineEventCodes.BackfillCompleted, - $"Storico di {ItalianText.Handle(account.Username)} completato: {ItalianText.Count(total, "post", "post")} in libreria.{tail}", - account.Id, - state.Context.SessionId, - ct).ConfigureAwait(false); - break; - } - - case RecipeKind.Backfill: + // A history completed: FinishBackfillAsync, from ApplyOutcomeAsync. + case RecipeKind.Backfill when !outcome.BackfillFinished: if (contactable) { // Behind the other accounts «Storico in corso»: they alternate. @@ -980,6 +969,30 @@ internal sealed class SessionComposer } } + /// + /// The history of the account is complete: «Aggiornato» (or «In pausa» with «Tieni aggiornato» off) and the one + /// «storico completato» line of Attività, which is also the alert (spec §13.3). The recipes write no line of their + /// own for it. + /// + private async Task FinishBackfillAsync(Account account, SessionState state, DateTimeOffset now, CancellationToken ct) + { + var fresh = await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account; + await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false); + var newState = fresh.KeepUpdated ? AccountState.UpToDate : AccountState.Paused; + await Store.Accounts.SetStateAsync(account.Id, newState, now, null, ct).ConfigureAwait(false); + var total = await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false); + var tail = fresh.KeepUpdated + ? " Da ora lo tengo aggiornato." + : " «Tieni aggiornato» è spento: l'account resta in pausa."; + await _s.Events.WriteAsync( + EventSeverity.Success, + EngineEventCodes.BackfillCompleted, + $"Storico di {ItalianText.Handle(account.Username)} completato: {ItalianText.Count(total, "post", "post")} in libreria.{tail}", + account.Id, + state.Context.SessionId, + ct).ConfigureAwait(false); + } + private async Task PauseAfterSingleDownloadAsync(Account account, DateTimeOffset now, SessionState state, CancellationToken ct) { await Store.Accounts.SetStateAsync(account.Id, AccountState.Paused, now, null, ct).ConfigureAwait(false); diff --git a/tests/Febe.Tests/Engine/BackfillCompletedTests.cs b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs new file mode 100644 index 0000000..50b191b --- /dev/null +++ b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs @@ -0,0 +1,59 @@ +using Febe.Core.Abstractions; +using Febe.Core.Alerts; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Storage; +using Febe.Tests.Alerts.Support; +using Febe.Tests.Engine.Support; + +namespace Febe.Tests.Engine; + +/// +/// «Storico completato» is one line of Attività and one alert per history, written by the engine with its numbers, +/// also for the runs that end otherwise right after the last page. +/// +[TestClass] +public sealed class BackfillCompletedTests +{ + private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0); + + /// + /// The walk reached the beginning of the profile and stored it, then a signal or a cancellation changed how the + /// run ended: the history is complete all the same and keeps its line (it would never be walked again). + /// + [TestMethod] + [DataRow(RecipeStatus.StoppedBySignal)] + [DataRow(RecipeStatus.Cancelled)] + public async Task AHistoryCompletedRightBeforeARunEndsOtherwiseKeepsItsLine(RecipeStatus status) + { + await using var bed = await AlertBed.CreateAsync(start: Morning); + var engine = bed.Engine; + var account = await engine.AddAccountAsync("luca.prova", followed: true, state: AccountState.Backfilling, postCount: 30); + await engine.Db.Accounts.UpdateAsync((await engine.Db.Accounts.GetAsync(account.Id))! with { KeepUpdated = false }); + var runner = new ScriptedRunner(engine.Governor, engine.Clock); + var backfills = 0; + runner.Before = async r => + { + if (r.Kind == RecipeKind.Backfill && r.AccountId == account.Id && ++backfills == 1) + { + // What the recipe stores when the walk meets the end of the list. + await engine.Db.Accounts.SetBackfillAsync(account.Id, null, engine.Clock.Now); + } + }; + runner.Script = r => r.Kind == RecipeKind.Backfill && r.AccountId == account.Id && backfills == 1 + ? new RecipeOutcome(status, 1, 6) { BackfillFinished = true } + : null; + engine.Start(runner); + await engine.RunUntilAsync(Morning.AddDays(2)); + await engine.StopAsync(); + await bed.Alerts.FlushAsync(); + + Assert.AreEqual(1, backfills, "Never walked again."); + var finished = await engine.Db.Accounts.GetAsync(account.Id); + Assert.AreEqual(AccountState.Paused, finished!.State, "«Tieni aggiornato» off: one download, then paused."); + var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] }); + Assert.HasCount(1, lines); + Assert.AreEqual("Storico di @luca.prova completato: 0 post in libreria. «Tieni aggiornato» è spento: l'account resta in pausa.", lines[0].Message); + Assert.HasCount(1, bed.Shell.Notifications.Where(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone))); + } +} -- 2.54.1 From afbd0b4a1ad8974e7ef02cb8be3fc04954d22eda Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 15:30:24 +0200 Subject: [PATCH 32/44] Storico completato: una riga sola, quella del motore MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Provando Febe per Windows contro il sito di prova, alla fine dello storico di marta.prova la sezione «Avvisi» di Attività mostrava due righe per lo stesso fatto, entrambe «storico-completato»: quella del motore («Storico di @marta.prova completato: 18 post in libreria. Da ora lo tengo aggiornato.») e una della ricetta Storico («Storico di marta.prova completato.», senza @ e senza numeri). La notifica di Windows partiva una volta sola, ma con il testo corto, perché la riga della ricetta arrivava prima. Resta solo la riga del motore, che è anche quella che cambia lo stato dell'account e che usano la dimostrazione e la simulazione. La ricetta segna lo storico come completato e lo dice al motore, senza scrivere altro. Prova nuova con le ricette vere sul sito finto sotto il motore vero: una riga negli Avvisi, una notifica e un messaggio Telegram, con il testo intero. Riga in docs/decisioni.md. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 1 + .../Recipes/RecipeRunner.Profile.cs | 3 +- .../Engine/BackfillCompletedTests.cs | 86 ++++++++++++++++++- 3 files changed, 87 insertions(+), 3 deletions(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index be3e037..75b276e 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -226,3 +226,4 @@ 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 | «Storico completato» lo scrive solo il motore (`SessionComposer.FinishBackfillAsync`: @nome, post in libreria, che cosa succede ora); la ricetta Storico non scrive più una riga sua. Il motore chiude lo storico ogni volta che il cammino è arrivato in fondo (`BackfillFinished`), anche se poi la corsa finisce con un segnale o un'interruzione | Due righe in «Avvisi» per lo stesso storico (@marta.prova, 14:31) e la notifica col testo corto, partito per primo; con un segnale subito dopo l'ultima pagina l'account restava «Storico in corso» per sempre | diff --git a/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs b/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs index dbdf9c5..c7c577b 100644 --- a/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs +++ b/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs @@ -394,9 +394,10 @@ public sealed partial class RecipeRunner run.Finished = true; if (walk.IsGrid) { + // «Storico completato» in Attività, and the new state of the account, are the engine's: one line per + // history, with its numbers (SessionComposer, from RecipeOutcome.BackfillFinished). await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false); await settings.SetAsync(walk.MarkKey(account.Id), null, run.Ct).ConfigureAwait(false); - await Writer.EventAsync("storico-completato", $"Storico di {account.Username} completato.", EventSeverity.Success, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false); } else { diff --git a/tests/Febe.Tests/Engine/BackfillCompletedTests.cs b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs index 50b191b..7aab63d 100644 --- a/tests/Febe.Tests/Engine/BackfillCompletedTests.cs +++ b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs @@ -1,22 +1,71 @@ using Febe.Core.Abstractions; using Febe.Core.Alerts; +using Febe.Core.Collection; +using Febe.Core.Collection.Readers; +using Febe.Core.Collection.Recipes; using Febe.Core.Domain; using Febe.Core.Engine; using Febe.Core.Storage; using Febe.Tests.Alerts.Support; +using Febe.Tests.Collection.Support; using Febe.Tests.Engine.Support; +using Febe.Web.Api; namespace Febe.Tests.Engine; /// -/// «Storico completato» is one line of Attività and one alert per history, written by the engine with its numbers, -/// also for the runs that end otherwise right after the last page. +/// «Storico completato» is one line of Attività and one alert per history, written by the engine with its numbers: +/// the real recipes on the scripted site (no browser) under the real engine, and the runs that end otherwise right +/// after the last page. /// [TestClass] public sealed class BackfillCompletedTests { private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0); + /// Found testing Febe for Windows on the test site: two lines in «Avvisi» for one history, at 14:31. + [TestMethod] + public async Task AHistoryCompletedByTheRecipesIsOneLineOfAvvisiWithItsNumbersAndOneNotification() + { + await using var bed = await AlertBed.CreateAsync(start: Morning); + var engine = bed.Engine; + var (runner, site) = RealRecipes(engine); + var marta = site.Add(new ScriptedAccount("2002", "marta.prova") { Followed = false }); + marta.Posts.AddRange(ScriptedBed.Posts(0, 18, Morning.AddDays(-30))); + var account = await AddBackfillingAsync(engine, marta, postCount: 18); + + engine.Start(runner); + await engine.RunUntilAsync(Morning.AddDays(2)); + await engine.StopAsync(); + await bed.Alerts.FlushAsync(); + + const string Expected = "Storico di @marta.prova completato: 18 post in libreria. Da ora lo tengo aggiornato."; + var done = await engine.Db.Accounts.GetAsync(account.Id); + Assert.IsNotNull(done!.BackfillCompletedAt, "The history reached the beginning of the profile."); + Assert.AreEqual(AccountState.UpToDate, done.State); + Assert.HasCount(18, await engine.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 })); + + var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] }); + Assert.HasCount(1, lines, "One line for one history: " + string.Join(" | ", lines.Select(e => e.Message))); + Assert.AreEqual(Expected, lines[0].Message); + Assert.AreEqual(EventSeverity.Success, lines[0].Severity); + Assert.AreEqual(account.Id, lines[0].AccountId); + Assert.IsNotNull(lines[0].SessionId); + + // The «Avvisi» list of Attività. + var alerts = (await ActivityApi.AlertsAsync(engine.Db, engine.Clock, CancellationToken.None)).Items.Where(i => i.Kind == "backfillDone").ToList(); + Assert.HasCount(1, alerts); + Assert.AreEqual(Expected, alerts[0].Message); + + // One Windows notification and one Telegram message, with the same full text. + var notification = bed.Shell.Notifications.Single(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone)); + Assert.AreEqual(Expected, notification.Message); + var telegram = bed.Telegram.Requests.Where(r => r.Text.StartsWith("Febe · Storico completato\n", StringComparison.Ordinal)).ToList(); + Assert.HasCount(1, telegram); + Assert.AreEqual("Febe · Storico completato\n" + Expected, telegram[0].Text); + Assert.HasCount(1, bed.Outcomes.Where(o => o.Alert.Kind == AlertKind.BackfillDone), "Nothing held back as a repeat either."); + } + /// /// The walk reached the beginning of the profile and stored it, then a signal or a cancellation changed how the /// run ended: the history is complete all the same and keeps its line (it would never be walked again). @@ -56,4 +105,37 @@ public sealed class BackfillCompletedTests Assert.AreEqual("Storico di @luca.prova completato: 0 post in libreria. «Tieni aggiornato» è spento: l'account resta in pausa.", lines[0].Message); Assert.HasCount(1, bed.Shell.Notifications.Where(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone))); } + + /// The real recipes over the scripted site, on the engine's database, clock, Governor and breaker. + private static (RecipeRunner Runner, ScriptedSite Site) RealRecipes(EngineTestBed engine) + { + var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), engine.Clock); + var site = new ScriptedSite(capture, engine.Clock); + var runner = new RecipeRunner(new RecipeEnvironment + { + Driver = site, + Capture = capture, + Governor = engine.Governor, + Budget = engine.Governor, + DataBudget = engine.Governor, + Signals = new SignalDetector(SignalRules.LoadTestSite(), engine.Breaker, engine.Clock), + Storage = engine.Db, + SiteMap = SiteMap.LoadTestSite(), + Clock = engine.Clock, + Random = new SeededRandom(7), + Breaker = engine.Breaker, + }); + return (runner, site); + } + + /// An account «Storico in corso» for a scripted account: posts only, so that a visit is the profile check. + private static Task AddBackfillingAsync(EngineTestBed engine, ScriptedAccount scripted, int postCount) => + engine.Db.Accounts.AddAsync(Account.Create(scripted.Username, StartingPoint.EverythingAndKeepUpdated, engine.Clock.Now, EngineTestBed.Zone, engine.Runtime.Profile) with + { + InstagramId = scripted.Id, + IsFollowed = scripted.Followed, + State = AccountState.Backfilling, + ContentTypes = ContentTypes.PostPhotos | ContentTypes.PostVideos, + PostCount = postCount, + }); } -- 2.54.1 From 9d959f910b4ba5a1c3a14b565eb72a0be400ca2c Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 16:00:04 +0200 Subject: [PATCH 33/44] Storico chiuso dal controllo del profilo: il motore lo chiude subito, con la sua riga MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Se un profilo sta tutto nella prima pagina, il controllo del profilo segnava lo storico come completato ma non cambiava lo stato e non scriveva righe. Dalla sessione dopo l'account usciva dai candidati dello Storico, quindi nessuno lo chiudeva più: restava «Storico in corso» per sempre, senza riga e senza avviso. Con due account in «Storico in corso» succedeva sempre (rilievo F1 della revisione). - Il controllo del profilo lo dice al motore con BackfillFinished, solo per un account «Storico in corso»: chi tiene solo i post nuovi non ha uno storico da annunciare. - Il motore chiude lo storico anche dopo il controllo del profilo, con la stessa FinishBackfillAsync, e prosegue con l'account aggiornato. - La fase dello Storico rilegge gli account invece di usare quelli di inizio sessione: altrimenti tornava a scorrere lo storico appena chiuso e scriveva una seconda riga. - A inizio sessione il motore chiude gli account rimasti «Storico in corso» con lo storico già completato (Febe fermata a metà, o lasciati così dalla 0.1.0). Co-Authored-By: Claude Opus 5.5 --- .../Recipes/RecipeRunner.Profile.cs | 4 + src/Febe.Core/Engine/Contracts.cs | 5 +- src/Febe.Core/Engine/SessionComposer.cs | 53 +++++++++-- .../Engine/BackfillCompletedTests.cs | 90 +++++++++++++++++++ 4 files changed, 142 insertions(+), 10 deletions(-) diff --git a/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs b/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs index c7c577b..414ed97 100644 --- a/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs +++ b/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs @@ -184,7 +184,11 @@ public sealed partial class RecipeRunner } else if (page?.HasMore == false) { + // The whole profile is on the first page, saved just now. For an account «Storico in corso» its history + // is complete: the engine closes it, with its line (RecipeOutcome.BackfillFinished). An account that + // keeps only the new posts had no history to announce. await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false); + run.Finished = account.State == AccountState.Backfilling; } } else if (CollectionWriter.Wants(account, EntryKind.Post) && (account.BackfillCursor is not null || account.BackfillCompletedAt is not null)) diff --git a/src/Febe.Core/Engine/Contracts.cs b/src/Febe.Core/Engine/Contracts.cs index 7efcf6b..fffe4ba 100644 --- a/src/Febe.Core/Engine/Contracts.cs +++ b/src/Febe.Core/Engine/Contracts.cs @@ -89,7 +89,10 @@ public sealed record RecipeOutcome( /// Accounts where the sweep saw new posts (FollowingSweep). public IReadOnlyList AccountsWithNewPosts { get; init; } = []; - /// For Backfill: true when the beginning of the profile has been reached. + /// + /// Backfill: true when the beginning of the profile has been reached. ProfileCheck: true when the check found the + /// whole profile of an account «Storico in corso» on its first page (its history is complete as well). + /// public bool BackfillFinished { get; init; } } diff --git a/src/Febe.Core/Engine/SessionComposer.cs b/src/Febe.Core/Engine/SessionComposer.cs index 9d62a89..e736465 100644 --- a/src/Febe.Core/Engine/SessionComposer.cs +++ b/src/Febe.Core/Engine/SessionComposer.cs @@ -51,6 +51,7 @@ internal sealed class SessionComposer public async Task RunAsync(SessionContext context, EngineTask? outsideWindowTask, CancellationToken ct) { var state = new SessionState(context); + await CloseCompletedHistoriesAsync(state, ct).ConfigureAwait(false); var accounts = await SyncQueueAsync(ct).ConfigureAwait(false); if (outsideWindowTask is not null) @@ -145,12 +146,41 @@ internal sealed class SessionComposer // 5. A few pages of history on one account. if (!light && !Over(state, ct)) { - await RunBackfillAsync(accounts, state, ct).ConfigureAwait(false); + await RunBackfillAsync(state, ct).ConfigureAwait(false); } return state.Summary(); } + /// + /// Accounts still «Storico in corso» whose history is complete: a run closed it but its outcome was never recorded + /// (Febe stopped in between), or an earlier version left them so. Closed before the session plans anything, with + /// their line (); nothing towards the site. + /// + private async Task CloseCompletedHistoriesAsync(SessionState state, CancellationToken ct) + { + var complete = (await Store.Accounts.ListAsync(ct).ConfigureAwait(false)) + .Where(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is not null) + .ToList(); + if (complete.Count == 0) + { + return; + } + + await _queueGate.WaitAsync(ct).ConfigureAwait(false); + try + { + foreach (var account in complete) + { + await FinishBackfillAsync(account, state, Clock.Now, CancellationToken.None).ConfigureAwait(false); + } + } + finally + { + _queueGate.Release(); + } + } + /// /// Keeps the queue in step with the accounts: a profile check and a story check (as the account wants them) for /// every contactable account, a look at each highlight collection on its profile, a backfill task for every account @@ -568,14 +598,16 @@ internal sealed class SessionComposer /// History advances on one account per session, alternating among the accounts «Storico in corso», each up to its /// daily maximum; suspended while the account has too many files waiting or the data budget is reached (§6.3). /// - private async Task RunBackfillAsync(Dictionary accounts, SessionState state, CancellationToken ct) + private async Task RunBackfillAsync(SessionState state, CancellationToken ct) { if (_health.IsSuspended(RecipeKind.Backfill) || state.Exhausted.Contains(ActionKind.BackfillPage)) { return; } - var candidates = accounts.Values + // Read again, not taken from the start of the session: a profile check of this session may have completed a + // history already (its line is written), and that account is not walked again. + var candidates = (await Store.Accounts.ListAsync(ct).ConfigureAwait(false)) .Where(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is null && CheckPolicy.IsContactable(a)) .ToList(); if (candidates.Count == 0) @@ -772,11 +804,12 @@ internal sealed class SessionComposer var kind = request.Kind; var writes = new List(); - // The walk reached the beginning of the profile: the history is complete however the run ended (a signal or a - // cancellation can come right after the last page was stored, and that account would not be walked again). - if (kind == RecipeKind.Backfill && outcome.BackfillFinished && account is not null) + // The history reached the beginning of the profile: the walk of the Storico, however the run ended (a signal or + // a cancellation can come right after the last page was stored, and that account would not be walked again), + // or a profile check that found the whole profile on its first page. What follows sees the account as it is now. + if (kind is RecipeKind.Backfill or RecipeKind.ProfileCheck && outcome.BackfillFinished && account is not null) { - await FinishBackfillAsync(account, state, now, ct).ConfigureAwait(false); + account = await FinishBackfillAsync(account, state, now, ct).ConfigureAwait(false); } switch (outcome.Status) @@ -972,9 +1005,10 @@ internal sealed class SessionComposer /// /// The history of the account is complete: «Aggiornato» (or «In pausa» with «Tieni aggiornato» off) and the one /// «storico completato» line of Attività, which is also the alert (spec §13.3). The recipes write no line of their - /// own for it. + /// own for it. Called once per history: after it the account is no longer «Storico in corso». Returns the account + /// as it is now. /// - private async Task FinishBackfillAsync(Account account, SessionState state, DateTimeOffset now, CancellationToken ct) + private async Task FinishBackfillAsync(Account account, SessionState state, DateTimeOffset now, CancellationToken ct) { var fresh = await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account; await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false); @@ -991,6 +1025,7 @@ internal sealed class SessionComposer account.Id, state.Context.SessionId, ct).ConfigureAwait(false); + return await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? fresh; } private async Task PauseAfterSingleDownloadAsync(Account account, DateTimeOffset now, SessionState state, CancellationToken ct) diff --git a/tests/Febe.Tests/Engine/BackfillCompletedTests.cs b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs index 7aab63d..3eedbd5 100644 --- a/tests/Febe.Tests/Engine/BackfillCompletedTests.cs +++ b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs @@ -106,6 +106,96 @@ public sealed class BackfillCompletedTests Assert.HasCount(1, bed.Shell.Notifications.Where(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone))); } + /// + /// A profile that fits on its first page: the profile check completes its history. When the walk of the session + /// went to another account «Storico in corso», the small one stayed so for ever, with no line and no alert (review + /// F1). Added first, the small one is the walk's next pick in that very session: it must not get a second line. + /// An account that keeps only the new posts has no history to announce. + /// + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task AHistoryCompletedByTheProfileCheckIsClosedAtOnceWithOneLine(bool smallFirst) + { + await using var bed = await AlertBed.CreateAsync(start: Morning); + var engine = bed.Engine; + var (runner, site) = RealRecipes(engine); + var big = site.Add(new ScriptedAccount("3003", "grande.prova") { Followed = false }); + big.Posts.AddRange(ScriptedBed.Posts(0, 400, Morning.AddDays(-30), prefix: "g")); + var small = site.Add(new ScriptedAccount("4004", "piccolo.prova") { Followed = false }); + small.Posts.AddRange(ScriptedBed.Posts(0, 5, Morning.AddDays(-30), prefix: "s")); + var news = site.Add(new ScriptedAccount("5005", "nuovi.prova") { Followed = false }); + news.Posts.AddRange(ScriptedBed.Posts(0, 3, Morning.AddDays(-30), prefix: "n")); + + // Among the accounts «Storico in corso» the walk takes the lowest id first. + Account smallAccount; + if (smallFirst) + { + smallAccount = await AddBackfillingAsync(engine, small, postCount: 5); + await AddBackfillingAsync(engine, big, postCount: 400); + } + else + { + await AddBackfillingAsync(engine, big, postCount: 400); + smallAccount = await AddBackfillingAsync(engine, small, postCount: 5); + } + + var newsAccount = await engine.Db.Accounts.AddAsync(Account.Create(news.Username, StartingPoint.OnlyNewFromToday, engine.Clock.Now, EngineTestBed.Zone, engine.Runtime.Profile) with + { + InstagramId = news.Id, + IsFollowed = news.Followed, + ContentTypes = ContentTypes.PostPhotos | ContentTypes.PostVideos, + PostCount = 3, + }); + Assert.AreEqual(AccountState.UpToDate, newsAccount.State); + + engine.Start(runner); + await engine.RunUntilAsync(Morning.AddDays(4)); + await engine.StopAsync(); + await bed.Alerts.FlushAsync(); + + var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] }); + var all = string.Join(" | ", lines.Select(e => e.Message)); + var done = await engine.Db.Accounts.GetAsync(smallAccount.Id); + Assert.IsNotNull(done!.BackfillCompletedAt, "The whole profile is on its first page."); + Assert.AreEqual(AccountState.UpToDate, done.State, all); + const string Expected = "Storico di @piccolo.prova completato: 5 post in libreria. Da ora lo tengo aggiornato."; + Assert.HasCount(1, lines.Where(e => e.AccountId == smallAccount.Id).ToList(), all); + Assert.AreEqual(Expected, lines.Single(e => e.AccountId == smallAccount.Id).Message); + Assert.AreEqual(1, bed.Shell.Notifications.Count(n => n.Message == Expected)); + + Assert.IsFalse(lines.Any(e => e.AccountId == newsAccount.Id), "«Solo i nuovi»: no history. " + all); + Assert.AreEqual(AccountState.UpToDate, (await engine.Db.Accounts.GetAsync(newsAccount.Id))!.State); + Assert.IsTrue(lines.GroupBy(e => e.AccountId).All(g => g.Count() == 1), "One line per history: " + all); + } + + /// + /// An account «Storico in corso» whose history is already complete (a profile check closed it and Febe stopped + /// before recording the outcome, or a version that left it so): closed when the next session starts, with its + /// line, without walking anything. + /// + [TestMethod] + public async Task AnAccountLeftStoricoInCorsoWithItsHistoryCompleteIsClosedWhenASessionStarts() + { + await using var bed = await AlertBed.CreateAsync(start: Morning); + var engine = bed.Engine; + var account = await engine.AddAccountAsync("anna.prova", followed: true, state: AccountState.Backfilling, postCount: 7); + await engine.Db.Accounts.SetBackfillAsync(account.Id, null, engine.Clock.Now); + var runner = new ScriptedRunner(engine.Governor, engine.Clock); + engine.Start(runner); + await engine.RunUntilAsync(Morning.AddDays(1)); + await engine.StopAsync(); + await bed.Alerts.FlushAsync(); + + Assert.AreEqual(AccountState.UpToDate, (await engine.Db.Accounts.GetAsync(account.Id))!.State); + var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] }); + Assert.HasCount(1, lines); + Assert.AreEqual("Storico di @anna.prova completato: 0 post in libreria. Da ora lo tengo aggiornato.", lines[0].Message); + Assert.IsNotNull(lines[0].SessionId); + Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.Backfill), "Nothing left to walk."); + Assert.HasCount(1, bed.Shell.Notifications.Where(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone))); + } + /// The real recipes over the scripted site, on the engine's database, clock, Governor and breaker. private static (RecipeRunner Runner, ScriptedSite Site) RealRecipes(EngineTestBed engine) { -- 2.54.1 From 9ce61d26cedc73fc4cbfa6e7bf9a023bc4cc42ad Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 16:02:23 +0200 Subject: [PATCH 34/44] =?UTF-8?q?Storico=20chiuso:=20la=20Coda=20non=20mos?= =?UTF-8?q?tra=20pi=C3=B9=20uno=20=C2=ABStorico=C2=BB=20da=20fare=20per=20?= =?UTF-8?q?quell'account?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Quando lo storico si chiudeva con una corsa finita per un segnale o un'interruzione, il compito dello Storico tornava in coda come «Fermata da un segnale» o «Interrotta». Fino alla sessione dopo (dopo una verifica, fino a «Riprendi») la Coda mostrava uno Storico da fare per un account già «Aggiornato» o «In pausa». Lo stesso accadeva con lo storico chiuso dal controllo del profilo, e per un account rimasto in pausa restavano in coda anche i suoi controlli (rilievo F3 della revisione). - La corsa dello Storico arrivata in fondo chiude il suo compito anche se poi si è fermata. - FinishBackfillAsync toglie dalla coda lo Storico dell'account e, se l'account resta in pausa, tutto ciò che era pianificato per lui, come farebbe la sessione dopo. I comandi di Alberto restano. Co-Authored-By: Claude Opus 5.5 --- src/Febe.Core/Engine/SessionComposer.cs | 20 +++++++- .../Engine/BackfillCompletedTests.cs | 49 ++++++++++++++----- 2 files changed, 54 insertions(+), 15 deletions(-) diff --git a/src/Febe.Core/Engine/SessionComposer.cs b/src/Febe.Core/Engine/SessionComposer.cs index e736465..cd18075 100644 --- a/src/Febe.Core/Engine/SessionComposer.cs +++ b/src/Febe.Core/Engine/SessionComposer.cs @@ -839,7 +839,12 @@ internal sealed class SessionComposer case RecipeStatus.StoppedBySignal: case RecipeStatus.Cancelled: - if (task is not null) + if (task is not null && kind == RecipeKind.Backfill && outcome.BackfillFinished) + { + // The walk got to the end before the run stopped: nothing to take up again (closed above). + writes.Add(Store.Tasks.CompleteAsync(task.Id, now, ct)); + } + else if (task is not null) { await RequeueAsync(task, outcome.Status == RecipeStatus.Cancelled ? "Interrotta" : "Fermata da un segnale", now).ConfigureAwait(false); } @@ -1014,7 +1019,18 @@ internal sealed class SessionComposer await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false); var newState = fresh.KeepUpdated ? AccountState.UpToDate : AccountState.Paused; await Store.Accounts.SetStateAsync(account.Id, newState, now, null, ct).ConfigureAwait(false); - var total = await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false); + + // The Coda follows at once, not at the next session: no «Storico» left for the account, and nothing planned + // for an account that stays paused. Commands of Alberto stay; the task in flight is settled by its outcome. + foreach (var task in await Store.Tasks.ListPendingAsync(10_000, ct).ConfigureAwait(false)) + { + if (task.AccountId == account.Id && !task.IsManual && (newState == AccountState.Paused || task.Kind == EngineTaskKind.Backfill)) + { + await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false); + } + } + + var total =await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false); var tail = fresh.KeepUpdated ? " Da ora lo tengo aggiornato." : " «Tieni aggiornato» è spento: l'account resta in pausa."; diff --git a/tests/Febe.Tests/Engine/BackfillCompletedTests.cs b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs index 3eedbd5..2973ee0 100644 --- a/tests/Febe.Tests/Engine/BackfillCompletedTests.cs +++ b/tests/Febe.Tests/Engine/BackfillCompletedTests.cs @@ -67,37 +67,60 @@ public sealed class BackfillCompletedTests } /// - /// The walk reached the beginning of the profile and stored it, then a signal or a cancellation changed how the - /// run ended: the history is complete all the same and keeps its line (it would never be walked again). + /// A run that completes the history: the walk reached the beginning of the profile and stored it, then a signal or + /// a cancellation changed how the run ended; or a profile check found the whole profile on its first page. The + /// history is closed with its line (it would never be walked again), and right after that run the Coda shows + /// nothing planned for the account, now paused: no «Storico» put back in the queue (review F3). /// [TestMethod] - [DataRow(RecipeStatus.StoppedBySignal)] - [DataRow(RecipeStatus.Cancelled)] - public async Task AHistoryCompletedRightBeforeARunEndsOtherwiseKeepsItsLine(RecipeStatus status) + [DataRow(RecipeKind.Backfill, RecipeStatus.StoppedBySignal)] + [DataRow(RecipeKind.Backfill, RecipeStatus.Cancelled)] + [DataRow(RecipeKind.ProfileCheck, RecipeStatus.Completed)] + public async Task AHistoryCompletedByARunIsClosedWithItsLineAndLeavesNothingInTheQueue(RecipeKind kind, RecipeStatus status) { await using var bed = await AlertBed.CreateAsync(start: Morning); var engine = bed.Engine; var account = await engine.AddAccountAsync("luca.prova", followed: true, state: AccountState.Backfilling, postCount: 30); await engine.Db.Accounts.UpdateAsync((await engine.Db.Accounts.GetAsync(account.Id))! with { KeepUpdated = false }); var runner = new ScriptedRunner(engine.Governor, engine.Clock); - var backfills = 0; + RecipeRequest? closing = null; + var walksAfter = 0; runner.Before = async r => { - if (r.Kind == RecipeKind.Backfill && r.AccountId == account.Id && ++backfills == 1) + if (r.AccountId != account.Id) { - // What the recipe stores when the walk meets the end of the list. + return; + } + + if (closing is not null) + { + walksAfter += r.Kind == RecipeKind.Backfill ? 1 : 0; + } + else if (r.Kind == kind) + { + // What the recipe stores: the walk met the end of the list, or the whole profile is on its first page. await engine.Db.Accounts.SetBackfillAsync(account.Id, null, engine.Clock.Now); + closing = r; } }; - runner.Script = r => r.Kind == RecipeKind.Backfill && r.AccountId == account.Id && backfills == 1 - ? new RecipeOutcome(status, 1, 6) { BackfillFinished = true } - : null; + runner.Script = r => ReferenceEquals(r, closing) ? new RecipeOutcome(status, 1, 6) { BackfillFinished = true } : null; engine.Start(runner); - await engine.RunUntilAsync(Morning.AddDays(2)); + var end = Morning.AddDays(2); + while (closing is null && engine.Clock.Now < end) + { + await engine.RunForAsync(TimeSpan.FromMinutes(1)); + } + + // Right after that run, before the next session tidies the queue. + Assert.IsNotNull(closing); + var queued = (await engine.Db.Tasks.ListPendingAsync(1000)).Where(t => t.AccountId == account.Id).ToList(); + Assert.HasCount(0, queued, "Planned for a paused account: " + string.Join(", ", queued.Select(t => $"{t.Kind} «{t.LastError}»"))); + + await engine.RunUntilAsync(end); await engine.StopAsync(); await bed.Alerts.FlushAsync(); - Assert.AreEqual(1, backfills, "Never walked again."); + Assert.AreEqual(0, walksAfter, "Never walked again."); var finished = await engine.Db.Accounts.GetAsync(account.Id); Assert.AreEqual(AccountState.Paused, finished!.State, "«Tieni aggiornato» off: one download, then paused."); var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] }); -- 2.54.1 From 3bcbbbf7c10bdb286b88f6335b8912d4bf5574da Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 16:03:08 +0200 Subject: [PATCH 35/44] Decisioni: corretto il motivo della riga doppia, aggiunte le due scelte nuove MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La riga del 20 ottobre diceva che la notifica partiva col testo corto della ricetta. Era falso: la riga della ricetta (CollectionWriter.EventAsync) va direttamente nell'archivio, non passa da EngineEvents e AlertService non la vede; la notifica e il messaggio Telegram avevano già il testo intero del motore. Il doppione riguardava solo la cronologia e gli «Avvisi» (rilievo F2 della revisione). Il messaggio del commit afbd0b4 ripete la stessa idea sbagliata: vale questa riga. Aggiunte due righe: lo storico completato dal controllo del profilo lo chiude il motore, anche a inizio sessione (F1); quando chiude uno storico il motore toglie subito dalla coda il suo Storico (F3). Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index 75b276e..40ca1a3 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -226,4 +226,6 @@ 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 | «Storico completato» lo scrive solo il motore (`SessionComposer.FinishBackfillAsync`: @nome, post in libreria, che cosa succede ora); la ricetta Storico non scrive più una riga sua. Il motore chiude lo storico ogni volta che il cammino è arrivato in fondo (`BackfillFinished`), anche se poi la corsa finisce con un segnale o un'interruzione | Due righe in «Avvisi» per lo stesso storico (@marta.prova, 14:31) e la notifica col testo corto, partito per primo; con un segnale subito dopo l'ultima pagina l'account restava «Storico in corso» per sempre | +| 2026-10-20 | «Storico completato» lo scrive solo il motore (`SessionComposer.FinishBackfillAsync`: @nome, post in libreria, che cosa succede ora); la ricetta Storico non scrive più una riga sua. Il motore chiude lo storico ogni volta che il cammino è arrivato in fondo (`BackfillFinished`), anche se poi la corsa finisce con un segnale o un'interruzione | Due righe nella cronologia e in «Avvisi» per lo stesso storico (@marta.prova, 14:31): la corta della ricetta e quella del motore. La notifica era già una sola e col testo del motore, perché la riga della ricetta (`CollectionWriter.EventAsync`) non passa da `EngineEvents` e `AlertService` non la vede. Con un segnale subito dopo l'ultima pagina l'account restava «Storico in corso» per sempre | +| 2026-10-20 | Anche lo storico completato dal controllo del profilo (profilo tutto nella prima pagina) lo chiude il motore, con la sua riga (`BackfillFinished` del controllo, solo per un account «Storico in corso»). A inizio sessione il motore chiude gli account rimasti «Storico in corso» con lo storico già completato; la fase dello Storico rilegge gli account invece di usare quelli di inizio sessione | Con due account «Storico in corso» quello piccolo restava così per sempre, senza riga né avviso: dalla sessione dopo non era più candidato dello Storico. Rileggere gli account evita una seconda riga quando lo Storico della stessa sessione sceglierebbe proprio quello appena chiuso | +| 2026-10-20 | Quando chiude uno storico, il motore toglie subito dalla coda il suo «Storico» e, se l'account resta in pausa, gli altri compiti pianificati; non rimette in coda la corsa dello Storico arrivata in fondo e poi fermata da un segnale | La Coda mostrava fino alla sessione dopo (dopo una verifica, fino a «Riprendi») uno Storico da fare per un account già «Aggiornato» o «In pausa». I comandi di Alberto restano | -- 2.54.1 From 724c0752cf7165d7e449b61a281fade120ae6a83 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 16:54:50 +0200 Subject: [PATCH 36/44] Vista remota: l'avvio dei fotogrammi si ritenta mentre la pagina cambia documento MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Da ReadyToCommitNavigation al commit di una navigazione con un nuovo RenderFrameHost (con RenderDocument: ogni navigazione, anche verso la pagina di riposo) Chromium rifiuta Page.startScreencast con -32000 «Not attached to an active page». La vista aperta in quel momento (insieme alla pagina di accesso, dopo un riposo del motore, durante una sessione) finiva in «Il browser di Febe non risponde». Ora ScreencastSession rimanda l'avvio solo su quella risposta, con pause da 100 a 500 ms e per al più 5 s sull'orologio vero (IClock, iniettabile nelle prove); ogni altro errore sale subito com'era. Nessun comando CDP nuovo. Vale anche per il riavvio dei fotogrammi dopo un riavvio del browser. Co-Authored-By: Claude Opus 5.5 --- src/Febe.Browser/Cdp/CdpCommandPolicy.cs | 20 ++++++ .../RemoteView/RemoteViewSession.cs | 8 ++- .../RemoteView/ScreencastSession.cs | 67 +++++++++++++++---- 3 files changed, 81 insertions(+), 14 deletions(-) diff --git a/src/Febe.Browser/Cdp/CdpCommandPolicy.cs b/src/Febe.Browser/Cdp/CdpCommandPolicy.cs index bd543f2..2565107 100644 --- a/src/Febe.Browser/Cdp/CdpCommandPolicy.cs +++ b/src/Febe.Browser/Cdp/CdpCommandPolicy.cs @@ -92,11 +92,31 @@ public sealed class CdpCommandNotAllowedException(string method, string message) public sealed class CdpCommandException(string method, int code, string browserMessage) : Exception($"Il comando CDP «{method}» è fallito: {browserMessage} (codice {code}).") { + /// Chromium's generic «server error» code. + public const int ServerErrorCode = -32000; + + /// + /// What Chromium answers to a browser-side page command (Page.startScreencast, Page.captureScreenshot) + /// while the page's current document is not «active»: from ReadyToCommitNavigation of a navigation that uses + /// a new RenderFrameHost until that navigation commits, DevTools already points at the new, still uncommitted frame + /// (content/browser/devtools/protocol/page_handler.cc, AssureTopLevelActiveFrame; + /// render_frame_devtools_agent_host.cc, ReadyToCommitNavigation). A new RenderFrameHost comes with a process + /// swap, a cross-site or back-forward-cache swap and, with RenderDocument (on by default in current Chromium), with + /// every navigation of the page to a new document — the rest page included. + /// + public const string InactivePageMessage = "Not attached to an active page"; + public string Method { get; } = method; public int Code { get; } = code; public string BrowserMessage { get; } = browserMessage; + + /// + /// The page is between two documents (see ): the same command a moment later finds + /// the new document committed. A browser that is gone answers differently (closed connection, no answer). + /// + public bool IsInactivePage => Code == ServerErrorCode && string.Equals(BrowserMessage, InactivePageMessage, StringComparison.Ordinal); } /// The connection to the browser is closed (browser exited, crashed or is restarting). diff --git a/src/Febe.Browser/RemoteView/RemoteViewSession.cs b/src/Febe.Browser/RemoteView/RemoteViewSession.cs index a96a8f8..9ab7dd1 100644 --- a/src/Febe.Browser/RemoteView/RemoteViewSession.cs +++ b/src/Febe.Browser/RemoteView/RemoteViewSession.cs @@ -64,12 +64,16 @@ public sealed class RemoteViewSession : IAsyncDisposable private IDisposable? _lease; private int _buttons; - public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null) + /// The page session. + /// Where the «Alberto is driving» lease is taken. + /// Where opening and closing are noted (never keys). + /// Wall-clock time for the screencast's start attempts; null: the system clock. + public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null, IClock? clock = null) { _cdp = cdp ?? throw new ArgumentNullException(nameof(cdp)); _gate = gate ?? throw new ArgumentNullException(nameof(gate)); _log = log ?? NullBrowserLog.Instance; - Screencast = new ScreencastSession(cdp, _log); + Screencast = new ScreencastSession(cdp, _log, clock); } public ScreencastSession Screencast { get; } diff --git a/src/Febe.Browser/RemoteView/ScreencastSession.cs b/src/Febe.Browser/RemoteView/ScreencastSession.cs index 530f9a0..5b3e299 100644 --- a/src/Febe.Browser/RemoteView/ScreencastSession.cs +++ b/src/Febe.Browser/RemoteView/ScreencastSession.cs @@ -39,10 +39,22 @@ public sealed record ScreencastFrame( /// Page.screencastFrameAck, stopped with Page.stopScreencast. Frames are delivered through /// (only the latest ones are kept when the reader is slow) and . /// +/// +/// A view opened while the page changes document (the rest page after a session, the login page opened together with +/// the view) can meet the moment in which Chromium refuses the start with «Not attached to an active page»: the start +/// is sent again, a few times, for at most . Any other failure is reported at once. +/// public sealed class ScreencastSession : IAsyncDisposable { + /// How long a start refused because the page is between two documents is tried again. + public static readonly TimeSpan InactivePageBudget = TimeSpan.FromSeconds(5); + + private static readonly TimeSpan FirstPause = TimeSpan.FromMilliseconds(100); + private static readonly TimeSpan LongestPause = TimeSpan.FromMilliseconds(500); + private readonly ICdpSession _cdp; private readonly IBrowserLog _log; + private readonly IClock _clock; private readonly Channel _frames = Channel.CreateBounded( new BoundedChannelOptions(2) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true }); @@ -54,10 +66,14 @@ public sealed class ScreencastSession : IAsyncDisposable private int _stopped; private long _framesReceived; - public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null) + /// The page session. + /// Where the start and stop are noted (never parameters or frames). + /// Wall-clock time for the pauses between start attempts; null: the system clock. + public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null, IClock? clock = null) { _cdp = cdp ?? throw new ArgumentNullException(nameof(cdp)); _log = log ?? NullBrowserLog.Instance; + _clock = clock ?? new SystemClock(); } /// Raised on the browser event thread for every frame: handlers must be quick. @@ -144,20 +160,47 @@ public sealed class ScreencastSession : IAsyncDisposable _lifetime.Dispose(); } - private Task SendStartAsync(CancellationToken ct) + private async Task SendStartAsync(CancellationToken ct) { var o = _options ?? new ScreencastOptions(); - return _cdp.SendAsync( - "Page.startScreencast", - new JsonObject + var deadline = _clock.Now + InactivePageBudget; + var pause = FirstPause; + for (var attempt = 1; ; attempt++) + { + try { - ["format"] = "jpeg", - ["quality"] = Math.Clamp(o.Quality, 0, 100), - ["maxWidth"] = o.MaxWidth, - ["maxHeight"] = o.MaxHeight, - ["everyNthFrame"] = Math.Max(1, o.EveryNthFrame), - }, - ct); + await _cdp.SendAsync( + "Page.startScreencast", + new JsonObject + { + ["format"] = "jpeg", + ["quality"] = Math.Clamp(o.Quality, 0, 100), + ["maxWidth"] = o.MaxWidth, + ["maxHeight"] = o.MaxHeight, + ["everyNthFrame"] = Math.Max(1, o.EveryNthFrame), + }, + ct).ConfigureAwait(false); + if (attempt > 1) + { + _log.Debug($"Vista remota: fotogrammi avviati al tentativo {attempt.ToString(System.Globalization.CultureInfo.InvariantCulture)}, dopo un cambio di pagina."); + } + + return; + } + catch (CdpCommandException ex) when (ex.IsInactivePage && _clock.Now + pause <= deadline) + { + // A navigation is committing in a new frame of the page: nothing is started on the browser side, the + // same start a moment later finds the new document. Past the budget the error goes up as it is. + } + + await _clock.Delay(pause, ct).ConfigureAwait(false); + if (Volatile.Read(ref _stopped) == 1) + { + return; // stopped meanwhile (a restart's start in the background): nothing left to start + } + + pause = pause * 2 < LongestPause ? pause * 2 : LongestPause; + } } private void OnReconnected(object? sender, EventArgs e) => -- 2.54.1 From d07b072bf84ec6c1e05d4a19d135d5ad0f95751d Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 16:55:00 +0200 Subject: [PATCH 37/44] Vista remota: nessun istante senza conducente quando una vista sostituisce l'altra MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Aprendo una vista mentre un'altra è aperta, il permesso della vecchia si chiudeva prima che la nuova prendesse il suo: per un attimo nessuno usava il browser, il motore si svegliava e riportava la pagina a riposo proprio mentre la vista nuova avviava i fotogrammi (il fallimento della CI, issue #3), e avrebbe potuto perfino cominciare una sessione. Ora OpenAsync tiene un permesso di passaggio dalla fine della vista vecchia all'avvio della nuova. L'ospite della vista usa IFebeBrowser invece di ChromiumBrowser, così si prova senza browser, e aspetta il browser sull'orologio vero (le prove d'insieme comprimono quello del motore). Co-Authored-By: Claude Opus 5.5 --- src/Febe.Server/BrowserRemoteView.cs | 51 ++++++++++++++++++++++------ src/Febe.Server/DockerPlatform.cs | 2 +- 2 files changed, 41 insertions(+), 12 deletions(-) diff --git a/src/Febe.Server/BrowserRemoteView.cs b/src/Febe.Server/BrowserRemoteView.cs index 310262b..1593f3f 100644 --- a/src/Febe.Server/BrowserRemoteView.cs +++ b/src/Febe.Server/BrowserRemoteView.cs @@ -17,18 +17,40 @@ namespace Febe.Server; /// the older view is always ended — and its screencast stopped — before the newer one starts). Keys go to the browser /// and nowhere else. /// -internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log) : IRemoteViewHost +internal sealed class BrowserRemoteViewHost : IRemoteViewHost { + private readonly IFebeBrowser _browser; + private readonly BrowserUseTracker _tracker; + private readonly IClock _clock; + private readonly IClock _browserClock; + private readonly FebeLog _log; private readonly Lock _gate = new(); private readonly SemaphoreSlim _opening = new(1, 1); private BrowserRemoteViewConnection? _current; private bool _shuttingDown; + /// The browser shown. + /// Notes when Alberto last used the browser. + /// The composition's clock (the time of that note). + /// Febe's log. + /// + /// Time for the waits on the browser itself; null: the wall clock, because the browser commits a navigation in real + /// time whatever clock the engine runs on (the tests compress it). + /// + public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null) + { + _browser = browser ?? throw new ArgumentNullException(nameof(browser)); + _tracker = tracker ?? throw new ArgumentNullException(nameof(tracker)); + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + _log = log ?? throw new ArgumentNullException(nameof(log)); + _browserClock = browserClock ?? new SystemClock(clock.LocalZone); + } + public async Task OpenAsync(CancellationToken ct) { - if (!browser.IsAvailable) + if (!_browser.IsAvailable) { - throw new RemoteViewUnavailableException(browser.LastError is { } error + throw new RemoteViewUnavailableException(_browser.LastError is { } error ? "Il browser di Febe non è in funzione: " + error : "Il browser di Febe si sta avviando: riprova fra qualche secondo."); } @@ -37,6 +59,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT // would both start and the later assignment would orphan the other (still holding its lease, and stopping the // shared screencast when it closes). await _opening.WaitAsync(ct).ConfigureAwait(false); + IDisposable? handover = null; try { BrowserRemoteViewConnection? previous; @@ -53,13 +76,17 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT if (previous is not null) { + // Alberto is still at the browser while one view takes the place of the other: without this lease the + // engine would see nobody driving for a moment and put the page back to rest (a navigation under the new + // view's start) or even begin a session. + handover = _browser.UserDriving.Begin(); await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false); } - var connection = new BrowserRemoteViewConnection(this, browser, tracker, clock); + var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock); try { - await connection.StartAsync(browser.BrowserOptions.WindowWidth, browser.BrowserOptions.WindowHeight, ct).ConfigureAwait(false); + await connection.StartAsync(_browser.WindowWidth, _browser.WindowHeight, ct).ConfigureAwait(false); } catch (Exception ex) { @@ -90,11 +117,13 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT throw new RemoteViewUnavailableException("Febe si sta fermando."); } - log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta."); + _log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta."); return connection; } finally { + // The new view holds its own lease by now; if it did not start, nobody is at the browser any more. + handover?.Dispose(); _opening.Release(); } } @@ -126,7 +155,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT } } - log.Info("vista", "Vista remota chiusa."); + _log.Info("vista", "Vista remota chiusa."); } } @@ -134,7 +163,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection { private readonly BrowserRemoteViewHost _owner; - private readonly ChromiumBrowser _browser; + private readonly IFebeBrowser _browser; private readonly BrowserUseTracker _tracker; private readonly IClock _clock; private readonly RemoteViewSession _session; @@ -155,18 +184,18 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection private int _disposed; private bool _used; - public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock) + public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock) { _owner = owner; _browser = browser; _tracker = tracker; _clock = clock; - _session = new RemoteViewSession(browser.Host.Cdp, browser.Host.UserDriving); + _session = new RemoteViewSession(browser.Cdp, browser.UserDriving, clock: browserClock); } public RemoteViewEnd? Ended { get; private set; } - private ICdpSession Cdp => _browser.Host.Cdp; + private ICdpSession Cdp => _browser.Cdp; public async Task StartAsync(int width, int height, CancellationToken ct) { diff --git a/src/Febe.Server/DockerPlatform.cs b/src/Febe.Server/DockerPlatform.cs index e37aca2..1ef5ae8 100644 --- a/src/Febe.Server/DockerPlatform.cs +++ b/src/Febe.Server/DockerPlatform.cs @@ -53,7 +53,7 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(app); - RemoteView = new BrowserRemoteViewHost((ChromiumBrowser)app.Browser!, app.Tracker, app.Clock, app.Log); + RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log); services.AddSingleton(RemoteView); } -- 2.54.1 From 1b767d517d7c9fcc53f4bfeca0b7452a2c785457 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 16:55:01 +0200 Subject: [PATCH 38/44] Prove della vista remota aperta durante un cambio di pagina MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Senza browser (RemoteViewStartTests, su FakeCdpSession e VirtualClock): un primo rifiuto «Not attached to an active page» dà comunque una vista aperta con i suoi fotogrammi; un rifiuto che non passa finisce in «non risponde» entro 5 s di orologio; collegamento chiuso o altri rifiuti non si ritentano; la sostituzione di una vista non lascia mai i permessi a zero. Nella prova con Chromium vero (TwoViewsOpenedAtTheSameMoment...) si controlla anche che durante la sostituzione il browser non resti mai senza conducente. Co-Authored-By: Claude Opus 5.5 --- .../Febe.Tests/Server/RemoteViewStartTests.cs | 253 ++++++++++++++++++ .../Febe.Tests/Server/ServerEndToEndTests.cs | 28 +- 2 files changed, 279 insertions(+), 2 deletions(-) create mode 100644 tests/Febe.Tests/Server/RemoteViewStartTests.cs diff --git a/tests/Febe.Tests/Server/RemoteViewStartTests.cs b/tests/Febe.Tests/Server/RemoteViewStartTests.cs new file mode 100644 index 0000000..70cdb9a --- /dev/null +++ b/tests/Febe.Tests/Server/RemoteViewStartTests.cs @@ -0,0 +1,253 @@ +using System.Diagnostics; +using System.Text.Json.Nodes; +using Febe.App; +using Febe.Browser.Cdp; +using Febe.Browser.Hosting; +using Febe.Browser.RemoteView; +using Febe.Core.Abstractions; +using Febe.Server; +using Febe.Tests.Browser.TestSupport; +using Febe.Web.Connection; +using Febe.Web.Engine; + +namespace Febe.Tests.Server; + +/// +/// Opening the remote view while the page changes document (Gitea issue #3), without a browser. From +/// ReadyToCommitNavigation of a navigation in a new RenderFrameHost until it commits, Chromium answers +/// Page.startScreencast with -32000 «Not attached to an active page»: the view must open once the new document is +/// there, a page that never gets there must still end in «non risponde» within a few seconds, and a browser that is gone +/// must say so at once. +/// +[TestClass] +public sealed class RemoteViewStartTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + [Timeout(30_000, CooperativeCancellation = true)] + public async Task AViewOpenedWhileThePageChangesDocumentOpensOnceTheNewDocumentIsThere() + { + var ct = TestContext.CancellationToken; + await using var bed = new Bed(attempt => attempt == 1 ? InactivePage() : null); + + var view = await bed.Host.OpenAsync(ct); + + Assert.IsNull(view.Ended, "the view is open"); + Assert.AreEqual(2, bed.Starts, "the start refused while the page changed document was sent again"); + Assert.AreEqual(1, bed.Browser.UserDriving.Leases, "the open view holds the browser"); + Assert.IsLessThan(TimeSpan.FromSeconds(1), bed.Elapsed, "a short pause, not the whole budget"); + + // Frames flow to the view: meta first, then the JPEG. + bed.Cdp.Raise("Page.screencastFrame", Frame()); + var outputs = await ReadUntilFrameAsync(view, ct); + Assert.IsInstanceOfType(outputs[0]); + Assert.IsInstanceOfType(outputs[^1]); + + await view.DisposeAsync(); + Assert.AreEqual(0, bed.Browser.UserDriving.Leases, "no view, no lease"); + } + + [TestMethod] + [Timeout(30_000, CooperativeCancellation = true)] + public async Task APageThatStaysBetweenTwoDocumentsStillEndsInNonRispondeWithinTheBudget() + { + var ct = TestContext.CancellationToken; + await using var bed = new Bed(_ => InactivePage()); + var watch = Stopwatch.StartNew(); + + var error = await Assert.ThrowsExactlyAsync(() => bed.Host.OpenAsync(ct)); + + StringAssert.Contains(error.Message, "non risponde"); + Assert.IsTrue(error.InnerException is CdpCommandException { IsInactivePage: true }, "the browser's answer stays the cause"); + Assert.IsLessThanOrEqualTo(ScreencastSession.InactivePageBudget, bed.Elapsed, "never longer than the budget"); + Assert.IsGreaterThan(TimeSpan.FromSeconds(4), bed.Elapsed, "tried for the whole budget"); + Assert.IsInRange(5, 15, bed.Starts, "a few attempts, spaced out"); + Assert.IsLessThan(TimeSpan.FromSeconds(10), watch.Elapsed, "the pauses are the clock's, not a hang"); + Assert.AreEqual(0, bed.Browser.UserDriving.Leases, "nothing of the view stays behind"); + } + + [TestMethod] + [Timeout(30_000, CooperativeCancellation = true)] + public async Task ABrowserThatIsGoneIsNotTriedAgain() + { + var ct = TestContext.CancellationToken; + await using var bed = new Bed(_ => new CdpDisconnectedException("Il collegamento con il browser si è chiuso.")); + + var error = await Assert.ThrowsExactlyAsync(() => bed.Host.OpenAsync(ct)); + + StringAssert.Contains(error.Message, "non risponde"); + Assert.AreEqual(1, bed.Starts); + Assert.AreEqual(TimeSpan.Zero, bed.Elapsed, "no pause at all"); + Assert.AreEqual(0, bed.Browser.UserDriving.Leases); + } + + [TestMethod] + [Timeout(30_000, CooperativeCancellation = true)] + public async Task AnotherRefusalOfTheBrowserIsNotTriedAgain() + { + var ct = TestContext.CancellationToken; + await using var bed = new Bed(_ => new CdpCommandException("Page.startScreencast", CdpCommandException.ServerErrorCode, "Not attached to a page")); + + await Assert.ThrowsExactlyAsync(() => bed.Host.OpenAsync(ct)); + + Assert.AreEqual(1, bed.Starts, "only «Not attached to an active page» is the moment of a navigation"); + Assert.AreEqual(TimeSpan.Zero, bed.Elapsed); + } + + [TestMethod] + [Timeout(30_000, CooperativeCancellation = true)] + public async Task ReplacingAViewKeepsAlbertoAtTheBrowserThroughout() + { + var ct = TestContext.CancellationToken; + await using var bed = new Bed(_ => null); + var gate = bed.Browser.UserDriving; + var older = await bed.Host.OpenAsync(ct); + var released = 0; + void OnChanged(object? sender, bool driving) + { + if (!driving) + { + Interlocked.Increment(ref released); + } + } + + gate.Changed += OnChanged; + try + { + var newer = await bed.Host.OpenAsync(ct); + + Assert.AreEqual(RemoteViewEnd.Replaced, older.Ended); + Assert.IsNull(newer.Ended); + Assert.AreEqual(0, released, "the engine never sees nobody at the browser between the two views (it would rest the page under the new one)"); + Assert.AreEqual(1, gate.Leases); + + await newer.DisposeAsync(); + Assert.AreEqual(1, released, "closing the last view lets the engine go on"); + Assert.AreEqual(0, gate.Leases); + } + finally + { + gate.Changed -= OnChanged; + } + } + + private static CdpCommandException InactivePage() => + new("Page.startScreencast", CdpCommandException.ServerErrorCode, CdpCommandException.InactivePageMessage); + + private static JsonObject Frame() => new() + { + ["sessionId"] = 1, + ["data"] = Convert.ToBase64String([0xFF, 0xD8, 0xFF, 0xD9]), + ["metadata"] = new JsonObject { ["deviceWidth"] = Bed.Width, ["deviceHeight"] = Bed.Height, ["pageScaleFactor"] = 1 }, + }; + + private static async Task> ReadUntilFrameAsync(IRemoteViewConnection view, CancellationToken ct) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + var outputs = new List(); + await foreach (var output in view.ReadAsync(timeout.Token)) + { + outputs.Add(output); + if (output is RemoteViewFrame) + { + break; + } + } + + return outputs; + } + + /// The host over a fake page whose answer to each Page.startScreencast is chosen by the test. + private sealed class Bed : IAsyncDisposable + { + public const int Width = 1280; + public const int Height = 900; + + private readonly FebeLog _log; + private readonly DateTimeOffset _start; + private int _starts; + + /// For the n-th start (from 1), the exception the browser answers with; null: started. + public Bed(Func startFailure) + { + Clock = new VirtualClock(); + _start = Clock.Now; + Cdp = new FakeCdpSession(Clock) + { + Responder = (method, _) => + { + switch (method) + { + case "Page.getFrameTree": + return new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } }; + case "Page.startScreencast": + if (startFailure(Interlocked.Increment(ref _starts)) is { } failure) + { + throw failure; + } + + return null; + default: + return null; + } + }, + }; + Browser = new PageBrowser(Cdp); + _log = new FebeLog(null, null, Clock); + Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock); + } + + public VirtualClock Clock { get; } + + public FakeCdpSession Cdp { get; } + + public PageBrowser Browser { get; } + + public BrowserRemoteViewHost Host { get; } + + public int Starts => Volatile.Read(ref _starts); + + /// Time spent in the host's pauses (the virtual clock moves only there). + public TimeSpan Elapsed => Clock.Now - _start; + + public async ValueTask DisposeAsync() + { + await Host.ShutdownAsync(); + _log.Dispose(); + } + } + + /// A running browser on one page, as the remote view host sees it. + private sealed class PageBrowser(ICdpSession cdp) : IFebeBrowser + { + public ICdpSession Cdp { get; } = cdp; + + public UserDrivingGate UserDriving { get; } = new(); + + public bool UserIsDriving => UserDriving.IsDriving; + + public bool IsAvailable => true; + + public string? LastError => null; + + public string ProfileDirectory => "browser"; + + public int WindowWidth => Bed.Width; + + public int WindowHeight => Bed.Height; + + public Task RunAsync(CancellationToken ct) => Task.CompletedTask; + + public Task RestAsync(CancellationToken ct) => Cdp.RestAsync(ct); + + public Task ShowToUserAsync(CancellationToken ct) => Task.CompletedTask; + + public Task HideFromUserAsync(CancellationToken ct) => Task.CompletedTask; + + public Task RestartWithEmptyProfileAsync(CancellationToken ct) => Task.CompletedTask; + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/tests/Febe.Tests/Server/ServerEndToEndTests.cs b/tests/Febe.Tests/Server/ServerEndToEndTests.cs index fb69719..ec283c0 100644 --- a/tests/Febe.Tests/Server/ServerEndToEndTests.cs +++ b/tests/Febe.Tests/Server/ServerEndToEndTests.cs @@ -250,20 +250,44 @@ public sealed partial class ServerEndToEndTests await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct); var host = server.RemoteView!; var gate = server.Browser!.UserDriving; + var released = 0; + void OnChanged(object? sender, bool driving) + { + if (!driving) + { + Interlocked.Increment(ref released); + } + } + for (var round = 0; round < 5; round++) { // From the rest page: where the browser starts, and where the engine puts it once nobody is at the browser. + // Page.getFrameTree is answered by the page itself, which DevTools holds back while a navigation is pending: + // «about:blank» here means the engine's rest has committed. await ServerTestBed.WaitUntilAsync( async () => await Febe.Browser.Cdp.CdpPageExtensions.GetMainFrameUrlAsync(server.Browser.Cdp, ct) == "about:blank", TimeSpan.FromSeconds(20), "la pagina di riposo"); - // Two tabs restored together, or the phone and the PC at once: the newest wins, the other is ended. - var views = await Task.WhenAll(Task.Run(() => host.OpenAsync(ct), ct), Task.Run(() => host.OpenAsync(ct), ct)); + // Two tabs restored together, or the phone and the PC at once: the newest wins, the other is ended — and the + // engine never sees nobody at the browser in between (it would put the page to rest under the newer view). + Volatile.Write(ref released, 0); + gate.Changed += OnChanged; + IRemoteViewConnection[] views; + try + { + views = await Task.WhenAll(Task.Run(() => host.OpenAsync(ct), ct), Task.Run(() => host.OpenAsync(ct), ct)); + } + finally + { + gate.Changed -= OnChanged; + } + var open = views.Where(v => v.Ended is null).ToList(); Assert.HasCount(1, open, $"Round {round}: one view stays open."); Assert.AreEqual(RemoteViewEnd.Replaced, views.Single(v => v.Ended is not null).Ended); Assert.AreEqual(1, gate.Leases, $"Round {round}: only the open view holds the browser."); + Assert.AreEqual(0, Volatile.Read(ref released), $"Round {round}: the browser was never left without a driver while one view replaced the other."); // The page of the replaced view closes its socket: the open view still gets its frames. await views.Single(v => v.Ended is not null).DisposeAsync(); -- 2.54.1 From 1b2faa4c7a52c7a464541da000d68091d66e162f Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 16:55:01 +0200 Subject: [PATCH 39/44] Decisioni: vista remota durante i cambi di pagina (issue #3) Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/decisioni.md b/docs/decisioni.md index be3e037..a39b8ee 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -226,3 +226,5 @@ 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 | Vista remota: `Page.startScreencast` si manda di nuovo solo se Chromium risponde -32000 «Not attached to an active page», con pause da 100 a 500 ms e per al più 5 s di orologio vero (`ScreencastSession.InactivePageBudget`); collegamento chiuso, nessuna risposta o qualunque altro rifiuto danno subito «Il browser di Febe non risponde». Nessun comando CDP nuovo | Issue #3. Dal `ReadyToCommitNavigation` di una navigazione con un nuovo RenderFrameHost fino al suo commit, DevTools punta già al documento nuovo non ancora attivo e i comandi di pagina gestiti dal browser falliscono così (`page_handler.cc`, `AssureTopLevelActiveFrame`); con RenderDocument, attivo in Chromium, vale per ogni navigazione, anche verso la pagina di riposo. Ci cadevano la vista aperta insieme alla pagina di accesso, dopo un riposo del motore o durante una sessione | +| 2026-10-20 | Sostituzione di una vista remota: `BrowserRemoteViewHost.OpenAsync` tiene un permesso «Alberto usa il browser» di passaggio dalla fine della vista vecchia all'avvio della nuova; l'ospite della vista usa `IFebeBrowser` invece di `ChromiumBrowser` | Fra le due viste i permessi scendevano a zero: il motore si svegliava e riportava la pagina a riposo proprio mentre la vista nuova avviava i fotogrammi (il fallimento della CI, issue #3), e avrebbe potuto cominciare una sessione. L'interfaccia permette di provarlo senza browser | -- 2.54.1 From 67568ae36ff461f445a7c04106e62dfa3d9fe75b Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 17:39:22 +0200 Subject: [PATCH 40/44] Prova con Chromium vero: la vista remota avviata prima del commit di una pagina MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nessuna prova con un browser vero arrivava al ritentativo di Page.startScreencast: TwoViews… prova solo il permesso di passaggio e il ritentativo girava solo su FakeCdpSession. Se Chromium cambiasse testo o codice del rifiuto, la CI resterebbe verde e Alberto ritroverebbe «Il browser di Febe non risponde». La pagina /occupata del sito locale delle prove tiene occupato il renderer per 2 s: la navigazione verso un'altra pagina dello stesso sito resta fra «ready to commit» e il commit, e l'avvio dei fotogrammi ci cade apposta. In ogni giro la vista deve aprirsi e mostrare un JPEG. Se nessun giro incontra il rifiuto, la prova è inconcludente: il ritentativo non è stato messo alla prova. Co-Authored-By: Claude Opus 5.5 --- .../RemoteViewDuringNavigationTests.cs | 129 ++++++++++++++++++ .../Browser/TestSupport/LocalTestSite.cs | 4 + 2 files changed, 133 insertions(+) create mode 100644 tests/Febe.Tests/Browser/RemoteViewDuringNavigationTests.cs diff --git a/tests/Febe.Tests/Browser/RemoteViewDuringNavigationTests.cs b/tests/Febe.Tests/Browser/RemoteViewDuringNavigationTests.cs new file mode 100644 index 0000000..5dd2d0f --- /dev/null +++ b/tests/Febe.Tests/Browser/RemoteViewDuringNavigationTests.cs @@ -0,0 +1,129 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using Febe.Browser.Cdp; +using Febe.Browser.Diagnostics; +using Febe.Browser.RemoteView; +using Febe.Tests.Browser.TestSupport; + +namespace Febe.Tests.Browser; + +/// +/// The remote view started while the page is between two documents (Gitea issue #3), on a real Chromium on Xvfb and the +/// local test site. From ReadyToCommitNavigation of a navigation in a new RenderFrameHost until its commit, +/// DevTools points at the new, not yet active document and Chromium refuses Page.startScreencast with -32000 +/// «Not attached to an active page». That moment lasts milliseconds in real use; here a page keeps its renderer busy, so +/// a navigation away from it to a page of the same site waits to commit for over a second and the start lands in it on +/// purpose. The view must open once the new document has committed and show its frames. If Chromium ever answers that +/// moment with another text or code, the start fails here, on the CI, and not in Alberto's hands. +/// +/// +/// Seen with Chrome 155 on the development machine (a standalone CDP experiment, same pages): the start was refused in +/// every round to a page of the same site and went through once the new document had committed. A navigation to +/// about:blank from a site page commits in another renderer, which is not busy, so it is not used here. And a view opened +/// through the host after a navigation has begun does not meet the refusal at all: its Page.getFrameTree is answered +/// only once that navigation has committed (see ServerEndToEndTests.AViewOpenedWhileThePageIsNavigating…). +/// +[TestClass] +[DoNotParallelize] +public sealed class RemoteViewDuringNavigationTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestInitialize] + public void RequireBrowser() + { + if (RealBrowser.UnavailableReason() is { } reason) + { + Assert.Inconclusive(reason); + } + } + + [TestMethod] + [Timeout(180_000, CooperativeCancellation = true)] + public async Task AViewStartedBeforeTheNewDocumentCommitsOpensOnceItHasCommitted() + { + var ct = TestContext.CancellationToken; + await using var browser = await RealBrowser.StartAsync(); + var cdp = browser.Cdp; + + const int rounds = 6; + var refusedRounds = 0; + for (var round = 0; round < rounds; round++) + { + // Page.navigate answers once the new document is ready to commit; the busy page commits a moment later and its + // script holds the renderer from 0.1 s after that, for 2 s. + var busy = await cdp.NavigateAsync(browser.Site.Url("/occupata"), ct); + Assert.IsTrue(busy.Succeeded, busy.ErrorText); + await Task.Delay(TimeSpan.FromMilliseconds(500), ct); + + // The login page of the site, as «Accedi a Instagram» opens it: ready to commit at once, committed only when + // the busy script lets go. + var navigation = cdp.NavigateAsync(browser.Site.Url($"/accesso?giro={round}"), ct); + await Task.Delay(TimeSpan.FromMilliseconds(150), ct); + + var notes = new ConcurrentQueue(); + var log = new DelegateBrowserLog((level, message, _) => + { + if (level == BrowserLogLevel.Debug) + { + notes.Enqueue(message); + } + }); + var view = new RemoteViewSession(cdp, browser.Host.UserDriving, log); + try + { + var watch = Stopwatch.StartNew(); + await view.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900), ct); + watch.Stop(); + var navigated = await navigation; + Assert.IsTrue(navigated.Succeeded, $"Round {round}: {navigated.ErrorText}"); + Assert.IsTrue(browser.Host.UserIsDriving, $"Round {round}: the open view holds the browser."); + + // Only the attempt number is in the note (ScreencastSession): «… al tentativo N, dopo un cambio di pagina.» + var retry = notes.FirstOrDefault(n => n.Contains("tentativo", StringComparison.Ordinal)); + if (retry is not null) + { + refusedRounds++; + } + + TestContext.WriteLine($"Giro {round}: vista aperta in {watch.ElapsedMilliseconds} ms; {retry ?? "fotogrammi avviati al primo tentativo."}"); + + // The frames of the new document: an animated page repaints all the time. + var animated = await cdp.NavigateAsync(browser.Site.Url("/animata"), ct); + Assert.IsTrue(animated.Succeeded, animated.ErrorText); + Assert.IsTrue(await JpegArrivesAsync(view.Screencast, ct), $"Round {round}: frames after the view opened."); + } + finally + { + await view.DisposeAsync(); + } + + Assert.IsFalse(browser.Host.UserIsDriving, $"Round {round}: the closed view released the browser."); + } + + TestContext.WriteLine($"Giri in cui Chromium ha rifiutato il primo avvio con «{CdpCommandException.InactivePageMessage}»: {refusedRounds} su {rounds}."); + if (refusedRounds == 0) + { + // Every view opened: the product is fine, but the start never met the refusal, so the retry was not exercised. + Assert.Inconclusive("La vista si è aperta in ogni giro, ma Chromium non ha mai rifiutato il primo avvio: la prova non ha raggiunto il momento fra «ready to commit» e il commit (pagina /occupata, versione di Chromium) e il ritentativo non è stato messo alla prova."); + } + } + + private static async Task JpegArrivesAsync(ScreencastSession screencast, CancellationToken ct) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(15)); + try + { + await foreach (var frame in screencast.ReadFramesAsync(timeout.Token)) + { + return frame.Jpeg is [0xFF, 0xD8, ..]; + } + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + } + + return false; + } +} diff --git a/tests/Febe.Tests/Browser/TestSupport/LocalTestSite.cs b/tests/Febe.Tests/Browser/TestSupport/LocalTestSite.cs index 4c76bd4..866285e 100644 --- a/tests/Febe.Tests/Browser/TestSupport/LocalTestSite.cs +++ b/tests/Febe.Tests/Browser/TestSupport/LocalTestSite.cs @@ -202,6 +202,10 @@ public sealed class LocalTestSite : IDisposable "/spa" => "

Applicazione

", "/verifica" => "

Verifica

", "/accesso" => "

Accesso

", + + // Keeps its renderer busy for 2 s, from 0.1 s after it has committed: a navigation away from it to a page of the + // same site (same renderer) reaches «ready to commit» at once but commits only when the script lets go. + "/occupata" => "

Occupata

", _ => "

Pagina di prova

", }; -- 2.54.1 From 62941b104d1a19c841f5f7b5c430910bd3b747d8 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 17:39:22 +0200 Subject: [PATCH 41/44] Prova d'insieme: vista remota aperta mentre il browser naviga MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sul server vero, la vista si apre insieme alla navigazione verso una pagina del sito (come «Accedi a Instagram» dalla pagina Collegamento) o insieme al riposo del motore: deve aprirsi, tenere un solo permesso e ricevere i fotogrammi. È una guardia di queste coppie, non del ritentativo: con la navigazione già partita Page.getFrameTree risponde solo dopo il commit. Il ritentativo lo prova RemoteViewDuringNavigationTests. Co-Authored-By: Claude Opus 5.5 --- .../Febe.Tests/Server/ServerEndToEndTests.cs | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/tests/Febe.Tests/Server/ServerEndToEndTests.cs b/tests/Febe.Tests/Server/ServerEndToEndTests.cs index ec283c0..44f6d85 100644 --- a/tests/Febe.Tests/Server/ServerEndToEndTests.cs +++ b/tests/Febe.Tests/Server/ServerEndToEndTests.cs @@ -299,6 +299,55 @@ public sealed partial class ServerEndToEndTests } } + [TestMethod] + [Timeout(180_000, CooperativeCancellation = true)] + public async Task AViewOpenedWhileThePageIsNavigatingOpensAndShowsItsFrames() + { + var ct = TestContext.CancellationToken; + await using var bed = await ServerTestBed.StartAsync(); + var server = bed.Server; + await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct); + var host = server.RemoteView!; + var browser = server.Browser!; + + for (var round = 0; round < 6; round++) + { + // From the rest page, as in TwoViews…: the previous round ends on a site page, so «about:blank» here means the + // engine's rest after the last view has committed and nothing else navigates. + await ServerTestBed.WaitUntilAsync( + async () => await Febe.Browser.Cdp.CdpPageExtensions.GetMainFrameUrlAsync(browser.Cdp, ct) == "about:blank", + TimeSpan.FromSeconds(20), + "la pagina di riposo"); + + // Even rounds: «Accedi a Instagram» on the Collegamento page navigates to the login page while the same page + // opens the view. Odd rounds: the rest page, as the engine puts it after a session or after the last view. + // A guard of these pairs, not of the retry: with the navigation already sent, the view's first look at the + // page (Page.getFrameTree) is answered only once it has committed, so the start comes after the commit (seen + // with Chrome 155). RemoteViewDuringNavigationTests makes the start meet the refusal on purpose. + var navigation = round % 2 == 0 + ? Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, $"{bed.Site.SiteUrl}/?vista={round}", ct) + : browser.RestAsync(ct); + var view = await host.OpenAsync(ct); + try + { + var navigated = await navigation; + Assert.IsTrue(navigated.Succeeded, $"Round {round}: {navigated.ErrorText}"); + Assert.IsNull(view.Ended, $"Round {round}: the view is open."); + Assert.AreEqual(1, browser.UserDriving.Leases, $"Round {round}: only the view holds the browser."); + + // A new page paints: its frames reach the view. + await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, $"{bed.Site.SiteUrl}/?giro={round}", ct); + Assert.IsTrue(await FrameArrivesAsync(view, ct), $"Round {round}: frames of the page."); + } + finally + { + await view.DisposeAsync(); + } + + Assert.AreEqual(0, browser.UserDriving.Leases, $"Round {round}: no view, no lease."); + } + } + private static async Task FrameArrivesAsync(IRemoteViewConnection view, CancellationToken ct) { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); -- 2.54.1 From ef23421d2dc3f52eabd555a4174889c707926497 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 17:39:22 +0200 Subject: [PATCH 42/44] Decisioni: come si prova con Chromium vero il ritentativo della vista remota Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/decisioni.md b/docs/decisioni.md index a39b8ee..d9d1b69 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -228,3 +228,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 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 | Vista remota: `Page.startScreencast` si manda di nuovo solo se Chromium risponde -32000 «Not attached to an active page», con pause da 100 a 500 ms e per al più 5 s di orologio vero (`ScreencastSession.InactivePageBudget`); collegamento chiuso, nessuna risposta o qualunque altro rifiuto danno subito «Il browser di Febe non risponde». Nessun comando CDP nuovo | Issue #3. Dal `ReadyToCommitNavigation` di una navigazione con un nuovo RenderFrameHost fino al suo commit, DevTools punta già al documento nuovo non ancora attivo e i comandi di pagina gestiti dal browser falliscono così (`page_handler.cc`, `AssureTopLevelActiveFrame`); con RenderDocument, attivo in Chromium, vale per ogni navigazione, anche verso la pagina di riposo. Ci cadevano la vista aperta insieme alla pagina di accesso, dopo un riposo del motore o durante una sessione | | 2026-10-20 | Sostituzione di una vista remota: `BrowserRemoteViewHost.OpenAsync` tiene un permesso «Alberto usa il browser» di passaggio dalla fine della vista vecchia all'avvio della nuova; l'ospite della vista usa `IFebeBrowser` invece di `ChromiumBrowser` | Fra le due viste i permessi scendevano a zero: il motore si svegliava e riportava la pagina a riposo proprio mentre la vista nuova avviava i fotogrammi (il fallimento della CI, issue #3), e avrebbe potuto cominciare una sessione. L'interfaccia permette di provarlo senza browser | +| 2026-10-20 | Prova con Chromium vero del ritentativo della vista remota (`RemoteViewDuringNavigationTests`): una pagina del sito locale delle prove (`/occupata`) tiene occupato il renderer per 2 s, così la navigazione verso un'altra pagina dello stesso sito resta fra «ready to commit» e il commit e `Page.startScreencast` ci cade apposta; se in nessun giro Chromium rifiuta il primo avvio, la prova risulta inconcludente e non superata | Revisione dell'issue #3: TwoViews… prova solo il permesso di passaggio, e una vista aperta dall'ospite dopo l'inizio di una navigazione non incontra il rifiuto (`Page.getFrameTree` risponde solo dopo il commit). Con Chrome 155 sulla macchina di sviluppo, in un esperimento a parte con lo stesso codice di Febe, il rifiuto è arrivato in 18 giri su 18 e la vista si è aperta al sesto tentativo; con il testo atteso cambiato la stessa sequenza fallisce. Verso about:blank da una pagina del sito il commit avviene in un altro renderer: quel caso non serve allo scopo | -- 2.54.1 From 1eed5044469a5374f37543e0fd3cb85f1f50bb10 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 18:06:21 +0200 Subject: [PATCH 43/44] =?UTF-8?q?VS=20Code:=20attivit=C3=A0=20=C2=ABprove?= =?UTF-8?q?=20Windows=C2=BB,=20ora=20che=20il=20progetto=20delle=20prove?= =?UTF-8?q?=20Windows=20=C3=A8=20in=20main?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Il ramo strumenti/vscode non poteva citare tests/Febe.Tests.Windows, che nasceva su un altro ramo: unita la correzione di WebView2, l'attività esiste e la guida la elenca. Co-Authored-By: Claude Opus 5.5 --- .vscode/tasks.json | 16 ++++++++++++++++ docs/guida/Sviluppo.md | 3 ++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 1599c2b..bcdacd1 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -34,6 +34,22 @@ "problemMatcher": "$msCompile", "presentation": { "clear": true } }, + { + "label": "prove Windows", + "detail": "dotnet test tests/Febe.Tests.Windows: le prove con WebView2 vero e un Dispatcher di WPF, solo su Windows (aprono per qualche istante la finestra «Browser di Febe»)", + "type": "process", + "command": "dotnet", + "args": [ + "test", + "${workspaceFolder}/tests/Febe.Tests.Windows", + "-nologo", + "-tl:off", + "-clp:ForceNoAlign" + ], + "group": "test", + "problemMatcher": "$msCompile", + "presentation": { "clear": true } + }, { "label": "prove con filtro", "detail": "dotnet test tests/Febe.Tests --filter …: una prova o un gruppo, per nome", diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index 1816f1f..f69ffa8 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -94,7 +94,8 @@ La cartella `.vscode/` prepara VS Code per Febe: estensioni consigliate (C# Dev stessa cartella per tutti i checkout. Instagram vero da un terminale solo con `dotnet run --project src/Febe.Desktop --no-launch-profile`: come la configurazione ⚠, è per le prove dal vivo di Alberto. -- Attività (Terminale ▸ Esegui attività): `compila`, `prove` (`dotnet test tests/Febe.Tests`), `prove con filtro` +- Attività (Terminale ▸ Esegui attività): `compila`, `prove` (`dotnet test tests/Febe.Tests`), `prove Windows` + (`dotnet test tests/Febe.Tests.Windows`, WebView2 vero: solo su Windows), `prove con filtro` (chiede il filtro, per esempio `FullyQualifiedName~Febe.Tests.Docs`), `sito di prova`, `pubblica Febe.exe` (un file solo in `out/pubblicazione/`, come `installer/costruisci.sh`) e `immagine Docker (serve Docker Desktop)`. - I file di `.vscode/` sono JSON senza commenti, così li legge anche un lettore rigido come quello dei controlli della -- 2.54.1 From 5fdbf8075aae5c3c878256677e053a10774c567f Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 18:07:39 +0200 Subject: [PATCH 44/44] =?UTF-8?q?Novit=C3=A0=20e=20stato=20per=20la=200.1.?= =?UTF-8?q?1:=20Febe=20per=20Windows=20si=20collega,=20CI,=20VS=20Code,=20?= =?UTF-8?q?prove=20su=20Windows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CHANGELOG.md ha la sezione 0.1.1 «in preparazione» con le correzioni e il lavoro sulla qualità del 20 ottobre; docs/stato.md dice che cosa è stato provato su Windows, come gira ora la CI, che cosa resta ad Alberto (C5, S2, REGISTRY_TOKEN, sicurezza dell'istanza) e i rilievi aperti. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 33 +++++++++++++++++++++++++++++++ docs/stato.md | 54 +++++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 81 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41e6111..8890624 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,38 @@ # Novità +## 0.1.1 (in preparazione) + +Versione correttiva: **Febe per Windows si collega**. Con la 0.1.0 il browser di Febe non diventava mai pronto e +l'accesso a Instagram non poteva cominciare. + +Correzioni: + +- **Febe per Windows**: il browser di Febe parte al primo tentativo. Prima WebView2 partiva, ma subito dopo veniva + toccato fuori dal suo thread; l'errore era scambiato per un avvio fallito, e il browser veniva chiuso e riavviato + per sempre. +- Febe per Windows: un «Scollega» premuto durante un nuovo tentativo di avvio poteva lasciare due browser nella finestra + e la sessione sul disco. «Esci» non resta più fermo dietro un avvio di WebView2. +- Collegamento: prima del primo giro il pannello dice «Collegato» e «Nome non ancora noto», non più «Collegato come @». +- Storico: la fine dello storico di un account dà una sola riga negli Avvisi, con il testo intero. Lo storico si chiude + anche se subito dopo l'ultima pagina arrivano un segnale, un'interruzione o il controllo del profilo: prima l'account + restava «Storico in corso» per sempre. +- Vista remota (Docker): aprirne una mentre un'altra la sostituisce, o mentre la pagina sta cambiando, non dà più «Il + browser di Febe non risponde». + +Sviluppo e qualità: + +- **CI a ogni push e a ogni unione** (`docs/processo.md`): + - controlli e gitleaks; + - tutte le prove con Chromium vero e dati sintetici, con un seme diverso a ogni esecuzione; + - installatore per Windows; + - immagine Docker provata senza rete e scansionata con Trivy. + + Dopo ogni unione in `main` l'immagine esce come `:main` e `:sha-`. Ogni esecuzione toglie ciò che ha creato, + e c'è una pulizia settimanale. +- **Sviluppo da VS Code**: attività e configurazioni di debug in `.vscode/` (guida, «Sviluppo» ▸ «Da VS Code»). +- Prove: `tests/Febe.Tests` verdi anche su Windows, e prove nuove con WebView2 vero in `tests/Febe.Tests.Windows`. +- Sito di prova: `/benvenuto`, la pagina di accesso che Febe apre in sviluppo. + ## 0.1.0 Prima versione, **anteprima**: il programma è completo e provato contro il sito di prova locale, ma non ha mai diff --git a/docs/stato.md b/docs/stato.md index 29e7d30..9e3e235 100644 --- a/docs/stato.md +++ b/docs/stato.md @@ -1,10 +1,24 @@ # Stato Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché. -Aggiornato il 13 ottobre 2026, versione 0.1.0 (anteprima). +Aggiornato il 20 ottobre 2026: versione 0.1.0 (anteprima), 0.1.1 in preparazione. ## In breve +**20 ottobre 2026.** Febe per Windows non riusciva a collegarsi: il browser di Febe non diventava mai pronto (registro di +Alberto del 14 e del 19/10). Era un errore di thread, corretto. Febe per Windows ha girato per la prima volta su un +Windows vero: collegamento, account e sessioni contro il sito di prova, dall'interfaccia. Lo stesso giorno sono arrivati: + +- la CI da grande azienda (`docs/processo.md`), con prove con Chromium vero, installatore e immagine a ogni push, + gitleaks, Trivy e pulizia; +- lo sviluppo da VS Code; +- le prove verdi anche su Windows; +- altre tre correzioni trovate provando: lo storico completato doppio o bloccato, la vista remota durante un cambio di + pagina, il pannello «Collegato come @». + +Il lavoro è su sei rami, ciascuno con la sua revisione avversaria, unito in `main` con la PR #2 (CI) e la PR +d'integrazione della 0.1.1. + Tutte le tappe M0–M8 sono state realizzate in una volta, su richiesta di Alberto del 13 ottobre 2026, sul ramo `febe-v1`. Il programma è completo e provato **contro il sito di prova locale** (§14.2) con un Chromium vero su Xvfb. **Non ha mai contattato Instagram** (regola 9): per questo le ricette, per costruzione, **si rifiutano di girare su @@ -21,14 +35,22 @@ Instagram** finché la sonda di M0 non ha prodotto i campioni da cui compilare ` | M3 | Governatore, interruttore, fascia, sessioni, composizione, avvio graduale, cruscotto, simulazione | Prove del motore verdi; `--simula 30g` per i tre profili: **zero superamenti**, nessuna azione fuori fascia, nessuna pausa sotto il pavimento. **Arresto di M3**: Alberto legge i numeri (`docs/decisioni.md` e il resoconto della simulazione) | | M4 | API, eventi, ossatura, tutte le schermate, tema scuro, finestra stretta, modalità dimostrativa | Schermate confrontate con i mockup (`docs/schermate/`, differenze in `docs/schermate/differenze.md`); gli originali di 02, 04–07, 09, 11–14 non sono stati forniti: confronto sui ritagli della panoramica | | M5 | Composizione reale, vista remota, password, pagina di errore, `/salute`, Dockerfile, compose, modello Unraid | Prova d'insieme del server reale contro il sito di prova; immagine costruita dalla CI sul runner; **non provata su Unraid** | -| M6 | Febe per Windows (WPF, WebView2Host, area di notifica, funzioni native), installatore NSIS | `Febe.exe` (file unico) e `Febe-Setup-0.1.0.exe` costruiti su Linux; **mai eseguiti su Windows**: S1–S3 da provare (`docs/prove-dal-vivo.md`, parte C) | +| M6 | Febe per Windows (WPF, WebView2Host, area di notifica, funzioni native), installatore NSIS | `Febe.exe` (file unico) e `Febe-Setup-0.1.0.exe` costruiti su Linux. **20/10, su Windows 11 (WebView2 155)**: «Browser di Febe pronto» al primo tentativo; S1 e una sessione di raccolta nelle 11 prove di `tests/Febe.Tests.Windows`. Dall'interfaccia, contro il sito di prova: collegamento, due account, «Controlla ora», 47 file in libreria, sessioni con il browser fuori vista (S2, primo caso), sessione ritrovata dopo un riavvio (S3, primo caso). **Da provare**: S2 con la finestra ridotta a icona e con lo schermo bloccato, S3 con Instagram (parte C5), l'installatore su un Windows pulito (C2) | | M7 | Importazione in quattro passi, riconoscitori, doppioni, copia verificata | Prove di importazione verdi; riconoscitore 4K Stogram solo come ipotesi (domanda 4 di §16) | | M8 | Avvisi (interfaccia, notifiche di Windows, Telegram), esportazione CSV, guida | Un arresto simulato produce striscia, notifica e messaggio (prova automatica con canali finti); guida in `docs/guida/`, pubblicata nel wiki | Revisione avversaria completata il 14 ottobre (54 rilievi confermati e corretti, vedi `docs/decisioni.md`). -Prove automatiche: `dotnet test tests/Febe.Tests` — 750 prove, tutte verdi (le prove con il browser vero si -saltano da sole dove mancano Chromium e Xvfb, come sul runner della CI). +Prove automatiche: + +- `dotnet test tests/Febe.Tests`, nella CI dal 20/10 dentro un contenitore Debian con Chromium, Xvfb, ffmpeg e NSIS: + tutte girano, **nessuna saltata** (prima, sul runner, se ne saltavano 66). Le prove del sito di prova girano una + seconda volta con il seme `1000 + numero dell'esecuzione`. +- Su Windows le prove con Chromium e Xvfb si saltano, e nessuna fallisce. +- `dotnet test tests/Febe.Tests.Windows` (solo Windows): 11 prove con WebView2 vero. + +CI: ogni push su ogni ramo passa da quattro controlli (controlli, prove, installatore, immagine). Il processo e la +protezione di `main` sono in `docs/processo.md`. ## Da fare (di Alberto) @@ -36,9 +58,29 @@ saltano da sole dove mancano Chromium e Xvfb, come sul runner della CI). campioni **ripuliti** e le righe di `interazioni.jsonl` dei comandi dell'interfaccia: con quelli si compilano `bersagli.instagram.json` e `lettori.instagram.json` e si portano le ipotesi H1–H11 a un esito. 2. **Prima sessione dal vivo** dopo la sonda, con il profilo Prudente su un profilo pubblico (parte B). -3. **Windows**: S1–S3 (parte C). **Docker su Unraid**: S3–S6 nel contenitore vero. +3. **Windows**: C5 (accesso con l'account di prova, Esci e riapri, riavvio di Windows), S2 con la finestra ridotta a + icona e con lo schermo bloccato, C2 (installatore su un Windows pulito). **Docker su Unraid**: S3–S6 nel contenitore + vero. 4. Le domande aperte di §16 (sono state adottate le proposte della terza colonna, vedi `docs/decisioni.md`). -5. Il segreto `REGISTRY_TOKEN` nel repository, perché il rilascio pubblichi l'immagine sul registro di Gitea. +5. Il segreto `REGISTRY_TOKEN` nel repository: senza, la CI e il rilascio costruiscono, provano e scansionano + l'immagine, ma non la pubblicano (lo dicono con un avviso). Il 20/10 mancava ancora. +6. Sicurezza dell'istanza Gitea: la registrazione è aperta, senza CAPTCHA, con quattro account creati da programmi fra + agosto e settembre. Il runner `fa94b0298b8d` è registrato per tutta l'istanza e i suoi lavori parlano con il Docker + dell'host, quindi un utente registrato potrebbe farci girare un suo flusso. Si consiglia di chiudere la registrazione + (`[service] DISABLE_REGISTRATION = true`) o di registrare il runner per il solo utente o repository. + +## Rilievi aperti (20 ottobre) + +- Il motore e le ricette scrivono due righe per lo stesso fatto anche per «formato-non-riconosciuto», e solo nella + cronologia per «bersaglio-non-trovato» e «ricetta-fallita». La notifica è una sola. Visto leggendo il codice, da + correggere in un cambio a parte, come «storico-completato». +- Su Windows il controllo «cartella dei dati in rete» non segue un collegamento simbolico verso una condivisione. Visto + leggendo il codice, non provato. +- Trivy, nell'immagine del 20/10: una CRITICAL (`libxml2`, CVE-2026-6653) e 246 HIGH, nessuna con una correzione di + Debian. La CI si fermerà da sola quando la correzione esisterà e non sarà ancora applicata. +- La prima sessione dopo il collegamento: se il primo giro programmato trova Febe senza account, conta come sessione + (vuota) e quella vera arriva dopo la pausa minima, circa 20 minuti. È il comportamento della specifica, ma chi ha + appena collegato Febe aspetta. ## Rimandato, e perché -- 2.54.1