app: redesign the panel and add limit forecasts and daily week use #6

Merged
schmidt.florian merged 14 commits from 5-panel-redesign into master 2026-10-15 19:06:05 +02:00
14 changed files with 592 additions and 101 deletions
Showing only changes of commit ab8d245df8 - Show all commits
+1 -1
View File
@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<Version>1.0.1</Version>
<Version>1.1.0</Version>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14</LangVersion>
<Nullable>enable</Nullable>
+15 -3
View File
@@ -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.
+116
View File
@@ -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<BreakdownRow> rows;
private readonly BreakdownState state;
private readonly string title;
private readonly bool projects;
private readonly Provider? filter;
public BreakdownTable(string title, IReadOnlyList<BreakdownRow> 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<BreakdownRow> SortRows(IEnumerable<BreakdownRow> 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);
}
}
}
+143
View File
@@ -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<LimitInstance> 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));
}
}
}
+27 -17
View File
@@ -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<DataTooltip> 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<DataTooltip> 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;
+46
View File
@@ -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);
/// <summary>D8: every data tooltip uses the same title and aligned label/value layout.</summary>
public sealed class DataTooltip : Border
{
public string Title { get; }
public IReadOnlyList<TooltipRow> 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<TooltipRow> { 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));
}
+2 -4
View File
@@ -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()
{
+18
View File
@@ -0,0 +1,18 @@
using Avalonia;
using Avalonia.Controls;
namespace FinalToken.App;
/// <summary>Template reapplication never registers another checked handler.</summary>
public sealed class NeutralCheckBox : CheckBox
{
public static readonly DirectProperty<NeutralCheckBox, bool> MarkVisibleProperty =
AvaloniaProperty.RegisterDirect<NeutralCheckBox, bool>(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);
}
}
+24 -6
View File
@@ -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<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);
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)
{
public IReadOnlyList<LimitDetail> Details { get; init; } = [];
public IReadOnlyList<BreakdownRow> AllModels { get; init; } = [];
public IReadOnlyList<BreakdownRow> 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<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
@@ -42,13 +52,17 @@ public partial class PanelViewModel : ObservableObject
var hourly = Series(SeriesInterval.Hour);
var daily = Series(SeriesInterval.Day);
var details = new List<LimitDetail>();
IReadOnlyList<BreakdownRow> 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<ChartValue> 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" };
}
+30 -54
View File
@@ -20,6 +20,7 @@ public sealed class PanelWindow : Window
private bool wide;
private int limitColumns;
private readonly Dictionary<Provider, string> 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<BreakdownRow> 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;
}
+6 -3
View File
@@ -8,7 +8,7 @@ namespace FinalToken.App;
public sealed class SettingsWindow : Window
{
public SettingsWindow(Settings initial, PluginInstallStatus status, Func<Settings, Task> save, Action? quit = null)
public SettingsWindow(Settings initial, PluginInstallStatus status, Func<Settings, Task> save, Action? quit = null, Action<string>? 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<ProviderSettings, ProviderSettings> 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<CheckBox>()) 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<ProviderSettings> 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() };
+12 -4
View File
@@ -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<ToggleButton>().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<ToggleButton>().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<CheckBox>());
checks.Setters.Add(new Setter(TemplatedControl.TemplateProperty, new FuncControlTemplate<CheckBox>((check, _) =>
var checks = new Style(s => s.OfType<NeutralCheckBox>());
checks.Setters.Add(new Setter(TemplatedControl.BorderBrushProperty, Brushes.Transparent));
checks.Setters.Add(new Setter(TemplatedControl.TemplateProperty, new FuncControlTemplate<NeutralCheckBox>((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<NeutralCheckBox>().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()
+98 -2
View File
@@ -59,6 +59,22 @@ public sealed class HeadlessTests
Dispatcher.UIThread.RunJobs();
panel.GetVisualDescendants().OfType<ComboBox>().Single().SelectedIndex = 1;
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Claude · Week · Fable");
var wheelSelector = panel.GetVisualDescendants().OfType<ComboBox>().Single();
wheelSelector.BringIntoView(); Dispatcher.UIThread.RunJobs(); using (panel.CaptureRenderedFrame()) { }
wheelSelector.Focus();
var wheelViewport = panel.GetVisualDescendants().OfType<ScrollViewer>().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<ToggleButton>().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<ToggleButton>().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<NeutralCheckBox>().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<TextBlock>().Single(t => t.Name == "NeutralCheckGlyph");
Assert.Equal(theme == ThemeVariant.Dark ? "#fff0efec" : "#ff0b0b0b", glyph.Foreground?.ToString());
Assert.Equal(56, panel.GetVisualDescendants().OfType<Grid>().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<TextBlock>().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<Button>().Single(b => b.Content as string == "Show all 110").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Save(panel, stem + "-breakdown-expanded.png");
Assert.Contains(panel.GetVisualDescendants().OfType<Button>(), b => b.Content as string == "Show top 8");
panel.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Show top 8").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
}
}
var prior = viewport.Offset;
model.Snapshot = model.Snapshot! with { MadeAt = DateTimeOffset.UtcNow }; Dispatcher.UIThread.RunJobs();
Assert.Equal(prior, viewport.Offset);
}
var earlyModel = FakeData.EarlyResetModel();
var earlyPanel = new PanelWindow(earlyModel, () => { }, () => { }, () => { }, () => { });
earlyPanel.Show();
var earlyTile = earlyPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
Assert.DoesNotContain(earlyTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains("at reset") == true || t.Text?.Contains("100 % on") == true || t.Text?.StartsWith("Last ") == true);
Assert.Null(Assert.Single(earlyModel.History.Limits).Forecast);
Assert.All(Assert.Single(earlyModel.History.Limits).Analysis!.Past, instance => Assert.True(instance.End <= earlyModel.Snapshot!.MadeAt));
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
earlyPanel.Width = width; earlyPanel.Height = height; earlyPanel.RequestedThemeVariant = theme;
var viewport = earlyPanel.GetVisualDescendants().OfType<ScrollViewer>().First(); viewport.Offset = default;
Save(earlyPanel, $"panel-{width}x{height}-{theme}-early-limits.png");
var heading = earlyPanel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "Window charts");
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(earlyPanel, $"panel-{width}x{height}-{theme}-early-windows.png");
}
earlyPanel.Close();
panel.Width = 1000; panel.Height = 900;
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default; Save(panel, "panel-1000x900-light.png");
panel.Width = 1500; panel.Height = 1000;
@@ -117,6 +164,46 @@ public sealed class HeadlessTests
Save(panel, $"panel-{width}x{height}-{theme}-collecting-days.png");
}
model.History = originalHistory;
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var weekData = originalHistory.Details.Single(d => d.Provider == Provider.Claude && d.Id == "week").Days!;
Assert.Contains(weekData.Current, d => d.Origin == UseOrigin.Estimated);
var future = DataTooltip.Day(new(DateTimeOffset.Now.AddDays(1), DateTimeOffset.Now.AddDays(2), null, 42, false, true));
Assert.DoesNotContain(future.Rows, row => row.Label == "Cumulative");
var types = new (string Name, DataTooltip Tip)[]
{
("day-estimated", DataTooltip.Day(weekData.Current.First(d => d.Origin == UseOrigin.Estimated))),
("day-measured", DataTooltip.Day(weekData.Current.Last(d => d.Used is not null && d.Origin == UseOrigin.Measured))),
("future-day", future),
("project", DataTooltip.Tokens("D:/Projects/Customer/Workspace/Project-with-a-long-name", new(100000000, 1900000000, 10000000, 53670717, 1234567, 2063670717))),
("tile", (DataTooltip)ToolTip.GetTip(panel.GetVisualDescendants().OfType<Border>().First(b => b.Name == "LimitTile-Claude-week"))!),
("tokens", DataTooltip.Tokens("Claude - This week", originalSnapshot.Providers[0].Week)),
};
var limit = originalHistory.Limits.Single(l => l.Provider == Provider.Claude && l.Window!.Window.Id == "week");
CaptureChartTip("burnup", new BurnUpChart(limit), new Point(240, 100));
CaptureChartTip("past-instance", new InstancePeaks(limit.Analysis!.Past, Provider.Claude), new Point(30, 30));
CaptureChartTip("past-limit-reached", new InstancePeaks(limit.Analysis!.Past, Provider.Claude), new Point(600, 30));
CaptureChartTip("hourly", new UsageChart { Values = originalHistory.Hourly }, new Point(60, 170));
CaptureChartTip("daily", new UsageChart { Values = originalHistory.Daily, Interval = TimeSpan.FromDays(1) }, new Point(60, 170));
CaptureChartTip("composition", new CompositionBar(originalSnapshot.Providers[0].Week, Provider.Claude, true) { Height = 8 }, new Point(100, 4));
void CaptureChartTip(string name, Control chartControl, Point hover)
{
var window = new Window { Width = 740, Height = 600, RequestedThemeVariant = theme }; Ui.Theme(window);
var content = Ui.Stack(Ui.Text(name, 20), chartControl); content.Margin = new Thickness(24); window.Content = content;
window.Show(); Dispatcher.UIThread.RunJobs(); using (window.CaptureRenderedFrame()) { }
window.MouseMove(chartControl.TranslatePoint(hover, window)!.Value);
var actualTip = Assert.IsType<DataTooltip>(ToolTip.GetTip(chartControl));
window.MouseMove(new Point(0, 0)); ToolTip.SetIsOpen(chartControl, false);
content.Children.Add(new DataTooltip(actualTip.Title, actualTip.Rows.ToArray()));
Save(window, $"tooltip-{name}-{theme}.png"); window.Close();
}
foreach (var (name, tip) in types)
{
var tooltipWindow = new Window { Width = 620, Height = 300, RequestedThemeVariant = theme };
Ui.Theme(tooltipWindow); tooltipWindow.Content = new Border { Child = tip, Padding = new Thickness(24), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
tooltipWindow.Show(); Save(tooltipWindow, $"tooltip-{name}-{theme}.png"); tooltipWindow.Close();
}
}
model.Snapshot = FakeData.Snapshot(DateTimeOffset.UtcNow, true);
Dispatcher.UIThread.RunJobs(); panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
Save(panel, "panel-unavailable.png");
@@ -133,10 +220,19 @@ public sealed class HeadlessTests
expander.IsExpanded = true; panel.UpdateLayout();
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = new Vector(0, 100000);
Save(panel, "panel-diagnostics-expanded.png"); panel.Close();
string? folder = null; var quitCalls = 0; var saveCalls = 0;
var actions = new SettingsWindow(new(), new(PluginInstallState.NoHostFound), _ => { saveCalls++; return Task.CompletedTask; }, () => quitCalls++, path => folder = path);
actions.Show();
void ClickSettings(string text) => actions.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == text).RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
ClickSettings("Open folder"); Assert.Equal(DataPaths.DataDirectory, folder);
ClickSettings("Quit FinalToken"); Assert.Equal(1, quitCalls);
ClickSettings("Cancel"); Assert.False(actions.IsVisible); Assert.Equal(0, saveCalls);
Settings? saved = null;
var initial = new Settings { StartWithOs = true, StreamDeckInstallMode = InstallMode.Automatic, DismissedPluginVersion = "0.9" };
var settings = new SettingsWindow(initial, new(PluginInstallState.Outdated, "1.0", "0.9"), value => { saved = value; return Task.CompletedTask; }, () => { });
settings.Show(); Save(settings, "settings.png");
var providerNames = settings.GetVisualDescendants().OfType<CheckBox>().Select(c => c.Name).ToArray();
Assert.Equal(providerNames.Length, providerNames.Distinct().Count());
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
settings.RequestedThemeVariant = theme;
@@ -184,7 +280,7 @@ public sealed class HeadlessTests
var chartWindow = new Window { Content = chart, Width = 400, Height = 180 };
chartWindow.Show();
using (chartWindow.CaptureRenderedFrame()) { }
chartWindow.MouseMove(new Point(65, 80));
chartWindow.MouseMove(new Point(200, 100));
Assert.Contains(123456.ToString("N0"), ToolTip.GetTip(chart)?.ToString()); chartWindow.Close();
var polishShots = shots;
Directory.CreateDirectory(polishShots);
+54 -7
View File
@@ -5,6 +5,37 @@ namespace FinalToken.App.Tests;
public sealed class ViewModelTests
{
[Fact] public async Task RefreshIgnoresConcurrentRequestsAndClearsGuardAfterFailure()
{
var model = new PanelViewModel(); var completion = new TaskCompletionSource(); var calls = 0;
var first = model.RefreshAsync(() => { calls++; return completion.Task; });
Assert.True(model.Refreshing);
await model.RefreshAsync(() => { calls++; return Task.CompletedTask; });
Assert.Equal(1, calls); completion.SetResult(); await first; Assert.False(model.Refreshing);
await Assert.ThrowsAsync<IOException>(() => model.RefreshAsync(() => throw new IOException("fixture")));
Assert.False(model.Refreshing);
}
[Theory]
[InlineData(-1, "now")]
[InlineData(0, "now")]
[InlineData(59, "1 min")]
[InlineData(3600, "1 h 0 min")]
[InlineData(90061, "1 d 1 h")]
public void DurationUsesDaysHoursAndRoundedMinutes(int seconds, string expected)
=> Assert.Equal(expected, Display.Duration(TimeSpan.FromSeconds(seconds)));
[Theory]
[InlineData(PaceState.Ahead, "\u25b2 Ahead")]
[InlineData(PaceState.Behind, "\u25bc Behind")]
[InlineData(PaceState.OnTrack, "\u2713 On track")]
[InlineData(PaceState.Unknown, "? Pace unknown")]
public void StatusChipsAlwaysNameTheirState(PaceState state, string expected) => Assert.Equal(expected, Display.State(state));
[Fact] public void BreakdownSortingUsesTheSelectedNumericColumn()
{
BreakdownRow[] rows = [new("a", new(Input: 30, Output: 2, Total: 32), .4), new("b", new(Input: 10, Output: 40, Total: 50), .6)];
Assert.Equal("b", BreakdownTable.SortRows(rows, BreakdownColumn.Total, true).First().Name);
Assert.Equal("a", BreakdownTable.SortRows(rows, BreakdownColumn.Input, true).First().Name);
Assert.Equal("a", BreakdownTable.SortRows(rows, BreakdownColumn.Output, false).First().Name);
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
@@ -129,7 +160,7 @@ internal static class FakeData
public static Snapshot Snapshot(DateTimeOffset now, bool unavailable = false) => new()
{
MadeAt = now, RefreshInterval = TimeSpan.FromSeconds(60), Providers =
[new(Provider.Claude, ProviderStatus.Available, null, [Window(Provider.Claude, "session", "Session · 5 h", 12, now, 5, 1), Window(Provider.Claude, "week", "Week · all models", 70, now, 168, 84)],
[new(Provider.Claude, ProviderStatus.Available, null, [Window(Provider.Claude, "session", "Session · 5 h", 12, now, 5, 1), Window(Provider.Claude, "week", "Week · all models", 98, now, 168, 24)],
new(12000000, 218000000, 2000000, 47000000, 0, 279000000), new(4000000, 6000000, 1000000, 1600000, 0, 12600000), new(85000000, 1920000000, 16000000, 259000000, 0, 2280000000)),
new(Provider.Codex, unavailable ? ProviderStatus.Unavailable : ProviderStatus.Available, unavailable ? "CLI is not installed. Token history remains available." : null,
[Window(Provider.Codex, "secondary", "Week", 86, now, 168, 24)],
@@ -137,6 +168,22 @@ internal static class FakeData
};
private static WindowSnapshot Window(Provider provider, string id, string label, double percent, DateTimeOffset now, int hours, int resetHours)
{ var w = new LimitWindow(provider, id, label, percent, now.AddHours(resetHours), TimeSpan.FromHours(hours), now.AddMinutes(-3), "fixture"); return new(w, Pace.Calculate(w, now)); }
public static PanelViewModel EarlyResetModel()
{
var now = DateTimeOffset.UtcNow;
var transition = now.AddHours(-1);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-early", Guid.NewGuid().ToString("N")), new DiagnosticLog());
var snapshot = Snapshot(now);
var codex = snapshot.Providers.Single(p => p.Provider == Provider.Codex);
var window = codex.Windows[0].Window with { UsedPercent = 2, ResetsAt = transition.AddDays(7), SampleTime = now };
var previous = window with { ResetsAt = transition.AddDays(5), SampleTime = transition.AddDays(-1), UsedPercent = 40 };
store.AddLimits([previous, window with { SampleTime = transition, UsedPercent = 1 }, window]);
var start = previous.ResetsAt!.Value - previous.Length!.Value;
void Add(DateTimeOffset time, long input, string id) => store.Add(new(Provider.Codex, time, "gpt-6.1-sol", "Fixture/Project", new(Input: input, Total: input), id));
Add(start, 1000000, "a"); Add(previous.SampleTime.AddHours(1), 5000000, "b"); Add(transition, 100000, "c");
snapshot = snapshot with { Providers = [codex with { Windows = [new(window, Pace.Calculate(window, now))] }] };
return new() { Snapshot = snapshot, History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
}
public static PanelViewModel Model(bool unavailable = false)
{
var now = DateTimeOffset.UtcNow;
@@ -144,20 +191,20 @@ internal static class FakeData
var snapshot = Snapshot(now, unavailable);
foreach (var provider in snapshot.Providers)
{
for (var i = 0; i < 168; i++)
for (var i = 0; i < 336; i++)
{
var input = 1000000 + i * 10000; var cache = input * 8;
store.Add(new(provider.Provider, now.AddHours(-168 + i), provider.Provider == Provider.Claude ? "claude-fable" : "gpt-6.1-sol",
store.Add(new(provider.Provider, now.AddHours(-336 + i), provider.Provider == Provider.Claude ? "claude-fable" : "gpt-6.1-sol",
$"D:/Projects/Customer-{i % 110}/Workspace/Project-{i % 110}",
provider.Provider == Provider.Claude ? new(input, cache, 200000, 500000, 0, input + cache + 700000) : new(input + cache, cache, 0, 500000, 100000, input + cache + 500000), $"{provider.Provider}-{i}"));
}
foreach (var ws in provider.Windows.Where(w => w.Window.Length > TimeSpan.FromDays(1)))
foreach (var ws in provider.Windows)
{
var w = ws.Window; var start = w.ResetsAt!.Value - w.Length!.Value;
for (var i = 0; i <= (int)(now - start).TotalHours; i += 3)
for (var i = provider.Provider == Provider.Claude && w.Length > TimeSpan.FromDays(1) ? (int)(now - start).TotalHours - 24 : 0; i <= (int)(now - start).TotalHours; i += w.Length > TimeSpan.FromDays(1) ? 3 : 1)
store.AddLimits([w with { SampleTime = start.AddHours(i), UsedPercent = w.UsedPercent * i / (now - start).TotalHours }]);
for (var i = 0; i < 168; i += 6)
store.AddLimits([w with { ResetsAt = w.ResetsAt.Value.AddDays(-7), SampleTime = start.AddDays(-7).AddHours(i), UsedPercent = i * .5 }]);
for (var i = 0; i < (int)w.Length!.Value.TotalHours; i += w.Length > TimeSpan.FromDays(1) ? 6 : 1)
store.AddLimits([w with { ResetsAt = w.ResetsAt.Value - w.Length.Value, SampleTime = start - w.Length.Value + TimeSpan.FromHours(i), UsedPercent = 100.0 * i / w.Length.Value.TotalHours }]);
}
}
return new() { Snapshot = snapshot, Message = "Updated just now", History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };