Files
Febe/src/Febe.Desktop.Core/DesktopPlatform.cs
T
Alby96andClaude Opus 5.5 c49df4ca7b Browser mai bianco né muto: pagina iniziale, finestra che resta, fotogrammi che ripartono (#52)
Il browser di Febe a volte era bianco o non mostrava nulla. Le cause erano
diverse e si correggono insieme.

- Pagina iniziale. Se il browser è a riposo su about:blank e Alberto lo apre
  («Usa il browser», «Apri il browser»), Febe lo porta sulla home del sito
  quando è collegato, altrimenti sulla pagina di accesso. È un'azione di
  Alberto, sotto il suo permesso di guida, non del motore: Febe aspetta che
  la sessione finisca e prende il turno della pagina.
  Il nuovo pulsante «Pagina iniziale» sta nella barra della finestra di
  Windows e nella vista remota. Su about:blank la barra dice «Il browser è a
  riposo su una pagina vuota». «Indietro» non torna più sulla pagina di
  riposo.
- Disconnessione. «Apri il browser» nella striscia rossa apre la pagina di
  accesso. Con --accesso-di-prova il primo controllo all'avvio non segnala
  più una disconnessione finta.
- Windows: la finestra resta.
  - Lasciare una pagina di Febe non nasconde più la finestra «Browser di
    Febe» e non la rimette a riposo: finisce solo il permesso tenuto dalla
    pagina (cancel con pageLeft, IConnectionService.ReleaseAsync).
  - Sullo schermo la finestra ha il suo pulsante nella barra delle
    applicazioni, così ridurla a icona non la fa sparire. Dopo 2 minuti
    ridotta a icona torna fuori vista (S2).
  - Se lo schermo è troppo piccolo, la finestra si restringe all'area di
    lavoro e la pagina si rimpicciolisce con ZoomFactor, con le stesse misure
    CSS.
  - I bordi della pagina si riapplicano, con NotifyParentWindowPositionChanged,
    quando la finestra si mostra, si sposta o riparte il processo GPU.
  - Una pagina che non risponde mentre Alberto guida resta com'è.
  - IBrowserWindow.ShowAsync lascia il posto a
    IConnectionService.ShowBrowserAsync.
- Docker: fotogrammi che ripartono. La vista remota ha un watchdog. Riavvia
  i fotogrammi dopo una pagina nuova caricata senza fotogrammi e dopo circa
  2 s di silenzio. L'attesa raddoppia fino a 30 s finché la pagina resta
  ferma. Se il riavvio non porta nulla, la vista riceve un'immagine ferma
  (Page.captureScreenshot, già fra i comandi ammessi).
  RemoteViewSession ha ora un registro vero: avvii, riavvii e silenzi vanno
  a livello Info, categoria «vista», senza indirizzi.
  Se dopo 8 s non arriva nessuna immagine, l'interfaccia mostra «Nessuna
  immagine dal browser» con «Riprova».

Nessun comando CDP nuovo e nessuna dipendenza nuova. Aggiornati PROTOCOLLO.md
e la guida (Primo collegamento, Attività e arresti, Installazione Windows,
Problemi comuni).

Prove nuove:
- ScreencastWatchdogTests, RemoteViewFramesTests (Chromium vero, solo CI
  Linux)
- Home e Indietro in RemoteViewStartTests
- RemoteViewSocketTests
- ConnectionApiTests
- BrowserStartPageTests
- BrowserWindowDecisionTests e BrowserWindowTests (WebView2 vero)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 12:51:12 +01:00

332 lines
14 KiB
C#

using System.Globalization;
using Febe.App;
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Core.Library;
using Febe.Web;
using Febe.Web.Api;
using Febe.Web.Connection;
using Febe.Web.Library;
using Febe.Web.Native;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Desktop.Core;
/// <summary>How the window «Browser di Febe» hosts WebView2 (spec §6.1, §12, S2).</summary>
/// <param name="ProfileDirectory">The WebView2 user data folder: <c>Dati\browser</c>, with the Instagram session.</param>
/// <param name="Width">Width of the page in CSS pixels, always the same.</param>
/// <param name="Height">Height of the page in CSS pixels, always the same.</param>
/// <param name="Hosting"><see cref="BrowserHosting.Window"/> or <see cref="BrowserHosting.Composition"/>.</param>
/// <param name="AdditionalBrowserArguments">The switches of S2 (<see cref="BrowserArguments.ForWebView2"/>).</param>
public sealed record WebView2BrowserSettings(string ProfileDirectory, int Width, int Height, BrowserHosting Hosting, string AdditionalBrowserArguments);
/// <summary>
/// What the Windows-only part of the desktop (Febe.Desktop, WPF) gives the platform: the native shell (with the
/// notifications), the WebView2 browser, Edge's window, the WebView2 runtime probe. Tests on Linux pass fakes.
/// </summary>
public interface IDesktopShell
{
/// <summary>
/// Folder picker, «Mostra nella cartella», default browser, notifications, start with the computer. Its
/// notifications are the Windows channel of the alerts (spec §13.3): the shared composition sends them through it.
/// </summary>
INativeShell Native { get; }
/// <summary>The installed WebView2 runtime; null when missing.</summary>
string? WebView2Version();
/// <summary>The window «Browser di Febe» on WebView2.</summary>
IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context);
/// <summary>Microsoft Edge (fallback «edge» of S2); null when it is not installed.</summary>
string? FindEdge();
/// <summary>Brings the main window of a process (Edge) to the front, on screen.</summary>
Task ShowProcessWindowAsync(int processId, CancellationToken ct);
/// <summary>Moves the main window of a process (Edge) out of view, still open: never minimised (S2).</summary>
Task HideProcessWindowAsync(int processId, CancellationToken ct);
/// <summary>
/// Ties a process Febe started (Edge) to the life of Febe.exe: Windows ends it, with the processes it opens, when
/// Febe ends — also after a crash or «Termina attività», so that it never stays behind holding the profile and the
/// debugging port. False when Windows refused (the process then lives on its own, as before).
/// </summary>
bool EndWithFebe(System.Diagnostics.Process process);
}
/// <summary>
/// The Windows edition's parts of the composition (spec §12, §13.1): the interface on 127.0.0.1 with a port chosen at
/// start-up and a token of this start, the Data folder and the WebView2 runtime checked at start-up, the browser of
/// Instagram in its own window (or, for S2, as a composition visual or as Edge), and the native functions.
/// </summary>
public sealed class DesktopPlatform : IFebePlatform
{
private readonly DesktopOptions _options;
private readonly IDesktopShell _shell;
private readonly IDataFolderLocationStore _locations;
private readonly bool _dataFolderFixed;
/// <param name="options">The command line.</param>
/// <param name="shell">The Windows-only part.</param>
/// <param name="locations">Where a move of the Data folder is recorded.</param>
/// <param name="dataFolderFixed">True when the Data folder came from <c>--dati</c>: «Cambia…» is not offered.</param>
public DesktopPlatform(DesktopOptions options, IDesktopShell shell, IDataFolderLocationStore locations, bool dataFolderFixed)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
_shell = shell ?? throw new ArgumentNullException(nameof(shell));
_locations = locations ?? throw new ArgumentNullException(nameof(locations));
_dataFolderFixed = dataFolderFixed;
WebOptions = new FebeWebOptions
{
Edition = FebeEdition.Desktop,
Access = AccessMode.Token,
AccessToken = AccessToken,
AllowedHosts = FebeWebOptions.LoopbackHosts(0),
};
}
/// <summary>The token of this start: the interface window opens <c>/?gettone=…</c> once. Never logged.</summary>
public string AccessToken { get; } = Febe.Web.Security.AccessToken.Create();
public FebeWebOptions WebOptions { get; }
/// <summary>127.0.0.1 only, on a port chosen at start-up.</summary>
public FebeListen Listen => FebeListen.Loopback(0);
/// <summary>The hosting actually used (after a missing Edge fell back to the window).</summary>
public BrowserHosting? Hosting { get; private set; }
/// <summary>The address the interface window opens once: the token becomes a cookie and leaves the address.</summary>
public Uri FirstAddress(Uri address)
{
ArgumentNullException.ThrowIfNull(address);
return new Uri(address, "/?" + Febe.Web.Security.AccessToken.QueryName + "=" + Uri.EscapeDataString(AccessToken));
}
public IReadOnlyList<ConfigurationProblem> CheckConfiguration(FebeAppOptions options, DataFolderCheck dataFolderCheck)
{
ArgumentNullException.ThrowIfNull(options);
return DesktopStartupChecks.Run(options.DataFolder, _shell.WebView2Version, dataFolderCheck);
}
public async Task<IFebeBrowser> CreateBrowserAsync(FebePlatformContext context, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(context);
var settings = context.Storage.Settings;
BrowserHosting hosting;
if (_options.Hosting is { } chosen)
{
hosting = chosen;
await settings.SetAsync(BrowserHostingNames.SettingKey, BrowserHostingNames.Name(chosen), ct).ConfigureAwait(false);
}
else
{
BrowserHostingNames.TryParse(await settings.GetAsync(BrowserHostingNames.SettingKey, ct).ConfigureAwait(false), out hosting);
}
var profile = context.Data.BrowserProfile;
if (hosting == BrowserHosting.Edge)
{
if (_shell.FindEdge() is { } edge)
{
Hosting = hosting;
context.Log.Info("browser", $"Browser di Febe: Microsoft Edge avviato come processo (ripiego di S2), porta di debug {_options.EdgeDebugPort.ToString(CultureInfo.InvariantCulture)} solo su 127.0.0.1.");
return new EdgeBrowser(CreateEdge(context, edge), _shell, context);
}
context.Log.Warn("browser", "Microsoft Edge non si trova su questo computer: il browser di Febe usa la sua finestra WebView2.");
hosting = BrowserHosting.Window;
}
Hosting = hosting;
context.Log.Info("browser", $"Browser di Febe: WebView2 nella sua finestra ({BrowserHostingNames.Name(hosting)}), fuori vista quando non serve.");
return _shell.CreateWebView2Browser(
new WebView2BrowserSettings(profile, _options.BrowserWidth, _options.BrowserHeight, hosting, BrowserArguments.ForWebView2()),
context);
}
public void RegisterServices(IServiceCollection services, FebeApp app)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(app);
services.AddSingleton(_shell.Native);
services.AddSingleton<IBrowserWindow>(new DesktopBrowserWindow());
services.AddSingleton<IDataFolderChange>(new DesktopDataFolderChange(_locations, app.Options.DataFolder, _dataFolderFixed));
}
public void RegisterProblemServices(IServiceCollection services, FebeApp app)
{
ArgumentNullException.ThrowIfNull(services);
services.AddSingleton(_shell.Native);
}
public Task StoppingAsync() => Task.CompletedTask;
/// <summary>
/// Edge for the last fallback of S2: the same <see cref="ChromiumProcessHost"/> as Docker, with its fixed DevTools
/// port on 127.0.0.1, a profile of its own inside <c>Dati\browser</c> (so «Scollega» deletes both), preferences
/// with password saving and autofill off, and the switches of S2. Every Edge started is tied to the life of
/// Febe.exe (<see cref="IDesktopShell.EndWithFebe"/>): an Edge left behind by a crash would keep the port, and every
/// later start would find it «occupata».
/// </summary>
private ChromiumBrowser CreateEdge(FebePlatformContext context, string executable) => new(
new ChromiumBrowserSettings
{
ProfileDirectory = Path.Combine(context.Data.BrowserProfile, "edge"),
ProfileFolderToDelete = context.Data.BrowserProfile,
WindowWidth = _options.BrowserWidth,
WindowHeight = _options.BrowserHeight,
DebugPort = _options.EdgeDebugPort,
ExecutablePath = executable,
Display = null,
Launch = new ChromiumLaunchOptions
{
ExtraArguments = BrowserArguments.ForEdge(),
SessionCookie = _options.Site.SessionCookie,
SeedProfilePreferences = true,
ProcessStarted = process =>
{
if (!_shell.EndWithFebe(process))
{
context.Log.Warn("browser", "Windows non ha legato Edge a Febe: se Febe si chiudesse all'improvviso, Edge resterebbe aperto (chiudilo dal Gestione attività).");
}
},
},
},
context.Clock,
context.Log);
}
/// <summary>
/// The browser of Windows is the window «Browser di Febe» (spec §10.3): «Apri il browser» brings it to the front through
/// the connection (<c>IConnectionService.ShowBrowserAsync</c>, which opens the start page when it was at rest). While
/// it is on screen Alberto is driving and the engine is still; closing the window ends it, leaving a page of Febe does
/// not (issue #52).
/// </summary>
public sealed class DesktopBrowserWindow : IBrowserWindow
{
public bool IsSeparateWindow => true;
}
/// <summary>
/// Edge started as a process (the last fallback of S2): a <see cref="ChromiumBrowser"/> whose window is moved out of
/// view after every start and brought to the front when Alberto uses it. While it is in front Alberto is driving.
/// </summary>
public sealed class EdgeBrowser : IFebeBrowser
{
private readonly ChromiumBrowser _inner;
private readonly IDesktopShell _shell;
private readonly FebePlatformContext _context;
private readonly Lock _gate = new();
private IDisposable? _lease;
public EdgeBrowser(ChromiumBrowser inner, IDesktopShell shell, FebePlatformContext context)
{
_inner = inner ?? throw new ArgumentNullException(nameof(inner));
_shell = shell ?? throw new ArgumentNullException(nameof(shell));
_context = context ?? throw new ArgumentNullException(nameof(context));
_inner.Host.Connection.Reconnected += OnRestarted;
}
public ChromiumBrowser Inner => _inner;
public ICdpSession Cdp => _inner.Cdp;
public UserDrivingGate UserDriving => _inner.UserDriving;
public bool UserIsDriving => _inner.UserIsDriving;
public bool IsAvailable => _inner.IsAvailable;
public string? LastError => _inner.LastError;
public string ProfileDirectory => _inner.ProfileDirectory;
public int WindowWidth => _inner.WindowWidth;
public int WindowHeight => _inner.WindowHeight;
public async Task RunAsync(CancellationToken ct)
{
await _inner.RunAsync(ct).ConfigureAwait(false);
if (_inner.IsAvailable)
{
await MoveOutOfViewAsync(ct).ConfigureAwait(false);
}
}
public Task<NavigationResult> RestAsync(CancellationToken ct) => _inner.RestAsync(ct);
public async Task ShowToUserAsync(CancellationToken ct)
{
lock (_gate)
{
_lease ??= _inner.UserDriving.Begin();
}
_context.Tracker.MarkUsed(_context.Clock.Now);
if (_inner.Host.ProcessId is { } pid)
{
await _shell.ShowProcessWindowAsync(pid, ct).ConfigureAwait(false);
}
}
public async Task HideFromUserAsync(CancellationToken ct)
{
ReleaseLease();
await MoveOutOfViewAsync(ct).ConfigureAwait(false);
}
public Task RestartWithEmptyProfileAsync(CancellationToken ct) => _inner.RestartWithEmptyProfileAsync(ct);
public async ValueTask DisposeAsync()
{
_inner.Host.Connection.Reconnected -= OnRestarted;
ReleaseLease();
await _inner.DisposeAsync().ConfigureAwait(false);
}
private async Task MoveOutOfViewAsync(CancellationToken ct)
{
if (_inner.Host.ProcessId is { } pid)
{
await _shell.HideProcessWindowAsync(pid, ct).ConfigureAwait(false);
}
}
/// <summary>Edge restarted (it crashed, or Alberto closed its window): a new window opens on screen, it goes out of view.</summary>
private void OnRestarted(object? sender, EventArgs e)
{
ReleaseLease();
_ = Task.Run(async () =>
{
try
{
await MoveOutOfViewAsync(CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex) when (ex is InvalidOperationException or IOException)
{
_context.Log.Warn("browser", "La finestra di Edge non è andata fuori vista.", ex);
}
});
}
private void ReleaseLease()
{
IDisposable? lease;
lock (_gate)
{
lease = _lease;
_lease = null;
}
if (lease is not null)
{
lease.Dispose();
_context.Tracker.MarkUsed(_context.Clock.Now);
}
}
}