From 63776c7689591311427a433e1bbac57ccaa23721 Mon Sep 17 00:00:00 2001 From: Scott Hanselman Date: Tue, 1 Dec 2026 19:49:02 -0800 Subject: [PATCH 1/6] fix: don't start a connectivity probe after the Add gateway form closes Follows up #2433. LostFocus on the URL box can fire after a successful save collapses the form; ScheduleConnectivityTest now returns unless the Add form is open. The debounce delay moves inside the try so its cancellation is observed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Pages/ConnectionPage.xaml.cs | 18 +++++++++--------- .../AccessibilityThemeResourceSourceTests.cs | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs b/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs index 98482e5b47..30d8e8640c 100644 --- a/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs +++ b/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs @@ -2871,6 +2871,8 @@ private void StopConnectivityTest() private void ScheduleConnectivityTest(string? rawUrl) { _connectivityTestCts?.Cancel(); + // LostFocus can fire after a successful save closes the form; a probe then would announce a stale result. + if (_userIntent != UserIntent.AddingGateway) return; if (string.IsNullOrWhiteSpace(rawUrl)) { AddTestResultText.Visibility = Microsoft.UI.Xaml.Visibility.Collapsed; @@ -2884,18 +2886,16 @@ private void ScheduleConnectivityTest(string? rawUrl) private async Task RunConnectivityTestAsync(string rawUrl, System.Threading.CancellationToken ct, int delay = 0) { - if (delay > 0) + try { - await Task.Delay(delay, ct); + if (delay > 0) + await Task.Delay(delay, ct); if (ct.IsCancellationRequested) return; - } - AddTestResultText.Visibility = Microsoft.UI.Xaml.Visibility.Visible; - AddTestResultText.Foreground = (Microsoft.UI.Xaml.Media.Brush)Application.Current.Resources["TextFillColorSecondaryBrush"]; - AddTestResultText.Text = LocalizationHelper.GetString("ConnectionPage_TestingConnection"); + AddTestResultText.Visibility = Microsoft.UI.Xaml.Visibility.Visible; + AddTestResultText.Foreground = (Microsoft.UI.Xaml.Media.Brush)Application.Current.Resources["TextFillColorSecondaryBrush"]; + AddTestResultText.Text = LocalizationHelper.GetString("ConnectionPage_TestingConnection"); - try - { var url = GatewayUrlHelper.NormalizeForWebSocket(rawUrl); var httpUrl = url.Replace("ws://", "http://").Replace("wss://", "https://").TrimEnd('/'); @@ -3366,12 +3366,12 @@ private void OnAddDiscoveredGateway(object sender, RoutedEventArgs e) // Pre-fill the Direct pane and enter AddGateway mode. User types // the token there and clicks Save & connect. _editingGatewayId = null; + _userIntent = UserIntent.AddingGateway; DirectUrlBox.Text = url; DirectTokenBox.Text = ""; DirectNameBox.Text = ""; AddDirectItem.IsSelected = true; ShowAddPane("direct"); - _userIntent = UserIntent.AddingGateway; RefreshFromSnapshot(_lastSnapshot); } diff --git a/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs b/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs index af2941b870..9123316a7e 100644 --- a/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs +++ b/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs @@ -222,6 +222,21 @@ public void LeavingTheAddForm_StopsThePendingConnectivityProbe(string method) Assert.Contains("StopConnectivityTest();", source[start..end]); } + // LostFocus on the URL box can fire after a successful save closes the form. + [Fact] + public void ConnectivityProbe_IsOnlyScheduledWhileAddingAGateway() + { + var source = ReadSource("src", "OpenClaw.Tray.WinUI", "Pages", "ConnectionPage.xaml.cs"); + var method = "private void ScheduleConnectivityTest("; + var start = source.IndexOf(method, StringComparison.Ordinal); + Assert.True(start >= 0, $"{method} not found"); + var end = source.IndexOf("\n private ", start + method.Length, StringComparison.Ordinal); + var body = source[start..end]; + var guard = body.IndexOf("if (_userIntent != UserIntent.AddingGateway) return;", StringComparison.Ordinal); + Assert.True(guard >= 0, "ScheduleConnectivityTest must return when the Add form is not open."); + Assert.True(guard < body.IndexOf("new System.Threading.CancellationTokenSource()", StringComparison.Ordinal)); + } + // The URL box stays editable while saving, so an edit during the await can start a new probe. [Theory] [InlineData("private async Task DoDirectConnectFromAddFormAsync(")] From c0b234ac6cea297886e2393b8520192298c010dd Mon Sep 17 00:00:00 2001 From: Scott Hanselman Date: Tue, 1 Dec 2026 20:54:31 -0800 Subject: [PATCH 2/6] fix: only announce connection-test results while the Add form is open Re-checks the Add-form intent before announcing a probe result, and pins the discovered-gateway intent-before-URL order with a source test. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Pages/ConnectionPage.xaml.cs | 6 +++-- .../AccessibilityThemeResourceSourceTests.cs | 24 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs b/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs index 30d8e8640c..86f4256774 100644 --- a/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs +++ b/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs @@ -2942,7 +2942,8 @@ private async Task RunConnectivityTestAsync(string rawUrl, System.Threading.Canc AddTestResultText.Foreground = (Microsoft.UI.Xaml.Media.Brush)Application.Current.Resources["SystemFillColorCriticalBrush"]; } // This probe reruns while the URL is typed, so its result is announced politely. - AutomationAnnouncer.Announce(this, AddTestResultText.Text); + if (_userIntent == UserIntent.AddingGateway) + AutomationAnnouncer.Announce(this, AddTestResultText.Text); } // slopwatch-ignore: SW003 Shutdown cancellation or disposal is expected and the caller already preserves the safe state. catch (OperationCanceledException) when (ct.IsCancellationRequested) { /* debounce or page nav */ } @@ -2953,7 +2954,8 @@ private async Task RunConnectivityTestAsync(string rawUrl, System.Threading.Canc Logger.Warn($"ConnectionPage: Gateway connectivity test failed for {GatewayUrlHelper.SanitizeForDisplay(rawUrl)}: {ex.Message}"); AddTestResultText.Text = "✗ Unable to test gateway connection. Check the URL and try again."; AddTestResultText.Foreground = (Microsoft.UI.Xaml.Media.Brush)Application.Current.Resources["SystemFillColorCriticalBrush"]; - AutomationAnnouncer.Announce(this, AddTestResultText.Text); + if (_userIntent == UserIntent.AddingGateway) + AutomationAnnouncer.Announce(this, AddTestResultText.Text); } } } diff --git a/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs b/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs index 9123316a7e..13a53a4b0f 100644 --- a/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs +++ b/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs @@ -237,6 +237,30 @@ public void ConnectivityProbe_IsOnlyScheduledWhileAddingAGateway() Assert.True(guard < body.IndexOf("new System.Threading.CancellationTokenSource()", StringComparison.Ordinal)); } + // Setting the URL fires TextChanged, which schedules a probe only if the form is already marked open. + [Fact] + public void AddDiscoveredGateway_OpensTheFormBeforeFillingInTheUrl() + { + var body = MethodBody("ConnectionPage.xaml.cs", "private void OnAddDiscoveredGateway("); + var intent = body.IndexOf("_userIntent = UserIntent.AddingGateway;", StringComparison.Ordinal); + var url = body.IndexOf("DirectUrlBox.Text = url;", StringComparison.Ordinal); + Assert.True(intent >= 0 && url >= 0, "Expected both the intent and URL assignments."); + Assert.True(intent < url, "_userIntent must be set before DirectUrlBox.Text."); + } + + // A probe already in flight when the form closes must not announce its result. + [Fact] + public void ConnectivityProbe_AnnouncesOnlyWhileAddingAGateway() + { + var body = MethodBody("ConnectionPage.xaml.cs", "private async Task RunConnectivityTestAsync("); + const string announce = "AutomationAnnouncer.Announce(this, AddTestResultText.Text);"; + var announces = body.Split(announce).Length - 1; + var guarded = System.Text.RegularExpressions.Regex.Matches( + body, @"if \(_userIntent == UserIntent\.AddingGateway\)\s*" + System.Text.RegularExpressions.Regex.Escape(announce)).Count; + Assert.Equal(2, announces); + Assert.Equal(announces, guarded); + } + // The URL box stays editable while saving, so an edit during the await can start a new probe. [Theory] [InlineData("private async Task DoDirectConnectFromAddFormAsync(")] From e6f7f742cbf6e80a1a2c5c56ba77d13296d75913 Mon Sep 17 00:00:00 2001 From: Scott Hanselman Date: Tue, 1 Dec 2026 21:33:47 -0800 Subject: [PATCH 3/6] test: prove a stale Add-gateway connection test stays silent Move the Add gateway probe lifecycle into AddGatewayConnectivityTest so it can be tested without WinUI. Behavioral tests hold a request in flight through Stop and a form close, then release it and assert nothing is reported. Also stop the probe when switching to a saved gateway. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Pages/ConnectionPage.xaml.cs | 113 ++++------------ .../Services/AddGatewayConnectivityTest.cs | 126 ++++++++++++++++++ .../AccessibilityThemeResourceSourceTests.cs | 43 +----- .../AddGatewayConnectivityTestTests.cs | 117 ++++++++++++++++ .../OpenClaw.Tray.Tests.csproj | 1 + 5 files changed, 277 insertions(+), 123 deletions(-) create mode 100644 src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs create mode 100644 tests/OpenClaw.Tray.Tests/AddGatewayConnectivityTestTests.cs diff --git a/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs b/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs index 86f4256774..6df8843d1b 100644 --- a/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs +++ b/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs @@ -191,7 +191,7 @@ private void OnPageUnloaded(object sender, RoutedEventArgs e) _reconnectMaskTimer = null; } _gatewayHostActionCts?.Cancel(); - _connectivityTestCts?.Cancel(); + _connectivityTest?.Stop(); if (!_gatewayHostActionInProgress) { _gatewayHostActionCts?.Dispose(); @@ -2634,6 +2634,7 @@ private async Task OnConnectSavedGatewayAsync(object sender) try { _userIntent = UserIntent.None; + StopConnectivityTest(); // Await the switch so any failure surfaces in the strip via the // catch below rather than becoming a silent unobserved task // exception. The state-change events that drive the rest of the @@ -2829,7 +2830,7 @@ private async Task OnSavedRowRemoveAsync(object sender) // ─── Auto-test connectivity (debounced) ──────────────────────────── - private System.Threading.CancellationTokenSource? _connectivityTestCts; + private AddGatewayConnectivityTest? _connectivityTest; private void OnDirectInputChanged(object sender, RoutedEventArgs e) { @@ -2860,104 +2861,44 @@ private void AutoFillTokenForUrl(string? url, bool force = false) DirectTokenBox.Text = ""; } - // A probe finishing after the form is saved or closed must not show or announce a stale result. + // A test finishing after the form is saved or closed must not show or announce a stale result. private void StopConnectivityTest() { - _connectivityTestCts?.Cancel(); + _connectivityTest?.Stop(); AddTestResultText.Text = ""; AddTestResultText.Visibility = Microsoft.UI.Xaml.Visibility.Collapsed; } private void ScheduleConnectivityTest(string? rawUrl) { - _connectivityTestCts?.Cancel(); - // LostFocus can fire after a successful save closes the form; a probe then would announce a stale result. - if (_userIntent != UserIntent.AddingGateway) return; - if (string.IsNullOrWhiteSpace(rawUrl)) - { + _connectivityTest ??= new AddGatewayConnectivityTest( + isFormOpen: () => _userIntent == UserIntent.AddingGateway, + onTesting: ShowConnectivityTesting, + onCompleted: ShowConnectivityResult, + warn: message => Logger.Warn($"ConnectionPage: {message}")); + if (!_connectivityTest.Schedule(rawUrl) && string.IsNullOrWhiteSpace(rawUrl)) AddTestResultText.Visibility = Microsoft.UI.Xaml.Visibility.Collapsed; - return; - } - _connectivityTestCts = new System.Threading.CancellationTokenSource(); - var token = _connectivityTestCts.Token; - // Debounce 600ms so we don't hit the network on every keystroke - _ = RunConnectivityTestAsync(rawUrl, token, delay: 600); } - private async Task RunConnectivityTestAsync(string rawUrl, System.Threading.CancellationToken ct, int delay = 0) + private void ShowConnectivityTesting() { - try - { - if (delay > 0) - await Task.Delay(delay, ct); - if (ct.IsCancellationRequested) return; - - AddTestResultText.Visibility = Microsoft.UI.Xaml.Visibility.Visible; - AddTestResultText.Foreground = (Microsoft.UI.Xaml.Media.Brush)Application.Current.Resources["TextFillColorSecondaryBrush"]; - AddTestResultText.Text = LocalizationHelper.GetString("ConnectionPage_TestingConnection"); - - var url = GatewayUrlHelper.NormalizeForWebSocket(rawUrl); - var httpUrl = url.Replace("ws://", "http://").Replace("wss://", "https://").TrimEnd('/'); - - using var httpClient = new System.Net.Http.HttpClient { Timeout = TimeSpan.FromSeconds(5) }; - System.Net.Http.HttpResponseMessage? response = null; - Exception? firstProbeError = null; - try { response = await httpClient.GetAsync(httpUrl, ct); } - catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } - catch (Exception ex) - { - firstProbeError = ex; - Logger.Warn($"ConnectionPage: Gateway connectivity probe failed for {GatewayUrlHelper.SanitizeForDisplay(httpUrl)}: {ex.Message}"); - } - - if (ct.IsCancellationRequested) return; - - if (response == null || !response.IsSuccessStatusCode) - { - var healthUrl = $"{httpUrl}/health"; - try { response = await httpClient.GetAsync(healthUrl, ct); } - catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } - catch (Exception ex) - { - Logger.Warn($"ConnectionPage: Gateway /health connectivity probe failed for {GatewayUrlHelper.SanitizeForDisplay(httpUrl)}: {ex.Message}"); - firstProbeError ??= ex; - } - } - - if (ct.IsCancellationRequested) return; + AddTestResultText.Visibility = Microsoft.UI.Xaml.Visibility.Visible; + AddTestResultText.Foreground = (Microsoft.UI.Xaml.Media.Brush)Application.Current.Resources["TextFillColorSecondaryBrush"]; + AddTestResultText.Text = LocalizationHelper.GetString("ConnectionPage_TestingConnection"); + } - if (response != null && response.IsSuccessStatusCode) - { - AddTestResultText.Text = $"✓ {LocalizationHelper.GetString("ConnectionPage_GatewayReachable")}"; - AddTestResultText.Foreground = (Microsoft.UI.Xaml.Media.Brush)Application.Current.Resources["SystemFillColorSuccessBrush"]; - } - else if (response != null) - { - AddTestResultText.Text = $"⚠ {string.Format(LocalizationHelper.GetString("ConnectionPage_GatewayRespondedWith"), (int)response.StatusCode)}"; - AddTestResultText.Foreground = (Microsoft.UI.Xaml.Media.Brush)Application.Current.Resources["SystemFillColorCautionBrush"]; - } - else - { - AddTestResultText.Text = $"✗ {LocalizationHelper.GetString("ConnectionPage_CannotReachGateway")}"; - AddTestResultText.Foreground = (Microsoft.UI.Xaml.Media.Brush)Application.Current.Resources["SystemFillColorCriticalBrush"]; - } - // This probe reruns while the URL is typed, so its result is announced politely. - if (_userIntent == UserIntent.AddingGateway) - AutomationAnnouncer.Announce(this, AddTestResultText.Text); - } - // slopwatch-ignore: SW003 Shutdown cancellation or disposal is expected and the caller already preserves the safe state. - catch (OperationCanceledException) when (ct.IsCancellationRequested) { /* debounce or page nav */ } - catch (Exception ex) + private void ShowConnectivityResult(GatewayProbeOutcome outcome, int? statusCode) + { + (AddTestResultText.Text, var brush) = outcome switch { - if (!ct.IsCancellationRequested) - { - Logger.Warn($"ConnectionPage: Gateway connectivity test failed for {GatewayUrlHelper.SanitizeForDisplay(rawUrl)}: {ex.Message}"); - AddTestResultText.Text = "✗ Unable to test gateway connection. Check the URL and try again."; - AddTestResultText.Foreground = (Microsoft.UI.Xaml.Media.Brush)Application.Current.Resources["SystemFillColorCriticalBrush"]; - if (_userIntent == UserIntent.AddingGateway) - AutomationAnnouncer.Announce(this, AddTestResultText.Text); - } - } + GatewayProbeOutcome.Reachable => ($"✓ {LocalizationHelper.GetString("ConnectionPage_GatewayReachable")}", "SystemFillColorSuccessBrush"), + GatewayProbeOutcome.ErrorStatus => ($"⚠ {string.Format(LocalizationHelper.GetString("ConnectionPage_GatewayRespondedWith"), statusCode)}", "SystemFillColorCautionBrush"), + GatewayProbeOutcome.Unreachable => ($"✗ {LocalizationHelper.GetString("ConnectionPage_CannotReachGateway")}", "SystemFillColorCriticalBrush"), + _ => ("✗ Unable to test gateway connection. Check the URL and try again.", "SystemFillColorCriticalBrush"), + }; + AddTestResultText.Foreground = (Microsoft.UI.Xaml.Media.Brush)Application.Current.Resources[brush]; + // This test reruns while the URL is typed, so its result is announced politely. + AutomationAnnouncer.Announce(this, AddTestResultText.Text); } private void OnAddSave(object sender, RoutedEventArgs e) => diff --git a/src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs b/src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs new file mode 100644 index 0000000000..11c6900147 --- /dev/null +++ b/src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs @@ -0,0 +1,126 @@ +// AddGatewayConnectivityTest: owns the Add gateway form's live connection test. +// It debounces URL edits, probes the base URL then /health over HTTP, and reports +// the outcome through callbacks. Stop() cancels the in-flight test, and a result +// is only reported while the form is still open, so a test that outlives Save, +// Back or a saved-gateway switch never shows or announces a stale result. Only +// caller cancellation is silent: an HttpClient timeout is reported as Unreachable. +// +// Usage (from the WinUI page, on the UI thread): +// _test = new AddGatewayConnectivityTest( +// isFormOpen: () => _userIntent == UserIntent.AddingGateway, +// onTesting: () => ShowTesting(), +// onCompleted: (outcome, status) => ShowAndAnnounce(outcome, status), +// warn: Logger.Warn); +// _test.Schedule(DirectUrlBox.Text); // on each URL edit +// _test.Stop(); // when the form closes +using System; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using OpenClaw.Shared; + +namespace OpenClawTray.Services; + +public enum GatewayProbeOutcome { Reachable, ErrorStatus, Unreachable, Failed } + +public sealed class AddGatewayConnectivityTest +{ + public static readonly TimeSpan DefaultDebounce = TimeSpan.FromMilliseconds(600); + public static readonly TimeSpan DefaultRequestTimeout = TimeSpan.FromSeconds(5); + + private readonly Func _isFormOpen; + private readonly Action _onTesting; + private readonly Action _onCompleted; + private readonly Action? _warn; + private readonly Func _createClient; + private readonly TimeSpan _debounce; + private CancellationTokenSource? _cts; + + public AddGatewayConnectivityTest( + Func isFormOpen, + Action onTesting, + Action onCompleted, + Action? warn = null, + Func? createClient = null, + TimeSpan? debounce = null) + { + _isFormOpen = isFormOpen; + _onTesting = onTesting; + _onCompleted = onCompleted; + _warn = warn; + _createClient = createClient ?? (() => new HttpClient { Timeout = DefaultRequestTimeout }); + _debounce = debounce ?? DefaultDebounce; + } + + /// The in-flight test, for tests that need to await completion. + public Task Current { get; private set; } = Task.CompletedTask; + + /// Cancels any pending test and starts a new one. Returns false when nothing was scheduled. + public bool Schedule(string? rawUrl) + { + _cts?.Cancel(); + if (!_isFormOpen() || string.IsNullOrWhiteSpace(rawUrl)) return false; + _cts = new CancellationTokenSource(); + Current = RunAsync(rawUrl, _cts.Token); + return true; + } + + public void Stop() => _cts?.Cancel(); + + private bool ShouldReport(CancellationToken ct) => !ct.IsCancellationRequested && _isFormOpen(); + + // No ConfigureAwait(false): callbacks must run on the caller's (UI) context. + private async Task RunAsync(string rawUrl, CancellationToken ct) + { + try + { + if (_debounce > TimeSpan.Zero) + await Task.Delay(_debounce, ct); + if (!ShouldReport(ct)) return; + _onTesting(); + + var url = GatewayUrlHelper.NormalizeForWebSocket(rawUrl); + var httpUrl = url.Replace("ws://", "http://").Replace("wss://", "https://").TrimEnd('/'); + using var http = _createClient(); + + var response = await TryGetAsync(http, httpUrl, ct); + if (response == null || !response.IsSuccessStatusCode) + { + response?.Dispose(); + response = await TryGetAsync(http, $"{httpUrl}/health", ct); + } + + using (response) + { + if (!ShouldReport(ct)) return; + if (response == null) _onCompleted(GatewayProbeOutcome.Unreachable, null); + else if (response.IsSuccessStatusCode) _onCompleted(GatewayProbeOutcome.Reachable, null); + else _onCompleted(GatewayProbeOutcome.ErrorStatus, (int)response.StatusCode); + } + } + // slopwatch-ignore: SW003 Caller cancellation means the form changed or closed; nothing should be shown. + catch (OperationCanceledException) when (ct.IsCancellationRequested) { } + catch (Exception ex) + { + _warn?.Invoke($"Gateway connectivity test failed for {GatewayUrlHelper.SanitizeForDisplay(rawUrl)}: {ex.Message}"); + if (ShouldReport(ct)) _onCompleted(GatewayProbeOutcome.Failed, null); + } + } + + private async Task TryGetAsync(HttpClient http, string url, CancellationToken ct) + { + try + { + return await http.GetAsync(url, ct); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + _warn?.Invoke($"Gateway connectivity probe failed for {GatewayUrlHelper.SanitizeForDisplay(url)}: {ex.Message}"); + return null; + } + } +} diff --git a/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs b/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs index 13a53a4b0f..9d536a43bd 100644 --- a/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs +++ b/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs @@ -188,7 +188,7 @@ public void SystemAndConnectionNavigationSvgIcons_HaveHighContrastGlyphFallbacks [InlineData("PermissionsPage.xaml.cs", "private void OnCopyMcpUrl(", 1)] [InlineData("ConnectionPage.xaml.cs", "private void SetGatewayHostActionStatus(", 1)] [InlineData("ConnectionPage.xaml.cs", "private async Task OnApplyRepairCodeAsync(", 1)] - [InlineData("ConnectionPage.xaml.cs", "private async Task RunConnectivityTestAsync(", 2)] + [InlineData("ConnectionPage.xaml.cs", "private void ShowConnectivityResult(", 1)] public void ActionResultSurfaces_AnnounceTheirResultToScreenReaders(string page, string method, int expected) { // Retire when native UI tests can observe UIA notification events for these action results (#1946). @@ -213,6 +213,7 @@ public void GatewayHostActions_AnnounceFinalResultsOnly() [Theory] [InlineData("private void OnAddBack(")] [InlineData("private async Task OnAddSaveAsync(")] + [InlineData("private async Task OnConnectSavedGatewayAsync(")] public void LeavingTheAddForm_StopsThePendingConnectivityProbe(string method) { var source = ReadSource("src", "OpenClaw.Tray.WinUI", "Pages", "ConnectionPage.xaml.cs"); @@ -222,21 +223,13 @@ public void LeavingTheAddForm_StopsThePendingConnectivityProbe(string method) Assert.Contains("StopConnectivityTest();", source[start..end]); } - // LostFocus on the URL box can fire after a successful save closes the form. + // The behavioral gate lives in AddGatewayConnectivityTest; the page must feed it the Add-form state. [Fact] - public void ConnectivityProbe_IsOnlyScheduledWhileAddingAGateway() + public void ConnectivityTest_IsGatedOnTheAddForm() { - var source = ReadSource("src", "OpenClaw.Tray.WinUI", "Pages", "ConnectionPage.xaml.cs"); - var method = "private void ScheduleConnectivityTest("; - var start = source.IndexOf(method, StringComparison.Ordinal); - Assert.True(start >= 0, $"{method} not found"); - var end = source.IndexOf("\n private ", start + method.Length, StringComparison.Ordinal); - var body = source[start..end]; - var guard = body.IndexOf("if (_userIntent != UserIntent.AddingGateway) return;", StringComparison.Ordinal); - Assert.True(guard >= 0, "ScheduleConnectivityTest must return when the Add form is not open."); - Assert.True(guard < body.IndexOf("new System.Threading.CancellationTokenSource()", StringComparison.Ordinal)); + var body = MethodBody("ConnectionPage.xaml.cs", "private void ScheduleConnectivityTest("); + Assert.Contains("isFormOpen: () => _userIntent == UserIntent.AddingGateway", body); } - // Setting the URL fires TextChanged, which schedules a probe only if the form is already marked open. [Fact] public void AddDiscoveredGateway_OpensTheFormBeforeFillingInTheUrl() @@ -248,19 +241,6 @@ public void AddDiscoveredGateway_OpensTheFormBeforeFillingInTheUrl() Assert.True(intent < url, "_userIntent must be set before DirectUrlBox.Text."); } - // A probe already in flight when the form closes must not announce its result. - [Fact] - public void ConnectivityProbe_AnnouncesOnlyWhileAddingAGateway() - { - var body = MethodBody("ConnectionPage.xaml.cs", "private async Task RunConnectivityTestAsync("); - const string announce = "AutomationAnnouncer.Announce(this, AddTestResultText.Text);"; - var announces = body.Split(announce).Length - 1; - var guarded = System.Text.RegularExpressions.Regex.Matches( - body, @"if \(_userIntent == UserIntent\.AddingGateway\)\s*" + System.Text.RegularExpressions.Regex.Escape(announce)).Count; - Assert.Equal(2, announces); - Assert.Equal(announces, guarded); - } - // The URL box stays editable while saving, so an edit during the await can start a new probe. [Theory] [InlineData("private async Task DoDirectConnectFromAddFormAsync(")] @@ -273,17 +253,6 @@ public void SuccessfulAddFormSave_StopsAProbeStartedDuringTheSave(string method) Assert.True(stop >= 0 && reload > stop, $"{method} must stop the probe before reloading the gateway list"); } - // An HttpClient timeout throws TaskCanceledException without cancelling ct; it must reach an announced result. - [Fact] - public void ConnectivityProbe_TreatsOnlyCallerCancellationAsSilent() - { - var body = MethodBody("ConnectionPage.xaml.cs", "private async Task RunConnectivityTestAsync("); - var allCatches = body.Split("catch (OperationCanceledException)").Length - 1; - var callerOnly = body.Split("catch (OperationCanceledException) when (ct.IsCancellationRequested)").Length - 1; - Assert.Equal(3, allCatches); - Assert.Equal(allCatches, callerOnly); - } - private static string MethodBody(string page, string method) { var source = ReadSource("src", "OpenClaw.Tray.WinUI", "Pages", page); diff --git a/tests/OpenClaw.Tray.Tests/AddGatewayConnectivityTestTests.cs b/tests/OpenClaw.Tray.Tests/AddGatewayConnectivityTestTests.cs new file mode 100644 index 0000000000..a7dcf449c9 --- /dev/null +++ b/tests/OpenClaw.Tray.Tests/AddGatewayConnectivityTestTests.cs @@ -0,0 +1,117 @@ +using System.Net; +using OpenClawTray.Services; + +namespace OpenClaw.Tray.Tests; + +// Drives the Add gateway connection test with a fake HTTP handler that holds the request in flight. +public sealed class AddGatewayConnectivityTestTests +{ + private const string Url = "ws://gateway.test:18789"; + + // Save & connect and Back both call StopConnectivityTest while a request may still be pending. + [Fact] + public async Task StoppedWhileInFlight_ShowsNothingAfterTheRequestFinishes() + { + var harness = new Harness(); + Assert.True(harness.Test.Schedule(Url)); + await harness.Handler.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + + harness.Test.Stop(); + harness.Handler.Release(HttpStatusCode.OK); + await harness.Test.Current.WaitAsync(TimeSpan.FromSeconds(10)); + + Assert.Equal(1, harness.TestingCount); + Assert.Empty(harness.Results); + } + + // A successful save, or switching to a saved gateway, closes the form before the request returns. + [Fact] + public async Task FormClosedWhileInFlight_ShowsNothingAfterTheRequestFinishes() + { + var harness = new Harness(); + Assert.True(harness.Test.Schedule(Url)); + await harness.Handler.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + + harness.FormOpen = false; + harness.Handler.Release(HttpStatusCode.OK); + await harness.Test.Current.WaitAsync(TimeSpan.FromSeconds(10)); + + Assert.Empty(harness.Results); + } + + // LostFocus on the URL box can fire after the form closes. + [Fact] + public void ScheduleWhileFormClosed_StartsNothing() + { + var harness = new Harness { FormOpen = false }; + + Assert.False(harness.Test.Schedule(Url)); + Assert.Equal(0, harness.Handler.RequestCount); + } + + [Fact] + public async Task OpenForm_ReportsTheResult() + { + var harness = new Harness(); + Assert.True(harness.Test.Schedule(Url)); + await harness.Handler.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + + harness.Handler.Release(HttpStatusCode.OK); + await harness.Test.Current.WaitAsync(TimeSpan.FromSeconds(10)); + + Assert.Equal([(GatewayProbeOutcome.Reachable, (int?)null)], harness.Results); + } + + // An HttpClient timeout throws TaskCanceledException without cancelling the caller's token. + [Fact] + public async Task HttpClientTimeout_ReportsUnreachable() + { + var harness = new Harness(requestTimeout: TimeSpan.FromMilliseconds(50)); + Assert.True(harness.Test.Schedule(Url)); + + await harness.Test.Current.WaitAsync(TimeSpan.FromSeconds(10)); + + Assert.Equal([(GatewayProbeOutcome.Unreachable, (int?)null)], harness.Results); + Assert.Equal(2, harness.Handler.RequestCount); + } + + private sealed class Harness + { + public Harness(TimeSpan? requestTimeout = null) + { + Handler = new BlockingHandler(ignoreCancellation: requestTimeout is null); + Test = new AddGatewayConnectivityTest( + isFormOpen: () => FormOpen, + onTesting: () => TestingCount++, + onCompleted: (outcome, status) => Results.Add((outcome, status)), + createClient: () => new HttpClient(Handler, disposeHandler: false) { Timeout = requestTimeout ?? TimeSpan.FromSeconds(30) }, + debounce: TimeSpan.Zero); + } + + public BlockingHandler Handler { get; } + public AddGatewayConnectivityTest Test { get; } + public bool FormOpen { get; set; } = true; + public int TestingCount { get; private set; } + public List<(GatewayProbeOutcome, int?)> Results { get; } = []; + } + + // Holds every request until Release. Ignoring cancellation models a slow gateway that answers after Stop. + private sealed class BlockingHandler(bool ignoreCancellation) : HttpMessageHandler + { + private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _requestCount; + + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public int RequestCount => Volatile.Read(ref _requestCount); + + public void Release(HttpStatusCode status) => _release.TrySetResult(status); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Interlocked.Increment(ref _requestCount); + Entered.TrySetResult(); + var status = ignoreCancellation ? await _release.Task : await _release.Task.WaitAsync(cancellationToken); + return new HttpResponseMessage(status); + } + } +} diff --git a/tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj b/tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj index 5b3c446660..a815caa4c3 100644 --- a/tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj +++ b/tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj @@ -66,6 +66,7 @@ + From adad5e8b4b0168bc92228e4a539dff6c56fb22f0 Mon Sep 17 00:00:00 2001 From: Scott Hanselman Date: Tue, 1 Dec 2026 22:19:01 -0800 Subject: [PATCH 4/6] fix: keep the base status when /health fails and clear the probe on unload - OnPageUnloaded uses StopConnectivityTest so stale text is cleared. - A failed /health fallback keeps the base non-2xx status, as before the extraction. - Stop rechecks cancellation before /health and disposes replaced token sources. - Tests: pre-buffered Stop fake, ordered save-path guards, base-status test, ledger row. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/ARCHITECTURE.md | 1 + .../Pages/ConnectionPage.xaml.cs | 2 +- .../Services/AddGatewayConnectivityTest.cs | 25 ++++++++++++--- .../AccessibilityThemeResourceSourceTests.cs | 19 +++++++---- .../AddGatewayConnectivityTestTests.cs | 32 ++++++++++++++++++- 5 files changed, 67 insertions(+), 12 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d22af178fc..b522afddd8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1129,6 +1129,7 @@ leading and trailing pipe. Columns, in order: | managed-local-repair | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs and direct reconnect callbacks | repair eligibility, restart budgets, port remediation, and reconnect verification | ManagedLocalGatewayAutoRepairMonitor + ManagedLocalGatewayRepairCoordinator | App composition and dependency callbacks only | explicit disconnect and gateway switches abort repair before restart or reconnect | ManagedLocalGatewayRepairCoordinatorTests.UserDisconnectedIntent_AbortsBeforeProbeOrRestart | behavioral | - | | app-managed-local-repair-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | managed-local repair loops, probing, restart budgeting, and verification implementation | ManagedLocalGatewayAutoRepairMonitor + ManagedLocalGatewayRepairCoordinator | service construction, callback adapters, and lifetime wiring only | App remains the composition root and does not regain repair implementation | AppRefactorContractTests.ManagedLocalGatewayRepair_StaysDelegatedToDedicatedOwners | source-shape | when App no longer constructs the managed-local repair services directly | | connection-page-direct-connect-closed | closed | src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs | direct-connect registry, identity-token, settings, rollback, terminal-wait, and runtime-tunnel transaction | GatewayDirectConnectService | add-form control reads, input validation, result text, and post-success visual refresh only | the page delegates one request; rollback restores the durable registry before identity and settings, reconnects a previously live gateway, and a later credential writer wins | GatewayDirectConnectServiceTests.Connect_Failure_RestoresPreviousLiveConnection | behavioral | when the Connection page no longer contains any direct-connect persistence or rollback logic | +| connection-page-add-connectivity-test-closed | closed | src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs | Add form live connection test debounce, HTTP probe, /health fallback, and stale-result gating | AddGatewayConnectivityTest | result text, live-region announcement, and StopConnectivityTest calls when leaving the Add form or completing a save only | no result is shown or announced after Stop or form close; only caller cancellation is silent; a failed /health fallback keeps the base status | AddGatewayConnectivityTestTests.StoppedWhileInFlight_ShowsNothingAfterTheRequestFinishes | behavioral | when the Add form no longer runs a live connection test | | connection-status-direct-connect-closed | closed | src/OpenClaw.Tray.WinUI/Windows/ConnectionStatusWindow.xaml.cs | direct-connect registry, settings, rollback, terminal-wait, and runtime-tunnel transaction | GatewayDirectConnectService | diagnostics control reads, input validation, and result text only | diagnostics direct connect delegates one request and cannot report success before a terminal manager state | AppRefactorContractTests.StatusWindowDirectConnect_WaitsForManagerStateBeforeReportingConnected | source-shape | when the status window no longer contains direct-connect persistence or rollback logic | | app-window-manager | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | Settings companion, Workspace, status, setup, canvas request, and runtime-anchor window creation, reuse, focus, theme, owner, and lifetime mechanics | IWindowManager + WindowManager | App owns composition, typed activation-plan application through WindowManager, service-policy callback adapters, setup restart policy, pairing approval dialog workflow and shell, and shutdown-plan callback construction | distinct window types and exact routes are preserved; Settings close resets navigation scope; setup replacement waits for cleanup; shutdown closes owned windows once before provider disposal | WindowManagerTests.CloseForShutdown_GatesCreationAndClosesOwnedWindowsOnce | source-shape | when App is replaced as the WinUI composition root | | app-window-surface-ownership-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | concrete non-tray window fields, constructors, show/hide/focus/theme/close mechanics, and window event lifetime | IWindowManager + WindowManager | interface forwarding, immutable request construction, route and policy callbacks, and setup restart dialog policy only | App cannot regain a parallel Settings, Workspace, status, setup, canvas-request, or runtime-anchor owner, nor revive the retired chat popup | AppSurfaceOwnershipContractTests.App_DelegatesConcreteTrayAndWindowOwnership | source-shape | when App is replaced as the WinUI composition root | diff --git a/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs b/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs index 6df8843d1b..f508efd0e1 100644 --- a/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs +++ b/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs @@ -191,7 +191,7 @@ private void OnPageUnloaded(object sender, RoutedEventArgs e) _reconnectMaskTimer = null; } _gatewayHostActionCts?.Cancel(); - _connectivityTest?.Stop(); + StopConnectivityTest(); if (!_gatewayHostActionInProgress) { _gatewayHostActionCts?.Dispose(); diff --git a/src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs b/src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs index 11c6900147..0f508b7e73 100644 --- a/src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs +++ b/src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs @@ -58,14 +58,21 @@ public AddGatewayConnectivityTest( /// Cancels any pending test and starts a new one. Returns false when nothing was scheduled. public bool Schedule(string? rawUrl) { - _cts?.Cancel(); + Stop(); if (!_isFormOpen() || string.IsNullOrWhiteSpace(rawUrl)) return false; _cts = new CancellationTokenSource(); Current = RunAsync(rawUrl, _cts.Token); return true; } - public void Stop() => _cts?.Cancel(); + // Cancel runs the token's callbacks before returning, so the in-flight test only reads its + // cancelled state afterwards, which stays valid once the source is disposed. + public void Stop() + { + _cts?.Cancel(); + _cts?.Dispose(); + _cts = null; + } private bool ShouldReport(CancellationToken ct) => !ct.IsCancellationRequested && _isFormOpen(); @@ -84,10 +91,20 @@ private async Task RunAsync(string rawUrl, CancellationToken ct) using var http = _createClient(); var response = await TryGetAsync(http, httpUrl, ct); - if (response == null || !response.IsSuccessStatusCode) + if (!ShouldReport(ct)) { response?.Dispose(); - response = await TryGetAsync(http, $"{httpUrl}/health", ct); + return; + } + if (response == null || !response.IsSuccessStatusCode) + { + // Keep the base status if /health fails, so "Gateway responded with N" still reports it. + var health = await TryGetAsync(http, $"{httpUrl}/health", ct); + if (health != null) + { + response?.Dispose(); + response = health; + } } using (response) diff --git a/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs b/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs index 9d536a43bd..7b013b5494 100644 --- a/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs +++ b/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs @@ -214,6 +214,7 @@ public void GatewayHostActions_AnnounceFinalResultsOnly() [InlineData("private void OnAddBack(")] [InlineData("private async Task OnAddSaveAsync(")] [InlineData("private async Task OnConnectSavedGatewayAsync(")] + [InlineData("private void OnPageUnloaded(")] public void LeavingTheAddForm_StopsThePendingConnectivityProbe(string method) { var source = ReadSource("src", "OpenClaw.Tray.WinUI", "Pages", "ConnectionPage.xaml.cs"); @@ -242,15 +243,21 @@ public void AddDiscoveredGateway_OpensTheFormBeforeFillingInTheUrl() } // The URL box stays editable while saving, so an edit during the await can start a new probe. + // Only a Stop after the save completes, on its success path, catches that probe. [Theory] - [InlineData("private async Task DoDirectConnectFromAddFormAsync(")] - [InlineData("private async Task DoApplySetupCodeFromAddFormAsync(")] - public void SuccessfulAddFormSave_StopsAProbeStartedDuringTheSave(string method) + [InlineData("private async Task DoDirectConnectFromAddFormAsync(", "await _gatewayDirectConnectService.ConnectAsync(", "_userIntent = UserIntent.None;")] + [InlineData("private async Task DoApplySetupCodeFromAddFormAsync(", "await _connectionManager.ApplySetupCodeAsync(code, sshConfig);", "if (result.Outcome == SetupCodeOutcome.Success)")] + public void SuccessfulAddFormSave_StopsAProbeStartedDuringTheSave(string method, string save, string success) { var body = MethodBody("ConnectionPage.xaml.cs", method); - var stop = body.IndexOf("StopConnectivityTest();", StringComparison.Ordinal); - var reload = body.IndexOf("LoadSavedGateways();", StringComparison.Ordinal); - Assert.True(stop >= 0 && reload > stop, $"{method} must stop the probe before reloading the gateway list"); + var saved = body.IndexOf(save, StringComparison.Ordinal); + Assert.True(saved >= 0, $"{method}: save await not found"); + var succeeded = body.IndexOf(success, saved, StringComparison.Ordinal); + Assert.True(succeeded > saved, $"{method}: success path must follow the save await"); + var stop = body.IndexOf("StopConnectivityTest();", saved, StringComparison.Ordinal); + var reload = body.IndexOf("LoadSavedGateways();", saved, StringComparison.Ordinal); + Assert.True(stop > succeeded && reload > stop, + $"{method} must, after the save succeeds, stop the probe and then reload the gateway list"); } private static string MethodBody(string page, string method) diff --git a/tests/OpenClaw.Tray.Tests/AddGatewayConnectivityTestTests.cs b/tests/OpenClaw.Tray.Tests/AddGatewayConnectivityTestTests.cs index a7dcf449c9..231f3c9208 100644 --- a/tests/OpenClaw.Tray.Tests/AddGatewayConnectivityTestTests.cs +++ b/tests/OpenClaw.Tray.Tests/AddGatewayConnectivityTestTests.cs @@ -75,6 +75,24 @@ public async Task HttpClientTimeout_ReportsUnreachable() Assert.Equal(2, harness.Handler.RequestCount); } + // The /health fallback failing must not hide the base URL's own status code. + [Fact] + public async Task BaseErrorStatusThenHealthFailure_ReportsTheBaseStatus() + { + var results = new List<(GatewayProbeOutcome, int?)>(); + var test = new AddGatewayConnectivityTest( + isFormOpen: () => true, + onTesting: () => { }, + onCompleted: (outcome, status) => results.Add((outcome, status)), + createClient: () => new HttpClient(new BaseErrorThenHealthFailureHandler()), + debounce: TimeSpan.Zero); + + Assert.True(test.Schedule(Url)); + await test.Current.WaitAsync(TimeSpan.FromSeconds(10)); + + Assert.Equal([(GatewayProbeOutcome.ErrorStatus, (int?)503)], results); + } + private sealed class Harness { public Harness(TimeSpan? requestTimeout = null) @@ -96,6 +114,8 @@ public Harness(TimeSpan? requestTimeout = null) } // Holds every request until Release. Ignoring cancellation models a slow gateway that answers after Stop. + // The response is pre-buffered so HttpClient's own content read cannot observe the cancelled token; only + // the connection test's final check can keep a stopped test silent. private sealed class BlockingHandler(bool ignoreCancellation) : HttpMessageHandler { private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); @@ -111,7 +131,17 @@ protected override async Task SendAsync(HttpRequestMessage Interlocked.Increment(ref _requestCount); Entered.TrySetResult(); var status = ignoreCancellation ? await _release.Task : await _release.Task.WaitAsync(cancellationToken); - return new HttpResponseMessage(status); + var response = new HttpResponseMessage(status) { Content = new ByteArrayContent([]) }; + await response.Content.LoadIntoBufferAsync(); + return response; } } + + private sealed class BaseErrorThenHealthFailureHandler : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + request.RequestUri!.AbsolutePath == "/health" + ? throw new HttpRequestException("connection reset") + : Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)); + } } From 887d953617f03a1addc0e49f97e512c2db7a0abd Mon Sep 17 00:00:00 2001 From: Scott Hanselman Date: Tue, 1 Dec 2026 22:59:50 -0800 Subject: [PATCH 5/6] fix: dispose the base response before the /health fallback - Record the base error status and dispose the base response before awaiting /health, so a Stop during the fallback leaves nothing undisposed. - Test: base 503, /health held past Stop then 200, reports nothing and disposes the base. - Source guards: Stop clears and collapses the text; Save stop sits in the success branch. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Services/AddGatewayConnectivityTest.cs | 22 +++---- .../AccessibilityThemeResourceSourceTests.cs | 11 ++++ .../AddGatewayConnectivityTestTests.cs | 58 +++++++++++++++++++ 3 files changed, 80 insertions(+), 11 deletions(-) diff --git a/src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs b/src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs index 0f508b7e73..e784edf4f0 100644 --- a/src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs +++ b/src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs @@ -91,26 +91,26 @@ private async Task RunAsync(string rawUrl, CancellationToken ct) using var http = _createClient(); var response = await TryGetAsync(http, httpUrl, ct); + int? baseErrorStatus = null; + if (response != null && !response.IsSuccessStatusCode) + { + // Keep the base status if /health fails, so "Gateway responded with N" still reports it. + baseErrorStatus = (int)response.StatusCode; + response.Dispose(); + response = null; + } if (!ShouldReport(ct)) { response?.Dispose(); return; } - if (response == null || !response.IsSuccessStatusCode) - { - // Keep the base status if /health fails, so "Gateway responded with N" still reports it. - var health = await TryGetAsync(http, $"{httpUrl}/health", ct); - if (health != null) - { - response?.Dispose(); - response = health; - } - } + response ??= await TryGetAsync(http, $"{httpUrl}/health", ct); using (response) { if (!ShouldReport(ct)) return; - if (response == null) _onCompleted(GatewayProbeOutcome.Unreachable, null); + if (response == null && baseErrorStatus != null) _onCompleted(GatewayProbeOutcome.ErrorStatus, baseErrorStatus); + else if (response == null) _onCompleted(GatewayProbeOutcome.Unreachable, null); else if (response.IsSuccessStatusCode) _onCompleted(GatewayProbeOutcome.Reachable, null); else _onCompleted(GatewayProbeOutcome.ErrorStatus, (int)response.StatusCode); } diff --git a/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs b/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs index 7b013b5494..43962b8ed3 100644 --- a/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs +++ b/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs @@ -258,6 +258,17 @@ public void SuccessfulAddFormSave_StopsAProbeStartedDuringTheSave(string method, var reload = body.IndexOf("LoadSavedGateways();", saved, StringComparison.Ordinal); Assert.True(stop > succeeded && reload > stop, $"{method} must, after the save succeeds, stop the probe and then reload the gateway list"); + Assert.DoesNotContain("}", body[succeeded..stop]); + } + + // Stopping must also remove any "Testing connection…" or result text already on screen. + [Fact] + public void StopConnectivityTest_ClearsAndCollapsesTheResultText() + { + var body = MethodBody("ConnectionPage.xaml.cs", "private void StopConnectivityTest("); + Assert.Contains("_connectivityTest?.Stop();", body); + Assert.Contains("AddTestResultText.Text = \"\";", body); + Assert.Contains("AddTestResultText.Visibility = Microsoft.UI.Xaml.Visibility.Collapsed;", body); } private static string MethodBody(string page, string method) diff --git a/tests/OpenClaw.Tray.Tests/AddGatewayConnectivityTestTests.cs b/tests/OpenClaw.Tray.Tests/AddGatewayConnectivityTestTests.cs index 231f3c9208..15b47989df 100644 --- a/tests/OpenClaw.Tray.Tests/AddGatewayConnectivityTestTests.cs +++ b/tests/OpenClaw.Tray.Tests/AddGatewayConnectivityTestTests.cs @@ -93,6 +93,30 @@ public async Task BaseErrorStatusThenHealthFailure_ReportsTheBaseStatus() Assert.Equal([(GatewayProbeOutcome.ErrorStatus, (int?)503)], results); } + // Back or Save can stop the test while the /health fallback is pending after a base 503. + [Fact] + public async Task StoppedDuringHealthFallback_ShowsNothingAndDisposesTheBaseResponse() + { + var results = new List<(GatewayProbeOutcome, int?)>(); + var handler = new BaseErrorThenHeldHealthHandler(); + var test = new AddGatewayConnectivityTest( + isFormOpen: () => true, + onTesting: () => { }, + onCompleted: (outcome, status) => results.Add((outcome, status)), + createClient: () => new HttpClient(handler, disposeHandler: false), + debounce: TimeSpan.Zero); + + Assert.True(test.Schedule(Url)); + await handler.HealthEntered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.True(handler.BaseContent.Disposed); + + test.Stop(); + handler.ReleaseHealth.TrySetResult(); + await test.Current.WaitAsync(TimeSpan.FromSeconds(10)); + + Assert.Empty(results); + } + private sealed class Harness { public Harness(TimeSpan? requestTimeout = null) @@ -144,4 +168,38 @@ protected override Task SendAsync(HttpRequestMessage reques ? throw new HttpRequestException("connection reset") : Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)); } + + // Base returns 503 at once; /health is held until released, ignoring cancellation, then returns 200. + private sealed class BaseErrorThenHeldHealthHandler : HttpMessageHandler + { + public TrackingContent BaseContent { get; } = new(); + public TaskCompletionSource HealthEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource ReleaseHealth { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (request.RequestUri!.AbsolutePath != "/health") + { + await BaseContent.LoadIntoBufferAsync(); + return new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) { Content = BaseContent }; + } + + HealthEntered.TrySetResult(); + await ReleaseHealth.Task; + var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent([]) }; + await response.Content.LoadIntoBufferAsync(); + return response; + } + } + + private sealed class TrackingContent() : ByteArrayContent([]) + { + public bool Disposed { get; private set; } + + protected override void Dispose(bool disposing) + { + Disposed = true; + base.Dispose(disposing); + } + } } From 3447f756e7d98b34d560a7f655e19502d8b3432e Mon Sep 17 00:00:00 2001 From: Scott Hanselman Date: Tue, 1 Dec 2026 23:52:51 -0800 Subject: [PATCH 6/6] fix: do not start a connection test on an unloaded Connection page Unloaded keeps the Add intent, so gate the test on IsLoaded too. Correct the ledger row: the base status is kept only when /health throws. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/ARCHITECTURE.md | 2 +- src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs | 3 ++- .../AccessibilityThemeResourceSourceTests.cs | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b522afddd8..b4f2ebffb9 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1129,7 +1129,7 @@ leading and trailing pipe. Columns, in order: | managed-local-repair | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs and direct reconnect callbacks | repair eligibility, restart budgets, port remediation, and reconnect verification | ManagedLocalGatewayAutoRepairMonitor + ManagedLocalGatewayRepairCoordinator | App composition and dependency callbacks only | explicit disconnect and gateway switches abort repair before restart or reconnect | ManagedLocalGatewayRepairCoordinatorTests.UserDisconnectedIntent_AbortsBeforeProbeOrRestart | behavioral | - | | app-managed-local-repair-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | managed-local repair loops, probing, restart budgeting, and verification implementation | ManagedLocalGatewayAutoRepairMonitor + ManagedLocalGatewayRepairCoordinator | service construction, callback adapters, and lifetime wiring only | App remains the composition root and does not regain repair implementation | AppRefactorContractTests.ManagedLocalGatewayRepair_StaysDelegatedToDedicatedOwners | source-shape | when App no longer constructs the managed-local repair services directly | | connection-page-direct-connect-closed | closed | src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs | direct-connect registry, identity-token, settings, rollback, terminal-wait, and runtime-tunnel transaction | GatewayDirectConnectService | add-form control reads, input validation, result text, and post-success visual refresh only | the page delegates one request; rollback restores the durable registry before identity and settings, reconnects a previously live gateway, and a later credential writer wins | GatewayDirectConnectServiceTests.Connect_Failure_RestoresPreviousLiveConnection | behavioral | when the Connection page no longer contains any direct-connect persistence or rollback logic | -| connection-page-add-connectivity-test-closed | closed | src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs | Add form live connection test debounce, HTTP probe, /health fallback, and stale-result gating | AddGatewayConnectivityTest | result text, live-region announcement, and StopConnectivityTest calls when leaving the Add form or completing a save only | no result is shown or announced after Stop or form close; only caller cancellation is silent; a failed /health fallback keeps the base status | AddGatewayConnectivityTestTests.StoppedWhileInFlight_ShowsNothingAfterTheRequestFinishes | behavioral | when the Add form no longer runs a live connection test | +| connection-page-add-connectivity-test-closed | closed | src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs | Add form live connection test debounce, HTTP probe, /health fallback, and stale-result gating | AddGatewayConnectivityTest | result text, live-region announcement, and StopConnectivityTest calls when leaving the Add form or completing a save only | no result is shown or announced after Stop or form close; only caller cancellation is silent; the base non-2xx status is kept only when /health throws, and a /health response (for example 404) is reported as-is | AddGatewayConnectivityTestTests.StoppedWhileInFlight_ShowsNothingAfterTheRequestFinishes | behavioral | when the Add form no longer runs a live connection test | | connection-status-direct-connect-closed | closed | src/OpenClaw.Tray.WinUI/Windows/ConnectionStatusWindow.xaml.cs | direct-connect registry, settings, rollback, terminal-wait, and runtime-tunnel transaction | GatewayDirectConnectService | diagnostics control reads, input validation, and result text only | diagnostics direct connect delegates one request and cannot report success before a terminal manager state | AppRefactorContractTests.StatusWindowDirectConnect_WaitsForManagerStateBeforeReportingConnected | source-shape | when the status window no longer contains direct-connect persistence or rollback logic | | app-window-manager | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | Settings companion, Workspace, status, setup, canvas request, and runtime-anchor window creation, reuse, focus, theme, owner, and lifetime mechanics | IWindowManager + WindowManager | App owns composition, typed activation-plan application through WindowManager, service-policy callback adapters, setup restart policy, pairing approval dialog workflow and shell, and shutdown-plan callback construction | distinct window types and exact routes are preserved; Settings close resets navigation scope; setup replacement waits for cleanup; shutdown closes owned windows once before provider disposal | WindowManagerTests.CloseForShutdown_GatesCreationAndClosesOwnedWindowsOnce | source-shape | when App is replaced as the WinUI composition root | | app-window-surface-ownership-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | concrete non-tray window fields, constructors, show/hide/focus/theme/close mechanics, and window event lifetime | IWindowManager + WindowManager | interface forwarding, immutable request construction, route and policy callbacks, and setup restart dialog policy only | App cannot regain a parallel Settings, Workspace, status, setup, canvas-request, or runtime-anchor owner, nor revive the retired chat popup | AppSurfaceOwnershipContractTests.App_DelegatesConcreteTrayAndWindowOwnership | source-shape | when App is replaced as the WinUI composition root | diff --git a/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs b/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs index f508efd0e1..0e922edf52 100644 --- a/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs +++ b/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs @@ -2872,7 +2872,8 @@ private void StopConnectivityTest() private void ScheduleConnectivityTest(string? rawUrl) { _connectivityTest ??= new AddGatewayConnectivityTest( - isFormOpen: () => _userIntent == UserIntent.AddingGateway, + // Unloaded keeps _userIntent, so a late LostFocus on the detached page must not start a test. + isFormOpen: () => IsLoaded && _userIntent == UserIntent.AddingGateway, onTesting: ShowConnectivityTesting, onCompleted: ShowConnectivityResult, warn: message => Logger.Warn($"ConnectionPage: {message}")); diff --git a/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs b/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs index 43962b8ed3..aae252296b 100644 --- a/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs +++ b/tests/OpenClaw.Tray.Tests/AccessibilityThemeResourceSourceTests.cs @@ -229,7 +229,8 @@ public void LeavingTheAddForm_StopsThePendingConnectivityProbe(string method) public void ConnectivityTest_IsGatedOnTheAddForm() { var body = MethodBody("ConnectionPage.xaml.cs", "private void ScheduleConnectivityTest("); - Assert.Contains("isFormOpen: () => _userIntent == UserIntent.AddingGateway", body); + // IsLoaded: Unloaded keeps the Add intent, and a late LostFocus must not probe from a detached page. + Assert.Contains("isFormOpen: () => IsLoaded && _userIntent == UserIntent.AddingGateway", body); } // Setting the URL fires TextChanged, which schedules a probe only if the form is already marked open. [Fact]