diff --git a/docs/decisioni.md b/docs/decisioni.md index 7b64921..3d9f7c7 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -262,3 +262,6 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-10-20 | «Storico completato» lo scrive solo il motore (`SessionComposer.FinishBackfillAsync`: @nome, post in libreria, che cosa succede ora); la ricetta Storico non scrive più una riga sua. Il motore chiude lo storico ogni volta che il cammino è arrivato in fondo (`BackfillFinished`), anche se poi la corsa finisce con un segnale o un'interruzione | Due righe nella cronologia e in «Avvisi» per lo stesso storico (@marta.prova, 14:31): la corta della ricetta e quella del motore. La notifica era già una sola e col testo del motore, perché la riga della ricetta (`CollectionWriter.EventAsync`) non passa da `EngineEvents` e `AlertService` non la vede. Con un segnale subito dopo l'ultima pagina l'account restava «Storico in corso» per sempre | | 2026-10-20 | Anche lo storico completato dal controllo del profilo (profilo tutto nella prima pagina) lo chiude il motore, con la sua riga (`BackfillFinished` del controllo, solo per un account «Storico in corso»). A inizio sessione il motore chiude gli account rimasti «Storico in corso» con lo storico già completato; la fase dello Storico rilegge gli account invece di usare quelli di inizio sessione | Con due account «Storico in corso» quello piccolo restava così per sempre, senza riga né avviso: dalla sessione dopo non era più candidato dello Storico. Rileggere gli account evita una seconda riga quando lo Storico della stessa sessione sceglierebbe proprio quello appena chiuso | | 2026-10-20 | Quando chiude uno storico, il motore toglie subito dalla coda il suo «Storico» e, se l'account resta in pausa, gli altri compiti pianificati; non rimette in coda la corsa dello Storico arrivata in fondo e poi fermata da un segnale | La Coda mostrava fino alla sessione dopo (dopo una verifica, fino a «Riprendi») uno Storico da fare per un account già «Aggiornato» o «In pausa». I comandi di Alberto restano | +| 2026-10-20 | Vista remota: `Page.startScreencast` si manda di nuovo solo se Chromium risponde -32000 «Not attached to an active page», con pause da 100 a 500 ms e per al più 5 s di orologio vero (`ScreencastSession.InactivePageBudget`); collegamento chiuso, nessuna risposta o qualunque altro rifiuto danno subito «Il browser di Febe non risponde». Nessun comando CDP nuovo | Issue #3. Dal `ReadyToCommitNavigation` di una navigazione con un nuovo RenderFrameHost fino al suo commit, DevTools punta già al documento nuovo non ancora attivo e i comandi di pagina gestiti dal browser falliscono così (`page_handler.cc`, `AssureTopLevelActiveFrame`); con RenderDocument, attivo in Chromium, vale per ogni navigazione, anche verso la pagina di riposo. Ci cadevano la vista aperta insieme alla pagina di accesso, dopo un riposo del motore o durante una sessione | +| 2026-10-20 | Sostituzione di una vista remota: `BrowserRemoteViewHost.OpenAsync` tiene un permesso «Alberto usa il browser» di passaggio dalla fine della vista vecchia all'avvio della nuova; l'ospite della vista usa `IFebeBrowser` invece di `ChromiumBrowser` | Fra le due viste i permessi scendevano a zero: il motore si svegliava e riportava la pagina a riposo proprio mentre la vista nuova avviava i fotogrammi (il fallimento della CI, issue #3), e avrebbe potuto cominciare una sessione. L'interfaccia permette di provarlo senza browser | +| 2026-10-20 | Prova con Chromium vero del ritentativo della vista remota (`RemoteViewDuringNavigationTests`): una pagina del sito locale delle prove (`/occupata`) tiene occupato il renderer per 2 s, così la navigazione verso un'altra pagina dello stesso sito resta fra «ready to commit» e il commit e `Page.startScreencast` ci cade apposta; se in nessun giro Chromium rifiuta il primo avvio, la prova risulta inconcludente e non superata | Revisione dell'issue #3: TwoViews… prova solo il permesso di passaggio, e una vista aperta dall'ospite dopo l'inizio di una navigazione non incontra il rifiuto (`Page.getFrameTree` risponde solo dopo il commit). Con Chrome 155 sulla macchina di sviluppo, in un esperimento a parte con lo stesso codice di Febe, il rifiuto è arrivato in 18 giri su 18 e la vista si è aperta al sesto tentativo; con il testo atteso cambiato la stessa sequenza fallisce. Verso about:blank da una pagina del sito il commit avviene in un altro renderer: quel caso non serve allo scopo | diff --git a/src/Febe.Browser/Cdp/CdpCommandPolicy.cs b/src/Febe.Browser/Cdp/CdpCommandPolicy.cs index bd543f2..2565107 100644 --- a/src/Febe.Browser/Cdp/CdpCommandPolicy.cs +++ b/src/Febe.Browser/Cdp/CdpCommandPolicy.cs @@ -92,11 +92,31 @@ public sealed class CdpCommandNotAllowedException(string method, string message) public sealed class CdpCommandException(string method, int code, string browserMessage) : Exception($"Il comando CDP «{method}» è fallito: {browserMessage} (codice {code}).") { + /// Chromium's generic «server error» code. + public const int ServerErrorCode = -32000; + + /// + /// What Chromium answers to a browser-side page command (Page.startScreencast, Page.captureScreenshot) + /// while the page's current document is not «active»: from ReadyToCommitNavigation of a navigation that uses + /// a new RenderFrameHost until that navigation commits, DevTools already points at the new, still uncommitted frame + /// (content/browser/devtools/protocol/page_handler.cc, AssureTopLevelActiveFrame; + /// render_frame_devtools_agent_host.cc, ReadyToCommitNavigation). A new RenderFrameHost comes with a process + /// swap, a cross-site or back-forward-cache swap and, with RenderDocument (on by default in current Chromium), with + /// every navigation of the page to a new document — the rest page included. + /// + public const string InactivePageMessage = "Not attached to an active page"; + public string Method { get; } = method; public int Code { get; } = code; public string BrowserMessage { get; } = browserMessage; + + /// + /// The page is between two documents (see ): the same command a moment later finds + /// the new document committed. A browser that is gone answers differently (closed connection, no answer). + /// + public bool IsInactivePage => Code == ServerErrorCode && string.Equals(BrowserMessage, InactivePageMessage, StringComparison.Ordinal); } /// The connection to the browser is closed (browser exited, crashed or is restarting). diff --git a/src/Febe.Browser/RemoteView/RemoteViewSession.cs b/src/Febe.Browser/RemoteView/RemoteViewSession.cs index a96a8f8..9ab7dd1 100644 --- a/src/Febe.Browser/RemoteView/RemoteViewSession.cs +++ b/src/Febe.Browser/RemoteView/RemoteViewSession.cs @@ -64,12 +64,16 @@ public sealed class RemoteViewSession : IAsyncDisposable private IDisposable? _lease; private int _buttons; - public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null) + /// The page session. + /// Where the «Alberto is driving» lease is taken. + /// Where opening and closing are noted (never keys). + /// Wall-clock time for the screencast's start attempts; null: the system clock. + 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); + Screencast = new ScreencastSession(cdp, _log, clock); } public ScreencastSession Screencast { get; } diff --git a/src/Febe.Browser/RemoteView/ScreencastSession.cs b/src/Febe.Browser/RemoteView/ScreencastSession.cs index 530f9a0..5b3e299 100644 --- a/src/Febe.Browser/RemoteView/ScreencastSession.cs +++ b/src/Febe.Browser/RemoteView/ScreencastSession.cs @@ -39,10 +39,22 @@ public sealed record ScreencastFrame( /// Page.screencastFrameAck, stopped with Page.stopScreencast. Frames are delivered through /// (only the latest ones are kept when the reader is slow) and . /// +/// +/// A view opened while the page changes document (the rest page after a session, the login page opened together with +/// the view) can meet the moment in which Chromium refuses the start with «Not attached to an active page»: the start +/// is sent again, a few times, for at most . Any other failure is reported at once. +/// public sealed class ScreencastSession : IAsyncDisposable { + /// How long a start refused because the page is between two documents is tried again. + public static readonly TimeSpan InactivePageBudget = TimeSpan.FromSeconds(5); + + private static readonly TimeSpan FirstPause = TimeSpan.FromMilliseconds(100); + private static readonly TimeSpan LongestPause = TimeSpan.FromMilliseconds(500); + private readonly ICdpSession _cdp; private readonly IBrowserLog _log; + private readonly IClock _clock; private readonly Channel _frames = Channel.CreateBounded( new BoundedChannelOptions(2) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true }); @@ -54,10 +66,14 @@ public sealed class ScreencastSession : IAsyncDisposable private int _stopped; private long _framesReceived; - public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null) + /// The page session. + /// Where the start and stop are noted (never parameters or frames). + /// Wall-clock time for the pauses between start attempts; null: the system clock. + public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null, IClock? clock = null) { _cdp = cdp ?? throw new ArgumentNullException(nameof(cdp)); _log = log ?? NullBrowserLog.Instance; + _clock = clock ?? new SystemClock(); } /// Raised on the browser event thread for every frame: handlers must be quick. @@ -144,20 +160,47 @@ public sealed class ScreencastSession : IAsyncDisposable _lifetime.Dispose(); } - private Task SendStartAsync(CancellationToken ct) + private async Task SendStartAsync(CancellationToken ct) { var o = _options ?? new ScreencastOptions(); - return _cdp.SendAsync( - "Page.startScreencast", - new JsonObject + var deadline = _clock.Now + InactivePageBudget; + var pause = FirstPause; + for (var attempt = 1; ; attempt++) + { + try { - ["format"] = "jpeg", - ["quality"] = Math.Clamp(o.Quality, 0, 100), - ["maxWidth"] = o.MaxWidth, - ["maxHeight"] = o.MaxHeight, - ["everyNthFrame"] = Math.Max(1, o.EveryNthFrame), - }, - ct); + await _cdp.SendAsync( + "Page.startScreencast", + new JsonObject + { + ["format"] = "jpeg", + ["quality"] = Math.Clamp(o.Quality, 0, 100), + ["maxWidth"] = o.MaxWidth, + ["maxHeight"] = o.MaxHeight, + ["everyNthFrame"] = Math.Max(1, o.EveryNthFrame), + }, + ct).ConfigureAwait(false); + if (attempt > 1) + { + _log.Debug($"Vista remota: fotogrammi avviati al tentativo {attempt.ToString(System.Globalization.CultureInfo.InvariantCulture)}, dopo un cambio di pagina."); + } + + return; + } + catch (CdpCommandException ex) when (ex.IsInactivePage && _clock.Now + pause <= deadline) + { + // A navigation is committing in a new frame of the page: nothing is started on the browser side, the + // same start a moment later finds the new document. Past the budget the error goes up as it is. + } + + await _clock.Delay(pause, ct).ConfigureAwait(false); + if (Volatile.Read(ref _stopped) == 1) + { + return; // stopped meanwhile (a restart's start in the background): nothing left to start + } + + pause = pause * 2 < LongestPause ? pause * 2 : LongestPause; + } } private void OnReconnected(object? sender, EventArgs e) => diff --git a/src/Febe.Server/BrowserRemoteView.cs b/src/Febe.Server/BrowserRemoteView.cs index 310262b..1593f3f 100644 --- a/src/Febe.Server/BrowserRemoteView.cs +++ b/src/Febe.Server/BrowserRemoteView.cs @@ -17,18 +17,40 @@ namespace Febe.Server; /// the older view is always ended — and its screencast stopped — before the newer one starts). Keys go to the browser /// and nowhere else. /// -internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log) : IRemoteViewHost +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 Lock _gate = new(); private readonly SemaphoreSlim _opening = new(1, 1); private BrowserRemoteViewConnection? _current; private bool _shuttingDown; + /// The browser shown. + /// Notes when Alberto last used the browser. + /// The composition's clock (the time of that note). + /// Febe's log. + /// + /// Time for the waits on the browser itself; null: the wall clock, because the browser commits a navigation in real + /// time whatever clock the engine runs on (the tests compress it). + /// + public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = 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); + } + public async Task OpenAsync(CancellationToken ct) { - if (!browser.IsAvailable) + if (!_browser.IsAvailable) { - throw new RemoteViewUnavailableException(browser.LastError is { } error + 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."); } @@ -37,6 +59,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT // 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; @@ -53,13 +76,17 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT 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); + var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock); try { - await connection.StartAsync(browser.BrowserOptions.WindowWidth, browser.BrowserOptions.WindowHeight, ct).ConfigureAwait(false); + await connection.StartAsync(_browser.WindowWidth, _browser.WindowHeight, ct).ConfigureAwait(false); } catch (Exception ex) { @@ -90,11 +117,13 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT throw new RemoteViewUnavailableException("Febe si sta fermando."); } - log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta."); + _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(); } } @@ -126,7 +155,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT } } - log.Info("vista", "Vista remota chiusa."); + _log.Info("vista", "Vista remota chiusa."); } } @@ -134,7 +163,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection { private readonly BrowserRemoteViewHost _owner; - private readonly ChromiumBrowser _browser; + private readonly IFebeBrowser _browser; private readonly BrowserUseTracker _tracker; private readonly IClock _clock; private readonly RemoteViewSession _session; @@ -155,18 +184,18 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection private int _disposed; private bool _used; - public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock) + public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock) { _owner = owner; _browser = browser; _tracker = tracker; _clock = clock; - _session = new RemoteViewSession(browser.Host.Cdp, browser.Host.UserDriving); + _session = new RemoteViewSession(browser.Cdp, browser.UserDriving, clock: browserClock); } public RemoteViewEnd? Ended { get; private set; } - private ICdpSession Cdp => _browser.Host.Cdp; + private ICdpSession Cdp => _browser.Cdp; public async Task StartAsync(int width, int height, CancellationToken ct) { diff --git a/src/Febe.Server/DockerPlatform.cs b/src/Febe.Server/DockerPlatform.cs index e37aca2..1ef5ae8 100644 --- a/src/Febe.Server/DockerPlatform.cs +++ b/src/Febe.Server/DockerPlatform.cs @@ -53,7 +53,7 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(app); - RemoteView = new BrowserRemoteViewHost((ChromiumBrowser)app.Browser!, app.Tracker, app.Clock, app.Log); + RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log); services.AddSingleton(RemoteView); } diff --git a/tests/Febe.Tests/Browser/RemoteViewDuringNavigationTests.cs b/tests/Febe.Tests/Browser/RemoteViewDuringNavigationTests.cs new file mode 100644 index 0000000..5dd2d0f --- /dev/null +++ b/tests/Febe.Tests/Browser/RemoteViewDuringNavigationTests.cs @@ -0,0 +1,129 @@ +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; + +/// +/// 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 ReadyToCommitNavigation of a navigation in a new RenderFrameHost until its commit, +/// DevTools points at the new, not yet active document and Chromium refuses Page.startScreencast 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. +/// +/// +/// 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 Page.getFrameTree is answered +/// only once that navigation has committed (see ServerEndToEndTests.AViewOpenedWhileThePageIsNavigating…). +/// +[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(); + var log = new DelegateBrowserLog((level, message, _) => + { + if (level == BrowserLogLevel.Debug) + { + 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 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; + } +} diff --git a/tests/Febe.Tests/Browser/TestSupport/LocalTestSite.cs b/tests/Febe.Tests/Browser/TestSupport/LocalTestSite.cs index 4c76bd4..866285e 100644 --- a/tests/Febe.Tests/Browser/TestSupport/LocalTestSite.cs +++ b/tests/Febe.Tests/Browser/TestSupport/LocalTestSite.cs @@ -202,6 +202,10 @@ public sealed class LocalTestSite : IDisposable "/spa" => "

