app: show the reset history of each long limit window (#16)
The developer asked for a detailed breakdown of every reset (feedback of 2026-10-18). Limits do not only reset at the end of their week: most Codex weeks in the local history ended early. - Core: a limit's samples form a window series (provider, limit name and length), so the history follows Codex's week across slots (D7). Instance spans are built once. One backward walk gives each instance, real or inferred, the start of the instance after it. The hour that holds a boundary goes to the instance that starts in it, or else to the one that ends in it (#9). A stale sample that would put its instance after a later one is ignored. The reset history lists the real instances with their figures, totals and early-reset hours (D12). API value uses a dated list price table; unknown models stay unpriced (D13). - App: a Resets section per long window with totals, a timeline of burn-ups side by side with skipped time in lanes below, early resets by hour and weekday, and a sortable table (D8). The reset tooltip lists every model with its tokens and API value. Tall tooltips open beside the pointer, and Fluent's 320 px tooltip cap no longer wraps data values. - Docs: D12 and D13 are new; D7 and D8 cover window series, boundary hours and the Resets section. Closes #14 Closes #9
This commit was merged in pull request #16.
This commit is contained in:
@@ -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] `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-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
|
## Archive
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
> Always-loaded. Everything else is on-demand. Update TOC when files change.
|
> Always-loaded. Everything else is on-demand. Update TOC when files change.
|
||||||
|
|
||||||
## Current Focus
|
## 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
|
## Invariants
|
||||||
- No credential is ever read, stored or sent; providers are reached only through their CLIs (D2).
|
- 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).
|
- `snapshot.json` is the only interface between the app and other processes (D9).
|
||||||
|
|
||||||
## Table of Contents
|
## 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.
|
||||||
|
|||||||
+68
-4
@@ -188,12 +188,20 @@ probe.
|
|||||||
is reached stops use, so an estimate that would pass it shows "limit reached (estimated)" at
|
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
|
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
|
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
|
instance's start, whichever comes first (Codex can start a new window early). Tokens are
|
||||||
instances (a session window opens only with the next message) belong to none. A past instance
|
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
|
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
|
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
|
never inferred, since a session starts with whatever message comes next. Past instances are
|
||||||
labelled with their real start and end.
|
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
|
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.
|
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
|
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
|
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
|
[D9](#d9--the-snapshot-file-is-the-apps-only-output-to-other-processes), each saying since
|
||||||
when; charts, one window chart per limit
|
when; charts, one window chart per limit window; the reset history of each long window
|
||||||
window, and the top entries by model and by project, with the rest folded into an expandable
|
([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
|
"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
|
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
|
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.
|
**Why.** R7.
|
||||||
|
|
||||||
**Gives up.** Elgato's double-click `.streamDeckPlugin` installer, which always asks.
|
**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.
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
|
|||||||
## Panel and visual rules
|
## Panel and visual rules
|
||||||
|
|
||||||
- Keep this order: fixed 56 px header; Limits; Week use per day; Tokens (totals, hourly and daily
|
- Keep this order: fixed 56 px header; Limits; Week use per day; Tokens (totals, hourly and daily
|
||||||
charts); Window charts (current-instance burn-up and past peaks); Breakdown by model and project; collapsed Diagnostics, hidden when empty.
|
charts); Window charts (current-instance burn-up and past peaks); Resets (one full-width card per
|
||||||
|
provider); Breakdown by model and project; collapsed Diagnostics, hidden when empty.
|
||||||
Preserve scroll offset on snapshots. Sections have two columns from 1200 px content width;
|
Preserve scroll offset on snapshots. Sections have two columns from 1200 px content width;
|
||||||
limit tiles have three from 1400 px. Cards align at the top and size to their content.
|
limit tiles have three from 1400 px. Cards align at the top and size to their content.
|
||||||
- Follow the OS light/dark theme through `Ui.Theme` and `Ui.NeutralTheme`. Selection never uses
|
- Follow the OS light/dark theme through `Ui.Theme` and `Ui.NeutralTheme`. Selection never uses
|
||||||
@@ -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.
|
have a 2 px surface gap; below 6 px width remove gaps and snap shared edges to physical pixels.
|
||||||
Breakdowns show eight rows plus expandable Other; keep every detail column sortable and right-aligned.
|
Breakdowns show eight rows plus expandable Other; keep every detail column sortable and right-aligned.
|
||||||
- Estimated day bars use provider outlines and 45-degree hatching; measured days stay solid. Align past
|
- Estimated day bars use provider outlines and 45-degree hatching; measured days stay solid. Align past
|
||||||
days by index and burn-ups by elapsed time. Never join different resets on one time axis.
|
days by index and burn-ups by elapsed time. The Resets timeline puts real instances side by side
|
||||||
|
on one time axis without joining their lines; 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.
|
Burn-ups use solid measured and lighter dashed estimated lines, with no point markers.
|
||||||
- Use DataTooltip for every data hover: bold title, two-column label/value grid, exact and compact
|
- Use DataTooltip for every data hover: bold title, two-column label/value grid, exact and compact
|
||||||
counts, optional series swatches. Future days have no cumulative value. Share one date formatter
|
counts, optional series swatches. Future days have no cumulative value. Share one date formatter
|
||||||
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;
|
- Custom segments and checkboxes must show keyboard focus. NeutralCheckBox owns checked state;
|
||||||
templates bind its MarkVisible property and must never register checked handlers.
|
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;
|
Instances start at reset minus length and end at reset or the next start. Keep gaps unassigned;
|
||||||
never infer short windows or overlap a sampled window with an inferred one (D7). Label real dates.
|
never infer short windows or overlap a sampled window with an inferred one (D7). Label real dates.
|
||||||
Page wheel events must never change a selection: WindowSelector bubbles them to the scroll view.
|
Page wheel events must never change a selection: WindowSelector bubbles them to the scroll view.
|
||||||
|
- Resets use the shared detail-table sorting, headers, row placement and expansion. Preserve
|
||||||
|
the selected window, sort and expansion on renders. Money is invariant USD at API list prices;
|
||||||
|
unknown models stay unpriced, and percent-derived values and token estimates carry `≈` (D13).
|
||||||
|
Reset tooltips list every model in Core's token order, with its tokens and API list value.
|
||||||
|
|||||||
@@ -8,12 +8,7 @@ using FinalToken.Core;
|
|||||||
namespace FinalToken.App;
|
namespace FinalToken.App;
|
||||||
|
|
||||||
public enum BreakdownColumn { Name, Total, Share, Input, Output, CacheWrite, CacheRead, Reasoning }
|
public enum BreakdownColumn { Name, Total, Share, Input, Output, CacheWrite, CacheRead, Reasoning }
|
||||||
public sealed class BreakdownState
|
public sealed class BreakdownState() : TableState<BreakdownColumn>(BreakdownColumn.Total);
|
||||||
{
|
|
||||||
public bool Expanded { get; set; }
|
|
||||||
public BreakdownColumn Sort { get; set; } = BreakdownColumn.Total;
|
|
||||||
public bool Descending { get; set; } = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class BreakdownTable : StackPanel
|
public sealed class BreakdownTable : StackPanel
|
||||||
{
|
{
|
||||||
@@ -29,21 +24,21 @@ public sealed class BreakdownTable : StackPanel
|
|||||||
}
|
}
|
||||||
public static IReadOnlyList<BreakdownRow> SortRows(IEnumerable<BreakdownRow> rows, BreakdownColumn column, bool descending)
|
public static IReadOnlyList<BreakdownRow> SortRows(IEnumerable<BreakdownRow> rows, BreakdownColumn column, bool descending)
|
||||||
{
|
{
|
||||||
if (column == BreakdownColumn.Name) return (descending ? rows.OrderByDescending(r => r.Name, StringComparer.OrdinalIgnoreCase) : rows.OrderBy(r => r.Name, StringComparer.OrdinalIgnoreCase)).ToArray();
|
if (column == BreakdownColumn.Name) return DetailTable.Sort(rows, r => r.Name, descending, StringComparer.OrdinalIgnoreCase).ToArray();
|
||||||
double Key(BreakdownRow r) => column switch
|
double Key(BreakdownRow r) => column switch
|
||||||
{
|
{
|
||||||
BreakdownColumn.Total => r.Counts.Total, BreakdownColumn.Share => r.Share, BreakdownColumn.Input => r.Counts.Input,
|
BreakdownColumn.Total => r.Counts.Total, BreakdownColumn.Share => r.Share, BreakdownColumn.Input => r.Counts.Input,
|
||||||
BreakdownColumn.Output => r.Counts.Output, BreakdownColumn.CacheWrite => r.Counts.CacheWrite,
|
BreakdownColumn.Output => r.Counts.Output, BreakdownColumn.CacheWrite => r.Counts.CacheWrite,
|
||||||
BreakdownColumn.CacheRead => r.Counts.CacheRead, _ => r.Counts.ReasoningOutput
|
BreakdownColumn.CacheRead => r.Counts.CacheRead, _ => r.Counts.ReasoningOutput
|
||||||
};
|
};
|
||||||
return (descending ? rows.OrderByDescending(Key) : rows.OrderBy(Key)).ThenBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray();
|
return DetailTable.Sort(rows, Key, descending).ThenBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray();
|
||||||
}
|
}
|
||||||
private void RenderTable()
|
private void RenderTable()
|
||||||
{
|
{
|
||||||
Children.Clear(); var header = new DockPanel();
|
Children.Clear(); var header = new DockPanel();
|
||||||
if (rows.Count > 8)
|
if (rows.Count > 8)
|
||||||
{
|
{
|
||||||
var expand = Ui.Button(state.Expanded ? "Show top 8" : $"Show all {rows.Count}", () => { state.Expanded = !state.Expanded; RenderTable(); });
|
var expand = DetailTable.Expansion(rows.Count, state, RenderTable);
|
||||||
DockPanel.SetDock(expand, Dock.Right); header.Children.Add(expand);
|
DockPanel.SetDock(expand, Dock.Right); header.Children.Add(expand);
|
||||||
}
|
}
|
||||||
header.Children.Add(Ui.Text(title, 15)); Children.Add(header);
|
header.Children.Add(Ui.Text(title, 15)); Children.Add(header);
|
||||||
@@ -61,12 +56,7 @@ public sealed class BreakdownTable : StackPanel
|
|||||||
for (var c = 0; c < (reasoning ? 8 : 7); c++)
|
for (var c = 0; c < (reasoning ? 8 : 7); c++)
|
||||||
{
|
{
|
||||||
var column = (BreakdownColumn)c;
|
var column = (BreakdownColumn)c;
|
||||||
var button = Ui.Button(headers[c] + (state.Sort == column ? state.Descending ? " ↓" : " ↑" : ""), () =>
|
var button = DetailTable.Header(headers[c], column, state, RenderTable, title.Replace(" ", "") + "Sort" + column, c == 0);
|
||||||
{
|
|
||||||
state.Descending = state.Sort != column || !state.Descending; state.Sort = column; RenderTable();
|
|
||||||
});
|
|
||||||
button.Name = title.Replace(" ", "") + "Sort" + column;
|
|
||||||
button.Padding = new Thickness(0, 4); button.HorizontalAlignment = c == 0 ? HorizontalAlignment.Left : HorizontalAlignment.Right;
|
|
||||||
Add(button, 0, c);
|
Add(button, 0, c);
|
||||||
}
|
}
|
||||||
var names = projects ? PanelWindow.ShortProjectNames(visible.Select(r => r.Name).ToArray()) : visible.Select(r => r.Name).ToArray();
|
var names = projects ? PanelWindow.ShortProjectNames(visible.Select(r => r.Name).ToArray()) : visible.Select(r => r.Name).ToArray();
|
||||||
@@ -105,12 +95,11 @@ public sealed class BreakdownTable : StackPanel
|
|||||||
ToolTip.SetTip(value, DataTooltip.Tokens(row.Name, counts)); Add(value, i + 1, c);
|
ToolTip.SetTip(value, DataTooltip.Tokens(row.Name, counts)); Add(value, i + 1, c);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Children.Add(new ScrollViewer { Content = grid, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Disabled });
|
Children.Add(DetailTable.Scroll(grid));
|
||||||
if (rows.Count == 0) Children.Add(Ui.Text("No tokens in this range.", 12, "Muted"));
|
if (rows.Count == 0) Children.Add(Ui.Text("No tokens in this range.", 12, "Muted"));
|
||||||
void Add(Control control, int row, int column)
|
void Add(Control control, int row, int column)
|
||||||
{
|
{
|
||||||
while (grid.RowDefinitions.Count <= row) grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
|
DetailTable.Add(grid, control, row, column);
|
||||||
Grid.SetRow(control, row); Grid.SetColumn(control, column); grid.Children.Add(control);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using Avalonia;
|
using Avalonia;
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Controls.Primitives.PopupPositioning;
|
||||||
using Avalonia.Layout;
|
using Avalonia.Layout;
|
||||||
using Avalonia.Media;
|
using Avalonia.Media;
|
||||||
using FinalToken.Core;
|
using FinalToken.Core;
|
||||||
@@ -9,7 +10,7 @@ namespace FinalToken.App;
|
|||||||
public sealed record TooltipRow(string Label, string Value, IBrush? Swatch = null);
|
public sealed record TooltipRow(string Label, string Value, IBrush? Swatch = null);
|
||||||
|
|
||||||
/// <summary>D8: every data tooltip uses the same title and aligned label/value layout.</summary>
|
/// <summary>D8: every data tooltip uses the same title and aligned label/value layout.</summary>
|
||||||
public sealed class DataTooltip : Border
|
public sealed partial class DataTooltip : Border
|
||||||
{
|
{
|
||||||
public string Title { get; }
|
public string Title { get; }
|
||||||
public IReadOnlyList<TooltipRow> Rows { get; }
|
public IReadOnlyList<TooltipRow> Rows { get; }
|
||||||
@@ -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"));
|
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());
|
return new(day.Start.DateTime.ToString("D"), rows.ToArray());
|
||||||
}
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// Opens a tall tooltip beside the pointer, never over it: a tooltip that covers the pointer takes
|
||||||
|
/// it from <paramref name="control"/>, which then loses the tooltip. Call before other pointer handlers.
|
||||||
|
/// </summary>
|
||||||
|
public static void BesidePointer(Control control)
|
||||||
|
{
|
||||||
|
var pointer = default(Point);
|
||||||
|
control.PointerMoved += (_, e) => pointer = e.GetPosition(control);
|
||||||
|
ToolTip.SetPlacement(control, PlacementMode.Custom);
|
||||||
|
ToolTip.SetCustomPopupPlacementCallback(control, placement =>
|
||||||
|
{
|
||||||
|
// The anchor arrives as the control's bounds in window coordinates. The gap lives in the anchor,
|
||||||
|
// because a flip mirrors anchor and gravity but not the offset.
|
||||||
|
placement.AnchorRectangle = new Rect(placement.AnchorRectangle.TopLeft + pointer - new Point(16, 0), new Size(32, 1));
|
||||||
|
placement.Anchor = PopupAnchor.Right; placement.Gravity = PopupGravity.Right;
|
||||||
|
placement.ConstraintAdjustment = PopupPositionerConstraintAdjustment.FlipX | PopupPositionerConstraintAdjustment.SlideY;
|
||||||
|
});
|
||||||
|
}
|
||||||
public override string ToString() => Title + "\n" + string.Join('\n', Rows.Select(r => r.Label + ": " + r.Value));
|
public override string ToString() => Title + "\n" + string.Join('\n', Rows.Select(r => r.Label + ": " + r.Value));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
using Avalonia;
|
||||||
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Controls.Primitives;
|
||||||
|
using Avalonia.Layout;
|
||||||
|
|
||||||
|
namespace FinalToken.App;
|
||||||
|
|
||||||
|
public class TableState<TColumn>(TColumn sort) where TColumn : struct, Enum
|
||||||
|
{
|
||||||
|
public bool Expanded { get; set; }
|
||||||
|
public TColumn Sort { get; set; } = sort;
|
||||||
|
public bool Descending { get; set; } = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Shared sorting, headers, row placement and expansion for detail tables.</summary>
|
||||||
|
public static class DetailTable
|
||||||
|
{
|
||||||
|
public static IOrderedEnumerable<TRow> Sort<TRow, TKey>(IEnumerable<TRow> rows, Func<TRow, TKey> key,
|
||||||
|
bool descending, IComparer<TKey>? comparer = null) =>
|
||||||
|
descending ? rows.OrderByDescending(key, comparer) : rows.OrderBy(key, comparer);
|
||||||
|
|
||||||
|
public static Button Header<TColumn>(string label, TColumn column, TableState<TColumn> state,
|
||||||
|
Action render, string name, bool first = false) where TColumn : struct, Enum
|
||||||
|
{
|
||||||
|
var button = Ui.Button(label + (state.Sort.Equals(column) ? state.Descending ? " ↓" : " ↑" : ""), () =>
|
||||||
|
{
|
||||||
|
state.Descending = !state.Sort.Equals(column) || !state.Descending; state.Sort = column; render();
|
||||||
|
});
|
||||||
|
button.Name = name; button.Padding = new Thickness(0, 4);
|
||||||
|
button.HorizontalAlignment = first ? HorizontalAlignment.Left : HorizontalAlignment.Right;
|
||||||
|
return button;
|
||||||
|
}
|
||||||
|
public static Button Expansion<TColumn>(int count, TableState<TColumn> state, Action render) where TColumn : struct, Enum =>
|
||||||
|
Ui.Button(state.Expanded ? "Show top 8" : $"Show all {count}", () => { state.Expanded = !state.Expanded; render(); });
|
||||||
|
|
||||||
|
public static void Add(Grid grid, Control control, int row, int column)
|
||||||
|
{
|
||||||
|
while (grid.RowDefinitions.Count <= row) grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
|
||||||
|
Grid.SetRow(control, row); Grid.SetColumn(control, column); grid.Children.Add(control);
|
||||||
|
}
|
||||||
|
public static ScrollViewer Scroll(Grid grid) => new() { Content = grid,
|
||||||
|
HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Disabled };
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ public sealed record HistoryView(IReadOnlyList<ChartValue> Hourly, IReadOnlyList
|
|||||||
IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> Projects)
|
IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> Projects)
|
||||||
{
|
{
|
||||||
public IReadOnlyList<LimitDetail> Details { get; init; } = [];
|
public IReadOnlyList<LimitDetail> Details { get; init; } = [];
|
||||||
|
public IReadOnlyList<ResetHistory> Resets { get; init; } = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
public partial class PanelViewModel : ObservableObject
|
public partial class PanelViewModel : ObservableObject
|
||||||
@@ -50,14 +51,25 @@ public partial class PanelViewModel : ObservableObject
|
|||||||
var hourly = Series(SeriesInterval.Hour);
|
var hourly = Series(SeriesInterval.Hour);
|
||||||
var daily = Series(SeriesInterval.Day);
|
var daily = Series(SeriesInterval.Day);
|
||||||
var details = new List<LimitDetail>();
|
var details = new List<LimitDetail>();
|
||||||
|
var resets = new List<ResetHistory>();
|
||||||
var limits = providers.SelectMany(p => p.Windows.Select(w =>
|
var limits = providers.SelectMany(p => p.Windows.Select(w =>
|
||||||
{
|
{
|
||||||
var samples = store.LimitSamples(p.Provider, w.Window.Id, from, now);
|
var instanceFrom = w.Window.ResetsAt is { } r && w.Window.Length is { } l
|
||||||
var instanceSamples = store.LimitSamples(p.Provider, w.Window.Id,
|
? r - l * 9 - TimeSpan.FromMinutes(15) : now.AddDays(-14);
|
||||||
w.Window.ResetsAt is { } r && w.Window.Length is { } l ? r - l * 9 - TimeSpan.FromMinutes(15) : now.AddDays(-14), now);
|
var resetFrom = from == DateTimeOffset.MinValue ? from : from - (w.Window.Length ?? TimeSpan.Zero) - TimeSpan.FromMinutes(15);
|
||||||
|
var series = store.LimitSamples(w.Window, resetFrom < instanceFrom ? resetFrom : instanceFrom, now);
|
||||||
|
var samples = series.Where(s => s.SampleTime >= from).ToArray();
|
||||||
|
var instanceSamples = series.Where(s => s.SampleTime >= instanceFrom).ToArray();
|
||||||
var tokens = w.Window.ResetsAt is { } tokenReset && w.Window.Length is { } tokenLength
|
var tokens = w.Window.ResetsAt is { } tokenReset && w.Window.Length is { } tokenLength
|
||||||
? store.TokenSeriesByModel(p.Provider, tokenReset - tokenLength * 9 - TimeSpan.FromMinutes(15), now, SeriesInterval.Hour) : [];
|
? store.TokenSeriesByModel(p.Provider, tokenReset - tokenLength * 9 - TimeSpan.FromMinutes(15), now, SeriesInterval.Hour) : [];
|
||||||
var analysis = LimitAnalysis.Analyze(w.Window, instanceSamples, tokens, now);
|
var analysis = LimitAnalysis.Analyze(w.Window, instanceSamples, tokens, now);
|
||||||
|
if (w.Window.Length > TimeSpan.FromDays(1))
|
||||||
|
{
|
||||||
|
var tokenFrom = series.Where(s => s.ResetsAt is not null).Select(s => s.ResetsAt!.Value - s.Length!.Value)
|
||||||
|
.Append(w.Window.ResetsAt is { } resetAt ? resetAt - w.Window.Length.Value : now).Min();
|
||||||
|
resets.Add(LimitAnalysis.Resets(w.Window, series,
|
||||||
|
store.TokenSeriesByModel(p.Provider, tokenFrom, now, SeriesInterval.Hour), from, now));
|
||||||
|
}
|
||||||
details.Add(new(p.Provider, w.Window.Id, LimitAnalysis.Recent(w.Window, instanceSamples, now, w.Pace),
|
details.Add(new(p.Provider, w.Window.Id, LimitAnalysis.Recent(w.Window, instanceSamples, now, w.Pace),
|
||||||
analysis?.Days,
|
analysis?.Days,
|
||||||
instanceSamples.Where(s => LimitAnalysis.SameInstance(s, w.Window)).Select(s => s.SampleTime).DefaultIfEmpty(w.Window.SampleTime).Min()));
|
instanceSamples.Where(s => LimitAnalysis.SameInstance(s, w.Window)).Select(s => s.SampleTime).DefaultIfEmpty(w.Window.SampleTime).Min()));
|
||||||
@@ -71,7 +83,7 @@ public partial class PanelViewModel : ObservableObject
|
|||||||
new(now, p.Provider.ToString(), w.Window.UsedPercent), analysis, w, now);
|
new(now, p.Provider.ToString(), w.Window.UsedPercent), analysis, w, now);
|
||||||
})).ToArray();
|
})).ToArray();
|
||||||
var models = Breakdown(true); var projects = Breakdown(false);
|
var models = Breakdown(true); var projects = Breakdown(false);
|
||||||
return new(hourly, daily, limits, models, projects) { Details = details };
|
return new(hourly, daily, limits, models, projects) { Details = details, Resets = resets };
|
||||||
|
|
||||||
IReadOnlyList<ChartValue> Series(SeriesInterval interval)
|
IReadOnlyList<ChartValue> Series(SeriesInterval interval)
|
||||||
{
|
{
|
||||||
@@ -137,4 +149,12 @@ public static class Display
|
|||||||
public static string Forecast(DateTimeOffset date, PaceState state, TimeProvider? clock = null) =>
|
public static string Forecast(DateTimeOffset date, PaceState state, TimeProvider? clock = null) =>
|
||||||
(state == PaceState.Ahead ? "⚠ " : "At this pace ") + "100 % on " + Projection(date, clock);
|
(state == PaceState.Ahead ? "⚠ " : "At this pace ") + "100 % on " + Projection(date, clock);
|
||||||
public static string State(PaceState state) => state switch { PaceState.OnTrack => "✓ On track", PaceState.Ahead => "▲ Ahead", PaceState.Behind => "▼ Behind", _ => "? Pace unknown" };
|
public static string State(PaceState state) => state switch { PaceState.OnTrack => "✓ On track", PaceState.Ahead => "▲ Ahead", PaceState.Behind => "▼ Behind", _ => "? Pace unknown" };
|
||||||
|
public static string Money(decimal? value) => value is { } dollars
|
||||||
|
? "≈ $" + dollars.ToString(dollars >= 100 ? "N0" : "N2", System.Globalization.CultureInfo.InvariantCulture) : "Unpriced";
|
||||||
|
public static string Limits(double percent) => "≈ " + (percent / 100).ToString("0.0") + " 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));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ public sealed class PanelWindow : Window
|
|||||||
private bool wide;
|
private bool wide;
|
||||||
private int limitColumns;
|
private int limitColumns;
|
||||||
private readonly Dictionary<Provider, string> selectedDailyWindow = [];
|
private readonly Dictionary<Provider, string> selectedDailyWindow = [];
|
||||||
|
private readonly Dictionary<Provider, WindowSeries> selectedResetWindow = [];
|
||||||
|
private readonly Dictionary<WindowSeries, TableState<ResetColumn>> resetTables = [];
|
||||||
private readonly BreakdownState modelBreakdown = new(), projectBreakdown = new();
|
private readonly BreakdownState modelBreakdown = new(), projectBreakdown = new();
|
||||||
|
|
||||||
public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload, TimeProvider? clock = null)
|
public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload, TimeProvider? clock = null)
|
||||||
@@ -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("Measured · dashed: estimated · faint: previous · dotted: forecast", 12, "Muted"), new BurnUpChart(limit with { Now = now }, clock),
|
||||||
Ui.Text("Past instances · peak use", 12, "Muted"), new InstancePeaks(limit.Analysis!.Past, limit.Provider, clock)))), wide));
|
Ui.Text("Past instances · peak use", 12, "Muted"), new InstancePeaks(limit.Analysis!.Past, limit.Provider, clock)))), wide));
|
||||||
}
|
}
|
||||||
|
var resetHistories = h.Resets.Where(r => model.ProviderFilter is null || r.Window.Provider == model.ProviderFilter).ToArray();
|
||||||
|
if (resetHistories.Length > 0)
|
||||||
|
{
|
||||||
|
content.Add(Ui.Text("Resets", 20));
|
||||||
|
foreach (var group in resetHistories.GroupBy(r => r.Window.Provider))
|
||||||
|
{
|
||||||
|
var entries = group.ToArray();
|
||||||
|
var index = Array.FindIndex(entries, r => WindowSeries.For(r.Window) == selectedResetWindow.GetValueOrDefault(group.Key));
|
||||||
|
if (index < 0) index = 0;
|
||||||
|
var title = Ui.Text(group.Key + " · " + entries[index].Window.Label, 15);
|
||||||
|
Control View(ResetHistory history)
|
||||||
|
{
|
||||||
|
var key = WindowSeries.For(history.Window);
|
||||||
|
if (!resetTables.TryGetValue(key, out var state)) resetTables[key] = state = new(ResetColumn.Start);
|
||||||
|
return new ResetCard(history, state, clock);
|
||||||
|
}
|
||||||
|
var view = new Border { Child = View(entries[index]) };
|
||||||
|
var stack = Ui.Stack(title);
|
||||||
|
if (entries.Length > 1)
|
||||||
|
{
|
||||||
|
var selector = new WindowSelector { Name = "ResetWindowSelector", ItemsSource = entries.Select(r => r.Window.Label).ToArray(), SelectedIndex = index };
|
||||||
|
selector.SelectionChanged += (_, _) =>
|
||||||
|
{
|
||||||
|
if (selector.SelectedIndex < 0) return;
|
||||||
|
var history = entries[selector.SelectedIndex]; selectedResetWindow[group.Key] = WindowSeries.For(history.Window);
|
||||||
|
title.Text = group.Key + " · " + history.Window.Label; view.Child = View(history);
|
||||||
|
};
|
||||||
|
stack.Children.Add(selector);
|
||||||
|
}
|
||||||
|
stack.Children.Add(view); content.Add(Ui.Card(stack));
|
||||||
|
}
|
||||||
|
}
|
||||||
content.Add(Ui.Text("Breakdown", 20));
|
content.Add(Ui.Text("Breakdown", 20));
|
||||||
content.Add(Ui.Card(new BreakdownTable("By model", h.Models, false, model.ProviderFilter, modelBreakdown)));
|
content.Add(Ui.Card(new BreakdownTable("By model", h.Models, false, model.ProviderFilter, modelBreakdown)));
|
||||||
content.Add(Ui.Card(new BreakdownTable("By project", h.Projects, true, model.ProviderFilter, projectBreakdown)));
|
content.Add(Ui.Card(new BreakdownTable("By project", h.Projects, true, model.ProviderFilter, projectBreakdown)));
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
using Avalonia;
|
||||||
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Controls.Primitives;
|
||||||
|
using Avalonia.Layout;
|
||||||
|
using FinalToken.Core;
|
||||||
|
|
||||||
|
namespace FinalToken.App;
|
||||||
|
|
||||||
|
public sealed class ResetCard : StackPanel
|
||||||
|
{
|
||||||
|
public ResetCard(ResetHistory history, TableState<ResetColumn> state, TimeProvider clock)
|
||||||
|
{
|
||||||
|
Spacing = 16;
|
||||||
|
var totals = history.Totals;
|
||||||
|
if (totals.Finished == 0)
|
||||||
|
Children.Add(Ui.Text("No reset observed since " + Display.Projection(history.FirstSample, clock), 12, "Muted"));
|
||||||
|
if (history.Instances.Count == 0) return;
|
||||||
|
var stats = new UniformGrid { Columns = 6, Rows = 1 };
|
||||||
|
void Stat(string label, string value, string caption, DataTooltip tooltip, bool available = true)
|
||||||
|
{
|
||||||
|
var tile = Ui.Stack(Ui.Text(label, 12, "Secondary"), Ui.Text(Display.ResetFigure(value), 24, available ? "Ink" : "Muted"), Ui.Text(caption, 12, "Muted"));
|
||||||
|
tile.Margin = new Thickness(0, 0, 12, 0); ToolTip.SetTip(tile, tooltip); stats.Children.Add(tile);
|
||||||
|
}
|
||||||
|
DataTooltip ValueTip(string title, ResetValue value) => new(title, new("Limits", Display.Limits(value.Percent)),
|
||||||
|
new("Percent", $"{value.Percent:N2} %"), new("Estimated tokens", value.Tokens is { } tokens ? "≈ " + tokens.ToString("N0") : "No qualifying instance"),
|
||||||
|
new("Estimated API value", Display.Money(value.ApiValue)), new("Basis", "Own instance ≥ 5 %, else series median"),
|
||||||
|
new("Coverage", "Whole listed instances; hourly boundary tokens"));
|
||||||
|
string ValueCaption(ResetValue value) => (value.Tokens is { } tokens ? Display.ResetFigure("≈ " + Display.Compact(tokens) + " tokens") + " · " : "") + Display.ResetFigure(Display.Money(value.ApiValue));
|
||||||
|
var resetCaption = totals.Finished == 0 ? "none yet" : Display.ResetFigure($"{totals.Early} early");
|
||||||
|
if (history.Instances[0].Running) resetCaption += " · " + Display.ResetFigure("1 running");
|
||||||
|
Stat("Resets", totals.Finished.ToString(), resetCaption, new DataTooltip("Listed instances",
|
||||||
|
new("Total", totals.Instances.ToString()), new("Finished", totals.Finished.ToString()), new("Early", totals.Early.ToString()),
|
||||||
|
new("Running", (totals.Instances - totals.Finished).ToString())));
|
||||||
|
Stat("Tokens", Display.Compact(totals.Tokens.Total), "in listed instances", DataTooltip.Tokens("Reset history tokens", totals.Tokens));
|
||||||
|
Stat("API value", Display.Money(totals.ApiValue), "at API list prices", new DataTooltip("API value at list prices",
|
||||||
|
new("Value", Display.Money(totals.ApiValue)), new("Unpriced tokens", DataTooltip.Count(totals.UnpricedTokens)),
|
||||||
|
new("Prices checked", ApiPrices.CheckedOn.ToString("yyyy-MM-dd"))));
|
||||||
|
Stat("Unused", totals.Finished > 0 ? Display.Limits(totals.Unused.Percent) : "—",
|
||||||
|
totals.Finished > 0 ? ValueCaption(totals.Unused) : "no finished instance",
|
||||||
|
totals.Finished > 0 ? ValueTip("Unused limit · estimated value", totals.Unused) : new DataTooltip("Unused limit", new TooltipRow("Coverage", "No finished instance")), totals.Finished > 0);
|
||||||
|
Stat("Gift", totals.Early > 0 ? Display.Limits(totals.Gift.Percent) : "—",
|
||||||
|
totals.Early > 0 ? ValueCaption(totals.Gift) + " · " + Display.ResetDuration(totals.Skipped) + " skipped" : "no early reset",
|
||||||
|
totals.Early > 0 ? ValueTip("Early-reset gift · estimated value", totals.Gift) : new DataTooltip("Early-reset gift", new TooltipRow("Coverage", "No early reset")), totals.Early > 0);
|
||||||
|
Stat("100 % reached", totals.ReachedLimit + "×", Display.ResetDuration(totals.TimeAtLimit) + " at 100\u00a0%", new DataTooltip("100 % reached",
|
||||||
|
new("Instances", totals.ReachedLimit.ToString()), new("Total time", Display.ResetDuration(totals.TimeAtLimit)),
|
||||||
|
new("Source", history.Instances.Any(r => r.BurnUp.ReachedOrigin == UseOrigin.Estimated) ? "Includes token estimates" : "Measured")));
|
||||||
|
Children.Add(stats);
|
||||||
|
Children.Add(Ui.Text("Measured · dashed: estimated · vertical: reset · hatched bars below: skipped · top band: time at 100 %", 12, "Muted"));
|
||||||
|
Children.Add(new ResetTimeline(history, clock));
|
||||||
|
if (totals.Early == 0) Children.Add(Ui.Text("No early resets in this range", 12, "Muted"));
|
||||||
|
else Children.Add(Ui.Columns([
|
||||||
|
Ui.Stack(Ui.Text("Early resets by hour · local time", 13, "Secondary"), new ResetHistogram(history.EarlyByHour, history.Window.Provider, false)),
|
||||||
|
Ui.Stack(Ui.Text("Early resets by weekday · local time", 13, "Secondary"), new ResetHistogram(history.EarlyByWeekday, history.Window.Provider, true))], true));
|
||||||
|
Children.Add(Ui.Text((history.MedianDuration is { } median ? "Median instance " + Display.ResetDuration(median) : "No finished instance yet") +
|
||||||
|
$" · early resets {totals.Early} of {totals.Finished}", 12, "Secondary"));
|
||||||
|
Children.Add(new ResetTable(history, state, clock));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
using Avalonia;
|
||||||
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Media;
|
||||||
|
using FinalToken.Core;
|
||||||
|
|
||||||
|
namespace FinalToken.App;
|
||||||
|
|
||||||
|
public sealed record ResetSkippedLane(ResetInstance Instance, int Lane);
|
||||||
|
public sealed record ResetTimelineLayout(DateTimeOffset From, DateTimeOffset To, IReadOnlyList<ResetSkippedLane> Skipped)
|
||||||
|
{
|
||||||
|
public int LaneCount => Skipped.Count == 0 ? 0 : Skipped.Max(s => s.Lane) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>D12: real instances share a time axis; their burn-ups are never connected.</summary>
|
||||||
|
public sealed class ResetTimeline(ResetHistory history, TimeProvider clock) : Control
|
||||||
|
{
|
||||||
|
private const double LaneHeight = 10;
|
||||||
|
private readonly ResetTimelineLayout layout = CalculateLayout(history, clock.GetUtcNow());
|
||||||
|
private readonly List<(Rect Bounds, ResetInstance Instance)> hits = [];
|
||||||
|
public static ResetTimelineLayout CalculateLayout(ResetHistory history, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
var from = history.Instances.Select(r => r.Start).DefaultIfEmpty(now).Min();
|
||||||
|
var to = history.Instances.Where(r => r.Early).Select(r => r.Reset).Append(now).Max();
|
||||||
|
if (to <= from) to = from.AddHours(1);
|
||||||
|
var laneEnds = new List<DateTimeOffset>();
|
||||||
|
var skipped = new List<ResetSkippedLane>();
|
||||||
|
foreach (var row in history.Instances.Where(r => r.Early).OrderBy(r => r.End).ThenBy(r => r.Reset))
|
||||||
|
{
|
||||||
|
var lane = laneEnds.FindIndex(end => end <= row.End);
|
||||||
|
if (lane < 0) { lane = laneEnds.Count; laneEnds.Add(row.Reset); }
|
||||||
|
else laneEnds[lane] = row.Reset;
|
||||||
|
skipped.Add(new(row, lane));
|
||||||
|
}
|
||||||
|
return new(from, to, skipped);
|
||||||
|
}
|
||||||
|
protected override void OnInitialized()
|
||||||
|
{
|
||||||
|
base.OnInitialized(); Height = 210 + layout.LaneCount * LaneHeight; ToolTip.SetShowDelay(this, 0); DataTooltip.BesidePointer(this);
|
||||||
|
PointerMoved += (_, e) =>
|
||||||
|
{
|
||||||
|
var point = e.GetPosition(this);
|
||||||
|
var instance = hits.Where(h => h.Bounds.Contains(point)).OrderBy(h => Math.Abs(h.Bounds.Center.X - point.X))
|
||||||
|
.Select(h => h.Instance).FirstOrDefault();
|
||||||
|
ToolTip.SetTip(this, instance is null ? null : DataTooltip.Reset(instance, clock));
|
||||||
|
};
|
||||||
|
}
|
||||||
|
public override void Render(DrawingContext context)
|
||||||
|
{
|
||||||
|
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear();
|
||||||
|
if (history.Instances.Count == 0) return;
|
||||||
|
var dark = Ui.Dark(this); var colour = Ui.ProviderColour(history.Window.Provider, dark); var muted = Ui.Colour("Muted", dark);
|
||||||
|
var laneSpace = layout.LaneCount * LaneHeight;
|
||||||
|
var plot = new Rect(42, 12, Math.Max(1, Bounds.Width - 58), Math.Max(1, Bounds.Height - 48 - laneSpace));
|
||||||
|
var from = layout.From; var to = layout.To;
|
||||||
|
double X(DateTimeOffset time) => plot.Left + (time - from).TotalSeconds / (to - from).TotalSeconds * plot.Width;
|
||||||
|
double Y(double used) => plot.Bottom - used / 100 * plot.Height;
|
||||||
|
foreach (var tick in new[] { 0, 25, 50, 75, 100 })
|
||||||
|
{
|
||||||
|
context.DrawLine(new Pen(Ui.Colour("Grid", dark)), new(plot.Left, Y(tick)), new(plot.Right, Y(tick)));
|
||||||
|
ChartText.Draw(context, tick + "%", new(0, Y(tick) - 7), muted);
|
||||||
|
}
|
||||||
|
using (context.PushClip(plot))
|
||||||
|
{
|
||||||
|
foreach (var row in history.Instances.Reverse())
|
||||||
|
{
|
||||||
|
var hitWidth = Math.Max(8, X(row.End) - X(row.Start));
|
||||||
|
hits.Add((new Rect((X(row.Start) + X(row.End) - hitWidth) / 2, plot.Top, hitWidth, plot.Height), row));
|
||||||
|
if (!row.Running)
|
||||||
|
context.DrawLine(new Pen(Ui.Colour("Axis", dark)), new(X(row.End), plot.Top), new(X(row.End), plot.Bottom));
|
||||||
|
if (row.ReachedLimit is { } reached)
|
||||||
|
{
|
||||||
|
using (context.PushOpacity(.16)) context.DrawRectangle(colour, null,
|
||||||
|
new Rect(X(reached), plot.Top, Math.Max(1, X(row.End) - X(reached)), 7));
|
||||||
|
context.DrawLine(new Pen(colour, 3), new(X(reached), plot.Top + 1), new(X(row.End), plot.Top + 1));
|
||||||
|
}
|
||||||
|
var points = row.BurnUp.Points;
|
||||||
|
for (var i = 1; i < points.Count; i++)
|
||||||
|
{
|
||||||
|
var a = points[i - 1]; var b = points[i];
|
||||||
|
if (i == 1 && a.Time == row.Start && row.BurnUp.Scale is null && b.Origin == UseOrigin.Measured && b.Time > row.Start) continue;
|
||||||
|
var estimated = a.Origin == UseOrigin.Estimated || b.Origin == UseOrigin.Estimated;
|
||||||
|
using (context.PushOpacity(estimated ? .55 : 1))
|
||||||
|
context.DrawLine(new Pen(colour, 2, estimated ? new DashStyle([4, 3], 0) : null), new(X(a.Time), Y(a.Used)), new(X(b.Time), Y(b.Used)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach (var skipped in layout.Skipped)
|
||||||
|
{
|
||||||
|
var row = skipped.Instance;
|
||||||
|
var band = new Rect(X(row.End), plot.Bottom + 4 + skipped.Lane * LaneHeight, Math.Max(0, X(row.Reset) - X(row.End)), 6);
|
||||||
|
var hitWidth = Math.Max(8, band.Width);
|
||||||
|
hits.Add((new Rect(band.Center.X - hitWidth / 2, band.Top - 1, hitWidth, 8), row));
|
||||||
|
using (context.PushClip(band))
|
||||||
|
{
|
||||||
|
using (context.PushOpacity(.08)) context.DrawRectangle(colour, null, band);
|
||||||
|
using (context.PushOpacity(.5))
|
||||||
|
for (var x = band.Left - band.Height; x < band.Right; x += 8)
|
||||||
|
context.DrawLine(new Pen(colour), new(x, band.Bottom), new(x + band.Height, band.Top));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (var i = 0; i < 5; i++)
|
||||||
|
{
|
||||||
|
var time = from.AddTicks((to - from).Ticks * i / 4);
|
||||||
|
ChartText.Draw(context, Display.ResetDate(time, clock), new(Math.Clamp(X(time) - 36, plot.Left, Math.Max(plot.Left, plot.Right - 86)), plot.Bottom + laneSpace + 12), muted);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class ResetHistogram(IReadOnlyList<int> counts, Provider provider, bool weekdays) : Control
|
||||||
|
{
|
||||||
|
private readonly List<(Rect Bounds, int Index)> hits = [];
|
||||||
|
private static readonly string[] Weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
|
||||||
|
protected override void OnInitialized()
|
||||||
|
{
|
||||||
|
base.OnInitialized(); Height = 104; ToolTip.SetShowDelay(this, 0);
|
||||||
|
PointerMoved += (_, e) =>
|
||||||
|
{
|
||||||
|
var hit = hits.Where(h => h.Bounds.Contains(e.GetPosition(this))).Select(h => (int?)h.Index).FirstOrDefault();
|
||||||
|
ToolTip.SetTip(this, hit is { } index ? new DataTooltip(weekdays ? Weekdays[index] : $"{index:00}:00–{index:00}:59 local",
|
||||||
|
new TooltipRow("Early resets", counts[index].ToString())) : null);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
public override void Render(DrawingContext context)
|
||||||
|
{
|
||||||
|
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear();
|
||||||
|
if (counts.Count == 0) return;
|
||||||
|
var dark = Ui.Dark(this); var colour = Ui.ProviderColour(provider, dark); var muted = Ui.Colour("Muted", dark);
|
||||||
|
var plot = new Rect(26, 10, Math.Max(1, Bounds.Width - 34), Math.Max(1, Bounds.Height - 34));
|
||||||
|
var maximum = Math.Max(1, counts.Max()); var width = plot.Width / counts.Count;
|
||||||
|
ChartText.Draw(context, maximum.ToString(), new(0, plot.Top - 6), muted);
|
||||||
|
ChartText.Draw(context, "0", new(8, plot.Bottom - 6), muted);
|
||||||
|
context.DrawLine(new Pen(Ui.Colour("Grid", dark)), plot.TopLeft, plot.TopRight);
|
||||||
|
context.DrawLine(new Pen(Ui.Colour("Axis", dark)), plot.BottomLeft, plot.BottomRight);
|
||||||
|
for (var i = 0; i < counts.Count; i++)
|
||||||
|
{
|
||||||
|
var height = plot.Height * counts[i] / maximum;
|
||||||
|
var left = plot.Left + i * width;
|
||||||
|
var bar = UsageChart.BarBounds(left, plot.Bottom, width, height, TopLevel.GetTopLevel(this)?.RenderScaling ?? 1);
|
||||||
|
if (height > 0) context.DrawRectangle(colour, null, bar);
|
||||||
|
hits.Add((new(left, plot.Top, Math.Max(8, width), plot.Height), i));
|
||||||
|
if (weekdays || i % 3 == 0)
|
||||||
|
ChartText.Draw(context, weekdays ? Weekdays[i] : i.ToString("00"), new(left + width / 2 - (weekdays ? 10 : 6), plot.Bottom + 8), muted, 11);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Layout;
|
||||||
|
using FinalToken.Core;
|
||||||
|
|
||||||
|
namespace FinalToken.App;
|
||||||
|
|
||||||
|
public enum ResetColumn { Start, End, Lasted, Reset, Final, Reached, Tokens, ApiValue, Unused, Gift }
|
||||||
|
|
||||||
|
public sealed class ResetTable : StackPanel
|
||||||
|
{
|
||||||
|
private readonly ResetHistory history;
|
||||||
|
private readonly TableState<ResetColumn> state;
|
||||||
|
private readonly TimeProvider clock;
|
||||||
|
public ResetTable(ResetHistory history, TableState<ResetColumn> state, TimeProvider clock)
|
||||||
|
{
|
||||||
|
this.history = history; this.state = state; this.clock = clock; Spacing = 8;
|
||||||
|
AttachedToVisualTree += (_, _) => RenderTable();
|
||||||
|
}
|
||||||
|
public static IReadOnlyList<ResetInstance> SortRows(IEnumerable<ResetInstance> rows, ResetColumn column, bool descending)
|
||||||
|
{
|
||||||
|
double Key(ResetInstance row) => column switch
|
||||||
|
{
|
||||||
|
ResetColumn.Start => row.Start.UtcTicks, ResetColumn.End => row.End.UtcTicks,
|
||||||
|
ResetColumn.Lasted => row.Duration.Ticks, ResetColumn.Reset => row.Skipped.Ticks,
|
||||||
|
ResetColumn.Final => row.Final.Used, ResetColumn.Reached => row.ReachedLimit?.UtcTicks ?? double.MinValue,
|
||||||
|
ResetColumn.Tokens => row.Tokens.Total, ResetColumn.ApiValue => (double?)row.ApiValue ?? double.MinValue,
|
||||||
|
ResetColumn.Unused => row.Unused?.Percent ?? double.MinValue, _ => row.Gift?.Percent ?? double.MinValue
|
||||||
|
};
|
||||||
|
return DetailTable.Sort(rows, Key, descending).ThenByDescending(r => r.Start).ToArray();
|
||||||
|
}
|
||||||
|
private void RenderTable()
|
||||||
|
{
|
||||||
|
Children.Clear();
|
||||||
|
var heading = new DockPanel();
|
||||||
|
if (history.Instances.Count > 8)
|
||||||
|
{
|
||||||
|
var expand = DetailTable.Expansion(history.Instances.Count, state, RenderTable);
|
||||||
|
expand.Name = "ResetExpand"; DockPanel.SetDock(expand, Dock.Right); heading.Children.Add(expand);
|
||||||
|
}
|
||||||
|
heading.Children.Add(Ui.Text(state.Sort == ResetColumn.Start && state.Descending ? "Instances · newest first" : "Instances", 13, "Secondary")); Children.Add(heading);
|
||||||
|
var grid = new Grid { Name = "ResetRows", ColumnDefinitions = new ColumnDefinitions("100,100,90,150,110,110,80,90,100,100"),
|
||||||
|
ColumnSpacing = 12, RowSpacing = 8, MinWidth = 1138 };
|
||||||
|
string[] headers = ["Start", "End", "Lasted", "Reset", "Final (peak)", "100 % at", "Tokens", "API value", "Unused", "Gift"];
|
||||||
|
for (var c = 0; c < headers.Length; c++)
|
||||||
|
DetailTable.Add(grid, DetailTable.Header(headers[c], (ResetColumn)c, state, RenderTable, "ResetSort" + (ResetColumn)c, c == 0), 0, c);
|
||||||
|
var sorted = SortRows(history.Instances, state.Sort, state.Descending);
|
||||||
|
var visible = state.Expanded ? sorted : sorted.Take(8).ToArray();
|
||||||
|
for (var r = 0; r < visible.Count; r++)
|
||||||
|
{
|
||||||
|
var row = visible[r];
|
||||||
|
string Value(ResetValue? value) => value is null ? "—" : Display.ResetPercent(value.Percent, UseOrigin.Estimated);
|
||||||
|
string[] cells = [Display.ResetDate(row.Start, clock), row.Running ? "Running" : Display.ResetDate(row.End, clock), Display.ResetDuration(row.Duration),
|
||||||
|
row.Running ? "Running" : row.Early ? "Early by " + Display.ResetDuration(row.Skipped) : "On time",
|
||||||
|
Display.ResetPercent(row.Final.Used, row.Final.Origin) + (row.Peak is { } peak ? " (" + Display.ResetPercent(peak, row.PeakOrigin) + ")" : ""),
|
||||||
|
row.ReachedLimit is { } reached ? (row.BurnUp.ReachedOrigin == UseOrigin.Estimated ? "≈ " : "") + Display.ResetDate(reached, clock) : "—",
|
||||||
|
Display.Compact(row.Tokens.Total), Display.Money(row.ApiValue), Value(row.Unused), Value(row.Gift)];
|
||||||
|
for (var c = 0; c < cells.Length; c++)
|
||||||
|
{
|
||||||
|
var text = Ui.TableNumber(cells[c], 12); text.HorizontalAlignment = c == 0 ? HorizontalAlignment.Left : HorizontalAlignment.Right;
|
||||||
|
ToolTip.SetTip(text, DataTooltip.Reset(row, clock)); DataTooltip.BesidePointer(text); DetailTable.Add(grid, text, r + 1, c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Children.Add(DetailTable.Scroll(grid));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
using FinalToken.Core;
|
||||||
|
|
||||||
|
namespace FinalToken.App;
|
||||||
|
|
||||||
|
public sealed partial class DataTooltip
|
||||||
|
{
|
||||||
|
public static DataTooltip Reset(ResetInstance row, TimeProvider clock)
|
||||||
|
{
|
||||||
|
var rows = new List<TooltipRow>
|
||||||
|
{
|
||||||
|
new("Start", Display.Projection(row.Start, clock)),
|
||||||
|
new(row.Running ? "As of" : "End", Display.Projection(row.End, clock)),
|
||||||
|
new("Nominal reset", Display.Projection(row.Reset, clock)),
|
||||||
|
new("Lasted", Display.ResetDuration(row.Duration)),
|
||||||
|
new("Final use", Display.ResetPercent(row.Final.Used, row.Final.Origin)),
|
||||||
|
new("Peak", row.Peak is { } peak ? Display.ResetPercent(peak, row.PeakOrigin) : "Collecting history"),
|
||||||
|
new("100 % reached", row.ReachedLimit is { } reached ?
|
||||||
|
(row.BurnUp.ReachedOrigin == UseOrigin.Estimated ? "≈ " : "") + Display.Projection(reached, clock) : "Not reached"),
|
||||||
|
new("Time at 100 %", Display.ResetDuration(row.TimeAtLimit)),
|
||||||
|
new("Total tokens", Count(row.Tokens.Total)), new("Input", Count(row.Tokens.Input)),
|
||||||
|
new("Cache read", Count(row.Tokens.CacheRead)), new("Cache write", Count(row.Tokens.CacheWrite)),
|
||||||
|
new("Output", Count(row.Tokens.Output)), new("Reasoning (in output)", Count(row.Tokens.ReasoningOutput)),
|
||||||
|
new("API list value", Display.Money(row.ApiValue)), new("Unpriced tokens", Count(row.UnpricedTokens))
|
||||||
|
};
|
||||||
|
if (row.Models.Count > 0) rows.Add(new("Models", row.Models.Count.ToString()));
|
||||||
|
foreach (var model in row.Models)
|
||||||
|
rows.Add(new(model.Model ?? "Unknown model", Count(model.Tokens.Total) + " · " + Display.Money(model.ApiValue)));
|
||||||
|
rows.Add(new("Tokens per percent", row.ValuePerPercent is { } rate ? "≈ " + Display.Compact(rate.Tokens) +
|
||||||
|
" · " + rate.Tokens.ToString("N2") : "No qualifying instance"));
|
||||||
|
rows.Add(new("API value per percent", Display.Money(row.ValuePerPercent?.ApiValue)));
|
||||||
|
rows.Add(new("Value basis", row.ValuePerPercent?.Basis switch
|
||||||
|
{
|
||||||
|
PercentBasis.OwnInstance => "Own instance (final ≥ 5 %)",
|
||||||
|
PercentBasis.SeriesMedian => "Median of qualifying listed instances",
|
||||||
|
_ => "No instance with final ≥ 5 %"
|
||||||
|
}));
|
||||||
|
if (row.Unused is { } unused) AddValue("Unused", unused);
|
||||||
|
if (row.Gift is { } gift) { AddValue("Gift", gift); rows.Add(new("Skipped", Display.ResetDuration(row.Skipped))); }
|
||||||
|
var estimates = new List<string>();
|
||||||
|
if (row.Final.Origin == UseOrigin.Estimated) estimates.Add("final");
|
||||||
|
if (row.PeakOrigin == UseOrigin.Estimated) estimates.Add("peak");
|
||||||
|
if (row.BurnUp.ReachedOrigin == UseOrigin.Estimated) estimates.Add("100 % time");
|
||||||
|
if (row.Unused is not null) estimates.Add("unused value");
|
||||||
|
if (row.Gift is not null) estimates.Add("gift value");
|
||||||
|
rows.Add(new("Estimated figures", estimates.Count == 0 ? "API list value" : string.Join(", ", estimates) + ", API list value"));
|
||||||
|
rows.Add(new("Prices checked", ApiPrices.CheckedOn.ToString("yyyy-MM-dd") + " · hourly boundary tokens"));
|
||||||
|
return new(row.Running ? "Running instance" : row.Early ? "Early reset" : "On-time reset", rows.ToArray());
|
||||||
|
|
||||||
|
void AddValue(string label, ResetValue value) => rows.Add(new(label,
|
||||||
|
Display.ResetPercent(value.Percent, UseOrigin.Estimated) + " · " +
|
||||||
|
(value.Tokens is { } count ? "≈ " + Display.Compact(count) + " tokens · " : "") + Display.Money(value.ApiValue)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -83,6 +83,8 @@ public static class Ui
|
|||||||
window.Styles.Add(checks);
|
window.Styles.Add(checks);
|
||||||
var focusCheck = new Style(s => s.OfType<NeutralCheckBox>().Class(":focus-visible"));
|
var focusCheck = new Style(s => s.OfType<NeutralCheckBox>().Class(":focus-visible"));
|
||||||
focusCheck.Setters.Add(new Setter(TemplatedControl.BorderBrushProperty, new DynamicResourceExtension("Ink"))); window.Styles.Add(focusCheck);
|
focusCheck.Setters.Add(new Setter(TemplatedControl.BorderBrushProperty, new DynamicResourceExtension("Ink"))); window.Styles.Add(focusCheck);
|
||||||
|
// Fluent caps tooltips at 320 px, which wraps the values of a data tooltip below its own width.
|
||||||
|
var tips = new Style(s => s.OfType<ToolTip>()); tips.Setters.Add(new Setter(Layoutable.MaxWidthProperty, 560d)); window.Styles.Add(tips);
|
||||||
}
|
}
|
||||||
// Explicit palettes keep every remaining Fluent control independent of the OS accent.
|
// Explicit palettes keep every remaining Fluent control independent of the OS accent.
|
||||||
public static FluentTheme NeutralTheme()
|
public static FluentTheme NeutralTheme()
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
# Core
|
# 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.
|
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
|
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`.
|
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
|
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.
|
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
|
## Store persistence and scaling
|
||||||
|
|
||||||
- Refresh changes append as one durable, newline-terminated transaction to
|
- Refresh changes append as one durable, newline-terminated transaction to
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
|
||||||
|
namespace FinalToken.Core;
|
||||||
|
|
||||||
|
public sealed record ApiPrice(decimal Input, decimal CacheWrite, decimal CacheRead, decimal Output);
|
||||||
|
|
||||||
|
/// <summary>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.</summary>
|
||||||
|
public static class ApiPrices
|
||||||
|
{
|
||||||
|
public static DateOnly CheckedOn => new(2026, 10, 18);
|
||||||
|
private static readonly Dictionary<string, ApiPrice> 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<string, ApiPrice> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -212,6 +212,14 @@ public sealed class HistoryStore
|
|||||||
.Where(w => w.Provider == provider && w.Id == windowId && w.SampleTime >= from && w.SampleTime < to)
|
.Where(w => w.Provider == provider && w.Id == windowId && w.SampleTime >= from && w.SampleTime < to)
|
||||||
.OrderBy(w => w.SampleTime).ToArray();
|
.OrderBy(w => w.SampleTime).ToArray();
|
||||||
}
|
}
|
||||||
|
public IReadOnlyList<LimitWindow> 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<LimitWindow> LimitSamples(LimitWindow window, DateTimeOffset from, DateTimeOffset to) =>
|
||||||
|
LimitSamples(window.Provider, from, to).Where(WindowSeries.For(window).Matches).ToArray();
|
||||||
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval)
|
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval)
|
||||||
=> TokenSeries(provider, from, to, interval, TimeZoneInfo.Local);
|
=> TokenSeries(provider, from, to, interval, TimeZoneInfo.Local);
|
||||||
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval,
|
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval,
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ public static partial class LimitAnalysis
|
|||||||
{
|
{
|
||||||
/// <summary>D7: minute-rounded probe resets may drift within 15 minutes in either direction.</summary>
|
/// <summary>D7: minute-rounded probe resets may drift within 15 minutes in either direction.</summary>
|
||||||
public static bool SameInstance(LimitWindow first, LimitWindow second) =>
|
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 &&
|
first.ResetsAt is { } firstReset && second.ResetsAt is { } secondReset &&
|
||||||
(firstReset - secondReset).Duration() <= TimeSpan.FromMinutes(15);
|
(firstReset - secondReset).Duration() <= TimeSpan.FromMinutes(15);
|
||||||
|
|
||||||
|
|||||||
@@ -2,18 +2,18 @@ namespace FinalToken.Core;
|
|||||||
|
|
||||||
public static partial class LimitAnalysis
|
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,
|
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 hour = Hour(from < start ? start : from);
|
||||||
var exclusiveEnd = Hour(end);
|
return weighted.Where(p => p.Time >= hour && p.Time < to && p.Time < tokenEnd).Sum(p => p.Weight);
|
||||||
return weighted.Where(p => p.Time >= hour && p.Time < to && p.Time < exclusiveEnd).Sum(p => p.Weight);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// D7: plan from the day baseline; spending within that plan does not take from later days.
|
// 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,
|
private static WindowDays PlanDays(LimitWindow window, LimitInstance current, LimitInstance? previous,
|
||||||
LimitDay? today, IReadOnlyList<LimitWindow> observations, IReadOnlyList<(DateTimeOffset Time, double Weight)> weighted,
|
LimitDay? today, IReadOnlyList<LimitWindow> observations, IReadOnlyList<(DateTimeOffset Time, double Weight)> weighted,
|
||||||
DateTimeOffset now, TimeZoneInfo zone)
|
DateTimeOffset tokenEnd, DateTimeOffset now, TimeZoneInfo zone)
|
||||||
{
|
{
|
||||||
var length = window.Length!.Value;
|
var length = window.Length!.Value;
|
||||||
double? baseline = null; UseOrigin? origin = null;
|
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.
|
// D7: use only completed hours before the first sample; its own hour can still grow.
|
||||||
var sampleHour = Hour(first.SampleTime);
|
var sampleHour = Hour(first.SampleTime);
|
||||||
var baselineEnd = start < sampleHour ? start : sampleHour;
|
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)
|
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;
|
origin = UseOrigin.Estimated;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,59 +24,34 @@ 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;
|
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;
|
zone ??= TimeZoneInfo.Local;
|
||||||
var observations = samples.Append(window).Where(s => s.Provider == window.Provider && s.Id == window.Id &&
|
var spans = RealSpans(window, samples, now);
|
||||||
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 observations = spans.SelectMany(s => s.Samples).ToArray();
|
||||||
var weighted = tokens.Where(p => TokenWeights.Matches(window, p.Model)).GroupBy(p => p.Time)
|
var weighted = WeightedTokens(window, tokens);
|
||||||
.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<List<LimitWindow>> { 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 currentSpan = spans.Single(g => SameInstance(g.Anchor, window));
|
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 currentTokenEnd = TokenEnd(currentSpan.End, null);
|
||||||
var realPast = spans.Where(g => g.Start < currentSpan.Start).OrderByDescending(g => g.Start).ToArray();
|
var current = BuildInstance(window, observations, weighted, currentSpan.Start, currentSpan.End,
|
||||||
|
now < currentSpan.End ? now : currentSpan.End, null, currentTokenEnd, now, zone);
|
||||||
var past = new List<LimitInstance>();
|
var past = new List<LimitInstance>();
|
||||||
var realIndex = 0;
|
foreach (var (span, successorStart) in SpansWithSuccessors(window, spans).Skip(1).Take(8))
|
||||||
var cursor = currentSpan.Start;
|
|
||||||
for (var i = 0; i < 8; i++)
|
|
||||||
{
|
{
|
||||||
var canInfer = length > TimeSpan.FromDays(1);
|
var instance = BuildInstance(span.Anchor, observations, weighted, span.Start, span.End,
|
||||||
if (!canInfer && realIndex == realPast.Length) break;
|
span.End < now ? span.End : now, current.Scale, TokenEnd(span.End, successorStart), now, zone);
|
||||||
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);
|
|
||||||
if (instance.HasData) past.Add(instance);
|
if (instance.HasData) past.Add(instance);
|
||||||
cursor = span.Start;
|
|
||||||
}
|
}
|
||||||
WindowDays? days = null;
|
WindowDays? days = null;
|
||||||
if (length > TimeSpan.FromDays(1))
|
if (length > TimeSpan.FromDays(1))
|
||||||
{
|
{
|
||||||
var today = current.Days.FirstOrDefault(d => d.IsToday);
|
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);
|
return new(current, past, days);
|
||||||
|
|
||||||
LimitInstance Build(LimitWindow anchor, DateTimeOffset start, DateTimeOffset end, DateTimeOffset until,
|
|
||||||
double? fallback)
|
|
||||||
{
|
|
||||||
double Weight(DateTimeOffset from, DateTimeOffset to)
|
|
||||||
{
|
|
||||||
return WeightedTokens(weighted, start, end, from, to);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static LimitInstance BuildInstance(LimitWindow anchor, IReadOnlyList<LimitWindow> 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)
|
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();
|
.GroupBy(s => s.SampleTime).Select(g => g.Last()).OrderBy(s => s.SampleTime).ToArray();
|
||||||
var last = measured.LastOrDefault();
|
var last = measured.LastOrDefault();
|
||||||
@@ -86,7 +61,7 @@ public static partial class LimitAnalysis
|
|||||||
var points = new SortedDictionary<DateTimeOffset, LimitPoint> { [start] = new(start, 0, UseOrigin.Measured) };
|
var points = new SortedDictionary<DateTimeOffset, LimitPoint> { [start] = new(start, 0, UseOrigin.Measured) };
|
||||||
if (scale is { } k)
|
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())
|
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())
|
||||||
{
|
{
|
||||||
var cutoff = time < until ? time : until;
|
var cutoff = time < until ? time : until;
|
||||||
if (cutoff <= start) continue;
|
if (cutoff <= start) continue;
|
||||||
@@ -137,5 +112,4 @@ public static partial class LimitAnalysis
|
|||||||
return new(start, anchor.ResetsAt!.Value, series, daily, scale, peak, reached, end, reachedOrigin);
|
return new(start, anchor.ResetsAt!.Value, series, daily, scale, peak, reached, end, reachedOrigin);
|
||||||
double? Last(DateTimeOffset time) => measured.LastOrDefault(s => s.SampleTime <= time)?.UsedPercent;
|
double? Last(DateTimeOffset time) => measured.LastOrDefault(s => s.SampleTime <= time)?.UsedPercent;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
namespace FinalToken.Core;
|
||||||
|
|
||||||
|
public static partial class LimitAnalysis
|
||||||
|
{
|
||||||
|
private sealed record InstanceSpan(LimitWindow Anchor, IReadOnlyList<LimitWindow> Samples,
|
||||||
|
DateTimeOffset Start, DateTimeOffset End);
|
||||||
|
|
||||||
|
private static InstanceSpan[] RealSpans(LimitWindow window, IEnumerable<LimitWindow> 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<List<LimitWindow>> { 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<InstanceSpan> { 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<InstanceSpan> 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<ModelTokenPoint> 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();
|
||||||
|
}
|
||||||
@@ -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<ResetModel> 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<ResetInstance> Instances, ResetTotals Totals,
|
||||||
|
IReadOnlyList<int> EarlyByHour, IReadOnlyList<int> EarlyByWeekday, TimeSpan? MedianDuration, DateTimeOffset FirstSample);
|
||||||
|
|
||||||
|
public static partial class LimitAnalysis
|
||||||
|
{
|
||||||
|
/// <summary>D12: only observed real instances; values cover whole overlapping instances, not a clipped range.</summary>
|
||||||
|
public static ResetHistory Resets(LimitWindow window, IEnumerable<LimitWindow> samples,
|
||||||
|
IReadOnlyList<ModelTokenPoint> tokens, DateTimeOffset from, DateTimeOffset now, TimeZoneInfo? zone = null)
|
||||||
|
{
|
||||||
|
zone ??= TimeZoneInfo.Local;
|
||||||
|
var rows = new List<ResetInstance>();
|
||||||
|
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<ResetValue?> source)
|
||||||
|
{
|
||||||
|
var values = source.OfType<ResetValue>().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<decimal?> values)
|
||||||
|
{
|
||||||
|
var known = values.OfType<decimal>().ToArray();
|
||||||
|
return known.Length == 0 ? null : known.Sum();
|
||||||
|
}
|
||||||
|
private static double? Median(IEnumerable<double> 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<decimal> source)
|
||||||
|
{
|
||||||
|
var sorted = source.Order().ToArray(); var n = sorted.Length;
|
||||||
|
return n == 0 ? null : (sorted[(n - 1) / 2] + sorted[n / 2]) / 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace FinalToken.Core;
|
||||||
|
|
||||||
|
/// <summary>D7: Codex slots can change; a limit's name and length identify its series.</summary>
|
||||||
|
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);
|
||||||
|
}
|
||||||
@@ -434,6 +434,7 @@ public sealed class HeadlessTests
|
|||||||
popupClock.Fire(); Dispatcher.UIThread.RunJobs();
|
popupClock.Fire(); Dispatcher.UIThread.RunJobs();
|
||||||
Assert.False(first.IsVisible); Assert.False(second.IsVisible);
|
Assert.False(first.IsVisible); Assert.False(second.IsVisible);
|
||||||
Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed));
|
Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed));
|
||||||
|
ResetViews.Verify((window, name) => Save(window, name));
|
||||||
completion.SetResult();
|
completion.SetResult();
|
||||||
void SaveThemes(Window window, string stem)
|
void SaveThemes(Window window, string stem)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -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<ResetColumn>())
|
||||||
|
{
|
||||||
|
var ascending = ResetTable.SortRows(rows, column, false); var descending = ResetTable.SortRows(rows, column, true);
|
||||||
|
Assert.Equal(rows.Count, ascending.Count); Assert.Equal(rows.Count, descending.Count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed record ResetFixture(HistoryStore Store, Snapshot Snapshot, DateTimeOffset Now, HistoryView History)
|
||||||
|
{
|
||||||
|
public static ResetFixture Create()
|
||||||
|
=> 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<Window, string> 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<TextBlock>().Where(t => t.FontSize == 20).Select(t => t.Text).ToArray();
|
||||||
|
Assert.True(Array.IndexOf(headings, "Window charts") < Array.IndexOf(headings, "Resets"));
|
||||||
|
Assert.True(Array.IndexOf(headings, "Resets") < Array.IndexOf(headings, "Breakdown"));
|
||||||
|
var selector = panel.GetVisualDescendants().OfType<ComboBox>().Single(c => c.Name == "ResetWindowSelector");
|
||||||
|
selector.SelectedIndex = 1;
|
||||||
|
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Codex · Week (Bengalfox)");
|
||||||
|
model.Snapshot = model.Snapshot with { MadeAt = fixture.Now.AddMinutes(-1) }; Dispatcher.UIThread.RunJobs();
|
||||||
|
Assert.Equal(1, panel.GetVisualDescendants().OfType<ComboBox>().Single(c => c.Name == "ResetWindowSelector").SelectedIndex);
|
||||||
|
panel.GetVisualDescendants().OfType<ComboBox>().Single(c => c.Name == "ResetWindowSelector").SelectedIndex = 0;
|
||||||
|
Dispatcher.UIThread.RunJobs();
|
||||||
|
using (panel.CaptureRenderedFrame()) { }
|
||||||
|
var card = panel.GetVisualDescendants().OfType<ResetCard>().First();
|
||||||
|
var table = card.GetVisualDescendants().OfType<ResetTable>().Single();
|
||||||
|
Grid Rows()
|
||||||
|
{
|
||||||
|
Dispatcher.UIThread.RunJobs();
|
||||||
|
using (panel.CaptureRenderedFrame()) { }
|
||||||
|
return table.GetVisualDescendants().OfType<Grid>().Single(g => g.Name == "ResetRows");
|
||||||
|
}
|
||||||
|
void Click(string name)
|
||||||
|
{
|
||||||
|
Dispatcher.UIThread.RunJobs();
|
||||||
|
using (panel.CaptureRenderedFrame()) { }
|
||||||
|
table.GetVisualDescendants().OfType<Button>().Single(b => b.Name == name).RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
|
||||||
|
Dispatcher.UIThread.RunJobs();
|
||||||
|
using (panel.CaptureRenderedFrame()) { }
|
||||||
|
}
|
||||||
|
Assert.Equal(9, Rows().RowDefinitions.Count); // Header plus eight rows.
|
||||||
|
var cells = Rows().Children.OfType<TextBlock>().ToArray();
|
||||||
|
Assert.All(cells, text => Assert.IsType<DataTooltip>(ToolTip.GetTip(text)));
|
||||||
|
Assert.Contains(cells, t => t.Text == "Running");
|
||||||
|
Assert.Contains(cells, t => t.Text?.StartsWith("Early by ", StringComparison.Ordinal) == true);
|
||||||
|
Assert.Contains(cells, t => t.Text?.Contains("100 %", StringComparison.Ordinal) == true);
|
||||||
|
Click("ResetSortFinal");
|
||||||
|
Assert.StartsWith("≈ 100 %", Rows().Children.OfType<TextBlock>().Single(t => Grid.GetRow(t) == 1 && Grid.GetColumn(t) == 4).Text);
|
||||||
|
Click("ResetExpand");
|
||||||
|
Assert.Equal(11, Rows().RowDefinitions.Count);
|
||||||
|
Assert.Contains(Rows().Children.OfType<TextBlock>(), t => t.Text == "On time");
|
||||||
|
model.Snapshot = model.Snapshot with { MadeAt = fixture.Now }; Dispatcher.UIThread.RunJobs();
|
||||||
|
table = panel.GetVisualDescendants().OfType<ResetCard>().First().GetVisualDescendants().OfType<ResetTable>().Single();
|
||||||
|
Assert.Equal(11, Rows().RowDefinitions.Count);
|
||||||
|
Assert.Contains(table.GetVisualDescendants().OfType<Button>(), b => b.Content as string == "Final (peak) ↓");
|
||||||
|
Click("ResetExpand");
|
||||||
|
Click("ResetSortStart");
|
||||||
|
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
|
||||||
|
{
|
||||||
|
panel.RequestedThemeVariant = theme; Dispatcher.UIThread.RunJobs();
|
||||||
|
var viewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
|
||||||
|
var heading = panel.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Text == "Resets" && t.FontSize == 20);
|
||||||
|
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
|
||||||
|
save(panel, $"resets-panel-{theme}.png");
|
||||||
|
}
|
||||||
|
panel.Close();
|
||||||
|
|
||||||
|
var history = fixture.History.Resets[0];
|
||||||
|
foreach (var width in new[] { 1280, 1500 })
|
||||||
|
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
|
||||||
|
{
|
||||||
|
var content = new ResetCard(history, new(ResetColumn.Start), clock);
|
||||||
|
var window = new Window { Width = width, Height = 1030, Content = new Border { Padding = new Thickness(24),
|
||||||
|
Child = Ui.Stack(Ui.Text("Resets", 20), Ui.Card(Ui.Stack(Ui.Text("Codex · Week", 15), content))) }, RequestedThemeVariant = theme };
|
||||||
|
Ui.Theme(window); window.Show();
|
||||||
|
save(window, $"resets-{width}-{theme}.png");
|
||||||
|
var timeline = content.GetVisualDescendants().OfType<ResetTimeline>().Single();
|
||||||
|
window.MouseMove(timeline.TranslatePoint(new Point(timeline.Bounds.Width / 2, 80), window)!.Value);
|
||||||
|
Assert.IsType<DataTooltip>(ToolTip.GetTip(timeline));
|
||||||
|
var histogram = content.GetVisualDescendants().OfType<ResetHistogram>().First();
|
||||||
|
window.MouseMove(histogram.TranslatePoint(new Point(40, 40), window)!.Value);
|
||||||
|
Assert.IsType<DataTooltip>(ToolTip.GetTip(histogram));
|
||||||
|
var tableTip = content.GetVisualDescendants().OfType<ResetTable>().Single().GetVisualDescendants().OfType<TextBlock>()
|
||||||
|
.Select(t => ToolTip.GetTip(t)).OfType<DataTooltip>().First();
|
||||||
|
Assert.Contains(tableTip.Rows, r => r.Label == "Unpriced tokens");
|
||||||
|
Assert.Contains(tableTip.Rows, r => r.Label == "Tokens per percent");
|
||||||
|
Assert.Contains(tableTip.Rows, r => r.Label == "Estimated figures");
|
||||||
|
var oldest = history.Instances[^1];
|
||||||
|
Assert.False(oldest.Early); Assert.False(oldest.Running);
|
||||||
|
window.Close();
|
||||||
|
}
|
||||||
|
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
|
||||||
|
{
|
||||||
|
var tip = DataTooltip.Reset(history.Instances[1], clock);
|
||||||
|
var window = new Window { Width = 580, Height = 1120, Content = new Border { Child = tip, Padding = new Thickness(16) }, RequestedThemeVariant = theme };
|
||||||
|
Ui.Theme(window); window.Show(); save(window, $"resets-tooltip-{theme}.png"); window.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void VerifyEveryModelsTokensAndValue(Action<Window, string> save)
|
||||||
|
{
|
||||||
|
var fixture = ResetFixture.ManyModels();
|
||||||
|
var history = fixture.History.Resets[0];
|
||||||
|
var row = history.Instances[1];
|
||||||
|
Assert.False(row.Running); Assert.Equal(9, row.Models.Count);
|
||||||
|
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
|
||||||
|
{
|
||||||
|
var card = new ResetCard(history, new(ResetColumn.Start), new FixedClock(fixture.Now));
|
||||||
|
var window = new Window { Width = 1280, Height = 1030, RequestedThemeVariant = theme,
|
||||||
|
Content = new Border { Padding = new Thickness(24), Child = Ui.Card(Ui.Stack(Ui.Text("Codex · Week", 15), card)) } };
|
||||||
|
Ui.Theme(window); window.Show(); Dispatcher.UIThread.RunJobs();
|
||||||
|
using (window.CaptureRenderedFrame()) { }
|
||||||
|
var cell = card.GetVisualDescendants().OfType<Grid>().Single(g => g.Name == "ResetRows")
|
||||||
|
.Children.OfType<TextBlock>().Single(t => Grid.GetRow(t) == 2 && Grid.GetColumn(t) == 0);
|
||||||
|
var tip = Assert.IsType<DataTooltip>(ToolTip.GetTip(cell));
|
||||||
|
foreach (var model in row.Models)
|
||||||
|
{
|
||||||
|
var detail = Assert.Single(tip.Rows, r => r.Label == model.Model);
|
||||||
|
Assert.Equal(DataTooltip.Count(model.Tokens.Total) + " · " + Display.Money(model.ApiValue), detail.Value);
|
||||||
|
}
|
||||||
|
Assert.Equal(row.Models.Select(m => m.Model), tip.Rows.Where(r => row.Models.Any(m => m.Model == r.Label)).Select(r => r.Label));
|
||||||
|
Assert.DoesNotContain(tip.Rows, r => r.Label == "Other models");
|
||||||
|
var pointer = cell.TranslatePoint(new Point(12, cell.Bounds.Height / 2), window)!.Value;
|
||||||
|
window.MouseMove(pointer); ToolTip.SetIsOpen(cell, true); Dispatcher.UIThread.RunJobs();
|
||||||
|
using (window.CaptureRenderedFrame()) { }
|
||||||
|
Assert.True(ToolTip.GetIsOpen(cell)); Assert.True(tip.Bounds.Width > 320);
|
||||||
|
var bounds = new PixelRect(tip.PointToScreen(default), PixelSize.FromSize(tip.Bounds.Size, 1));
|
||||||
|
Assert.False(bounds.Contains(window.PointToScreen(pointer)));
|
||||||
|
Assert.True(window.Screens.ScreenFromWindow(window)!.WorkingArea.Contains(bounds), $"tooltip {bounds}");
|
||||||
|
save(window, $"resets-many-models-hover-{theme}.png");
|
||||||
|
ToolTip.SetIsOpen(cell, false); window.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void VerifyScenarios(Action<Window, string> save)
|
||||||
|
{
|
||||||
|
foreach (var (name, fixture) in new[] { ("running-only", ResetFixture.RunningOnly()),
|
||||||
|
("on-time", ResetFixture.OnTimeOnly()), ("overlapping", ResetFixture.Overlapping()) })
|
||||||
|
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
|
||||||
|
{
|
||||||
|
var history = fixture.History.Resets[0];
|
||||||
|
var card = new ResetCard(history, new(ResetColumn.Start), new FixedClock(fixture.Now));
|
||||||
|
var window = new Window { Width = 1280, Height = 950, RequestedThemeVariant = theme,
|
||||||
|
Content = new Border { Padding = new Thickness(24), Child = Ui.Card(Ui.Stack(Ui.Text("Codex · Week", 15), card)) } };
|
||||||
|
Ui.Theme(window); window.Show(); Dispatcher.UIThread.RunJobs();
|
||||||
|
using (window.CaptureRenderedFrame()) { }
|
||||||
|
save(window, $"resets-{name}-{theme}.png");
|
||||||
|
TextBlock[] TileBlocks(string label) => card.GetVisualDescendants().OfType<StackPanel>()
|
||||||
|
.Select(s => s.Children.OfType<TextBlock>().ToArray())
|
||||||
|
.Single(blocks => blocks.Length == 3 && blocks[0].Text == label);
|
||||||
|
string[] Tile(string label) => TileBlocks(label).Select(t => t.Text!).ToArray();
|
||||||
|
Assert.Equal(history.Totals.Finished.ToString(), Tile("Resets")[1]);
|
||||||
|
var caption = history.Totals.Finished == 0 ? "none yet" : history.Totals.Early + "\u00a0early";
|
||||||
|
Assert.Equal(caption + " · 1\u00a0running", Tile("Resets")[2]);
|
||||||
|
var texts = card.GetVisualDescendants().OfType<TextBlock>().Select(t => t.Text).ToArray();
|
||||||
|
Assert.Contains("early resets " + history.Totals.Early + " of " + history.Totals.Finished,
|
||||||
|
texts.Single(t => t?.StartsWith("Median instance ", StringComparison.Ordinal) == true || t?.StartsWith("No finished instance yet", StringComparison.Ordinal) == true));
|
||||||
|
if (history.Totals.Finished == 0)
|
||||||
|
{
|
||||||
|
Assert.Equal(["Unused", "—", "no finished instance"], Tile("Unused"));
|
||||||
|
Assert.Equal(Ui.Colour("Muted", theme == ThemeVariant.Dark).ToString(), TileBlocks("Unused")[1].Foreground?.ToString());
|
||||||
|
Assert.Contains(texts, text => text?.StartsWith("No finished instance yet", StringComparison.Ordinal) == true);
|
||||||
|
}
|
||||||
|
if (history.Totals.Early == 0)
|
||||||
|
{
|
||||||
|
Assert.Equal(["Gift", "—", "no early reset"], Tile("Gift"));
|
||||||
|
Assert.Equal(Ui.Colour("Muted", theme == ThemeVariant.Dark).ToString(), TileBlocks("Gift")[1].Foreground?.ToString());
|
||||||
|
Assert.Contains("No early resets in this range", texts);
|
||||||
|
Assert.Empty(card.GetVisualDescendants().OfType<ResetHistogram>());
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Assert.Equal(2, card.GetVisualDescendants().OfType<ResetHistogram>().Count());
|
||||||
|
Assert.Contains(Display.ResetDuration(history.Totals.Skipped) + " skipped", Tile("Gift")[2]);
|
||||||
|
Assert.DoesNotContain("≈ ", Tile("Gift")[2]);
|
||||||
|
var timeline = card.GetVisualDescendants().OfType<ResetTimeline>().Single();
|
||||||
|
var layout = ResetTimeline.CalculateLayout(history, fixture.Now);
|
||||||
|
foreach (var skipped in layout.Skipped)
|
||||||
|
{
|
||||||
|
ToolTip.SetIsOpen(timeline, false);
|
||||||
|
window.MouseMove(new Point(4, 4)); Dispatcher.UIThread.RunJobs();
|
||||||
|
var mid = skipped.Instance.End + skipped.Instance.Skipped / 2;
|
||||||
|
var x = 42 + (mid - layout.From).TotalSeconds / (layout.To - layout.From).TotalSeconds * (timeline.Bounds.Width - 58);
|
||||||
|
var pointer = timeline.TranslatePoint(new Point(x, 181 + skipped.Lane * 10), window)!.Value;
|
||||||
|
window.MouseMove(pointer);
|
||||||
|
Assert.True(ToolTip.GetTip(timeline) is DataTooltip, $"{name} {theme}, lane {skipped.Lane}, timeline {timeline.Bounds}");
|
||||||
|
var tooltip = Assert.IsType<DataTooltip>(ToolTip.GetTip(timeline));
|
||||||
|
// The tall tooltip opens beside the pointer; over it, it would take the pointer from the timeline.
|
||||||
|
Assert.True(ToolTip.GetIsOpen(timeline));
|
||||||
|
Assert.True(tooltip.Bounds.Width > 320, $"tooltip width {tooltip.Bounds.Width}");
|
||||||
|
var tipBounds = new PixelRect(tooltip.PointToScreen(default), PixelSize.FromSize(tooltip.Bounds.Size, 1));
|
||||||
|
Assert.False(tipBounds.Contains(window.PointToScreen(pointer)), $"{name} {theme}, lane {skipped.Lane}, tooltip {tipBounds}, pointer {window.PointToScreen(pointer)}, placement {ToolTip.GetPlacement(timeline)}");
|
||||||
|
if (skipped == layout.Skipped[0] || skipped == layout.Skipped[^1]) save(window, $"resets-{name}-hover-lane{skipped.Lane}-{theme}.png");
|
||||||
|
Assert.Contains(tooltip.Rows, r => r.Label == "End" && r.Value == Display.Projection(skipped.Instance.End, new FixedClock(fixture.Now)));
|
||||||
|
}
|
||||||
|
ToolTip.SetIsOpen(timeline, false);
|
||||||
|
window.MouseMove(timeline.TranslatePoint(new Point(timeline.Bounds.Width - 10, 80), window)!.Value);
|
||||||
|
Assert.Null(ToolTip.GetTip(timeline));
|
||||||
|
window.MouseMove(new Point(4, 4));
|
||||||
|
}
|
||||||
|
window.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -99,6 +99,17 @@ public sealed class LimitInstanceTests
|
|||||||
AssertNoOverlap(result);
|
AssertNoOverlap(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact] public void AdjacentInferredWeeksAssignTheBoundaryHourOnlyToTheStartingWeek()
|
||||||
|
{
|
||||||
|
var start = Day.AddMinutes(13);
|
||||||
|
var current = Window(start, TimeSpan.FromDays(7), start.AddHours(2), 20);
|
||||||
|
var result = Analyze(current, [], [Token(Day, 100), Token(Day.AddDays(-7), 100)], current.SampleTime);
|
||||||
|
var past = Assert.Single(result.Past);
|
||||||
|
Assert.Equal(start.AddDays(-7), past.Start); Assert.Equal(20, past.Peak);
|
||||||
|
Assert.DoesNotContain(result.Past, p => p.Start == start.AddDays(-14));
|
||||||
|
AssertNoOverlap(result);
|
||||||
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(5)]
|
[InlineData(5)]
|
||||||
[InlineData(24)]
|
[InlineData(24)]
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests;
|
||||||
|
|
||||||
|
public sealed class ResetBoundaryTests
|
||||||
|
{
|
||||||
|
private static readonly DateTimeOffset Day = new(2026, 10, 15, 0, 0, 0, TimeSpan.Zero);
|
||||||
|
private static LimitWindow Window(DateTimeOffset start, DateTimeOffset sample, double used) =>
|
||||||
|
new(Provider.Codex, "codex:primary", "Session", used, start.AddHours(5), TimeSpan.FromHours(5), sample, "fixture");
|
||||||
|
|
||||||
|
[Fact] public void ResetHourBeforeAGapBelongsToTheEndingInstance()
|
||||||
|
{
|
||||||
|
var previous = Window(Day.AddHours(10).AddMinutes(13), Day.AddHours(14), 50);
|
||||||
|
var current = Window(Day.AddHours(20), Day.AddHours(21), 10);
|
||||||
|
ModelTokenPoint[] tokens = [new(Day.AddHours(10), "model", new(Input: 100, Total: 100)),
|
||||||
|
new(Day.AddHours(15), "model", new(Input: 50, Total: 50))];
|
||||||
|
var past = Assert.Single(LimitAnalysis.Analyze(current, [previous], tokens, current.SampleTime, TimeZoneInfo.Utc)!.Past);
|
||||||
|
Assert.Equal(75, past.Points.Last().Used);
|
||||||
|
Assert.Equal(UseOrigin.Estimated, past.Points.Last().Origin);
|
||||||
|
Assert.Equal(previous.ResetsAt, past.Points.Last().Time);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact] public void EarlierSampleCannotPutAnInstanceAfterTheCurrentWindow()
|
||||||
|
{
|
||||||
|
var current = Window(Day.AddHours(10), Day.AddHours(12), 10);
|
||||||
|
var stale = Window(Day.AddHours(11), Day.AddHours(11.5), 90);
|
||||||
|
var result = LimitAnalysis.Analyze(current, [stale], [], current.SampleTime, TimeZoneInfo.Utc)!;
|
||||||
|
Assert.Equal(current.ResetsAt, result.Current.End);
|
||||||
|
Assert.Equal(10, result.Current.Peak);
|
||||||
|
Assert.Empty(result.Past);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests;
|
||||||
|
|
||||||
|
public sealed class ResetHistoryTests
|
||||||
|
{
|
||||||
|
private static readonly DateTimeOffset Day = new(2026, 10, 1, 0, 0, 0, TimeSpan.Zero);
|
||||||
|
private static readonly TimeSpan Week = TimeSpan.FromDays(7);
|
||||||
|
private static LimitWindow Window(DateTimeOffset start, double used = 50, double sampleHour = 1) =>
|
||||||
|
new(Provider.Codex, "codex:primary", "Week", used, start + Week, Week, start.AddHours(sampleHour), "fixture");
|
||||||
|
private static ModelTokenPoint Token(DateTimeOffset time, long input = 1_000_000, string model = "gpt-6.1-sol") =>
|
||||||
|
new(time, model, new(Input: input, Total: input));
|
||||||
|
private static ResetHistory History(LimitWindow current, LimitWindow[] samples, ModelTokenPoint[] tokens,
|
||||||
|
DateTimeOffset? from = null, DateTimeOffset? now = null, TimeZoneInfo? zone = null) =>
|
||||||
|
LimitAnalysis.Resets(current, samples, tokens, from ?? DateTimeOffset.MinValue, now ?? current.SampleTime, zone ?? TimeZoneInfo.Utc);
|
||||||
|
|
||||||
|
[Fact] public void SeriesMergesCodexSlotsButSeparatesLengthsNamesAndProviders()
|
||||||
|
{
|
||||||
|
var week = Window(Day);
|
||||||
|
Assert.True(LimitAnalysis.SameInstance(week, week with { Id = "codex:secondary" }));
|
||||||
|
Assert.False(LimitAnalysis.SameInstance(week, week with { Length = TimeSpan.FromHours(5) }));
|
||||||
|
Assert.False(LimitAnalysis.SameInstance(week, week with { Id = "codex_bengalfox:primary" }));
|
||||||
|
Assert.False(LimitAnalysis.SameInstance(week, week with { Provider = Provider.Claude }));
|
||||||
|
var previous = Window(Day - Week, 30) with { Id = "codex:secondary" };
|
||||||
|
var wrong = previous with { Id = week.Id, Length = TimeSpan.FromHours(5), UsedPercent = 99 };
|
||||||
|
var other = previous with { Id = "codex_bengalfox:secondary", UsedPercent = 98 };
|
||||||
|
var analysis = LimitAnalysis.Analyze(week, [previous, wrong, other], [], week.SampleTime, TimeZoneInfo.Utc)!;
|
||||||
|
Assert.Equal(30, Assert.Single(analysis.Past).Peak);
|
||||||
|
Assert.Equal(30, History(week, [previous, wrong, other], []).Instances[1].Final.Used);
|
||||||
|
Assert.Null(LimitAnalysis.Recent(week, [week with { Length = TimeSpan.FromHours(5), UsedPercent = 0, SampleTime = week.SampleTime.AddHours(-4) }], week.SampleTime));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact] public void StoreSeriesQueryKeepsTheOriginalIdQueryWorking()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
var week = Window(Day);
|
||||||
|
var moved = week with { Id = "codex:secondary", SampleTime = week.SampleTime.AddHours(-1) };
|
||||||
|
var shortWindow = week with { Length = TimeSpan.FromHours(5) };
|
||||||
|
store.AddLimits([moved, shortWindow, week]);
|
||||||
|
Assert.Equal(3, store.LimitSamples(Provider.Codex, Day, Day.AddDays(1)).Count);
|
||||||
|
Assert.Equal(2, store.LimitSamples(week, Day, Day.AddDays(1)).Count);
|
||||||
|
Assert.Equal(2, store.LimitSamples(Provider.Codex, week.Id, Day, Day.AddDays(1)).Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("claude-haiku-4-5")]
|
||||||
|
[InlineData("claude-haiku-4-5-20251001")]
|
||||||
|
public void PriceMatchesExactAndDatedModel(string model) => Assert.Equal(1, ApiPrices.Find(Provider.Claude, model)!.Input);
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("codex-auto-review")]
|
||||||
|
[InlineData("gpt-6.1-sol-latest")]
|
||||||
|
[InlineData("gpt-6.1-sol-20261301")]
|
||||||
|
[InlineData("gpt-6.1-sol-20261018-extra")]
|
||||||
|
[InlineData(null)]
|
||||||
|
public void UnknownModelHasNoValue(string? model) => Assert.Null(ApiPrices.Value(Provider.Codex, model, new(Input: 100)));
|
||||||
|
|
||||||
|
[Fact] public void ProviderValuesDoNotDoubleCountTokenSubsets()
|
||||||
|
{
|
||||||
|
var counts = new TokenCounts(1_000_000, 400_000, 200_000, 100_000, 80_000);
|
||||||
|
Assert.Equal(17.6m, ApiPrices.Value(Provider.Claude, "claude-fable-5-1", counts));
|
||||||
|
Assert.Equal(2.24m, ApiPrices.Value(Provider.Codex, "gpt-6.1-sol", counts));
|
||||||
|
Assert.Null(ApiPrices.Find(Provider.Claude, "gpt-6.1-sol"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact] public void OnTimeEarlyAndRunningInstancesHaveOwnValuesAndTotals()
|
||||||
|
{
|
||||||
|
var first = Window(Day, 40);
|
||||||
|
var second = Window(Day + Week, 50);
|
||||||
|
var current = Window(Day.AddDays(9), 20);
|
||||||
|
var history = History(current, [first, second], [Token(Day), Token(second.ResetsAt!.Value - Week), Token(Day.AddDays(9))]);
|
||||||
|
Assert.Equal(3, history.Instances.Count);
|
||||||
|
var running = history.Instances[0]; var early = history.Instances[1]; var onTime = history.Instances[2];
|
||||||
|
Assert.True(running.Running); Assert.Null(running.Unused); Assert.Null(running.Gift);
|
||||||
|
Assert.Equal(TimeSpan.FromHours(1), running.Duration); Assert.Equal(current.SampleTime, running.End);
|
||||||
|
Assert.False(onTime.Early); Assert.Equal(Week, onTime.Duration); Assert.Equal(60, onTime.Unused!.Percent);
|
||||||
|
Assert.True(early.Early); Assert.Equal(TimeSpan.FromDays(2), early.Duration); Assert.Equal(TimeSpan.FromDays(5), early.Skipped);
|
||||||
|
Assert.Equal(100d * 5 / 7, early.Gift!.Percent, 8); Assert.Equal(50, early.Unused!.Percent);
|
||||||
|
Assert.Equal(20_000, early.ValuePerPercent!.Tokens); Assert.Equal(.04m, early.ValuePerPercent.ApiValue);
|
||||||
|
Assert.Equal(PercentBasis.OwnInstance, early.ValuePerPercent.Basis);
|
||||||
|
Assert.Equal(1_000_000, early.Unused.Tokens); Assert.Equal(2m, early.Unused.ApiValue);
|
||||||
|
Assert.Equal(3, history.Totals.Instances); Assert.Equal(2, history.Totals.Finished); Assert.Equal(1, history.Totals.Early);
|
||||||
|
Assert.Equal(3_000_000, history.Totals.Tokens.Total); Assert.Equal(6m, history.Totals.ApiValue);
|
||||||
|
Assert.Equal(110, history.Totals.Unused.Percent); Assert.Equal(TimeSpan.FromDays(4.5), history.MedianDuration);
|
||||||
|
Assert.Equal(TimeSpan.FromDays(5), history.Totals.Skipped);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact] public void RunningInstanceHasNoFinishedDurationOrResetValues()
|
||||||
|
{
|
||||||
|
var history = History(Window(Day), [], []);
|
||||||
|
Assert.True(Assert.Single(history.Instances).Running);
|
||||||
|
Assert.Equal(0, history.Totals.Finished); Assert.Equal(0, history.Totals.Early);
|
||||||
|
Assert.Null(history.MedianDuration);
|
||||||
|
Assert.Null(history.Instances[0].Unused); Assert.Null(history.Instances[0].Gift);
|
||||||
|
Assert.All(history.EarlyByHour, count => Assert.Equal(0, count));
|
||||||
|
Assert.All(history.EarlyByWeekday, count => Assert.Equal(0, count));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact] public void OnTimeFinishedInstancesHaveNoEarlyResetAndExcludeRunningDurationFromMedian()
|
||||||
|
{
|
||||||
|
var history = History(Window(Day + Week * 2), [Window(Day), Window(Day + Week)], []);
|
||||||
|
Assert.Equal(2, history.Totals.Finished); Assert.Equal(0, history.Totals.Early);
|
||||||
|
Assert.Equal(Week, history.MedianDuration);
|
||||||
|
Assert.All(history.Instances.Where(r => !r.Running), row => Assert.NotNull(row.Unused));
|
||||||
|
Assert.All(history.Instances, row => Assert.Null(row.Gift));
|
||||||
|
Assert.All(history.EarlyByHour, count => Assert.Equal(0, count));
|
||||||
|
Assert.All(history.EarlyByWeekday, count => Assert.Equal(0, count));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact] public void LowUseUsesMedianOfQualifyingListedInstances()
|
||||||
|
{
|
||||||
|
var first = Window(Day, 50); var second = Window(Day + Week, 25); var current = Window(Day + Week * 2, 4);
|
||||||
|
var result = History(current, [first, second], [Token(Day), Token(Day + Week), Token(Day + Week * 2)]);
|
||||||
|
var rate = result.Instances[0].ValuePerPercent!;
|
||||||
|
Assert.Equal(30_000, rate.Tokens); Assert.Equal(.06m, rate.ApiValue); Assert.Equal(PercentBasis.SeriesMedian, rate.Basis);
|
||||||
|
var onlyLow = History(current, [first, second], [Token(Day + Week * 2)], from: current.ResetsAt!.Value - Week);
|
||||||
|
Assert.Null(Assert.Single(onlyLow.Instances).ValuePerPercent);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact] public void NoQualifyingInstanceKeepsOnlyUnusedAndGiftPercent()
|
||||||
|
{
|
||||||
|
var old = Window(Day, 4); var current = Window(Day.AddDays(2), 0);
|
||||||
|
var row = History(current, [old], []).Instances[1];
|
||||||
|
Assert.Null(row.ValuePerPercent); Assert.Equal(96, row.Unused!.Percent);
|
||||||
|
Assert.Null(row.Unused.Tokens); Assert.Null(row.Unused.ApiValue); Assert.Null(row.Gift!.Tokens);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact] public void ReachedLimitAndTimeAtLimitReuseTheBurnUpIncludingEstimates()
|
||||||
|
{
|
||||||
|
var old = Window(Day, 50); var current = Window(Day + Week, 20);
|
||||||
|
var tokens = new[] { Token(Day), Token(Day.AddHours(2), 2_000_000), Token(Day + Week) };
|
||||||
|
var row = History(current, [old], tokens).Instances[1];
|
||||||
|
var analysis = LimitAnalysis.Analyze(current, [old], tokens, current.SampleTime, TimeZoneInfo.Utc)!;
|
||||||
|
Assert.Equal(analysis.Past[0].Points, row.BurnUp.Points);
|
||||||
|
Assert.Equal(100, row.Peak); Assert.Equal(100, row.Final.Used); Assert.Equal(UseOrigin.Estimated, row.Final.Origin);
|
||||||
|
Assert.Equal(Day.AddHours(2.5), row.ReachedLimit);
|
||||||
|
Assert.Equal(Week - TimeSpan.FromHours(2.5), row.TimeAtLimit);
|
||||||
|
Assert.Equal(0, row.Unused!.Percent);
|
||||||
|
var measured = History(current, [old with { UsedPercent = 100 }], [Token(Day), Token(Day + Week)]).Instances[1];
|
||||||
|
Assert.Equal(old.SampleTime, measured.ReachedLimit); Assert.Equal(UseOrigin.Measured, measured.BurnUp.ReachedOrigin);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0, false)]
|
||||||
|
[InlineData(20, false)]
|
||||||
|
[InlineData(50, true)]
|
||||||
|
public void RealWeekKeepsItsEndHourOnlyWhenTheInferredSuccessorStartsInALaterHour(int gapMinutes, bool ownsEndHour)
|
||||||
|
{
|
||||||
|
var start = Day.AddMinutes(13);
|
||||||
|
var previous = Window(start);
|
||||||
|
var currentStart = start + Week * 2 + TimeSpan.FromMinutes(gapMinutes);
|
||||||
|
var current = Window(currentStart, 20, 2);
|
||||||
|
ModelTokenPoint[] tokens = [Token(Day, 100), Token(Day + Week, 50), Token(currentStart.AddMinutes(-currentStart.Minute), 100)];
|
||||||
|
var analysis = LimitAnalysis.Analyze(current, [previous], tokens, current.SampleTime, TimeZoneInfo.Utc)!;
|
||||||
|
var past = Assert.Single(analysis.Past, p => p.Start == start);
|
||||||
|
Assert.Equal(ownsEndHour ? 75 : 50, past.Points[^1].Used);
|
||||||
|
var history = History(current, [previous], tokens);
|
||||||
|
var row = Assert.Single(history.Instances, r => r.Start == start);
|
||||||
|
Assert.Equal(past.Points, row.BurnUp.Points);
|
||||||
|
Assert.Equal(ownsEndHour ? 150 : 100, row.Tokens.Total);
|
||||||
|
Assert.Equal(row.Tokens, Assert.Single(row.Models).Tokens);
|
||||||
|
Assert.Equal(previous.ResetsAt, row.End); Assert.False(row.Early);
|
||||||
|
Assert.Equal(2, history.Instances.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact] public void ResetHistoryUsesInferredSuccessorsBeyondTheEightPastChartInstances()
|
||||||
|
{
|
||||||
|
var start = Day.AddMinutes(13);
|
||||||
|
var previous = Window(start);
|
||||||
|
var current = Window(start + Week * 11, 20, 2);
|
||||||
|
ModelTokenPoint[] tokens = [Token(Day, 100), Token(Day + Week, 50), Token(Day + Week * 11, 100)];
|
||||||
|
var row = Assert.Single(History(current, [previous], tokens).Instances, r => r.Start == start);
|
||||||
|
Assert.Equal(100, row.Tokens.Total); Assert.Equal(50, row.Final.Used);
|
||||||
|
Assert.Equal(2, History(current, [previous], tokens).Instances.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact] public void FamilyFilterAndUnpricedModelsAreExplicit()
|
||||||
|
{
|
||||||
|
var current = Window(Day, 20) with { Provider = Provider.Claude, Id = "fable", Label = "Week (Fable)" };
|
||||||
|
var row = Assert.Single(History(current, [], [Token(Day, 100, "claude-fable-5"), Token(Day, 200, "claude-fable-new"),
|
||||||
|
Token(Day, 10_000, "claude-sonnet-5")]).Instances);
|
||||||
|
Assert.Equal(300, row.Tokens.Total); Assert.Equal(200, row.UnpricedTokens); Assert.Equal(.001m, row.ApiValue);
|
||||||
|
Assert.Equal(2, row.Models.Count);
|
||||||
|
var zero = Assert.Single(History(current with { UsedPercent = 0 }, [], [Token(Day, 100, "claude-sonnet-5")]).Instances);
|
||||||
|
Assert.Equal(0, zero.Tokens.Total); Assert.Null(zero.ApiValue); Assert.Null(zero.ValuePerPercent);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact] public void RangeIncludesWholeOverlappingRealInstanceAndLeavesInferredOnesOut()
|
||||||
|
{
|
||||||
|
var old = Window(Day, 30); var current = Window(Day + Week * 2, 20);
|
||||||
|
var result = History(current, [old], [Token(Day), Token(Day + Week), Token(Day + Week * 2)], from: Day.AddDays(3));
|
||||||
|
Assert.Equal(2, result.Instances.Count); Assert.Equal(Day, result.Instances[1].Start);
|
||||||
|
Assert.Equal(1_000_000, result.Instances[1].Tokens.Total);
|
||||||
|
Assert.Single(History(current, [old], [], from: Day + Week).Instances);
|
||||||
|
Assert.Equal(old.SampleTime, result.FirstSample);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact] public void JitterAndInterleavedOldRolloutAfterEarlyResetDoNotCreateAnotherInstance()
|
||||||
|
{
|
||||||
|
var transition = Day.AddHours(10).AddMinutes(48).AddSeconds(56);
|
||||||
|
var old = Window(Day.AddDays(-2), 90);
|
||||||
|
var current = Window(transition, 2);
|
||||||
|
var newFirst = current with { SampleTime = transition, UsedPercent = 0, ResetsAt = current.ResetsAt!.Value.AddSeconds(-11) };
|
||||||
|
var stale = old with { SampleTime = transition.AddSeconds(4), UsedPercent = 98, ResetsAt = old.ResetsAt!.Value.AddSeconds(9) };
|
||||||
|
var jitter = old with { SampleTime = old.SampleTime.AddHours(1), UsedPercent = 95, ResetsAt = old.ResetsAt.Value.AddSeconds(11) };
|
||||||
|
var result = History(current, [old, jitter, newFirst, stale], [Token(Day.AddDays(-2)), Token(Day.AddHours(10))]);
|
||||||
|
Assert.Equal(2, result.Instances.Count); Assert.Equal(95, result.Instances[1].Final.Used);
|
||||||
|
Assert.Equal(transition, result.Instances[1].End); Assert.Equal(1_000_000, result.Instances[0].Tokens.Total);
|
||||||
|
Assert.Equal(jitter.ResetsAt, result.Instances[1].Reset);
|
||||||
|
Assert.Equal(1_000_000, result.Instances[1].Tokens.Total);
|
||||||
|
Assert.DoesNotContain(result.Instances[1].BurnUp.Points, p => p.Used == 98);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact] public void HistogramsUseLocalEndHourAndMondayBasedWeekday()
|
||||||
|
{
|
||||||
|
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture +03", TimeSpan.FromHours(3), "Fixture", "Fixture");
|
||||||
|
var old = Window(Day); var transition = Day.AddDays(1).AddHours(22); // Saturday locally.
|
||||||
|
var result = History(Window(transition), [old], [], zone: zone);
|
||||||
|
Assert.Equal(1, result.EarlyByHour[1]); Assert.Equal(1, result.EarlyByHour.Sum());
|
||||||
|
Assert.Equal(1, result.EarlyByWeekday[5]); Assert.Equal(1, result.EarlyByWeekday.Sum());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(15, false)]
|
||||||
|
[InlineData(16, true)]
|
||||||
|
public void EarlyThresholdIsStrictlyMoreThanFifteenMinutes(int minutes, bool early)
|
||||||
|
{
|
||||||
|
var old = Window(Day); var next = Window(Day + Week - TimeSpan.FromMinutes(minutes));
|
||||||
|
Assert.Equal(early, History(next, [old], []).Instances[1].Early);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user