Skip to content

Commit 787db18

Browse files
shanselmanCopilot
andauthored
fix(setup): require WSL cleanup ownership (#1229)
Co-authored-by: Copilot App <[email protected]>
1 parent 8ff0353 commit 787db18

11 files changed

Lines changed: 694 additions & 15 deletions

File tree

‎docs/ARCHITECTURE.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@ leading and trailing pipe. Columns, in order:
160160
| setup-shellescape-closed | closed | src/OpenClaw.SetupEngine/SetupSteps.cs | private ShellEscape helpers with divergent wrap semantics | WslShellQuoting | - | OpenClaw.SetupEngine builds WSL command lines only via WslShellQuoting; no local ShellEscape helper anywhere in the project | SetupStepsShellEscapeClosureTests.SetupEngine_DoesNotReintroduce_PrivateShellEscape | source-shape | when no file under src/OpenClaw.SetupEngine builds any WSL command strings |
161161
| setup-keepalive-process-manager | authoritative | src/OpenClaw.SetupEngine/SetupSteps.cs (StartKeepaliveStep) | setup-time WSL keepalive process discovery, start, marker read/write, command-line identity, and rollback cleanup | KeepaliveProcessManager (raw OS calls delegated to internal IKeepaliveProcessRuntime seam; StartKeepaliveStep is the only caller that reads SetupContext) | StartKeepaliveStep keeps Id/DisplayName and thin ExecuteAsync/RollbackAsync orchestration only | setup-time keepalive never hard-fails the pipeline on start failure (null PID or thrown exception both soft-fail identically); its marker path/JSON are the intentional handoff consumed by the tray keepalive service; rollback kills only wsl/wsl.exe processes whose command line matches this distro via WslCommandLineMatcher, leaves wrong-distro/unmatched command lines untouched, and deletes only its own marker/empty directory | KeepaliveProcessManagerTests.RollbackAsync_KillsOnlyMatchingDistroProcesses_LeavesOthersUntouched | behavioral | when StartKeepaliveStep contains no process/marker logic of its own |
162162
| 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 | - |
163+
| setup-managed-distro-ownership | authoritative | ExistingConfigDetector, CleanupStaleDistroStep, and CreateWslInstanceStep | durable ownership evidence parsing and marker lifecycle | ManagedDistroOwnership | detector and setup steps request ownership checks or scoped marker operations only | automatic cleanup unregisters or deletes same-named WSL data only with an exact managed registry binding, matching setup state, or a matching marker whose canonical path is the expected managed install path; exact UI or CLI destructive consent may override | SetupStepsTests.CleanupStaleDistro_PreservesUnownedRegisteredDistro | behavioral | - |
163164
| 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 | - |
164165
| local-ai-gateway-distro-binding | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | hardcoded Local AI WSL distro selection | LocalAiGatewayDistroResolver | App loads the gateway registry and composes the resolver, provider coordinator, and runtime | the singleton Local AI installation binds to exactly one explicit setup-managed local no-SSH gateway record; its record ID and SetupManagedDistroName are pinned and revalidated before every WSL command, while missing, ambiguous, unavailable, or drifted ownership fails closed | LocalAiGatewayProviderCoordinatorTests.Quiesce_OwnerDriftsAfterInspection_BlocksFirstMutation | behavioral | - |
165166
| 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, and a terminal hosted-wizard payload completes on the exact TUI SIGTERM termination only when the request just sent answered the authoritative final done acknowledgement step | GatewayWizardRestartRecoveryPolicyTests.Exact2026_7_1TerminalModelCheckServiceRestart_IsExpected | behavioral | when the 2026.7.1 terminal-restart compatibility path is removed |

‎docs/ONBOARDING_WIZARD.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ The setup flow no longer configures remote/manual gateways inline. The Welcome p
2424
Displays the OpenClaw icon, app title, and a brief description. If an app-owned local WSL gateway already exists, the primary CTA reads **Install new WSL Gateway** and confirmation warns that the current OpenClaw WSL gateway and distro will be deleted. If only an external gateway exists, the CTA remains **Set up locally** and confirmation explains that the external connection remains available in Connections.
2525

2626
### Local setup progress
27-
Installs and connects a new app-owned `OpenClawGateway` WSL instance from a clean WSL baseline. Setup does not export from or mutate an existing user Ubuntu distro; if WSL cannot create the named app-owned distro directly, setup fails with an actionable update message. When replacing an app-owned local gateway, the removal step is shown as part of progress and can be retried on failure.
27+
Installs and connects a new app-owned `OpenClawGateway` WSL instance from a clean WSL baseline. Setup does not export from or mutate an existing user Ubuntu distro; if WSL cannot create the named app-owned distro directly, setup fails with an actionable update message. Cleanup automatically removes only a distro backed by durable OpenClaw setup or gateway-registry ownership evidence. An unproven same-named distro or leftover data directory is preserved unless the user explicitly confirms its permanent replacement in the setup UI or passes `--confirm-destructive`. When replacing an app-owned local gateway, the removal step is shown as part of progress and can be retried on failure.
2828

2929
The managed distro is locked down and is not intended to be a normal interactive Ubuntu profile. For editing `openclaw.json` as the `openclaw` user and using root for protected-file administration, see [Managing the locked-down WSL gateway](WSL_GATEWAY_ADMIN.md).
3030

‎docs/SETUP_ENGINE_REDESIGN.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ Executed sequentially. Each step is a small class (30–120 lines) in its own fi
179179
| 2 | `PreflightOsStep` | Validate Windows 64-bit, version ≥ 22H2 |
180180
| 3 | `PreflightWslStep` | Verify WSL is installed and supports direct named clean installs |
181181
| 4 | `PreflightWindowsTailscaleStep` | Validate optional Windows Tailscale prerequisites |
182-
| 5 | `CleanupStaleDistroStep` | Unregister leftover app-owned WSL distro and remove its VHD directory if `CleanBeforeRun` |
182+
| 5 | `CleanupStaleDistroStep` | Unregister leftover WSL distro and remove its VHD directory only when `CleanBeforeRun` is enabled and app ownership or explicit destructive confirmation is present |
183183
| 6 | `CleanupStaleGatewayStep` | Stop orphaned gateway service, remove config |
184184
| 7 | `PreflightPortStep` | Check gateway port is available |
185185
| 8 | `CreateWslInstanceStep` | Directly install a fresh app-owned WSL distro; never export a user's Ubuntu distro |

‎src/OpenClaw.SetupEngine.UI/Pages/WelcomePage.xaml.cs‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,10 @@ private async Task StartInstallAsync()
155155
ExistingConfigDetector.ExistingConfig existing;
156156
try
157157
{
158-
existing = await Task.Run(() => ExistingConfigDetector.Detect(dataDir, config.DistroName));
158+
existing = await Task.Run(() => ExistingConfigDetector.Detect(
159+
dataDir,
160+
config.DistroName,
161+
setupWindow?.LocalDataDir));
159162
}
160163
catch (InvalidOperationException ex)
161164
{
@@ -181,14 +184,20 @@ private async Task StartInstallAsync()
181184
InstallCheckProgress.IsActive = false;
182185
InstallCheckProgress.Visibility = Visibility.Collapsed;
183186
var summary = ExistingConfigDetector.BuildReplacementSummary(existing);
187+
var requiresDestructiveConfirmation =
188+
ExistingConfigDetector.RequiresDestructiveConfirmation(existing);
184189

185190
var dialog = new ContentDialog
186191
{
187-
Title = existing.HasLocalGateway || existing.HasDistro
188-
? "Replace existing WSL gateway?"
189-
: "Install a new WSL gateway?",
192+
Title = requiresDestructiveConfirmation
193+
? $"Permanently delete WSL distro '{config.DistroName}'?"
194+
: existing.HasLocalGateway || existing.HasDistro || existing.HasDistroDataDirectory
195+
? "Replace existing WSL gateway?"
196+
: "Install a new WSL gateway?",
190197
Content = summary,
191-
PrimaryButtonText = "Continue",
198+
PrimaryButtonText = requiresDestructiveConfirmation
199+
? "Delete and replace"
200+
: "Continue",
192201
CloseButtonText = "Cancel",
193202
DefaultButton = ContentDialogButton.Close,
194203
XamlRoot = xamlRoot,
@@ -198,6 +207,10 @@ private async Task StartInstallAsync()
198207
if (result != ContentDialogResult.Primary)
199208
return;
200209

210+
config.ConfirmedDestructiveDistroName = requiresDestructiveConfirmation
211+
? config.DistroName
212+
: null;
213+
201214
navigating = true;
202215
setupWindow.NavigateToCapabilities();
203216
}

‎src/OpenClaw.SetupEngine/CleanupStaleDistroStep.cs‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,26 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
3737
// Distro not registered, but disk directory may still exist from prior crash
3838
if (Directory.Exists(wslDir))
3939
{
40+
if (EnsureDestructiveCleanupAllowed(ctx, distro) is { } ownershipFailure)
41+
return ownershipFailure;
42+
4043
ctx.Logger.Info($"Removing orphaned WSL directory: {wslDir}");
4144
var delete = await DeleteDistroDirectoryWithRetries(ctx, distro, wslDir, ct);
4245
if (!delete.IsSuccess)
4346
return delete;
47+
48+
ManagedDistroOwnership.DeleteMarker(ctx.LocalDataDir, distro);
4449
}
50+
else
51+
ManagedDistroOwnership.DeleteMarker(ctx.LocalDataDir, distro);
52+
4553
ctx.Logger.Decision("No stale distro found", "skip cleanup");
4654
return StepResult.Ok("No stale distro to clean");
4755
}
4856

57+
if (EnsureDestructiveCleanupAllowed(ctx, distro) is { } distroOwnershipFailure)
58+
return distroOwnershipFailure;
59+
4960
ctx.Logger.Decision($"Found existing distro '{distro}'", "terminating and unregistering");
5061

5162
// Stop only the app-owned distro. Global WSL shutdown would disrupt unrelated distros.
@@ -68,6 +79,8 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
6879
if (!delete.IsSuccess)
6980
return delete;
7081

82+
ManagedDistroOwnership.DeleteMarker(ctx.LocalDataDir, distro);
83+
7184
// Wait for port to be released
7285
ctx.Logger.Info("Waiting for port release after distro termination...");
7386
await PreflightPortStep.WaitForPortFreeAsync(ctx.Config.GatewayPort, ctx.Config.Gateway.Bind, ctx.Logger, ct);
@@ -77,6 +90,33 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
7790
return StepResult.Fail($"Failed to unregister distro: {unregister.Stderr}");
7891
}
7992

