app: show the reset history of each long limit window (#16)

The developer asked for a detailed breakdown of every reset (feedback of
2026-10-18). Limits do not only reset at the end of their week: most Codex
weeks in the local history ended early.

- Core: a limit's samples form a window series (provider, limit name and
  length), so the history follows Codex's week across slots (D7). Instance
  spans are built once. One backward walk gives each instance, real or
  inferred, the start of the instance after it. The hour that holds a
  boundary goes to the instance that starts in it, or else to the one that
  ends in it (#9). A stale sample that would put its instance after a later
  one is ignored. The reset history lists the real instances with their
  figures, totals and early-reset hours (D12). API value uses a dated list
  price table; unknown models stay unpriced (D13).
- App: a Resets section per long window with totals, a timeline of
  burn-ups side by side with skipped time in lanes below, early resets by
  hour and weekday, and a sortable table (D8). The reset tooltip lists
  every model with its tokens and API value. Tall tooltips open beside the
  pointer, and Fluent's 320 px tooltip cap no longer wraps data values.
- Docs: D12 and D13 are new; D7 and D8 cover window series, boundary
  hours and the Resets section.

Closes #14
Closes #9
This commit was merged in pull request #16.
This commit is contained in:
2026-10-18 11:12:38 +02:00
parent 0a08b508a2
commit 82fece85f5
29 changed files with 1570 additions and 137 deletions
+13 -3
View File
@@ -13,7 +13,8 @@ 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); 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;
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
@@ -51,11 +52,16 @@ 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.
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.
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; mark observed resets and show skipped time as thin
hatched bars below the plot, with overlapping spans in separate lanes (D12). Its axis ends at
the latest of now and the early resets' nominal resets, never the running instance's reset.
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.
for resets and forecasts. Recent-rate captions name the actual span. Tall tooltips open beside
the pointer through `DataTooltip.BesidePointer`; a tooltip over the pointer takes the hover from
its control. Do not clear a chart's tip on pointer exit.
- Custom segments and checkboxes must show keyboard focus. NeutralCheckBox owns checked state;
templates bind its MarkVisible property and must never register checked handlers.
@@ -63,3 +69,7 @@ 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;
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.
- 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).
Reset tooltips list every model in Core's token order, with its tokens and API list value.
+7 -18
View File
@@ -8,12 +8,7 @@ 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 BreakdownState() : TableState<BreakdownColumn>(BreakdownColumn.Total);
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)
{
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
{
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();
return DetailTable.Sort(rows, Key, descending).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(); });
var expand = DetailTable.Expansion(rows.Count, state, RenderTable);
DockPanel.SetDock(expand, Dock.Right); header.Children.Add(expand);
}
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++)
{
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;
var button = DetailTable.Header(headers[c], column, state, RenderTable, title.Replace(" ", "") + "Sort" + column, c == 0);
Add(button, 0, c);
}
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);
}
}
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"));
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);
DetailTable.Add(grid, control, row, column);
}
}
}
+20 -1
View File
@@ -1,5 +1,6 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives.PopupPositioning;
using Avalonia.Layout;
using Avalonia.Media;
using FinalToken.Core;
@@ -9,7 +10,7 @@ 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 sealed partial class DataTooltip : Border
{
public string Title { get; }
public IReadOnlyList<TooltipRow> Rows { get; }
@@ -45,5 +46,23 @@ public sealed class DataTooltip : Border
rows.Add(new("Budget", day.Budget is { } budget ? $"{budget:0.##} %" + (day.BudgetOrigin == UseOrigin.Estimated ? " (estimated)" : "") : "Unavailable"));
return new(day.Start.DateTime.ToString("D"), rows.ToArray());
}
/// <summary>
/// Opens a tall tooltip beside the pointer, never over it: a tooltip that covers the pointer takes
/// it from <paramref name="control"/>, which then loses the tooltip. Call before other pointer handlers.
/// </summary>
public static void BesidePointer(Control control)
{
var pointer = default(Point);
control.PointerMoved += (_, e) => pointer = e.GetPosition(control);
ToolTip.SetPlacement(control, PlacementMode.Custom);
ToolTip.SetCustomPopupPlacementCallback(control, placement =>
{
// The anchor arrives as the control's bounds in window coordinates. The gap lives in the anchor,
// because a flip mirrors anchor and gravity but not the offset.
placement.AnchorRectangle = new Rect(placement.AnchorRectangle.TopLeft + pointer - new Point(16, 0), new Size(32, 1));
placement.Anchor = PopupAnchor.Right; placement.Gravity = PopupGravity.Right;
placement.ConstraintAdjustment = PopupPositionerConstraintAdjustment.FlipX | PopupPositionerConstraintAdjustment.SlideY;
});
}
public override string ToString() => Title + "\n" + string.Join('\n', Rows.Select(r => r.Label + ": " + r.Value));
}
+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 };
}
+24 -4
View File
@@ -14,6 +14,7 @@ public sealed record HistoryView(IReadOnlyList<ChartValue> Hourly, IReadOnlyList
IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> Projects)
{
public IReadOnlyList<LimitDetail> Details { get; init; } = [];
public IReadOnlyList<ResetHistory> Resets { get; init; } = [];
}
public partial class PanelViewModel : ObservableObject
@@ -50,14 +51,25 @@ public partial class PanelViewModel : ObservableObject
var hourly = Series(SeriesInterval.Hour);
var daily = Series(SeriesInterval.Day);
var details = new List<LimitDetail>();
var resets = new List<ResetHistory>();
var limits = providers.SelectMany(p => p.Windows.Select(w =>
{
var samples = store.LimitSamples(p.Provider, w.Window.Id, from, now);
var instanceSamples = store.LimitSamples(p.Provider, w.Window.Id,
w.Window.ResetsAt is { } r && w.Window.Length is { } l ? r - l * 9 - TimeSpan.FromMinutes(15) : now.AddDays(-14), now);
var instanceFrom = w.Window.ResetsAt is { } r && w.Window.Length is { } l
? r - l * 9 - TimeSpan.FromMinutes(15) : now.AddDays(-14);
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
? store.TokenSeriesByModel(p.Provider, tokenReset - tokenLength * 9 - TimeSpan.FromMinutes(15), now, SeriesInterval.Hour) : [];
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),
analysis?.Days,
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);
})).ToArray();
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)
{
@@ -137,4 +149,12 @@ public static class Display
public static string Forecast(DateTimeOffset date, PaceState state, TimeProvider? clock = null) =>
(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 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") + " limits";
public static string ResetPercent(double percent, UseOrigin origin) => (origin == UseOrigin.Estimated ? "≈ " : "") +
percent.ToString("0.#") + " %";
public static string ResetDate(DateTimeOffset time, TimeProvider clock) => TimeZoneInfo.ConvertTime(time, clock.LocalTimeZone).ToString("MM-dd HH:mm");
public static string ResetFigure(string figure) => figure.Replace(' ', '\u00a0');
public static string ResetDuration(TimeSpan span) => ResetFigure(span <= TimeSpan.Zero ? "0 min" : Duration(span));
}
+34
View File
@@ -21,6 +21,8 @@ public sealed class PanelWindow : Window
private bool wide;
private int limitColumns;
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();
public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload, TimeProvider? clock = null)
@@ -177,6 +179,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("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.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)));
+58
View File
@@ -0,0 +1,58 @@
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, bool available = true)
{
var tile = Ui.Stack(Ui.Text(label, 12, "Secondary"), Ui.Text(Display.ResetFigure(value), 24, available ? "Ink" : "Muted"), 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.ResetFigure("≈ " + Display.Compact(tokens) + " tokens") + " · " : "") + Display.ResetFigure(Display.Money(value.ApiValue));
var resetCaption = totals.Finished == 0 ? "none yet" : Display.ResetFigure($"{totals.Early} early");
if (history.Instances[0].Running) resetCaption += " · " + Display.ResetFigure("1 running");
Stat("Resets", totals.Finished.ToString(), resetCaption, 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", totals.Finished > 0 ? Display.Limits(totals.Unused.Percent) : "—",
totals.Finished > 0 ? ValueCaption(totals.Unused) : "no finished instance",
totals.Finished > 0 ? ValueTip("Unused limit · estimated value", totals.Unused) : new DataTooltip("Unused limit", new TooltipRow("Coverage", "No finished instance")), totals.Finished > 0);
Stat("Gift", totals.Early > 0 ? Display.Limits(totals.Gift.Percent) : "—",
totals.Early > 0 ? ValueCaption(totals.Gift) + " · " + Display.ResetDuration(totals.Skipped) + " skipped" : "no early reset",
totals.Early > 0 ? ValueTip("Early-reset gift · estimated value", totals.Gift) : new DataTooltip("Early-reset gift", new TooltipRow("Coverage", "No early reset")), totals.Early > 0);
Stat("100 % reached", totals.ReachedLimit + "×", Display.ResetDuration(totals.TimeAtLimit) + " at 100\u00a0%", 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 bars below: skipped · top band: time at 100 %", 12, "Muted"));
Children.Add(new ResetTimeline(history, clock));
if (totals.Early == 0) Children.Add(Ui.Text("No early resets in this range", 12, "Muted"));
else 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((history.MedianDuration is { } median ? "Median instance " + Display.ResetDuration(median) : "No finished instance yet") +
$" · early resets {totals.Early} of {totals.Finished}", 12, "Secondary"));
Children.Add(new ResetTable(history, state, clock));
}
}
+145
View File
@@ -0,0 +1,145 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using FinalToken.Core;
namespace FinalToken.App;
public sealed record ResetSkippedLane(ResetInstance Instance, int Lane);
public sealed record ResetTimelineLayout(DateTimeOffset From, DateTimeOffset To, IReadOnlyList<ResetSkippedLane> Skipped)
{
public int LaneCount => Skipped.Count == 0 ? 0 : Skipped.Max(s => s.Lane) + 1;
}
/// <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 const double LaneHeight = 10;
private readonly ResetTimelineLayout layout = CalculateLayout(history, clock.GetUtcNow());
private readonly List<(Rect Bounds, ResetInstance Instance)> hits = [];
public static ResetTimelineLayout CalculateLayout(ResetHistory history, DateTimeOffset now)
{
var from = history.Instances.Select(r => r.Start).DefaultIfEmpty(now).Min();
var to = history.Instances.Where(r => r.Early).Select(r => r.Reset).Append(now).Max();
if (to <= from) to = from.AddHours(1);
var laneEnds = new List<DateTimeOffset>();
var skipped = new List<ResetSkippedLane>();
foreach (var row in history.Instances.Where(r => r.Early).OrderBy(r => r.End).ThenBy(r => r.Reset))
{
var lane = laneEnds.FindIndex(end => end <= row.End);
if (lane < 0) { lane = laneEnds.Count; laneEnds.Add(row.Reset); }
else laneEnds[lane] = row.Reset;
skipped.Add(new(row, lane));
}
return new(from, to, skipped);
}
protected override void OnInitialized()
{
base.OnInitialized(); Height = 210 + layout.LaneCount * LaneHeight; ToolTip.SetShowDelay(this, 0); DataTooltip.BesidePointer(this);
PointerMoved += (_, e) =>
{
var point = e.GetPosition(this);
var instance = hits.Where(h => h.Bounds.Contains(point)).OrderBy(h => Math.Abs(h.Bounds.Center.X - point.X))
.Select(h => h.Instance).FirstOrDefault();
ToolTip.SetTip(this, instance is null ? null : DataTooltip.Reset(instance, clock));
};
}
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);
var laneSpace = layout.LaneCount * LaneHeight;
var plot = new Rect(42, 12, Math.Max(1, Bounds.Width - 58), Math.Max(1, Bounds.Height - 48 - laneSpace));
var from = layout.From; var to = layout.To;
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.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)));
}
}
}
foreach (var skipped in layout.Skipped)
{
var row = skipped.Instance;
var band = new Rect(X(row.End), plot.Bottom + 4 + skipped.Lane * LaneHeight, Math.Max(0, X(row.Reset) - X(row.End)), 6);
var hitWidth = Math.Max(8, band.Width);
hits.Add((new Rect(band.Center.X - hitWidth / 2, band.Top - 1, hitWidth, 8), row));
using (context.PushClip(band))
{
using (context.PushOpacity(.08)) context.DrawRectangle(colour, null, band);
using (context.PushOpacity(.5))
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));
}
}
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 + laneSpace + 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);
};
}
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)); DataTooltip.BesidePointer(text); 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))
};
if (row.Models.Count > 0) rows.Add(new("Models", row.Models.Count.ToString()));
foreach (var model in row.Models)
rows.Add(new(model.Model ?? "Unknown model", Count(model.Tokens.Total) + " · " + Display.Money(model.ApiValue)));
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)));
}
}
+2
View File
@@ -83,6 +83,8 @@ public static class Ui
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);
// Fluent caps tooltips at 320 px, which wraps the values of a data tooltip below its own width.
var tips = new Style(s => s.OfType<ToolTip>()); tips.Setters.Add(new Setter(Layoutable.MaxWidthProperty, 560d)); window.Styles.Add(tips);
}
// Explicit palettes keep every remaining Fluent control independent of the OS accent.
public static FluentTheme NeutralTheme()