|
| 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 | +} |
0 commit comments