diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d22af178fc..b4f2ebffb9 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; 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 98482e5b47..0e922edf52 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(); + StopConnectivityTest(); 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,102 +2861,45 @@ 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(); - if (string.IsNullOrWhiteSpace(rawUrl)) - { + _connectivityTest ??= new AddGatewayConnectivityTest( + // 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}")); + 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() { - 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"); + } - try - { - 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; - - 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. - 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"]; - 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) => @@ -3366,12 +3310,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/src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs b/src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs new file mode 100644 index 0000000000..e784edf4f0 --- /dev/null +++ b/src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs @@ -0,0 +1,143 @@ +// 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) + { + Stop(); + if (!_isFormOpen() || string.IsNullOrWhiteSpace(rawUrl)) return false; + _cts = new CancellationTokenSource(); + Current = RunAsync(rawUrl, _cts.Token); + return true; + } + + // 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(); + + // 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); + 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; + } + response ??= await TryGetAsync(http, $"{httpUrl}/health", ct); + + using (response) + { + if (!ShouldReport(ct)) return; + 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); + } + } + // 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 af2941b870..aae252296b 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,8 @@ public void GatewayHostActions_AnnounceFinalResultsOnly() [Theory] [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"); @@ -222,27 +224,52 @@ public void LeavingTheAddForm_StopsThePendingConnectivityProbe(string method) Assert.Contains("StopConnectivityTest();", source[start..end]); } + // The behavioral gate lives in AddGatewayConnectivityTest; the page must feed it the Add-form state. + [Fact] + public void ConnectivityTest_IsGatedOnTheAddForm() + { + var body = MethodBody("ConnectionPage.xaml.cs", "private void ScheduleConnectivityTest("); + // 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] + 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."); + } + // 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"); + Assert.DoesNotContain("}", body[succeeded..stop]); } - // An HttpClient timeout throws TaskCanceledException without cancelling ct; it must reach an announced result. + // Stopping must also remove any "Testing connection…" or result text already on screen. [Fact] - public void ConnectivityProbe_TreatsOnlyCallerCancellationAsSilent() + public void StopConnectivityTest_ClearsAndCollapsesTheResultText() { - 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); + 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 new file mode 100644 index 0000000000..15b47989df --- /dev/null +++ b/tests/OpenClaw.Tray.Tests/AddGatewayConnectivityTestTests.cs @@ -0,0 +1,205 @@ +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); + } + + // 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); + } + + // 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) + { + 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. + // 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); + 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); + 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)); + } + + // 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); + } + } +} 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 @@ +