From 724c0752cf7165d7e449b61a281fade120ae6a83 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 16:54:50 +0200 Subject: [PATCH 1/7] Vista remota: l'avvio dei fotogrammi si ritenta mentre la pagina cambia documento MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Da ReadyToCommitNavigation al commit di una navigazione con un nuovo RenderFrameHost (con RenderDocument: ogni navigazione, anche verso la pagina di riposo) Chromium rifiuta Page.startScreencast con -32000 «Not attached to an active page». La vista aperta in quel momento (insieme alla pagina di accesso, dopo un riposo del motore, durante una sessione) finiva in «Il browser di Febe non risponde». Ora ScreencastSession rimanda l'avvio solo su quella risposta, con pause da 100 a 500 ms e per al più 5 s sull'orologio vero (IClock, iniettabile nelle prove); ogni altro errore sale subito com'era. Nessun comando CDP nuovo. Vale anche per il riavvio dei fotogrammi dopo un riavvio del browser. Co-Authored-By: Claude Opus 5.5 --- src/Febe.Browser/Cdp/CdpCommandPolicy.cs | 20 ++++++ .../RemoteView/RemoteViewSession.cs | 8 ++- .../RemoteView/ScreencastSession.cs | 67 +++++++++++++++---- 3 files changed, 81 insertions(+), 14 deletions(-) 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) => From d07b072bf84ec6c1e05d4a19d135d5ad0f95751d Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 16:55:00 +0200 Subject: [PATCH 2/7] Vista remota: nessun istante senza conducente quando una vista sostituisce l'altra MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Aprendo una vista mentre un'altra è aperta, il permesso della vecchia si chiudeva prima che la nuova prendesse il suo: per un attimo nessuno usava il browser, 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 perfino cominciare una sessione. Ora OpenAsync tiene un permesso di passaggio dalla fine della vista vecchia all'avvio della nuova. L'ospite della vista usa IFebeBrowser invece di ChromiumBrowser, così si prova senza browser, e aspetta il browser sull'orologio vero (le prove d'insieme comprimono quello del motore). Co-Authored-By: Claude Opus 5.5 --- src/Febe.Server/BrowserRemoteView.cs | 51 ++++++++++++++++++++++------ src/Febe.Server/DockerPlatform.cs | 2 +- 2 files changed, 41 insertions(+), 12 deletions(-) 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); } From 1b767d517d7c9fcc53f4bfeca0b7452a2c785457 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 16:55:01 +0200 Subject: [PATCH 3/7] Prove della vista remota aperta durante un cambio di pagina MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Senza browser (RemoteViewStartTests, su FakeCdpSession e VirtualClock): un primo rifiuto «Not attached to an active page» dà comunque una vista aperta con i suoi fotogrammi; un rifiuto che non passa finisce in «non risponde» entro 5 s di orologio; collegamento chiuso o altri rifiuti non si ritentano; la sostituzione di una vista non lascia mai i permessi a zero. Nella prova con Chromium vero (TwoViewsOpenedAtTheSameMoment...) si controlla anche che durante la sostituzione il browser non resti mai senza conducente. Co-Authored-By: Claude Opus 5.5 --- .../Febe.Tests/Server/RemoteViewStartTests.cs | 253 ++++++++++++++++++ .../Febe.Tests/Server/ServerEndToEndTests.cs | 28 +- 2 files changed, 279 insertions(+), 2 deletions(-) create mode 100644 tests/Febe.Tests/Server/RemoteViewStartTests.cs 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 fb69719..ec283c0 100644 --- a/tests/Febe.Tests/Server/ServerEndToEndTests.cs +++ b/tests/Febe.Tests/Server/ServerEndToEndTests.cs @@ -250,20 +250,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(); From 1b2faa4c7a52c7a464541da000d68091d66e162f Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 16:55:01 +0200 Subject: [PATCH 4/7] Decisioni: vista remota durante i cambi di pagina (issue #3) Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/decisioni.md b/docs/decisioni.md index be3e037..a39b8ee 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -226,3 +226,5 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-10-13 | Prove dell'interfaccia in un Chromium senza finestra guidato col protocollo DevTools diretto (`UiBrowser`, solo 127.0.0.1), inconcludenti senza Chromium | Come `tools/schermate`; il client CDP di Febe accetta solo letture | | 2026-10-14 | Revisione avversaria di tutto il codice (7 aree, ogni rilievo verificato da un secondo revisore indipendente): 54 rilievi confermati e corretti con prove di regressione, 2 smentiti, 3 incerti corretti dove il rimedio era sicuro | §14, regola 14: resoconti onesti | | 2026-10-14 | Restano noti e accettati: «Tieni il più grande» scrive con il proprio SafeFileWriter e non passa dal lucchetto per account di `LibraryIngest` (un'importazione e uno scaricamento con gli stessi byte nello stesso istante potrebbero entrare entrambi); le prove d'interfaccia con browser vero aspettano fino a 30 s | Finestra rarissima, nessuna perdita di dati: al più un doppione esatto da togliere a mano | +| 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 | From 67568ae36ff461f445a7c04106e62dfa3d9fe75b Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 17:39:22 +0200 Subject: [PATCH 5/7] Prova con Chromium vero: la vista remota avviata prima del commit di una pagina MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nessuna prova con un browser vero arrivava al ritentativo di Page.startScreencast: TwoViews… prova solo il permesso di passaggio e il ritentativo girava solo su FakeCdpSession. Se Chromium cambiasse testo o codice del rifiuto, la CI resterebbe verde e Alberto ritroverebbe «Il browser di Febe non risponde». La pagina /occupata del sito locale delle prove tiene occupato il renderer per 2 s: la navigazione verso un'altra pagina dello stesso sito resta fra «ready to commit» e il commit, e l'avvio dei fotogrammi ci cade apposta. In ogni giro la vista deve aprirsi e mostrare un JPEG. Se nessun giro incontra il rifiuto, la prova è inconcludente: il ritentativo non è stato messo alla prova. Co-Authored-By: Claude Opus 5.5 --- .../RemoteViewDuringNavigationTests.cs | 129 ++++++++++++++++++ .../Browser/TestSupport/LocalTestSite.cs | 4 + 2 files changed, 133 insertions(+) create mode 100644 tests/Febe.Tests/Browser/RemoteViewDuringNavigationTests.cs 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

", }; From 62941b104d1a19c841f5f7b5c430910bd3b747d8 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 17:39:22 +0200 Subject: [PATCH 6/7] Prova d'insieme: vista remota aperta mentre il browser naviga MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sul server vero, la vista si apre insieme alla navigazione verso una pagina del sito (come «Accedi a Instagram» dalla pagina Collegamento) o insieme al riposo del motore: deve aprirsi, tenere un solo permesso e ricevere i fotogrammi. È una guardia di queste coppie, non del ritentativo: con la navigazione già partita Page.getFrameTree risponde solo dopo il commit. Il ritentativo lo prova RemoteViewDuringNavigationTests. Co-Authored-By: Claude Opus 5.5 --- .../Febe.Tests/Server/ServerEndToEndTests.cs | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/tests/Febe.Tests/Server/ServerEndToEndTests.cs b/tests/Febe.Tests/Server/ServerEndToEndTests.cs index ec283c0..44f6d85 100644 --- a/tests/Febe.Tests/Server/ServerEndToEndTests.cs +++ b/tests/Febe.Tests/Server/ServerEndToEndTests.cs @@ -299,6 +299,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); From ef23421d2dc3f52eabd555a4174889c707926497 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 17:39:22 +0200 Subject: [PATCH 7/7] Decisioni: come si prova con Chromium vero il ritentativo della vista remota Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/decisioni.md b/docs/decisioni.md index a39b8ee..d9d1b69 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -228,3 +228,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-10-14 | Restano noti e accettati: «Tieni il più grande» scrive con il proprio SafeFileWriter e non passa dal lucchetto per account di `LibraryIngest` (un'importazione e uno scaricamento con gli stessi byte nello stesso istante potrebbero entrare entrambi); le prove d'interfaccia con browser vero aspettano fino a 30 s | Finestra rarissima, nessuna perdita di dati: al più un doppione esatto da togliere a mano | | 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 |