Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
108 changes: 26 additions & 82 deletions src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ private void OnPageUnloaded(object sender, RoutedEventArgs e)
_reconnectMaskTimer = null;
}
_gatewayHostActionCts?.Cancel();
_connectivityTestCts?.Cancel();
StopConnectivityTest();
if (!_gatewayHostActionInProgress)
{
_gatewayHostActionCts?.Dispose();
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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) =>
Expand Down Expand Up @@ -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);
}

Expand Down
143 changes: 143 additions & 0 deletions src/OpenClaw.Tray.WinUI/Services/AddGatewayConnectivityTest.cs
Original file line number Diff line number Diff line change
@@ -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<bool> _isFormOpen;
private readonly Action _onTesting;
private readonly Action<GatewayProbeOutcome, int?> _onCompleted;
private readonly Action<string>? _warn;
private readonly Func<HttpClient> _createClient;
private readonly TimeSpan _debounce;
private CancellationTokenSource? _cts;

public AddGatewayConnectivityTest(
Func<bool> isFormOpen,
Action onTesting,
Action<GatewayProbeOutcome, int?> onCompleted,
Action<string>? warn = null,
Func<HttpClient>? createClient = null,
TimeSpan? debounce = null)
{
_isFormOpen = isFormOpen;
_onTesting = onTesting;
_onCompleted = onCompleted;
_warn = warn;
_createClient = createClient ?? (() => new HttpClient { Timeout = DefaultRequestTimeout });
_debounce = debounce ?? DefaultDebounce;
}

/// <summary>The in-flight test, for tests that need to await completion.</summary>
public Task Current { get; private set; } = Task.CompletedTask;

/// <summary>Cancels any pending test and starts a new one. Returns false when nothing was scheduled.</summary>
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<HttpResponseMessage?> 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;
}
}
}
Loading
Loading