diff --git a/src/Febe.Desktop/Browser/WebView2Browser.cs b/src/Febe.Desktop/Browser/WebView2Browser.cs index a68effc..96a8be2 100644 --- a/src/Febe.Desktop/Browser/WebView2Browser.cs +++ b/src/Febe.Desktop/Browser/WebView2Browser.cs @@ -12,8 +12,15 @@ namespace Febe.Desktop.Browser; /// /// The browser of Instagram on Windows as the shared composition sees it (): a /// started with retries like 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. /// +/// +/// 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). +/// 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); } /// The host: window «Browser di Febe», WebView2, CDP. @@ -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(); - /// «Scollega»: WebView2 closes and its process exits, Dati\browser is deleted, the browser starts empty. + /// + /// «Scollega»: WebView2 closes and its process exits, Dati\browser is deleted, the browser starts empty. When + /// the profile cannot be deleted completely an 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). + /// 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(); - - /// The browser process of WebView2 went away by itself: it starts again with the same profile. - private async Task RecoverAsync() + /// + /// Stops the retries, waits for a restart in progress, then closes WebView2 and its window. _lifetime stays + /// undisposed on purpose: a late caller may still read its (cancelled) token. + /// + 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); + } + + /// + /// Runs until it works (true) or is cancelled (false), waiting + /// between attempts. With the first attempt already failed with it. + /// Only an exception of the start itself is a failed start; this method never throws. + /// + private async Task StartWithRetriesAsync(Func 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; + } + + /// A start failed: it is said, what it left is closed, and the next attempt waits. False when cancelled. + private async Task 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; } } - /// Deletes the profile; a process of WebView2 may still hold a file for a moment. + private void MarkStarted() + { + _started = true; + _lastError = null; + } + + /// + /// The browser must start again (its process went away by itself, or the start after «Scollega» failed with + /// ): 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. + /// + 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")); + } + } + } + + /// Plain values only (the version was read on the UI thread during the start). + 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."; + + /// + /// Deletes the profile — off the UI thread, it can be large — retrying while a process of WebView2 still holds a + /// file for a moment. + /// 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); } } } diff --git a/src/Febe.Desktop/Browser/WebView2Host.cs b/src/Febe.Desktop/Browser/WebView2Host.cs index 8fe5919..13ed81c 100644 --- a/src/Febe.Desktop/Browser/WebView2Host.cs +++ b/src/Febe.Desktop/Browser/WebView2Host.cs @@ -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». /// Stopping closes the WebView and waits for its browser process to exit, so the session is on disk (S3); /// («Scollega») does the same before deleting the profile. -/// Every WebView2 call runs on the UI thread through its dispatcher. +/// Threads: every WebView2 object (environment, controller, CoreWebView2, 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 (, ), the CDP session, and tasks. Start, +/// restart, reset and stop run one at a time. /// /// internal sealed class WebView2Host : IBrowserHost { private static readonly TimeSpan ExitWait = TimeSpan.FromSeconds(15); + /// How long stopping waits for a start or restart in progress before closing what there is. + 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 /// public string? Version => _version; - /// Raised on the UI thread when the browser process of WebView2 went away by itself (the owner restarts). + /// The browser process of WebView2 when it last started (0 before the first start). Any thread. + public int BrowserProcessId => Volatile.Read(ref _browserProcessId); + + /// The window «Browser di Febe» (null before the first start). UI thread only, like every WPF object. + internal BrowserWindow? Window => _window; + + /// + /// 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. + /// public event EventHandler? BrowserProcessFailed; /// Creates the window (once), the environment and the controller, and attaches the CDP session. @@ -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 /// /// Closes the WebView, waits for its browser process to exit (the profile is free and written), runs /// — «Scollega» deletes the profile there — and starts it again. - /// stays the same object. The browser starts again even when fails; its error is - /// thrown afterwards. + /// stays the same object. The browser starts again even when fails with an + /// or ; that error is thrown afterwards. A failed + /// start throws its own error and, as after a failed , the caller closes what it left with + /// before trying again. /// - public Task RestartAsync(Func? whileStopped, CancellationToken ct) => OnUiAsync(async () => + public Task RestartAsync(Func? 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); + } + })); /// Closes what a failed start left, so that the next start begins clean. - 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); } + /// UI thread, one at a time (). 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 /// Closes the controller and waits for the browser process to exit (the profile is written). UI thread. 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 action, Func 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 action) => _ui.CheckAccess() ? action() : _ui.InvokeAsync(action).Task.Unwrap(); + /// + /// Runs one step of the life of the WebView (start, restart, reset, stop) after the others. UI thread. With + /// the step runs anyway once that time has passed (stopping must not hang behind a start + /// that WebView2 never completes). + /// + private async Task ExclusiveAsync(Func 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(); + } + } + } + + /// + /// Runs 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. + /// + private Task OnUiAsync(Func 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); + } + } } diff --git a/tests/Febe.Tests.Windows/Support/BrowserBed.cs b/tests/Febe.Tests.Windows/Support/BrowserBed.cs index 5315764..c09263b 100644 --- a/tests/Febe.Tests.Windows/Support/BrowserBed.cs +++ b/tests/Febe.Tests.Windows/Support/BrowserBed.cs @@ -15,13 +15,14 @@ namespace Febe.Tests.Windows.Support; /// internal sealed class BrowserBed : IAsyncDisposable { - private BrowserBed(TestFolder folder, UiThread ui, LogLines lines, FebeLog log, FebeDatabase database, WebView2Browser browser) + 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; } @@ -36,6 +37,9 @@ internal sealed class BrowserBed : IAsyncDisposable public FebeDatabase Database { get; } + /// When Alberto last used the browser («Riprendi» after a verification). + public BrowserUseTracker Tracker { get; } + public WebView2Browser Browser { get; } public static async Task CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window) @@ -48,14 +52,33 @@ internal sealed class BrowserBed : IAsyncDisposable 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 context = new FebePlatformContext(options, data, database, clock, log, new BrowserUseTracker()); + 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, browser); + return new BrowserBed(folder, ui, lines, log, database, tracker, browser); } + /// Waits (real time) until holds; fails with and the log otherwise. + public async Task WaitUntilAsync(Func 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); + } + } + + /// Reads a value of the UI thread (the window, its position) through the dispatcher. + public Task OnUiAsync(Func read) => Ui.InvokeAsync(read); + /// /// Starts the browser from a thread-pool thread, like FebeApp.BringUpBrowserAsync, and waits until /// returns. Fails at once when the log reports a failed start: the loop of diff --git a/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs b/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs new file mode 100644 index 0000000..31f79f1 --- /dev/null +++ b/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs @@ -0,0 +1,191 @@ +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; + +/// +/// 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. +/// +/// Two tests bring the window «Browser di Febe» on screen for a moment, as «Accedi a Instagram» does. +[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); + } + + [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"); + } +}