Skip to content

Commit 9b5ce4b

Browse files
authored
fix: wizard shutdown no longer reports a timeout (#1018)
* fix: preserve wizard cancellation on client shutdown Co-authored-by: Copilot App <[email protected]> Copilot-Session: ef1a489e-d0db-416e-a8da-ac6184e5f6af * test: strengthen wizard request race coverage Co-authored-by: Copilot App <[email protected]> Copilot-Session: ef1a489e-d0db-416e-a8da-ac6184e5f6af
1 parent ee4817d commit 9b5ce4b

4 files changed

Lines changed: 210 additions & 10 deletions

File tree

‎src/OpenClaw.Shared/OpenClawGatewayClient.cs‎

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -621,22 +621,17 @@ public async Task<JsonElement> SendWizardRequestAsync(string method, object? par
621621
try
622622
{
623623
await SendRawAsync(SerializeRequest(requestId, method, parameters));
624+
return await completion.Task.WaitAsync(TimeSpan.FromMilliseconds(timeoutMs), CancellationToken);
624625
}
625-
catch
626+
catch (TimeoutException ex)
626627
{
627-
_pendingWizardResponses.TryRemove(requestId, out _);
628-
RemovePendingRequest(requestId);
629-
throw;
628+
throw new TimeoutException($"Timed out waiting for {method} response", ex);
630629
}
631-
632-
var completedTask = await Task.WhenAny(completion.Task, Task.Delay(timeoutMs, CancellationToken));
633-
if (completedTask != completion.Task)
630+
finally
634631
{
635632
_pendingWizardResponses.TryRemove(requestId, out _);
636-
throw new TimeoutException($"Timed out waiting for {method} response");
633+
RemovePendingRequest(requestId);
637634
}
638-
639-
return await completion.Task;
640635
}
641636

642637
/// <summary>Request session list from gateway.</summary>

‎tests/OpenClaw.Shared.Tests/OpenClaw.Shared.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.Shared\OpenClaw.Shared.csproj" />
5+
<ProjectReference Include="..\OpenClaw.TestSupport\OpenClaw.TestSupport.csproj" />
56
</ItemGroup>
67

78
<ItemGroup>

‎tests/OpenClaw.Shared.Tests/OpenClawGatewayClientTests.cs‎

Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Text.Json;
66
using Xunit;
77
using OpenClaw.Shared;
8+
using OpenClaw.TestSupport;
89

910
namespace OpenClaw.Shared.Tests;
1011

@@ -487,11 +488,189 @@ public List<string> CaptureAuthenticationFailedEvents()
487488
_client.AuthenticationFailed += (_, msg) => events.Add(msg);
488489
return events;
489490
}
491+
492+
public (int WizardResponses, int RequestMethods) GetPendingRequestCounts()
493+
{
494+
var wizardField = typeof(OpenClawGatewayClient).GetField(
495+
"_pendingWizardResponses",
496+
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
497+
var wizardResponses =
498+
(System.Collections.Concurrent.ConcurrentDictionary<string, TaskCompletionSource<JsonElement>>)wizardField!.GetValue(_client)!;
499+
500+
var methodsField = typeof(OpenClawGatewayClient).GetField(
501+
"_pendingRequestMethods",
502+
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
503+
var requestMethods = (Dictionary<string, string>)methodsField!.GetValue(_client)!;
504+
505+
return (wizardResponses.Count, requestMethods.Count);
506+
}
490507
}
491508

492509
private static string CreateTempIdentityPath() =>
493510
Path.Combine(Path.GetTempPath(), "OpenClawGatewayClientTests", Guid.NewGuid().ToString("N"));
494511

512+
[Fact]
513+
public async Task SendWizardRequestAsync_ResponseBeforeDispose_ReturnsPayloadAndCleansTracking()
514+
{
515+
using var server = new LoopbackWebSocketServer();
516+
using var identity = new TempDirectory("wizard-request-");
517+
await server.StartAsync();
518+
var helper = new GatewayClientTestHelper(
519+
gatewayUrl: server.WebSocketUrl,
520+
identityPath: identity.Path);
521+
using var client = helper.Client;
522+
await client.ConnectAsync();
523+
524+
var responseTask = client.SendWizardRequestAsync("wizard.start", timeoutMs: 10_000);
525+
var request = await server.ReceiveTextAsync().WaitAsync(TimeSpan.FromSeconds(2));
526+
var requestId = ReadRequestId(request);
527+
528+
await server.SendTextAsync(
529+
JsonSerializer.Serialize(new
530+
{
531+
type = "res",
532+
id = requestId,
533+
ok = true,
534+
payload = new { stepId = "welcome" }
535+
}));
536+
537+
var payload = await responseTask.WaitAsync(TimeSpan.FromSeconds(2));
538+
539+
Assert.Equal("welcome", payload.GetProperty("stepId").GetString());
540+
Assert.Equal((0, 0), helper.GetPendingRequestCounts());
541+
542+
client.Dispose();
543+
Assert.Equal((0, 0), helper.GetPendingRequestCounts());
544+
}
545+
546+
[Fact]
547+
public async Task SendWizardRequestAsync_GatewayError_PropagatesUnchangedAndCleansTracking()
548+
{
549+
using var server = new LoopbackWebSocketServer();
550+
using var identity = new TempDirectory("wizard-request-");
551+
await server.StartAsync();
552+
var helper = new GatewayClientTestHelper(
553+
gatewayUrl: server.WebSocketUrl,
554+
identityPath: identity.Path);
555+
using var client = helper.Client;
556+
await client.ConnectAsync();
557+
558+
var responseTask = client.SendWizardRequestAsync("wizard.next", timeoutMs: 10_000);
559+
var request = await server.ReceiveTextAsync().WaitAsync(TimeSpan.FromSeconds(2));
560+
var requestId = ReadRequestId(request);
561+
562+
await server.SendTextAsync(
563+
JsonSerializer.Serialize(new
564+
{
565+
type = "res",
566+
id = requestId,
567+
ok = false,
568+
error = new { message = "wizard rejected" }
569+
}));
570+
571+
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
572+
async () => await responseTask.WaitAsync(TimeSpan.FromSeconds(2)));
573+
574+
Assert.Equal("wizard rejected", exception.Message);
575+
Assert.Equal((0, 0), helper.GetPendingRequestCounts());
576+
}
577+
578+
[Fact]
579+
public async Task SendWizardRequestAsync_DeadlineExpires_ThrowsTimeoutAndCleansTracking()
580+
{
581+
using var server = new LoopbackWebSocketServer();
582+
using var identity = new TempDirectory("wizard-request-");
583+
await server.StartAsync();
584+
var helper = new GatewayClientTestHelper(
585+
gatewayUrl: server.WebSocketUrl,
586+
identityPath: identity.Path);
587+
using var client = helper.Client;
588+
await client.ConnectAsync();
589+
590+
var responseTask = client.SendWizardRequestAsync("wizard.status", timeoutMs: 250);
591+
await server.ReceiveTextAsync().WaitAsync(TimeSpan.FromSeconds(2));
592+
593+
var exception = await Assert.ThrowsAsync<TimeoutException>(async () => await responseTask);
594+
595+
Assert.Equal("Timed out waiting for wizard.status response", exception.Message);
596+
Assert.Equal((0, 0), helper.GetPendingRequestCounts());
597+
}
598+
599+
[Fact]
600+
public async Task SendWizardRequestAsync_LateResponseAfterTimeout_DoesNotChangeOutcomeOrTracking()
601+
{
602+
using var server = new LoopbackWebSocketServer();
603+
using var identity = new TempDirectory("wizard-request-");
604+
await server.StartAsync();
605+
var helper = new GatewayClientTestHelper(
606+
gatewayUrl: server.WebSocketUrl,
607+
identityPath: identity.Path);
608+
using var client = helper.Client;
609+
await client.ConnectAsync();
610+
611+
var timedOutTask = client.SendWizardRequestAsync("wizard.status", timeoutMs: 250);
612+
var timedOutRequest = await server.ReceiveTextAsync().WaitAsync(TimeSpan.FromSeconds(2));
613+
var timedOutRequestId = ReadRequestId(timedOutRequest);
614+
var firstTimeout = await Assert.ThrowsAsync<TimeoutException>(async () => await timedOutTask);
615+
616+
await server.SendTextAsync(
617+
JsonSerializer.Serialize(new
618+
{
619+
type = "res",
620+
id = timedOutRequestId,
621+
ok = true,
622+
payload = new { stepId = "too-late" }
623+
}));
624+
625+
var probeTask = client.SendWizardRequestAsync("wizard.status", timeoutMs: 10_000);
626+
var probeRequest = await server.ReceiveTextAsync().WaitAsync(TimeSpan.FromSeconds(2));
627+
var probeRequestId = ReadRequestId(probeRequest);
628+
await server.SendTextAsync(
629+
JsonSerializer.Serialize(new
630+
{
631+
type = "res",
632+
id = probeRequestId,
633+
ok = true,
634+
payload = new { stepId = "probe" }
635+
}));
636+
637+
var probePayload = await probeTask.WaitAsync(TimeSpan.FromSeconds(2));
638+
var repeatedTimeout = await Assert.ThrowsAsync<TimeoutException>(async () => await timedOutTask);
639+
640+
Assert.Equal("probe", probePayload.GetProperty("stepId").GetString());
641+
Assert.Same(firstTimeout, repeatedTimeout);
642+
Assert.Equal((0, 0), helper.GetPendingRequestCounts());
643+
}
644+
645+
[Fact]
646+
public async Task SendWizardRequestAsync_DisposeBeforeResponse_ThrowsCancellationAndCleansTracking()
647+
{
648+
using var server = new LoopbackWebSocketServer();
649+
using var identity = new TempDirectory("wizard-request-");
650+
await server.StartAsync();
651+
var helper = new GatewayClientTestHelper(
652+
gatewayUrl: server.WebSocketUrl,
653+
identityPath: identity.Path);
654+
using var client = helper.Client;
655+
await client.ConnectAsync();
656+
657+
var responseTask = client.SendWizardRequestAsync("wizard.cancel", timeoutMs: 10_000);
658+
await server.ReceiveTextAsync().WaitAsync(TimeSpan.FromSeconds(2));
659+
660+
client.Dispose();
661+
662+
await Assert.ThrowsAnyAsync<OperationCanceledException>(
663+
async () => await responseTask.WaitAsync(TimeSpan.FromSeconds(2)));
664+
Assert.Equal((0, 0), helper.GetPendingRequestCounts());
665+
}
666+
667+
private static string ReadRequestId(string request)
668+
{
669+
using var document = JsonDocument.Parse(request);
670+
return document.RootElement.GetProperty("id").GetString()
671+
?? throw new InvalidOperationException("Gateway request did not include an id.");
672+
}
673+
495674
[Fact]
496675
public void ExtractChatTimestampMs_FallsBackFromInvalidTimestampToTs()
497676
{

‎tests/OpenClaw.Shared.Tests/WebSocketClientBaseTests.cs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Linq;
55
using System.Net;
66
using System.Net.WebSockets;
7+
using System.Text;
78
using System.Threading;
89
using System.Threading.Tasks;
910
using Xunit;
@@ -522,6 +523,8 @@ internal sealed class LoopbackWebSocketServer : IDisposable
522523
private readonly HttpListener _listener = new();
523524
private readonly CancellationTokenSource _cts = new();
524525
private readonly List<WebSocket> _acceptedSockets = new();
526+
private readonly TaskCompletionSource<WebSocket> _firstAcceptedSocket =
527+
new(TaskCreationOptions.RunContinuationsAsynchronously);
525528
private Task? _acceptLoop;
526529

527530
public string WebSocketUrl { get; }
@@ -581,9 +584,31 @@ private async Task AcceptLoopAsync()
581584
{
582585
_acceptedSockets.Add(wsContext.WebSocket);
583586
}
587+
_firstAcceptedSocket.TrySetResult(wsContext.WebSocket);
584588
}
585589
}
586590

591+
public async Task<string> ReceiveTextAsync(CancellationToken cancellationToken = default)
592+
{
593+
var socket = await _firstAcceptedSocket.Task.WaitAsync(cancellationToken);
594+
var buffer = new byte[64 * 1024];
595+
var result = await socket.ReceiveAsync(buffer, cancellationToken);
596+
if (result.MessageType != WebSocketMessageType.Text || !result.EndOfMessage)
597+
throw new InvalidOperationException("Expected one complete WebSocket text message.");
598+
599+
return Encoding.UTF8.GetString(buffer, 0, result.Count);
600+
}
601+
602+
public async Task SendTextAsync(string message, CancellationToken cancellationToken = default)
603+
{
604+
var socket = await _firstAcceptedSocket.Task.WaitAsync(cancellationToken);
605+
await socket.SendAsync(
606+
Encoding.UTF8.GetBytes(message),
607+
WebSocketMessageType.Text,
608+
endOfMessage: true,
609+
cancellationToken);
610+
}
611+
587612
public async Task CloseSocketAsync(int index)
588613
{
589614
WebSocket socket;

0 commit comments

Comments
 (0)