Skip to content

Commit 294ef17

Browse files
fix(setup): propagate caller cancellation through node pairing instead of reporting Timeout/Failed
When a user cancels setup while the node-pairing step waits to connect, the cancellation was misreported: WaitForNodeConnection caught every OperationCanceledException and returned NodeConnectionOutcome.Timeout, and even once that propagated, PairNodeStep.ExecuteAsync's catch-all re-swallowed the OCE into StepResult.Fail. So the pipeline reported Failed (or a Timeout message) rather than Cancelled for a user-driven abort. Two-layer fix, both following the file's existing cancel-rethrow idiom: - WaitForNodeConnection: guard the Timeout mapping with when (!ct.IsCancellationRequested) so only the internal CancelAfter(timeout) firing is a Timeout. - PairNodeStep.ExecuteAsync: add catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } ahead of the catch-all so a caller cancel propagates and the pipeline maps it to PipelineOutcome.Cancelled (exit 3), not Failed. Tests (both red before / green after): - SetupNodeConnectCancellationTests: helper emits OCE on caller cancel, not Timeout. - SetupStepsTests.PairNodeStep_CallerCancellation_PropagatesInsteadOfFailing: drives the real PairNodeStep to its node wait (fake reachability + approval drain, silent WS server) and asserts the cancel propagates as OCE, not a swallowed StepResult.Fail.
1 parent 9fb1960 commit 294ef17

7 files changed

Lines changed: 254 additions & 1 deletion

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
"sha": "c4da82f06b0eeb2e7aad0c9c6d3eed72ef63bc44",
3+
"tree": "83c4b487b239e9be29d4e8a179e63d9349b4eb9f",
4+
"repo": "openclaw-windows-node",
5+
"branch": "fix/setup-node-connect-cancel-provenance",
6+
"required": [
7+
"base_check",
8+
"autoreview",
9+
"ci",
10+
"proof",
11+
"concurrency",
12+
"local_clawsweeper",
13+
"review_log",
14+
"pr_body"
15+
],
16+
"gates": {
17+
"base_check": {
18+
"status": "ok",
19+
"ts": "2026-07-17T13:53:16Z",
20+
"detail": ""
21+
}
22+
},
23+
"approved": false,
24+
"approved_ts": null
25+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
0bdbede425c116811993f71fed9816b9

‎src/OpenClaw.SetupEngine/SetupSteps.cs‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2257,6 +2257,13 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
22572257

22582258
return StepResult.Fail($"Node connection failed: {outcome.Outcome}");
22592259
}
2260+
catch (OperationCanceledException) when (ct.IsCancellationRequested)
2261+
{
2262+
// Let a caller-driven cancel propagate so the pipeline reports Cancelled,
2263+
// not a Failed step — the catch-all below would otherwise convert it back
2264+
// into StepResult.Fail (same idiom as the other steps' cancel rethrow).
2265+
throw;
2266+
}
22602267
catch (Exception ex)
22612268
{
22622269
return StepResult.Fail($"Node pairing failed: {ex.Message}", ex);
@@ -2387,8 +2394,11 @@ void OnPairingStatusChanged(object? sender, PairingStatusEventArgs args)
23872394
cts.CancelAfter(timeout);
23882395
return await tcs.Task.WaitAsync(cts.Token);
23892396
}
2390-
catch (OperationCanceledException)
2397+
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
23912398
{
2399+
// Only the internal CancelAfter(timeout) firing is a Timeout; a caller
2400+
// (user aborting setup) cancelling `ct` must propagate so the pipeline
2401+
// reports Cancelled, rather than being misreported as a node timeout.
23922402
return new NodeConnectionResult(NodeConnectionOutcome.Timeout);
23932403
}
23942404
finally

‎tests/OpenClaw.SetupEngine.Tests/OpenClaw.SetupEngine.Tests.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
<ItemGroup>
44
<ProjectReference Include="..\..\src\OpenClaw.SetupEngine\OpenClaw.SetupEngine.csproj" />
5+
<ProjectReference Include="..\OpenClaw.TestSupport\OpenClaw.TestSupport.csproj" />
56
</ItemGroup>
67

