Browser di Febe per Windows: ripartenze robuste, WebView2 toccato solo dal suo thread

Dopo la correzione dell'avvio, la revisione di tutto il percorso del browser per Windows ha
trovato altri punti della stessa famiglia: lavoro che, se va storto, lascia il browser morto o
riprova per sempre.

- WebView2Host: avvio, ripartenza, chiusura dopo un avvio fallito e arresto passano uno alla
  volta (ognuno aspetta WebView2 sul thread dell'interfaccia e prima potevano intrecciarsi);
  un arresto del processo del browser durante un avvio fa fallire quell'avvio invece di
  lasciare un WebView morto dato per buono; l'arresto del processo si annuncia solo dopo che il
  gestore dell'evento di WebView2 è tornato (WebView2 non regge chiusure e ricreazioni dentro i
  suoi gestori) e solo per il WebView in uso; versione e numero del processo sono valori
  semplici letti sul thread dell'interfaccia; MoveFocus, Bounds, Indietro e Ricarica non fanno
  più cadere eccezioni nell'interfaccia se il processo è appena morto; in primo piano il
  permesso di guida si prende prima di spostare il fuoco.
- WebView2Browser: dopo un arresto del processo e dopo un «Scollega» la cui ripartenza fallisce,
  il browser riparte con gli stessi tentativi del primo avvio (prima: un tentativo solo, poi
  morto fino al riavvio di Febe; e con «Scollega» anche il motore restava fermo, perché
  l'errore non era di cartella); un solo ciclo di ripartenza alla volta, sul pool e mai dentro
  un gestore di WebView2; la cancellazione del profilo non blocca più la finestra.

Prove nuove su WebView2 vero: un avvio che fallisce davvero si riprova una volta sola e poi
va; la finestra viene in primo piano e torna fuori vista con il permesso di guida, anche
chiudendola; «Scollega» cancella profilo e sessione e il browser riparte vuoto; ucciso (per
numero di processo) il browser avviato dalla prova, Febe lo fa ripartire da solo; l'ospitalità
«composizione» di S2 parte e disegna.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-20 10:29:59 +02:00
1 parent a6623e5736
commit ccfd8b5c08
4 files changed
+649 -114

No files matched your search

+198 -58
View File
@@ -12,8 +12,15 @@ 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)];
@@ -22,6 +29,11 @@ internal sealed class WebView2Browser : IFebeBrowser
private readonly FebePlatformContext _context;
private readonly IClock _wallClock;
private readonly BrowserOptions _options;
private readonly CancellationTokenSource _lifetime = new();
private readonly Lock _gate = new();
private Task? _restartLoop;
private bool _restartWanted;
private Exception? _restartFailure;
private volatile bool _started;
private volatile string? _lastError;
@@ -39,7 +51,7 @@ internal sealed class WebView2Browser : IFebeBrowser
ui,
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now)),
context.Log);
Host.BrowserProcessFailed += (_, _) => _ = RecoverAsync();
Host.BrowserProcessFailed += (_, _) => RequestRestart(null);
}
/// <summary>The host: window «Browser di Febe», WebView2, CDP.</summary>
@@ -63,40 +75,10 @@ internal sealed class WebView2Browser : IFebeBrowser
public async Task RunAsync(CancellationToken ct)
{
for (var attempt = 0; !ct.IsCancellationRequested; attempt++)
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct, _lifetime.Token);
if (await StartWithRetriesAsync(token => Host.StartAsync(_options, token), stop.Token).ConfigureAwait(false))
{
try
{
await Host.StartAsync(_options, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_lastError = $"WebView2 non parte ({ex.GetType().Name}: {FirstLine(ex.Message)}).";
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
_context.Log.Error("browser", $"{_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
await Host.ResetAsync().ConfigureAwait(false);
try
{
await _wallClock.Delay(wait, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
continue;
}
// Outside the retries: what follows a start that worked never undoes it. This runs on a thread of the
// composition, so it reads only plain values of the host (the version was read on the UI thread).
_started = true;
_lastError = null;
_context.Log.Info("browser", $"Browser di Febe pronto: WebView2 {Host.Version}, pagina {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, {BrowserHostingNames.Name(_settings.Hosting)}, fuori vista.");
return;
_context.Log.Info("browser", ReadyMessage("Browser di Febe pronto"));
}
}
@@ -106,56 +88,214 @@ internal sealed class WebView2Browser : IFebeBrowser
public Task HideFromUserAsync(CancellationToken ct) => Host.HideFromUserAsync();
/// <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)
{
try
Exception? deletion = null;
async Task DeleteProfileQuietlyAsync()
{
await Host.RestartAsync(DeleteProfileAsync, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
throw new IOException($"La cartella del browser ({ProfileDirectory}) non si è potuta cancellare del tutto: esci da Febe e cancellala tu, contiene la sessione di Instagram.", ex);
try
{
await DeleteProfileAsync().ConfigureAwait(true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
deletion = ex;
}
}
_context.Log.Info("browser", "Profilo del browser cancellato; il browser è ripartito vuoto.");
var restarted = false;
try
{
await Host.RestartAsync(DeleteProfileQuietlyAsync, ct).ConfigureAwait(false);
MarkStarted();
restarted = true;
}
catch (Exception ex) when (ex is not (OutOfMemoryException or ObjectDisposedException))
{
// The start that follows the deletion failed: never a dead browser after «Scollega».
RequestRestart(ex);
}
if (deletion is not null)
{
throw new IOException($"La cartella del browser ({ProfileDirectory}) non si è potuta cancellare del tutto: esci da Febe e cancellala tu, contiene la sessione di Instagram.", deletion);
}
_context.Log.Info("browser", restarted
? "Profilo del browser cancellato; il browser è ripartito vuoto."
: "Profilo del browser cancellato; il browser ripartirà vuoto.");
}
public ValueTask DisposeAsync() => Host.DisposeAsync();
/// <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 a restart in progress, 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)
{
await restarting.ConfigureAwait(false);
}
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, what it left is closed, and the next attempt waits. False when cancelled.</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 Host.ResetAsync().ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_started = false;
_lastError = $"WebView2 non riparte ({ex.GetType().Name}).";
_context.Log.Error("browser", _lastError);
_context.Log.Warn("browser", "WebView2: quello che l'avvio non riuscito ha lasciato aperto non si è chiuso del tutto.", ex);
}
try
{
await _wallClock.Delay(wait, ct).ConfigureAwait(false);
return true;
}
catch (OperationCanceledException)
{
return false;
}
}
/// <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 restarts it, with the retries of the first start, on the thread
/// pool — never inside an event handler of WebView2. A request that comes while the loop runs makes it go round again.
/// </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.RestartAsync(null, 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);
}
}
}