Browser mai bianco né muto: pagina iniziale, finestra che resta, fotogrammi che ripartono (#52)

Il browser di Febe a volte era bianco o non mostrava nulla. Le cause erano
diverse e si correggono insieme.

- Pagina iniziale. Se il browser è a riposo su about:blank e Alberto lo apre
  («Usa il browser», «Apri il browser»), Febe lo porta sulla home del sito
  quando è collegato, altrimenti sulla pagina di accesso. È un'azione di
  Alberto, sotto il suo permesso di guida, non del motore: Febe aspetta che
  la sessione finisca e prende il turno della pagina.
  Il nuovo pulsante «Pagina iniziale» sta nella barra della finestra di
  Windows e nella vista remota. Su about:blank la barra dice «Il browser è a
  riposo su una pagina vuota». «Indietro» non torna più sulla pagina di
  riposo.
- Disconnessione. «Apri il browser» nella striscia rossa apre la pagina di
  accesso. Con --accesso-di-prova il primo controllo all'avvio non segnala
  più una disconnessione finta.
- Windows: la finestra resta.
  - Lasciare una pagina di Febe non nasconde più la finestra «Browser di
    Febe» e non la rimette a riposo: finisce solo il permesso tenuto dalla
    pagina (cancel con pageLeft, IConnectionService.ReleaseAsync).
  - Sullo schermo la finestra ha il suo pulsante nella barra delle
    applicazioni, così ridurla a icona non la fa sparire. Dopo 2 minuti
    ridotta a icona torna fuori vista (S2).
  - Se lo schermo è troppo piccolo, la finestra si restringe all'area di
    lavoro e la pagina si rimpicciolisce con ZoomFactor, con le stesse misure
    CSS.
  - I bordi della pagina si riapplicano, con NotifyParentWindowPositionChanged,
    quando la finestra si mostra, si sposta o riparte il processo GPU.
  - Una pagina che non risponde mentre Alberto guida resta com'è.
  - IBrowserWindow.ShowAsync lascia il posto a
    IConnectionService.ShowBrowserAsync.
- Docker: fotogrammi che ripartono. La vista remota ha un watchdog. Riavvia
  i fotogrammi dopo una pagina nuova caricata senza fotogrammi e dopo circa
  2 s di silenzio. L'attesa raddoppia fino a 30 s finché la pagina resta
  ferma. Se il riavvio non porta nulla, la vista riceve un'immagine ferma
  (Page.captureScreenshot, già fra i comandi ammessi).
  RemoteViewSession ha ora un registro vero: avvii, riavvii e silenzi vanno
  a livello Info, categoria «vista», senza indirizzi.
  Se dopo 8 s non arriva nessuna immagine, l'interfaccia mostra «Nessuna
  immagine dal browser» con «Riprova».

Nessun comando CDP nuovo e nessuna dipendenza nuova. Aggiornati PROTOCOLLO.md
e la guida (Primo collegamento, Attività e arresti, Installazione Windows,
Problemi comuni).

Prove nuove:
- ScreencastWatchdogTests, RemoteViewFramesTests (Chromium vero, solo CI
  Linux)
- Home e Indietro in RemoteViewStartTests
- RemoteViewSocketTests
- ConnectionApiTests
- BrowserStartPageTests
- BrowserWindowDecisionTests e BrowserWindowTests (WebView2 vero)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-16 12:51:12 +01:00
1 parent 65c0c4470e
commit c49df4ca7b
49 files changed
+2056 -177

No files matched your search

@@ -0,0 +1,183 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using Febe.Browser.Cdp;
using Febe.Desktop.Browser;
using Febe.SitoDiProva;
using Febe.Tests.Windows.Support;
using Microsoft.Web.WebView2.Core;
namespace Febe.Tests.Windows;
/// <summary>
/// The decisions of the window «Browser di Febe» that need no browser (Gitea issue #52): what a failed process of
/// WebView2 asks of the host, and how much a page is shrunk to fit a small screen.
/// </summary>
[TestClass]
public sealed class BrowserWindowDecisionTests
{
[TestMethod]
public void AFailedProcessIsAnsweredByWhatItBroke()
{
Assert.AreEqual(ProcessFailureResponse.Restart, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.BrowserProcessExited, userIsDriving: false));
Assert.AreEqual(ProcessFailureResponse.Restart, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.BrowserProcessExited, userIsDriving: true));
Assert.AreEqual(ProcessFailureResponse.Rest, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.RenderProcessExited, userIsDriving: true), "a crashed page is gone anyway");
Assert.AreEqual(ProcessFailureResponse.Rest, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.RenderProcessUnresponsive, userIsDriving: false));
Assert.AreEqual(ProcessFailureResponse.None, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.RenderProcessUnresponsive, userIsDriving: true), "never white under Alberto's eyes");
Assert.AreEqual(ProcessFailureResponse.Redraw, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.GpuProcessExited, userIsDriving: false));
Assert.AreEqual(ProcessFailureResponse.Redraw, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.GpuProcessExited, userIsDriving: true));
Assert.AreEqual(ProcessFailureResponse.None, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.UtilityProcessExited, userIsDriving: false));
Assert.AreEqual(ProcessFailureResponse.None, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.FrameRenderProcessExited, userIsDriving: true));
}
[TestMethod]
public void APageThatDoesNotFitIsShrunkButNeverBelowTheSmallestFit()
{
// 1280×900 and its bar, in a frame of 16×39.
Assert.AreEqual(1, BrowserWindow.FitFor(1920, 1040, 1280, 900, 16, 39), "a full HD screen: as it is");
Assert.AreEqual(0.72, BrowserWindow.FitFor(1366, 728, 1280, 900, 16, 39), 1e-9, "a small laptop: by the height");
Assert.AreEqual(0.78, BrowserWindow.FitFor(1024, 1200, 1280, 900, 16, 39), 1e-9, "a narrow screen: by the width");
Assert.AreEqual(BrowserWindow.SmallestFit, BrowserWindow.FitFor(400, 300, 1280, 900, 16, 39));
Assert.AreEqual(1, BrowserWindow.FitFor(1366, 728, 0, 0, 16, 39), "no page size: nothing to fit");
}
}
/// <summary>
/// The window «Browser di Febe» on a real Windows (Gitea issue #52): on screen it has its taskbar button and says when
/// the page is the empty rest page, «Pagina iniziale» opens the start page, and a minimised window keeps Alberto at the
/// wheel until it has been minimised too long. The window comes on screen for a moment.
/// </summary>
[TestClass]
public sealed class BrowserWindowTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireWebView2() => WebView2Runtime.Require();
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task OnScreenTheWindowHasItsTaskbarButtonAndSaysWhenItRests()
{
var ct = TestContext.CancellationToken;
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
var start = site.Url("/benvenuto");
await using var bed = await BrowserBed.CreateAsync("finestra-pagina-iniziale", startPage: () => start);
await bed.StartAsync(ct);
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar), "out of view, no taskbar button");
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
Assert.IsTrue(await bed.OnUiAsync(() => window.IsOnScreen));
Assert.IsTrue(await bed.OnUiAsync(() => window.ShowInTaskbar), "on screen, a taskbar button");
Assert.AreEqual(BrowserWindow.RestNotice, await bed.OnUiAsync(() => window.AddressText), "the empty page says what it is");
Assert.IsGreaterThan(0, await bed.OnUiAsync(() => window.Fit));
// «Pagina iniziale»: Alberto's own navigation, to the start page the composition gives.
await bed.OnUiAsync(() =>
{
Button(window, "Pagina iniziale").RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
return true;
});
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (await bed.OnUiAsync(() => window.AddressText) != start)
{
Assert.IsLessThan(deadline, DateTime.UtcNow, "la pagina iniziale nella barra: " + bed.Lines.Text);
await Task.Delay(100, ct);
}
Assert.AreEqual(start, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
await Task.Run(() => bed.Browser.HideFromUserAsync(ct), ct);
Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar), "out of view again, no taskbar button");
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task AMinimisedWindowKeepsAlbertoAtTheWheelUntilItIsMinimisedTooLong()
{
var ct = TestContext.CancellationToken;
await using var bed = await BrowserBed.CreateAsync("finestra-ridotta");
await bed.StartAsync(ct);
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
await bed.OnUiAsync(() => window.MinimizedLimit = TimeSpan.FromSeconds(1));
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
await bed.OnUiAsync(() => window.WindowState = WindowState.Minimized);
Assert.IsTrue(bed.Browser.UserIsDriving, "minimised is not «ho finito»: its taskbar button brings it back");
Assert.IsTrue(await bed.OnUiAsync(() => window.ShowInTaskbar));
// Left there: restored and put out of view, as if closed (S2: never minimised for long).
await bed.WaitUntilAsync(() => !bed.Browser.UserIsDriving, TimeSpan.FromSeconds(15), "la fine della guida dopo la finestra ridotta a icona", ct);
Assert.AreEqual(WindowState.Normal, await bed.OnUiAsync(() => window.WindowState));
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar));
// Brought back before the limit, it stays Alberto's.
await bed.OnUiAsync(() => window.MinimizedLimit = TimeSpan.FromMinutes(2));
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
await bed.OnUiAsync(() => window.WindowState = WindowState.Minimized);
await bed.OnUiAsync(() => window.WindowState = WindowState.Normal);
await Task.Delay(1500, ct);
Assert.IsTrue(bed.Browser.UserIsDriving);
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
await Task.Run(() => bed.Browser.HideFromUserAsync(ct), ct);
}
[TestMethod]
[Timeout(240_000, CooperativeCancellation = true)]
public async Task LeavingThePageOfFebeLeavesTheWindowOnScreenWithItsPage()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopBed.StartAsync("finestra-resta", autoLogin: false, ct);
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
var connection = bed.App.Connection!;
var browser = bed.Browser;
var window = await bed.Ui.InvokeAsync(() => browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
// «Usa il browser» on the rest page, not connected: the login page of the test site, never a white window.
await connection.BeginUserDrivingAsync(openLogin: false, ct);
var opened = (await connection.GetStatusAsync(ct)).CurrentUrl;
StringAssert.StartsWith(opened, bed.Site.Url("/benvenuto"));
Assert.IsTrue(await bed.Ui.InvokeAsync(() => window.IsOnScreen));
// The page of Febe goes (another page, the tab closed): the window stays, with its page and the engine still.
await connection.ReleaseAsync(ct);
await Task.Delay(1500, ct);
Assert.IsTrue(await bed.Ui.InvokeAsync(() => window.IsOnScreen), "still on screen");
Assert.IsTrue(browser.UserIsDriving, "the window on screen holds the engine");
Assert.AreEqual(opened, (await connection.GetStatusAsync(ct)).CurrentUrl, "its page as it was");
Assert.IsTrue(bed.Lines.Any("Pagina di Febe lasciata: la finestra del browser resta com'è finché non la chiudi."), bed.Lines.Text);
// Closed with its X: out of view, the engine may work again.
await bed.Ui.InvokeAsync(() =>
{
window.Close();
return true;
});
await bed.WaitUntilAsync(() => Task.FromResult(!browser.UserIsDriving), TimeSpan.FromSeconds(10), "la fine della guida dopo la chiusura", ct);
Assert.IsFalse(await bed.Ui.InvokeAsync(() => window.IsOnScreen));
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
}
private static Button Button(DependencyObject root, string text) =>
FindOrNull(root, text) ?? throw new AssertFailedException($"Nessun pulsante «{text}» nella finestra.");
private static Button? FindOrNull(DependencyObject root, string text)
{
foreach (var child in LogicalTreeHelper.GetChildren(root).OfType<DependencyObject>())
{
if (child is Button { Content: string content } button && content == text)
{
return button;
}
if (FindOrNull(child, text) is { } found)
{
return found;
}
}
return null;
}
}
@@ -42,7 +42,10 @@ internal sealed class BrowserBed : IAsyncDisposable
public WebView2Browser Browser { get; }
public static async Task<BrowserBed> CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window)
/// <param name="name">Prefix of the temporary folder.</param>
/// <param name="hosting">How WebView2 draws (S2).</param>
/// <param name="startPage">Where «Pagina iniziale» goes; null: the login page of the options.</param>
public static async Task<BrowserBed> CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window, Func<string>? startPage = null)
{
var folder = new TestFolder(name);
var ui = await UiThread.StartAsync();
@@ -53,7 +56,7 @@ internal sealed class BrowserBed : IAsyncDisposable
var database = await FebeDatabase.OpenAsync(data.Root);
var options = new FebeAppOptions { DataFolder = data.Root, LibraryFolder = folder.Combine("libreria") };
var tracker = new BrowserUseTracker();
var context = new FebePlatformContext(options, data, database, clock, log, tracker);
var context = new FebePlatformContext(options, data, database, clock, log, tracker, startPage);
var settings = new WebView2BrowserSettings(data.BrowserProfile, 1280, 900, hosting, BrowserArguments.ForWebView2());
// Built off the UI thread, as DesktopPlatform.CreateBrowserAsync does after its awaits.
@@ -64,7 +64,8 @@ public sealed class RemoteViewDuringNavigationTests
var notes = new ConcurrentQueue<string>();
var log = new DelegateBrowserLog((level, message, _) =>
{
if (level == BrowserLogLevel.Debug)
// The retry note is written at Info since issue #52 (it reaches the registro).
if (level is BrowserLogLevel.Debug or BrowserLogLevel.Information)
{
notes.Enqueue(message);
}
@@ -0,0 +1,130 @@
using System.Diagnostics;
using Febe.Browser.Cdp;
using Febe.Browser.RemoteView;
using Febe.Tests.Browser.TestSupport;
namespace Febe.Tests.Browser;
/// <summary>
/// The remote view that stayed white (Gitea issue #52), on a real Chromium on Xvfb and the local test site: a page that
/// does not move still shows itself, and the frames keep coming when the page changes renderer (another site, the rest
/// page and back). Only in the Linux CI; never Instagram.
/// </summary>
[TestClass]
[DoNotParallelize]
public sealed class RemoteViewFramesTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireBrowser()
{
if (RealBrowser.UnavailableReason() is { } reason)
{
Assert.Inconclusive(reason);
}
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task AStillPageAndTheRestPageShowAPictureWithinFiveSeconds()
{
var ct = TestContext.CancellationToken;
await using var browser = await RealBrowser.StartAsync();
var cdp = browser.Cdp;
var opened = await cdp.NavigateAsync(browser.Site.Url("/accesso"), ct);
Assert.IsTrue(opened.Succeeded, opened.ErrorText);
await cdp.WaitForLoadAsync(new Febe.Core.Abstractions.SystemClock(), TimeSpan.FromSeconds(15), ct);
var view = new RemoteViewSession(cdp, browser.Host.UserDriving);
try
{
await view.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900, Watchdog: ScreencastWatchdog.Default), ct);
Assert.IsTrue(await PictureAfterAsync(view.Screencast, null, TimeSpan.FromSeconds(5), ct), "a picture of the login page");
var last = view.Screencast.LastFrame;
var rest = await cdp.RestAsync(ct);
Assert.IsTrue(rest.Succeeded, rest.ErrorText);
Assert.IsTrue(await PictureAfterAsync(view.Screencast, last, TimeSpan.FromSeconds(5), ct), "a picture of the rest page too");
}
finally
{
await view.DisposeAsync();
}
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task FramesKeepComingWhenThePageChangesRenderer()
{
var ct = TestContext.CancellationToken;
await using var browser = await RealBrowser.StartAsync();
var cdp = browser.Cdp;
var first = await cdp.NavigateAsync(browser.Site.Url("/animata"), ct);
Assert.IsTrue(first.Succeeded, first.ErrorText);
var view = new RemoteViewSession(cdp, browser.Host.UserDriving);
try
{
await view.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900, Watchdog: ScreencastWatchdog.Default), ct);
Assert.IsTrue(await FramesAfterAsync(view.Screencast, ct), "frames of the animated page");
foreach (var (address, moving) in new[]
{
(browser.Site.LocalhostUrl("/animata"), true),
("about:blank", false),
(browser.Site.Url("/animata"), true),
})
{
var last = view.Screencast.LastFrame;
var watch = Stopwatch.StartNew();
var navigated = await cdp.NavigateAsync(address, ct);
Assert.IsTrue(navigated.Succeeded, $"{address}: {navigated.ErrorText}");
var shown = moving
? await FramesAfterAsync(view.Screencast, ct)
: await PictureAfterAsync(view.Screencast, last, TimeSpan.FromSeconds(5), ct);
TestContext.WriteLine($"{address}: {(shown ? "immagini" : "niente")} dopo {watch.ElapsedMilliseconds} ms, riavvii {view.Screencast.Restarts}.");
Assert.IsTrue(shown, $"{address}: the view is not white");
}
}
finally
{
await view.DisposeAsync();
}
}
/// <summary>A frame or a still picture other than <paramref name="last"/>, within <paramref name="timeout"/>.</summary>
private static async Task<bool> PictureAfterAsync(ScreencastSession screencast, ScreencastFrame? last, TimeSpan timeout, CancellationToken ct)
{
var deadline = Stopwatch.StartNew();
while (deadline.Elapsed < timeout)
{
if (screencast.LastFrame is { Jpeg: [0xFF, 0xD8, ..] } frame && !ReferenceEquals(frame, last))
{
return true;
}
await Task.Delay(50, ct);
}
return false;
}
/// <summary>A few real frames of the screencast (not still pictures) after now, within ten seconds.</summary>
private static async Task<bool> FramesAfterAsync(ScreencastSession screencast, CancellationToken ct)
{
var before = screencast.FramesReceived;
var deadline = Stopwatch.StartNew();
while (deadline.Elapsed < TimeSpan.FromSeconds(10))
{
if (screencast.FramesReceived >= before + 3)
{
return true;
}
await Task.Delay(50, ct);
}
return false;
}
}
@@ -0,0 +1,336 @@
using System.Collections.Concurrent;
using System.Text.Json.Nodes;
using Febe.Browser.Cdp;
using Febe.Browser.Diagnostics;
using Febe.Browser.RemoteView;
using Febe.Core.Abstractions;
using Febe.Tests.Browser.TestSupport;
namespace Febe.Tests.Browser;
/// <summary>
/// The frames' watchdog of the remote view (Gitea issue #52), without a browser: a lost acknowledgement, a page that
/// does not repaint and a new document loaded without frames must never leave the view white and silent. The clock
/// moves only when the test says so, one look of the watchdog at a time.
/// </summary>
[TestClass]
public sealed class ScreencastWatchdogTests
{
private static readonly ScreencastWatchdog Watchdog = new(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(250), TimeSpan.FromSeconds(30));
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task ALostAcknowledgementIsFollowedByARestartAndTheFramesComeBack()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(lostAcks: true);
await bed.StartAsync(ct);
bed.Frame();
Assert.AreEqual(1, bed.Starts);
// The ack was lost: Chromium sends nothing more. Two seconds later the frames are started again.
await bed.StepAsync(TimeSpan.FromSeconds(2.25), ct);
Assert.AreEqual(1, bed.Session.Restarts);
Assert.AreEqual(2, bed.Starts, "a new screencast session");
var methods = bed.Cdp.Sent.Select(c => c.Method).Where(m => m is "Page.stopScreencast" or "Page.startScreencast").ToList();
CollectionAssert.AreEqual(new[] { "Page.startScreencast", "Page.stopScreencast", "Page.startScreencast" }, methods);
Assert.IsTrue(bed.Info.Contains("Vista remota: nessun fotogramma da 2 s, riavvio dei fotogrammi."), bed.AllLines);
// Frames flow again: said once, at Info.
for (var i = 0; i < ScreencastWatchdog.FlowingFrames; i++)
{
bed.Frame();
}
Assert.IsTrue(bed.Info.Any(l => l.StartsWith("Vista remota: fotogrammi di nuovo in arrivo, dopo ", StringComparison.Ordinal)), bed.AllLines);
Assert.AreEqual(1 + ScreencastWatchdog.FlowingFrames, bed.Session.FramesReceived);
// The stop is the last word: no start after it.
await bed.Session.StopAsync(ct);
Assert.AreEqual("Page.stopScreencast", bed.Cdp.Sent.Last(c => c.Method.Contains("Screencast", StringComparison.Ordinal) && c.Method != "Page.screencastFrameAck").Method);
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task APageThatNeverSendsAFrameGetsAStillPictureOfItself()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(screenshot: Jpeg(800, 600));
await bed.StartAsync(ct);
await bed.StepAsync(TimeSpan.FromSeconds(2.25), ct);
var still = bed.Session.LastFrame;
Assert.IsNotNull(still, "something to show");
Assert.IsTrue(still.Still);
Assert.AreEqual(800, still.DeviceWidth, "the size written in the picture");
Assert.AreEqual(600, still.DeviceHeight);
Assert.AreEqual(0, bed.Session.FramesReceived, "a still picture is not a frame of the screencast");
Assert.AreEqual(1, bed.Cdp.Sent.Count(c => c.Method == "Page.captureScreenshot"));
using var read = CancellationTokenSource.CreateLinkedTokenSource(ct);
read.CancelAfter(TimeSpan.FromSeconds(5));
await foreach (var frame in bed.Session.ReadFramesAsync(read.Token))
{
Assert.IsTrue(frame.Still, "the reader gets it like any frame");
break;
}
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task ANewDocumentLoadedWithoutFramesStartsThemAgainAtTheNextLook()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed();
await bed.StartAsync(ct);
bed.Frame();
// A frame of a page inside the page changes nothing; the main frame does.
bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F2", ["parentId"] = "F1", ["url"] = "http://127.0.0.1/pubblicita" } });
bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "http://127.0.0.1/animata" } });
bed.Cdp.Raise("Page.loadEventFired", new JsonObject { ["timestamp"] = 1.0 });
await bed.StepAsync(Watchdog.Tick, ct);
Assert.AreEqual(1, bed.Session.Restarts, "no two seconds of white after a new page");
Assert.IsTrue(bed.Info.Contains("Vista remota: pagina nuova caricata senza fotogrammi, riavvio dei fotogrammi."), bed.AllLines);
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task ANewDocumentWhoseFramesArriveIsLeftAlone()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed();
await bed.StartAsync(ct);
bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "http://127.0.0.1/animata" } });
bed.Frame();
bed.Cdp.Raise("Page.loadEventFired", new JsonObject { ["timestamp"] = 1.0 });
for (var i = 0; i < 6; i++)
{
await bed.StepAsync(Watchdog.Tick, ct);
bed.Frame();
}
Assert.AreEqual(0, bed.Session.Restarts);
Assert.AreEqual(1, bed.Starts);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task AStillPageCostsFewerAndFewerRestartsAndOneLineInTheRegistro()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(screenshot: Jpeg(1280, 900));
await bed.StartAsync(ct);
// Thirty seconds of a page that does not move: restarts after 2, 4, 8 and 16 more seconds, not fifteen.
await bed.StepAsync(TimeSpan.FromSeconds(30.25), ct);
Assert.AreEqual(4, bed.Session.Restarts, bed.AllLines);
Assert.AreEqual(1, bed.Info.Count(l => l.Contains("riavvio dei fotogrammi", StringComparison.Ordinal)), "one line for the whole silence, the others at Debug");
Assert.IsFalse(bed.AllLines.Contains("http", StringComparison.Ordinal), "no addresses in the registro");
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task WithoutAWatchdogNothingIsStartedAgain()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(noWatchdog: true);
await bed.StartAsync(ct);
Assert.AreEqual(0, bed.Clock.Waiting, "nobody watches");
bed.Clock.Advance(TimeSpan.FromMinutes(1));
Assert.AreEqual(1, bed.Starts);
Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.captureScreenshot"));
}
[TestMethod]
public void TheSizeOfAJpegIsReadFromItsFrameHeader()
{
Assert.AreEqual((800, 600), ScreencastSession.JpegSize(Jpeg(800, 600)));
Assert.AreEqual((1280, 900), ScreencastSession.JpegSize(Jpeg(1280, 900, progressive: true)));
Assert.IsNull(ScreencastSession.JpegSize([0xFF, 0xD8, 0xFF, 0xD9]), "no frame header");
Assert.IsNull(ScreencastSession.JpegSize([0x89, 0x50, 0x4E, 0x47]), "not a JPEG");
Assert.IsNull(ScreencastSession.JpegSize([]));
Assert.IsNull(ScreencastSession.JpegSize([0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08]), "cut short");
}
/// <summary>A minimal JPEG header: SOI, an APP0 segment, then a SOF0 (or SOF2) with the size.</summary>
private static byte[] Jpeg(int width, int height, bool progressive = false) =>
[
0xFF, 0xD8,
0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00,
0xFF, progressive ? (byte)0xC2 : (byte)0xC0, 0x00, 0x11, 0x08,
(byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width,
0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01,
0xFF, 0xD9,
];
/// <summary>A screencast over a fake page and a clock that moves only when stepped.</summary>
private sealed class Bed : IAsyncDisposable
{
private readonly ConcurrentQueue<(BrowserLogLevel Level, string Message)> _lines = new();
private readonly ScreencastWatchdog? _watchdog;
private int _starts;
private int _frameSession;
public Bed(bool lostAcks = false, byte[]? screenshot = null, bool noWatchdog = false)
{
_watchdog = noWatchdog ? null : Watchdog;
Clock = new SteppingClock();
Cdp = new FakeCdpSession(Clock)
{
Responder = (method, _) =>
{
switch (method)
{
case "Page.startScreencast":
Interlocked.Increment(ref _starts);
return null;
case "Page.screencastFrameAck" when lostAcks:
throw new CdpCommandException(method, CdpCommandException.ServerErrorCode, "Session is not attached");
case "Page.captureScreenshot":
return screenshot is null ? null : new JsonObject { ["data"] = Convert.ToBase64String(screenshot) };
default:
return null;
}
},
};
Session = new ScreencastSession(Cdp, new DelegateBrowserLog((level, message, _) => _lines.Enqueue((level, message))), Clock);
}
public SteppingClock Clock { get; }
public FakeCdpSession Cdp { get; }
public ScreencastSession Session { get; }
public int Starts => Volatile.Read(ref _starts);
public List<string> Info => [.. _lines.Where(l => l.Level == BrowserLogLevel.Information).Select(l => l.Message)];
public string AllLines => string.Join('\n', _lines.Select(l => $"{l.Level} {l.Message}"));
public async Task StartAsync(CancellationToken ct)
{
await Session.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900, Watchdog: _watchdog), ct);
if (_watchdog is not null)
{
await Clock.WaitForSleeperAsync(ct);
}
}
/// <summary>A frame of the screencast, as Chromium sends it.</summary>
public void Frame() => Cdp.Raise("Page.screencastFrame", new JsonObject
{
["sessionId"] = Interlocked.Increment(ref _frameSession),
["data"] = Convert.ToBase64String(Jpeg(1280, 900)),
["metadata"] = new JsonObject { ["deviceWidth"] = 1280, ["deviceHeight"] = 900, ["pageScaleFactor"] = 1 },
});
/// <summary>Moves the clock by <paramref name="time"/>, one look of the watchdog at a time.</summary>
public async Task StepAsync(TimeSpan time, CancellationToken ct)
{
var tick = (_watchdog ?? Watchdog).Tick;
for (var moved = TimeSpan.Zero; moved < time; moved += tick)
{
Clock.Advance(tick);
await Clock.WaitForSleeperAsync(ct);
}
}
public async ValueTask DisposeAsync() => await Session.DisposeAsync();
}
/// <summary>A clock whose delays end only when the test moves it past them.</summary>
private sealed class SteppingClock : IClock
{
private readonly Lock _gate = new();
private readonly List<(DateTimeOffset Due, TaskCompletionSource Done)> _sleepers = [];
private DateTimeOffset _now = new(2026, 11, 16, 9, 0, 0, TimeSpan.Zero);
public DateTimeOffset Now
{
get
{
lock (_gate)
{
return _now;
}
}
}
public TimeZoneInfo LocalZone => TimeZoneInfo.Utc;
public int Waiting
{
get
{
lock (_gate)
{
return _sleepers.Count;
}
}
}
public Task Delay(TimeSpan time, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
if (time <= TimeSpan.Zero)
{
return Task.CompletedTask;
}
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
lock (_gate)
{
_sleepers.Add((_now + time, done));
}
ct.Register(() =>
{
lock (_gate)
{
_sleepers.RemoveAll(s => s.Done == done);
}
done.TrySetCanceled(ct);
});
return done.Task;
}
public void Advance(TimeSpan time)
{
List<TaskCompletionSource> due;
lock (_gate)
{
_now += time;
due = [.. _sleepers.Where(s => s.Due <= _now).Select(s => s.Done)];
_sleepers.RemoveAll(s => s.Due <= _now);
}
foreach (var done in due)
{
done.TrySetResult();
}
}
/// <summary>Waits (in real time) until someone sleeps on the clock again: the watchdog finished its look.</summary>
public async Task WaitForSleeperAsync(CancellationToken ct)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(10));
while (Waiting == 0)
{
await Task.Delay(1, timeout.Token);
}
}
}
}
@@ -44,6 +44,9 @@ public sealed class LocalTestSite : IDisposable
public string Url(string path) => $"http://{SiteHost}{path}";
/// <summary>The same site under the name «localhost»: another site for Chromium, so another renderer.</summary>
public string LocalhostUrl(string path) => $"http://localhost:{SitePort}{path}";
public string CdnUrl(string path) => $"http://{CdnHost}{path}";
public static int FreePort()
@@ -0,0 +1,196 @@
using System.Net;
using Febe.Core.Abstractions;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Desktop;
/// <summary>
/// The browser that showed nothing (Gitea issue #52), in the shared composition with the fake window «Browser di Febe»:
/// opened from the empty rest page it goes to a page of its own, «Apri il browser» of a disconnection opens the login,
/// leaving a page of Febe leaves the window as it is, and the test site's automatic login raises no false alarm.
/// Never Instagram: the fake browser answers by itself.
/// </summary>
[TestClass]
public sealed class BrowserStartPageTests
{
private const string Login = "https://www.instagram.com/accounts/login/";
private const string Home = "https://www.instagram.com/";
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task UsaIlBrowserFromTheRestPageOpensTheLoginOrTheHomeAndAnyOtherPageStays()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
Assert.AreEqual("about:blank", browser.FakeCdp.Url);
// Not connected: never a white window, the login page.
await BeginAsync(bed, openLogin: false);
Assert.AreEqual(Login, browser.FakeCdp.Url);
Assert.AreEqual(1, browser.Shown, "the window came to the front");
browser.FakeCdp.LoggedIn = true;
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean());
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo «Ho finito»");
// Connected: the site's home.
await BeginAsync(bed, openLogin: false);
Assert.AreEqual(Home, browser.FakeCdp.Url);
// A page he opened stays as it is.
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
var navigations = Navigations(browser);
await BeginAsync(bed, openLogin: false);
Assert.AreEqual("https://www.instagram.com/marta.prova/", browser.FakeCdp.Url);
Assert.AreEqual(navigations, Navigations(browser), "no navigation of his page");
var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection");
Assert.IsTrue(status.GetProperty("userIsDriving").GetBoolean());
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ApriIlBrowserBringsTheWindowWithItsStartPageAndTheLoginAfterADisconnection()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
// Connected, at rest: «Apri il browser» (Attività) opens the home, the window in front.
await LoginAsync(bed);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo «Ho finito»");
var shown = browser.Shown;
var result = await bed.JsonAsync(HttpMethod.Post, "/api/browser/show");
StringAssert.Contains(result.GetProperty("message").GetString(), "primo piano");
Assert.AreEqual(Home, browser.FakeCdp.Url);
Assert.AreEqual(shown + 1, browser.Shown);
Assert.IsTrue(browser.UserIsDriving, "the window on screen holds the engine still");
// Closed with its X: out of view, the engine puts the page to rest.
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo la chiusura");
// The session goes while nobody looks: a disconnection. The red strip's «Apri il browser» asks for the login.
browser.FakeCdp.LoggedIn = false;
await bed.App.Connection!.RefreshAsync(ct);
var breaker = bed.App.Engine!.Services.Breaker;
await breaker.FlushAsync();
Assert.AreEqual(BreakerStatus.Disconnected, breaker.State.Status);
Assert.AreEqual(Login, bed.App.Connection.StartPageUrl, "disconnected: the start page is the login");
using (var show = await bed.SendAsync(HttpMethod.Post, "/api/browser/show", """{"openLogin":true}"""))
{
Assert.AreEqual(HttpStatusCode.OK, show.StatusCode, await show.Content.ReadAsStringAsync(ct));
}
Assert.AreEqual(Login, browser.FakeCdp.Url);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task LeavingThePageOfFebeLeavesTheWindowOnScreenButAnnullaPutsItAway()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
await LoginAsync(bed);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo «Ho finito»");
await BeginAsync(bed, openLogin: false);
Assert.AreEqual(Home, browser.FakeCdp.Url);
var hidden = browser.Hidden;
// Another page of Febe, the tab closed or reloaded: the page's hold ends, the window stays where it is.
using (var left = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel", """{"pageLeft":true}"""))
{
Assert.AreEqual(HttpStatusCode.NoContent, left.StatusCode);
}
await Task.Delay(TimeSpan.FromSeconds(1), ct);
Assert.AreEqual(hidden, browser.Hidden, "not put out of view");
Assert.AreEqual(Home, browser.FakeCdp.Url, "not put to rest");
Assert.IsTrue(browser.UserIsDriving, "on screen, the window still holds the engine");
Assert.IsTrue(bed.App.Engine!.Services.Runtime.UserIsDriving);
// «Annulla» from the page is still «Annulla»: out of view and at rest.
await BeginAsync(bed, openLogin: false);
using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel"))
{
Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode);
}
Assert.AreEqual(hidden + 1, browser.Hidden);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo «Annulla»");
Assert.AreEqual("about:blank", browser.FakeCdp.Url);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task HoFinitoWithoutTheLoginSaysTheSessionIsNotThere()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
await BeginAsync(bed, openLogin: true);
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsFalse(finish.GetProperty("connected").GetBoolean());
StringAssert.Contains(finish.GetProperty("message").GetString(), "non trova la sessione");
}
[TestMethod]
[Timeout(90_000, CooperativeCancellation = true)]
public async Task TheTestSitesAutomaticLoginIsNoDisconnectionAtTheNextStart()
{
var ct = TestContext.CancellationToken;
const string site = "http://127.0.0.1:8481";
string[] args = ["--sito-di-prova", site, "--accesso-di-prova"];
using var temp = new TempFolder("accesso-di-prova");
var locations = new MemoryLocationStore();
FakeDesktopShell Shell() => new() { OnCreated = b => b.FakeCdp.LogsInOnVisit = site };
await using (var bed = await DesktopTestBed.StartAsync(args, Shell(), temp, locations))
{
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
Assert.IsTrue(bed.App.Connection!.IsConnected, "logged in by the automatic login");
await bed.StopAsync();
}
// The next start: the new browser has no session yet (the test site forgot it); the automatic login opens it again.
await using (var bed = await DesktopTestBed.StartAsync(args, Shell(), temp, locations))
{
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var breaker = bed.App.Engine!.Services.Breaker;
await breaker.FlushAsync();
Assert.IsTrue(bed.App.Connection!.IsConnected);
Assert.AreEqual(BreakerStatus.Closed, breaker.State.Status, "not a disconnection: the session the login was about to open");
Assert.IsEmpty(await bed.App.Database.Incidents.ListOpenAsync(ct));
await bed.StopAsync();
}
}
private static int Navigations(FakeBrowser browser) => browser.FakeCdp.Methods.Count(m => m == "Page.navigate");
private static async Task BeginAsync(DesktopTestBed bed, bool openLogin)
{
using var begin = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", openLogin ? """{"openLogin":true}""" : """{"openLogin":false}""");
Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode);
}
private static async Task LoginAsync(DesktopTestBed bed)
{
await BeginAsync(bed, openLogin: true);
bed.Browser!.FakeCdp.LoggedIn = true;
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean(), finish.GetProperty("message").GetString());
}
}
@@ -28,11 +28,15 @@ internal sealed class FakeDesktopShell : IDesktopShell
public ConcurrentQueue<string> ProcessWindows { get; } = new();
/// <summary>Called with each browser as it is created, before Febe uses it (to set up the fake page).</summary>
public Action<FakeBrowser>? OnCreated { get; set; }
public string? WebView2Version() => RuntimeVersion;
public IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context)
{
var browser = new FakeBrowser(settings.ProfileDirectory, settings.Width, settings.Height, context);
OnCreated?.Invoke(browser);
Created.Enqueue((settings, browser));
return browser;
}
@@ -225,6 +229,12 @@ internal sealed class FakeCdp : ICdpSession
public bool LoggedIn { get; set; }
/// <summary>
/// Like the test site, which sets its session cookie on any visit: a navigation to an address starting with this
/// logs in, and the page reports itself loaded. Null: only the test logs in.
/// </summary>
public string? LogsInOnVisit { get; set; }
public string Url { get; private set; } = "about:blank";
public ConcurrentQueue<string> Methods { get; } = new();
@@ -244,7 +254,9 @@ internal sealed class FakeCdp : ICdpSession
{
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = Url } } },
"Page.navigate" => Navigate(parameters),
"Network.getCookies" => new JsonObject { ["cookies"] = LoggedIn ? new JsonArray(new JsonObject { ["name"] = "sessionid" }) : new JsonArray() },
// The session cookie of Instagram, and the test site's one.
"Network.getCookies" => new JsonObject { ["cookies"] = LoggedIn ? new JsonArray(new JsonObject { ["name"] = "sessionid" }, new JsonObject { ["name"] = "sessione_prova" }) : new JsonArray() },
"Runtime.evaluate" when LogsInOnVisit is not null => new JsonObject { ["result"] = new JsonObject { ["type"] = "string", ["value"] = "complete" } },
_ => new JsonObject(),
};
return Task.FromResult(JsonDocument.Parse(result.ToJsonString()).RootElement.Clone());
@@ -276,6 +288,11 @@ internal sealed class FakeCdp : ICdpSession
var url = (parameters as JsonObject)?["url"]?.GetValue<string>();
if (url is not null)
{
if (LogsInOnVisit is { } site && url.StartsWith(site, StringComparison.Ordinal))
{
LoggedIn = true;
}
Navigated(url);
}
@@ -177,6 +177,17 @@ public sealed class RemoteViewSocketTests
Assert.AreEqual("about:blank", BrowserRemoteViewConnection.WithoutQuery("about:blank"));
}
[TestMethod]
public void TheThreeButtonsOfTheBarAreNavigations()
{
static object? Parse(string json) => RemoteViewSocket.Parse(Encoding.UTF8.GetBytes(json));
Assert.AreEqual(RemoteViewNavigation.Back, Parse("""{"type":"navigate","action":"back"}"""));
Assert.AreEqual(RemoteViewNavigation.Reload, Parse("""{"type":"navigate","action":"reload"}"""));
Assert.AreEqual(RemoteViewNavigation.Home, Parse("""{"type":"navigate","action":"home"}"""), "«Pagina iniziale» (issue #52)");
Assert.IsNull(Parse("""{"type":"navigate","action":"https://example.com/"}"""), "never an address from the page");
}
private static Task<WebTestServer> StartAsync(FakeRemoteViewHost host) =>
WebTestServer.StartAsync(
new FebeWebOptions { Edition = FebeEdition.Docker, Access = AccessMode.Password, Password = Password },
@@ -132,6 +132,65 @@ public sealed class RemoteViewStartTests
}
}
[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);
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);
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 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);
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 CdpCommandException InactivePage() =>
new("Page.startScreencast", CdpCommandException.ServerErrorCode, CdpCommandException.InactivePageMessage);
@@ -170,7 +229,8 @@ public sealed class RemoteViewStartTests
private int _starts;
/// <param name="startFailure">For the n-th start (from 1), the exception the browser answers with; null: started.</param>
public Bed(Func<int, Exception?> startFailure)
/// <param name="startPage">Where «Pagina iniziale» goes; null: nowhere.</param>
public Bed(Func<int, Exception?> startFailure, Func<string>? startPage = null)
{
Clock = new VirtualClock();
_start = Clock.Now;
@@ -196,7 +256,11 @@ public sealed class RemoteViewStartTests
};
Browser = new PageBrowser(Cdp);
_log = new FebeLog(null, null, Clock);
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock);
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, startPage: startPage)
{
// The virtual clock moves only in the pauses: a watchdog on it would never wait.
Watchdog = null,
};
}
public VirtualClock Clock { get; }
@@ -209,6 +273,13 @@ public sealed class RemoteViewStartTests
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;
@@ -227,12 +227,15 @@ public sealed partial class ServerEndToEndTests
TimeSpan.FromSeconds(60),
"il motore di nuovo in funzione, in attesa del collegamento");
// «Ho finito» without having logged in: Febe says it does not find the session.
// «Usa il browser» on the rest page, not connected (issue #52): never the white page, the login page. (The test
// site sets its session on any visit, so «Ho finito» without a login is proved with the fake browser of
// BrowserStartPageTests.)
await connection.BeginUserDrivingAsync(openLogin: false, ct);
Assert.IsTrue(server.Browser.UserIsDriving);
var finish = await connection.FinishAsync(ct);
Assert.IsFalse(finish.Connected);
StringAssert.Contains(finish.Message, "non trova la sessione");
var opened = (await connection.GetStatusAsync(ct)).CurrentUrl;
Assert.IsNotNull(opened);
StringAssert.Contains(opened, "/benvenuto", "the login page of the test site");
await connection.CancelAsync(ct);
Assert.IsFalse(server.Browser.UserIsDriving);
// «Annulla» ends the driving and leaves the browser on the rest page.
@@ -62,6 +62,38 @@ public sealed class ConnectionApiTests
CollectionAssert.AreEqual(new[] { "begin:True", "finish", "cancel", "disconnect" }, connection.Calls);
}
[TestMethod]
public async Task LeavingThePageIsAnnullaInDockerAndOnlyTheEndOfTheHoldOnWindows()
{
// Docker: the remote view is the page, leaving it gives the browser back to rest.
var docker = new RecordingConnection();
await using (var server = await Part2.StartAsync(services: s => s.AddSingleton<IConnectionService>(docker)))
{
var (status, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel", new { pageLeft = true });
Assert.AreEqual(HttpStatusCode.NoContent, status);
var (showStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show");
Assert.AreEqual(HttpStatusCode.BadRequest, showStatus, "in Docker the browser is the Browser page");
}
CollectionAssert.AreEqual(new[] { "cancel" }, docker.Calls);
// Windows (issue #52): the window stays as it is; «Annulla» is still «Annulla»; «Apri il browser» says which page.
var windows = new RecordingConnection();
await using (var server = await Part2.StartAsync(services: s => s
.AddSingleton<IConnectionService>(windows)
.AddSingleton<Febe.Web.Native.IBrowserWindow>(new SeparateWindow())))
{
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel", new { pageLeft = true });
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel");
var (shown, message) = await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show");
Assert.AreEqual(HttpStatusCode.OK, shown);
StringAssert.Contains(message.Str("message"), "primo piano");
await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show", new { openLogin = true });
}
CollectionAssert.AreEqual(new[] { "release", "cancel", "show:False", "show:True" }, windows.Calls);
}
[TestMethod]
public async Task CommandsFromAnotherPageAreRefused()
{
@@ -99,4 +131,10 @@ public sealed class ConnectionApiTests
Assert.AreEqual(problem.Message, listed[0].Str("message"));
Assert.AreEqual(problem.Remedy, listed[0].Str("remedy"));
}
/// <summary>The browser as a window of its own, as on Windows.</summary>
private sealed class SeparateWindow : Febe.Web.Native.IBrowserWindow
{
public bool IsSeparateWindow => true;
}
}
@@ -109,6 +109,20 @@ internal sealed class RecordingConnection : IConnectionService
return Task.CompletedTask;
}
public Task ShowBrowserAsync(bool openLogin, CancellationToken ct)
{
Record("show:" + openLogin);
Status = Status with { UserIsDriving = true };
return Task.CompletedTask;
}
public Task ReleaseAsync(CancellationToken ct)
{
Record("release");
Status = Status with { UserIsDriving = false };
return Task.CompletedTask;
}
public Task DisconnectAsync(CancellationToken ct)
{
Record("disconnect");