Skip to content

Commit 3091303

Browse files
bkudiessCopilot
andcommitted
fix: recover managed local gateway connections
Add trusted endpoint provenance, role-aware credential recovery, explicit operator intent, and bounded managed-WSL repair so local gateway failures recover safely without leaking stronger credentials or overriding disconnects. Co-authored-by: Copilot App <[email protected]>
1 parent acf4ab1 commit 3091303

58 files changed

Lines changed: 6135 additions & 135 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/CONNECTION_ARCHITECTURE.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,24 @@ Node credential precedence follows the same invariant with a distinct stored tok
194194

195195
**`InteractiveGatewayCredentialResolver`** resolves credentials for HTTP surfaces (chat URL `?token=` auth). It **prefers SharedGatewayToken** over DeviceToken because HTTP endpoints expect the shared token, not the per-device WebSocket token. Browser proxy diagnostics should treat the missing shared token as a browser-control caveat, not as proof that the operator or node gateway connection is disconnected.
196196

197+
## Self-recovery and automatic local-gateway repair
198+
199+
Two orthogonal self-healing behaviors keep the connection reliable without dead-ending the user:
200+
201+
### Stale device-token self-recovery (operator + node)
202+
203+
The gateway may reject a stored device token with the structured code `AUTH_DEVICE_TOKEN_MISMATCH` (a rotated/revoked/replaced device token) — distinct from a wrong *shared* token. `GatewayErrorClassifier` is the single classifier for this: `ClassifyWithCode(message, ...codes)` inspects the structured `error.code`/`error.details.code` **before** the textual heuristic and returns the exact `GatewayErrorKind.DeviceTokenMismatch`, keeping a stale *device* token (auto-recoverable) separate from a wrong *shared* token (`Auth`, not device-recoverable). Broad `GatewayErrorKind.TokenDrift` remains a manual re-pair signal for UI copy.
204+
205+
On a device-token mismatch, the manager clears **only the rejected role's** device token and reconnects, letting `CredentialResolver` fall back to the same record's `SharedGatewayToken` (preferred) or `BootstrapToken`. This kills the post-setup "need a new token" dead end (setup clears the bootstrap token once pairing is durable, but the shared token remains). Operator recovery runs in `TryScheduleOperatorTokenRecovery`; node recovery is driven off the node client's classified `INodeConnectorTelemetryEvents.ConnectionFailure(GatewayErrorKind)` — the manager's `OnNodeConnectionFailure` queues `HandleNodeDeviceTokenMismatchAsync` off the connector's dispatch lock (capturing lifecycle+node generations at fire time and re-checking `IsCurrentNodeAttempt` before/after the transition semaphore). A per-gateway, per-role attempt guard (reset on handshake success / node pairing) prevents clear→reconnect→mismatch loops.
206+
207+
**Security — trust gate and endpoint provenance.** Clearing a device token downgrades to the more powerful shared/bootstrap credential, so `IsRecoverySafeEndpoint` restricts recovery to trusted endpoints: an owned SSH tunnel, a validated TLS (`wss`/`https`) endpoint, or — for a setup-managed WSL loopback gateway — a listener proven by `ManagedLocalGatewayPortProvenanceService` to be the Windows WSL relay. Loopback is not treated as identity by itself: an unknown listener or a proven obsolete native OpenClaw gateway blocks fallback, so a wrong local process cannot return a device-token mismatch to induce disclosure of the shared credential. A plain `ws://` remote endpoint is never eligible.
208+
209+
### Automatic managed-local WSL gateway repair (tray)
210+
211+
For an app-owned setup-managed local WSL gateway (`WslKeepAlivePolicy.IsSetupManagedLocalRecord` — never SSH/remote/ambiguous-localhost), the tray owns process supervision, keeping it out of the connection layer. `ManagedLocalGatewayAutoRepairMonitor` watches the operator connection and, when it is positively transport-unreachable (`GatewayErrorKind.Network`/`Server`, plus a cold-start `Connecting` state with no failure yet; never unknown/auth/pairing/rate-limit/scope/TLS/tunnel/token-drift) for a sustained window, invokes `ManagedLocalGatewayRepairCoordinator`. A typed `LocalPortConflict` is also repairable because its remediation is provenance-gated rather than a blind process restart. The monitor honors a **startup grace** (so a slow WSL cold start is not interrupted), a per-gateway unhealthy threshold and cooldown, a manager-owned explicit disconnect/stop intent, and a settings **kill switch** (`SettingsData.EnableManagedLocalGatewayAutoRepair`, default on).
212+
213+
`ManagedLocalGatewayRepairCoordinator` **probes before it restarts**: if the gateway is already reachable it just reconnects (the macOS "attach" path); only a genuinely-down gateway triggers a WSL distro restart (via `WslGatewayController`), a keepalive re-arm (`WslGatewayKeepAliveService.TryEnsureAsync`), and a reconnect. For the native-vs-WSL collision case, `ManagedLocalGatewayPortProvenanceService` classifies listeners by address and proves process command line plus scheduled-task/profile lineage. It automatically disables/stops only a fully proven obsolete native OpenClaw gateway; an unknown listener is never killed and produces precise `LocalPortConflict` diagnostics. The shared lifecycle lease serializes that destructive work with manual WSL actions. Reconnect is **gateway-pinned, intent-aware, and cancellable** (`GatewayConnectionManager.ReconnectIfCurrentAsync(gatewayId, ct)`), so gateway switches, explicit Disconnect/Stop, and shutdown always win. Repair is single-flight, verifies success by a real operator connection to the same gateway, is per-gateway restart-budget-bounded, and never reads or logs credentials.
214+
197215
## Client instance lifecycle
198216

199217
**Operator client** (`OpenClawGatewayClient`): Single instance at a time, owned by `GatewayConnectionManager`. Created via `GatewayClientFactory.Create()`. Old instance disposed before creating new one. `OperatorClientChanged` event notifies consumers of swaps.

‎src/OpenClaw.Connection/ConnectionStateMachine.cs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ internal sealed class ConnectionStateMachine
1212
private RoleConnectionState _operatorState = RoleConnectionState.Idle;
1313
private RoleConnectionState _nodeState = RoleConnectionState.Idle;
1414
private string? _operatorError;
15+
private OpenClaw.Shared.GatewayErrorKind? _operatorErrorKind;
1516
private string? _nodeError;
1617
private string? _operatorCredentialSource;
1718
private string? _nodeCredentialSource;
@@ -154,6 +155,7 @@ public void Reset()
154155
_operatorState = RoleConnectionState.Idle;
155156
_nodeState = _nodeEnabled ? RoleConnectionState.Idle : RoleConnectionState.Disabled;
156157
_operatorError = null;
158+
_operatorErrorKind = null;
157159
_nodeError = null;
158160
_operatorCredentialSource = null;
159161
_nodeCredentialSource = null;
@@ -207,6 +209,12 @@ internal void SetOperatorCredentialResolution(GatewayCredentialResolution resolu
207209
RebuildSnapshot();
208210
}
209211

