Skip to content

Commit 9f4d238

Browse files
bkudiessCopilot
andauthored
Port mismerged MXC and pairing approval work to main
Ports the MXC probe/SDK 0.7.0 work and inbound pairing approval dialog from the mistaken master branch target onto main. Maintainer repair included: - Preserving non-actionable handling for ambiguous legacy pairing fallback IDs in the new approval queue. - Adding regression coverage for device and node fallback ambiguity. - Version-stamping MXC SDK restore so stale node_modules cannot satisfy the 0.7.0 port. Validation: - Local .\build.ps1 passed. - Local Shared tests passed: 2411 passed / 29 skipped. - Local Tray tests passed: 1127 passed. - Local Connection tests passed: 373 passed. - GitHub CI passed on repaired head 7be0688: test, E2E setup-connect, E2E revocation-recovery, E2E network-recovery, build win-x64, build win-arm64, repo-hygiene. Co-authored-by: Copilot <[email protected]>
1 parent e7ef271 commit 9f4d238

42 files changed

Lines changed: 3280 additions & 156 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/CONNECTION_ARCHITECTURE.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,12 @@ Setup codes (from QR scan or paste) decode to `{ url, bootstrapToken }` via `Set
168168

169169
**Approval boundaries**: `GatewayConnectionManager` leaves node-pair command-trust requests and reapproval pending for explicit operator approval. It may automatically approve and reconnect only an explicitly typed device-pair request used for a device role upgrade.
170170

171+
## Inbound pairing approval (operator)
172+
173+
When **another** device or node requests pairing, the gateway broadcasts `device.pair.requested` / `node.pair.requested` to operators with pairing scope. `OpenClawGatewayClient` refreshes the pending lists and raises `DevicePairListUpdated` / `NodePairListUpdated`, which `GatewayService` forwards via its `PairListsChanged` event.
174+
175+
`PairingApprovalCoordinator` (tray) reconciles those snapshots through the pure `PairingApprovalQueue` (OpenClaw.Connection) into add/resolve deltas, de-duplicating, suppressing already-decided requests, and filtering out the local node's own pending request (handled by the auto-approve path above). For genuinely new requests — when `ShowPairingApprovalDialog` is enabled and the operator holds pairing scope — it raises `ApprovalRequested`, and the app presents a focused **`PairingApprovalDialog`** plus an awareness toast (with a "Review" action). The dialog shows the requester's identity and the **operator scopes being granted** (mapped to friendly text by `PairingScopeDescriptions`), with Approve / Reject / Decide-later. Approve is briefly disabled on each new request to prevent click-through. Approve/Reject call the `IOperatorGatewayClient.{Device,Node}Pair{Approve,Reject}Async` RPCs; the queue advances and the dialog closes when empty. The existing Connections-page "Pending approvals" banner remains as the passive fallback when the dialog is disabled. Pure queue/scope logic is unit-tested in `OpenClaw.Connection.Tests`.
176+
171177
## SSH tunnel integration
172178

173179
`SshTunnelService` manages an SSH local port-forward process. `SshTunnelManager` wraps it behind `ISshTunnelManager` for the connection manager.

‎package-lock.json‎

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,6 @@
44
"private": true,
55
"description": "MXC sandbox dependency used by the OpenClaw tray build to copy wxc-exec.exe into the app output.",
66
"dependencies": {
7-
"@microsoft/mxc-sdk": "^0.6.1"
7+
"@microsoft/mxc-sdk": "^0.7.0"
88
}
99
}
Lines changed: 241 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,241 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using OpenClaw.Shared;
5+
6+
namespace OpenClaw.Connection;
7+
8+
/// <summary>A pairing decision the gateway has now confirmed by removing it from the pending list.</summary>
9+
public sealed record PairingApprovalResolution(PendingApproval Approval, bool Approved);
10+
11+
/// <summary>The result of reconciling a fresh pair-list snapshot against prior state.</summary>
12+
public sealed class PairingApprovalDelta
13+
{
14+
/// <summary>Requests that are newly surfaced and prompt-worthy (not previously known, not awaiting resolution).</summary>
15+
public IReadOnlyList<PendingApproval> Added { get; init; } = Array.Empty<PendingApproval>();
16+
17+
/// <summary>Keys (<see cref="PendingApproval.Key"/>) that were present last time but have now left the list.</summary>
18+
public IReadOnlyList<string> ResolvedKeys { get; init; } = Array.Empty<string>();
19+
20+
/// <summary>
21+
/// Decisions the local user submitted that the gateway has now confirmed (the request left the
22+
/// pending list). These — not the send-ack — are the source of truth for "approved/rejected".
23+
/// </summary>
24+
public IReadOnlyList<PairingApprovalResolution> ConfirmedDecisions { get; init; } = Array.Empty<PairingApprovalResolution>();
25+
26+
/// <summary>All currently actionable pending approvals (excludes ones awaiting resolution).</summary>
27+
public IReadOnlyList<PendingApproval> Current { get; init; } = Array.Empty<PendingApproval>();
28+
29+
public bool HasChanges => Added.Count > 0 || ResolvedKeys.Count > 0 || ConfirmedDecisions.Count > 0;
30+
}
31+
32+
/// <summary>
33+
/// Pure, UI-agnostic diff engine for inbound pairing approvals. Translates successive
34+
/// device/node pair-list snapshots (the gateway re-sends the full list on every
35+
/// <c>*.pair.requested</c>/<c>*.pair.resolved</c> event) into add/resolve deltas the
36+
/// presentation layer can act on without re-prompting for requests it has already shown
37+
/// or that are awaiting resolution of a submitted decision.
38+
///
39+
/// Responsibilities:
40+
/// <list type="bullet">
41+
/// <item>Merge device + node pending lists into a single ordered queue (oldest first). A null
42+
/// list for a kind means "no update for that kind" (its prior entries are carried forward),
43+
/// NOT "that kind is now empty" — so a partial snapshot never silently drops or confirms.</item>
44+
/// <item>Filter out the local node's own pairing request (handled by the auto-approve path)
45+
/// so the operator is never prompted to approve their own machine. Matches against any of
46+
/// the node's advertised identifiers (device id and/or gateway node id).</item>
47+
/// <item>Drop entries with no usable id and legacy fallback-id collisions that cannot be
48+
/// approved/rejected unambiguously, then de-duplicate by <see cref="PendingApproval.Key"/>.</item>
49+
/// <item>Treat a submitted approve/reject as <em>optimistic-pending</em> — suppress it from the
50+
/// actionable set, but only report it <see cref="PairingApprovalDelta.ConfirmedDecisions">
51+
/// confirmed</see> once the gateway actually drops it from a provided list for that kind. If
52+
/// the gateway never acts within <see cref="SubmissionResolveTimeoutMs"/>, re-surface the
53+
/// request so a lost decision is retried rather than hidden forever.</item>
54+
/// </list>
55+
/// Not thread-safe; the coordinator marshals all calls onto a single dispatcher thread.
56+
/// </summary>
57+
public sealed class PairingApprovalQueue
58+
{
59+
/// <summary>How long a submitted-but-unresolved decision is suppressed before it is re-surfaced.</summary>
60+
public const long SubmissionResolveTimeoutMs = 10_000;
61+
62+
private readonly Dictionary<string, PendingApproval> _current = new(StringComparer.Ordinal);
63+
private readonly Dictionary<string, Submission> _submitted = new(StringComparer.Ordinal);
64+
65+
private readonly record struct Submission(PendingApproval Approval, bool Approved, long SubmittedAtMs);
66+
67+
/// <summary>Snapshot of currently actionable approvals, oldest first.</summary>
68+
public IReadOnlyList<PendingApproval> Current =>
69+
_current.Values
70+
.Where(a => !_submitted.ContainsKey(a.Key))
71+
.OrderBy(a => a.Ts)
72+
.ThenBy(a => a.Key, StringComparer.Ordinal)
73+
.ToArray();
74+
75+
/// <summary>True when there are no actionable approvals.</summary>
76+
public bool IsEmpty => Current.Count == 0;
77+
78+
/// <summary>
79+
/// Reconcile a fresh snapshot. <paramref name="ownNodeDeviceIds"/>, when provided, filters out the
80+
/// local Windows node's own pending node request (matched against any advertised id).
81+
/// <paramref name="nowMs"/> is a monotonic timestamp (e.g. <see cref="Environment.TickCount64"/>)
82+
/// used to expire stale submissions. A null <paramref name="devices"/> or <paramref name="nodes"/>
83+
/// means that kind has no fresh snapshot: its existing entries are carried forward and its
84+
/// submissions are neither confirmed nor expired this round.
85+
/// </summary>
86+
public PairingApprovalDelta Reconcile(
87+
DevicePairingListInfo? devices,
88+
PairingListInfo? nodes,
89+
IReadOnlyCollection<string>? ownNodeDeviceIds = null,
90+
long nowMs = 0)
91+
{
92+
var devicesProvided = devices is not null;
93+
var nodesProvided = nodes is not null;
94+
bool KindProvided(PairingApprovalKind kind) =>
95+
kind == PairingApprovalKind.DevicePair ? devicesProvided : nodesProvided;
96+
97+
var incoming = BuildIncoming(devices, nodes, ownNodeDeviceIds);
98+
var ambiguousFallbackKeys = FindAmbiguousFallbackKeys(incoming);
99+
if (ambiguousFallbackKeys.Count > 0)
100+
incoming = incoming.Where(a => !ambiguousFallbackKeys.Contains(a.Key)).ToList();
101+
102+
var incomingByKey = new Dictionary<string, PendingApproval>(StringComparer.Ordinal);
103+
foreach (var item in incoming)
104+
incomingByKey[item.Key] = item; // last wins on duplicate ids
105+
106+
// Carry forward prior entries whose kind had NO fresh snapshot — a missing list is "no
107+
// update", not "now empty", so we never drop or resolve a kind we didn't actually hear about.
108+
foreach (var kv in _current)
109+
if (!KindProvided(kv.Value.Kind) && !incomingByKey.ContainsKey(kv.Key))
110+
incomingByKey[kv.Key] = kv.Value;
111+
112+
// If a legacy fallback id becomes ambiguous, cancel any optimistic wait instead of treating
113+
// its absence from the actionable queue as a confirmed gateway decision.
114+
foreach (var key in _submitted.Keys.Where(ambiguousFallbackKeys.Contains).ToArray())
115+
_submitted.Remove(key);
116+
117+
// Confirmed resolutions: decisions we submitted whose request has now left a PROVIDED list.
118+
// This — not the send-ack — is the authoritative "the gateway accepted it" signal.
119+
var confirmed = new List<PairingApprovalResolution>();
120+
foreach (var sub in _submitted.Values)
121+
if (KindProvided(sub.Approval.Kind) && !incomingByKey.ContainsKey(sub.Approval.Key))
122+
confirmed.Add(new PairingApprovalResolution(sub.Approval, sub.Approved));
123+
foreach (var c in confirmed)
124+
_submitted.Remove(c.Approval.Key);
125+
126+
// Expire submissions the gateway hasn't acted on in time (in a provided list) → drop
127+
// suppression so they re-surface (a lost/rejected decision is retried, not hidden forever).
128+
var expired = _submitted
129+
.Where(kv => KindProvided(kv.Value.Approval.Kind)
130+
&& incomingByKey.ContainsKey(kv.Key)
131+
&& nowMs - kv.Value.SubmittedAtMs >= SubmissionResolveTimeoutMs)
132+
.Select(kv => kv.Key)
133+
.ToArray();
134+
foreach (var k in expired)
135+
_submitted.Remove(k);
136+
var expiredSet = new HashSet<string>(expired, StringComparer.Ordinal);
137+
138+
// Added: genuinely new requests, plus expired-and-re-surfaced ones. Skip anything still
139+
// awaiting resolution.
140+
var added = new List<PendingApproval>();
141+
var seen = new HashSet<string>(StringComparer.Ordinal);
142+
foreach (var item in incoming)
143+
{
144+
if (_submitted.ContainsKey(item.Key)) continue; // awaiting resolution
145+
if (_current.ContainsKey(item.Key) && !expiredSet.Contains(item.Key)) continue; // already known
146+
if (!seen.Add(item.Key)) continue;
147+
added.Add(item);
148+
}
149+
150+
var resolvedKeys = _current.Keys
151+
.Where(key => !incomingByKey.ContainsKey(key))
152+
.ToArray();
153+
154+
// Swap in the new snapshot (includes carried-forward entries for non-provided kinds).
155+
_current.Clear();
156+
foreach (var kvp in incomingByKey)
157+
_current[kvp.Key] = kvp.Value;
158+
159+
return new PairingApprovalDelta
160+
{
161+
Added = added,
162+
ResolvedKeys = resolvedKeys,
163+
ConfirmedDecisions = confirmed,
164+
Current = Current,
165+
};
166+
}
167+
168+
/// <summary>
169+
/// Record that the local user submitted an approve/reject for a request. The request is suppressed
170+
/// from the actionable set (so the UI advances) but remains tracked until the gateway confirms by
171+
/// dropping it from the pending list, or until <see cref="SubmissionResolveTimeoutMs"/> elapses.
172+
/// </summary>
173+
public void MarkSubmitted(PendingApproval approval, bool approved, long nowMs)
174+
{
175+
if (approval is null || string.IsNullOrEmpty(approval.Key))
176+
return;
177+
_submitted[approval.Key] = new Submission(approval, approved, nowMs);
178+
}
179+
180+
/// <summary>Look up a currently-actionable approval by its key (excludes ones awaiting resolution).</summary>
181+
public PendingApproval? Find(string key) =>
182+
!_submitted.ContainsKey(key) && _current.TryGetValue(key, out var value) ? value : null;
183+
184+
/// <summary>Clears all state (e.g. on disconnect / gateway switch).</summary>
185+
public void Reset()
186+
{
187+
_current.Clear();
188+
_submitted.Clear();
189+
}
190+
191+
private static List<PendingApproval> BuildIncoming(
192+
DevicePairingListInfo? devices,
193+
PairingListInfo? nodes,
194+
IReadOnlyCollection<string>? ownNodeDeviceIds)
195+
{
196+
var list = new List<PendingApproval>();
197+
198+
if (devices?.Pending is { Count: > 0 })
199+
{
200+
foreach (var req in devices.Pending)
201+
{
202+
var approval = PendingApproval.FromDevice(req);
203+
if (approval.IsActionable)
204+
list.Add(approval);
205+
}
206+
}
207+
208+
if (nodes?.Pending is { Count: > 0 })
209+
{
210+
foreach (var req in nodes.Pending)
211+
{
212+
var approval = PendingApproval.FromNode(req);
213+
if (!approval.IsActionable) continue;
214+
if (IsOwnNode(approval, ownNodeDeviceIds)) continue;
215+
list.Add(approval);
216+
}
217+
}
218+
219+
return list;
220+
}
221+
222+
private static HashSet<string> FindAmbiguousFallbackKeys(IEnumerable<PendingApproval> incoming)
223+
{
224+
var ambiguous = incoming
225+
.GroupBy(a => a.Key, StringComparer.Ordinal)
226+
.Where(g => g.Count() > 1 && g.Any(a => string.IsNullOrEmpty(a.RequestId)))
227+
.Select(g => g.Key);
228+
229+
return new HashSet<string>(ambiguous, StringComparer.Ordinal);
230+
}
231+
232+
private static bool IsOwnNode(PendingApproval approval, IReadOnlyCollection<string>? ownNodeDeviceIds)
233+
{
234+
if (ownNodeDeviceIds is null || ownNodeDeviceIds.Count == 0) return false;
235+
if (string.IsNullOrEmpty(approval.DeviceId)) return false;
236+
foreach (var id in ownNodeDeviceIds)
237+
if (!string.IsNullOrWhiteSpace(id) && approval.DeviceId.Equals(id, StringComparison.OrdinalIgnoreCase))
238+
return true;
239+
return false;
240+
}
241+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
5+
namespace OpenClaw.Connection;
6+
7+
/// <summary>
8+
/// Maps gateway operator scope identifiers to short, human-readable descriptions so a person
9+
/// approving a pairing request understands what access they are granting — mirroring the
10+
/// friendly scope list shown by the macOS pairing prompt.
11+
///
12+
/// Returns canonical English fallbacks; the presentation layer may override any entry with a
13+
/// localized resource keyed by scope before falling back to <see cref="Describe"/>.
14+
/// </summary>
15+
public static class PairingScopeDescriptions
16+
{
17+
private static readonly IReadOnlyDictionary<string, string> Map =
18+
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
19+
{
20+
["operator.admin"] = "Admin access",
21+
["operator.read"] = "Read OpenClaw data",
22+
["operator.write"] = "Send messages and make changes",
23+
["operator.approvals"] = "Manage approvals",
24+
["operator.pairing"] = "Pair and repair devices",
25+
["operator.talk.secrets"] = "Use Talk credentials",
26+
};
27+
28+
/// <summary>True when a friendly description exists for the scope; false for unknown scopes.</summary>
29+
public static bool IsKnown(string scope) =>
30+
!string.IsNullOrWhiteSpace(scope) && Map.ContainsKey(scope.Trim());
31+
32+
/// <summary>
33+
/// Returns a friendly description for a scope, or the raw scope string (trimmed) when unknown
34+
/// so the approver still sees exactly what was requested rather than nothing.
35+
/// </summary>
36+
public static string Describe(string scope)
37+
{
38+
if (string.IsNullOrWhiteSpace(scope)) return string.Empty;
39+
var trimmed = scope.Trim();
40+
return Map.TryGetValue(trimmed, out var friendly) ? friendly : trimmed;
41+
}
42+
43+
/// <summary>Describes a set of scopes, dropping blanks and de-duplicating while preserving order.</summary>
44+
public static IReadOnlyList<string> DescribeAll(IEnumerable<string>? scopes)
45+
{
46+
if (scopes == null) return Array.Empty<string>();
47+
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
48+
var result = new List<string>();
49+
foreach (var scope in scopes)
50+
{
51+
if (string.IsNullOrWhiteSpace(scope)) continue;
52+
if (!seen.Add(scope.Trim())) continue;
53+
result.Add(Describe(scope));
54+
}
55+
return result;
56+
}
57+
}

0 commit comments

Comments
 (0)