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();