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

+1
View File
@@ -11,6 +11,7 @@
</Folder>
<Folder Name="/tests/">
<Project Path="tests/Febe.Tests/Febe.Tests.csproj" />
<Project Path="tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj" />
</Folder>
<Folder Name="/tools/">
<Project Path="tools/Febe.Sonda/Febe.Sonda.csproj" />
+11
View File
@@ -244,3 +244,14 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-10-20 | Processo in `docs/processo.md`: rami `<tipo>/<argomento>` da `main`, commit piccoli in italiano, una richiesta di unione per ramo con il modello di `.gitea/` (comprese le 14 regole di §2), unione con commit di unione e ramo cancellato; `main` protetto con i quattro lavori di `verifica` come controlli richiesti e «blocca se indietro»; tag `v*` protetti; Alberto proprietario di tutto (`CODEOWNERS`) | Decisione di Alberto del 20 ottobre (processo da grande azienda); con il ramo aggiornato il commit di unione ha lo stesso contenuto del commit verificato, quindi in `main` entra solo codice provato. Le approvazioni richieste dipendono da chi apre le richieste (Gitea non conta quella dell'autore): domanda aperta per Alberto |
| 2026-10-20 | Nella verifica il lavoro «immagine» viene dopo «prove» e «installatore» (`needs: [prove, installatore]`) | `:main` e `:sha-` devono uscire solo da un commit con tutta la verifica verde, come dice `docs/docker.md`; sull'unico runner i lavori vanno comunque uno alla volta, quindi la durata non cambia. Su un ramo, se l'installatore fallisce l'immagine si salta: la richiesta di unione è già bloccata dall'installatore |
| 2026-10-20 | Anche nel rilascio il lavoro «immagine» viene dopo «prove» e «windows» (`needs: [prove, windows]`) | Come nella verifica: `:X.Y.Z` e `:latest` si pubblicano solo se anche la release potrà uscire; prima, con l'installatore rosso, l'immagine usciva senza release |
| 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 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 |
| 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 |
+58 -5
View File
@@ -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,18 @@ 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.
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:
- **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 +229,42 @@ 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: 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); «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 |
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
| 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 |
@@ -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);
}
/// <summary>
/// <see cref="Reconnected"/>, on the thread of <see cref="Attach"/> (WebView2's UI thread), one handler at a time: an
/// error of a handler is logged and never reaches <see cref="Attach"/>, 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).
/// </summary>
private void RaiseReconnected()
{
if (Reconnected is not { } handlers)
{
return;
}
foreach (var handler in handlers.GetInvocationList().Cast<EventHandler>())
{
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)));
+203 -51
View File
@@ -12,16 +12,31 @@ namespace Febe.Desktop.Browser;
/// <summary>
/// The browser of Instagram on Windows as the shared composition sees it (<see cref="IFebeBrowser"/>): a
/// <see cref="WebView2Host"/> started with retries like <see cref="ChromiumBrowser"/> 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.
/// </summary>
/// <remarks>
/// 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).
/// </remarks>
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)];
/// <summary>How long stopping waits for the restart loop to end before closing WebView2 anyway.</summary>
private static readonly TimeSpan StopWait = TimeSpan.FromSeconds(30);
private readonly WebView2BrowserSettings _settings;
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 +54,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);
}
/// <summary>The host: window «Browser di Febe», WebView2, CDP.</summary>
@@ -63,35 +78,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);
_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)
{
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;
}
}
_context.Log.Info("browser", ReadyMessage("Browser di Febe pronto"));
}
}
@@ -101,56 +91,218 @@ internal sealed class WebView2Browser : IFebeBrowser
public Task HideFromUserAsync(CancellationToken ct) => Host.HideFromUserAsync();
/// <summary>«Scollega»: WebView2 closes and its process exits, <c>Dati\browser</c> is deleted, the browser starts empty.</summary>
/// <summary>
/// «Scollega»: WebView2 closes and its process exits, <c>Dati\browser</c> is deleted, the browser starts empty. When
/// the profile cannot be deleted completely an <see cref="IOException"/> 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).
/// </summary>
public async Task RestartWithEmptyProfileAsync(CancellationToken ct)
{
Exception? deletion = null;
async Task DeleteProfileQuietlyAsync()
{
try
{
await DeleteProfileAsync().ConfigureAwait(true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
deletion = ex;
}
}
var restarted = false;
try
{
await Host.RestartAsync(DeleteProfileAsync, ct).ConfigureAwait(false);
await Host.RestartAsync(DeleteProfileQuietlyAsync, ct).ConfigureAwait(false);
MarkStarted();
restarted = true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
catch (Exception ex) when (ex is not (OutOfMemoryException or ObjectDisposedException))
{
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);
// The start that follows the deletion failed: never a dead browser after «Scollega».
RequestRestart(ex);
}
_context.Log.Info("browser", "Profilo del browser cancellato; il browser è ripartito vuoto.");
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();
/// <summary>The browser process of WebView2 went away by itself: it starts again with the same profile.</summary>
private async Task RecoverAsync()
/// <summary>
/// Stops the retries, waits for the restart loop to notice (it stops waiting for WebView2 as soon as
/// <c>_lifetime</c> is cancelled; at most <see cref="StopWait"/> in any case), then closes WebView2 and its window.
/// <c>_lifetime</c> stays undisposed on purpose: a late caller may still read its (cancelled) token.
/// </summary>
public async ValueTask DisposeAsync()
{
await _lifetime.CancelAsync().ConfigureAwait(false);
Task? restarting;
lock (_gate)
{
restarting = _restartLoop;
}
if (restarting is not null)
{
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);
}
/// <summary>
/// Runs <paramref name="start"/> until it works (true) or <paramref name="ct"/> is cancelled (false), waiting
/// <see cref="Retry"/> between attempts. With <paramref name="failedFirst"/> the first attempt already failed with it.
/// Only an exception of the start itself is a failed start; this method never throws.
/// </summary>
private async Task<bool> StartWithRetriesAsync(Func<CancellationToken, Task> 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;
}
/// <summary>
/// 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.
/// </summary>
private async Task<bool> 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 _wallClock.Delay(wait, ct).ConfigureAwait(false);
return true;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
catch (OperationCanceledException)
{
_started = false;
_lastError = $"WebView2 non riparte ({ex.GetType().Name}).";
_context.Log.Error("browser", _lastError);
return false;
}
}
/// <summary>Deletes the profile; a process of WebView2 may still hold a file for a moment.</summary>
private void MarkStarted()
{
_started = true;
_lastError = null;
}
/// <summary>
/// The browser must start again (its process went away by itself, or the start after «Scollega» failed with
/// <paramref name="failure"/>): 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.
/// </summary>
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.StartAsync(_options, token), _lifetime.Token, failure).ConfigureAwait(false))
{
_context.Log.Info("browser", ReadyMessage("Browser di Febe ripartito"));
}
}
}
/// <summary>Plain values only (the version was read on the UI thread during the start).</summary>
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.";
/// <summary>
/// Deletes the profile — off the UI thread, it can be large — retrying while a process of WebView2 still holds a
/// file for a moment.
/// </summary>
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);
}
}
}
+314 -63
View File
@@ -1,3 +1,4 @@
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Threading;
@@ -35,27 +36,49 @@ internal sealed record WebView2HostOptions(BrowserHosting Hosting, string Additi
/// «Ho finito»; using and closing it marks the browser as used for «Riprendi».</item>
/// <item>Stopping closes the WebView and waits for its browser process to exit, so the session is on disk (S3);
/// <see cref="RestartAsync"/> («Scollega») does the same before deleting the profile.</item>
/// <item>Every WebView2 call runs on the UI thread through its dispatcher.</item>
/// <item>Threads: every WebView2 object (environment, controller, <c>CoreWebView2</c>, 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 (<see cref="Version"/>, <see cref="BrowserProcessId"/>), the CDP session, and tasks. Start,
/// restart and stop run one at a time.</item>
/// <item>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.</item>
/// </list>
/// </remarks>
internal sealed class WebView2Host : IBrowserHost
{
private static readonly TimeSpan ExitWait = TimeSpan.FromSeconds(15);
/// <summary>How long stopping waits for a start or restart in progress before closing what there is.</summary>
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 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;
// 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)
{
@@ -79,18 +102,41 @@ internal sealed class WebView2Host : IBrowserHost
/// <summary>True while a WebView is attached (commands can be sent).</summary>
public bool IsAttached => _session.IsAttached;
/// <summary>The version of the WebView2 runtime in use (for the log).</summary>
public string? Version => _environment?.BrowserVersionString;
/// <summary>
/// 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.
/// </summary>
public string? Version => _version;
/// <summary>Raised on the UI thread when the browser process of WebView2 went away by itself (the owner restarts).</summary>
/// <summary>The browser process of WebView2 when it last started (0 before the first start). Any thread.</summary>
public int BrowserProcessId => Volatile.Read(ref _browserProcessId);
/// <summary>The window «Browser di Febe» (null before the first start). UI thread only, like every WPF object.</summary>
internal BrowserWindow? Window => _window;
/// <summary>
/// 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.
/// </summary>
public event EventHandler? BrowserProcessFailed;
/// <summary>Creates the window (once), the environment and the controller, and attaches the CDP session.</summary>
/// <summary>
/// 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. When <paramref name="ct"/> 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.
/// </summary>
public Task StartAsync(BrowserOptions options, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(options);
_options = options;
return OnUiAsync(StartCoreAsync);
var start = OnUiAsync(() => ExclusiveAsync(() =>
{
ct.ThrowIfCancellationRequested();
return StartCoreAsync();
}));
return UntilCancelledAsync(start, ct);
}
public Task ShowToUserAsync() => OnUiAsync(() =>
@@ -104,8 +150,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;
});
@@ -119,55 +175,50 @@ internal sealed class WebView2Host : IBrowserHost
/// <summary>
/// Closes the WebView, waits for its browser process to exit (the profile is free and written), runs
/// <paramref name="whileStopped"/> — «Scollega» deletes the profile there — and starts it again. <see cref="Cdp"/>
/// stays the same object. The browser starts again even when <paramref name="whileStopped"/> fails; its error is
/// thrown afterwards.
/// stays the same object. The browser starts again even when <paramref name="whileStopped"/> fails with an
/// <see cref="IOException"/> or <see cref="UnauthorizedAccessException"/>; that error is thrown afterwards. A failed
/// start throws its own error and, like a failed <see cref="StartAsync"/>, leaves nothing open. Once begun it goes
/// to the end whatever <paramref name="ct"/> says (the profile with the Instagram session must go, and the engine
/// starts again after it); stopping waits for it at most <see cref="StopWait"/>.
/// </summary>
public Task RestartAsync(Func<Task>? whileStopped, CancellationToken ct) => OnUiAsync(async () =>
public Task RestartAsync(Func<Task>? whileStopped, CancellationToken ct) => OnUiAsync(() => ExclusiveAsync(async () =>
{
_restarting = true;
try
ObjectDisposedException.ThrowIf(_closing, this);
Exception? failure = null;
await CloseWebViewAsync().ConfigureAwait(true);
if (whileStopped is not null)
{
await CloseWebViewAsync().ConfigureAwait(true);
Exception? failure = null;
try
{
if (whileStopped is not null)
{
await whileStopped().ConfigureAwait(true);
}
await whileStopped().ConfigureAwait(true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
failure = ex;
}
await StartCoreAsync().ConfigureAwait(true);
if (failure is not null)
{
throw failure;
}
}
finally
await StartCoreAsync().ConfigureAwait(true);
if (failure is not null)
{
_restarting = false;
ExceptionDispatchInfo.Throw(failure);
}
});
/// <summary>Closes what a failed start left, so that the next start begins clean.</summary>
public Task ResetAsync() => OnUiAsync(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)
{
@@ -177,9 +228,71 @@ internal sealed class WebView2Host : IBrowserHost
await _session.DisposeAsync().ConfigureAwait(false);
}
/// <summary>True while a WebView is in the window and attached to the session (its browser process did not die).</summary>
private bool IsRunning => _controller is not null && _session.IsAttached;
/// <summary>
/// UI thread, one at a time (<see cref="ExclusiveAsync"/>): 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.
/// </summary>
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
{
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.");
}
// 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)
{
// 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)
{
var window = new BrowserWindow(options.WindowWidth, options.WindowHeight, _settings.Icon);
@@ -196,24 +309,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;
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;
@@ -221,6 +341,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;
@@ -228,11 +350,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);
@@ -240,19 +365,37 @@ internal sealed class WebView2Host : IBrowserHost
await _session.SendAsync("Page.enable", null, CancellationToken.None).ConfigureAwait(true);
}
/// <summary>Closes the controller and waits for the browser process to exit (the profile is written). UI thread.</summary>
/// <summary>
/// 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.
/// </summary>
private async Task CloseWebViewAsync()
{
_ui.VerifyAccess();
_generation++;
_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)
@@ -260,7 +403,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);
@@ -276,24 +418,42 @@ 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 WebView that is closing, closed or replaced is not ours any more (a restart, «Scollega», a failed start).
if (_closing || generation != _generation)
{
return;
}
if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
// During a start the failure is the start's own error: the start closes what it created and the caller retries.
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 (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.
}
}
}
@@ -331,19 +491,40 @@ internal sealed class WebView2Host : IBrowserHost
private void UserNavigation(Action<CoreWebView2> action, Func<CoreWebView2, bool> 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()
@@ -368,5 +549,75 @@ internal sealed class WebView2Host : IBrowserHost
}
}
private Task OnUiAsync(Func<Task> action) => _ui.CheckAccess() ? action() : _ui.InvokeAsync(action).Task.Unwrap();
/// <summary>
/// Runs one step of the life of the WebView (start, restart, stop) after the others. UI thread. With
/// <paramref name="wait"/> the step runs anyway once that time has passed (stopping must not hang behind a start
/// that WebView2 never completes).
/// </summary>
private async Task ExclusiveAsync(Func<Task> 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();
}
}
}
/// <summary>
/// Waits for <paramref name="work"/> until <paramref name="ct"/> 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.
/// </summary>
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;
}
}
/// <summary>
/// Runs <paramref name="action"/> 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.
/// </summary>
private Task OnUiAsync(Func<Task> 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);
}
}
}
+4
View File
@@ -38,6 +38,10 @@
<ProjectReference Include="..\Febe.Desktop.Core\Febe.Desktop.Core.csproj" />
<PackageReference Include="Microsoft.Web.WebView2" />
</ItemGroup>
<ItemGroup>
<!-- Le prove che girano solo su Windows (WebView2 vero sul thread dell'interfaccia). -->
<InternalsVisibleTo Include="Febe.Tests.Windows" />
</ItemGroup>
<ItemGroup>
<!-- L'icona del marchio (appendice C), generata da BrandMark e IcoWriter: finestre e area di notifica la leggono da qui. -->
<EmbeddedResource Include="Febe.ico" LogicalName="Febe.ico" />
+18 -4
View File
@@ -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,22 @@ 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.
- 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).
## Pubblicazione
+9 -2
View File
@@ -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);
}
}
/// <summary>
/// Opens <paramref name="uri"/> 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).
/// </summary>
private void OpenOutsideLater(Uri uri) => Dispatcher.InvokeAsync(() => _openOutside(uri), DispatcherPriority.Background);
}
+5 -2
View File
@@ -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')),
@@ -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()
{