Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/OpenClaw.SetupEngine/CleanupStaleDistroStep.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
if (!DistroInstallPathPolicy.TryGetManagedInstallPath(ctx.LocalDataDir, distro, out var wslDir, out var pathError))
return StepResult.Terminal(pathError);

var list = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--quiet"], TimeSpan.FromSeconds(15), ct: ct);
var list = await ctx.Commands.RunAsync(
WslConstants.WslExePath,
["--list", "--quiet"],
TimeSpan.FromSeconds(15),
ct: ct,
allowInheritedPipeHandleEscape: true);
if (list.ExitCode != 0)
return StepResult.Ok("WSL not available or no distros - nothing to clean");

Expand Down
23 changes: 15 additions & 8 deletions src/OpenClaw.SetupEngine/CommandRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ Task<CommandResult> RunAsync(
string? workingDirectory = null,
string? stdinInput = null,
CancellationToken ct = default,
Stream? stdinStream = null);
Stream? stdinStream = null,
bool allowInheritedPipeHandleEscape = false);

/// <summary>
/// Run a command inside a WSL distro.
Expand Down Expand Up @@ -86,7 +87,8 @@ public async Task<CommandResult> RunAsync(
string? workingDirectory = null,
string? stdinInput = null,
CancellationToken ct = default,
Stream? stdinStream = null)
Stream? stdinStream = null,
bool allowInheritedPipeHandleEscape = false)
{
ArgumentNullException.ThrowIfNull(executable);
ArgumentNullException.ThrowIfNull(arguments);
Expand Down Expand Up @@ -192,12 +194,17 @@ public async Task<CommandResult> RunAsync(
throw;
}

// A surviving descendant can keep inherited pipe handles open after the child
// exits. Preserve output already in flight without charging the command's full
// timeout to an EOF that may never arrive.
await Task.WhenAny(
Task.WhenAll(stdoutClosed.Task, stderrClosed.Task),
Task.Delay(s_outputDrainGrace));
var outputClosed = Task.WhenAll(stdoutClosed.Task, stderrClosed.Task);
if (timedOut || allowInheritedPipeHandleEscape)
{
// Some WSL inspection commands can leave a descendant holding inherited
// pipe handles. Bound only those known waits, plus timeout cleanup.
await Task.WhenAny(outputClosed, Task.Delay(s_outputDrainGrace));
}
else
{
await outputClosed;
}

sw.Stop();
var result = new CommandResult(
Expand Down
24 changes: 20 additions & 4 deletions src/OpenClaw.SetupEngine/CreateWslInstanceStep.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,12 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati

ctx.Logger.Info($"Creating clean app-owned WSL distro '{distro}' from '{baseDistro}' at '{installPath}'");

var existing = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--quiet"], TimeSpan.FromSeconds(15), ct: ct);
var existing = await ctx.Commands.RunAsync(
WslConstants.WslExePath,
["--list", "--quiet"],
TimeSpan.FromSeconds(15),
ct: ct,
allowInheritedPipeHandleEscape: true);
if (existing.ExitCode != 0)
return StepResult.Fail($"Failed to list WSL distros before creating '{distro}': {existing.Stderr}");

Expand Down Expand Up @@ -108,7 +113,12 @@ private static StepResult EnsureInstallPathReady(string installPath)

private static async Task<StepResult> VerifyFreshDistro(SetupContext ctx, string distro, string installPath, CancellationToken ct)
{
var list = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--quiet"], TimeSpan.FromSeconds(15), ct: ct);
var list = await ctx.Commands.RunAsync(
WslConstants.WslExePath,
["--list", "--quiet"],
TimeSpan.FromSeconds(15),
ct: ct,
allowInheritedPipeHandleEscape: true);
if (list.ExitCode != 0 || !WslInstallSupport.ContainsDistro(list.Stdout, distro))
{
var environmentIssue = await PreflightWslStep.DetectEnvironmentIssueAsync(ctx, ct);
Expand All @@ -120,7 +130,8 @@ private static async Task<StepResult> VerifyFreshDistro(SetupContext ctx, string
WslConstants.WslExePath,
["--list", "--verbose"],
DistroVersionVerificationTimeout,
ct: ct);
ct: ct,
allowInheritedPipeHandleEscape: true);
if (verbose.ExitCode != 0 || !WslInstallSupport.TryGetDistroVersion(verbose.Stdout, distro, out var version))
return StepResult.Fail($"Fresh WSL install registered '{distro}', but setup could not verify it is WSL2.");

Expand Down Expand Up @@ -164,7 +175,12 @@ private static async Task<string> CleanupPartialInstall(SetupContext ctx, string
{
var cleanupErrors = new List<string>();
var installPathExists = Directory.Exists(installPath) || File.Exists(installPath);
var list = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--quiet"], TimeSpan.FromSeconds(15), ct: ct);
var list = await ctx.Commands.RunAsync(
WslConstants.WslExePath,
["--list", "--quiet"],
TimeSpan.FromSeconds(15),
ct: ct,
allowInheritedPipeHandleEscape: true);
var registrationStateKnown = list.ExitCode == 0;
var distroExists = registrationStateKnown && WslInstallSupport.ContainsDistro(list.Stdout, distro);
var canDeleteInstallPath = registrationStateKnown && !distroExists;
Expand Down
6 changes: 5 additions & 1 deletion src/OpenClaw.SetupEngine/ExistingConfigDetector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ public static ExistingConfig Detect(string dataDir, string targetDistroName)

var logger = new SetupLogger(filePath: null, LogLevel.Warn);
var result = new CommandRunner(logger)
.RunAsync(WslConstants.WslExePath, ["--list", "--quiet"], TimeSpan.FromSeconds(5))
.RunAsync(
WslConstants.WslExePath,
["--list", "--quiet"],
TimeSpan.FromSeconds(5),
allowInheritedPipeHandleEscape: true)
.GetAwaiter()
.GetResult();
var hasDistro = InterpretDistroList(result, targetDistroName);
Expand Down
12 changes: 8 additions & 4 deletions src/OpenClaw.SetupEngine/PreflightWslStep.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ public static async Task<WslViabilityResult> InspectAsync(
WslConstants.WslExePath,
["--version"],
TimeSpan.FromSeconds(5),
ct: ct);
ct: ct,
allowInheritedPipeHandleEscape: true);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Expand Down Expand Up @@ -106,7 +107,8 @@ public static async Task<WslViabilityResult> InspectAsync(
WslConstants.WslExePath,
["--status"],
TimeSpan.FromSeconds(10),
ct: ct);
ct: ct,
allowInheritedPipeHandleEscape: true);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Expand Down Expand Up @@ -186,7 +188,8 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
WslConstants.WslExePath,
["--status"],
TimeSpan.FromSeconds(10),
ct: ct);
ct: ct,
allowInheritedPipeHandleEscape: true);
var combined = $"{status.Stdout}\n{status.Stderr}";
if (!WslInstallSupport.TryGetEnvironmentIssue(combined, out var message))
return null;
Expand Down Expand Up @@ -230,7 +233,8 @@ internal static async Task<StepResult> InstallWslPlatformAsync(SetupContext ctx,
WslConstants.WslExePath,
["--version"],
TimeSpan.FromSeconds(5),
ct: ct);
ct: ct,
allowInheritedPipeHandleEscape: true);
if (probe.ExitCode != 0 || WslViabilityInspector.LooksUnavailable(probe))
{
return StepResult.Terminal(
Expand Down
14 changes: 12 additions & 2 deletions src/OpenClaw.SetupEngine/StartGatewayStep.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,15 +148,25 @@ public override async Task RollbackAsync(SetupContext ctx, CancellationToken ct)
var distro = ctx.DistroName!;

// Check if distro is running before trying systemctl stop
var list = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--quiet"], TimeSpan.FromSeconds(15), ct: ct);
var list = await ctx.Commands.RunAsync(
WslConstants.WslExePath,
["--list", "--quiet"],
TimeSpan.FromSeconds(15),
ct: ct,
allowInheritedPipeHandleEscape: true);
if (!WslInstallSupport.ContainsDistro(list.Stdout, distro))
{
ctx.Logger.Info("[Uninstall] Distro not registered — skipping gateway stop");
return;
}

// Check distro state — only stop if Running
var verbose = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--verbose"], TimeSpan.FromSeconds(15), ct: ct);
var verbose = await ctx.Commands.RunAsync(
WslConstants.WslExePath,
["--list", "--verbose"],
TimeSpan.FromSeconds(15),
ct: ct,
allowInheritedPipeHandleEscape: true);
var isRunning = WslInstallSupport.Normalize(verbose.Stdout)
.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries)
.Any(line => line.Contains(distro, StringComparison.OrdinalIgnoreCase)
Expand Down
65 changes: 64 additions & 1 deletion tests/OpenClaw.SetupEngine.Tests/CommandRunnerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,23 @@ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => runner.RunAsync(
Assert.InRange(stopwatch.Elapsed, TimeSpan.Zero, TimeSpan.FromSeconds(5));
}

[Fact]
public async Task RunAsync_ProcessTimeoutRemainsBounded()
{
var runner = CreateRunner();
var (executable, arguments) = SleepingCommand();
var stopwatch = Stopwatch.StartNew();

var result = await runner.RunAsync(
executable,
arguments,
TimeSpan.FromMilliseconds(250));

Assert.True(result.TimedOut);
Assert.Equal(-1, result.ExitCode);
Assert.InRange(stopwatch.Elapsed, TimeSpan.Zero, TimeSpan.FromSeconds(5));
}

[Fact]
public async Task RunAsync_StreamStdinPreservesBinaryBytes()
{
Expand Down Expand Up @@ -87,13 +104,36 @@ public async Task RunAsync_ReturnsWhenDescendantKeepsOutputPipesOpen()
var (executable, arguments) = ExitsLeavingPipeHolderCommand();
var stopwatch = Stopwatch.StartNew();

var result = await runner.RunAsync(executable, arguments, TimeSpan.FromSeconds(30));
var result = await runner.RunAsync(
executable,
arguments,
TimeSpan.FromSeconds(30),
allowInheritedPipeHandleEscape: true);

Assert.False(result.TimedOut);
Assert.Equal(0, result.ExitCode);
Assert.InRange(stopwatch.Elapsed, TimeSpan.Zero, TimeSpan.FromSeconds(5));
}

[Fact]
public async Task RunAsync_DrainsHighVolumeStdoutAndStderrThroughTrailingMarkers()
{
const int lineCount = 8_000;
var (executable, arguments) = HighVolumeOutputCommand(lineCount);

var result = await CreateRunner().RunAsync(
executable,
arguments,
TimeSpan.FromSeconds(30));

Assert.False(result.TimedOut);
Assert.Equal(0, result.ExitCode);
Assert.Equal(lineCount, CountLinesStartingWith(result.Stdout, "stdout-"));
Assert.Equal(lineCount, CountLinesStartingWith(result.Stderr, "stderr-"));
Assert.EndsWith($"STDOUT_MARKER{Environment.NewLine}", result.Stdout, StringComparison.Ordinal);
Assert.EndsWith($"STDERR_MARKER{Environment.NewLine}", result.Stderr, StringComparison.Ordinal);
}

private static CommandRunner CreateRunner()
=> new(new SetupLogger(filePath: null, LogLevel.Trace));

Expand All @@ -107,6 +147,29 @@ private static (string Executable, string[] Arguments) SleepingCommand()
? ("cmd.exe", ["/d", "/s", "/c", "ping 127.0.0.1 -n 30 >nul"])
: ("/bin/sh", ["-c", "sleep 30"]);

private static (string Executable, string[] Arguments) HighVolumeOutputCommand(int lineCount)
{
if (!OperatingSystem.IsWindows())
{
var shellScript =
$"i=0; while [ $i -lt {lineCount} ]; do echo stdout-$i; echo stderr-$i >&2; i=$((i+1)); done; " +
"echo STDOUT_MARKER; echo STDERR_MARKER >&2";
return ("/bin/sh", ["-c", shellScript]);
}

var powerShellScript =
$"for ($i = 0; $i -lt {lineCount}; $i++) {{ " +
"[Console]::Out.WriteLine(\"stdout-$i\"); " +
"[Console]::Error.WriteLine(\"stderr-$i\") }; " +
"[Console]::Out.WriteLine('STDOUT_MARKER'); " +
"[Console]::Error.WriteLine('STDERR_MARKER')";
return ("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", powerShellScript]);
}

private static int CountLinesStartingWith(string value, string prefix)
=> value.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)
.Count(line => line.StartsWith(prefix, StringComparison.Ordinal));

private static (string Executable, string[] Arguments) CopyStdinCommand(string path)
{
if (!OperatingSystem.IsWindows())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,8 @@ public Task<CommandResult> RunAsync(
string? workingDirectory = null,
string? stdinInput = null,
CancellationToken ct = default,
Stream? stdinStream = null) => throw new NotSupportedException();
Stream? stdinStream = null,
bool allowInheritedPipeHandleEscape = false) => throw new NotSupportedException();

public Task<CommandResult> RunInWslAsync(
string distroName,
Expand Down
3 changes: 2 additions & 1 deletion tests/OpenClaw.SetupEngine.Tests/SetupStepsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4592,7 +4592,8 @@ public Task<CommandResult> RunAsync(
string? workingDirectory = null,
string? stdinInput = null,
CancellationToken ct = default,
Stream? stdinStream = null)
Stream? stdinStream = null,
bool allowInheritedPipeHandleEscape = false)
{
Calls.Add((executable, arguments));
TimedCalls.Add((executable, arguments, timeout));
Expand Down
Loading