Files
Febe/tests/Febe.Tests.Windows/BrowserWindowTests.cs
T
Alby96andClaude Opus 5.5 2bbad2e9b7 «Pagina iniziale» solo finché Alberto guida, e la vista che non si blocca (#52)
Una verifica indipendente di 654076d ha trovato tre punti deboli.

- «Pagina iniziale» guardava il permesso di guida una volta sola, prima di
  aspettare fino a 15 s la fine della sessione e 15 s il turno della pagina
  (che poi prendeva comunque). Se nel frattempo Alberto chiudeva la finestra,
  Febe navigava senza permesso e fuori dal Governatore (regole 7 e 8). Ora la
  pressione vale finché dura il permesso di chi l'ha premuta: la finestra di
  Windows passa un gettone che si annulla con il suo permesso, la vista remota
  quello della propria vita. Con il turno della pagina in mano la connessione
  guarda di nuovo che Alberto guidi ancora; senza turno rinuncia invece di
  prendere la pagina a un passo della ricerca. L'attesa del turno è
  BrowserConnectionService.PageTurnWait (15 s, le prove la accorciano).
- Nella vista remota «Pagina iniziale» aspettava dentro il ciclo di ricezione:
  la vista restava ferma fino a mezzo minuto e poi riversava clic e tasti sulla
  pagina nuova. Ora la pressione corre a parte, una per volta, e intanto clic,
  tasti, «Indietro» e «Ricarica» si scartano.
- Repaint chiedeva un ridisegno sincrono (RDW_UPDATENOW) a finestre figlie del
  processo del browser di WebView2: uno bloccato avrebbe fermato il thread
  dell'interfaccia. Ora si chiede solo di ridisegnare.

Prove nuove, che senza le correzioni non passano: la pressione dimenticata se
Alberto lascia il browser, quella che finisce con il permesso di chi l'ha
premuta, la pagina mai tolta a un passo della ricerca, la vista che non si
blocca e scarta l'input; su Windows con WebView2 vero, il gettone che si
annulla quando la finestra si chiude. PROTOCOLLO.md, la guida e decisioni.md
dicono il comportamento nuovo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 13:53:29 +01:00

249 lines
13 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Interop;
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, the window is never hidden while on screen
/// (WPF hides it to change its taskbar button) and out of view the page is at 100%, 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");
// Every hide of the window (SWP_HIDEWINDOW), and those while it is on screen, where Alberto would see it go.
var hides = 0;
var hidesOnScreen = 0;
await bed.OnUiAsync(() =>
{
var source = (HwndSource)PresentationSource.FromVisual(window);
source.AddHook((IntPtr _, int message, IntPtr _, IntPtr data, ref bool _) =>
{
const int WindowPosChanged = 0x0047;
const int HideWindow = 0x0080;
if (message == WindowPosChanged && (System.Runtime.InteropServices.Marshal.ReadInt32(data, (IntPtr.Size * 2) + 16) & HideWindow) != 0)
{
hides++;
if (window.IsOnScreen)
{
hidesOnScreen++;
}
}
return IntPtr.Zero;
});
return true;
});
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");
Assert.AreEqual(1.0, await bed.OnUiAsync(() => window.Fit), "out of view the page is at 100%, whatever the screen");
Assert.AreEqual(0, await bed.OnUiAsync(() => hidesOnScreen), $"never hidden on screen ({await bed.OnUiAsync(() => hides)} hides out of view)");
TestContext.WriteLine($"Nascosta fuori vista {await bed.OnUiAsync(() => hides)} volte per il pulsante nella barra delle applicazioni.");
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task PaginaInizialeLastsAsLongAsTheWindowsLease()
{
var ct = TestContext.CancellationToken;
var pressedWith = new TaskCompletionSource<CancellationToken>(TaskCreationOptions.RunContinuationsAsynchronously);
// As the connection while a session ends or a search step holds the page: it waits, here until the press is over.
await using var bed = await BrowserBed.CreateAsync("finestra-pagina-iniziale-chiusa", openStartPage: async token =>
{
pressedWith.TrySetResult(token);
await Task.Delay(Timeout.Infinite, token);
});
await bed.StartAsync(ct);
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
await bed.OnUiAsync(() =>
{
Button(window, "Pagina iniziale").RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
return true;
});
var token = await pressedWith.Task.WaitAsync(TimeSpan.FromSeconds(30), ct);
Assert.IsFalse(token.IsCancellationRequested, "the window is still on screen");
// Alberto closes the window before the start page opened: the press is over with the window's lease.
await bed.OnUiAsync(() =>
{
window.Close();
return true;
});
Assert.IsFalse(bed.Browser.UserIsDriving);
await bed.WaitUntilAsync(() => token.IsCancellationRequested, TimeSpan.FromSeconds(10), "la fine della «Pagina iniziale» con la finestra", ct);
Assert.IsFalse(bed.Lines.Any("non aperta"), "a press given up is no failure: " + bed.Lines.Text);
}
[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;
}
}