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); } /// /// 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. /// The proof is what happens, not how long it takes (#46): an orphan keeps the browser process alive, so that process /// never exits and the profile stays. Under full CPU load a healthy process may report its exit after ExitWait /// (15 s), which a time limit could not tell from the orphan; the limits here only stop a hang. /// [TestMethod] [Timeout(420_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(90), "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(90), 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, the profile goes, the browser comes back. var marker = Path.Combine(profile, "segno-della-prova"); await File.WriteAllTextAsync(marker, "x", ct); using var first = Process.GetProcessById(pid); var watch = Stopwatch.StartNew(); await Task.Run(() => bed.Browser.RestartWithEmptyProfileAsync(ct), ct).WaitAsync(HangGuard, ct); TestContext.WriteLine($"Secondo «Scollega»: {watch.Elapsed.TotalSeconds:0.0} s."); Assert.IsTrue(await HasExitedAsync(first, ct), "the browser process of the first «Scollega» exited: no orphan kept it alive"); Assert.IsFalse(File.Exists(marker), "the profile with the session was deleted"); Assert.HasCount(1, await bed.ChildWindowsAsync()); Assert.IsTrue(bed.Browser.IsAvailable); var second = bed.Browser.Host.BrowserProcessId; Assert.AreNotEqual(pid, second, "a new browser process"); using var last = Process.GetProcessById(second); // Exiting closes the only WebView and its process exits: nothing is left running. watch.Restart(); await bed.Browser.DisposeAsync().AsTask().WaitAsync(HangGuard, ct); TestContext.WriteLine($"Arresto: {watch.Elapsed.TotalSeconds:0.0} s."); TestContext.WriteLine(bed.Lines.Text); Assert.IsTrue(await HasExitedAsync(last, ct), "exiting leaves no browser process behind"); 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. // The proof is the order, not a time (#46): RunAsync returns while the UI thread is still busy, which it stays // until released below (or 60 s). The 30 s only bound a RunAsync that does wait for it. var watch = Stopwatch.StartNew(); await lifetime.CancelAsync(); bool uiStillBusy; try { await run.WaitAsync(TimeSpan.FromSeconds(30), ct); uiStillBusy = !busy.Task.IsCompleted; } finally { Volatile.Write(ref released, true); await busy.Task; } TestContext.WriteLine($"RunAsync è tornato {watch.Elapsed.TotalSeconds:0.0} s dopo la cancellazione."); Assert.IsTrue(uiStillBusy, "RunAsync stops waiting at once, while the UI thread is still busy"); 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); } /// /// Only against a hang: well above ExitWait of WebView2Host (15 s) and the retries of the profile deletion (5 s), /// so a slow but healthy machine never reaches it (#46). /// private static readonly TimeSpan HangGuard = TimeSpan.FromSeconds(90); /// /// Whether a browser process exits, waiting for it by condition: a process that exits late under load is fine, one /// kept alive by an orphan WebView never exits and the guard ends the wait. /// private static async Task HasExitedAsync(Process process, CancellationToken ct) { using var guard = CancellationTokenSource.CreateLinkedTokenSource(ct); guard.CancelAfter(HangGuard); try { await process.WaitForExitAsync(guard.Token); return true; } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { return false; } } [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"); } }