app: redesign the panel and add limit forecasts and daily week use (#6)
Redesign the stats panel after the developer's feedback on v1 and add limit forecasts, daily week use and token-based estimates (D7, D8). - Panel: a fixed header with range and provider controls, limit tiles with pace chips, meters and forecasts, week use per day, token KPIs and charts, one burn-up chart per limit window with past instances, and a sortable breakdown whose "Other" row expands. One tooltip component for every chart, tile and table. - Core (D7): average and recent-rate forecasts, the reach date whenever use is over pace, days of a long window with even pace and daily budget, window instances derived from resets with a 15-minute tolerance, and estimates from price-weighted tokens where samples are missing. Forecasts start at 10 % of a window, or as soon as it is ahead, so a Codex week far ahead right after its reset warns too. - Settings, popups and the version (1.1.0) follow the new design. Closes #5 Closes #7
This commit was merged in pull request #6.
This commit is contained in:
@@ -4,11 +4,17 @@ 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);
|
||||
public sealed record BreakdownRow(string Name, TokenCounts Counts, double Share);
|
||||
public sealed record LimitChart(string Label, IReadOnlyList<ChartValue> Values);
|
||||
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<Provider>? Providers = null);
|
||||
public sealed record LimitChart(string Label, IReadOnlyList<ChartValue> 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<ChartValue> Hourly, IReadOnlyList<ChartValue> Daily,
|
||||
IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> Projects);
|
||||
IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> Projects)
|
||||
{
|
||||
public IReadOnlyList<LimitDetail> Details { get; init; } = [];
|
||||
}
|
||||
|
||||
public partial class PanelViewModel : ObservableObject
|
||||
{
|
||||
@@ -18,6 +24,16 @@ public partial class PanelViewModel : ObservableObject
|
||||
[ObservableProperty] private HistoryView history = new([], [], [], [], []);
|
||||
[ObservableProperty] private IReadOnlyList<Diagnostic> diagnostics = [];
|
||||
[ObservableProperty] private string message = "Reading local CLI data…";
|
||||
[ObservableProperty] private bool includeCacheReads = true;
|
||||
[ObservableProperty] private bool refreshing;
|
||||
public async Task RefreshAsync(Func<Task> 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
|
||||
{
|
||||
@@ -33,43 +49,60 @@ public partial class PanelViewModel : ObservableObject
|
||||
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<LimitDetail>();
|
||||
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, w.Window.Label, s.UsedPercent,
|
||||
new ChartValue(s.SampleTime, p.Provider.ToString(), s.UsedPercent,
|
||||
Pace.Calculate(s, s.SampleTime).ElapsedFraction * 100,
|
||||
i > 0 && s.ResetsAt != samples[i - 1].ResetsAt)).ToArray());
|
||||
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();
|
||||
return new(hourly, daily, limits, Breakdown(true), Breakdown(false));
|
||||
var models = Breakdown(true); var projects = Breakdown(false);
|
||||
return new(hourly, daily, limits, models, projects) { Details = details };
|
||||
|
||||
IReadOnlyList<ChartValue> Series(SeriesInterval interval) => providers.SelectMany(p =>
|
||||
store.TokenSeries(p.Provider, from, now, interval).SelectMany(point => filter is null
|
||||
? new[] { new ChartValue(point.Time, p.Provider.ToString(), point.Counts.Total) }
|
||||
: ModelsAtPoint(p.Provider, point.Time, interval))).ToArray();
|
||||
IEnumerable<ChartValue> ModelsAtPoint(Provider provider, DateTimeOffset time, SeriesInterval interval)
|
||||
IReadOnlyList<ChartValue> Series(SeriesInterval interval)
|
||||
{
|
||||
var end = interval == SeriesInterval.Hour ? time.AddHours(1) : CalendarDays.NextStart(time);
|
||||
return store.ByModel(provider, time < from ? from : time, end > now ? now : end)
|
||||
.Select(m => new ChartValue(time, m.Name ?? "Unknown model", m.Counts.Total));
|
||||
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<BreakdownRow> Breakdown(bool models)
|
||||
{
|
||||
var rows = providers.SelectMany(p => models ? store.ByModel(p.Provider, from, now) : store.ByProject(p.Provider, from, now))
|
||||
.GroupBy(r => r.Name ?? "Unknown").Select(g => new TokenBreakdown(g.Key,
|
||||
g.Aggregate(new TokenCounts(), (sum, r) => sum + r.Counts))).OrderByDescending(r => r.Counts.Total).ToArray();
|
||||
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 => new BreakdownRow(r.Name!, r.Counts, total == 0 ? 0 : r.Counts.Total / total)).ToArray();
|
||||
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) =>
|
||||
window.Pace.State != PaceState.Unknown && !Pace.CanForecast(window.Window, now, window.Pace) &&
|
||||
Pace.ForecastStartsAt(window.Window) is { } start && start > now ? "Forecast from " + Projection(start) : 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("g");
|
||||
=> 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)
|
||||
@@ -80,9 +113,26 @@ public static class Display
|
||||
culture ?? System.Globalization.CultureInfo.CurrentCulture);
|
||||
}
|
||||
public static string Duration(TimeSpan span) => span <= TimeSpan.Zero ? "now" : span.TotalDays >= 1
|
||||
? $"{span.TotalDays:0.0} d" : span.TotalHours >= 1 ? $"{span.TotalHours:0.0} h" : $"{Math.Ceiling(span.TotalMinutes):0} min";
|
||||
? $"{(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 State(PaceState state) => state switch { PaceState.OnTrack => "On track", PaceState.Unknown => "Pace unknown", _ => state.ToString() };
|
||||
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) =>
|
||||
(state == PaceState.Ahead ? "⚠ " : "At this pace ") + "100 % on " + Projection(date);
|
||||
public static string State(PaceState state) => state switch { PaceState.OnTrack => "✓ On track", PaceState.Ahead => "▲ Ahead", PaceState.Behind => "▼ Behind", _ => "? Pace unknown" };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user