Integrazione 0.1.1: unione di correzione/webview2-avvio

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	docs/decisioni.md
This commit is contained in:
Alby96 committed 2026-10-20 18:05:32 +02:00
commit 309ace91de
27 files changed
+2008 -128

No files matched your search

@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Prove che girano solo su Windows, con il WebView2 vero: il thread dell'interfaccia di WPF, il browser di Febe,
il protocollo DevTools sul sito di prova locale e una sessione di raccolta della composizione condivisa.
Si compila anche da Linux (EnableWindowsTargeting, come Febe.Desktop: la CI compila tutta la soluzione), ma si
esegue solo su Windows (dotnet test tests/Febe.Tests.Windows); dove manca il runtime WebView2 le prove risultano
inconcludenti. Mai Instagram: il browser vede solo 127.0.0.1. -->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<EnableWindowsTargeting>true</EnableWindowsTargeting>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<!-- Con WPF l'SDK toglie System.IO dagli using impliciti (Path di System.Windows.Shapes): qui serve. -->
<Using Include="System.IO" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MSTest" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Febe.Core\Febe.Core.csproj" />
<ProjectReference Include="..\..\src\Febe.Data\Febe.Data.csproj" />
<ProjectReference Include="..\..\src\Febe.Browser\Febe.Browser.csproj" />
<ProjectReference Include="..\..\src\Febe.Web\Febe.Web.csproj" />
<ProjectReference Include="..\..\src\Febe.App\Febe.App.csproj" />
<ProjectReference Include="..\..\src\Febe.Desktop.Core\Febe.Desktop.Core.csproj" />
<ProjectReference Include="..\..\src\Febe.Desktop\Febe.Desktop.csproj" />
<ProjectReference Include="..\..\tools\Febe.SitoDiProva\Febe.SitoDiProva.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,2 @@
// One WebView2 at a time: every test starts its own browser process, window and UI thread.
[assembly: DoNotParallelize]
@@ -0,0 +1,127 @@
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;
/// <summary>
/// The browser of Febe for Windows on its own, as the composition builds it (<see cref="DesktopPlatform"/> through
/// <c>DesktopShell</c>): a <see cref="WebView2Browser"/> 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.
/// </summary>
internal sealed class BrowserBed : IAsyncDisposable
{
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;
}
public TestFolder Folder { get; }
public UiThread Ui { get; }
/// <summary>What Febe wrote in its log.</summary>
public LogLines Lines { get; }
public FebeLog Log { get; }
public FebeDatabase Database { get; }
/// <summary>When Alberto last used the browser («Riprendi» after a verification).</summary>
public BrowserUseTracker Tracker { get; }
public WebView2Browser Browser { get; }
public static async Task<BrowserBed> 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 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, tracker, browser);
}
/// <summary>Waits (real time) until <paramref name="condition"/> holds; fails with <paramref name="what"/> and the log otherwise.</summary>
public async Task WaitUntilAsync(Func<bool> 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);
}
}
/// <summary>Reads a value of the UI thread (the window, its position) through the dispatcher.</summary>
public Task<T> OnUiAsync<T>(Func<T> read) => Ui.InvokeAsync(read);
/// <summary>The class names of the child windows of «Browser di Febe»: one per WebView hosted in it.</summary>
public Task<IReadOnlyList<string>> ChildWindowsAsync() =>
OnUiAsync(() => Browser.Host.Window is { } window ? ChildWindows.Of(window.Handle) : (IReadOnlyList<string>)[]);
/// <summary>
/// Starts the browser from a thread-pool thread, like <c>FebeApp.BringUpBrowserAsync</c>, and waits until
/// <see cref="WebView2Browser.RunAsync"/> returns. Fails at once when the log reports a failed start: the loop of
/// retries would otherwise go on for ever.
/// </summary>
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();
}
}
}
@@ -0,0 +1,31 @@
using System.Runtime.InteropServices;
namespace Febe.Tests.Windows.Support;
/// <summary>
/// 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.
/// </summary>
internal static class ChildWindows
{
/// <summary>The class names of the direct children of <paramref name="parent"/>, in Z order.</summary>
public static IReadOnlyList<string> Of(IntPtr parent)
{
var names = new List<string>();
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);
}
@@ -0,0 +1,78 @@
using Febe.Core.Abstractions;
using Febe.Desktop.Core;
namespace Febe.Tests.Windows.Support;
/// <summary>
/// A clock that compresses time, like the one of the Linux suite: <see cref="Delay"/> waits for real only a fraction
/// of the requested time and <see cref="Now"/> moves on by the whole of it, so the engine keeps its order of events
/// while a session lasts minutes instead of hours.
/// </summary>
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
{
/// <summary>
/// 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.
/// </summary>
public static TimeZoneInfo Noon()
{
var offset = 12 - DateTimeOffset.UtcNow.Hour;
return TimeZoneInfo.CreateCustomTimeZone("Febe/Mezzogiorno", TimeSpan.FromHours(offset), "Mezzogiorno di prova", "Mezzogiorno di prova");
}
}
/// <summary>The registry values «CartellaDati» and «NuovaCartellaDati», in memory.</summary>
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;
}
@@ -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;
/// <summary>
/// The shared composition (<see cref="FebeApp"/>) as Febe.exe composes it — <see cref="DesktopPlatform"/>,
/// <c>DesktopShell</c>, 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.
/// </summary>
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; }
/// <summary>What Febe wrote in its log.</summary>
public LogLines Lines { get; }
public CompressedClock Clock { get; }
public DesktopPlatform Platform { get; }
public FebeApp App { get; }
/// <summary>The browser of Febe: WebView2 (Febe.exe never uses another one unless asked with <c>--browser edge</c>).</summary>
public WebView2Browser Browser => App.Browser as WebView2Browser ?? throw new AssertFailedException("Il browser della composizione non è WebView2.");
/// <param name="name">Prefix of the temporary folder.</param>
/// <param name="autoLogin"><c>--accesso-di-prova</c>: the composition opens the test site once at start-up.</param>
public static async Task<DesktopBed> 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<string> 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;
}
}
/// <summary>A request as the main window sends it; the answer must be 200 with JSON.</summary>
public async Task<JsonElement> 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();
}
/// <summary>Waits (real time) until <paramref name="condition"/> holds; fails with <paramref name="what"/> and the log otherwise.</summary>
public async Task WaitUntilAsync(Func<Task<bool>> 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);
}
}
/// <summary>Stops the composition (the browser of Febe closes on its UI thread), then the UI thread, folders, site.</summary>
public async ValueTask DisposeAsync()
{
_client.Dispose();
try
{
await App.DisposeAsync();
}
finally
{
await Ui.DisposeAsync();
Folder.Dispose();
await Site.DisposeAsync();
}
}
}
@@ -0,0 +1,54 @@
using System.Text;
namespace Febe.Tests.Windows.Support;
/// <summary>The «console» of <see cref="Febe.App.FebeLog"/> in a test: the lines Alberto would find in his log.</summary>
internal sealed class LogLines : TextWriter
{
private readonly Lock _gate = new();
private readonly List<string> _lines = [];
private readonly StringBuilder _current = new();
public override Encoding Encoding => Encoding.UTF8;
public IReadOnlyList<string> 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();
}
}
}
@@ -0,0 +1,39 @@
namespace Febe.Tests.Windows.Support;
/// <summary>
/// A temporary folder under <see cref="Path.GetTempPath"/> (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.
/// </summary>
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);
}
}
}
}
@@ -0,0 +1,55 @@
using System.Windows.Threading;
namespace Febe.Tests.Windows.Support;
/// <summary>
/// A UI thread like the one of Febe.exe: an STA thread running a WPF <see cref="System.Windows.Threading.Dispatcher"/>
/// (its message pump and its <see cref="DispatcherSynchronizationContext"/>). The browser of Febe is created on it,
/// while the test itself — like the engine of Febe — runs on thread-pool threads.
/// </summary>
internal sealed class UiThread : IAsyncDisposable
{
private readonly Thread _thread;
private UiThread(Thread thread, Dispatcher dispatcher)
{
_thread = thread;
Dispatcher = dispatcher;
}
public Dispatcher Dispatcher { get; }
/// <summary>The managed id of the UI thread (to tell where code ran).</summary>
public int ThreadId => _thread.ManagedThreadId;
public static async Task<UiThread> StartAsync()
{
var ready = new TaskCompletionSource<Dispatcher>(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);
}
/// <summary>Runs <paramref name="action"/> on the UI thread and waits for it.</summary>
public Task<T> InvokeAsync<T>(Func<T> 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);
}
}
@@ -0,0 +1,39 @@
using System.Runtime.CompilerServices;
using Microsoft.Web.WebView2.Core;
namespace Febe.Tests.Windows.Support;
/// <summary>Whether these tests can run here: Windows with the WebView2 runtime (the tests are inconclusive otherwise).</summary>
internal static class WebView2Runtime
{
/// <summary>Null when WebView2 can run; otherwise why not, in Italian (the text of the inconclusive result).</summary>
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}).";
}
}
/// <summary>The version of the installed WebView2 runtime, e.g. «141.0.3537.71».</summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public static string? InstalledVersion() => CoreWebView2Environment.GetAvailableBrowserVersionString();
/// <summary>Marks the test inconclusive where WebView2 cannot run.</summary>
public static void Require()
{
if (UnavailableReason() is { } reason)
{
Assert.Inconclusive(reason);
}
}
}
@@ -0,0 +1,50 @@
using System.Text.RegularExpressions;
using Febe.Browser.Cdp;
using Febe.Tests.Windows.Support;
namespace Febe.Tests.Windows;
/// <summary>
/// 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.
/// </summary>
[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();
}
@@ -0,0 +1,200 @@
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;
/// <summary>
/// S1 on a real Windows (docs/prove-dal-vivo.md, C3): the DevTools protocol of WebView2 through the real
/// <see cref="WebView2CdpSession"/> 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.
/// </summary>
[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<WebView2CdpSession>(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<CdpCommandNotAllowedException>(() => cdp.SendAsync("Emulation.setTimezoneOverride", new JsonObject { ["timezoneId"] = "America/New_York" }, ct));
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Network.setUserAgentOverride", new JsonObject { ["userAgent"] = "Febe" }, ct));
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Page.addScriptToEvaluateOnNewDocument", new JsonObject { ["source"] = "1" }, ct));
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Fetch.enable", null, ct));
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Target.createTarget", new JsonObject { ["url"] = "about:blank" }, ct));
var before = (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble();
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.EvaluateAsync("window.scrollBy(0, 500)", ct));
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);
// 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<bool> 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);
}
}
/// <summary>The JSON bodies the page received, by path.</summary>
private sealed class BodyCollector : IResponseConsumer
{
private readonly ConcurrentDictionary<string, string> _bodies = new(StringComparer.Ordinal);
public ICollection<string> 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;
}
}
}
@@ -0,0 +1,102 @@
using System.Net.Http;
using Febe.App;
using Febe.Core.Domain;
using Febe.Desktop.Browser;
using Febe.Tests.Windows.Support;
namespace Febe.Tests.Windows;
/// <summary>
/// One real collection session of the shared composition (<see cref="FebeApp"/>) running on WebView2, as Febe.exe
/// 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.
/// </summary>
[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 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 path that failed on Alberto's PC), the pipeline and
// the engine follow.
await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
Assert.IsInstanceOfType<WebView2Browser>(app.Browser);
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, 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 bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", null, ct);
if (check.GetProperty("status").GetString() == "needsConfirmation")
{
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 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",
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<Media> stored = [];
await bed.WaitUntilAsync(
async () =>
{
stored = await StoredAsync(app, marta.Id, ct);
return stored.Count >= 3;
},
TimeSpan.FromSeconds(180),
"tre file di marta.prova nella libreria",
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, bed.Folder.Path, "inside the temporary library");
}
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: {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<List<Media>> StoredAsync(FebeApp app, long accountId, CancellationToken ct)
{
var list = new List<Media>();
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;
}
}
@@ -0,0 +1,67 @@
using Febe.Core.Storage;
using Febe.Tests.Windows.Support;
using Febe.Web.Connection;
namespace Febe.Tests.Windows;
/// <summary>
/// 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.
/// </summary>
[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);
}
}
@@ -0,0 +1,299 @@
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);
}
/// <summary>
/// «Esci» while the start does not complete (review of 20 October 2026): the composition awaits
/// <see cref="Febe.Desktop.Browser.WebView2Browser.RunAsync"/> 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.
/// </summary>
[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()
{
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");
}
}
@@ -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()
{
+15
View File
@@ -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()
{