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

@@ -0,0 +1,123 @@
using System.Net;
using System.Text;
using System.Text.Json;
using Febe.App;
using Febe.Desktop.Core;
using Febe.Tests.Support;
namespace Febe.Tests.Desktop.Support;
/// <summary>
/// The Windows composition on Linux: the shared <see cref="FebeApp"/> with the real <see cref="DesktopPlatform"/>
/// (token of this start, 127.0.0.1 on a port chosen at start-up, start-up checks, hosting of S2, native services) and
/// a fake of the Windows-only part (<see cref="FakeDesktopShell"/>). Data and library in a temporary folder; the
/// interface is asked like the main window asks it, with the token and the Origin of the interface.
/// </summary>
internal sealed class DesktopTestBed : IAsyncDisposable
{
private readonly bool _ownsTemp;
private DesktopTestBed(TempFolder temp, bool ownsTemp, FakeDesktopShell shell, MemoryLocationStore locations, DesktopPlatform platform, FebeApp app)
{
Temp = temp;
_ownsTemp = ownsTemp;
Shell = shell;
Locations = locations;
Platform = platform;
App = app;
Client = new HttpClient(new HttpClientHandler { UseCookies = false, AllowAutoRedirect = false }) { BaseAddress = app.Address, Timeout = TimeSpan.FromSeconds(30) };
}
public TempFolder Temp { get; }
public FakeDesktopShell Shell { get; }
public MemoryLocationStore Locations { get; }
public DesktopPlatform Platform { get; }
public FebeApp App { get; }
public HttpClient Client { get; }
public DesktopFolders Folders => new(Temp.Combine("AppData", "Local"), Temp.Combine("Immagini"));
/// <summary>The fake window «Browser di Febe» (null with a configuration problem or with Edge).</summary>
public FakeBrowser? Browser => App.Browser as FakeBrowser;
public string Origin => $"{App.Address.Scheme}://{App.Address.Authority}";
public static async Task<DesktopTestBed> StartAsync(string[]? args = null, FakeDesktopShell? shell = null, TempFolder? temp = null, MemoryLocationStore? locations = null)
{
var ownsTemp = temp is null;
temp ??= new TempFolder("desktop");
shell ??= new FakeDesktopShell();
locations ??= new MemoryLocationStore();
if (!DesktopCommandLine.TryParse(args ?? [], out var options, out var problem))
{
throw new ArgumentException(problem);
}
var folders = new DesktopFolders(temp.Combine("AppData", "Local"), temp.Combine("Immagini"));
var platform = new DesktopPlatform(options, shell, locations, dataFolderFixed: options.DataFolder is not null);
var app = await FebeApp.StartAsync(options.AppOptions(options.DataFolder ?? folders.DefaultDataFolder, folders), platform, new FebeAppHooks { ShutdownTimeout = TimeSpan.FromSeconds(1) });
return new DesktopTestBed(temp, ownsTemp, shell, locations, platform, app);
}
/// <summary>A request as the main window sends it: the token (here as the header the cookie stands for) and the Origin.</summary>
public async Task<HttpResponseMessage> SendAsync(HttpMethod method, string path, string? json = null, bool token = true)
{
using var request = new HttpRequestMessage(method, path);
if (token)
{
request.Headers.TryAddWithoutValidation(Febe.Web.Security.AccessToken.HeaderName, Platform.AccessToken);
}
request.Headers.TryAddWithoutValidation("Origin", Origin);
if (json is not null)
{
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
}
return await Client.SendAsync(request);
}
public async Task<JsonElement> JsonAsync(HttpMethod method, string path, string? json = null)
{
using var response = await SendAsync(method, path, json);
var text = await response.Content.ReadAsStringAsync();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
return JsonDocument.Parse(text).RootElement.Clone();
}
public static async Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout, string what)
{
var deadline = DateTime.UtcNow + timeout;
while (!condition())
{
if (DateTime.UtcNow > deadline)
{
Assert.Fail($"Tempo scaduto: {what}.");
}
await Task.Delay(50);
}
}
/// <summary>Stops the composition; the folders stay for a second start (dispose <see cref="Temp"/> at the end).</summary>
public async ValueTask StopAsync()
{
Client.Dispose();
await App.DisposeAsync();
}
/// <summary>Stops; deletes the temporary folder only when the bed created it (a shared one is the caller's).</summary>
public async ValueTask DisposeAsync()
{
await StopAsync();
if (_ownsTemp)
{
Temp.Dispose();
}
}
}
@@ -0,0 +1,261 @@
using System.Collections.Concurrent;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.App;
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Desktop.Core;
using Febe.Web.Native;
namespace Febe.Tests.Desktop.Support;
/// <summary>The Windows-only part of the desktop, faked: what the platform asks of it is recorded.</summary>
internal sealed class FakeDesktopShell : IDesktopShell
{
public FakeNativeShell NativeShell { get; } = new();
public RecordingAlertChannel Alerts { get; } = new();
public INativeShell Native => NativeShell;
public IAlertChannel? Notifications => Alerts;
/// <summary>The WebView2 runtime this «Windows» has (null: missing).</summary>
public string? RuntimeVersion { get; set; } = "141.0.3537.71";
/// <summary>Where «Edge» is (null: not installed).</summary>
public string? EdgePath { get; set; }
/// <summary>The browsers created, with the settings the platform gave them.</summary>
public ConcurrentQueue<(WebView2BrowserSettings Settings, FakeBrowser Browser)> Created { get; } = new();
public ConcurrentQueue<string> ProcessWindows { get; } = new();
public string? WebView2Version() => RuntimeVersion;
public IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context)
{
var browser = new FakeBrowser(settings.ProfileDirectory, settings.Width, settings.Height, context);
Created.Enqueue((settings, browser));
return browser;
}
public string? FindEdge() => EdgePath;
public Task ShowProcessWindowAsync(int processId, CancellationToken ct)
{
ProcessWindows.Enqueue("mostra " + processId);
return Task.CompletedTask;
}
public Task HideProcessWindowAsync(int processId, CancellationToken ct)
{
ProcessWindows.Enqueue("nascondi " + processId);
return Task.CompletedTask;
}
}
/// <summary>Folder picker, explorer, default browser, notifications and autostart, faked.</summary>
internal sealed class FakeNativeShell : INativeShell
{
public bool CanPickFolder => true;
public bool CanShowInFolder => true;
public bool CanOpenUrl => true;
public bool CanNotify => true;
public bool SupportsAutostart => true;
public bool Autostart { get; private set; }
public string? FolderToPick { get; set; }
public ConcurrentQueue<string> Shown { get; } = new();
public ConcurrentQueue<Uri> Opened { get; } = new();
public ConcurrentQueue<(string Title, string Message)> Notified { get; } = new();
public Task<string?> PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => Task.FromResult(FolderToPick);
public Task<bool> ShowInFolderAsync(string fullPath, CancellationToken ct)
{
Shown.Enqueue(fullPath);
return Task.FromResult(true);
}
public Task<bool> OpenUrlAsync(Uri address, CancellationToken ct)
{
Opened.Enqueue(address);
return Task.FromResult(true);
}
public Task NotifyAsync(string title, string message, CancellationToken ct)
{
Notified.Enqueue((title, message));
return Task.CompletedTask;
}
public Task<bool> GetAutostartAsync(CancellationToken ct) => Task.FromResult(Autostart);
public Task SetAutostartAsync(bool enabled, CancellationToken ct)
{
Autostart = enabled;
return Task.CompletedTask;
}
}
/// <summary>The Windows notifications, recorded.</summary>
internal sealed class RecordingAlertChannel : IAlertChannel
{
public ConcurrentQueue<FebeAlert> Received { get; } = new();
public bool IsEnabled(AlertSettings settings) => settings.WindowsNotifications;
public Task SendAsync(FebeAlert alert, AlertSettings settings, CancellationToken ct)
{
Received.Enqueue(alert);
return Task.CompletedTask;
}
}
/// <summary>
/// The window «Browser di Febe», faked: a CDP session that answers like a browser on a blank page, a session cookie
/// that exists once «Alberto» has logged in, and a record of every time the window came to the front or went away.
/// </summary>
internal sealed class FakeBrowser : IFebeBrowser
{
private readonly FebePlatformContext _context;
private IDisposable? _lease;
public FakeBrowser(string profileDirectory, int width, int height, FebePlatformContext context)
{
ProfileDirectory = profileDirectory;
WindowWidth = width;
WindowHeight = height;
_context = context;
}
public FakeCdp FakeCdp { get; } = new();
public ICdpSession Cdp => FakeCdp;
public UserDrivingGate UserDriving { get; } = new();
public bool UserIsDriving => UserDriving.IsDriving;
public bool IsAvailable { get; private set; }
public string? LastError => null;
public string ProfileDirectory { get; }
public int WindowWidth { get; }
public int WindowHeight { get; }
public int Shown { get; private set; }
public int Hidden { get; private set; }
public int EmptiedProfiles { get; private set; }
public bool Disposed { get; private set; }
public Task RunAsync(CancellationToken ct)
{
Directory.CreateDirectory(ProfileDirectory);
IsAvailable = true;
return Task.CompletedTask;
}
public Task<NavigationResult> RestAsync(CancellationToken ct) => FakeCdp.NavigateAsync(CdpPageExtensions.RestUrl, ct);
/// <summary>Like the real window: in front, Alberto is driving.</summary>
public Task ShowToUserAsync(CancellationToken ct)
{
Shown++;
_lease ??= UserDriving.Begin();
_context.Tracker.MarkUsed(_context.Clock.Now);
return Task.CompletedTask;
}
public Task HideFromUserAsync(CancellationToken ct)
{
Hidden++;
_lease?.Dispose();
_lease = null;
return Task.CompletedTask;
}
/// <summary>The next «Scollega» finds a file held by another process (Windows) and cannot delete the profile.</summary>
public bool ProfileLocked { get; set; }
public Task RestartWithEmptyProfileAsync(CancellationToken ct)
{
if (ProfileLocked)
{
throw new IOException("Il file Cookies è in uso da un altro processo.");
}
if (Directory.Exists(ProfileDirectory))
{
Directory.Delete(ProfileDirectory, recursive: true);
}
Directory.CreateDirectory(ProfileDirectory);
FakeCdp.LoggedIn = false;
EmptiedProfiles++;
return Task.CompletedTask;
}
public ValueTask DisposeAsync()
{
Disposed = true;
IsAvailable = false;
return ValueTask.CompletedTask;
}
}
/// <summary>A CDP session answering like a page: frame tree, navigation, the session cookie (name only).</summary>
internal sealed class FakeCdp : ICdpSession
{
public bool LoggedIn { get; set; }
public string Url { get; private set; } = "about:blank";
public ConcurrentQueue<string> Methods { get; } = new();
public Task<JsonElement> SendAsync(string method, object? parameters = null, CancellationToken ct = default)
{
CdpCommandPolicy.EnsureAllowed(method);
Methods.Enqueue(method);
JsonNode result = method switch
{
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = Url } } },
"Page.navigate" => Navigate(parameters),
"Network.getCookies" => new JsonObject { ["cookies"] = LoggedIn ? new JsonArray(new JsonObject { ["name"] = "sessionid" }) : new JsonArray() },
_ => new JsonObject(),
};
return Task.FromResult(JsonDocument.Parse(result.ToJsonString()).RootElement.Clone());
}
public IDisposable On(string eventName, Action<JsonElement> handler) => new Nothing();
private JsonObject Navigate(object? parameters)
{
Url = (parameters as JsonObject)?["url"]?.GetValue<string>() ?? Url;
return new JsonObject { ["frameId"] = "F1" };
}
private sealed class Nothing : IDisposable
{
public void Dispose()
{
}
}
}
@@ -0,0 +1,89 @@
using System.Collections.Concurrent;
using Febe.Browser.Diagnostics;
using Febe.Browser.WebView2;
namespace Febe.Tests.Desktop.Support;
/// <summary>
/// A stand-in for the two WebView2 calls (<c>CallDevToolsProtocolMethodAsync</c>, <c>GetDevToolsProtocolEventReceiver</c>):
/// records what reaches «WebView2», answers with <see cref="Answer"/>, and raises events like WebView2 does, on the
/// thread of the caller (WebView2's UI thread in the real application).
/// </summary>
internal sealed class FakeDevTools : IWebView2DevTools
{
private readonly ConcurrentDictionary<string, List<Action<string>>> _receivers = new(StringComparer.Ordinal);
/// <summary>Every call that reached «WebView2»: method and parameters as JSON.</summary>
public ConcurrentQueue<(string Method, string Json)> Calls { get; } = new();
/// <summary>The answer to a call (default: an empty result object).</summary>
public Func<string, string, Task<string>> Answer { get; set; } = (_, _) => Task.FromResult("{}");
/// <summary>How many event handlers are attached to «WebView2» right now, by event name.</summary>
public int Subscribed(string eventName) => _receivers.TryGetValue(eventName, out var list) ? list.Count : 0;
/// <summary>Total subscriptions ever made (to see re-subscriptions after a new WebView).</summary>
public int SubscriptionsMade { get; private set; }
public Task<string> CallMethodAsync(string methodName, string parametersAsJson)
{
Calls.Enqueue((methodName, parametersAsJson));
return Answer(methodName, parametersAsJson);
}
public IDisposable Subscribe(string eventName, Action<string> onEvent)
{
var list = _receivers.GetOrAdd(eventName, _ => []);
lock (list)
{
list.Add(onEvent);
}
SubscriptionsMade++;
return new Removal(() =>
{
lock (list)
{
list.Remove(onEvent);
}
});
}
/// <summary>«WebView2» receives a protocol event: <c>ParameterObjectAsJson</c> goes to the handlers.</summary>
public void Raise(string eventName, string parametersJson)
{
if (!_receivers.TryGetValue(eventName, out var list))
{
return;
}
Action<string>[] handlers;
lock (list)
{
handlers = [.. list];
}
foreach (var handler in handlers)
{
handler(parametersJson);
}
}
private sealed class Removal(Action remove) : IDisposable
{
private Action? _remove = remove;
public void Dispose() => Interlocked.Exchange(ref _remove, null)?.Invoke();
}
}
/// <summary>Collects what the browser layer logs (to prove that only names get there).</summary>
internal sealed class RecordingBrowserLog : IBrowserLog
{
public ConcurrentQueue<string> Lines { get; } = new();
public void Write(BrowserLogLevel level, string message, Exception? exception = null) =>
Lines.Enqueue($"{level} {message} {exception?.GetType().Name} {exception?.Message}");
public string All => string.Join('\n', Lines);
}
@@ -0,0 +1,15 @@
using Febe.Desktop.Core;
namespace Febe.Tests.Desktop.Support;
/// <summary>The registry values «CartellaDati» and «NuovaCartellaDati», in memory.</summary>
internal sealed class MemoryLocationStore : IDataFolderLocationStore
{
public string? Current { get; set; }
public string? Pending { get; set; }
public void SetCurrent(string? folder) => Current = folder;
public void SetPending(string? folder) => Pending = folder;
}
@@ -0,0 +1,31 @@
namespace Febe.Tests.Desktop.Support;
/// <summary>Files of the repository the desktop tests look at (the committed icon, the NSIS script).</summary>
internal static class Repository
{
/// <summary>The folder with Febe.slnx, found from the test binaries upward; null outside a checkout.</summary>
public static string? Root()
{
for (var folder = new DirectoryInfo(AppContext.BaseDirectory); folder is not null; folder = folder.Parent)
{
if (File.Exists(Path.Combine(folder.FullName, "Febe.slnx")))
{
return folder.FullName;
}
}
return null;
}
/// <summary>A file of the repository; the test is inconclusive when the checkout is not there.</summary>
public static string PathOf(params string[] parts)
{
var root = Root();
if (root is null)
{
Assert.Inconclusive("Il repository non è accanto alle prove.");
}
return Path.Combine([root, .. parts]);
}
}