Files
Febe/src/Febe.Desktop/Browser/WebView2Host.cs
T
Alby96andClaude Opus 5.5 7aaa93fe3b Browser di Febe per Windows: all'uscita l'avvio non resta appeso a WebView2
Il limite di 30 s all'arresto copriva solo un «Scollega» in corso (rilievo R3
della revisione). FebeApp aspetta RunAsync prima di chiudere il browser, e
RunAsync e il ciclo di ripartenza aspettavano WebView2 senza limite: con un
WebView2 che non risponde, «Esci» restava fermo.

Ora WebView2Host.StartAsync onora il suo token. Chi chiama smette subito di
aspettare, un avvio non ancora cominciato non comincia più, uno in corso finisce
da sé e chiude ciò che ha creato se l'arresto è già passato. Il ciclo di
ripartenza usa lo stesso avvio, e WebView2Browser.DisposeAsync lo aspetta al
più 30 s. «Scollega», una volta cominciato, va invece fino in fondo: il profilo
con la sessione deve sparire e il motore deve ripartire.

Nuova prova: con il thread dell'interfaccia occupato, RunAsync torna subito
alla cancellazione e dopo l'uscita non si apre nessuna finestra. Rossa prima
della correzione (ancora in attesa dopo 10 s), verde dopo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:27:22 +02:00

624 lines
25 KiB
C#

