«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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-16 13:53:29 +01:00
1 parent 654076d280
commit 2bbad2e9b7
12 files changed
+340 -24

No files matched your search

@@ -121,6 +121,42 @@ public sealed class BrowserWindowTests
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()
@@ -49,7 +49,8 @@ internal sealed class BrowserBed : IAsyncDisposable
/// Where «Pagina iniziale» goes, opened as the connection would (here without an engine to wait for); null: the button
/// does nothing (never the default login page of the options, which is Instagram's).
/// </param>
public static async Task<BrowserBed> CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window, Func<string>? startPage = null)
/// <param name="openStartPage">What «Pagina iniziale» does instead (it wins over <paramref name="startPage"/>).</param>
public static async Task<BrowserBed> CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window, Func<string>? startPage = null, Func<CancellationToken, Task>? openStartPage = null)
{
var folder = new TestFolder(name);
var ui = await UiThread.StartAsync();
@@ -61,7 +62,7 @@ internal sealed class BrowserBed : IAsyncDisposable
var options = new FebeAppOptions { DataFolder = data.Root, LibraryFolder = folder.Combine("libreria") };
var tracker = new BrowserUseTracker();
WebView2Browser? built = null;
Func<CancellationToken, Task>? openStartPage = startPage is null ? null : async ct => await built!.Cdp.NavigateAsync(startPage(), ct);
openStartPage ??= startPage is null ? null : async ct => await built!.Cdp.NavigateAsync(startPage(), ct);
var context = new FebePlatformContext(options, data, database, clock, log, tracker, openStartPage);
var settings = new WebView2BrowserSettings(data.BrowserProfile, 1280, 900, hosting, BrowserArguments.ForWebView2());
@@ -207,6 +207,78 @@ public sealed class BrowserStartPageTests
Assert.AreEqual(Login, browser.FakeCdp.Url, "not connected: the login page");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task PaginaInizialeIsForgottenWhenAlbertoLetGoOfTheBrowserWhileItWaited()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
var connection = bed.App.Connection!;
var turns = bed.App.Engine!.Services.PageTurns;
// The window on screen (its lease), a step of the profile search on the page: «Pagina iniziale» waits for its turn.
var window = browser.UserDriving.Begin();
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
var turn = await turns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct);
var home = connection.OpenStartPageAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => turns.IsWaiting(Febe.Core.Engine.PageUser.Engine), TimeSpan.FromSeconds(10), "«Pagina iniziale» in attesa del turno della pagina");
// Alberto closes the window meanwhile: the page is the engine's again, and the press is forgotten (rules 7 and 8).
window.Dispose();
Assert.IsFalse(browser.UserIsDriving);
turn.Dispose();
await home.WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.DoesNotContain(Login, browser.FakeCdp.Visited, "no navigation of Alberto's without his lease");
Assert.DoesNotContain(Home, browser.FakeCdp.Visited);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task PaginaInizialeEndsWithTheLeaseOfWhoPressedIt()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
var connection = bed.App.Connection!;
var turns = bed.App.Engine!.Services.PageTurns;
// Someone else still drives (Febe's page with «Usa il browser»), but the window that pressed the button closed.
using var other = browser.UserDriving.Begin();
using var pressedBy = new CancellationTokenSource();
var turn = await turns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct);
var home = connection.OpenStartPageAsync(pressedBy.Token);
await DesktopTestBed.WaitUntilAsync(() => turns.IsWaiting(Febe.Core.Engine.PageUser.Engine), TimeSpan.FromSeconds(10), "«Pagina iniziale» in attesa del turno della pagina");
await pressedBy.CancelAsync();
await home.WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.IsFalse(turns.IsWaiting(Febe.Core.Engine.PageUser.Engine), "no longer in the queue");
turn.Dispose();
Assert.DoesNotContain(Login, browser.FakeCdp.Visited);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task PaginaInizialeNeverTakesThePageFromUnderASearchStep()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageTurnWait = TimeSpan.FromMilliseconds(300);
var turns = bed.App.Engine!.Services.PageTurns;
using var window = browser.UserDriving.Begin();
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
using var turn = await turns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct);
await connection.OpenStartPageAsync(ct).WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.AreEqual("https://www.instagram.com/marta.prova/", browser.FakeCdp.Url, "the step keeps its page");
Assert.DoesNotContain(Login, browser.FakeCdp.Visited);
}
private static int Navigations(FakeBrowser browser) => browser.FakeCdp.Methods.Count(m => m == "Page.navigate");
private static async Task BeginAsync(DesktopTestBed bed, bool openLogin)
@@ -239,6 +239,9 @@ internal sealed class FakeCdp : ICdpSession
public ConcurrentQueue<string> Methods { get; } = new();
/// <summary>Every address a <c>Page.navigate</c> asked for, in order.</summary>
public ConcurrentQueue<string> Visited { get; } = new();
/// <summary>The main frame moved to <paramref name="url"/> by itself (a redirect of the site), not by a command.</summary>
public void Navigated(string url)
{
@@ -288,6 +291,7 @@ internal sealed class FakeCdp : ICdpSession
var url = (parameters as JsonObject)?["url"]?.GetValue<string>();
if (url is not null)
{
Visited.Enqueue(url);
if (LogsInOnVisit is { } site && url.StartsWith(site, StringComparison.Ordinal))
{
LoggedIn = true;
@@ -142,17 +142,77 @@ public sealed class RemoteViewStartTests
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()
@@ -162,6 +222,7 @@ public sealed class RemoteViewStartTests
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();
@@ -191,6 +252,11 @@ public sealed class RemoteViewStartTests
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);
@@ -233,7 +299,8 @@ public sealed class RemoteViewStartTests
/// Where «Pagina iniziale» goes, as the connection would open it (BrowserConnectionService.OpenStartPageAsync,
/// tested in BrowserStartPageTests); null: nowhere.
/// </param>
public Bed(Func<int, Exception?> startFailure, Func<string>? startPage = null)
/// <param name="open">What «Pagina iniziale» does instead (it wins over <paramref name="startPage"/>).</param>
public Bed(Func<int, Exception?> startFailure, Func<string>? startPage = null, Func<CancellationToken, Task>? open = null)
{
Clock = new VirtualClock();
_start = Clock.Now;
@@ -259,7 +326,7 @@ public sealed class RemoteViewStartTests
};
Browser = new PageBrowser(Cdp);
_log = new FebeLog(null, null, Clock);
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, openStartPage: startPage is null ? null : async ct => await Cdp.NavigateAsync(startPage(), ct))
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, openStartPage: open ?? (startPage is null ? null : async ct => await Cdp.NavigateAsync(startPage(), ct)))
{
// The virtual clock moves only in the pauses: a watchdog on it would never wait.
Watchdog = null,