Compare commits

5 Commits
Author SHA1 Message Date
Alby96andClaude Opus 5.5 2acb264346 Documenti: #67 fatto, e la correzione del riposo del motore
verifica / controlli (push) Successful in 16s
verifica / prove (push) Successful in 18m15s
verifica / installatore (push) Successful in 2m6s
verifica / immagine (push) Successful in 16m31s
La riga di decisioni.md su #67 descrive ora come è costruita l'attesa
(10 s, una domanda ogni 200 ms, poi la pagina di accesso); una riga nuova
spiega perché il motore non rimette a riposo la pagina appena ripresa da
Alberto. In stato.md esce il «Rimandato» di #67 ed entra la finestra
stretta che resta.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 16:00:44 +01:00
Alby96 550ae8607f Merge remote-tracking branch 'origin/main' into correzione/browser-senza-risposta 2026-11-29 15:58:32 +01:00
Alby96andClaude Opus 5.5 98769b5870 Correzione: il motore non rimette a riposo la pagina che Alberto ha appena ripreso
verifica / controlli (push) Successful in 28s
verifica / prove (push) Failing after 39m9s
verifica / installatore (push) Skipped
verifica / immagine (push) Skipped
Le prove di BrowserStartPageTests fallivano a volte (pagina «about:blank» invece
della pagina iniziale, o la pagina iniziale invece di quella aperta da Alberto).
Non era l'attesa del browser di #67: la stessa corsa si vede anche con il codice
di main. Dopo «Ho finito» il giro del motore vede che Alberto ha lasciato il
browser e chiede il turno della pagina per il riposo; se nel frattempo Alberto
riprende il browser e la sua navigazione prende il turno per prima, il riposo
arriva subito dopo e gli porta via la pagina (una finestra bianca, #52).

Ora il riposo dopo la guida e quello di fine sessione guardano di nuovo, con il
turno in mano, se Alberto guida (o se una verifica tiene la pagina), come fa già
la ricerca dei profili; il riposo resta dovuto per quando lascia il browser.
Nuova prova deterministica in EngineHostTests.

Il motore conta come avviato già in StartAsync, non solo quando il pool di
thread arriva al suo giro: «Scollega» che fallisce lo dice subito (l'altra prova
che falliva a volte, DesktopCompositionTests).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 13:26:58 +01:00
Alby96andClaude Opus 5.5 8d1b344366 Revisione: il browser che non risponde nemmeno alla navigazione viene comunque in primo piano (#67)
verifica / controlli (push) Successful in 18s
verifica / prove (push) Successful in 18m26s
verifica / installatore (push) Canceled after 0s
verifica / immagine (push) Canceled after 0s
Con la correzione #67 un browser che resta muto per tutta l'attesa conta come a riposo, e Febe prova ad aprire la
pagina iniziale. Un browser che si sta ancora riavviando dopo «Scollega» rifiuta però anche Page.navigate: l'errore
risaliva fino all'API e Alberto vedeva, dopo dieci secondi, un errore interno al posto della finestra. Ora quella
navigazione mancata si annota nel registro («non aperta (il browser non risponde)») e la finestra viene in primo
piano come prima. Nuova prova con un browser che non risponde a nulla, per «Usa il browser» e «Apri il browser».

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:28:37 +01:00
Alby96andClaude Opus 5.5 8edb706e06 Correzione: il browser che non risponde ancora si aspetta, poi si apre l'accesso (#67)
verifica / controlli (push) Successful in 19s
verifica / prove (push) Successful in 20m6s
verifica / installatore (push) Successful in 2m10s
verifica / immagine (push) Canceled after 0s
Subito dopo «Scollega» il browser riparte con il profilo vuoto e, sotto carico,
può non dire ancora quale pagina mostra. Febe prendeva l'indirizzo sconosciuto
per una pagina di Alberto e lasciava la finestra bianca (about:blank), contro
la #52. Decisione di Alberto del 29 novembre 2026: quando l'indirizzo è
sconosciuto si richiede al browser ogni 200 ms, al massimo per 10 secondi
(AddressWait); se resta muto la pagina conta come quella di riposo e si apre
la pagina iniziale (l'accesso, senza sessione). Una pagina nota che Alberto
usa non si tocca mai; l'attesa finisce con la richiesta.

Il finto browser delle prove può restare muto (Silent): quattro prove nuove
per la risposta tardiva, il silenzio oltre l'attesa, la pagina di Alberto
lasciata com'è e l'annullamento durante l'attesa.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 11:57:57 +01:00
7 changed files with 311 additions and 9 deletions

No files matched your search

+2 -1
View File
@@ -659,4 +659,5 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-28 | Seconda revisione della tappa E3, fotogrammi: i tempi di `WriteStall` dello zip passano da un `TimeProvider` della BCL (`FrameService.StallTime`, di serie quello di sistema); la prova del lettore lento usa un `TimeProvider` scritto nella prova che avanza solo quando il collegamento finto manda un pezzo. | La prova dipendeva da orologi veri con 250 ms di margine e poteva cadere su un esecutore carico della CI; ora non dipende dal carico. Nessun pacchetto esterno. |
| 2026-11-29 | **Confermate le risposte proposte delle domande 19–38 di §16**, che le tappe D1, S4b, E2 ed E3 avevano già adottato: D1 (19 e 21) le raccolte in evidenza subito dopo le storie nell'ordine predefinito e il posto su otto della coda al file che aspetta da più tempo, senza quote per tipo; S4b (20) i 5 secondi di grazia prima che lasciare la pagina del browser in Docker copi la sessione; E2 (22–27) «Esporta questo account» spento salta anche le copie a mano, `/esporta` attiva su un montaggio in `/esporta` o sotto, «Automatica» nascosta fino a E5, «Copia di nuovo anche i N tolti o superati» spenta all'apertura, conteggi e segni sui soli file dovuti, margine di 64 MB; E3 (28–38) «già copiato» guarda il file e non il formato, «Solo i nuovi» per la conversione della libreria, i convertiti nel visualizzatore, CMYK e più di 8 bit copiati come sono verso PNG/WEBP, nomi, istanti e limiti dei fotogrammi, zip, PNG per i fotogrammi, WEBP con perdita copiato byte per byte, i convertiti riconosciuti «già in libreria» all'importazione. La riga di ogni domanda dice la risposta (§16) e i paragrafi che le citavano come proposte ora la citano come risposta | Risposta di Alberto del 29 novembre 2026: «Le confermo tutte». Nulla cambia nel codice: le tappe facevano già così |
| 2026-11-29 | Commenti in inglese anche negli script di shell di `.gitea/scripts/` e `installer/`, nei blocchi `run:` dei flussi di `.gitea/workflows/` e in `docker/entrypoint.sh`; restano in italiano i messaggi che una persona legge (`echo`, `::warning::`/`::error::`, nomi dei passi, note della release, istruzioni d'uso), come nel resto del codice. Decisione di Alberto (#43) | La regola «codice e commenti in inglese; interfaccia, documenti e messaggi in italiano» vale per tutto il repository, script compresi: nessuna eccezione per la CI |
| 2026-11-29 | **Subito dopo «Scollega», con l'indirizzo della pagina sconosciuto** (il browser non risponde ancora, `FullUrlAsync` dà `null`), Febe aspetta che il browser risponda, entro un limite; se ancora non risponde apre la pagina di accesso (#67). È la sola decisione: da fare, il codice oggi non aspetta (`OpenForAlbertoAsync` scrive «Alberto usa il browser» e non apre nulla; `docs/stato.md`, «Rimandato») | Decisione di Alberto del 29 novembre 2026: senza sapere quale pagina mostra il browser non si può dire se è già quella di accesso; aspettare un poco evita di ricaricare una pagina che sta arrivando, e il limite evita di restare fermi |
| 2026-11-29 | **Subito dopo «Scollega», con l'indirizzo della pagina sconosciuto** (il browser non risponde ancora, `FullUrlAsync` dà `null`), Febe aspetta che il browser risponda, entro un limite; se ancora non risponde apre la pagina di accesso (#67). Fatto così: `BrowserConnectionService` chiede l'indirizzo ogni 200 ms (`AddressPoll`, con `IClock`) per al più 10 s (`AddressWait`), poi apre la pagina di accesso o d'inizio; se anche la navigazione non riesce, la finestra resta su e il registro dice «Alberto usa il browser: … non aperta (il browser non risponde).» | Decisione di Alberto del 29 novembre 2026: senza sapere quale pagina mostra il browser non si può dire se è già quella di accesso; aspettare un poco evita di ricaricare una pagina che sta arrivando, e il limite evita di restare fermi |
| 2026-11-29 | **Il motore non rimette a riposo la pagina che Alberto ha appena ripreso**: a fine sessione e dopo la guida di Alberto il riposo (`about:blank`) si dà solo se, ottenuto il turno, Alberto non guida il browser e l'interruttore non è su Verifica o Scollegato (`KeepsPageAfterWaitingForTurn`); `IsRunning` si accende in `StartAsync` prima di avviare il lavoro | Le prove del desktop su #67 cadevano a volte: fra il controllo e il turno Alberto poteva riprendere il browser, e il motore gli toglieva la pagina. Resta una finestra stretta fra il turno e la navigazione, scritta in `docs/stato.md` |
+3 -3
View File
@@ -776,13 +776,13 @@ protezione di `main` sono in `docs/processo.md`.
- Un solo timeout di `OpenAsync` all'apertura di `/browser` (`AfterHoFinitoLeavingTheBrowserPageChangesNothingMore`) in
migliaia di esecuzioni delle prove d'interfaccia, senza causa trovata. Se ricompare nella CI, va fatto dire a
`OpenAsync` quale condizione mancava.
- #67, motore: il riposo della pagina (`about:blank`) si dà solo se, ottenuto il turno, Alberto non guida il browser;
resta una finestra stretta fra quel controllo e la navigazione, in cui Alberto può riprendere il browser e vedere
comunque la pagina vuota. Non chiusa: servirebbe che la presa del browser da parte di Alberto passasse dal turno.
- Su questo PC Febe ha avvisato «Disco quasi pieno»: libreria e dati stanno su C:, dove restano circa 12 GB.
## Rimandato, e perché
- #67: deciso il 29 novembre 2026 (subito dopo «Scollega», con l'indirizzo della pagina sconosciuto, aspettare il
browser entro un limite, poi la pagina di accesso), non ancora fatto: oggi Febe scrive «Alberto usa il browser» e non
apre nulla. Da fare in un ramo a parte, con la sua prova.
- Via `HttpClient` verso il CDN (§6.5 punto 3): dipende da H7.
- Riconoscitore di 4K Stogram vero e lettura di `stogram.sqlite`: servono i nomi veri dei file (domanda 4).
- M9 (desktop collegato a un Febe remoto, seconda lingua): facoltativa.
+74 -4
View File
@@ -189,6 +189,17 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// </summary>
public TimeSpan PageTurnWait { get; set; } = TimeSpan.FromSeconds(15);
/// <summary>
/// How long Alberto's first navigation waits, at most, for the browser to say which page it shows when it does not
/// answer (real time): right after «Scollega» it has just restarted with an empty profile and may not answer yet.
/// After it the page counts as the rest page, and the start page opens (issue #67, decision of 29 November 2026):
/// never a white window (issue #52). Read at every wait; tests shorten it.
/// </summary>
public TimeSpan AddressWait { get; set; } = TimeSpan.FromSeconds(10);
/// <summary>How often the wait of <see cref="AddressWait"/> asks the browser again.</summary>
private static readonly TimeSpan AddressPoll = TimeSpan.FromMilliseconds(200);
/// <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));
@@ -1083,15 +1094,24 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// <summary>
/// Alberto's own first navigation (rule 7: not an engine action, no Governor), under his lease: the login page when
/// asked for, and the start page when the browser rests on the empty page (issue #52). Any other page stays as it is
/// — the one he was using, or the verification page of a stop.
/// — the one he was using, or the verification page of a stop. A browser that does not say its page is waited for,
/// up to <see cref="AddressWait"/>; still silent, its page counts as the rest page (issue #67).
/// </summary>
private async Task OpenForAlbertoAsync(bool openLogin, CancellationToken ct)
{
if (!openLogin && !IsRest(await FullUrlAsync(ct).ConfigureAwait(false)))
// A known address that is not the rest page is a page Alberto uses: never touched. An unknown one (the browser
// still silent after the wait) is the rest page.
var answered = true;
if (!openLogin)
{
var first = await AwaitFullUrlAsync(ct).ConfigureAwait(false);
answered = first is not null;
if (answered && !IsRest(first))
{
_log.Info("collegamento", "Alberto usa il browser.");
return;
}
}
// The engine ends its session when the lease starts; wait for it before taking the page. A search step in
// progress (issue #37) stops at its next check of the lease: Alberto's page waits for its turn.
@@ -1104,7 +1124,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
target = _loginUrl;
what = "pagina di accesso";
}
else if (IsRest(await FullUrlAsync(ct).ConfigureAwait(false)))
else if (await IsAtRestAsync(wait: answered, ct).ConfigureAwait(false))
{
target = StartPageUrl;
what = target == _loginUrl ? "era a riposo, pagina di accesso" : "era a riposo, pagina iniziale del sito";
@@ -1116,7 +1136,19 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
return;
}
var result = await _browser.Cdp.NavigateAsync(target, ct).ConfigureAwait(false);
// A browser still silent (restarting after «Scollega», issue #67) usually refuses the navigation too: the window
// comes to the front all the same, as when its page was unknown before, never an internal error.
NavigationResult result;
try
{
result = await _browser.Cdp.NavigateAsync(target, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
_log.Info("collegamento", $"Alberto usa il browser: {what} non aperta (il browser non risponde).");
return;
}
_log.Info("collegamento", result.Succeeded
? $"Alberto usa il browser: {what} aperta."
: $"Alberto usa il browser: {what} non aperta (errore di rete del browser).");
@@ -1267,6 +1299,44 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
/// <summary>
/// The address of the main frame as <see cref="FullUrlAsync"/> gives it, but a browser that does not answer is asked
/// again every <see cref="AddressPoll"/> until it does, for at most <see cref="AddressWait"/> (real time, issue #67);
/// null when it stayed silent. Cancelled with <paramref name="ct"/>.
/// </summary>
private async Task<string?> AwaitFullUrlAsync(CancellationToken ct)
{
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
limit.CancelAfter(AddressWait);
try
{
while (true)
{
if (await FullUrlAsync(limit.Token).ConfigureAwait(false) is { } url)
{
return url;
}
await _clock.Delay(AddressPoll, limit.Token).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
_log.Info("collegamento", "Il browser non ha indicato la pagina in tempo: la pagina conta come quella di riposo.");
return null;
}
}
/// <summary>
/// After the engine's session ended: whether the page is the rest page (or still unknown). A browser that already let
/// <see cref="AddressWait"/> pass is asked once more (<paramref name="wait"/> false), not waited for again.
/// </summary>
private async Task<bool> IsAtRestAsync(bool wait, CancellationToken ct)
{
var url = wait ? await AwaitFullUrlAsync(ct).ConfigureAwait(false) : await FullUrlAsync(ct).ConfigureAwait(false);
return url is null || IsRest(url);
}
private async Task WaitForSessionEndAsync(CancellationToken ct)
{
if (_engine is not { } engine)
+30 -1
View File
@@ -74,7 +74,10 @@ public sealed class EngineHost : IAsyncDisposable
internal IReadOnlyList<RecentAction> RecentActions(int limit) => _recent.Snapshot(limit);
/// <summary>Starts the background loop.</summary>
/// <summary>
/// Starts the background loop. It counts as running from here (<see cref="EngineRuntime.IsRunning"/>), not only once
/// the thread pool gets to it: whoever started it (Febe's start, «Scollega») says so right away.
/// </summary>
public Task StartAsync(CancellationToken ct = default)
{
lock (_gate)
@@ -86,6 +89,7 @@ public sealed class EngineHost : IAsyncDisposable
_loopCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
var token = _loopCts.Token;
_s.Runtime.IsRunning = true;
_loop = Task.Run(() => RunAsync(token), CancellationToken.None);
}
@@ -738,10 +742,13 @@ public sealed class EngineHost : IAsyncDisposable
await using (turn.ConfigureAwait(false))
{
try
{
if (!KeepsPageAfterWaitingForTurn())
{
await _runner.RestAsync(ct).ConfigureAwait(false);
s.PageTurns.NoteRested();
}
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
await s.Events.WriteAsync(
@@ -797,6 +804,23 @@ public sealed class EngineHost : IAsyncDisposable
s.Events.Publish(EngineNotificationKind.StateChanged);
}
/// <summary>
/// Looked at again with the page turn in hand, right before a rest of the engine: the turn may have come only after
/// Alberto's own navigation, which takes it too (he took the browser again right after letting go of it), or after a
/// verification. Then the page is his, or must stay as it is (spec §6.1, §7.6): no rest, and the rest is owed for
/// when he lets go. The profile search looks again in the same way before its own rest.
/// </summary>
private bool KeepsPageAfterWaitingForTurn()
{
if (_s.Runtime.UserIsDriving)
{
Volatile.Write(ref _restAfterDriving, 1);
return true;
}
return _s.Breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected;
}
/// <summary>
/// Alberto let go of the browser and no session runs: the page goes back to rest (spec §6.1), so that nothing he or a
/// cancelled session left open stays on the site — a story viewer moves on by itself to other accounts (§6.3).
@@ -821,6 +845,11 @@ public sealed class EngineHost : IAsyncDisposable
await using (turn.ConfigureAwait(false))
{
if (KeepsPageAfterWaitingForTurn())
{
return;
}
await _runner.RestAsync(ct).ConfigureAwait(false);
_s.PageTurns.NoteRested();
}
@@ -54,6 +54,128 @@ public sealed class BrowserStartPageTests
Assert.IsTrue(status.GetProperty("userIsDriving").GetBoolean());
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ABrowserThatDoesNotAnswerYetIsWaitedForAndThenOpensTheLogin()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
// Just restarted (after «Scollega», issue #67): the browser does not say its page yet. Febe asks again and waits.
browser.FakeCdp.Silent = true;
var asked = browser.FakeCdp.SilentAnswers;
var begin = BeginAsync(bed, openLogin: false);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.SilentAnswers >= asked + 3, TimeSpan.FromSeconds(5), "le domande ripetute al browser che non risponde");
Assert.IsFalse(begin.IsCompleted, "still waiting for the browser");
Assert.DoesNotContain(Login, browser.FakeCdp.Visited);
// It answers, on the empty rest page: the login page, never a white window (issue #52).
browser.FakeCdp.Silent = false;
await begin.WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.AreEqual(Login, browser.FakeCdp.Url);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ABrowserSilentBeyondTheWaitCountsAsAtRestAndOpensTheLogin()
{
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.AddressWait = TimeSpan.FromMilliseconds(400);
browser.FakeCdp.Silent = true;
var watch = System.Diagnostics.Stopwatch.StartNew();
await BeginAsync(bed, openLogin: false);
watch.Stop();
Assert.IsGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(350), watch.Elapsed, "it waited for the browser first");
Assert.AreEqual(Login, browser.FakeCdp.Url, "still silent: the rest page, and the login opens");
Assert.AreEqual(1, browser.FakeCdp.Visited.Count(v => v == Login));
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ABrowserThatAnswersLateWithAPageOfAlbertosLeavesItAlone()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
var navigations = Navigations(browser);
browser.FakeCdp.Silent = true;
var asked = browser.FakeCdp.SilentAnswers;
var begin = BeginAsync(bed, openLogin: false);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.SilentAnswers >= asked + 2, TimeSpan.FromSeconds(5), "le domande ripetute al browser che non risponde");
browser.FakeCdp.Silent = false;
await begin.WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.AreEqual("https://www.instagram.com/marta.prova/", browser.FakeCdp.Url);
Assert.AreEqual(navigations, Navigations(browser), "no navigation of his page");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheWaitForASilentBrowserEndsWithTheRequest()
{
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 navigations = Navigations(browser);
browser.FakeCdp.Silent = true;
var asked = browser.FakeCdp.SilentAnswers;
using var request = new CancellationTokenSource();
var begin = connection.BeginUserDrivingAsync(openLogin: false, request.Token);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.SilentAnswers >= asked + 2, TimeSpan.FromSeconds(5), "le domande ripetute al browser che non risponde");
await request.CancelAsync();
await Assert.ThrowsAsync<OperationCanceledException>(() => begin.WaitAsync(TimeSpan.FromSeconds(10), ct));
Assert.AreEqual(navigations, Navigations(browser), "nothing opened after the request went away");
Assert.AreEqual("about:blank", browser.FakeCdp.Url);
// The commands of the connection are free again: the next request, with the browser answering, opens the login.
browser.FakeCdp.Silent = false;
await BeginAsync(bed, openLogin: false);
Assert.AreEqual(Login, browser.FakeCdp.Url);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ABrowserThatAnswersNothingStillComesToTheFrontWithoutAnError()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
bed.App.Connection!.AddressWait = TimeSpan.FromMilliseconds(300);
// Still restarting (issue #67): no page and no navigation either. The window comes all the same, never a 500.
browser.FakeCdp.Silent = true;
browser.FakeCdp.RefusesNavigation = true;
var shown = browser.Shown;
await BeginAsync(bed, openLogin: false);
Assert.AreEqual(shown + 1, browser.Shown, "«Usa il browser»: the window came to the front");
var result = await bed.JsonAsync(HttpMethod.Post, "/api/browser/show");
StringAssert.Contains(result.GetProperty("message").GetString(), "primo piano");
Assert.AreEqual(shown + 2, browser.Shown, "«Apri il browser»: the window came to the front");
Assert.AreEqual("about:blank", browser.FakeCdp.Url, "nothing could open");
Assert.DoesNotContain(Login, browser.FakeCdp.Visited);
browser.FakeCdp.Silent = false;
browser.FakeCdp.RefusesNavigation = false;
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ApriIlBrowserBringsTheWindowWithItsStartPageAndTheLoginAfterADisconnection()
@@ -263,6 +263,9 @@ internal sealed class FakeCdp : ICdpSession
private readonly Dictionary<string, List<Action<JsonElement>>> _handlers = new(StringComparer.Ordinal);
private int _captureReads;
private int _cookieReads;
private bool _silent;
private int _silentAnswers;
private bool _refusesNavigation;
public bool LoggedIn { get; set; }
@@ -313,6 +316,29 @@ internal sealed class FakeCdp : ICdpSession
public string Url { get; private set; } = "about:blank";
/// <summary>
/// While true the page does not say where it is, like a browser that has just restarted and does not answer yet
/// (issue #67): <c>Page.getFrameTree</c> fails as a closed connection, and is counted in <see cref="SilentAnswers"/>.
/// </summary>
public bool Silent
{
get => Volatile.Read(ref _silent);
set => Volatile.Write(ref _silent, value);
}
/// <summary>How many times <c>Page.getFrameTree</c> was asked while <see cref="Silent"/>.</summary>
public int SilentAnswers => Volatile.Read(ref _silentAnswers);
/// <summary>
/// While true <c>Page.navigate</c> fails as a closed connection too, like a browser that has not finished restarting
/// (issue #67): with <see cref="Silent"/>, a browser that answers nothing at all.
/// </summary>
public bool RefusesNavigation
{
get => Volatile.Read(ref _refusesNavigation);
set => Volatile.Write(ref _refusesNavigation, value);
}
public ConcurrentQueue<string> Methods { get; } = new();
/// <summary>Every address a <c>Page.navigate</c> asked for, in order.</summary>
@@ -329,6 +355,17 @@ internal sealed class FakeCdp : ICdpSession
{
CdpCommandPolicy.EnsureAllowed(method);
Methods.Enqueue(method);
if (method == "Page.getFrameTree" && Silent)
{
Interlocked.Increment(ref _silentAnswers);
return Task.FromException<JsonElement>(new CdpDisconnectedException());
}
if (method == "Page.navigate" && RefusesNavigation)
{
return Task.FromException<JsonElement>(new CdpDisconnectedException());
}
JsonNode result = method switch
{
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = Url } } },
@@ -519,6 +519,49 @@ public sealed class EngineHostTests
Assert.AreEqual(restsWhenTaken + 1, runner.Rests, "The verification page is left as it is.");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ARestThatGetsThePageOnlyAfterAlbertoTookTheBrowserAgainLeavesHisPage()
{
var driving = false;
await using var bed = await EngineTestBed.CreateAsync(Morning, userIsDriving: () => driving);
await bed.AddAccountAsync("uno.demo", followed: true);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
var host = bed.Start(runner);
await host.PauseAsync();
driving = true;
host.NotifyUserDrivingChanged();
await bed.RunForAsync(TimeSpan.FromSeconds(1));
var rests = runner.Rests;
// He lets go while his own navigation still holds the page (the turn of «Usa il browser»): the rest waits for it.
var turns = bed.Services.PageTurns;
var albertos = await turns.TakeAsync(PageUser.Engine, CancellationToken.None);
driving = false;
host.NotifyUserDrivingChanged();
// Real time: the loop, woken, waits for the turn and for no timer of the virtual clock.
var watch = System.Diagnostics.Stopwatch.StartNew();
while (!turns.IsWaiting(PageUser.Engine))
{
Assert.IsLessThan(TimeSpan.FromSeconds(10), watch.Elapsed, "the rest waits for the page turn");
await Task.Delay(TimeSpan.FromMilliseconds(10));
}
// He takes the browser again and his page opens before the rest gets the turn: the page is his, not rested.
driving = true;
host.NotifyUserDrivingChanged();
albertos.Dispose();
await bed.RunForAsync(TimeSpan.FromSeconds(1));
Assert.AreEqual(rests, runner.Rests, "the page he took is not put to rest under him");
Assert.IsFalse(turns.IsWaiting(PageUser.Engine));
// The rest is still owed: when he lets go again, the page goes back to rest.
driving = false;
host.NotifyUserDrivingChanged();
await bed.RunForAsync(TimeSpan.FromSeconds(1));
Assert.AreEqual(rests + 1, runner.Rests, "back to rest once he lets go");
}
[TestMethod]
public async Task ChangingTheAccountsDuringARecipeDoesNotBringItsNextCheckForward()
{