Skip to content

fix: setup flow, connection page, and chat token bugs - #305

Merged
shanselman merged 2 commits into
openclaw:masterfrom
ranjeshj:fix/setup-connection-bugs
May 11, 2026
Merged

shanselman merged 2 commits into
openclaw:masterfrom
ranjeshj:fix/setup-connection-bugs

Conversation

@ranjeshj

Copy link
Copy Markdown
Contributor

Summary

Fixes 12 bugs across setup flow, connection page, connection manager, and chat token resolution.

Wizard RadioButtons (user-reported)

  • RadioButtons selection not sticking — \ConfigureRadioButtons\ always reassigned \ItemsSource\ on every re-render (even when items were identical), causing WinUI to reset the visual selection. Now skips \ItemsSource\ when items are content-equal.

ConnectionPage — Direct Connect

  • SSH validation — empty user/host and invalid ports now rejected upfront before any state mutation
  • Registry revert on failure — if connect fails, active gateway reverts to previous instead of leaving a broken config active
  • Silent catches logged — identity file read/write errors now logged via \Debug.WriteLine\
  • StateChanged leak — page now unsubscribes from \StateChanged\ on \Unloaded\

GatewayConnectionManager

  • ReconnectAsync race condition — extracted \ConnectCoreAsync/\DisconnectCore\ so \ReconnectAsync\ and \SwitchGatewayAsync\ hold the semaphore atomically across disconnect+connect
  • Deadlock risk — \DisposeActiveClient\ now uses \Task.Run\ to avoid sync context deadlocks
  • Dispose timeout — tunnel stop in \Dispose()\ uses \Task.Run().Wait(3s)\ instead of unbounded \GetResult()\

Setup Flow

  • Cancelled state persisted — cancellation now saves \Cancelled\ status before rethrowing, preventing stale \Running\ phase on restart
  • Permanent failures classified — \UnauthorizedAccessException, \InvalidOperationException, etc. marked non-retryable
  • Corrupt state file — \LoadAsync\ catches \JsonException, deletes corrupt file, starts fresh

Chat Token

  • Wrong token for HTTP auth — \InteractiveGatewayCredentialResolver\ now prefers \SharedGatewayToken\ for chat/dashboard HTTP surfaces instead of \DeviceToken\ (which is for WebSocket auth)

Testing

  • All 2353 tests pass (1443 shared + 910 tray)
  • Manual testing: direct connect, chat, wizard radio buttons

- Fix wizard RadioButtons selection not sticking (FunctionalUI)
- Validate SSH config before direct connect; revert registry on failure
- Log identity file errors instead of silent catch blocks
- Unsubscribe ConnectionPage from StateChanged on Unloaded
- Fix ReconnectAsync/SwitchGatewayAsync race condition (atomic semaphore)
- Fix sync-over-async deadlock risk in DisposeActiveClient
- Add timeout to tunnel stop in Dispose
- Persist Cancelled status on setup cancellation
- Classify permanent setup failures as non-retryable
- Handle corrupt setup-state.json gracefully
- Fix chat using DeviceToken instead of SharedGatewayToken for HTTP auth

Co-authored-by: Copilot <[email protected]>
@ranjeshj
ranjeshj force-pushed the fix/setup-connection-bugs branch from 199f59a to eed21c3 Compare May 11, 2026 01:33
@shanselman

Copy link
Copy Markdown
Collaborator

Thanks for the broad setup/connection cleanup here. I did a deep adversarial review of #305 against the claimed fixes. Overall this looks like a strong bug-fix PR and CI is green, but I think a small follow-up pass would make it safer before merge.

Summary

The good parts look valid:

  • The FunctionalUI RadioButtons fix is the right shape: avoiding ItemsSource reassignment when the item content is unchanged should prevent WinUI from rebuilding the control and dropping visual selection.
  • SSH config validation now happens before mutating registry/settings, which avoids saving obviously invalid user/host/port values.
  • The GatewayConnectionManager ConnectCoreAsync / DisconnectCore extraction makes reconnect/switch operations more atomic and reduces interleaving races.
  • Setup cancellation/corrupt-state handling is a good resilience improvement.
  • Prefering SharedGatewayToken for interactive HTTP chat/dashboard surfaces appears aligned with the current auth model, while WebSocket connection auth still uses the normal credential resolver.

Please address before merge

1. Direct Connect rollback/success semantics are only partially fixed

ConnectionPage.OnDirectConnect now saves previousActiveId and restores it in catch, but most real connection failures do not appear to throw from await _connectionManager.ConnectAsync(recordId).

In GatewayConnectionManager.ConnectCoreAsync, the actual client connection is started fire-and-forget:

