app: date far projections and give charts distinct axis ticks

The popup showed only the time of a projection two days away, which
read as today; the popup and the panel now share one formatter that adds
the date unless the projection is today. Chart axes used max/4 steps,
which repeated labels for small or empty ranges; they now use whole 1,
2 or 5 steps and an empty chart shows only 0.

Refs #1
This commit is contained in:
Florian Schmidt
2026-10-14 20:54:12 +02:00
parent 4f4ed5fe17
commit 5c5973aa6c
6 changed files with 91 additions and 9 deletions
+16 -4
View File
@@ -12,6 +12,18 @@ public sealed class UsageChart : Control
{ {
private static readonly IBrush[] Palette = [Brush.Parse("#3878D4"), Brush.Parse("#B377D1"), Brush.Parse("#249A88"), Brush.Parse("#C98926")]; private static readonly IBrush[] Palette = [Brush.Parse("#3878D4"), Brush.Parse("#B377D1"), Brush.Parse("#249A88"), Brush.Parse("#C98926")];
public static IBrush SeriesColour(int index) => Palette[index % Palette.Length]; public static IBrush SeriesColour(int index) => Palette[index % Palette.Length];
/// <summary>At most five ticks. Token steps are whole numbers rounded up to 1, 2 or 5 times a power of ten.</summary>
public static IReadOnlyList<double> AxisTicks(double maximum, bool percent = false)
{
if (!double.IsFinite(maximum) || maximum <= 0) return [0];
if (percent) return [0, 25, 50, 75, 100];
var target = Math.Max(1, maximum / 4);
var magnitude = Math.Pow(10, Math.Floor(Math.Log10(target)));
var fraction = target / magnitude;
var step = (fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10) * magnitude;
var intervals = (int)Math.Ceiling(maximum / step);
return Enumerable.Range(0, intervals + 1).Select(i => i * step).ToArray();
}
public IReadOnlyList<ChartValue> Values { get; init; } = []; public IReadOnlyList<ChartValue> Values { get; init; } = [];
public bool Percent { get; init; } public bool Percent { get; init; }
public TimeSpan Interval { get; init; } = TimeSpan.FromHours(1); public TimeSpan Interval { get; init; } = TimeSpan.FromHours(1);
@@ -29,12 +41,12 @@ public sealed class UsageChart : Control
var ink = ActualThemeVariant == ThemeVariant.Dark ? Brushes.WhiteSmoke : Brushes.DarkSlateGray; var ink = ActualThemeVariant == ThemeVariant.Dark ? Brushes.WhiteSmoke : Brushes.DarkSlateGray;
var plot = new Rect(58, 12, Math.Max(1, Bounds.Width - 74), Math.Max(1, Bounds.Height - 46)); var plot = new Rect(58, 12, Math.Max(1, Bounds.Width - 74), Math.Max(1, Bounds.Height - 46));
var groups = Values.GroupBy(v => v.Time).OrderBy(g => g.Key).ToArray(); var groups = Values.GroupBy(v => v.Time).OrderBy(g => g.Key).ToArray();
var max = Percent ? 100 : Math.Max(1, groups.Select(g => g.Sum(v => v.Value)).DefaultIfEmpty().Max()); var ticks = AxisTicks(groups.Length == 0 ? 0 : Percent ? 100 : groups.Max(g => g.Sum(v => v.Value)), Percent);
for (var i = 0; i <= 4; i++) var max = Math.Max(1, ticks[^1]);
foreach (var tick in ticks)
{ {
var y = plot.Bottom - plot.Height * i / 4; var y = plot.Bottom - plot.Height * tick / max;
context.DrawLine(new Pen(ActualThemeVariant == ThemeVariant.Dark ? Brush.Parse("#354052") : Brush.Parse("#DFE5EE")), new(plot.Left, y), new(plot.Right, y)); context.DrawLine(new Pen(ActualThemeVariant == ThemeVariant.Dark ? Brush.Parse("#354052") : Brush.Parse("#DFE5EE")), new(plot.Left, y), new(plot.Right, y));
var tick = max * i / 4;
var label = Percent ? $"{tick:0}%" : tick >= 1e9 ? $"{tick / 1e9:0.#}B" : tick >= 1e6 ? $"{tick / 1e6:0.#}M" : tick >= 1000 ? $"{tick / 1000:0.#}K" : $"{tick:0}"; var label = Percent ? $"{tick:0}%" : tick >= 1e9 ? $"{tick / 1e9:0.#}B" : tick >= 1e6 ? $"{tick / 1e6:0.#}M" : tick >= 1000 ? $"{tick / 1000:0.#}K" : $"{tick:0}";
Text(context, label, new(0, y - 8), ink); Text(context, label, new(0, y - 8), ink);
} }
+7
View File
@@ -66,6 +66,13 @@ public partial class PanelViewModel : ObservableObject
public static class Display public static class Display
{ {
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 Duration(TimeSpan span) => span <= TimeSpan.Zero ? "now" : span.TotalDays >= 1 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"; ? $"{span.TotalDays:0.0} d" : span.TotalHours >= 1 ? $"{span.TotalHours:0.0} h" : $"{Math.Ceiling(span.TotalMinutes):0} min";
public static string Tokens(TokenCounts? counts) => counts is { } c public static string Tokens(TokenCounts? counts) => counts is { } c
+1 -1
View File
@@ -67,7 +67,7 @@ public sealed class PanelWindow : Window
card.Children.Add(title); card.Children.Add(title);
card.Children.Add(new PaceBar(window) { Height = 14 }); card.Children.Add(new PaceBar(window) { Height = 14 });
card.Children.Add(Ui.Text($"Reset: {(w.ResetsAt is { } reset ? Display.Duration(reset - DateTimeOffset.UtcNow) + " · " + reset.LocalDateTime.ToString("g") : "unknown")} Sample age: {Display.Duration(DateTimeOffset.UtcNow - w.SampleTime)}" + card.Children.Add(Ui.Text($"Reset: {(w.ResetsAt is { } reset ? Display.Duration(reset - DateTimeOffset.UtcNow) + " · " + reset.LocalDateTime.ToString("g") : "unknown")} Sample age: {Display.Duration(DateTimeOffset.UtcNow - w.SampleTime)}" +
(pace.Projection is { } projection ? $" Reaches 100%: {projection.LocalDateTime:g}" : ""))); (pace.Projection is { } projection ? $" Reaches 100%: {Display.Projection(projection)}" : "")));
} }
card.Children.Add(Ui.Text("Tokens · provider totals", 15)); card.Children.Add(Ui.Text("Tokens · provider totals", 15));
card.Children.Add(Ui.Text("Today " + Display.Tokens(provider.Today))); card.Children.Add(Ui.Text("Today " + Display.Tokens(provider.Today)));
+1 -1
View File
@@ -38,7 +38,7 @@ public sealed class PopupWindow : Window
} }
public static PopupWindow Pace(PopupEvent alert, Action open) => new($"{alert.Provider} · {Display.State(alert.State)}", public static PopupWindow Pace(PopupEvent alert, Action open) => new($"{alert.Provider} · {Display.State(alert.State)}",
$"{alert.Label}: {alert.Delta:+0.0;-0.0;0} points from pace." + $"{alert.Label}: {alert.Delta:+0.0;-0.0;0} points from pace." +
(alert.Projection is { } projection ? $" At this rate: 100% at {projection.LocalDateTime:t}." : ""), open, accent: PaceBar.Colour(alert.State)); (alert.Projection is { } projection ? $" At this rate: 100% at {Display.Projection(projection)}." : ""), open, accent: PaceBar.Colour(alert.State));
} }
public sealed class PopupStack(Action open) : IDisposable public sealed class PopupStack(Action open) : IDisposable
@@ -0,0 +1,53 @@
using System.Globalization;
using Xunit;
namespace FinalToken.App.Tests;
public sealed class FormattingTests
{
[Theory]
[InlineData("de-DE")]
[InlineData("en-US")]
public void FutureProjectionIncludesLocalDateInUsersCulture(string culture)
{
var clock = new FixedClock();
var projection = new DateTimeOffset(2026, 10, 16, 6, 24, 0, TimeSpan.Zero);
var userCulture = CultureInfo.GetCultureInfo(culture);
Assert.Equal(new DateTime(2026, 10, 16, 8, 24, 0).ToString("g", userCulture), Display.Projection(projection, clock, userCulture));
}
[Fact]
public void TodaysProjectionUsesLocalTimeOnly()
{
Assert.Equal("23:24", Display.Projection(new(2026, 10, 14, 21, 24, 0, TimeSpan.Zero), new FixedClock(), CultureInfo.GetCultureInfo("de-DE")));
}
[Fact]
public void ProjectionDateChangesAtLocalMidnight()
{
Assert.Equal("15.10.2026 00:24", Display.Projection(new(2026, 10, 14, 22, 24, 0, TimeSpan.Zero), new FixedClock(), CultureInfo.GetCultureInfo("de-DE")));
}
[Theory]
[InlineData(0, new double[] { 0 })]
[InlineData(1, new double[] { 0, 1 })]
[InlineData(2, new double[] { 0, 1, 2 })]
[InlineData(3, new double[] { 0, 1, 2, 3 })]
public void SmallChartTicksAreDistinctIntegers(double maximum, double[] expected)
=> Assert.Equal(expected, UsageChart.AxisTicks(maximum));
[Theory]
[InlineData(5, new double[] { 0, 2, 4, 6 })]
[InlineData(17, new double[] { 0, 5, 10, 15, 20 })]
[InlineData(123456, new double[] { 0, 50000, 100000, 150000 })]
public void LargerChartTicksUseRoundedStepsAndCoverMaximum(double maximum, double[] expected)
=> Assert.Equal(expected, UsageChart.AxisTicks(maximum));
[Fact]
public void PercentTicksKeepQuarterMarksAndEmptyPercentChartHasOnlyZero()
{
Assert.Equal([0d, 25, 50, 75, 100], UsageChart.AxisTicks(3, true));
Assert.Equal([0d], UsageChart.AxisTicks(0, true));
}
private sealed class FixedClock : TimeProvider
{
public override DateTimeOffset GetUtcNow() => new(2026, 10, 14, 18, 0, 0, TimeSpan.Zero);
public override TimeZoneInfo LocalTimeZone { get; } = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
}
}
+13 -3
View File
@@ -82,16 +82,26 @@ public sealed class HeadlessTests
var chartWindow = new Window { Content = chart, Width = 400, Height = 180 }; var chartWindow = new Window { Content = chart, Width = 400, Height = 180 };
chartWindow.Show(); chartWindow.Show();
using (chartWindow.CaptureRenderedFrame()) { } using (chartWindow.CaptureRenderedFrame()) { }
chartWindow.MouseMove(new Point(65, 30)); chartWindow.MouseMove(new Point(65, 80));
Assert.Contains(123456.ToString("N0"), ToolTip.GetTip(chart)?.ToString()); chartWindow.Close(); Assert.Contains(123456.ToString("N0"), ToolTip.GetTip(chart)?.ToString()); chartWindow.Close();
var polishShots = Path.Combine(root.Parent!.FullName, "runs", "shots", "w1");
Directory.CreateDirectory(polishShots);
var emptyChart = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), new UsageChart())), Width = 620, Height = 260,
RequestedThemeVariant = ThemeVariant.Light };
emptyChart.Show(); Save(emptyChart, "chart-empty.png", polishShots); emptyChart.Close();
var time = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var smallChart = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), new UsageChart
{ Values = [new(time, "Claude", 1), new(time.AddHours(1), "Claude", 2), new(time.AddHours(2), "Claude", 3)] })),
Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light };
smallChart.Show(); Save(smallChart, "chart-max-3.png", polishShots); smallChart.Close();
Thread.Sleep(8200); Dispatcher.UIThread.RunJobs(); Thread.Sleep(8200); Dispatcher.UIThread.RunJobs();
Assert.False(first.IsVisible); Assert.False(second.IsVisible); Assert.False(first.IsVisible); Assert.False(second.IsVisible);
completion.SetResult(); completion.SetResult();
void Save(Window window, string name) void Save(Window window, string name, string? destination = null)
{ {
Dispatcher.UIThread.RunJobs(); Dispatcher.UIThread.RunJobs();
using var bitmap = window.CaptureRenderedFrame(); Assert.NotNull(bitmap); using var bitmap = window.CaptureRenderedFrame(); Assert.NotNull(bitmap);
using var output = File.Create(Path.Combine(shots, name)); bitmap.Save(output, PngBitmapEncoderOptions.Default); using var output = File.Create(Path.Combine(destination ?? shots, name)); bitmap.Save(output, PngBitmapEncoderOptions.Default);
Assert.True(output.Length > 2000); Assert.True(output.Length > 2000);
} }
} }