Files
Febe/tests/Febe.Tests/Browser/RemoteViewDuringNavigationTests.cs
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

131 lines
6.3 KiB
C#

using System.Collections.Concurrent;
using System.Diagnostics;
using Febe.Browser.Cdp;
using Febe.Browser.Diagnostics;
using Febe.Browser.RemoteView;
using Febe.Tests.Browser.TestSupport;
namespace Febe.Tests.Browser;
/// <summary>
/// The remote view started while the page is between two documents (Gitea issue #3), on a real Chromium on Xvfb and the
/// local test site. From <c>ReadyToCommitNavigation</c> of a navigation in a new RenderFrameHost until its commit,
/// DevTools points at the new, not yet active document and Chromium refuses <c>Page.startScreencast</c> with -32000
/// «Not attached to an active page». That moment lasts milliseconds in real use; here a page keeps its renderer busy, so
/// a navigation away from it to a page of the same site waits to commit for over a second and the start lands in it on
/// purpose. The view must open once the new document has committed and show its frames. If Chromium ever answers that
/// moment with another text or code, the start fails here, on the CI, and not in Alberto's hands.
/// </summary>
/// <remarks>
/// Seen with Chrome 155 on the development machine (a standalone CDP experiment, same pages): the start was refused in
/// every round to a page of the same site and went through once the new document had committed. A navigation to
/// about:blank from a site page commits in another renderer, which is not busy, so it is not used here. And a view opened
/// through the host after a navigation has begun does not meet the refusal at all: its <c>Page.getFrameTree</c> is answered
/// only once that navigation has committed (see ServerEndToEndTests.AViewOpenedWhileThePageIsNavigating…).
/// </remarks>
[TestClass]
[DoNotParallelize]
public sealed class RemoteViewDuringNavigationTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireBrowser()
{
if (RealBrowser.UnavailableReason() is { } reason)
{
Assert.Inconclusive(reason);
}
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task AViewStartedBeforeTheNewDocumentCommitsOpensOnceItHasCommitted()
{
var ct = TestContext.CancellationToken;
await using var browser = await RealBrowser.StartAsync();
var cdp = browser.Cdp;
const int rounds = 6;
var refusedRounds = 0;
for (var round = 0; round < rounds; round++)
{
// Page.navigate answers once the new document is ready to commit; the busy page commits a moment later and its
// script holds the renderer from 0.1 s after that, for 2 s.
var busy = await cdp.NavigateAsync(browser.Site.Url("/occupata"), ct);
Assert.IsTrue(busy.Succeeded, busy.ErrorText);
await Task.Delay(TimeSpan.FromMilliseconds(500), ct);
// The login page of the site, as «Accedi a Instagram» opens it: ready to commit at once, committed only when
// the busy script lets go.
var navigation = cdp.NavigateAsync(browser.Site.Url($"/accesso?giro={round}"), ct);
await Task.Delay(TimeSpan.FromMilliseconds(150), ct);
var notes = new ConcurrentQueue<string>();
var log = new DelegateBrowserLog((level, message, _) =>
{
// The retry note is written at Info since issue #52 (it reaches the registro).
if (level is BrowserLogLevel.Debug or BrowserLogLevel.Information)
{
notes.Enqueue(message);
}
});
var view = new RemoteViewSession(cdp, browser.Host.UserDriving, log);
try
{
var watch = Stopwatch.StartNew();
await view.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900), ct);
watch.Stop();
var navigated = await navigation;
Assert.IsTrue(navigated.Succeeded, $"Round {round}: {navigated.ErrorText}");
Assert.IsTrue(browser.Host.UserIsDriving, $"Round {round}: the open view holds the browser.");
// Only the attempt number is in the note (ScreencastSession): «… al tentativo N, dopo un cambio di pagina.»
var retry = notes.FirstOrDefault(n => n.Contains("tentativo", StringComparison.Ordinal));
if (retry is not null)
{
refusedRounds++;
}
TestContext.WriteLine($"Giro {round}: vista aperta in {watch.ElapsedMilliseconds} ms; {retry ?? "fotogrammi avviati al primo tentativo."}");
// The frames of the new document: an animated page repaints all the time.
var animated = await cdp.NavigateAsync(browser.Site.Url("/animata"), ct);
Assert.IsTrue(animated.Succeeded, animated.ErrorText);
Assert.IsTrue(await JpegArrivesAsync(view.Screencast, ct), $"Round {round}: frames after the view opened.");
}
finally
{
await view.DisposeAsync();
}
Assert.IsFalse(browser.Host.UserIsDriving, $"Round {round}: the closed view released the browser.");
}
TestContext.WriteLine($"Giri in cui Chromium ha rifiutato il primo avvio con «{CdpCommandException.InactivePageMessage}»: {refusedRounds} su {rounds}.");
if (refusedRounds == 0)
{
// Every view opened: the product is fine, but the start never met the refusal, so the retry was not exercised.
Assert.Inconclusive("La vista si è aperta in ogni giro, ma Chromium non ha mai rifiutato il primo avvio: la prova non ha raggiunto il momento fra «ready to commit» e il commit (pagina /occupata, versione di Chromium) e il ritentativo non è stato messo alla prova.");
}
}
private static async Task<bool> JpegArrivesAsync(ScreencastSession screencast, CancellationToken ct)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(15));
try
{
await foreach (var frame in screencast.ReadFramesAsync(timeout.Token))
{
return frame.Jpeg is [0xFF, 0xD8, ..];
}
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
}
return false;
}
}