Skip to content

Commit 32c1e18

Browse files
shanselmanCopilot
andcommitted
Harden pairing approval decisions
Avoid recording approvals after the operator client changes during an in-flight decision, and route stale review-pairing toast activations to Connection instead of silently no-oping. Co-authored-by: Copilot <[email protected]>
1 parent 4a2b8bb commit 32c1e18

4 files changed

Lines changed: 190 additions & 7 deletions

File tree

‎src/OpenClaw.Tray.WinUI/App.xaml.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3034,7 +3034,11 @@ private void OnPairingDecisionCompleted(object? sender, PairingDecisionResult re
30343034
private void ShowPairingApprovalDialog(bool bringToFront)
30353035
{
30363036
if (_pairingApprovalCoordinator == null) return;
3037-
if (_pairingApprovalCoordinator.Current.Count == 0) return;
3037+
if (_pairingApprovalCoordinator.Current.Count == 0)
3038+
{
3039+
ShowStatusDetail();
3040+
return;
3041+
}
30383042

30393043
if (_pairingApprovalDialog is { IsClosed: false } existing)
30403044
{

‎src/OpenClaw.Tray.WinUI/Services/PairingApprovalCoordinator.cs‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -252,14 +252,15 @@ private async Task<bool> DecideAsync(string key, bool approve)
252252
if (ok)
253253
{
254254
// Send-ack only means the frame left the socket, NOT that the gateway accepted it.
255-
// But first re-validate the connection: a disconnect may have raced the await (and
256-
// already Reset() the queue). Recording a submission now would strand a likely-dropped
257-
// frame and risk a later false confirmation, so treat it as not completed instead —
258-
// the request re-surfaces on reconnect for a clean retry.
255+
// But first re-validate the exact connection: a disconnect/reconnect may have raced
256+
// the await (and already Reset() the queue). Recording a submission against a new
257+
// client would strand a likely-dropped frame and risk a later false confirmation, so
258+
// treat it as not completed instead — the request re-surfaces on reconnect for a
259+
// clean retry.
259260
var liveClient = _getClient();
260-
if (liveClient is not { IsConnectedToGateway: true })
261+
if (!ReferenceEquals(liveClient, client) || !CanApproveWith(liveClient))
261262
{
262-
_logger.Info("[PairApproval] Connection lost during decision; not recording optimistic submission");
263+
_logger.Info("[PairApproval] Connection changed during decision; not recording optimistic submission");
263264
return false;
264265
}
265266

‎tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
<Compile Include="..\..\src\OpenClaw.Tray.WinUI\Services\GatewayNavVisibilityDebouncePolicy.cs" Link="Services\GatewayNavVisibilityDebouncePolicy.cs" />
5858
<Compile Include="..\..\src\OpenClaw.Tray.WinUI\Services\NodeInvokeActivityFormatter.cs" Link="Services\NodeInvokeActivityFormatter.cs" />
5959
<Compile Include="..\..\src\OpenClaw.Tray.WinUI\Services\NodeCapabilityGating.cs" Link="Services\NodeCapabilityGating.cs" />
60+
<Compile Include="..\..\src\OpenClaw.Tray.WinUI\Services\PairingApprovalCoordinator.cs" Link="Services\PairingApprovalCoordinator.cs" />
6061
<Compile Include="..\..\src\OpenClaw.Tray.WinUI\Services\ToastActivationRouter.cs" Link="Services\ToastActivationRouter.cs" />
6162
<Compile Include="..\..\src\OpenClaw.Tray.WinUI\Helpers\TrayTooltipFormatter.cs" Link="Helpers\TrayTooltipFormatter.cs" />
6263
<Compile Include="..\..\src\OpenClaw.Tray.WinUI\Helpers\GatewayDashboardUrlBuilder.cs" Link="Helpers\GatewayDashboardUrlBuilder.cs" />
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
using System.Text.Json;
2+
using OpenClaw.Shared;
3+
using OpenClawTray.Services;
4+
5+
namespace OpenClaw.Tray.Tests;
6+
7+
public sealed class PairingApprovalCoordinatorTests
8+
{
9+
[Fact]
10+
public async Task ApproveAsync_WhenClientChangesBeforeAck_DoesNotMarkSubmitted()
11+
{
12+
var originalClient = new FakeOperatorGatewayClient();
13+
var replacementClient = new FakeOperatorGatewayClient();
14+
var approveGate = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
15+
originalClient.DeviceApproveResult = approveGate.Task;
16+
IOperatorGatewayClient? currentClient = originalClient;
17+
var coordinator = NewCoordinator(() => currentClient);
18+
19+
coordinator.OnPairListsUpdated(Devices(Device("req-1")), null);
20+
var approval = Assert.Single(coordinator.Current);
21+
22+
var approveTask = coordinator.ApproveAsync(approval.Key);
23+
Assert.Equal(1, originalClient.DeviceApproveCalls);
24+
25+
currentClient = replacementClient;
26+
approveGate.SetResult(true);
27+
var result = await approveTask;
28+
29+
Assert.False(result);
30+
Assert.Single(coordinator.Current);
31+
Assert.Equal(0, originalClient.DeviceListRequests);
32+
Assert.Equal(0, replacementClient.DeviceListRequests);
33+
}
34+
35+
[Fact]
36+
public async Task ApproveAsync_WhenSameClientAcks_RecordsSubmissionAndRefreshesList()
37+
{
38+
var client = new FakeOperatorGatewayClient();
39+
var coordinator = NewCoordinator(() => client);
40+
41+
coordinator.OnPairListsUpdated(Devices(Device("req-1")), null);
42+
var approval = Assert.Single(coordinator.Current);
43+
44+
var result = await coordinator.ApproveAsync(approval.Key);
45+
46+
Assert.True(result);
47+
Assert.Empty(coordinator.Current);
48+
Assert.Equal(1, client.DeviceApproveCalls);
49+
Assert.Equal(1, client.DeviceListRequests);
50+
}
51+
52+
private static PairingApprovalCoordinator NewCoordinator(Func<IOperatorGatewayClient?> getClient) =>
53+
new(
54+
getClient,
55+
getOwnNodeIds: () => Array.Empty<string>(),
56+
isPromptEnabled: () => true,
57+
logger: NullLogger.Instance);
58+
59+
private static DevicePairingListInfo Devices(params DevicePairingRequest[] requests) =>
60+
new() { Pending = requests.ToList() };
61+
62+
private static DevicePairingRequest Device(string requestId) =>
63+
new()
64+
{
65+
RequestId = requestId,
66+
DeviceId = $"device-{requestId}",
67+
DisplayName = requestId,
68+
Scopes = ["operator.read"],
69+
};
70+
71+
#pragma warning disable CS0067
72+
private sealed class FakeOperatorGatewayClient : IOperatorGatewayClient
73+
{
74+
public Task<bool> DeviceApproveResult { get; set; } = Task.FromResult(true);
75+
public int DeviceApproveCalls { get; private set; }
76+
public int DeviceListRequests { get; private set; }
77+
public string? OperatorDeviceId => "operator";
78+
public IReadOnlyList<string> GrantedOperatorScopes { get; set; } = ["operator.admin"];
79+
public bool IsConnectedToGateway { get; set; } = true;
80+
public string? MainSessionKey => "main";
81+
public bool HasHandshakeSnapshot => true;
82+
83+
public event EventHandler<OpenClawNotification>? NotificationReceived;
84+
public event EventHandler<AgentActivity>? ActivityChanged;
85+
public event EventHandler<ChannelHealth[]>? ChannelHealthUpdated;
86+
public event EventHandler<SessionInfo[]>? SessionsUpdated;
87+
public event EventHandler<GatewayUsageInfo>? UsageUpdated;
88+
public event EventHandler<GatewayUsageStatusInfo>? UsageStatusUpdated;
89+
public event EventHandler<GatewayCostUsageInfo>? UsageCostUpdated;
90+
public event EventHandler<GatewayNodeInfo[]>? NodesUpdated;
91+
public event EventHandler<SessionsPreviewPayloadInfo>? SessionPreviewUpdated;
92+
public event EventHandler<SessionCommandResult>? SessionCommandCompleted;
93+
public event EventHandler<GatewaySelfInfo>? GatewaySelfUpdated;
94+
public event EventHandler<JsonElement>? CronListUpdated;
95+
public event EventHandler<JsonElement>? CronStatusUpdated;
96+
public event EventHandler<JsonElement>? CronRunsUpdated;
97+
public event EventHandler<JsonElement>? SkillsStatusUpdated;
98+
public event EventHandler<JsonElement>? ConfigUpdated;
99+
public event EventHandler<JsonElement>? ConfigSchemaUpdated;
100+
public event EventHandler<AgentEventInfo>? AgentEventReceived;
101+
public event EventHandler<PairingListInfo>? NodePairListUpdated;
102+
public event EventHandler<DevicePairingListInfo>? DevicePairListUpdated;
103+
public event EventHandler<ModelsListInfo>? ModelsListUpdated;
104+
public event EventHandler<PresenceEntry[]>? PresenceUpdated;
105+
public event EventHandler<JsonElement>? AgentsListUpdated;
106+
public event EventHandler<JsonElement>? AgentFilesListUpdated;
107+
public event EventHandler<JsonElement>? AgentFileContentUpdated;
108+
public event EventHandler<AgentEventInfo>? ChatEventReceived;
109+
public event EventHandler<ConnectionStatus>? StatusChanged;
110+
public event EventHandler<string>? AuthenticationFailed;
111+
public event EventHandler<DeviceTokenReceivedEventArgs>? DeviceTokenReceived;
112+
public event EventHandler? HandshakeSucceeded;
113+
114+
public void SetUserRules(IReadOnlyList<UserNotificationRule>? rules) { }
115+
public void SetPreferStructuredCategories(bool value) { }
116+
public Task SendChatMessageAsync(string message, string? sessionKey = null) => Task.CompletedTask;
117+
public Task<ChatSendResult> SendChatMessageForRunAsync(string message, string? sessionKey = null) => Task.FromResult(new ChatSendResult());
118+
public Task CheckHealthAsync() => Task.CompletedTask;
119+
public Task RequestSessionsAsync(string? agentId = null) => Task.CompletedTask;
120+
public Task RequestUsageAsync() => Task.CompletedTask;
121+
public Task RequestNodesAsync() => Task.CompletedTask;
122+
public Task RequestUsageStatusAsync() => Task.CompletedTask;
123+
public Task RequestUsageCostAsync(int days = 30) => Task.CompletedTask;
124+
public Task RequestSessionPreviewAsync(string[] keys, int limit = 12, int maxChars = 240) => Task.CompletedTask;
125+
public Task<bool> PatchSessionAsync(string key, string? model = null, string? thinkingLevel = null, string? verboseLevel = null) => Task.FromResult(false);
126+
public Task<bool> ResetSessionAsync(string key) => Task.FromResult(false);
127+
public Task<bool> DeleteSessionAsync(string key, bool deleteTranscript = true) => Task.FromResult(false);
128+
public Task<bool> CompactSessionAsync(string key, int maxLines = 400) => Task.FromResult(false);
129+
public Task RequestCronListAsync() => Task.CompletedTask;
130+
public Task RequestCronStatusAsync() => Task.CompletedTask;
131+
public Task<bool> RunCronJobAsync(string jobId, bool force = true) => Task.FromResult(false);
132+
public Task<bool> RemoveCronJobAsync(string jobId) => Task.FromResult(false);
133+
public Task<bool> AddCronJobAsync(object jobDefinition) => Task.FromResult(false);
134+
public Task<bool> UpdateCronJobAsync(string id, object patch) => Task.FromResult(false);
135+
public Task RequestCronRunsAsync(string? id = null, int limit = 20, int offset = 0) => Task.CompletedTask;
136+
public Task RequestSkillsStatusAsync(string? agentId = null) => Task.CompletedTask;
137+
public Task<bool> InstallSkillAsync(string skillId) => Task.FromResult(false);
138+
public Task<bool> SetSkillEnabledAsync(string skillKey, bool enabled) => Task.FromResult(false);
139+
public Task RequestConfigAsync() => Task.CompletedTask;
140+
public Task RequestConfigSchemaAsync() => Task.CompletedTask;
141+
public Task<bool> SetConfigAsync(string path, object value) => Task.FromResult(false);
142+
public Task<bool> PatchConfigAsync(JsonElement fullConfig, string? baseHash) => Task.FromResult(false);
143+
public Task<ConfigPatchResult> PatchConfigDetailedAsync(JsonElement fullConfig, string? baseHash, int timeoutMs = 15000) =>
144+
Task.FromResult(new ConfigPatchResult { Ok = false, Error = "stub" });
145+
public Task RequestAgentsListAsync() => Task.CompletedTask;
146+
public Task RequestAgentFilesListAsync(string agentId = "main") => Task.CompletedTask;
147+
public Task RequestAgentFileGetAsync(string agentId, string name) => Task.CompletedTask;
148+
public Task RequestModelsListAsync() => Task.CompletedTask;
149+
public Task RequestNodePairListAsync() => Task.CompletedTask;
150+
public Task<bool> NodePairApproveAsync(string requestId) => Task.FromResult(false);
151+
public Task<bool> NodePairRejectAsync(string requestId) => Task.FromResult(false);
152+
public Task<NodeForgetResult> NodePairRemoveAsync(string nodeId) => Task.FromResult(new NodeForgetResult(false, "stub"));
153+
public Task<NodeRenameResult> NodeRenameAsync(string nodeId, string displayName) => Task.FromResult(new NodeRenameResult(false, ErrorMessage: "stub"));
154+
public Task RequestDevicePairListAsync()
155+
{
156+
DeviceListRequests++;
157+
return Task.CompletedTask;
158+
}
159+
160+
public Task<bool> DevicePairApproveAsync(string requestId)
161+
{
162+
DeviceApproveCalls++;
163+
return DeviceApproveResult;
164+
}
165+
166+
public Task<bool> DevicePairRejectAsync(string requestId) => Task.FromResult(false);
167+
public Task<bool> StartChannelAsync(string channelName) => Task.FromResult(false);
168+
public Task<ChannelStartResult?> StartChannelDetailedAsync(string channelName, int timeoutMs = 12000) => Task.FromResult<ChannelStartResult?>(null);
169+
public Task<bool> StopChannelAsync(string channelName) => Task.FromResult(false);
170+
public Task<ChannelsStatusSnapshot?> GetChannelsStatusAsync(bool probe = false, int timeoutMs = 12000) => Task.FromResult<ChannelsStatusSnapshot?>(null);
171+
public Task<bool> LogoutChannelAsync(string channelName, int timeoutMs = 12000) => Task.FromResult(false);
172+
public Task<WebLoginStartResult?> WebLoginStartAsync(bool force = false, int timeoutMs = 30000) => Task.FromResult<WebLoginStartResult?>(null);
173+
public Task<WebLoginWaitResult?> WebLoginWaitAsync(string? currentQrDataUrl = null, int timeoutMs = 30000) => Task.FromResult<WebLoginWaitResult?>(null);
174+
public Task<JsonElement> SendWizardRequestAsync(string method, object? parameters = null, int timeoutMs = 30000) => Task.FromResult(default(JsonElement));
175+
}
176+
#pragma warning restore CS0067
177+
}

0 commit comments

Comments
 (0)