Files
Febe/src/Febe.Server/BrowserRemoteView.cs
T
Alby96andClaude Opus 5.5 2bbad2e9b7 «Pagina iniziale» solo finché Alberto guida, e la vista che non si blocca (#52)
Una verifica indipendente di 654076d ha trovato tre punti deboli.

- «Pagina iniziale» guardava il permesso di guida una volta sola, prima di
  aspettare fino a 15 s la fine della sessione e 15 s il turno della pagina
  (che poi prendeva comunque). Se nel frattempo Alberto chiudeva la finestra,
  Febe navigava senza permesso e fuori dal Governatore (regole 7 e 8). Ora la
  pressione vale finché dura il permesso di chi l'ha premuta: la finestra di
  Windows passa un gettone che si annulla con il suo permesso, la vista remota
  quello della propria vita. Con il turno della pagina in mano la connessione
  guarda di nuovo che Alberto guidi ancora; senza turno rinuncia invece di
  prendere la pagina a un passo della ricerca. L'attesa del turno è
  BrowserConnectionService.PageTurnWait (15 s, le prove la accorciano).
- Nella vista remota «Pagina iniziale» aspettava dentro il ciclo di ricezione:
  la vista restava ferma fino a mezzo minuto e poi riversava clic e tasti sulla
  pagina nuova. Ora la pressione corre a parte, una per volta, e intanto clic,
  tasti, «Indietro» e «Ricarica» si scartano.
- Repaint chiedeva un ridisegno sincrono (RDW_UPDATENOW) a finestre figlie del
  processo del browser di WebView2: uno bloccato avrebbe fermato il thread
  dell'interfaccia. Ora si chiede solo di ridisegnare.

Prove nuove, che senza le correzioni non passano: la pressione dimenticata se
Alberto lascia il browser, quella che finisce con il permesso di chi l'ha
premuta, la pagina mai tolta a un passo della ricerca, la vista che non si
blocca e scarta l'input; su Windows con WebView2 vero, il gettone che si
annulla quando la finestra si chiude. PROTOCOLLO.md, la guida e decisioni.md
dicono il comportamento nuovo.

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

619 lines
22 KiB
C#

using System.Runtime.CompilerServices;
using System.Text.Json;
using Febe.App;
using Febe.Browser.Cdp;
using Febe.Browser.Diagnostics;
using Febe.Browser.Gestures;
using Febe.Browser.RemoteView;
using Febe.Core.Abstractions;
using Febe.Web.Connection;
using Febe.Web.Engine;
namespace Febe.Server;
/// <summary>
/// The remote view over the real Chromium (spec §4.1, §11, PROTOCOLLO.md): a <see cref="RemoteViewSession"/> per open
/// view, which holds the «Alberto is driving» lease while it is open, so the engine is still. One view at a time: a
/// view opened in another tab replaces the older one, also when two open at the same moment (opening is serialized, so
/// the older view is always ended — and its screencast stopped — before the newer one starts). Keys go to the browser
/// and nowhere else.
/// </summary>
internal sealed class BrowserRemoteViewHost : IRemoteViewHost
{
private readonly IFebeBrowser _browser;
private readonly BrowserUseTracker _tracker;
private readonly IClock _clock;
private readonly IClock _browserClock;
private readonly FebeLog _log;
private readonly Func<CancellationToken, Task>? _openStartPage;
private readonly Lock _gate = new();
private readonly SemaphoreSlim _opening = new(1, 1);
private BrowserRemoteViewConnection? _current;
private bool _shuttingDown;
/// <param name="browser">The browser shown.</param>
/// <param name="tracker">Notes when Alberto last used the browser.</param>
/// <param name="clock">The composition's clock (the time of that note).</param>
/// <param name="log">Febe's log.</param>
/// <param name="browserClock">
/// Time for the waits on the browser itself and for the frames' watchdog; null: the wall clock, because the browser
/// commits a navigation and paints in real time whatever clock the engine runs on (the tests compress it).
/// </param>
/// <param name="openStartPage">
/// What «Pagina iniziale» does (issue #52): the connection opens the start page once the engine's session ended and
/// with the page's turn; null: the button does nothing.
/// </param>
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func<CancellationToken, Task>? openStartPage = null)
{
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_log = log ?? throw new ArgumentNullException(nameof(log));
_browserClock = browserClock ?? new SystemClock(clock.LocalZone);
_openStartPage = openStartPage;
}
/// <summary>
/// How an open view notices that frames stopped coming and starts them again (issue #52); null: never (tests whose
/// clock moves only when asked).
/// </summary>
public ScreencastWatchdog? Watchdog { get; set; } = ScreencastWatchdog.Default;
public async Task<IRemoteViewConnection> OpenAsync(CancellationToken ct)
{
if (!_browser.IsAvailable)
{
throw new RemoteViewUnavailableException(_browser.LastError is { } error
? "Il browser di Febe non è in funzione: " + error
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
}
// From the look at the current view to the new one in its place, one opening at a time: two views opened at once
// would both start and the later assignment would orphan the other (still holding its lease, and stopping the
// shared screencast when it closes).
await _opening.WaitAsync(ct).ConfigureAwait(false);
IDisposable? handover = null;
try
{
BrowserRemoteViewConnection? previous;
lock (_gate)
{
if (_shuttingDown)
{
throw new RemoteViewUnavailableException("Febe si sta fermando.");
}
previous = _current;
_current = null;
}
if (previous is not null)
{
// Alberto is still at the browser while one view takes the place of the other: without this lease the
// engine would see nobody driving for a moment and put the page back to rest (a navigation under the new
// view's start) or even begin a session.
handover = _browser.UserDriving.Begin();
await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false);
}
var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock, _log.ForBrowser("vista"), _openStartPage, Watchdog);
try
{
await connection.StartAsync(_browser.WindowWidth, _browser.WindowHeight, ct).ConfigureAwait(false);
}
catch (Exception ex)
{
// Whatever went wrong (the page gone away, an unexpected frame tree), nothing of the view stays behind:
// no lease, no screencast, no subscription.
await connection.DisposeAsync().ConfigureAwait(false);
if (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
throw new RemoteViewUnavailableException("Il browser di Febe non risponde: riprova fra qualche secondo.", ex);
}
throw;
}
bool stopping;
lock (_gate)
{
stopping = _shuttingDown;
if (!stopping)
{
_current = connection;
}
}
if (stopping)
{
await connection.EndAsync(RemoteViewEnd.ShuttingDown).ConfigureAwait(false);
throw new RemoteViewUnavailableException("Febe si sta fermando.");
}
_log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
return connection;
}
finally
{
// The new view holds its own lease by now; if it did not start, nobody is at the browser any more.
handover?.Dispose();
_opening.Release();
}
}
/// <summary>Febe is stopping: the open view is closed with a reason the page can show.</summary>
public async Task ShutdownAsync()
{
BrowserRemoteViewConnection? current;
lock (_gate)
{
_shuttingDown = true;
current = _current;
_current = null;
}
if (current is not null)
{
await current.EndAsync(RemoteViewEnd.ShuttingDown).ConfigureAwait(false);
}
}
internal void Closed(BrowserRemoteViewConnection connection)
{
lock (_gate)
{
if (ReferenceEquals(_current, connection))
{
_current = null;
}
}
_log.Info("vista", "Vista remota chiusa.");
}
}
/// <summary>One open remote view on the real browser.</summary>
internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
{
private readonly BrowserRemoteViewHost _owner;
private readonly IFebeBrowser _browser;
private readonly BrowserUseTracker _tracker;
private readonly IClock _clock;
private readonly RemoteViewSession _session;
private readonly Func<CancellationToken, Task>? _openStartPage;
private readonly ScreencastWatchdog? _watchdog;
private readonly IBrowserLog _log;
private readonly Lock _gate = new();
private readonly Queue<RemoteViewMeta> _meta = new();
private readonly SemaphoreSlim _signal = new(0, int.MaxValue);
private readonly CancellationTokenSource _ended = new();
private readonly List<IDisposable> _subscriptions = [];
// Full addresses of this view, for «back»: kept in memory only, never logged and never sent (the page gets them
// without query string).
private readonly List<string> _history = [];
private ScreencastFrame? _pendingFrame;
private string? _mainFrameId;
private string _url = "about:blank";
private int _width;
private int _height;
private int _disposed;
private bool _used;
private int _startPagePending;
private Task _startPage = Task.CompletedTask;
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock, IBrowserLog log, Func<CancellationToken, Task>? openStartPage, ScreencastWatchdog? watchdog)
{
_owner = owner;
_browser = browser;
_tracker = tracker;
_clock = clock;
_openStartPage = openStartPage;
_watchdog = watchdog;
_log = log;
// A real log (issue #52): the starts, restarts and silences of the frames reach the registro.
_session = new RemoteViewSession(browser.Cdp, browser.UserDriving, log, browserClock);
}
public RemoteViewEnd? Ended { get; private set; }
private ICdpSession Cdp => _browser.Cdp;
/// <summary>True while a «Pagina iniziale» waits or loads: the input of the view is dropped meanwhile.</summary>
internal bool StartPagePending => Volatile.Read(ref _startPagePending) != 0;
/// <summary>The last «Pagina iniziale» of this view (a completed task before the first): tests wait on it.</summary>
internal Task StartPageOpening
{
get
{
lock (_gate)
{
return _startPage;
}
}
}
public async Task StartAsync(int width, int height, CancellationToken ct)
{
_width = width;
_height = height;
_subscriptions.Add(Cdp.On("Page.frameNavigated", OnFrameNavigated));
_subscriptions.Add(Cdp.On("Page.navigatedWithinDocument", OnNavigatedWithinDocument));
var tree = await Cdp.SendAsync("Page.getFrameTree", null, ct).ConfigureAwait(false);
var frame = tree.GetProperty("frameTree").GetProperty("frame");
_mainFrameId = frame.GetProperty("id").GetString();
var url = frame.TryGetProperty("url", out var u) ? u.GetString() ?? string.Empty : string.Empty;
lock (_gate)
{
_history.Add(url);
_url = WithoutQuery(url);
_meta.Enqueue(new RemoteViewMeta(_width, _height, _url));
}
_signal.Release();
_session.Screencast.FrameReceived += OnFrame;
await _session.StartAsync(new ScreencastOptions(Quality: 70, MaxWidth: width, MaxHeight: height, Watchdog: _watchdog), ct).ConfigureAwait(false);
}
public async IAsyncEnumerable<RemoteViewOutput> ReadAsync([EnumeratorCancellation] CancellationToken ct)
{
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _ended.Token);
while (true)
{
try
{
await _signal.WaitAsync(linked.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
yield break;
}
RemoteViewMeta? meta = null;
ScreencastFrame? frame = null;
lock (_gate)
{
if (_meta.Count > 0)
{
meta = _meta.Dequeue();
}
else
{
frame = _pendingFrame;
_pendingFrame = null;
}
}
if (meta is not null)
{
yield return meta;
}
else if (frame is not null)
{
yield return new RemoteViewFrame(frame.Jpeg);
}
}
}
public Task MouseAsync(RemoteViewMouse input, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(input);
if (_session.Screencast.LastFrame is null || StartPagePending)
{
// No frame yet: nothing on screen to point at. «Pagina iniziale» in progress: a click would land on the page
// about to go, or on the start page while it loads.
return Task.CompletedTask;
}
MarkUsed();
var action = input.Action switch
{
RemoteViewMouseAction.Down => RemoteMouseAction.Down,
RemoteViewMouseAction.Up => RemoteMouseAction.Up,
RemoteViewMouseAction.Wheel => RemoteMouseAction.Wheel,
_ => RemoteMouseAction.Move,
};
var button = input.Button switch
{
RemoteViewButton.Left => RemoteMouseButton.Left,
RemoteViewButton.Middle => RemoteMouseButton.Middle,
RemoteViewButton.Right => RemoteMouseButton.Right,
_ => RemoteMouseButton.None,
};
return _session.MouseAsync(new RemoteMouseEvent(action, input.X, input.Y, button, input.ClickCount, input.DeltaX, input.DeltaY), ct);
}
public Task KeyAsync(RemoteViewKey input, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(input);
if (StartPagePending)
{
return Task.CompletedTask; // as for the mouse: not typed into a page about to change
}
MarkUsed();
if (input.Action == RemoteViewKeyAction.Char)
{
return _session.CharAsync(input.Text!, ct);
}
return _session.KeyAsync(new RemoteKeyEvent(input.Action == RemoteViewKeyAction.Down, RemoteKeys.ToStroke(input)), ct);
}
public async Task NavigateAsync(RemoteViewNavigation action, CancellationToken ct)
{
MarkUsed();
if (action == RemoteViewNavigation.Home)
{
OpenStartPage();
return;
}
if (StartPagePending)
{
return; // the start page is about to replace the page anyway
}
string? target;
lock (_gate)
{
if (action == RemoteViewNavigation.Back)
{
// Back never lands on the empty rest page (issue #52): it skips it, and with nothing before it stays.
var previous = _history.Count - 2;
while (previous >= 0 && IsRest(_history[previous]))
{
previous--;
}
if (previous < 0)
{
return;
}
_history.RemoveRange(previous + 1, _history.Count - previous - 1);
target = _history[^1];
}
else
{
target = _history.Count > 0 ? _history[^1] : null;
}
}
if (string.IsNullOrEmpty(target))
{
return;
}
// Alberto's own navigation while he drives (rule 7): not an engine action, no Governor.
await _session.NavigateAsync(target, ct).ConfigureAwait(false);
}
/// <summary>
/// «Pagina iniziale»: Alberto's own navigation (rule 7), done by the connection — like the start page opened from the
/// rest page, it waits for the engine's session to end and takes the page's turn first, up to half a minute. So it runs
/// beside the view, not in its receive loop (the view would freeze meanwhile), for as long as the view and its lease
/// last; one at a time, and until it is done the view's input is dropped.
/// </summary>
private void OpenStartPage()
{
if (_openStartPage is not { } open || Interlocked.CompareExchange(ref _startPagePending, 1, 0) != 0)
{
return;
}
var task = Task.Run(() => OpenStartPageAsync(open), CancellationToken.None);
lock (_gate)
{
_startPage = task;
}
}
private async Task OpenStartPageAsync(Func<CancellationToken, Task> open)
{
try
{
await open(_ended.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (_ended.IsCancellationRequested)
{
// The view closed first: its lease is gone, the page is the engine's.
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log.Write(BrowserLogLevel.Warning, $"«Pagina iniziale» non aperta ({ex.GetType().Name}).");
}
finally
{
Volatile.Write(ref _startPagePending, 0);
}
}
/// <summary>Ends the view from the server side (another tab, shutdown): the page is told why.</summary>
public async Task EndAsync(RemoteViewEnd reason)
{
Ended ??= reason;
await DisposeAsync().ConfigureAwait(false);
}
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1)
{
return;
}
Ended ??= RemoteViewEnd.BrowserStopped;
await _ended.CancelAsync().ConfigureAwait(false);
_session.Screencast.FrameReceived -= OnFrame;
foreach (var subscription in _subscriptions)
{
subscription.Dispose();
}
try
{
await _session.DisposeAsync().ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or OperationCanceledException)
{
// The browser is gone: the lease is released anyway.
}
_owner.Closed(this);
}
private void MarkUsed()
{
if (!_used)
{
_used = true;
_tracker.MarkUsed(_clock.Now);
}
}
private void OnFrame(object? sender, ScreencastFrame frame)
{
var width = (int)Math.Round(frame.DeviceWidth);
var height = (int)Math.Round(frame.DeviceHeight);
lock (_gate)
{
if (width > 0 && height > 0 && (width != _width || height != _height))
{
_width = width;
_height = height;
_meta.Enqueue(new RemoteViewMeta(width, height, _url));
_signal.Release();
}
var hadPending = _pendingFrame is not null;
_pendingFrame = frame;
if (hadPending)
{
return; // the older frame is replaced: the reader is behind
}
}
_signal.Release();
}
private void OnFrameNavigated(JsonElement e)
{
if (!e.TryGetProperty("frame", out var frame) || frame.TryGetProperty("parentId", out _))
{
return;
}
if (frame.TryGetProperty("id", out var id) && id.GetString() is { } frameId)
{
_mainFrameId = frameId; // a new main frame after a browser restart
}
Navigated(frame.TryGetProperty("url", out var u) ? u.GetString() : null);
}
private void OnNavigatedWithinDocument(JsonElement e)
{
if (e.TryGetProperty("frameId", out var id) && id.GetString() is { } frameId && frameId == _mainFrameId)
{
Navigated(e.TryGetProperty("url", out var u) ? u.GetString() : null);
}
}
private void Navigated(string? url)
{
if (string.IsNullOrEmpty(url))
{
return;
}
lock (_gate)
{
if (_history.Count == 0 || _history[^1] != url)
{
_history.Add(url);
if (_history.Count > 50)
{
_history.RemoveAt(0);
}
}
var shown = WithoutQuery(url);
if (shown == _url)
{
return;
}
_url = shown;
_meta.Enqueue(new RemoteViewMeta(_width, _height, shown));
}
_signal.Release();
}
/// <summary>The address without query string or fragment (they may carry tokens).</summary>
internal static string WithoutQuery(string url) => Addresses.WithoutQuery(url);
private static bool IsRest(string url) => url is "" or CdpPageExtensions.RestUrl;
}
/// <summary>Turns the DOM key of the page into what <c>Input.dispatchKeyEvent</c> needs (virtual key codes).</summary>
internal static class RemoteKeys
{
private static readonly Dictionary<string, int> Named = new(StringComparer.Ordinal)
{
["Backspace"] = 8, ["Tab"] = 9, ["Enter"] = 13, ["Shift"] = 16, ["Control"] = 17, ["Alt"] = 18, ["Pause"] = 19,
["CapsLock"] = 20, ["Escape"] = 27, [" "] = 32, ["PageUp"] = 33, ["PageDown"] = 34, ["End"] = 35, ["Home"] = 36,
["ArrowLeft"] = 37, ["ArrowUp"] = 38, ["ArrowRight"] = 39, ["ArrowDown"] = 40, ["Insert"] = 45, ["Delete"] = 46,
["Meta"] = 91, ["ContextMenu"] = 93,
};
private static readonly Dictionary<string, int> Codes = new(StringComparer.Ordinal)
{
["Space"] = 32, ["Semicolon"] = 186, ["Equal"] = 187, ["Comma"] = 188, ["Minus"] = 189, ["Period"] = 190,
["Slash"] = 191, ["Backquote"] = 192, ["BracketLeft"] = 219, ["Backslash"] = 220, ["BracketRight"] = 221,
["Quote"] = 222, ["IntlBackslash"] = 226, ["NumpadEnter"] = 13,
};
public static KeyStroke ToStroke(RemoteViewKey key)
{
ArgumentNullException.ThrowIfNull(key);
var code = key.Code;
var keyCode = 0;
if (Named.TryGetValue(key.Key, out var named))
{
keyCode = named;
}
else if (code.Length == 4 && code.StartsWith("Key", StringComparison.Ordinal) && code[3] is >= 'A' and <= 'Z')
{
keyCode = code[3];
}
else if (code.Length == 6 && code.StartsWith("Digit", StringComparison.Ordinal) && code[5] is >= '0' and <= '9')
{
keyCode = code[5];
}
else if (code.Length == 7 && code.StartsWith("Numpad", StringComparison.Ordinal) && code[6] is >= '0' and <= '9')
{
keyCode = 96 + (code[6] - '0');
}
else if (code.Length is 2 or 3 && code[0] == 'F' && int.TryParse(code.AsSpan(1), out var f) && f is >= 1 and <= 12)
{
keyCode = 111 + f;
}
else if (Codes.TryGetValue(code, out var byCode))
{
keyCode = byCode;
}
else if (key.Key.Length == 1 && char.ToUpperInvariant(key.Key[0]) is var c && c is >= 'A' and <= 'Z' or >= '0' and <= '9')
{
keyCode = c;
}
// Enter must carry its text, or forms are not submitted.
var text = key.Text ?? (key.Key == "Enter" ? "\r" : null);
return new KeyStroke(key.Key, code, keyCode, (KeyModifiers)(key.Modifiers & 15), text);
}
}