Il browser di Febe a volte era bianco o non mostrava nulla. Le cause erano
diverse e si correggono insieme.
- Pagina iniziale. Se il browser è a riposo su about:blank e Alberto lo apre
(«Usa il browser», «Apri il browser»), Febe lo porta sulla home del sito
quando è collegato, altrimenti sulla pagina di accesso. È un'azione di
Alberto, sotto il suo permesso di guida, non del motore: Febe aspetta che
la sessione finisca e prende il turno della pagina.
Il nuovo pulsante «Pagina iniziale» sta nella barra della finestra di
Windows e nella vista remota. Su about:blank la barra dice «Il browser è a
riposo su una pagina vuota». «Indietro» non torna più sulla pagina di
riposo.
- Disconnessione. «Apri il browser» nella striscia rossa apre la pagina di
accesso. Con --accesso-di-prova il primo controllo all'avvio non segnala
più una disconnessione finta.
- Windows: la finestra resta.
- Lasciare una pagina di Febe non nasconde più la finestra «Browser di
Febe» e non la rimette a riposo: finisce solo il permesso tenuto dalla
pagina (cancel con pageLeft, IConnectionService.ReleaseAsync).
- Sullo schermo la finestra ha il suo pulsante nella barra delle
applicazioni, così ridurla a icona non la fa sparire. Dopo 2 minuti
ridotta a icona torna fuori vista (S2).
- Se lo schermo è troppo piccolo, la finestra si restringe all'area di
lavoro e la pagina si rimpicciolisce con ZoomFactor, con le stesse misure
CSS.
- I bordi della pagina si riapplicano, con NotifyParentWindowPositionChanged,
quando la finestra si mostra, si sposta o riparte il processo GPU.
- Una pagina che non risponde mentre Alberto guida resta com'è.
- IBrowserWindow.ShowAsync lascia il posto a
IConnectionService.ShowBrowserAsync.
- Docker: fotogrammi che ripartono. La vista remota ha un watchdog. Riavvia
i fotogrammi dopo una pagina nuova caricata senza fotogrammi e dopo circa
2 s di silenzio. L'attesa raddoppia fino a 30 s finché la pagina resta
ferma. Se il riavvio non porta nulla, la vista riceve un'immagine ferma
(Page.captureScreenshot, già fra i comandi ammessi).
RemoteViewSession ha ora un registro vero: avvii, riavvii e silenzi vanno
a livello Info, categoria «vista», senza indirizzi.
Se dopo 8 s non arriva nessuna immagine, l'interfaccia mostra «Nessuna
immagine dal browser» con «Riprova».
Nessun comando CDP nuovo e nessuna dipendenza nuova. Aggiornati PROTOCOLLO.md
e la guida (Primo collegamento, Attività e arresti, Installazione Windows,
Problemi comuni).
Prove nuove:
- ScreencastWatchdogTests, RemoteViewFramesTests (Chromium vero, solo CI
Linux)
- Home e Indietro in RemoteViewStartTests
- RemoteViewSocketTests
- ConnectionApiTests
- BrowserStartPageTests
- BrowserWindowDecisionTests e BrowserWindowTests (WebView2 vero)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
231 lines
9.5 KiB
C#
231 lines
9.5 KiB
C#
using System.Net;
|
||
using System.Net.Sockets;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
|
||
namespace Febe.Tests.Browser.TestSupport;
|
||
|
||
/// <summary>
|
||
/// Tiny local site served by the test itself on 127.0.0.1 (never Instagram): one port plays the site, another the CDN.
|
||
/// </summary>
|
||
public sealed class LocalTestSite : IDisposable
|
||
{
|
||
public const int BigFileBytes = 24 * 1024 * 1024;
|
||
|
||
private static readonly Lazy<(byte[] Bytes, string Sha256)> BigFile = new(() =>
|
||
{
|
||
var bytes = new byte[BigFileBytes];
|
||
new Random(20261013).NextBytes(bytes);
|
||
return (bytes, Convert.ToHexString(SHA256.HashData(bytes)));
|
||
});
|
||
|
||
private readonly HttpListener _listener = new();
|
||
private readonly CancellationTokenSource _stop = new();
|
||
|
||
public LocalTestSite()
|
||
{
|
||
SitePort = FreePort();
|
||
CdnPort = FreePort();
|
||
_listener.Prefixes.Add($"http://127.0.0.1:{SitePort}/");
|
||
_listener.Prefixes.Add($"http://127.0.0.1:{CdnPort}/");
|
||
_listener.Start();
|
||
_ = Task.Run(LoopAsync);
|
||
}
|
||
|
||
public int SitePort { get; }
|
||
|
||
public int CdnPort { get; }
|
||
|
||
public string SiteHost => $"127.0.0.1:{SitePort}";
|
||
|
||
public string CdnHost => $"127.0.0.1:{CdnPort}";
|
||
|
||
public static string BigFileSha256 => BigFile.Value.Sha256;
|
||
|
||
public string Url(string path) => $"http://{SiteHost}{path}";
|
||
|
||
/// <summary>The same site under the name «localhost»: another site for Chromium, so another renderer.</summary>
|
||
public string LocalhostUrl(string path) => $"http://localhost:{SitePort}{path}";
|
||
|
||
public string CdnUrl(string path) => $"http://{CdnHost}{path}";
|
||
|
||
public static int FreePort()
|
||
{
|
||
var probe = new TcpListener(IPAddress.Loopback, 0);
|
||
probe.Start();
|
||
var port = ((IPEndPoint)probe.LocalEndpoint).Port;
|
||
probe.Stop();
|
||
return port;
|
||
}
|
||
|
||
private int _disposed;
|
||
|
||
public void Dispose()
|
||
{
|
||
if (Interlocked.Exchange(ref _disposed, 1) == 1)
|
||
{
|
||
return;
|
||
}
|
||
|
||
_stop.Cancel();
|
||
try
|
||
{
|
||
_listener.Stop();
|
||
_listener.Close();
|
||
}
|
||
catch (ObjectDisposedException)
|
||
{
|
||
}
|
||
|
||
_stop.Dispose();
|
||
}
|
||
|
||
private async Task LoopAsync()
|
||
{
|
||
while (!_stop.IsCancellationRequested)
|
||
{
|
||
HttpListenerContext context;
|
||
try
|
||
{
|
||
context = await _listener.GetContextAsync();
|
||
}
|
||
catch (Exception ex) when (ex is HttpListenerException or ObjectDisposedException or InvalidOperationException)
|
||
{
|
||
return;
|
||
}
|
||
|
||
_ = Task.Run(() => HandleAsync(context));
|
||
}
|
||
}
|
||
|
||
private async Task HandleAsync(HttpListenerContext context)
|
||
{
|
||
var response = context.Response;
|
||
try
|
||
{
|
||
var path = context.Request.Url!.AbsolutePath;
|
||
if (context.Request.Url.Port == CdnPort)
|
||
{
|
||
if (path == "/file.bin")
|
||
{
|
||
response.ContentType = "application/octet-stream";
|
||
response.ContentLength64 = BigFile.Value.Bytes.Length;
|
||
await response.OutputStream.WriteAsync(BigFile.Value.Bytes);
|
||
}
|
||
else
|
||
{
|
||
response.StatusCode = 404;
|
||
}
|
||
|
||
return;
|
||
}
|
||
|
||
switch (path)
|
||
{
|
||
case "/api/dati.json":
|
||
await JsonAsync(response, 200, """{"elementi":[{"id":"1","testo":"ciao"},{"id":"2","testo":"mondo"}]}""");
|
||
return;
|
||
case "/api/troppe":
|
||
await JsonAsync(response, 429, """{"messaggio":"troppe richieste"}""");
|
||
return;
|
||
case "/api/attendi.json":
|
||
await JsonAsync(response, 200, """{"messaggio":"Attendi qualche minuto prima di riprovare."}""");
|
||
return;
|
||
case "/vai-a-verifica":
|
||
response.StatusCode = 302;
|
||
response.RedirectLocation = "/verifica?da=prova";
|
||
return;
|
||
case "/cookie":
|
||
response.AppendHeader("Set-Cookie", "sessionid=valore-finto-di-prova; Path=/; Max-Age=86400; SameSite=Lax");
|
||
await HtmlAsync(response, "<p>Cookie impostato</p>");
|
||
return;
|
||
default:
|
||
await HtmlAsync(response, Page(path));
|
||
return;
|
||
}
|
||
}
|
||
catch (Exception ex) when (ex is HttpListenerException or IOException or ObjectDisposedException)
|
||
{
|
||
}
|
||
finally
|
||
{
|
||
try
|
||
{
|
||
response.Close();
|
||
}
|
||
catch (Exception ex) when (ex is HttpListenerException or ObjectDisposedException or InvalidOperationException)
|
||
{
|
||
}
|
||
}
|
||
}
|
||
|
||
private static string Page(string path) => path switch
|
||
{
|
||
"/lunga" => string.Concat(Enumerable.Range(1, 300).Select(i => $"<p>Riga {i} di una pagina lunga.</p>"))
|
||
+ "<script>window.__wheel = { count: 0, trusted: true };"
|
||
+ "addEventListener('wheel', (e) => { window.__wheel.count++; window.__wheel.trusted = window.__wheel.trusted && e.isTrusted; }, { passive: true });</script>",
|
||
"/bottoni" => """
|
||
<div style="height:3000px;position:relative">
|
||
<button id="b1" aria-label="Indietro" style="position:absolute;left:100px;top:100px;width:120px;height:40px">‹</button>
|
||
<button id="b2" aria-label="Avanti" style="position:absolute;left:400px;top:300px;width:160px;height:50px">›</button>
|
||
<button id="b3" aria-label="Avanti" style="display:none">nascosto</button>
|
||
<a id="l1" href="/profilo/alice/" style="position:absolute;left:100px;top:500px">alice</a>
|
||
<a id="l2" href="/stories/alice/123/" style="position:absolute;left:300px;top:500px"><span>Storia di alice</span></a>
|
||
<button id="b4" aria-label="Coperto" style="position:absolute;left:700px;top:100px;width:100px;height:40px">x</button>
|
||
<div style="position:absolute;left:690px;top:90px;width:140px;height:70px;background:#ddd"></div>
|
||
<button id="b5" style="position:absolute;left:400px;top:2400px;width:120px;height:40px">Lontano</button>
|
||
</div>
|
||
<script>
|
||
window.__clicks = [];
|
||
window.__moves = 0;
|
||
document.addEventListener('mousemove', () => { window.__moves++; });
|
||
document.addEventListener('click', (e) => {
|
||
const t = e.target.closest('[id]');
|
||
window.__clicks.push({ id: t ? t.id : '', x: e.clientX, y: e.clientY, trusted: e.isTrusted });
|
||
});
|
||
</script>
|
||
""",
|
||
"/cattura" => "<p>Cattura</p><script>addEventListener('load', () => fetch('/api/dati.json').then((r) => r.json()).then(() => { document.title = 'caricato'; }));</script>",
|
||
"/cattura-429" => "<p>Troppe</p><script>addEventListener('load', () => fetch('/api/troppe').then((r) => r.text()));</script>",
|
||
"/cattura-attendi" => "<p>Attendi</p><script>addEventListener('load', () => fetch('/api/attendi.json').then((r) => r.json()));</script>",
|
||
"/animata" => """
|
||
<style>@keyframes giro { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
|
||
#q { width: 200px; height: 200px; margin: 100px; background: #c63; animation: giro 1s linear infinite; }</style>
|
||
<div id="q"></div>
|
||
""",
|
||
"/modulo" => """
|
||
<input id="campo" aria-label="Campo" style="position:absolute;left:200px;top:200px;width:300px;height:30px">
|
||
<script>
|
||
window.__keys = 0;
|
||
window.__clicks = 0;
|
||
document.addEventListener('keydown', () => { window.__keys++; });
|
||
document.addEventListener('mousedown', () => { window.__clicks++; });
|
||
</script>
|
||
""",
|
||
"/spa" => "<p>Applicazione</p><script>addEventListener('load', () => setTimeout(() => history.pushState({}, '', '/verifica/interna?x=1'), 300));</script>",
|
||
"/verifica" => "<h1>Verifica</h1>",
|
||
"/accesso" => "<h1>Accesso</h1>",
|
||
|
||
// Keeps its renderer busy for 2 s, from 0.1 s after it has committed: a navigation away from it to a page of the
|
||
// same site (same renderer) reaches «ready to commit» at once but commits only when the script lets go.
|
||
"/occupata" => "<p>Occupata</p><script>setTimeout(() => { const end = performance.now() + 2000; while (performance.now() < end) { } }, 100);</script>",
|
||
_ => "<p>Pagina di prova</p>",
|
||
};
|
||
|
||
private static Task HtmlAsync(HttpListenerResponse response, string body) =>
|
||
WriteAsync(response, 200, "text/html; charset=utf-8", $"<!doctype html><html lang=\"it\"><head><meta charset=\"utf-8\"><title>Prova</title></head><body>{body}</body></html>");
|
||
|
||
private static Task JsonAsync(HttpListenerResponse response, int status, string json) =>
|
||
WriteAsync(response, status, "application/json; charset=utf-8", json);
|
||
|
||
private static async Task WriteAsync(HttpListenerResponse response, int status, string contentType, string body)
|
||
{
|
||
var bytes = Encoding.UTF8.GetBytes(body);
|
||
response.StatusCode = status;
|
||
response.ContentType = contentType;
|
||
response.ContentLength64 = bytes.Length;
|
||
response.AddHeader("Cache-Control", "no-store");
|
||
await response.OutputStream.WriteAsync(bytes);
|
||
}
|
||
}
|