212+
internal void SetOperatorErrorKind(OpenClaw.Shared.GatewayErrorKind? kind)
213+
{
214+
_operatorErrorKind = kind;
215+
RebuildSnapshot();
216+
}
217+
210218
/// <summary>Update node info (device ID, pairing status, optional request ID) in the snapshot.</summary>
211219
internal void SetNodeInfo(
212220
string? deviceId,
@@ -293,6 +301,7 @@ private void ApplyTransition(ConnectionTrigger trigger, string? detail)
293301
case ConnectionTrigger.ConnectRequested:
294302
_operatorState = RoleConnectionState.Connecting;
295303
_operatorError = null;
304+
_operatorErrorKind = null;
296305
break;
297306

298307
case ConnectionTrigger.ConnectRequestSent:
@@ -304,6 +313,7 @@ private void ApplyTransition(ConnectionTrigger trigger, string? detail)
304313
case ConnectionTrigger.HandshakeSucceeded:
305314
_operatorState = RoleConnectionState.Connected;
306315
_operatorError = null;
316+
_operatorErrorKind = null;
307317
break;
308318

309319
case ConnectionTrigger.PairingPending:
@@ -317,16 +327,19 @@ private void ApplyTransition(ConnectionTrigger trigger, string? detail)
317327
case ConnectionTrigger.PairingRejected:
318328
_operatorState = RoleConnectionState.Error;
319329
_operatorError = detail ?? "Pairing rejected";
330+
_operatorErrorKind = OpenClaw.Shared.GatewayErrorKind.PairingRejected;
320331
break;
321332

322333
case ConnectionTrigger.AuthenticationFailed:
323334
_operatorState = RoleConnectionState.Error;
324335
_operatorError = detail ?? "Authentication failed";
336+
_operatorErrorKind ??= OpenClaw.Shared.GatewayErrorClassifier.ClassifyWithCode(_operatorError);
325337
break;
326338

327339
case ConnectionTrigger.RateLimited:
328340
_operatorState = RoleConnectionState.Error;
329341
_operatorError = detail ?? "Rate limited";
342+
_operatorErrorKind = OpenClaw.Shared.GatewayErrorKind.RateLimited;
330343
break;
331344

332345
case ConnectionTrigger.WebSocketDisconnected:
@@ -339,19 +352,22 @@ private void ApplyTransition(ConnectionTrigger trigger, string? detail)
339352
{
340353
_operatorState = RoleConnectionState.Connecting;
341354
_operatorError = null;
355+
_operatorErrorKind = null;
342356
}
343357
break;
344358

345359
case ConnectionTrigger.WebSocketError:
346360
_operatorState = RoleConnectionState.Error;
347361
_operatorError = detail ?? "WebSocket error";
362+
_operatorErrorKind ??= OpenClaw.Shared.GatewayErrorClassifier.Classify(_operatorError);
348363
break;
349364

350365
case ConnectionTrigger.DisconnectRequested:
351366
case ConnectionTrigger.Disposed:
352367
_operatorState = RoleConnectionState.Idle;
353368
_nodeState = _nodeEnabled ? RoleConnectionState.Idle : RoleConnectionState.Disabled;
354369
_operatorError = null;
370+
_operatorErrorKind = null;
355371
_nodeError = null;
356372
_operatorCredentialSource = null;
357373
_nodeCredentialSource = null;
@@ -368,6 +384,7 @@ private void ApplyTransition(ConnectionTrigger trigger, string? detail)
368384
case ConnectionTrigger.ReconnectScheduled:
369385
_operatorState = RoleConnectionState.Connecting;
370386
_operatorError = null;
387+
_operatorErrorKind = null;
371388
break;
372389

373390
case ConnectionTrigger.ReconnectSuppressed:
@@ -377,6 +394,7 @@ private void ApplyTransition(ConnectionTrigger trigger, string? detail)
377394
case ConnectionTrigger.Cancelled:
378395
_operatorState = RoleConnectionState.Idle;
379396
_operatorError = null;
397+
_operatorErrorKind = null;
380398
break;
381399

382400
// ─── Node transitions ───
@@ -424,6 +442,7 @@ private void RebuildSnapshot()
424442
OverallState = GatewayConnectionSnapshot.DeriveOverall(_operatorState, _nodeState, _nodeEnabled),
425443
OperatorState = _operatorState,
426444
OperatorError = _operatorError,
445+
OperatorErrorKind = _operatorErrorKind,
427446
OperatorCredentialSource = _operatorCredentialSource,
428447
OperatorCredentialStatus = _operatorCredentialStatus,
429448
OperatorCredentialFallbackUsed = _operatorCredentialFallbackUsed,

0 commit comments

Comments
 (0)