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>
252 lines
13 KiB
C#
252 lines
13 KiB
C#
using System.Net;
|
|
using System.Net.WebSockets;
|
|
using System.Text;
|
|
using Febe.Server;
|
|
using Febe.Tests.Server.Support;
|
|
using Febe.Tests.Web.Support;
|
|
using Febe.Web;
|
|
using Febe.Web.Connection;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace Febe.Tests.Server;
|
|
|
|
/// <summary>
|
|
/// <c>/api/vista</c> (PROTOCOLLO.md, spec §13.1) without a browser: session and Origin checks, frames as binary
|
|
/// messages, meta as text, input parsed and forwarded, limits, and the reasons a view ends.
|
|
/// </summary>
|
|
[TestClass]
|
|
public sealed class RemoteViewSocketTests
|
|
{
|
|
private const string Password = "la password della vista";
|
|
|
|
public TestContext TestContext { get; set; } = null!;
|
|
|
|
[TestMethod]
|
|
public async Task TheViewNeedsTheSessionAndTheOriginOfTheInterface()
|
|
{
|
|
var host = new FakeRemoteViewHost();
|
|
await using var server = await StartAsync(host);
|
|
var cookies = await LoginAsync(server);
|
|
|
|
// No session: refused before the WebSocket opens.
|
|
Assert.AreEqual(HttpStatusCode.Unauthorized, await RefusedAsync(server, null, server.Origin));
|
|
|
|
// Another page (another origin) cannot open it, even with the session cookie of Alberto's browser.
|
|
Assert.AreEqual(HttpStatusCode.Forbidden, await RefusedAsync(server, cookies, "http://pagina-di-altri.example"));
|
|
Assert.IsEmpty(host.Opened);
|
|
|
|
// The interface itself can.
|
|
using var socket = await ConnectAsync(server, cookies);
|
|
Assert.AreEqual(WebSocketState.Open, socket.State);
|
|
Assert.HasCount(1, host.Opened);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task FramesAreBinaryMetaIsTextAndGesturesComeBack()
|
|
{
|
|
var host = new FakeRemoteViewHost();
|
|
await using var server = await StartAsync(host);
|
|
var cookies = await LoginAsync(server);
|
|
using var socket = await ConnectAsync(server, cookies);
|
|
var view = host.Opened.Single();
|
|
|
|
view.Write(new RemoteViewMeta(1279, 760, "http://127.0.0.1:8481/benvenuto"));
|
|
view.Write(new RemoteViewFrame(new byte[] { 0xFF, 0xD8, 1, 2, 3, 0xFF, 0xD9 }));
|
|
var (metaType, meta) = await ReceiveAsync(socket);
|
|
Assert.AreEqual(WebSocketMessageType.Text, metaType);
|
|
Assert.AreEqual("""{"type":"meta","width":1279,"height":760,"url":"http://127.0.0.1:8481/benvenuto"}""", Encoding.UTF8.GetString(meta));
|
|
var (frameType, frame) = await ReceiveAsync(socket);
|
|
Assert.AreEqual(WebSocketMessageType.Binary, frameType);
|
|
CollectionAssert.AreEqual(new byte[] { 0xFF, 0xD8, 1, 2, 3, 0xFF, 0xD9 }, frame);
|
|
|
|
foreach (var message in new[]
|
|
{
|
|
"""{"type":"mouse","action":"down","x":0.25,"y":0.5,"button":"left","clickCount":1}""",
|
|
"""{"type":"key","action":"down","key":"a","code":"KeyA","text":"a","modifiers":0}""",
|
|
"""{"type":"key","action":"char","text":"è"}""",
|
|
"""{"type":"navigate","action":"back"}""",
|
|
"""{"type":"mouse","action":"move","x":1.5,"y":0.5}""",
|
|
"""{"type":"navigate","action":"vai","url":"https://altrove.example/"}""",
|
|
"""{"type":"script","code":"alert(1)"}""",
|
|
"non è JSON",
|
|
})
|
|
{
|
|
await socket.SendAsync(Encoding.UTF8.GetBytes(message), WebSocketMessageType.Text, true, TestContext.CancellationToken);
|
|
}
|
|
|
|
await ServerTestBed.WaitUntilAsync(() => Task.FromResult(view.Inputs.Count >= 4), TimeSpan.FromSeconds(10), "quattro gesti inoltrati");
|
|
await Task.Delay(200);
|
|
var inputs = view.Inputs.ToArray();
|
|
Assert.HasCount(4, inputs, "out-of-range, unknown and malformed messages are dropped");
|
|
var mouse = (RemoteViewMouse)inputs[0];
|
|
Assert.AreEqual(RemoteViewMouseAction.Down, mouse.Action);
|
|
Assert.AreEqual(0.25, mouse.X);
|
|
Assert.AreEqual(RemoteViewButton.Left, mouse.Button);
|
|
var key = (RemoteViewKey)inputs[1];
|
|
Assert.AreEqual(RemoteViewKeyAction.Down, key.Action);
|
|
Assert.AreEqual("a", key.Text);
|
|
Assert.AreEqual("RemoteViewKey(…)", key.ToString(), "a key never shows in a log line");
|
|
Assert.AreEqual(RemoteViewKeyAction.Char, ((RemoteViewKey)inputs[2]).Action);
|
|
Assert.AreEqual(RemoteViewNavigation.Back, inputs[3]);
|
|
|
|
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "fine", TestContext.CancellationToken);
|
|
await ServerTestBed.WaitUntilAsync(() => Task.FromResult(view.Disposed), TimeSpan.FromSeconds(10), "la vista chiusa dal server");
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task AViewOpenedElsewhereReplacesTheOldOneAndATooLongMessageClosesIt()
|
|
{
|
|
var host = new FakeRemoteViewHost();
|
|
await using var server = await StartAsync(host);
|
|
var cookies = await LoginAsync(server);
|
|
using var first = await ConnectAsync(server, cookies);
|
|
using var second = await ConnectAsync(server, cookies);
|
|
await ExpectCloseAsync(first, (WebSocketCloseStatus)RemoteViewSocket.CloseReplaced);
|
|
Assert.AreEqual(RemoteViewEnd.Replaced, host.Opened[0].Ended);
|
|
|
|
await second.SendAsync(new byte[RemoteViewSocket.MaxMessageBytes + 10], WebSocketMessageType.Text, true, TestContext.CancellationToken);
|
|
await ExpectCloseAsync(second, WebSocketCloseStatus.MessageTooBig);
|
|
await ServerTestBed.WaitUntilAsync(() => Task.FromResult(host.Opened[1].Disposed), TimeSpan.FromSeconds(10), "la vista chiusa");
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task WithoutBrowserOrOnTheDesktopThereIsNoView()
|
|
{
|
|
var host = new FakeRemoteViewHost { Unavailable = true };
|
|
await using var server = await StartAsync(host);
|
|
var cookies = await LoginAsync(server);
|
|
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, await RefusedAsync(server, cookies, server.Origin));
|
|
|
|
// A plain request is not a WebSocket.
|
|
using var client = new HttpClient(new HttpClientHandler { CookieContainer = cookies }) { BaseAddress = server.Address };
|
|
using (var plain = await client.GetAsync("/api/vista", TestContext.CancellationToken))
|
|
{
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, plain.StatusCode);
|
|
}
|
|
|
|
await using var desktop = await WebTestServer.StartAsync(new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None }, s => s.AddSingleton<IRemoteViewHost>(new FakeRemoteViewHost()));
|
|
using var response = await desktop.Client.GetAsync("/api/vista", TestContext.CancellationToken);
|
|
Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void TheServerPingsThePageAndGivesUpOnOneThatStopsAnswering()
|
|
{
|
|
// With an interval alone ASP.NET Core sends unsolicited pongs and never notices a page that vanished.
|
|
var accept = RemoteViewSocket.AcceptContext();
|
|
Assert.AreEqual(RemoteViewSocket.KeepAliveInterval, accept.KeepAliveInterval);
|
|
Assert.IsNotNull(accept.KeepAliveTimeout, "a ping must have a deadline");
|
|
Assert.IsTrue(accept.KeepAliveTimeout > TimeSpan.Zero && accept.KeepAliveTimeout <= TimeSpan.FromMinutes(1), $"{accept.KeepAliveTimeout}");
|
|
Assert.IsFalse(accept.DangerousEnableCompression);
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(30_000, CooperativeCancellation = true)]
|
|
public async Task AViewWhosePageVanishedEndsWhenItsPingGoesUnanswered()
|
|
{
|
|
// The same keep-alive as the server, with short times: the page's machine went to sleep (it never answers).
|
|
using var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);
|
|
listener.Start();
|
|
using var page = new System.Net.Sockets.TcpClient();
|
|
await page.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port, TestContext.CancellationToken);
|
|
using var accepted = await listener.AcceptTcpClientAsync(TestContext.CancellationToken);
|
|
using var socket = WebSocket.CreateFromStream(accepted.GetStream(), new WebSocketCreationOptions
|
|
{
|
|
IsServer = true,
|
|
KeepAliveInterval = TimeSpan.FromMilliseconds(200),
|
|
KeepAliveTimeout = TimeSpan.FromMilliseconds(300),
|
|
});
|
|
var view = new FakeRemoteViewConnection();
|
|
var run = RemoteViewSocket.RunAsync(socket, view, CancellationToken.None);
|
|
Assert.AreSame(run, await Task.WhenAny(run, Task.Delay(TimeSpan.FromSeconds(10), TestContext.CancellationToken)), "the view ends by itself");
|
|
await run;
|
|
}
|
|
|
|
[TestMethod]
|
|
public void KeysGetTheVirtualCodesChromiumNeeds()
|
|
{
|
|
Assert.AreEqual(65, RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "a", "KeyA", "a", 0)).KeyCode);
|
|
Assert.AreEqual(8, RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "Backspace", "Backspace", null, 0)).KeyCode);
|
|
var enter = RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "Enter", "Enter", null, 0));
|
|
Assert.AreEqual(13, enter.KeyCode);
|
|
Assert.AreEqual("\r", enter.Text, "Enter submits forms only with its text");
|
|
Assert.AreEqual(50, RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "\"", "Digit2", "\"", 8)).KeyCode, "Italian layout: Shift+2");
|
|
Assert.AreEqual(219, RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "è", "BracketLeft", "è", 0)).KeyCode, "Italian layout: è");
|
|
Assert.AreEqual("KeyStroke(…)", RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "x", "KeyX", "x", 0)).ToString());
|
|
Assert.AreEqual("http://127.0.0.1:8481/profilo/marta.prova/", BrowserRemoteViewConnection.WithoutQuery("http://127.0.0.1:8481/profilo/marta.prova/?gettone=segreto#x"));
|
|
Assert.AreEqual("about:blank", BrowserRemoteViewConnection.WithoutQuery("about:blank"));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void TheThreeButtonsOfTheBarAreNavigations()
|
|
{
|
|
static object? Parse(string json) => RemoteViewSocket.Parse(Encoding.UTF8.GetBytes(json));
|
|
|
|
Assert.AreEqual(RemoteViewNavigation.Back, Parse("""{"type":"navigate","action":"back"}"""));
|
|
Assert.AreEqual(RemoteViewNavigation.Reload, Parse("""{"type":"navigate","action":"reload"}"""));
|
|
Assert.AreEqual(RemoteViewNavigation.Home, Parse("""{"type":"navigate","action":"home"}"""), "«Pagina iniziale» (issue #52)");
|
|
Assert.IsNull(Parse("""{"type":"navigate","action":"https://example.com/"}"""), "never an address from the page");
|
|
}
|
|
|
|
private static Task<WebTestServer> StartAsync(FakeRemoteViewHost host) =>
|
|
WebTestServer.StartAsync(
|
|
new FebeWebOptions { Edition = FebeEdition.Docker, Access = AccessMode.Password, Password = Password },
|
|
s => s.AddSingleton<IRemoteViewHost>(host));
|
|
|
|
private async Task<CookieContainer> LoginAsync(WebTestServer server)
|
|
{
|
|
var cookies = new CookieContainer();
|
|
using var client = new HttpClient(new HttpClientHandler { CookieContainer = cookies, UseCookies = true }) { BaseAddress = server.Address };
|
|
using var request = server.Request(HttpMethod.Post, "/api/accesso", $$"""{"password":"{{Password}}"}""");
|
|
using var response = await client.SendAsync(request, TestContext.CancellationToken);
|
|
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
|
return cookies;
|
|
}
|
|
|
|
private async Task<ClientWebSocket> ConnectAsync(WebTestServer server, CookieContainer cookies)
|
|
{
|
|
var socket = new ClientWebSocket();
|
|
socket.Options.Cookies = cookies;
|
|
socket.Options.SetRequestHeader("Origin", server.Origin);
|
|
await socket.ConnectAsync(new UriBuilder(server.Address) { Scheme = "ws", Path = RemoteViewSocket.Path }.Uri, TestContext.CancellationToken);
|
|
return socket;
|
|
}
|
|
|
|
private async Task<HttpStatusCode?> RefusedAsync(WebTestServer server, CookieContainer? cookies, string origin)
|
|
{
|
|
using var socket = new ClientWebSocket();
|
|
socket.Options.CollectHttpResponseDetails = true;
|
|
socket.Options.SetRequestHeader("Origin", origin);
|
|
if (cookies is not null)
|
|
{
|
|
socket.Options.Cookies = cookies;
|
|
}
|
|
|
|
await Assert.ThrowsAsync<WebSocketException>(() => socket.ConnectAsync(new UriBuilder(server.Address) { Scheme = "ws", Path = RemoteViewSocket.Path }.Uri, TestContext.CancellationToken));
|
|
return socket.HttpStatusCode;
|
|
}
|
|
|
|
private async Task<(WebSocketMessageType Type, byte[] Data)> ReceiveAsync(ClientWebSocket socket)
|
|
{
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
|
var buffer = new byte[8192];
|
|
using var data = new MemoryStream();
|
|
WebSocketReceiveResult result;
|
|
do
|
|
{
|
|
result = await socket.ReceiveAsync(buffer, timeout.Token);
|
|
data.Write(buffer, 0, result.Count);
|
|
}
|
|
while (!result.EndOfMessage);
|
|
return (result.MessageType, data.ToArray());
|
|
}
|
|
|
|
private async Task ExpectCloseAsync(ClientWebSocket socket, WebSocketCloseStatus status)
|
|
{
|
|
var (type, _) = await ReceiveAsync(socket);
|
|
Assert.AreEqual(WebSocketMessageType.Close, type);
|
|
Assert.AreEqual(status, socket.CloseStatus);
|
|
}
|
|
}
|