From 2bbad2e9b7b554f32e348b044e5ebd737c7d3798 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Mon, 16 Nov 2026 13:53:29 +0100 Subject: [PATCH] =?UTF-8?q?=C2=ABPagina=20iniziale=C2=BB=20solo=20finch?= =?UTF-8?q?=C3=A9=20Alberto=20guida,=20e=20la=20vista=20che=20non=20si=20b?= =?UTF-8?q?locca=20(#52)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/decisioni.md | 2 + docs/guida/Primo-collegamento.md | 4 +- src/Febe.App/BrowserConnectionService.cs | 52 +++++++++++- src/Febe.Desktop/Browser/WebView2Host.cs | 28 ++++++- src/Febe.Desktop/Native/Win32.cs | 1 - src/Febe.Server/BrowserRemoteView.cs | 83 +++++++++++++++++-- src/Febe.Web/Connection/PROTOCOLLO.md | 6 +- .../Febe.Tests.Windows/BrowserWindowTests.cs | 36 ++++++++ .../Febe.Tests.Windows/Support/BrowserBed.cs | 5 +- .../Desktop/BrowserStartPageTests.cs | 72 ++++++++++++++++ .../Desktop/Support/FakeDesktopShell.cs | 4 + .../Febe.Tests/Server/RemoteViewStartTests.cs | 71 +++++++++++++++- 12 files changed, 340 insertions(+), 24 deletions(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index fee79d0..64e78f0 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -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 | `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 | «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 | diff --git a/docs/guida/Primo-collegamento.md b/docs/guida/Primo-collegamento.md index b945a98..93abc81 100644 --- a/docs/guida/Primo-collegamento.md +++ b/docs/guida/Primo-collegamento.md @@ -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 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 -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 scheda chiusa o ricaricata): diff --git a/src/Febe.App/BrowserConnectionService.cs b/src/Febe.App/BrowserConnectionService.cs index 2966fc7..5b51947 100644 --- a/src/Febe.App/BrowserConnectionService.cs +++ b/src/Febe.App/BrowserConnectionService.cs @@ -128,6 +128,12 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa /// public TimeSpan DrivingGrace { get; set; } = TimeSpan.FromMinutes(2); + /// + /// 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. + /// + public TimeSpan PageTurnWait { get; set; } = TimeSpan.FromSeconds(15); + /// The engine, once it exists (it is built after the browser). 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 /// while he is at the browser: otherwise the page is the engine's and nothing happens. /// + /// + /// 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. + /// + /// + /// The waits can last up to 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. + /// public async Task OpenStartPageAsync(CancellationToken ct) { if (!_browser.IsAvailable) @@ -219,7 +236,15 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa return; } - await _commands.WaitAsync(ct).ConfigureAwait(false); + try + { + await _commands.WaitAsync(ct).ConfigureAwait(false); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return; + } + try { if (!_browser.UserIsDriving) @@ -229,6 +254,20 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa await WaitForSessionEndAsync(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 what = target == _loginUrl ? "pagina di accesso" : "pagina iniziale del sito"; 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} 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 { _commands.Release(); @@ -686,8 +729,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa } /// - /// The page turn for Alberto's login page, so that no step of the profile search runs under it; after 15 seconds - /// the page is taken anyway (Alberto asked for it), and null comes back. + /// The page turn for Alberto's own navigation, so that no step of the profile search runs under it; null after + /// (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. /// private async Task TakePageAsync(CancellationToken ct) { @@ -697,7 +741,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa } using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct); - limit.CancelAfter(TimeSpan.FromSeconds(15)); + limit.CancelAfter(PageTurnWait); try { return await engine.Services.PageTurns.TakeAsync(PageUser.Engine, limit.Token).ConfigureAwait(false); diff --git a/src/Febe.Desktop/Browser/WebView2Host.cs b/src/Febe.Desktop/Browser/WebView2Host.cs index 1980008..830ac43 100644 --- a/src/Febe.Desktop/Browser/WebView2Host.cs +++ b/src/Febe.Desktop/Browser/WebView2Host.cs @@ -95,6 +95,7 @@ internal sealed class WebView2Host : IBrowserHost private CoreWebView2DevTools? _devTools; private TaskCompletionSource? _exited; private IDisposable? _lease; + private CancellationTokenSource? _leaseEnded; private int _generation; private bool _starting; private bool _crashedWhileStarting; @@ -595,14 +596,21 @@ internal sealed class WebView2Host : IBrowserHost } 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 open) + private async Task OpenStartPageQuietlyAsync(Func open, CancellationToken whileLeased) { 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) { @@ -646,7 +654,9 @@ internal sealed class WebView2Host : IBrowserHost { 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) { _lease = UserDriving.Begin(); + _leaseEnded = new CancellationTokenSource(); _log.Info("browser", "Alberto usa il browser di Febe: il motore resta fermo."); } @@ -701,6 +712,15 @@ internal sealed class WebView2Host : IBrowserHost _lease = null; _settings.MarkUsed(); 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."); } } diff --git a/src/Febe.Desktop/Native/Win32.cs b/src/Febe.Desktop/Native/Win32.cs index e08b11c..048183f 100644 --- a/src/Febe.Desktop/Native/Win32.cs +++ b/src/Febe.Desktop/Native/Win32.cs @@ -68,7 +68,6 @@ internal static class Win32 public const uint RdwInvalidate = 0x0001; public const uint RdwAllChildren = 0x0080; - public const uint RdwUpdateNow = 0x0100; /// DWMWA_CLOAK: the window stays shown for Windows but DWM does not put it on screen. public const int DwmCloak = 13; diff --git a/src/Febe.Server/BrowserRemoteView.cs b/src/Febe.Server/BrowserRemoteView.cs index 5aa4203..451d37e 100644 --- a/src/Febe.Server/BrowserRemoteView.cs +++ b/src/Febe.Server/BrowserRemoteView.cs @@ -182,6 +182,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection private readonly RemoteViewSession _session; private readonly Func? _openStartPage; private readonly ScreencastWatchdog? _watchdog; + private readonly IBrowserLog _log; private readonly Lock _gate = new(); private readonly Queue _meta = new(); private readonly SemaphoreSlim _signal = new(0, int.MaxValue); @@ -198,6 +199,8 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection private int _height; private int _disposed; 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? openStartPage, ScreencastWatchdog? watchdog) { @@ -207,6 +210,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection _clock = clock; _openStartPage = openStartPage; _watchdog = watchdog; + _log = log; // 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); @@ -216,6 +220,21 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection private ICdpSession Cdp => _browser.Cdp; + /// True while a «Pagina iniziale» waits or loads: the input of the view is dropped meanwhile. + internal bool StartPagePending => Volatile.Read(ref _startPagePending) != 0; + + /// The last «Pagina iniziale» of this view (a completed task before the first): tests wait on it. + internal Task StartPageOpening + { + get + { + lock (_gate) + { + return _startPage; + } + } + } + public async Task StartAsync(int width, int height, CancellationToken ct) { _width = width; @@ -281,9 +300,11 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection public Task MouseAsync(RemoteViewMouse input, CancellationToken ct) { 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(); @@ -307,6 +328,11 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection public Task KeyAsync(RemoteViewKey input, CancellationToken ct) { ArgumentNullException.ThrowIfNull(input); + if (StartPagePending) + { + return Task.CompletedTask; // as for the mouse: not typed into a page about to change + } + MarkUsed(); if (input.Action == RemoteViewKeyAction.Char) { @@ -321,16 +347,15 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection MarkUsed(); if (action == RemoteViewNavigation.Home) { - // 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. - if (_openStartPage is { } open) - { - await open(ct).ConfigureAwait(false); - } - + OpenStartPage(); return; } + if (StartPagePending) + { + return; // the start page is about to replace the page anyway + } + string? target; lock (_gate) { @@ -366,6 +391,46 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection await _session.NavigateAsync(target, ct).ConfigureAwait(false); } + /// + /// «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. + /// + 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 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); + } + } + /// Ends the view from the server side (another tab, shutdown): the page is told why. public async Task EndAsync(RemoteViewEnd reason) { diff --git a/src/Febe.Web/Connection/PROTOCOLLO.md b/src/Febe.Web/Connection/PROTOCOLLO.md index 911d85a..b67224e 100644 --- a/src/Febe.Web/Connection/PROTOCOLLO.md +++ b/src/Febe.Web/Connection/PROTOCOLLO.md @@ -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 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 -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`). In modalità dimostrativa la scena `scollegato` dà `notConnected`, la scena `fermo` dà `verificationRequired`. diff --git a/tests/Febe.Tests.Windows/BrowserWindowTests.cs b/tests/Febe.Tests.Windows/BrowserWindowTests.cs index 6c63d20..41631cd 100644 --- a/tests/Febe.Tests.Windows/BrowserWindowTests.cs +++ b/tests/Febe.Tests.Windows/BrowserWindowTests.cs @@ -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(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() diff --git a/tests/Febe.Tests.Windows/Support/BrowserBed.cs b/tests/Febe.Tests.Windows/Support/BrowserBed.cs index e3f6c2d..03f3928 100644 --- a/tests/Febe.Tests.Windows/Support/BrowserBed.cs +++ b/tests/Febe.Tests.Windows/Support/BrowserBed.cs @@ -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). /// - public static async Task CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window, Func? startPage = null) + /// What «Pagina iniziale» does instead (it wins over ). + public static async Task CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window, Func? startPage = null, Func? 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? 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()); diff --git a/tests/Febe.Tests/Desktop/BrowserStartPageTests.cs b/tests/Febe.Tests/Desktop/BrowserStartPageTests.cs index 74a7cc7..c34947f 100644 --- a/tests/Febe.Tests/Desktop/BrowserStartPageTests.cs +++ b/tests/Febe.Tests/Desktop/BrowserStartPageTests.cs @@ -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) diff --git a/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs b/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs index 49bc08e..155010b 100644 --- a/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs +++ b/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs @@ -239,6 +239,9 @@ internal sealed class FakeCdp : ICdpSession public ConcurrentQueue Methods { get; } = new(); + /// Every address a Page.navigate asked for, in order. + public ConcurrentQueue Visited { get; } = new(); + /// The main frame moved to by itself (a redirect of the site), not by a command. public void Navigated(string url) { @@ -288,6 +291,7 @@ internal sealed class FakeCdp : ICdpSession var url = (parameters as JsonObject)?["url"]?.GetValue(); if (url is not null) { + Visited.Enqueue(url); if (LogsInOnVisit is { } site && url.StartsWith(site, StringComparison.Ordinal)) { LoggedIn = true; diff --git a/tests/Febe.Tests/Server/RemoteViewStartTests.cs b/tests/Febe.Tests/Server/RemoteViewStartTests.cs index cfe0454..c105d67 100644 --- a/tests/Febe.Tests/Server/RemoteViewStartTests.cs +++ b/tests/Febe.Tests/Server/RemoteViewStartTests.cs @@ -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(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. /// - public Bed(Func startFailure, Func? startPage = null) + /// What «Pagina iniziale» does instead (it wins over ). + public Bed(Func startFailure, Func? startPage = null, Func? 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,