M6 Windows: composizione condivisa Febe.App per Server e Desktop; Febe per Windows (WPF) con l'interfaccia in WebView2, area di notifica, istanza unica, «Browser di Febe» su WebView2 con CDP filtrato (WebView2CdpSession) e ripieghi di S2 (composizione, Edge), guscio nativo, avvisi, spostamento verificato della cartella dei dati, icona del marchio; un solo Febe.exe, installatore NSIS e zip portabile; guida docs/windows.md e prove dal vivo S1–S3

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 21:50:25 +00:00
1 parent dc4d1fc738
commit b443adfa8b
73 files changed
+7914 -699

No files matched your search

+334
View File
@@ -0,0 +1,334 @@
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, the WebView2
/// browser, Edge's window, the notifications, 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.</summary>
INativeShell Native { get; }
/// <summary>Windows notifications (balloon tips of the notification-area icon); null when there is no icon.</summary>
IAlertChannel? Notifications { 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>
/// 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(() => app.Browser));
services.AddSingleton<IDataFolderChange>(new DesktopDataFolderChange(_locations, app.Options.DataFolder, _dataFolderFixed));
if (_shell.Notifications is { } notifications)
{
services.AddSingleton(notifications);
}
}
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.
/// </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,
},
},
context.Clock,
context.Log);
}
/// <summary>
/// «Apri il browser» on Windows (spec §10.3): brings the window «Browser di Febe» to the front. While it is in front
/// Alberto is driving and the engine is still; closing the window ends it.
/// </summary>
public sealed class DesktopBrowserWindow(Func<IFebeBrowser?> browser) : IBrowserWindow
{
public bool IsSeparateWindow => true;
public async Task ShowAsync(CancellationToken ct)
{
if (browser() is not { } current)
{
throw new BadRequestException("Il browser di Febe non è in funzione in questo momento.");
}
if (!current.IsAvailable)
{
throw new BadRequestException(current.LastError is { } error
? "Il browser di Febe non è in funzione: " + error
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
}
await current.ShowToUserAsync(ct).ConfigureAwait(false);
}
}
/// <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);
}
}
}