_ = Task.Run(async () =>
{
    try
    {
        await lifecycle.ConnectAsync(ct);
    }
    catch (OperationCanceledException) { }
    catch (Exception ex)
    {
        _logger.Error($"[ConnMgr] Connect failed: {ex.Message}");
    }
}, ct);

That means bad token, unreachable gateway, handshake/auth failure, etc. will generally flow through connection manager state/events later, not through the OnDirectConnect catch. As written, OnDirectConnect can set:

DirectConnectResultText.Text = $"✓ Connected to {GatewayUrlHelper.SanitizeForDisplay(url)}";

immediately after starting the attempt, not after a successful connection.

The rollback is also incomplete when the catch does run:

  • It restores only ActiveGatewayId.
  • It leaves the newly added/updated failed GatewayRecord in the registry.
  • It leaves legacy Settings values (GatewayUrl, SSH settings) pointing at the failed attempt.
  • If there was no previous active gateway, it does not clear the newly active bad one.

Suggested fix plan:

  1. Snapshot the previous active gateway ID and the legacy settings fields that this method mutates.
  2. Track whether the direct-connect attempt created a new gateway record or updated an existing one.
  3. Do not display Connected until the connection manager reports a successful connected/ready state for the attempted recordId.
  4. If the attempt fails, times out, or reports auth/pairing/error state, restore the previous active gateway and previous settings.
  5. If the failed attempt created a new gateway record, remove it; if it updated an existing record, restore the previous record values.
  6. If there was no previous active gateway, clear the active gateway rather than leaving the failed record active.

This is the main correctness issue I would fix before merging because it can leave users thinking Direct Connect succeeded while the async connection is still failing.

2. Rename the updated credential resolver test

The test TryResolve_PrefersPerGatewayDeviceToken now asserts the opposite behavior: it sets an identity reader token but expects shared-token and source record.SharedGatewayToken.

Suggested fix:

Rename it to something like:

TryResolve_PrefersSharedGatewayTokenOverDeviceTokenForInteractiveHttpSurfaces

That will prevent future agents/maintainers from “fixing” the test back to the old behavior based on the misleading name.

3. Use the existing source constant for shared-token resolution

InteractiveGatewayCredentialResolver currently hardcodes:

"record.SharedGatewayToken"

Please use the existing constant instead:

CredentialResolver.SourceSharedGatewayToken

This keeps production behavior and tests tied to the same source label.

Worth considering while you are in GatewayConnectionManager

4. Avoid holding _transitionSemaphore across a potentially hung tunnel stop

SwitchGatewayAsync now awaits _tunnelManager.StopAsync() while holding _transitionSemaphore:

await _transitionSemaphore.WaitAsync();
try
{
    DisconnectCore();
    if (_tunnelManager?.IsActive == true)
    {
        try { await _tunnelManager.StopAsync(); }
        catch (Exception ex) { ... }
    }
    _registry.SetActive(gatewayId);
    await ConnectCoreAsync(gatewayId);
}
finally
{
    _transitionSemaphore.Release();
}

If tunnel shutdown hangs, all connection transitions are blocked behind the semaphore. Consider using a bounded timeout/background stop here, similar to the new dispose timeout, or otherwise ensure StopAsync() cannot block indefinitely.

5. Dispose() can race with in-flight semaphore users

This may be pre-existing, but the PR holds _transitionSemaphore for longer during reconnect/switch, so the window is wider. Dispose() disposes _transitionSemaphore without acquiring it. If a reconnect/switch is in progress, the in-flight method can hit ObjectDisposedException in its finally release path.

Suggested options:

  • Have Dispose() acquire the semaphore with a short timeout before disposing it.
  • Or make release/dispose robust to ObjectDisposedException during shutdown.

Suggested validation after fixes

After the follow-up changes, please run the repository-required validation:

.\build.ps1
dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj --no-restore
dotnet test .\tests\OpenClaw.Tray.Tests\OpenClaw.Tray.Tests.csproj --no-restore

Thanks again — this PR is doing useful cleanup. The main thing I’d like tightened is the Direct Connect flow so success/rollback matches the async connection manager reality.

…tants, timeouts

- Direct connect now polls connection state before reporting success
- Full rollback on failure: removes new records, restores existing ones, reverts settings
- Pairing-required state handled without rollback
- Renamed test to TryResolve_PrefersSharedGatewayTokenOverDeviceTokenForHttpSurfaces
- Use CredentialResolver.SourceSharedGatewayToken constant instead of hardcoded string
- SwitchGatewayAsync tunnel stop bounded to 5s timeout
- Dispose acquires semaphore briefly before disposal to avoid race with in-flight operations

Co-authored-by: Copilot <[email protected]>
@shanselman
shanselman merged commit ef0240f into openclaw:master May 11, 2026
8 checks passed
@ranjeshj
ranjeshj deleted the fix/setup-connection-bugs branch May 12, 2026 00:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants