Skip to content

Commit a2ff988

Browse files
shanselmanCopilot
andcommitted
fix: bound all keepalive command-line inspections
Co-authored-by: Copilot App <[email protected]>
1 parent 2a2cac6 commit a2ff988

4 files changed

Lines changed: 121 additions & 25 deletions

File tree

‎src/OpenClaw.Connection/WindowsTcpListenerSnapshot.cs‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,11 @@ public static WindowsTcpListenerSnapshotResult Capture()
5656
var output = AwaitRedirectedOutput(process, readTask, timeoutMs: 5_000);
5757
return output?.Trim();
5858
}
59-
catch
59+
catch (Exception ex)
6060
{
61+
Trace.WriteLine(
62+
$"Windows process command-line lookup failed for PID {processId}: " +
63+
$"{ex.GetType().Name}: {ex.Message}");
6164
return null;
6265
}
6366
}
@@ -75,8 +78,10 @@ public static WindowsTcpListenerSnapshotResult Capture()
7578
var sw = Stopwatch.StartNew();
7679
if (!process.WaitForExit(timeoutMs))
7780
{
81+
Trace.WriteLine(
82+
$"Windows process command-line lookup timed out waiting for PID {process.Id}.");
7883
try { process.Kill(entireProcessTree: true); } catch { }
79-
ObserveQuietly(readTask);
84+
AbandonRead(process, readTask);
8085
return null;
8186
}
8287

@@ -86,8 +91,10 @@ public static WindowsTcpListenerSnapshotResult Capture()
8691
{
8792
if (!readTask.Wait(drainBudgetMs))
8893
{
94+
Trace.WriteLine(
95+
$"Windows process command-line lookup timed out draining PID {process.Id} stdout.");
8996
try { process.Kill(entireProcessTree: true); } catch { }
90-
ObserveQuietly(readTask);
97+
AbandonRead(process, readTask);
9198
return null;
9299
}
93100
}
@@ -99,6 +106,12 @@ public static WindowsTcpListenerSnapshotResult Capture()
99106
return readTask.Status == TaskStatus.RanToCompletion ? readTask.Result : null;
100107
}
101108

109+
private static void AbandonRead(Process process, Task readTask)
110+
{
111+
ObserveQuietly(readTask);
112+
try { process.StandardOutput.Dispose(); } catch { }
113+
}
114+
102115
private static void ObserveQuietly(Task task) =>
103116
_ = task.ContinueWith(
104117
static t => { _ = t.Exception; },

‎src/OpenClaw.SetupEngine/KeepaliveProcessRuntime.cs‎

Lines changed: 6 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System.Diagnostics;
2+
using OpenClaw.Connection;
23

34
namespace OpenClaw.SetupEngine;
45

@@ -19,9 +20,7 @@ internal interface IKeepaliveProcessRuntime
1920

2021
/// <summary>
2122
/// Best-effort command-line lookup for a PID. Returns null if the process is gone or the
22-
/// lookup otherwise fails to produce a value. May throw for exceptional OS failures — callers
23-
/// in <see cref="KeepaliveProcessManager"/> catch per-call so one failure doesn't abort a
24-
/// broader scan.
23+
/// lookup otherwise fails to produce a value. The production runtime does not throw.
2524
/// </summary>
2625
string? GetCommandLine(int pid);
2726

@@ -48,9 +47,8 @@ internal sealed record KeepaliveProcessStartSpec(string FileName, IReadOnlyList<
4847

4948
/// <summary>
5049
/// Production <see cref="IKeepaliveProcessRuntime"/> backed by <see cref="System.Diagnostics.Process"/>
51-
/// and a WMI/CIM command-line lookup via a spawned <c>powershell.exe</c> helper (unchanged from the
52-
/// pre-extraction inline implementation). Every <see cref="Process"/> wrapper obtained here is
53-
/// disposed before the method returns.
50+
/// and the shared bounded WMI/CIM command-line lookup. Every <see cref="Process"/> wrapper obtained
51+
/// here is disposed before the method returns.
5452
/// </summary>
5553
internal sealed class ProcessKeepaliveRuntime : IKeepaliveProcessRuntime
5654
{
@@ -60,21 +58,8 @@ public bool IsProcessAlive(int pid)
6058
return !process.HasExited;
6159
}
6260

63-
public string? GetCommandLine(int pid)
64-
{
65-
var psi = new ProcessStartInfo("powershell.exe",
66-
$"-NoProfile -Command \"(Get-CimInstance Win32_Process -Filter 'ProcessId={pid}').CommandLine\"")
67-
{
68-
RedirectStandardOutput = true,
69-
UseShellExecute = false,
70-
CreateNoWindow = true
71-
};
72-
using var p = Process.Start(psi);
73-
if (p == null) return null;
74-
var output = p.StandardOutput.ReadToEnd();
75-
p.WaitForExit(5000);
76-
return output.Trim();
77-
}
61+
public string? GetCommandLine(int pid) =>
62+
WindowsTcpListenerSnapshot.GetProcessCommandLine(pid);
7863

7964
public IReadOnlyList<int> EnumerateProcessIds(string processName)
8065
{

‎tests/OpenClaw.Connection.Tests/WindowsTcpListenerSnapshotTests.cs‎

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,84 @@ public async Task AwaitRedirectedOutput_ReturnsNullWhenStdoutNeverCloses()
2424
});
2525
Assert.NotNull(process);
2626

27-
var never = new TaskCompletionSource<string>().Task;
27+
var never = new TaskCompletionSource<string>(
28+
TaskCreationOptions.RunContinuationsAsynchronously).Task;
2829
var helper = Task.Run(() =>
2930
WindowsTcpListenerSnapshot.AwaitRedirectedOutput(process, never, timeoutMs: 400));
3031

3132
var completed = await Task.WhenAny(helper, Task.Delay(TimeSpan.FromSeconds(3)));
3233
Assert.Same(helper, completed);
3334
Assert.Null(await helper);
3435
}
36+
37+
[Fact]
38+
public void AwaitRedirectedOutput_PreservesOutputCompletedDuringDrainGrace()
39+
{
40+
using var process = StartExitingProcess();
41+
Assert.True(process.WaitForExit(3_000));
42+
var outputTask = Task.Run(async () =>
43+
{
44+
await Task.Delay(100);
45+
return "complete output";
46+
});
47+
48+
var output = WindowsTcpListenerSnapshot.AwaitRedirectedOutput(
49+
process,
50+
outputTask,
51+
timeoutMs: 400);
52+
53+
Assert.Equal("complete output", output);
54+
}
55+
56+
[Fact]
57+
public async Task AwaitRedirectedOutput_ReturnsNullWhenDescendantKeepsStdoutOpen()
58+
{
59+
var (fileName, arguments) = DescendantPipeHolderCommand();
60+
using var process = Process.Start(new ProcessStartInfo
61+
{
62+
FileName = fileName,
63+
Arguments = arguments,
64+
RedirectStandardOutput = true,
65+
UseShellExecute = false,
66+
CreateNoWindow = true,
67+
});
68+
Assert.NotNull(process);
69+
70+
var readTask = process.StandardOutput.ReadToEndAsync();
71+
var stopwatch = Stopwatch.StartNew();
72+
var output = WindowsTcpListenerSnapshot.AwaitRedirectedOutput(
73+
process,
74+
readTask,
75+
timeoutMs: 400);
76+
77+
Assert.Null(output);
78+
Assert.InRange(stopwatch.Elapsed, TimeSpan.Zero, TimeSpan.FromSeconds(2));
79+
await readTask.WaitAsync(TimeSpan.FromSeconds(5));
80+
}
81+
82+
[Fact]
83+
public void GetProcessCommandLine_CurrentProcess_IsBoundedOnWindows()
84+
{
85+
if (!OperatingSystem.IsWindows())
86+
return;
87+
88+
var stopwatch = Stopwatch.StartNew();
89+
_ = WindowsTcpListenerSnapshot.GetProcessCommandLine(Environment.ProcessId);
90+
91+
Assert.InRange(stopwatch.Elapsed, TimeSpan.Zero, TimeSpan.FromSeconds(7));
92+
}
93+
94+
private static Process StartExitingProcess() =>
95+
Process.Start(new ProcessStartInfo
96+
{
97+
FileName = OperatingSystem.IsWindows() ? "cmd.exe" : "/bin/sh",
98+
Arguments = OperatingSystem.IsWindows() ? "/d /c exit 0" : "-c \"exit 0\"",
99+
UseShellExecute = false,
100+
CreateNoWindow = true,
101+
})!;
102+
103+
private static (string FileName, string Arguments) DescendantPipeHolderCommand() =>
104+
OperatingSystem.IsWindows()
105+
? ("cmd.exe", "/d /s /c \"start /b ping 127.0.0.1 -n 3\"")
106+
: ("/bin/sh", "-c \"sleep 2 & exit 0\"");
35107
}

‎tests/OpenClaw.Tray.Tests/ConnectionRegressionSourceTests.cs‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,32 @@ public void SetupKeepaliveRuntime_DisposesProcessWrapperAfterStartingDetachedPro
160160
"return proc?.Id;");
161161
}
162162

163+
[Fact]
164+
public void SetupKeepaliveRuntime_UsesSharedBoundedCommandLineLookup()
165+
{
166+
var source = ReadSource("src", "OpenClaw.SetupEngine", "KeepaliveProcessRuntime.cs");
167+
168+
Assert.Contains(
169+
"WindowsTcpListenerSnapshot.GetProcessCommandLine(pid)",
170+
source);
171+
Assert.DoesNotContain("StandardOutput.ReadToEnd", source);
172+
}
173+
174+
[Fact]
175+
public void TrayKeepaliveService_UsesSharedBoundedCommandLineLookup()
176+
{
177+
var source = ReadSource(
178+
"src",
179+
"OpenClaw.Tray.WinUI",
180+
"Services",
181+
"WslGatewayKeepAliveService.cs");
182+
183+
Assert.Contains(
184+
"WindowsTcpListenerSnapshot.GetProcessCommandLine(pid)",
185+
source);
186+
Assert.DoesNotContain("StandardOutput.ReadToEnd", source);
187+
}
188+
163189
[Fact]
164190
public void SetupKeepaliveManager_WritesMarkerAfterSuccessfulStart()
165191
{

0 commit comments

Comments
 (0)