Browser vuoto: correzioni dopo la revisione (#52)

La revisione di c49df4c ha trovato alcuni punti deboli. Si correggono qui.

- Fuori vista la pagina torna al 100%. Lo zoom calcolato per uno schermo
  piccolo restava anche per le sessioni del motore, e le pagine vedevano un
  devicePixelRatio diverso (regola 4). Il rapporto si ricalcola solo quando
  la finestra viene sullo schermo.
- Pulsante nella barra delle applicazioni. WPF lo cambia nascondendo la
  finestra e mostrandola di nuovo (verificato con un aggancio a
  WM_WINDOWPOSCHANGED). Ora il pulsante cambia solo mentre la finestra è
  fuori vista. Sullo schermo la finestra chiede di ridisegnarsi
  (RedrawWindow), senza nulla che la pagina veda. Una prova con WebView2
  vero controlla che la finestra non si nasconda mai sullo schermo.
- Ridotta a icona troppo a lungo, la finestra si ripristina coperta (DWM) e
  senza prendere il fuoco, e si sposta fuori vista prima di scoprirsi. Prima
  ricompariva per un attimo dove stava. Spostare la posizione di ripristino
  non basta: Windows la riporta su uno schermo (provato).
- Dopo un riavvio del processo GPU i bordi della pagina cambiano davvero: un
  pixel in meno, poi quelli veri. Gli stessi bordi di nuovo potevano non
  servire a nulla.
- «Pagina iniziale», sulla barra di Windows e nella vista remota, passa da
  BrowserConnectionService.OpenStartPageAsync. Aspetta la fine della
  sessione del motore e il turno della pagina, come l'apertura dal riposo,
  e agisce solo mentre Alberto guida.
- Vista remota.
  - Dopo un riavvio dei fotogrammi la vista aspetta il primo fotogramma per
    mezzo secondo prima dell'immagine ferma: Chromium lo manda solo dopo la
    risposta allo start, e prima quasi ogni riavvio costava una cattura.
  - L'immagine ferma si scarta se nel frattempo arriva un fotogramma vero.
  - Il silenzio si conta dall'avvio.
  - Un riavvio del browser durante la chiusura non lascia eccezioni non
    osservate.
- Un POST vuoto senza Content-Length (a pezzi, HTTP/2) non dà più 400 su
  begin, cancel e browser/show (ApiHttp.OptionalBodyAsync).
- La pagina Browser toglie ?accesso=1 dall'indirizzo. Ricaricarla riapriva
  la pagina di accesso.
- RemoteViewFramesTests aspetta fino a 20 s invece di 5. Controlla che
  l'immagine arrivi, non quanto in fretta; il tempo va nell'uscita della
  prova.

Aggiornati PROTOCOLLO.md, la guida (Primo collegamento, Installazione
Windows) e docs/decisioni.md con le righe di #52.

Prove nuove:
- AFrameSoonAfterARestartNeedsNoStillPicture
- PaginaInizialeWaitsForThePageTurnAndActsOnlyWhileAlbertoIsAtTheBrowser
- ABodyWithoutALengthIsReadAndAnEmptyOneIsNoBody
- nella prova della finestra vera: nessun nascondere sullo schermo e pagina
  al 100% fuori vista

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-16 13:28:08 +01:00
1 parent c49df4ca7b
commit 654076d280
25 files changed
+505 -86

No files matched your search

@@ -8,12 +8,17 @@ namespace Febe.Tests.Browser;
/// <summary>
/// The remote view that stayed white (Gitea issue #52), on a real Chromium on Xvfb and the local test site: a page that
/// does not move still shows itself, and the frames keep coming when the page changes renderer (another site, the rest
/// page and back). Only in the Linux CI; never Instagram.
/// page and back). Only in the Linux CI; never Instagram. The tests ask that a picture arrives, not how fast: the waits are
/// generous for a busy runner (issue #46), and the time it took goes to the test's output (about two seconds, the
/// watchdog's silence, at most five on a calm machine).
/// </summary>
[TestClass]
[DoNotParallelize]
public sealed class RemoteViewFramesTests
{
/// <summary>How long a picture may take on a busy runner before the view counts as white.</summary>
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(20);
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
@@ -27,7 +32,7 @@ public sealed class RemoteViewFramesTests
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task AStillPageAndTheRestPageShowAPictureWithinFiveSeconds()
public async Task AStillPageAndTheRestPageShowAPicture()
{
var ct = TestContext.CancellationToken;
await using var browser = await RealBrowser.StartAsync();
@@ -40,12 +45,16 @@ public sealed class RemoteViewFramesTests
try
{
await view.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900, Watchdog: ScreencastWatchdog.Default), ct);
Assert.IsTrue(await PictureAfterAsync(view.Screencast, null, TimeSpan.FromSeconds(5), ct), "a picture of the login page");
var watch = Stopwatch.StartNew();
Assert.IsTrue(await PictureAfterAsync(view.Screencast, null, Patience, ct), "a picture of the login page");
TestContext.WriteLine($"pagina di accesso: immagine dopo {watch.ElapsedMilliseconds} ms.");
var last = view.Screencast.LastFrame;
var rest = await cdp.RestAsync(ct);
Assert.IsTrue(rest.Succeeded, rest.ErrorText);
Assert.IsTrue(await PictureAfterAsync(view.Screencast, last, TimeSpan.FromSeconds(5), ct), "a picture of the rest page too");
watch.Restart();
Assert.IsTrue(await PictureAfterAsync(view.Screencast, last, Patience, ct), "a picture of the rest page too");
TestContext.WriteLine($"pagina di riposo: immagine dopo {watch.ElapsedMilliseconds} ms, riavvii {view.Screencast.Restarts}.");
}
finally
{
@@ -82,7 +91,7 @@ public sealed class RemoteViewFramesTests
Assert.IsTrue(navigated.Succeeded, $"{address}: {navigated.ErrorText}");
var shown = moving
? await FramesAfterAsync(view.Screencast, ct)
: await PictureAfterAsync(view.Screencast, last, TimeSpan.FromSeconds(5), ct);
: await PictureAfterAsync(view.Screencast, last, Patience, ct);
TestContext.WriteLine($"{address}: {(shown ? "immagini" : "niente")} dopo {watch.ElapsedMilliseconds} ms, riavvii {view.Screencast.Restarts}.");
Assert.IsTrue(shown, $"{address}: the view is not white");
}
@@ -110,12 +119,12 @@ public sealed class RemoteViewFramesTests
return false;
}
/// <summary>A few real frames of the screencast (not still pictures) after now, within ten seconds.</summary>
/// <summary>A few real frames of the screencast (not still pictures) after now, within <see cref="Patience"/>.</summary>
private static async Task<bool> FramesAfterAsync(ScreencastSession screencast, CancellationToken ct)
{
var before = screencast.FramesReceived;
var deadline = Stopwatch.StartNew();
while (deadline.Elapsed < TimeSpan.FromSeconds(10))
while (deadline.Elapsed < Patience)
{
if (screencast.FramesReceived >= before + 3)
{
@@ -61,7 +61,8 @@ public sealed class ScreencastWatchdogTests
await using var bed = new Bed(screenshot: Jpeg(800, 600));
await bed.StartAsync(ct);
await bed.StepAsync(TimeSpan.FromSeconds(2.25), ct);
// The restart after two seconds, then its wait for a first frame.
await bed.StepAsync(TimeSpan.FromSeconds(2.25) + ScreencastWatchdog.FirstFrameWait, ct);
var still = bed.Session.LastFrame;
Assert.IsNotNull(still, "something to show");
@@ -80,6 +81,25 @@ public sealed class ScreencastWatchdogTests
}
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task AFrameSoonAfterARestartNeedsNoStillPicture()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(screenshot: Jpeg(800, 600));
await bed.StartAsync(ct);
// Restarted after two seconds: Chromium answers the start first and sends its frame a moment later.
await bed.StepAsync(TimeSpan.FromSeconds(2.25), ct);
Assert.AreEqual(1, bed.Session.Restarts);
bed.Frame();
await bed.StepAsync(TimeSpan.FromSeconds(1), ct);
Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.captureScreenshot"), "the frame came: no picture taken. " + string.Join(", ", bed.Cdp.Sent.Where(c => c.Method != "Page.screencastFrameAck").Select(c => $"{c.Method}@{c.At:ss.fff}")) + " | " + bed.AllLines);
Assert.IsNotNull(bed.Session.LastFrame);
Assert.IsFalse(bed.Session.LastFrame.Still);
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task ANewDocumentLoadedWithoutFramesStartsThemAgainAtTheNextLook()
@@ -178,6 +178,35 @@ public sealed class BrowserStartPageTests
}
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task PaginaInizialeWaitsForThePageTurnAndActsOnlyWhileAlbertoIsAtTheBrowser()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
var connection = bed.App.Connection!;
// Nobody at the browser: the page is the engine's, the button does nothing.
var navigations = Navigations(browser);
await connection.OpenStartPageAsync(ct);
Assert.AreEqual(navigations, Navigations(browser));
// At the browser, on a page of his: the start page — but only once a step of the profile search let go of the page.
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
var turns = bed.App.Engine!.Services.PageTurns;
var turn = await turns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct);
var home = connection.OpenStartPageAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => turns.IsWaiting(Febe.Core.Engine.PageUser.Engine), TimeSpan.FromSeconds(10), "«Pagina iniziale» in attesa del turno della pagina");
Assert.IsFalse(home.IsCompleted, "the search step still has the page");
Assert.AreEqual("https://www.instagram.com/marta.prova/", browser.FakeCdp.Url);
turn.Dispose();
await home.WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.AreEqual(Login, browser.FakeCdp.Url, "not connected: the login page");
}
private static int Navigations(FakeBrowser browser) => browser.FakeCdp.Methods.Count(m => m == "Page.navigate");
private static async Task BeginAsync(DesktopTestBed bed, bool openLogin)
@@ -229,7 +229,10 @@ public sealed class RemoteViewStartTests
private int _starts;
/// <param name="startFailure">For the n-th start (from 1), the exception the browser answers with; null: started.</param>
/// <param name="startPage">Where «Pagina iniziale» goes; null: nowhere.</param>
/// <param name="startPage">
/// Where «Pagina iniziale» goes, as the connection would open it (BrowserConnectionService.OpenStartPageAsync,
/// tested in BrowserStartPageTests); null: nowhere.
/// </param>
public Bed(Func<int, Exception?> startFailure, Func<string>? startPage = null)
{
Clock = new VirtualClock();
@@ -256,7 +259,7 @@ public sealed class RemoteViewStartTests
};
Browser = new PageBrowser(Cdp);
_log = new FebeLog(null, null, Clock);
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, startPage: startPage)
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, openStartPage: startPage is null ? null : async ct => await Cdp.NavigateAsync(startPage(), ct))
{
// The virtual clock moves only in the pauses: a watchdog on it would never wait.
Watchdog = null,
@@ -94,6 +94,34 @@ public sealed class ConnectionApiTests
CollectionAssert.AreEqual(new[] { "release", "cancel", "show:False", "show:True" }, windows.Calls);
}
[TestMethod]
public async Task ABodyWithoutALengthIsReadAndAnEmptyOneIsNoBody()
{
// Chunked, as a body without Content-Length may come (HTTP/2 too): empty is the default, not a 400.
var windows = new RecordingConnection();
await using var server = await Part2.StartAsync(services: s => s
.AddSingleton<IConnectionService>(windows)
.AddSingleton<Febe.Web.Native.IBrowserWindow>(new SeparateWindow()));
foreach (var (path, body) in new[]
{
("/api/connection/begin", ""),
("/api/connection/cancel", ""),
("/api/browser/show", ""),
("/api/connection/cancel", """{"pageLeft":true}"""),
("/api/browser/show", """{"openLogin":true}"""),
})
{
using var request = server.Request(HttpMethod.Post, path);
request.Content = new StreamContent(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(body)));
request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
request.Headers.TransferEncodingChunked = true;
using var response = await server.Client.SendAsync(request);
Assert.IsTrue(response.IsSuccessStatusCode, $"{path} «{body}»: {(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
}
CollectionAssert.AreEqual(new[] { "begin:False", "cancel", "show:False", "release", "show:True" }, windows.Calls);
}
[TestMethod]
public async Task CommandsFromAnotherPageAreRefused()
{