|
| 1 | +using OpenClaw.Shared; |
| 2 | +using System; |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Globalization; |
| 5 | +using System.Linq; |
| 6 | + |
| 7 | +namespace OpenClawTray.Services; |
| 8 | + |
| 9 | +internal enum TrayHealthSeverity |
| 10 | +{ |
| 11 | + Neutral, |
| 12 | + Ok, |
| 13 | + Caution, |
| 14 | + Critical, |
| 15 | +} |
| 16 | + |
| 17 | +internal sealed record TrayDashboardActiveSession( |
| 18 | + string Label, |
| 19 | + string Title, |
| 20 | + string? Detail, |
| 21 | + int ContextPercent); |
| 22 | + |
| 23 | +/// <summary> |
| 24 | +/// Pure, render-free computation for the tray dashboard glance. |
| 25 | +/// </summary> |
| 26 | +internal sealed record TrayDashboardSummary |
| 27 | +{ |
| 28 | + internal required TrayHealthSeverity Severity { get; init; } |
| 29 | + internal required string Headline { get; init; } |
| 30 | + internal required string? Endpoint { get; init; } |
| 31 | + internal required string? Heartbeat { get; init; } |
| 32 | + internal required string? MetricsLine { get; init; } |
| 33 | + internal required TrayDashboardActiveSession? ActiveSession { get; init; } |
| 34 | + |
| 35 | + internal bool HasActiveSession => ActiveSession is not null; |
| 36 | +} |
| 37 | + |
| 38 | +/// <summary> |
| 39 | +/// Builds tray dashboard summary text from a menu snapshot. |
| 40 | +/// </summary> |
| 41 | +internal sealed class TrayDashboardSummaryBuilder |
| 42 | +{ |
| 43 | + private readonly TrayMenuSnapshot _snapshot; |
| 44 | + private readonly DateTime _nowUtc; |
| 45 | + |
| 46 | + internal TrayDashboardSummaryBuilder(TrayMenuSnapshot snapshot, DateTime? nowUtc = null) |
| 47 | + { |
| 48 | + _snapshot = snapshot; |
| 49 | + _nowUtc = nowUtc ?? DateTime.UtcNow; |
| 50 | + } |
| 51 | + |
| 52 | + internal TrayDashboardSummary Build() |
| 53 | + { |
| 54 | + var isConnected = _snapshot.CurrentStatus == ConnectionStatus.Connected; |
| 55 | + |
| 56 | + var (severity, headline) = ClassifyHealth(); |
| 57 | + |
| 58 | + string? endpoint = null; |
| 59 | + if (!string.IsNullOrEmpty(_snapshot.GatewayUrl) |
| 60 | + && Uri.TryCreate(_snapshot.GatewayUrl, UriKind.Absolute, out var uri)) |
| 61 | + { |
| 62 | + endpoint = uri.IsDefaultPort ? uri.Host : $"{uri.Host}:{uri.Port}"; |
| 63 | + } |
| 64 | + |
| 65 | + return new TrayDashboardSummary |
| 66 | + { |
| 67 | + Severity = severity, |
| 68 | + Headline = headline, |
| 69 | + Endpoint = endpoint, |
| 70 | + Heartbeat = isConnected ? BuildHeartbeat() : null, |
| 71 | + MetricsLine = BuildMetricsLine(isConnected), |
| 72 | + ActiveSession = BuildActiveSession(), |
| 73 | + }; |
| 74 | + } |
| 75 | + |
| 76 | + private (TrayHealthSeverity, string) ClassifyHealth() |
| 77 | + { |
| 78 | + if (!string.IsNullOrEmpty(_snapshot.AuthFailureMessage)) |
| 79 | + return (TrayHealthSeverity.Critical, "Authentication failed"); |
| 80 | + |
| 81 | + var pending = (_snapshot.NodePairList?.Pending.Count ?? 0) |
| 82 | + + (_snapshot.DevicePairList?.Pending.Count ?? 0); |
| 83 | + if (pending > 0) |
| 84 | + return (TrayHealthSeverity.Caution, $"Pairing approval pending ({pending})"); |
| 85 | + |
| 86 | + return _snapshot.CurrentStatus switch |
| 87 | + { |
| 88 | + ConnectionStatus.Connected => (TrayHealthSeverity.Ok, "Connected"), |
| 89 | + ConnectionStatus.Connecting => (TrayHealthSeverity.Caution, "Connecting…"), |
| 90 | + ConnectionStatus.Error => (TrayHealthSeverity.Critical, "Connection error"), |
| 91 | + _ => (TrayHealthSeverity.Neutral, "Disconnected"), |
| 92 | + }; |
| 93 | + } |
| 94 | + |
| 95 | + private string? BuildHeartbeat() |
| 96 | + { |
| 97 | + if (_snapshot.LastUpdated is not { } updated) |
| 98 | + return null; |
| 99 | + |
| 100 | + var updatedUtc = updated.Kind == DateTimeKind.Utc ? updated : updated.ToUniversalTime(); |
| 101 | + var age = _nowUtc - updatedUtc; |
| 102 | + if (age < TimeSpan.Zero) age = TimeSpan.Zero; |
| 103 | + return $"Updated {FormatAge(age)}"; |
| 104 | + } |
| 105 | + |
| 106 | + private string? BuildMetricsLine(bool isConnected) |
| 107 | + { |
| 108 | + var parts = new List<string>(3); |
| 109 | + |
| 110 | + var nodesTotal = _snapshot.Nodes.Length; |
| 111 | + if (nodesTotal > 0) |
| 112 | + { |
| 113 | + var online = _snapshot.Nodes.Count(n => n.IsOnline); |
| 114 | + parts.Add($"{online}/{nodesTotal} {(nodesTotal == 1 ? "node" : "nodes")}"); |
| 115 | + } |
| 116 | + |
| 117 | + var sessionCount = _snapshot.Sessions.Length; |
| 118 | + if (sessionCount > 0) |
| 119 | + { |
| 120 | + var active = _snapshot.Sessions.Count( |
| 121 | + s => string.Equals(s.Status, "active", StringComparison.OrdinalIgnoreCase)); |
| 122 | + parts.Add(active > 0 |
| 123 | + ? $"{sessionCount} {(sessionCount == 1 ? "session" : "sessions")} ({active} active)" |
| 124 | + : $"{sessionCount} {(sessionCount == 1 ? "session" : "sessions")}"); |
| 125 | + } |
| 126 | + |
| 127 | + if (isConnected) |
| 128 | + { |
| 129 | + var usage = BuildUsageGlance(); |
| 130 | + if (usage != null) parts.Add(usage); |
| 131 | + } |
| 132 | + |
| 133 | + return parts.Count == 0 ? null : string.Join(" · ", parts); |
| 134 | + } |
| 135 | + |
| 136 | + private string? BuildUsageGlance() |
| 137 | + { |
| 138 | + var cost = FirstPositiveCost( |
| 139 | + _snapshot.Usage?.CostUsd, |
| 140 | + _snapshot.UsageCost?.Totals.TotalCost); |
| 141 | + |
| 142 | + var totalTokens = FirstPositiveTokens( |
| 143 | + _snapshot.Usage?.TotalTokens, |
| 144 | + _snapshot.UsageCost?.Totals.TotalTokens, |
| 145 | + _snapshot.Sessions.Sum(SessionUsedTokens)); |
| 146 | + |
| 147 | + if (cost <= 0 && totalTokens <= 0) |
| 148 | + return null; |
| 149 | + |
| 150 | + if (cost >= 0.005) |
| 151 | + return "$" + cost.ToString("F2", CultureInfo.InvariantCulture); |
| 152 | + return $"{FormatTokenCount(totalTokens)} tokens"; |
| 153 | + } |
| 154 | + |
| 155 | + internal static double FirstPositiveCost(params double?[] candidates) |
| 156 | + { |
| 157 | + foreach (var c in candidates) |
| 158 | + if (c is > 0) return c.Value; |
| 159 | + return 0.0; |
| 160 | + } |
| 161 | + |
| 162 | + internal static long FirstPositiveTokens(params long?[] candidates) |
| 163 | + { |
| 164 | + foreach (var c in candidates) |
| 165 | + if (c is > 0) return c.Value; |
| 166 | + return 0L; |
| 167 | + } |
| 168 | + |
| 169 | + internal static long SessionUsedTokens(SessionInfo session) => |
| 170 | + session.TotalTokens > 0 ? session.TotalTokens : session.InputTokens + session.OutputTokens; |
| 171 | + |
| 172 | + internal static SessionInfo? SelectActiveSession(IReadOnlyList<SessionInfo> sessions) |
| 173 | + { |
| 174 | + if (sessions == null || sessions.Count == 0) |
| 175 | + return null; |
| 176 | + |
| 177 | + static bool IsActive(SessionInfo s) => |
| 178 | + string.Equals(s.Status, "active", StringComparison.OrdinalIgnoreCase); |
| 179 | + |
| 180 | + var activeMain = sessions.FirstOrDefault(s => s.IsMain && IsActive(s)); |
| 181 | + if (activeMain != null) return activeMain; |
| 182 | + |
| 183 | + var activeRecent = sessions |
| 184 | + .Where(IsActive) |
| 185 | + .OrderByDescending(s => s.UpdatedAt ?? s.LastSeen) |
| 186 | + .FirstOrDefault(); |
| 187 | + if (activeRecent != null) return activeRecent; |
| 188 | + |
| 189 | + var main = sessions.FirstOrDefault(s => s.IsMain); |
| 190 | + if (main != null) return main; |
| 191 | + |
| 192 | + return sessions.OrderByDescending(s => s.UpdatedAt ?? s.LastSeen).First(); |
| 193 | + } |
| 194 | + |
| 195 | + private TrayDashboardActiveSession? BuildActiveSession() |
| 196 | + { |
| 197 | + var session = SelectActiveSession(_snapshot.Sessions); |
| 198 | + if (session == null) |
| 199 | + return null; |
| 200 | + |
| 201 | + var isActive = string.Equals(session.Status, "active", StringComparison.OrdinalIgnoreCase); |
| 202 | + var label = isActive ? "Active" : (session.IsMain ? "Main" : "Session"); |
| 203 | + |
| 204 | + var title = !string.IsNullOrWhiteSpace(session.DisplayName) |
| 205 | + ? session.DisplayName! |
| 206 | + : (session.IsMain ? "Main session" : (string.IsNullOrEmpty(session.Key) ? "Session" : session.ShortKey)); |
| 207 | + |
| 208 | + var usedTokens = SessionUsedTokens(session); |
| 209 | + var contextTokens = session.ContextTokens > 0 ? session.ContextTokens : 200_000; |
| 210 | + var pct = usedTokens > 0 |
| 211 | + ? (int)Math.Round(Math.Min(100.0, (double)usedTokens / contextTokens * 100.0)) |
| 212 | + : 0; |
| 213 | + |
| 214 | + // Detail carries only stable metadata; CurrentActivity can include |
| 215 | + // command/query/path/URL snippets and should stay out of the top-level |
| 216 | + // tray glance. |
| 217 | + var detailParts = new List<string>(1); |
| 218 | + if (!string.IsNullOrWhiteSpace(session.Model)) detailParts.Add(session.Model!); |
| 219 | + var detail = detailParts.Count == 0 ? null : string.Join(" · ", detailParts); |
| 220 | + |
| 221 | + return new TrayDashboardActiveSession( |
| 222 | + Label: label, |
| 223 | + Title: title, |
| 224 | + Detail: detail, |
| 225 | + ContextPercent: pct); |
| 226 | + } |
| 227 | + |
| 228 | + private static string FormatTokenCount(long n) |
| 229 | + { |
| 230 | + if (n >= 1_000_000) return $"{n / 1_000_000.0:F1}M"; |
| 231 | + if (n >= 1_000) return $"{n / 1_000.0:F1}K"; |
| 232 | + return n.ToString(CultureInfo.InvariantCulture); |
| 233 | + } |
| 234 | + |
| 235 | + private static string FormatAge(TimeSpan age) |
| 236 | + { |
| 237 | + if (age.TotalSeconds < 60) return $"{(int)age.TotalSeconds}s ago"; |
| 238 | + if (age.TotalMinutes < 60) return $"{(int)age.TotalMinutes}m ago"; |
| 239 | + if (age.TotalHours < 24) return $"{(int)age.TotalHours}h ago"; |
| 240 | + return $"{(int)age.TotalDays}d ago"; |
| 241 | + } |
| 242 | + |
| 243 | +} |
0 commit comments