app: show the reset history of each long limit window

A Resets section after the window charts gives, per provider, totals for
the listed instances, a timeline with each burn-up and the skipped time,
early resets by local hour and weekday, and a sortable instance table with
a detailed tooltip per row (D8, D12). The breakdown and reset tables share
their sorting, header and expander code.

Refs #14
This commit is contained in:
Florian Schmidt
2026-10-18 10:07:40 +02:00
parent 1c3f857a2c
commit e39a244751
13 changed files with 612 additions and 25 deletions
+7 -2
View File
@@ -13,7 +13,8 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
## Panel and visual rules ## Panel and visual rules
- Keep this order: fixed 56 px header; Limits; Week use per day; Tokens (totals, hourly and daily - Keep this order: fixed 56 px header; Limits; Week use per day; Tokens (totals, hourly and daily
charts); Window charts (current-instance burn-up and past peaks); Breakdown by model and project; collapsed Diagnostics, hidden when empty. charts); Window charts (current-instance burn-up and past peaks); Resets (one full-width card per
provider); Breakdown by model and project; collapsed Diagnostics, hidden when empty.
Preserve scroll offset on snapshots. Sections have two columns from 1200 px content width; 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. 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 - Follow the OS light/dark theme through `Ui.Theme` and `Ui.NeutralTheme`. Selection never uses
@@ -50,7 +51,8 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
have a 2 px surface gap; below 6 px width remove gaps and snap shared edges to physical pixels. have a 2 px surface gap; below 6 px width remove gaps and snap shared edges to physical pixels.
Breakdowns show eight rows plus expandable Other; keep every detail column sortable and right-aligned. 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 - 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. days by index and burn-ups by elapsed time. The Resets timeline puts real instances side by side
on one time axis without joining their lines; hatch skipped time and mark observed resets (D12).
Burn-ups use solid measured and lighter dashed estimated lines, with no point markers. 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 - 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 counts, optional series swatches. Future days have no cumulative value. Share one date formatter
@@ -62,3 +64,6 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
Instances start at reset minus length and end at reset or the next start. Keep gaps unassigned; Instances start at reset minus length and end at reset or the next start. Keep gaps unassigned;
never infer short windows or overlap a sampled window with an inferred one (D7). Label real dates. never infer short windows or overlap a sampled window with an inferred one (D7). Label real dates.
Page wheel events must never change a selection: WindowSelector bubbles them to the scroll view. Page wheel events must never change a selection: WindowSelector bubbles them to the scroll view.
- Resets use the shared detail-table sorting, headers, row placement and expansion. Preserve
the selected window, sort and expansion on renders. Money is invariant USD at API list prices;
unknown models stay unpriced, and percent-derived values and token estimates carry `≈` (D13).
+7 -18
View File
@@ -8,12 +8,7 @@ using FinalToken.Core;
namespace FinalToken.App; namespace FinalToken.App;
public enum BreakdownColumn { Name, Total, Share, Input, Output, CacheWrite, CacheRead, Reasoning } public enum BreakdownColumn { Name, Total, Share, Input, Output, CacheWrite, CacheRead, Reasoning }
public sealed class BreakdownState public sealed class BreakdownState() : TableState<BreakdownColumn>(BreakdownColumn.Total);
{
public bool Expanded { get; set; }
public BreakdownColumn Sort { get; set; } = BreakdownColumn.Total;
public bool Descending { get; set; } = true;
}
public sealed class BreakdownTable : StackPanel public sealed class BreakdownTable : StackPanel
{ {
@@ -29,21 +24,21 @@ public sealed class BreakdownTable : StackPanel
} }
public static IReadOnlyList<BreakdownRow> SortRows(IEnumerable<BreakdownRow> rows, BreakdownColumn column, bool descending) 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(); if (column == BreakdownColumn.Name) return DetailTable.Sort(rows, r => r.Name, descending, StringComparer.OrdinalIgnoreCase).ToArray();
double Key(BreakdownRow r) => column switch double Key(BreakdownRow r) => column switch
{ {
BreakdownColumn.Total => r.Counts.Total, BreakdownColumn.Share => r.Share, BreakdownColumn.Input => r.Counts.Input, 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.Output => r.Counts.Output, BreakdownColumn.CacheWrite => r.Counts.CacheWrite,
BreakdownColumn.CacheRead => r.Counts.CacheRead, _ => r.Counts.ReasoningOutput BreakdownColumn.CacheRead => r.Counts.CacheRead, _ => r.Counts.ReasoningOutput
}; };
return (descending ? rows.OrderByDescending(Key) : rows.OrderBy(Key)).ThenBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray(); return DetailTable.Sort(rows, Key, descending).ThenBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray();
} }
private void RenderTable() private void RenderTable()
{ {
Children.Clear(); var header = new DockPanel(); Children.Clear(); var header = new DockPanel();
if (rows.Count > 8) if (rows.Count > 8)
{ {
var expand = Ui.Button(state.Expanded ? "Show top 8" : $"Show all {rows.Count}", () => { state.Expanded = !state.Expanded; RenderTable(); }); var expand = DetailTable.Expansion(rows.Count, state, RenderTable);
DockPanel.SetDock(expand, Dock.Right); header.Children.Add(expand); DockPanel.SetDock(expand, Dock.Right); header.Children.Add(expand);
} }
header.Children.Add(Ui.Text(title, 15)); Children.Add(header); header.Children.Add(Ui.Text(title, 15)); Children.Add(header);
@@ -61,12 +56,7 @@ public sealed class BreakdownTable : StackPanel
for (var c = 0; c < (reasoning ? 8 : 7); c++) for (var c = 0; c < (reasoning ? 8 : 7); c++)
{ {
var column = (BreakdownColumn)c; var column = (BreakdownColumn)c;
var button = Ui.Button(headers[c] + (state.Sort == column ? state.Descending ? " ↓" : " ↑" : ""), () => var button = DetailTable.Header(headers[c], column, state, RenderTable, title.Replace(" ", "") + "Sort" + column, c == 0);
{
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); Add(button, 0, c);
} }
var names = projects ? PanelWindow.ShortProjectNames(visible.Select(r => r.Name).ToArray()) : visible.Select(r => r.Name).ToArray(); var names = projects ? PanelWindow.ShortProjectNames(visible.Select(r => r.Name).ToArray()) : visible.Select(r => r.Name).ToArray();
@@ -105,12 +95,11 @@ public sealed class BreakdownTable : StackPanel
ToolTip.SetTip(value, DataTooltip.Tokens(row.Name, counts)); Add(value, i + 1, c); 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 }); Children.Add(DetailTable.Scroll(grid));
if (rows.Count == 0) Children.Add(Ui.Text("No tokens in this range.", 12, "Muted")); if (rows.Count == 0) Children.Add(Ui.Text("No tokens in this range.", 12, "Muted"));
void Add(Control control, int row, int column) void Add(Control control, int row, int column)
{ {
while (grid.RowDefinitions.Count <= row) grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); DetailTable.Add(grid, control, row, column);
Grid.SetRow(control, row); Grid.SetColumn(control, column); grid.Children.Add(control);
} }
} }
} }
+1 -1
View File
@@ -9,7 +9,7 @@ namespace FinalToken.App;
public sealed record TooltipRow(string Label, string Value, IBrush? Swatch = null); 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> /// <summary>D8: every data tooltip uses the same title and aligned label/value layout.</summary>
public sealed class DataTooltip : Border public sealed partial class DataTooltip : Border
{ {
public string Title { get; } public string Title { get; }
public IReadOnlyList<TooltipRow> Rows { get; } public IReadOnlyList<TooltipRow> Rows { get; }
+43
View File
@@ -0,0 +1,43 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
namespace FinalToken.App;
public class TableState<TColumn>(TColumn sort) where TColumn : struct, Enum
{
public bool Expanded { get; set; }
public TColumn Sort { get; set; } = sort;
public bool Descending { get; set; } = true;
}
/// <summary>Shared sorting, headers, row placement and expansion for detail tables.</summary>
public static class DetailTable
{
public static IOrderedEnumerable<TRow> Sort<TRow, TKey>(IEnumerable<TRow> rows, Func<TRow, TKey> key,
bool descending, IComparer<TKey>? comparer = null) =>
descending ? rows.OrderByDescending(key, comparer) : rows.OrderBy(key, comparer);
public static Button Header<TColumn>(string label, TColumn column, TableState<TColumn> state,
Action render, string name, bool first = false) where TColumn : struct, Enum
{
var button = Ui.Button(label + (state.Sort.Equals(column) ? state.Descending ? " ↓" : " ↑" : ""), () =>
{
state.Descending = !state.Sort.Equals(column) || !state.Descending; state.Sort = column; render();
});
button.Name = name; button.Padding = new Thickness(0, 4);
button.HorizontalAlignment = first ? HorizontalAlignment.Left : HorizontalAlignment.Right;
return button;
}
public static Button Expansion<TColumn>(int count, TableState<TColumn> state, Action render) where TColumn : struct, Enum =>
Ui.Button(state.Expanded ? "Show top 8" : $"Show all {count}", () => { state.Expanded = !state.Expanded; render(); });
public static void Add(Grid grid, 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);
}
public static ScrollViewer Scroll(Grid grid) => new() { Content = grid,
HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Disabled };
}
+23 -4
View File
@@ -14,6 +14,7 @@ public sealed record HistoryView(IReadOnlyList<ChartValue> Hourly, IReadOnlyList
IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> Projects) IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> Projects)
{ {
public IReadOnlyList<LimitDetail> Details { get; init; } = []; public IReadOnlyList<LimitDetail> Details { get; init; } = [];
public IReadOnlyList<ResetHistory> Resets { get; init; } = [];
} }
public partial class PanelViewModel : ObservableObject public partial class PanelViewModel : ObservableObject
@@ -50,14 +51,25 @@ public partial class PanelViewModel : ObservableObject
var hourly = Series(SeriesInterval.Hour); var hourly = Series(SeriesInterval.Hour);
var daily = Series(SeriesInterval.Day); var daily = Series(SeriesInterval.Day);
var details = new List<LimitDetail>(); var details = new List<LimitDetail>();
var resets = new List<ResetHistory>();
var limits = providers.SelectMany(p => p.Windows.Select(w => var limits = providers.SelectMany(p => p.Windows.Select(w =>
{ {
var samples = store.LimitSamples(p.Provider, w.Window.Id, from, now); var instanceFrom = w.Window.ResetsAt is { } r && w.Window.Length is { } l
var instanceSamples = store.LimitSamples(p.Provider, w.Window.Id, ? r - l * 9 - TimeSpan.FromMinutes(15) : now.AddDays(-14);
w.Window.ResetsAt is { } r && w.Window.Length is { } l ? r - l * 9 - TimeSpan.FromMinutes(15) : now.AddDays(-14), now); var resetFrom = from == DateTimeOffset.MinValue ? from : from - (w.Window.Length ?? TimeSpan.Zero) - TimeSpan.FromMinutes(15);
var series = store.LimitSamples(w.Window, resetFrom < instanceFrom ? resetFrom : instanceFrom, now);
var samples = series.Where(s => s.SampleTime >= from).ToArray();
var instanceSamples = series.Where(s => s.SampleTime >= instanceFrom).ToArray();
var tokens = w.Window.ResetsAt is { } tokenReset && w.Window.Length is { } tokenLength 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) : []; ? store.TokenSeriesByModel(p.Provider, tokenReset - tokenLength * 9 - TimeSpan.FromMinutes(15), now, SeriesInterval.Hour) : [];
var analysis = LimitAnalysis.Analyze(w.Window, instanceSamples, tokens, now); var analysis = LimitAnalysis.Analyze(w.Window, instanceSamples, tokens, now);
if (w.Window.Length > TimeSpan.FromDays(1))
{
var tokenFrom = series.Where(s => s.ResetsAt is not null).Select(s => s.ResetsAt!.Value - s.Length!.Value)
.Append(w.Window.ResetsAt is { } resetAt ? resetAt - w.Window.Length.Value : now).Min();
resets.Add(LimitAnalysis.Resets(w.Window, series,
store.TokenSeriesByModel(p.Provider, tokenFrom, now, SeriesInterval.Hour), from, now));
}
details.Add(new(p.Provider, w.Window.Id, LimitAnalysis.Recent(w.Window, instanceSamples, now, w.Pace), details.Add(new(p.Provider, w.Window.Id, LimitAnalysis.Recent(w.Window, instanceSamples, now, w.Pace),
analysis?.Days, analysis?.Days,
instanceSamples.Where(s => LimitAnalysis.SameInstance(s, w.Window)).Select(s => s.SampleTime).DefaultIfEmpty(w.Window.SampleTime).Min())); instanceSamples.Where(s => LimitAnalysis.SameInstance(s, w.Window)).Select(s => s.SampleTime).DefaultIfEmpty(w.Window.SampleTime).Min()));
@@ -71,7 +83,7 @@ public partial class PanelViewModel : ObservableObject
new(now, p.Provider.ToString(), w.Window.UsedPercent), analysis, w, now); new(now, p.Provider.ToString(), w.Window.UsedPercent), analysis, w, now);
})).ToArray(); })).ToArray();
var models = Breakdown(true); var projects = Breakdown(false); var models = Breakdown(true); var projects = Breakdown(false);
return new(hourly, daily, limits, models, projects) { Details = details }; return new(hourly, daily, limits, models, projects) { Details = details, Resets = resets };
IReadOnlyList<ChartValue> Series(SeriesInterval interval) IReadOnlyList<ChartValue> Series(SeriesInterval interval)
{ {
@@ -135,4 +147,11 @@ public static class Display
public static string Forecast(DateTimeOffset date, PaceState state, TimeProvider? clock = null) => public static string Forecast(DateTimeOffset date, PaceState state, TimeProvider? clock = null) =>
(state == PaceState.Ahead ? "⚠ " : "At this pace ") + "100 % on " + Projection(date, clock); (state == PaceState.Ahead ? "⚠ " : "At this pace ") + "100 % on " + Projection(date, clock);
public static string State(PaceState state) => state switch { PaceState.OnTrack => "✓ On track", PaceState.Ahead => "▲ Ahead", PaceState.Behind => "▼ Behind", _ => "? Pace unknown" }; public static string State(PaceState state) => state switch { PaceState.OnTrack => "✓ On track", PaceState.Ahead => "▲ Ahead", PaceState.Behind => "▼ Behind", _ => "? Pace unknown" };
public static string Money(decimal? value) => value is { } dollars
? "≈ $" + dollars.ToString(dollars >= 100 ? "N0" : "N2", System.Globalization.CultureInfo.InvariantCulture) : "Unpriced";
public static string Limits(double percent) => "≈ " + (percent / 100).ToString("0.0", System.Globalization.CultureInfo.InvariantCulture) + " limits";
public static string ResetPercent(double percent, UseOrigin origin) => (origin == UseOrigin.Estimated ? "≈ " : "") +
percent.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture) + " %";
public static string ResetDate(DateTimeOffset time, TimeProvider clock) => TimeZoneInfo.ConvertTime(time, clock.LocalTimeZone).ToString("MM-dd HH:mm");
public static string ResetDuration(TimeSpan span) => span <= TimeSpan.Zero ? "0 min" : Duration(span);
} }
+34
View File
@@ -21,6 +21,8 @@ public sealed class PanelWindow : Window
private bool wide; private bool wide;
private int limitColumns; private int limitColumns;
private readonly Dictionary<Provider, string> selectedDailyWindow = []; private readonly Dictionary<Provider, string> selectedDailyWindow = [];
private readonly Dictionary<Provider, WindowSeries> selectedResetWindow = [];
private readonly Dictionary<WindowSeries, TableState<ResetColumn>> resetTables = [];
private readonly BreakdownState modelBreakdown = new(), projectBreakdown = new(); private readonly BreakdownState modelBreakdown = new(), projectBreakdown = new();
public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload, TimeProvider? clock = null) public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload, TimeProvider? clock = null)
@@ -175,6 +177,38 @@ public sealed class PanelWindow : Window
Ui.Text("Measured · dashed: estimated · faint: previous · dotted: forecast", 12, "Muted"), new BurnUpChart(limit with { Now = now }, clock), Ui.Text("Measured · dashed: estimated · faint: previous · dotted: forecast", 12, "Muted"), new BurnUpChart(limit with { Now = now }, clock),
Ui.Text("Past instances · peak use", 12, "Muted"), new InstancePeaks(limit.Analysis!.Past, limit.Provider, clock)))), wide)); Ui.Text("Past instances · peak use", 12, "Muted"), new InstancePeaks(limit.Analysis!.Past, limit.Provider, clock)))), wide));
} }
var resetHistories = h.Resets.Where(r => model.ProviderFilter is null || r.Window.Provider == model.ProviderFilter).ToArray();
if (resetHistories.Length > 0)
{
content.Add(Ui.Text("Resets", 20));
foreach (var group in resetHistories.GroupBy(r => r.Window.Provider))
{
var entries = group.ToArray();
var index = Array.FindIndex(entries, r => WindowSeries.For(r.Window) == selectedResetWindow.GetValueOrDefault(group.Key));
if (index < 0) index = 0;
var title = Ui.Text(group.Key + " · " + entries[index].Window.Label, 15);
Control View(ResetHistory history)
{
var key = WindowSeries.For(history.Window);
if (!resetTables.TryGetValue(key, out var state)) resetTables[key] = state = new(ResetColumn.Start);
return new ResetCard(history, state, clock);
}
var view = new Border { Child = View(entries[index]) };
var stack = Ui.Stack(title);
if (entries.Length > 1)
{
var selector = new WindowSelector { Name = "ResetWindowSelector", ItemsSource = entries.Select(r => r.Window.Label).ToArray(), SelectedIndex = index };
selector.SelectionChanged += (_, _) =>
{
if (selector.SelectedIndex < 0) return;
var history = entries[selector.SelectedIndex]; selectedResetWindow[group.Key] = WindowSeries.For(history.Window);
title.Text = group.Key + " · " + history.Window.Label; view.Child = View(history);
};
stack.Children.Add(selector);
}
stack.Children.Add(view); content.Add(Ui.Card(stack));
}
}
content.Add(Ui.Text("Breakdown", 20)); content.Add(Ui.Text("Breakdown", 20));
content.Add(Ui.Card(new BreakdownTable("By model", h.Models, false, model.ProviderFilter, modelBreakdown))); content.Add(Ui.Card(new BreakdownTable("By model", h.Models, false, model.ProviderFilter, modelBreakdown)));
content.Add(Ui.Card(new BreakdownTable("By project", h.Projects, true, model.ProviderFilter, projectBreakdown))); content.Add(Ui.Card(new BreakdownTable("By project", h.Projects, true, model.ProviderFilter, projectBreakdown)));
+51
View File
@@ -0,0 +1,51 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using FinalToken.Core;
namespace FinalToken.App;
public sealed class ResetCard : StackPanel
{
public ResetCard(ResetHistory history, TableState<ResetColumn> state, TimeProvider clock)
{
Spacing = 16;
var totals = history.Totals;
if (totals.Finished == 0)
Children.Add(Ui.Text("No reset observed since " + Display.Projection(history.FirstSample, clock), 12, "Muted"));
if (history.Instances.Count == 0) return;
var stats = new UniformGrid { Columns = 6, Rows = 1 };
void Stat(string label, string value, string caption, DataTooltip tooltip)
{
var tile = Ui.Stack(Ui.Text(label, 12, "Secondary"), Ui.Text(value, 24), Ui.Text(caption, 12, "Muted"));
tile.Margin = new Thickness(0, 0, 12, 0); ToolTip.SetTip(tile, tooltip); stats.Children.Add(tile);
}
DataTooltip ValueTip(string title, ResetValue value) => new(title, new("Limits", Display.Limits(value.Percent)),
new("Percent", $"{value.Percent:N2} %"), new("Estimated tokens", value.Tokens is { } tokens ? "≈ " + tokens.ToString("N0") : "No qualifying instance"),
new("Estimated API value", Display.Money(value.ApiValue)), new("Basis", "Own instance ≥ 5 %, else series median"),
new("Coverage", "Whole listed instances; hourly boundary tokens"));
string ValueCaption(ResetValue value) => (value.Tokens is { } tokens ? "≈ " + Display.Compact(tokens) + " tokens · " : "") + Display.Money(value.ApiValue);
Stat("Resets", totals.Instances.ToString(), $"{totals.Early} early", new DataTooltip("Listed instances",
new("Total", totals.Instances.ToString()), new("Finished", totals.Finished.ToString()), new("Early", totals.Early.ToString()),
new("Running", (totals.Instances - totals.Finished).ToString())));
Stat("Tokens", Display.Compact(totals.Tokens.Total), "in listed instances", DataTooltip.Tokens("Reset history tokens", totals.Tokens));
Stat("API value", Display.Money(totals.ApiValue), "at API list prices", new DataTooltip("API value at list prices",
new("Value", Display.Money(totals.ApiValue)), new("Unpriced tokens", DataTooltip.Count(totals.UnpricedTokens)),
new("Prices checked", ApiPrices.CheckedOn.ToString("yyyy-MM-dd"))));
Stat("Unused", Display.Limits(totals.Unused.Percent), ValueCaption(totals.Unused), ValueTip("Unused limit · estimated value", totals.Unused));
Stat("Gift", Display.Limits(totals.Gift.Percent), ValueCaption(totals.Gift) + " · " + Display.ResetDuration(totals.Skipped) + " skipped", ValueTip("Early-reset gift · estimated value", totals.Gift));
Stat("100 % reached", totals.ReachedLimit + "×", Display.ResetDuration(totals.TimeAtLimit) + " at 100 %", new DataTooltip("100 % reached",
new("Instances", totals.ReachedLimit.ToString()), new("Total time", Display.ResetDuration(totals.TimeAtLimit)),
new("Source", history.Instances.Any(r => r.BurnUp.ReachedOrigin == UseOrigin.Estimated) ? "Includes token estimates" : "Measured")));
Children.Add(stats);
Children.Add(Ui.Text("Measured · dashed: estimated · vertical: reset · hatched: skipped · top band: time at 100 %", 12, "Muted"));
Children.Add(new ResetTimeline(history, clock));
Children.Add(Ui.Columns([
Ui.Stack(Ui.Text("Early resets by hour · local time", 13, "Secondary"), new ResetHistogram(history.EarlyByHour, history.Window.Provider, false)),
Ui.Stack(Ui.Text("Early resets by weekday · local time", 13, "Secondary"), new ResetHistogram(history.EarlyByWeekday, history.Window.Provider, true))], true));
Children.Add(Ui.Text("Median instance " + (history.MedianDuration is { } median ? Display.ResetDuration(median) : "—") +
$" · early resets {totals.Early} of {totals.Instances}", 12, "Secondary"));
Children.Add(new ResetTable(history, state, clock));
}
}
+126
View File
@@ -0,0 +1,126 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using FinalToken.Core;
namespace FinalToken.App;
/// <summary>D12: real instances share a time axis; their burn-ups are never connected.</summary>
public sealed class ResetTimeline(ResetHistory history, TimeProvider clock) : Control
{
private Rect plot;
private DateTimeOffset from, to;
private readonly List<(Rect Bounds, ResetInstance Instance)> hits = [];
protected override void OnInitialized()
{
base.OnInitialized(); Height = 210; ToolTip.SetShowDelay(this, 0);
PointerMoved += (_, e) =>
{
var point = e.GetPosition(this);
if (!plot.Contains(point) || to <= from) { ToolTip.SetTip(this, null); return; }
var time = from.AddTicks((long)((to - from).Ticks * (point.X - plot.Left) / plot.Width));
var instance = hits.Where(h => h.Bounds.Contains(point)).OrderBy(h => Math.Abs(h.Bounds.Center.X - point.X))
.Select(h => h.Instance).FirstOrDefault() ??
history.Instances.FirstOrDefault(r => r.Early && r.End <= time && r.Reset >= time);
ToolTip.SetTip(this, instance is null ? null : DataTooltip.Reset(instance, clock));
};
PointerExited += (_, _) => ToolTip.SetTip(this, null);
}
public override void Render(DrawingContext context)
{
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear();
if (history.Instances.Count == 0) return;
var dark = Ui.Dark(this); var colour = Ui.ProviderColour(history.Window.Provider, dark); var muted = Ui.Colour("Muted", dark);
plot = new Rect(42, 12, Math.Max(1, Bounds.Width - 58), Math.Max(1, Bounds.Height - 48));
from = history.Instances.Min(r => r.Start);
to = history.Instances.Max(r => r.Early ? r.Reset : r.End);
if (to <= from) to = from.AddHours(1);
double X(DateTimeOffset time) => plot.Left + (time - from).TotalSeconds / (to - from).TotalSeconds * plot.Width;
double Y(double used) => plot.Bottom - used / 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);
}
using (context.PushClip(plot))
{
foreach (var row in history.Instances.Where(r => r.Early))
{
var band = new Rect(X(row.End), plot.Top, Math.Max(0, X(row.Reset) - X(row.End)), plot.Height);
using (context.PushClip(band))
{
using (context.PushOpacity(.035)) context.DrawRectangle(colour, null, band);
using (context.PushOpacity(.14))
for (var x = band.Left - band.Height; x < band.Right; x += 8)
context.DrawLine(new Pen(colour), new(x, band.Bottom), new(x + band.Height, band.Top));
}
}
foreach (var row in history.Instances.Reverse())
{
var hitWidth = Math.Max(8, X(row.End) - X(row.Start));
hits.Add((new Rect((X(row.Start) + X(row.End) - hitWidth) / 2, plot.Top, hitWidth, plot.Height), row));
if (!row.Running)
context.DrawLine(new Pen(Ui.Colour("Axis", dark)), new(X(row.End), plot.Top), new(X(row.End), plot.Bottom));
if (row.ReachedLimit is { } reached)
{
using (context.PushOpacity(.16)) context.DrawRectangle(colour, null,
new Rect(X(reached), plot.Top, Math.Max(1, X(row.End) - X(reached)), 7));
context.DrawLine(new Pen(colour, 3), new(X(reached), plot.Top + 1), new(X(row.End), plot.Top + 1));
}
var points = row.BurnUp.Points;
for (var i = 1; i < points.Count; i++)
{
var a = points[i - 1]; var b = points[i];
if (i == 1 && a.Time == row.Start && row.BurnUp.Scale is null && b.Origin == UseOrigin.Measured && b.Time > row.Start) continue;
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), new(X(a.Time), Y(a.Used)), new(X(b.Time), Y(b.Used)));
}
}
}
for (var i = 0; i < 5; i++)
{
var time = from.AddTicks((to - from).Ticks * i / 4);
ChartText.Draw(context, Display.ResetDate(time, clock), new(Math.Clamp(X(time) - 36, plot.Left, Math.Max(plot.Left, plot.Right - 86)), plot.Bottom + 12), muted);
}
}
}
public sealed class ResetHistogram(IReadOnlyList<int> counts, Provider provider, bool weekdays) : Control
{
private readonly List<(Rect Bounds, int Index)> hits = [];
private static readonly string[] Weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
protected override void OnInitialized()
{
base.OnInitialized(); Height = 104; ToolTip.SetShowDelay(this, 0);
PointerMoved += (_, e) =>
{
var hit = hits.Where(h => h.Bounds.Contains(e.GetPosition(this))).Select(h => (int?)h.Index).FirstOrDefault();
ToolTip.SetTip(this, hit is { } index ? new DataTooltip(weekdays ? Weekdays[index] : $"{index:00}:00–{index:00}:59 local",
new TooltipRow("Early resets", counts[index].ToString())) : null);
};
PointerExited += (_, _) => ToolTip.SetTip(this, null);
}
public override void Render(DrawingContext context)
{
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear();
if (counts.Count == 0) return;
var dark = Ui.Dark(this); var colour = Ui.ProviderColour(provider, dark); var muted = Ui.Colour("Muted", dark);
var plot = new Rect(26, 10, Math.Max(1, Bounds.Width - 34), Math.Max(1, Bounds.Height - 34));
var maximum = Math.Max(1, counts.Max()); var width = plot.Width / counts.Count;
ChartText.Draw(context, maximum.ToString(), new(0, plot.Top - 6), muted);
ChartText.Draw(context, "0", new(8, plot.Bottom - 6), muted);
context.DrawLine(new Pen(Ui.Colour("Grid", dark)), plot.TopLeft, plot.TopRight);
context.DrawLine(new Pen(Ui.Colour("Axis", dark)), plot.BottomLeft, plot.BottomRight);
for (var i = 0; i < counts.Count; i++)
{
var height = plot.Height * counts[i] / maximum;
var left = plot.Left + i * width;
var bar = UsageChart.BarBounds(left, plot.Bottom, width, height, TopLevel.GetTopLevel(this)?.RenderScaling ?? 1);
if (height > 0) context.DrawRectangle(colour, null, bar);
hits.Add((new(left, plot.Top, Math.Max(8, width), plot.Height), i));
if (weekdays || i % 3 == 0)
ChartText.Draw(context, weekdays ? Weekdays[i] : i.ToString("00"), new(left + width / 2 - (weekdays ? 10 : 6), plot.Bottom + 8), muted, 11);
}
}
}
+65
View File
@@ -0,0 +1,65 @@
using Avalonia.Controls;
using Avalonia.Layout;
using FinalToken.Core;
namespace FinalToken.App;
public enum ResetColumn { Start, End, Lasted, Reset, Final, Reached, Tokens, ApiValue, Unused, Gift }
public sealed class ResetTable : StackPanel
{
private readonly ResetHistory history;
private readonly TableState<ResetColumn> state;
private readonly TimeProvider clock;
public ResetTable(ResetHistory history, TableState<ResetColumn> state, TimeProvider clock)
{
this.history = history; this.state = state; this.clock = clock; Spacing = 8;
AttachedToVisualTree += (_, _) => RenderTable();
}
public static IReadOnlyList<ResetInstance> SortRows(IEnumerable<ResetInstance> rows, ResetColumn column, bool descending)
{
double Key(ResetInstance row) => column switch
{
ResetColumn.Start => row.Start.UtcTicks, ResetColumn.End => row.End.UtcTicks,
ResetColumn.Lasted => row.Duration.Ticks, ResetColumn.Reset => row.Skipped.Ticks,
ResetColumn.Final => row.Final.Used, ResetColumn.Reached => row.ReachedLimit?.UtcTicks ?? double.MinValue,
ResetColumn.Tokens => row.Tokens.Total, ResetColumn.ApiValue => (double?)row.ApiValue ?? double.MinValue,
ResetColumn.Unused => row.Unused?.Percent ?? double.MinValue, _ => row.Gift?.Percent ?? double.MinValue
};
return DetailTable.Sort(rows, Key, descending).ThenByDescending(r => r.Start).ToArray();
}
private void RenderTable()
{
Children.Clear();
var heading = new DockPanel();
if (history.Instances.Count > 8)
{
var expand = DetailTable.Expansion(history.Instances.Count, state, RenderTable);
expand.Name = "ResetExpand"; DockPanel.SetDock(expand, Dock.Right); heading.Children.Add(expand);
}
heading.Children.Add(Ui.Text(state.Sort == ResetColumn.Start && state.Descending ? "Instances · newest first" : "Instances", 13, "Secondary")); Children.Add(heading);
var grid = new Grid { Name = "ResetRows", ColumnDefinitions = new ColumnDefinitions("100,100,90,150,110,110,80,90,100,100"),
ColumnSpacing = 12, RowSpacing = 8, MinWidth = 1138 };
string[] headers = ["Start", "End", "Lasted", "Reset", "Final (peak)", "100 % at", "Tokens", "API value", "Unused", "Gift"];
for (var c = 0; c < headers.Length; c++)
DetailTable.Add(grid, DetailTable.Header(headers[c], (ResetColumn)c, state, RenderTable, "ResetSort" + (ResetColumn)c, c == 0), 0, c);
var sorted = SortRows(history.Instances, state.Sort, state.Descending);
var visible = state.Expanded ? sorted : sorted.Take(8).ToArray();
for (var r = 0; r < visible.Count; r++)
{
var row = visible[r];
string Value(ResetValue? value) => value is null ? "—" : Display.ResetPercent(value.Percent, UseOrigin.Estimated);
string[] cells = [Display.ResetDate(row.Start, clock), row.Running ? "Running" : Display.ResetDate(row.End, clock), Display.ResetDuration(row.Duration),
row.Running ? "Running" : row.Early ? "Early by " + Display.ResetDuration(row.Skipped) : "On time",
Display.ResetPercent(row.Final.Used, row.Final.Origin) + (row.Peak is { } peak ? " (" + Display.ResetPercent(peak, row.PeakOrigin) + ")" : ""),
row.ReachedLimit is { } reached ? (row.BurnUp.ReachedOrigin == UseOrigin.Estimated ? "≈ " : "") + Display.ResetDate(reached, clock) : "—",
Display.Compact(row.Tokens.Total), Display.Money(row.ApiValue), Value(row.Unused), Value(row.Gift)];
for (var c = 0; c < cells.Length; c++)
{
var text = Ui.TableNumber(cells[c], 12); text.HorizontalAlignment = c == 0 ? HorizontalAlignment.Left : HorizontalAlignment.Right;
ToolTip.SetTip(text, DataTooltip.Reset(row, clock)); DetailTable.Add(grid, text, r + 1, c);
}
}
Children.Add(DetailTable.Scroll(grid));
}
}
+53
View File
@@ -0,0 +1,53 @@
using FinalToken.Core;
namespace FinalToken.App;
public sealed partial class DataTooltip
{
public static DataTooltip Reset(ResetInstance row, TimeProvider clock)
{
var rows = new List<TooltipRow>
{
new("Start", Display.Projection(row.Start, clock)),
new(row.Running ? "As of" : "End", Display.Projection(row.End, clock)),
new("Nominal reset", Display.Projection(row.Reset, clock)),
new("Lasted", Display.ResetDuration(row.Duration)),
new("Final use", Display.ResetPercent(row.Final.Used, row.Final.Origin)),
new("Peak", row.Peak is { } peak ? Display.ResetPercent(peak, row.PeakOrigin) : "Collecting history"),
new("100 % reached", row.ReachedLimit is { } reached ?
(row.BurnUp.ReachedOrigin == UseOrigin.Estimated ? "≈ " : "") + Display.Projection(reached, clock) : "Not reached"),
new("Time at 100 %", Display.ResetDuration(row.TimeAtLimit)),
new("Total tokens", Count(row.Tokens.Total)), new("Input", Count(row.Tokens.Input)),
new("Cache read", Count(row.Tokens.CacheRead)), new("Cache write", Count(row.Tokens.CacheWrite)),
new("Output", Count(row.Tokens.Output)), new("Reasoning (in output)", Count(row.Tokens.ReasoningOutput)),
new("API list value", Display.Money(row.ApiValue)), new("Unpriced tokens", Count(row.UnpricedTokens))
};
foreach (var model in row.Models.Take(5))
rows.Add(new(model.Model ?? "Unknown model", Count(model.Tokens.Total) + " · " + Display.Money(model.ApiValue)));
if (row.Models.Count > 5) rows.Add(new("Other models", (row.Models.Count - 5).ToString()));
rows.Add(new("Tokens per percent", row.ValuePerPercent is { } rate ? "≈ " + Display.Compact(rate.Tokens) +
" · " + rate.Tokens.ToString("N2") : "No qualifying instance"));
rows.Add(new("API value per percent", Display.Money(row.ValuePerPercent?.ApiValue)));
rows.Add(new("Value basis", row.ValuePerPercent?.Basis switch
{
PercentBasis.OwnInstance => "Own instance (final ≥ 5 %)",
PercentBasis.SeriesMedian => "Median of qualifying listed instances",
_ => "No instance with final ≥ 5 %"
}));
if (row.Unused is { } unused) AddValue("Unused", unused);
if (row.Gift is { } gift) { AddValue("Gift", gift); rows.Add(new("Skipped", Display.ResetDuration(row.Skipped))); }
var estimates = new List<string>();
if (row.Final.Origin == UseOrigin.Estimated) estimates.Add("final");
if (row.PeakOrigin == UseOrigin.Estimated) estimates.Add("peak");
if (row.BurnUp.ReachedOrigin == UseOrigin.Estimated) estimates.Add("100 % time");
if (row.Unused is not null) estimates.Add("unused value");
if (row.Gift is not null) estimates.Add("gift value");
rows.Add(new("Estimated figures", estimates.Count == 0 ? "API list value" : string.Join(", ", estimates) + ", API list value"));
rows.Add(new("Prices checked", ApiPrices.CheckedOn.ToString("yyyy-MM-dd") + " · hourly boundary tokens"));
return new(row.Running ? "Running instance" : row.Early ? "Early reset" : "On-time reset", rows.ToArray());
void AddValue(string label, ResetValue value) => rows.Add(new(label,
Display.ResetPercent(value.Percent, UseOrigin.Estimated) + " · " +
(value.Tokens is { } count ? "≈ " + Display.Compact(count) + " tokens · " : "") + Display.Money(value.ApiValue)));
}
}
@@ -364,6 +364,7 @@ public sealed class HeadlessTests
popupClock.Fire(); Dispatcher.UIThread.RunJobs(); popupClock.Fire(); Dispatcher.UIThread.RunJobs();
Assert.False(first.IsVisible); Assert.False(second.IsVisible); Assert.False(first.IsVisible); Assert.False(second.IsVisible);
Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed)); Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed));
ResetViews.Verify((window, name) => Save(window, name));
completion.SetResult(); completion.SetResult();
void SaveThemes(Window window, string stem) void SaveThemes(Window window, string stem)
{ {
+94
View File
@@ -0,0 +1,94 @@
using System.Globalization;
using FinalToken.Core;
using Xunit;
namespace FinalToken.App.Tests;
public sealed class ResetTests
{
[Fact] public void HistoryQueriesOnlyLongWindowsAndFollowsProviderAndRange()
{
var fixture = ResetFixture.Create();
var all = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, null, fixture.Now);
Assert.Equal(3, all.Resets.Count);
Assert.All(all.Resets, r => Assert.True(r.Window.Length > TimeSpan.FromDays(1)));
var filtered = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, Provider.Codex, fixture.Now);
Assert.Equal(2, filtered.Resets.Count); Assert.All(filtered.Resets, r => Assert.Equal(Provider.Codex, r.Window.Provider));
var recent = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.Hours24, Provider.Codex, fixture.Now);
var week = recent.Resets.Single(r => r.Window.Id == "codex:primary");
Assert.True(week.Instances.Count < filtered.Resets[0].Instances.Count);
Assert.Contains(week.Instances, r => r.Start < fixture.Now.AddHours(-24) && r.End > fixture.Now.AddHours(-24));
Assert.Equal(10, filtered.Resets[0].Instances.Count);
}
[Fact] public void BurnUpQueriesReadTheSeriesAcrossCodexSlotsAndExcludeShortWindows()
{
var fixture = ResetFixture.Create();
var history = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, Provider.Codex, fixture.Now);
var week = history.Limits.Single(l => l.Window!.Window.Id == "codex:primary" && l.Window.Window.Length > TimeSpan.FromDays(1));
Assert.DoesNotContain(week.Values, v => v.Value == 99);
Assert.True(week.Values.Count > 10);
Assert.Equal(8, week.Analysis!.Past.Count);
}
[Fact] public void MoneyAndLimitsStayInvariantOnAGermanDesktop()
{
var previous = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE");
Assert.Equal("≈ $1,234", Display.Money(1234)); Assert.Equal("≈ $99.25", Display.Money(99.25m));
Assert.Equal("Unpriced", Display.Money(null)); Assert.Equal("≈ 3.1 limits", Display.Limits(310));
Assert.Equal("0 min", Display.ResetDuration(TimeSpan.Zero));
}
finally { CultureInfo.CurrentCulture = previous; }
}
[Fact] public void EveryInstanceColumnSortsByItsUnderlyingValue()
{
var fixture = ResetFixture.Create();
var rows = fixture.History.Resets[0].Instances;
Assert.Equal(rows.OrderBy(r => r.Start), ResetTable.SortRows(rows, ResetColumn.Start, false));
Assert.Equal(rows.Max(r => r.Final.Used), ResetTable.SortRows(rows, ResetColumn.Final, true)[0].Final.Used);
Assert.Equal(rows.Max(r => r.Skipped), ResetTable.SortRows(rows, ResetColumn.Reset, true)[0].Skipped);
Assert.Equal(rows.Max(r => r.Duration), ResetTable.SortRows(rows, ResetColumn.Lasted, true)[0].Duration);
foreach (var column in Enum.GetValues<ResetColumn>())
{
var ascending = ResetTable.SortRows(rows, column, false); var descending = ResetTable.SortRows(rows, column, true);
Assert.Equal(rows.Count, ascending.Count); Assert.Equal(rows.Count, descending.Count);
}
}
}
internal sealed record ResetFixture(HistoryStore Store, Snapshot Snapshot, DateTimeOffset Now, HistoryView History)
{
public static ResetFixture Create()
{
var start = new DateTimeOffset(2026, 9, 12, 6, 0, 0, TimeSpan.Zero);
int[] durations = [7, 1, 2, 7, 1, 2, 1, 1, 2];
var now = start.AddDays(durations.Sum()).AddHours(12);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-resets", Guid.NewGuid().ToString("N")), new(), new FixedClock(now));
var currentStart = start; LimitWindow current = null!;
for (var i = 0; i <= durations.Length; i++)
{
var used = i == 2 ? 100 : i == 4 ? 4 : 20 + i * 7;
current = new(Provider.Codex, i < 4 ? "codex:secondary" : "codex:primary", "Week", used,
currentStart.AddDays(7), TimeSpan.FromDays(7), currentStart.AddHours(6), "fixture");
store.AddLimits([current with { SampleTime = currentStart.AddHours(1), UsedPercent = used / 2.0 }, current]);
store.AddLimits([current with { Id = "codex_bengalfox:secondary", Label = "Week (Bengalfox)", UsedPercent = 0 }]);
store.Add(new(Provider.Codex, currentStart.AddMinutes(30), "gpt-6.1-sol", "Fixture", new(10_000_000, 4_000_000, 0, 2_000_000, 300_000, 12_000_000), "a" + i));
store.Add(new(Provider.Codex, currentStart.AddHours(2), "gpt-6-astra", "Fixture", new(1_000_000, 200_000, 0, 2_000_000, 300_000, 3_000_000), "b" + i));
store.Add(new(Provider.Codex, currentStart.AddHours(2), "codex-auto-review", "Fixture", new(Input: 100_000, Total: 100_000), "c" + i));
if (i < durations.Length) currentStart = currentStart.AddDays(durations[i]);
}
var shortWindow = current with { Id = "codex:primary", Length = TimeSpan.FromHours(5), ResetsAt = now.AddHours(2), UsedPercent = 99, SampleTime = now.AddMinutes(-1), Label = "Session" };
store.AddLimits([shortWindow]);
var claude = current with { Provider = Provider.Claude, Id = "week", Label = "Week (all models)" };
var alternate = current with { Id = "codex_bengalfox:primary", Label = "Week (Bengalfox)", UsedPercent = 0 };
var snapshot = FakeData.Snapshot(now) with { Providers =
[new(Provider.Codex, ProviderStatus.Available, null, [new(current, Pace.Calculate(current, now)), new(alternate, Pace.Calculate(alternate, now)),
new(shortWindow, Pace.Calculate(shortWindow, now))], new(), new(), new()),
new(Provider.Claude, ProviderStatus.Available, null, [new(claude, Pace.Calculate(claude, now))], new(), null, new())] };
return new(store, snapshot, now, PanelViewModel.QueryHistory(store, snapshot, HistoryRange.All, null, now));
}
}
+107
View File
@@ -0,0 +1,107 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Interactivity;
using Avalonia.Styling;
using Avalonia.Threading;
using Avalonia.VisualTree;
using FinalToken.Core;
using Xunit;
namespace FinalToken.App.Tests;
internal static class ResetViews
{
public static void Verify(Action<Window, string> save)
{
var fixture = ResetFixture.Create();
var clock = new FixedClock(fixture.Now);
var model = new PanelViewModel { Snapshot = fixture.Snapshot, History = fixture.History, Range = HistoryRange.All };
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }, clock);
panel.Show(); Dispatcher.UIThread.RunJobs();
var headings = panel.GetVisualDescendants().OfType<TextBlock>().Where(t => t.FontSize == 20).Select(t => t.Text).ToArray();
Assert.True(Array.IndexOf(headings, "Window charts") < Array.IndexOf(headings, "Resets"));
Assert.True(Array.IndexOf(headings, "Resets") < Array.IndexOf(headings, "Breakdown"));
var selector = panel.GetVisualDescendants().OfType<ComboBox>().Single(c => c.Name == "ResetWindowSelector");
selector.SelectedIndex = 1;
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Codex · Week (Bengalfox)");
model.Snapshot = model.Snapshot with { MadeAt = fixture.Now.AddMinutes(-1) }; Dispatcher.UIThread.RunJobs();
Assert.Equal(1, panel.GetVisualDescendants().OfType<ComboBox>().Single(c => c.Name == "ResetWindowSelector").SelectedIndex);
panel.GetVisualDescendants().OfType<ComboBox>().Single(c => c.Name == "ResetWindowSelector").SelectedIndex = 0;
Dispatcher.UIThread.RunJobs();
using (panel.CaptureRenderedFrame()) { }
var card = panel.GetVisualDescendants().OfType<ResetCard>().First();
var table = card.GetVisualDescendants().OfType<ResetTable>().Single();
Grid Rows()
{
Dispatcher.UIThread.RunJobs();
using (panel.CaptureRenderedFrame()) { }
return table.GetVisualDescendants().OfType<Grid>().Single(g => g.Name == "ResetRows");
}
void Click(string name)
{
Dispatcher.UIThread.RunJobs();
using (panel.CaptureRenderedFrame()) { }
table.GetVisualDescendants().OfType<Button>().Single(b => b.Name == name).RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Dispatcher.UIThread.RunJobs();
using (panel.CaptureRenderedFrame()) { }
}
Assert.Equal(9, Rows().RowDefinitions.Count); // Header plus eight rows.
var cells = Rows().Children.OfType<TextBlock>().ToArray();
Assert.All(cells, text => Assert.IsType<DataTooltip>(ToolTip.GetTip(text)));
Assert.Contains(cells, t => t.Text == "Running");
Assert.Contains(cells, t => t.Text?.StartsWith("Early by ", StringComparison.Ordinal) == true);
Assert.Contains(cells, t => t.Text?.Contains("100 %", StringComparison.Ordinal) == true);
Click("ResetSortFinal");
Assert.StartsWith("≈ 100 %", Rows().Children.OfType<TextBlock>().Single(t => Grid.GetRow(t) == 1 && Grid.GetColumn(t) == 4).Text);
Click("ResetExpand");
Assert.Equal(11, Rows().RowDefinitions.Count);
Assert.Contains(Rows().Children.OfType<TextBlock>(), t => t.Text == "On time");
model.Snapshot = model.Snapshot with { MadeAt = fixture.Now }; Dispatcher.UIThread.RunJobs();
table = panel.GetVisualDescendants().OfType<ResetCard>().First().GetVisualDescendants().OfType<ResetTable>().Single();
Assert.Equal(11, Rows().RowDefinitions.Count);
Assert.Contains(table.GetVisualDescendants().OfType<Button>(), b => b.Content as string == "Final (peak) ↓");
Click("ResetExpand");
Click("ResetSortStart");
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.RequestedThemeVariant = theme; Dispatcher.UIThread.RunJobs();
var viewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
var heading = panel.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Text == "Resets" && t.FontSize == 20);
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
save(panel, $"resets-panel-{theme}.png");
}
panel.Close();
var history = fixture.History.Resets[0];
foreach (var width in new[] { 1280, 1500 })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var content = new ResetCard(history, new(ResetColumn.Start), clock);
var window = new Window { Width = width, Height = 1030, Content = new Border { Padding = new Thickness(24),
Child = Ui.Stack(Ui.Text("Resets", 20), Ui.Card(Ui.Stack(Ui.Text("Codex · Week", 15), content))) }, RequestedThemeVariant = theme };
Ui.Theme(window); window.Show();
save(window, $"resets-{width}-{theme}.png");
var timeline = content.GetVisualDescendants().OfType<ResetTimeline>().Single();
window.MouseMove(timeline.TranslatePoint(new Point(timeline.Bounds.Width / 2, 80), window)!.Value);
Assert.IsType<DataTooltip>(ToolTip.GetTip(timeline));
var histogram = content.GetVisualDescendants().OfType<ResetHistogram>().First();
window.MouseMove(histogram.TranslatePoint(new Point(40, 40), window)!.Value);
Assert.IsType<DataTooltip>(ToolTip.GetTip(histogram));
var tableTip = content.GetVisualDescendants().OfType<ResetTable>().Single().GetVisualDescendants().OfType<TextBlock>()
.Select(t => ToolTip.GetTip(t)).OfType<DataTooltip>().First();
Assert.Contains(tableTip.Rows, r => r.Label == "Unpriced tokens");
Assert.Contains(tableTip.Rows, r => r.Label == "Tokens per percent");
Assert.Contains(tableTip.Rows, r => r.Label == "Estimated figures");
var oldest = history.Instances[^1];
Assert.False(oldest.Early); Assert.False(oldest.Running);
window.Close();
}
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var tip = DataTooltip.Reset(history.Instances[1], clock);
var window = new Window { Width = 580, Height = 1120, Content = new Border { Child = tip, Padding = new Thickness(16) }, RequestedThemeVariant = theme };
Ui.Theme(window); window.Show(); save(window, $"resets-tooltip-{theme}.png"); window.Close();
}
}
}