using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Threading;
using Febe.App;
using Febe.Browser.Cdp;
using Febe.Browser.Diagnostics;
using Febe.Browser.Hosting;
using Febe.Browser.WebView2;
using Febe.Core.Abstractions;
using Febe.Desktop.Core;
using Microsoft.Web.WebView2.Core;
namespace Febe.Desktop.Browser;
/// <summary>Windows-only settings of <see cref="WebView2Host"/>, on top of <see cref="BrowserOptions"/>.</summary>
/// <param name="Hosting"><see cref="BrowserHosting.Window"/> or <see cref="BrowserHosting.Composition"/> (S2).</param>
/// <param name="AdditionalBrowserArguments">The switches of S2 (<see cref="BrowserArguments.ForWebView2"/>).</param>
/// <param name="Icon">The icon of the window.</param>
/// <param name="MarkUsed">Called when Alberto uses the browser and when he is done with it («Riprendi»).</param>
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed);
/// <summary>
/// The browser host of the Windows edition (spec §5, §6.1, §12): WebView2 in the window «Browser di Febe», with its own
/// user data folder (<see cref="BrowserOptions.ProfileDirectory"/>, <c>Dati\browser</c>), driven through
/// <see cref="WebView2CdpSession"/> — the same allowlist and refusals as the Chromium client — over
/// <c>CallDevToolsProtocolMethodAsync</c> and <c>GetDevToolsProtocolEventReceiver</c>. No port, no process of ours.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item>Password saving and general autofill off; no developer tools, no zoom: the page has a fixed size.</item>
/// <item>S2: the window is open but parked out of view when Alberto does not use it; the controller stays visible; the
/// switches of <see cref="BrowserArguments"/> turn off occlusion detection. Never hidden, never minimised.</item>
/// <item>Alberto is driving (the engine is still) from «Apri il browser», «Portalo in primo piano» or the login — the
/// window comes on screen — and whenever he clicks into it while it is on screen, until he closes it or presses
/// «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>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;
// 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)
{
_ui = ui ?? throw new ArgumentNullException(nameof(ui));
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
_log = log ?? throw new ArgumentNullException(nameof(log));
_session = new WebView2CdpSession(log.ForBrowser());
}
/// <summary>The page session: stable for the whole life of the host (a restart attaches a new WebView to it).</summary>
public ICdpSession Cdp => _session;
/// <summary>Raised when a new WebView replaced the previous one (subscriptions survive; domains are enabled again).</summary>
public ICdpConnectionEvents Connection => _session;
/// <summary>Leases taken while Alberto uses the browser.</summary>
public UserDrivingGate UserDriving { get; } = new();
public bool UserIsDriving => UserDriving.IsDriving;
/// <summary>True while a WebView is attached (commands can be sent).</summary>
public bool IsAttached => _session.IsAttached;
/// <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>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 — 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;
var start = OnUiAsync(() => ExclusiveAsync(() =>
{
ct.ThrowIfCancellationRequested();
return StartCoreAsync();
}));
return UntilCancelledAsync(start, ct);
}
public Task ShowToUserAsync() => OnUiAsync(() =>
{
if (_window is not { } window)
{
return Task.CompletedTask;
}
window.MoveOnScreen();
window.Activate();
window.Topmost = true;
window.Topmost = false;
// 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;
});
public Task HideFromUserAsync() => OnUiAsync(() =>
{
_window?.MoveOffScreen();
ReleaseLease();
return Task.CompletedTask;
});
/// <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 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(() => ExclusiveAsync(async () =>
{
ObjectDisposedException.ThrowIf(_closing, this);
Exception? failure = null;
await CloseWebViewAsync().ConfigureAwait(true);
if (whileStopped is not null)
{
try
{
await whileStopped().ConfigureAwait(true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
failure = ex;
}
}
await StartCoreAsync().ConfigureAwait(true);
if (failure is not null)
{
ExceptionDispatchInfo.Throw(failure);
}
}));
public async ValueTask DisposeAsync()
{
try
{
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)
{
// The dispatcher already stopped: Windows closes what is left.
}
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);
window.MoveOffScreen();
window.Show();
window.Activated += OnActivated;
window.DoneRequested += (_, _) => Done();
window.BackRequested += (_, _) => UserNavigation(core => core.GoBack(), core => core.CanGoBack);
window.ReloadRequested += (_, _) => UserNavigation(core => core.Reload(), _ => true);
window.DpiChanged += (_, _) => UpdateBounds();
_window = window;
}
var profile = Path.GetFullPath(options.ProfileDirectory);
Directory.CreateDirectory(profile);
var environmentOptions = new CoreWebView2EnvironmentOptions { AdditionalBrowserArguments = _settings.AdditionalBrowserArguments };
var environment = await CoreWebView2Environment.CreateAsync(null, profile, environmentOptions).ConfigureAwait(true);
_environment = environment;
_exited = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
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);
controller = composition;
_controller = controller;
_composition = new CompositionHost(hwnd, () => _window?.PageBounds ?? default);
_composition.Attach(composition);
}
else
{
controller = await environment.CreateCoreWebView2ControllerAsync(hwnd).ConfigureAwait(true);
_controller = controller;
}
controller.BoundsMode = CoreWebView2BoundsMode.UseRawPixels;
controller.Bounds = _window.PageBounds;
// WebView2 stops painting when IsVisible is false (S2): it stays true for the whole life of the browser.
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;
s.AreDevToolsEnabled = false;
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 += (sender, e) => OnProcessFailed(generation, sender, e);
core.Navigate(CdpPageExtensions.RestUrl);
_devTools = new CoreWebView2DevTools(_ui, core);
_session.Attach(_devTools);
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. 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
{
controller.Close();
}
catch (Exception ex) when (ex is COMException or InvalidOperationException)
{
// The browser process is already gone (it crashed): nothing left to close.
}
if (exited is not null)
{
await Task.WhenAny(exited.Task, Task.Delay(ExitWait)).ConfigureAwait(true);
}
}
if (_environment is { } environment)
{
environment.BrowserProcessExited -= OnBrowserProcessExited;
_environment = null;
}
}
private void OnBrowserProcessExited(object? sender, CoreWebView2BrowserProcessExitedEventArgs e) => _exited?.TrySetResult();
private void OnProcessFailed(int generation, object? sender, CoreWebView2ProcessFailedEventArgs e)
{
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;
}
// During a start the failure is the start's own error: the start closes what it created and the caller retries.
if (_starting)
{
_crashedWhileStarting |= kind == CoreWebView2ProcessFailedKind.BrowserProcessExited;
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.
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.
}
}
}
private void OnNewWindowRequested(object? sender, CoreWebView2NewWindowRequestedEventArgs e)
{
// Pages that open a new window stay in this one: the session stays in the profile of Febe.
e.Handled = true;
if (sender is CoreWebView2 core && Uri.TryCreate(e.Uri, UriKind.Absolute, out var uri) && uri.Scheme is "http" or "https")
{
core.Navigate(uri.AbsoluteUri);
}
}
/// <summary>
/// Alberto clicked into the window while it is on screen: he is driving. An activation while it is parked out of view
/// is not his (Windows activates the next window when another one closes) and changes nothing.
/// </summary>
private void OnActivated(object? sender, EventArgs e)
{
if (_window is not { } window || _closing || !window.IsOnScreen)
{
return;
}
TakeLease();
}
/// <summary>Alberto closed or minimised the window: done, out of view.</summary>
private void Done()
{
_window?.MoveOffScreen();
ReleaseLease();
}
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 (_core is not { } 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 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()
{
if (_lease is null)
{
_lease = UserDriving.Begin();
_log.Info("browser", "Alberto usa il browser di Febe: il motore resta fermo.");
}
_settings.MarkUsed();
}
private void ReleaseLease()
{
if (_lease is { } lease)
{
_lease = null;
_settings.MarkUsed();
lease.Dispose();
_log.Info("browser", "Browser di Febe fuori vista.");
}
}
/// <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);
}
}
}