«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

+2
View File
@@ -364,3 +364,5 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-16 | La pagina Browser toglie `?accesso=1` dall'indirizzo appena l'ha usato | Ricaricare la pagina, o riaprire la scheda, riapriva la pagina di accesso anche da collegati | | 2026-11-16 | La pagina Browser toglie `?accesso=1` dall'indirizzo appena l'ha usato | Ricaricare la pagina, o riaprire la scheda, riapriva la pagina di accesso anche da collegati |
| 2026-11-16 | `IBrowserWindow.ShowAsync` tolto: «Apri il browser» passa da `IConnectionService.ShowBrowserAsync(openLogin)` | Aprire la pagina iniziale richiede il permesso di guida e il turno della pagina, che tiene il servizio di collegamento | | 2026-11-16 | `IBrowserWindow.ShowAsync` tolto: «Apri il browser» passa da `IConnectionService.ShowBrowserAsync(openLogin)` | Aprire la pagina iniziale richiede il permesso di guida e il turno della pagina, che tiene il servizio di collegamento |
| 2026-11-16 | Con `--accesso-di-prova` il primo controllo della sessione all'avvio non segnala nulla (`RefreshAsync` con `mayReport: false`) | La sessione mancante è quella che l'accesso automatico sta per aprire, non una disconnessione | | 2026-11-16 | Con `--accesso-di-prova` il primo controllo della sessione all'avvio non segnala nulla (`RefreshAsync` con `mayReport: false`) | La sessione mancante è quella che l'accesso automatico sta per aprire, non una disconnessione |
| 2026-11-16 | «Pagina iniziale» vale finché dura il permesso di chi l'ha premuta: la finestra di Windows e la vista remota passano un gettone che si annulla con il loro permesso, e la connessione guarda di nuovo, con il turno della pagina in mano, che Alberto guidi ancora; senza turno rinuncia invece di prendere la pagina. Nella vista remota la pressione corre a parte, una per volta, e intanto clic e tasti si scartano | L'attesa (fine della sessione, turno della pagina) può durare mezzo minuto: Alberto poteva aver chiuso la finestra e Febe navigava senza permesso e fuori dal Governatore (regole 7 e 8); nella vista l'attesa nel ciclo di ricezione bloccava i comandi e poi li riversava sulla pagina nuova |
| 2026-11-16 | `Repaint` della finestra «Browser di Febe» chiede solo di ridisegnare (`RDW_INVALIDATE \| RDW_ALLCHILDREN`), senza `RDW_UPDATENOW` | Le finestre figlie sono del processo del browser di WebView2: un processo bloccato avrebbe fermato il thread dell'interfaccia in un ridisegno sincrono |
+3 -1
View File
@@ -71,7 +71,9 @@ Quando Febe non lo usa, il browser resta **a riposo su una pagina vuota**. Se lo
te la **pagina iniziale**: la home di Instagram se sei collegato, la pagina di accesso se non lo sei (o se Instagram ti te la **pagina iniziale**: la home di Instagram se sei collegato, la pagina di accesso se non lo sei (o se Instagram ti
ha scollegato). Se invece c'è già una pagina (per esempio quella di una verifica), la lascia com'è. «Pagina iniziale» ha scollegato). Se invece c'è già una pagina (per esempio quella di una verifica), la lascia com'è. «Pagina iniziale»
ci torna quando vuoi; se la barra dice «Il browser è a riposo su una pagina vuota», premilo. Se Febe sta finendo un ci torna quando vuoi; se la barra dice «Il browser è a riposo su una pagina vuota», premilo. Se Febe sta finendo un
lavoro nel browser, «Pagina iniziale» aspetta che finisca: può volerci qualche secondo. lavoro nel browser, «Pagina iniziale» aspetta che finisca: può volerci qualche secondo (nella vista remota, intanto,
clic e tasti non arrivano al browser). Se nel frattempo chiudi il browser, o se il lavoro dura troppo, non succede
nulla: premilo di nuovo.
Se lasci la pagina Browser, o la pagina Collegamento mentre accedi, senza premere «Ho finito» (un'altra pagina, la Se lasci la pagina Browser, o la pagina Collegamento mentre accedi, senza premere «Ho finito» (un'altra pagina, la
scheda chiusa o ricaricata): scheda chiusa o ricaricata):
+48 -4
View File
@@ -128,6 +128,12 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// </summary> /// </summary>
public TimeSpan DrivingGrace { get; set; } = TimeSpan.FromMinutes(2); public TimeSpan DrivingGrace { get; set; } = TimeSpan.FromMinutes(2);
/// <summary>
/// How long Alberto's page waits for its turn while a step of the profile search holds it (real time). Read at every
/// wait; tests shorten it.
/// </summary>
public TimeSpan PageTurnWait { get; set; } = TimeSpan.FromSeconds(15);
/// <summary>The engine, once it exists (it is built after the browser).</summary> /// <summary>The engine, once it exists (it is built after the browser).</summary>
public void AttachEngine(EngineHost engine) => _engine = engine ?? throw new ArgumentNullException(nameof(engine)); public void AttachEngine(EngineHost engine) => _engine = engine ?? throw new ArgumentNullException(nameof(engine));
@@ -212,6 +218,17 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// with the page's turn, so that no step of a session or of the profile search has its page swapped under it. Only /// with the page's turn, so that no step of a session or of the profile search has its page swapped under it. Only
/// while he is at the browser: otherwise the page is the engine's and nothing happens. /// while he is at the browser: otherwise the page is the engine's and nothing happens.
/// </summary> /// </summary>
/// <param name="ct">
/// Cancelled when the lease of whoever pressed the button ends (the window closed, the remote view closed): the press
/// is then forgotten, whatever it was waiting for.
/// </param>
/// <remarks>
/// The waits can last up to <see cref="PageTurnWait"/> and more: Alberto may have let go of the browser meanwhile, and
/// then the page is the engine's again (rules 7 and 8: no navigation without his lease, outside the Governor). So
/// right before navigating, with the page's turn in hand, it looks again: he still drives and the caller's lease still
/// holds. Without the page's turn (a step of the search kept it) nothing happens either: the page is not taken from
/// under the step.
/// </remarks>
public async Task OpenStartPageAsync(CancellationToken ct) public async Task OpenStartPageAsync(CancellationToken ct)
{ {
if (!_browser.IsAvailable) if (!_browser.IsAvailable)
@@ -219,7 +236,15 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
return; return;
} }
await _commands.WaitAsync(ct).ConfigureAwait(false); try
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
try try
{ {
if (!_browser.UserIsDriving) if (!_browser.UserIsDriving)
@@ -229,6 +254,20 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
await WaitForSessionEndAsync(ct).ConfigureAwait(false); await WaitForSessionEndAsync(ct).ConfigureAwait(false);
using var turn = await TakePageAsync(ct).ConfigureAwait(false); using var turn = await TakePageAsync(ct).ConfigureAwait(false);
if (_engine is not null && turn is null)
{
_log.Info("collegamento", "«Pagina iniziale» non aperta: la pagina è ancora occupata dalla ricerca dei profili. Riprova fra poco.");
return;
}
// The last look, with the page's turn in hand (no recipe and no search step can open a page until it is given
// back): Alberto still drives and the caller's lease still holds.
if (ct.IsCancellationRequested || !_browser.UserIsDriving)
{
_log.Info("collegamento", "«Pagina iniziale» non aperta: nel frattempo hai lasciato il browser.");
return;
}
var target = StartPageUrl; var target = StartPageUrl;
var what = target == _loginUrl ? "pagina di accesso" : "pagina iniziale del sito"; var what = target == _loginUrl ? "pagina di accesso" : "pagina iniziale del sito";
var result = await _browser.Cdp.NavigateAsync(target, ct).ConfigureAwait(false); var result = await _browser.Cdp.NavigateAsync(target, ct).ConfigureAwait(false);
@@ -236,6 +275,10 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
? $"«Pagina iniziale»: {what} aperta." ? $"«Pagina iniziale»: {what} aperta."
: $"«Pagina iniziale»: {what} non aperta (errore di rete del browser)."); : $"«Pagina iniziale»: {what} non aperta (errore di rete del browser).");
} }
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
_log.Info("collegamento", "«Pagina iniziale» non aperta: nel frattempo hai lasciato il browser.");
}
finally finally
{ {
_commands.Release(); _commands.Release();
@@ -686,8 +729,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
} }
/// <summary> /// <summary>
/// The page turn for Alberto's login page, so that no step of the profile search runs under it; after 15 seconds /// The page turn for Alberto's own navigation, so that no step of the profile search runs under it; null after
/// the page is taken anyway (Alberto asked for it), and null comes back. /// <see cref="PageTurnWait"/> (and always without an engine). The login and the start page from the rest page then
/// take the page anyway (Alberto asked for it, under his lease); «Pagina iniziale» gives up.
/// </summary> /// </summary>
private async Task<PageTurn?> TakePageAsync(CancellationToken ct) private async Task<PageTurn?> TakePageAsync(CancellationToken ct)
{ {
@@ -697,7 +741,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
} }
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct); using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
limit.CancelAfter(TimeSpan.FromSeconds(15)); limit.CancelAfter(PageTurnWait);
try try
{ {
return await engine.Services.PageTurns.TakeAsync(PageUser.Engine, limit.Token).ConfigureAwait(false); return await engine.Services.PageTurns.TakeAsync(PageUser.Engine, limit.Token).ConfigureAwait(false);
+24 -4
View File
@@ -95,6 +95,7 @@ internal sealed class WebView2Host : IBrowserHost
private CoreWebView2DevTools? _devTools; private CoreWebView2DevTools? _devTools;
private TaskCompletionSource? _exited; private TaskCompletionSource? _exited;
private IDisposable? _lease; private IDisposable? _lease;
private CancellationTokenSource? _leaseEnded;
private int _generation; private int _generation;
private bool _starting; private bool _starting;
private bool _crashedWhileStarting; private bool _crashedWhileStarting;
@@ -595,14 +596,21 @@ internal sealed class WebView2Host : IBrowserHost
} }
TakeLease(); TakeLease();
_ = OpenStartPageQuietlyAsync(open);
// The press lasts as long as this lease: closed meanwhile, the window gives the page back to the engine and the
// connection forgets the press (rules 7 and 8).
_ = OpenStartPageQuietlyAsync(open, _leaseEnded!.Token);
} }
private async Task OpenStartPageQuietlyAsync(Func<CancellationToken, Task> open) private async Task OpenStartPageQuietlyAsync(Func<CancellationToken, Task> open, CancellationToken whileLeased)
{ {
try try
{ {
await open(CancellationToken.None).ConfigureAwait(true); await open(whileLeased).ConfigureAwait(true);
}
catch (OperationCanceledException) when (whileLeased.IsCancellationRequested)
{
// The window went out of view before the start page could open: nothing to say.
} }
catch (Exception ex) when (ex is not OutOfMemoryException) catch (Exception ex) when (ex is not OutOfMemoryException)
{ {
@@ -646,7 +654,9 @@ internal sealed class WebView2Host : IBrowserHost
{ {
if (_window is { } window) if (_window is { } window)
{ {
Win32.RedrawWindow(window.Handle, IntPtr.Zero, IntPtr.Zero, Win32.RdwInvalidate | Win32.RdwAllChildren | Win32.RdwUpdateNow); // Only invalidated, never painted at once (RDW_UPDATENOW): the children belong to WebView2's browser process,
// and a hung one would hold the UI thread in a synchronous paint.
Win32.RedrawWindow(window.Handle, IntPtr.Zero, IntPtr.Zero, Win32.RdwInvalidate | Win32.RdwAllChildren);
} }
} }
@@ -688,6 +698,7 @@ internal sealed class WebView2Host : IBrowserHost
if (_lease is null) if (_lease is null)
{ {
_lease = UserDriving.Begin(); _lease = UserDriving.Begin();
_leaseEnded = new CancellationTokenSource();
_log.Info("browser", "Alberto usa il browser di Febe: il motore resta fermo."); _log.Info("browser", "Alberto usa il browser di Febe: il motore resta fermo.");
} }
@@ -701,6 +712,15 @@ internal sealed class WebView2Host : IBrowserHost
_lease = null; _lease = null;
_settings.MarkUsed(); _settings.MarkUsed();
lease.Dispose(); lease.Dispose();
// Off the UI thread: whatever waited on this lease (a «Pagina iniziale» in progress) gives up there. The source
// has no timer and is never disposed, so a late look at its token is still safe.
if (_leaseEnded is { } ended)
{
_leaseEnded = null;
_ = ended.CancelAsync();
}
_log.Info("browser", "Browser di Febe fuori vista."); _log.Info("browser", "Browser di Febe fuori vista.");
} }
} }
-1
View File
@@ -68,7 +68,6 @@ internal static class Win32
public const uint RdwInvalidate = 0x0001; public const uint RdwInvalidate = 0x0001;
public const uint RdwAllChildren = 0x0080; public const uint RdwAllChildren = 0x0080;
public const uint RdwUpdateNow = 0x0100;
/// <summary>DWMWA_CLOAK: the window stays shown for Windows but DWM does not put it on screen.</summary> /// <summary>DWMWA_CLOAK: the window stays shown for Windows but DWM does not put it on screen.</summary>
public const int DwmCloak = 13; public const int DwmCloak = 13;
+74 -9
View File
@@ -182,6 +182,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
private readonly RemoteViewSession _session; private readonly RemoteViewSession _session;
private readonly Func<CancellationToken, Task>? _openStartPage; private readonly Func<CancellationToken, Task>? _openStartPage;
private readonly ScreencastWatchdog? _watchdog; private readonly ScreencastWatchdog? _watchdog;
private readonly IBrowserLog _log;
private readonly Lock _gate = new(); private readonly Lock _gate = new();
private readonly Queue<RemoteViewMeta> _meta = new(); private readonly Queue<RemoteViewMeta> _meta = new();
private readonly SemaphoreSlim _signal = new(0, int.MaxValue); private readonly SemaphoreSlim _signal = new(0, int.MaxValue);
@@ -198,6 +199,8 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
private int _height; private int _height;
private int _disposed; private int _disposed;
private bool _used; private bool _used;
private int _startPagePending;
private Task _startPage = Task.CompletedTask;
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock, IBrowserLog log, Func<CancellationToken, Task>? openStartPage, ScreencastWatchdog? watchdog) public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock, IBrowserLog log, Func<CancellationToken, Task>? openStartPage, ScreencastWatchdog? watchdog)
{ {
@@ -207,6 +210,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
_clock = clock; _clock = clock;
_openStartPage = openStartPage; _openStartPage = openStartPage;
_watchdog = watchdog; _watchdog = watchdog;
_log = log;
// A real log (issue #52): the starts, restarts and silences of the frames reach the registro. // A real log (issue #52): the starts, restarts and silences of the frames reach the registro.
_session = new RemoteViewSession(browser.Cdp, browser.UserDriving, log, browserClock); _session = new RemoteViewSession(browser.Cdp, browser.UserDriving, log, browserClock);
@@ -216,6 +220,21 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
private ICdpSession Cdp => _browser.Cdp; private ICdpSession Cdp => _browser.Cdp;
/// <summary>True while a «Pagina iniziale» waits or loads: the input of the view is dropped meanwhile.</summary>
internal bool StartPagePending => Volatile.Read(ref _startPagePending) != 0;
/// <summary>The last «Pagina iniziale» of this view (a completed task before the first): tests wait on it.</summary>
internal Task StartPageOpening
{
get
{
lock (_gate)
{
return _startPage;
}
}
}
public async Task StartAsync(int width, int height, CancellationToken ct) public async Task StartAsync(int width, int height, CancellationToken ct)
{ {
_width = width; _width = width;
@@ -281,9 +300,11 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
public Task MouseAsync(RemoteViewMouse input, CancellationToken ct) public Task MouseAsync(RemoteViewMouse input, CancellationToken ct)
{ {
ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(input);
if (_session.Screencast.LastFrame is null) if (_session.Screencast.LastFrame is null || StartPagePending)
{ {
return Task.CompletedTask; // no frame yet: nothing on screen to point at // No frame yet: nothing on screen to point at. «Pagina iniziale» in progress: a click would land on the page
// about to go, or on the start page while it loads.
return Task.CompletedTask;
} }
MarkUsed(); MarkUsed();
@@ -307,6 +328,11 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
public Task KeyAsync(RemoteViewKey input, CancellationToken ct) public Task KeyAsync(RemoteViewKey input, CancellationToken ct)
{ {
ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(input);
if (StartPagePending)
{
return Task.CompletedTask; // as for the mouse: not typed into a page about to change
}
MarkUsed(); MarkUsed();
if (input.Action == RemoteViewKeyAction.Char) if (input.Action == RemoteViewKeyAction.Char)
{ {
@@ -321,16 +347,15 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
MarkUsed(); MarkUsed();
if (action == RemoteViewNavigation.Home) if (action == RemoteViewNavigation.Home)
{ {
// Alberto's own navigation (rule 7), done by the connection: like the start page opened from the rest page, OpenStartPage();
// it waits for the engine's session to end and takes the page's turn first.
if (_openStartPage is { } open)
{
await open(ct).ConfigureAwait(false);
}
return; return;
} }
if (StartPagePending)
{
return; // the start page is about to replace the page anyway
}
string? target; string? target;
lock (_gate) lock (_gate)
{ {
@@ -366,6 +391,46 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
await _session.NavigateAsync(target, ct).ConfigureAwait(false); await _session.NavigateAsync(target, ct).ConfigureAwait(false);
} }
/// <summary>
/// «Pagina iniziale»: Alberto's own navigation (rule 7), done by the connection — like the start page opened from the
/// rest page, it waits for the engine's session to end and takes the page's turn first, up to half a minute. So it runs
/// beside the view, not in its receive loop (the view would freeze meanwhile), for as long as the view and its lease
/// last; one at a time, and until it is done the view's input is dropped.
/// </summary>
private void OpenStartPage()
{
if (_openStartPage is not { } open || Interlocked.CompareExchange(ref _startPagePending, 1, 0) != 0)
{
return;
}
var task = Task.Run(() => OpenStartPageAsync(open), CancellationToken.None);
lock (_gate)
{
_startPage = task;
}
}
private async Task OpenStartPageAsync(Func<CancellationToken, Task> open)
{
try
{
await open(_ended.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (_ended.IsCancellationRequested)
{
// The view closed first: its lease is gone, the page is the engine's.
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log.Write(BrowserLogLevel.Warning, $"«Pagina iniziale» non aperta ({ex.GetType().Name}).");
}
finally
{
Volatile.Write(ref _startPagePending, 0);
}
}
/// <summary>Ends the view from the server side (another tab, shutdown): the page is told why.</summary> /// <summary>Ends the view from the server side (another tab, shutdown): the page is told why.</summary>
public async Task EndAsync(RemoteViewEnd reason) public async Task EndAsync(RemoteViewEnd reason)
{ {
+5 -1
View File
@@ -18,7 +18,11 @@ Lo usano due parti scritte in parallelo: non cambiarlo senza aggiornare entrambe
pagina di accesso. Aprirla, dal riposo o con il pulsante «Pagina iniziale» (barra della finestra di Windows, vista pagina di accesso. Aprirla, dal riposo o con il pulsante «Pagina iniziale» (barra della finestra di Windows, vista
remota), è un'azione di Alberto, sotto il suo permesso di guida (`UserIsDriving`), non del motore: Febe aspetta che la remota), è un'azione di Alberto, sotto il suo permesso di guida (`UserIsDriving`), non del motore: Febe aspetta che la
sessione del motore finisca, prende il turno della pagina (un passo della ricerca dei profili finisce prima) e solo sessione del motore finisca, prende il turno della pagina (un passo della ricerca dei profili finisce prima) e solo
dopo naviga. «Indietro», «Ricarica» e i clic nella pagina invece agiscono subito, come nel browser. La striscia rossa dopo naviga. La pressione del pulsante vale finché resta aperto chi l'ha premuta (la finestra sullo schermo, la vista
remota): se nel frattempo Alberto l'ha chiusa, o non guida più, o il turno della pagina non arriva entro 15 s, non
succede nulla. Nella vista remota l'attesa non ferma la vista: una pressione per volta, e finché non è finita i clic,
i tasti, «Indietro» e «Ricarica» si scartano (finirebbero sulla pagina che sta per cambiare). Fuori da quell'attesa
«Indietro», «Ricarica» e i clic nella pagina agiscono subito, come nel browser. La striscia rossa
di una disconnessione apre il browser con `openLogin: true` (in Docker la pagina Browser con `?accesso=1`). di una disconnessione apre il browser con `openLogin: true` (in Docker la pagina Browser con `?accesso=1`).
In modalità dimostrativa la scena `scollegato` dà `notConnected`, la scena `fermo` dà `verificationRequired`. In modalità dimostrativa la scena `scollegato` dà `notConnected`, la scena `fermo` dà `verificationRequired`.
@@ -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."); 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] [TestMethod]
[Timeout(120_000, CooperativeCancellation = true)] [Timeout(120_000, CooperativeCancellation = true)]
public async Task AMinimisedWindowKeepsAlbertoAtTheWheelUntilItIsMinimisedTooLong() 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 /// 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). /// does nothing (never the default login page of the options, which is Instagram's).
/// </param> /// </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 folder = new TestFolder(name);
var ui = await UiThread.StartAsync(); 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 options = new FebeAppOptions { DataFolder = data.Root, LibraryFolder = folder.Combine("libreria") };
var tracker = new BrowserUseTracker(); var tracker = new BrowserUseTracker();
WebView2Browser? built = null; 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 context = new FebePlatformContext(options, data, database, clock, log, tracker, openStartPage);
var settings = new WebView2BrowserSettings(data.BrowserProfile, 1280, 900, hosting, BrowserArguments.ForWebView2()); 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"); 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 int Navigations(FakeBrowser browser) => browser.FakeCdp.Methods.Count(m => m == "Page.navigate");
private static async Task BeginAsync(DesktopTestBed bed, bool openLogin) private static async Task BeginAsync(DesktopTestBed bed, bool openLogin)
@@ -239,6 +239,9 @@ internal sealed class FakeCdp : ICdpSession
public ConcurrentQueue<string> Methods { get; } = new(); 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> /// <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) public void Navigated(string url)
{ {
@@ -288,6 +291,7 @@ internal sealed class FakeCdp : ICdpSession
var url = (parameters as JsonObject)?["url"]?.GetValue<string>(); var url = (parameters as JsonObject)?["url"]?.GetValue<string>();
if (url is not null) if (url is not null)
{ {
Visited.Enqueue(url);
if (LogsInOnVisit is { } site && url.StartsWith(site, StringComparison.Ordinal)) if (LogsInOnVisit is { } site && url.StartsWith(site, StringComparison.Ordinal))
{ {
LoggedIn = true; LoggedIn = true;
@@ -142,17 +142,77 @@ public sealed class RemoteViewStartTests
var view = await bed.Host.OpenAsync(ct); var view = await bed.Host.OpenAsync(ct);
await view.NavigateAsync(RemoteViewNavigation.Home, 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"); Assert.AreEqual(start, bed.LastNavigation, "not connected: the login page");
// Connected meanwhile: the same button opens the site's home. // Connected meanwhile: the same button opens the site's home.
start = "http://127.0.0.1:8481/"; start = "http://127.0.0.1:8481/";
await view.NavigateAsync(RemoteViewNavigation.Home, ct); await view.NavigateAsync(RemoteViewNavigation.Home, ct);
await StartPageOf(view).WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.AreEqual(start, bed.LastNavigation); Assert.AreEqual(start, bed.LastNavigation);
Assert.AreEqual(2, bed.Cdp.Sent.Count(c => c.Method == "Page.navigate"), "Alberto's own navigations, one per press"); Assert.AreEqual(2, bed.Cdp.Sent.Count(c => c.Method == "Page.navigate"), "Alberto's own navigations, one per press");
await view.DisposeAsync(); 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] [TestMethod]
[Timeout(30_000, CooperativeCancellation = true)] [Timeout(30_000, CooperativeCancellation = true)]
public async Task WithoutAStartPageTheButtonDoesNothing() public async Task WithoutAStartPageTheButtonDoesNothing()
@@ -162,6 +222,7 @@ public sealed class RemoteViewStartTests
var view = await bed.Host.OpenAsync(ct); var view = await bed.Host.OpenAsync(ct);
await view.NavigateAsync(RemoteViewNavigation.Home, 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")); Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.navigate"));
await view.DisposeAsync(); await view.DisposeAsync();
@@ -191,6 +252,11 @@ public sealed class RemoteViewStartTests
await view.DisposeAsync(); 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() => private static CdpCommandException InactivePage() =>
new("Page.startScreencast", CdpCommandException.ServerErrorCode, CdpCommandException.InactivePageMessage); 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, /// Where «Pagina iniziale» goes, as the connection would open it (BrowserConnectionService.OpenStartPageAsync,
/// tested in BrowserStartPageTests); null: nowhere. /// tested in BrowserStartPageTests); null: nowhere.
/// </param> /// </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(); Clock = new VirtualClock();
_start = Clock.Now; _start = Clock.Now;
@@ -259,7 +326,7 @@ public sealed class RemoteViewStartTests
}; };
Browser = new PageBrowser(Cdp); Browser = new PageBrowser(Cdp);
_log = new FebeLog(null, null, Clock); _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. // The virtual clock moves only in the pauses: a watchdog on it would never wait.
Watchdog = null, Watchdog = null,