Skip to content

Commit 4c078f9

Browse files
authored
fix(setup): recover uninitialized WSL automatically (#1202)
Recognize known uninitialized WSL states, invoke the existing one-shot installer, reinspect readiness, and provide reboot guidance.
1 parent a1d7cb0 commit 4c078f9

4 files changed

Lines changed: 228 additions & 8 deletions

File tree

‎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. Cleanup automatically unregisters a distro only when durable OpenClaw evidence is paired with exactly one readable current-user WSL registration whose canonical base path matches the expected managed install path. Automatic orphan-directory cleanup requires a marker bound to that exact path. 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.
27+
Installs and connects a new app-owned `OpenClawGateway` WSL instance from a clean WSL baseline. If the WSL platform is missing or its optional component is not initialized, setup requests administrator approval to install it, re-inspects readiness, and reports when a Windows restart is required. 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 unregisters a distro only when durable OpenClaw evidence is paired with exactly one readable current-user WSL registration whose canonical base path matches the expected managed install path. Automatic orphan-directory cleanup requires a marker bound to that exact path. 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

‎src/OpenClaw.SetupEngine/PreflightWslStep.cs‎

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,14 @@ public static async Task<WslViabilityResult> InspectAsync(
115115
}
116116

117117
var combined = $"{status.Stdout}\n{status.Stderr}";
118+
if (LooksPlatformInstallRequired(status))
119+
{
120+
return new(
121+
WslViabilityKind.Installable,
122+
"WSL is not initialized yet.",
123+
"Setup can request administrator approval to initialize and verify it before continuing.");
124+
}
125+
118126
if (WslInstallSupport.TryGetEnvironmentIssue(combined, out var message))
119127
{
120128
logger.Warn($"WSL environment issue detected: {NormalizeWslOutput(combined).Trim()}");
@@ -147,10 +155,20 @@ internal static bool LooksUnavailable(CommandResult result)
147155
var text = NormalizeWslOutput($"{result.Stdout}\n{result.Stderr}");
148156
return text.Contains("aka.ms/wslinstall", StringComparison.OrdinalIgnoreCase)
149157
|| text.Contains("Windows Subsystem for Linux has no installed distributions", StringComparison.OrdinalIgnoreCase)
158+
|| LooksPlatformInstallRequired(text)
150159
|| text.Contains("not recognized", StringComparison.OrdinalIgnoreCase)
151160
|| text.Contains("not installed", StringComparison.OrdinalIgnoreCase);
152161
}
153162

163+
private static bool LooksPlatformInstallRequired(CommandResult result) =>
164+
LooksPlatformInstallRequired(NormalizeWslOutput($"{result.Stdout}\n{result.Stderr}"));
165+
166+
private static bool LooksPlatformInstallRequired(string text) =>
167+
text.Contains("WSL_E_WSL_OPTIONAL_COMPONENT_REQUIRED", StringComparison.OrdinalIgnoreCase)
168+
|| text.Contains("0x8007019e", StringComparison.OrdinalIgnoreCase)
169+
|| text.Contains("requires the Windows Subsystem for Linux Optional Component", StringComparison.OrdinalIgnoreCase)
170+
|| text.Contains("Optional components needed to run WSL are not installed", StringComparison.OrdinalIgnoreCase);
171+
154172
private static bool LooksTooOldForVersionCommand(CommandResult result)
155173
{
156174
var text = NormalizeWslOutput($"{result.Stdout}\n{result.Stderr}");
@@ -273,7 +291,7 @@ internal EnsureWslPlatformStep(
273291

274292
public override string Id => "ensure-wsl-platform";
275293
public override string DisplayName => "Prepare WSL platform";
276-
public override bool CanRetry => true;
294+
public override bool CanRetry => false;
277295

278296
public override async Task<StepResult> ExecuteAsync(SetupContext ctx, CancellationToken ct)
279297
{
@@ -294,8 +312,15 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
294312

295313
viability = await WslViabilityInspector.InspectAsync(ctx.Commands, ctx.Logger, ct);
296314
ctx.WslViability = viability;
297-
return viability.Kind == WslViabilityKind.Ready
298-
? StepResult.Ok("WSL platform installed and verified.")
299-
: StepResult.Terminal(viability.Description);
315+
if (viability.Kind == WslViabilityKind.Ready)
316+
return StepResult.Ok("WSL platform installed and verified.");
317+
if (viability.Kind == WslViabilityKind.Installable)
318+
{
319+
return StepResult.Terminal(
320+
"WSL platform installation completed, but Windows must be restarted before WSL is ready. " +
321+
"Reboot Windows, then run setup again.");
322+
}
323+
324+
return StepResult.Terminal(viability.Description);
300325
}
301326
}

‎tests/OpenClaw.SetupEngine.Tests/SetupStepsTests.cs‎

Lines changed: 196 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1972,6 +1972,182 @@ public async Task EnsureWslPlatform_InstallsOnlyAfterReadOnlyPreflight()
19721972
Assert.Equal(3, commands.Calls.Count);
19731973
}
19741974

1975+
[Fact]
1976+
public async Task EnsureWslPlatform_LeavesReadyWslUnchanged()
1977+
{
1978+
var installCalls = 0;
1979+
var commands = new FakeCommandRunner(args => args switch
1980+
{
1981+
["--version"] => Ok("WSL version: 2.7.3.0\n"),
1982+
["--status"] => Ok("Default Version: 2\n"),
1983+
_ => Fail($"unexpected args: {string.Join(' ', args)}"),
1984+
});
1985+
var ctx = CreateContext(commands: commands);
1986+
var step = new EnsureWslPlatformStep((_, _) =>
1987+
{
1988+
installCalls++;
1989+
return Task.FromResult(StepResult.Ok("initialized"));
1990+
});
1991+
1992+
var result = await step.ExecuteAsync(ctx, CancellationToken.None);
1993+
1994+
Assert.Equal(StepOutcome.Success, result.Outcome);
1995+
Assert.Equal("WSL platform is ready.", result.Message);
1996+
Assert.Equal(0, installCalls);
1997+
Assert.Equal(WslViabilityKind.Ready, ctx.WslViability?.Kind);
1998+
Assert.Equal(2, commands.Calls.Count);
1999+
}
2000+
2001+
[Fact]
2002+
public async Task PreflightWsl_UninitializedPlatformIsInstallable()
2003+
{
2004+
var commands = new FakeCommandRunner(args => args switch
2005+
{
2006+
["--version"] => Ok("WSL version: 2.7.3.0\n"),
2007+
["--status"] => new CommandResult(
2008+
1,
2009+
"",
2010+
"This application requires the Windows Subsystem for Linux Optional Component.\n" +
2011+
"Install it by running: wsl.exe --install --no-distribution\n" +
2012+
"Error code: Wsl/WSL_E_WSL_OPTIONAL_COMPONENT_REQUIRED",
2013+
TimeSpan.Zero,
2014+
TimedOut: false),
2015+
_ => Fail($"unexpected args: {string.Join(' ', args)}"),
2016+
});
2017+
var ctx = CreateContext(commands: commands);
2018+
2019+
var result = await new PreflightWslStep().ExecuteAsync(ctx, CancellationToken.None);
2020+
2021+
Assert.Equal(StepOutcome.Success, result.Outcome);
2022+
Assert.Equal(WslViabilityKind.Installable, ctx.WslViability?.Kind);
2023+
Assert.Contains("not initialized", result.Message);
2024+
Assert.DoesNotContain(commands.Calls, call => call.Arguments.Contains("--install"));
2025+
}
2026+
2027+
[Fact]
2028+
public async Task EnsureWslPlatform_InitializesPlatformAndReinspectsReadiness()
2029+
{
2030+
var initialized = false;
2031+
var installCalls = 0;
2032+
var commands = new FakeCommandRunner(args => args switch
2033+
{
2034+
["--version"] => Ok("WSL version: 2.7.3.0\n"),
2035+
["--status"] when !initialized => new CommandResult(
2036+
1,
2037+
"",
2038+
"Error code: Wsl/WSL_E_WSL_OPTIONAL_COMPONENT_REQUIRED",
2039+
TimeSpan.Zero,
2040+
TimedOut: false),
2041+
["--status"] => Ok("Default Version: 2\n"),
2042+
_ => Fail($"unexpected args: {string.Join(' ', args)}"),
2043+
});
2044+
var ctx = CreateContext(commands: commands);
2045+
var step = new EnsureWslPlatformStep((_, _) =>
2046+
{
2047+
installCalls++;
2048+
initialized = true;
2049+
return Task.FromResult(StepResult.Ok("initialized"));
2050+
});
2051+
2052+
var result = await step.ExecuteAsync(ctx, CancellationToken.None);
2053+
2054+
Assert.Equal(StepOutcome.Success, result.Outcome);
2055+
Assert.Equal("WSL platform installed and verified.", result.Message);
2056+
Assert.Equal(1, installCalls);
2057+
Assert.Equal(WslViabilityKind.Ready, ctx.WslViability?.Kind);
2058+
Assert.Equal(4, commands.Calls.Count);
2059+
}
2060+
2061+
[Fact]
2062+
public async Task EnsureWslPlatform_RequiresRestartWhenInitializationIsStillPending()
2063+
{
2064+
var installCalls = 0;
2065+
var commands = new FakeCommandRunner(args => args switch
2066+
{
2067+
["--version"] => Ok("WSL version: 2.7.3.0\n"),
2068+
["--status"] => new CommandResult(
2069+
1,
2070+
"",
2071+
"Error code: Wsl/WSL_E_WSL_OPTIONAL_COMPONENT_REQUIRED",
2072+
TimeSpan.Zero,
2073+
TimedOut: false),
2074+
_ => Fail($"unexpected args: {string.Join(' ', args)}"),
2075+
});
2076+
var ctx = CreateContext(commands: commands);
2077+
var step = new EnsureWslPlatformStep((_, _) =>
2078+
{
2079+
installCalls++;
2080+
return Task.FromResult(StepResult.Ok("initialized"));
2081+
});
2082+
2083+
var result = await step.ExecuteAsync(ctx, CancellationToken.None);
2084+
2085+
Assert.Equal(StepOutcome.FailedTerminal, result.Outcome);
2086+
Assert.Contains("restarted", result.Message, StringComparison.OrdinalIgnoreCase);
2087+
Assert.Contains("Reboot Windows", result.Message);
2088+
Assert.Equal(1, installCalls);
2089+
Assert.Equal(WslViabilityKind.Installable, ctx.WslViability?.Kind);
2090+
Assert.Equal(4, commands.Calls.Count);
2091+
}
2092+
2093+
[Fact]
2094+
public async Task EnsureWslPlatform_PropagatesElevationCancellationWithoutReinspection()
2095+
{
2096+
var commands = new FakeCommandRunner(args => args switch
2097+
{
2098+
["--version"] => Ok("WSL version: 2.7.3.0\n"),
2099+
["--status"] => new CommandResult(
2100+
1,
2101+
"",
2102+
"Error code: Wsl/WSL_E_WSL_OPTIONAL_COMPONENT_REQUIRED",
2103+
TimeSpan.Zero,
2104+
TimedOut: false),
2105+
_ => Fail($"unexpected args: {string.Join(' ', args)}"),
2106+
});
2107+
var ctx = CreateContext(commands: commands);
2108+
var step = new EnsureWslPlatformStep((_, _) =>
2109+
Task.FromResult(StepResult.Fail("WSL platform install was cancelled at the elevation prompt.")));
2110+
2111+
var result = await step.ExecuteAsync(ctx, CancellationToken.None);
2112+
2113+
Assert.Equal(StepOutcome.Failed, result.Outcome);
2114+
Assert.Contains("elevation prompt", result.Message);
2115+
Assert.Equal(2, commands.Calls.Count);
2116+
}
2117+
2118+
[Fact]
2119+
public async Task EnsureWslPlatform_ElevationCancellationIsNotRetriedByPipeline()
2120+
{
2121+
var installCalls = 0;
2122+
var commands = new FakeCommandRunner(args => args switch
2123+
{
2124+
["--version"] => Ok("WSL version: 2.7.3.0\n"),
2125+
["--status"] => new CommandResult(
2126+
1,
2127+
"",
2128+
"Error code: Wsl/WSL_E_WSL_OPTIONAL_COMPONENT_REQUIRED",
2129+
TimeSpan.Zero,
2130+
TimedOut: false),
2131+
_ => Fail($"unexpected args: {string.Join(' ', args)}"),
2132+
});
2133+
var ctx = CreateContext(commands: commands);
2134+
var step = new EnsureWslPlatformStep((_, _) =>
2135+
{
2136+
installCalls++;
2137+
return Task.FromResult(
2138+
StepResult.Fail("WSL platform install was cancelled at the elevation prompt."));
2139+
});
2140+
var pipeline = new SetupPipeline([step]);
2141+
2142+
var result = await pipeline.RunAsync(ctx);
2143+
2144+
Assert.Equal(PipelineOutcome.Failed, result.Outcome);
2145+
Assert.Equal(step.Id, result.FailedStepId);
2146+
Assert.Contains("elevation prompt", result.Message);
2147+
Assert.Equal(1, installCalls);
2148+
Assert.Equal(2, commands.Calls.Count);
2149+
}
2150+
19752151
[Fact]
19762152
public async Task PreflightWsl_UnclassifiedStatusFailureFailsClosed()
19772153
{
@@ -2555,10 +2731,16 @@ public async Task PreflightWsl_FailsTerminalWhenVirtualizationDisabledInFirmware
25552731
if (args is ["--version"])
25562732
return Ok("WSL version: 2.7.3.0\n");
25572733
if (args is ["--status"])
2558-
return Ok(
2734+
{
2735+
return new CommandResult(
2736+
1,
2737+
"",
25592738
"WSL2 is unable to start since virtualization is not enabled on this machine. "
25602739
+ "Please ensure the 'Virtual Machine Platform' optional component is enabled "
2561-
+ "and virtualization is turned on in your computer's firmware settings.");
2740+
+ "and virtualization is turned on in your computer's firmware settings.",
2741+
TimeSpan.Zero,
2742+
TimedOut: false);
2743+
}
25622744
return Ok();
25632745
});
25642746
var ctx = CreateContext(commands: commands);
@@ -3688,6 +3870,18 @@ public void ExistingConfigDetector_KeepsConclusiveUnavailableAnswerWhenRunAlsoTi
36883870
Assert.False(ExistingConfigDetector.InterpretDistroList(result, "OpenClawGateway"));
36893871
}
36903872