78
</Project>
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
using System;
2+
using System.Diagnostics;
3+
using System.IO;
4+
using System.Linq;
5+
using System.Reflection;
6+
using System.Threading;
7+
using System.Threading.Tasks;
8+
using OpenClaw.Shared;
9+
using OpenClaw.TestSupport;
10+
using Xunit;
11+
using Xunit.Abstractions;
12+
13+
namespace OpenClaw.SetupEngine.Tests;
14+
15+
/// <summary>
16+
/// Regression: WaitForNodeConnection must not report a caller-driven cancellation as a
17+
/// connection <see cref="NodeConnectionOutcome.Timeout"/>. The method links the caller's
18+
/// token with an internal CancelAfter(timeout); only the internal timeout firing is a
19+
/// Timeout, while the caller cancelling (user aborting setup) must propagate. Before the
20+
/// fix this test is red: the method returns Timeout ~0.3s into a 15s window.
21+
/// </summary>
22+
public sealed class SetupNodeConnectCancellationTests : IDisposable
23+
{
24+
private readonly ITestOutputHelper _output;
25+
private readonly string _dataDir;
26+
27+
public SetupNodeConnectCancellationTests(ITestOutputHelper output)
28+
{
29+
_output = output;
30+
_dataDir = Path.Combine(Path.GetTempPath(), "setup-cancel-" + Guid.NewGuid().ToString("N"));
31+
Directory.CreateDirectory(_dataDir);
32+
}
33+
34+
public void Dispose()
35+
{
36+
try { Directory.Delete(_dataDir, recursive: true); } catch { /* best effort */ }
37+
}
38+
39+
[Fact]
40+
public async Task WaitForNodeConnection_CallerCancellation_PropagatesInsteadOfTimeout()
41+
{
42+
// Completes the WS upgrade then stays silent, so the node client parks in the wait.
43+
using var server = new SilentWebSocketServer();
44+
45+
var logger = new SetupLogger(filePath: null, LogLevel.Trace);
46+
var ctx = new SetupContext(
47+
new SetupConfig(), logger, new TransactionJournal(filePath: null),
48+
new CommandRunner(logger), CancellationToken.None,
49+
dataDir: _dataDir, localDataDir: _dataDir);
50+
51+
using var client = new WindowsNodeClient(
52+
$"ws://127.0.0.1:{server.Port}", "test-token-placeholder", _dataDir);
53+
54+
var method = typeof(SetupStep).Assembly.GetTypes()
55+
.SelectMany(t => t.GetMethods(BindingFlags.NonPublic | BindingFlags.Static))
56+
.Single(m => m.Name == "WaitForNodeConnection");
57+
58+
// Caller cancels 300ms in; the method's own timeout window is 15s, so an outcome
59+
// of "Timeout" is provably a misclassification of the caller's cancellation.
60+
using var callerCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
61+
var sw = Stopwatch.StartNew();
62+
var task = (Task)method.Invoke(null,
63+
new object[] { client, ctx, TimeSpan.FromSeconds(15), callerCts.Token })!;
64+
65+
try
66+
{
67+
await task.WaitAsync(TimeSpan.FromSeconds(30));
68+
sw.Stop();
69+
var result = task.GetType().GetProperty("Result")!.GetValue(task)!;
70+
var outcome = result.GetType().GetProperty("Outcome")!.GetValue(result)!.ToString();
71+
_output.WriteLine($"completed with Outcome={outcome} after {sw.ElapsedMilliseconds}ms (timeout window 15000ms)");
72+
Assert.Fail(
73+
$"Caller cancellation was misclassified: returned Outcome={outcome} after {sw.ElapsedMilliseconds}ms " +
74+
"with the 15s timeout never elapsed and the caller's token cancelled. Expected OperationCanceledException.");
75+
}
76+
catch (OperationCanceledException)
77+
{
78+
sw.Stop();
79+
_output.WriteLine($"caller cancellation propagated after {sw.ElapsedMilliseconds}ms");
80+
}
81+
}
82+
}

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

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using OpenClaw.Connection;
2+
using OpenClaw.TestSupport;
23
using System.Net;
34
using System.Net.Sockets;
45
using System.Runtime.InteropServices;
@@ -2195,6 +2196,64 @@ private SetupContext CreatePairingContext(string failureStdout)
21952196
return ctx;
21962197
}
21972198

2199+
// Regression for the caller-cancellation propagation fix: drive the REAL PairNodeStep to its
2200+
// node-connection wait (past reachability + approval-drain), cancel the caller token mid-wait,
2201+
// and assert the cancellation propagates as an OperationCanceledException — NOT swallowed by the
2202+
// step's catch-all into StepResult.Fail (which the pipeline would map to Failed, not Cancelled).
2203+
[Fact]
2204+
public async Task PairNodeStep_CallerCancellation_PropagatesInsteadOfFailing()
2205+
{
2206+
// Reachability HTTP endpoint on GatewayPort so WindowsGatewayReachability.VerifyAsync passes.
2207+
var httpPort = GetFreeTcpPort();
2208+
using var http = new HttpListener();
2209+
http.Prefixes.Add($"http://localhost:{httpPort}/");
2210+
http.Start();
2211+
_ = Task.Run(async () =>
2212+
{
2213+
while (http.IsListening)
2214+
{
2215+
HttpListenerContext c;
2216+
try { c = await http.GetContextAsync(); }
2217+
catch { return; }
2218+
c.Response.StatusCode = 200;
2219+
c.Response.Close();
2220+
}
2221+
});
2222+
2223+
// A WebSocket server that completes the upgrade then stays silent, so the node client
2224+
// connects and WaitForNodeConnection parks in its timeout wait — the state the caller cancels.
2225+
using var ws = new SilentWebSocketServer();
2226+
2227+
// Fake WSL runner: the approval drain sees "No pending" and returns immediately.
2228+
var commands = new FakeCommandRunner(
2229+
_ => Ok(),
2230+
(_, _, _) => Ok(stdout: "No pending device approvals"));
2231+
2232+
var ctx = CreateContext(new SetupConfig { GatewayPort = httpPort }, commands);
2233+
ctx.DistroName = "test-distro";
2234+
ctx.SharedGatewayToken = "test-token-placeholder";
2235+
ctx.GatewayUrl = $"ws://127.0.0.1:{ws.Port}";
2236+
ctx.GatewayRecordId = "test-gw";
2237+
2238+
var registry = new GatewayRegistry(_tempDir);
2239+
registry.Load();
2240+
registry.AddOrUpdate(new GatewayRecord
2241+
{
2242+
Id = "test-gw",
2243+
Url = ctx.GatewayUrl,
2244+
IsLocal = true,
2245+
SetupManagedDistroName = ctx.DistroName,
2246+
SshTunnel = null,
2247+
});
2248+
registry.Save();
2249+
2250+
// Caller cancels 300 ms in; the node wait window is 15 s, so a Timeout/Fail outcome would be
2251+
// a misclassification. Before the fix the step returns StepResult.Fail; after, the OCE propagates.
2252+
using var callerCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
2253+
await Assert.ThrowsAnyAsync<OperationCanceledException>(
2254+
() => new PairNodeStep().ExecuteAsync(ctx, callerCts.Token));
2255+
}
2256+
21982257
private sealed class FakeCommandRunner(
21992258
Func<string[], CommandResult> run,
22002259
Func<string, string, TimeSpan, CommandResult>? runInWsl = null) : ICommandRunner
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
using System.Net;
2+
using System.Net.Sockets;
3+
using System.Security.Cryptography;
4+
using System.Text;
5+
6+
namespace OpenClaw.TestSupport;
7+
8+
/// <summary>
9+
/// Loopback WebSocket server that completes the upgrade handshake and then stays
10+
/// silent — the client connects successfully but never receives a message, so code
11+
/// that waits for a gateway challenge/response parks in its wait. Lets a test drive
12+
/// the real <c>ClientWebSocket</c> connect path and then exercise cancellation while
13+
/// the wait is in flight, without any running gateway. Shared single source so the
14+
/// helper can't drift across test projects.
15+
/// </summary>
16+
public sealed class SilentWebSocketServer : IDisposable
17+
{
18+
private readonly TcpListener _listener;
19+
private readonly CancellationTokenSource _cts = new();
20+
21+
/// <summary>The loopback port the server is listening on (use as <c>ws://127.0.0.1:{Port}</c>).</summary>
22+
public int Port { get; }
23+
24+
public SilentWebSocketServer()
25+
{
26+
_listener = new TcpListener(IPAddress.Loopback, 0);
27+
_listener.Start();
28+
Port = ((IPEndPoint)_listener.LocalEndpoint).Port;
29+
_ = AcceptLoopAsync();
30+
}
31+
32+
private async Task AcceptLoopAsync()
33+
{
34+
while (!_cts.IsCancellationRequested)
35+
{
36+
TcpClient tcp;
37+
try { tcp = await _listener.AcceptTcpClientAsync(_cts.Token); }
38+
catch { return; }
39+
_ = HandleAsync(tcp);
40+
}
41+
}
42+
43+
private async Task HandleAsync(TcpClient tcp)
44+
{
45+
try
46+
{
47+
var stream = tcp.GetStream();
48+
var buf = new byte[16384];
49+
var sb = new StringBuilder();
50+
while (!sb.ToString().Contains("\r\n\r\n"))
51+
{
52+
var n = await stream.ReadAsync(buf, _cts.Token);
53+
if (n <= 0) return;
54+
sb.Append(Encoding.ASCII.GetString(buf, 0, n));
55+
}
56+
var key = sb.ToString().Split("\r\n")
57+
.FirstOrDefault(l => l.StartsWith("Sec-WebSocket-Key:", StringComparison.OrdinalIgnoreCase))
58+
?.Split(':', 2)[1].Trim();
59+
var accept = Convert.ToBase64String(SHA1.HashData(
60+
Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")));
61+
var resp = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n" +
62+
"Connection: Upgrade\r\nSec-WebSocket-Accept: " + accept + "\r\n\r\n";
63+
await stream.WriteAsync(Encoding.ASCII.GetBytes(resp), _cts.Token);
64+
await Task.Delay(Timeout.Infinite, _cts.Token);
65+
}
66+
catch { /* torn down with the test */ }
67+
finally { try { tcp.Dispose(); } catch { } }
68+
}
69+
70+
public void Dispose()
71+
{
72+
_cts.Cancel();
73+
_listener.Stop();
74+
}
75+
}

0 commit comments

Comments
 (0)