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>
337 lines
14 KiB
C#
337 lines
14 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);
|
|
|
|
await bed.StepAsync(TimeSpan.FromSeconds(2.25), 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 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);
|
|
}
|
|
}
|
|
}
|
|
}
|