In Docker lasciare la pagina «Browser» o la vista remota di Collegamento mentre Alberto guida (un'altra pagina, la scheda chiusa, il collegamento perso) valeva «Annulla» e la sessione non si copiava. Ora è come chiudere la finestra del browser su Windows: `cancel` con `pageLeft` va a LeavePageAsync, la vista remota chiusa dalla sua pagina lo dice alla connessione, e se per 5 secondi non si apre un'altra vista né arriva un `begin` (una pagina ricaricata) il controllo del permesso copia la sessione con CopyOnLetGoAsync, solo da una pagina del sito che non sia di accesso o di verifica, poi rilascia il permesso e il motore rimette il browser a riposo. Il pulsante «Annulla» continua a non copiare; Windows non cambia. Prove nuove per la copia lasciando la pagina, la ricarica che non è lasciare, la pagina di accesso, la vista sostituita o chiusa da Febe; guida, protocollo e una riga in decisioni.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
423 lines
19 KiB
C#
423 lines
19 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// Opening the remote view while the page changes document (Gitea issue #3), without a browser. From
|
|
/// <c>ReadyToCommitNavigation</c> of a navigation in a new RenderFrameHost until it commits, Chromium answers
|
|
/// <c>Page.startScreencast</c> 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.
|
|
/// </summary>
|
|
[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<RemoteViewMeta>(outputs[0]);
|
|
Assert.IsInstanceOfType<RemoteViewFrame>(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<RemoteViewUnavailableException>(() => 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<RemoteViewUnavailableException>(() => 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<RemoteViewUnavailableException>(() => 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;
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(30_000, CooperativeCancellation = true)]
|
|
public async Task OnlyAViewClosedByItsPageIsToldToTheConnection()
|
|
{
|
|
// Docker (answer of 25 November 2026): a view closed by its page may be Alberto leaving the browser; one replaced
|
|
// by another tab, one that did not start, or one closed because Febe stops is not.
|
|
var ct = TestContext.CancellationToken;
|
|
var told = 0;
|
|
await using var bed = new Bed(attempt => attempt == 3 ? new CdpDisconnectedException("Il collegamento con il browser si è chiuso.") : null, viewClosed: () => Interlocked.Increment(ref told));
|
|
|
|
var older = await bed.Host.OpenAsync(ct);
|
|
var newer = await bed.Host.OpenAsync(ct);
|
|
Assert.AreEqual(RemoteViewEnd.Replaced, older.Ended);
|
|
Assert.AreEqual(0, Volatile.Read(ref told), "replaced by another tab: Alberto is still at the browser");
|
|
|
|
await newer.DisposeAsync();
|
|
Assert.AreEqual(1, Volatile.Read(ref told), "the page closed its view");
|
|
|
|
await Assert.ThrowsExactlyAsync<RemoteViewUnavailableException>(() => bed.Host.OpenAsync(ct));
|
|
Assert.AreEqual(1, Volatile.Read(ref told), "a view that did not start was never the page's");
|
|
|
|
var last = await bed.Host.OpenAsync(ct);
|
|
await bed.Host.ShutdownAsync();
|
|
Assert.AreEqual(RemoteViewEnd.ShuttingDown, last.Ended);
|
|
Assert.AreEqual(1, Volatile.Read(ref told), "Febe stopping is not Alberto leaving");
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(30_000, CooperativeCancellation = true)]
|
|
public async Task PaginaInizialeOpensTheStartPageOfTheMoment()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
var start = "http://127.0.0.1:8481/benvenuto";
|
|
await using var bed = new Bed(_ => null, () => start);
|
|
var view = await bed.Host.OpenAsync(ct);
|
|
|
|
await view.NavigateAsync(RemoteViewNavigation.Home, ct);
|
|
await StartPageOf(view).WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
Assert.AreEqual(start, bed.LastNavigation, "not connected: the login page");
|
|
|
|
// Connected meanwhile: the same button opens the site's home.
|
|
start = "http://127.0.0.1:8481/";
|
|
await view.NavigateAsync(RemoteViewNavigation.Home, ct);
|
|
await StartPageOf(view).WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
Assert.AreEqual(start, bed.LastNavigation);
|
|
Assert.AreEqual(2, bed.Cdp.Sent.Count(c => c.Method == "Page.navigate"), "Alberto's own navigations, one per press");
|
|
|
|
await view.DisposeAsync();
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(30_000, CooperativeCancellation = true)]
|
|
public async Task PaginaInizialeWaitsBesideTheViewDroppingItsInputAndEndsWithIt()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
var presses = 0;
|
|
var pressedWith = new TaskCompletionSource<CancellationToken>(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
await using var bed = new Bed(_ => null, open: async token =>
|
|
{
|
|
Interlocked.Increment(ref presses);
|
|
pressedWith.TrySetResult(token);
|
|
|
|
// As the connection while a session ends or a search step holds the page: up to half a minute.
|
|
await Task.Delay(Timeout.Infinite, token);
|
|
});
|
|
var view = await bed.Host.OpenAsync(ct);
|
|
bed.Cdp.Raise("Page.screencastFrame", Frame());
|
|
await ReadUntilFrameAsync(view, ct);
|
|
bed.Cdp.ClearSent();
|
|
|
|
// The receive loop goes on at once: the press waits beside it.
|
|
await view.NavigateAsync(RemoteViewNavigation.Home, ct).WaitAsync(TimeSpan.FromSeconds(5), ct);
|
|
var token = await pressedWith.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
Assert.IsFalse(StartPageOf(view).IsCompleted, "still waiting for its turn");
|
|
|
|
// Meanwhile clicks, keys and the other buttons are dropped (they would land on the start page as it loads), and a
|
|
// second press waits for the first.
|
|
await view.MouseAsync(new RemoteViewMouse(RemoteViewMouseAction.Down, 0.5, 0.5, RemoteViewButton.Left, 1, 0, 0), ct);
|
|
await view.KeyAsync(new RemoteViewKey(RemoteViewKeyAction.Char, "a", "KeyA", "a", 0), ct);
|
|
await view.NavigateAsync(RemoteViewNavigation.Reload, ct);
|
|
await view.NavigateAsync(RemoteViewNavigation.Home, ct);
|
|
Assert.IsFalse(bed.Cdp.Sent.Any(c => IsInputOrNavigation(c.Method)), "nothing reached the browser: " + string.Join(", ", bed.Cdp.Sent.Select(c => c.Method)));
|
|
Assert.AreEqual(1, Volatile.Read(ref presses));
|
|
|
|
// The view closes: its lease is gone, and so is the press.
|
|
Assert.IsFalse(token.IsCancellationRequested);
|
|
await view.DisposeAsync();
|
|
Assert.IsTrue(token.IsCancellationRequested, "the press lasts as long as the view");
|
|
await StartPageOf(view).WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(30_000, CooperativeCancellation = true)]
|
|
public async Task AfterPaginaInizialeTheInputReachesTheBrowserAgain()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var bed = new Bed(_ => null, () => "http://127.0.0.1:8481/benvenuto");
|
|
var view = await bed.Host.OpenAsync(ct);
|
|
|
|
await view.NavigateAsync(RemoteViewNavigation.Home, ct);
|
|
await StartPageOf(view).WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
bed.Cdp.ClearSent();
|
|
await view.KeyAsync(new RemoteViewKey(RemoteViewKeyAction.Char, "a", "KeyA", "a", 0), ct);
|
|
|
|
Assert.IsTrue(bed.Cdp.Sent.Any(c => c.Method.StartsWith("Input.", StringComparison.Ordinal)), string.Join(", ", bed.Cdp.Sent.Select(c => c.Method)));
|
|
await view.DisposeAsync();
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(30_000, CooperativeCancellation = true)]
|
|
public async Task WithoutAStartPageTheButtonDoesNothing()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var bed = new Bed(_ => null);
|
|
var view = await bed.Host.OpenAsync(ct);
|
|
|
|
await view.NavigateAsync(RemoteViewNavigation.Home, ct);
|
|
await StartPageOf(view).WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
|
|
Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.navigate"));
|
|
await view.DisposeAsync();
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(30_000, CooperativeCancellation = true)]
|
|
public async Task IndietroNeverLandsOnTheEmptyRestPage()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var bed = new Bed(_ => null);
|
|
var view = await bed.Host.OpenAsync(ct);
|
|
|
|
// The view opened on the rest page; then a page, the rest page again (a session of the engine), another page.
|
|
bed.Navigated("http://127.0.0.1:8481/profilo/marta.prova/");
|
|
bed.Navigated("about:blank");
|
|
bed.Navigated("http://127.0.0.1:8481/esplora/");
|
|
|
|
await view.NavigateAsync(RemoteViewNavigation.Back, ct);
|
|
Assert.AreEqual("http://127.0.0.1:8481/profilo/marta.prova/", bed.LastNavigation, "the rest page in between is skipped");
|
|
|
|
// Before that only the rest page: «Indietro» stays where it is instead of turning the view white.
|
|
bed.Cdp.ClearSent();
|
|
await view.NavigateAsync(RemoteViewNavigation.Back, ct);
|
|
Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.navigate"));
|
|
|
|
await view.DisposeAsync();
|
|
}
|
|
|
|
private static bool IsInputOrNavigation(string method) =>
|
|
method.StartsWith("Input.", StringComparison.Ordinal) || method is "Page.navigate" or "Page.reload";
|
|
|
|
private static Task StartPageOf(IRemoteViewConnection view) => ((BrowserRemoteViewConnection)view).StartPageOpening;
|
|
|
|
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<List<RemoteViewOutput>> ReadUntilFrameAsync(IRemoteViewConnection view, CancellationToken ct)
|
|
{
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
|
var outputs = new List<RemoteViewOutput>();
|
|
await foreach (var output in view.ReadAsync(timeout.Token))
|
|
{
|
|
outputs.Add(output);
|
|
if (output is RemoteViewFrame)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
return outputs;
|
|
}
|
|
|
|
/// <summary>The host over a fake page whose answer to each <c>Page.startScreencast</c> is chosen by the test.</summary>
|
|
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;
|
|
|
|
/// <param name="startFailure">For the n-th start (from 1), the exception the browser answers with; null: started.</param>
|
|
/// <param name="startPage">
|
|
/// Where «Pagina iniziale» goes, as the connection would open it (BrowserConnectionService.OpenStartPageAsync,
|
|
/// tested in BrowserStartPageTests); null: nowhere.
|
|
/// </param>
|
|
/// <param name="open">What «Pagina iniziale» does instead (it wins over <paramref name="startPage"/>).</param>
|
|
/// <param name="viewClosed">What the connection is told when a view is closed by its page.</param>
|
|
public Bed(Func<int, Exception?> startFailure, Func<string>? startPage = null, Func<CancellationToken, Task>? open = null, Action? viewClosed = null)
|
|
{
|
|
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, openStartPage: open ?? (startPage is null ? null : async ct => await Cdp.NavigateAsync(startPage(), ct)), viewClosed: viewClosed)
|
|
{
|
|
// The virtual clock moves only in the pauses: a watchdog on it would never wait.
|
|
Watchdog = null,
|
|
};
|
|
}
|
|
|
|
public VirtualClock Clock { get; }
|
|
|
|
public FakeCdpSession Cdp { get; }
|
|
|
|
public PageBrowser Browser { get; }
|
|
|
|
public BrowserRemoteViewHost Host { get; }
|
|
|
|
public int Starts => Volatile.Read(ref _starts);
|
|
|
|
/// <summary>The address of the last <c>Page.navigate</c>.</summary>
|
|
public string? LastNavigation => Cdp.Sent.LastOrDefault(c => c.Method == "Page.navigate")?.Parameters?["url"]?.GetValue<string>();
|
|
|
|
/// <summary>The main frame committed a new document.</summary>
|
|
public void Navigated(string url) =>
|
|
Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = url } });
|
|
|
|
/// <summary>Time spent in the host's pauses (the virtual clock moves only there).</summary>
|
|
public TimeSpan Elapsed => Clock.Now - _start;
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await Host.ShutdownAsync();
|
|
_log.Dispose();
|
|
}
|
|
}
|
|
|
|
/// <summary>A running browser on one page, as the remote view host sees it.</summary>
|
|
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<NavigationResult> 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;
|
|
}
|
|
}
|