Skip to content

Commit 01faa64

Browse files
shanselmanCopilot
andauthored
Harden managed Gateway release setup and restart recovery (#1120)
* fix: prove relayless managed gateway ownership Co-authored-by: Copilot App <[email protected]> * fix: close relayless provenance races Co-authored-by: Copilot App <[email protected]> * test(e2e): lease mirrored-WSL-safe gateway ports Co-authored-by: Copilot App <[email protected]> Copilot-Session: 184fa070-4567-45dc-ac2d-c81c2840af14 * test(e2e): prove selected gateway port Co-authored-by: Copilot App <[email protected]> Copilot-Session: 184fa070-4567-45dc-ac2d-c81c2840af14 * test(e2e): bound Windows port inspection Co-authored-by: Copilot App <[email protected]> Copilot-Session: 184fa070-4567-45dc-ac2d-c81c2840af14 * test(e2e): harden WSL port proof Co-authored-by: Copilot App <[email protected]> Copilot-Session: 184fa070-4567-45dc-ac2d-c81c2840af14 * test(e2e): parse localized port exclusions Co-authored-by: Copilot App <[email protected]> Copilot-Session: 184fa070-4567-45dc-ac2d-c81c2840af14 * test(e2e): tolerate unrelated port exclusions Co-authored-by: Copilot App <[email protected]> * Fix gateway reload mode default Co-authored-by: Copilot App <[email protected]> * fix(setup): recover gateway 2026.7.1 restart Co-authored-by: Copilot App <[email protected]> Copilot-Session: 15b5584f-677b-453f-8aa4-4f33fe60bc50 * test(shared): cover gateway 1012 close frame Co-authored-by: Copilot App <[email protected]> Copilot-Session: 15b5584f-677b-453f-8aa4-4f33fe60bc50 * test(shared): target managed 1012 loopback Co-authored-by: Copilot App <[email protected]> Copilot-Session: 15b5584f-677b-453f-8aa4-4f33fe60bc50 * test(shared): verify restart clears handshake Co-authored-by: Copilot App <[email protected]> Copilot-Session: 15b5584f-677b-453f-8aa4-4f33fe60bc50 * test(shared): place restart handshake setup Co-authored-by: Copilot App <[email protected]> Copilot-Session: 15b5584f-677b-453f-8aa4-4f33fe60bc50 * fix(setup): harden gateway restart recovery Classify the Gateway 2026.7.1 terminal restart from stable model-check context, and bound managed-local NoListener retries without weakening endpoint ownership checks. Co-authored-by: Copilot App <[email protected]> * fix(setup): bound gateway startup races Keep retryable startup close 1013 and typed listener snapshot changes inside the existing managed-local restart window while preserving immediate failure for every other unknown owner. Co-authored-by: Copilot App <[email protected]> * fix(connection): retry bootstrap cleanup after save failure Keep gateway registry memory aligned with persisted state when bootstrap credential cleanup cannot be saved, so later connection lifecycle events can retry safely. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 73908040-d4b7-493b-b024-b0c9ebcfc98d --------- Co-authored-by: Copilot App <[email protected]> Copilot-Session: 184fa070-4567-45dc-ac2d-c81c2840af14 Copilot-Session: 15b5584f-677b-453f-8aa4-4f33fe60bc50 Copilot-Session: 73908040-d4b7-493b-b024-b0c9ebcfc98d
1 parent a1d933a commit 01faa64

32 files changed

Lines changed: 1968 additions & 100 deletions

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,7 @@ jobs:
352352
include:
353353
- name: setup-connect
354354
timeout_minutes: 45
355-
filter: "FullyQualifiedName~OpenClaw.E2ETests.Setup.SetupAndConnectTests|FullyQualifiedName~OpenClaw.E2ETests.Setup.MxcSetupAndConnectTests"
355+
filter: "FullyQualifiedName~OpenClaw.E2ETests.Setup.SetupAndConnectTests|FullyQualifiedName~OpenClaw.E2ETests.Setup.MxcSetupAndConnectTests|FullyQualifiedName~OpenClaw.E2ETests.Setup.MirroredWslPortLeaseTests"
356356
- name: revocation-recovery
357357
timeout_minutes: 25
358358
filter: FullyQualifiedName~OpenClaw.E2ETests.Setup.RevocationAndRecoveryTests

‎docs/ARCHITECTURE.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ These are the canonical homes. Do not reintroduce private copies elsewhere.
6161
| Settings page load/persist view logic | `SettingsPageViewModel` | authoritative |
6262
| Native tool identity, display arguments, payload extraction, and flattened-history projection | `NativeToolProjector` | authoritative |
6363
| Managed-local listener provenance and strong-credential authorization | `ManagedLocalGatewayPortProvenanceService` | authoritative |
64+
| Exact Gateway wizard terminal-restart compatibility and bounded retry policy | `GatewayWizardRestartRecoveryPolicy` | authoritative |
6465
| Managed-local automatic repair eligibility and orchestration | `ManagedLocalGatewayAutoRepairMonitor` + `ManagedLocalGatewayRepairCoordinator` | authoritative |
6566
| Capability UI metadata | `NodeCapabilityUiCatalog` (planned) | planned |
6667
| Capability registration/gating | `NodeCapabilityRegistrationPolicy` (planned) | planned |
@@ -120,7 +121,8 @@ leading and trailing pipe. Columns, in order:
120121
| 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 |
121122
| 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 |
122123
| 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 | - |
123-
| 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 | - |
124+
| 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, incomplete, conflicting, or changed Windows listener ownership never receives strong credentials or destructive remediation; relayless ownership requires a complete empty Windows snapshot, expected-distro systemd MainPID proof, and immediate complete empty revalidation | ManagedLocalGatewayPortProvenanceServiceTests.InteractiveCredentialGate_ExpectedCacheThenOwnerChanges_FailsClosed | behavioral | - |
125+
| gateway-wizard-restart-recovery | authoritative | WizardPage + SetupWizardRunner reconnect call sites | duplicated exact-version terminal-restart classification and bounded provenance retry orchestration | GatewayWizardRestartRecoveryPolicy | WizardPage and SetupWizardRunner apply hosted and headless lifecycle and consume provenance inspection results | only managed-local restart-like disconnects may retry NoListener or the typed snapshot-changed race; other unknown or conflicting ownership fails immediately, retryable startup close 1013 stays inside the existing reconnect bound, and exact Gateway 2026.7.1 final model-check close 1012 completes only after a fresh hello-ok | GatewayWizardRestartRecoveryPolicyTests.Exact2026_7_1TerminalModelCheckServiceRestart_IsExpected | behavioral | when the 2026.7.1 terminal-restart compatibility path is removed |
124126
| 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 | - |
125127
| 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 |
126128
| 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 |

‎docs/CONNECTION_ARCHITECTURE.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -204,15 +204,15 @@ The gateway may reject a stored device token with the structured code `AUTH_DEVI
204204

205205
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.
206206

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.
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 a setup-managed WSL loopback gateway proven by `ManagedLocalGatewayPortProvenanceService`. The managed-local proof accepts either the existing verified Windows WSL relay identity or a relayless mirrored-networking endpoint with a complete empty Windows listener snapshot, positive expected-distro systemd MainPID ownership, and an immediate second complete empty snapshot. Strong credentials repeat that relayless proof immediately before use. Loopback is not treated as identity by itself: incomplete capture or any unknown, conflicting, or changed Windows listener 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.
208208

209209
### Automatic managed-local WSL gateway repair (tray)
210210

211211
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).
212212

213213
**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.
214214

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.
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. Relayless mirrored networking is accepted only when complete Windows captures remain empty around positive expected-distro systemd MainPID proof. It automatically disables/stops only a fully proven obsolete native OpenClaw gateway; an unknown, incomplete, or conflicting listener is never trusted or 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.
216216

217217
## Client instance lifecycle
218218

‎docs/ONBOARDING_WIZARD.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ If the gateway doesn't support the wizard protocol or is unreachable, this scree
4747

4848
The wizard keeps recovery choices visible while setup steps are running so users can start the wizard again or skip it for now if an auth flow stalls. If the gateway restarts or the wizard connection is lost while setup is running, the same recovery choices are presented in the error state so the user is not trapped retrying a broken session.
4949

50+
Exact Gateway 2026.7.1 has a terminal compatibility path for an app-managed local WSL gateway. When the final `model-check` answer produces WebSocket close 1012 before the gateway can return `done`, setup retries the temporary `NoListener` state and the typed snapshot-changed race that can occur while the listener is restarting. Other unknown or conflicting endpoint ownership fails immediately, and no credential is sent until the managed endpoint is verified again. A retryable startup close 1013 remains inside the existing reconnect timeout. Setup completes only after a fresh authenticated `hello-ok` handshake. Other versions and steps keep the normal managed-local wizard replay behavior with the same bounded ownership wait; remote gateways and other disconnects do not enter this recovery path.
51+
5052
When the gateway config wizard surfaces an error and the active gateway is an app-managed WSL distro, the error state also offers **Open terminal** and **Restart gateway**. The wizard does not parse or classify the gateway's error text; it leaves the message visible and selectable so the user can copy any command the gateway reports. The buttons reuse the shared `GatewayTerminalLauncher` and `WslGatewayController` (in `OpenClaw.Connection`, also used by the Connections tab). Restart re-enters the gateway config wizard (the provider/model onboarding step - not the whole V2 onboarding, and without re-installing the WSL distro) so fixes such as newly-installed tools are picked up on `PATH`. Because the gateway restart clears its wizard session, this resumes at the first config question rather than the exact step that failed. Detection is gated on `GatewayRecord.SetupManagedDistroName`, so it never appears for remote/SSH gateways.
5153

5254
### All set
@@ -93,6 +95,7 @@ Use a temp settings directory for tests that construct `SettingsManager`, or set
9395
| `src/OpenClaw.SetupEngine.UI/Pages/CapabilitiesPage.xaml(.cs)` | Capability profile, inline Windows permission status, and install review |
9496
| `src/OpenClaw.SetupEngine.UI/Pages/ProgressPage.xaml(.cs)` | WSL gateway install progress and gateway-installed handoff |
9597
| `src/OpenClaw.SetupEngine.UI/Pages/WizardPage.xaml(.cs)` | OpenClaw onboard provider/model/key wizard driven by gateway `wizard.*` frames |
98+
| `src/OpenClaw.SetupEngine/GatewayWizardRestartRecoveryPolicy.cs` | Exact terminal-restart classification and bounded restart provenance/reconnect retry policy |
9699
| `src/OpenClaw.SetupEngine.UI/Pages/CompletePage.xaml(.cs)` | Success, failure, log/help, and startup preference summary |
97100
| `src/OpenClaw.SetupEngine.UI/Pages/SetupPermissionHelper.cs` | Passive Windows permission checks and inline permission rows |
98101
| `src/OpenClaw.Connection/GatewayRegistry.cs` | Persistent gateway records and migration target |

‎scripts/validate-mxc-e2e.ps1‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111
claim end-to-end validation on a host that did not exercise MXC.
1212
1313
.PARAMETER NoBuild
14-
Skip build steps and run against existing outputs.
14+
Skip the repository and tray-app build steps. The E2E test project is always
15+
rebuilt so fixture source changes cannot run against stale --no-build output.
1516
1617
.PARAMETER AllowSkip
1718
Return success when MXC tests are reported but skipped. Use only for
@@ -100,6 +101,7 @@ function Assert-GatewayMxcProofsPassed {
100101
param([Parameter(Mandatory = $true)][xml]$Trx)
101102

102103
$expectedProofs = @(
104+
"MirroredWslSafeGatewayPort_IsListeningAndRecorded",
103105
"RealGateway_SystemRun_ExecutesThroughWindowsNodeMxcSandbox",
104106
"RealGateway_SystemRun_BlocksWritesToTrayDataDirectoryInMxcSandbox"
105107
)
@@ -182,9 +184,10 @@ try {
182184
& dotnet build ".\src\OpenClaw.Tray.WinUI\OpenClaw.Tray.WinUI.csproj" -c $Configuration -r $RuntimeIdentifier
183185
}
184186

185-
Invoke-Checked -Name "Build E2E tests for $RuntimeIdentifier" -Command {
186-
& dotnet build ".\tests\OpenClaw.E2ETests\OpenClaw.E2ETests.csproj" -c $Configuration -r $RuntimeIdentifier
187-
}
187+
}
188+
189+
Invoke-Checked -Name "Build E2E tests for $RuntimeIdentifier (always current)" -Command {
190+
& dotnet build ".\tests\OpenClaw.E2ETests\OpenClaw.E2ETests.csproj" -c $Configuration -r $RuntimeIdentifier
188191
}
189192

190193
$e2eTrx = Join-Path $ResultsDirectory "OpenClaw.E2ETests.Mxc.trx"
@@ -199,7 +202,7 @@ try {
199202
--results-directory $ResultsDirectory `
200203
--logger "trx;LogFileName=OpenClaw.E2ETests.Mxc.trx" `
201204
--logger "console;verbosity=detailed" `
202-
--filter "FullyQualifiedName~OpenClaw.E2ETests.Setup.MxcSetupAndConnectTests" `
205+
--filter "FullyQualifiedName~OpenClaw.E2ETests.Setup.MxcSetupAndConnectTests|FullyQualifiedName~OpenClaw.E2ETests.Setup.MirroredWslPortLeaseTests" `
203206
2>&1 | Tee-Object -FilePath $e2eConsoleLog
204207
}
205208
Assert-GatewayMxcProofsPassed -Trx (Read-Trx -Path $e2eTrx)

‎src/OpenClaw.Connection/GatewayConnectionManager.cs‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1886,13 +1886,14 @@ private void TryClearBootstrapTokenAfterDurablePairing(string gatewayRecordId, s
18861886
return;
18871887
}
18881888

1889-
var updated = _registry.Update(gatewayRecordId, r => r with { BootstrapToken = null });
1890-
if (updated == null)
1891-
return;
1892-
18931889
try
18941890
{
1895-
_registry.Save();
1891+
var updated = _registry.UpdateAndSave(
1892+
gatewayRecordId,
1893+
r => r with { BootstrapToken = null });
1894+
if (updated == null)
1895+
return;
1896+
18961897
_diagnostics.Record("credential", "Cleared bootstrap token — operator and node tokens are durable");
18971898
}
18981899
catch (Exception ex)

0 commit comments

Comments
 (0)