Files
Febe/src/Febe.Browser/RemoteView/RemoteViewSession.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

266 lines
9.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Browser.Cdp;
using Febe.Browser.Diagnostics;
using Febe.Browser.Gestures;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
namespace Febe.Browser.RemoteView;
public enum RemoteMouseAction
{
Move,
Down,
Up,
Wheel,
}
public enum RemoteMouseButton
{
None,
Left,
Middle,
Right,
}
/// <summary>A mouse event from the interface's remote view.</summary>
/// <param name="Action">Move, press, release or wheel.</param>
/// <param name="X">Horizontal position: 0–1 of the frame when <paramref name="Normalized"/>, CSS pixels otherwise.</param>
/// <param name="Y">Vertical position: 0–1 of the frame when <paramref name="Normalized"/>, CSS pixels otherwise.</param>
/// <param name="Button">Button pressed or released.</param>
/// <param name="ClickCount">1 for a click, 2 for a double click.</param>
/// <param name="DeltaX">Horizontal wheel delta in CSS pixels.</param>
/// <param name="DeltaY">Vertical wheel delta in CSS pixels (positive scrolls down).</param>
/// <param name="Modifiers">Modifier keys held.</param>
/// <param name="Normalized">Whether X and Y are fractions of the frame.</param>
public sealed record RemoteMouseEvent(
RemoteMouseAction Action,
double X,
double Y,
RemoteMouseButton Button = RemoteMouseButton.None,
int ClickCount = 1,
double DeltaX = 0,
double DeltaY = 0,
KeyModifiers Modifiers = KeyModifiers.None,
bool Normalized = true);
/// <summary>A key event from the interface's remote view. Never logged or stored (spec §13.2).</summary>
public sealed record RemoteKeyEvent(bool Down, KeyStroke Key)
{
public override string ToString() => "RemoteKeyEvent(…)";
}
/// <summary>
/// The remote view used by Alberto from the interface (spec §4.1, §11, mockup 10): the screencast goes to the page,
/// mouse and keys come back to the browser through <c>Input.*</c>. While the session is active the
/// <see cref="UserDrivingGate"/> holds a lease, so the engine stays still. Keys are forwarded, never logged.
/// </summary>
public sealed class RemoteViewSession : IAsyncDisposable
{
private readonly ICdpSession _cdp;
private readonly UserDrivingGate _gate;
private readonly IBrowserLog _log;
private IDisposable? _lease;
private int _buttons;
/// <param name="cdp">The page session.</param>
/// <param name="gate">Where the «Alberto is driving» lease is taken.</param>
/// <param name="log">Where the frames' starts, restarts and silences are noted (never keys).</param>
/// <param name="clock">Wall-clock time for the screencast's start attempts; null: the system clock.</param>
public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null, IClock? clock = null)
{
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
_gate = gate ?? throw new ArgumentNullException(nameof(gate));
_log = log ?? NullBrowserLog.Instance;
Screencast = new ScreencastSession(cdp, _log, clock);
}
public ScreencastSession Screencast { get; }
public bool IsActive => _lease is not null;
/// <summary>Takes the «Alberto is driving» lease and starts the frames.</summary>
public async Task StartAsync(ScreencastOptions? options = null, CancellationToken ct = default)
{
if (_lease is not null)
{
throw new InvalidOperationException("La vista remota è già attiva.");
}
_lease = _gate.Begin();
try
{
await Screencast.StartAsync(options, ct).ConfigureAwait(false);
}
catch
{
_lease.Dispose();
_lease = null;
throw;
}
// The host notes the opening in its own words; here only for whoever uses the session alone.
_log.Debug("Vista remota aperta: il motore resta fermo finché Alberto usa il browser.");
}
public async Task MouseAsync(RemoteMouseEvent e, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(e);
EnsureActive();
var (x, y) = ToPage(e);
var button = e.Button switch
{
RemoteMouseButton.Left => "left",
RemoteMouseButton.Middle => "middle",
RemoteMouseButton.Right => "right",
_ => "none",
};
var bit = e.Button switch
{
RemoteMouseButton.Left => 1,
RemoteMouseButton.Right => 2,
RemoteMouseButton.Middle => 4,
_ => 0,
};
var parameters = new JsonObject
{
["x"] = x,
["y"] = y,
["modifiers"] = (int)e.Modifiers,
["pointerType"] = "mouse",
};
switch (e.Action)
{
case RemoteMouseAction.Move:
parameters["type"] = "mouseMoved";
parameters["button"] = "none";
parameters["buttons"] = _buttons;
break;
case RemoteMouseAction.Down:
_buttons |= bit;
parameters["type"] = "mousePressed";
parameters["button"] = button;
parameters["buttons"] = _buttons;
parameters["clickCount"] = Math.Max(1, e.ClickCount);
break;
case RemoteMouseAction.Up:
_buttons &= ~bit;
parameters["type"] = "mouseReleased";
parameters["button"] = button;
parameters["buttons"] = _buttons;
parameters["clickCount"] = Math.Max(1, e.ClickCount);
break;
case RemoteMouseAction.Wheel:
parameters["type"] = "mouseWheel";
parameters["deltaX"] = e.DeltaX;
parameters["deltaY"] = e.DeltaY;
break;
default:
throw new ArgumentOutOfRangeException(nameof(e), e.Action, null);
}
await _cdp.SendAsync("Input.dispatchMouseEvent", parameters, ct).ConfigureAwait(false);
}
public Task KeyAsync(RemoteKeyEvent e, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(e);
EnsureActive();
return e.Down ? Keyboard.KeyDownAsync(_cdp, e.Key, ct) : Keyboard.KeyUpAsync(_cdp, e.Key, ct);
}
/// <summary>Inserts composed text (a «char» event without key codes). Never logged.</summary>
public Task CharAsync(string text, CancellationToken ct = default)
{
EnsureActive();
return Keyboard.CharAsync(_cdp, text, ct);
}
/// <summary>Opens an address chosen by Alberto (e.g. the login page from the connection page).</summary>
public Task<NavigationResult> NavigateAsync(string url, CancellationToken ct = default)
{
EnsureActive();
return _cdp.NavigateAsync(url, ct);
}
/// <summary>Stops the frames and releases the lease: the engine may act again.</summary>
public async Task StopAsync(CancellationToken ct = default)
{
try
{
await Screencast.StopAsync(ct).ConfigureAwait(false);
}
finally
{
Interlocked.Exchange(ref _lease, null)?.Dispose();
_buttons = 0;
}
_log.Debug("Vista remota chiusa.");
}
public async ValueTask DisposeAsync()
{
if (_lease is not null)
{
await StopAsync().ConfigureAwait(false);
}
await Screencast.DisposeAsync().ConfigureAwait(false);
}
private (double X, double Y) ToPage(RemoteMouseEvent e)
{
if (!e.Normalized)
{
return (e.X, e.Y);
}
var frame = Screencast.LastFrame;
if (frame is null || frame.DeviceWidth <= 0 || frame.DeviceHeight <= 0)
{
throw new InvalidOperationException("Nessun fotogramma ricevuto: posizione del puntatore non calcolabile.");
}
var scale = frame.PageScaleFactor > 0 ? frame.PageScaleFactor : 1;
var x = Math.Clamp(e.X, 0, 1) * frame.DeviceWidth / scale;
var y = Math.Clamp(e.Y, 0, 1) * frame.DeviceHeight / scale;
return (Math.Round(x, 1), Math.Round(y, 1));
}
private void EnsureActive()
{
if (_lease is null)
{
throw new InvalidOperationException("La vista remota non è attiva.");
}
}
}
/// <summary>The still preview of the Activity page (mockup 06): one frame every few seconds, not a video.</summary>
public static class PagePreview
{
/// <summary>Captures the visible page as JPEG through <c>Page.captureScreenshot</c>.</summary>
public static async Task<byte[]> CaptureAsync(ICdpSession cdp, int quality = 60, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(cdp);
var result = await cdp.SendAsync(
"Page.captureScreenshot",
new JsonObject
{
["format"] = "jpeg",
["quality"] = Math.Clamp(quality, 0, 100),
["fromSurface"] = true,
["captureBeyondViewport"] = false,
},
ct).ConfigureAwait(false);
return result.TryGetProperty("data", out var data) && data.ValueKind == JsonValueKind.String
? data.GetBytesFromBase64()
: [];
}
}