Docker: lasciare la pagina del browser copia la sessione (#36, S4b, risposta 1)
verifica / controlli (push) Successful in 24s
verifica / prove (push) Failing after 41m21s
verifica / installatore (push) Skipped
verifica / immagine (push) Skipped

In Docker lasciare la pagina «Browser» o la vista remota di Collegamento mentre
Alberto guida (un'altra pagina, la scheda chiusa, il collegamento perso) valeva
«Annulla» e la sessione non si copiava. Ora è come chiudere la finestra del
browser su Windows: `cancel` con `pageLeft` va a LeavePageAsync, la vista
remota chiusa dalla sua pagina lo dice alla connessione, e se per 5 secondi
non si apre un'altra vista né arriva un `begin` (una pagina ricaricata) il
controllo del permesso copia la sessione con CopyOnLetGoAsync, solo da una
pagina del sito che non sia di accesso o di verifica, poi rilascia il permesso
e il motore rimette il browser a riposo. Il pulsante «Annulla» continua a non
copiare; Windows non cambia.

Prove nuove per la copia lasciando la pagina, la ricarica che non è lasciare,
la pagina di accesso, la vista sostituita o chiusa da Febe; guida, protocollo
e una riga in decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-25 10:52:51 +01:00
1 parent 537517b855
commit 2fc4b40c41
15 files changed
+312 -44

No files matched your search

+1
View File
@@ -458,3 +458,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-18 | Correzioni della revisione di S4b. (1) Un errore imprevisto durante la copia senza «Ho finito» (database, disco, Febe che si ferma) non trattiene più il permesso di guida: la copia lo scrive nel registro con il solo tipo d'errore e la fine del permesso arriva lo stesso; il controllo della fine della guida, se si interrompe per un errore, rilascia il permesso. (2) Un «Ho finito» tardivo, dopo che lo stesso uso del browser ha già copiato quando è tornato al motore, non legge nulla e dice che la sessione era già stata copiata (senza chiedere un nuovo accesso se la copia è completa); un nuovo «Accedi» / «Usa il browser» dimentica quella copia. (3) Il registro distingue «Finestra del browser chiusa» da «Finestra del browser ridotta a icona troppo a lungo» (`BrowserWindowLetGo`). (4) `EngineSnapshot.SessionCopyMissing`: con il motore in funzione `/api/engine` e gli eventi prendono «Serve «Ho finito»» dall'istantanea del motore, senza chiedere al browser; il collegamento si interroga solo con il motore spento | Il permesso tenuto per sempre lasciava il motore in «Stai usando il browser» senza un errore nel registro; il messaggio tardivo diceva «non è stata copiata, rifai l'accesso» di una sessione appena salvata; il registro diceva «chiusa» di una finestra solo ridotta a icona; ogni evento del flusso costava un indirizzo e un controllo del cookie via CDP |
| 2026-11-18 | Seconda revisione di S4b. (1) La scelta «sessione.copia-incompleta» si legge prima dell'ultimo controllo che la pagina sia ancora di Alberto (`mayKeep`), non dopo; se non si legge (database occupato o in errore) vale la predefinita «Sostituisci comunque» e il registro scrive solo il tipo d'errore. (2) Ogni volta che lo stesso uso del browser viene lasciato senza «Ho finito» (finestra chiusa, fine della guida) dimentica la copia fatta a un abbandono precedente prima di provare la sua: un «Ho finito» tardivo segue l'ultimo abbandono | (1) Regola 7: fra l'ultimo sguardo alla pagina e la scrittura non deve passare nessuna attesa; un errore dell'impostazione faceva fallire «Ho finito» senza rilasciare il permesso di guida. (2) Dopo una copia riuscita e un secondo abbandono rifiutato (pagina di accesso, forse un altro account) il messaggio diceva «era già stata copiata… Non serve rifare l'accesso» |
| 2026-11-18 | Terza revisione di S4b. (1) La fine della guida da sola, dopo la copia, guarda di nuovo nello stesso passo in cui rilascia il permesso (sotto lo stesso lucchetto): se nel frattempo è tornata la vista remota o la finestra, o è arrivato un nuovo «Accedi» / «Usa il browser», il permesso resta e il controllo continua (`ReleaseIdleLease`). (2) Ogni «Ho finito» che prova davvero a copiare, o che chiude lui il permesso, dimentica la copia fatta a un abbandono precedente; anche la chiusura della finestra che rinuncia (browser fermo, un altro comando ancora in corso) la dimentica. (3) Se il tempo della chiusura della finestra finisce mentre la ricerca dei profili tiene la pagina, il registro dice «la pagina era occupata dalla ricerca dei profili», non «il browser non ha risposto in tempo». (4) La riga di avvio del motore segue `IsReadyToCollect`, con una terza frase per «aspetta la copia della sessione». (5) Il riquadro «Se una copia nuova è incompleta» non mostra né lascia scegliere nulla finché il server non dice la scelta salvata; una risposta tardiva non cambia una scelta già fatta; una scelta non salvata torna alla precedente; se la scelta non si legge, una riga lo dice. (6) Singolare italiano nei messaggi e nel registro («manca 1 valore che serve», «1 di questi serve»). (7) La guida dice che in Docker copia solo «Ho finito»: lasciare la pagina vale «Annulla» e non copia; la copia alla fine della guida in Docker resta solo una riserva per una pagina sparita senza avvisare. Corregge la frase «In Docker c'è solo la fine del permesso» della riga sulla copia alla chiusura della finestra | (1) Dopo una copia lunga (fino a 15 s di turno della pagina più il browser e il database) il permesso finiva anche se Alberto era tornato al browser, e alla chiusura successiva il motore riprendeva subito, senza attesa né copia. (2) Dopo un «Ho finito» rifiutato, un secondo «Ho finito» diceva «era già stata copiata… Non serve rifare l'accesso» di una copia forse di un altro accesso. (3) Il registro dava la colpa al browser. (4) Il registro diceva «collegato» mentre il monitor diceva «Serve «Ho finito»». (5) La pagina poteva mostrare una scelta diversa da quella che la copia seguente usa. (7) In Docker la pagina, lasciandola, manda «Annulla» (`pageLeft`) e la vista remota tiene il suo permesso finché è aperta: la copia alla fine della guida non scatta quasi mai. Se Alberto vuole che in Docker anche lasciare la pagina copi, va deciso (domanda aperta) |
| 2026-11-25 | **In Docker lasciare la pagina del browser copia la sessione: costruito** (risposta 1 di Alberto del 25 novembre 2026; ramo `funzione/sessione-s4b`). `cancel` con `pageLeft` in Docker va a `IConnectionService.LeavePageAsync` (predefinita: «Annulla», per i servizi senza sessione salvata come la dimostrazione) e non più a `CancelAsync`; la vista remota chiusa dalla sua pagina (né sostituita da un'altra scheda, né chiusa da Febe perché si ferma o perché la vista non è partita, né con il browser fermo) lo dice alla connessione (`BrowserRemoteViewHost`, `viewClosed` → `RemoteViewClosed`). Il controllo del permesso di guida, se dopo l'ultimo dei due segni passano `PageLeaveGrace` (5 s) senza viste aperte né `begin`, fa la copia di `CopyOnLetGoAsync` («Pagina del browser lasciata» nel registro, con le garanzie della chiusura della finestra), poi finisce il permesso e il motore rimette il browser a riposo; un `begin` (la pagina ricaricata) dimentica il segno. Il solo pulsante «Annulla» non copia. Windows non cambia (`pageLeft` → `ReleaseAsync`). Chiude la domanda aperta della riga «Terza revisione di S4b» (punto 7) e supera «la guida dice che in Docker copia solo «Ho finito»» | Prima in Docker lasciare la pagina valeva «Annulla» e la sessione non si copiava; una scheda chiusa senza `cancel` teneva il permesso fino ai 2 minuti di `DrivingGrace`. Il riposo lo fa il motore dopo la fine del permesso, come per la fine della guida: rimettere a riposo prima, sotto il permesso, avrebbe lasciato la pagina vuota a una vista riaperta proprio in quel momento |
+11 -8
View File
@@ -46,14 +46,15 @@ Febe copia la sessione anche quando lasci il browser **senza** «Ho finito», se
pagina del sito che non sia di accesso o di verifica:
- **su Windows**, quando chiudi la finestra «Browser di Febe» (o la lasci ridotta a icona troppo a lungo);
- **su Windows**, quando dopo «Accedi a Instagram» o «Usa il browser» la finestra resta fuori vista per 2 minuti e
la guida finisce da sola.
- **in Docker**, quando lasci la pagina Browser, o la pagina Collegamento mentre accedi, senza «Ho finito»: passi a
un'altra pagina di Febe, chiudi la scheda o la finestra del browser in cui la guardi, o se ne perde il collegamento.
Febe aspetta 5 secondi: se in quel tempo la vista remota non si riapre (una pagina ricaricata la riapre subito, e
ricaricare non è lasciare), copia la sessione e il motore può riprendere;
- quando dopo «Accedi a Instagram» o «Usa il browser» nessuna vista del browser resta aperta per 2 minuti (su Windows
la finestra fuori vista) e la guida finisce da sola.
**In Docker copia solo «Ho finito».** Se lasci la pagina Collegamento o la pagina Browser, o chiudi la scheda, senza
premere «Ho finito», per Febe è come «Annulla»: il browser torna al motore e la sessione **non** si copia (poi lo stato
diventa «Serve «Ho finito»» se non c'era già una copia). La copia alla fine della guida resta solo come riserva per
quando la pagina sparisce senza poterlo dire, per esempio se la rete cade o il portatile va in sospensione: allora la
guida finisce da sola dopo 2 minuti e Febe copia prima di riprendersi il browser.
Solo il pulsante **«Annulla»** non copia mai: il browser torna sulla pagina vuota e, se non c'era già una copia, lo
stato diventa «Serve «Ho finito»».
In questi casi non compare nessun messaggio: il registro dice com'è andata (solo conteggi, mai valori), e la pagina
Collegamento mostra la copia. Se poi premi «Ho finito» lo stesso:
@@ -127,7 +128,9 @@ nulla: premilo di nuovo.
Se lasci la pagina Browser, o la pagina Collegamento mentre accedi, senza premere «Ho finito» (un'altra pagina, la
scheda chiusa o ricaricata):
- **in Docker** vale come «Annulla»: il browser torna sulla pagina vuota e il motore può lavorare di nuovo;
- **in Docker** è come chiudere la finestra del browser su Windows: se entro 5 secondi la vista remota non si riapre
(ricaricare la pagina la riapre), Febe copia la sessione come detto sopra e il motore può lavorare di nuovo (poi
rimette il browser a riposo sulla pagina vuota). Non è «Annulla»: quello lo fa solo il suo pulsante;
- **su Windows** la finestra «Browser di Febe» resta com'è, sullo schermo e con la sua pagina, finché non la chiudi (o
premi «Ho finito»); finché è sullo schermo il motore resta fermo.
+85 -9
View File
@@ -43,8 +43,10 @@ namespace Febe.App;
/// </para>
/// <para>
/// With a saved session (issue #36, S4b) the session is copied at «Ho finito», and also when Alberto lets go of the
/// browser without it: the window «Browser di Febe» closed on Windows (<see cref="CopyOnWindowClosedAsync"/>) and the
/// lease of «Accedi» / «Usa il browser» ending by itself. Always before the page goes back to the engine, with the
/// browser without it: the window «Browser di Febe» closed on Windows (<see cref="CopyOnWindowClosedAsync"/>), the page
/// of the browser left in Docker (<see cref="LeavePageAsync"/>, <see cref="RemoteViewClosed"/>: after
/// <see cref="PageLeaveGrace"/> without a view open again, answer of 25 November 2026) and the lease of «Accedi» /
/// «Usa il browser» ending by itself. «Annulla» never copies. Always before the page goes back to the engine, with the
/// same guarantees as «Ho finito» (the driving gate held, the page's turn), and only from a page of the site that is
/// not a login or verification page. «Collegato» then also needs a readable saved session: without one the state is
/// <see cref="ConnectionState.SessionCopyMissing"/> («Serve «Ho finito»») and the engine waits.
@@ -64,6 +66,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// <summary>How often the cookie is looked at in the background (outside sessions it is the only way to notice).</summary>
public static readonly TimeSpan BackgroundCheck = TimeSpan.FromSeconds(30);
/// <summary>How the log names leaving the page of the browser in Docker (answer of 25 November 2026).</summary>
private const string PageLeftText = "Pagina del browser lasciata";
private readonly IFebeBrowser _browser;
private readonly IFebeStorage _storage;
private readonly BrowserUseTracker _tracker;
@@ -85,6 +90,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
private DateTimeOffset _checkedAt = DateTimeOffset.MinValue;
private DateTimeOffset _lastCopyAt = DateTimeOffset.MinValue;
private SessionCopyOutcome? _letGoCopy;
private DateTimeOffset? _leftAt;
/// <param name="browser">The browser of Febe.</param>
/// <param name="storage">The database (first connection, «Scollega»).</param>
@@ -169,6 +175,14 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// </summary>
public TimeSpan DrivingGrace { get; set; } = TimeSpan.FromMinutes(2);
/// <summary>
/// How long after Alberto left the page of the browser in Docker (<see cref="LeavePageAsync"/>, or its remote view
/// closed by the page: <see cref="RemoteViewClosed"/>) no view may open again before Febe takes it as letting go of
/// the browser (answer of 25 November 2026, proposal of 5 seconds): a reload of the page opens its view again well
/// before. Read at every look; tests shorten it.
/// </summary>
public TimeSpan PageLeaveGrace { get; set; } = TimeSpan.FromSeconds(5);
/// <summary>
/// How long Alberto's page waits for its turn while a step of the profile search holds it (real time). Read at every
/// wait; tests shorten it.
@@ -273,6 +287,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
_lastDrivingSign = _clock.Now;
// Alberto is back (a reload of the page left a moment ago): not a letting go.
_leftAt = null;
}
_tracker.MarkUsed(_clock.Now);
@@ -397,6 +414,52 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
/// <summary>
/// Docker (answer of 25 November 2026): the page of the browser was left without «Ho finito» or «Annulla». Nothing
/// happens at once — a reload opens the page, «Usa il browser» and the view again within a moment. The watch of the
/// lease lets go of the browser once, for <see cref="PageLeaveGrace"/> after this and after the last view closed, no
/// view is open and no «Accedi» / «Usa il browser» came: the copy of the session as when the window is closed on
/// Windows, then the lease ends and the page goes back to the engine (which puts it to rest).
/// </summary>
public Task LeavePageAsync(CancellationToken ct)
{
if (NoteLeft())
{
_log.Info("collegamento", $"Pagina del browser lasciata senza «Ho finito» né «Annulla»: se entro {ItalianText.Duration(PageLeaveGrace)} non torni al browser, Febe copia la sessione e il motore può riprendere.");
}
return Task.CompletedTask;
}
/// <summary>
/// Docker: a remote view was closed by its page (the page left, the tab closed, the link lost; not another view taking
/// its place, nor Febe stopping). While the lease of «Accedi» / «Usa il browser» holds it counts as leaving the page
/// (<see cref="LeavePageAsync"/>): the last view closed, the moment starts again from now.
/// </summary>
public void RemoteViewClosed()
{
// The browser gone: its view closed with it, Alberto did not leave (the page opens it again once it is back).
if (_browser.IsAvailable)
{
NoteLeft();
}
}
/// <summary>Notes that Alberto may have left the browser; false without the lease of «Accedi» / «Usa il browser».</summary>
private bool NoteLeft()
{
lock (_gate)
{
if (_lease is null)
{
return false;
}
_leftAt = _clock.Now;
return true;
}
}
public async Task<FinishResult> FinishAsync(CancellationToken ct)
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
@@ -718,9 +781,12 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
while (true)
{
var grace = DrivingGrace;
var poll = TimeSpan.FromTicks(Math.Clamp(grace.Ticks / 8, TimeSpan.FromMilliseconds(20).Ticks, TimeSpan.FromSeconds(5).Ticks));
var leaveGrace = PageLeaveGrace;
var shortest = leaveGrace < grace ? leaveGrace : grace;
var poll = TimeSpan.FromTicks(Math.Clamp(shortest.Ticks / 8, TimeSpan.FromMilliseconds(20).Ticks, TimeSpan.FromSeconds(5).Ticks));
await _clock.Delay(poll, ct).ConfigureAwait(false);
DateTimeOffset lastSign;
DateTimeOffset? leftAt;
lock (_gate)
{
if (!ReferenceEquals(_lease, lease))
@@ -735,15 +801,22 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
lastSign = _lastDrivingSign;
leftAt = _leftAt;
}
if (_clock.Now - lastSign < grace)
// Docker: the page of the browser left, or its last view closed by the page, and for a moment nothing came
// back (answer of 25 November 2026). Otherwise the long wait of a lease nobody uses.
var now = _clock.Now;
var left = leftAt is { } at && now - (at > lastSign ? at : lastSign) >= leaveGrace;
if (!left && now - lastSign < grace)
{
continue;
}
// Before the page goes back to the engine: the copy of the session (S4b, answer 5).
if (!await CopyBeforeLeaseEndsAsync(lease, lastSign, poll, ct).ConfigureAwait(false))
// Before the page goes back to the engine: the copy of the session (S4b, answer 5; leaving the page in
// Docker, answer of 25 November 2026).
var what = left ? PageLeftText : "Fine della guida del browser";
if (!await CopyBeforeLeaseEndsAsync(lease, lastSign, poll, what, ct).ConfigureAwait(false))
{
continue;
}
@@ -753,7 +826,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
// the lease, so that nothing slips in between.
if (ReleaseIdleLease(lease, lastSign))
{
_log.Info("collegamento", $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere.");
_log.Info("collegamento", left
? $"{PageLeftText}: nessuna vista del browser riaperta, il motore può riprendere."
: $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere.");
return;
}
}
@@ -777,7 +852,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// (<paramref name="poll"/>) of the copy is that hold, not Alberto. False when the lease must not end now: a sign of
/// driving came while the copy waited for its turn.
/// </summary>
private async Task<bool> CopyBeforeLeaseEndsAsync(IDisposable lease, DateTimeOffset lastSign, TimeSpan poll, CancellationToken ct)
private async Task<bool> CopyBeforeLeaseEndsAsync(IDisposable lease, DateTimeOffset lastSign, TimeSpan poll, string what, CancellationToken ct)
{
if (_copier is null)
{
@@ -828,7 +903,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
return false;
}
await CopyOnLetGoAsync("Fine della guida del browser", StillAlbertos, ct).ConfigureAwait(false);
await CopyOnLetGoAsync(what, StillAlbertos, ct).ConfigureAwait(false);
return true;
}
finally
@@ -1345,6 +1420,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
var taken = (_lease, _leaseWatch);
_lease = null;
_leaseWatch = null;
_leftAt = null;
return taken;
}
+20 -5
View File
@@ -26,6 +26,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
private readonly IClock _browserClock;
private readonly FebeLog _log;
private readonly Func<CancellationToken, Task>? _openStartPage;
private readonly Action? _viewClosed;
private readonly Lock _gate = new();
private readonly SemaphoreSlim _opening = new(1, 1);
private BrowserRemoteViewConnection? _current;
@@ -43,7 +44,12 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
/// What «Pagina iniziale» does (issue #52): the connection opens the start page once the engine's session ended and
/// with the page's turn; null: the button does nothing.
/// </param>
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func<CancellationToken, Task>? openStartPage = null)
/// <param name="viewClosed">
/// Told when a view ends from the page's side (the page left, the tab closed, the link lost), not when another view
/// takes its place or Febe stops: the connection then knows that Alberto may have left the browser (Docker, answer of
/// 25 November 2026, spec §6.0 «Quando si copia»); null: nobody is told.
/// </param>
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func<CancellationToken, Task>? openStartPage = null, Action? viewClosed = null)
{
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
@@ -51,6 +57,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
_log = log ?? throw new ArgumentNullException(nameof(log));
_browserClock = browserClock ?? new SystemClock(clock.LocalZone);
_openStartPage = openStartPage;
_viewClosed = viewClosed;
}
/// <summary>
@@ -104,8 +111,8 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
catch (Exception ex)
{
// Whatever went wrong (the page gone away, an unexpected frame tree), nothing of the view stays behind:
// no lease, no screencast, no subscription.
await connection.DisposeAsync().ConfigureAwait(false);
// no lease, no screencast, no subscription. Ended by the server: the page did not leave the browser.
await connection.EndAsync(RemoteViewEnd.BrowserStopped).ConfigureAwait(false);
if (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
throw new RemoteViewUnavailableException("Il browser di Febe non risponde: riprova fra qualche secondo.", ex);
@@ -158,7 +165,9 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
}
}
internal void Closed(BrowserRemoteViewConnection connection)
/// <param name="connection">The view that ended.</param>
/// <param name="byPage">True when the page ended it (left, tab closed, link lost), false when the server did.</param>
internal void Closed(BrowserRemoteViewConnection connection, bool byPage)
{
lock (_gate)
{
@@ -169,6 +178,10 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
}
_log.Info("vista", "Vista remota chiusa.");
if (byPage)
{
_viewClosed?.Invoke();
}
}
}
@@ -445,6 +458,8 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
return;
}
// No reason given by the server (another view, Febe stopping, the browser gone): the page closed it.
var byPage = Ended is null;
Ended ??= RemoteViewEnd.BrowserStopped;
await _ended.CancelAsync().ConfigureAwait(false);
_session.Screencast.FrameReceived -= OnFrame;
@@ -462,7 +477,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
// The browser is gone: the lease is released anyway.
}
_owner.Closed(this);
_owner.Closed(this, byPage);
}
private void MarkUsed()
+9 -1
View File
@@ -87,7 +87,15 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(app);
RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log, openStartPage: ct => app.Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask);
// A view closed by its page may be Alberto leaving the browser (answer of 25 November 2026): the connection copies
// the session and gives the page back if no other view opens within a moment (spec §6.0 «Quando si copia»).
RemoteView = new BrowserRemoteViewHost(
app.Browser!,
app.Tracker,
app.Clock,
app.Log,
openStartPage: ct => app.Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask,
viewClosed: () => app.Connection?.RemoteViewClosed());
services.AddSingleton<IRemoteViewHost>(RemoteView);
}
+7 -1
View File
@@ -38,7 +38,9 @@ public static class ConnectionApi
});
// «Annulla», or a page left without either button ({ pageLeft: true }). On Windows the browser is a window of its
// own: leaving a page of Febe leaves it as it is, on screen until Alberto closes it (issue #52).
// own: leaving a page of Febe leaves it as it is, on screen until Alberto closes it (issue #52). In Docker leaving
// the page lets go of the browser like closing that window: the session is copied, not cancelled (answer of
// 25 November 2026). Only the button «Annulla» cancels without copying.
endpoints.MapPost("/api/connection/cancel", async (HttpContext context, IConnectionService connection, IBrowserWindow window, CancellationToken ct) =>
{
var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.CancelDrivingRequest, new CancelDrivingRequest(false)).ConfigureAwait(false);
@@ -46,6 +48,10 @@ public static class ConnectionApi
{
await connection.ReleaseAsync(ct).ConfigureAwait(false);
}
else if (body.PageLeft)
{
await connection.LeavePageAsync(ct).ConfigureAwait(false);
}
else
{
await connection.CancelAsync(ct).ConfigureAwait(false);
@@ -114,6 +114,15 @@ public interface IConnectionService
/// </summary>
Task ReleaseAsync(CancellationToken ct);
/// <summary>
/// The Febe page that took the browser was left (another page, a reload, the tab closed) while the browser is the
/// remote view (Docker, answer of Alberto of 25 November 2026, spec §6.0 «Quando si copia»): like closing the window
/// «Browser di Febe» on Windows, not like «Annulla». If within a moment no view opens again and no «Accedi» / «Usa il
/// browser» comes (a reload is not leaving), the session is copied while the page is still his, and then the page goes
/// back to the engine. By default, for a service without a saved session to copy, it is «Annulla».
/// </summary>
Task LeavePageAsync(CancellationToken ct) => CancelAsync(ct);
/// <summary>«Scollega» (after confirmation in the UI): stops the engine and deletes the browser profile.</summary>
Task DisconnectAsync(CancellationToken ct);
}
+9 -5
View File
@@ -33,14 +33,18 @@ nessuna operazione configurata); altrimenti `{ state: "present"|"none"|"unreadab
valuesPresent, valuesExpected, missingValues: [nomi], docIdsPresent, docIdsExpected, missingDocIds: [operazioni],
neededMissing }`: solo conteggi e nomi, mai valori. Con il cookie di sessione nel browser ma senza una sessione salvata
leggibile lo stato è `copyMissing` («Serve «Ho finito»»): il motore aspetta, e `/api/engine` dice `copyMissing` nel
collegamento. La sessione si copia a «Ho finito», alla chiusura della finestra del browser su Windows e quando il
permesso di guida finisce da solo, sempre prima che la pagina torni al motore.
collegamento. La sessione si copia a «Ho finito», alla chiusura della finestra del browser su Windows, lasciando la
pagina del browser in Docker (sotto) e quando il permesso di guida finisce da solo, sempre prima che la pagina torni al
motore. «Annulla» non copia mai.
L'interfaccia manda `cancel` con `{ "pageLeft": true }` anche quando Alberto lascia la pagina Browser, o la pagina
Collegamento mentre accede, senza «Ho finito» né «Annulla»: un'altra pagina, la scheda chiusa o ricaricata (`fetch`
con `keepalive`, che porta l'`Origin` dell'interfaccia). In Docker vale come «Annulla» (il browser torna a riposo) e
non copia la sessione: in Docker la copia viene da «Ho finito», e dalla fine del permesso solo quando la pagina sparisce
senza riuscire a mandare `cancel` (rete caduta, sospensione).
con `keepalive`, che porta l'`Origin` dell'interfaccia). In Docker non è «Annulla» (`IConnectionService.LeavePageAsync`,
risposta di Alberto del 25 novembre 2026): è come chiudere la finestra del browser su Windows. Febe lo nota e aspetta
5 secondi; anche la vista remota chiusa dalla sua pagina (scheda chiusa, collegamento perso, non sostituita da un'altra
scheda) fa ricominciare l'attesa. Se in quel tempo non si apre un'altra vista e non arriva un `begin` (una pagina
ricaricata fa tutti e due), copia la sessione come alla chiusura della finestra (solo da una pagina del sito che non sia
di accesso o di verifica), poi il permesso finisce e il motore rimette il browser a riposo.
Su Windows, dove il browser è una finestra a parte, finisce solo il permesso tenuto dalla pagina: la finestra resta
com'è, sullo schermo e con la sua pagina, finché Alberto non la chiude (e finché è sullo schermo il motore resta
fermo). Dopo un «Ho finito» riuscito la pagina chiude la vista remota e non manda un nuovo `begin`.
+2 -2
View File
@@ -1,8 +1,8 @@
// Browser (spec §10.3 «Apri il browser»; mockup 10 without the steps column): in Docker the remote view of the
// server's browser and «Ho finito»; on Windows the browser is its own window. While Alberto uses the browser the
// engine is still; «Ho finito» lets «Riprendi» become active after a verification. Leaving the page without «Ho finito»
// (another page, a reload, closing the tab) gives the browser back, like «Annulla» (on Windows the window stays as it
// is until Alberto closes it). A browser at rest opens its start page; «?accesso=1» (the red strip of a disconnection)
// (another page, a reload, closing the tab) gives the browser back, like closing the window on Windows: the server copies
// the session if no view opens again within a moment (on Windows the window stays as it is until Alberto closes it). A browser at rest opens its start page; «?accesso=1» (the red strip of a disconnection)
// opens the login page, once: the parameter leaves the address straight away.
import { api } from '../core/api.js';
+4 -3
View File
@@ -42,9 +42,10 @@ export async function beginDriving(openLogin) {
/**
* The browser as a page uses it (spec §4.1, §10.3: the engine is still only while Alberto uses the browser). begin()
* takes it; «Ho finito», «Annulla» and «Scollega» give it back on the server, and the page calls settled(). Leaving the
* page in any other way — another page, a reload, closing the tab — gives it back too: in Docker like «Annulla» (the
* browser goes back to the empty page and the engine may work again); on Windows the window «Browser di Febe» stays as
* it is, on screen until Alberto closes it (issue #52), and only the page's hold ends.
* page in any other way — another page, a reload, closing the tab — gives it back too: in Docker like closing the
* window on Windows, not like «Annulla» (answer of 25 November 2026: if no view opens again within a moment, the
* server copies the session and the engine may work again; a reload opens the view again); on Windows the window
* «Browser di Febe» stays as it is, on screen until Alberto closes it (issue #52), and only the page's hold ends.
*/
export function drivingLease(page) {
let held = false;
@@ -295,6 +295,102 @@ public sealed class SessionCopyOnLetGoTests
StringAssert.Contains(ReadLog(bed), "Finestra del browser chiusa: sessione copiata");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task LeavingTheBrowserPageInDockerCopiesTheSessionOnceNoViewOpensAgain()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromMilliseconds(400);
// «Usa il browser» from the Browser page of Docker: no window, the remote view holds the engine still.
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
bool? drivingWhileCopying = null;
browser.FakeCdp.OnCapture = () => drivingWhileCopying = browser.UserIsDriving;
// The page says it is left; while its view (or another tab's) is still open nothing happens.
await connection.LeavePageAsync(ct);
await Task.Delay(TimeSpan.FromMilliseconds(900), ct);
Assert.IsTrue(browser.UserIsDriving, "a view is still open");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
// Its view closes with it and no other opens: the copy while the page is still his, then it goes back to the engine.
view.Dispose();
connection.RemoteViewClosed();
await DesktopTestBed.WaitUntilAsync(() => ReadLog(bed).Contains("Pagina del browser lasciata: nessuna vista del browser riaperta, il motore può riprendere.", StringComparison.Ordinal), TimeSpan.FromSeconds(10), "la fine della guida lasciando la pagina");
Assert.IsFalse(browser.UserIsDriving);
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
Assert.IsTrue(drivingWhileCopying, "the page is still Alberto's while it is read");
Assert.IsNotNull(bed.App.SavedSession!.Read());
StringAssert.Contains(ReadLog(bed), "Pagina del browser lasciata: sessione copiata");
// A late «Ho finito» from another tab reads nothing and says that the session was already copied.
var finish = (await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish")).GetProperty("message").GetString()!;
StringAssert.Contains(finish, "era già stata copiata");
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task AReloadOfTheBrowserPageIsNotLeavingItAndAnnullaStillCopiesNothing()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromSeconds(1);
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
// A reload: the old page says it left and its view closes, the new page takes the browser and opens its view.
await connection.LeavePageAsync(ct);
view.Dispose();
connection.RemoteViewClosed();
view = await DockerBeginAsync(bed);
await Task.Delay(TimeSpan.FromSeconds(2), ct);
Assert.IsTrue(browser.UserIsDriving, "a reload is not leaving the browser");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
// «Annulla» on the reloaded page: the browser goes back to rest, nothing is copied.
view.Dispose();
using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel"))
{
Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode);
}
Assert.IsFalse(browser.UserIsDriving);
await Task.Delay(TimeSpan.FromSeconds(1.5), ct);
Assert.AreEqual(0, browser.FakeCdp.CaptureReads, "«Annulla» never copies");
Assert.IsNull(bed.App.SavedSession!.Read());
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task LeavingTheBrowserPageOnTheLoginPageCopiesNothingButGivesThePageBack()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromMilliseconds(300);
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/accesso/");
// The tab closed on the site's login page (a path of its stop rules): the copier refuses it.
view.Dispose();
connection.RemoteViewClosed();
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida lasciando la pagina di accesso");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads, "refused before the modules are read");
Assert.IsNull(bed.App.SavedSession!.Read());
await DesktopTestBed.WaitUntilAsync(() => ReadLog(bed).Contains("Pagina del browser lasciata: sessione non copiata", StringComparison.Ordinal), TimeSpan.FromSeconds(10), "la riga della copia rifiutata");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task WithRichiesteCollegatoNeedsTheSavedSessionAndTheEngineWaitsForIt()
@@ -481,6 +577,17 @@ public sealed class SessionCopyOnLetGoTests
Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode);
}
/// <summary>
/// «Usa il browser» as the Browser page of Docker takes it: the lease of the connection and the lease of its remote
/// view (returned), without the window of this composition (put away at once).
/// </summary>
private async Task<IDisposable> DockerBeginAsync(DesktopTestBed bed)
{
await BeginAsync(bed, openLogin: false);
await bed.Browser!.HideFromUserAsync(TestContext.CancellationToken);
return bed.Browser.UserDriving.Begin();
}
/// <summary>«Accedi» or «Usa il browser», the site's home with the session, «Ho finito». Returns the message.</summary>
private static async Task<string> FinishOnSiteAsync(DesktopTestBed bed, bool openLogin)
{
@@ -132,6 +132,33 @@ public sealed class RemoteViewStartTests
}
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task OnlyAViewClosedByItsPageIsToldToTheConnection()
{
// Docker (answer of 25 November 2026): a view closed by its page may be Alberto leaving the browser; one replaced
// by another tab, one that did not start, or one closed because Febe stops is not.
var ct = TestContext.CancellationToken;
var told = 0;
await using var bed = new Bed(attempt => attempt == 3 ? new CdpDisconnectedException("Il collegamento con il browser si è chiuso.") : null, viewClosed: () => Interlocked.Increment(ref told));
var older = await bed.Host.OpenAsync(ct);
var newer = await bed.Host.OpenAsync(ct);
Assert.AreEqual(RemoteViewEnd.Replaced, older.Ended);
Assert.AreEqual(0, Volatile.Read(ref told), "replaced by another tab: Alberto is still at the browser");
await newer.DisposeAsync();
Assert.AreEqual(1, Volatile.Read(ref told), "the page closed its view");
await Assert.ThrowsExactlyAsync<RemoteViewUnavailableException>(() => bed.Host.OpenAsync(ct));
Assert.AreEqual(1, Volatile.Read(ref told), "a view that did not start was never the page's");
var last = await bed.Host.OpenAsync(ct);
await bed.Host.ShutdownAsync();
Assert.AreEqual(RemoteViewEnd.ShuttingDown, last.Ended);
Assert.AreEqual(1, Volatile.Read(ref told), "Febe stopping is not Alberto leaving");
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task PaginaInizialeOpensTheStartPageOfTheMoment()
@@ -300,7 +327,8 @@ public sealed class RemoteViewStartTests
/// tested in BrowserStartPageTests); null: nowhere.
/// </param>
/// <param name="open">What «Pagina iniziale» does instead (it wins over <paramref name="startPage"/>).</param>
public Bed(Func<int, Exception?> startFailure, Func<string>? startPage = null, Func<CancellationToken, Task>? open = null)
/// <param name="viewClosed">What the connection is told when a view is closed by its page.</param>
public Bed(Func<int, Exception?> startFailure, Func<string>? startPage = null, Func<CancellationToken, Task>? open = null, Action? viewClosed = null)
{
Clock = new VirtualClock();
_start = Clock.Now;
@@ -326,7 +354,7 @@ public sealed class RemoteViewStartTests
};
Browser = new PageBrowser(Cdp);
_log = new FebeLog(null, null, Clock);
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, openStartPage: open ?? (startPage is null ? null : async ct => await Cdp.NavigateAsync(startPage(), ct)))
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, openStartPage: open ?? (startPage is null ? null : async ct => await Cdp.NavigateAsync(startPage(), ct)), viewClosed: viewClosed)
{
// The virtual clock moves only in the pauses: a watchdog on it would never wait.
Watchdog = null,
+5 -3
View File
@@ -63,19 +63,21 @@ public sealed class ConnectionApiTests
}
[TestMethod]
public async Task LeavingThePageIsAnnullaInDockerAndOnlyTheEndOfTheHoldOnWindows()
public async Task LeavingThePageLetsGoOfTheBrowserInDockerAndOnlyEndsTheHoldOnWindows()
{
// Docker: the remote view is the page, leaving it gives the browser back to rest.
// Docker: the remote view is the page; leaving it lets go of the browser like closing the window on Windows (the
// session is copied: answer of 25 November 2026), while the button «Annulla» still cancels.
var docker = new RecordingConnection();
await using (var server = await Part2.StartAsync(services: s => s.AddSingleton<IConnectionService>(docker)))
{
var (status, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel", new { pageLeft = true });
Assert.AreEqual(HttpStatusCode.NoContent, status);
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel");
var (showStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show");
Assert.AreEqual(HttpStatusCode.BadRequest, showStatus, "in Docker the browser is the Browser page");
}
CollectionAssert.AreEqual(new[] { "cancel" }, docker.Calls);
CollectionAssert.AreEqual(new[] { "leave", "cancel" }, docker.Calls);
// Windows (issue #52): the window stays as it is; «Annulla» is still «Annulla»; «Apri il browser» says which page.
var windows = new RecordingConnection();
+5 -5
View File
@@ -90,12 +90,12 @@ public sealed class InterfaceTests
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»).
// Another page from the sidebar: the view closes and the page lets go of the browser (not «Annulla»: the session is copied).
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(() => connection.Snapshot().Contains("leave"), "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());
CollectionAssert.AreEqual(new[] { "begin:False", "leave" }, connection.Snapshot());
}
[TestMethod]
@@ -111,7 +111,7 @@ public sealed class InterfaceTests
// 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");
await ui.WaitForAsync(() => connection.Snapshot().Contains("leave"), "il browser restituito chiudendo la scheda");
}
[TestMethod]
@@ -258,7 +258,7 @@ public sealed class InterfaceTests
await ui.NavigateAsync("/libreria");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await ui.WaitForQuietAsync("richieste della pagina finite");
CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "cancel" }, connection.Snapshot(), "leaving the page gives the browser back");
CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "leave" }, connection.Snapshot(), "leaving the page gives the browser back");
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
}
@@ -124,6 +124,14 @@ internal sealed class RecordingConnection : IConnectionService
return Task.CompletedTask;
}
/// <summary>Docker: the page of the browser left without «Ho finito» or «Annulla» (not «Annulla»: it copies).</summary>
public Task LeavePageAsync(CancellationToken ct)
{
Record("leave");
Status = Status with { UserIsDriving = false };
return Task.CompletedTask;
}
public Task ReleaseAsync(CancellationToken ct)
{
Record("release");