Integrazione 0.1.1: Febe per Windows si collega, VS Code, prove su Windows, storico e vista remota #4
No files matched your search
+2
-1
@@ -229,8 +229,9 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-10-20 | Nuovo progetto di prove `tests/Febe.Tests.Windows` (`net10.0-windows`, WPF, solo MSTest e riferimenti ai progetti, nella soluzione): WebView2 vero su un thread STA con un `Dispatcher` di WPF vero, il sito di prova in processo; si compila anche da Linux (`EnableWindowsTargeting`), gira solo su Windows, senza runtime WebView2 è inconcludente | L'errore che bloccava Febe per Windows (14 e 19 ottobre) si vedeva solo con WebView2 vero e un thread dell'interfaccia vero: le prove su Linux con il finto `IWebView2DevTools` non potevano coglierlo |
|
||||
| 2026-10-20 | `WebView2Host` legge sul thread dell'interfaccia, durante l'avvio, i valori che servono altrove (versione di WebView2, numero del processo del browser) e li espone come valori semplici; nessun membro di un oggetto di WebView2 si legge fuori da quel thread | Causa dell'errore: `Version` leggeva `BrowserVersionString` dell'ambiente da un thread del pool, dopo `ConfigureAwait(false)`, e WebView2 lanciava `InvalidOperationException` |
|
||||
| 2026-10-20 | Nel ciclo di avvio di `WebView2Browser` si riprova solo l'eccezione dell'avvio stesso: stato e riga «Browser di Febe pronto» stanno fuori dal blocco dei tentativi | La riga del registro, dentro il `try`, trasformava ogni avvio riuscito in un avvio fallito: chiusura del WebView buono e nuovi tentativi per sempre |
|
||||
| 2026-10-20 | Avvio, ripartenza, chiusura dopo un avvio fallito e arresto di `WebView2Host` uno alla volta (un `SemaphoreSlim` preso sul thread dell'interfaccia); l'arresto aspetta al più 30 s chi è in corso, poi chiude quello che c'è | Ognuno aspetta WebView2 sul thread dell'interfaccia e fra un'attesa e l'altra potevano intrecciarsi (per esempio una ripartenza dopo un arresto del processo e «Scollega»); l'uscita da Febe non deve restare appesa a un avvio che WebView2 non completa |
|
||||
| 2026-10-20 | Avvio, ripartenza e arresto di `WebView2Host` uno alla volta (un `SemaphoreSlim` preso sul thread dell'interfaccia); l'arresto aspetta al più 30 s chi è in corso, poi chiude quello che c'è | Ognuno aspetta WebView2 sul thread dell'interfaccia e fra un'attesa e l'altra potevano intrecciarsi (per esempio una ripartenza dopo un arresto del processo e «Scollega»); l'uscita da Febe non deve restare appesa a un avvio che WebView2 non completa |
|
||||
| 2026-10-20 | Arresto del processo del browser: annunciato solo dopo che il gestore di `ProcessFailed` è tornato e solo per il WebView in uso (numero di generazione); se capita durante un avvio fa fallire quell'avvio; la ripartenza (e quella dopo un «Scollega» la cui ripartenza fallisce) usa gli stessi tentativi del primo avvio, un solo ciclo alla volta sul pool | Modello dei thread di WebView2: niente chiusure né ricreazioni dentro i suoi gestori. Prima: un solo tentativo, poi browser morto fino al riavvio di Febe; dopo «Scollega» restava fermo anche il motore, perché l'errore non era di cartella e `DisconnectAsync` non lo gestiva |
|
||||
| 2026-10-20 | `WebView2CdpSession.Attach` chiama i gestori di `Reconnected` uno per uno: l'errore di uno va nel registro e non esce da `Attach` (l'avviso resta sincrono) | `Attach` è dentro l'avvio del nuovo WebView: un'eccezione di chi ascolta avrebbe disfatto un avvio riuscito, ancora e ancora |
|
||||
| 2026-10-20 | La finestra dell'interfaccia apre gli indirizzi esterni nel browser predefinito dopo che il gestore di WebView2 è tornato (in coda sul dispatcher) | La shell di Windows può far girare un ciclo di messaggi suo e WebView2 non regge di essere richiamato dentro i propri gestori |
|
||||
| 2026-10-20 | Le prove per Windows hanno un `CompressedClock` e un fuso «mezzogiorno» propri, copie di quelli della suite per Linux; `Febe.Desktop` concede gli `internal` a `Febe.Tests.Windows` e `WebView2Host` espone la sua finestra come `internal` (da leggere sul thread dell'interfaccia) | Un progetto di prove non può dipendere dall'altro; la finestra serve alle prove del primo piano e del fuori vista |
|
||||
| 2026-10-20 | Un solo WebView alla volta in `WebView2Host`: l'avvio, dentro la sezione esclusiva, non fa nulla se un WebView è già collegato, chiude prima i resti di uno morto, e se fallisce chiude da sé ciò che ha creato (il ciclo dei tentativi non chiude più niente da fuori); la ripartenza dopo un arresto del processo usa lo stesso avvio; chiudere un WebView ne cambia la generazione, così i suoi eventi tardivi non contano | Revisione del ramo: un «Scollega» durante i tentativi del primo avvio faceva partire il browser, poi il tentativo in attesa ne apriva un secondo nella stessa finestra senza chiudere il primo. Il processo orfano teneva il profilo: il «Scollega» dopo aspettava 20 s e non cancellava la sessione di Instagram, l'uscita aspettava 15 s a vuoto |
|
||||
+3
-1
@@ -191,6 +191,8 @@ dell'interfaccia: Febe li tocca solo da lì (i comandi del motore arrivano da al
|
||||
dispatcher di WPF), e il resto del programma legge solo valori semplici presi durante l'avvio, come la versione per il
|
||||
registro. Se il processo del browser si chiude da solo, Febe lo fa ripartire con lo stesso profilo e con gli stessi
|
||||
tentativi del primo avvio (5, 15, 30, 60 secondi, poi ogni 5 minuti), e lo stesso se dopo «Scollega» non ripartisse.
|
||||
Nella finestra c'è sempre un solo browser: se «Scollega» lo fa ripartire mentre il primo avvio aspetta il prossimo
|
||||
tentativo, quel tentativo lo trova già in funzione e non ne apre un secondo.
|
||||
|
||||
Le prove da fare su un Windows vero, con la procedura esatta, sono in `docs/prove-dal-vivo.md`, **parte C**. In breve:
|
||||
|
||||
@@ -249,7 +251,7 @@ raccolta.
|
||||
| Classe | Che cosa prova |
|
||||
|---|---|
|
||||
| `WebView2BrowserStartTests` | Avviato da un thread del pool, come fa la composizione, il browser è pronto al primo tentativo e il registro dice «Browser di Febe pronto: WebView2 …» (l'errore del 14 ottobre) |
|
||||
| `WebView2LifecycleTests` | Un avvio che fallisce davvero si riprova e poi va; primo piano e fuori vista con il permesso di guida; «Scollega»; ripartenza dopo l'arresto del processo; «composizione» di S2 |
|
||||
| `WebView2LifecycleTests` | Un avvio che fallisce davvero si riprova e poi va; primo piano e fuori vista con il permesso di guida; «Scollega»; «Scollega» mentre il primo avvio aspetta di riprovare (un solo browser nella finestra, il «Scollega» dopo riesce subito); ripartenza dopo l'arresto del processo; «composizione» di S2 |
|
||||
| `WebView2CdpTests` | S1: i comandi dell'elenco su WebView2 contro il sito di prova, con la finestra fuori vista, e i comandi vietati rifiutati |
|
||||
| `WebView2CollectionTests` | Una sessione vera della composizione (`FebeApp` con `DesktopPlatform`) su WebView2: i file arrivano nella libreria |
|
||||
| `WebView2ConnectionTests` | Il collegamento dal servizio vero della composizione: «Accedi a Instagram» porta in primo piano la finestra con la pagina di accesso (del sito di prova), «Ho finito» trova la sessione e la rimette fuori vista, «Scollega» cancella il profilo e il motore riparte |
|
||||
|
||||
@@ -193,21 +193,15 @@ internal sealed class WebView2Browser : IFebeBrowser
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>A start failed: it is said, what it left is closed, and the next attempt waits. False when cancelled.</summary>
|
||||
/// <summary>
|
||||
/// A start failed: it is said, and the next attempt waits. False when cancelled. What the failed start created it
|
||||
/// closed itself, inside the host: a close from here could catch a browser that «Scollega» started meanwhile.
|
||||
/// </summary>
|
||||
private async Task<bool> AfterFailedStartAsync(Exception error, int attempt, CancellationToken ct)
|
||||
{
|
||||
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
|
||||
_lastError = $"WebView2 non parte ({error.GetType().Name}: {FirstLine(error.Message)}).";
|
||||
_context.Log.Error("browser", $"{_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
|
||||
try
|
||||
{
|
||||
await Host.ResetAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_context.Log.Warn("browser", "WebView2: quello che l'avvio non riuscito ha lasciato aperto non si è chiuso del tutto.", ex);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _wallClock.Delay(wait, ct).ConfigureAwait(false);
|
||||
@@ -227,8 +221,10 @@ internal sealed class WebView2Browser : IFebeBrowser
|
||||
|
||||
/// <summary>
|
||||
/// The browser must start again (its process went away by itself, or the start after «Scollega» failed with
|
||||
/// <paramref name="failure"/>): one loop at a time restarts it, with the retries of the first start, on the thread
|
||||
/// pool — never inside an event handler of WebView2. A request that comes while the loop runs makes it go round again.
|
||||
/// <paramref name="failure"/>): one loop at a time starts it, with the retries of the first start, on the thread
|
||||
/// pool — never inside an event handler of WebView2. A request that comes while the loop runs makes it go round
|
||||
/// again. The loop only starts what is not running: when another way in (the first start, «Scollega») brought the
|
||||
/// browser back first, its attempt finds it running and is done.
|
||||
/// </summary>
|
||||
private void RequestRestart(Exception? failure)
|
||||
{
|
||||
@@ -263,7 +259,7 @@ internal sealed class WebView2Browser : IFebeBrowser
|
||||
_restartFailure = null;
|
||||
}
|
||||
|
||||
if (await StartWithRetriesAsync(token => Host.RestartAsync(null, token), _lifetime.Token, failure).ConfigureAwait(false))
|
||||
if (await StartWithRetriesAsync(token => Host.StartAsync(_options, token), _lifetime.Token, failure).ConfigureAwait(false))
|
||||
{
|
||||
_context.Log.Info("browser", ReadyMessage("Browser di Febe ripartito"));
|
||||
}
|
||||
|
||||
@@ -40,7 +40,10 @@ internal sealed record WebView2HostOptions(BrowserHosting Hosting, string Additi
|
||||
/// receivers) and the window are touched only on the UI thread, through its dispatcher; WebView2 throws on any other
|
||||
/// thread. Callers on other threads (the composition, the engine) get only plain values captured on the UI thread
|
||||
/// during the start (<see cref="Version"/>, <see cref="BrowserProcessId"/>), the CDP session, and tasks. Start,
|
||||
/// restart, reset and stop run one at a time.</item>
|
||||
/// restart and stop run one at a time.</item>
|
||||
/// <item>One WebView at a time, whoever starts it (the first start and its retries, «Scollega», the start after a
|
||||
/// crash): a start finds the WebView running and does nothing, closes what a dead one left before creating a new one,
|
||||
/// and when it fails it closes what it created itself. Events of a closed WebView never count.</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
internal sealed class WebView2Host : IBrowserHost
|
||||
@@ -55,7 +58,7 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
private readonly FebeLog _log;
|
||||
private readonly WebView2CdpSession _session;
|
||||
|
||||
// Start, restart, reset and dispose each await WebView2 on the UI thread: without this they could interleave there.
|
||||
// Start, restart and dispose each await WebView2 on the UI thread: without this they could interleave there.
|
||||
private readonly SemaphoreSlim _lifecycle = new(1, 1);
|
||||
|
||||
// The fields below are touched on the UI thread only.
|
||||
@@ -72,7 +75,6 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
private bool _starting;
|
||||
private bool _crashedWhileStarting;
|
||||
private bool _closing;
|
||||
private bool _restarting;
|
||||
|
||||
// Plain values read on the UI thread during the start: any thread may read them.
|
||||
private volatile string? _version;
|
||||
@@ -118,7 +120,11 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
/// </summary>
|
||||
public event EventHandler? BrowserProcessFailed;
|
||||
|
||||
/// <summary>Creates the window (once), the environment and the controller, and attaches the CDP session.</summary>
|
||||
/// <summary>
|
||||
/// Creates the window (once), the environment and the controller, and attaches the CDP session — unless a WebView
|
||||
/// is already running, because another way in started it («Scollega», the start after a crash): then it does nothing
|
||||
/// and the start counts as done. A failed start leaves nothing open.
|
||||
/// </summary>
|
||||
public Task StartAsync(BrowserOptions options, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
@@ -164,45 +170,32 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
/// <paramref name="whileStopped"/> — «Scollega» deletes the profile there — and starts it again. <see cref="Cdp"/>
|
||||
/// stays the same object. The browser starts again even when <paramref name="whileStopped"/> fails with an
|
||||
/// <see cref="IOException"/> or <see cref="UnauthorizedAccessException"/>; that error is thrown afterwards. A failed
|
||||
/// start throws its own error and, as after a failed <see cref="StartAsync"/>, the caller closes what it left with
|
||||
/// <see cref="ResetAsync"/> before trying again.
|
||||
/// start throws its own error and, like a failed <see cref="StartAsync"/>, leaves nothing open.
|
||||
/// </summary>
|
||||
public Task RestartAsync(Func<Task>? whileStopped, CancellationToken ct) => OnUiAsync(() => ExclusiveAsync(async () =>
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_closing, this);
|
||||
Exception? failure = null;
|
||||
_restarting = true;
|
||||
try
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
if (whileStopped is not null)
|
||||
{
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
if (whileStopped is not null)
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
await whileStopped().ConfigureAwait(true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
failure = ex;
|
||||
}
|
||||
await whileStopped().ConfigureAwait(true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
failure = ex;
|
||||
}
|
||||
|
||||
await StartCoreAsync().ConfigureAwait(true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_restarting = false;
|
||||
}
|
||||
|
||||
await StartCoreAsync().ConfigureAwait(true);
|
||||
if (failure is not null)
|
||||
{
|
||||
ExceptionDispatchInfo.Throw(failure);
|
||||
}
|
||||
}));
|
||||
|
||||
/// <summary>Closes what a failed start left, so that the next start begins clean.</summary>
|
||||
public Task ResetAsync() => OnUiAsync(() => ExclusiveAsync(CloseWebViewAsync));
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
try
|
||||
@@ -226,12 +219,29 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
await _session.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>UI thread, one at a time (<see cref="ExclusiveAsync"/>).</summary>
|
||||
/// <summary>True while a WebView is in the window and attached to the session (its browser process did not die).</summary>
|
||||
private bool IsRunning => _controller is not null && _session.IsAttached;
|
||||
|
||||
/// <summary>
|
||||
/// UI thread, one at a time (<see cref="ExclusiveAsync"/>): the only place a WebView is created, so the window never
|
||||
/// holds two. A WebView already running stays (the start is done); what a dead one left is closed first; a failed
|
||||
/// start closes what it created.
|
||||
/// </summary>
|
||||
private async Task StartCoreAsync()
|
||||
{
|
||||
_ui.VerifyAccess();
|
||||
ObjectDisposedException.ThrowIf(_closing, this);
|
||||
var options = _options ?? throw new InvalidOperationException("Opzioni del browser mancanti.");
|
||||
|
||||
// Started already, by «Scollega» or by the start after a crash, while this start waited for its turn or for its
|
||||
// next attempt: a second WebView would orphan the first, whose browser process then holds the profile.
|
||||
if (IsRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// A WebView whose browser process died (the session is detached) is closed before the new one exists.
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
_starting = true;
|
||||
_crashedWhileStarting = false;
|
||||
try
|
||||
@@ -244,12 +254,30 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
throw new InvalidOperationException("Il processo del browser WebView2 si è chiuso durante l'avvio.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Nothing stays open after a failed start, whoever retries it and whenever: here, inside the same step.
|
||||
await CloseAfterFailedStartAsync().ConfigureAwait(true);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_starting = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CloseAfterFailedStartAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_log.Warn("browser", "WebView2: quello che l'avvio non riuscito ha lasciato aperto non si è chiuso del tutto.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CreateWebViewAsync(BrowserOptions options)
|
||||
{
|
||||
if (_window is null)
|
||||
@@ -324,10 +352,14 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
await _session.SendAsync("Page.enable", null, CancellationToken.None).ConfigureAwait(true);
|
||||
}
|
||||
|
||||
/// <summary>Closes the controller and waits for the browser process to exit (the profile is written). UI thread.</summary>
|
||||
/// <summary>
|
||||
/// Closes the controller and waits for the browser process to exit (the profile is written). UI thread. From here on
|
||||
/// the events of the WebView being closed belong to an old generation: they change nothing.
|
||||
/// </summary>
|
||||
private async Task CloseWebViewAsync()
|
||||
{
|
||||
_ui.VerifyAccess();
|
||||
_generation++;
|
||||
_session.Detach();
|
||||
_devTools?.Close();
|
||||
_devTools = null;
|
||||
@@ -378,25 +410,19 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
var kind = e.ProcessFailedKind;
|
||||
_log.Warn("browser", $"WebView2: processo terminato ({kind}).");
|
||||
|
||||
// A closed or replaced WebView is not ours any more.
|
||||
// A WebView that is closing, closed or replaced is not ours any more (a restart, «Scollega», a failed start).
|
||||
if (_closing || generation != _generation)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// During a start the failure is the start's own error (the caller retries); while a restart closes the old
|
||||
// WebView the failure changes nothing.
|
||||
// During a start the failure is the start's own error: the start closes what it created and the caller retries.
|
||||
if (_starting)
|
||||
{
|
||||
_crashedWhileStarting |= kind == CoreWebView2ProcessFailedKind.BrowserProcessExited;
|
||||
return;
|
||||
}
|
||||
|
||||
if (_restarting)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (kind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
|
||||
{
|
||||
// The whole browser is gone: commands fail from now on, and the owner starts it again (same profile), as
|
||||
@@ -511,7 +537,7 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs one step of the life of the WebView (start, restart, reset, stop) after the others. UI thread. With
|
||||
/// Runs one step of the life of the WebView (start, restart, stop) after the others. UI thread. With
|
||||
/// <paramref name="wait"/> the step runs anyway once that time has passed (stopping must not hang behind a start
|
||||
/// that WebView2 never completes).
|
||||
/// </summary>
|
||||
|
||||
@@ -34,6 +34,10 @@ Regole che valgono anche qui:
|
||||
- Dentro un gestore di un evento di WebView2 niente chiusure, ricreazioni, cicli di messaggi o shell: si mette in coda
|
||||
sul dispatcher e si fa dopo (modello dei thread di WebView2).
|
||||
- Si riprova solo un avvio fallito: ciò che segue un avvio riuscito (registro, stato) non lo disfa mai.
|
||||
- Un solo WebView alla volta, chiunque lo avvii (primo avvio e suoi tentativi, «Scollega», ripartenza dopo un arresto
|
||||
del processo): l'avvio, dentro la sezione esclusiva di `WebView2Host`, trova quello in funzione e non fa nulla, chiude
|
||||
prima i resti di uno morto, e se fallisce chiude da sé ciò che ha creato. Un WebView orfano terrebbe vivo il processo
|
||||
del browser sul profilo, e «Scollega» non potrebbe più cancellarlo.
|
||||
- Il browser di Febe non si nasconde e non si riduce mai a icona (S2); nel registro mai indirizzi con il gettone, cookie
|
||||
o tasti; nessun pacchetto oltre a `Microsoft.Web.WebView2` (WPF e Windows Forms vengono con il .NET per Windows).
|
||||
|
||||
|
||||
@@ -79,6 +79,10 @@ internal sealed class BrowserBed : IAsyncDisposable
|
||||
/// <summary>Reads a value of the UI thread (the window, its position) through the dispatcher.</summary>
|
||||
public Task<T> OnUiAsync<T>(Func<T> read) => Ui.InvokeAsync(read);
|
||||
|
||||
/// <summary>The class names of the child windows of «Browser di Febe»: one per WebView hosted in it.</summary>
|
||||
public Task<IReadOnlyList<string>> ChildWindowsAsync() =>
|
||||
OnUiAsync(() => Browser.Host.Window is { } window ? ChildWindows.Of(window.Handle) : (IReadOnlyList<string>)[]);
|
||||
|
||||
/// <summary>
|
||||
/// Starts the browser from a thread-pool thread, like <c>FebeApp.BringUpBrowserAsync</c>, and waits until
|
||||
/// <see cref="WebView2Browser.RunAsync"/> returns. Fails at once when the log reports a failed start: the loop of
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// The direct child windows of a window, by class name. WebView2 hosted in a window («finestra») puts one child window
|
||||
/// per controller into its parent: two of them in «Browser di Febe» mean two WebViews, one of them orphaned.
|
||||
/// </summary>
|
||||
internal static class ChildWindows
|
||||
{
|
||||
/// <summary>The class names of the direct children of <paramref name="parent"/>, in Z order.</summary>
|
||||
public static IReadOnlyList<string> Of(IntPtr parent)
|
||||
{
|
||||
var names = new List<string>();
|
||||
var buffer = new char[256];
|
||||
var child = IntPtr.Zero;
|
||||
while ((child = FindWindowEx(parent, child, null, null)) != IntPtr.Zero)
|
||||
{
|
||||
var length = GetClassName(child, buffer, buffer.Length);
|
||||
names.Add(new string(buffer, 0, Math.Max(length, 0)));
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
[DllImport("user32.dll", EntryPoint = "FindWindowExW", CharSet = CharSet.Unicode)]
|
||||
private static extern IntPtr FindWindowEx(IntPtr parent, IntPtr childAfter, string? className, string? windowName);
|
||||
|
||||
[DllImport("user32.dll", EntryPoint = "GetClassNameW", CharSet = CharSet.Unicode)]
|
||||
private static extern int GetClassName(IntPtr window, [Out] char[] className, int maxCount);
|
||||
}
|
||||
@@ -132,6 +132,60 @@ public sealed class WebView2LifecycleTests
|
||||
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Regression (review of 20 October 2026): «Scollega» while the first start waits for its next attempt started the
|
||||
/// browser, then the waiting attempt started a second WebView in the same window without closing the first. The
|
||||
/// orphan kept its browser process alive on the profile: the next «Scollega» waited 15 s for nothing and could not
|
||||
/// delete the profile (the Instagram session stayed on disk), and exiting waited 15 s more.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task ScollegaWhileTheFirstStartWaitsToRetryLeavesOneWebViewAndTheNextScollegaWorks()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("scollega-nei-tentativi");
|
||||
|
||||
// A file where the profile folder must go: the first start fails, and fails again 5 s later.
|
||||
var profile = bed.Browser.ProfileDirectory;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(profile)!);
|
||||
await File.WriteAllTextAsync(profile, "occupa il posto della cartella del profilo", ct);
|
||||
var run = Task.Run(() => bed.Browser.RunAsync(ct), ct);
|
||||
await bed.WaitUntilAsync(() => bed.Lines.Any("Nuovo tentativo fra 15 s."), TimeSpan.FromSeconds(40), "il secondo avvio non riuscito", ct);
|
||||
File.Delete(profile);
|
||||
|
||||
// «Scollega» while RunAsync waits 15 s for its third attempt: the browser starts with it.
|
||||
await Task.Run(() => bed.Browser.RestartWithEmptyProfileAsync(ct), ct);
|
||||
Assert.IsTrue(bed.Browser.IsAvailable, bed.Lines.Text);
|
||||
var pid = bed.Browser.Host.BrowserProcessId;
|
||||
|
||||
// The waiting attempt finds the browser running: no second WebView, the one of «Scollega» untouched.
|
||||
await run.WaitAsync(TimeSpan.FromSeconds(40), ct);
|
||||
var children = await bed.ChildWindowsAsync();
|
||||
Assert.HasCount(1, children, "one WebView in the window: " + string.Join(", ", children));
|
||||
Assert.AreEqual(pid, bed.Browser.Host.BrowserProcessId, "the browser process of «Scollega» is still the one in use");
|
||||
Assert.IsTrue(bed.Lines.Any("Browser di Febe pronto: WebView2 "), bed.Lines.Text);
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
|
||||
// The next «Scollega»: the only browser process exits at once, the profile goes, the browser comes back.
|
||||
var marker = Path.Combine(profile, "segno-della-prova");
|
||||
await File.WriteAllTextAsync(marker, "x", ct);
|
||||
var watch = Stopwatch.StartNew();
|
||||
await Task.Run(() => bed.Browser.RestartWithEmptyProfileAsync(ct), ct);
|
||||
TestContext.WriteLine($"Secondo «Scollega»: {watch.Elapsed.TotalSeconds:0.0} s.");
|
||||
Assert.IsLessThan(10, watch.Elapsed.TotalSeconds, "no wait for a browser process that never exits");
|
||||
Assert.IsFalse(File.Exists(marker), "the profile with the session was deleted");
|
||||
Assert.HasCount(1, await bed.ChildWindowsAsync());
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
|
||||
// Exiting closes the only WebView and its process exits: no wait in vain.
|
||||
watch.Restart();
|
||||
await bed.Browser.DisposeAsync();
|
||||
TestContext.WriteLine($"Arresto: {watch.Elapsed.TotalSeconds:0.0} s.");
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsLessThan(10, watch.Elapsed.TotalSeconds, "exiting waits for nothing");
|
||||
Assert.HasCount(2, bed.Lines.Lines.Where(l => l.Contains("ERRORE", StringComparison.Ordinal)), "only the two failed starts: " + bed.Lines.Text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task WhenItsBrowserProcessDiesTheBrowserStartsAgainByItself()
|
||||
|
||||
Reference in new issue
Block a user