Skip to content

Commit caa94d5

Browse files
bkudiessCopilot
andauthored
fix(tray): refetch the operator snapshot when a client swap attaches late (#2416)
The connection manager raises OperatorClientChanged before it connects the new client, but GatewayService subscribes on the UI thread. When the Gateway restart repair rebuilt the client and the UI thread lagged, the new client finished its handshake and published node.list (and health, sessions, usage, agents, Connected) with no subscriber. AppState.Nodes stayed empty, so app.nodes returned [] and NetworkRecoveryTests timed out (main run 46499427168). After subscribing to a swapped-in client that is already connected, GatewayService now requests that snapshot again and clears the stale auth failure the lost Connected status would have cleared. The normal path, where the attach runs before the connect, sends nothing extra. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 5f72553 commit caa94d5

2 files changed

Lines changed: 107 additions & 4 deletions

File tree

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

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,8 @@ public void AttachClient(IOperatorGatewayClient? newClient, IOperatorGatewayClie
7373
_state.AgentsListUnsupported = newClient?.IsAgentsListUnsupported ?? false;
7474

7575
// Clear service-level caches on actual client swap
76-
if (!ReferenceEquals(oldClient, newClient))
76+
var swapped = !ReferenceEquals(oldClient, newClient);
77+
if (swapped)
7778
{
7879
_agentIdentityRevision++;
7980
_state.AgentsList = null;
@@ -84,8 +85,36 @@ public void AttachClient(IOperatorGatewayClient? newClient, IOperatorGatewayClie
8485
_lastSessionSwitch = DateTime.MinValue;
8586
}
8687

87-
if (newClient != null)
88-
SubscribeAll(newClient);
88+
if (newClient == null)
89+
return;
90+
91+
SubscribeAll(newClient);
92+
93+
// The connection manager announces a new client before connecting it, but the swap
94+
// reaches this UI-thread method through the dispatcher. If the client finished its
95+
// handshake first, its post-handshake snapshot and Connected status were published with
96+
// no subscriber, and nothing republishes them until the next change. Fetch them again.
97+
if (swapped && newClient.IsConnectedToGateway)
98+
{
99+
_state.AuthFailureMessage = null;
100+
_ = RequestConnectedSnapshotAsync(newClient);
101+
}
102+
}
103+
104+
private static async Task RequestConnectedSnapshotAsync(IOperatorGatewayClient client)
105+
{
106+
try
107+
{
108+
await client.RequestNodesAsync();
109+
await client.CheckHealthAsync();
110+
await client.RequestSessionsAsync();
111+
await client.RequestUsageAsync();
112+
await client.RequestAgentsListAsync();
113+
}
114+
catch (Exception ex)
115+
{
116+
Logger.Warn($"[GatewayService] Snapshot refresh after a late client attach failed: {ex.Message}");
117+
}
89118
}
90119

91120
// ── Dispatcher helper ───────────────────────────────────────────────

‎tests/OpenClaw.Tray.UITests/GatewayServiceSessionPublicationTests.cs‎

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@
66

77
namespace OpenClaw.Tray.UITests;
88

9-
/// <summary>Protects the existing session array and preview cache from queued stale callbacks.</summary>
9+
/// <summary>
10+
/// Protects the existing session array and preview cache from queued stale callbacks, and
11+
/// the connected snapshot from a client swap that reaches the UI thread after the handshake.
12+
/// </summary>
1013
[Collection(UICollection.Name)]
1114
public sealed class GatewayServiceSessionPublicationTests(UIThreadFixture ui)
1215
{
@@ -19,6 +22,8 @@ public class GatewayProxy : DispatchProxy
1922
private readonly Dictionary<string, Delegate?> _handlers = new();
2023
public long? Epoch = 7;
2124
public bool Connected = true;
25+
public readonly List<string> Requests = new();
26+
public GatewayNodeInfo[]? NodeListReply;
2227

2328
protected override object? Invoke(MethodInfo? targetMethod, object?[]? args)
2429
{
@@ -38,12 +43,81 @@ public class GatewayProxy : DispatchProxy
3843
"get_IsConnectedToGateway" => Connected,
3944
"get_IsAgentsListUnsupported" => false,
4045
"RequestSessionPreviewAsync" => Task.CompletedTask,
46+
"RequestSessionsAsync" or "RequestUsageAsync" or "RequestAgentsListAsync" or "CheckHealthAsync" => Record(name),
47+
"RequestNodesAsync" => ReplyToNodeList(),
4148
_ => throw new NotSupportedException(name),
4249
};
4350
}
4451

52+
private Task Record(string name)
53+
{
54+
Requests.Add(name);
55+
return Task.CompletedTask;
56+
}
57+
58+
private Task ReplyToNodeList()
59+
{
60+
Record("RequestNodesAsync");
61+
// Replies arrive on a socket thread and reach AppState through the dispatcher queue.
62+
// A dedicated thread keeps delivery independent of thread-pool load.
63+
if (NodeListReply is { } nodes)
64+
{
65+
var socket = new Thread(() => RaiseNodes(nodes)) { IsBackground = true };
66+
socket.Start();
67+
if (!socket.Join(DispatchDeadline))
68+
throw new TimeoutException("node.list reply was not delivered");
69+
}
70+
return Task.CompletedTask;
71+
}
72+
4573
public void RaiseSessions(SessionInfo[] rows) =>
4674
((EventHandler<SessionInfo[]>?)_handlers.GetValueOrDefault("SessionsUpdated"))?.Invoke(this, rows);
75+
76+
public void RaiseNodes(GatewayNodeInfo[] nodes) =>
77+
((EventHandler<GatewayNodeInfo[]>?)_handlers.GetValueOrDefault("NodesUpdated"))?.Invoke(this, nodes);
78+
}
79+
80+
[Fact]
81+
public async Task LateAttachToConnectedClient_RecoversTheNodeSnapshotPublishedBeforeSubscription()
82+
{
83+
// Gateway restart repair rebuilds the operator client. It can finish its handshake and
84+
// publish node.list before the UI-dispatched swap subscribes (main run 46499427168).
85+
var client = DispatchProxy.Create<IOperatorGatewayClient, GatewayProxy>();
86+
var wire = (GatewayProxy)client;
87+
GatewayNodeInfo[] nodes = [new() { NodeId = "node-1", IsOnline = true, CapabilityCount = 10 }];
88+
wire.NodeListReply = nodes;
89+
AppState state = null!;
90+
GatewayService service = null!;
91+
try
92+
{
93+
await ui.RunOnUIAsync(() =>
94+
{
95+
state = new AppState(ui.Dispatcher) { AuthFailureMessage = "stale" };
96+
service = new GatewayService(state, ui.Dispatcher);
97+
service.AttachClient(client, null);
98+
});
99+
await ui.RunOnUIAsync(() =>
100+
{
101+
Assert.Same(nodes, state.Nodes);
102+
Assert.Null(state.AuthFailureMessage);
103+
});
104+
// The snapshot requests run on the UI thread inside AttachClient.
105+
Assert.Equivalent(
106+
new[] { "RequestNodesAsync", "CheckHealthAsync", "RequestSessionsAsync", "RequestUsageAsync", "RequestAgentsListAsync" },
107+
wire.Requests,
108+
strict: true);
109+
110+
// A client that is not connected yet publishes its own snapshot after subscription.
111+
var pending = DispatchProxy.Create<IOperatorGatewayClient, GatewayProxy>();
112+
((GatewayProxy)pending).Connected = false;
113+
await ui.RunOnUIAsync(() => service.AttachClient(pending, client));
114+
client = pending;
115+
Assert.Empty(((GatewayProxy)pending).Requests);
116+
}
117+
finally
118+
{
119+
if (service is not null) await ui.RunOnUIAsync(() => service.AttachClient(null, client));
120+
}
47121
}
48122

49123
[Theory]

0 commit comments

Comments
 (0)