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

Redesign the stats panel after the developer's feedback on v1 and add
limit forecasts, daily week use and token-based estimates (D7, D8).

- Panel: a fixed header with range and provider controls, limit tiles
  with pace chips, meters and forecasts, week use per day, token KPIs
  and charts, one burn-up chart per limit window with past instances,
  and a sortable breakdown whose "Other" row expands. One tooltip
  component for every chart, tile and table.
- Core (D7): average and recent-rate forecasts, the reach date whenever
  use is over pace, days of a long window with even pace and daily
  budget, window instances derived from resets with a 15-minute
  tolerance, and estimates from price-weighted tokens where samples are
  missing. Forecasts start at 10 % of a window, or as soon as it is
  ahead, so a Codex week far ahead right after its reset warns too.
- Settings, popups and the version (1.1.0) follow the new design.

Closes #5
Closes #7
This commit was merged in pull request #6.
This commit is contained in:
2026-10-15 19:06:04 +02:00
parent f8afd11679
commit adb8f5b88d
31 changed files with 2461 additions and 246 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<Version>1.0.1</Version> <Version>1.1.0</Version>
<TargetFramework>net10.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<LangVersion>14</LangVersion> <LangVersion>14</LangVersion>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
+63 -5
View File
@@ -149,15 +149,62 @@ probe.
- expected use `100·e`, pace delta `d = u − 100·e` in percentage points - expected use `100·e`, pace delta `d = u − 100·e` in percentage points
- **ahead** when `d ≥ +threshold`; **behind** when `d ≤ −threshold` and `e ≥ 0.5`; **on track** - **ahead** when `d ≥ +threshold`; **behind** when `d ≤ −threshold` and `e ≥ 0.5`; **on track**
otherwise. The threshold defaults to 10 points and is a setting. otherwise. The threshold defaults to 10 points and is a setting.
- when ahead, the projected time of reaching 100 % at the average rate so far, - **Forecasts.** At the average rate so far, the use at reset is `u / e` (for `e > 0`). Whenever
`t + (100 − u) · e·W / u`, shown only if it comes before `r`. that passes 100 % (that is, `d > 0`, whatever the threshold), the time of reaching 100 %,
`t + (100 − u) · e·W / u`, is shown; it always comes before `r`. A second forecast uses the
recent rate: the rise of `u` over the window's samples from the last 24 h, when they span at
least 3 h. It is shown beside the average forecast, never instead of it. Forecasts start once
10 % of the window has passed (30 min of a session, about 17 h of a week), or as soon as the
window is ahead. Before either, one hour at 1 % already "reaches" 100 % within days, which is
noise. Until forecasts start, the tile and the window chart say when they will.
- **Window instance.** The samples of one window whose reset times lie within 15 minutes of each
other. Claude reports resets to the minute and drifts by a minute between probes ("8pm", then
"7:59pm"), so exact equality would split one week. A reset starts a new instance at 0 %.
- **Days of a long window.** For a window longer than a day: today's use is `u` now minus `u` at
the local start of today (the last sample of the same instance at or before it, or 0 when the
instance began today). The use of each local day of the instance is computed the same way.
The even pace per day is `100 · 1 d / W`. The daily budget is `(100 − u)` divided by the days
left until `r`. A 7-day instance that resets at another time than midnight touches 8 local
dates; the first and the last are partial days and both are shown.
- **Estimates from tokens.** Where samples do not cover a span, its use is estimated from the
token history. Tokens are weighted by the provider's API price ratios: Claude input 1,
output 5, cache write 1.25, cache read 0.1; Codex uncached input 1, cached input 0.1,
output 8. A window whose label names a model family ("Fable") counts only that family's
models; any other window counts all of the provider's models. Because an instance starts at
0 %, the scale `k = u / (weighted tokens from the instance start to the sample)` turns weighted
tokens into percent of the limit; the newest sample gives `k`. A day, or a stretch of the
window chart, then uses samples where they exist at both ends, and `k` × its weighted tokens
where they do not. A finished instance uses its own last sample for `k` when it has one, else
the current `k`. Estimates are always marked as estimates and never exceed 100 %: a limit that
is reached stops use, so an estimate that would pass it shows "limit reached (estimated)" at
the time it crosses. No tokens in the instance means no estimate. Instance boundaries come from
resets: an instance starts at its reset minus its length, and ends at its reset or at the next
instance's start, whichever comes first (Codex can start a new window early). Spans between
instances (a session window opens only with the next message) belong to none. A past instance
with samples is always the real one; an instance is only inferred where no samples exist, by
stepping back one window length, and never overlaps a real one. Windows of a day or shorter are
never inferred, since a session starts with whatever message comes next. Past instances are
labelled with their real start and end.
A window without a known length or reset has no pace; FinalToken never guesses one. 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.
**Why.** R5. A straight line from the window's start to its reset is a pace the user can check **Why.** R5. A straight line from the window's start to its reset is a pace the user can check
by hand. by hand. A user over pace by less than the threshold still runs out before the reset, so the
date shows from the first point over pace. The day figures answer "how much of the week did I
use today" and "how much may I use per day from now on" (developer feedback, 2026-10-14).
Measured samples alone left the day chart empty until the app had run for a whole week, while the
token history already covers it; the estimate fills it at once and agrees with the measured use
of the instance by construction (developer feedback, 2026-10-15). A window that is ahead in
its first 10 % is no noise: a Codex week at 39 % ten hours after its reset reaches 100 % within
a day, and that is the warning the user needs (developer feedback, 2026-10-15).
**Gives up.** Weekday and working-hour patterns. **Gives up.** Weekday and working-hour patterns. Forecasts assume a constant rate; early in a
window, a burst that puts it ahead gives a reach date that a quiet hour moves out again.
Measured day figures are only as fine as the samples (D5 keeps one per hour while the value
stands still). Estimates miss use from other devices and from claude.ai or the web, which
counts against the limit but leaves no local tokens; they also miss changes in model mix within
an instance and any weighting the provider applies beyond the price ratios.
## D8 — Desktop app ## D8 — Desktop app
@@ -173,6 +220,17 @@ by hand.
The tray icon offers Open, Refresh now, Settings and Quit. Closing the window keeps the app The tray icon offers Open, Refresh now, Settings and Quit. Closing the window keeps the app
running in the tray. Starting the app opens the stats panel (R4). Start with the OS is an running in the tray. Starting the app opens the stats panel (R4). Start with the OS is an
opt-in setting. opt-in setting.
- **Panel (R4).** It leads with one tile per limit window: used percent, pace, the forecasts of
[D7](#d7--pace) and, for windows longer than a day, today's use and the daily budget. Then
follow the per-day use of the long windows, token totals and charts, one window chart per limit
window, and the top entries by model and by project, with the rest folded into an expandable
"Other". A window chart is a burn-up of one instance from its start to its reset: the used
percent as a line (measured, or estimated before the first sample), the even-pace diagonal
from 0 % to 100 %, the forecast to the reset and the previous instance faintly behind, with no
point markers; under it, the peak each past instance reached. Tooltips are one component: a
title and a label/value grid. Diagnostics are collapsed. Provider colours are fixed (Claude orange, Codex blue, validated for colour vision
deficiency on both themes). Pace states use status colours with an icon and a label, never
colour alone.
- **Popups (R5).** A small borderless, topmost window that does not take focus, at the - **Popups (R5).** A small borderless, topmost window that does not take focus, at the
bottom right of the primary screen's work area. It goes away after 8 s or on a click; a click bottom right of the primary screen's work area. It goes away after 8 s or on a click; a click
opens the stats panel. A popup shows when a window's pace state ([D7](#d7--pace)) changes to opens the stats panel. A popup shows when a window's pace state ([D7](#d7--pace)) changes to
+53
View File
@@ -8,3 +8,56 @@ Daily charts use local calendar boundaries; never assume a day lasts 24 hours.
Stream Deck policy and the real installer come through IPluginInstaller (D11). Stream Deck policy and the real installer come through IPluginInstaller (D11).
UsePlatformDetect selects X11 on Linux in the pinned Avalonia version. Keep XWayland support. UsePlatformDetect selects X11 on Linux in the pinned Avalonia version. Keep XWayland support.
Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
## Panel and visual rules
- Keep this order: fixed 56 px header; Limits; Week use per day; Tokens (totals, hourly and daily
charts); Window charts (current-instance burn-up and past peaks); Breakdown by model and project; collapsed Diagnostics, hidden when empty.
Preserve scroll offset on snapshots. Sections have two columns from 1200 px content width;
limit tiles have three from 1400 px. Cards align at the top and size to their content.
- Follow the OS light/dark theme through `Ui.Theme` and `Ui.NeutralTheme`. Selection never uses
the OS accent. Selected segments use primary ink, semibold and the neutral selection surface;
checkboxes use primary ink on that surface. Keep all other Fluent accent states neutral too.
- Dark/light tokens: page `#0d0d0d`/`#f9f9f7`; surface `#1a1a19`/`#fcfcfb`;
border white/`#0b0b0b` at 10%; primary ink `#f0efec`/`#0b0b0b`;
secondary `#c3c2b7`/`#52514e`; muted `#898781` on both;
grid `#2c2c2a`/`#e1e0d9`; axis `#383835`/`#c3c2b7`;
neutral selection `#383835`/`#e1e0d9`; cache read `#5c5b57`/`#c3c2b7`.
- Claude is always orange `#d95926`/`#eb6834`; Codex always blue `#3987e5`/`#2a78d6`.
Model breakdown dots use the provider identity returned by the query, never a name heuristic.
Filtered model charts sort names into six categorical slots; later names fold into Other.
Slots in order: dark `#3987e5 #d95926 #199e70 #c98500 #d55181 #9085e9`;
light `#2a78d6 #eb6834 #1baf7a #eda100 #e87ba4 #6250d6`. Other is muted.
- Status chips always have icon and label: `#0ca30c` ✓ On track, `#ec835a` ▲ Ahead,
`#fab219` ▼ Behind. Forecasts start at 10% elapsed or as soon as Ahead, using the configured pace (D7);
until then, tiles and window charts show the Core forecast start time. Dates remain visible for every positive pace delta, but
only Ahead gets the critical `#d03b3b` mark and ⚠. Other states say "At this pace 100 % on …"
in secondary ink. Text paragraphs stay in ink colours; colour belongs to marks and meters.
- Spacing is 8/16/24 px; card radius 10, padding 16–20; system sans. Use about 12 px captions,
13 body, 15 card titles, 20 section titles and 32–36 hero numbers. Tabular figures only in
tables and axes. Compact counts use three significant digits; axes omit trailing zeros.
Exact values stay in tooltips.
- Show one composition legend in the Tokens header. Cache reads are neutral; input/output/cache
write use full/65%/40% provider colour. Reasoning is part of output; Codex cache read is part
of input. Never add either subset twice.
- Week charts show dashed muted even pace and thin solid secondary budget, with labels beside
their own right endpoints and separated when close. No known day values means a collecting
message. Use CalendarDays, including partial dates at both ends of a window (D7).
Use `LimitAnalysis.SameInstance` for reset membership, history gaps and previous-window lookup;
resets within 15 minutes belong together, including minute drift in either direction.
- Charts use 2 px lines, hit targets at least 8 px, tooltips and recessive grids. Bars normally
have a 2 px surface gap; below 6 px width remove gaps and snap shared edges to physical pixels.
Breakdowns show eight rows plus expandable Other; keep every detail column sortable and right-aligned.
- Estimated day bars use provider outlines and 45-degree hatching; measured days stay solid. Align past
days by index and burn-ups by elapsed time. Never join different resets on one time axis.
Burn-ups use solid measured and lighter dashed estimated lines, with no point markers.
- Use DataTooltip for every data hover: bold title, two-column label/value grid, exact and compact
counts, optional series swatches. Future days have no cumulative value. Share one date formatter
for resets and forecasts. Recent-rate captions name the actual span.
- Custom segments and checkboxes must show keyboard focus. NeutralCheckBox owns checked state;
templates bind its MarkVisible property and must never register checked handlers.
- Cap token estimates at 100%, retain the estimated crossing time and leave measured samples intact.
Instances start at reset minus length and end at reset or the next start. Keep gaps unassigned;
never infer short windows or overlap a sampled window with an inferred one (D7). Label real dates.
Page wheel events must never change a selection: WindowSelector bubbles them to the scroll view.
+116
View File
@@ -0,0 +1,116 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
using FinalToken.Core;
namespace FinalToken.App;
public enum BreakdownColumn { Name, Total, Share, Input, Output, CacheWrite, CacheRead, Reasoning }
public sealed class BreakdownState
{
public bool Expanded { get; set; }
public BreakdownColumn Sort { get; set; } = BreakdownColumn.Total;
public bool Descending { get; set; } = true;
}
public sealed class BreakdownTable : StackPanel
{
private readonly IReadOnlyList<BreakdownRow> rows;
private readonly BreakdownState state;
private readonly string title;
private readonly bool projects;
private readonly Provider? filter;
public BreakdownTable(string title, IReadOnlyList<BreakdownRow> rows, bool projects, Provider? filter, BreakdownState state)
{
this.title = title; this.rows = rows; this.projects = projects; this.filter = filter; this.state = state; Spacing = 12;
AttachedToVisualTree += (_, _) => RenderTable();
}
public static IReadOnlyList<BreakdownRow> SortRows(IEnumerable<BreakdownRow> rows, BreakdownColumn column, bool descending)
{
if (column == BreakdownColumn.Name) return (descending ? rows.OrderByDescending(r => r.Name, StringComparer.OrdinalIgnoreCase) : rows.OrderBy(r => r.Name, StringComparer.OrdinalIgnoreCase)).ToArray();
double Key(BreakdownRow r) => column switch
{
BreakdownColumn.Total => r.Counts.Total, BreakdownColumn.Share => r.Share, BreakdownColumn.Input => r.Counts.Input,
BreakdownColumn.Output => r.Counts.Output, BreakdownColumn.CacheWrite => r.Counts.CacheWrite,
BreakdownColumn.CacheRead => r.Counts.CacheRead, _ => r.Counts.ReasoningOutput
};
return (descending ? rows.OrderByDescending(Key) : rows.OrderBy(Key)).ThenBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray();
}
private void RenderTable()
{
Children.Clear(); var header = new DockPanel();
if (rows.Count > 8)
{
var expand = Ui.Button(state.Expanded ? "Show top 8" : $"Show all {rows.Count}", () => { state.Expanded = !state.Expanded; RenderTable(); });
DockPanel.SetDock(expand, Dock.Right); header.Children.Add(expand);
}
header.Children.Add(Ui.Text(title, 15)); Children.Add(header);
var sorted = SortRows(rows, state.Sort, state.Descending);
var visible = state.Expanded ? sorted.ToList() : sorted.Take(8).ToList();
if (!state.Expanded && sorted.Count > 8)
{
var tail = sorted.Skip(8).ToArray();
visible.Add(new($"Other ({tail.Length})", tail.Aggregate(new TokenCounts(), (sum, row) => sum + row.Counts), tail.Sum(r => r.Share), tail.SelectMany(r => r.Providers ?? []).Distinct().Order().ToArray()));
}
var reasoning = rows.Any(r => r.Providers?.Contains(Provider.Codex) == true || r.Counts.ReasoningOutput > 0);
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions(reasoning ? "*,90,130,90,90,90,90,90" : "*,90,130,90,90,90,90"),
ColumnSpacing = 12, RowSpacing = 6, MinWidth = reasoning ? 1060 : 960 };
var headers = new[] { "Name", "Total", "Share", "Input", "Output", "Cache write", "Cache read", "Reasoning" };
for (var c = 0; c < (reasoning ? 8 : 7); c++)
{
var column = (BreakdownColumn)c;
var button = Ui.Button(headers[c] + (state.Sort == column ? state.Descending ? " ↓" : " ↑" : ""), () =>
{
state.Descending = state.Sort != column || !state.Descending; state.Sort = column; RenderTable();
});
button.Name = title.Replace(" ", "") + "Sort" + column;
button.Padding = new Thickness(0, 4); button.HorizontalAlignment = c == 0 ? HorizontalAlignment.Left : HorizontalAlignment.Right;
Add(button, 0, c);
}
var names = projects ? PanelWindow.ShortProjectNames(visible.Select(r => r.Name).ToArray()) : visible.Select(r => r.Name).ToArray();
for (var i = 0; i < visible.Count; i++)
{
var row = visible[i]; var tooltip = DataTooltip.Tokens(row.Name, row.Counts);
Control name;
if (!state.Expanded && i == 8 && sorted.Count > 8)
name = Ui.Button(row.Name + " ▸", () => { state.Expanded = true; RenderTable(); });
else
{
var label = Ui.Text(names[i]); label.TextWrapping = TextWrapping.NoWrap; label.TextTrimming = TextTrimming.CharacterEllipsis;
var cell = new DockPanel();
if (!projects && filter is null)
foreach (var provider in row.Providers ?? [])
{
var dot = Ui.Mark("●", Ui.ProviderColour(provider, Ui.Dark(this))); dot.Margin = new Thickness(0, 0, 6, 0);
DockPanel.SetDock(dot, Dock.Left); cell.Children.Add(dot);
}
cell.Children.Add(label); name = cell;
}
ToolTip.SetTip(name, tooltip); Add(name, i + 1, 0);
var counts = row.Counts;
long[] numbers = [counts.Total, 0, counts.Input, counts.Output, counts.CacheWrite, counts.CacheRead, counts.ReasoningOutput];
for (var c = 1; c < (reasoning ? 8 : 7); c++)
{
Control value;
if (c == 2)
{
var share = new Grid { ColumnDefinitions = new ColumnDefinitions("*,48"), ColumnSpacing = 6 };
share.Children.Add(new ProgressBar { Value = row.Share, Maximum = 1, Width = 70, MinWidth = 0, Height = 4, VerticalAlignment = VerticalAlignment.Center,
Foreground = filter is { } p ? Ui.ProviderColour(p, Ui.Dark(this)) : Ui.Colour("Muted", Ui.Dark(this)) });
var percent = Ui.TableNumber(row.Share.ToString("P1"), 12); percent.HorizontalAlignment = HorizontalAlignment.Right; Grid.SetColumn(percent, 1); share.Children.Add(percent); value = share;
}
else { var text = Ui.TableNumber(Display.Compact(numbers[c - 1]), 12); text.HorizontalAlignment = HorizontalAlignment.Right; value = text; }
ToolTip.SetTip(value, DataTooltip.Tokens(row.Name, counts)); Add(value, i + 1, c);
}
}
Children.Add(new ScrollViewer { Content = grid, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Disabled });
if (rows.Count == 0) Children.Add(Ui.Text("No tokens in this range.", 12, "Muted"));
void Add(Control control, int row, int column)
{
while (grid.RowDefinitions.Count <= row) grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
Grid.SetRow(control, row); Grid.SetColumn(control, column); grid.Children.Add(control);
}
}
}
+147
View File
@@ -0,0 +1,147 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using FinalToken.Core;
namespace FinalToken.App;
public sealed class BurnUpChart(LimitChart chart) : Decorator
{
private Rect plot;
private double? crosshair;
public BurnUpChart() : this(new("", [])) { }
protected override void OnInitialized()
{
base.OnInitialized(); Height = 240; ToolTip.SetShowDelay(this, 0);
if (chart.Window is { } snapshot && Display.ForecastWaiting(snapshot, chart.Now) is { } waiting)
Child = new TextBlock { Text = waiting, FontSize = 12, Foreground = Ui.Colour("Muted", Ui.Dark(this)),
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center,
VerticalAlignment = Avalonia.Layout.VerticalAlignment.Top, Margin = new Thickness(42, 40, 16, 0) };
PointerMoved += (_, e) =>
{
if (chart.Analysis is not { } analysis || !plot.Contains(e.GetPosition(this))) return;
crosshair = Math.Clamp(e.GetPosition(this).X, plot.Left, plot.Right);
var time = analysis.Current.Start.AddTicks((long)((analysis.Current.Reset - analysis.Current.Start).Ticks * (crosshair.Value - plot.Left) / plot.Width));
var current = analysis.Current;
var before = current.Points.LastOrDefault(p => p.Time <= time);
var after = current.Points.FirstOrDefault(p => p.Time >= time);
double? used = before?.Used;
var source = before?.Origin == UseOrigin.Estimated ? "Estimated from tokens" : "Measured";
if (time > chart.Now)
{
if (current.ReachedOrigin == UseOrigin.Estimated)
{ used = 100; source = "Limit reached (estimated)"; }
else if (chart.Window is { } window && LimitAnalysis.AverageUseAtReset(window.Window, chart.Now, window.Pace) is { } forecast)
{
used = window.Window.UsedPercent + (forecast - window.Window.UsedPercent) * (time - chart.Now).TotalSeconds / (current.Reset - chart.Now).TotalSeconds;
source = "Average forecast";
}
else used = null;
}
else if (before is not null && after is not null && after.Time > before.Time)
{
if (before.Time == current.Start && current.Scale is null && after.Time > current.Start) used = null;
else used = before.Used + (after.Used - before.Used) * (time - before.Time).TotalSeconds / (after.Time - before.Time).TotalSeconds;
if (before.Origin == UseOrigin.Estimated || after.Origin == UseOrigin.Estimated) source = "Estimated from tokens";
}
var expected = 100 * (time - current.Start).TotalSeconds / (current.Reset - current.Start).TotalSeconds;
ToolTip.SetTip(this, new DataTooltip(Display.Projection(time), new("Used", used is { } use ? $"{use:0.##} %" : "Collecting history", Ui.ProviderColour(chart.Provider, Ui.Dark(this))),
new("Expected", $"{expected:0.##} %"), new("Delta", used is { } value ? $"{value - expected:+0.##;-0.##;0} points" : "Unknown"),
new("Source", used is null ? "No baseline" : source)));
InvalidateVisual();
};
PointerExited += (_, _) => { crosshair = null; InvalidateVisual(); };
}
public override void Render(DrawingContext context)
{
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size));
if (chart.Analysis is not { } data || chart.Window is not { } snapshot) return;
var instance = data.Current; var dark = Ui.Dark(this); var muted = Ui.Colour("Muted", dark); var colour = Ui.ProviderColour(chart.Provider, dark);
plot = new Rect(42, 22, Math.Max(1, Bounds.Width - 58), Math.Max(1, Bounds.Height - 60));
var duration = (instance.Reset - instance.Start).TotalSeconds;
double X(DateTimeOffset time) => plot.Left + (time - instance.Start).TotalSeconds / duration * plot.Width;
double Y(double use) => plot.Bottom - use / 100 * plot.Height;
foreach (var tick in new[] { 0, 25, 50, 75, 100 })
{
context.DrawLine(new Pen(Ui.Colour("Grid", dark)), new(plot.Left, Y(tick)), new(plot.Right, Y(tick)));
ChartText.Draw(context, tick + "%", new(0, Y(tick) - 7), muted);
}
context.DrawLine(new Pen(muted, 1), new(plot.Left, plot.Bottom), new(plot.Right, plot.Top));
using (context.PushClip(plot))
{
if (data.Previous is { } previous)
using (context.PushOpacity(.2)) DrawSeries(previous, true);
DrawSeries(instance, false);
if (instance.ReachedLimit is null && LimitAnalysis.AverageUseAtReset(snapshot.Window, chart.Now, snapshot.Pace) is { } average && instance.Reset > chart.Now)
context.DrawLine(new Pen(colour, 2, new DashStyle([1, 3], 0)), new(X(chart.Now), Y(snapshot.Window.UsedPercent)), new(plot.Right, Y(average)));
var nowX = X(chart.Now);
if (nowX >= plot.Left && nowX <= plot.Right) context.DrawLine(new Pen(muted, 1, new DashStyle([3, 3], 0)), new(nowX, plot.Top), new(nowX, plot.Bottom));
if (crosshair is { } x) context.DrawLine(new Pen(Ui.Colour("Secondary", dark), 1), new(x, plot.Top), new(x, plot.Bottom));
}
if (instance.ReachedLimit is null && snapshot.Pace.Projection is { } crossing && crossing <= instance.Reset && crossing >= chart.Now)
{
var x = X(crossing); var mark = snapshot.Pace.State == PaceState.Ahead ? Brush.Parse("#d03b3b") : colour;
context.DrawLine(new Pen(mark, 2), new(x, plot.Top - 5), new(x, plot.Top + 5));
ChartText.Draw(context, "100 % " + Display.Projection(crossing), new(Math.Clamp(x - 80, plot.Left, Math.Max(plot.Left, plot.Right - 175)), 0), Ui.Colour("Secondary", dark));
}
if (instance.ReachedLimit is { } reached && instance.ReachedOrigin == UseOrigin.Estimated)
{
var labelX = Math.Clamp(X(reached) - 80, plot.Left, Math.Max(plot.Left, plot.Right - 260));
context.DrawLine(new Pen(colour, 2), new(X(reached), plot.Top - 5), new(X(reached), plot.Top + 5));
ChartText.Draw(context, "Limit reached (estimated) " + Display.Projection(reached), new(labelX, 0), Ui.Colour("Secondary", dark));
}
ChartText.Draw(context, Display.Projection(instance.Start), new(plot.Left, plot.Bottom + 12), muted);
ChartText.Draw(context, Display.Projection(instance.Reset), new(Math.Max(plot.Left, plot.Right - 120), plot.Bottom + 12), muted);
var tickX = X(chart.Now);
if (tickX > plot.Left + 160 && tickX < plot.Right - 160) ChartText.Draw(context, "now", new(tickX - 10, plot.Bottom + 12), Ui.Colour("Secondary", dark));
void DrawSeries(LimitInstance series, bool previous)
{
for (var i = 1; i < series.Points.Count; i++)
{
var a = series.Points[i - 1]; var b = series.Points[i];
if (i == 1 && a.Time == series.Start && b.Origin == UseOrigin.Measured && series.Scale is null && b.Time > series.Start) continue;
var offset = previous ? instance.Start - series.Start : TimeSpan.Zero;
var estimated = a.Origin == UseOrigin.Estimated || b.Origin == UseOrigin.Estimated;
using (context.PushOpacity(estimated ? .55 : 1))
context.DrawLine(new Pen(colour, 2, estimated ? new DashStyle([4, 3], 0) : null, lineCap: PenLineCap.Round), new(X(a.Time + offset), Y(a.Used)), new(X(b.Time + offset), Y(b.Used)));
}
}
}
}
public sealed class InstancePeaks(IReadOnlyList<LimitInstance> instances, Provider provider) : Control
{
private readonly List<(Rect Bounds, LimitInstance Instance)> hits = [];
protected override void OnInitialized()
{
base.OnInitialized(); Height = 96; ToolTip.SetShowDelay(this, 0);
PointerMoved += (_, e) =>
{
var instance = hits.FirstOrDefault(h => h.Bounds.Contains(e.GetPosition(this))).Instance;
ToolTip.SetTip(this, instance is null ? null : new DataTooltip(Display.Projection(instance.Start) + " — " + Display.Projection(instance.End),
new("Peak", $"{instance.Peak:0.##} %", Ui.ProviderColour(provider, Ui.Dark(this))),
new(instance.ReachedOrigin == UseOrigin.Estimated ? "Limit reached (estimated)" : "100 % reached", instance.ReachedLimit is { } time ? "⚠ " + Display.Projection(time) : "Not reached"),
new("Source", instance.Points.Any(p => p.Origin == UseOrigin.Estimated) ? "Includes token estimates" : "Measured")));
};
}
public override void Render(DrawingContext context)
{
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear(); if (instances.Count == 0) return;
var colour = Ui.ProviderColour(provider, Ui.Dark(this)); var width = Bounds.Width / instances.Count;
for (var i = 0; i < instances.Count; i++)
{
var instance = instances[instances.Count - 1 - i]; var x = i * width + width / 2;
context.DrawLine(new Pen(colour, 5, lineCap: PenLineCap.Round), new(x, 44), new(x, 44 - Math.Clamp(instance.Peak ?? 0, 0, 100) / 100 * 26));
var session = instance.Reset - instance.Start <= TimeSpan.FromDays(1);
var label = session ? instance.Start.LocalDateTime.ToString("HH:mm") + "\u2013" + instance.End.LocalDateTime.ToString("HH:mm")
: instance.Start.LocalDateTime.ToString("dd.MM") + "\u2013" + instance.End.LocalDateTime.ToString("dd.MM");
ChartText.Draw(context, label, new(Math.Max(i * width, x - 26), 52), Ui.Colour("Muted", Ui.Dark(this)), 9);
var caption = instance.ReachedLimit is { } reached ? "\u26a0 " + reached.LocalDateTime.ToString("dd.MM HH:mm")
: session ? instance.Start.LocalDateTime.ToString("dd.MM") : "";
ChartText.Draw(context, caption, new(Math.Max(i * width, x - 30), 68), Ui.Colour("Secondary", Ui.Dark(this)), 9);
ChartText.Draw(context, $"{instance.Peak:0.#}%", new(x - 16, 0), Ui.Colour("Secondary", Ui.Dark(this)));
hits.Add((new Rect(i * width, 0, width, Bounds.Height), instance));
}
}
}
+180 -45
View File
@@ -1,8 +1,6 @@
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media; using Avalonia.Media;
using Avalonia.Styling;
using FinalToken.Core; using FinalToken.Core;
using System.Globalization; using System.Globalization;
@@ -10,9 +8,26 @@ namespace FinalToken.App;
public sealed class UsageChart : Control public sealed class UsageChart : Control
{ {
private static readonly IBrush[] Palette = [Brush.Parse("#3878D4"), Brush.Parse("#B377D1"), Brush.Parse("#249A88"), Brush.Parse("#C98926")]; public static Rect BarBounds(double x, double bottom, double width, double height, double scaling = 1)
public static IBrush SeriesColour(int index) => Palette[index % Palette.Length]; {
/// <summary>At most five ticks. Token steps are whole numbers rounded up to 1, 2 or 5 times a power of ten.</summary> var gap = width < 6 ? 0 : 2;
if (gap == 0)
{
var left = Math.Round(x * scaling) / scaling;
var right = Math.Round((x + width) * scaling) / scaling;
return new Rect(left, bottom - height, Math.Max(0, right - left), Math.Max(0, height));
}
return new Rect(x + gap / 2, bottom - height, Math.Max(0, width - gap), Math.Max(0, height - gap));
}
public static IBrush SeriesColour(int index) => ModelColour(index, true);
private static IBrush ModelColour(int index, bool dark) => Brush.Parse((dark
? new[] { "#3987e5", "#d95926", "#199e70", "#c98500", "#d55181", "#9085e9" }
: new[] { "#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#6250d6" })[index % 6]);
public static IBrush SeriesColour(string name, IReadOnlyList<string> names, bool dark) => name switch
{
"Claude" => Ui.ProviderColour(Provider.Claude, dark), "Codex" => Ui.ProviderColour(Provider.Codex, dark),
"Other" => Ui.Colour("Muted", dark), _ => ModelColour(Math.Max(0, names.Where(n => n != "Other").Order(StringComparer.Ordinal).ToList().IndexOf(name)), dark)
};
public static IReadOnlyList<double> AxisTicks(double maximum, bool percent = false) public static IReadOnlyList<double> AxisTicks(double maximum, bool percent = false)
{ {
if (!double.IsFinite(maximum) || maximum <= 0) return [0]; if (!double.IsFinite(maximum) || maximum <= 0) return [0];
@@ -21,94 +36,214 @@ public sealed class UsageChart : Control
var magnitude = Math.Pow(10, Math.Floor(Math.Log10(target))); var magnitude = Math.Pow(10, Math.Floor(Math.Log10(target)));
var fraction = target / magnitude; var fraction = target / magnitude;
var step = (fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10) * magnitude; var step = (fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10) * magnitude;
var intervals = (int)Math.Ceiling(maximum / step); return Enumerable.Range(0, (int)Math.Ceiling(maximum / step) + 1).Select(i => i * step).ToArray();
return Enumerable.Range(0, intervals + 1).Select(i => i * step).ToArray();
} }
public IReadOnlyList<ChartValue> Values { get; init; } = []; public IReadOnlyList<ChartValue> Values { get; init; } = [];
public IReadOnlyList<string> SeriesNames { get; init; } = [];
public bool Percent { get; init; } public bool Percent { get; init; }
public Provider LimitProvider { get; init; }
public ChartValue? Forecast { get; init; }
public ChartValue? ForecastStart { get; init; }
public TimeSpan Interval { get; init; } = TimeSpan.FromHours(1); public TimeSpan Interval { get; init; } = TimeSpan.FromHours(1);
private readonly List<(Rect Rect, string Text)> hits = []; private readonly List<(Rect Rect, Func<DataTooltip> Tip)> hits = [];
public UsageChart() public UsageChart()
{ {
Height = 180; Height = 208;
PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Text); ToolTip.SetShowDelay(this, 0);
PointerExited += (_, _) => ToolTip.SetTip(this, null); PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Tip?.Invoke());
} }
public override void Render(DrawingContext context) public override void Render(DrawingContext context)
{ {
base.Render(context); base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear();
hits.Clear(); var dark = Ui.Dark(this); var ink = Ui.Colour("Muted", dark);
var ink = ActualThemeVariant == ThemeVariant.Dark ? Brushes.WhiteSmoke : Brushes.DarkSlateGray; var plot = new Rect(50, 16, Math.Max(1, Bounds.Width - 66), Math.Max(1, Bounds.Height - 48));
var plot = new Rect(58, 12, Math.Max(1, Bounds.Width - 74), Math.Max(1, Bounds.Height - 46));
var groups = Values.GroupBy(v => v.Time).OrderBy(g => g.Key).ToArray(); var groups = Values.GroupBy(v => v.Time).OrderBy(g => g.Key).ToArray();
var ticks = AxisTicks(groups.Length == 0 ? 0 : Percent ? 100 : groups.Max(g => g.Sum(v => v.Value)), Percent); var ticks = AxisTicks(groups.Length == 0 ? 0 : Percent ? 100 : groups.Max(g => g.Sum(v => v.Value)), Percent);
var max = Math.Max(1, ticks[^1]); var max = Math.Max(1, ticks[^1]);
foreach (var tick in ticks) foreach (var tick in ticks)
{ {
var y = plot.Bottom - plot.Height * tick / max; var y = plot.Bottom - plot.Height * tick / max;
context.DrawLine(new Pen(ActualThemeVariant == ThemeVariant.Dark ? Brush.Parse("#354052") : Brush.Parse("#DFE5EE")), new(plot.Left, y), new(plot.Right, y)); context.DrawLine(new Pen(Ui.Colour(tick == 0 ? "Axis" : "Grid", dark)), new(plot.Left, y), new(plot.Right, y));
var label = Percent ? $"{tick:0}%" : tick >= 1e9 ? $"{tick / 1e9:0.#}B" : tick >= 1e6 ? $"{tick / 1e6:0.#}M" : tick >= 1000 ? $"{tick / 1000:0.#}K" : $"{tick:0}"; ChartText.Draw(context, Percent ? $"{tick:0}%" : Display.Axis(tick), new(0, y - 8), ink);
Text(context, label, new(0, y - 8), ink);
} }
if (groups.Length == 0) { Text(context, "No samples in this range", new(plot.Left + 12, plot.Top + 32), ink); return; } if (groups.Length == 0) { ChartText.Draw(context, "No samples in this range", new(plot.Left + 12, plot.Top + 32), ink); return; }
var series = Values.Select(v => v.Series).Distinct().ToArray(); var series = SeriesNames.Count > 0 ? SeriesNames : Values.Select(v => v.Series).Distinct().Order(StringComparer.Ordinal).ToArray();
var minTime = groups[0].Key;
var lastTime = Forecast is { } f && f.Time > groups[^1].Key ? f.Time : groups[^1].Key;
var duration = Math.Max(Interval.TotalSeconds, (lastTime - minTime).TotalSeconds + (Percent ? 0 : Interval.TotalSeconds));
double X(DateTimeOffset time) => plot.Left + (time - minTime).TotalSeconds / duration * plot.Width;
Point Position(ChartValue v, double value) => new(X(v.Time), plot.Bottom - Math.Clamp(value, 0, max) / max * plot.Height);
if (Percent) if (Percent)
{ {
var colour = Ui.ProviderColour(LimitProvider, dark);
ChartValue? previous = null; ChartValue? previous = null;
var minTime = groups[0].Key;
var timeSpan = Math.Max(1, (groups[^1].Key - minTime).TotalSeconds);
Point Position(ChartValue v, double value) => new(plot.Left + (v.Time - minTime).TotalSeconds / timeSpan * plot.Width, plot.Bottom - Math.Clamp(value, 0, 100) / 100 * plot.Height);
foreach (var value in Values.OrderBy(v => v.Time)) foreach (var value in Values.OrderBy(v => v.Time))
{ {
var point = Position(value, value.Value); var point = Position(value, value.Value);
if (previous is { } p && !value.BreakBefore) if (previous is { } p && !value.BreakBefore)
{ {
context.DrawLine(new Pen(Palette[0], 2), Position(p, p.Value), point); context.DrawLine(new Pen(colour, 2, lineCap: PenLineCap.Round), Position(p, p.Value), point);
if (p.Expected is { } pe && value.Expected is { } expected) if (p.Expected is { } pe && value.Expected is { } expected)
context.DrawLine(new Pen(Palette[2], 1, new DashStyle([4, 3], 0)), Position(p, pe), Position(value, expected)); context.DrawLine(new Pen(ink, 1, new DashStyle([4, 3], 0)), Position(p, pe), Position(value, expected));
} }
context.DrawEllipse(Palette[0], null, point, 3, 3); context.DrawEllipse(colour, null, point, 2, 2);
hits.Add((new(point.X - 8, point.Y - 10, 16, 20), $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Value:0.##}% · expected {(value.Expected is { } e ? $"{e:0.##}%" : "unknown")}")); hits.Add((new(point.X - 8, point.Y - 10, 16, 20), () => new DataTooltip(Display.ChartTimestamp(value.Time, Interval), new("Used", $"{value.Value:0.##} %"), new("Expected", $"{value.Expected:0.##} %"))));
previous = value; previous = value;
} }
if (previous is { } tail && Forecast is { } forecast)
{
var start = ForecastStart ?? tail;
context.DrawLine(new Pen(colour, 2, new DashStyle([1, 3], 0)), Position(start, start.Value), Position(forecast, forecast.Value));
hits.Add((new Rect(Position(forecast, forecast.Value) - new Vector(8, 8), new Size(16, 16)), () => new DataTooltip("Average forecast", new("Time", Display.Projection(forecast.Time)), new("Use", $"{forecast.Value:0.#} %"))));
}
} }
else else
{ {
var duration = Math.Max(Interval.TotalSeconds, (groups[^1].Key - groups[0].Key).TotalSeconds + Interval.TotalSeconds);
var width = plot.Width * Interval.TotalSeconds / duration; var width = plot.Width * Interval.TotalSeconds / duration;
for (var i = 0; i < groups.Length; i++) foreach (var group in groups)
{ {
var bottom = plot.Bottom; var bottom = plot.Bottom;
foreach (var value in groups[i]) foreach (var value in group.OrderBy(v => v.Series, StringComparer.Ordinal))
{ {
var height = value.Value / max * plot.Height; var height = value.Value / max * plot.Height;
var x = plot.Left + (groups[i].Key - groups[0].Key).TotalSeconds / duration * plot.Width; var x = X(group.Key);
var rect = new Rect(x + Math.Min(1, width / 8), bottom - height, Math.Max(0.5, width - Math.Min(2, width / 4)), height); var gap = width < 6 ? 0 : 2;
context.DrawRectangle(Palette[Array.IndexOf(series, value.Series) % Palette.Length], null, rect); var rect = BarBounds(x, bottom, width, height, TopLevel.GetTopLevel(this)?.RenderScaling ?? 1);
hits.Add((rect, $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Series}: {value.Value:N0} tokens")); if (height > 0) context.DrawRectangle(SeriesColour(value.Series, series, dark), null, rect, gap == 0 ? 0 : 3, gap == 0 ? 0 : 3);
hits.Add((new(x, bottom - Math.Max(8, height), Math.Max(8, width), Math.Max(8, height)), () => new DataTooltip(Display.ChartTimestamp(group.Key, Interval),
group.Select(v => new TooltipRow(v.Series, Display.Compact(v.Value) + " · " + v.Value.ToString("N0"), SeriesColour(v.Series, series, dark))).ToArray())));
bottom -= height; bottom -= height;
} }
} }
} }
Text(context, Display.ChartDateLabel(groups[0].Key, Interval), new(plot.Left, plot.Bottom + 8), ink); // Daily calendar ticks remain anchored to local dates through DST.
Text(context, Display.ChartDateLabel(groups[^1].Key, Interval), new(Math.Max(plot.Left, plot.Right - 110), plot.Bottom + 8), ink); var spanDays = (lastTime - minTime).TotalDays;
ToolTip.SetShowDelay(this, 0); var stride = Math.Max(1, (int)Math.Ceiling(spanDays / Math.Max(2, plot.Width / 70)));
var day = Interval >= TimeSpan.FromDays(1) ? minTime : CalendarDays.Start(minTime);
var index = 0;
while (day <= lastTime)
{
if (day >= minTime && index % stride == 0)
ChartText.Draw(context, day.DateTime.ToString("dd.MM"), new(Math.Clamp(X(day) - 12, plot.Left, plot.Right - 40), plot.Bottom + 8), ink);
day = CalendarDays.NextStart(day); index++;
}
if (spanDays < 1) ChartText.Draw(context, minTime.LocalDateTime.ToString("dd.MM HH:mm"), new(plot.Left, plot.Bottom + 8), ink);
}
}
internal static class ChartText
{
public static void Draw(DrawingContext context, string text, Point point, IBrush brush, double size = 11)
{
var formatted = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, Typeface.Default, size, brush);
formatted.SetFontFeatures(FontFeatureCollection.Parse("tnum")); context.DrawText(formatted, point);
} }
private static void Text(DrawingContext context, string text, Point point, IBrush brush) => context.DrawText(
new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, Typeface.Default, 11, brush), point);
} }
public sealed class PaceBar(WindowSnapshot window) : Control public sealed class PaceBar(WindowSnapshot window) : Control
{ {
public static IBrush Colour(PaceState state) => Brush.Parse(state switch public static IBrush Colour(PaceState state) => Brush.Parse(state switch
{ PaceState.Ahead => "#D98236", PaceState.Behind => "#3A8CCB", PaceState.OnTrack => "#279884", _ => "#8C95A3" }); { PaceState.Ahead => "#ec835a", PaceState.Behind => "#fab219", PaceState.OnTrack => "#0ca30c", _ => "#898781" });
public override void Render(DrawingContext context) public override void Render(DrawingContext context)
{ {
base.Render(context); base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size));
context.DrawRectangle(Brush.Parse("#338795A5"), null, new Rect(Bounds.Size), 4, 4); var dark = Ui.Dark(this); var colour = Ui.ProviderColour(window.Window.Provider, dark);
context.DrawRectangle(Colour(window.Pace.State), null, new Rect(0, 0, Bounds.Width * Math.Clamp(window.Window.UsedPercent / 100, 0, 1), Bounds.Height), 4, 4); context.DrawRectangle(Ui.Colour("Grid", dark), null, new Rect(Bounds.Size), 3, 3);
var used = Bounds.Width * Math.Clamp(window.Window.UsedPercent / 100, 0, 1);
if (LimitAnalysis.AverageUseAtReset(window.Window, DateTimeOffset.UtcNow, window.Pace) is { } forecast && forecast > window.Window.UsedPercent)
{
using (context.PushOpacity(0.25)) context.DrawRectangle(colour, null, new Rect(used, 0, Math.Max(0, Bounds.Width * Math.Min(1, forecast / 100) - used), Bounds.Height), 3, 3);
if (forecast > 100) context.DrawLine(new Pen(window.Pace.State == PaceState.Ahead ? Brush.Parse("#d03b3b") : Ui.Colour("Secondary", dark), 3), new(Bounds.Width - 2, 0), new(Bounds.Width - 2, Bounds.Height));
}
context.DrawRectangle(colour, null, new Rect(0, 0, used, Bounds.Height), 3, 3);
if (window.Pace.ElapsedFraction is { } elapsed) if (window.Pace.ElapsedFraction is { } elapsed)
context.DrawLine(new Pen(ActualThemeVariant == ThemeVariant.Dark ? Brushes.White : Brushes.Black, 2), new(Bounds.Width * elapsed, 0), new(Bounds.Width * elapsed, Bounds.Height)); context.DrawLine(new Pen(Ui.Colour("Ink", dark), 2), new(Bounds.Width * elapsed, -2), new(Bounds.Width * elapsed, Bounds.Height + 2));
ToolTip.SetTip(this, $"Used {window.Window.UsedPercent:0.##}% · expected {window.Pace.ElapsedFraction * 100:0.##}%"); ToolTip.SetTip(this, new DataTooltip(window.Window.Label, new("Used", $"{window.Window.UsedPercent:0.##} %"), new("Expected", $"{window.Pace.ElapsedFraction * 100:0.##} %")));
}
}
public sealed class CompositionBar(TokenCounts counts, Provider provider, bool includeCache) : Control
{
public override void Render(DrawingContext context)
{
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size));
var input = Math.Max(0, counts.Input - (provider == Provider.Codex ? counts.CacheRead : 0));
double[] values = [input, counts.Output, counts.CacheWrite, includeCache ? counts.CacheRead : 0];
var sum = Math.Max(1, values.Sum()); var x = 0d;
for (var i = 0; i < values.Length; i++)
{
var width = Bounds.Width * values[i] / sum;
using (context.PushOpacity(i == 1 ? .65 : i == 2 ? .4 : 1))
context.DrawRectangle(i == 3 ? Ui.Colour("Cache", Ui.Dark(this)) : Ui.ProviderColour(provider, Ui.Dark(this)), null,
new Rect(x, 0, Math.Max(0, width - 2), Bounds.Height), 3, 3);
x += width;
}
ToolTip.SetTip(this, DataTooltip.Tokens(provider + " · token composition", counts));
}
}
public sealed class DailyLimitChart(WindowDays days, Provider provider) : Control
{
private readonly List<(Rect Rect, Func<DataTooltip> Tip)> hits = [];
public DailyLimitChart() : this(new([], [], null, 0, null), Provider.Claude) { }
protected override void OnInitialized()
{
base.OnInitialized(); Height = 248; ToolTip.SetShowDelay(this, 0);
PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Tip?.Invoke());
}
public override void Render(DrawingContext context)
{
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear();
var dark = Ui.Dark(this); var ink = Ui.Colour("Muted", dark); var colour = Ui.ProviderColour(provider, dark);
var plot = new Rect(40, 24, Math.Max(1, Bounds.Width - 174), Math.Max(1, Bounds.Height - 60));
var maximum = Math.Max(days.EvenPace, Math.Max(days.DailyBudget ?? 0, days.Current.Concat(days.Previous).Select(d => d.Used ?? 0).DefaultIfEmpty(0).Max()));
var ticks = UsageChart.AxisTicks(maximum * 1.15); var max = Math.Max(1, ticks[^1]);
double Y(double value) => plot.Bottom - value / max * plot.Height;
foreach (var tick in ticks)
{
context.DrawLine(new Pen(Ui.Colour("Grid", dark)), new(plot.Left, Y(tick)), new(plot.Right, Y(tick)));
ChartText.Draw(context, $"{tick:0.#}%", new(0, Y(tick) - 7), ink);
}
var width = plot.Width / Math.Max(1, days.Current.Count);
for (var i = 0; i < days.Current.Count; i++)
{
var day = days.Current[i]; var x = plot.Left + i * width;
if (i < days.Previous.Count && days.Previous[i].Used is { } prior)
using (context.PushOpacity(.18)) context.DrawRectangle(null, new Pen(colour, 2), new Rect(x + 4, Y(prior), width - 8, plot.Bottom - Y(prior)), 3, 3);
if (day.Used is { } use)
{
var rect = new Rect(x + 8, Y(use), Math.Max(1, width - 16), Math.Max(0, plot.Bottom - Y(use)));
using (context.PushOpacity(day.Origin == UseOrigin.Estimated ? .45 : day.IsToday ? 1 : .5))
{
if (day.Origin == UseOrigin.Measured) context.DrawRectangle(colour, null, rect, 3, 3);
else
{
context.DrawRectangle(null, new Pen(colour, 1), rect, 3, 3);
using (context.PushClip(rect))
for (var hatchX = rect.Left - rect.Height; hatchX < rect.Right; hatchX += 8)
context.DrawLine(new Pen(colour, 1), new(hatchX, rect.Bottom), new(hatchX + rect.Height, rect.Top));
}
}
if (day.IsToday) ChartText.Draw(context, $"{use:0.#}%", new(x + 8, Y(use) - 18), Ui.Colour("Ink", dark), 12);
}
ChartText.Draw(context, day.Start.DateTime.ToString("ddd"), new(x + 8, plot.Bottom + 8), day.IsToday ? Ui.Colour("Ink", dark) : ink);
hits.Add((new Rect(x, plot.Top, width, plot.Height + 30), () => DataTooltip.Day(day)));
}
var evenLabel = Math.Clamp(Y(days.EvenPace) - 7, plot.Top, plot.Bottom - 14);
var budgetLabel = days.DailyBudget is { } b ? Math.Clamp(Y(b) - 7, plot.Top, plot.Bottom - 14) : 0;
if (days.DailyBudget is { } budget && Math.Abs(evenLabel - budgetLabel) < 18)
{
var middle = Math.Clamp((evenLabel + budgetLabel) / 2, plot.Top + 9, plot.Bottom - 23);
evenLabel = middle + (budget >= days.EvenPace ? 9 : -9);
budgetLabel = middle + (budget >= days.EvenPace ? -9 : 9);
}
Reference(days.EvenPace, $"Even {days.EvenPace:0.#}%/day", ink, evenLabel, true);
if (days.DailyBudget is { } dailyBudget) Reference(dailyBudget, $"Budget {dailyBudget:0.#}%/day", Ui.Colour("Secondary", dark), budgetLabel, false);
void Reference(double value, string label, IBrush brush, double labelY, bool dashed)
{
context.DrawLine(new Pen(brush, 1, dashed ? new DashStyle([4, 4], 0) : null), new(plot.Left, Y(value)), new(plot.Right, Y(value)));
if (Math.Abs(labelY + 7 - Y(value)) > 3) context.DrawLine(new Pen(brush, 1), new(plot.Right, Y(value)), new(plot.Right + 6, labelY + 7));
ChartText.Draw(context, label, new(plot.Right + 8, labelY), brush);
}
} }
} }
+46
View File
@@ -0,0 +1,46 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using FinalToken.Core;
namespace FinalToken.App;
public sealed record TooltipRow(string Label, string Value, IBrush? Swatch = null);
/// <summary>D8: every data tooltip uses the same title and aligned label/value layout.</summary>
public sealed class DataTooltip : Border
{
public string Title { get; }
public IReadOnlyList<TooltipRow> Rows { get; }
public DataTooltip(string title, params TooltipRow[] rows)
{
Title = title; Rows = rows; MaxWidth = 520; MinWidth = 260; Padding = new Thickness(12); CornerRadius = new CornerRadius(8);
this.Bind(BackgroundProperty, this.GetResourceObservable("Surface"));
this.Bind(BorderBrushProperty, this.GetResourceObservable("Border")); BorderThickness = new Thickness(1);
var heading = Ui.Text(title, 13); heading.FontWeight = FontWeight.SemiBold; heading.MaxWidth = 480;
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 20, RowSpacing = 6 };
for (var i = 0; i < rows.Length; i++)
{
grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
var row = rows[i]; var label = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
if (row.Swatch is { } colour) label.Children.Add(new Border { Width = 6, Height = 6, Background = colour, CornerRadius = new CornerRadius(2), VerticalAlignment = VerticalAlignment.Center });
var labelText = Ui.Text(row.Label, 12, "Secondary"); labelText.MaxWidth = 180; label.Children.Add(labelText);
var value = Ui.TableNumber(row.Value, 12); value.HorizontalAlignment = HorizontalAlignment.Right;
Grid.SetRow(label, i); grid.Children.Add(label); Grid.SetRow(value, i); Grid.SetColumn(value, 1); grid.Children.Add(value);
}
Child = Ui.Stack(heading, grid);
}
public static string Count(long value) => Display.Compact(value) + " · " + value.ToString("N0");
public static DataTooltip Tokens(string title, TokenCounts counts) => new(title,
new("Total", Count(counts.Total)), new("Input", Count(counts.Input)), new("Output", Count(counts.Output)),
new("Cache write", Count(counts.CacheWrite)), new("Cache read", Count(counts.CacheRead)), new("Reasoning", Count(counts.ReasoningOutput)));
public static DataTooltip Day(LimitDay day)
{
var rows = new List<TooltipRow> { new("Use", day.IsFuture ? "Future day" : day.Used is { } use ? $"{use:0.##} % of the week" : "Collecting history") };
if (!day.IsFuture && day.Used is not null) rows.Add(new("Source", day.Origin == UseOrigin.Estimated ? "Estimated from tokens" : "Measured"));
if (!day.IsFuture && day.Cumulative is { } cumulative) rows.Add(new("Cumulative", $"{cumulative:0.##} %"));
return new(day.Start.DateTime.ToString("D"), rows.ToArray());
}
public override string ToString() => Title + "\n" + string.Join('\n', Rows.Select(r => r.Label + ": " + r.Value));
}
+9 -3
View File
@@ -27,7 +27,7 @@ public sealed class DesktopApp : Application
private bool quitting; private bool quitting;
private PluginInstallStatus pluginStatus = new(PluginInstallState.NoHostFound); private PluginInstallStatus pluginStatus = new(PluginInstallState.NoHostFound);
public IPluginInstaller PluginInstaller { get; set; } = FinalToken.Core.StreamDeck.PluginInstaller.CreateDefault(); public IPluginInstaller PluginInstaller { get; set; } = FinalToken.Core.StreamDeck.PluginInstaller.CreateDefault();
public override void Initialize() => Styles.Add(new FluentTheme()); public override void Initialize() => Styles.Add(Ui.NeutralTheme());
public override void OnFrameworkInitializationCompleted() public override void OnFrameworkInitializationCompleted()
{ {
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime) if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime)
@@ -53,6 +53,7 @@ public sealed class DesktopApp : Application
engine.PopupRequested += alert => Dispatcher.UIThread.Post(() => { if (!quitting) popups.Pace(alert); }); engine.PopupRequested += alert => Dispatcher.UIThread.Post(() => { if (!quitting) popups.Pace(alert); });
engine.ActivationRequested += () => Dispatcher.UIThread.Post(OpenPanel); engine.ActivationRequested += () => Dispatcher.UIThread.Post(OpenPanel);
model.Snapshot = engine.CurrentSnapshot; model.Snapshot = engine.CurrentSnapshot;
model.ProbeInterval = engine.Settings.ProbeInterval;
ageTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) }; ageTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
ageTimer.Tick += (_, _) => { if (panel.IsVisible) model.Diagnostics = engine.RecentDiagnostics; }; ageTimer.Tick += (_, _) => { if (panel.IsVisible) model.Diagnostics = engine.RecentDiagnostics; };
ageTimer.Start(); ageTimer.Start();
@@ -88,7 +89,11 @@ public sealed class DesktopApp : Application
panel.Show(); panel.WindowState = WindowState.Normal; panel.Activate(); panel.Show(); panel.WindowState = WindowState.Normal; panel.Activate();
if (OperatingSystem.IsWindows()) WindowsActivation.Activate(panel); if (OperatingSystem.IsWindows()) WindowsActivation.Activate(panel);
} }
private Task Refresh() => engine is null ? Task.CompletedTask : engine.RefreshNowAsync(); private async Task Refresh()
{
if (engine is null) return;
await model.RefreshAsync(() => engine.RefreshNowAsync());
}
private async Task LoadHistory() private async Task LoadHistory()
{ {
if (engine is null || model.Snapshot is not { } snapshot || quitting) return; if (engine is null || model.Snapshot is not { } snapshot || quitting) return;
@@ -100,7 +105,7 @@ public sealed class DesktopApp : Application
{ {
if (engine is null) return; if (engine is null) return;
if (settingsWindow is not null) { settingsWindow.Activate(); return; } if (settingsWindow is not null) { settingsWindow.Activate(); return; }
settingsWindow = new SettingsWindow(engine.Settings, pluginStatus, value => settingsSave = SaveSettings(value)); settingsWindow = new SettingsWindow(engine.Settings, pluginStatus, value => settingsSave = SaveSettings(value), () => Run(Quit));
settingsWindow.Closed += (_, _) => settingsWindow = null; settingsWindow.Closed += (_, _) => settingsWindow = null;
settingsWindow.Show(); settingsWindow.Show();
} }
@@ -113,6 +118,7 @@ public sealed class DesktopApp : Application
try { await engine.UpdateSettingsAsync(value); } try { await engine.UpdateSettingsAsync(value); }
catch { await OsStartup.ApplyAsync(previous.StartWithOs); throw; } catch { await OsStartup.ApplyAsync(previous.StartWithOs); throw; }
if (quitting) return; if (quitting) return;
model.ProbeInterval = value.ProbeInterval;
await CheckPlugin(); await CheckPlugin();
if (!quitting) await engine.RefreshNowAsync(); if (!quitting) await engine.RefreshNowAsync();
} }
+18
View File
@@ -0,0 +1,18 @@
using Avalonia;
using Avalonia.Controls;
namespace FinalToken.App;
/// <summary>Template reapplication never registers another checked handler.</summary>
public sealed class NeutralCheckBox : CheckBox
{
public static readonly DirectProperty<NeutralCheckBox, bool> MarkVisibleProperty =
AvaloniaProperty.RegisterDirect<NeutralCheckBox, bool>(nameof(MarkVisible), c => c.MarkVisible);
private bool markVisible;
public bool MarkVisible => markVisible;
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == IsCheckedProperty) SetAndRaise(MarkVisibleProperty, ref markVisible, IsChecked == true);
}
}
+72 -22
View File
@@ -4,11 +4,17 @@ using FinalToken.Core;
namespace FinalToken.App; namespace FinalToken.App;
public enum HistoryRange { Hours24, Days7, Days30, Days90, All } public enum HistoryRange { Hours24, Days7, Days30, Days90, All }
public sealed record ChartValue(DateTimeOffset Time, string Series, double Value, double? Expected = null, bool BreakBefore = false); public sealed record ChartValue(DateTimeOffset Time, string Series, double Value, double? Expected = null, bool BreakBefore = false, double CacheRead = 0);
public sealed record BreakdownRow(string Name, TokenCounts Counts, double Share); public sealed record BreakdownRow(string Name, TokenCounts Counts, double Share, IReadOnlyList<Provider>? Providers = null);
public sealed record LimitChart(string Label, IReadOnlyList<ChartValue> Values); public sealed record LimitChart(string Label, IReadOnlyList<ChartValue> Values, Provider Provider = Provider.Claude,
DateTimeOffset? Since = null, ChartValue? Forecast = null, ChartValue? ForecastStart = null,
LimitEstimate? Analysis = null, WindowSnapshot? Window = null, DateTimeOffset Now = default);
public sealed record LimitDetail(Provider Provider, string Id, RateForecast? Recent, WindowDays? Days, DateTimeOffset? Since = null);
public sealed record HistoryView(IReadOnlyList<ChartValue> Hourly, IReadOnlyList<ChartValue> Daily, public sealed record HistoryView(IReadOnlyList<ChartValue> Hourly, IReadOnlyList<ChartValue> Daily,
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 partial class PanelViewModel : ObservableObject public partial class PanelViewModel : ObservableObject
{ {
@@ -18,6 +24,16 @@ public partial class PanelViewModel : ObservableObject
[ObservableProperty] private HistoryView history = new([], [], [], [], []); [ObservableProperty] private HistoryView history = new([], [], [], [], []);
[ObservableProperty] private IReadOnlyList<Diagnostic> diagnostics = []; [ObservableProperty] private IReadOnlyList<Diagnostic> diagnostics = [];
[ObservableProperty] private string message = "Reading local CLI data…"; [ObservableProperty] private string message = "Reading local CLI data…";
[ObservableProperty] private bool includeCacheReads = true;
[ObservableProperty] private bool refreshing;
public async Task RefreshAsync(Func<Task> refresh)
{
if (Refreshing) return;
Refreshing = true;
try { await refresh(); }
finally { Refreshing = false; }
}
public TimeSpan ProbeInterval { get; set; } = TimeSpan.FromMinutes(5);
public static DateTimeOffset RangeStart(HistoryRange range, DateTimeOffset now) => range switch public static DateTimeOffset RangeStart(HistoryRange range, DateTimeOffset now) => range switch
{ {
@@ -33,43 +49,60 @@ public partial class PanelViewModel : ObservableObject
var providers = snapshot.Providers.Where(p => filter is null || p.Provider == filter).ToArray(); var providers = snapshot.Providers.Where(p => filter is null || p.Provider == filter).ToArray();
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 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 samples = store.LimitSamples(p.Provider, w.Window.Id, from, now);
var instanceSamples = store.LimitSamples(p.Provider, w.Window.Id,
w.Window.ResetsAt is { } r && w.Window.Length is { } l ? r - l * 9 - TimeSpan.FromMinutes(15) : now.AddDays(-14), now);
var tokens = w.Window.ResetsAt is { } tokenReset && w.Window.Length is { } tokenLength
? store.TokenSeriesByModel(p.Provider, tokenReset - tokenLength * 9 - TimeSpan.FromMinutes(15), now, SeriesInterval.Hour) : [];
var analysis = LimitAnalysis.Analyze(w.Window, instanceSamples, tokens, now);
details.Add(new(p.Provider, w.Window.Id, LimitAnalysis.Recent(w.Window, instanceSamples, now, w.Pace),
analysis?.Days,
instanceSamples.Where(s => LimitAnalysis.SameInstance(s, w.Window)).Select(s => s.SampleTime).DefaultIfEmpty(w.Window.SampleTime).Min()));
return new LimitChart($"{p.Provider} · {w.Window.Label}", samples.Select((s, i) => return new LimitChart($"{p.Provider} · {w.Window.Label}", samples.Select((s, i) =>
new ChartValue(s.SampleTime, w.Window.Label, s.UsedPercent, new ChartValue(s.SampleTime, p.Provider.ToString(), s.UsedPercent,
Pace.Calculate(s, s.SampleTime).ElapsedFraction * 100, Pace.Calculate(s, s.SampleTime).ElapsedFraction * 100,
i > 0 && s.ResetsAt != samples[i - 1].ResetsAt)).ToArray()); i > 0 && !LimitAnalysis.SameInstance(s, samples[i - 1]))).ToArray(), p.Provider,
samples.FirstOrDefault()?.SampleTime ?? instanceSamples.FirstOrDefault()?.SampleTime ?? w.Window.SampleTime,
w.Pace.Projection is { } projection ? new(projection, p.Provider.ToString(), 100) :
w.Window.ResetsAt is { } reset && LimitAnalysis.AverageUseAtReset(w.Window, now, w.Pace) is { } average ? new(reset, p.Provider.ToString(), average) : null,
new(now, p.Provider.ToString(), w.Window.UsedPercent), analysis, w, now);
})).ToArray(); })).ToArray();
return new(hourly, daily, limits, Breakdown(true), Breakdown(false)); var models = Breakdown(true); var projects = Breakdown(false);
return new(hourly, daily, limits, models, projects) { Details = details };
IReadOnlyList<ChartValue> Series(SeriesInterval interval) => providers.SelectMany(p => IReadOnlyList<ChartValue> Series(SeriesInterval interval)
store.TokenSeries(p.Provider, from, now, interval).SelectMany(point => filter is null
? new[] { new ChartValue(point.Time, p.Provider.ToString(), point.Counts.Total) }
: ModelsAtPoint(p.Provider, point.Time, interval))).ToArray();
IEnumerable<ChartValue> ModelsAtPoint(Provider provider, DateTimeOffset time, SeriesInterval interval)
{ {
var end = interval == SeriesInterval.Hour ? time.AddHours(1) : CalendarDays.NextStart(time); if (filter is null) return providers.SelectMany(p => store.TokenSeries(p.Provider, from, now, interval)
return store.ByModel(provider, time < from ? from : time, end > now ? now : end) .Select(point => new ChartValue(point.Time, p.Provider.ToString(), point.Counts.Total, CacheRead: point.Counts.CacheRead))).ToArray();
.Select(m => new ChartValue(time, m.Name ?? "Unknown model", m.Counts.Total)); var points = store.TokenSeriesByModel(filter.Value, from, now, interval);
var names = points.Select(p => p.Model ?? "Unknown model").Distinct().Order(StringComparer.Ordinal).Take(6).ToHashSet();
return points.GroupBy(p => (p.Time, Name: names.Contains(p.Model ?? "Unknown model") ? p.Model ?? "Unknown model" : "Other"))
.Select(g => new ChartValue(g.Key.Time, g.Key.Name, g.Sum(p => (double)p.Counts.Total), CacheRead: g.Sum(p => (double)p.Counts.CacheRead))).ToArray();
} }
IReadOnlyList<BreakdownRow> Breakdown(bool models) IReadOnlyList<BreakdownRow> Breakdown(bool models)
{ {
var rows = providers.SelectMany(p => models ? store.ByModel(p.Provider, from, now) : store.ByProject(p.Provider, from, now)) var rows = providers.SelectMany(p => (models ? store.ByModel(p.Provider, from, now) : store.ByProject(p.Provider, from, now))
.GroupBy(r => r.Name ?? "Unknown").Select(g => new TokenBreakdown(g.Key, .Select(r => (p.Provider, r.Name, r.Counts)))
g.Aggregate(new TokenCounts(), (sum, r) => sum + r.Counts))).OrderByDescending(r => r.Counts.Total).ToArray(); .GroupBy(r => r.Name ?? "Unknown").Select(g => new BreakdownRow(g.Key,
g.Aggregate(new TokenCounts(), (sum, r) => sum + r.Counts), 0, g.Select(r => r.Provider).Distinct().Order().ToArray())).OrderByDescending(r => r.Counts.Total).ToArray();
var total = rows.Sum(r => (double)r.Counts.Total); var total = rows.Sum(r => (double)r.Counts.Total);
return rows.Select(r => new BreakdownRow(r.Name!, r.Counts, total == 0 ? 0 : r.Counts.Total / total)).ToArray(); return rows.Select(r => r with { Share = total == 0 ? 0 : r.Counts.Total / total }).ToArray();
} }
} }
} }
public static class Display public static class Display
{ {
public static string? ForecastWaiting(WindowSnapshot window, DateTimeOffset now) =>
window.Pace.State != PaceState.Unknown && !Pace.CanForecast(window.Window, now, window.Pace) &&
Pace.ForecastStartsAt(window.Window) is { } start && start > now ? "Forecast from " + Projection(start) : null;
public static string ChartDateLabel(DateTimeOffset time, TimeSpan interval) public static string ChartDateLabel(DateTimeOffset time, TimeSpan interval)
=> ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "MM-dd" : "MM-dd HH:mm"); => ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "MM-dd" : "MM-dd HH:mm");
public static string ChartTimestamp(DateTimeOffset time, TimeSpan interval) public static string ChartTimestamp(DateTimeOffset time, TimeSpan interval)
=> ChartTime(time, interval).ToString("g"); => ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "d" : "g");
private static DateTime ChartTime(DateTimeOffset time, TimeSpan interval) private static DateTime ChartTime(DateTimeOffset time, TimeSpan interval)
=> interval >= TimeSpan.FromDays(1) ? time.DateTime : time.LocalDateTime; => interval >= TimeSpan.FromDays(1) ? time.DateTime : time.LocalDateTime;
public static string Projection(DateTimeOffset projection, TimeProvider? clock = null, System.Globalization.CultureInfo? culture = null) public static string Projection(DateTimeOffset projection, TimeProvider? clock = null, System.Globalization.CultureInfo? culture = null)
@@ -80,9 +113,26 @@ public static class Display
culture ?? System.Globalization.CultureInfo.CurrentCulture); culture ?? System.Globalization.CultureInfo.CurrentCulture);
} }
public static string Duration(TimeSpan span) => span <= TimeSpan.Zero ? "now" : span.TotalDays >= 1 public static string Duration(TimeSpan span) => span <= TimeSpan.Zero ? "now" : span.TotalDays >= 1
? $"{span.TotalDays:0.0} d" : span.TotalHours >= 1 ? $"{span.TotalHours:0.0} h" : $"{Math.Ceiling(span.TotalMinutes):0} min"; ? $"{(int)span.TotalDays} d {span.Hours} h" : span.TotalHours >= 1 ? $"{(int)span.TotalHours} h {span.Minutes} min" : $"{Math.Ceiling(span.TotalMinutes):0} min";
public static string Span(TimeSpan span) => span.TotalHours >= 1 ? $"{span.TotalHours:0.#} h" : $"{span.TotalMinutes:0} min";
public static string Tokens(TokenCounts? counts) => counts is { } c public static string Tokens(TokenCounts? counts) => counts is { } c
? $"{c.Total:N0} total · input {c.Input:N0} · cache read {c.CacheRead:N0} · cache write {c.CacheWrite:N0} · output {c.Output:N0} · reasoning {c.ReasoningOutput:N0}" ? $"{c.Total:N0} total · input {c.Input:N0} · cache read {c.CacheRead:N0} · cache write {c.CacheWrite:N0} · output {c.Output:N0} · reasoning {c.ReasoningOutput:N0}"
: "Unavailable — no known session window"; : "Unavailable — no known session window";
public static string State(PaceState state) => state switch { PaceState.OnTrack => "On track", PaceState.Unknown => "Pace unknown", _ => state.ToString() }; public static string Compact(double count) => CompactNumber(count, false);
public static string Axis(double count) => CompactNumber(count, true);
private static string CompactNumber(double count, bool trimTrailingZeros)
{
var unit = Math.Abs(count) >= 1e9 ? 3 : Math.Abs(count) >= 1e6 ? 2 : Math.Abs(count) >= 1000 ? 1 : 0;
if (unit == 0) return count.ToString("0");
var value = count / Math.Pow(1000, unit);
var decimals = Math.Max(0, 2 - (int)Math.Floor(Math.Log10(Math.Abs(value))));
value = Math.Round(value, decimals, MidpointRounding.AwayFromZero);
if (Math.Abs(value) >= 1000 && unit < 3) { value /= 1000; unit++; }
decimals = Math.Max(0, 2 - (int)Math.Floor(Math.Log10(Math.Abs(value))));
var format = trimTrailingZeros ? decimals == 0 ? "0" : "0." + new string('#', decimals) : "F" + decimals;
return value.ToString(format) + new[] { "", " K", " M", " B" }[unit];
}
public static string Forecast(DateTimeOffset date, PaceState state) =>
(state == PaceState.Ahead ? "⚠ " : "At this pace ") + "100 % on " + Projection(date);
public static string State(PaceState state) => state switch { PaceState.OnTrack => "✓ On track", PaceState.Ahead => "▲ Ahead", PaceState.Behind => "▼ Behind", _ => "? Pace unknown" };
} }
+239 -92
View File
@@ -1,130 +1,277 @@
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout; using Avalonia.Layout;
using Avalonia.Media; using Avalonia.Media;
using Avalonia.Threading;
using FinalToken.Core; using FinalToken.Core;
namespace FinalToken.App; namespace FinalToken.App;
public static class Ui
{
public static TextBlock Text(string text, double size = 13) => new() { Text = text, FontSize = size, TextWrapping = TextWrapping.Wrap };
public static StackPanel Stack(params Control[] children)
{
var stack = new StackPanel { Spacing = 10 };
foreach (var child in children) stack.Children.Add(child);
return stack;
}
public static Border Card(Control content) => new() { Child = content, Padding = new Thickness(18), CornerRadius = new CornerRadius(9), BorderThickness = new Thickness(1), BorderBrush = Brush.Parse("#558795A5") };
public static Button Button(string text, Action action)
{
var button = new Button { Content = text };
button.Click += (_, _) => action();
return button;
}
}
public sealed class PanelWindow : Window public sealed class PanelWindow : Window
{ {
private readonly PanelViewModel model; private readonly PanelViewModel model;
private readonly StackPanel body = new() { Spacing = 16, Margin = new Thickness(24) }; private readonly StackPanel body = new() { Spacing = 24, Margin = new Thickness(24) };
private readonly StackPanel statuses = new() { Orientation = Orientation.Horizontal, Spacing = 8 };
private readonly TextBlock updated = Ui.Text("", 12, "Muted");
private readonly ScrollViewer scroll;
private readonly Button refreshButton;
private bool queued;
private bool wide;
private int limitColumns;
private readonly Dictionary<Provider, string> selectedDailyWindow = [];
private readonly BreakdownState modelBreakdown = new(), projectBreakdown = new();
public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload) public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload)
{ {
this.model = model; this.model = model;
Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}"; Width = 1160; Height = 920; MinWidth = 720; MinHeight = 500; Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}";
var header = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 }; Width = 1280; Height = 900; MinWidth = 960; MinHeight = 500; Ui.Theme(this);
header.Children.Add(Ui.Text("FinalToken", 28)); var brand = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };
header.Children.Add(Ui.Button("Refresh now", refresh)); brand.Children.Add(Ui.Text("FinalToken", 20));
header.Children.Add(Ui.Button("Settings", settings)); var version = Ui.Text(typeof(Program).Assembly.GetName().Version?.ToString(3) ?? "", 12, "Muted"); version.VerticalAlignment = VerticalAlignment.Center;
header.Children.Add(Ui.Button("Quit", quit)); brand.Children.Add(version);
var range = new ComboBox { ItemsSource = new[] { "24 hours", "7 days", "30 days", "90 days", "All history" }, SelectedIndex = (int)model.Range, MinWidth = 150 }; updated.VerticalAlignment = VerticalAlignment.Center; statuses.VerticalAlignment = VerticalAlignment.Center;
range.SelectionChanged += (_, _) => { model.Range = (HistoryRange)range.SelectedIndex; reload(); }; var left = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12, VerticalAlignment = VerticalAlignment.Center };
var providers = new ComboBox { ItemsSource = new[] { "All providers", "Claude", "Codex" }, SelectedIndex = 0, MinWidth = 150 }; left.Children.Add(brand); left.Children.Add(updated); left.Children.Add(statuses);
providers.SelectionChanged += (_, _) => { model.ProviderFilter = providers.SelectedIndex == 0 ? null : (Provider)(providers.SelectedIndex - 1); reload(); }; var range = Segments(["24 h", "7 d", "30 d", "90 d", "All"], (int)model.Range, i => { model.Range = (HistoryRange)i; reload(); });
var filters = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 }; var providers = Segments(["All", "Claude", "Codex"], model.ProviderFilter is { } p ? (int)p + 1 : 0,
filters.Children.Add(range); filters.Children.Add(providers); i => { model.ProviderFilter = i == 0 ? null : (Provider)(i - 1); reload(); });
var dock = new DockPanel { Margin = new Thickness(0, 18, 0, 0) }; refreshButton = Ui.Button("↻", refresh); ToolTip.SetTip(refreshButton, "Refresh local data");
var top = Ui.Stack(header, filters); top.Margin = new Thickness(24, 0, 24, 0); var settingsButton = Ui.Button("⚙", settings); ToolTip.SetTip(settingsButton, "Settings");
DockPanel.SetDock(top, Dock.Top); dock.Children.Add(top); var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };
dock.Children.Add(new ScrollViewer { Content = body }); Content = dock; actions.Children.Add(range); actions.Children.Add(providers); actions.Children.Add(refreshButton); actions.Children.Add(settingsButton);
model.PropertyChanged += (_, _) => RenderModel(); var header = new Grid { Name = "PanelHeader", ColumnDefinitions = new ColumnDefinitions("*,Auto"), Margin = new Thickness(24, 0), Height = 56, ColumnSpacing = 16 };
header.Children.Add(left); Grid.SetColumn(actions, 1); header.Children.Add(actions);
var dock = new DockPanel(); DockPanel.SetDock(header, Dock.Top); dock.Children.Add(header);
scroll = new ScrollViewer { Content = body }; dock.Children.Add(scroll); Content = dock;
model.PropertyChanged += (_, _) => QueueRender();
SizeChanged += (_, _) => { if (wide != (Bounds.Width - 48 >= 1200) || limitColumns != LimitColumnCount(Bounds.Width - 48)) QueueRender(); };
ActualThemeVariantChanged += (_, _) => QueueRender();
RenderModel(); RenderModel();
} }
public static Control Segments(string[] labels, int selected, Action<int> change)
{
var panel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 0 };
var changing = false;
var buttons = labels.Select((label, index) => new ToggleButton { Content = label, IsChecked = index == selected,
Padding = new Thickness(8, 6), FontSize = 12 }).ToArray();
foreach (var button in buttons) button.Classes.Add("segment");
for (var i = 0; i < buttons.Length; i++)
{
var index = i;
buttons[i].IsCheckedChanged += (_, _) =>
{
if (changing) return;
changing = true;
foreach (var other in buttons.Where((_, j) => j != index)) other.IsChecked = false;
buttons[index].IsChecked = true; changing = false; change(index);
};
panel.Children.Add(buttons[i]);
}
return panel;
}
private void QueueRender()
{
if (queued) return; queued = true;
Dispatcher.UIThread.Post(() => { queued = false; RenderModel(); }, DispatcherPriority.Background);
}
public void RenderModel() public void RenderModel()
{ {
body.Children.Clear(); var offset = scroll.Offset;
body.Children.Add(Ui.Text(model.Message)); wide = (Bounds.Width > 0 ? Bounds.Width : Width) - 48 >= 1200;
limitColumns = LimitColumnCount((Bounds.Width > 0 ? Bounds.Width : Width) - 48);
var content = new List<Control>();
statuses.Children.Clear(); refreshButton.IsEnabled = !model.Refreshing;
var now = DateTimeOffset.UtcNow;
updated.Text = model.Snapshot is { } s ? "Updated " + (now - s.MadeAt < TimeSpan.FromMinutes(1) ? "just now" : Display.Duration(now - s.MadeAt) + " ago") : model.Message;
ToolTip.SetTip(updated, model.Snapshot?.MadeAt.LocalDateTime.ToString("F"));
if (model.Snapshot is { } snapshot) if (model.Snapshot is { } snapshot)
{ {
foreach (var provider in snapshot.Providers.Where(p => model.ProviderFilter is null || p.Provider == model.ProviderFilter)) foreach (var p in snapshot.Providers)
{ {
var card = Ui.Stack(Ui.Text(provider.Provider.ToString(), 22), Ui.Text($"{provider.Status} {provider.Reason}")); var label = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 };
foreach (var window in provider.Windows) label.Children.Add(Ui.Mark("●", p.Status == ProviderStatus.Available ? Ui.ProviderColour(p.Provider, Ui.Dark(this)) : Ui.Colour("Muted", Ui.Dark(this))));
label.Children.Add(Ui.Text(p.Provider.ToString(), 12));
var pill = new Border { Child = label, CornerRadius = new CornerRadius(10), Padding = new Thickness(8, 4), BorderThickness = new Thickness(1), BorderBrush = Ui.Colour("Border", Ui.Dark(this)) };
ToolTip.SetTip(pill, p.Reason ?? p.Status.ToString()); statuses.Children.Add(pill);
}
var providers = snapshot.Providers.Where(p => model.ProviderFilter is null || p.Provider == model.ProviderFilter).ToArray();
content.Add(Ui.Text("Limits", 20));
var tiles = new List<Control>();
foreach (var provider in providers)
{ {
var w = window.Window; var pace = window.Pace; if (provider.Status != ProviderStatus.Available)
var title = Ui.Text($"{w.Label} {w.UsedPercent:0.##}% {Display.State(pace.State)} {(pace.Delta is { } d ? $"{d:+0.0;-0.0;0} points" : "")}", 15); tiles.Add(Ui.Card(Ui.Stack(Ui.Text(provider.Provider + " · " + provider.Status, 15), Ui.Text(provider.Reason ?? "Provider disabled", 13, "Secondary"))));
title.Foreground = PaceBar.Colour(pace.State); else foreach (var window in provider.Windows) tiles.Add(LimitTile(window, now));
card.Children.Add(title);
card.Children.Add(new PaceBar(window) { Height = 14 });
card.Children.Add(Ui.Text($"Reset: {(w.ResetsAt is { } reset ? Display.Duration(reset - DateTimeOffset.UtcNow) + " · " + reset.LocalDateTime.ToString("g") : "unknown")} Sample age: {Display.Duration(DateTimeOffset.UtcNow - w.SampleTime)}" +
(pace.Projection is { } projection ? $" Reaches 100%: {Display.Projection(projection)}" : "")));
} }
card.Children.Add(Ui.Text("Tokens · provider totals", 15)); content.Add(Ui.Columns(tiles, limitColumns));
card.Children.Add(Ui.Text("Today " + Display.Tokens(provider.Today))); var longWindows = model.History.Details.Where(d => d.Days is not null && providers.Any(p => p.Provider == d.Provider &&
card.Children.Add(Ui.Text("Session " + Display.Tokens(provider.Session))); p.Status == ProviderStatus.Available && p.Windows.Any(w => w.Window.Id == d.Id))).ToArray();
card.Children.Add(Ui.Text("Week " + Display.Tokens(provider.Week))); if (longWindows.Length > 0)
card.Children.Add(Ui.Text("Cache read is included in Codex input; reasoning is included in output.", 11)); {
body.Children.Add(Ui.Card(card)); content.Add(Ui.Text("Week use per day", 20));
content.Add(Ui.Columns(longWindows.GroupBy(d => d.Provider).Select(group =>
{
var entries = group.ToArray();
var index = Array.FindIndex(entries, d => d.Id == selectedDailyWindow.GetValueOrDefault(group.Key));
if (index < 0) index = 0;
var labels = entries.Select(d => providers.SelectMany(p => p.Windows).First(w => w.Window.Provider == d.Provider && w.Window.Id == d.Id).Window.Label).ToArray();
Control DayView(LimitDetail item) => item.Days!.Current.Any(d => d.Used is not null)
? new DailyLimitChart(item.Days, item.Provider)
: Ui.Text($"Collecting history since {(item.Since ?? providers.SelectMany(p => p.Windows).First(w => w.Window.Provider == item.Provider && w.Window.Id == item.Id).Window.SampleTime).LocalDateTime:dd.MM. HH:mm}", 12, "Muted");
var chart = new Border { Child = DayView(entries[index]) };
var title = Ui.Text(group.Key + " · " + labels[index], 15);
var stack = Ui.Stack(title);
var explanation = Ui.Text("Measured · Estimated from tokens (hatched) · faint: previous window, same day of the window", 12, "Muted");
void UpdateExplanation(LimitDetail item) => explanation.IsVisible = item.Days!.Current.Any(d => d.Used is not null);
UpdateExplanation(entries[index]);
if (entries.Length > 1)
{
var selector = new WindowSelector { ItemsSource = labels, SelectedIndex = index };
selector.SelectionChanged += (_, _) =>
{
if (selector.SelectedIndex < 0) return;
var item = entries[selector.SelectedIndex]; selectedDailyWindow[group.Key] = item.Id;
title.Text = group.Key + " · " + labels[selector.SelectedIndex];
chart.Child = DayView(item);
UpdateExplanation(item);
};
stack.Children.Add(selector);
} }
stack.Children.Add(explanation);
stack.Children.Add(chart); return Ui.Card(stack);
}), wide));
}
var tokenHeader = new DockPanel();
var toggle = new NeutralCheckBox { Content = "Include cache reads", IsChecked = model.IncludeCacheReads, HorizontalAlignment = HorizontalAlignment.Right };
toggle.IsCheckedChanged += (_, _) => model.IncludeCacheReads = toggle.IsChecked == true;
DockPanel.SetDock(toggle, Dock.Right); tokenHeader.Children.Add(toggle);
var tokenTitle = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 24, VerticalAlignment = VerticalAlignment.Center };
tokenTitle.Children.Add(Ui.Text("Tokens", 20)); tokenTitle.Children.Add(CompositionLegend()); tokenHeader.Children.Add(tokenTitle); content.Add(tokenHeader);
var totals = providers.Select(p =>
{
var row = new WrapPanel();
row.Children.Add(TokenTile(p, "Today", p.Today));
if (p.Session is { } session && p.Windows.Any(w => w.Window.Length <= TimeSpan.FromDays(1))) row.Children.Add(TokenTile(p, "Current session", session));
row.Children.Add(TokenTile(p, "This week", p.Week));
return (Control)Ui.Card(Ui.Stack(Ui.Text(p.Provider.ToString(), 15), row));
});
content.Add(Ui.Columns(totals, wide));
} }
var h = model.History; var h = model.History;
body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), Legend(h.Hourly), new UsageChart { Values = h.Hourly }))); var seriesNames = h.Hourly.Concat(h.Daily).Select(v => v.Series).Distinct().Order(StringComparer.Ordinal).ToArray();
body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per day", 19), Legend(h.Daily), new UsageChart { Values = h.Daily, Interval = TimeSpan.FromDays(1) }))); Control TokenChart(string title, IReadOnlyList<ChartValue> values, bool daily) => Ui.Card(Ui.Stack(Ui.Text(title, 15),
foreach (var limit in h.Limits) Legend(seriesNames), new UsageChart { Values = values.Select(v => v with { Value = Math.Max(0, v.Value - (model.IncludeCacheReads ? 0 : v.CacheRead)) }).ToArray(),
body.Children.Add(Ui.Card(Ui.Stack(Ui.Text(limit.Label, 19), Ui.Text("Blue: used · dashed green: expected pace · gaps: window reset", 11), new UsageChart { Values = limit.Values, Percent = true }))); SeriesNames = seriesNames, Interval = daily ? TimeSpan.FromDays(1) : TimeSpan.FromHours(1) }));
body.Children.Add(Breakdown("By model", h.Models)); content.Add(Ui.Columns([TokenChart("Tokens per hour", h.Hourly, false), TokenChart("Tokens per day", h.Daily, true)], wide));
body.Children.Add(Breakdown("By project", h.Projects)); var windows = h.Limits.Where(l => l.Analysis?.Current.HasData == true).ToArray();
var diagnostics = Ui.Stack(Ui.Text("Recent diagnostics", 19)); if (windows.Length > 0)
foreach (var d in model.Diagnostics) diagnostics.Children.Add(Ui.Text($"{d.Time.LocalDateTime:g} · {d.Provider} · {d.Code} · {d.Summary}")); {
if (model.Diagnostics.Count == 0) diagnostics.Children.Add(Ui.Text("No recent problems.")); content.Add(Ui.Text("Window charts", 20));
body.Children.Add(Ui.Card(diagnostics)); content.Add(Ui.Columns(windows.Select(limit => Ui.Card(Ui.Stack(Ui.Text(limit.Label, 15),
Ui.Text("Measured · dashed: estimated · faint: previous · dotted: forecast", 12, "Muted"), new BurnUpChart(limit),
Ui.Text("Past instances · peak use", 12, "Muted"), new InstancePeaks(limit.Analysis!.Past, limit.Provider)))), wide));
} }
private static Control Legend(IReadOnlyList<ChartValue> values) content.Add(Ui.Text("Breakdown", 20));
content.Add(Ui.Card(new BreakdownTable("By model", h.Models, false, model.ProviderFilter, modelBreakdown)));
content.Add(Ui.Card(new BreakdownTable("By project", h.Projects, true, model.ProviderFilter, projectBreakdown)));
if (model.Diagnostics.Count > 0)
{ {
var legend = new WrapPanel { Orientation = Orientation.Horizontal }; var lines = Ui.Stack();
var index = 0; foreach (var d in model.Diagnostics) lines.Children.Add(Ui.Text($"{d.Time.LocalDateTime:g} · {d.Provider} · {d.Code} · {d.Summary} ({d.Count})", 12, "Secondary"));
foreach (var series in values.Select(v => v.Series).Distinct()) content.Add(Ui.Card(new Expander { Header = $"Diagnostics ({model.Diagnostics.Count})", Content = lines, IsExpanded = false }));
}
body.Children.Clear(); foreach (var control in content) body.Children.Add(control);
scroll.UpdateLayout(); scroll.Offset = offset;
}
private Control LimitTile(WindowSnapshot window, DateTimeOffset now)
{ {
var label = Ui.Text("● " + series, 12); label.Foreground = UsageChart.SeriesColour(index++); var w = window.Window; var pace = window.Pace;
label.Margin = new Thickness(0, 0, 14, 0); legend.Children.Add(label); var detail = model.History.Details.FirstOrDefault(d => d.Provider == w.Provider && d.Id == w.Id);
var title = new DockPanel();
var chip = new Border { Child = Ui.Mark(Display.State(pace.State), Brush.Parse("#0b0b0b")), Background = PaceBar.Colour(pace.State), CornerRadius = new CornerRadius(6), Padding = new Thickness(8, 4) };
DockPanel.SetDock(chip, Dock.Right); title.Children.Add(chip); title.Children.Add(Ui.Text(w.Provider + " · " + w.Label, 15));
var card = Ui.Stack(title, Ui.Text($"{w.UsedPercent:0.#} %", 36), Ui.Text("used", 12, "Muted"), new PaceBar(window) { Height = 10 });
card.Children.Add(Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {Display.Projection(reset)}" : "Reset unknown", 13, "Secondary"));
if (pace.Projection is { } projection)
{
var caption = Display.Forecast(projection, pace.State) + $" ({Display.Duration(w.ResetsAt!.Value - projection)} before reset)";
if (pace.State == PaceState.Ahead)
{
var line = new DockPanel(); var mark = Ui.Mark("⚠ ", Brush.Parse("#d03b3b"), 13);
DockPanel.SetDock(mark, Dock.Left); line.Children.Add(mark); line.Children.Add(Ui.Text(caption[2..], 13, "Secondary")); card.Children.Add(line);
}
else card.Children.Add(Ui.Text(caption, 13, "Secondary"));
}
else if (LimitAnalysis.AverageUseAtReset(w, now, pace) is { } average)
card.Children.Add(Ui.Text($"≈ {average:0.#} % at reset", 13, "Secondary"));
else if (Display.ForecastWaiting(window, now) is { } waiting)
card.Children.Add(Ui.Text(waiting, 13, "Muted"));
if (detail?.Recent is { } recent)
{
var line = Ui.Text($"Last {Display.Span(recent.Span)}: +{recent.Increase:0.#} %" + (recent.ReachesLimit is { } date ? $" · 100 % on {Display.Projection(date)}" : $" · ≈ {recent.UseAtReset:0.#} % at reset"), 13, "Secondary");
ToolTip.SetTip(line, new DataTooltip("Recent rate", new("Rate", $"{recent.PercentPerDay:0.##} %/day"), new("Observed span", Display.Duration(recent.Span)))); card.Children.Add(line);
}
if (detail?.Days is { } days)
{
card.Children.Add(Ui.Text(days.Today is { } today ? days.TodayOrigin == UseOrigin.Estimated
? $"Today ≈ +{today:0.#} % of the week (estimated)" : $"Today +{today:0.#} % of the week" : "Today · collecting a day baseline", 15));
card.Children.Add(Ui.Text($"Even pace {days.EvenPace:0.#} %/day", 13, "Secondary"));
if (days.DailyBudget is { } budget) card.Children.Add(Ui.Text($"Budget {budget:0.#} %/day for {Display.Duration(w.ResetsAt!.Value - now)}", 15));
}
if (now - w.SampleTime > model.ProbeInterval * 2) card.Children.Add(Ui.Text($"⚠ sample {Display.Duration(now - w.SampleTime)} old", 12, "Muted"));
var tile = Ui.Card(card); tile.Name = $"LimitTile-{w.Provider}-{w.Id}";
ToolTip.SetTip(tile, new DataTooltip(w.Provider + " · " + w.Label, new("Used", $"{w.UsedPercent:0.##} %"), new("Expected", $"{pace.ElapsedFraction * 100:0.##} %"),
new("State", Display.State(pace.State)), new("Reset", w.ResetsAt is { } r ? Display.Projection(r) : "Unknown"), new("Sample", w.SampleTime.LocalDateTime.ToString("g")))); return tile;
}
private Control TokenTile(ProviderSnapshot provider, string label, TokenCounts counts)
{
var tile = Ui.Stack(Ui.Text(label, 12, "Secondary"), Ui.Text(Display.Compact(Math.Max(0, counts.Total - (model.IncludeCacheReads ? 0 : counts.CacheRead))), 32),
new CompositionBar(counts, provider.Provider, model.IncludeCacheReads) { Height = 6 });
tile.Width = wide ? 164 : 188; tile.Margin = new Thickness(0, 8, 16, 0);
ToolTip.SetTip(tile, DataTooltip.Tokens(provider.Provider + " · " + label, counts)); return tile;
}
private Control CompositionLegend()
{
var panel = new WrapPanel { Name = "CompositionLegend", VerticalAlignment = VerticalAlignment.Center }; var colour = model.ProviderFilter is { } provider
? Ui.ProviderColour(provider, Ui.Dark(this)) : Ui.Colour("Secondary", Ui.Dark(this));
var labels = new[] { "Input", "Output", "Cache write", "Cache read" };
for (var i = 0; i < labels.Length; i++)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, Margin = new Thickness(0, 0, 6, 0) };
row.Children.Add(new Border { Background = i == 3 ? Ui.Colour("Cache", Ui.Dark(this)) : colour,
Opacity = i == 1 ? .65 : i == 2 ? .4 : 1, Width = 5, Height = 5, CornerRadius = new CornerRadius(2), VerticalAlignment = VerticalAlignment.Center });
row.Children.Add(Ui.Text(labels[i], 11, "Muted")); panel.Children.Add(row);
}
return panel;
}
private Control Legend(string[] names)
{
var legend = new WrapPanel();
foreach (var name in names)
{
var item = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 };
item.Children.Add(Ui.Mark("●", UsageChart.SeriesColour(name, names, Ui.Dark(this)))); item.Children.Add(Ui.Text(name, 12, "Secondary"));
item.Margin = new Thickness(0, 0, 16, 0); legend.Children.Add(item);
} }
return legend; return legend;
} }
private static Border Breakdown(string title, IReadOnlyList<BreakdownRow> rows) public static string[] ShortProjectNames(string[] paths)
{ {
var table = Ui.Stack(Ui.Text(title, 19)); var parts = paths.Select(p => p.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries)).ToArray();
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("3*,1*,1*,1*,1*,1*,1*,1*"), MinWidth = 900 }; return parts.Select((p, i) =>
var headers = new[] { "Name", "Total", "Share", "Input", "Cache read", "Cache write", "Output", "Reasoning" };
AddRow(headers, 0);
var index = 1;
foreach (var row in rows)
{ {
var c = row.Counts; var depth = Math.Min(2, p.Length);
AddRow([row.Name, c.Total.ToString("N0"), row.Share.ToString("P1"), c.Input.ToString("N0"), c.CacheRead.ToString("N0"), while (depth < p.Length && parts.Where((_, j) => j != i).Any(other => string.Join('/', other.TakeLast(depth)) == string.Join('/', p.TakeLast(depth)))) depth++;
c.CacheWrite.ToString("N0"), c.Output.ToString("N0"), c.ReasoningOutput.ToString("N0")], index++); return string.Join('/', p.TakeLast(depth));
}).ToArray();
} }
table.Children.Add(new ScrollViewer { Content = grid, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, // Leave wheel events unhandled so they bubble to the page instead of changing selection.
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled }); private sealed class WindowSelector : ComboBox
if (rows.Count == 0) table.Children.Add(Ui.Text("No tokens in this range."));
return Ui.Card(table);
void AddRow(string[] values, int row)
{ {
grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); protected override Type StyleKeyOverride => typeof(ComboBox);
for (var column = 0; column < values.Length; column++) protected override void OnPointerWheelChanged(Avalonia.Input.PointerWheelEventArgs e) { }
{
var text = Ui.Text(values[column], 11); text.Margin = new Thickness(0, 4, 8, 4);
Grid.SetRow(text, row); Grid.SetColumn(text, column); grid.Children.Add(text);
}
}
} }
public static int LimitColumnCount(double contentWidth) => contentWidth >= 1400 ? 3 : contentWidth >= 1200 ? 2 : 1;
} }
+4 -7
View File
@@ -13,8 +13,7 @@ public sealed class PopupWindow : Window
{ {
public PopupWindow(string title, string message, Action open, string? installLabel = null, Action? install = null, Action? dismiss = null, IBrush? accent = null) public PopupWindow(string title, string message, Action open, string? installLabel = null, Action? install = null, Action? dismiss = null, IBrush? accent = null)
{ {
Width = 380; Height = install is null ? 145 : 180; Width = 400; Height = install is null ? 152 : 184; Ui.Theme(this);
RequestedThemeVariant = ThemeVariant.Dark;
WindowDecorations = WindowDecorations.None; CanResize = false; Topmost = true; ShowInTaskbar = false; ShowActivated = false; WindowDecorations = WindowDecorations.None; CanResize = false; Topmost = true; ShowInTaskbar = false; ShowActivated = false;
var body = Ui.Stack(Ui.Text(title, 19), Ui.Text(message)); var body = Ui.Stack(Ui.Text(title, 19), Ui.Text(message));
if (install is not null) if (install is not null)
@@ -24,10 +23,8 @@ public sealed class PopupWindow : Window
actions.Children.Add(Ui.Button("Not now", () => { dismiss?.Invoke(); Close(); })); actions.Children.Add(Ui.Button("Not now", () => { dismiss?.Invoke(); Close(); }));
body.Children.Add(actions); body.Children.Add(actions);
} }
var card = Ui.Card(body); card.Background = Brush.Parse("#202C40"); var card = Ui.Card(body);
body.Resources["TextControlForeground"] = Brushes.WhiteSmoke; if (accent is not null) { card.Resources["Border"] = accent; card.BorderThickness = new Thickness(3, 1, 1, 1); }
foreach (var text in body.Children.OfType<TextBlock>()) text.Foreground = Brushes.WhiteSmoke;
((TextBlock)body.Children[0]).Foreground = accent ?? Brushes.WhiteSmoke;
Content = card; Content = card;
PointerPressed += (_, e) => PointerPressed += (_, e) =>
{ {
@@ -38,7 +35,7 @@ public sealed class PopupWindow : Window
} }
public static PopupWindow Pace(PopupEvent alert, Action open) => new($"{alert.Provider} · {Display.State(alert.State)}", public static PopupWindow Pace(PopupEvent alert, Action open) => new($"{alert.Provider} · {Display.State(alert.State)}",
$"{alert.Label}: {alert.Delta:+0.0;-0.0;0} points from pace." + $"{alert.Label}: {alert.Delta:+0.0;-0.0;0} points from pace." +
(alert.Projection is { } projection ? $" At this rate: 100% at {Display.Projection(projection)}." : ""), open, accent: PaceBar.Colour(alert.State)); (alert.Projection is { } projection ? "\n" + Display.Forecast(projection, alert.State) : ""), open, accent: PaceBar.Colour(alert.State));
} }
public sealed class PopupStack(Action open, TimeProvider? clock = null) : IDisposable public sealed class PopupStack(Action open, TimeProvider? clock = null) : IDisposable
+84 -35
View File
@@ -1,5 +1,6 @@
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Layout;
using FinalToken.Core; using FinalToken.Core;
using FinalToken.Core.StreamDeck; using FinalToken.Core.StreamDeck;
@@ -7,30 +8,62 @@ namespace FinalToken.App;
public sealed class SettingsWindow : Window public sealed class SettingsWindow : Window
{ {
public SettingsWindow(Settings initial, PluginInstallStatus status, Func<Settings, Task> save) public SettingsWindow(Settings initial, PluginInstallStatus status, Func<Settings, Task> save, Action? quit = null, Action<string>? openFolder = null)
{ {
Title = "FinalToken settings"; Width = 620; Height = 800; Title = "FinalToken settings"; Width = 760; Height = 900; MinWidth = 600; MinHeight = 500; Ui.Theme(this);
var body = Ui.Stack(Ui.Text("Settings", 26)); body.Margin = new Thickness(24); var body = new StackPanel { Spacing = 16, Margin = new Thickness(24) };
var refresh = Number("Token refresh (seconds, 1–60)", (decimal)initial.RefreshInterval.TotalSeconds, 1, 60); body.Children.Add(Ui.Text("Settings", 24));
var probe = Number("Limit probe (minutes, 1–60)", (decimal)initial.ProbeInterval.TotalMinutes, 1, 60); var general = Ui.Stack(Ui.Text("General", 15));
var threshold = Number("Pace threshold (points)", (decimal)initial.PaceThreshold, 0.1m, 100); var refresh = Number(general, "Token refresh (seconds, 1–60)", (decimal)initial.RefreshInterval.TotalSeconds, 1, 60);
var ahead = Check("Ahead popups", initial.PopupAhead); var behind = Check("Behind popups", initial.PopupBehind); var probe = Number(general, "Limit probe (minutes, 1–60)", (decimal)initial.ProbeInterval.TotalMinutes, 1, 60);
var startup = Check("Start with the OS", initial.StartWithOs); var tray = Check("Close to tray", initial.CloseToTray); var threshold = Number(general, "Pace threshold (points)", (decimal)initial.PaceThreshold, 0.1m, 100);
var claude = ProviderControls("Claude", initial.Claude); var codex = ProviderControls("Codex", initial.Codex); var startup = Check(general, "Start with the OS", initial.StartWithOs);
body.Children.Add(Ui.Text("Stream Deck", 19)); var tray = Check(general, "Close to tray", initial.CloseToTray);
body.Children.Add(Ui.Text($"{status.State} · shipped {status.ShippedVersion ?? "none"} · installed {status.InstalledVersion ?? "none"}")); body.Children.Add(Ui.Card(general));
var mode = new ComboBox { ItemsSource = new[] { "Off", "Ask", "Automatic" }, SelectedIndex = (int)initial.StreamDeckInstallMode }; var popups = Ui.Stack(Ui.Text("Popups", 15));
body.Children.Add(mode); var ahead = Check(popups, "Ahead popups", initial.PopupAhead);
body.Children.Add(Ui.Text("Dismissed plugin version (clear to ask again)")); var behind = Check(popups, "Behind popups", initial.PopupBehind);
var dismissed = new TextBox { Text = initial.DismissedPluginVersion ?? "" }; body.Children.Add(dismissed); var claudePopups = PopupControls(popups, "Claude", initial.Claude);
var error = Ui.Text(""); body.Children.Add(error); var codexPopups = PopupControls(popups, "Codex", initial.Codex);
var button = new Button { Content = "Save", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right }; body.Children.Add(Ui.Card(popups));
var providers = Ui.Stack(Ui.Text("Providers", 15));
var claude = ProviderControls(providers, "Claude", initial.Claude);
var codex = ProviderControls(providers, "Codex", initial.Codex);
body.Children.Add(Ui.Card(providers));
var streamDeck = Ui.Stack(Ui.Text("Stream Deck", 15), Ui.Text($"{status.State} · shipped {status.ShippedVersion ?? "none"} · installed {status.InstalledVersion ?? "none"}", 13, "Secondary"));
var selectedMode = initial.StreamDeckInstallMode;
streamDeck.Children.Add(PanelWindow.Segments(["Off", "Ask", "Automatic"], (int)selectedMode, i => selectedMode = (InstallMode)i));
streamDeck.Children.Add(Ui.Text("Dismissed plugin version (clear to ask again)", 12, "Secondary"));
var dismissed = new TextBox { Text = initial.DismissedPluginVersion ?? "" }; streamDeck.Children.Add(dismissed);
body.Children.Add(Ui.Card(streamDeck));
var about = Ui.Stack(Ui.Text("About", 15), Ui.Text("FinalToken " + typeof(Program).Assembly.GetName().Version?.ToString(3)), Ui.Text(DataPaths.DataDirectory, 12, "Secondary"));
var error = Ui.Text("", 12, "Secondary");
about.Children.Add(Ui.Button("Open folder", () =>
{
try
{
if (openFolder is not null) openFolder(DataPaths.DataDirectory);
else System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(DataPaths.DataDirectory) { UseShellExecute = true });
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception or InvalidOperationException)
{ error.Text = "Could not open the data folder."; }
}));
body.Children.Add(Ui.Card(about));
var footer = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto,Auto"), ColumnSpacing = 8, Margin = new Thickness(24, 16) };
var quitButton = Ui.Button("Quit FinalToken", () => quit?.Invoke()); quitButton.IsEnabled = quit is not null;
footer.Children.Add(quitButton);
var cancel = Ui.Button("Cancel", Close); Grid.SetColumn(cancel, 2); footer.Children.Add(cancel);
var button = Ui.Button("Save", () => { }); Grid.SetColumn(button, 3); footer.Children.Add(button);
button.Click += async (_, _) => button.Click += async (_, _) =>
{ {
var value = initial with { RefreshInterval = TimeSpan.FromSeconds((double)(refresh.Value ?? 0)), ProbeInterval = TimeSpan.FromMinutes((double)(probe.Value ?? 0)), var value = initial with
{
RefreshInterval = TimeSpan.FromSeconds((double)(refresh.Value ?? 0)), ProbeInterval = TimeSpan.FromMinutes((double)(probe.Value ?? 0)),
PaceThreshold = (double)(threshold.Value ?? 0), PopupAhead = ahead.IsChecked == true, PopupBehind = behind.IsChecked == true, PaceThreshold = (double)(threshold.Value ?? 0), PopupAhead = ahead.IsChecked == true, PopupBehind = behind.IsChecked == true,
StartWithOs = startup.IsChecked == true, CloseToTray = tray.IsChecked == true, Claude = claude(), Codex = codex(), StartWithOs = startup.IsChecked == true, CloseToTray = tray.IsChecked == true,
StreamDeckInstallMode = (InstallMode)mode.SelectedIndex, DismissedPluginVersion = string.IsNullOrWhiteSpace(dismissed.Text) ? null : dismissed.Text.Trim() }; Claude = claudePopups(claude()), Codex = codexPopups(codex()), StreamDeckInstallMode = selectedMode,
DismissedPluginVersion = string.IsNullOrWhiteSpace(dismissed.Text) ? null : dismissed.Text.Trim()
};
if (!value.IsValid) { error.Text = "Check the intervals and pace threshold."; return; } if (!value.IsValid) { error.Text = "Check the intervals and pace threshold."; return; }
button.IsEnabled = false; button.IsEnabled = false;
try { await save(value); Close(); } try { await save(value); Close(); }
@@ -38,21 +71,37 @@ public sealed class SettingsWindow : Window
catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException) catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
{ error.Text = "Could not apply settings: " + e.Message; button.IsEnabled = true; } { error.Text = "Could not apply settings: " + e.Message; button.IsEnabled = true; }
}; };
body.Children.Add(button); Content = new ScrollViewer { Content = body }; var dock = new DockPanel();
var bottom = Ui.Stack(error, footer); DockPanel.SetDock(bottom, Dock.Bottom); dock.Children.Add(bottom);
NumericUpDown Number(string label, decimal value, decimal min, decimal max) dock.Children.Add(new ScrollViewer { Content = body }); Content = dock;
{ body.Children.Add(Ui.Text(label)); var c = new NumericUpDown { Value = value, Minimum = min, Maximum = max }; body.Children.Add(c); return c; }
CheckBox Check(string label, bool value)
{ var c = new CheckBox { Content = label, IsChecked = value }; body.Children.Add(c); return c; }
Func<ProviderSettings> ProviderControls(string name, ProviderSettings config)
{
body.Children.Add(Ui.Text(name, 19));
var enabled = Check("Enabled", config.Enabled); var popups = Check("Popups enabled", config.PopupsEnabled);
var pa = Check("Ahead", config.PopupAhead); var pb = Check("Behind", config.PopupBehind);
body.Children.Add(Ui.Text("CLI path (empty uses PATH)"));
var path = new TextBox { Name = name + "CliPath", Text = config.CliPath ?? "" }; body.Children.Add(path);
return () => config with { Enabled = enabled.IsChecked == true, PopupsEnabled = popups.IsChecked == true, PopupAhead = pa.IsChecked == true,
PopupBehind = pb.IsChecked == true, CliPath = string.IsNullOrWhiteSpace(path.Text) ? null : path.Text.Trim() };
} }
private static NumericUpDown Number(StackPanel parent, string label, decimal value, decimal min, decimal max)
{
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,160"), ColumnSpacing = 16 };
grid.Children.Add(Ui.Text(label, 13, "Secondary"));
var control = new NumericUpDown { Value = value, Minimum = min, Maximum = max }; Grid.SetColumn(control, 1); grid.Children.Add(control);
parent.Children.Add(grid); return control;
}
private static CheckBox Check(StackPanel parent, string label, bool value)
{
var c = new NeutralCheckBox { Content = label, IsChecked = value, Name = label.Replace(" ", "") }; parent.Children.Add(c); return c;
}
private static Func<ProviderSettings, ProviderSettings> PopupControls(StackPanel parent, string name, ProviderSettings config)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 16 };
row.Children.Add(Ui.Text(name));
var enabled = Check(row, "Popups enabled", config.PopupsEnabled);
var ahead = Check(row, "Ahead", config.PopupAhead); var behind = Check(row, "Behind", config.PopupBehind);
foreach (var c in row.Children.OfType<CheckBox>()) c.Name = name + c.Name;
parent.Children.Add(row);
return value => value with { PopupsEnabled = enabled.IsChecked == true, PopupAhead = ahead.IsChecked == true, PopupBehind = behind.IsChecked == true };
}
private static Func<ProviderSettings> ProviderControls(StackPanel parent, string name, ProviderSettings config)
{
parent.Children.Add(Ui.Text(name)); var enabled = Check(parent, "Enabled", config.Enabled);
enabled.Name = name + "Enabled";
parent.Children.Add(Ui.Text("CLI path (empty uses PATH)", 12, "Secondary"));
var path = new TextBox { Name = name + "CliPath", Text = config.CliPath ?? "" }; parent.Children.Add(path);
return () => config with { Enabled = enabled.IsChecked == true, CliPath = string.IsNullOrWhiteSpace(path.Text) ? null : path.Text.Trim() };
} }
} }
+139
View File
@@ -0,0 +1,139 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Styling;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Templates;
using Avalonia.Markup.Xaml.MarkupExtensions;
using Avalonia.Themes.Fluent;
using FinalToken.Core;
namespace FinalToken.App;
public static class Ui
{
public static IBrush Colour(string role, bool dark) => Brush.Parse(role switch
{
"Page" => dark ? "#0d0d0d" : "#f9f9f7",
"Surface" => dark ? "#1a1a19" : "#fcfcfb",
"Border" => dark ? "#1affffff" : "#1a0b0b0b",
"Ink" => dark ? "#f0efec" : "#0b0b0b",
"Secondary" => dark ? "#c3c2b7" : "#52514e",
"Grid" => dark ? "#2c2c2a" : "#e1e0d9",
"Axis" => dark ? "#383835" : "#c3c2b7",
"Selection" => dark ? "#383835" : "#e1e0d9",
"Claude" => dark ? "#d95926" : "#eb6834",
"Codex" => dark ? "#3987e5" : "#2a78d6",
"Cache" => dark ? "#5c5b57" : "#c3c2b7",
_ => "#898781"
});
public static bool Dark(StyledElement element) => element.ActualThemeVariant == ThemeVariant.Dark;
public static IBrush ProviderColour(Provider provider, bool dark) => Colour(provider.ToString(), dark);
public static void Theme(Window window)
{
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var resources = new ResourceDictionary();
foreach (var role in new[] { "Page", "Surface", "Border", "Ink", "Secondary", "Muted", "Grid", "Axis", "Selection", "Claude", "Codex", "Cache" })
resources[role] = Colour(role, theme == ThemeVariant.Dark);
window.Resources.ThemeDictionaries[theme] = resources;
}
window.Bind(TemplatedControl.BackgroundProperty, window.GetResourceObservable("Page"));
window.Bind(TemplatedControl.ForegroundProperty, window.GetResourceObservable("Ink"));
window.FontSize = 13;
var segments = new Style(s => s.OfType<ToggleButton>().Class("segment"));
segments.Setters.Add(new Setter(TemplatedControl.BackgroundProperty, new DynamicResourceExtension("Surface")));
segments.Setters.Add(new Setter(TemplatedControl.ForegroundProperty, new DynamicResourceExtension("Ink")));
segments.Setters.Add(new Setter(TemplatedControl.TemplateProperty, new FuncControlTemplate<ToggleButton>((button, _) =>
{
var presenter = new ContentPresenter { HorizontalContentAlignment = HorizontalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center };
presenter.Bind(ContentPresenter.ContentProperty, button.GetObservable(ContentControl.ContentProperty));
presenter.Bind(ContentPresenter.ForegroundProperty, button.GetObservable(TemplatedControl.ForegroundProperty));
presenter.Bind(ContentPresenter.FontWeightProperty, button.GetObservable(TemplatedControl.FontWeightProperty));
var border = new Border { Child = presenter, Padding = new Thickness(8, 6), CornerRadius = new CornerRadius(4) };
border.Bind(Border.BackgroundProperty, button.GetObservable(TemplatedControl.BackgroundProperty));
border.BorderThickness = new Thickness(1); border.Bind(Border.BorderBrushProperty, button.GetObservable(TemplatedControl.BorderBrushProperty));
return border;
})));
window.Styles.Add(segments);
var focusSegment = new Style(s => s.OfType<ToggleButton>().Class("segment").Class(":focus-visible"));
focusSegment.Setters.Add(new Setter(TemplatedControl.BorderBrushProperty, new DynamicResourceExtension("Ink"))); window.Styles.Add(focusSegment);
var selected = new Style(s => s.OfType<ToggleButton>().Class("segment").Class(":checked"));
selected.Setters.Add(new Setter(TemplatedControl.BackgroundProperty, new DynamicResourceExtension("Selection")));
selected.Setters.Add(new Setter(TemplatedControl.FontWeightProperty, FontWeight.SemiBold)); window.Styles.Add(selected);
var checks = new Style(s => s.OfType<NeutralCheckBox>());
checks.Setters.Add(new Setter(TemplatedControl.BorderBrushProperty, Brushes.Transparent));
checks.Setters.Add(new Setter(TemplatedControl.TemplateProperty, new FuncControlTemplate<NeutralCheckBox>((check, _) =>
{
var glyph = Text("✓", 14); glyph.Name = "NeutralCheckGlyph"; glyph.HorizontalAlignment = HorizontalAlignment.Center;
var box = new Border { Name = "NeutralCheckSurface", Child = glyph, Width = 20, Height = 20, CornerRadius = new CornerRadius(4),
BorderThickness = new Thickness(1), VerticalAlignment = VerticalAlignment.Center };
box.Bind(Border.BackgroundProperty, box.GetResourceObservable("Selection")); box.Bind(Border.BorderBrushProperty, box.GetResourceObservable("Axis"));
glyph.Bind(Visual.IsVisibleProperty, check.GetObservable(NeutralCheckBox.MarkVisibleProperty));
var label = new ContentPresenter { Margin = new Thickness(8, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center };
label.Bind(ContentPresenter.ContentProperty, check.GetObservable(ContentControl.ContentProperty));
label.Bind(ContentPresenter.ForegroundProperty, label.GetResourceObservable("Ink"));
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("20,*"), MinHeight = 32 };
grid.Children.Add(box); Grid.SetColumn(label, 1); grid.Children.Add(label);
var focus = new Border { Child = grid, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(4) };
focus.Bind(Border.BorderBrushProperty, check.GetObservable(TemplatedControl.BorderBrushProperty)); return focus;
})));
window.Styles.Add(checks);
var focusCheck = new Style(s => s.OfType<NeutralCheckBox>().Class(":focus-visible"));
focusCheck.Setters.Add(new Setter(TemplatedControl.BorderBrushProperty, new DynamicResourceExtension("Ink"))); window.Styles.Add(focusCheck);
}
// Explicit palettes keep every remaining Fluent control independent of the OS accent.
public static FluentTheme NeutralTheme()
{
var theme = new FluentTheme();
theme.Palettes[ThemeVariant.Dark] = new ColorPaletteResources { Accent = Color.Parse("#383835") };
theme.Palettes[ThemeVariant.Light] = new ColorPaletteResources { Accent = Color.Parse("#e1e0d9") };
return theme;
}
public static TextBlock Text(string text, double size = 13, string role = "Ink")
{
var block = new TextBlock { Text = text, FontSize = size, TextWrapping = TextWrapping.Wrap };
block.Bind(TextBlock.ForegroundProperty, block.GetResourceObservable(role));
return block;
}
public static TextBlock Mark(string text, IBrush colour, double size = 12) => new() { Text = text, FontSize = size, Foreground = colour };
public static TextBlock TableNumber(string text, double size = 13, string role = "Ink")
{
var block = Text(text, size, role); block.FontFeatures = FontFeatureCollection.Parse("tnum"); return block;
}
public static StackPanel Stack(params Control[] children)
{
var stack = new StackPanel { Spacing = 8 };
foreach (var child in children) stack.Children.Add(child);
return stack;
}
public static Border Card(Control content)
{
var card = new Border { Child = content, Padding = new Thickness(16), CornerRadius = new CornerRadius(10), BorderThickness = new Thickness(1) };
card.Bind(Border.BackgroundProperty, card.GetResourceObservable("Surface"));
card.Bind(Border.BorderBrushProperty, card.GetResourceObservable("Border"));
return card;
}
public static Button Button(string text, Action action)
{
var button = new Button { Content = text, Padding = new Thickness(12, 6) };
button.Click += (_, _) => action();
return button;
}
public static Control Columns(IEnumerable<Control> children, bool wide) => Columns(children, wide ? 2 : 1);
public static Control Columns(IEnumerable<Control> children, int columns)
{
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions(string.Join(',', Enumerable.Repeat("*", columns))), ColumnSpacing = 16, RowSpacing = 16 };
var index = 0;
foreach (var child in children)
{
child.VerticalAlignment = VerticalAlignment.Top;
if (index % columns == 0) grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
Grid.SetColumn(child, index % columns); Grid.SetRow(child, index / columns);
grid.Children.Add(child); index++;
}
return grid;
}
}
+1
View File
@@ -45,6 +45,7 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root
Codex replay protection uses the last session timestamp and cumulative counts, with no Codex replay protection uses the last session timestamp and cumulative counts, with no
per-event dedupe keys. A later counter reset still permits subsequent increases. per-event dedupe keys. A later counter reset still permits subsequent increases.
- Store changed percent/reset samples and at most one unchanged sample per window per hour. - Store changed percent/reset samples and at most one unchanged sample per window per hour.
A reset that moves within 15 minutes is unchanged for sampling and instance identity (D7).
Late observations from archived files use neighbouring timestamps so they keep real changes Late observations from archived files use neighbouring timestamps so they keep real changes
without inserting redundant unchanged points. Bucket lookup is O(1); stored limit points have without inserting redundant unchanged points. Bucket lookup is O(1); stored limit points have
a per-window time index for ordered lookup. a per-window time index for ordered lookup.
+12 -2
View File
@@ -5,6 +5,7 @@ namespace FinalToken.Core;
public sealed record TokenBucket(Provider Provider, DateTimeOffset Hour, string? Model, string? Project, TokenCounts Counts); public sealed record TokenBucket(Provider Provider, DateTimeOffset Hour, string? Model, string? Project, TokenCounts Counts);
public sealed record TokenPoint(DateTimeOffset Time, TokenCounts Counts); public sealed record TokenPoint(DateTimeOffset Time, TokenCounts Counts);
public sealed record ModelTokenPoint(DateTimeOffset Time, string? Model, TokenCounts Counts);
public sealed record TokenBreakdown(string? Name, TokenCounts Counts); public sealed record TokenBreakdown(string? Name, TokenCounts Counts);
public enum SeriesInterval { Hour, Day } public enum SeriesInterval { Hour, Day }
@@ -185,10 +186,10 @@ public sealed class HistoryStore
if (GetPartition(later).NextLimit(window) is { } found) { chronologicalNext = found; break; } if (GetPartition(later).NextLimit(window) is { } found) { chronologicalNext = found; break; }
} }
if (chronologicalPrevious is not null && window.UsedPercent == chronologicalPrevious.UsedPercent && if (chronologicalPrevious is not null && window.UsedPercent == chronologicalPrevious.UsedPercent &&
window.ResetsAt == chronologicalPrevious.ResetsAt && LimitAnalysis.SameInstance(window, chronologicalPrevious) &&
window.SampleTime - chronologicalPrevious.SampleTime < TimeSpan.FromHours(1)) continue; window.SampleTime - chronologicalPrevious.SampleTime < TimeSpan.FromHours(1)) continue;
if (chronologicalNext is not null && window.UsedPercent == chronologicalNext.UsedPercent && if (chronologicalNext is not null && window.UsedPercent == chronologicalNext.UsedPercent &&
window.ResetsAt == chronologicalNext.ResetsAt && LimitAnalysis.SameInstance(window, chronologicalNext) &&
chronologicalNext.SampleTime - window.SampleTime < TimeSpan.FromHours(1)) continue; chronologicalNext.SampleTime - window.SampleTime < TimeSpan.FromHours(1)) continue;
if (previous is null || window.SampleTime >= previous.SampleTime) if (previous is null || window.SampleTime >= previous.SampleTime)
state.LastSamples[key] = pending.LastSamples[key] = window; state.LastSamples[key] = pending.LastSamples[key] = window;
@@ -198,6 +199,7 @@ public sealed class HistoryStore
foreach (var provider in changedSets) pending.LatestWindows[provider] = state.LatestWindows[provider]; foreach (var provider in changedSets) pending.LatestWindows[provider] = state.LatestWindows[provider];
} }
} }
// D5: retain exact probe metadata; D7 tolerance applies only to instance identity and sampling.
private static (string, string, double, DateTimeOffset?, TimeSpan?, string) WindowValue(LimitWindow window) => private static (string, string, double, DateTimeOffset?, TimeSpan?, string) WindowValue(LimitWindow window) =>
(window.Id, window.Label, window.UsedPercent, window.ResetsAt, window.Length, window.Source); (window.Id, window.Label, window.UsedPercent, window.ResetsAt, window.Length, window.Source);
public IReadOnlyList<LimitWindow> LatestLimits(Provider provider) public IReadOnlyList<LimitWindow> LatestLimits(Provider provider)
@@ -227,6 +229,14 @@ public sealed class HistoryStore
} }
} }
public IReadOnlyList<TokenBreakdown> ByModel(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, true); public IReadOnlyList<TokenBreakdown> ByModel(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, true);
public IReadOnlyList<ModelTokenPoint> TokenSeriesByModel(Provider provider, DateTimeOffset from, DateTimeOffset to,
SeriesInterval interval, TimeZoneInfo? zone = null)
{
lock (gate) return Range(provider, from, to)
.GroupBy(b => (Time: interval == SeriesInterval.Hour ? b.Hour : CalendarDays.Start(b.Hour, zone), b.Model))
.OrderBy(g => g.Key.Time).ThenBy(g => g.Key.Model, StringComparer.Ordinal)
.Select(g => new ModelTokenPoint(g.Key.Time, g.Key.Model, Sum(g.Select(b => b.Counts)))).ToArray();
}
public IReadOnlyList<TokenBreakdown> ByProject(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, false); public IReadOnlyList<TokenBreakdown> ByProject(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, false);
private IReadOnlyList<TokenBreakdown> Breakdown(Provider provider, DateTimeOffset from, DateTimeOffset to, bool model) private IReadOnlyList<TokenBreakdown> Breakdown(Provider provider, DateTimeOffset from, DateTimeOffset to, bool model)
{ {
+49
View File
@@ -0,0 +1,49 @@
namespace FinalToken.Core;
public sealed record RateForecast(double PercentPerDay, double UseAtReset, DateTimeOffset? ReachesLimit,
double Increase = 0, TimeSpan Span = default);
public sealed record LimitDay(DateTimeOffset Start, DateTimeOffset End, double? Used, double? Cumulative,
bool IsToday, bool IsFuture, UseOrigin Origin = UseOrigin.Measured);
public sealed record WindowDays(IReadOnlyList<LimitDay> Current, IReadOnlyList<LimitDay> Previous,
double? Today, double EvenPace, double? DailyBudget, UseOrigin TodayOrigin = UseOrigin.Measured);
/// <summary>Pure D7 calculations. Missing baselines use marked token estimates when calibration is available.</summary>
public static partial class LimitAnalysis
{
/// <summary>D7: minute-rounded probe resets may drift within 15 minutes in either direction.</summary>
public static bool SameInstance(LimitWindow first, LimitWindow second) =>
first.Provider == second.Provider && first.Id == second.Id &&
first.ResetsAt is { } firstReset && second.ResetsAt is { } secondReset &&
(firstReset - secondReset).Duration() <= TimeSpan.FromMinutes(15);
public static double? AverageUseAtReset(LimitWindow window, DateTimeOffset now, PaceResult? pace = null)
{
pace ??= Pace.Calculate(window, now);
return Pace.CanForecast(window, now, pace) && pace.ElapsedFraction is > 0 and var elapsed ? window.UsedPercent / elapsed : null;
}
public static RateForecast? Recent(LimitWindow window, IEnumerable<LimitWindow> samples, DateTimeOffset now, PaceResult? pace = null)
{
pace ??= Pace.Calculate(window, now);
if (!Pace.CanForecast(window, now, pace) || window.ResetsAt is not { } reset || window.Length is not { Ticks: > 0 } length || reset <= now) return null;
var points = Instance(window, samples).Append(window).Where(s => s.SampleTime >= now.AddHours(-24) &&
s.SampleTime >= reset - length && s.SampleTime <= now).OrderBy(s => s.SampleTime).ToArray();
if (points.Length < 2) return null;
var first = points[0]; var last = points[^1];
var span = last.SampleTime - first.SampleTime;
if (span < TimeSpan.FromHours(3) || points.Zip(points.Skip(1)).Any(p => p.Second.UsedPercent < p.First.UsedPercent)) return null;
var rate = (last.UsedPercent - first.UsedPercent) / span.TotalDays;
var projected = window.UsedPercent + rate * (reset - now).TotalDays;
DateTimeOffset? reaches = null;
if (rate > 0 && projected > 100)
reaches = now.AddDays((100 - window.UsedPercent) / rate);
return new(rate, projected, reaches, last.UsedPercent - first.UsedPercent, span);
}
public static WindowDays? Days(LimitWindow window, IEnumerable<LimitWindow> samples, DateTimeOffset now, TimeZoneInfo? zone = null)
=> Analyze(window, samples, [], now, zone)?.Days;
private static IEnumerable<LimitWindow> Instance(LimitWindow window, IEnumerable<LimitWindow> samples) =>
samples.Where(s => SameInstance(window, s) &&
double.IsFinite(s.UsedPercent) && s.UsedPercent is >= 0 and <= 100);
}
+144
View File
@@ -0,0 +1,144 @@
namespace FinalToken.Core;
public enum UseOrigin { Measured, Estimated }
public sealed record LimitPoint(DateTimeOffset Time, double Used, UseOrigin Origin);
public sealed record LimitInstance(DateTimeOffset Start, DateTimeOffset Reset, IReadOnlyList<LimitPoint> Points,
IReadOnlyList<LimitDay> Days, double? Scale, double? Peak, DateTimeOffset? ReachedLimit, DateTimeOffset? EndedAt = null, UseOrigin? ReachedOrigin = null)
{
public DateTimeOffset End => EndedAt ?? Reset;
public bool HasData => Points.Count > 1;
}
public sealed record LimitEstimate(LimitInstance Current, IReadOnlyList<LimitInstance> Past, WindowDays? Days)
{
public LimitInstance? Previous => Past.FirstOrDefault();
}
public static partial class LimitAnalysis
{
private static DateTimeOffset Hour(DateTimeOffset time) => new(time.UtcTicks - time.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero);
/// <summary>D7: pure estimates from hourly token buckets, calibrated to the newest sample.
/// Boundary hours are included as in D5; estimates cannot recover sub-hour token timing.</summary>
public static LimitEstimate? Analyze(LimitWindow window, IEnumerable<LimitWindow> samples,
IReadOnlyList<ModelTokenPoint> tokens, DateTimeOffset now, TimeZoneInfo? zone = 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;
var observations = samples.Append(window).Where(s => s.Provider == window.Provider && s.Id == window.Id &&
s.ResetsAt is not null && s.Length is { Ticks: > 0 } && s.SampleTime <= now && double.IsFinite(s.UsedPercent) && s.UsedPercent is >= 0 and <= 100).OrderBy(s => s.SampleTime).ToArray();
var weighted = tokens.Where(p => TokenWeights.Matches(window, p.Model)).GroupBy(p => p.Time)
.Select(g => (Time: g.Key, Weight: g.Sum(p => TokenWeights.Weighted(window.Provider, p.Counts)))).OrderBy(p => p.Time).ToArray();
// D7: samples identify real instances; resets and lengths define their boundaries.
var groups = new List<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 current = Build(window, currentSpan.Start, currentSpan.End, now < currentSpan.End ? now : currentSpan.End, null);
var realPast = spans.Where(g => g.Start < currentSpan.Start).OrderByDescending(g => g.Start).ToArray();
var past = new List<LimitInstance>();
var realIndex = 0;
var cursor = currentSpan.Start;
for (var i = 0; i < 8; i++)
{
var canInfer = length > TimeSpan.FromDays(1);
if (!canInfer && realIndex == realPast.Length) break;
var inferredStart = cursor - length;
// A candidate overlapping the nearest real span yields to that whole span.
// A shorter gap stays unassigned. Sessions never produce inferred candidates.
var span = realIndex < realPast.Length && (!canInfer || realPast[realIndex].End > inferredStart)
? realPast[realIndex++]
: (Anchor: window with { ResetsAt = cursor }, Start: inferredStart, End: cursor);
var instance = Build(span.Anchor, span.Start, span.End, span.End < now ? span.End : now, current.Scale);
if (instance.HasData) past.Add(instance);
cursor = span.Start;
}
WindowDays? days = null;
if (length > TimeSpan.FromDays(1))
{
var today = current.Days.FirstOrDefault(d => d.IsToday);
days = new(current.Days, past.FirstOrDefault()?.Days ?? [], today?.Used, 100 / length.TotalDays,
reset > now ? (100 - window.UsedPercent) / (reset - now).TotalDays : null, today?.Origin ?? UseOrigin.Measured);
}
return new(current, past, days);
LimitInstance Build(LimitWindow anchor, DateTimeOffset start, DateTimeOffset end, DateTimeOffset until,
double? fallback)
{
double Weight(DateTimeOffset from, DateTimeOffset to)
{
var hour = Hour(from < start ? start : from);
var exclusiveEnd = Hour(end);
return weighted.Where(p => p.Time >= hour && p.Time < to && p.Time < exclusiveEnd).Sum(p => p.Weight);
}
var measured = Instance(anchor, observations).Where(s => s.SampleTime >= start - TimeSpan.FromMinutes(15) && s.SampleTime <= until)
.GroupBy(s => s.SampleTime).Select(g => g.Last()).OrderBy(s => s.SampleTime).ToArray();
var last = measured.LastOrDefault();
var denominator = last is null ? 0 : Weight(start, last.SampleTime);
var total = Weight(start, until);
double? scale = total <= 0 ? null : last is not null ? denominator > 0 ? last.UsedPercent / denominator : null : fallback;
var points = new SortedDictionary<DateTimeOffset, LimitPoint> { [start] = new(start, 0, UseOrigin.Measured) };
if (scale is { } k)
{
foreach (var time in weighted.Where(p => p.Time >= Hour(start) && p.Time < until && p.Time < Hour(end)).SelectMany(p => new[] { p.Time, p.Time.AddHours(1) }).Append(until).Distinct())
{
var cutoff = time < until ? time : until;
if (cutoff <= start) continue;
// Samples own the measured span; tokens fill before the first sample and after the last.
if (measured.Length == 0 || cutoff < measured[0].SampleTime)
points[cutoff] = new(cutoff, k * Weight(start, cutoff), UseOrigin.Estimated);
else if (last is not null && cutoff > last.SampleTime)
points[cutoff] = new(cutoff, last.UsedPercent + k * (Weight(start, cutoff) - Weight(start, last.SampleTime)), UseOrigin.Estimated);
}
}
foreach (var sample in measured) points[sample.SampleTime] = new(sample.SampleTime, sample.UsedPercent, UseOrigin.Measured);
DateTimeOffset? reached = null; UseOrigin? reachedOrigin = null;
var raw = points.Values.OrderBy(p => p.Time).ToArray();
for (var i = 1; i < raw.Length; i++)
{
var point = raw[i]; var prior = raw[i - 1];
if (reached is null && point.Used >= 100)
{
reached = point.Origin == UseOrigin.Measured || point.Used <= prior.Used ? point.Time
: prior.Time.AddTicks((long)((point.Time - prior.Time).Ticks * Math.Clamp((100 - prior.Used) / (point.Used - prior.Used), 0, 1)));
reachedOrigin = point.Origin;
if (point.Origin == UseOrigin.Estimated) points[reached.Value] = new(reached.Value, 100, UseOrigin.Estimated);
}
if (point.Origin == UseOrigin.Estimated)
points[point.Time] = point with { Used = reached is not null ? 100 : Math.Min(100, point.Used) };
}
double EstimatedAt(DateTimeOffset time, double factor) => reachedOrigin == UseOrigin.Estimated && time >= reached
? 100 : Math.Min(100, factor * Weight(start, time));
var daily = new List<LimitDay>();
for (var day = CalendarDays.Start(start, zone); day < end; day = CalendarDays.NextStart(day, zone))
{
var next = CalendarDays.NextStart(day, zone); var dayEnd = next < end ? next : end;
var cutoff = dayEnd < until ? dayEnd : until; var future = day > until;
var baseline = day <= start ? 0 : Last(day);
var cumulative = cutoff >= start ? Last(cutoff) : null;
if (last is not null && scale is not null && cutoff > last.SampleTime && Weight(start, cutoff) > Weight(start, last.SampleTime)) cumulative = null;
double? use = !future && baseline is { } b && cumulative is { } c ? Math.Max(0, c - b) : null;
var origin = UseOrigin.Measured;
if (!future && use is null && scale is { } factor)
{
use = Math.Max(0, EstimatedAt(cutoff, factor) - (day > start ? EstimatedAt(day, factor) : 0)); origin = UseOrigin.Estimated;
cumulative ??= EstimatedAt(cutoff, factor);
}
daily.Add(new(day, dayEnd, use, future ? null : cumulative, day == CalendarDays.Start(now, zone), future, origin));
}
var series = points.Values.OrderBy(p => p.Time).ToArray();
double? peak = series.Length > 1 ? series.Max(p => p.Used) : null;
return new(start, anchor.ResetsAt!.Value, series, daily, scale, peak, reached, end, reachedOrigin);
double? Last(DateTimeOffset time) => measured.LastOrDefault(s => s.SampleTime <= time)?.UsedPercent;
}
}
}
+14 -1
View File
@@ -2,6 +2,19 @@ namespace FinalToken.Core;
public static class Pace public static class Pace
{ {
// D7: use ticks at the boundary so exactly 10% is eligible despite floating-point rounding.
public static DateTimeOffset? ForecastStartsAt(LimitWindow window) =>
window.Length is { Ticks: > 0 } length && window.ResetsAt is { } reset
? reset - TimeSpan.FromTicks(length.Ticks - length.Ticks / 10) : null;
public static bool CanForecast(LimitWindow window, DateTimeOffset now, double threshold = 10) =>
CanForecast(window, now, Calculate(window, now, threshold));
// Reuse the configured pace, so every forecast agrees with the chip's Ahead state.
public static bool CanForecast(LimitWindow window, DateTimeOffset now, PaceResult pace) =>
pace.State != PaceState.Unknown && pace.ElapsedFraction is > 0 &&
ForecastStartsAt(window) is { } start && (now >= start || pace.State == PaceState.Ahead);
// D7. A reset in the past clamps elapsed to one; it never has a future projection. // D7. A reset in the past clamps elapsed to one; it never has a future projection.
public static PaceResult Calculate(LimitWindow window, DateTimeOffset now, double threshold = 10) public static PaceResult Calculate(LimitWindow window, DateTimeOffset now, double threshold = 10)
{ {
@@ -14,7 +27,7 @@ public static class Pace
var state = delta >= threshold ? PaceState.Ahead : var state = delta >= threshold ? PaceState.Ahead :
delta <= -threshold && elapsed >= 0.5 ? PaceState.Behind : PaceState.OnTrack; delta <= -threshold && elapsed >= 0.5 ? PaceState.Behind : PaceState.OnTrack;
DateTimeOffset? projection = null; DateTimeOffset? projection = null;
if (state == PaceState.Ahead && window.UsedPercent > 0 && elapsed > 0) if (delta > 0 && window.UsedPercent > 0 && CanForecast(window, now, new PaceResult(state, elapsed, delta)))
{ {
var seconds = (100 - window.UsedPercent) * elapsed * length.TotalSeconds / window.UsedPercent; var seconds = (100 - window.UsedPercent) * elapsed * length.TotalSeconds / window.UsedPercent;
if (seconds >= 0 && seconds < (reset - now).TotalSeconds) projection = now.AddSeconds(seconds); if (seconds >= 0 && seconds < (reset - now).TotalSeconds) projection = now.AddSeconds(seconds);
+3 -1
View File
@@ -53,8 +53,10 @@ public static class SettingsFile
var value = JsonSerializer.Deserialize(SharedFile.ReadAllText(Path.Combine(directory, "settings.json")), CoreJsonContext.Default.Settings); var value = JsonSerializer.Deserialize(SharedFile.ReadAllText(Path.Combine(directory, "settings.json")), CoreJsonContext.Default.Settings);
if (value is { IsValid: true }) return value; if (value is { IsValid: true }) return value;
} }
catch (FileNotFoundException) { return new(); }
catch (DirectoryNotFoundException) { return new(); }
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException) { } catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException) { }
diagnostics.Add(null, "settings-defaults", "Settings missing or invalid; using defaults."); diagnostics.Add(null, "settings-defaults", "Settings invalid or unreadable; using defaults.");
return new(); return new();
} }
public static Task SaveAsync(string directory, Settings settings, CancellationToken cancellationToken = default) public static Task SaveAsync(string directory, Settings settings, CancellationToken cancellationToken = default)
+28
View File
@@ -0,0 +1,28 @@
namespace FinalToken.Core;
/// <summary>D7 price ratios. Reasoning is already included in output; Codex cached input is a subset of input.</summary>
public static class TokenWeights
{
public const double Input = 1;
public const double ClaudeOutput = 5;
public const double ClaudeCacheWrite = 1.25;
public const double CacheRead = 0.1;
public const double CodexOutput = 8;
private static readonly string[] ClaudeFamilies = ["Fable", "Opus", "Sonnet", "Haiku"];
public static double Weighted(Provider provider, TokenCounts counts) => provider == Provider.Claude
? Math.Max(0, counts.Input) * Input + Math.Max(0, counts.Output) * ClaudeOutput + Math.Max(0, counts.CacheWrite) * ClaudeCacheWrite + Math.Max(0, counts.CacheRead) * CacheRead
: Math.Max(0, counts.Input - counts.CacheRead) * Input + Math.Max(0, counts.CacheRead) * CacheRead + Math.Max(0, counts.Output) * CodexOutput;
public static string? Family(LimitWindow window)
{
// Provider labels expose the family in parentheses; the dashboard also uses a middle dot.
var label = window.Label;
var open = label.LastIndexOf('('); var close = label.LastIndexOf(')');
var separator = label.LastIndexOf('\u00b7');
var family = open >= 0 && close > open ? label[(open + 1)..close].Trim()
: separator >= 0 ? label[(separator + 1)..].Trim() : null;
if (family is { Length: > 0 } && !family.Equals("all models", StringComparison.OrdinalIgnoreCase) &&
!family.Equals("all", StringComparison.OrdinalIgnoreCase) && !char.IsDigit(family[0])) return family;
return ClaudeFamilies.FirstOrDefault(f => label.Contains(f, StringComparison.OrdinalIgnoreCase));
}
public static bool Matches(LimitWindow window, string? model) => Family(window) is not { } family || model?.Contains(family, StringComparison.OrdinalIgnoreCase) == true;
}
+55 -1
View File
@@ -5,13 +5,67 @@ namespace FinalToken.App.Tests;
public sealed class FormattingTests public sealed class FormattingTests
{ {
[Theory]
[InlineData(6000000000, "6 B")]
[InlineData(2000000000, "2 B")]
[InlineData(1500000000, "1,5 B")]
[InlineData(600000000, "600 M")]
[InlineData(82500, "82,5 K")]
[InlineData(0, "0")]
public void AxisNumbersDropTrailingZerosWithoutChangingCompactValues(double value, string expected)
{
var previous = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE");
Assert.Equal(expected, Display.Axis(value));
Assert.Equal("2,00 B", Display.Compact(2000000000));
}
finally { CultureInfo.CurrentCulture = previous; }
}
[Theory]
[InlineData(292950000, "293 M")]
[InlineData(2300000000, "2,30 B")]
[InlineData(966690000, "967 M")]
[InlineData(82500, "82,5 K")]
[InlineData(999950, "1,00 M")]
[InlineData(0, "0")]
public void CompactNumbersUseThreeSignificantDigits(double value, string expected)
{
var previous = CultureInfo.CurrentCulture;
try { CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); Assert.Equal(expected, Display.Compact(value)); }
finally { CultureInfo.CurrentCulture = previous; }
}
[Theory]
[InlineData(FinalToken.Core.PaceState.Ahead, true)]
[InlineData(FinalToken.Core.PaceState.OnTrack, false)]
[InlineData(FinalToken.Core.PaceState.Behind, false)]
[InlineData(FinalToken.Core.PaceState.Unknown, false)]
public void ForecastWarningFollowsState(FinalToken.Core.PaceState state, bool warning)
{
var text = Display.Forecast(new(2026, 10, 18, 14, 43, 0, TimeSpan.Zero), state);
Assert.Equal(warning, text.Contains('⚠'));
Assert.StartsWith(warning ? "⚠ 100 % on " : "At this pace 100 % on ", text);
}
[Theory]
[InlineData(1)]
[InlineData(1.25)]
[InlineData(2)]
public void DenseBarEdgesMeetOnPhysicalPixelsWithoutGaps(double scaling)
{
var first = UsageChart.BarBounds(50.13, 100, 3.17, 40, scaling);
var next = UsageChart.BarBounds(53.30, 100, 3.17, 40, scaling);
Assert.Equal(first.Right, next.Left, 6);
Assert.Equal(Math.Round(first.Left * scaling), first.Left * scaling, 6);
Assert.Equal(Math.Round(first.Right * scaling), first.Right * scaling, 6);
}
[Fact] [Fact]
public void DailyChartLabelAndTooltipUseTheBucketsLocalDate() public void DailyChartLabelAndTooltipUseTheBucketsLocalDate()
{ {
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture"); var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
var day = FinalToken.Core.CalendarDays.Start(new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero), zone); var day = FinalToken.Core.CalendarDays.Start(new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero), zone);
Assert.Equal("10-14", Display.ChartDateLabel(day, TimeSpan.FromDays(1))); Assert.Equal("10-14", Display.ChartDateLabel(day, TimeSpan.FromDays(1)));
Assert.Equal(day.DateTime.ToString("g"), Display.ChartTimestamp(day, TimeSpan.FromDays(1))); Assert.Equal(day.DateTime.ToString("d"), Display.ChartTimestamp(day, TimeSpan.FromDays(1)));
} }
[Theory] [Theory]
[InlineData(null)] [InlineData(null)]
+267 -13
View File
@@ -1,5 +1,6 @@
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Headless; using Avalonia.Headless;
using Avalonia.Interactivity; using Avalonia.Interactivity;
using Avalonia.Media.Imaging; using Avalonia.Media.Imaging;
@@ -29,23 +30,262 @@ public sealed class HeadlessTests
var shots = Environment.GetEnvironmentVariable("FINALTOKEN_SCREENSHOT_DIR") ?? Path.Combine(root.Parent!.FullName, "runs", "shots", "app"); var shots = Environment.GetEnvironmentVariable("FINALTOKEN_SCREENSHOT_DIR") ?? Path.Combine(root.Parent!.FullName, "runs", "shots", "app");
Directory.CreateDirectory(shots); Directory.CreateDirectory(shots);
var model = FakeData.Model(); var model = FakeData.Model();
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }) { Height = 2450 }; var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { });
panel.Resources["SystemAccentColor"] = Avalonia.Media.Colors.Red;
panel.RequestedThemeVariant = ThemeVariant.Light; panel.Show(); Save(panel, "panel-light.png"); panel.RequestedThemeVariant = ThemeVariant.Light; panel.Show(); Save(panel, "panel-light.png");
Assert.Equal($"FinalToken {typeof(Program).Assembly.GetName().Version!.ToString(3)}", panel.Title); Assert.Equal($"FinalToken {typeof(Program).Assembly.GetName().Version!.ToString(3)}", panel.Title);
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Claude"); Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Claude");
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Tokens per day"); Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Tokens per day");
var filters = panel.GetVisualDescendants().OfType<ComboBox>().ToArray(); Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "●" && t.Foreground?.ToString() == "#ffeb6834");
filters[0].SelectedIndex = 4; filters[1].SelectedIndex = 2; Assert.All(panel.GetVisualDescendants().OfType<ProgressBar>(), bar => Assert.True(bar.Bounds.Width <= 140, $"Share bar width {bar.Bounds.Width}"));
Assert.Single(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Current session");
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("At this pace 100 % on ", StringComparison.Ordinal) == true);
Assert.Single(panel.GetVisualDescendants().OfType<WrapPanel>(), p => p.Name == "CompositionLegend");
var codexTile = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
Assert.DoesNotContain(codexTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains('⚠') == true || t.Foreground?.ToString() == "#ffd03b3b");
var withCache = panel.GetVisualDescendants().OfType<UsageChart>().Where(c => !c.Percent).Sum(c => c.Values.Sum(v => v.Value));
panel.GetVisualDescendants().OfType<CheckBox>().Single(c => c.Content as string == "Include cache reads").IsChecked = false;
Dispatcher.UIThread.RunJobs();
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == Display.Compact(61000000));
Assert.True(panel.GetVisualDescendants().OfType<UsageChart>().Where(c => !c.Percent).Sum(c => c.Values.Sum(v => v.Value)) < withCache);
model.IncludeCacheReads = true; Dispatcher.UIThread.RunJobs();
var originalSnapshot = model.Snapshot!;
var originalHistory = model.History;
var claude = originalSnapshot.Providers.Single(p => p.Provider == Provider.Claude);
var week = claude.Windows.Single(w => w.Window.Id == "week");
model.Snapshot = originalSnapshot with { Providers = originalSnapshot.Providers.Select(p => p.Provider == Provider.Claude
? p with { Windows = p.Windows.Append(week with { Window = week.Window with { Id = "fable", Label = "Week · Fable" } }).ToArray() } : p).ToArray() };
model.History = originalHistory with { Details = originalHistory.Details.Append(originalHistory.Details.Single(d => d.Provider == Provider.Claude && d.Id == "week") with { Id = "fable" }).ToArray() };
Dispatcher.UIThread.RunJobs();
panel.GetVisualDescendants().OfType<ComboBox>().Single().SelectedIndex = 1;
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Claude · Week · Fable");
var wheelSelector = panel.GetVisualDescendants().OfType<ComboBox>().Single();
var wheelViewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
Dispatcher.UIThread.RunJobs(); using (panel.CaptureRenderedFrame()) { }
var maximumOffset = wheelViewport.Extent.Height - wheelViewport.Viewport.Height;
const double scrollRoom = 80;
Assert.True(maximumOffset > scrollRoom * 2);
var selectorTop = wheelSelector.TranslatePoint(default, wheelViewport)!.Value.Y + wheelViewport.Offset.Y;
// BringIntoView can leave offset zero with Linux fonts. Centre the selector with room both ways.
var centredOffset = selectorTop - (wheelViewport.Viewport.Height - wheelSelector.Bounds.Height) / 2;
wheelViewport.Offset = new Vector(0, Math.Clamp(centredOffset, scrollRoom, maximumOffset - scrollRoom));
Dispatcher.UIThread.RunJobs(); wheelSelector.Focus();
foreach (var direction in new[] { 1, -1 })
{
using (panel.CaptureRenderedFrame()) { }
var selectorY = wheelSelector.TranslatePoint(default, wheelViewport)!.Value.Y;
Assert.InRange(selectorY, 0, wheelViewport.Viewport.Height - wheelSelector.Bounds.Height);
var beforeWheel = wheelViewport.Offset.Y;
Assert.InRange(beforeWheel, 1, maximumOffset - 1);
panel.MouseWheel(wheelSelector.TranslatePoint(new Point(20, 16), panel)!.Value, new Vector(0, direction));
Dispatcher.UIThread.RunJobs();
Assert.Equal(1, wheelSelector.SelectedIndex);
Assert.True(direction > 0 ? wheelViewport.Offset.Y < beforeWheel : wheelViewport.Offset.Y > beforeWheel,
$"Wheel {direction}: before={beforeWheel}, after={wheelViewport.Offset.Y}");
}
foreach (var segment in panel.GetVisualDescendants().OfType<ToggleButton>().Where(b => b.Classes.Contains("segment")))
{
segment.Focus(); var rangeBefore = model.Range; var providerBefore = model.ProviderFilter;
panel.MouseWheel(segment.TranslatePoint(new Point(8, 8), panel)!.Value, new Vector(0, -1));
Assert.Equal(rangeBefore, model.Range); Assert.Equal(providerBefore, model.ProviderFilter);
}
wheelViewport.Offset = default;
model.History = originalHistory;
model.Snapshot = originalSnapshot with { Providers = originalSnapshot.Providers.Select(p => p.Provider == Provider.Claude ? p with { Windows = [] } : p).ToArray() };
Dispatcher.UIThread.RunJobs();
Assert.Single(panel.GetVisualDescendants().OfType<DailyLimitChart>());
model.Snapshot = originalSnapshot; Dispatcher.UIThread.RunJobs();
var filters = panel.GetVisualDescendants().OfType<ToggleButton>().Where(b => b is not CheckBox).ToArray();
filters[4].IsChecked = true; filters[7].IsChecked = true;
Assert.Equal(HistoryRange.All, model.Range); Assert.Equal(Provider.Codex, model.ProviderFilter); Assert.Equal(HistoryRange.All, model.Range); Assert.Equal(Provider.Codex, model.ProviderFilter);
filters[0].SelectedIndex = 1; filters[1].SelectedIndex = 0; filters[1].IsChecked = true; filters[5].IsChecked = true;
panel.RequestedThemeVariant = ThemeVariant.Dark; Save(panel, "panel-dark.png"); panel.RequestedThemeVariant = ThemeVariant.Dark; Save(panel, "panel-dark.png");
model.Snapshot = FakeData.Snapshot(DateTimeOffset.UtcNow, true); Save(panel, "panel-unavailable.png"); panel.Close(); foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.Width = width; panel.Height = height; panel.RequestedThemeVariant = theme;
var stem = $"panel-{width}x{height}-{theme.ToString().ToLowerInvariant()}";
var viewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
viewport.Offset = default; Save(panel, stem + "-limits.png");
var selected = panel.GetVisualDescendants().OfType<ToggleButton>().First(b => b.Classes.Contains("segment") && b.IsChecked == true);
Assert.Equal(theme == ThemeVariant.Dark ? "#ff383835" : "#ffe1e0d9", selected.Background?.ToString());
Assert.Equal(Avalonia.Media.FontWeight.SemiBold, selected.FontWeight);
selected.Focus(Avalonia.Input.NavigationMethod.Tab); Dispatcher.UIThread.RunJobs();
Assert.Equal(theme == ThemeVariant.Dark ? "#fff0efec" : "#ff0b0b0b", selected.BorderBrush?.ToString());
var neutralCheck = panel.GetVisualDescendants().OfType<NeutralCheckBox>().Single();
neutralCheck.Focus(Avalonia.Input.NavigationMethod.Tab); Dispatcher.UIThread.RunJobs();
Assert.Equal(theme == ThemeVariant.Dark ? "#fff0efec" : "#ff0b0b0b", neutralCheck.BorderBrush?.ToString());
Assert.True(neutralCheck.MarkVisible);
var glyph = panel.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Name == "NeutralCheckGlyph");
Assert.Equal(theme == ThemeVariant.Dark ? "#fff0efec" : "#ff0b0b0b", glyph.Foreground?.ToString());
Assert.Equal(56, panel.GetVisualDescendants().OfType<Grid>().Single(g => g.Name == "PanelHeader").Bounds.Height);
if (width == 1500)
{
var sessionTile = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Claude-session");
var weekTile = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Claude-week");
var codexLimit = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
Assert.Equal(sessionTile.Bounds.Y, weekTile.Bounds.Y); Assert.Equal(weekTile.Bounds.Y, codexLimit.Bounds.Y);
Assert.True(sessionTile.Bounds.Height < weekTile.Bounds.Height);
}
foreach (var (name, target) in new[] { ("week", "Week use per day"), ("tokens", "Tokens"), ("windows", "Window charts"), ("breakdown", "Breakdown") })
{
var text = panel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == target);
var position = text.TranslatePoint(default, viewport)!.Value;
viewport.Offset = new Vector(0, viewport.Offset.Y + position.Y - 16);
Save(panel, stem + "-" + name + ".png");
if (name == "breakdown")
{
panel.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Show all 110").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Save(panel, stem + "-breakdown-expanded.png");
Assert.Contains(panel.GetVisualDescendants().OfType<Button>(), b => b.Content as string == "Show top 8");
panel.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Show top 8").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
}
}
var prior = viewport.Offset;
model.Snapshot = model.Snapshot! with { MadeAt = DateTimeOffset.UtcNow }; Dispatcher.UIThread.RunJobs();
Assert.Equal(prior, viewport.Offset);
}
var forecastModel = FakeData.ForecastModel();
var forecastPanel = new PanelWindow(forecastModel, () => { }, () => { }, () => { }, () => { });
forecastPanel.Show(); Dispatcher.UIThread.RunJobs();
var aheadTile = forecastPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-primary");
Assert.Contains(aheadTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("100 % on ") == true);
Assert.Contains(aheadTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "⚠ ");
Assert.NotNull(forecastModel.History.Limits.Single(l => l.Window!.Window.Id == "primary").Forecast);
var waitingTile = forecastPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
var note = Assert.Single(waitingTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("Forecast from ") == true).Text;
Assert.Contains(forecastPanel.GetVisualDescendants().OfType<BurnUpChart>(), c => c.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text == note));
var aheadWindow = forecastModel.Snapshot!.Providers[0].Windows[0];
var earlyAlert = new PopupDecider().Observe(aheadWindow.Window, aheadWindow.Pace, new Settings());
Assert.NotNull(earlyAlert);
var earlyPopup = PopupWindow.Pace(earlyAlert, () => { }); earlyPopup.Show();
Assert.Contains(earlyPopup.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains("⚠ 100 % on ") == true);
earlyPopup.Close();
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
forecastPanel.Width = 1280; forecastPanel.Height = 900; forecastPanel.RequestedThemeVariant = theme;
var viewport = forecastPanel.GetVisualDescendants().OfType<ScrollViewer>().First(); viewport.Offset = default;
Save(forecastPanel, $"forecast-1280x900-{theme}-limits.png");
var heading = forecastPanel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "Window charts");
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(forecastPanel, $"forecast-1280x900-{theme}-windows.png");
var charts = forecastPanel.GetVisualDescendants().OfType<BurnUpChart>().ToArray();
Assert.Equal(2, charts.Length);
Assert.True(DrawsForecast(charts[0])); Assert.False(DrawsForecast(charts[1]));
}
forecastPanel.Close();
var earlyModel = FakeData.EarlyResetModel();
var earlyPanel = new PanelWindow(earlyModel, () => { }, () => { }, () => { }, () => { });
earlyPanel.Show();
var earlyTile = earlyPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
Assert.DoesNotContain(earlyTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains("at reset") == true || t.Text?.Contains("100 % on") == true || t.Text?.StartsWith("Last ") == true);
Assert.Null(Assert.Single(earlyModel.History.Limits).Forecast);
Assert.All(Assert.Single(earlyModel.History.Limits).Analysis!.Past, instance => Assert.True(instance.End <= earlyModel.Snapshot!.MadeAt));
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
earlyPanel.Width = width; earlyPanel.Height = height; earlyPanel.RequestedThemeVariant = theme;
var viewport = earlyPanel.GetVisualDescendants().OfType<ScrollViewer>().First(); viewport.Offset = default;
Save(earlyPanel, $"panel-{width}x{height}-{theme}-early-limits.png");
var heading = earlyPanel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "Window charts");
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(earlyPanel, $"panel-{width}x{height}-{theme}-early-windows.png");
}
earlyPanel.Close();
panel.Width = 1000; panel.Height = 900;
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default; Save(panel, "panel-1000x900-light.png");
panel.Width = 1500; panel.Height = 1000;
model.History = originalHistory with { Details = originalHistory.Details.Select(d => d.Provider == Provider.Claude && d.Days is { } days
? d with { Days = days with { Current = days.Current.Select(day => day with { Used = null }).ToArray(), Today = null } } : d).ToArray() };
Dispatcher.UIThread.RunJobs(); Assert.Single(panel.GetVisualDescendants().OfType<DailyLimitChart>());
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.Width = width; panel.Height = height; panel.RequestedThemeVariant = theme; Dispatcher.UIThread.RunJobs();
var viewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
var heading = panel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "Week use per day");
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(panel, $"panel-{width}x{height}-{theme}-collecting-days.png");
}
model.History = originalHistory;
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var weekData = originalHistory.Details.Single(d => d.Provider == Provider.Claude && d.Id == "week").Days!;
Assert.Contains(weekData.Current, d => d.Origin == UseOrigin.Estimated);
var future = DataTooltip.Day(new(DateTimeOffset.Now.AddDays(1), DateTimeOffset.Now.AddDays(2), null, 42, false, true));
Assert.DoesNotContain(future.Rows, row => row.Label == "Cumulative");
var types = new (string Name, DataTooltip Tip)[]
{
("day-estimated", DataTooltip.Day(weekData.Current.First(d => d.Origin == UseOrigin.Estimated))),
("day-measured", DataTooltip.Day(weekData.Current.Last(d => d.Used is not null && d.Origin == UseOrigin.Measured))),
("future-day", future),
("project", DataTooltip.Tokens("D:/Projects/Customer/Workspace/Project-with-a-long-name", new(100000000, 1900000000, 10000000, 53670717, 1234567, 2063670717))),
("tile", (DataTooltip)ToolTip.GetTip(panel.GetVisualDescendants().OfType<Border>().First(b => b.Name == "LimitTile-Claude-week"))!),
("tokens", DataTooltip.Tokens("Claude - This week", originalSnapshot.Providers[0].Week)),
};
var limit = originalHistory.Limits.Single(l => l.Provider == Provider.Claude && l.Window!.Window.Id == "week");
CaptureChartTip("burnup", new BurnUpChart(limit), new Point(240, 100));
CaptureChartTip("past-instance", new InstancePeaks(limit.Analysis!.Past, Provider.Claude), new Point(30, 30));
CaptureChartTip("past-limit-reached", new InstancePeaks(limit.Analysis!.Past, Provider.Claude), new Point(600, 30));
CaptureChartTip("hourly", new UsageChart { Values = originalHistory.Hourly }, new Point(60, 170));
CaptureChartTip("daily", new UsageChart { Values = originalHistory.Daily, Interval = TimeSpan.FromDays(1) }, new Point(60, 170));
CaptureChartTip("composition", new CompositionBar(originalSnapshot.Providers[0].Week, Provider.Claude, true) { Height = 8 }, new Point(100, 4));
void CaptureChartTip(string name, Control chartControl, Point hover)
{
var window = new Window { Width = 740, Height = 600, RequestedThemeVariant = theme }; Ui.Theme(window);
var content = Ui.Stack(Ui.Text(name, 20), chartControl); content.Margin = new Thickness(24); window.Content = content;
window.Show(); Dispatcher.UIThread.RunJobs(); using (window.CaptureRenderedFrame()) { }
window.MouseMove(chartControl.TranslatePoint(hover, window)!.Value);
var actualTip = Assert.IsType<DataTooltip>(ToolTip.GetTip(chartControl));
window.MouseMove(new Point(0, 0)); ToolTip.SetIsOpen(chartControl, false);
content.Children.Add(new DataTooltip(actualTip.Title, actualTip.Rows.ToArray()));
Save(window, $"tooltip-{name}-{theme}.png"); window.Close();
}
foreach (var (name, tip) in types)
{
var tooltipWindow = new Window { Width = 620, Height = 300, RequestedThemeVariant = theme };
Ui.Theme(tooltipWindow); tooltipWindow.Content = new Border { Child = tip, Padding = new Thickness(24), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
tooltipWindow.Show(); Save(tooltipWindow, $"tooltip-{name}-{theme}.png"); tooltipWindow.Close();
}
}
model.Snapshot = FakeData.Snapshot(DateTimeOffset.UtcNow, true);
Dispatcher.UIThread.RunJobs(); panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
Save(panel, "panel-unavailable.png");
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.Width = width; panel.Height = height; panel.RequestedThemeVariant = theme;
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
Save(panel, $"panel-{width}x{height}-{theme}-unavailable.png");
}
model.Diagnostics = [new(DateTimeOffset.UtcNow, Provider.Claude, "fixture", "Probe timed out. Last good sample retained.")];
Dispatcher.UIThread.RunJobs(); var expander = panel.GetVisualDescendants().OfType<Expander>().Single();
expander.BringIntoView(); Save(panel, "panel-diagnostics-collapsed.png");
expander.IsExpanded = true; panel.UpdateLayout();
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = new Vector(0, 100000);
Save(panel, "panel-diagnostics-expanded.png"); panel.Close();
string? folder = null; var quitCalls = 0; var saveCalls = 0;
var actions = new SettingsWindow(new(), new(PluginInstallState.NoHostFound), _ => { saveCalls++; return Task.CompletedTask; }, () => quitCalls++, path => folder = path);
actions.Show();
void ClickSettings(string text) => actions.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == text).RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
ClickSettings("Open folder"); Assert.Equal(DataPaths.DataDirectory, folder);
ClickSettings("Quit FinalToken"); Assert.Equal(1, quitCalls);
ClickSettings("Cancel"); Assert.False(actions.IsVisible); Assert.Equal(0, saveCalls);
Settings? saved = null; Settings? saved = null;
var initial = new Settings { StartWithOs = true, StreamDeckInstallMode = InstallMode.Automatic, DismissedPluginVersion = "0.9" }; var initial = new Settings { StartWithOs = true, StreamDeckInstallMode = InstallMode.Automatic, DismissedPluginVersion = "0.9" };
var settings = new SettingsWindow(initial, new(PluginInstallState.Outdated, "1.0", "0.9"), value => { saved = value; return Task.CompletedTask; }) { Height = 1600 }; var settings = new SettingsWindow(initial, new(PluginInstallState.Outdated, "1.0", "0.9"), value => { saved = value; return Task.CompletedTask; }, () => { });
settings.Show(); Save(settings, "settings.png"); settings.Show(); Save(settings, "settings.png");
var providerNames = settings.GetVisualDescendants().OfType<CheckBox>().Select(c => c.Name).ToArray();
Assert.Equal(providerNames.Length, providerNames.Distinct().Count());
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
settings.RequestedThemeVariant = theme;
var viewport = settings.GetVisualDescendants().OfType<ScrollViewer>().First();
viewport.Offset = default; Save(settings, $"settings-{theme}-general.png");
viewport.Offset = new Vector(0, 10000); Save(settings, $"settings-{theme}-providers.png");
}
var refresh = settings.GetVisualDescendants().OfType<NumericUpDown>().First(); refresh.Value = 25; var refresh = settings.GetVisualDescendants().OfType<NumericUpDown>().First(); refresh.Value = 25;
settings.GetVisualDescendants().OfType<CheckBox>().First().IsChecked = false; settings.GetVisualDescendants().OfType<CheckBox>().Single(c => c.Content as string == "Ahead popups").IsChecked = false;
settings.GetVisualDescendants().OfType<TextBox>().Single(t => t.Name == "ClaudeCliPath").Text = "claude-fixture"; settings.GetVisualDescendants().OfType<TextBox>().Single(t => t.Name == "ClaudeCliPath").Text = "claude-fixture";
settings.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Save").RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); settings.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Save").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Assert.NotNull(saved); Assert.Equal(TimeSpan.FromSeconds(25), saved.RefreshInterval); Assert.True(saved.StartWithOs); Assert.NotNull(saved); Assert.Equal(TimeSpan.FromSeconds(25), saved.RefreshInterval); Assert.True(saved.StartWithOs);
@@ -63,13 +303,13 @@ public sealed class HeadlessTests
Assert.Contains(cancelled.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Settings save was cancelled."); cancelled.Close(); Assert.Contains(cancelled.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Settings save was cancelled."); cancelled.Close();
var opened = 0; var opened = 0;
var ahead = PopupWindow.Pace(new(Provider.Claude, "session", "Session", PaceState.Ahead, 22, DateTimeOffset.UtcNow.AddHours(1)), () => opened++); var ahead = PopupWindow.Pace(new(Provider.Claude, "session", "Session", PaceState.Ahead, 22, DateTimeOffset.UtcNow.AddHours(1)), () => opened++);
ahead.Show(); Save(ahead, "popup-ahead.png"); Assert.False(ahead.ShowActivated); ahead.Show(); SaveThemes(ahead, "popup-ahead"); Assert.False(ahead.ShowActivated);
ahead.MouseDown(new Point(100, 60), Avalonia.Input.MouseButton.Left); Assert.Equal(1, opened); Assert.False(ahead.IsVisible); ahead.MouseDown(new Point(100, 60), Avalonia.Input.MouseButton.Left); Assert.Equal(1, opened); Assert.False(ahead.IsVisible);
var behind = PopupWindow.Pace(new(Provider.Codex, "primary", "Primary", PaceState.Behind, -18, null), () => { }); var behind = PopupWindow.Pace(new(Provider.Codex, "primary", "Primary", PaceState.Behind, -18, null), () => { });
behind.Show(); Save(behind, "popup-behind.png"); behind.Close(); behind.Show(); SaveThemes(behind, "popup-behind"); behind.Close();
var installed = 0; var dismissed = 0; var installed = 0; var dismissed = 0;
var ask = new PopupWindow("Stream Deck plugin", "Version 1.0 is ready.", () => { }, "Install", () => installed++, () => dismissed++); var ask = new PopupWindow("Stream Deck plugin", "Version 1.0 is ready.", () => { }, "Install", () => installed++, () => dismissed++);
ask.Show(); Save(ask, "popup-streamdeck-ask.png"); ask.Show(); SaveThemes(ask, "popup-streamdeck-ask");
ask.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Not now").RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); ask.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Not now").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Assert.Equal(0, installed); Assert.Equal(1, dismissed); Assert.Equal(0, installed); Assert.Equal(1, dismissed);
var install = new PopupWindow("Stream Deck plugin", "Update ready", () => { }, "Update", () => installed++); var install = new PopupWindow("Stream Deck plugin", "Update ready", () => { }, "Update", () => installed++);
@@ -84,7 +324,7 @@ public sealed class HeadlessTests
var chartWindow = new Window { Content = chart, Width = 400, Height = 180 }; var chartWindow = new Window { Content = chart, Width = 400, Height = 180 };
chartWindow.Show(); chartWindow.Show();
using (chartWindow.CaptureRenderedFrame()) { } using (chartWindow.CaptureRenderedFrame()) { }
chartWindow.MouseMove(new Point(65, 80)); chartWindow.MouseMove(new Point(200, 100));
Assert.Contains(123456.ToString("N0"), ToolTip.GetTip(chart)?.ToString()); chartWindow.Close(); Assert.Contains(123456.ToString("N0"), ToolTip.GetTip(chart)?.ToString()); chartWindow.Close();
var polishShots = shots; var polishShots = shots;
Directory.CreateDirectory(polishShots); Directory.CreateDirectory(polishShots);
@@ -102,11 +342,25 @@ public sealed class HeadlessTests
Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light }; Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light };
dailyWindow.Show(); Save(dailyWindow, "chart-local-day.png"); dailyWindow.Show(); Save(dailyWindow, "chart-local-day.png");
dailyWindow.MouseMove(new Point(90, 150)); dailyWindow.MouseMove(new Point(90, 150));
Assert.Contains(day.DateTime.ToString("g"), ToolTip.GetTip(daily)?.ToString()); dailyWindow.Close(); Assert.Contains(day.DateTime.ToString("d"), ToolTip.GetTip(daily)?.ToString()); dailyWindow.Close();
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));
completion.SetResult(); completion.SetResult();
void SaveThemes(Window window, string stem)
{
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{ window.RequestedThemeVariant = theme; Save(window, stem + "-" + theme + ".png"); }
}
bool DrawsForecast(BurnUpChart chart)
{
var drawing = new Avalonia.Media.DrawingGroup();
using (var context = drawing.Open()) chart.Render(context);
return HasForecast(drawing);
static bool HasForecast(Avalonia.Media.DrawingGroup group) => group.Children.Any(d =>
d is Avalonia.Media.GeometryDrawing { Pen.DashStyle.Dashes: { } dashes } && dashes.SequenceEqual(new double[] { 1, 3 }) ||
d is Avalonia.Media.DrawingGroup nested && HasForecast(nested));
}
void Save(Window window, string name, string? destination = null) void Save(Window window, string name, string? destination = null)
{ {
Dispatcher.UIThread.RunJobs(); Dispatcher.UIThread.RunJobs();
@@ -121,7 +375,7 @@ public sealed class HeadlessTests
thread.Start(); await completion.Task; thread.Join(); thread.Start(); await completion.Task; thread.Join();
} }
public sealed class TestApplication : Application public sealed class TestApplication : Application
{ public override void Initialize() => Styles.Add(new FluentTheme()); } { public override void Initialize() => Styles.Add(Ui.NeutralTheme()); }
private sealed class PopupClock : TimeProvider private sealed class PopupClock : TimeProvider
{ {
public List<PopupTimer> Timers { get; } = []; public List<PopupTimer> Timers { get; } = [];
+156 -10
View File
@@ -5,6 +5,70 @@ namespace FinalToken.App.Tests;
public sealed class ViewModelTests public sealed class ViewModelTests
{ {
[Theory]
[InlineData(10, true)]
[InlineData(40, false)]
public void HistoryForecastsUseTheSnapshotsConfiguredPace(double threshold, bool eligible)
{
var model = FakeData.ForecastModel(threshold);
Assert.Equal(eligible, model.History.Limits.Single(l => l.Window!.Window.Id == "primary").Forecast is not null);
Assert.Equal(eligible, model.History.Details.Single(d => d.Id == "primary").Recent is not null);
}
[Fact] public async Task RefreshIgnoresConcurrentRequestsAndClearsGuardAfterFailure()
{
var model = new PanelViewModel(); var completion = new TaskCompletionSource(); var calls = 0;
var first = model.RefreshAsync(() => { calls++; return completion.Task; });
Assert.True(model.Refreshing);
await model.RefreshAsync(() => { calls++; return Task.CompletedTask; });
Assert.Equal(1, calls); completion.SetResult(); await first; Assert.False(model.Refreshing);
await Assert.ThrowsAsync<IOException>(() => model.RefreshAsync(() => throw new IOException("fixture")));
Assert.False(model.Refreshing);
}
[Theory]
[InlineData(-1, "now")]
[InlineData(0, "now")]
[InlineData(59, "1 min")]
[InlineData(3600, "1 h 0 min")]
[InlineData(90061, "1 d 1 h")]
public void DurationUsesDaysHoursAndRoundedMinutes(int seconds, string expected)
=> Assert.Equal(expected, Display.Duration(TimeSpan.FromSeconds(seconds)));
[Theory]
[InlineData(PaceState.Ahead, "\u25b2 Ahead")]
[InlineData(PaceState.Behind, "\u25bc Behind")]
[InlineData(PaceState.OnTrack, "\u2713 On track")]
[InlineData(PaceState.Unknown, "? Pace unknown")]
public void StatusChipsAlwaysNameTheirState(PaceState state, string expected) => Assert.Equal(expected, Display.State(state));
[Fact] public void BreakdownSortingUsesTheSelectedNumericColumn()
{
BreakdownRow[] rows = [new("a", new(Input: 30, Output: 2, Total: 32), .4), new("b", new(Input: 10, Output: 40, Total: 50), .6)];
Assert.Equal("b", BreakdownTable.SortRows(rows, BreakdownColumn.Total, true).First().Name);
Assert.Equal("a", BreakdownTable.SortRows(rows, BreakdownColumn.Input, true).First().Name);
Assert.Equal("a", BreakdownTable.SortRows(rows, BreakdownColumn.Output, false).First().Name);
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void ResetDriftKeepsChartContinuousAndRealResetAddsGap(int minutes)
{
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
var window = new LimitWindow(Provider.Claude, "week", "Week", 60, now.AddDays(4), TimeSpan.FromDays(7), now.AddMinutes(-1), "fixture");
var first = window with { SampleTime = CalendarDays.Start(now).AddHours(-1), UsedPercent = 40, ResetsAt = window.ResetsAt!.Value.AddMinutes(minutes) };
store.AddLimits([first]);
store.AddLimits([window with { SampleTime = now.AddHours(-3), UsedPercent = 50, ResetsAt = window.ResetsAt!.Value.AddMinutes(-minutes) }]);
store.AddLimits([window]);
Snapshot SnapshotFor(LimitWindow w, DateTimeOffset time) => new() { MadeAt = time, RefreshInterval = TimeSpan.FromMinutes(1),
Providers = [new(Provider.Claude, ProviderStatus.Available, null, [new(w, Pace.Calculate(w, time))], new(), null, new())] };
var view = PanelViewModel.QueryHistory(store, SnapshotFor(window, now), HistoryRange.All, null, now);
Assert.All(Assert.Single(view.Limits).Values, v => Assert.False(v.BreakBefore));
var detail = Assert.Single(view.Details);
Assert.Equal(first.SampleTime, detail.Since); Assert.Equal(20, detail.Days!.Today); Assert.NotNull(detail.Recent);
var next = window with { ResetsAt = window.ResetsAt!.Value.AddDays(7), SampleTime = now.AddDays(7).AddMinutes(-1), UsedPercent = 5 };
store.AddLimits([next]);
var nextView = PanelViewModel.QueryHistory(store, SnapshotFor(next, now.AddDays(7)), HistoryRange.All, null, now.AddDays(7));
Assert.Equal(1, Assert.Single(nextView.Limits).Values.Count(v => v.BreakBefore));
Assert.True(Assert.Single(nextView.Limits).Values[^1].BreakBefore);
}
[Theory] [Theory]
[InlineData(HistoryRange.Hours24, 1)] [InlineData(HistoryRange.Hours24, 1)]
[InlineData(HistoryRange.Days7, 7)] [InlineData(HistoryRange.Days7, 7)]
@@ -55,6 +119,43 @@ public sealed class ViewModelTests
} }
[Fact] public void DesktopEntryQuotesExecutableAndEscapesFieldCodes() [Fact] public void DesktopEntryQuotesExecutableAndEscapesFieldCodes()
{ var text = OsStartup.DesktopEntry("/opt/Final Token/100%/app"); Assert.Contains("Exec=\"/opt/Final Token/100%%/app\"", text); Assert.Contains("Terminal=false", text); } { var text = OsStartup.DesktopEntry("/opt/Final Token/100%/app"); Assert.Contains("Exec=\"/opt/Final Token/100%%/app\"", text); Assert.Contains("Terminal=false", text); }
[Fact] public void BreakdownQueryReturnsEveryRowAndItsShareWithoutPrebuildingOther()
{
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
for (var i = 0; i < 110; i++) store.Add(new(Provider.Claude, now.AddHours(-1), "model", $"project-{i}", new(Total: i + 1), $"{i}"));
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, null, now);
Assert.Equal(110, view.Projects.Count); Assert.Equal("project-109", view.Projects[0].Name);
Assert.Equal("project-0", view.Projects[^1].Name); Assert.Equal(6105, view.Projects.Sum(r => r.Counts.Total));
Assert.Equal(1, view.Projects.Sum(r => r.Share), 8);
}
[Fact] public void FilteredModelSeriesUseSixAlphabeticSlotsAndOther()
{
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
for (var i = 9; i >= 0; i--) store.Add(new(Provider.Claude, now.AddHours(-1), $"model-{i}", "p", new(CacheRead: 2, Total: 10), $"{i}"));
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, Provider.Claude, now);
Assert.Equal(7, view.Hourly.Count); Assert.Equal(40, view.Hourly.Single(p => p.Series == "Other").Value);
Assert.Equal(100, view.Hourly.Sum(p => p.Value)); Assert.Equal(20, view.Hourly.Sum(p => p.CacheRead));
Assert.Equal(view.Hourly.Select(p => p.Series).Order(), view.Daily.Select(p => p.Series).Order());
Assert.DoesNotContain(view.Hourly, p => p.Series == "model-6");
}
[Fact] public void ProjectNamesKeepTwoSegmentsAndDisambiguateCollisions()
{
var names = PanelWindow.ShortProjectNames(["D:/First/Shared/App", "D:/Second/Shared/App", "/work/Only/App", "Unknown"]);
Assert.Equal(["First/Shared/App", "Second/Shared/App", "Only/App", "Unknown"], names);
}
[Fact] public void ModelBreakdownKeepsActualProviderIdentityForDots()
{
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
store.Add(new(Provider.Claude, now.AddHours(-1), "arbitrary-name", "p", new(Total: 10), "a"));
store.Add(new(Provider.Codex, now.AddHours(-1), "shared-name", "p", new(Total: 20), "b"));
store.Add(new(Provider.Claude, now.AddHours(-1), "shared-name", "p", new(Total: 30), "c"));
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, null, now);
Assert.Equal([Provider.Claude], view.Models.Single(r => r.Name == "arbitrary-name").Providers);
Assert.Equal([Provider.Claude, Provider.Codex], view.Models.Single(r => r.Name == "shared-name").Providers);
}
[Fact] public void DesktopEntryRejectsInjectedLine() => Assert.Throws<ArgumentException>(() => OsStartup.DesktopEntry("/app\nExec=other")); [Fact] public void DesktopEntryRejectsInjectedLine() => Assert.Throws<ArgumentException>(() => OsStartup.DesktopEntry("/app\nExec=other"));
[Fact] public void DesktopEntryEscapesCommandCharactersAtBothParsingLevels() [Fact] public void DesktopEntryEscapesCommandCharactersAtBothParsingLevels()
{ {
@@ -65,25 +166,70 @@ public sealed class ViewModelTests
internal static class FakeData internal static class FakeData
{ {
public static PanelViewModel ForecastModel(double threshold = 10)
{
var now = new DateTimeOffset(2026, 10, 15, 16, 45, 0, TimeSpan.Zero);
var ahead = new LimitWindow(Provider.Codex, "primary", "Week", 39,
new(2026, 10, 22, 6, 18, 0, TimeSpan.Zero), TimeSpan.FromDays(7), now, "fixture");
var early = ahead with { Id = "secondary", Label = "Week · early on track", UsedPercent = 1, ResetsAt = now.AddDays(7).AddHours(-1) };
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
store.AddLimits([ahead with { SampleTime = now.AddHours(-4), UsedPercent = 20 }, ahead,
early with { SampleTime = now.AddHours(-1), UsedPercent = 0 }, early]);
var snapshot = Snapshot(now) with { Providers = [Snapshot(now).Providers[1] with
{ Windows = [new(ahead, Pace.Calculate(ahead, now, threshold)), new(early, Pace.Calculate(early, now, threshold))] }] };
return new() { Snapshot = snapshot, History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
}
public static Snapshot Snapshot(DateTimeOffset now, bool unavailable = false) => new() public static Snapshot Snapshot(DateTimeOffset now, bool unavailable = false) => new()
{ {
MadeAt = now, RefreshInterval = TimeSpan.FromSeconds(60), Providers = MadeAt = now, RefreshInterval = TimeSpan.FromSeconds(60), Providers =
[new(Provider.Claude, ProviderStatus.Available, null, [Window(Provider.Claude, "session", "Current session", 68, now, 5, 3), Window(Provider.Claude, "week", "Current week", 32, now, 168, 48)], [new(Provider.Claude, ProviderStatus.Available, null, [Window(Provider.Claude, "session", "Session · 5 h", 12, now, 5, 1), Window(Provider.Claude, "week", "Week · all models", 98, now, 168, 24)],
new(12000, 18000, 2000, 4200, 0, 36200), new(4000, 6000, 1000, 1600, 0, 12600), new(85000, 92000, 16000, 28000, 0, 221000)), new(12000000, 218000000, 2000000, 47000000, 0, 279000000), new(4000000, 6000000, 1000000, 1600000, 0, 12600000), new(85000000, 1920000000, 16000000, 259000000, 0, 2280000000)),
new(Provider.Codex, unavailable ? ProviderStatus.Unavailable : ProviderStatus.Available, unavailable ? "CLI is not installed. Token history remains available." : null, new(Provider.Codex, unavailable ? ProviderStatus.Unavailable : ProviderStatus.Available, unavailable ? "CLI is not installed. Token history remains available." : null,
[Window(Provider.Codex, "primary", "Primary · 5 hours", 12, now, 5, 1), Window(Provider.Codex, "secondary", "Secondary · 7 days", 62, now, 168, 80)], [Window(Provider.Codex, "secondary", "Week", 86, now, 168, 24)],
new(72000, 42000, 0, 8400, 2100, 80400), new(23000, 10000, 0, 3200, 700, 26200), new(340000, 150000, 0, 38000, 11000, 378000))] new(72000000, 42000000, 0, 8400000, 2100000, 80400000), null, new(340000000, 150000000, 0, 38000000, 11000000, 378000000))]
}; };
private static WindowSnapshot Window(Provider provider, string id, string label, double percent, DateTimeOffset now, int hours, int resetHours) private static WindowSnapshot Window(Provider provider, string id, string label, double percent, DateTimeOffset now, int hours, int resetHours)
{ var w = new LimitWindow(provider, id, label, percent, now.AddHours(resetHours), TimeSpan.FromHours(hours), now.AddMinutes(-3), "fixture"); return new(w, Pace.Calculate(w, now)); } { var w = new LimitWindow(provider, id, label, percent, now.AddHours(resetHours), TimeSpan.FromHours(hours), now.AddMinutes(-3), "fixture"); return new(w, Pace.Calculate(w, now)); }
public static PanelViewModel EarlyResetModel()
{
var now = DateTimeOffset.UtcNow;
var transition = now.AddHours(-1);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-early", Guid.NewGuid().ToString("N")), new DiagnosticLog());
var snapshot = Snapshot(now);
var codex = snapshot.Providers.Single(p => p.Provider == Provider.Codex);
var window = codex.Windows[0].Window with { UsedPercent = 2, ResetsAt = transition.AddDays(7), SampleTime = now };
var previous = window with { ResetsAt = transition.AddDays(5), SampleTime = transition.AddDays(-1), UsedPercent = 40 };
store.AddLimits([previous, window with { SampleTime = transition, UsedPercent = 1 }, window]);
var start = previous.ResetsAt!.Value - previous.Length!.Value;
void Add(DateTimeOffset time, long input, string id) => store.Add(new(Provider.Codex, time, "gpt-6.1-sol", "Fixture/Project", new(Input: input, Total: input), id));
Add(start, 1000000, "a"); Add(previous.SampleTime.AddHours(1), 5000000, "b"); Add(transition, 100000, "c");
snapshot = snapshot with { Providers = [codex with { Windows = [new(window, Pace.Calculate(window, now))] }] };
return new() { Snapshot = snapshot, History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
}
public static PanelViewModel Model(bool unavailable = false) public static PanelViewModel Model(bool unavailable = false)
{ {
var now = DateTimeOffset.UtcNow; var now = DateTimeOffset.UtcNow;
var hourly = Enumerable.Range(0, 24).SelectMany(i => new[] { new ChartValue(now.AddHours(-24 + i), "Claude", 1000 + i * 210), new ChartValue(now.AddHours(-24 + i), "Codex", 2000 + (i % 5) * 800) }).ToArray(); var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-fake", Guid.NewGuid().ToString("N")), new DiagnosticLog());
var daily = Enumerable.Range(0, 7).SelectMany(i => new[] { new ChartValue(now.AddDays(-7 + i), "Claude", 20000 + i * 2000), new ChartValue(now.AddDays(-7 + i), "Codex", 30000 + i * 5000) }).ToArray(); var snapshot = Snapshot(now, unavailable);
return new() { Snapshot = Snapshot(now, unavailable), Message = "Updated just now · local CLI data", History = new(hourly, daily, foreach (var provider in snapshot.Providers)
[new("Claude · Current session", Enumerable.Range(0, 8).Select(i => new ChartValue(now.AddMinutes(-140 + i * 20), "session", i * 8 + 12, i * 6)).ToArray())], {
[new("claude-sonnet", new(Total: 221000), 0.37), new("gpt-6.1-sol", new(Total: 378000), 0.63)], [new("FinalToken", new(Total: 599000), 1)]), for (var i = 0; i < 336; i++)
Diagnostics = [new(now.AddMinutes(-4), Provider.Claude, "sample-age", "Latest limit sample is three minutes old.")] }; {
var input = 1000000 + i * 10000; var cache = input * 8;
store.Add(new(provider.Provider, now.AddHours(-336 + i), provider.Provider == Provider.Claude ? "claude-fable" : "gpt-6.1-sol",
$"D:/Projects/Customer-{i % 110}/Workspace/Project-{i % 110}",
provider.Provider == Provider.Claude ? new(input, cache, 200000, 500000, 0, input + cache + 700000) : new(input + cache, cache, 0, 500000, 100000, input + cache + 500000), $"{provider.Provider}-{i}"));
}
foreach (var ws in provider.Windows)
{
var w = ws.Window; var start = w.ResetsAt!.Value - w.Length!.Value;
for (var i = provider.Provider == Provider.Claude && w.Length > TimeSpan.FromDays(1) ? (int)(now - start).TotalHours - 24 : 0; i <= (int)(now - start).TotalHours; i += w.Length > TimeSpan.FromDays(1) ? 3 : 1)
store.AddLimits([w with { SampleTime = start.AddHours(i), UsedPercent = w.UsedPercent * i / (now - start).TotalHours }]);
var previousReset = start - (w.Length > TimeSpan.FromDays(1) ? TimeSpan.Zero : TimeSpan.FromHours(6));
for (var i = 0; i < (int)w.Length!.Value.TotalHours; i += w.Length > TimeSpan.FromDays(1) ? 6 : 1)
store.AddLimits([w with { ResetsAt = previousReset, SampleTime = previousReset - w.Length.Value + TimeSpan.FromHours(i), UsedPercent = 100.0 * i / w.Length.Value.TotalHours }]);
}
}
return new() { Snapshot = snapshot, Message = "Updated just now", History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
} }
} }
@@ -0,0 +1,81 @@
using Xunit;
namespace FinalToken.Core.Tests;
public class EarlyForecastTests
{
private static readonly DateTimeOffset Now = new(2026, 10, 15, 16, 45, 0, TimeSpan.Zero);
private static LimitWindow Week(double used = 39) => new(Provider.Codex, "primary", "Week", used,
new(2026, 10, 22, 6, 18, 0, TimeSpan.Zero), TimeSpan.FromDays(7), Now, "fixture");
[Fact] public void AheadCodexWeekProjectsBeforeTenPercent()
{
var window = Week(); var pace = Pace.Calculate(window, Now);
Assert.Equal(PaceState.Ahead, pace.State);
Assert.InRange(pace.ElapsedFraction!.Value, .061, .063);
Assert.NotNull(pace.Projection);
Assert.InRange(pace.Projection.Value, Now, window.ResetsAt!.Value);
}
[Fact] public void AheadCodexWeekHasAverageForecast() => Assert.NotNull(LimitAnalysis.AverageUseAtReset(Week(), Now));
[Fact] public void AheadCodexWeekHasRecentForecast()
{
var window = Week();
var recent = LimitAnalysis.Recent(window, [window with { SampleTime = Now.AddHours(-4), UsedPercent = 20 }], Now);
Assert.NotNull(recent); Assert.NotNull(recent.ReachesLimit);
Assert.Equal(TimeSpan.FromHours(4), recent.Span);
}
[Fact] public void AheadCodexPopupIncludesProjection()
{
var window = Week();
var popup = new PopupDecider().Observe(window, Pace.Calculate(window, Now), new Settings());
Assert.NotNull(popup); Assert.NotNull(popup.Projection);
}
[Fact] public void OnePercentOneHourIntoWeekDoesNotForecast()
{
var window = Week(1) with { ResetsAt = Now.AddDays(7).AddHours(-1) };
Assert.Equal(PaceState.OnTrack, Pace.Calculate(window, Now).State);
Assert.Null(Pace.Calculate(window, Now).Projection);
Assert.Null(LimitAnalysis.AverageUseAtReset(window, Now));
Assert.Null(LimitAnalysis.Recent(window, [], Now));
}
[Theory]
[InlineData(10, true)]
[InlineData(40, false)]
public void AllForecastsFollowConfiguredThreshold(double threshold, bool eligible)
{
var window = Week(); var pace = Pace.Calculate(window, Now, threshold);
Assert.Equal(eligible, pace.State == PaceState.Ahead);
Assert.Equal(eligible, Pace.CanForecast(window, Now, threshold));
Assert.Equal(eligible, pace.Projection is not null);
Assert.Equal(eligible, LimitAnalysis.AverageUseAtReset(window, Now, pace) is not null);
Assert.Equal(eligible, LimitAnalysis.Recent(window,
[window with { SampleTime = Now.AddHours(-4), UsedPercent = 20 }], Now, pace) is not null);
}
[Fact] public void ExactlyAheadThresholdEnablesEarlyForecasts()
{
var window = Week(); var threshold = Pace.Calculate(window, Now).Delta!.Value;
var pace = Pace.Calculate(window, Now, threshold);
Assert.Equal(PaceState.Ahead, pace.State);
Assert.NotNull(pace.Projection);
Assert.NotNull(LimitAnalysis.AverageUseAtReset(window, Now, pace));
Assert.NotNull(LimitAnalysis.Recent(window, [window with { SampleTime = Now.AddHours(-4), UsedPercent = 20 }], Now, pace));
}
[Fact] public void ForecastStartIsTenPercentIntoWindow()
{
var window = Week(1);
Assert.Equal(window.ResetsAt - TimeSpan.FromDays(6.3), Pace.ForecastStartsAt(window));
Assert.Null(Pace.ForecastStartsAt(window with { Length = null }));
Assert.Null(Pace.ForecastStartsAt(window with { ResetsAt = null }));
Assert.Null(Pace.ForecastStartsAt(window with { Length = TimeSpan.Zero }));
var start = Pace.ForecastStartsAt(window)!.Value;
Assert.False(Pace.CanForecast(window, start.AddTicks(-1), 40));
Assert.True(Pace.CanForecast(window, start, 40));
}
}
@@ -0,0 +1,168 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class LimitAnalysisTests
{
private static readonly DateTimeOffset Now = new(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
private static LimitWindow Window(double use = 60) => new(Provider.Claude, "week", "Week", use,
Now.AddDays(3.5), TimeSpan.FromDays(7), Now, "fixture");
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void MinuteDriftAcrossMidnightKeepsDaysRecentRateAndPreviousWeek(int minutes)
{
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
var w = Window() with { ResetsAt = new DateTimeOffset(2026, 10, 18, 20, 0, 0, TimeSpan.Zero) };
LimitWindow[] samples =
[
w with { SampleTime = Now.AddDays(-2).AddHours(9), UsedPercent = 30, ResetsAt = w.ResetsAt!.Value.AddMinutes(minutes) },
w with { SampleTime = Now.AddHours(-15), UsedPercent = 40, ResetsAt = w.ResetsAt!.Value.AddMinutes(minutes) },
w with { SampleTime = Now.AddHours(-6), UsedPercent = 50, ResetsAt = w.ResetsAt!.Value.AddMinutes(-minutes) },
w with { SampleTime = Now.AddDays(-3).AddHours(7), UsedPercent = 90, ResetsAt = w.ResetsAt!.Value.AddDays(-7) }
];
var days = LimitAnalysis.Days(w, samples, Now, zone)!;
Assert.Equal(20, days.Today);
Assert.Equal(20, Assert.Single(days.Current, d => d.IsToday).Used);
Assert.Equal(10, Assert.Single(days.Current, d => d.Start == CalendarDays.Start(Now.AddDays(-1), zone)).Used);
Assert.Equal(90, days.Previous.Last(d => d.Cumulative is not null).Cumulative);
var recent = LimitAnalysis.Recent(w, samples, Now);
Assert.NotNull(recent); Assert.Equal(20, recent.Increase); Assert.Equal(32, recent.PercentPerDay);
Assert.Equal(Now.AddDays(1.25), recent.ReachesLimit);
}
[Fact] public void RealWeekResetStartsAtZeroAndKeepsOldWeekSeparate()
{
var old = Window() with { UsedPercent = 90, SampleTime = Window().ResetsAt!.Value.AddHours(-3) };
var now = old.ResetsAt!.Value.AddHours(1);
var current = old with { ResetsAt = old.ResetsAt.Value.AddDays(7), SampleTime = now, UsedPercent = 5 };
var days = LimitAnalysis.Days(current, [old], now, TimeZoneInfo.Utc)!;
Assert.Equal(5, days.Today); Assert.Equal(90, days.Previous.Last(d => d.Cumulative is not null).Cumulative);
Assert.Null(LimitAnalysis.Recent(current, [old], now));
}
[Theory]
[InlineData(-900, true)]
[InlineData(900, true)]
[InlineData(-901, false)]
[InlineData(901, false)]
[InlineData(604800, false)]
public void InstanceToleranceIsInclusiveAndKeepsWindowAndProviderIdentity(int seconds, bool same)
{
var window = Window();
var other = window with { ResetsAt = window.ResetsAt!.Value.AddSeconds(seconds) };
Assert.Equal(same, LimitAnalysis.SameInstance(window, other));
Assert.Equal(same, LimitAnalysis.SameInstance(other, window));
Assert.False(LimitAnalysis.SameInstance(window, window with { Id = "session" }));
Assert.False(LimitAnalysis.SameInstance(window, window with { Provider = Provider.Codex }));
Assert.False(LimitAnalysis.SameInstance(window with { ResetsAt = null }, window with { ResetsAt = null }));
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void SessionRecentRateSurvivesMinuteDriftAcrossMidnight(int minutes)
{
var now = new DateTimeOffset(2026, 10, 14, 2, 0, 0, TimeSpan.Zero);
var session = new LimitWindow(Provider.Claude, "session", "Session", 30, now.AddHours(2), TimeSpan.FromHours(5), now, "fixture");
var samples = new[] { session with { UsedPercent = 0, SampleTime = now.AddHours(-3), ResetsAt = session.ResetsAt!.Value.AddMinutes(minutes) },
session with { UsedPercent = 10, SampleTime = now.AddHours(-2), ResetsAt = session.ResetsAt!.Value.AddMinutes(-minutes) } };
var recent = LimitAnalysis.Recent(session, samples, now);
Assert.NotNull(recent); Assert.Equal(240, recent.PercentPerDay); Assert.Equal(50, recent.UseAtReset);
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void LateSampleDeduplicatesAgainstDriftingChronologicalNeighbour(int minutes)
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new DiagnosticLog());
var window = Window();
store.AddLimits([window with { SampleTime = Now.AddHours(2) }]);
store.AddLimits([window with { SampleTime = Now.AddHours(1), UsedPercent = 50 }]);
store.AddLimits([window with { SampleTime = Now.AddMinutes(115), ResetsAt = window.ResetsAt!.Value.AddMinutes(minutes) }]);
Assert.Equal(2, store.LimitSamples(window.Provider, window.Id, Now, Now.AddHours(3)).Count);
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void UnchangedDriftingResetKeepsHourlySamplingAndLatestMetadata(int minutes)
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new DiagnosticLog());
var w = Window();
store.AddLimits([w]);
var drifted = w with { ResetsAt = w.ResetsAt!.Value.AddMinutes(minutes), SampleTime = Now.AddMinutes(5) };
store.AddLimits([drifted]);
Assert.Single(store.LimitSamples(w.Provider, w.Id, Now.AddHours(-1), Now.AddHours(1)));
Assert.Equal(drifted.ResetsAt, Assert.Single(store.LatestLimits(w.Provider)).ResetsAt);
store.AddLimits([drifted with { UsedPercent = 61, SampleTime = Now.AddMinutes(10) }]);
store.AddLimits([w with { ResetsAt = w.ResetsAt.Value.AddDays(7), SampleTime = Now.AddMinutes(15), UsedPercent = 61 }]);
Assert.Equal(3, store.LimitSamples(w.Provider, w.Id, Now.AddHours(-1), Now.AddHours(1)).Count);
}
[Fact] public void AverageAndRecentAreIndependent()
{
var w = Window();
Assert.Equal(120, LimitAnalysis.AverageUseAtReset(w, Now));
var recent = LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-12), UsedPercent = 50 }], Now);
Assert.NotNull(recent); Assert.Equal(20, recent.PercentPerDay); Assert.Equal(130, recent.UseAtReset);
Assert.Equal(Now.AddDays(2), recent.ReachesLimit);
}
[Fact] public void RecentRequiresThreeHoursOfSameResetAndLast24Hours()
{
var w = Window();
Assert.Null(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-2), UsedPercent = 40 }], Now));
Assert.Null(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-4), ResetsAt = Now, UsedPercent = 40 }], Now));
Assert.Null(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-25), UsedPercent = 40 }], Now));
Assert.NotNull(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-3), UsedPercent = 40 }], Now));
}
[Fact] public void FlatRecentRateHasNoLimitDateAndDecreasingSamplesAreUnknown()
{
var w = Window();
var recent = LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-4) }], Now);
Assert.NotNull(recent); Assert.Equal(60, recent.UseAtReset); Assert.Null(recent.ReachesLimit);
Assert.Null(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-4), UsedPercent = 70 }], Now));
}
[Fact] public void DaysUsePriorSampleAndKeepUnknownBaselinesUnknown()
{
var w = Window();
var days = LimitAnalysis.Days(w, [w with { SampleTime = Now.AddHours(-14), UsedPercent = 51 }], Now, TimeZoneInfo.Utc)!;
Assert.Equal(9, days.Today); Assert.Equal(100d / 7, days.EvenPace); Assert.Equal(40 / 3.5, days.DailyBudget);
Assert.Contains(days.Current, d => d.IsFuture && d.Used is null);
Assert.Contains(days.Current, d => d.Start == Now.AddHours(-36) && d.Used is null);
Assert.Null(LimitAnalysis.Days(w, [], Now, TimeZoneInfo.Utc)!.Today);
}
[Fact] public void FirstDayStartsAtZeroAndPreviousInstanceIsReturned()
{
var w = Window() with { ResetsAt = Now.AddDays(7).AddHours(-2) };
var previous = w with { ResetsAt = w.ResetsAt!.Value.AddDays(-7), SampleTime = Now.AddHours(-3), UsedPercent = 80 };
var days = LimitAnalysis.Days(w, [previous], Now, TimeZoneInfo.Utc)!;
Assert.Equal(60, days.Today); Assert.NotEmpty(days.Previous);
Assert.Null(LimitAnalysis.Days(w with { Length = TimeSpan.FromHours(5) }, [], Now));
}
[Theory]
[InlineData("Europe/Berlin", 2026, 3, 29, 23)]
[InlineData("Europe/Berlin", 2026, 10, 25, 25)]
[InlineData("America/Santiago", 2026, 9, 6, 23)]
public void DaysFollowCalendarIncludingMissingMidnight(string id, int year, int month, int day, int hours)
{
var zone = TimeZoneInfo.FindSystemTimeZoneById(id);
var start = CalendarDays.Start(new DateTime(year, month, day), zone);
var now = start.AddHours(12);
var w = Window() with { ResetsAt = start.AddDays(5), SampleTime = now };
var days = LimitAnalysis.Days(w, [w with { SampleTime = start.AddHours(-1), UsedPercent = 50 }], now, zone)!;
var today = Assert.Single(days.Current, d => d.IsToday);
Assert.Equal(hours, (today.End - today.Start).TotalHours); Assert.Equal(10, today.Used);
}
[Fact] public void ModelSeriesGroupsInOnePassAndMatchesTotals()
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new DiagnosticLog());
store.Add(new(Provider.Claude, Now.AddHours(-2), "a", "p", new(Total: 20), "a"));
store.Add(new(Provider.Claude, Now.AddHours(-2), "b", "p", new(Total: 30), "b"));
store.Add(new(Provider.Claude, Now.AddHours(-1), "a", "p", new(Total: 40), "c"));
store.Add(new(Provider.Codex, Now.AddHours(-1), "a", "p", new(Total: 900), "d"));
var points = store.TokenSeriesByModel(Provider.Claude, Now.AddDays(-1), Now, SeriesInterval.Day, TimeZoneInfo.Utc);
Assert.Equal(2, points.Count); Assert.Equal(90, points.Sum(p => p.Counts.Total));
Assert.Equal(60, points.Single(p => p.Model == "a").Counts.Total);
}
}
@@ -0,0 +1,117 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class LimitInstanceTests
{
private static readonly DateTimeOffset Day = new(2026, 10, 15, 0, 0, 0, TimeSpan.Zero);
private static LimitWindow Window(DateTimeOffset start, TimeSpan length, DateTimeOffset sample, double used) =>
new(Provider.Codex, "window", "Window", used, start + length, length, sample, "fixture");
private static ModelTokenPoint Token(DateTimeOffset time, long input) => new(time, "model", new(Input: input, Total: input));
private static LimitEstimate Analyze(LimitWindow current, LimitWindow[] samples, ModelTokenPoint[] tokens, DateTimeOffset now) =>
LimitAnalysis.Analyze(current, samples, tokens, now, TimeZoneInfo.Utc)!;
[Fact] public void SessionGapKeepsTheReviewersMeasuredSessionAndItsOwnScale()
{
var length = TimeSpan.FromHours(5);
var current = Window(Day.AddHours(14), length, Day.AddHours(15), 50);
var previous = Window(Day.AddHours(3), length, Day.AddHours(7.5), 80);
var first = previous with { SampleTime = Day.AddHours(3.5), UsedPercent = 10 };
var result = Analyze(current, [previous, first],
[Token(Day.AddHours(3), 50), Token(Day.AddHours(7), 350), Token(Day.AddHours(9), 1000000), Token(Day.AddHours(14), 100)], current.SampleTime);
var past = Assert.Single(result.Past);
Assert.Equal(Day.AddHours(3), past.Start); Assert.Equal(Day.AddHours(8), past.End);
Assert.Equal(.2, past.Scale); Assert.Equal(80, past.Peak); Assert.Null(past.ReachedLimit);
Assert.Contains(new(first.SampleTime, 10, UseOrigin.Measured), past.Points);
Assert.Contains(new(previous.SampleTime, 80, UseOrigin.Measured), past.Points);
Assert.Equal(.5, result.Current.Scale);
}
[Fact] public void SeveralRealSessionsLeaveEveryGapUnassigned()
{
var length = TimeSpan.FromHours(5);
var current = Window(Day.AddHours(24), length, Day.AddHours(25), 50);
var previous = new[] { 0, 8, 16 }.Select((hour, i) => Window(Day.AddHours(hour), length, Day.AddHours(hour + 2), 20 * (i + 1))).ToArray();
var tokens = new[] { 0, 8, 16, 24 }.Select(hour => Token(Day.AddHours(hour), 100))
.Concat(new[] { 6, 14, 22 }.Select(hour => Token(Day.AddHours(hour), 1000000))).ToArray();
var result = Analyze(current, previous, tokens, current.SampleTime);
Assert.Equal(3, result.Past.Count);
for (var i = 0; i < 3; i++)
{
var sample = previous[2 - i]; var past = result.Past[i];
Assert.Equal(sample.ResetsAt!.Value - length, past.Start); Assert.Equal(sample.ResetsAt, past.End);
Assert.Equal(sample.UsedPercent, past.Peak); Assert.Equal(sample.UsedPercent / 100, past.Scale);
Assert.Contains(new(sample.SampleTime, sample.UsedPercent, UseOrigin.Measured), past.Points);
}
AssertNoOverlap(result);
}
[Theory]
[InlineData(5)]
[InlineData(168)]
public void EarlyCodexReplacementSplitsAtResetDerivedStartBeforeItsFirstSample(int hours)
{
var length = TimeSpan.FromHours(hours); var start = Day.AddHours(10);
var oldStart = hours == 5 ? start.AddHours(-3) : start.AddDays(-3);
var previous = Window(oldStart, length, oldStart.AddHours(2), 50);
var current = Window(start, length, start.AddHours(1.5), 40);
var first = current with { SampleTime = start.AddHours(1), UsedPercent = 20 };
var result = Analyze(current, [previous, first],
[Token(oldStart, 100), Token(start, 300), Token(start.AddHours(1), 200)], start.AddHours(2));
var past = Assert.Single(result.Past);
Assert.Equal(start, result.Current.Start); Assert.Equal(start, past.End);
Assert.Equal(oldStart, past.Start); Assert.Equal(.5, past.Scale); Assert.Equal(50, past.Peak);
Assert.Null(past.ReachedLimit); Assert.Equal(40d / 500, result.Current.Scale);
Assert.All(past.Points, p => Assert.True(p.Time <= start));
AssertNoOverlap(result);
}
[Fact] public void EarlierWeeksWithoutSamplesAreInferredInWholeNonOverlappingWindows()
{
var length = TimeSpan.FromDays(7); var current = Window(Day, length, Day.AddDays(2), 20);
var tokens = new[] { Token(Day, 100), Token(Day.AddDays(-7), 100), Token(Day.AddDays(-14), 200), Token(Day.AddDays(-21), 300) };
var result = Analyze(current, [], tokens, current.SampleTime);
Assert.Equal(3, result.Past.Count);
for (var i = 0; i < 3; i++)
{
var past = result.Past[i]; Assert.Equal(Day.AddDays(-7 * (i + 1)), past.Start);
Assert.Equal(past.Start + length, past.End); Assert.Equal(.2, past.Scale); Assert.Equal(20 * (i + 1), past.Peak);
Assert.All(past.Points.Skip(1), p => Assert.Equal(UseOrigin.Estimated, p.Origin));
}
AssertNoOverlap(result);
}
[Fact] public void ARealWeekBetweenInferredWeeksKeepsItsSamplesAndLeavesTheShortGapEmpty()
{
var length = TimeSpan.FromDays(7); var current = Window(Day, length, Day.AddDays(2), 20);
var start = Day.AddDays(-17); var previous = Window(start, length, start.AddDays(6), 60);
var first = previous with { SampleTime = start.AddHours(1), UsedPercent = 10 };
var result = Analyze(current, [first, previous],
[Token(Day, 100), Token(Day.AddDays(-7), 100), Token(start, 100), Token(start.AddDays(5), 100),
Token(start.AddDays(-7), 200), Token(previous.ResetsAt!.Value.AddDays(1), 1000000)], current.SampleTime);
Assert.Equal(3, result.Past.Count);
Assert.Equal(Day.AddDays(-7), result.Past[0].Start); Assert.Equal(20, result.Past[0].Peak);
var real = result.Past[1]; Assert.Equal(start, real.Start); Assert.Equal(previous.ResetsAt, real.End);
Assert.Equal(.3, real.Scale); Assert.Equal(60, real.Peak);
Assert.Contains(new(first.SampleTime, 10, UseOrigin.Measured), real.Points);
Assert.Contains(new(previous.SampleTime, 60, UseOrigin.Measured), real.Points);
Assert.Equal(start.AddDays(-7), result.Past[2].Start); Assert.Equal(.2, result.Past[2].Scale); Assert.Equal(40, result.Past[2].Peak);
AssertNoOverlap(result);
}
[Theory]
[InlineData(5)]
[InlineData(24)]
public void ADayOrShorterNeverInfersAnUnobservedWindow(int hours)
{
var length = TimeSpan.FromHours(hours); var current = Window(Day, length, Day.AddHours(1), 20);
var result = Analyze(current, [], [Token(Day, 100), Token(Day - length, 10000)], current.SampleTime);
Assert.Empty(result.Past);
}
private static void AssertNoOverlap(LimitEstimate result)
{
var spans = result.Past.Append(result.Current).OrderBy(p => p.Start).ToArray();
for (var i = 1; i < spans.Length; i++) Assert.True(spans[i - 1].End <= spans[i].Start);
}
}
+9
View File
@@ -29,6 +29,15 @@ public class PaceTests
[Fact] public void ProjectionAfterResetIsHidden() => Assert.Null(Pace.Calculate(Window(10), Now).Projection); [Fact] public void ProjectionAfterResetIsHidden() => Assert.Null(Pace.Calculate(Window(10), Now).Projection);
[Fact] public void ZeroElapsedDoesNotProject() => Assert.Null(Pace.Calculate(Window(50, 0), Now).Projection); [Fact] public void ZeroElapsedDoesNotProject() => Assert.Null(Pace.Calculate(Window(50, 0), Now).Projection);
[Fact] public void ZeroUsageDoesNotProject() => Assert.Null(Pace.Calculate(Window(0), Now).Projection); [Fact] public void ZeroUsageDoesNotProject() => Assert.Null(Pace.Calculate(Window(0), Now).Projection);
[Fact] public void BelowAlertThresholdStillProjectsWithoutPopup()
{
var window = Window(55);
var pace = Pace.Calculate(window, Now);
Assert.Equal(PaceState.OnTrack, pace.State);
Assert.NotNull(pace.Projection);
Assert.True(pace.Projection < window.ResetsAt);
Assert.Null(new PopupDecider().Observe(window, pace, new Settings()));
}
[Fact] [Fact]
public void PopupHysteresisPreventsFlappingAndRearmsAfterClear() public void PopupHysteresisPreventsFlappingAndRearmsAfterClear()
@@ -5,6 +5,23 @@ namespace FinalToken.Core.Tests;
public sealed class PartialSettingsTests public sealed class PartialSettingsTests
{ {
[Fact]
public void MissingSettingsIsNormalFirstStart()
{
using var directory = new TestDirectory();
var diagnostics = new DiagnosticLog();
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, diagnostics));
Assert.Empty(diagnostics.Recent);
}
[Fact]
public void PresentMalformedSettingsIsDiagnostic()
{
using var directory = new TestDirectory();
directory.Write("settings.json", "{broken");
var diagnostics = new DiagnosticLog();
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, diagnostics));
Assert.Equal("settings-defaults", Assert.Single(diagnostics.Recent).Code);
}
[Theory] [Theory]
[InlineData("{}")] [InlineData("{}")]
[InlineData("{\"refreshInterval\":\"00:00:30\"}")] [InlineData("{\"refreshInterval\":\"00:00:30\"}")]
+1 -1
View File
@@ -123,7 +123,7 @@ public class StorageTests
using var directory = new TestDirectory(); using var directory = new TestDirectory();
var log = new DiagnosticLog(); var log = new DiagnosticLog();
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, log)); Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, log));
Assert.Single(log.Recent); Assert.Empty(log.Recent);
var settings = new Settings { StreamDeckInstallMode = InstallMode.Automatic, Claude = new() { Enabled = false } }; var settings = new Settings { StreamDeckInstallMode = InstallMode.Automatic, Claude = new() { Enabled = false } };
await SettingsFile.SaveAsync(directory.Path, settings, cancellationToken: TestContext.Current.CancellationToken); await SettingsFile.SaveAsync(directory.Path, settings, cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(settings, SettingsFile.Load(directory.Path, new())); Assert.Equal(settings, SettingsFile.Load(directory.Path, new()));
@@ -0,0 +1,161 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class TokenEstimateTests
{
private static readonly DateTimeOffset Start = new(2026, 10, 8, 0, 0, 0, TimeSpan.Zero);
private static readonly DateTimeOffset Now = Start.AddDays(6).AddHours(12);
private static LimitWindow Window => new(Provider.Claude, "week", "Week · all models", 65, Start.AddDays(7), TimeSpan.FromDays(7), Now, "fixture");
private static ModelTokenPoint Token(DateTimeOffset time, long input = 100, string model = "claude-fable") => new(time, model, new(Input: input, Total: input));
private static ModelTokenPoint[] WeekTokens => Enumerable.Range(0, 6).Select(i => Token(Start.AddDays(i))).Append(Token(Start.AddDays(6), 50)).ToArray();
[Fact] public void ProviderWeightsDoNotDoubleCountCachedInputOrReasoning()
{
var counts = new TokenCounts(Input: 100, CacheRead: 40, CacheWrite: 20, Output: 10, ReasoningOutput: 8);
Assert.Equal(179, TokenWeights.Weighted(Provider.Claude, counts));
Assert.Equal(144, TokenWeights.Weighted(Provider.Codex, counts));
}
[Fact] public void NewestSampleCalibratesScaleAndDaysMixMeasuredAndEstimated()
{
var w = Window;
var baseline = w with { SampleTime = Start.AddDays(6), UsedPercent = 60 };
var result = LimitAnalysis.Analyze(w, [baseline], WeekTokens, Now, TimeZoneInfo.Utc)!;
Assert.Equal(.1, result.Current.Scale);
Assert.Equal(5, result.Days!.Today); Assert.Equal(UseOrigin.Measured, result.Days.TodayOrigin);
Assert.Equal(10, result.Days.Current[0].Used); Assert.Equal(UseOrigin.Estimated, result.Days.Current[0].Origin);
Assert.Contains(result.Current.Points, p => p.Origin == UseOrigin.Estimated);
Assert.Contains(result.Current.Points, p => p.Time == Now && p.Used == 65 && p.Origin == UseOrigin.Measured);
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void DriftAndMissingBaselineFallBackToTokens(int drift)
{
var w = Window;
var result = LimitAnalysis.Analyze(w, [w with { ResetsAt = w.ResetsAt!.Value.AddMinutes(drift), SampleTime = Now.AddHours(-2), UsedPercent = 64 }], WeekTokens, Now, TimeZoneInfo.Utc)!;
Assert.Equal(5, result.Days!.Today); Assert.Equal(UseOrigin.Estimated, result.Days.TodayOrigin);
Assert.Contains(result.Current.Points, p => p.Used == 64 && p.Origin == UseOrigin.Measured);
Assert.Equal(.1, result.Current.Scale);
}
[Fact] public void FamilyWindowUsesOnlyMatchingModelsCaseInsensitively()
{
var w = Window with { Label = "Current week (FABLE)", UsedPercent = 50 };
var tokens = new[] { Token(Start, 100, "claude-fable-5"), Token(Start, 10000, "claude-sonnet"), Token(Start, 10000, "unrelated") };
Assert.Equal(.5, LimitAnalysis.Analyze(w, [], tokens, Now, TimeZoneInfo.Utc)!.Current.Scale);
Assert.Equal(50d / 20100, LimitAnalysis.Analyze(w with { Label = "Week" }, [], tokens, Now, TimeZoneInfo.Utc)!.Current.Scale);
}
[Theory]
[InlineData("Current week (Cedar)")]
[InlineData("Week \u00b7 Cedar")]
public void FamilyNamesAreNotLimitedToKnownModelNames(string label)
{
var window = Window with { Label = label, UsedPercent = 50 };
ModelTokenPoint[] tokens = [Token(Start, 100, "claude-CEDAR-7"), Token(Start, 10000, "claude-fable")];
Assert.Equal(.5, LimitAnalysis.Analyze(window, [], tokens, Now, TimeZoneInfo.Utc)!.Current.Scale);
}
[Fact] public void FinishedInstancesUseOwnSampleOrCurrentScale()
{
var w = Window with { UsedPercent = 50 };
var tokens = new[] { Token(Start, 100), Token(Start.AddDays(-7), 100), Token(Start.AddDays(-14), 300) };
var previous = w with { ResetsAt = Start, SampleTime = Start.AddHours(-1), UsedPercent = 90 };
var result = LimitAnalysis.Analyze(w, [previous], tokens, Now, TimeZoneInfo.Utc)!;
Assert.Equal(.5, result.Current.Scale); Assert.Equal(.9, result.Past[0].Scale); Assert.Equal(90, result.Past[0].Peak);
Assert.Equal(.5, result.Past[1].Scale); Assert.Equal(100, result.Past[1].Peak); Assert.NotNull(result.Past[1].ReachedLimit);
Assert.All(result.Past[1].Points.Skip(1), p => Assert.Equal(UseOrigin.Estimated, p.Origin));
}
[Fact] public void ExpiredInstanceNeverConsumesTokensFromTheNextWindow()
{
var window = Window;
var afterReset = window.ResetsAt!.Value.AddHours(1);
var tokens = WeekTokens.Append(Token(afterReset, 1000000)).ToArray();
var result = LimitAnalysis.Analyze(window, [], tokens, afterReset.AddHours(1), TimeZoneInfo.Utc)!;
Assert.All(result.Current.Points, p => Assert.True(p.Time <= window.ResetsAt));
Assert.Equal(65, result.Current.Peak);
}
[Fact] public void NewTokensAfterTheLastSampleAddOnlyTheNewBucket()
{
var window = Window with { SampleTime = Now.AddMinutes(-30) };
var tokens = WeekTokens.Append(Token(Now, 100)).ToArray();
var result = LimitAnalysis.Analyze(window, [], tokens, Now.AddMinutes(30), TimeZoneInfo.Utc)!;
Assert.Equal(.1, result.Current.Scale);
Assert.Equal(75, result.Current.Points.Last().Used);
Assert.Equal(UseOrigin.Estimated, result.Current.Points.Last().Origin);
}
[Fact] public void EstimatesStopAtTheCrossingAndDailyUseCannotSpendTheLimitTwice()
{
var window = Window with { UsedPercent = 50 };
var pastStart = Start.AddDays(-7);
ModelTokenPoint[] tokens = [Token(Start, 100), Token(pastStart, 300), Token(pastStart.AddDays(1), 300)];
var result = LimitAnalysis.Analyze(window, [], tokens, Now, TimeZoneInfo.Utc)!;
var past = result.Past[0];
Assert.Equal(100, past.Peak);
Assert.Equal(pastStart.AddMinutes(40), past.ReachedLimit);
Assert.Equal(UseOrigin.Estimated, past.ReachedOrigin);
Assert.All(past.Points, p => Assert.InRange(p.Used, 0, 100));
Assert.Contains(past.Points, p => p.Time == past.ReachedLimit && p.Used == 100);
Assert.Equal(100, past.Days.Sum(d => d.Used ?? 0));
Assert.Equal(0, past.Days[1].Used);
}
[Fact] public void MeasuredSamplesRemainUnchangedWhenLaterEstimatesReachTheLimit()
{
var window = Window;
var pastStart = Start.AddDays(-7);
var measured = window with { ResetsAt = Start, SampleTime = pastStart.AddHours(2), UsedPercent = 10 };
ModelTokenPoint[] tokens = [Token(Start, 100), Token(pastStart, 100), Token(pastStart.AddDays(1), 10000)];
var past = LimitAnalysis.Analyze(window, [measured], tokens, Now, TimeZoneInfo.Utc)!.Past[0];
Assert.Equal(100, past.Peak); Assert.Equal(UseOrigin.Estimated, past.ReachedOrigin);
Assert.Equal(new(measured.SampleTime, 10, UseOrigin.Measured), past.Points.Single(p => p.Time == measured.SampleTime));
Assert.Equal(10, measured.UsedPercent);
Assert.Equal(pastStart.AddDays(1).AddMinutes(5.4), past.ReachedLimit);
Assert.All(past.Days, day => Assert.InRange(day.Used ?? 0, 0, 100));
Assert.Equal(100, past.Days.Sum(day => day.Used ?? 0));
}
[Fact] public void EarlyReplacementEndsThePreviousInstanceAndOwnsItsBoundaryHour()
{
var transition = new DateTimeOffset(2026, 10, 15, 8, 18, 0, TimeSpan.Zero);
var now = transition.AddHours(1);
var current = Window with { ResetsAt = transition.AddDays(7), SampleTime = now, UsedPercent = 2 };
var first = current with { SampleTime = transition, UsedPercent = 1 };
var previous = current with { ResetsAt = transition.AddDays(5), SampleTime = transition.AddDays(-1), UsedPercent = 20 };
var previousStart = previous.ResetsAt!.Value - previous.Length!.Value;
ModelTokenPoint[] tokens = [Token(previousStart, 100), Token(transition.AddMinutes(-18), 100), Token(transition.AddMinutes(42), 1000)];
var result = LimitAnalysis.Analyze(current, [previous, first], tokens, now, TimeZoneInfo.Utc)!;
var past = result.Past[0];
Assert.All(past.Points, p => Assert.True(p.Time <= transition));
Assert.All(past.Days, d => Assert.True(d.End <= transition));
Assert.Equal(transition, past.End);
Assert.Equal(previousStart, past.Start);
Assert.Equal(20, past.Points.Single(p => p.Time == previous.SampleTime).Used);
Assert.Equal(20, past.Peak);
Assert.Equal(2d / 1100, result.Current.Scale);
Assert.DoesNotContain(result.Past, p => p.Points.Any(v => v.Time > transition));
}
[Theory]
[InlineData(5)]
[InlineData(168)]
public void ForecastsBeginAtExactlyTenPercentWithoutChangingState(int hours)
{
var start = Start; var length = TimeSpan.FromHours(hours);
var atThreshold = start + TimeSpan.FromTicks(length.Ticks / 10);
var before = atThreshold.AddTicks(-1);
var window = Window with { ResetsAt = start + length, Length = length, SampleTime = before, UsedPercent = 11 };
Assert.Equal(PaceState.OnTrack, Pace.Calculate(window, before).State);
var pace = Pace.Calculate(window, before);
Assert.Null(pace.Projection);
var popup = new PopupDecider().Observe(window, pace, new Settings());
Assert.Null(popup);
Assert.Null(LimitAnalysis.AverageUseAtReset(window, before));
Assert.Null(LimitAnalysis.Recent(window, [window with { SampleTime = start, UsedPercent = 0 }], before));
window = window with { SampleTime = atThreshold };
Assert.NotNull(Pace.Calculate(window, atThreshold).Projection);
Assert.NotNull(LimitAnalysis.AverageUseAtReset(window, atThreshold));
if (hours == 168) Assert.NotNull(LimitAnalysis.Recent(window, [window with { SampleTime = start, UsedPercent = 0 }], atThreshold));
}
[Fact] public void NoTokensMeansNoEstimates()
{
var result = LimitAnalysis.Analyze(Window, [], [], Now, TimeZoneInfo.Utc)!;
Assert.Null(result.Current.Scale); Assert.Null(result.Days!.Today); Assert.Empty(result.Past);
Assert.DoesNotContain(result.Current.Points, p => p.Origin == UseOrigin.Estimated);
}
}