From ab8d245df8f4772af356107a7dc9eed8ca19633e Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Thu, 15 Oct 2026 09:38:11 +0200 Subject: [PATCH] app: burn-up window charts, estimated days, full breakdown, one tooltip From developer feedback on the redesign: - Week use per day draws estimated days hatched beside measured ones. - Limit history becomes a burn-up chart per window instance: even-pace diagonal, used line without point markers, forecast to the reset, the previous instance faintly, and a strip of past peaks with their real start and end. - The breakdown has its detail columns back, sorts by any column and expands "Other" to every row. - One tooltip component, a title and a label/value grid, for every chart and table. Also the review notes of #7: dated forecasts, the real span of the recent rate, keyboard focus, distinct settings names, a wheel that no longer changes selections, and version 1.1.0. Refs #5, #7 --- Directory.Build.props | 2 +- src/FinalToken.App/AGENTS.md | 18 ++- src/FinalToken.App/BreakdownTable.cs | 116 +++++++++++++++ src/FinalToken.App/BurnUpChart.cs | 143 +++++++++++++++++++ src/FinalToken.App/Charts.cs | 44 +++--- src/FinalToken.App/DataTooltip.cs | 46 ++++++ src/FinalToken.App/DesktopApp.cs | 6 +- src/FinalToken.App/NeutralCheckBox.cs | 18 +++ src/FinalToken.App/PanelViewModel.cs | 30 +++- src/FinalToken.App/PanelWindow.cs | 84 ++++------- src/FinalToken.App/SettingsWindow.cs | 9 +- src/FinalToken.App/Ui.cs | 16 ++- tests/FinalToken.App.Tests/HeadlessTests.cs | 100 ++++++++++++- tests/FinalToken.App.Tests/ViewModelTests.cs | 61 +++++++- 14 files changed, 592 insertions(+), 101 deletions(-) create mode 100644 src/FinalToken.App/BreakdownTable.cs create mode 100644 src/FinalToken.App/BurnUpChart.cs create mode 100644 src/FinalToken.App/DataTooltip.cs create mode 100644 src/FinalToken.App/NeutralCheckBox.cs diff --git a/Directory.Build.props b/Directory.Build.props index aff0546..aa675fc 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 1.0.1 + 1.1.0 net10.0 14 enable diff --git a/src/FinalToken.App/AGENTS.md b/src/FinalToken.App/AGENTS.md index d690076..83a17d5 100644 --- a/src/FinalToken.App/AGENTS.md +++ b/src/FinalToken.App/AGENTS.md @@ -12,7 +12,7 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. ## Panel and visual rules - Keep this order: fixed 56 px header; Limits; Week use per day; Tokens (totals, hourly and daily - charts); Limit history; Breakdown by model and project; collapsed Diagnostics, hidden when empty. + charts); Window charts (current-instance burn-up and past peaks); Breakdown by model and project; collapsed Diagnostics, hidden when empty. Preserve scroll offset on snapshots. Sections have two columns from 1200 px content width; limit tiles have three from 1400 px. Cards align at the top and size to their content. - Follow the OS light/dark theme through `Ui.Theme` and `Ui.NeutralTheme`. Selection never uses @@ -29,7 +29,7 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. Slots in order: dark `#3987e5 #d95926 #199e70 #c98500 #d55181 #9085e9`; light `#2a78d6 #eb6834 #1baf7a #eda100 #e87ba4 #6250d6`. Other is muted. - Status chips always have icon and label: `#0ca30c` ✓ On track, `#ec835a` ▲ Ahead, - `#fab219` ▼ Behind. Forecast dates remain visible for every positive pace delta (D7), but + `#fab219` ▼ Behind. Forecasts start at 10% elapsed; then dates remain visible for every positive pace delta (D7), but only Ahead gets the critical `#d03b3b` mark and ⚠. Other states say "At this pace 100 % on …" in secondary ink. Text paragraphs stay in ink colours; colour belongs to marks and meters. - Spacing is 8/16/24 px; card radius 10, padding 16–20; system sans. Use about 12 px captions, @@ -46,4 +46,16 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. resets within 15 minutes belong together, including minute drift in either direction. - Charts use 2 px lines, hit targets at least 8 px, tooltips and recessive grids. Bars normally have a 2 px surface gap; below 6 px width remove gaps and snap shared edges to physical pixels. - Breakdowns show eight rows plus Other; keep full project paths and exact counts in tooltips. + Breakdowns show eight rows plus expandable Other; keep every detail column sortable and right-aligned. +- Estimated day bars use provider outlines and 45-degree hatching; measured days stay solid. Align past + days by index and burn-ups by elapsed time. Never join different resets on one time axis. + Burn-ups use solid measured and lighter dashed estimated lines, with no point markers. +- Use DataTooltip for every data hover: bold title, two-column label/value grid, exact and compact + counts, optional series swatches. Future days have no cumulative value. Share one date formatter + for resets and forecasts. Recent-rate captions name the actual span. +- Custom segments and checkboxes must show keyboard focus. NeutralCheckBox owns checked state; + templates bind its MarkVisible property and must never register checked handlers. + +- Cap token estimates at 100%, retain the estimated crossing time and leave measured samples intact. + Past windows end at their reset or the next instance's first sample; label real start/end dates. + Page wheel events must never change a selection: WindowSelector bubbles them to the scroll view. diff --git a/src/FinalToken.App/BreakdownTable.cs b/src/FinalToken.App/BreakdownTable.cs new file mode 100644 index 0000000..76e8bc5 --- /dev/null +++ b/src/FinalToken.App/BreakdownTable.cs @@ -0,0 +1,116 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Layout; +using Avalonia.Media; +using FinalToken.Core; + +namespace FinalToken.App; + +public enum BreakdownColumn { Name, Total, Share, Input, Output, CacheWrite, CacheRead, Reasoning } +public sealed class BreakdownState +{ + public bool Expanded { get; set; } + public BreakdownColumn Sort { get; set; } = BreakdownColumn.Total; + public bool Descending { get; set; } = true; +} + +public sealed class BreakdownTable : StackPanel +{ + private readonly IReadOnlyList rows; + private readonly BreakdownState state; + private readonly string title; + private readonly bool projects; + private readonly Provider? filter; + public BreakdownTable(string title, IReadOnlyList rows, bool projects, Provider? filter, BreakdownState state) + { + this.title = title; this.rows = rows; this.projects = projects; this.filter = filter; this.state = state; Spacing = 12; + AttachedToVisualTree += (_, _) => RenderTable(); + } + public static IReadOnlyList SortRows(IEnumerable rows, BreakdownColumn column, bool descending) + { + if (column == BreakdownColumn.Name) return (descending ? rows.OrderByDescending(r => r.Name, StringComparer.OrdinalIgnoreCase) : rows.OrderBy(r => r.Name, StringComparer.OrdinalIgnoreCase)).ToArray(); + double Key(BreakdownRow r) => column switch + { + BreakdownColumn.Total => r.Counts.Total, BreakdownColumn.Share => r.Share, BreakdownColumn.Input => r.Counts.Input, + BreakdownColumn.Output => r.Counts.Output, BreakdownColumn.CacheWrite => r.Counts.CacheWrite, + BreakdownColumn.CacheRead => r.Counts.CacheRead, _ => r.Counts.ReasoningOutput + }; + return (descending ? rows.OrderByDescending(Key) : rows.OrderBy(Key)).ThenBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray(); + } + private void RenderTable() + { + Children.Clear(); var header = new DockPanel(); + if (rows.Count > 8) + { + var expand = Ui.Button(state.Expanded ? "Show top 8" : $"Show all {rows.Count}", () => { state.Expanded = !state.Expanded; RenderTable(); }); + DockPanel.SetDock(expand, Dock.Right); header.Children.Add(expand); + } + header.Children.Add(Ui.Text(title, 15)); Children.Add(header); + var sorted = SortRows(rows, state.Sort, state.Descending); + var visible = state.Expanded ? sorted.ToList() : sorted.Take(8).ToList(); + if (!state.Expanded && sorted.Count > 8) + { + var tail = sorted.Skip(8).ToArray(); + visible.Add(new($"Other ({tail.Length})", tail.Aggregate(new TokenCounts(), (sum, row) => sum + row.Counts), tail.Sum(r => r.Share), tail.SelectMany(r => r.Providers ?? []).Distinct().Order().ToArray())); + } + var reasoning = rows.Any(r => r.Providers?.Contains(Provider.Codex) == true || r.Counts.ReasoningOutput > 0); + var grid = new Grid { ColumnDefinitions = new ColumnDefinitions(reasoning ? "*,90,130,90,90,90,90,90" : "*,90,130,90,90,90,90"), + ColumnSpacing = 12, RowSpacing = 6, MinWidth = reasoning ? 1060 : 960 }; + var headers = new[] { "Name", "Total", "Share", "Input", "Output", "Cache write", "Cache read", "Reasoning" }; + for (var c = 0; c < (reasoning ? 8 : 7); c++) + { + var column = (BreakdownColumn)c; + var button = Ui.Button(headers[c] + (state.Sort == column ? state.Descending ? " ↓" : " ↑" : ""), () => + { + state.Descending = state.Sort != column || !state.Descending; state.Sort = column; RenderTable(); + }); + button.Name = title.Replace(" ", "") + "Sort" + column; + button.Padding = new Thickness(0, 4); button.HorizontalAlignment = c == 0 ? HorizontalAlignment.Left : HorizontalAlignment.Right; + Add(button, 0, c); + } + var names = projects ? PanelWindow.ShortProjectNames(visible.Select(r => r.Name).ToArray()) : visible.Select(r => r.Name).ToArray(); + for (var i = 0; i < visible.Count; i++) + { + var row = visible[i]; var tooltip = DataTooltip.Tokens(row.Name, row.Counts); + Control name; + if (!state.Expanded && i == 8 && sorted.Count > 8) + name = Ui.Button(row.Name + " ▸", () => { state.Expanded = true; RenderTable(); }); + else + { + var label = Ui.Text(names[i]); label.TextWrapping = TextWrapping.NoWrap; label.TextTrimming = TextTrimming.CharacterEllipsis; + var cell = new DockPanel(); + if (!projects && filter is null) + foreach (var provider in row.Providers ?? []) + { + var dot = Ui.Mark("●", Ui.ProviderColour(provider, Ui.Dark(this))); dot.Margin = new Thickness(0, 0, 6, 0); + DockPanel.SetDock(dot, Dock.Left); cell.Children.Add(dot); + } + cell.Children.Add(label); name = cell; + } + ToolTip.SetTip(name, tooltip); Add(name, i + 1, 0); + var counts = row.Counts; + long[] numbers = [counts.Total, 0, counts.Input, counts.Output, counts.CacheWrite, counts.CacheRead, counts.ReasoningOutput]; + for (var c = 1; c < (reasoning ? 8 : 7); c++) + { + Control value; + if (c == 2) + { + var share = new Grid { ColumnDefinitions = new ColumnDefinitions("*,48"), ColumnSpacing = 6 }; + share.Children.Add(new ProgressBar { Value = row.Share, Maximum = 1, Width = 70, MinWidth = 0, Height = 4, VerticalAlignment = VerticalAlignment.Center, + Foreground = filter is { } p ? Ui.ProviderColour(p, Ui.Dark(this)) : Ui.Colour("Muted", Ui.Dark(this)) }); + var percent = Ui.TableNumber(row.Share.ToString("P1"), 12); percent.HorizontalAlignment = HorizontalAlignment.Right; Grid.SetColumn(percent, 1); share.Children.Add(percent); value = share; + } + else { var text = Ui.TableNumber(Display.Compact(numbers[c - 1]), 12); text.HorizontalAlignment = HorizontalAlignment.Right; value = text; } + ToolTip.SetTip(value, DataTooltip.Tokens(row.Name, counts)); Add(value, i + 1, c); + } + } + Children.Add(new ScrollViewer { Content = grid, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Disabled }); + if (rows.Count == 0) Children.Add(Ui.Text("No tokens in this range.", 12, "Muted")); + void Add(Control control, int row, int column) + { + while (grid.RowDefinitions.Count <= row) grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); + Grid.SetRow(control, row); Grid.SetColumn(control, column); grid.Children.Add(control); + } + } +} diff --git a/src/FinalToken.App/BurnUpChart.cs b/src/FinalToken.App/BurnUpChart.cs new file mode 100644 index 0000000..3939b59 --- /dev/null +++ b/src/FinalToken.App/BurnUpChart.cs @@ -0,0 +1,143 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Media; +using FinalToken.Core; + +namespace FinalToken.App; + +public sealed class BurnUpChart(LimitChart chart) : Control +{ + private Rect plot; + private double? crosshair; + public BurnUpChart() : this(new("", [])) { } + protected override void OnInitialized() + { + base.OnInitialized(); Height = 240; ToolTip.SetShowDelay(this, 0); + PointerMoved += (_, e) => + { + if (chart.Analysis is not { } analysis || !plot.Contains(e.GetPosition(this))) return; + crosshair = Math.Clamp(e.GetPosition(this).X, plot.Left, plot.Right); + var time = analysis.Current.Start.AddTicks((long)((analysis.Current.Reset - analysis.Current.Start).Ticks * (crosshair.Value - plot.Left) / plot.Width)); + var current = analysis.Current; + var before = current.Points.LastOrDefault(p => p.Time <= time); + var after = current.Points.FirstOrDefault(p => p.Time >= time); + double? used = before?.Used; + var source = before?.Origin == UseOrigin.Estimated ? "Estimated from tokens" : "Measured"; + if (time > chart.Now) + { + if (current.ReachedOrigin == UseOrigin.Estimated) + { used = 100; source = "Limit reached (estimated)"; } + else if (chart.Window is { } window && LimitAnalysis.AverageUseAtReset(window.Window, chart.Now) is { } forecast) + { + used = window.Window.UsedPercent + (forecast - window.Window.UsedPercent) * (time - chart.Now).TotalSeconds / (current.Reset - chart.Now).TotalSeconds; + source = "Average forecast"; + } + else used = null; + } + else if (before is not null && after is not null && after.Time > before.Time) + { + if (before.Time == current.Start && current.Scale is null && after.Time > current.Start) used = null; + else used = before.Used + (after.Used - before.Used) * (time - before.Time).TotalSeconds / (after.Time - before.Time).TotalSeconds; + if (before.Origin == UseOrigin.Estimated || after.Origin == UseOrigin.Estimated) source = "Estimated from tokens"; + } + var expected = 100 * (time - current.Start).TotalSeconds / (current.Reset - current.Start).TotalSeconds; + ToolTip.SetTip(this, new DataTooltip(Display.Projection(time), new("Used", used is { } use ? $"{use:0.##} %" : "Collecting history", Ui.ProviderColour(chart.Provider, Ui.Dark(this))), + new("Expected", $"{expected:0.##} %"), new("Delta", used is { } value ? $"{value - expected:+0.##;-0.##;0} points" : "Unknown"), + new("Source", used is null ? "No baseline" : source))); + InvalidateVisual(); + }; + PointerExited += (_, _) => { crosshair = null; InvalidateVisual(); }; + } + public override void Render(DrawingContext context) + { + base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); + if (chart.Analysis is not { } data || chart.Window is not { } snapshot) return; + var instance = data.Current; var dark = Ui.Dark(this); var muted = Ui.Colour("Muted", dark); var colour = Ui.ProviderColour(chart.Provider, dark); + plot = new Rect(42, 22, Math.Max(1, Bounds.Width - 58), Math.Max(1, Bounds.Height - 60)); + var duration = (instance.Reset - instance.Start).TotalSeconds; + double X(DateTimeOffset time) => plot.Left + (time - instance.Start).TotalSeconds / duration * plot.Width; + double Y(double use) => plot.Bottom - use / 100 * plot.Height; + foreach (var tick in new[] { 0, 25, 50, 75, 100 }) + { + context.DrawLine(new Pen(Ui.Colour("Grid", dark)), new(plot.Left, Y(tick)), new(plot.Right, Y(tick))); + ChartText.Draw(context, tick + "%", new(0, Y(tick) - 7), muted); + } + context.DrawLine(new Pen(muted, 1), new(plot.Left, plot.Bottom), new(plot.Right, plot.Top)); + using (context.PushClip(plot)) + { + if (data.Previous is { } previous) + using (context.PushOpacity(.2)) DrawSeries(previous, true); + DrawSeries(instance, false); + if (instance.ReachedLimit is null && LimitAnalysis.AverageUseAtReset(snapshot.Window, chart.Now) is { } average && instance.Reset > chart.Now) + context.DrawLine(new Pen(colour, 2, new DashStyle([1, 3], 0)), new(X(chart.Now), Y(snapshot.Window.UsedPercent)), new(plot.Right, Y(average))); + var nowX = X(chart.Now); + if (nowX >= plot.Left && nowX <= plot.Right) context.DrawLine(new Pen(muted, 1, new DashStyle([3, 3], 0)), new(nowX, plot.Top), new(nowX, plot.Bottom)); + if (crosshair is { } x) context.DrawLine(new Pen(Ui.Colour("Secondary", dark), 1), new(x, plot.Top), new(x, plot.Bottom)); + } + if (instance.ReachedLimit is null && snapshot.Pace.Projection is { } crossing && crossing <= instance.Reset && crossing >= chart.Now) + { + var x = X(crossing); var mark = snapshot.Pace.State == PaceState.Ahead ? Brush.Parse("#d03b3b") : colour; + context.DrawLine(new Pen(mark, 2), new(x, plot.Top - 5), new(x, plot.Top + 5)); + ChartText.Draw(context, "100 % " + Display.Projection(crossing), new(Math.Clamp(x - 80, plot.Left, Math.Max(plot.Left, plot.Right - 175)), 0), Ui.Colour("Secondary", dark)); + } + if (instance.ReachedLimit is { } reached && instance.ReachedOrigin == UseOrigin.Estimated) + { + var labelX = Math.Clamp(X(reached) - 80, plot.Left, Math.Max(plot.Left, plot.Right - 260)); + context.DrawLine(new Pen(colour, 2), new(X(reached), plot.Top - 5), new(X(reached), plot.Top + 5)); + ChartText.Draw(context, "Limit reached (estimated) " + Display.Projection(reached), new(labelX, 0), Ui.Colour("Secondary", dark)); + } + ChartText.Draw(context, Display.Projection(instance.Start), new(plot.Left, plot.Bottom + 12), muted); + ChartText.Draw(context, Display.Projection(instance.Reset), new(Math.Max(plot.Left, plot.Right - 120), plot.Bottom + 12), muted); + var tickX = X(chart.Now); + if (tickX > plot.Left + 160 && tickX < plot.Right - 160) ChartText.Draw(context, "now", new(tickX - 10, plot.Bottom + 12), Ui.Colour("Secondary", dark)); + + void DrawSeries(LimitInstance series, bool previous) + { + for (var i = 1; i < series.Points.Count; i++) + { + var a = series.Points[i - 1]; var b = series.Points[i]; + if (i == 1 && a.Time == series.Start && b.Origin == UseOrigin.Measured && series.Scale is null && b.Time > series.Start) continue; + var offset = previous ? instance.Start - series.Start : TimeSpan.Zero; + var estimated = a.Origin == UseOrigin.Estimated || b.Origin == UseOrigin.Estimated; + using (context.PushOpacity(estimated ? .55 : 1)) + context.DrawLine(new Pen(colour, 2, estimated ? new DashStyle([4, 3], 0) : null, lineCap: PenLineCap.Round), new(X(a.Time + offset), Y(a.Used)), new(X(b.Time + offset), Y(b.Used))); + } + } + } +} + +public sealed class InstancePeaks(IReadOnlyList instances, Provider provider) : Control +{ + private readonly List<(Rect Bounds, LimitInstance Instance)> hits = []; + protected override void OnInitialized() + { + base.OnInitialized(); Height = 96; ToolTip.SetShowDelay(this, 0); + PointerMoved += (_, e) => + { + var instance = hits.FirstOrDefault(h => h.Bounds.Contains(e.GetPosition(this))).Instance; + ToolTip.SetTip(this, instance is null ? null : new DataTooltip(Display.Projection(instance.Start) + " — " + Display.Projection(instance.End), + new("Peak", $"{instance.Peak:0.##} %", Ui.ProviderColour(provider, Ui.Dark(this))), + new(instance.ReachedOrigin == UseOrigin.Estimated ? "Limit reached (estimated)" : "100 % reached", instance.ReachedLimit is { } time ? "⚠ " + Display.Projection(time) : "Not reached"), + new("Source", instance.Points.Any(p => p.Origin == UseOrigin.Estimated) ? "Includes token estimates" : "Measured"))); + }; + } + public override void Render(DrawingContext context) + { + base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear(); if (instances.Count == 0) return; + var colour = Ui.ProviderColour(provider, Ui.Dark(this)); var width = Bounds.Width / instances.Count; + for (var i = 0; i < instances.Count; i++) + { + var instance = instances[instances.Count - 1 - i]; var x = i * width + width / 2; + context.DrawLine(new Pen(colour, 5, lineCap: PenLineCap.Round), new(x, 44), new(x, 44 - Math.Clamp(instance.Peak ?? 0, 0, 100) / 100 * 26)); + var session = instance.Reset - instance.Start <= TimeSpan.FromDays(1); + var label = session ? instance.Start.LocalDateTime.ToString("HH:mm") + "\u2013" + instance.End.LocalDateTime.ToString("HH:mm") + : instance.Start.LocalDateTime.ToString("dd.MM") + "\u2013" + instance.End.LocalDateTime.ToString("dd.MM"); + ChartText.Draw(context, label, new(Math.Max(i * width, x - 26), 52), Ui.Colour("Muted", Ui.Dark(this)), 9); + var caption = instance.ReachedLimit is { } reached ? "\u26a0 " + reached.LocalDateTime.ToString("dd.MM HH:mm") + : session ? instance.Start.LocalDateTime.ToString("dd.MM") : ""; + ChartText.Draw(context, caption, new(Math.Max(i * width, x - 30), 68), Ui.Colour("Secondary", Ui.Dark(this)), 9); + ChartText.Draw(context, $"{instance.Peak:0.#}%", new(x - 16, 0), Ui.Colour("Secondary", Ui.Dark(this))); + hits.Add((new Rect(i * width, 0, width, Bounds.Height), instance)); + } + } +} diff --git a/src/FinalToken.App/Charts.cs b/src/FinalToken.App/Charts.cs index aa3fe7b..33db041 100644 --- a/src/FinalToken.App/Charts.cs +++ b/src/FinalToken.App/Charts.cs @@ -45,17 +45,16 @@ public sealed class UsageChart : Control public ChartValue? Forecast { get; init; } public ChartValue? ForecastStart { get; init; } public TimeSpan Interval { get; init; } = TimeSpan.FromHours(1); - private readonly List<(Rect Rect, string Text)> hits = []; + private readonly List<(Rect Rect, Func Tip)> hits = []; public UsageChart() { Height = 208; ToolTip.SetShowDelay(this, 0); - PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Text); - PointerExited += (_, _) => ToolTip.SetTip(this, null); + PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Tip?.Invoke()); } public override void Render(DrawingContext context) { - base.Render(context); hits.Clear(); + base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear(); var dark = Ui.Dark(this); var ink = Ui.Colour("Muted", dark); var plot = new Rect(50, 16, Math.Max(1, Bounds.Width - 66), Math.Max(1, Bounds.Height - 48)); var groups = Values.GroupBy(v => v.Time).OrderBy(g => g.Key).ToArray(); @@ -88,14 +87,14 @@ public sealed class UsageChart : Control context.DrawLine(new Pen(ink, 1, new DashStyle([4, 3], 0)), Position(p, pe), Position(value, expected)); } context.DrawEllipse(colour, null, point, 2, 2); - hits.Add((new(point.X - 8, point.Y - 10, 16, 20), $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Value:0.##}% · expected {value.Expected:0.##}%")); + hits.Add((new(point.X - 8, point.Y - 10, 16, 20), () => new DataTooltip(Display.ChartTimestamp(value.Time, Interval), new("Used", $"{value.Value:0.##} %"), new("Expected", $"{value.Expected:0.##} %")))); previous = value; } if (previous is { } tail && Forecast is { } forecast) { var start = ForecastStart ?? tail; context.DrawLine(new Pen(colour, 2, new DashStyle([1, 3], 0)), Position(start, start.Value), Position(forecast, forecast.Value)); - hits.Add((new Rect(Position(forecast, forecast.Value) - new Vector(8, 8), new Size(16, 16)), $"Average forecast · {forecast.Time.LocalDateTime:g} · {forecast.Value:0.#}%")); + hits.Add((new Rect(Position(forecast, forecast.Value) - new Vector(8, 8), new Size(16, 16)), () => new DataTooltip("Average forecast", new("Time", Display.Projection(forecast.Time)), new("Use", $"{forecast.Value:0.#} %")))); } } else @@ -111,7 +110,8 @@ public sealed class UsageChart : Control var gap = width < 6 ? 0 : 2; var rect = BarBounds(x, bottom, width, height, TopLevel.GetTopLevel(this)?.RenderScaling ?? 1); if (height > 0) context.DrawRectangle(SeriesColour(value.Series, series, dark), null, rect, gap == 0 ? 0 : 3, gap == 0 ? 0 : 3); - hits.Add((new(x, bottom - Math.Max(8, height), Math.Max(8, width), Math.Max(8, height)), $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Series}: {value.Value:N0} tokens")); + hits.Add((new(x, bottom - Math.Max(8, height), Math.Max(8, width), Math.Max(8, height)), () => new DataTooltip(Display.ChartTimestamp(group.Key, Interval), + group.Select(v => new TooltipRow(v.Series, Display.Compact(v.Value) + " · " + v.Value.ToString("N0"), SeriesColour(v.Series, series, dark))).ToArray()))); bottom -= height; } } @@ -146,7 +146,7 @@ public sealed class PaceBar(WindowSnapshot window) : Control { PaceState.Ahead => "#ec835a", PaceState.Behind => "#fab219", PaceState.OnTrack => "#0ca30c", _ => "#898781" }); public override void Render(DrawingContext context) { - base.Render(context); + base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); var dark = Ui.Dark(this); var colour = Ui.ProviderColour(window.Window.Provider, dark); context.DrawRectangle(Ui.Colour("Grid", dark), null, new Rect(Bounds.Size), 3, 3); var used = Bounds.Width * Math.Clamp(window.Window.UsedPercent / 100, 0, 1); @@ -158,7 +158,7 @@ public sealed class PaceBar(WindowSnapshot window) : Control context.DrawRectangle(colour, null, new Rect(0, 0, used, Bounds.Height), 3, 3); if (window.Pace.ElapsedFraction is { } elapsed) context.DrawLine(new Pen(Ui.Colour("Ink", dark), 2), new(Bounds.Width * elapsed, -2), new(Bounds.Width * elapsed, Bounds.Height + 2)); - ToolTip.SetTip(this, $"Used {window.Window.UsedPercent:0.##}% · expected {window.Pace.ElapsedFraction * 100:0.##}%"); + ToolTip.SetTip(this, new DataTooltip(window.Window.Label, new("Used", $"{window.Window.UsedPercent:0.##} %"), new("Expected", $"{window.Pace.ElapsedFraction * 100:0.##} %"))); } } @@ -166,7 +166,7 @@ public sealed class CompositionBar(TokenCounts counts, Provider provider, bool i { public override void Render(DrawingContext context) { - base.Render(context); + base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); var input = Math.Max(0, counts.Input - (provider == Provider.Codex ? counts.CacheRead : 0)); double[] values = [input, counts.Output, counts.CacheWrite, includeCache ? counts.CacheRead : 0]; var sum = Math.Max(1, values.Sum()); var x = 0d; @@ -178,23 +178,22 @@ public sealed class CompositionBar(TokenCounts counts, Provider provider, bool i new Rect(x, 0, Math.Max(0, width - 2), Bounds.Height), 3, 3); x += width; } - ToolTip.SetTip(this, Display.Tokens(counts)); + ToolTip.SetTip(this, DataTooltip.Tokens(provider + " · token composition", counts)); } } public sealed class DailyLimitChart(WindowDays days, Provider provider) : Control { - private readonly List<(Rect Rect, string Text)> hits = []; + private readonly List<(Rect Rect, Func Tip)> hits = []; public DailyLimitChart() : this(new([], [], null, 0, null), Provider.Claude) { } protected override void OnInitialized() { base.OnInitialized(); Height = 248; ToolTip.SetShowDelay(this, 0); - PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Text); - PointerExited += (_, _) => ToolTip.SetTip(this, null); + PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Tip?.Invoke()); } public override void Render(DrawingContext context) { - base.Render(context); hits.Clear(); + base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear(); var dark = Ui.Dark(this); var ink = Ui.Colour("Muted", dark); var colour = Ui.ProviderColour(provider, dark); var plot = new Rect(40, 24, Math.Max(1, Bounds.Width - 174), Math.Max(1, Bounds.Height - 60)); var maximum = Math.Max(days.EvenPace, Math.Max(days.DailyBudget ?? 0, days.Current.Concat(days.Previous).Select(d => d.Used ?? 0).DefaultIfEmpty(0).Max())); @@ -213,11 +212,22 @@ public sealed class DailyLimitChart(WindowDays days, Provider provider) : Contro using (context.PushOpacity(.18)) context.DrawRectangle(null, new Pen(colour, 2), new Rect(x + 4, Y(prior), width - 8, plot.Bottom - Y(prior)), 3, 3); if (day.Used is { } use) { - using (context.PushOpacity(day.IsToday ? 1 : .5)) context.DrawRectangle(colour, null, new Rect(x + 8, Y(use), Math.Max(1, width - 16), plot.Bottom - Y(use)), 3, 3); + var rect = new Rect(x + 8, Y(use), Math.Max(1, width - 16), Math.Max(0, plot.Bottom - Y(use))); + using (context.PushOpacity(day.Origin == UseOrigin.Estimated ? .45 : day.IsToday ? 1 : .5)) + { + if (day.Origin == UseOrigin.Measured) context.DrawRectangle(colour, null, rect, 3, 3); + else + { + context.DrawRectangle(null, new Pen(colour, 1), rect, 3, 3); + using (context.PushClip(rect)) + for (var hatchX = rect.Left - rect.Height; hatchX < rect.Right; hatchX += 8) + context.DrawLine(new Pen(colour, 1), new(hatchX, rect.Bottom), new(hatchX + rect.Height, rect.Top)); + } + } if (day.IsToday) ChartText.Draw(context, $"{use:0.#}%", new(x + 8, Y(use) - 18), Ui.Colour("Ink", dark), 12); } ChartText.Draw(context, day.Start.DateTime.ToString("ddd"), new(x + 8, plot.Bottom + 8), day.IsToday ? Ui.Colour("Ink", dark) : ink); - hits.Add((new Rect(x, plot.Top, width, plot.Height + 30), $"{day.Start.DateTime:d} · {(day.Used is { } u ? $"{u:0.##}% of week" : day.IsFuture ? "Future day" : "No day baseline")} · cumulative {day.Cumulative:0.##}%")); + hits.Add((new Rect(x, plot.Top, width, plot.Height + 30), () => DataTooltip.Day(day))); } var evenLabel = Math.Clamp(Y(days.EvenPace) - 7, plot.Top, plot.Bottom - 14); var budgetLabel = days.DailyBudget is { } b ? Math.Clamp(Y(b) - 7, plot.Top, plot.Bottom - 14) : 0; diff --git a/src/FinalToken.App/DataTooltip.cs b/src/FinalToken.App/DataTooltip.cs new file mode 100644 index 0000000..f08fb68 --- /dev/null +++ b/src/FinalToken.App/DataTooltip.cs @@ -0,0 +1,46 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; +using FinalToken.Core; + +namespace FinalToken.App; + +public sealed record TooltipRow(string Label, string Value, IBrush? Swatch = null); + +/// D8: every data tooltip uses the same title and aligned label/value layout. +public sealed class DataTooltip : Border +{ + public string Title { get; } + public IReadOnlyList Rows { get; } + public DataTooltip(string title, params TooltipRow[] rows) + { + Title = title; Rows = rows; MaxWidth = 520; MinWidth = 260; Padding = new Thickness(12); CornerRadius = new CornerRadius(8); + this.Bind(BackgroundProperty, this.GetResourceObservable("Surface")); + this.Bind(BorderBrushProperty, this.GetResourceObservable("Border")); BorderThickness = new Thickness(1); + var heading = Ui.Text(title, 13); heading.FontWeight = FontWeight.SemiBold; heading.MaxWidth = 480; + var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 20, RowSpacing = 6 }; + for (var i = 0; i < rows.Length; i++) + { + grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); + var row = rows[i]; var label = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 }; + if (row.Swatch is { } colour) label.Children.Add(new Border { Width = 6, Height = 6, Background = colour, CornerRadius = new CornerRadius(2), VerticalAlignment = VerticalAlignment.Center }); + var labelText = Ui.Text(row.Label, 12, "Secondary"); labelText.MaxWidth = 180; label.Children.Add(labelText); + var value = Ui.TableNumber(row.Value, 12); value.HorizontalAlignment = HorizontalAlignment.Right; + Grid.SetRow(label, i); grid.Children.Add(label); Grid.SetRow(value, i); Grid.SetColumn(value, 1); grid.Children.Add(value); + } + Child = Ui.Stack(heading, grid); + } + public static string Count(long value) => Display.Compact(value) + " · " + value.ToString("N0"); + public static DataTooltip Tokens(string title, TokenCounts counts) => new(title, + new("Total", Count(counts.Total)), new("Input", Count(counts.Input)), new("Output", Count(counts.Output)), + new("Cache write", Count(counts.CacheWrite)), new("Cache read", Count(counts.CacheRead)), new("Reasoning", Count(counts.ReasoningOutput))); + public static DataTooltip Day(LimitDay day) + { + var rows = new List { new("Use", day.IsFuture ? "Future day" : day.Used is { } use ? $"{use:0.##} % of the week" : "Collecting history") }; + if (!day.IsFuture && day.Used is not null) rows.Add(new("Source", day.Origin == UseOrigin.Estimated ? "Estimated from tokens" : "Measured")); + if (!day.IsFuture && day.Cumulative is { } cumulative) rows.Add(new("Cumulative", $"{cumulative:0.##} %")); + return new(day.Start.DateTime.ToString("D"), rows.ToArray()); + } + public override string ToString() => Title + "\n" + string.Join('\n', Rows.Select(r => r.Label + ": " + r.Value)); +} diff --git a/src/FinalToken.App/DesktopApp.cs b/src/FinalToken.App/DesktopApp.cs index 1856871..8da5ca7 100644 --- a/src/FinalToken.App/DesktopApp.cs +++ b/src/FinalToken.App/DesktopApp.cs @@ -91,10 +91,8 @@ public sealed class DesktopApp : Application } private async Task Refresh() { - if (engine is null || model.Refreshing) return; - model.Refreshing = true; - try { await engine.RefreshNowAsync(); } - finally { model.Refreshing = false; } + if (engine is null) return; + await model.RefreshAsync(() => engine.RefreshNowAsync()); } private async Task LoadHistory() { diff --git a/src/FinalToken.App/NeutralCheckBox.cs b/src/FinalToken.App/NeutralCheckBox.cs new file mode 100644 index 0000000..abde94b --- /dev/null +++ b/src/FinalToken.App/NeutralCheckBox.cs @@ -0,0 +1,18 @@ +using Avalonia; +using Avalonia.Controls; + +namespace FinalToken.App; + +/// Template reapplication never registers another checked handler. +public sealed class NeutralCheckBox : CheckBox +{ + public static readonly DirectProperty MarkVisibleProperty = + AvaloniaProperty.RegisterDirect(nameof(MarkVisible), c => c.MarkVisible); + private bool markVisible; + public bool MarkVisible => markVisible; + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + if (change.Property == IsCheckedProperty) SetAndRaise(MarkVisibleProperty, ref markVisible, IsChecked == true); + } +} diff --git a/src/FinalToken.App/PanelViewModel.cs b/src/FinalToken.App/PanelViewModel.cs index c937106..c905f1a 100644 --- a/src/FinalToken.App/PanelViewModel.cs +++ b/src/FinalToken.App/PanelViewModel.cs @@ -7,12 +7,15 @@ 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); + 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 IReadOnlyList AllModels { get; init; } = []; + public IReadOnlyList AllProjects { get; init; } = []; } public partial class PanelViewModel : ObservableObject @@ -25,6 +28,13 @@ public partial class PanelViewModel : ObservableObject [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 @@ -42,13 +52,17 @@ public partial class PanelViewModel : ObservableObject var hourly = Series(SeriesInterval.Hour); var daily = Series(SeriesInterval.Day); var details = new List(); + IReadOnlyList allModels = [], allProjects = []; 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 - l : now.AddDays(-14), now); + 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), - LimitAnalysis.Days(w.Window, instanceSamples, now), + 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, @@ -57,9 +71,10 @@ public partial class PanelViewModel : ObservableObject 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) is { } average ? new(reset, p.Provider.ToString(), average) : null, - new(now, p.Provider.ToString(), w.Window.UsedPercent)); + new(now, p.Provider.ToString(), w.Window.UsedPercent), analysis, w, now); })).ToArray(); - return new(hourly, daily, limits, Breakdown(true), Breakdown(false)) { Details = details }; + var models = Breakdown(true); var projects = Breakdown(false); + return new(hourly, daily, limits, models, projects) { Details = details, AllModels = allModels, AllProjects = allProjects }; IReadOnlyList Series(SeriesInterval interval) { @@ -77,6 +92,8 @@ public partial class PanelViewModel : ObservableObject .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); + var allRows = rows.Select(r => r with { Share = total == 0 ? 0 : r.Counts.Total / total }).ToArray(); + if (models) allModels = allRows; else allProjects = allRows; var top = rows.Take(8).ToList(); if (rows.Length > 8) top.Add(new($"Other ({rows.Length - 8})", rows.Skip(8).Aggregate(new TokenCounts(), (sum, r) => sum + r.Counts), 0, rows.Skip(8).SelectMany(r => r.Providers ?? []).Distinct().Order().ToArray())); @@ -102,6 +119,7 @@ public static class Display } 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"; @@ -120,6 +138,6 @@ public static class Display 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 {date.LocalDateTime:ddd HH:mm}"; + (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" }; } diff --git a/src/FinalToken.App/PanelWindow.cs b/src/FinalToken.App/PanelWindow.cs index 2d3ae2b..925cca9 100644 --- a/src/FinalToken.App/PanelWindow.cs +++ b/src/FinalToken.App/PanelWindow.cs @@ -20,6 +20,7 @@ public sealed class PanelWindow : Window private bool wide; private int limitColumns; private readonly Dictionary selectedDailyWindow = []; + private readonly BreakdownState modelBreakdown = new(), projectBreakdown = new(); public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload) { @@ -122,12 +123,12 @@ public sealed class PanelWindow : Window var chart = new Border { Child = DayView(entries[index]) }; var title = Ui.Text(group.Key + " · " + labels[index], 15); var stack = Ui.Stack(title); - var explanation = Ui.Text("Filled: this window · outline: previous window", 12, "Muted"); - void UpdateExplanation(LimitDetail item) => explanation.IsVisible = item.Days!.Previous.Count > 0 && item.Days.Current.Any(d => d.Used is not null); + var explanation = Ui.Text("Measured · Estimated from tokens (hatched) · faint: previous", 12, "Muted"); + void UpdateExplanation(LimitDetail item) => explanation.IsVisible = item.Days!.Current.Any(d => d.Used is not null); UpdateExplanation(entries[index]); if (entries.Length > 1) { - var selector = new ComboBox { ItemsSource = labels, SelectedIndex = index }; + var selector = new WindowSelector { ItemsSource = labels, SelectedIndex = index }; selector.SelectionChanged += (_, _) => { if (selector.SelectedIndex < 0) return; @@ -143,7 +144,7 @@ public sealed class PanelWindow : Window }), wide)); } var tokenHeader = new DockPanel(); - var toggle = new CheckBox { Content = "Include cache reads", IsChecked = model.IncludeCacheReads, HorizontalAlignment = HorizontalAlignment.Right }; + var toggle = new NeutralCheckBox { Content = "Include cache reads", IsChecked = model.IncludeCacheReads, HorizontalAlignment = HorizontalAlignment.Right }; toggle.IsCheckedChanged += (_, _) => model.IncludeCacheReads = toggle.IsChecked == true; DockPanel.SetDock(toggle, Dock.Right); tokenHeader.Children.Add(toggle); var tokenTitle = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 24, VerticalAlignment = VerticalAlignment.Center }; @@ -164,14 +165,17 @@ public sealed class PanelWindow : Window Legend(seriesNames), new UsageChart { Values = values.Select(v => v with { Value = Math.Max(0, v.Value - (model.IncludeCacheReads ? 0 : v.CacheRead)) }).ToArray(), SeriesNames = seriesNames, Interval = daily ? TimeSpan.FromDays(1) : TimeSpan.FromHours(1) })); content.Add(Ui.Columns([TokenChart("Tokens per hour", h.Hourly, false), TokenChart("Tokens per day", h.Daily, true)], wide)); - content.Add(Ui.Text("Limit history", 20)); - foreach (var limit in h.Limits.Where(l => l.Values.Count < 2)) - content.Add(Ui.Text($"{limit.Label} · Collecting history since {limit.Since?.LocalDateTime:dd.MM. HH:mm}", 12, "Muted")); - content.Add(Ui.Columns(h.Limits.Where(l => l.Values.Count >= 2).Select(limit => Ui.Card(Ui.Stack(Ui.Text(limit.Label, 15), - Ui.Text("Used · dashed: even pace · dotted: average forecast", 12, "Muted"), - new UsageChart { Values = limit.Values, Percent = true, LimitProvider = limit.Provider, Forecast = limit.Forecast, ForecastStart = limit.ForecastStart }))), wide)); + var windows = h.Limits.Where(l => l.Analysis?.Current.HasData == true).ToArray(); + if (windows.Length > 0) + { + content.Add(Ui.Text("Window charts", 20)); + content.Add(Ui.Columns(windows.Select(limit => Ui.Card(Ui.Stack(Ui.Text(limit.Label, 15), + Ui.Text("Measured · dashed: estimated · faint: previous · dotted: forecast", 12, "Muted"), new BurnUpChart(limit), + Ui.Text("Past instances · peak use", 12, "Muted"), new InstancePeaks(limit.Analysis!.Past, limit.Provider)))), wide)); + } content.Add(Ui.Text("Breakdown", 20)); - content.Add(Ui.Columns([Breakdown("By model", h.Models, false), Breakdown("By project", h.Projects, true)], wide)); + content.Add(Ui.Card(new BreakdownTable("By model", h.AllModels.Count > 0 ? h.AllModels : h.Models, false, model.ProviderFilter, modelBreakdown))); + content.Add(Ui.Card(new BreakdownTable("By project", h.AllProjects.Count > 0 ? h.AllProjects : h.Projects, true, model.ProviderFilter, projectBreakdown))); if (model.Diagnostics.Count > 0) { var lines = Ui.Stack(); @@ -189,7 +193,7 @@ public sealed class PanelWindow : Window var chip = new Border { Child = Ui.Mark(Display.State(pace.State), Brush.Parse("#0b0b0b")), Background = PaceBar.Colour(pace.State), CornerRadius = new CornerRadius(6), Padding = new Thickness(8, 4) }; DockPanel.SetDock(chip, Dock.Right); title.Children.Add(chip); title.Children.Add(Ui.Text(w.Provider + " · " + w.Label, 15)); var card = Ui.Stack(title, Ui.Text($"{w.UsedPercent:0.#} %", 36), Ui.Text("used", 12, "Muted"), new PaceBar(window) { Height = 10 }); - card.Children.Add(Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {reset.LocalDateTime:ddd HH:mm}" : "Reset unknown", 13, "Secondary")); + card.Children.Add(Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {Display.Projection(reset)}" : "Reset unknown", 13, "Secondary")); if (pace.Projection is { } projection) { var caption = Display.Forecast(projection, pace.State) + $" ({Display.Duration(w.ResetsAt!.Value - projection)} before reset)"; @@ -204,24 +208,27 @@ public sealed class PanelWindow : Window card.Children.Add(Ui.Text($"≈ {average:0.#} % at reset", 13, "Secondary")); if (detail?.Recent is { } recent) { - var line = Ui.Text($"Last 24 h: +{recent.Increase:0.#} %" + (recent.ReachesLimit is { } date ? $" · 100 % on {date.LocalDateTime:ddd HH:mm}" : $" · ≈ {recent.UseAtReset:0.#} % at reset"), 13, "Secondary"); - ToolTip.SetTip(line, $"{recent.PercentPerDay:0.##} %/day over {Display.Duration(recent.Span)} of samples"); card.Children.Add(line); + var line = Ui.Text($"Last {Display.Span(recent.Span)}: +{recent.Increase:0.#} %" + (recent.ReachesLimit is { } date ? $" · 100 % on {Display.Projection(date)}" : $" · ≈ {recent.UseAtReset:0.#} % at reset"), 13, "Secondary"); + ToolTip.SetTip(line, new DataTooltip("Recent rate", new("Rate", $"{recent.PercentPerDay:0.##} %/day"), new("Observed span", Display.Duration(recent.Span)))); card.Children.Add(line); } if (detail?.Days is { } days) { - card.Children.Add(Ui.Text(days.Today is { } today ? $"Today +{today:0.#} % of the week" : "Today · collecting a day baseline", 15)); + card.Children.Add(Ui.Text(days.Today is { } today ? days.TodayOrigin == UseOrigin.Estimated + ? $"Today ≈ +{today:0.#} % of the week (estimated)" : $"Today +{today:0.#} % of the week" : "Today · collecting a day baseline", 15)); card.Children.Add(Ui.Text($"Even pace {days.EvenPace:0.#} %/day", 13, "Secondary")); if (days.DailyBudget is { } budget) card.Children.Add(Ui.Text($"Budget {budget:0.#} %/day for {Display.Duration(w.ResetsAt!.Value - now)}", 15)); } if (now - w.SampleTime > model.ProbeInterval * 2) card.Children.Add(Ui.Text($"⚠ sample {Display.Duration(now - w.SampleTime)} old", 12, "Muted")); - var tile = Ui.Card(card); tile.Name = $"LimitTile-{w.Provider}-{w.Id}"; return tile; + var tile = Ui.Card(card); tile.Name = $"LimitTile-{w.Provider}-{w.Id}"; + ToolTip.SetTip(tile, new DataTooltip(w.Provider + " · " + w.Label, new("Used", $"{w.UsedPercent:0.##} %"), new("Expected", $"{pace.ElapsedFraction * 100:0.##} %"), + new("State", Display.State(pace.State)), new("Reset", w.ResetsAt is { } r ? Display.Projection(r) : "Unknown"), new("Sample", w.SampleTime.LocalDateTime.ToString("g")))); return tile; } private Control TokenTile(ProviderSnapshot provider, string label, TokenCounts counts) { var tile = Ui.Stack(Ui.Text(label, 12, "Secondary"), Ui.Text(Display.Compact(Math.Max(0, counts.Total - (model.IncludeCacheReads ? 0 : counts.CacheRead))), 32), new CompositionBar(counts, provider.Provider, model.IncludeCacheReads) { Height = 6 }); tile.Width = wide ? 164 : 188; tile.Margin = new Thickness(0, 8, 16, 0); - ToolTip.SetTip(tile, Display.Tokens(counts)); return tile; + ToolTip.SetTip(tile, DataTooltip.Tokens(provider.Provider + " · " + label, counts)); return tile; } private Control CompositionLegend() { @@ -248,43 +255,6 @@ public sealed class PanelWindow : Window } return legend; } - private Control Breakdown(string title, IReadOnlyList rows, bool projects) - { - var table = Ui.Stack(Ui.Text(title, 15)); - var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,90,140"), RowSpacing = 8, ColumnSpacing = 8 }; - var names = projects ? ShortProjectNames(rows.Select(r => r.Name).ToArray()) : rows.Select(r => r.Name).ToArray(); - Add(Ui.Text("Name", 12, "Muted"), 0, 0); Add(Ui.Text("Total", 12, "Muted"), 0, 1); Add(Ui.Text("Share", 12, "Muted"), 0, 2); - for (var i = 0; i < rows.Count; i++) - { - var row = rows[i]; var label = Ui.Text(names[i], 13); - label.TextWrapping = TextWrapping.NoWrap; label.TextTrimming = TextTrimming.CharacterEllipsis; - Control nameCell = label; - if (!projects && model.ProviderFilter is null && row.Providers is { Count: > 0 } rowProviders) - { - var cell = new DockPanel(); - foreach (var provider in rowProviders) - { - var dot = Ui.Mark("●", Ui.ProviderColour(provider, Ui.Dark(this))); dot.Margin = new Thickness(0, 0, 6, 0); - ToolTip.SetTip(dot, provider.ToString()); DockPanel.SetDock(dot, Dock.Left); cell.Children.Add(dot); - } - cell.Children.Add(label); nameCell = cell; - } - ToolTip.SetTip(nameCell, row.Name + "\n" + Display.Tokens(row.Counts)); Add(nameCell, i + 1, 0); - var total = Ui.TableNumber(Display.Compact(row.Counts.Total)); ToolTip.SetTip(total, Display.Tokens(row.Counts)); Add(total, i + 1, 1); - var share = new Grid { ColumnDefinitions = new ColumnDefinitions("*,50"), ColumnSpacing = 8 }; - share.Children.Add(new ProgressBar { Minimum = 0, Maximum = 1, Value = row.Share, Width = 82, MinWidth = 0, Height = 5, VerticalAlignment = VerticalAlignment.Center, - Foreground = model.ProviderFilter is { } p ? Ui.ProviderColour(p, Ui.Dark(this)) : Ui.Colour("Muted", Ui.Dark(this)) }); - var percent = Ui.TableNumber(row.Share.ToString("P1"), 12, "Secondary"); Grid.SetColumn(percent, 1); share.Children.Add(percent); - ToolTip.SetTip(share, row.Name + "\n" + Display.Tokens(row.Counts)); Add(share, i + 1, 2); - } - table.Children.Add(grid); if (rows.Count == 0) table.Children.Add(Ui.Text("No tokens in this range.", 12, "Muted")); - return Ui.Card(table); - void Add(Control c, int row, int col) - { - while (grid.RowDefinitions.Count <= row) grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); - Grid.SetRow(c, row); Grid.SetColumn(c, col); grid.Children.Add(c); - } - } public static string[] ShortProjectNames(string[] paths) { var parts = paths.Select(p => p.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries)).ToArray(); @@ -295,5 +265,11 @@ public sealed class PanelWindow : Window return string.Join('/', p.TakeLast(depth)); }).ToArray(); } + // Leave wheel events unhandled so they bubble to the page instead of changing selection. + private sealed class WindowSelector : ComboBox + { + protected override Type StyleKeyOverride => typeof(ComboBox); + protected override void OnPointerWheelChanged(Avalonia.Input.PointerWheelEventArgs e) { } + } public static int LimitColumnCount(double contentWidth) => contentWidth >= 1400 ? 3 : contentWidth >= 1200 ? 2 : 1; } diff --git a/src/FinalToken.App/SettingsWindow.cs b/src/FinalToken.App/SettingsWindow.cs index a3c766e..ee2c654 100644 --- a/src/FinalToken.App/SettingsWindow.cs +++ b/src/FinalToken.App/SettingsWindow.cs @@ -8,7 +8,7 @@ namespace FinalToken.App; public sealed class SettingsWindow : Window { - public SettingsWindow(Settings initial, PluginInstallStatus status, Func save, Action? quit = null) + public SettingsWindow(Settings initial, PluginInstallStatus status, Func save, Action? quit = null, Action? openFolder = null) { Title = "FinalToken settings"; Width = 760; Height = 900; MinWidth = 600; MinHeight = 500; Ui.Theme(this); var body = new StackPanel { Spacing = 16, Margin = new Thickness(24) }; @@ -42,7 +42,8 @@ public sealed class SettingsWindow : Window { try { - System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(DataPaths.DataDirectory) { UseShellExecute = true }); + if (openFolder is not null) openFolder(DataPaths.DataDirectory); + else System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(DataPaths.DataDirectory) { UseShellExecute = true }); } catch (Exception e) when (e is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception or InvalidOperationException) { error.Text = "Could not open the data folder."; } @@ -83,7 +84,7 @@ public sealed class SettingsWindow : Window } private static CheckBox Check(StackPanel parent, string label, bool value) { - var c = new CheckBox { Content = label, IsChecked = value, Name = label.Replace(" ", "") }; parent.Children.Add(c); return c; + var c = new NeutralCheckBox { Content = label, IsChecked = value, Name = label.Replace(" ", "") }; parent.Children.Add(c); return c; } private static Func PopupControls(StackPanel parent, string name, ProviderSettings config) { @@ -91,12 +92,14 @@ public sealed class SettingsWindow : Window row.Children.Add(Ui.Text(name)); var enabled = Check(row, "Popups enabled", config.PopupsEnabled); var ahead = Check(row, "Ahead", config.PopupAhead); var behind = Check(row, "Behind", config.PopupBehind); + foreach (var c in row.Children.OfType()) c.Name = name + c.Name; parent.Children.Add(row); return value => value with { PopupsEnabled = enabled.IsChecked == true, PopupAhead = ahead.IsChecked == true, PopupBehind = behind.IsChecked == true }; } private static Func ProviderControls(StackPanel parent, string name, ProviderSettings config) { parent.Children.Add(Ui.Text(name)); var enabled = Check(parent, "Enabled", config.Enabled); + enabled.Name = name + "Enabled"; parent.Children.Add(Ui.Text("CLI path (empty uses PATH)", 12, "Secondary")); var path = new TextBox { Name = name + "CliPath", Text = config.CliPath ?? "" }; parent.Children.Add(path); return () => config with { Enabled = enabled.IsChecked == true, CliPath = string.IsNullOrWhiteSpace(path.Text) ? null : path.Text.Trim() }; diff --git a/src/FinalToken.App/Ui.cs b/src/FinalToken.App/Ui.cs index 7ea9a11..c6f5ebf 100644 --- a/src/FinalToken.App/Ui.cs +++ b/src/FinalToken.App/Ui.cs @@ -54,27 +54,35 @@ public static class Ui presenter.Bind(ContentPresenter.FontWeightProperty, button.GetObservable(TemplatedControl.FontWeightProperty)); var border = new Border { Child = presenter, Padding = new Thickness(8, 6), CornerRadius = new CornerRadius(4) }; border.Bind(Border.BackgroundProperty, button.GetObservable(TemplatedControl.BackgroundProperty)); + border.BorderThickness = new Thickness(1); border.Bind(Border.BorderBrushProperty, button.GetObservable(TemplatedControl.BorderBrushProperty)); return border; }))); window.Styles.Add(segments); + var focusSegment = new Style(s => s.OfType().Class("segment").Class(":focus-visible")); + focusSegment.Setters.Add(new Setter(TemplatedControl.BorderBrushProperty, new DynamicResourceExtension("Ink"))); window.Styles.Add(focusSegment); var selected = new Style(s => s.OfType().Class("segment").Class(":checked")); selected.Setters.Add(new Setter(TemplatedControl.BackgroundProperty, new DynamicResourceExtension("Selection"))); selected.Setters.Add(new Setter(TemplatedControl.FontWeightProperty, FontWeight.SemiBold)); window.Styles.Add(selected); - var checks = new Style(s => s.OfType()); - checks.Setters.Add(new Setter(TemplatedControl.TemplateProperty, new FuncControlTemplate((check, _) => + var checks = new Style(s => s.OfType()); + checks.Setters.Add(new Setter(TemplatedControl.BorderBrushProperty, Brushes.Transparent)); + checks.Setters.Add(new Setter(TemplatedControl.TemplateProperty, new FuncControlTemplate((check, _) => { var glyph = Text("✓", 14); glyph.Name = "NeutralCheckGlyph"; glyph.HorizontalAlignment = HorizontalAlignment.Center; var box = new Border { Name = "NeutralCheckSurface", Child = glyph, Width = 20, Height = 20, CornerRadius = new CornerRadius(4), BorderThickness = new Thickness(1), VerticalAlignment = VerticalAlignment.Center }; box.Bind(Border.BackgroundProperty, box.GetResourceObservable("Selection")); box.Bind(Border.BorderBrushProperty, box.GetResourceObservable("Axis")); - glyph.IsVisible = check.IsChecked == true; check.IsCheckedChanged += (_, _) => glyph.IsVisible = check.IsChecked == true; + glyph.Bind(Visual.IsVisibleProperty, check.GetObservable(NeutralCheckBox.MarkVisibleProperty)); var label = new ContentPresenter { Margin = new Thickness(8, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center }; label.Bind(ContentPresenter.ContentProperty, check.GetObservable(ContentControl.ContentProperty)); label.Bind(ContentPresenter.ForegroundProperty, label.GetResourceObservable("Ink")); var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("20,*"), MinHeight = 32 }; - grid.Children.Add(box); Grid.SetColumn(label, 1); grid.Children.Add(label); return grid; + grid.Children.Add(box); Grid.SetColumn(label, 1); grid.Children.Add(label); + var focus = new Border { Child = grid, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(4) }; + focus.Bind(Border.BorderBrushProperty, check.GetObservable(TemplatedControl.BorderBrushProperty)); return focus; }))); window.Styles.Add(checks); + var focusCheck = new Style(s => s.OfType().Class(":focus-visible")); + focusCheck.Setters.Add(new Setter(TemplatedControl.BorderBrushProperty, new DynamicResourceExtension("Ink"))); window.Styles.Add(focusCheck); } // Explicit palettes keep every remaining Fluent control independent of the OS accent. public static FluentTheme NeutralTheme() diff --git a/tests/FinalToken.App.Tests/HeadlessTests.cs b/tests/FinalToken.App.Tests/HeadlessTests.cs index db9c88f..3fa2621 100644 --- a/tests/FinalToken.App.Tests/HeadlessTests.cs +++ b/tests/FinalToken.App.Tests/HeadlessTests.cs @@ -59,6 +59,22 @@ public sealed class HeadlessTests Dispatcher.UIThread.RunJobs(); panel.GetVisualDescendants().OfType().Single().SelectedIndex = 1; Assert.Contains(panel.GetVisualDescendants().OfType(), t => t.Text == "Claude · Week · Fable"); + var wheelSelector = panel.GetVisualDescendants().OfType().Single(); + wheelSelector.BringIntoView(); Dispatcher.UIThread.RunJobs(); using (panel.CaptureRenderedFrame()) { } + wheelSelector.Focus(); + var wheelViewport = panel.GetVisualDescendants().OfType().First(); + var beforeWheel = wheelViewport.Offset.Y; + panel.MouseWheel(wheelSelector.TranslatePoint(new Point(20, 16), panel)!.Value, new Vector(0, 1)); + Dispatcher.UIThread.RunJobs(); + Assert.Equal(1, wheelSelector.SelectedIndex); + Assert.True(wheelViewport.Offset.Y < beforeWheel); + foreach (var segment in panel.GetVisualDescendants().OfType().Where(b => b.Classes.Contains("segment"))) + { + segment.Focus(); var rangeBefore = model.Range; var providerBefore = model.ProviderFilter; + panel.MouseWheel(segment.TranslatePoint(new Point(8, 8), panel)!.Value, new Vector(0, -1)); + Assert.Equal(rangeBefore, model.Range); Assert.Equal(providerBefore, model.ProviderFilter); + } + wheelViewport.Offset = default; model.History = originalHistory; model.Snapshot = originalSnapshot with { Providers = originalSnapshot.Providers.Select(p => p.Provider == Provider.Claude ? p with { Windows = [] } : p).ToArray() }; Dispatcher.UIThread.RunJobs(); @@ -79,6 +95,12 @@ public sealed class HeadlessTests var selected = panel.GetVisualDescendants().OfType().First(b => b.Classes.Contains("segment") && b.IsChecked == true); Assert.Equal(theme == ThemeVariant.Dark ? "#ff383835" : "#ffe1e0d9", selected.Background?.ToString()); Assert.Equal(Avalonia.Media.FontWeight.SemiBold, selected.FontWeight); + selected.Focus(Avalonia.Input.NavigationMethod.Tab); Dispatcher.UIThread.RunJobs(); + Assert.Equal(theme == ThemeVariant.Dark ? "#fff0efec" : "#ff0b0b0b", selected.BorderBrush?.ToString()); + var neutralCheck = panel.GetVisualDescendants().OfType().Single(); + neutralCheck.Focus(Avalonia.Input.NavigationMethod.Tab); Dispatcher.UIThread.RunJobs(); + Assert.Equal(theme == ThemeVariant.Dark ? "#fff0efec" : "#ff0b0b0b", neutralCheck.BorderBrush?.ToString()); + Assert.True(neutralCheck.MarkVisible); var glyph = panel.GetVisualDescendants().OfType().Single(t => t.Name == "NeutralCheckGlyph"); Assert.Equal(theme == ThemeVariant.Dark ? "#fff0efec" : "#ff0b0b0b", glyph.Foreground?.ToString()); Assert.Equal(56, panel.GetVisualDescendants().OfType().Single(g => g.Name == "PanelHeader").Bounds.Height); @@ -90,17 +112,42 @@ public sealed class HeadlessTests Assert.Equal(sessionTile.Bounds.Y, weekTile.Bounds.Y); Assert.Equal(weekTile.Bounds.Y, codexLimit.Bounds.Y); Assert.True(sessionTile.Bounds.Height < weekTile.Bounds.Height); } - foreach (var (name, target) in new[] { ("week", "Week use per day"), ("tokens", "Tokens"), ("history", "Limit history"), ("breakdown", "Breakdown") }) + foreach (var (name, target) in new[] { ("week", "Week use per day"), ("tokens", "Tokens"), ("windows", "Window charts"), ("breakdown", "Breakdown") }) { var text = panel.GetVisualDescendants().OfType().First(t => t.Text == target); var position = text.TranslatePoint(default, viewport)!.Value; viewport.Offset = new Vector(0, viewport.Offset.Y + position.Y - 16); Save(panel, stem + "-" + name + ".png"); + if (name == "breakdown") + { + panel.GetVisualDescendants().OfType