93+
internal static StepResult? EnsureDestructiveCleanupAllowed(
94+
SetupContext ctx,
95+
string distroName)
96+
{
97+
if (ctx.Config.ConfirmDestructive ||
98+
string.Equals(
99+
ctx.Config.ConfirmedDestructiveDistroName,
100+
distroName,
101+
StringComparison.OrdinalIgnoreCase) ||
102+
ManagedDistroOwnership.HasEvidence(
103+
ctx.DataDir,
104+
ctx.LocalDataDir,
105+
distroName))
106+
{
107+
return null;
108+
}
109+
110+
ctx.Logger.Decision(
111+
$"Existing WSL distro or data '{distroName}' is not proven app-owned",
112+
"preserve existing data");
113+
var recovery = ctx.Config.Headless
114+
? "Rerun SetupEngine with --confirm-destructive to delete it."
115+
: "Return to the start of OpenClaw setup and explicitly confirm its permanent replacement.";
116+
return StepResult.Terminal(
117+
$"Existing WSL distro or data for '{distroName}' is not proven to be managed by OpenClaw and was preserved. {recovery}");
118+
}
119+
80120
internal static async Task<StepResult> DeleteDistroDirectoryWithRetries(
81121
SetupContext ctx,
82122
string distroName,

‎src/OpenClaw.SetupEngine/CreateWslInstanceStep.cs‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,24 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
5252
if (!pathCheck.IsSuccess)
5353
return pathCheck;
5454

55+
try
56+
{
57+
await ManagedDistroOwnership.WriteMarkerAsync(
58+
ctx.LocalDataDir,
59+
distro,
60+
installPath,
61+
ct);
62+
}
63+
catch (Exception ex) when (
64+
ex is IOException
65+
or UnauthorizedAccessException
66+
or ArgumentException
67+
or NotSupportedException)
68+
{
69+
return StepResult.Fail(
70+
$"OpenClaw could not record ownership before creating WSL distro '{distro}': {ex.Message}");
71+
}
72+
5573
Directory.CreateDirectory(Path.GetDirectoryName(installPath)!);
5674

5775
var installArgs = WslInstallSupport.BuildDirectInstallArgs(baseDistro, distro, installPath);
@@ -200,9 +218,13 @@ private static async Task<string> CleanupPartialInstall(SetupContext ctx, string
200218
cleanupErrors.Add(delete.Message ?? "install directory cleanup failed");
201219
}
202220

203-
return cleanupErrors.Count == 0
204-
? ""
205-
: $" Partial app-owned distro cleanup also failed: {string.Join("; ", cleanupErrors)}";
221+
if (cleanupErrors.Count == 0)
222+
{
223+
ManagedDistroOwnership.DeleteMarker(ctx.LocalDataDir, distro);
224+
return "";
225+
}
226+
227+
return $" Partial app-owned distro cleanup also failed: {string.Join("; ", cleanupErrors)}";
206228
}
207229

