diff --git a/.agents/mind/gotchas.md b/.agents/mind/gotchas.md index a36ec0e..9adc423 100644 --- a/.agents/mind/gotchas.md +++ b/.agents/mind/gotchas.md @@ -2,5 +2,7 @@ - [2026-10-14] `claude -p "/usage"` writes a transcript into the working directory's project folder unless `--no-session-persistence` is passed; that transcript would show up in Claude token history. - [2026-10-14] Git Bash rewrites an argument that starts with `/` (`/usage` becomes `C:/Program Files/Git/usage`). Run CLI probes from PowerShell, or set `MSYS_NO_PATHCONV=1`. The app itself starts processes with an argument list, so it is not affected. +- [2026-10-18] Avalonia 12 `CustomPopupPlacementCallback` gets the target's bounds in window coordinates, and a flip mirrors anchor and gravity but not the offset. Put a gap into the anchor rectangle (see `DataTooltip.BesidePointer`). +- [2026-10-18] Fluent caps `ToolTip` `MaxWidth` at 320 px, and a tooltip that covers the pointer takes pointer-over from its control, which raises `PointerExited`. `Ui.Theme` raises the cap; tall tips open beside the pointer. ## Archive diff --git a/.agents/mind/index.md b/.agents/mind/index.md index ddb8072..26ff08c 100644 --- a/.agents/mind/index.md +++ b/.agents/mind/index.md @@ -2,7 +2,7 @@ > Always-loaded. Everything else is on-demand. Update TOC when files change. ## Current Focus -- [2026-10-14] v1 on issue #1: Core collectors and store, Avalonia app, Stream Deck plugin. +- [2026-10-18] Reset history (D12), API value (D13) and panel fixes on issue #14, PR #16. ## Invariants - No credential is ever read, stored or sent; providers are reached only through their CLIs (D2). @@ -11,4 +11,4 @@ - `snapshot.json` is the only interface between the app and other processes (D9). ## Table of Contents -- `gotchas.md` — 2 entries — CLI probing pitfalls on this machine. +- `gotchas.md` — 4 entries — CLI probing pitfalls on this machine; Avalonia tooltip placement. diff --git a/docs/decisions.md b/docs/decisions.md index 8b32bff..374615e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -188,12 +188,20 @@ probe. is reached stops use, so an estimate that would pass it shows "limit reached (estimated)" at the time it crosses. No tokens in the instance means no estimate. Instance boundaries come from resets: an instance starts at its reset minus its length, and ends at its reset or at the next - instance's start, whichever comes first (Codex can start a new window early). Spans between - instances (a session window opens only with the next message) belong to none. A past instance + instance's start, whichever comes first (Codex can start a new window early). Tokens are + hourly (D5): an hour that holds a boundary goes to the instance that starts in it, or, when + none does, to the instance that ends in it. Other spans between instances (a session window + opens only with the next message) belong to none. A sample that would place its instance + after an instance sampled later is stale and is ignored. A past instance with samples is always the real one; an instance is only inferred where no samples exist, by stepping back one window length, and never overlaps a real one. Windows of a day or shorter are never inferred, since a session starts with whatever message comes next. Past instances are labelled with their real start and end. +- **Window series.** The samples of one limit share the provider, the limit name and the + length. The limit name is the window id without a Codex slot suffix (`:primary`, + `:secondary`): Codex moves a limit between its slots when another limit appears or goes, as + its week did on 2026-09-13 when its 5 h limit went away. Every analysis of a window reads its + series, never a window of another length under the same id. A window without a known length or reset has no pace; FinalToken never guesses one; an estimate is a marked calculation from measured tokens, not a guess. @@ -246,8 +254,9 @@ better, and overstates `u₀` by the use in that sample's hour before the sample windows, with each day's even pace and budget for its share and the instance start and reset marked on the first and last day; token totals for today, the current session and the week of [D9](#d9--the-snapshot-file-is-the-apps-only-output-to-other-processes), each saying since - when; charts, one window chart per limit - window, and the top entries by model and by project, with the rest folded into an expandable + when; charts, one window chart per limit window; the reset history of each long window + ([D12](#d12--reset-history)); and the top entries by model and by project, with the rest folded + into an expandable "Other". A window chart is a burn-up of one instance from its start to its reset: the used percent as a line (measured, or estimated before the first sample), the even-pace diagonal from 0 % to 100 %, the forecast to the reset and the previous instance faintly behind, with no @@ -323,3 +332,58 @@ setting says so and nothing happens. **Why.** R7. **Gives up.** Elgato's double-click `.streamDeckPlugin` installer, which always asks. + +## D12 — Reset history + +**Decision.** For each limit window longer than a day, the panel lists the instances of its +window series ([D7](#d7--pace)) that have samples and overlap the panel's range, newest first, +with totals over them. Inferred instances are left out, because their resets were not observed. + +- **End.** An instance ends at its reset or at the next instance's start (D7). One that ends + more than 15 minutes before its reset **reset early**, and the time from its end to its reset + is **skipped**. The running instance is marked as running and has no end figures yet. +- **Figures.** Start, end, duration and reset; peak and final use (the last point of its D7 + burn-up, marked when estimated); when it reached 100 % and how long it stayed there; tokens by + kind and by model in its hours (the window's model family only, boundary hours as in D7); and + their API value ([D13](#d13--api-value-at-list-prices)). +- **Unused.** A finished instance leaves `100 − final use` percent of its limit unused. +- **Gift.** An early reset hands out a fresh limit ahead of schedule: its gift is + `100 · skipped / W` percent of a limit. Over many windows, that is how many extra limits the + provider gave. +- **Value of a percent.** Unused and gift percent become tokens and money at the instance's own + tokens and API value per percent point when its final use is at least 5 %; otherwise at the + median of the series' instances that qualify. Without one, only the percent is shown. +- **Totals** over the listed instances: their number, early resets, tokens, API value, unused + and gift (in limits and value), and how often and how long 100 % was reached. +- **Timeline.** Each series shows its instances on one time axis without joining their lines, + marks each reset and the skipped time of early resets, and counts its early resets by local + hour and weekday. + +**Why.** R4. The developer asked for figures per reset, including wastage, API value and what +early resets give (developer feedback, 2026-10-18). Codex resets early often: 11 of its 12 week +instances from 2026-09-21 to 2026-10-17 ended early, some after 10 hours. + +**Gives up.** Resets FinalToken never saw: before its first sample, and instances without any +sample. Token figures at a boundary are only as fine as an hour. The gift assumes the provider +would have kept its schedule. Unused and gift values assume the instance's model mix. A drop in +use without a new reset is not a reset. + +## D13 — API value at list prices + +**Decision.** FinalToken estimates what tokens would cost at the providers' public API list +prices. A table compiled into Core gives, per model, US dollars per million tokens for input, +output, cache write and cache read (Claude) or input, cached input and output (Codex), with the +day it was checked and its source pages. A model id matches its entry exactly or with a +trailing date suffix (`claude-haiku-4-5-20251001`). A model without an entry has no value; its +tokens are counted and shown as unpriced. Claude cache writes use the 5-minute price. Reasoning +is part of output and Codex cached input part of input, as in [D7](#d7--pace). Values are +shown with "≈" as "at API list prices". + +**Why.** The developer asked what each window would cost at API prices (developer feedback, +2026-10-18). [D2](#d2--the-clis-are-the-only-interface-to-a-provider) rules out asking a +provider; a dated table can be checked by hand and is updated with a release. + +**Gives up.** Price changes after the check until a release updates the table. Long-context +prices (OpenAI above 272K input tokens, Claude Haiku 5.5 above 100K), because hourly buckets do +not keep request sizes. The 1-hour cache write price, fast and batch prices, and models not in +the table. diff --git a/src/FinalToken.App/AGENTS.md b/src/FinalToken.App/AGENTS.md index 85beac7..d540550 100644 --- a/src/FinalToken.App/AGENTS.md +++ b/src/FinalToken.App/AGENTS.md @@ -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. diff --git a/src/FinalToken.App/BreakdownTable.cs b/src/FinalToken.App/BreakdownTable.cs index 76e8bc5..5fe7d2d 100644 --- a/src/FinalToken.App/BreakdownTable.cs +++ b/src/FinalToken.App/BreakdownTable.cs @@ -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.Total); public sealed class BreakdownTable : StackPanel { @@ -29,21 +24,21 @@ public sealed class BreakdownTable : StackPanel } public static IReadOnlyList SortRows(IEnumerable rows, BreakdownColumn column, bool descending) { - if (column == BreakdownColumn.Name) return (descending ? rows.OrderByDescending(r => r.Name, StringComparer.OrdinalIgnoreCase) : rows.OrderBy(r => r.Name, StringComparer.OrdinalIgnoreCase)).ToArray(); + 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); } } } diff --git a/src/FinalToken.App/DataTooltip.cs b/src/FinalToken.App/DataTooltip.cs index 6641133..0719988 100644 --- a/src/FinalToken.App/DataTooltip.cs +++ b/src/FinalToken.App/DataTooltip.cs @@ -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); /// D8: every data tooltip uses the same title and aligned label/value layout. -public sealed class DataTooltip : Border +public sealed partial class DataTooltip : Border { public string Title { get; } public IReadOnlyList 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()); } + /// + /// Opens a tall tooltip beside the pointer, never over it: a tooltip that covers the pointer takes + /// it from , which then loses the tooltip. Call before other pointer handlers. + /// + 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)); } diff --git a/src/FinalToken.App/DetailTable.cs b/src/FinalToken.App/DetailTable.cs new file mode 100644 index 0000000..37c1d07 --- /dev/null +++ b/src/FinalToken.App/DetailTable.cs @@ -0,0 +1,43 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Layout; + +namespace FinalToken.App; + +public class TableState(TColumn sort) where TColumn : struct, Enum +{ + public bool Expanded { get; set; } + public TColumn Sort { get; set; } = sort; + public bool Descending { get; set; } = true; +} + +/// Shared sorting, headers, row placement and expansion for detail tables. +public static class DetailTable +{ + public static IOrderedEnumerable Sort(IEnumerable rows, Func key, + bool descending, IComparer? comparer = null) => + descending ? rows.OrderByDescending(key, comparer) : rows.OrderBy(key, comparer); + + public static Button Header(string label, TColumn column, TableState 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(int count, TableState 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 }; +} diff --git a/src/FinalToken.App/PanelViewModel.cs b/src/FinalToken.App/PanelViewModel.cs index 089f7f5..d39400e 100644 --- a/src/FinalToken.App/PanelViewModel.cs +++ b/src/FinalToken.App/PanelViewModel.cs @@ -14,6 +14,7 @@ public sealed record HistoryView(IReadOnlyList Hourly, IReadOnlyList IReadOnlyList Limits, IReadOnlyList Models, IReadOnlyList Projects) { public IReadOnlyList Details { get; init; } = []; + public IReadOnlyList 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(); + var resets = new List(); 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 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)); } diff --git a/src/FinalToken.App/PanelWindow.cs b/src/FinalToken.App/PanelWindow.cs index 5c9e85b..b4d2c99 100644 --- a/src/FinalToken.App/PanelWindow.cs +++ b/src/FinalToken.App/PanelWindow.cs @@ -21,6 +21,8 @@ public sealed class PanelWindow : Window private bool wide; private int limitColumns; private readonly Dictionary selectedDailyWindow = []; + private readonly Dictionary selectedResetWindow = []; + private readonly Dictionary> 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))); diff --git a/src/FinalToken.App/ResetCard.cs b/src/FinalToken.App/ResetCard.cs new file mode 100644 index 0000000..1b73f45 --- /dev/null +++ b/src/FinalToken.App/ResetCard.cs @@ -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 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)); + } +} diff --git a/src/FinalToken.App/ResetCharts.cs b/src/FinalToken.App/ResetCharts.cs new file mode 100644 index 0000000..79d591f --- /dev/null +++ b/src/FinalToken.App/ResetCharts.cs @@ -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 Skipped) +{ + public int LaneCount => Skipped.Count == 0 ? 0 : Skipped.Max(s => s.Lane) + 1; +} + +/// D12: real instances share a time axis; their burn-ups are never connected. +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(); + var skipped = new List(); + 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 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); + } + } +} diff --git a/src/FinalToken.App/ResetTable.cs b/src/FinalToken.App/ResetTable.cs new file mode 100644 index 0000000..5bf8e43 --- /dev/null +++ b/src/FinalToken.App/ResetTable.cs @@ -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 state; + private readonly TimeProvider clock; + public ResetTable(ResetHistory history, TableState state, TimeProvider clock) + { + this.history = history; this.state = state; this.clock = clock; Spacing = 8; + AttachedToVisualTree += (_, _) => RenderTable(); + } + public static IReadOnlyList SortRows(IEnumerable 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)); + } +} diff --git a/src/FinalToken.App/ResetTooltip.cs b/src/FinalToken.App/ResetTooltip.cs new file mode 100644 index 0000000..cf37056 --- /dev/null +++ b/src/FinalToken.App/ResetTooltip.cs @@ -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 + { + 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(); + 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))); + } +} diff --git a/src/FinalToken.App/Ui.cs b/src/FinalToken.App/Ui.cs index c6f5ebf..807171a 100644 --- a/src/FinalToken.App/Ui.cs +++ b/src/FinalToken.App/Ui.cs @@ -83,6 +83,8 @@ public static class Ui window.Styles.Add(checks); var focusCheck = new Style(s => s.OfType().Class(":focus-visible")); focusCheck.Setters.Add(new Setter(TemplatedControl.BorderBrushProperty, new DynamicResourceExtension("Ink"))); window.Styles.Add(focusCheck); + // 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()); 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() diff --git a/src/FinalToken.Core/AGENTS.md b/src/FinalToken.Core/AGENTS.md index d46af09..e356421 100644 --- a/src/FinalToken.Core/AGENTS.md +++ b/src/FinalToken.Core/AGENTS.md @@ -1,5 +1,5 @@ # Core -UI-free domain and file/CLI integration. Implements D1–D7, D9 and the D11 installer contract. +UI-free domain and file/CLI integration. Implements D1–D7, D9 and D11–D13. Keep parsers total. Only metadata leaves them. JSON uses CoreJsonContext. Hosts own StoreLock. Persisted defaults use settable properties: source-generated init-only property factories can overwrite initializers for missing JSON members. Treat settings as values; update them with `with`. @@ -29,6 +29,19 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root No shipped production dependency is needed in Core. Source parsers use temporary memory for one complete line; memory usage therefore scales with the largest transcript entry. +## Limit analysis + +- Use `WindowSeries` (provider, name, length) for all sample queries and instance membership (D7). + Codex `:primary` and `:secondary` suffixes identify slots, not limits. Read across ids with + `HistoryStore.LimitSamples(window, from, to)`; the original id query remains available. +- `LimitAnalysis` shares real spans and burn-up construction between `Analyze` and `Resets`. + Keep the current instance, ignore stale samples and leave gaps unassigned. A boundary hour + belongs to its starting instance, else to its ending instance (D7). +- Reset history lists only real instances overlapping the range, with whole-instance values (D12). + Percent values use the instance at final ≥ 5 %, else the qualifying listed-instance median. +- `ApiPrices` is the dated D13 list-price table. Match exact ids or a valid trailing date. + Unknown models remain unpriced; never infer a price from a family or count token subsets twice. + ## Store persistence and scaling - Refresh changes append as one durable, newline-terminated transaction to diff --git a/src/FinalToken.Core/ApiPrices.cs b/src/FinalToken.Core/ApiPrices.cs new file mode 100644 index 0000000..1f0ff45 --- /dev/null +++ b/src/FinalToken.Core/ApiPrices.cs @@ -0,0 +1,65 @@ +using System.Globalization; + +namespace FinalToken.Core; + +public sealed record ApiPrice(decimal Input, decimal CacheWrite, decimal CacheRead, decimal Output); + +/// D13: USD per million tokens, checked 2026-10-18. Standard short-context prices. +/// https://platform.claude.com/docs/en/about-claude/pricing +/// https://developers.openai.com/api/docs/pricing +/// Claude writes use the 5-minute price; Haiku 5.5 assumes prompts up to 100K. +public static class ApiPrices +{ + public static DateOnly CheckedOn => new(2026, 10, 18); + private static readonly Dictionary Claude = new(StringComparer.Ordinal) + { + ["claude-fable-5-1"] = new(10, 12.50m, .25m, 50), + ["claude-fable-5"] = new(10, 12.50m, 1, 50), + ["claude-opus-5-5"] = new(4, 5, .20m, 20), + ["claude-opus-5"] = new(5, 6.25m, .50m, 25), + ["claude-opus-4-8"] = new(5, 6.25m, .50m, 25), + ["claude-opus-4-7"] = new(5, 6.25m, .50m, 25), + ["claude-opus-4-6"] = new(5, 6.25m, .50m, 25), + ["claude-opus-4-5"] = new(5, 6.25m, .50m, 25), + ["claude-sonnet-5-5"] = new(2, 2.50m, .10m, 10), + ["claude-sonnet-5"] = new(2, 2.50m, .20m, 10), + ["claude-sonnet-4-6"] = new(3, 3.75m, .30m, 15), + ["claude-sonnet-4-5"] = new(3, 3.75m, .30m, 15), + ["claude-haiku-5-5"] = new(.10m, .125m, .01m, .50m), + ["claude-haiku-4-5"] = new(1, 1.25m, .10m, 5) + }; + private static readonly Dictionary Codex = new(StringComparer.Ordinal) + { + ["gpt-6-astra"] = new(10, 0, 1, 50), + ["gpt-6.1-sol"] = new(2, 0, .10m, 10), + ["gpt-6-sol"] = new(2, 0, .20m, 10), + ["gpt-6-luna"] = new(.10m, 0, .01m, .50m), + ["gpt-5.6-sol"] = new(4, 0, .40m, 20), + ["gpt-5.6-terra"] = new(2, 0, .20m, 12), + ["gpt-5.6-luna"] = new(.20m, 0, .02m, 1.20m), + ["gpt-5.5"] = new(5, 0, .50m, 30), + ["gpt-5.4"] = new(2.50m, 0, .25m, 15), + ["gpt-5.4-mini"] = new(.75m, 0, .075m, 4.50m), + ["gpt-5.3-codex"] = new(1.75m, 0, .175m, 14), + ["gpt-5.2"] = new(1.75m, 0, .175m, 14), + ["gpt-5.1"] = new(1.25m, 0, .125m, 10), + ["gpt-5"] = new(1.25m, 0, .125m, 10) + }; + public static ApiPrice? Find(Provider provider, string? model) + { + if (model is null) return null; + var prices = provider == Provider.Claude ? Claude : Codex; + if (prices.TryGetValue(model, out var price)) return price; + return model.Length > 9 && model[^9] == '-' && + DateOnly.TryParseExact(model[^8..], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _) && + prices.TryGetValue(model[..^9], out price) ? price : null; + } + public static decimal? Value(Provider provider, string? model, TokenCounts counts) + { + if (Find(provider, model) is not { } p) return null; + var input = provider == Provider.Claude ? Math.Max(0, counts.Input) : Math.Max(0, counts.Input - counts.CacheRead); + return (input * p.Input + Math.Max(0, counts.CacheRead) * p.CacheRead + + (provider == Provider.Claude ? Math.Max(0, counts.CacheWrite) * p.CacheWrite : 0) + + Math.Max(0, counts.Output) * p.Output) / 1_000_000; + } +} diff --git a/src/FinalToken.Core/HistoryStore.cs b/src/FinalToken.Core/HistoryStore.cs index 1e536dd..23601c9 100644 --- a/src/FinalToken.Core/HistoryStore.cs +++ b/src/FinalToken.Core/HistoryStore.cs @@ -212,6 +212,14 @@ public sealed class HistoryStore .Where(w => w.Provider == provider && w.Id == windowId && w.SampleTime >= from && w.SampleTime < to) .OrderBy(w => w.SampleTime).ToArray(); } + public IReadOnlyList LimitSamples(Provider provider, DateTimeOffset from, DateTimeOffset to) + { + lock (gate) return SelectMonths(from, to).SelectMany(m => GetPartition(m).Limits) + .Where(w => w.Provider == provider && w.SampleTime >= from && w.SampleTime < to) + .OrderBy(w => w.SampleTime).ToArray(); + } + public IReadOnlyList LimitSamples(LimitWindow window, DateTimeOffset from, DateTimeOffset to) => + LimitSamples(window.Provider, from, to).Where(WindowSeries.For(window).Matches).ToArray(); public IReadOnlyList TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval) => TokenSeries(provider, from, to, interval, TimeZoneInfo.Local); public IReadOnlyList TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval, diff --git a/src/FinalToken.Core/LimitAnalysis.cs b/src/FinalToken.Core/LimitAnalysis.cs index 8d905e7..e92025b 100644 --- a/src/FinalToken.Core/LimitAnalysis.cs +++ b/src/FinalToken.Core/LimitAnalysis.cs @@ -14,7 +14,7 @@ public static partial class LimitAnalysis { /// D7: minute-rounded probe resets may drift within 15 minutes in either direction. public static bool SameInstance(LimitWindow first, LimitWindow second) => - first.Provider == second.Provider && first.Id == second.Id && + WindowSeries.For(first) == WindowSeries.For(second) && first.ResetsAt is { } firstReset && second.ResetsAt is { } secondReset && (firstReset - secondReset).Duration() <= TimeSpan.FromMinutes(15); diff --git a/src/FinalToken.Core/LimitDays.cs b/src/FinalToken.Core/LimitDays.cs index ee97ec1..8f971d1 100644 --- a/src/FinalToken.Core/LimitDays.cs +++ b/src/FinalToken.Core/LimitDays.cs @@ -2,18 +2,18 @@ namespace FinalToken.Core; public static partial class LimitAnalysis { + // Hour buckets of one instance in [from, to); tokenEnd excludes the boundary hour a later instance owns. private static double WeightedTokens(IReadOnlyList<(DateTimeOffset Time, double Weight)> weighted, - DateTimeOffset start, DateTimeOffset end, DateTimeOffset from, DateTimeOffset to) + DateTimeOffset start, DateTimeOffset tokenEnd, DateTimeOffset from, DateTimeOffset to) { var hour = Hour(from < start ? start : from); - var exclusiveEnd = Hour(end); - return weighted.Where(p => p.Time >= hour && p.Time < to && p.Time < exclusiveEnd).Sum(p => p.Weight); + return weighted.Where(p => p.Time >= hour && p.Time < to && p.Time < tokenEnd).Sum(p => p.Weight); } // D7: plan from the day baseline; spending within that plan does not take from later days. private static WindowDays PlanDays(LimitWindow window, LimitInstance current, LimitInstance? previous, LimitDay? today, IReadOnlyList observations, IReadOnlyList<(DateTimeOffset Time, double Weight)> weighted, - DateTimeOffset now, TimeZoneInfo zone) + DateTimeOffset tokenEnd, DateTimeOffset now, TimeZoneInfo zone) { var length = window.Length!.Value; double? baseline = null; UseOrigin? origin = null; @@ -29,10 +29,10 @@ public static partial class LimitAnalysis // D7: use only completed hours before the first sample; its own hour can still grow. var sampleHour = Hour(first.SampleTime); var baselineEnd = start < sampleHour ? start : sampleHour; - var denominator = WeightedTokens(weighted, current.Start, current.End, current.Start, sampleHour); + var denominator = WeightedTokens(weighted, current.Start, tokenEnd, current.Start, sampleHour); if (denominator > 0) { - baseline = first.UsedPercent * WeightedTokens(weighted, current.Start, current.End, current.Start, baselineEnd) / denominator; + baseline = first.UsedPercent * WeightedTokens(weighted, current.Start, tokenEnd, current.Start, baselineEnd) / denominator; origin = UseOrigin.Estimated; } } diff --git a/src/FinalToken.Core/LimitEstimates.cs b/src/FinalToken.Core/LimitEstimates.cs index e91656f..8dbe6ba 100644 --- a/src/FinalToken.Core/LimitEstimates.cs +++ b/src/FinalToken.Core/LimitEstimates.cs @@ -24,118 +24,92 @@ public static partial class LimitAnalysis { if (window.ResetsAt is not { } reset || window.Length is not { Ticks: > 0 } length || Pace.Calculate(window, now).State == PaceState.Unknown) return null; zone ??= TimeZoneInfo.Local; - var observations = samples.Append(window).Where(s => s.Provider == window.Provider && s.Id == window.Id && - s.ResetsAt is not null && s.Length is { Ticks: > 0 } && s.SampleTime <= now && double.IsFinite(s.UsedPercent) && s.UsedPercent is >= 0 and <= 100).OrderBy(s => s.SampleTime).ToArray(); - var weighted = tokens.Where(p => TokenWeights.Matches(window, p.Model)).GroupBy(p => p.Time) - .Select(g => (Time: g.Key, Weight: g.Sum(p => TokenWeights.Weighted(window.Provider, p.Counts)))).OrderBy(p => p.Time).ToArray(); - // D7: samples identify real instances; resets and lengths define their boundaries. - var groups = new List> { new() { window } }; - foreach (var observation in observations) - { - var group = groups.FirstOrDefault(g => SameInstance(g[0], observation)); - if (group is null) groups.Add([observation]); else group.Add(observation); - } - var spans = groups.Select(g => - { - var anchor = SameInstance(g[0], window) ? window : g[^1]; - return (Anchor: anchor, Start: anchor.ResetsAt!.Value - anchor.Length!.Value, End: anchor.ResetsAt.Value); - }).OrderBy(g => g.Start).ToArray(); - for (var i = 0; i + 1 < spans.Length; i++) - if (spans[i + 1].Start < spans[i].End) spans[i].End = spans[i + 1].Start; + var spans = RealSpans(window, samples, now); + var observations = spans.SelectMany(s => s.Samples).ToArray(); + var weighted = WeightedTokens(window, tokens); var currentSpan = spans.Single(g => SameInstance(g.Anchor, window)); - var current = Build(window, currentSpan.Start, currentSpan.End, now < currentSpan.End ? now : currentSpan.End, null); - var realPast = spans.Where(g => g.Start < currentSpan.Start).OrderByDescending(g => g.Start).ToArray(); + var currentTokenEnd = TokenEnd(currentSpan.End, null); + var current = BuildInstance(window, observations, weighted, currentSpan.Start, currentSpan.End, + now < currentSpan.End ? now : currentSpan.End, null, currentTokenEnd, now, zone); var past = new List(); - var realIndex = 0; - var cursor = currentSpan.Start; - for (var i = 0; i < 8; i++) + foreach (var (span, successorStart) in SpansWithSuccessors(window, spans).Skip(1).Take(8)) { - var canInfer = length > TimeSpan.FromDays(1); - if (!canInfer && realIndex == realPast.Length) break; - var inferredStart = cursor - length; - // A candidate overlapping the nearest real span yields to that whole span. - // A shorter gap stays unassigned. Sessions never produce inferred candidates. - var span = realIndex < realPast.Length && (!canInfer || realPast[realIndex].End > inferredStart) - ? realPast[realIndex++] - : (Anchor: window with { ResetsAt = cursor }, Start: inferredStart, End: cursor); - var instance = Build(span.Anchor, span.Start, span.End, span.End < now ? span.End : now, current.Scale); + var instance = BuildInstance(span.Anchor, observations, weighted, span.Start, span.End, + span.End < now ? span.End : now, current.Scale, TokenEnd(span.End, successorStart), now, zone); if (instance.HasData) past.Add(instance); - cursor = span.Start; } WindowDays? days = null; if (length > TimeSpan.FromDays(1)) { var today = current.Days.FirstOrDefault(d => d.IsToday); - days = PlanDays(window, current, past.FirstOrDefault(), today, observations, weighted, now, zone); + days = PlanDays(window, current, past.FirstOrDefault(), today, observations, weighted, currentTokenEnd, now, zone); } return new(current, past, days); + } - LimitInstance Build(LimitWindow anchor, DateTimeOffset start, DateTimeOffset end, DateTimeOffset until, - double? fallback) + private static LimitInstance BuildInstance(LimitWindow anchor, IReadOnlyList observations, + (DateTimeOffset Time, double Weight)[] weighted, DateTimeOffset start, DateTimeOffset end, DateTimeOffset until, + double? fallback, DateTimeOffset tokenEnd, DateTimeOffset now, TimeZoneInfo zone) + { + double Weight(DateTimeOffset from, DateTimeOffset to) => WeightedTokens(weighted, start, tokenEnd, from, to); + var measured = Instance(anchor, observations).Where(s => s.SampleTime >= start - TimeSpan.FromMinutes(15) && s.SampleTime <= until) + .GroupBy(s => s.SampleTime).Select(g => g.Last()).OrderBy(s => s.SampleTime).ToArray(); + var last = measured.LastOrDefault(); + var denominator = last is null ? 0 : Weight(start, last.SampleTime); + var total = Weight(start, until); + double? scale = total <= 0 ? null : last is not null ? denominator > 0 ? last.UsedPercent / denominator : null : fallback; + var points = new SortedDictionary { [start] = new(start, 0, UseOrigin.Measured) }; + if (scale is { } k) { - double Weight(DateTimeOffset from, DateTimeOffset to) + foreach (var time in weighted.Where(p => p.Time >= Hour(start) && p.Time < until && p.Time < tokenEnd).SelectMany(p => new[] { p.Time, p.Time.AddHours(1) }).Append(until).Distinct()) { - return WeightedTokens(weighted, start, end, from, to); + var cutoff = time < until ? time : until; + if (cutoff <= start) continue; + // Samples own the measured span; tokens fill before the first sample and after the last. + if (measured.Length == 0 || cutoff < measured[0].SampleTime) + points[cutoff] = new(cutoff, k * Weight(start, cutoff), UseOrigin.Estimated); + else if (last is not null && cutoff > last.SampleTime) + points[cutoff] = new(cutoff, last.UsedPercent + k * (Weight(start, cutoff) - Weight(start, last.SampleTime)), UseOrigin.Estimated); } - var measured = Instance(anchor, observations).Where(s => s.SampleTime >= start - TimeSpan.FromMinutes(15) && s.SampleTime <= until) - .GroupBy(s => s.SampleTime).Select(g => g.Last()).OrderBy(s => s.SampleTime).ToArray(); - var last = measured.LastOrDefault(); - var denominator = last is null ? 0 : Weight(start, last.SampleTime); - var total = Weight(start, until); - double? scale = total <= 0 ? null : last is not null ? denominator > 0 ? last.UsedPercent / denominator : null : fallback; - var points = new SortedDictionary { [start] = new(start, 0, UseOrigin.Measured) }; - if (scale is { } k) - { - foreach (var time in weighted.Where(p => p.Time >= Hour(start) && p.Time < until && p.Time < Hour(end)).SelectMany(p => new[] { p.Time, p.Time.AddHours(1) }).Append(until).Distinct()) - { - var cutoff = time < until ? time : until; - if (cutoff <= start) continue; - // Samples own the measured span; tokens fill before the first sample and after the last. - if (measured.Length == 0 || cutoff < measured[0].SampleTime) - points[cutoff] = new(cutoff, k * Weight(start, cutoff), UseOrigin.Estimated); - else if (last is not null && cutoff > last.SampleTime) - points[cutoff] = new(cutoff, last.UsedPercent + k * (Weight(start, cutoff) - Weight(start, last.SampleTime)), UseOrigin.Estimated); - } - } - foreach (var sample in measured) points[sample.SampleTime] = new(sample.SampleTime, sample.UsedPercent, UseOrigin.Measured); - DateTimeOffset? reached = null; UseOrigin? reachedOrigin = null; - var raw = points.Values.OrderBy(p => p.Time).ToArray(); - for (var i = 1; i < raw.Length; i++) - { - var point = raw[i]; var prior = raw[i - 1]; - if (reached is null && point.Used >= 100) - { - reached = point.Origin == UseOrigin.Measured || point.Used <= prior.Used ? point.Time - : prior.Time.AddTicks((long)((point.Time - prior.Time).Ticks * Math.Clamp((100 - prior.Used) / (point.Used - prior.Used), 0, 1))); - reachedOrigin = point.Origin; - if (point.Origin == UseOrigin.Estimated) points[reached.Value] = new(reached.Value, 100, UseOrigin.Estimated); - } - if (point.Origin == UseOrigin.Estimated) - points[point.Time] = point with { Used = reached is not null ? 100 : Math.Min(100, point.Used) }; - } - double EstimatedAt(DateTimeOffset time, double factor) => reachedOrigin == UseOrigin.Estimated && time >= reached - ? 100 : Math.Min(100, factor * Weight(start, time)); - var daily = new List(); - for (var day = CalendarDays.Start(start, zone); day < end; day = CalendarDays.NextStart(day, zone)) - { - var next = CalendarDays.NextStart(day, zone); var dayEnd = next < end ? next : end; - var cutoff = dayEnd < until ? dayEnd : until; var future = day > until; - var baseline = day <= start ? 0 : Last(day); - var cumulative = cutoff >= start ? Last(cutoff) : null; - if (last is not null && scale is not null && cutoff > last.SampleTime && Weight(start, cutoff) > Weight(start, last.SampleTime)) cumulative = null; - double? use = !future && baseline is { } b && cumulative is { } c ? Math.Max(0, c - b) : null; - var origin = UseOrigin.Measured; - if (!future && use is null && scale is { } factor) - { - use = Math.Max(0, EstimatedAt(cutoff, factor) - (day > start ? EstimatedAt(day, factor) : 0)); origin = UseOrigin.Estimated; - cumulative ??= EstimatedAt(cutoff, factor); - } - daily.Add(new(day, dayEnd, use, future ? null : cumulative, day == CalendarDays.Start(now, zone), future, origin)); - } - var series = points.Values.OrderBy(p => p.Time).ToArray(); - double? peak = series.Length > 1 ? series.Max(p => p.Used) : null; - return new(start, anchor.ResetsAt!.Value, series, daily, scale, peak, reached, end, reachedOrigin); - double? Last(DateTimeOffset time) => measured.LastOrDefault(s => s.SampleTime <= time)?.UsedPercent; } + foreach (var sample in measured) points[sample.SampleTime] = new(sample.SampleTime, sample.UsedPercent, UseOrigin.Measured); + DateTimeOffset? reached = null; UseOrigin? reachedOrigin = null; + var raw = points.Values.OrderBy(p => p.Time).ToArray(); + for (var i = 1; i < raw.Length; i++) + { + var point = raw[i]; var prior = raw[i - 1]; + if (reached is null && point.Used >= 100) + { + reached = point.Origin == UseOrigin.Measured || point.Used <= prior.Used ? point.Time + : prior.Time.AddTicks((long)((point.Time - prior.Time).Ticks * Math.Clamp((100 - prior.Used) / (point.Used - prior.Used), 0, 1))); + reachedOrigin = point.Origin; + if (point.Origin == UseOrigin.Estimated) points[reached.Value] = new(reached.Value, 100, UseOrigin.Estimated); + } + if (point.Origin == UseOrigin.Estimated) + points[point.Time] = point with { Used = reached is not null ? 100 : Math.Min(100, point.Used) }; + } + double EstimatedAt(DateTimeOffset time, double factor) => reachedOrigin == UseOrigin.Estimated && time >= reached + ? 100 : Math.Min(100, factor * Weight(start, time)); + var daily = new List(); + for (var day = CalendarDays.Start(start, zone); day < end; day = CalendarDays.NextStart(day, zone)) + { + var next = CalendarDays.NextStart(day, zone); var dayEnd = next < end ? next : end; + var cutoff = dayEnd < until ? dayEnd : until; var future = day > until; + var baseline = day <= start ? 0 : Last(day); + var cumulative = cutoff >= start ? Last(cutoff) : null; + if (last is not null && scale is not null && cutoff > last.SampleTime && Weight(start, cutoff) > Weight(start, last.SampleTime)) cumulative = null; + double? use = !future && baseline is { } b && cumulative is { } c ? Math.Max(0, c - b) : null; + var origin = UseOrigin.Measured; + if (!future && use is null && scale is { } factor) + { + use = Math.Max(0, EstimatedAt(cutoff, factor) - (day > start ? EstimatedAt(day, factor) : 0)); origin = UseOrigin.Estimated; + cumulative ??= EstimatedAt(cutoff, factor); + } + daily.Add(new(day, dayEnd, use, future ? null : cumulative, day == CalendarDays.Start(now, zone), future, origin)); + } + var series = points.Values.OrderBy(p => p.Time).ToArray(); + double? peak = series.Length > 1 ? series.Max(p => p.Used) : null; + return new(start, anchor.ResetsAt!.Value, series, daily, scale, peak, reached, end, reachedOrigin); + double? Last(DateTimeOffset time) => measured.LastOrDefault(s => s.SampleTime <= time)?.UsedPercent; } } diff --git a/src/FinalToken.Core/LimitSpans.cs b/src/FinalToken.Core/LimitSpans.cs new file mode 100644 index 0000000..9a794f9 --- /dev/null +++ b/src/FinalToken.Core/LimitSpans.cs @@ -0,0 +1,81 @@ +namespace FinalToken.Core; + +public static partial class LimitAnalysis +{ + private sealed record InstanceSpan(LimitWindow Anchor, IReadOnlyList Samples, + DateTimeOffset Start, DateTimeOffset End); + + private static InstanceSpan[] RealSpans(LimitWindow window, IEnumerable samples, DateTimeOffset now) + { + var key = WindowSeries.For(window); + var observations = samples.Append(window).Where(s => key.Matches(s) && s.ResetsAt is not null && + s.Length is { Ticks: > 0 } && s.SampleTime <= now && double.IsFinite(s.UsedPercent) && + s.UsedPercent is >= 0 and <= 100).Distinct().OrderByDescending(s => s.SampleTime).ToArray(); + var groups = new List> { new() { window } }; + foreach (var sample in observations) + { + var group = groups.FirstOrDefault(g => SameInstance(g[0], sample)); + if (group is null) groups.Add([sample]); else group.Add(sample); + } + var candidates = groups.Select(g => + { + var anchor = SameInstance(g[0], window) ? window : g.MaxBy(s => s.SampleTime)!; + return new InstanceSpan(anchor, g.Distinct().OrderBy(s => s.SampleTime).ToArray(), + anchor.ResetsAt!.Value - anchor.Length!.Value, anchor.ResetsAt.Value); + }).ToArray(); + var current = candidates[0]; + var accepted = new List { current }; + var latestStart = current.Start; + // D7 / #9: earlier observations cannot put an instance after a later observed instance. + // Order by first observation so an interleaved late rollout cannot reorder real resets. + foreach (var span in candidates.Skip(1).OrderByDescending(s => s.Samples.Min(p => p.SampleTime))) + { + if (span.Start > latestStart) continue; + accepted.Add(span); latestStart = span.Start; + } + var result = accepted.OrderBy(s => s.Start).ToArray(); + for (var i = 0; i + 1 < result.Length; i++) + if (result[i + 1].Start < result[i].End) result[i] = result[i] with { End = result[i + 1].Start }; + // A late sample of the old instance after an early reset is stale too. + result = result.Select(s => + { + var valid = s.Samples.Where(p => p.SampleTime <= s.End).ToArray(); + var anchor = SameInstance(s.Anchor, window) ? window : valid.LastOrDefault() ?? s.Anchor; + return new InstanceSpan(anchor, valid, anchor.ResetsAt!.Value - anchor.Length!.Value, anchor.ResetsAt.Value); + }).Where(s => s.Samples.Count > 0 || SameInstance(s.Anchor, window)).OrderBy(s => s.Start).ToArray(); + for (var i = 0; i + 1 < result.Length; i++) + if (result[i + 1].Start < result[i].End) result[i] = result[i] with { End = result[i + 1].Start }; + return result.Select(s => s with { Samples = s.Samples.Where(p => p.SampleTime <= s.End).ToArray() }).ToArray(); + } + + private static IEnumerable<(InstanceSpan Span, DateTimeOffset? SuccessorStart)> SpansWithSuccessors( + LimitWindow window, IReadOnlyList spans) + { + var current = spans.Single(s => SameInstance(s.Anchor, window)); + yield return (current, null); + var realPast = spans.Where(s => s.Start < current.Start).OrderByDescending(s => s.Start).ToArray(); + var length = window.Length!.Value; + var canInfer = length > TimeSpan.FromDays(1); + var realIndex = 0; + var cursor = current.Start; + while (canInfer || realIndex < realPast.Length) + { + var inferredStart = cursor - length; + // D7: a candidate overlapping the nearest real span yields to that whole span. + // A shorter gap stays unassigned. Sessions never produce inferred candidates. + var span = realIndex < realPast.Length && (!canInfer || realPast[realIndex].End > inferredStart) + ? realPast[realIndex++] + : new InstanceSpan(window with { ResetsAt = cursor }, [], inferredStart, cursor); + yield return (span, cursor); + cursor = span.Start; + } + } + + private static DateTimeOffset TokenEnd(DateTimeOffset end, DateTimeOffset? successorStart) => + end == Hour(end) || successorStart is { } start && Hour(start) == Hour(end) ? Hour(end) : Hour(end).AddHours(1); + + private static (DateTimeOffset Time, double Weight)[] WeightedTokens(LimitWindow window, IReadOnlyList tokens) => + tokens.Where(p => TokenWeights.Matches(window, p.Model)).GroupBy(p => p.Time) + .Select(g => (Time: g.Key, Weight: g.Sum(p => TokenWeights.Weighted(window.Provider, p.Counts)))) + .OrderBy(p => p.Time).ToArray(); +} diff --git a/src/FinalToken.Core/ResetHistory.cs b/src/FinalToken.Core/ResetHistory.cs new file mode 100644 index 0000000..bbdedb6 --- /dev/null +++ b/src/FinalToken.Core/ResetHistory.cs @@ -0,0 +1,112 @@ +namespace FinalToken.Core; + +public enum PercentBasis { OwnInstance, SeriesMedian } +public sealed record PercentRate(double Tokens, decimal? ApiValue, PercentBasis Basis); +public sealed record ResetValue(double Percent, double? Tokens, decimal? ApiValue); +public sealed record ResetModel(string? Model, TokenCounts Tokens, decimal? ApiValue); +public sealed record ResetInstance(LimitInstance BurnUp, DateTimeOffset End, bool Running, bool Early, + TimeSpan Skipped, TokenCounts Tokens, IReadOnlyList Models, decimal? ApiValue, long UnpricedTokens, + PercentRate? ValuePerPercent = null, ResetValue? Unused = null, ResetValue? Gift = null) +{ + public DateTimeOffset Start => BurnUp.Start; + public DateTimeOffset Reset => BurnUp.Reset; + public TimeSpan Duration => End - Start; + public LimitPoint Final => BurnUp.Points[^1]; + public double? Peak => BurnUp.Peak; + public UseOrigin PeakOrigin => BurnUp.Points.Any(p => p.Used == Peak && p.Origin == UseOrigin.Measured) + ? UseOrigin.Measured : UseOrigin.Estimated; + public DateTimeOffset? ReachedLimit => BurnUp.ReachedLimit; + public TimeSpan TimeAtLimit => ReachedLimit is { } time && End > time ? End - time : TimeSpan.Zero; +} +public sealed record ResetTotals(int Instances, int Finished, int Early, TokenCounts Tokens, decimal? ApiValue, + long UnpricedTokens, ResetValue Unused, ResetValue Gift, TimeSpan Skipped, int ReachedLimit, TimeSpan TimeAtLimit); +public sealed record ResetHistory(LimitWindow Window, IReadOnlyList Instances, ResetTotals Totals, + IReadOnlyList EarlyByHour, IReadOnlyList EarlyByWeekday, TimeSpan? MedianDuration, DateTimeOffset FirstSample); + +public static partial class LimitAnalysis +{ + /// D12: only observed real instances; values cover whole overlapping instances, not a clipped range. + public static ResetHistory Resets(LimitWindow window, IEnumerable samples, + IReadOnlyList tokens, DateTimeOffset from, DateTimeOffset now, TimeZoneInfo? zone = null) + { + zone ??= TimeZoneInfo.Local; + var rows = new List(); + var hours = new int[24]; var weekdays = new int[7]; + var firstSample = window.SampleTime; + if (window.ResetsAt is not null && window.Length is { } length && length > TimeSpan.FromDays(1) && + Pace.Calculate(window, now).State != PaceState.Unknown) + { + var spans = RealSpans(window, samples, now); + firstSample = spans.SelectMany(s => s.Samples).Select(s => s.SampleTime).DefaultIfEmpty(window.SampleTime).Min(); + var weighted = WeightedTokens(window, tokens); + foreach (var (span, successorStart) in SpansWithSuccessors(window, spans) + .TakeWhile(s => s.Span.Start >= spans[0].Start) + .Where(s => s.Span.Samples.Count > 0 && s.Span.End > from && s.Span.Start <= now)) + { + var running = span.End > now; + var end = running ? now : span.End; + var tokenEnd = TokenEnd(span.End, successorStart); + var burn = BuildInstance(span.Anchor, span.Samples, weighted, span.Start, span.End, end, + null, tokenEnd, now, zone); + var models = tokens.Where(p => p.Time >= Hour(span.Start) && p.Time < end && + p.Time < tokenEnd && TokenWeights.Matches(window, p.Model)) + .GroupBy(p => p.Model).Select(g => + { + var counts = g.Aggregate(new TokenCounts(), (sum, p) => sum + p.Counts); + return new ResetModel(g.Key, counts, ApiPrices.Value(window.Provider, g.Key, counts)); + }).OrderByDescending(m => m.Tokens.Total).ToArray(); + var early = !running && span.Anchor.ResetsAt!.Value - end > TimeSpan.FromMinutes(15); + rows.Add(new(burn, end, running, early, early ? span.Anchor.ResetsAt!.Value - end : TimeSpan.Zero, + models.Aggregate(new TokenCounts(), (sum, m) => sum + m.Tokens), models, + SumMoney(models.Select(m => m.ApiValue)), models.Where(m => m.ApiValue is null).Sum(m => m.Tokens.Total))); + if (early) + { + var local = TimeZoneInfo.ConvertTime(end, zone); + hours[local.Hour]++; weekdays[((int)local.DayOfWeek + 6) % 7]++; + } + } + var qualifying = rows.Where(r => r.Final.Used >= 5).ToArray(); + var medianTokens = Median(qualifying.Select(r => r.Tokens.Total / r.Final.Used)); + var medianMoney = MedianMoney(qualifying.Where(r => r.ApiValue is not null).Select(r => r.ApiValue!.Value / (decimal)r.Final.Used)); + for (var i = 0; i < rows.Count; i++) + { + var row = rows[i]; + var rate = row.Final.Used >= 5 ? new PercentRate(row.Tokens.Total / row.Final.Used, + row.ApiValue / (decimal)row.Final.Used, PercentBasis.OwnInstance) : medianTokens is { } median + ? new PercentRate(median, medianMoney, PercentBasis.SeriesMedian) : null; + ResetValue Value(double percent) => new(percent, rate?.Tokens * percent, rate?.ApiValue * (decimal)percent); + rows[i] = row with { ValuePerPercent = rate, Unused = row.Running ? null : Value(100 - row.Final.Used), + Gift = row.Early ? Value(100 * row.Skipped.TotalSeconds / length.TotalSeconds) : null }; + } + } + ResetValue TotalValue(IEnumerable source) + { + var values = source.OfType().ToArray(); + return new(values.Sum(v => v.Percent), values.All(v => v.Tokens is not null) ? values.Sum(v => v.Tokens) : null, + values.All(v => v.ApiValue is not null) ? values.Sum(v => v.ApiValue) : null); + } + var totals = new ResetTotals(rows.Count, rows.Count(r => !r.Running), rows.Count(r => r.Early), + rows.Aggregate(new TokenCounts(), (sum, r) => sum + r.Tokens), SumMoney(rows.Select(r => r.ApiValue)), + rows.Sum(r => r.UnpricedTokens), TotalValue(rows.Select(r => r.Unused)), TotalValue(rows.Select(r => r.Gift)), + TimeSpan.FromTicks(rows.Sum(r => r.Skipped.Ticks)), rows.Count(r => r.ReachedLimit is not null), + TimeSpan.FromTicks(rows.Sum(r => r.TimeAtLimit.Ticks))); + return new(window, rows, totals, hours, weekdays, + Median(rows.Where(r => !r.Running).Select(r => (double)r.Duration.Ticks)) is { } ticks ? TimeSpan.FromTicks((long)ticks) : null, firstSample); + } + + private static decimal? SumMoney(IEnumerable values) + { + var known = values.OfType().ToArray(); + return known.Length == 0 ? null : known.Sum(); + } + private static double? Median(IEnumerable source) + { + var sorted = source.Order().ToArray(); var n = sorted.Length; + return n == 0 ? null : (sorted[(n - 1) / 2] + sorted[n / 2]) / 2; + } + private static decimal? MedianMoney(IEnumerable source) + { + var sorted = source.Order().ToArray(); var n = sorted.Length; + return n == 0 ? null : (sorted[(n - 1) / 2] + sorted[n / 2]) / 2; + } +} diff --git a/src/FinalToken.Core/WindowSeries.cs b/src/FinalToken.Core/WindowSeries.cs new file mode 100644 index 0000000..daa85d7 --- /dev/null +++ b/src/FinalToken.Core/WindowSeries.cs @@ -0,0 +1,15 @@ +namespace FinalToken.Core; + +/// D7: Codex slots can change; a limit's name and length identify its series. +public readonly record struct WindowSeries(Provider Provider, string Name, TimeSpan? Length) +{ + public static WindowSeries For(LimitWindow window) + { + var name = window.Id; + if (window.Provider == Provider.Codex) + foreach (var suffix in new[] { ":primary", ":secondary" }) + if (name.EndsWith(suffix, StringComparison.Ordinal)) { name = name[..^suffix.Length]; break; } + return new(window.Provider, name, window.Length); + } + public bool Matches(LimitWindow window) => this == For(window); +} diff --git a/tests/FinalToken.App.Tests/HeadlessTests.cs b/tests/FinalToken.App.Tests/HeadlessTests.cs index b0e0e49..4886556 100644 --- a/tests/FinalToken.App.Tests/HeadlessTests.cs +++ b/tests/FinalToken.App.Tests/HeadlessTests.cs @@ -434,6 +434,7 @@ public sealed class HeadlessTests popupClock.Fire(); Dispatcher.UIThread.RunJobs(); Assert.False(first.IsVisible); Assert.False(second.IsVisible); Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed)); + ResetViews.Verify((window, name) => Save(window, name)); completion.SetResult(); void SaveThemes(Window window, string stem) { diff --git a/tests/FinalToken.App.Tests/ResetTests.cs b/tests/FinalToken.App.Tests/ResetTests.cs new file mode 100644 index 0000000..753a184 --- /dev/null +++ b/tests/FinalToken.App.Tests/ResetTests.cs @@ -0,0 +1,171 @@ +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); + } + + [Theory] + [InlineData("de-DE", "≈ 4,5 limits", "≈ 94,1 %")] + [InlineData("en-US", "≈ 4.5 limits", "≈ 94.1 %")] + public void ResetFiguresFollowTheUsersCultureExceptUsd(string culture, string limits, string percent) + { + var previous = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); + Assert.Equal("≈ $1,234", Display.Money(1234)); Assert.Equal("≈ $99.25", Display.Money(99.25m)); + Assert.Equal("Unpriced", Display.Money(null)); Assert.Equal(limits, Display.Limits(450)); + Assert.Equal(percent, Display.ResetPercent(94.1, UseOrigin.Estimated)); + Assert.Equal(percent[2..], Display.ResetPercent(94.1, UseOrigin.Measured)); + } + finally { CultureInfo.CurrentCulture = previous; } + } + + [Fact] public void ResetDurationsCannotWrapInsideTheFigure() + { + Assert.Equal("0\u00a0min", Display.ResetDuration(TimeSpan.Zero)); + Assert.Equal("39\u00a0d\u00a00\u00a0h", Display.ResetDuration(TimeSpan.FromDays(39))); + Assert.Equal("≈\u00a015,1\u00a0M\u00a0tokens", Display.ResetFigure("≈ 15,1 M tokens")); + } + + [Fact] public void OverlappingSkippedSpansGetSeparateLanesInTimeOrder() + { + var fixture = ResetFixture.Overlapping(); + var history = fixture.History.Resets[0]; + var layout = ResetTimeline.CalculateLayout(history, fixture.Now); + Assert.Equal(5, history.Totals.Early); + Assert.True(history.Instances.Max(r => r.Start) - history.Instances.Min(r => r.Start) < TimeSpan.FromDays(10)); + Assert.Equal(5, layout.LaneCount); + Assert.Equal([0, 1, 2, 3, 4], layout.Skipped.Select(s => s.Lane)); + Assert.Equal(history.Instances.Where(r => r.Early).OrderBy(r => r.End), layout.Skipped.Select(s => s.Instance)); + } + + [Fact] public void SkippedSpansReuseTheFirstLaneAsSoonAsItIsFree() + { + var fixture = ResetFixture.Create(); + var layout = ResetTimeline.CalculateLayout(fixture.History.Resets[0], fixture.Now); + Assert.Equal(4, layout.LaneCount); + Assert.Equal([0, 1, 0, 1, 2, 3, 0], layout.Skipped.Select(s => s.Lane)); + Assert.Equal(layout.Skipped[2].Instance.Reset, layout.Skipped[^1].Instance.End); + foreach (var lane in layout.Skipped.GroupBy(s => s.Lane)) + { + var rows = lane.Select(s => s.Instance).ToArray(); + for (var i = 1; i < rows.Length; i++) Assert.True(rows[i - 1].Reset <= rows[i].End); + } + } + + [Fact] public void TimelineEndsAtNowOrTheLastEarlyNominalResetAndExcludesTheRunningReset() + { + var running = ResetFixture.RunningOnly(); + var history = running.History.Resets[0]; + var layout = ResetTimeline.CalculateLayout(history, running.Now); + Assert.Equal(history.Instances[0].Start, layout.From); + Assert.Equal(running.Now, layout.To); Assert.Empty(layout.Skipped); + Assert.True(layout.To < history.Instances[0].Reset); + + var early = ResetFixture.Overlapping(); + history = early.History.Resets[0]; + layout = ResetTimeline.CalculateLayout(history, early.Now); + Assert.Equal(history.Instances.Min(r => r.Start), layout.From); + Assert.Equal(history.Instances.Where(r => r.Early).Max(r => r.Reset), layout.To); + Assert.True(layout.To > early.Now); Assert.True(layout.To < history.Instances[0].Reset); + var later = early.Now.AddDays(30); + Assert.Equal(later, ResetTimeline.CalculateLayout(history, later).To); + + var onTime = ResetFixture.OnTimeOnly(); + history = onTime.History.Resets[0]; + history = history with { Instances = history.Instances.Where(r => !r.Running).ToArray() }; + Assert.Equal(onTime.Now, ResetTimeline.CalculateLayout(history, onTime.Now).To); + } + + [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()) + { + 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() + => Create([7, 1, 2, 7, 1, 2, 1, 1, 2]); + public static ResetFixture RunningOnly() => Create([]); + public static ResetFixture OnTimeOnly() => Create([7, 7]); + public static ResetFixture Overlapping() => Create([1, 1, 1, 1, 1]); + public static ResetFixture ManyModels() + { + var fixture = OnTimeOnly(); + var start = fixture.History.Resets[0].Instances[1].Start; + string[] models = ["gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.4-mini"]; + for (var i = 0; i < models.Length; i++) + { + var count = 2_000_123 - i * 200_001; + fixture.Store.Add(new(Provider.Codex, start.AddHours(2), models[i], "Fixture", new(Input: count, Total: count), "extra" + i)); + } + return fixture with { History = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, null, fixture.Now) }; + } + private static ResetFixture Create(int[] durations) + { + var start = new DateTimeOffset(2026, 9, 12, 6, 0, 0, TimeSpan.Zero); + 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)); + } +} diff --git a/tests/FinalToken.App.Tests/ResetViews.cs b/tests/FinalToken.App.Tests/ResetViews.cs new file mode 100644 index 0000000..477963e --- /dev/null +++ b/tests/FinalToken.App.Tests/ResetViews.cs @@ -0,0 +1,214 @@ +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 save) + { + VerifyEveryModelsTokensAndValue(save); + VerifyScenarios(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().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().Single(c => c.Name == "ResetWindowSelector"); + selector.SelectedIndex = 1; + Assert.Contains(panel.GetVisualDescendants().OfType(), 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().Single(c => c.Name == "ResetWindowSelector").SelectedIndex); + panel.GetVisualDescendants().OfType().Single(c => c.Name == "ResetWindowSelector").SelectedIndex = 0; + Dispatcher.UIThread.RunJobs(); + using (panel.CaptureRenderedFrame()) { } + var card = panel.GetVisualDescendants().OfType().First(); + var table = card.GetVisualDescendants().OfType().Single(); + Grid Rows() + { + Dispatcher.UIThread.RunJobs(); + using (panel.CaptureRenderedFrame()) { } + return table.GetVisualDescendants().OfType().Single(g => g.Name == "ResetRows"); + } + void Click(string name) + { + Dispatcher.UIThread.RunJobs(); + using (panel.CaptureRenderedFrame()) { } + table.GetVisualDescendants().OfType