Skip to content
Open
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
289 changes: 273 additions & 16 deletions src/OpenClaw.Connection/GatewayConnectionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ public sealed class GatewayConnectionManager :
internal const string AttemptsMetricName = "openclaw.connection.attempts";
internal const string AttemptDurationMetricName = "openclaw.connection.attempt.duration";
internal const string StateTransitionsMetricName = "openclaw.connection.state.transitions";
internal const string SharedTokenHandshakeTimeoutEnvironmentVariable =
"OPENCLAW_SHARED_TOKEN_HANDSHAKE_TIMEOUT_MS";
private const int DefaultSharedTokenHandshakeTimeoutMilliseconds = 15_000;
private static readonly TimeSpan SharedTokenHandshakePollInterval = TimeSpan.FromMilliseconds(25);

private const string RoleTag = "openclaw.connection.role";
private const string OperationTag = "openclaw.connection.operation";
Expand Down Expand Up @@ -1781,7 +1785,9 @@ public async Task<SetupCodeResult> ConnectWithSharedTokenAsync(
string gatewayUrl,
string token,
SshTunnelConfig? sshTunnel,
Func<GatewayRecord, CancellationToken, Task>? onGatewayCommitted)
Func<GatewayRecord, CancellationToken, Task>? onGatewayCommitted,
Func<CancellationToken, Task>? onAttemptStarted = null,
Func<CancellationToken, Task>? onNoActiveGateway = null)
{
ThrowIfDisposed();

Expand All @@ -1796,8 +1802,12 @@ public async Task<SetupCodeResult> ConnectWithSharedTokenAsync(
{
using var lifecycleLease = await BeginManualGatewayLifecycleOperationAsync();
await _transitionSemaphore.WaitAsync();
var transitionLockHeld = true;
try
{
if (onAttemptStarted is not null)
await onAttemptStarted(CancellationToken.None).ConfigureAwait(false);

var existing = _registry.FindByUrl(gatewayUrl);
var recordId = existing?.Id ?? Guid.NewGuid().ToString();
var identityDir = _registry.GetIdentityDirectory(recordId);
Expand Down Expand Up @@ -1922,9 +1932,20 @@ await onGatewayCommitted(record, CancellationToken.None)
_registry.SetActive(recordId);
gatewayCommitted = true;
rollbackError =
$" Registry rollback failed; the new gateway remains active: {rollbackException.Message}";
$" The new gateway is still active. Open Connection settings and reconnect a valid gateway. {rollbackException.Message}";
}
}

if (rollbackError is null && registryPersisted && _registry.GetActive() is null)
{
rollbackError = await RestoreEmptyGatewaySettingsAsync(
record,
recordId,
onNoActiveGateway).ConfigureAwait(false);
if (rollbackError is not null)
gatewayCommitted = true;
}

_logger.Warn($"[ConnMgr] Failed to persist shared-token gateway update: {ex.Message}");
return new SetupCodeResult(
SetupCodeOutcome.ConnectionFailed,
Expand All @@ -1942,30 +1963,93 @@ await onGatewayCommitted(record, CancellationToken.None)
SetGatewayConnectionIntent(recordId, shouldBeConnected: true);

// Disconnect current gateway only after replacement credentials have been validated and persisted.
await DisconnectCoreAsync();
var restoreLiveGatewayId = OperatorClient is not null ? previousActiveId : null;
try
{
await DisconnectCoreAsync();

// The replacement shared token was validated above. Preserve durable device tokens;
// they remain the preferred credential until a successful re-pair replaces them.
if (!Directory.Exists(identityDir))
Directory.CreateDirectory(identityDir);

// A failed attempt is not admission. AuthenticationFailed is raised after
// ConnectCoreAsync returns, and that handler cannot record the failure while
// this method still holds the transition lock.
await ConnectCoreAsync(recordId);
var handshakeFailed = _stateMachine.Current.OperatorState == RoleConnectionState.Error;
if (!handshakeFailed &&
_stateMachine.Current.OperatorState == RoleConnectionState.Connecting &&
ReadSharedTokenHandshakeTimeout() > TimeSpan.Zero)
{
var generation = Interlocked.Read(ref _generation);
_transitionSemaphore.Release();
transitionLockHeld = false;
try
{
await WaitForSharedTokenHandshakeAsync(generation).ConfigureAwait(false);
}
finally
{
await _transitionSemaphore.WaitAsync().ConfigureAwait(false);
transitionLockHeld = true;
}

// The replacement shared token was validated above. Preserve durable device tokens;
// they remain the preferred credential until a successful re-pair replaces them.
if (!Directory.Exists(identityDir))
Directory.CreateDirectory(identityDir);
if (Interlocked.Read(ref _generation) != generation)
{
return new SetupCodeResult(
SetupCodeOutcome.ConnectionFailed,
"A newer gateway connection replaced this shared-token attempt.",
GatewayUrl: gatewayUrl,
GatewayCommitted: string.Equals(
_registry.ActiveGatewayId,
recordId,
StringComparison.Ordinal));
}

// Connect to the gateway
await ConnectCoreAsync(recordId);
if (_stateMachine.Current.OperatorState == RoleConnectionState.Error)
// A device-token write can fail after the gateway has already accepted
// the shared token. That is not a rejected token, and disconnecting
// here abandons the replacement pairing.
handshakeFailed = _stateMachine.Current.OperatorState == RoleConnectionState.Error
&& !IsIdentityPersistenceFailure(_stateMachine.Current.OperatorError);
}

if (handshakeFailed)
{
var failure = _stateMachine.Current.OperatorError ?? "Gateway connection failed.";
return await RollbackRejectedSharedTokenAsync(
record,
recordId,
previousRecord,
previousActiveId,
restoreLiveGatewayId,
onGatewayCommitted,
onNoActiveGateway,
failure,
gatewayCommitted).ConfigureAwait(false);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
return new SetupCodeResult(
SetupCodeOutcome.ConnectionFailed,
_stateMachine.Current.OperatorError ?? "Gateway connection failed.",
GatewayUrl: gatewayUrl,
GatewayCommitted: true);
return await RollbackRejectedSharedTokenAsync(
record,
recordId,
previousRecord,
previousActiveId,
restoreLiveGatewayId,
onGatewayCommitted,
onNoActiveGateway,
ex.Message,
gatewayCommitted).ConfigureAwait(false);
}
}
finally
{
if (isolatedValidationTunnel is not null)
await StopAndDisposeValidationTunnelAsync(isolatedValidationTunnel).ConfigureAwait(false);

_transitionSemaphore.Release();
if (transitionLockHeld)
_transitionSemaphore.Release();
}
return new SetupCodeResult(
SetupCodeOutcome.Success,
Expand Down Expand Up @@ -1997,6 +2081,179 @@ await onGatewayCommitted(record, CancellationToken.None)
}
}

private static bool IsIdentityPersistenceFailure(string? operatorError) =>
string.Equals(
operatorError,
DeviceIdentityLoadException.RecoveryMessage,
StringComparison.Ordinal);

private static TimeSpan ReadSharedTokenHandshakeTimeout()
{
var raw = Environment.GetEnvironmentVariable(SharedTokenHandshakeTimeoutEnvironmentVariable);
if (int.TryParse(raw, out var milliseconds) && milliseconds >= 0)
return TimeSpan.FromMilliseconds(milliseconds);

return TimeSpan.FromMilliseconds(DefaultSharedTokenHandshakeTimeoutMilliseconds);
}

/// <summary>
/// Waits until the shared-token attempt leaves Connecting, the generation changes,
/// or the handshake budget ends. Caller must not hold <see cref="_transitionSemaphore"/>.
/// </summary>
private async Task WaitForSharedTokenHandshakeAsync(long generation)
{
var timeout = ReadSharedTokenHandshakeTimeout();
var stopwatch = Stopwatch.StartNew();
while (stopwatch.Elapsed < timeout &&
Interlocked.Read(ref _generation) == generation &&
_stateMachine.Current.OperatorState == RoleConnectionState.Connecting)
{
await Task.Delay(SharedTokenHandshakePollInterval).ConfigureAwait(false);
}
}

/// <summary>
/// Puts the rejected shared token back to the previous registry record and settings.
/// Drops the rejected operator client. Reconnects the previous gateway when it was live.
/// A rollback that cannot finish leaves the candidate committed.
/// </summary>
private async Task<SetupCodeResult> RollbackRejectedSharedTokenAsync(
GatewayRecord candidate,
string candidateId,
GatewayRecord? previousRecord,
string? previousActiveId,
string? restoreLiveGatewayId,
Func<GatewayRecord, CancellationToken, Task>? onGatewayCommitted,
Func<CancellationToken, Task>? onNoActiveGateway,
string failure,
bool gatewayCommitted)
{
var rollbackError = await RestoreSharedTokenCandidateAsync(
candidate,
candidateId,
previousRecord,
previousActiveId,
onGatewayCommitted,
onNoActiveGateway).ConfigureAwait(false);
if (rollbackError is null)
{
gatewayCommitted = false;
try
{
await DisconnectCoreAsync().ConfigureAwait(false);
if (restoreLiveGatewayId is not null)
await ConnectCoreAsync(restoreLiveGatewayId).ConfigureAwait(false);
}
catch (Exception ex)
{
rollbackError = $" The previous gateway connection was not restored. Open Connection settings and reconnect a valid gateway. {ex.Message}";
}
}

return new SetupCodeResult(
SetupCodeOutcome.ConnectionFailed,
failure + rollbackError,
GatewayUrl: candidate.Url,
GatewayCommitted: gatewayCommitted);
}

/// <summary>
/// Puts the registry back to the gateway that was active before a rejected shared token
/// was saved, then asks the settings callback to follow that restored record.
/// Returns an error suffix when the candidate has to stay because rollback could not finish.
/// </summary>
private async Task<string?> RestoreSharedTokenCandidateAsync(
GatewayRecord candidate,
string candidateId,
GatewayRecord? previousRecord,
string? previousActiveId,
Func<GatewayRecord, CancellationToken, Task>? onGatewayCommitted,
Func<CancellationToken, Task>? onNoActiveGateway)
{
if (previousRecord is null)
_registry.Remove(candidateId);
else
_registry.AddOrUpdate(previousRecord);
_registry.SetActive(previousActiveId);
try
{
_registry.Save();
}
catch (Exception rollbackException)
{
_registry.AddOrUpdate(candidate);
_registry.SetActive(candidateId);
try { _registry.Save(); }
catch (Exception persistException)
{
_logger.Warn($"[ConnMgr] Failed to keep the rejected shared-token gateway after rollback save failed: {persistException.Message}");
}

return $" The new gateway is still active. Open Connection settings and reconnect a valid gateway. {rollbackException.Message}";
}

if (_registry.GetActive() is { } restored)
{
if (onGatewayCommitted is null)
return null;

try
{
await onGatewayCommitted(restored, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception settingsException)
{
_registry.AddOrUpdate(candidate);
_registry.SetActive(candidateId);
try { _registry.Save(); }
catch (Exception persistException)
{
_logger.Warn($"[ConnMgr] Failed to keep the rejected shared-token gateway after settings rollback failed: {persistException.Message}");
}

return $" The new gateway is still active. Open Connection settings and reconnect a valid gateway. {settingsException.Message}";
}

return null;
}

return await RestoreEmptyGatewaySettingsAsync(
candidate,
candidateId,
onNoActiveGateway).ConfigureAwait(false);
}

/// <summary>
/// Restores connection settings when a rejected shared token leaves no active gateway.
/// A restore that cannot finish puts the candidate back and reports that it is still active.
/// </summary>
private async Task<string?> RestoreEmptyGatewaySettingsAsync(
GatewayRecord candidate,
string candidateId,
Func<CancellationToken, Task>? onNoActiveGateway)
{
if (onNoActiveGateway is null)
return null;

try
{
await onNoActiveGateway(CancellationToken.None).ConfigureAwait(false);
return null;
}
catch (Exception settingsException)
{
_registry.AddOrUpdate(candidate);
_registry.SetActive(candidateId);
try { _registry.Save(); }
catch (Exception persistException)
{
_logger.Warn($"[ConnMgr] Failed to keep the rejected shared-token gateway after settings rollback failed: {persistException.Message}");
}

return $" The new gateway is still active. Open Connection settings and reconnect a valid gateway. {settingsException.Message}";
}
}

private async Task<SetupCodeResult> ValidateSharedTokenBeforeReplacementAsync(
string gatewayUrl,
string token,
Expand Down
12 changes: 12 additions & 0 deletions src/OpenClaw.Tray.WinUI/App.CapabilityHandlers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,7 @@ private void WireAppCapabilityHandlers()
if (_gatewayDirectConnectService is null)
return new { outcome = "ConnectionFailed", error = "Gateway settings service is not initialized", connected = false };

GatewayDirectConnectService.ConnectionSettingsSnapshot? beforeSettings = null;
var result = await _connectionManager.ConnectWithSharedTokenAsync(
gatewayUrl,
token,
Expand All @@ -336,6 +337,17 @@ private void WireAppCapabilityHandlers()
{
_gatewayDirectConnectService.SynchronizeSettingsWithCommittedGateway(record);
return Task.CompletedTask;
},
onAttemptStarted: _ =>
{
beforeSettings = _gatewayDirectConnectService.CaptureConnectionSettings();
return Task.CompletedTask;
},
onNoActiveGateway: _ =>
{
if (beforeSettings is { } snapshot)
_gatewayDirectConnectService.RestoreConnectionSettings(snapshot);
return Task.CompletedTask;
});
return new
{
Expand Down
11 changes: 10 additions & 1 deletion src/OpenClaw.Tray.WinUI/Services/GatewayDirectConnectService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,15 @@ public GatewayValidationIdentity CreateValidationIdentity(GatewayDirectConnectRe
return matches.FirstOrDefault(record => IsSameSshCredentialEndpoint(record.SshTunnel, request.SshTunnel))
?? matches.FirstOrDefault();
}
internal ConnectionSettingsSnapshot CaptureConnectionSettings() =>
ConnectionSettingsSnapshot.Capture(_settings);

internal void RestoreConnectionSettings(ConnectionSettingsSnapshot snapshot)
{
snapshot.Restore(_settings);
_reconcileRuntimeTunnel();
}

public void SynchronizeSettingsWithCommittedGateway(GatewayRecord committedGateway)
{
var active = _registry.GetActive()
Expand Down Expand Up @@ -726,7 +735,7 @@ private static GatewayDirectConnectResult Failed(
error,
rollbackIncomplete);

private sealed record ConnectionSettingsSnapshot(
internal sealed record ConnectionSettingsSnapshot(
string GatewayUrl,
bool UseSshTunnel,
string SshUser,
Expand Down
Loading
Loading