Interfaccia: correzioni della revisione (web-1, web-2, web-3, web-4, web-5, web-6, web-7, web-9, web-10, web-11, web-12, web-13, web-14, web-15)

Il browser preso dalle pagine Browser e Collegamento si restituisce uscendo senza «Ho finito» (anche chiudendo o ricaricando la scheda); dopo «Ho finito» la vista remota si chiude e non si riprende il browser. Vista remota: AltGr/Option come testo, pulsante rilasciato anche fuori dalla vista. Mosaico e scheda account senza risposte vecchie né viste sovrascritte; nuovi elementi dopo la libreria vuota; intestazione sempre aggiornata. Indietro del browser con la richiesta delle modifiche non salvate; nulla resta registrato da una pagina lasciata mentre caricava; maniglie della fascia trascinabili. «Da una data» come giorno locale; niente «@null» nel riquadro di stato; orari futuri dei fermi «verso le». Prove nel browser vero (InterfaceTests).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-14 01:38:13 +00:00
1 parent 78c92eb2a4
commit 0ceffffe50
27 files changed
+1365 -59

No files matched your search

+1 -1
View File
@@ -103,7 +103,7 @@ public sealed class AlertServiceTests
Assert.AreEqual("Instagram ha chiesto di rallentare", banner.Title);
var stop = bed.Telegram.Requests.Single().Text;
StringAssert.StartsWith(stop, "Febe · Instagram ha chiesto di rallentare\n");
StringAssert.Contains(stop, "mi fermo per 1 ora, fino alle 13:00");
StringAssert.Contains(stop, "mi fermo per 1 ora: riparto verso le 13:00");
StringAssert.Contains(stop, "Non devi fare nulla: riparto da solo.");
// After the hour the breaker reopens by itself: «…e ripresa».
@@ -81,6 +81,17 @@ public sealed class EngineMonitorTests
Assert.IsTrue(snapshot.Today.Spans.Any(s => s.Kind == StripSpanKind.Throttle));
StringAssert.StartsWith(snapshot.ProfilesOpenedToday.Note, "Fermo dalle ");
StringAssert.Contains(snapshot.ReductionNote!, "Tetti dimezzati");
// Future engine times are always «verso le» (spec §10.4): the strip agrees with the status box.
var resumes = ItalianText.Around(bed.Breaker.State.Until!.Value, bed.Clock.Now, bed.Clock.LocalZone);
StringAssert.Contains(snapshot.Banner.Message, "riparto da solo " + resumes);
StringAssert.Contains(snapshot.SidebarLine, resumes);
StringAssert.Contains(snapshot.ReductionNote!, "verso l");
foreach (var text in new[] { snapshot.Banner.Message, snapshot.ReductionNote! })
{
Assert.DoesNotContain(" alle ", text);
Assert.DoesNotContain(" all'", text);
}
}
[TestMethod]
+39
View File
@@ -136,6 +136,45 @@ public sealed class AccountsApiTests
"in Docker (the default shell of the tests) folders are read-only");
}
[TestMethod]
public void FromDateIsTheLocalDayAndSurvivesARoundTrip()
{
// «Solo i nuovi da oggi» in Rome: local midnight of 13 October is 12 October 22:00 UTC.
var rome = TestZones.Rome;
var account = Account.Create("marta.demo", StartingPoint.OnlyNewFromToday, Make.T0, rome);
Assert.AreEqual(new DateTimeOffset(2026, 10, 12, 22, 0, 0, TimeSpan.Zero), account.Limits.FromDate);
var form = Febe.Web.Api.AccountSettingsMapper.ToDto(account, rome);
Assert.AreEqual("2026-10-13", form.FromDate, "the form shows the day Alberto chose");
var again = Febe.Web.Api.AccountSettingsMapper.Apply(account, form, rome, Make.T0, account.Folder);
Assert.AreEqual(account.Limits.FromDate, again.Limits.FromDate, "saving the form as it is changes nothing");
}
[TestMethod]
public async Task TheKeepUpdatedSwitchAndSavingDoNotMoveTheStartingDay()
{
await using var server = await WebTestServer.StartAsync();
var account = await server.Db.Accounts.AddAsync(Account.Create("anna.demo", StartingPoint.OnlyNewFromToday, Make.T0, server.Clock.LocalZone));
var from = account.Limits.FromDate;
Assert.IsNotNull(from);
var detail = await server.GetJsonAsync($"/api/accounts/{account.Id}");
Assert.AreEqual("2026-10-13", detail.GetProperty("settings").Str("fromDate"));
foreach (var value in new[] { false, true, false, true })
{
var (status, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{account.Id}/keep-updated", new { value });
Assert.AreEqual(HttpStatusCode.OK, status);
}
Assert.AreEqual(from, (await server.Db.Accounts.GetAsync(account.Id))!.Limits.FromDate, "«Tieni aggiornato» does not move «Da una data»");
var settings = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>((await server.GetJsonAsync($"/api/accounts/{account.Id}")).GetProperty("settings").GetRawText())!;
var (saveStatus, saved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{account.Id}/settings", settings);
Assert.AreEqual(HttpStatusCode.OK, saveStatus);
Assert.AreEqual("2026-10-13", saved.GetProperty("settings").Str("fromDate"));
Assert.AreEqual(from, (await server.Db.Accounts.GetAsync(account.Id))!.Limits.FromDate, "saving the settings as they are does not move it either");
}
[TestMethod]
public async Task AccountsAreAddedFromTheFollowedListOrByNameWithAStartingPoint()
{
+537
View File
@@ -0,0 +1,537 @@
using System.Runtime.CompilerServices;
using System.Text.Json.Nodes;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Tests.Server.Support;
using Febe.Tests.Support;
using Febe.Tests.Web.Part2Support;
using Febe.Tests.Web.Support;
using Febe.Web;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Febe.Web.Library;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
/// <summary>
/// The interface itself in a real (headless) Chromium against a test server: what only shows when the scripts run.
/// The «driving» lease of the Browser and Collegamento pages (spec §4.1, §10.3: the engine is still only while Alberto
/// uses the browser), the remote view's keyboard and mouse, the mosaic and the account card when filters change,
/// the unsaved-changes guard on the browser's Back button, the window bar of Limiti, the sidebar status box.
/// </summary>
[TestClass]
[DoNotParallelize]
public sealed class InterfaceTests
{
private static readonly ConnectionStatus Connected = new(ConnectionState.Connected, "tuo.profilo", "Il tuo profilo", false, null);
private static readonly ConnectionStatus Verification = new(ConnectionState.VerificationRequired, "tuo.profilo", "Il tuo profilo", false, "https://www.instagram.com/challenge/");
// ------------------------------------------------------------------------------------------ the driving lease
[TestMethod]
public async Task LeavingTheBrowserPageWithoutHoFinitoGivesTheBrowserBack()
{
var connection = new RecordingConnection { Status = Connected };
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view);
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/browser"));
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False") && view.Opened.Count == 1, "il browser in uso con la vista aperta");
// Another page from the sidebar: the view closes and the lease of «begin» goes too (like «Annulla»).
await ui.EvalAsync("document.querySelector('a[data-nav=libreria]').click()");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await ui.WaitForAsync(() => connection.Snapshot().Contains("cancel"), "il browser restituito lasciando la pagina");
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
CollectionAssert.AreEqual(new[] { "begin:False", "cancel" }, connection.Snapshot());
}
[TestMethod]
public async Task ClosingOrReloadingTheTabGivesTheBrowserBack()
{
var connection = new RecordingConnection { Status = Connected };
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view);
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/browser"));
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False"), "il browser in uso");
// The document goes away (tab closed, reload, another site): only the page-hide event is left to say so.
await ui.SendAsync("Page.navigate", new JsonObject { ["url"] = "about:blank" });
await ui.WaitForAsync(() => connection.Snapshot().Contains("cancel"), "il browser restituito chiudendo la scheda");
}
[TestMethod]
public async Task ABrowserPageLeftWhileLoadingNeverTakesTheBrowser()
{
var connection = new RecordingConnection { Status = Connected };
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view);
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.FetchDelays);
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
// The status of the connection answers late; Alberto is already elsewhere.
await ui.EvalAsync("""
import('/js/core/shell.js').then((m) => {
window.__delays.push({ match: '/api/connection', ms: 600 });
m.navigate('/browser');
setTimeout(() => m.navigate('/libreria'), 150);
return true;
})
""");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await ui.WaitAsync("window.__done['/api/connection'] >= 1", "risposta in ritardo arrivata");
await Task.Delay(300);
Assert.IsEmpty(connection.Snapshot(), "nothing taken by a page that is gone");
Assert.IsEmpty(view.Opened);
}
[TestMethod]
public async Task AfterHoFinitoLeavingTheBrowserPageChangesNothingMore()
{
var connection = new RecordingConnection { Status = Connected };
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view);
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/browser"));
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False"), "il browser in uso");
await ui.EvalAsync("document.querySelector('.salva .btn.primo').click()");
await ui.WaitAsync("location.pathname === '/attivita'", "Attività dopo «Ho finito»");
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
await ui.NavigateAsync("/libreria");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await Task.Delay(500);
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot(), "«Ho finito» already gave the browser back");
}
[TestMethod]
public async Task HoFinitoOnCollegamentoClosesTheRemoteView()
{
var connection = new RecordingConnection();
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view);
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento"));
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:True") && view.Opened.Count == 1, "pagina di accesso nella vista remota");
await ui.EvalAsync("document.querySelector('.bottoni-collegamento .btn.primo').click()");
await ui.WaitAsync("document.querySelector('.pannello.collegato') !== null", "collegato");
// The view held the engine still for as long as the page stayed open (PROTOCOLLO.md: closing it frees it).
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa dopo «Ho finito»");
await ui.NavigateAsync("/libreria");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await Task.Delay(500);
CollectionAssert.AreEqual(new[] { "begin:True", "finish" }, connection.Snapshot());
Assert.HasCount(1, view.Opened);
}
[TestMethod]
public async Task HoFinitoDuringAVerificationDoesNotTakeTheBrowserAgain()
{
var connection = new RecordingConnection { Status = Verification, StatusAfterFinish = Verification };
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view, new FixedMonitor(EngineMode.StoppedForVerification));
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento"));
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False") && view.Opened.Count == 1, "verifica nella vista remota");
await ui.EvalAsync("document.querySelector('.bottoni-collegamento .btn.primo').click()");
await ui.WaitAsync("document.querySelector('.riapri-browser') !== null", "«Ho finito» fatto, in attesa di «Riprendi»");
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa dopo «Ho finito»");
await Task.Delay(500);
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot(), "no new lease after «Ho finito»");
Assert.HasCount(1, view.Opened, "no new view after «Ho finito»");
// «Riapri il browser» takes it again; leaving the page then gives it back.
await ui.EvalAsync("document.querySelector('.riapri-browser').click()");
await ui.WaitForAsync(() => connection.Snapshot().Length == 3 && view.Opened.Count == 2, "browser riaperto");
await ui.NavigateAsync("/libreria");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await ui.WaitForAsync(() => connection.Snapshot().Length == 4, "il browser restituito lasciando la pagina");
CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "cancel" }, connection.Snapshot());
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
}
[TestMethod]
public async Task AfterRiprendiCollegamentoShowsTheConnectionWithoutTakingTheBrowser()
{
var connection = new RecordingConnection { Status = Verification, StatusAfterFinish = Verification };
var view = new FakeRemoteViewHost();
var engine = new FixedMonitor(EngineMode.StoppedForVerification);
await using var server = await DockerAsync(connection, view, engine);
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento"));
await ui.WaitAsync("document.querySelector('.arresto') !== null", "striscia rossa della verifica");
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False"), "verifica nella vista remota");
await ui.EvalAsync("document.querySelector('.bottoni-collegamento .btn.primo').click()");
await ui.WaitAsync("document.querySelector('.riapri-browser') !== null", "in attesa di «Riprendi»");
// «Riprendi»: the engine works again and the session is there.
engine.Mode = EngineMode.Resting;
connection.Status = Connected;
await ui.EvalAsync("import('/js/core/engine.js').then((m) => m.refreshEngine()).then(() => true)");
await ui.WaitAsync("document.querySelector('.pannello.collegato') !== null", "collegato dopo «Riprendi»");
await Task.Delay(300);
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot());
Assert.IsTrue(view.Opened.All(v => v.Disposed));
}
// ------------------------------------------------------------------------------------------ remote view input
[TestMethod]
public async Task AltGrCharactersReachTheRemotePageAsText()
{
var connection = new RecordingConnection { Status = Connected };
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view);
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/browser"));
await ui.WaitForAsync(() => view.Opened.Count == 1, "vista aperta");
await ui.WaitAsync("document.querySelector('canvas.vista-schermo') !== null", "schermo della vista");
await Task.Delay(300);
// Italian layout on Windows: AltGr+ò is «@», reported as Ctrl+Alt with the AltGraph modifier.
Assert.IsTrue((await ui.EvalAsync("new KeyboardEvent('keydown', { key: '@', modifierAltGraph: true }).getModifierState('AltGraph')")).GetBoolean());
await ui.EvalAsync("""
(() => {
const c = document.querySelector('canvas.vista-schermo');
const key = (type, init) => c.dispatchEvent(new KeyboardEvent(type, { bubbles: true, cancelable: true, ...init }));
const altGr = { ctrlKey: true, altKey: true, modifierAltGraph: true };
key('keydown', { key: '@', code: 'Semicolon', ...altGr });
key('keyup', { key: '@', code: 'Semicolon', ...altGr });
key('keydown', { key: 'a', code: 'KeyA' });
key('keyup', { key: 'a', code: 'KeyA' });
key('keydown', { key: 'f', code: 'KeyF', altKey: true });
key('keyup', { key: 'f', code: 'KeyF', altKey: true });
return true;
})()
""");
var connectionView = view.Opened.Single();
await ui.WaitForAsync(() => Keys(connectionView).Any(k => k.Action == RemoteViewKeyAction.Up && k.Key == "f"), "tasti arrivati");
var keys = Keys(connectionView);
Assert.IsTrue(keys.Any(k => k is { Action: RemoteViewKeyAction.Char, Text: "@", Modifiers: 0 }), "AltGr+ò types «@»: " + Describe(keys));
Assert.IsFalse(keys.Any(k => k.Key == "@" && k.Action != RemoteViewKeyAction.Char), "no Ctrl+Alt shortcut for «@»: " + Describe(keys));
Assert.IsTrue(keys.Any(k => k is { Action: RemoteViewKeyAction.Down, Key: "a", Text: "a", Modifiers: 0 }), "a plain key keeps its text");
Assert.IsTrue(keys.Any(k => k is { Action: RemoteViewKeyAction.Down, Key: "f", Text: null, Modifiers: 1 }), "Alt+F on Windows stays a shortcut: " + Describe(keys));
}
[TestMethod]
public async Task ReleasingTheMouseOutsideTheViewReleasesTheRemoteButton()
{
var connection = new RecordingConnection { Status = Connected };
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view);
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/browser"));
await ui.WaitForAsync(() => view.Opened.Count == 1, "vista aperta");
var remote = view.Opened.Single();
await Task.Delay(300);
remote.Write(new RemoteViewMeta(320, 225, "https://www.instagram.com/"));
remote.Write(new RemoteViewFrame(TestFile.PhotoBytes(3, 320, 225)));
await ui.WaitAsync("!document.querySelector('canvas.vista-schermo').hidden", "primo fotogramma");
var (x, y, _, _) = await ui.BoxAsync("canvas.vista-schermo");
await ui.MouseAsync("mouseMoved", x, y);
await ui.MouseAsync("mousePressed", x, y, buttons: 1);
await ui.MouseAsync("mouseMoved", x + 20, y + 10, buttons: 1);
await ui.MouseAsync("mouseMoved", 60, 60, buttons: 1);
await ui.MouseAsync("mouseReleased", 60, 60);
await ui.WaitForAsync(() => Mice(remote).Any(m => m.Action == RemoteViewMouseAction.Up), "pulsante rilasciato anche fuori dalla vista");
Assert.AreEqual(RemoteViewButton.Left, Mice(remote).Single(m => m.Action == RemoteViewMouseAction.Up).Button);
}
// ------------------------------------------------------------------------------------------ mosaic and account card
[TestMethod]
public async Task AfterInEvidenzaTheOtherTabsStayTheirs()
{
await using var server = await WebTestServer.StartAsync();
var account = await server.AddAccountWithEntriesAsync("marta.prova", 6, Make.T0, TimeSpan.FromHours(20));
var stories = await server.Db.Entries.AddManyAsync([.. Enumerable.Range(0, 3).Select(i => new NewEntry(
Make.Entry(account.Id, $"storia-{i}", Make.T0 - TimeSpan.FromDays(3 + i), EntryKind.Story) with { State = EntryState.Downloaded },
[Make.Stored(Make.Photo(), Make.Sha(9000 + i), $"storie/storia-{i}.jpg")]))]);
var summer = await server.Db.Highlights.UpsertAsync(new Highlight { AccountId = account.Id, InstagramId = "h1", Title = "Estate", Position = 0, DiscoveredAt = Make.T0 });
foreach (var story in stories)
{
await server.Db.Highlights.AddItemAsync(summer.Id, story.Stored.Entry.Id);
}
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.FetchDelays);
await ui.OpenAsync(new Uri(server.Address, $"/account/{account.Id}?tipo=evidenza"));
await ui.WaitAsync("document.querySelector('main .raccolta-titolo') !== null", "raccolte in evidenza");
// «Post» after «In evidenza»: the posts stay, also when the area changes size.
await ui.EvalAsync("document.querySelectorAll('.strumenti .filtri button')[0].click()");
await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post");
await Task.Delay(500);
await ui.SendAsync("Emulation.setDeviceMetricsOverride", new JsonObject { ["width"] = 1100, ["height"] = 900, ["deviceScaleFactor"] = 1, ["mobile"] = false });
await Task.Delay(600);
await AssertPostsShownAsync(ui);
// «In evidenza» and at once «Post», while the tiles of the collections are still loading.
await ui.EvalAsync("""
(() => {
window.__delays.push({ match: '/api/library/tiles', ms: 600 });
const chips = document.querySelectorAll('.strumenti .filtri button');
chips[2].click();
chips[0].click();
return true;
})()
""");
await ui.WaitAsync("window.__done['/api/library/tiles'] >= 1", "tessere delle raccolte arrivate in ritardo");
await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post");
await Task.Delay(400);
await AssertPostsShownAsync(ui);
}
[TestMethod]
public async Task AStaleAnswerOfTheLibraryDoesNotHideTheNewFilter()
{
await using var server = await WebTestServer.StartAsync();
await server.AddAccountWithEntriesAsync("anna.prova", 5, Make.T0, TimeSpan.FromHours(30));
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.FetchDelays);
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null", "mosaico");
// «Storie» (nothing: an empty answer, late) and at once «Foto».
await ui.EvalAsync("""
(() => {
window.__delays.push({ match: 'kind=stories', ms: 700 });
const chips = document.querySelectorAll('.strumenti .filtri button');
chips[3].click();
chips[1].click();
return true;
})()
""");
await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null", "foto");
await ui.WaitAsync("window.__done['kind=stories'] >= 1", "risposta delle storie arrivata in ritardo");
await Task.Delay(300);
Assert.IsTrue((await ui.EvalAsync("location.search.includes('tipo=foto')")).GetBoolean());
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null")).GetBoolean(), "the photos are shown " + ui.Report());
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .vuoto-pagina') === null")).GetBoolean(), "no empty state over the results");
StringAssert.StartsWith((await ui.EvalAsync("document.querySelector('.testa .quanti').textContent")).GetString(), "5 ");
}
[TestMethod]
public async Task NewEntriesAppearAfterTheEmptyLibrary()
{
await using var server = await WebTestServer.StartAsync();
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
await ui.WaitAsync("document.querySelector('main .vuoto-pagina, main .benvenuto') !== null", "libreria vuota (primo avvio)");
var account = await server.AddAccountWithEntriesAsync("primo.prova", 4, Make.T0, TimeSpan.FromHours(10));
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
var shown = false;
while (!shown && DateTime.UtcNow < deadline)
{
server.Changes.Publish(new LibraryChange(server.Clock.Now, account.Id, "stored"));
await Task.Delay(700);
shown = (await ui.EvalAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null")).GetBoolean();
}
Assert.IsTrue(shown, "the new entries appear at the top (spec §10.3) " + ui.Report());
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .vuoto-pagina, main .benvenuto') === null")).GetBoolean(), "the empty state goes away");
await ui.WaitAsync("document.querySelector('main .mosaico .tess') !== null", "tessere disegnate");
}
[TestMethod]
public async Task TheAccountHeaderFollowsEveryMenuAction()
{
await using var server = await WebTestServer.StartAsync();
var account = await server.AddAccountWithEntriesAsync("luca.prova", 2, Make.T0, TimeSpan.FromHours(10));
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, $"/account/{account.Id}"));
await ui.WaitAsync("document.querySelector('.scheda-testa h1') !== null", "scheda");
foreach (var (choice, next) in new[] { ("Metti in pausa", "Riattiva"), ("Riattiva", "Metti in pausa"), ("Metti in pausa", "Riattiva") })
{
await ui.EvalAsync("document.querySelector('.scheda-testa .azioni button[aria-haspopup]').click()");
await ui.WaitAsync("document.querySelector('.menu') !== null", "menu");
await ui.EvalAsync($$"""
(() => {
const item = [...document.querySelectorAll('.menu button')].find((b) => b.textContent.trim() === '{{choice}}');
if (!item) throw new Error('voce mancante: {{choice}} in ' + document.querySelector('.menu').textContent);
item.click();
return true;
})()
""");
// The header (and its menu) is drawn again with the new state of the account.
await ui.WaitAsync(
$$"""
(async () => {
document.querySelector('.scheda-testa .azioni button[aria-haspopup]').click();
const menu = document.querySelector('.menu');
const ok = Boolean(menu) && [...menu.querySelectorAll('button')].some((b) => b.textContent.trim() === '{{next}}');
(await import('/js/core/ui.js')).closeMenu();
return ok;
})()
""",
$"intestazione aggiornata dopo «{choice}»");
await Task.Delay(200);
}
}
// ------------------------------------------------------------------------------------------ shell
[TestMethod]
public async Task TheBackButtonAsksBeforeLosingUnsavedChanges()
{
await using var server = await WebTestServer.StartAsync();
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
await ui.NavigateAsync("/impostazioni/limiti");
await ui.WaitAsync("document.querySelector('.cerchio-giorno') !== null", "Limiti");
await ui.EvalAsync("document.querySelector('.cerchio-giorno').click()");
await ui.WaitAsync("!document.querySelector('.salva').hidden", "modifiche da salvare");
await ui.EvalAsync("history.back()");
await ui.WaitAsync("document.querySelector('.dialogo') !== null", "«Modifiche non salvate» con il pulsante Indietro");
await ui.EvalAsync("[...document.querySelectorAll('.dialogo footer button')].find((b) => b.textContent === 'Annulla').click()");
await ui.WaitAsync("document.querySelector('.dialogo') === null", "dialogo chiuso");
Assert.AreEqual("/impostazioni/limiti", (await ui.EvalAsync("location.pathname")).GetString());
Assert.IsTrue((await ui.EvalAsync("!document.querySelector('.salva').hidden && document.querySelector('.cerchio-giorno') !== null")).GetBoolean(), "the edits are still there");
await ui.EvalAsync("history.back()");
await ui.WaitAsync("document.querySelector('.dialogo') !== null", "di nuovo il dialogo");
await ui.EvalAsync("[...document.querySelectorAll('.dialogo footer button')].find((b) => b.textContent === 'Lascia le modifiche').click()");
await ui.WaitAsync("location.pathname === '/libreria' && document.querySelector('main .vuoto-pagina, main .mosaico') !== null", "Libreria");
}
[TestMethod]
public async Task APageLeftWhileLoadingLeavesNothingBehind()
{
await using var server = await WebTestServer.StartAsync();
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.FetchDelays);
await ui.AddInitScriptAsync("""
(() => {
const live = new Map();
const set = window.setInterval.bind(window);
const clear = window.clearInterval.bind(window);
window.setInterval = (fn, ms, ...rest) => { const id = set(fn, ms, ...rest); live.set(id, ms); return id; };
window.clearInterval = (id) => { live.delete(id); clear(id); };
window.__intervals = (ms) => [...live.values()].filter((v) => v === ms).length;
})();
""");
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
await ui.EvalAsync("""
import('/js/core/shell.js').then((m) => {
window.__delays.push({ match: '/api/alerts', ms: 600 });
m.navigate('/attivita');
setTimeout(() => m.navigate('/libreria'), 200);
return true;
})
""");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await ui.WaitAsync("window.__done['/api/alerts'] >= 1", "risposta in ritardo arrivata");
await Task.Delay(300);
Assert.AreEqual(0, (await ui.EvalAsync("window.__intervals(60000)")).GetInt32(), "the minute timer of Attività is gone with its page");
// The page that stays open still works as usual.
await ui.NavigateAsync("/attivita");
await ui.WaitAsync("window.__intervals(60000) === 1", "Attività aperta");
await ui.NavigateAsync("/libreria");
await ui.WaitAsync("window.__intervals(60000) === 0", "Attività lasciata");
}
[TestMethod]
public async Task TheWindowBarHandleFollowsTheWholeDrag()
{
await using var server = await WebTestServer.StartAsync();
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/impostazioni/limiti"));
await ui.WaitAsync("document.querySelector('.fascia-barra .maniglia') !== null", "barra della fascia");
var (barX, barY, barWidth, _) = await ui.BoxAsync(".fascia-barra");
var handle = await ui.EvalAsync("(() => { const r = document.querySelector('.fascia-barra .maniglia').getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; })()");
var (handleX, handleY) = (handle[0].GetDouble(), handle[1].GetDouble());
var left = barX - (barWidth / 2);
await ui.MouseAsync("mouseMoved", handleX, handleY);
await ui.MouseAsync("mousePressed", handleX, handleY, buttons: 1);
var x = handleX;
foreach (var ratio in new[] { 0.30, 0.34, 0.38, 0.42, 0.46 })
{
x = left + (barWidth * ratio);
await ui.MouseAsync("mouseMoved", x, barY, buttons: 1);
await Task.Delay(60);
}
await ui.MouseAsync("mouseReleased", x, barY);
var minutes = (int)(Math.Round((x - left) / barWidth * 1440 / 15) * 15);
var expected = $"{minutes / 60:00}:{minutes % 60:00}";
await ui.WaitAsync($"document.querySelector('#fascia-inizio').value === '{expected}'", $"inizio della fascia a {expected}");
}
[TestMethod]
public async Task TheStatusBoxDoesNotShowANameItDoesNotKnow()
{
var monitor = new FixedMonitor(EngineMode.StoppedForVerification);
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IEngineMonitor>(monitor));
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
await ui.WaitAsync("document.querySelector('.stato .chi') !== null", "riquadro di stato");
var text = (await ui.EvalAsync("document.querySelector('.stato .chi').textContent")).GetString()!;
Assert.DoesNotContain("@", text, "no handle before the first sweep learns it: " + text);
StringAssert.Contains(text, "Verifica richiesta");
}
// ------------------------------------------------------------------------------------------ helpers
private static Task<WebTestServer> DockerAsync(RecordingConnection connection, FakeRemoteViewHost view, IEngineMonitor? engine = null) =>
Part2.StartAsync(FebeEdition.Docker, s =>
{
s.AddSingleton<IConnectionService>(connection);
s.AddSingleton<IRemoteViewHost>(view);
if (engine is not null)
{
s.AddSingleton(engine);
}
});
private static List<RemoteViewKey> Keys(FakeRemoteViewConnection view) => [.. view.Inputs.OfType<RemoteViewKey>()];
private static List<RemoteViewMouse> Mice(FakeRemoteViewConnection view) => [.. view.Inputs.OfType<RemoteViewMouse>()];
private static string Describe(IEnumerable<RemoteViewKey> keys) =>
string.Join(", ", keys.Select(k => $"{k.Action}:{k.Key}:{k.Text ?? "∅"}:{k.Modifiers}"));
private static async Task AssertPostsShownAsync(UiBrowser ui)
{
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .raccolta-titolo') === null")).GetBoolean(), "the collections are gone " + ui.Report());
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null")).GetBoolean(), "the posts are shown " + ui.Report());
Assert.IsTrue((await ui.EvalAsync("document.querySelector('.strumenti .filtri button[aria-pressed=true]').textContent.startsWith('Post')")).GetBoolean());
}
/// <summary>An engine in the mode the test sets; stopped for a verification it shows the red strip.</summary>
private sealed class FixedMonitor(EngineMode mode) : IEngineMonitor
{
public EngineMode Mode { get; set; } = mode;
public Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default)
{
var snapshot = SnapshotParts.Build(new ManualClock(Make.T0), Mode, "Fermo", ["In attesa che tu completi la verifica"], "Serve il tuo intervento", CautionProfile.Prudent);
return Task.FromResult(Mode == EngineMode.StoppedForVerification
? snapshot with { Banner = new StopBanner(BannerLevel.Error, "Instagram chiede una verifica", "Ho fermato tutto e non riparto da solo.", true) }
: snapshot);
}
public async IAsyncEnumerable<EngineNotification> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
{
await Task.Delay(Timeout.Infinite, ct);
yield break;
}
}
}
@@ -68,36 +68,59 @@ internal sealed class FixedProblems(params ConfigurationProblem[] problems) : IC
/// <summary>A connection service that records what the API asks.</summary>
internal sealed class RecordingConnection : IConnectionService
{
private readonly Lock _gate = new();
public List<string> Calls { get; } = [];
public ConnectionStatus Status { get; set; } = new(ConnectionState.NotConnected, null, null, false, "https://www.instagram.com/accounts/login/");
/// <summary>The status after «Ho finito» (connected by default; a verification still pending is the other case).</summary>
public ConnectionStatus StatusAfterFinish { get; set; } = new(ConnectionState.Connected, "tuo.profilo", "Il tuo profilo", false, null);
/// <summary>The calls so far, safe to read while the interface keeps sending.</summary>
public string[] Snapshot()
{
lock (_gate)
{
return [.. Calls];
}
}
public Task<ConnectionStatus> GetStatusAsync(CancellationToken ct) => Task.FromResult(Status);
public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct)
{
Calls.Add("begin:" + openLogin);
Record("begin:" + openLogin);
Status = Status with { UserIsDriving = true };
return Task.CompletedTask;
}
public Task<FinishResult> FinishAsync(CancellationToken ct)
{
Calls.Add("finish");
Status = new ConnectionStatus(ConnectionState.Connected, "tuo.profilo", "Il tuo profilo", false, null);
Record("finish");
Status = StatusAfterFinish;
return Task.FromResult(new FinishResult(true, "Sei collegato come @tuo.profilo."));
}
public Task CancelAsync(CancellationToken ct)
{
Calls.Add("cancel");
Record("cancel");
Status = Status with { UserIsDriving = false };
return Task.CompletedTask;
}
public Task DisconnectAsync(CancellationToken ct)
{
Calls.Add("disconnect");
Record("disconnect");
Status = new ConnectionStatus(ConnectionState.NotConnected, null, null, false, null);
return Task.CompletedTask;
}
private void Record(string call)
{
lock (_gate)
{
Calls.Add(call);
}
}
}
+409
View File
@@ -0,0 +1,409 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Tests.Browser.TestSupport;
namespace Febe.Tests.Web.Support;
/// <summary>
/// A headless Chromium that drives Febe's own interface, like <c>tools/schermate</c>: only addresses on 127.0.0.1, never
/// Instagram (spec §2). It speaks the DevTools protocol directly, without the command policy of Febe's own client,
/// because here the tests click, type and run scripts in Febe's pages. Inconclusive when Chromium is missing.
/// </summary>
internal sealed class UiBrowser : IAsyncDisposable
{
/// <summary>
/// Installed before the page scripts: <c>window.__delays</c> holds { match, ms } rules that hold back a matching
/// fetch, so that a test can make one answer arrive late (stale answers, slow pages); <c>window.__done[match]</c>
/// counts the held-back requests that are over (answered, failed or aborted).
/// </summary>
public const string FetchDelays = """
(() => {
const original = window.fetch.bind(window);
window.__delays = [];
window.__done = {};
window.fetch = async (input, init) => {
const url = typeof input === 'string' ? input : input.url;
const rule = window.__delays.find((d) => url.includes(d.match));
if (!rule) return original(input, init);
try {
await new Promise((resolve) => setTimeout(resolve, rule.ms));
return await original(input, init);
} finally {
// After the page's own continuation of this answer has run.
setTimeout(() => { window.__done[rule.match] = (window.__done[rule.match] || 0) + 1; }, 50);
}
};
})();
""";
private readonly Process _process;
private readonly ClientWebSocket _socket;
private readonly string _profile;
private readonly ConcurrentDictionary<int, TaskCompletionSource<JsonElement>> _pending = new();
private readonly CancellationTokenSource _stop = new();
private readonly SemaphoreSlim _send = new(1, 1);
private readonly Task _reader;
private int _id;
private UiBrowser(Process process, ClientWebSocket socket, string profile)
{
_process = process;
_socket = socket;
_profile = profile;
_reader = Task.Run(ReadLoopAsync);
}
/// <summary>Uncaught exceptions and console errors of the pages (shown when a test fails).</summary>
public ConcurrentQueue<string> Problems { get; } = new();
public static async Task<UiBrowser> StartAsync(int width = 1280, int height = 900)
{
if (!OperatingSystem.IsLinux() || RealBrowser.ChromiumPath() is not { } chromium)
{
Assert.Inconclusive("Chromium non trovato (impostare FEBE_CHROMIUM): le prove dell'interfaccia nel browser non girano.");
throw new UnreachableException();
}
var profile = Path.Combine(Path.GetTempPath(), "febe-interfaccia-" + Guid.NewGuid().ToString("N"));
var port = LocalTestSite.FreePort();
var info = new ProcessStartInfo(chromium)
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
foreach (var argument in new[]
{
"--headless", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check",
"--disable-extensions", "--disable-background-networking", "--disable-component-update", "--no-proxy-server",
"--mute-audio", $"--window-size={width},{height}", $"--user-data-dir={profile}",
$"--remote-debugging-port={port}", "--remote-debugging-address=127.0.0.1", "about:blank",
})
{
info.ArgumentList.Add(argument);
}
if (RealBrowser.IsRoot)
{
info.ArgumentList.Add("--no-sandbox");
}
foreach (var (key, value) in RealBrowser.BrowserEnvironment)
{
if (value is null)
{
info.Environment.Remove(key);
}
else
{
info.Environment[key] = value;
}
}
var process = Process.Start(info) ?? throw new InvalidOperationException("Chromium non parte.");
process.OutputDataReceived += (_, _) => { };
process.ErrorDataReceived += (_, _) => { };
process.BeginOutputReadLine();
process.BeginErrorReadLine();
try
{
using var http = new HttpClient(new HttpClientHandler { UseProxy = false }) { Timeout = TimeSpan.FromSeconds(2) };
string? debugger = null;
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(20);
while (debugger is null && DateTime.UtcNow < deadline)
{
try
{
using var list = JsonDocument.Parse(await http.GetStringAsync(new Uri($"http://127.0.0.1:{port}/json/list")));
debugger = list.RootElement.EnumerateArray()
.Where(t => t.GetProperty("type").GetString() == "page")
.Select(t => t.GetProperty("webSocketDebuggerUrl").GetString())
.FirstOrDefault();
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException)
{
// Chromium is still starting.
}
if (debugger is null)
{
await Task.Delay(100);
}
}
if (debugger is null)
{
throw new TimeoutException("Chromium non risponde sulla porta di debug.");
}
var socket = new ClientWebSocket();
socket.Options.Proxy = null;
await socket.ConnectAsync(new Uri(debugger), CancellationToken.None);
var browser = new UiBrowser(process, socket, profile);
await browser.SendAsync("Runtime.enable");
await browser.SendAsync("Page.enable");
await browser.SendAsync("Log.enable");
return browser;
}
catch
{
Kill(process);
RealBrowser.TryDelete(profile);
throw;
}
}
/// <summary>One command of the DevTools protocol; its result (an error of the protocol fails the test).</summary>
public async Task<JsonElement> SendAsync(string method, JsonObject? parameters = null)
{
var id = Interlocked.Increment(ref _id);
var answer = new TaskCompletionSource<JsonElement>(TaskCreationOptions.RunContinuationsAsynchronously);
_pending[id] = answer;
var message = new JsonObject { ["id"] = id, ["method"] = method, ["params"] = parameters ?? new JsonObject() };
await _send.WaitAsync();
try
{
await _socket.SendAsync(Encoding.UTF8.GetBytes(message.ToJsonString()), WebSocketMessageType.Text, endOfMessage: true, CancellationToken.None);
}
finally
{
_send.Release();
}
return await answer.Task.WaitAsync(TimeSpan.FromSeconds(30));
}
/// <summary>Runs a script in the page (promises awaited) and returns its value; an exception fails the test.</summary>
public async Task<JsonElement> EvalAsync(string expression)
{
var result = await SendAsync("Runtime.evaluate", new JsonObject
{
["expression"] = expression,
["awaitPromise"] = true,
["returnByValue"] = true,
});
if (result.TryGetProperty("exceptionDetails", out var details))
{
var text = details.TryGetProperty("exception", out var ex) && ex.TryGetProperty("description", out var d) ? d.GetString() : details.GetProperty("text").GetString();
throw new AssertFailedException($"Errore nella pagina: {text}\n{Report()}");
}
return result.GetProperty("result").TryGetProperty("value", out var value) ? value.Clone() : default;
}
public async Task<T> EvalAsync<T>(string expression) => (await EvalAsync(expression)).Deserialize<T>(WebTestServer.Json)!;
/// <summary>
/// Polls until a condition of the page holds (an expression, or a promise of one; errors while the page changes
/// count as «not yet»).
/// </summary>
public async Task WaitAsync(string condition, string what, int milliseconds = 10_000)
{
var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(milliseconds);
string? last = null;
while (DateTime.UtcNow < deadline)
{
try
{
if ((await EvalAsync($"(async () => Boolean(await ({condition})))()")).ValueKind == JsonValueKind.True)
{
return;
}
}
catch (AssertFailedException ex)
{
last = ex.Message;
}
await Task.Delay(50);
}
Assert.Fail($"timeout: {what}{(last is null ? string.Empty : "\n" + last)}\n{Report()}");
}
/// <summary>Polls a condition of the test (the server side) while the page works.</summary>
public async Task WaitForAsync(Func<bool> condition, string what, int milliseconds = 10_000)
{
var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(milliseconds);
while (DateTime.UtcNow < deadline)
{
if (condition())
{
return;
}
await Task.Delay(50);
}
Assert.Fail($"timeout: {what}\n{Report()}");
}
/// <summary>A script that runs in every new document before its own scripts.</summary>
public Task AddInitScriptAsync(string source) =>
SendAsync("Page.addScriptToEvaluateOnNewDocument", new JsonObject { ["source"] = source });
/// <summary>Loads an address of the interface and waits until the frame and the first page are drawn.</summary>
public async Task OpenAsync(Uri address)
{
await SendAsync("Page.navigate", new JsonObject { ["url"] = address.AbsoluteUri });
await WaitAsync(
$"location.href.startsWith({JsonSerializer.Serialize(address.GetLeftPart(UriPartial.Authority))}) && document.readyState === 'complete' && !document.documentElement.hasAttribute('aria-busy') && document.querySelector('main.pagina .corpo') !== null",
$"apertura di {address}");
}
/// <summary>Goes to an internal address the way a link of the interface does (unsaved-changes guard included).</summary>
public Task NavigateAsync(string path) =>
EvalAsync($"import('/js/core/shell.js').then((m) => {{ m.navigate({JsonSerializer.Serialize(path)}); return true; }})");
/// <summary>Centre of the first element matching the selector, in viewport pixels (scrolled into view first).</summary>
public async Task<(double X, double Y, double Width, double Height)> BoxAsync(string selector)
{
var box = await EvalAsync($$"""
(() => {
const el = document.querySelector({{JsonSerializer.Serialize(selector)}});
if (!el) return null;
el.scrollIntoView({ block: 'center', inline: 'center' });
const r = el.getBoundingClientRect();
return { x: r.left + r.width / 2, y: r.top + r.height / 2, width: r.width, height: r.height };
})()
""");
Assert.AreEqual(JsonValueKind.Object, box.ValueKind, $"elemento non trovato: {selector}");
return (box.GetProperty("x").GetDouble(), box.GetProperty("y").GetDouble(), box.GetProperty("width").GetDouble(), box.GetProperty("height").GetDouble());
}
/// <summary>A real mouse event (Input.dispatchMouseEvent): «mousePressed», «mouseMoved», «mouseReleased».</summary>
public Task MouseAsync(string type, double x, double y, int buttons = 0) =>
SendAsync("Input.dispatchMouseEvent", new JsonObject
{
["type"] = type,
["x"] = x,
["y"] = y,
["button"] = type == "mouseMoved" && buttons == 0 ? "none" : "left",
["buttons"] = buttons,
["clickCount"] = type == "mouseMoved" ? 0 : 1,
});
/// <summary>What went wrong in the pages so far, for failure messages.</summary>
public string Report() => Problems.IsEmpty ? string.Empty : "Pagina: " + string.Join(" | ", Problems);
public async ValueTask DisposeAsync()
{
await _stop.CancelAsync();
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
await _socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "fine", timeout.Token);
}
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
{
}
Kill(_process);
try
{
await _reader.WaitAsync(TimeSpan.FromSeconds(5));
}
catch (Exception ex) when (ex is TimeoutException or WebSocketException or OperationCanceledException)
{
}
_socket.Dispose();
_process.Dispose();
_stop.Dispose();
_send.Dispose();
RealBrowser.TryDelete(_profile);
}
private static void Kill(Process process)
{
try
{
if (!process.HasExited)
{
process.Kill(entireProcessTree: true);
process.WaitForExit(5000);
}
}
catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception)
{
}
}
private async Task ReadLoopAsync()
{
var buffer = new byte[64 * 1024];
using var message = new MemoryStream();
try
{
while (!_stop.IsCancellationRequested && _socket.State == WebSocketState.Open)
{
message.SetLength(0);
WebSocketReceiveResult result;
do
{
result = await _socket.ReceiveAsync(buffer, _stop.Token);
if (result.MessageType == WebSocketMessageType.Close)
{
return;
}
message.Write(buffer, 0, result.Count);
}
while (!result.EndOfMessage);
Dispatch(message.ToArray());
}
}
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
{
}
finally
{
foreach (var pending in _pending.Values)
{
pending.TrySetException(new InvalidOperationException("Chromium si è chiuso."));
}
}
}
private void Dispatch(byte[] data)
{
using var document = JsonDocument.Parse(data);
var root = document.RootElement;
if (root.TryGetProperty("id", out var idElement) && _pending.TryRemove(idElement.GetInt32(), out var answer))
{
if (root.TryGetProperty("error", out var error))
{
answer.TrySetException(new InvalidOperationException("DevTools: " + error.GetRawText()));
}
else
{
answer.TrySetResult(root.GetProperty("result").Clone());
}
return;
}
if (!root.TryGetProperty("method", out var method))
{
return;
}
var parameters = root.GetProperty("params");
switch (method.GetString())
{
case "Runtime.exceptionThrown":
var details = parameters.GetProperty("exceptionDetails");
Problems.Enqueue("eccezione: " + (details.TryGetProperty("exception", out var ex) && ex.TryGetProperty("description", out var d) ? d.GetString() : details.GetProperty("text").GetString()));
break;
case "Runtime.consoleAPICalled" when parameters.GetProperty("type").GetString() == "error":
Problems.Enqueue("console: " + string.Join(' ', parameters.GetProperty("args").EnumerateArray().Select(a => a.TryGetProperty("value", out var v) ? v.ToString() : a.TryGetProperty("description", out var s) ? s.GetString() : "?")));
break;
}
}
}