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
+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).
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.
## 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.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Styling;
using FinalToken.Core;
using System.Globalization;
@@ -10,9 +8,26 @@ namespace FinalToken.App;
public sealed class UsageChart : Control
{
private static readonly IBrush[] Palette = [Brush.Parse("#3878D4"), Brush.Parse("#B377D1"), Brush.Parse("#249A88"), Brush.Parse("#C98926")];
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>
public static Rect BarBounds(double x, double bottom, double width, double height, double scaling = 1)
{
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)
{
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 fraction = target / 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, intervals + 1).Select(i => i * step).ToArray();
return Enumerable.Range(0, (int)Math.Ceiling(maximum / step) + 1).Select(i => i * step).ToArray();
}
public IReadOnlyList<ChartValue> Values { get; init; } = [];
public IReadOnlyList<string> SeriesNames { 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);
private readonly List<(Rect Rect, string Text)> hits = [];
private readonly List<(Rect Rect, Func<DataTooltip> Tip)> hits = [];
public UsageChart()
{
Height = 180;
PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Text);
PointerExited += (_, _) => ToolTip.SetTip(this, null);
Height = 208;
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);
hits.Clear();
var ink = ActualThemeVariant == ThemeVariant.Dark ? Brushes.WhiteSmoke : Brushes.DarkSlateGray;
var plot = new Rect(58, 12, Math.Max(1, Bounds.Width - 74), Math.Max(1, Bounds.Height - 46));
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 plot = new Rect(50, 16, Math.Max(1, Bounds.Width - 66), Math.Max(1, Bounds.Height - 48));
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 max = Math.Max(1, ticks[^1]);
foreach (var tick in ticks)
{
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));
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}";
Text(context, label, new(0, y - 8), ink);
context.DrawLine(new Pen(Ui.Colour(tick == 0 ? "Axis" : "Grid", dark)), new(plot.Left, y), new(plot.Right, y));
ChartText.Draw(context, Percent ? $"{tick:0}%" : Display.Axis(tick), 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; }
var series = Values.Select(v => v.Series).Distinct().ToArray();
if (groups.Length == 0) { ChartText.Draw(context, "No samples in this range", new(plot.Left + 12, plot.Top + 32), ink); return; }
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)
{
var colour = Ui.ProviderColour(LimitProvider, dark);
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))
{
var point = Position(value, value.Value);
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)
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);
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")}"));
context.DrawEllipse(colour, null, point, 2, 2);
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;
}
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
{
var duration = Math.Max(Interval.TotalSeconds, (groups[^1].Key - groups[0].Key).TotalSeconds + Interval.TotalSeconds);
var width = plot.Width * Interval.TotalSeconds / duration;
for (var i = 0; i < groups.Length; i++)
foreach (var group in groups)
{
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 x = plot.Left + (groups[i].Key - groups[0].Key).TotalSeconds / duration * plot.Width;
var rect = new Rect(x + Math.Min(1, width / 8), bottom - height, Math.Max(0.5, width - Math.Min(2, width / 4)), height);
context.DrawRectangle(Palette[Array.IndexOf(series, value.Series) % Palette.Length], null, rect);
hits.Add((rect, $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Series}: {value.Value:N0} tokens"));
var x = X(group.Key);
var gap = width < 6 ? 0 : 2;
var rect = BarBounds(x, bottom, width, height, TopLevel.GetTopLevel(this)?.RenderScaling ?? 1);
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;
}
}
}
Text(context, Display.ChartDateLabel(groups[0].Key, Interval), new(plot.Left, plot.Bottom + 8), ink);
Text(context, Display.ChartDateLabel(groups[^1].Key, Interval), new(Math.Max(plot.Left, plot.Right - 110), plot.Bottom + 8), ink);
ToolTip.SetShowDelay(this, 0);
// Daily calendar ticks remain anchored to local dates through DST.
var spanDays = (lastTime - minTime).TotalDays;
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 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)
{
base.Render(context);
context.DrawRectangle(Brush.Parse("#338795A5"), null, new Rect(Bounds.Size), 4, 4);
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);
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size));
var dark = Ui.Dark(this); var colour = Ui.ProviderColour(window.Window.Provider, dark);
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)
context.DrawLine(new Pen(ActualThemeVariant == ThemeVariant.Dark ? Brushes.White : Brushes.Black, 2), new(Bounds.Width * elapsed, 0), new(Bounds.Width * elapsed, Bounds.Height));
ToolTip.SetTip(this, $"Used {window.Window.UsedPercent:0.##}% · expected {window.Pace.ElapsedFraction * 100:0.##}%");
context.DrawLine(new Pen(Ui.Colour("Ink", dark), 2), new(Bounds.Width * elapsed, -2), new(Bounds.Width * elapsed, Bounds.Height + 2));
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 PluginInstallStatus pluginStatus = new(PluginInstallState.NoHostFound);
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()
{
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.ActivationRequested += () => Dispatcher.UIThread.Post(OpenPanel);
model.Snapshot = engine.CurrentSnapshot;
model.ProbeInterval = engine.Settings.ProbeInterval;
ageTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
ageTimer.Tick += (_, _) => { if (panel.IsVisible) model.Diagnostics = engine.RecentDiagnostics; };
ageTimer.Start();
@@ -88,7 +89,11 @@ public sealed class DesktopApp : Application
panel.Show(); panel.WindowState = WindowState.Normal; panel.Activate();
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()
{
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 (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.Show();
}
@@ -113,6 +118,7 @@ public sealed class DesktopApp : Application
try { await engine.UpdateSettingsAsync(value); }
catch { await OsStartup.ApplyAsync(previous.StartWithOs); throw; }
if (quitting) return;
model.ProbeInterval = value.ProbeInterval;
await CheckPlugin();
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;
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 BreakdownRow(string Name, TokenCounts Counts, double Share);
public sealed record LimitChart(string Label, IReadOnlyList<ChartValue> Values);
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, IReadOnlyList<Provider>? Providers = null);
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,
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
{
@@ -18,6 +24,16 @@ public partial class PanelViewModel : ObservableObject
[ObservableProperty] private HistoryView history = new([], [], [], [], []);
[ObservableProperty] private IReadOnlyList<Diagnostic> diagnostics = [];
[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
{
@@ -33,43 +49,60 @@ public partial class PanelViewModel : ObservableObject
var providers = snapshot.Providers.Where(p => filter is null || p.Provider == filter).ToArray();
var hourly = Series(SeriesInterval.Hour);
var daily = Series(SeriesInterval.Day);
var details = new List<LimitDetail>();
var limits = providers.SelectMany(p => p.Windows.Select(w =>
{
var samples = store.LimitSamples(p.Provider, w.Window.Id, from, now);
var instanceSamples = store.LimitSamples(p.Provider, w.Window.Id,
w.Window.ResetsAt is { } r && w.Window.Length is { } l ? r - l * 9 - TimeSpan.FromMinutes(15) : now.AddDays(-14), now);
var 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) =>
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,
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();
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 =>
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)
IReadOnlyList<ChartValue> Series(SeriesInterval interval)
{
var end = interval == SeriesInterval.Hour ? time.AddHours(1) : CalendarDays.NextStart(time);
return store.ByModel(provider, time < from ? from : time, end > now ? now : end)
.Select(m => new ChartValue(time, m.Name ?? "Unknown model", m.Counts.Total));
if (filter is null) return providers.SelectMany(p => store.TokenSeries(p.Provider, from, now, interval)
.Select(point => new ChartValue(point.Time, p.Provider.ToString(), point.Counts.Total, CacheRead: point.Counts.CacheRead))).ToArray();
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)
{
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,
g.Aggregate(new TokenCounts(), (sum, r) => sum + r.Counts))).OrderByDescending(r => r.Counts.Total).ToArray();
var rows = providers.SelectMany(p => (models ? store.ByModel(p.Provider, from, now) : store.ByProject(p.Provider, from, now))
.Select(r => (p.Provider, r.Name, r.Counts)))
.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);
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 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)
=> ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "MM-dd" : "MM-dd HH:mm");
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)
=> interval >= TimeSpan.FromDays(1) ? time.DateTime : time.LocalDateTime;
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);
}
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
? $"{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";
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" };
}
+245 -98
View File
@@ -1,130 +1,277 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using FinalToken.Core;
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
{
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)
{
this.model = model;
Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}"; Width = 1160; Height = 920; MinWidth = 720; MinHeight = 500;
var header = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 };
header.Children.Add(Ui.Text("FinalToken", 28));
header.Children.Add(Ui.Button("Refresh now", refresh));
header.Children.Add(Ui.Button("Settings", settings));
header.Children.Add(Ui.Button("Quit", quit));
var range = new ComboBox { ItemsSource = new[] { "24 hours", "7 days", "30 days", "90 days", "All history" }, SelectedIndex = (int)model.Range, MinWidth = 150 };
range.SelectionChanged += (_, _) => { model.Range = (HistoryRange)range.SelectedIndex; reload(); };
var providers = new ComboBox { ItemsSource = new[] { "All providers", "Claude", "Codex" }, SelectedIndex = 0, MinWidth = 150 };
providers.SelectionChanged += (_, _) => { model.ProviderFilter = providers.SelectedIndex == 0 ? null : (Provider)(providers.SelectedIndex - 1); reload(); };
var filters = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 };
filters.Children.Add(range); filters.Children.Add(providers);
var dock = new DockPanel { Margin = new Thickness(0, 18, 0, 0) };
var top = Ui.Stack(header, filters); top.Margin = new Thickness(24, 0, 24, 0);
DockPanel.SetDock(top, Dock.Top); dock.Children.Add(top);
dock.Children.Add(new ScrollViewer { Content = body }); Content = dock;
model.PropertyChanged += (_, _) => RenderModel();
Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}";
Width = 1280; Height = 900; MinWidth = 960; MinHeight = 500; Ui.Theme(this);
var brand = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };
brand.Children.Add(Ui.Text("FinalToken", 20));
var version = Ui.Text(typeof(Program).Assembly.GetName().Version?.ToString(3) ?? "", 12, "Muted"); version.VerticalAlignment = VerticalAlignment.Center;
brand.Children.Add(version);
updated.VerticalAlignment = VerticalAlignment.Center; statuses.VerticalAlignment = VerticalAlignment.Center;
var left = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12, VerticalAlignment = VerticalAlignment.Center };
left.Children.Add(brand); left.Children.Add(updated); left.Children.Add(statuses);
var range = Segments(["24 h", "7 d", "30 d", "90 d", "All"], (int)model.Range, i => { model.Range = (HistoryRange)i; reload(); });
var providers = Segments(["All", "Claude", "Codex"], model.ProviderFilter is { } p ? (int)p + 1 : 0,
i => { model.ProviderFilter = i == 0 ? null : (Provider)(i - 1); reload(); });
refreshButton = Ui.Button("↻", refresh); ToolTip.SetTip(refreshButton, "Refresh local data");
var settingsButton = Ui.Button("⚙", settings); ToolTip.SetTip(settingsButton, "Settings");
var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };
actions.Children.Add(range); actions.Children.Add(providers); actions.Children.Add(refreshButton); actions.Children.Add(settingsButton);
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();
}
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()
{
body.Children.Clear();
body.Children.Add(Ui.Text(model.Message));
var offset = scroll.Offset;
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)
{
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}"));
foreach (var window in provider.Windows)
{
var w = window.Window; var pace = window.Pace;
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);
title.Foreground = PaceBar.Colour(pace.State);
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));
card.Children.Add(Ui.Text("Today " + Display.Tokens(provider.Today)));
card.Children.Add(Ui.Text("Session " + Display.Tokens(provider.Session)));
card.Children.Add(Ui.Text("Week " + Display.Tokens(provider.Week)));
card.Children.Add(Ui.Text("Cache read is included in Codex input; reasoning is included in output.", 11));
body.Children.Add(Ui.Card(card));
var label = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 };
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)
{
if (provider.Status != ProviderStatus.Available)
tiles.Add(Ui.Card(Ui.Stack(Ui.Text(provider.Provider + " · " + provider.Status, 15), Ui.Text(provider.Reason ?? "Provider disabled", 13, "Secondary"))));
else foreach (var window in provider.Windows) tiles.Add(LimitTile(window, now));
}
content.Add(Ui.Columns(tiles, limitColumns));
var longWindows = model.History.Details.Where(d => d.Days is not null && providers.Any(p => p.Provider == d.Provider &&
p.Status == ProviderStatus.Available && p.Windows.Any(w => w.Window.Id == d.Id))).ToArray();
if (longWindows.Length > 0)
{
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;
body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), Legend(h.Hourly), new UsageChart { Values = h.Hourly })));
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) })));
foreach (var limit in h.Limits)
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 })));
body.Children.Add(Breakdown("By model", h.Models));
body.Children.Add(Breakdown("By project", h.Projects));
var diagnostics = Ui.Stack(Ui.Text("Recent diagnostics", 19));
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."));
body.Children.Add(Ui.Card(diagnostics));
}
private static Control Legend(IReadOnlyList<ChartValue> values)
{
var legend = new WrapPanel { Orientation = Orientation.Horizontal };
var index = 0;
foreach (var series in values.Select(v => v.Series).Distinct())
var seriesNames = h.Hourly.Concat(h.Daily).Select(v => v.Series).Distinct().Order(StringComparer.Ordinal).ToArray();
Control TokenChart(string title, IReadOnlyList<ChartValue> values, bool daily) => Ui.Card(Ui.Stack(Ui.Text(title, 15),
Legend(seriesNames), new UsageChart { Values = values.Select(v => v with { Value = Math.Max(0, v.Value - (model.IncludeCacheReads ? 0 : v.CacheRead)) }).ToArray(),
SeriesNames = seriesNames, Interval = daily ? TimeSpan.FromDays(1) : TimeSpan.FromHours(1) }));
content.Add(Ui.Columns([TokenChart("Tokens per hour", h.Hourly, false), TokenChart("Tokens per day", h.Daily, true)], wide));
var windows = h.Limits.Where(l => l.Analysis?.Current.HasData == true).ToArray();
if (windows.Length > 0)
{
var label = Ui.Text("● " + series, 12); label.Foreground = UsageChart.SeriesColour(index++);
label.Margin = new Thickness(0, 0, 14, 0); legend.Children.Add(label);
content.Add(Ui.Text("Window charts", 20));
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));
}
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 lines = Ui.Stack();
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"));
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 w = window.Window; var pace = window.Pace;
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;
}
private static Border Breakdown(string title, IReadOnlyList<BreakdownRow> rows)
public static string[] ShortProjectNames(string[] paths)
{
var table = Ui.Stack(Ui.Text(title, 19));
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("3*,1*,1*,1*,1*,1*,1*,1*"), MinWidth = 900 };
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 parts = paths.Select(p => p.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries)).ToArray();
return parts.Select((p, i) =>
{
var c = row.Counts;
AddRow([row.Name, c.Total.ToString("N0"), row.Share.ToString("P1"), c.Input.ToString("N0"), c.CacheRead.ToString("N0"),
c.CacheWrite.ToString("N0"), c.Output.ToString("N0"), c.ReasoningOutput.ToString("N0")], index++);
}
table.Children.Add(new ScrollViewer { Content = grid, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled });
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));
for (var column = 0; column < values.Length; column++)
{
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);
}
}
var depth = Math.Min(2, p.Length);
while (depth < p.Length && parts.Where((_, j) => j != i).Any(other => string.Join('/', other.TakeLast(depth)) == string.Join('/', p.TakeLast(depth)))) depth++;
return string.Join('/', p.TakeLast(depth));
}).ToArray();
}
// Leave wheel events unhandled so they bubble to the page instead of changing selection.
private sealed class WindowSelector : ComboBox
{
protected override Type StyleKeyOverride => typeof(ComboBox);
protected override void OnPointerWheelChanged(Avalonia.Input.PointerWheelEventArgs e) { }
}
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)
{
Width = 380; Height = install is null ? 145 : 180;
RequestedThemeVariant = ThemeVariant.Dark;
Width = 400; Height = install is null ? 152 : 184; Ui.Theme(this);
WindowDecorations = WindowDecorations.None; CanResize = false; Topmost = true; ShowInTaskbar = false; ShowActivated = false;
var body = Ui.Stack(Ui.Text(title, 19), Ui.Text(message));
if (install is not null)
@@ -24,10 +23,8 @@ public sealed class PopupWindow : Window
actions.Children.Add(Ui.Button("Not now", () => { dismiss?.Invoke(); Close(); }));
body.Children.Add(actions);
}
var card = Ui.Card(body); card.Background = Brush.Parse("#202C40");
body.Resources["TextControlForeground"] = Brushes.WhiteSmoke;
foreach (var text in body.Children.OfType<TextBlock>()) text.Foreground = Brushes.WhiteSmoke;
((TextBlock)body.Children[0]).Foreground = accent ?? Brushes.WhiteSmoke;
var card = Ui.Card(body);
if (accent is not null) { card.Resources["Border"] = accent; card.BorderThickness = new Thickness(3, 1, 1, 1); }
Content = card;
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)}",
$"{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
+85 -36
View File
@@ -1,5 +1,6 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using FinalToken.Core;
using FinalToken.Core.StreamDeck;
@@ -7,30 +8,62 @@ namespace FinalToken.App;
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;
var body = Ui.Stack(Ui.Text("Settings", 26)); body.Margin = new Thickness(24);
var refresh = Number("Token refresh (seconds, 1–60)", (decimal)initial.RefreshInterval.TotalSeconds, 1, 60);
var probe = Number("Limit probe (minutes, 1–60)", (decimal)initial.ProbeInterval.TotalMinutes, 1, 60);
var threshold = Number("Pace threshold (points)", (decimal)initial.PaceThreshold, 0.1m, 100);
var ahead = Check("Ahead popups", initial.PopupAhead); var behind = Check("Behind popups", initial.PopupBehind);
var startup = Check("Start with the OS", initial.StartWithOs); var tray = Check("Close to tray", initial.CloseToTray);
var claude = ProviderControls("Claude", initial.Claude); var codex = ProviderControls("Codex", initial.Codex);
body.Children.Add(Ui.Text("Stream Deck", 19));
body.Children.Add(Ui.Text($"{status.State} · shipped {status.ShippedVersion ?? "none"} · installed {status.InstalledVersion ?? "none"}"));
var mode = new ComboBox { ItemsSource = new[] { "Off", "Ask", "Automatic" }, SelectedIndex = (int)initial.StreamDeckInstallMode };
body.Children.Add(mode);
body.Children.Add(Ui.Text("Dismissed plugin version (clear to ask again)"));
var dismissed = new TextBox { Text = initial.DismissedPluginVersion ?? "" }; body.Children.Add(dismissed);
var error = Ui.Text(""); body.Children.Add(error);
var button = new Button { Content = "Save", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right };
Title = "FinalToken settings"; Width = 760; Height = 900; MinWidth = 600; MinHeight = 500; Ui.Theme(this);
var body = new StackPanel { Spacing = 16, Margin = new Thickness(24) };
body.Children.Add(Ui.Text("Settings", 24));
var general = Ui.Stack(Ui.Text("General", 15));
var refresh = Number(general, "Token refresh (seconds, 1–60)", (decimal)initial.RefreshInterval.TotalSeconds, 1, 60);
var probe = Number(general, "Limit probe (minutes, 1–60)", (decimal)initial.ProbeInterval.TotalMinutes, 1, 60);
var threshold = Number(general, "Pace threshold (points)", (decimal)initial.PaceThreshold, 0.1m, 100);
var startup = Check(general, "Start with the OS", initial.StartWithOs);
var tray = Check(general, "Close to tray", initial.CloseToTray);
body.Children.Add(Ui.Card(general));
var popups = Ui.Stack(Ui.Text("Popups", 15));
var ahead = Check(popups, "Ahead popups", initial.PopupAhead);
var behind = Check(popups, "Behind popups", initial.PopupBehind);
var claudePopups = PopupControls(popups, "Claude", initial.Claude);
var codexPopups = PopupControls(popups, "Codex", initial.Codex);
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 (_, _) =>
{
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,
StartWithOs = startup.IsChecked == true, CloseToTray = tray.IsChecked == true, Claude = claude(), Codex = codex(),
StreamDeckInstallMode = (InstallMode)mode.SelectedIndex, DismissedPluginVersion = string.IsNullOrWhiteSpace(dismissed.Text) ? null : dismissed.Text.Trim() };
StartWithOs = startup.IsChecked == true, CloseToTray = tray.IsChecked == true,
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; }
button.IsEnabled = false;
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)
{ error.Text = "Could not apply settings: " + e.Message; button.IsEnabled = true; }
};
body.Children.Add(button); Content = new ScrollViewer { Content = body };
NumericUpDown Number(string label, decimal value, decimal min, decimal max)
{ 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() };
}
var dock = new DockPanel();
var bottom = Ui.Stack(error, footer); DockPanel.SetDock(bottom, Dock.Bottom); dock.Children.Add(bottom);
dock.Children.Add(new ScrollViewer { Content = body }); Content = dock;
}
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
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.
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
without inserting redundant unchanged points. Bucket lookup is O(1); stored limit points have
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 TokenPoint(DateTimeOffset Time, TokenCounts Counts);
public sealed record ModelTokenPoint(DateTimeOffset Time, string? Model, TokenCounts Counts);
public sealed record TokenBreakdown(string? Name, TokenCounts Counts);
public enum SeriesInterval { Hour, Day }
@@ -185,10 +186,10 @@ public sealed class HistoryStore
if (GetPartition(later).NextLimit(window) is { } found) { chronologicalNext = found; break; }
}
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;
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;
if (previous is null || window.SampleTime >= previous.SampleTime)
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];
}
}
// 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) =>
(window.Id, window.Label, window.UsedPercent, window.ResetsAt, window.Length, window.Source);
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<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);
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
{
// 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.
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 :
delta <= -threshold && elapsed >= 0.5 ? PaceState.Behind : PaceState.OnTrack;
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;
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);
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) { }
diagnostics.Add(null, "settings-defaults", "Settings missing or invalid; using defaults.");
diagnostics.Add(null, "settings-defaults", "Settings invalid or unreadable; using defaults.");
return new();
}
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;
}