Applicazione

", "/verifica" => "

Verifica

", "/accesso" => "

Accesso

", + + // Keeps its renderer busy for 2 s, from 0.1 s after it has committed: a navigation away from it to a page of the + // same site (same renderer) reaches «ready to commit» at once but commits only when the script lets go. + "/occupata" => "

Occupata

", _ => "

Pagina di prova

", }; diff --git a/tests/Febe.Tests/Server/RemoteViewStartTests.cs b/tests/Febe.Tests/Server/RemoteViewStartTests.cs new file mode 100644 index 0000000..70cdb9a --- /dev/null +++ b/tests/Febe.Tests/Server/RemoteViewStartTests.cs @@ -0,0 +1,253 @@ +using System.Diagnostics; +using System.Text.Json.Nodes; +using Febe.App; +using Febe.Browser.Cdp; +using Febe.Browser.Hosting; +using Febe.Browser.RemoteView; +using Febe.Core.Abstractions; +using Febe.Server; +using Febe.Tests.Browser.TestSupport; +using Febe.Web.Connection; +using Febe.Web.Engine; + +namespace Febe.Tests.Server; + +/// +/// Opening the remote view while the page changes document (Gitea issue #3), without a browser. From +/// ReadyToCommitNavigation of a navigation in a new RenderFrameHost until it commits, Chromium answers +/// Page.startScreencast with -32000 «Not attached to an active page»: the view must open once the new document is +/// there, a page that never gets there must still end in «non risponde» within a few seconds, and a browser that is gone +/// must say so at once. +/// +[TestClass] +public sealed class RemoteViewStartTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + [Timeout(30_000, CooperativeCancellation = true)] + public async Task AViewOpenedWhileThePageChangesDocumentOpensOnceTheNewDocumentIsThere() + { + var ct = TestContext.CancellationToken; + await using var bed = new Bed(attempt => attempt == 1 ? InactivePage() : null); + + var view = await bed.Host.OpenAsync(ct); + + Assert.IsNull(view.Ended, "the view is open"); + Assert.AreEqual(2, bed.Starts, "the start refused while the page changed document was sent again"); + Assert.AreEqual(1, bed.Browser.UserDriving.Leases, "the open view holds the browser"); + Assert.IsLessThan(TimeSpan.FromSeconds(1), bed.Elapsed, "a short pause, not the whole budget"); + + // Frames flow to the view: meta first, then the JPEG. + bed.Cdp.Raise("Page.screencastFrame", Frame()); + var outputs = await ReadUntilFrameAsync(view, ct); + Assert.IsInstanceOfType(outputs[0]); + Assert.IsInstanceOfType(outputs[^1]); + + await view.DisposeAsync(); + Assert.AreEqual(0, bed.Browser.UserDriving.Leases, "no view, no lease"); + } + + [TestMethod] + [Timeout(30_000, CooperativeCancellation = true)] + public async Task APageThatStaysBetweenTwoDocumentsStillEndsInNonRispondeWithinTheBudget() + { + var ct = TestContext.CancellationToken; + await using var bed = new Bed(_ => InactivePage()); + var watch = Stopwatch.StartNew(); + + var error = await Assert.ThrowsExactlyAsync(() => bed.Host.OpenAsync(ct)); + + StringAssert.Contains(error.Message, "non risponde"); + Assert.IsTrue(error.InnerException is CdpCommandException { IsInactivePage: true }, "the browser's answer stays the cause"); + Assert.IsLessThanOrEqualTo(ScreencastSession.InactivePageBudget, bed.Elapsed, "never longer than the budget"); + Assert.IsGreaterThan(TimeSpan.FromSeconds(4), bed.Elapsed, "tried for the whole budget"); + Assert.IsInRange(5, 15, bed.Starts, "a few attempts, spaced out"); + Assert.IsLessThan(TimeSpan.FromSeconds(10), watch.Elapsed, "the pauses are the clock's, not a hang"); + Assert.AreEqual(0, bed.Browser.UserDriving.Leases, "nothing of the view stays behind"); + } + + [TestMethod] + [Timeout(30_000, CooperativeCancellation = true)] + public async Task ABrowserThatIsGoneIsNotTriedAgain() + { + var ct = TestContext.CancellationToken; + await using var bed = new Bed(_ => new CdpDisconnectedException("Il collegamento con il browser si è chiuso.")); + + var error = await Assert.ThrowsExactlyAsync(() => bed.Host.OpenAsync(ct)); + + StringAssert.Contains(error.Message, "non risponde"); + Assert.AreEqual(1, bed.Starts); + Assert.AreEqual(TimeSpan.Zero, bed.Elapsed, "no pause at all"); + Assert.AreEqual(0, bed.Browser.UserDriving.Leases); + } + + [TestMethod] + [Timeout(30_000, CooperativeCancellation = true)] + public async Task AnotherRefusalOfTheBrowserIsNotTriedAgain() + { + var ct = TestContext.CancellationToken; + await using var bed = new Bed(_ => new CdpCommandException("Page.startScreencast", CdpCommandException.ServerErrorCode, "Not attached to a page")); + + await Assert.ThrowsExactlyAsync(() => bed.Host.OpenAsync(ct)); + + Assert.AreEqual(1, bed.Starts, "only «Not attached to an active page» is the moment of a navigation"); + Assert.AreEqual(TimeSpan.Zero, bed.Elapsed); + } + + [TestMethod] + [Timeout(30_000, CooperativeCancellation = true)] + public async Task ReplacingAViewKeepsAlbertoAtTheBrowserThroughout() + { + var ct = TestContext.CancellationToken; + await using var bed = new Bed(_ => null); + var gate = bed.Browser.UserDriving; + var older = await bed.Host.OpenAsync(ct); + var released = 0; + void OnChanged(object? sender, bool driving) + { + if (!driving) + { + Interlocked.Increment(ref released); + } + } + + gate.Changed += OnChanged; + try + { + var newer = await bed.Host.OpenAsync(ct); + + Assert.AreEqual(RemoteViewEnd.Replaced, older.Ended); + Assert.IsNull(newer.Ended); + Assert.AreEqual(0, released, "the engine never sees nobody at the browser between the two views (it would rest the page under the new one)"); + Assert.AreEqual(1, gate.Leases); + + await newer.DisposeAsync(); + Assert.AreEqual(1, released, "closing the last view lets the engine go on"); + Assert.AreEqual(0, gate.Leases); + } + finally + { + gate.Changed -= OnChanged; + } + } + + private static CdpCommandException InactivePage() => + new("Page.startScreencast", CdpCommandException.ServerErrorCode, CdpCommandException.InactivePageMessage); + + private static JsonObject Frame() => new() + { + ["sessionId"] = 1, + ["data"] = Convert.ToBase64String([0xFF, 0xD8, 0xFF, 0xD9]), + ["metadata"] = new JsonObject { ["deviceWidth"] = Bed.Width, ["deviceHeight"] = Bed.Height, ["pageScaleFactor"] = 1 }, + }; + + private static async Task> ReadUntilFrameAsync(IRemoteViewConnection view, CancellationToken ct) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + var outputs = new List(); + await foreach (var output in view.ReadAsync(timeout.Token)) + { + outputs.Add(output); + if (output is RemoteViewFrame) + { + break; + } + } + + return outputs; + } + + /// The host over a fake page whose answer to each Page.startScreencast is chosen by the test. + private sealed class Bed : IAsyncDisposable + { + public const int Width = 1280; + public const int Height = 900; + + private readonly FebeLog _log; + private readonly DateTimeOffset _start; + private int _starts; + + /// For the n-th start (from 1), the exception the browser answers with; null: started. + public Bed(Func startFailure) + { + Clock = new VirtualClock(); + _start = Clock.Now; + Cdp = new FakeCdpSession(Clock) + { + Responder = (method, _) => + { + switch (method) + { + case "Page.getFrameTree": + return new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } }; + case "Page.startScreencast": + if (startFailure(Interlocked.Increment(ref _starts)) is { } failure) + { + throw failure; + } + + return null; + default: + return null; + } + }, + }; + Browser = new PageBrowser(Cdp); + _log = new FebeLog(null, null, Clock); + Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock); + } + + public VirtualClock Clock { get; } + + public FakeCdpSession Cdp { get; } + + public PageBrowser Browser { get; } + + public BrowserRemoteViewHost Host { get; } + + public int Starts => Volatile.Read(ref _starts); + + /// Time spent in the host's pauses (the virtual clock moves only there). + public TimeSpan Elapsed => Clock.Now - _start; + + public async ValueTask DisposeAsync() + { + await Host.ShutdownAsync(); + _log.Dispose(); + } + } + + /// A running browser on one page, as the remote view host sees it. + private sealed class PageBrowser(ICdpSession cdp) : IFebeBrowser + { + public ICdpSession Cdp { get; } = cdp; + + public UserDrivingGate UserDriving { get; } = new(); + + public bool UserIsDriving => UserDriving.IsDriving; + + public bool IsAvailable => true; + + public string? LastError => null; + + public string ProfileDirectory => "browser"; + + public int WindowWidth => Bed.Width; + + public int WindowHeight => Bed.Height; + + public Task RunAsync(CancellationToken ct) => Task.CompletedTask; + + public Task RestAsync(CancellationToken ct) => Cdp.RestAsync(ct); + + public Task ShowToUserAsync(CancellationToken ct) => Task.CompletedTask; + + public Task HideFromUserAsync(CancellationToken ct) => Task.CompletedTask; + + public Task RestartWithEmptyProfileAsync(CancellationToken ct) => Task.CompletedTask; + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/tests/Febe.Tests/Server/ServerEndToEndTests.cs b/tests/Febe.Tests/Server/ServerEndToEndTests.cs index 392c58b..ead76a1 100644 --- a/tests/Febe.Tests/Server/ServerEndToEndTests.cs +++ b/tests/Febe.Tests/Server/ServerEndToEndTests.cs @@ -252,20 +252,44 @@ public sealed partial class ServerEndToEndTests await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct); var host = server.RemoteView!; var gate = server.Browser!.UserDriving; + var released = 0; + void OnChanged(object? sender, bool driving) + { + if (!driving) + { + Interlocked.Increment(ref released); + } + } + for (var round = 0; round < 5; round++) { // From the rest page: where the browser starts, and where the engine puts it once nobody is at the browser. + // Page.getFrameTree is answered by the page itself, which DevTools holds back while a navigation is pending: + // «about:blank» here means the engine's rest has committed. await ServerTestBed.WaitUntilAsync( async () => await Febe.Browser.Cdp.CdpPageExtensions.GetMainFrameUrlAsync(server.Browser.Cdp, ct) == "about:blank", TimeSpan.FromSeconds(20), "la pagina di riposo"); - // Two tabs restored together, or the phone and the PC at once: the newest wins, the other is ended. - var views = await Task.WhenAll(Task.Run(() => host.OpenAsync(ct), ct), Task.Run(() => host.OpenAsync(ct), ct)); + // Two tabs restored together, or the phone and the PC at once: the newest wins, the other is ended — and the + // engine never sees nobody at the browser in between (it would put the page to rest under the newer view). + Volatile.Write(ref released, 0); + gate.Changed += OnChanged; + IRemoteViewConnection[] views; + try + { + views = await Task.WhenAll(Task.Run(() => host.OpenAsync(ct), ct), Task.Run(() => host.OpenAsync(ct), ct)); + } + finally + { + gate.Changed -= OnChanged; + } + var open = views.Where(v => v.Ended is null).ToList(); Assert.HasCount(1, open, $"Round {round}: one view stays open."); Assert.AreEqual(RemoteViewEnd.Replaced, views.Single(v => v.Ended is not null).Ended); Assert.AreEqual(1, gate.Leases, $"Round {round}: only the open view holds the browser."); + Assert.AreEqual(0, Volatile.Read(ref released), $"Round {round}: the browser was never left without a driver while one view replaced the other."); // The page of the replaced view closes its socket: the open view still gets its frames. await views.Single(v => v.Ended is not null).DisposeAsync(); @@ -277,6 +301,55 @@ public sealed partial class ServerEndToEndTests } } + [TestMethod] + [Timeout(180_000, CooperativeCancellation = true)] + public async Task AViewOpenedWhileThePageIsNavigatingOpensAndShowsItsFrames() + { + var ct = TestContext.CancellationToken; + await using var bed = await ServerTestBed.StartAsync(); + var server = bed.Server; + await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct); + var host = server.RemoteView!; + var browser = server.Browser!; + + for (var round = 0; round < 6; round++) + { + // From the rest page, as in TwoViews…: the previous round ends on a site page, so «about:blank» here means the + // engine's rest after the last view has committed and nothing else navigates. + await ServerTestBed.WaitUntilAsync( + async () => await Febe.Browser.Cdp.CdpPageExtensions.GetMainFrameUrlAsync(browser.Cdp, ct) == "about:blank", + TimeSpan.FromSeconds(20), + "la pagina di riposo"); + + // Even rounds: «Accedi a Instagram» on the Collegamento page navigates to the login page while the same page + // opens the view. Odd rounds: the rest page, as the engine puts it after a session or after the last view. + // A guard of these pairs, not of the retry: with the navigation already sent, the view's first look at the + // page (Page.getFrameTree) is answered only once it has committed, so the start comes after the commit (seen + // with Chrome 155). RemoteViewDuringNavigationTests makes the start meet the refusal on purpose. + var navigation = round % 2 == 0 + ? Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, $"{bed.Site.SiteUrl}/?vista={round}", ct) + : browser.RestAsync(ct); + var view = await host.OpenAsync(ct); + try + { + var navigated = await navigation; + Assert.IsTrue(navigated.Succeeded, $"Round {round}: {navigated.ErrorText}"); + Assert.IsNull(view.Ended, $"Round {round}: the view is open."); + Assert.AreEqual(1, browser.UserDriving.Leases, $"Round {round}: only the view holds the browser."); + + // A new page paints: its frames reach the view. + await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, $"{bed.Site.SiteUrl}/?giro={round}", ct); + Assert.IsTrue(await FrameArrivesAsync(view, ct), $"Round {round}: frames of the page."); + } + finally + { + await view.DisposeAsync(); + } + + Assert.AreEqual(0, browser.UserDriving.Leases, $"Round {round}: no view, no lease."); + } + } + private static async Task FrameArrivesAsync(IRemoteViewConnection view, CancellationToken ct) { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);