using System.Globalization;
using System.Windows.Media;
using System.Windows.Threading;
using Febe.App;
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Desktop.Core;
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
/// (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)];
/// How long stopping waits for the restart loop to end before closing WebView2 anyway.
private static readonly TimeSpan StopWait = TimeSpan.FromSeconds(30);
private readonly WebView2BrowserSettings _settings;
private readonly FebePlatformContext _context;
private readonly IClock _wallClock;
private readonly BrowserOptions _options;
private readonly CancellationTokenSource _lifetime = new();
private readonly Lock _gate = new();
private Task? _restartLoop;
private bool _restartWanted;
private Exception? _restartFailure;
private volatile bool _started;
private volatile string? _lastError;
public WebView2Browser(Dispatcher ui, WebView2BrowserSettings settings, FebePlatformContext context, ImageSource? icon)
{
ArgumentNullException.ThrowIfNull(ui);
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
_context = context ?? throw new ArgumentNullException(nameof(context));
// Starts and retries in wall-clock time, whatever clock the engine runs on.
_wallClock = new SystemClock(context.Clock.LocalZone);
ProfileDirectory = Path.GetFullPath(settings.ProfileDirectory);
_options = new BrowserOptions(ProfileDirectory, settings.Width, settings.Height);
Host = new WebView2Host(
ui,
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.OpenStartPage, context.CopyOnWindowClosed),
context.Log);
Host.BrowserProcessFailed += (_, _) => RequestRestart(null);
}
/// The host: window «Browser di Febe», WebView2, CDP.
public WebView2Host Host { get; }
public ICdpSession Cdp => Host.Cdp;
public UserDrivingGate UserDriving => Host.UserDriving;
public bool UserIsDriving => Host.UserIsDriving;
public bool IsAvailable => _started && Host.IsAttached;
public string? LastError => _lastError;
public string ProfileDirectory { get; }
public int WindowWidth => _settings.Width;
public int WindowHeight => _settings.Height;
public async Task RunAsync(CancellationToken ct)
{
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct, _lifetime.Token);
if (await StartWithRetriesAsync(token => Host.StartAsync(_options, token), stop.Token).ConfigureAwait(false))
{
_context.Log.Info("browser", ReadyMessage("Browser di Febe pronto"));
}
}
public Task RestAsync(CancellationToken ct) => Host.Cdp.RestAsync(ct);
public Task ShowToUserAsync(CancellationToken ct) => Host.ShowToUserAsync();
public Task HideFromUserAsync(CancellationToken ct) => Host.HideFromUserAsync();
///
/// «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)
{
Exception? deletion = null;
async Task DeleteProfileQuietlyAsync()
{
try
{
await DeleteProfileAsync().ConfigureAwait(true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
deletion = ex;
}
}
var restarted = false;
try
{
await Host.RestartAsync(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.");
}
///
/// Stops the retries, waits for the restart loop to notice (it stops waiting for WebView2 as soon as
/// _lifetime is cancelled; at most in any case), 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)
{
try
{
await restarting.WaitAsync(StopWait).ConfigureAwait(false);
}
catch (TimeoutException)
{
_context.Log.Warn("browser", "WebView2: la ripartenza del browser non si è fermata in tempo; Febe si chiude lo stesso.");
}
}
await Host.DisposeAsync().ConfigureAwait(false);
}
///
/// 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, and the next attempt waits. False when cancelled. What the failed start created it
/// closed itself, inside the host: a close from here could catch a browser that «Scollega» started meanwhile.
///
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 _wallClock.Delay(wait, ct).ConfigureAwait(false);
return true;
}
catch (OperationCanceledException)
{
return false;
}
}
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 starts it, with the retries of the first start, on the thread
/// pool — never inside an event handler of WebView2. A request that comes while the loop runs makes it go round
/// again. The loop only starts what is not running: when another way in (the first start, «Scollega») brought the
/// browser back first, its attempt finds it running and is done.
///
private void RequestRestart(Exception? failure)
{
lock (_gate)
{
if (_lifetime.IsCancellationRequested)
{
return;
}
_restartWanted = true;
_restartFailure ??= failure;
_restartLoop ??= Task.Run(RestartLoopAsync);
}
}
private async Task RestartLoopAsync()
{
while (true)
{
Exception? failure;
lock (_gate)
{
if (!_restartWanted || _lifetime.IsCancellationRequested)
{
_restartLoop = null;
return;
}
_restartWanted = false;
failure = _restartFailure;
_restartFailure = null;
}
if (await StartWithRetriesAsync(token => Host.StartAsync(_options, token), _lifetime.Token, failure).ConfigureAwait(false))
{
_context.Log.Info("browser", ReadyMessage("Browser di Febe ripartito"));
}
}
}
/// 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
{
await Task.Run(() =>
{
if (Directory.Exists(ProfileDirectory))
{
Directory.Delete(ProfileDirectory, recursive: true);
}
}).ConfigureAwait(true);
return;
}
catch (Exception ex) when ((ex is IOException or UnauthorizedAccessException) && attempt < 10)
{
await _wallClock.Delay(TimeSpan.FromMilliseconds(500), CancellationToken.None).ConfigureAwait(true);
}
}
}
private static string FirstLine(string text)
{
var line = text.Split('\n')[0].Trim();
return line.Length > 200 ? line[..200] : line;
}
}