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

+234 -53
View File
@@ -1,3 +1,4 @@
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Threading;
@@ -35,30 +36,47 @@ 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, reset and stop run one at a time.</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, reset 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;
// Read on the UI thread during the start: a plain value that any thread may read.
// 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)
{
@@ -88,7 +106,16 @@ internal sealed class WebView2Host : IBrowserHost
/// </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>
@@ -96,7 +123,7 @@ internal sealed class WebView2Host : IBrowserHost
{
ArgumentNullException.ThrowIfNull(options);
_options = options;
return OnUiAsync(StartCoreAsync);
return OnUiAsync(() => ExclusiveAsync(StartCoreAsync));
}
public Task ShowToUserAsync() => OnUiAsync(() =>
@@ -110,8 +137,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;
});
@@ -125,55 +162,61 @@ 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, as after a failed <see cref="StartAsync"/>, the caller closes what it left with
/// <see cref="ResetAsync"/> before trying again.
/// </summary>
public Task RestartAsync(Func<Task>? whileStopped, CancellationToken ct) => OnUiAsync(async () =>
public Task RestartAsync(Func<Task>? whileStopped, CancellationToken ct) => OnUiAsync(() => ExclusiveAsync(async () =>
{
ObjectDisposedException.ThrowIf(_closing, this);
Exception? failure = null;
_restarting = true;
try
{
await CloseWebViewAsync().ConfigureAwait(true);
Exception? failure = null;
try
if (whileStopped is not null)
{
if (whileStopped is not null)
try
{
await whileStopped().ConfigureAwait(true);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
failure = ex;
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
failure = ex;
}
}
await StartCoreAsync().ConfigureAwait(true);
if (failure is not null)
{
throw failure;
}
}
finally
{
_restarting = false;
}
});
if (failure is not null)
{
ExceptionDispatchInfo.Throw(failure);
}
}));
/// <summary>Closes what a failed start left, so that the next start begins clean.</summary>
public Task ResetAsync() => OnUiAsync(CloseWebViewAsync);
public Task ResetAsync() => OnUiAsync(() => ExclusiveAsync(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)
{
@@ -183,9 +226,32 @@ internal sealed class WebView2Host : IBrowserHost
await _session.DisposeAsync().ConfigureAwait(false);
}
/// <summary>UI thread, one at a time (<see cref="ExclusiveAsync"/>).</summary>
private async Task StartCoreAsync()
{
_ui.VerifyAccess();
ObjectDisposedException.ThrowIf(_closing, this);
var options = _options ?? throw new InvalidOperationException("Opzioni del browser mancanti.");
_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.");
}
}
finally
{
_starting = false;
}
}
private async Task CreateWebViewAsync(BrowserOptions options)
{
if (_window is null)
{
var window = new BrowserWindow(options.WindowWidth, options.WindowHeight, _settings.Icon);
@@ -202,28 +268,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;
_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;
@@ -231,6 +300,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;
@@ -238,11 +309,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);
@@ -253,16 +327,30 @@ internal sealed class WebView2Host : IBrowserHost
/// <summary>Closes the controller and waits for the browser process to exit (the profile is written). UI thread.</summary>
private async Task CloseWebViewAsync()
{
_ui.VerifyAccess();
_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)
@@ -270,7 +358,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);
@@ -286,24 +373,48 @@ 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 closed or replaced WebView is not ours any more.
if (_closing || generation != _generation)
{
return;
}
if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
// During a start the failure is the start's own error (the caller retries); while a restart closes the old
// WebView the failure changes nothing.
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 (_restarting)
{
return;
}
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.
}
}
}
@@ -341,19 +452,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()
@@ -378,5 +510,54 @@ 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, reset, 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>
/// 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);
}
}
}