La revisione di c49df4c ha trovato alcuni punti deboli. Si correggono qui.
- Fuori vista la pagina torna al 100%. Lo zoom calcolato per uno schermo
piccolo restava anche per le sessioni del motore, e le pagine vedevano un
devicePixelRatio diverso (regola 4). Il rapporto si ricalcola solo quando
la finestra viene sullo schermo.
- Pulsante nella barra delle applicazioni. WPF lo cambia nascondendo la
finestra e mostrandola di nuovo (verificato con un aggancio a
WM_WINDOWPOSCHANGED). Ora il pulsante cambia solo mentre la finestra è
fuori vista. Sullo schermo la finestra chiede di ridisegnarsi
(RedrawWindow), senza nulla che la pagina veda. Una prova con WebView2
vero controlla che la finestra non si nasconda mai sullo schermo.
- Ridotta a icona troppo a lungo, la finestra si ripristina coperta (DWM) e
senza prendere il fuoco, e si sposta fuori vista prima di scoprirsi. Prima
ricompariva per un attimo dove stava. Spostare la posizione di ripristino
non basta: Windows la riporta su uno schermo (provato).
- Dopo un riavvio del processo GPU i bordi della pagina cambiano davvero: un
pixel in meno, poi quelli veri. Gli stessi bordi di nuovo potevano non
servire a nulla.
- «Pagina iniziale», sulla barra di Windows e nella vista remota, passa da
BrowserConnectionService.OpenStartPageAsync. Aspetta la fine della
sessione del motore e il turno della pagina, come l'apertura dal riposo,
e agisce solo mentre Alberto guida.
- Vista remota.
- Dopo un riavvio dei fotogrammi la vista aspetta il primo fotogramma per
mezzo secondo prima dell'immagine ferma: Chromium lo manda solo dopo la
risposta allo start, e prima quasi ogni riavvio costava una cattura.
- L'immagine ferma si scarta se nel frattempo arriva un fotogramma vero.
- Il silenzio si conta dall'avvio.
- Un riavvio del browser durante la chiusura non lascia eccezioni non
osservate.
- Un POST vuoto senza Content-Length (a pezzi, HTTP/2) non dà più 400 su
begin, cancel e browser/show (ApiHttp.OptionalBodyAsync).
- La pagina Browser toglie ?accesso=1 dall'indirizzo. Ricaricarla riapriva
la pagina di accesso.
- RemoteViewFramesTests aspetta fino a 20 s invece di 5. Controlla che
l'immagine arrivi, non quanto in fretta; il tempo va nell'uscita della
prova.
Aggiornati PROTOCOLLO.md, la guida (Primo collegamento, Installazione
Windows) e docs/decisioni.md con le righe di #52.
Prove nuove:
- AFrameSoonAfterARestartNeedsNoStillPicture
- PaginaInizialeWaitsForThePageTurnAndActsOnlyWhileAlbertoIsAtTheBrowser
- ABodyWithoutALengthIsReadAndAnEmptyOneIsNoBody
- nella prova della finestra vera: nessun nascondere sullo schermo e pagina
al 100% fuori vista
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
357 lines
15 KiB
C#
357 lines
15 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Text.Json.Nodes;
|
|
using Febe.Browser.Cdp;
|
|
using Febe.Browser.Diagnostics;
|
|
using Febe.Browser.RemoteView;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Tests.Browser.TestSupport;
|
|
|
|
namespace Febe.Tests.Browser;
|
|
|
|
/// <summary>
|
|
/// The frames' watchdog of the remote view (Gitea issue #52), without a browser: a lost acknowledgement, a page that
|
|
/// does not repaint and a new document loaded without frames must never leave the view white and silent. The clock
|
|
/// moves only when the test says so, one look of the watchdog at a time.
|
|
/// </summary>
|
|
[TestClass]
|
|
public sealed class ScreencastWatchdogTests
|
|
{
|
|
private static readonly ScreencastWatchdog Watchdog = new(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(250), TimeSpan.FromSeconds(30));
|
|
|
|
public TestContext TestContext { get; set; } = null!;
|
|
|
|
[TestMethod]
|
|
[Timeout(30_000, CooperativeCancellation = true)]
|
|
public async Task ALostAcknowledgementIsFollowedByARestartAndTheFramesComeBack()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var bed = new Bed(lostAcks: true);
|
|
await bed.StartAsync(ct);
|
|
bed.Frame();
|
|
Assert.AreEqual(1, bed.Starts);
|
|
|
|
// The ack was lost: Chromium sends nothing more. Two seconds later the frames are started again.
|
|
await bed.StepAsync(TimeSpan.FromSeconds(2.25), ct);
|
|
|
|
Assert.AreEqual(1, bed.Session.Restarts);
|
|
Assert.AreEqual(2, bed.Starts, "a new screencast session");
|
|
var methods = bed.Cdp.Sent.Select(c => c.Method).Where(m => m is "Page.stopScreencast" or "Page.startScreencast").ToList();
|
|
CollectionAssert.AreEqual(new[] { "Page.startScreencast", "Page.stopScreencast", "Page.startScreencast" }, methods);
|
|
Assert.IsTrue(bed.Info.Contains("Vista remota: nessun fotogramma da 2 s, riavvio dei fotogrammi."), bed.AllLines);
|
|
|
|
// Frames flow again: said once, at Info.
|
|
for (var i = 0; i < ScreencastWatchdog.FlowingFrames; i++)
|
|
{
|
|
bed.Frame();
|
|
}
|
|
|
|
Assert.IsTrue(bed.Info.Any(l => l.StartsWith("Vista remota: fotogrammi di nuovo in arrivo, dopo ", StringComparison.Ordinal)), bed.AllLines);
|
|
Assert.AreEqual(1 + ScreencastWatchdog.FlowingFrames, bed.Session.FramesReceived);
|
|
|
|
// The stop is the last word: no start after it.
|
|
await bed.Session.StopAsync(ct);
|
|
Assert.AreEqual("Page.stopScreencast", bed.Cdp.Sent.Last(c => c.Method.Contains("Screencast", StringComparison.Ordinal) && c.Method != "Page.screencastFrameAck").Method);
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(30_000, CooperativeCancellation = true)]
|
|
public async Task APageThatNeverSendsAFrameGetsAStillPictureOfItself()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var bed = new Bed(screenshot: Jpeg(800, 600));
|
|
await bed.StartAsync(ct);
|
|
|
|
// The restart after two seconds, then its wait for a first frame.
|
|
await bed.StepAsync(TimeSpan.FromSeconds(2.25) + ScreencastWatchdog.FirstFrameWait, ct);
|
|
|
|
var still = bed.Session.LastFrame;
|
|
Assert.IsNotNull(still, "something to show");
|
|
Assert.IsTrue(still.Still);
|
|
Assert.AreEqual(800, still.DeviceWidth, "the size written in the picture");
|
|
Assert.AreEqual(600, still.DeviceHeight);
|
|
Assert.AreEqual(0, bed.Session.FramesReceived, "a still picture is not a frame of the screencast");
|
|
Assert.AreEqual(1, bed.Cdp.Sent.Count(c => c.Method == "Page.captureScreenshot"));
|
|
|
|
using var read = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
read.CancelAfter(TimeSpan.FromSeconds(5));
|
|
await foreach (var frame in bed.Session.ReadFramesAsync(read.Token))
|
|
{
|
|
Assert.IsTrue(frame.Still, "the reader gets it like any frame");
|
|
break;
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(30_000, CooperativeCancellation = true)]
|
|
public async Task AFrameSoonAfterARestartNeedsNoStillPicture()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var bed = new Bed(screenshot: Jpeg(800, 600));
|
|
await bed.StartAsync(ct);
|
|
|
|
// Restarted after two seconds: Chromium answers the start first and sends its frame a moment later.
|
|
await bed.StepAsync(TimeSpan.FromSeconds(2.25), ct);
|
|
Assert.AreEqual(1, bed.Session.Restarts);
|
|
bed.Frame();
|
|
await bed.StepAsync(TimeSpan.FromSeconds(1), ct);
|
|
|
|
Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.captureScreenshot"), "the frame came: no picture taken. " + string.Join(", ", bed.Cdp.Sent.Where(c => c.Method != "Page.screencastFrameAck").Select(c => $"{c.Method}@{c.At:ss.fff}")) + " | " + bed.AllLines);
|
|
Assert.IsNotNull(bed.Session.LastFrame);
|
|
Assert.IsFalse(bed.Session.LastFrame.Still);
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(30_000, CooperativeCancellation = true)]
|
|
public async Task ANewDocumentLoadedWithoutFramesStartsThemAgainAtTheNextLook()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var bed = new Bed();
|
|
await bed.StartAsync(ct);
|
|
bed.Frame();
|
|
|
|
// A frame of a page inside the page changes nothing; the main frame does.
|
|
bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F2", ["parentId"] = "F1", ["url"] = "http://127.0.0.1/pubblicita" } });
|
|
bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "http://127.0.0.1/animata" } });
|
|
bed.Cdp.Raise("Page.loadEventFired", new JsonObject { ["timestamp"] = 1.0 });
|
|
|
|
await bed.StepAsync(Watchdog.Tick, ct);
|
|
|
|
Assert.AreEqual(1, bed.Session.Restarts, "no two seconds of white after a new page");
|
|
Assert.IsTrue(bed.Info.Contains("Vista remota: pagina nuova caricata senza fotogrammi, riavvio dei fotogrammi."), bed.AllLines);
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(30_000, CooperativeCancellation = true)]
|
|
public async Task ANewDocumentWhoseFramesArriveIsLeftAlone()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var bed = new Bed();
|
|
await bed.StartAsync(ct);
|
|
|
|
bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "http://127.0.0.1/animata" } });
|
|
bed.Frame();
|
|
bed.Cdp.Raise("Page.loadEventFired", new JsonObject { ["timestamp"] = 1.0 });
|
|
for (var i = 0; i < 6; i++)
|
|
{
|
|
await bed.StepAsync(Watchdog.Tick, ct);
|
|
bed.Frame();
|
|
}
|
|
|
|
Assert.AreEqual(0, bed.Session.Restarts);
|
|
Assert.AreEqual(1, bed.Starts);
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(60_000, CooperativeCancellation = true)]
|
|
public async Task AStillPageCostsFewerAndFewerRestartsAndOneLineInTheRegistro()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var bed = new Bed(screenshot: Jpeg(1280, 900));
|
|
await bed.StartAsync(ct);
|
|
|
|
// Thirty seconds of a page that does not move: restarts after 2, 4, 8 and 16 more seconds, not fifteen.
|
|
await bed.StepAsync(TimeSpan.FromSeconds(30.25), ct);
|
|
|
|
Assert.AreEqual(4, bed.Session.Restarts, bed.AllLines);
|
|
Assert.AreEqual(1, bed.Info.Count(l => l.Contains("riavvio dei fotogrammi", StringComparison.Ordinal)), "one line for the whole silence, the others at Debug");
|
|
Assert.IsFalse(bed.AllLines.Contains("http", StringComparison.Ordinal), "no addresses in the registro");
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(30_000, CooperativeCancellation = true)]
|
|
public async Task WithoutAWatchdogNothingIsStartedAgain()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var bed = new Bed(noWatchdog: true);
|
|
await bed.StartAsync(ct);
|
|
|
|
Assert.AreEqual(0, bed.Clock.Waiting, "nobody watches");
|
|
bed.Clock.Advance(TimeSpan.FromMinutes(1));
|
|
Assert.AreEqual(1, bed.Starts);
|
|
Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.captureScreenshot"));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void TheSizeOfAJpegIsReadFromItsFrameHeader()
|
|
{
|
|
Assert.AreEqual((800, 600), ScreencastSession.JpegSize(Jpeg(800, 600)));
|
|
Assert.AreEqual((1280, 900), ScreencastSession.JpegSize(Jpeg(1280, 900, progressive: true)));
|
|
Assert.IsNull(ScreencastSession.JpegSize([0xFF, 0xD8, 0xFF, 0xD9]), "no frame header");
|
|
Assert.IsNull(ScreencastSession.JpegSize([0x89, 0x50, 0x4E, 0x47]), "not a JPEG");
|
|
Assert.IsNull(ScreencastSession.JpegSize([]));
|
|
Assert.IsNull(ScreencastSession.JpegSize([0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08]), "cut short");
|
|
}
|
|
|
|
/// <summary>A minimal JPEG header: SOI, an APP0 segment, then a SOF0 (or SOF2) with the size.</summary>
|
|
private static byte[] Jpeg(int width, int height, bool progressive = false) =>
|
|
[
|
|
0xFF, 0xD8,
|
|
0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00,
|
|
0xFF, progressive ? (byte)0xC2 : (byte)0xC0, 0x00, 0x11, 0x08,
|
|
(byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width,
|
|
0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01,
|
|
0xFF, 0xD9,
|
|
];
|
|
|
|
/// <summary>A screencast over a fake page and a clock that moves only when stepped.</summary>
|
|
private sealed class Bed : IAsyncDisposable
|
|
{
|
|
private readonly ConcurrentQueue<(BrowserLogLevel Level, string Message)> _lines = new();
|
|
private readonly ScreencastWatchdog? _watchdog;
|
|
private int _starts;
|
|
private int _frameSession;
|
|
|
|
public Bed(bool lostAcks = false, byte[]? screenshot = null, bool noWatchdog = false)
|
|
{
|
|
_watchdog = noWatchdog ? null : Watchdog;
|
|
Clock = new SteppingClock();
|
|
Cdp = new FakeCdpSession(Clock)
|
|
{
|
|
Responder = (method, _) =>
|
|
{
|
|
switch (method)
|
|
{
|
|
case "Page.startScreencast":
|
|
Interlocked.Increment(ref _starts);
|
|
return null;
|
|
case "Page.screencastFrameAck" when lostAcks:
|
|
throw new CdpCommandException(method, CdpCommandException.ServerErrorCode, "Session is not attached");
|
|
case "Page.captureScreenshot":
|
|
return screenshot is null ? null : new JsonObject { ["data"] = Convert.ToBase64String(screenshot) };
|
|
default:
|
|
return null;
|
|
}
|
|
},
|
|
};
|
|
Session = new ScreencastSession(Cdp, new DelegateBrowserLog((level, message, _) => _lines.Enqueue((level, message))), Clock);
|
|
}
|
|
|
|
public SteppingClock Clock { get; }
|
|
|
|
public FakeCdpSession Cdp { get; }
|
|
|
|
public ScreencastSession Session { get; }
|
|
|
|
public int Starts => Volatile.Read(ref _starts);
|
|
|
|
public List<string> Info => [.. _lines.Where(l => l.Level == BrowserLogLevel.Information).Select(l => l.Message)];
|
|
|
|
public string AllLines => string.Join('\n', _lines.Select(l => $"{l.Level} {l.Message}"));
|
|
|
|
public async Task StartAsync(CancellationToken ct)
|
|
{
|
|
await Session.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900, Watchdog: _watchdog), ct);
|
|
if (_watchdog is not null)
|
|
{
|
|
await Clock.WaitForSleeperAsync(ct);
|
|
}
|
|
}
|
|
|
|
/// <summary>A frame of the screencast, as Chromium sends it.</summary>
|
|
public void Frame() => Cdp.Raise("Page.screencastFrame", new JsonObject
|
|
{
|
|
["sessionId"] = Interlocked.Increment(ref _frameSession),
|
|
["data"] = Convert.ToBase64String(Jpeg(1280, 900)),
|
|
["metadata"] = new JsonObject { ["deviceWidth"] = 1280, ["deviceHeight"] = 900, ["pageScaleFactor"] = 1 },
|
|
});
|
|
|
|
/// <summary>Moves the clock by <paramref name="time"/>, one look of the watchdog at a time.</summary>
|
|
public async Task StepAsync(TimeSpan time, CancellationToken ct)
|
|
{
|
|
var tick = (_watchdog ?? Watchdog).Tick;
|
|
for (var moved = TimeSpan.Zero; moved < time; moved += tick)
|
|
{
|
|
Clock.Advance(tick);
|
|
await Clock.WaitForSleeperAsync(ct);
|
|
}
|
|
}
|
|
|
|
public async ValueTask DisposeAsync() => await Session.DisposeAsync();
|
|
}
|
|
|
|
/// <summary>A clock whose delays end only when the test moves it past them.</summary>
|
|
private sealed class SteppingClock : IClock
|
|
{
|
|
private readonly Lock _gate = new();
|
|
private readonly List<(DateTimeOffset Due, TaskCompletionSource Done)> _sleepers = [];
|
|
private DateTimeOffset _now = new(2026, 11, 16, 9, 0, 0, TimeSpan.Zero);
|
|
|
|
public DateTimeOffset Now
|
|
{
|
|
get
|
|
{
|
|
lock (_gate)
|
|
{
|
|
return _now;
|
|
}
|
|
}
|
|
}
|
|
|
|
public TimeZoneInfo LocalZone => TimeZoneInfo.Utc;
|
|
|
|
public int Waiting
|
|
{
|
|
get
|
|
{
|
|
lock (_gate)
|
|
{
|
|
return _sleepers.Count;
|
|
}
|
|
}
|
|
}
|
|
|
|
public Task Delay(TimeSpan time, CancellationToken ct)
|
|
{
|
|
ct.ThrowIfCancellationRequested();
|
|
if (time <= TimeSpan.Zero)
|
|
{
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
lock (_gate)
|
|
{
|
|
_sleepers.Add((_now + time, done));
|
|
}
|
|
|
|
ct.Register(() =>
|
|
{
|
|
lock (_gate)
|
|
{
|
|
_sleepers.RemoveAll(s => s.Done == done);
|
|
}
|
|
|
|
done.TrySetCanceled(ct);
|
|
});
|
|
return done.Task;
|
|
}
|
|
|
|
public void Advance(TimeSpan time)
|
|
{
|
|
List<TaskCompletionSource> due;
|
|
lock (_gate)
|
|
{
|
|
_now += time;
|
|
due = [.. _sleepers.Where(s => s.Due <= _now).Select(s => s.Done)];
|
|
_sleepers.RemoveAll(s => s.Due <= _now);
|
|
}
|
|
|
|
foreach (var done in due)
|
|
{
|
|
done.TrySetResult();
|
|
}
|
|
}
|
|
|
|
/// <summary>Waits (in real time) until someone sleeps on the clock again: the watchdog finished its look.</summary>
|
|
public async Task WaitForSleeperAsync(CancellationToken ct)
|
|
{
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
|
while (Waiting == 0)
|
|
{
|
|
await Task.Delay(1, timeout.Token);
|
|
}
|
|
}
|
|
}
|
|
}
|