Files
Febe/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs
T
Alby96andClaude Opus 5.5 a144d611ac Browser di Febe per Windows: un solo WebView nella finestra, chiunque lo avvii
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 <noreply@anthropic.com>
2026-10-20 11:23:19 +02:00

246 lines
13 KiB
C#

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;
/// <summary>
/// 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.
/// </summary>
/// <remarks>Two tests bring the window «Browser di Febe» on screen for a moment, as «Accedi a Instagram» does.</remarks>
[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);
}
/// <summary>
/// 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.
/// </summary>
[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()
{
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");
}
}