Files
Febe/src/Febe.Web/Api/EngineApi.cs
T
Alby96andClaude Opus 5.5 654076d280 Browser vuoto: correzioni dopo la revisione (#52)
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>
2026-11-16 13:28:08 +01:00

285 lines
12 KiB
C#

using System.Text;
using System.Text.Json;
using System.Threading.Channels;
using Febe.Core.Abstractions;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Febe.Web.Library;
using Febe.Web.Native;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace Febe.Web.Api;
/// <summary>The engine for the interface: snapshot, «Metti in pausa», «Riprendi», the browser, and the event stream.</summary>
public static class EngineApi
{
/// <summary>Idle time after which a comment line keeps the event stream open through proxies.</summary>
public static readonly TimeSpan Heartbeat = TimeSpan.FromSeconds(25);
/// <summary>The snapshot is pushed again at least this often, so «8 min fa» and «verso le» stay current.</summary>
public static readonly TimeSpan Refresh = TimeSpan.FromSeconds(60);
public static void Map(IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/api/engine", async (IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct) =>
ApiHttp.Json(await SnapshotAsync(monitor, storage, tracker, clock, connection, ct).ConfigureAwait(false), FebeJsonContext.Default.EngineDto));
endpoints.MapPost("/api/engine/pause", async (IEngineControl control, CancellationToken ct) =>
{
await control.PauseAsync(ct).ConfigureAwait(false);
return ApiHttp.Message("Febe è in pausa: non apre nulla finché non premi «Riprendi».");
});
endpoints.MapPost("/api/engine/resume", async (IEngineControl control, CancellationToken ct) =>
{
var result = await control.ResumeAsync(ct).ConfigureAwait(false);
return ApiHttp.Json(new ResumeDto(result.Resumed, result.Message), FebeJsonContext.Default.ResumeDto);
});
// «Riattiva» a recipe suspended after three unknown formats (or targets not found) in a row.
endpoints.MapPost("/api/engine/recipes/{recipe}/resume", async (string recipe, IEngineControl control, CancellationToken ct) =>
{
if (!Enum.TryParse<RecipeKind>(recipe, ignoreCase: true, out var kind) || !Enum.IsDefined(kind))
{
throw new BadRequestException("Ricetta sconosciuta.");
}
var resumed = await control.ResumeRecipeAsync(kind, ct).ConfigureAwait(false);
return ApiHttp.Json(
new ResumeDto(resumed, resumed
? "Ricetta riattivata: riprende alla prossima sessione. Se il formato è ancora sconosciuto, si sospende di nuovo dopo tre volte."
: "Questa ricetta non era sospesa."),
FebeJsonContext.Default.ResumeDto);
});
// «Apri il browser» on Windows: the window of the browser comes to the front, on the start page when it was at rest
// and on the login page with { openLogin: true } (the red strip of a disconnection; issue #52).
endpoints.MapPost("/api/browser/show", async (HttpContext context, IBrowserWindow browser, IConnectionService connection, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
{
if (!browser.IsSeparateWindow)
{
throw new BadRequestException("Qui il browser di Febe si usa dalla pagina Browser.");
}
var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest, new BeginDrivingRequest(false)).ConfigureAwait(false);
await connection.ShowBrowserAsync(body.OpenLogin, ct).ConfigureAwait(false);
tracker.MarkUsed(clock.Now);
return ApiHttp.Message("Il browser di Febe è in primo piano.");
});
// The Browser page («Ho finito») and the desktop window report that Alberto used the browser: «Riprendi» activates.
endpoints.MapPost("/api/browser/used", (BrowserUseTracker tracker, IClock clock) =>
{
tracker.MarkUsed(clock.Now);
return ApiHttp.Message("Bene: ora puoi premere «Riprendi».");
});
endpoints.MapGet("/api/eventi", StreamAsync);
}
/// <summary>
/// The engine as the interface needs it. The link comes from the session cookie, never from whether «Tu» is known:
/// the name of the connected account may come much later (H10), and meanwhile the sidebar says «Collegato» with
/// «Nome non ancora noto». The engine looks at the cookie on every turn and its mode says so; when it does not run
/// (or there is none in this process) the connection is asked.
/// </summary>
public static async Task<EngineDto> SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(monitor);
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(tracker);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(connection);
var snapshot = await monitor.GetSnapshotAsync(ct).ConfigureAwait(false);
var mine = await storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
var state = snapshot.Mode switch
{
EngineMode.NotConnected => "notConnected",
EngineMode.StoppedForVerification => "verification",
EngineMode.Disconnected => "disconnected",
EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State == ConnectionState.Connected ? "connected" : "notConnected",
_ => "connected",
};
var link = state == "notConnected"
? new ConnectionDto(state, null, null, null)
: new ConnectionDto(state, mine?.Username, mine?.DisplayName, null);
bool canResume;
if (snapshot.Banner is { NeedsResume: true })
{
var since = snapshot.Breaker.LastSignal?.At ?? DateTimeOffset.MinValue;
canResume = tracker.LastUsedAt is { } used && used >= since;
}
else
{
canResume = snapshot.Mode == EngineMode.Paused;
}
return new EngineDto(clock.Now.ToUnixTimeMilliseconds(), snapshot, link, canResume);
}
/// <summary>
/// <c>/api/eventi</c>: server-sent events. <c>motore</c> carries the engine (at once, at every change, at least every
/// minute); <c>libreria</c> says the library changed (at most every second and a half); a comment line keeps the
/// stream open. Never contains captions, bodies or addresses.
/// </summary>
public static async Task StreamAsync(
HttpContext context,
IEngineMonitor monitor,
IFebeStorage storage,
BrowserUseTracker tracker,
LibraryChanges library,
IClock clock,
IConnectionService connection)
{
ArgumentNullException.ThrowIfNull(context);
var response = context.Response;
response.ContentType = "text/event-stream; charset=utf-8";
response.Headers.CacheControl = "no-cache, no-transform";
response.Headers["X-Accel-Buffering"] = "no";
var ct = context.RequestAborted;
var signals = Channel.CreateBounded<string>(new BoundedChannelOptions(64) { FullMode = BoundedChannelFullMode.DropOldest });
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct);
var engineTask = Task.Run(
async () =>
{
await foreach (var _ in monitor.SubscribeAsync(stop.Token).ConfigureAwait(false))
{
signals.Writer.TryWrite("motore");
}
},
CancellationToken.None);
var libraryTask = Task.Run(
async () =>
{
await foreach (var change in library.SubscribeAsync(stop.Token).ConfigureAwait(false))
{
signals.Writer.TryWrite("libreria:" + JsonSerializer.Serialize(change, FebeJsonContext.Default.LibraryChange));
}
},
CancellationToken.None);
try
{
await WriteAsync(response, "retry: 3000\n\n", ct).ConfigureAwait(false);
await SendEngineAsync().ConfigureAwait(false);
var libraryGap = TimeSpan.FromMilliseconds(1500);
var lastEngine = DateTimeOffset.UtcNow;
var lastLibrary = DateTimeOffset.MinValue;
string? pendingLibrary = null;
var enginePending = false;
while (!ct.IsCancellationRequested)
{
var now = DateTimeOffset.UtcNow;
var wait = Heartbeat;
if (lastEngine + Refresh - now < wait)
{
wait = lastEngine + Refresh - now;
}
if (pendingLibrary is not null && lastLibrary + libraryGap - now < wait)
{
wait = lastLibrary + libraryGap - now;
}
var got = await WaitAsync(signals.Reader, wait < TimeSpan.Zero ? TimeSpan.Zero : wait, ct).ConfigureAwait(false);
if (got)
{
// Changes come in bursts: wait a moment and send one update for all of them.
await Task.Delay(TimeSpan.FromMilliseconds(300), ct).ConfigureAwait(false);
while (signals.Reader.TryRead(out var signal))
{
if (signal == "motore")
{
enginePending = true;
}
else
{
pendingLibrary = signal["libreria:".Length..];
}
}
}
now = DateTimeOffset.UtcNow;
var sent = false;
if (enginePending || now - lastEngine >= Refresh)
{
await SendEngineAsync().ConfigureAwait(false);
enginePending = false;
lastEngine = now;
sent = true;
}
if (pendingLibrary is not null && now - lastLibrary >= libraryGap)
{
await WriteAsync(response, "event: libreria\ndata: " + pendingLibrary + "\n\n", ct).ConfigureAwait(false);
pendingLibrary = null;
lastLibrary = now;
sent = true;
}
if (!sent && !got)
{
await WriteAsync(response, ": ancora qui\n\n", ct).ConfigureAwait(false);
}
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// The page closed the stream.
}
catch (IOException)
{
// The connection dropped.
}
finally
{
await stop.CancelAsync().ConfigureAwait(false);
await Task.WhenAll(Quiet(engineTask), Quiet(libraryTask)).ConfigureAwait(false);
}
async Task SendEngineAsync()
{
var dto = await SnapshotAsync(monitor, storage, tracker, clock, connection, ct).ConfigureAwait(false);
await WriteAsync(response, "event: motore\ndata: " + JsonSerializer.Serialize(dto, FebeJsonContext.Default.EngineDto) + "\n\n", ct).ConfigureAwait(false);
}
}
private static async Task<bool> WaitAsync(ChannelReader<string> reader, TimeSpan wait, CancellationToken ct)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(wait);
try
{
return await reader.WaitToReadAsync(timeout.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
return false;
}
}
private static async Task WriteAsync(HttpResponse response, string text, CancellationToken ct)
{
await response.Body.WriteAsync(Encoding.UTF8.GetBytes(text), ct).ConfigureAwait(false);
await response.Body.FlushAsync(ct).ConfigureAwait(false);
}
private static async Task Quiet(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
}