208230
private static async Task<bool> TryUnregisterPartialInstall(SetupContext ctx, string distro, List<string> cleanupErrors, CancellationToken ct)

‎src/OpenClaw.SetupEngine/ExistingConfigDetector.cs‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ public sealed record ExistingConfig(
1212
string? LocalGatewayId,
1313
string? LocalGatewayUrl,
1414
bool HasDistro,
15+
bool HasDistroDataDirectory,
16+
bool DistroIsAppOwned,
1517
string? DistroName,
1618
bool HasIdentityFiles,
1719
int PreservedGatewayCount,
@@ -20,8 +22,12 @@ public sealed record ExistingConfig(
2022
/// <summary>
2123
/// Detect existing local configuration by checking the gateway registry and WSL distros.
2224
/// </summary>
23-
public static ExistingConfig Detect(string dataDir, string targetDistroName)
25+
public static ExistingConfig Detect(
26+
string dataDir,
27+
string targetDistroName,
28+
string? localDataDir = null)
2429
{
30+
localDataDir ??= SetupContext.ResolveLocalDataDir();
2531
var registry = new GatewayRegistry(dataDir);
2632
registry.Load();
2733
var all = registry.GetAll();
@@ -35,6 +41,16 @@ public static ExistingConfig Detect(string dataDir, string targetDistroName)
3541
.GetAwaiter()
3642
.GetResult();
3743
var hasDistro = InterpretDistroList(result, targetDistroName);
44+
var hasDistroDataDirectory =
45+
DistroInstallPathPolicy.TryGetManagedInstallPath(
46+
localDataDir,
47+
targetDistroName,
48+
out var distroDataDirectory,
49+
out _) &&
50+
Directory.Exists(distroDataDirectory);
51+
var distroIsAppOwned =
52+
(hasDistro || hasDistroDataDirectory) &&
53+
ManagedDistroOwnership.HasEvidence(dataDir, localDataDir, targetDistroName);
3854

3955
var hasIdentity = false;
4056
if (localRecord != null)
@@ -48,7 +64,9 @@ public static ExistingConfig Detect(string dataDir, string targetDistroName)
4864
LocalGatewayId: localRecord?.Id,
4965
LocalGatewayUrl: localRecord?.Url,
5066
HasDistro: hasDistro,
51-
DistroName: hasDistro ? targetDistroName : null,
67+
HasDistroDataDirectory: hasDistroDataDirectory,
68+
DistroIsAppOwned: distroIsAppOwned,
69+
DistroName: hasDistro || hasDistroDataDirectory ? targetDistroName : null,
5270
HasIdentityFiles: hasIdentity,
5371
PreservedGatewayCount: preserved.Count,
5472
PreservedGatewayNames: preserved.Select(r => r.FriendlyName ?? r.Url).ToList());
@@ -72,13 +90,23 @@ internal static bool InterpretDistroList(CommandResult result, string targetDist
7290
/// </summary>
7391
public static string BuildReplacementSummary(ExistingConfig config)
7492
{
75-
if (!config.HasLocalGateway && !config.HasDistro)
93+
if (!config.HasLocalGateway && !config.HasDistro && !config.HasDistroDataDirectory)
7694
return "A new local WSL gateway will be created. No existing configuration will be affected.";
7795

7896
var lines = new List<string>();
7997

8098
if (config.HasDistro)
81-
lines.Add($"• WSL distro '{config.DistroName}' will be deleted and recreated");
99+
{
100+
lines.Add(config.DistroIsAppOwned
101+
? $"• App-owned WSL distro '{config.DistroName}' will be deleted and recreated"
102+
: $"• WSL distro '{config.DistroName}' is not proven to be app-owned. Continuing will permanently delete and recreate it");
103+
}
104+
else if (config.HasDistroDataDirectory)
105+
{
106+
lines.Add(config.DistroIsAppOwned
107+
? $"• App-owned WSL data for '{config.DistroName}' will be deleted"
108+
: $"• WSL data for '{config.DistroName}' is not proven to be app-owned. Continuing will permanently delete it");
109+
}
82110
if (config.HasLocalGateway)
83111
lines.Add("• Local gateway record will be replaced");
84112
if (config.HasIdentityFiles)
@@ -94,4 +122,8 @@ public static string BuildReplacementSummary(ExistingConfig config)
94122

95123
return string.Join("\n", lines);
96124
}
125+
126+
public static bool RequiresDestructiveConfirmation(ExistingConfig config) =>
127+
!config.DistroIsAppOwned &&
128+
(config.HasDistro || config.HasDistroDataDirectory);
97129
}

0 commit comments

Comments
 (0)