Skip to content

Commit bc210e0

Browse files
bkudiessCopilotshanselman
authored
fix: local gateway connections recover after listener or token drift (#1053)
* 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]> * fix: verify WSL relay ownership during setup Preserve WSL shell variables through stdin, isolate the Windows PowerShell module path for Authenticode verification, and account for relay family translation. Update the keepalive E2E contract to recognize an already-proven setup keepalive without spawning a duplicate. Co-authored-by: Copilot App <[email protected]> * fix: constrain managed gateway ownership migration Adopt setup-managed ownership only when setup state proves the same loopback endpoint, preserve manual and SSH-backed records, deduplicate external provenance probes, and record the repair ownership boundary in the architecture ledger. Co-authored-by: Copilot App <[email protected]> * fix: drop managed ownership when endpoint changes Preserve setup-managed metadata only for component-equivalent endpoints, strip stale explicit and legacy ownership on repoint, and cover standard versus nonstandard loopback aliases plus case-sensitive path and query changes. Co-authored-by: Copilot App <[email protected]> * docs: define default-on local gateway recovery Document the macOS-parity supervision contract, persist the default for fresh setup, verify existing settings inherit it, and preserve an explicitly disabled kill switch across setup reruns. Co-authored-by: Copilot App <[email protected]> --------- Co-authored-by: Copilot App <[email protected]> Co-authored-by: Scott Hanselman <[email protected]> Copilot-Session: f5f0e4a6-88fa-4782-9a60-5648648fda3e
1 parent 93ecfe5 commit bc210e0

64 files changed

Lines changed: 6618 additions & 138 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/ARCHITECTURE.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ These are the canonical homes. Do not reintroduce private copies elsewhere.
5959
| Presentation-layer DI composition root | `AppServiceRegistration` (root `ServiceProvider`, owned by `App`) | authoritative |
6060
| Settings snapshot read + batched save + non-echoing change notification | `ISettingsStore` | authoritative |
6161
| Settings page load/persist view logic | `SettingsPageViewModel` | authoritative |
62+
| Managed-local listener provenance and strong-credential authorization | `ManagedLocalGatewayPortProvenanceService` | authoritative |
63+
| Managed-local automatic repair eligibility and orchestration | `ManagedLocalGatewayAutoRepairMonitor` + `ManagedLocalGatewayRepairCoordinator` | authoritative |
6264
| Capability UI metadata | `NodeCapabilityUiCatalog` (planned) | planned |
6365
| Capability registration/gating | `NodeCapabilityRegistrationPolicy` (planned) | planned |
6466
| Local MCP exposure policy | `McpCapabilityPolicy` (planned) | planned |
@@ -117,6 +119,9 @@ leading and trailing pipe. Columns, in order:
117119
| wsl-posix-quoting | authoritative | OpenClaw.SetupEngine/SetupSteps.cs | ad hoc ShellEscape with divergent wrap semantics | WslShellQuoting | - | WSL command lines use POSIX single-quote quoting via WslShellQuoting not cmd/PowerShell quoting | WslShellQuotingTests.QuotePosixSingleQuote_WrapsAndEscapesEmbeddedQuote | behavioral | when no code builds WSL command lines outside WslShellQuoting |
118120
| setup-shellescape-closed | closed | src/OpenClaw.SetupEngine/SetupSteps.cs | private ShellEscape helpers with divergent wrap semantics | WslShellQuoting | - | SetupSteps builds WSL command lines only via WslShellQuoting; no local ShellEscape helper | SetupStepsShellEscapeClosureTests.SetupSteps_DoesNotReintroduce_PrivateShellEscape | source-shape | when SetupSteps.cs no longer builds any WSL command strings |
119121
| wsl-distro-install-path | authoritative | OpenClaw.SetupEngine/SetupSteps.cs | inline Path.Combine wsl distro install-path derivation | DistroInstallPathPolicy | - | new installs use the strict supported name grammar; teardown accepts only unambiguous single-segment names whose canonical path is an immediate child of LocalDataDir\wsl with no aliases, case or Unicode collisions, or reparse points at the root or child | SetupStepsTests.DistroInstallPathPolicy_ResolvesImmediateChild | behavioral | - |
122+
| managed-local-provenance | authoritative | scattered connection, setup, browser, and reconnect call sites | implicit loopback trust and duplicated strong-credential listener checks | ManagedLocalGatewayPortProvenanceService | callers request inspection, authorization, or conflict repair only | unknown or changed listener owners never receive strong credentials or destructive remediation | ManagedLocalGatewayPortProvenanceServiceTests.InteractiveCredentialGate_ExpectedCacheThenOwnerChanges_FailsClosed | behavioral | - |
123+
| 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 | - |
124+
| 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 |
120125
| app-window-manager | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | window creation/show/hide/shutdown | IWindowManager | composition/delegation only | startup/shutdown ordering deterministic; disposed once | none | review-only | extracted in Phase 3 |
121126
| app-tray-controller | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | tray icon/menu/action routing | ITrayController | composition/delegation only | tray actions route unchanged | none | review-only | extracted in Phase 3 |
122127
| app-activation-router | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | deep-link/toast/single-instance activation | IActivationRouter | composition/delegation only | activation routes land on the same UI/actions; current-user pipe security preserved | none | review-only | extracted in Phase 3 |

‎docs/CONNECTION_ARCHITECTURE.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,26 @@ 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+
**Default-on product contract and macOS parity.** App-installed local gateways are supervised by default for both fresh setups and upgrades, matching the macOS local-mode contract where launchd supervision is active unless OpenClaw is paused. Fresh Windows setup writes `EnableManagedLocalGatewayAutoRepair=true` explicitly; an existing settings file that predates the field deserializes to the same default. This enrollment is restricted to records whose setup-managed ownership is positively linked to the installed endpoint. Manual localhost, repointed, SSH, and remote records are never adopted. The user-facing controls are **Disconnect** and **Stop** on the Connection page: either records explicit operator intent and suppresses automatic restart, process remediation, and reconnect until the operator explicitly connects/starts again. An explicitly persisted `false` remains available as a policy/debug kill switch and is never overwritten by setup merge.
214+
215+
`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.
216+
197217
## Client instance lifecycle
198218

199219
**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)