using CommunityToolkit.Mvvm.ComponentModel; using FinalToken.Core; namespace FinalToken.App; public enum HistoryRange { Hours24, Days7, Days30, Days90, All } public sealed record ChartValue(DateTimeOffset Time, string Series, double Value, double? Expected = null, bool BreakBefore = false, double CacheRead = 0); public sealed record BreakdownRow(string Name, TokenCounts Counts, double Share, IReadOnlyList? Providers = null); public sealed record LimitChart(string Label, IReadOnlyList Values, Provider Provider = Provider.Claude, DateTimeOffset? Since = null, ChartValue? Forecast = null, ChartValue? ForecastStart = null, LimitEstimate? Analysis = null, WindowSnapshot? Window = null, DateTimeOffset Now = default); public sealed record LimitDetail(Provider Provider, string Id, RateForecast? Recent, WindowDays? Days, DateTimeOffset? Since = null); public sealed record HistoryView(IReadOnlyList Hourly, IReadOnlyList Daily, IReadOnlyList Limits, IReadOnlyList Models, IReadOnlyList Projects) { public IReadOnlyList Details { get; init; } = []; } public partial class PanelViewModel : ObservableObject { [ObservableProperty] private Snapshot? snapshot; [ObservableProperty] private HistoryRange range = HistoryRange.Days7; [ObservableProperty] private Provider? providerFilter; [ObservableProperty] private HistoryView history = new([], [], [], [], []); [ObservableProperty] private IReadOnlyList diagnostics = []; [ObservableProperty] private string message = "Reading local CLI data…"; [ObservableProperty] private bool includeCacheReads = true; [ObservableProperty] private bool refreshing; public async Task RefreshAsync(Func refresh) { if (Refreshing) return; Refreshing = true; try { await refresh(); } finally { Refreshing = false; } } public TimeSpan ProbeInterval { get; set; } = TimeSpan.FromMinutes(5); public static DateTimeOffset RangeStart(HistoryRange range, DateTimeOffset now) => range switch { HistoryRange.Hours24 => now.AddHours(-24), HistoryRange.Days7 => now.AddDays(-7), HistoryRange.Days30 => now.AddDays(-30), HistoryRange.Days90 => now.AddDays(-90), _ => DateTimeOffset.MinValue }; // D5: queries return copies; the caller runs this on a worker thread. public static HistoryView QueryHistory(HistoryStore store, Snapshot snapshot, HistoryRange range, Provider? filter, DateTimeOffset now) { var from = RangeStart(range, now); var providers = snapshot.Providers.Where(p => filter is null || p.Provider == filter).ToArray(); var hourly = Series(SeriesInterval.Hour); var daily = Series(SeriesInterval.Day); var details = new List(); var limits = providers.SelectMany(p => p.Windows.Select(w => { var samples = store.LimitSamples(p.Provider, w.Window.Id, from, now); var instanceSamples = store.LimitSamples(p.Provider, w.Window.Id, w.Window.ResetsAt is { } r && w.Window.Length is { } l ? r - l * 9 - TimeSpan.FromMinutes(15) : now.AddDays(-14), now); var tokens = w.Window.ResetsAt is { } tokenReset && w.Window.Length is { } tokenLength ? store.TokenSeriesByModel(p.Provider, tokenReset - tokenLength * 9 - TimeSpan.FromMinutes(15), now, SeriesInterval.Hour) : []; var analysis = LimitAnalysis.Analyze(w.Window, instanceSamples, tokens, now); details.Add(new(p.Provider, w.Window.Id, LimitAnalysis.Recent(w.Window, instanceSamples, now, w.Pace), analysis?.Days, instanceSamples.Where(s => LimitAnalysis.SameInstance(s, w.Window)).Select(s => s.SampleTime).DefaultIfEmpty(w.Window.SampleTime).Min())); return new LimitChart($"{p.Provider} · {w.Window.Label}", samples.Select((s, i) => new ChartValue(s.SampleTime, p.Provider.ToString(), s.UsedPercent, Pace.Calculate(s, s.SampleTime).ElapsedFraction * 100, i > 0 && !LimitAnalysis.SameInstance(s, samples[i - 1]))).ToArray(), p.Provider, samples.FirstOrDefault()?.SampleTime ?? instanceSamples.FirstOrDefault()?.SampleTime ?? w.Window.SampleTime, w.Pace.Projection is { } projection ? new(projection, p.Provider.ToString(), 100) : w.Window.ResetsAt is { } reset && LimitAnalysis.AverageUseAtReset(w.Window, now, w.Pace) is { } average ? new(reset, p.Provider.ToString(), average) : null, new(now, p.Provider.ToString(), w.Window.UsedPercent), analysis, w, now); })).ToArray(); var models = Breakdown(true); var projects = Breakdown(false); return new(hourly, daily, limits, models, projects) { Details = details }; IReadOnlyList Series(SeriesInterval interval) { if (filter is null) return providers.SelectMany(p => store.TokenSeries(p.Provider, from, now, interval) .Select(point => new ChartValue(point.Time, p.Provider.ToString(), point.Counts.Total, CacheRead: point.Counts.CacheRead))).ToArray(); var points = store.TokenSeriesByModel(filter.Value, from, now, interval); var names = points.Select(p => p.Model ?? "Unknown model").Distinct().Order(StringComparer.Ordinal).Take(6).ToHashSet(); return points.GroupBy(p => (p.Time, Name: names.Contains(p.Model ?? "Unknown model") ? p.Model ?? "Unknown model" : "Other")) .Select(g => new ChartValue(g.Key.Time, g.Key.Name, g.Sum(p => (double)p.Counts.Total), CacheRead: g.Sum(p => (double)p.Counts.CacheRead))).ToArray(); } IReadOnlyList Breakdown(bool models) { var rows = providers.SelectMany(p => (models ? store.ByModel(p.Provider, from, now) : store.ByProject(p.Provider, from, now)) .Select(r => (p.Provider, r.Name, r.Counts))) .GroupBy(r => r.Name ?? "Unknown").Select(g => new BreakdownRow(g.Key, g.Aggregate(new TokenCounts(), (sum, r) => sum + r.Counts), 0, g.Select(r => r.Provider).Distinct().Order().ToArray())).OrderByDescending(r => r.Counts.Total).ToArray(); var total = rows.Sum(r => (double)r.Counts.Total); return rows.Select(r => r with { Share = total == 0 ? 0 : r.Counts.Total / total }).ToArray(); } } } public static class Display { public static string? ForecastWaiting(WindowSnapshot window, DateTimeOffset now, TimeProvider? clock = null) => window.Pace.State != PaceState.Unknown && !Pace.CanForecast(window.Window, now, window.Pace) && Pace.ForecastStartsAt(window.Window) is { } start && start > now ? "Forecast from " + Projection(start, clock) : null; public static string ChartDateLabel(DateTimeOffset time, TimeSpan interval) => ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "MM-dd" : "MM-dd HH:mm"); public static string ChartTimestamp(DateTimeOffset time, TimeSpan interval) => ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "d" : "g"); private static DateTime ChartTime(DateTimeOffset time, TimeSpan interval) => interval >= TimeSpan.FromDays(1) ? time.DateTime : time.LocalDateTime; public static string Projection(DateTimeOffset projection, TimeProvider? clock = null, System.Globalization.CultureInfo? culture = null) { clock ??= TimeProvider.System; var local = TimeZoneInfo.ConvertTime(projection, clock.LocalTimeZone); return local.ToString(local.Date == clock.GetLocalNow().Date ? "t" : "g", culture ?? System.Globalization.CultureInfo.CurrentCulture); } public static string Time(DateTimeOffset time, TimeProvider? clock = null) => TimeZoneInfo.ConvertTime(time, (clock ?? TimeProvider.System).LocalTimeZone).ToString("t"); public static string Duration(TimeSpan span) => span <= TimeSpan.Zero ? "now" : span.TotalDays >= 1 ? $"{(int)span.TotalDays} d {span.Hours} h" : span.TotalHours >= 1 ? $"{(int)span.TotalHours} h {span.Minutes} min" : $"{Math.Ceiling(span.TotalMinutes):0} min"; public static string Span(TimeSpan span) => span.TotalHours >= 1 ? $"{span.TotalHours:0.#} h" : $"{span.TotalMinutes:0} min"; public static string Tokens(TokenCounts? counts) => counts is { } c ? $"{c.Total:N0} total · input {c.Input:N0} · cache read {c.CacheRead:N0} · cache write {c.CacheWrite:N0} · output {c.Output:N0} · reasoning {c.ReasoningOutput:N0}" : "Unavailable — no known session window"; public static string Compact(double count) => CompactNumber(count, false); public static string Axis(double count) => CompactNumber(count, true); private static string CompactNumber(double count, bool trimTrailingZeros) { var unit = Math.Abs(count) >= 1e9 ? 3 : Math.Abs(count) >= 1e6 ? 2 : Math.Abs(count) >= 1000 ? 1 : 0; if (unit == 0) return count.ToString("0"); var value = count / Math.Pow(1000, unit); var decimals = Math.Max(0, 2 - (int)Math.Floor(Math.Log10(Math.Abs(value)))); value = Math.Round(value, decimals, MidpointRounding.AwayFromZero); if (Math.Abs(value) >= 1000 && unit < 3) { value /= 1000; unit++; } decimals = Math.Max(0, 2 - (int)Math.Floor(Math.Log10(Math.Abs(value)))); var format = trimTrailingZeros ? decimals == 0 ? "0" : "0." + new string('#', decimals) : "F" + decimals; return value.ToString(format) + new[] { "", " K", " M", " B" }[unit]; } public static string Forecast(DateTimeOffset date, PaceState state, TimeProvider? clock = null) => (state == PaceState.Ahead ? "⚠ " : "At this pace ") + "100 % on " + Projection(date, clock); public static string State(PaceState state) => state switch { PaceState.OnTrack => "✓ On track", PaceState.Ahead => "▲ Ahead", PaceState.Behind => "▼ Behind", _ => "? Pace unknown" }; }