3873+
[Theory]
3874+
[InlineData("Error code: Wsl/WSL_E_WSL_OPTIONAL_COMPONENT_REQUIRED")]
3875+
[InlineData("This application requires the Windows Subsystem for Linux Optional Component.")]
3876+
[InlineData("Optional components needed to run WSL are not installed.")]
3877+
[InlineData("Error: 0x8007019e")]
3878+
public void ExistingConfigDetector_TreatsUninitializedWslAsNoDistro(string error)
3879+
{
3880+
var result = new CommandResult(1, "", error, TimeSpan.Zero, TimedOut: false);
3881+
3882+
Assert.False(ExistingConfigDetector.InterpretDistroList(result, "OpenClawGateway"));
3883+
}
3884+
36913885
[Theory]
36923886
[InlineData(true, 1, "")]
36933887
[InlineData(false, 1, "unexpected failure")]

‎tests/OpenClaw.SetupEngine.Tests/WslPlatformInstallDiagnosticsTests.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@ await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
4848
}
4949

5050
[Fact]
51-
public void EnsureWslPlatform_IsRetryable() => Assert.True(new EnsureWslPlatformStep().CanRetry);
51+
public void EnsureWslPlatform_DoesNotRetryElevatedMutation() =>
52+
Assert.False(new EnsureWslPlatformStep().CanRetry);
5253

5354
private sealed class DelayedHandler : HttpMessageHandler
5455
{

0 commit comments

Comments
 (0)