core: plan the daily budget per day, start forecasts at 2 % and follow the limit week (#15)

The developer's feedback of 2026-10-18 named four problems at the top
of the panel: late forecasts, a daily budget that shrank with every use,
unequal Claude and Codex tiles, and an unclear "This week".

- Core: forecasts start at 2 % of a window (D7). Each day of a long
  instance has a share, an even pace and a budget. Today's budget starts
  from the use at the start of the day and stays put while today is
  spent. An estimated start-of-day use counts only the whole hours before
  the first sample's hour, so later samples and tokens do not move it.
  Week token totals follow the provider's limit week, with the calendar
  week as the named fallback; the snapshot carries `weekStart` and
  `weekWindow` (D9).
- App: tiles of one window kind show the same rows, with muted
  placeholders that say why (D8). The stale warning sits in the Used row.
  Week charts draw even pace and budget as steps per day, mark the
  instance start and reset, and label full-day rates. Token tiles say
  since when.
- CLI: prints which week it uses and since when.

Closes #13
This commit was merged in pull request #15.
This commit is contained in:
2026-10-18 10:53:00 +02:00
parent d5ad3ecee9
commit 0a08b508a2
23 changed files with 629 additions and 87 deletions
+3 -2
View File
@@ -30,7 +30,7 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
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);
`#fab219` ▼ Behind. Forecasts start at 2% 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.
@@ -41,7 +41,8 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
- 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
- Week charts show per-day steps: dashed muted even pace, and thin solid secondary budget from
today onward. Mark partial start and reset times. Keep 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;
+45 -17
View File
@@ -183,21 +183,25 @@ public sealed class CompositionBar(TokenCounts counts, Provider provider, bool i
}
}
public sealed class DailyLimitChart(WindowDays days, Provider provider) : Control
public sealed class DailyLimitChart(WindowDays days, Provider provider, TimeProvider? clock = null) : Control
{
private readonly TimeProvider clock = clock ?? TimeProvider.System;
private readonly List<(Rect Rect, Func<DataTooltip> Tip)> hits = [];
public DailyLimitChart() : this(new([], [], null, 0, null), Provider.Claude) { }
public IReadOnlyList<string> AxisLabels => days.Current.Select((day, i) => day.Start.DateTime.ToString("ddd") +
(i == 0 && days.InstanceStart is { } start && start != CalendarDays.Start(start, clock.LocalTimeZone) ? "\nfrom " + Display.Time(start, clock) : "") +
(i == days.Current.Count - 1 && days.Reset is { } reset && reset != CalendarDays.Start(reset, clock.LocalTimeZone) ? "\nreset " + Display.Time(reset, clock) : "")).ToArray();
protected override void OnInitialized()
{
base.OnInitialized(); Height = 248; ToolTip.SetShowDelay(this, 0);
base.OnInitialized(); Height = 264; 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 plot = new Rect(40, 24, Math.Max(1, Bounds.Width - 174), Math.Max(1, Bounds.Height - 76));
var maximum = days.Current.Concat(days.Previous).Select(d => Math.Max(d.Used ?? 0, Math.Max(d.EvenPace, d.Budget ?? 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)
@@ -206,11 +210,12 @@ public sealed class DailyLimitChart(WindowDays days, Provider provider) : Contro
ChartText.Draw(context, $"{tick:0.#}%", new(0, Y(tick) - 7), ink);
}
var width = plot.Width / Math.Max(1, days.Current.Count);
var labels = AxisLabels;
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);
using (context.PushOpacity(.18)) context.DrawRectangle(null, new Pen(colour, 2), new Rect(x + 4, Y(prior), Math.Max(1, 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)));
@@ -227,23 +232,46 @@ public sealed class DailyLimitChart(WindowDays days, Provider provider) : Contro
}
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)));
ChartText.Draw(context, labels[i], new(x + 4, plot.Bottom + 8), day.IsToday ? Ui.Colour("Ink", dark) : ink);
hits.Add((new Rect(x, plot.Top, width, plot.Height + 48), () => 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)
if (days.Current.Count == 0) return;
if (days.Reset is { } reset && reset != CalendarDays.Start(reset, clock.LocalTimeZone))
{
var start = CalendarDays.Start(reset, clock.LocalTimeZone);
var fraction = (reset - start).TotalSeconds / (CalendarDays.NextStart(start, clock.LocalTimeZone) - start).TotalSeconds;
var x = plot.Left + (days.Current.Count - 1 + fraction) * width;
context.DrawLine(new Pen(ink, 1, new DashStyle([3, 3], 0)), new(x, plot.Top), new(x, plot.Bottom));
}
var even = days.Current[^1].EvenPace; var budget = days.Current[^1].Budget;
var evenLabel = Math.Clamp(Y(even) - 7, plot.Top, plot.Bottom - 14);
var budgetLabel = budget is { } b ? Math.Clamp(Y(b) - 7, plot.Top, plot.Bottom - 14) : 0;
if (budget is { } value && 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);
evenLabel = middle + (value >= even ? 9 : -9);
budgetLabel = middle + (value >= even ? -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)
// Labels name the full-day rates of the tile's plan row; partial days draw their share of it.
Reference(d => d.EvenPace, $"Even {days.EvenPace:0.#}%/day", ink, evenLabel, true);
if (budget is { } lastBudget) Reference(d => d.Budget, days.LaterBudget is { } later ? $"Budget {later:0.#}%/day" : $"Budget {lastBudget:0.#}%",
Ui.Colour("Secondary", dark), budgetLabel, false);
void Reference(Func<LimitDay, double?> select, 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));
var pen = new Pen(brush, 1, dashed ? new DashStyle([4, 4], 0) : null);
double? prior = null;
for (var i = 0; i < days.Current.Count; i++)
{
var current = select(days.Current[i]); var x = plot.Left + i * width;
if (current is { } v)
{
if (prior is { } p) context.DrawLine(pen, new(x, Y(p)), new(x, Y(v)));
context.DrawLine(pen, new(x, Y(v)), new(x + width, Y(v)));
}
prior = current;
}
if (prior is { } end && Math.Abs(labelY + 7 - Y(end)) > 3)
context.DrawLine(new Pen(brush, 1), new(plot.Right, Y(end)), new(plot.Right + 6, labelY + 7));
ChartText.Draw(context, label, new(plot.Right + 8, labelY), brush);
}
}
+3
View File
@@ -40,6 +40,9 @@ public sealed class DataTooltip : Border
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.##} %"));
if (day.IsPartial) rows.Add(new("Share", $"{day.Share.TotalHours:0.##} h"));
rows.Add(new("Even pace", $"{day.EvenPace:0.##} %"));
rows.Add(new("Budget", day.Budget is { } budget ? $"{budget:0.##} %" + (day.BudgetOrigin == UseOrigin.Estimated ? " (estimated)" : "") : "Unavailable"));
return new(day.Start.DateTime.ToString("D"), rows.ToArray());
}
public override string ToString() => Title + "\n" + string.Join('\n', Rows.Select(r => r.Label + ": " + r.Value));
+2
View File
@@ -112,6 +112,8 @@ public static class Display
return local.ToString(local.Date == clock.GetLocalNow().Date ? "t" : "g",
culture ?? System.Globalization.CultureInfo.CurrentCulture);
}
public static string Time(DateTimeOffset time, TimeProvider? clock = null) =>
TimeZoneInfo.ConvertTime(time, (clock ?? TimeProvider.System).LocalTimeZone).ToString("t");
public static string Duration(TimeSpan span) => span <= TimeSpan.Zero ? "now" : span.TotalDays >= 1
? $"{(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";
+35 -22
View File
@@ -120,7 +120,7 @@ public sealed class PanelWindow : Window
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)
? new DailyLimitChart(item.Days, item.Provider, clock)
: 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);
@@ -154,9 +154,11 @@ public sealed class PanelWindow : Window
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));
row.Children.Add(TokenTile(p, "Today", "since 00:00", p.Today));
if (p.Session is { } session && p.Windows.FirstOrDefault(w => w.Window.Length <= TimeSpan.FromHours(5) && w.Window.ResetsAt > now) is { Window: { ResetsAt: { } reset, Length: { } length } })
row.Children.Add(TokenTile(p, "Current session", "since " + Display.Time(reset - length, clock), session));
row.Children.Add(TokenTile(p, p.WeekWindow is not null ? "Limit week" : "Calendar week",
p.WeekWindow is not null ? "since " + TimeZoneInfo.ConvertTime(p.WeekStart, clock.LocalTimeZone).ToString("ddd HH:mm") : "since Mon 00:00", p.Week));
return (Control)Ui.Card(Ui.Stack(Ui.Text(p.Provider.ToString(), 15), row));
});
content.Add(Ui.Columns(totals, wide));
@@ -191,48 +193,59 @@ public sealed class PanelWindow : Window
{
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 title = new DockPanel { Name = "Title" };
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, now) { Height = 10 });
card.Children.Add(Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {Display.Projection(reset, clock)}" : "Reset unknown", 13, "Secondary"));
var card = Ui.Stack(title);
void Row(string name, Control control) { control.Name = name; card.Children.Add(control); }
Row("Percent", Ui.Text($"{w.UsedPercent:0.#} %", 36));
Row("Used", Ui.Text(now - w.SampleTime > model.ProbeInterval * 2
? $"used · ⚠ sample {Display.Duration(now - w.SampleTime)} old" : "used", 12, "Muted"));
Row("Pace", new PaceBar(window, now) { Height = 10 });
Row("Reset", Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {Display.Projection(reset, clock)}" : "Reset unknown", 13, "Secondary"));
if (pace.Projection is { } projection)
{
var caption = Display.Forecast(projection, pace.State, clock) + $" ({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);
DockPanel.SetDock(mark, Dock.Left); line.Children.Add(mark); line.Children.Add(Ui.Text(caption[2..], 13, "Secondary")); Row("Forecast", line);
}
else card.Children.Add(Ui.Text(caption, 13, "Secondary"));
else Row("Forecast", 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, clock) is { } waiting)
card.Children.Add(Ui.Text(waiting, 13, "Muted"));
Row("Forecast", Ui.Text($"≈ {average:0.#} % at reset", 13, "Secondary"));
else Row("Forecast", Ui.Text(Display.ForecastWaiting(window, now, clock) ?? "No forecast: pace unknown", 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, clock)}" : $" · ≈ {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);
ToolTip.SetTip(line, new DataTooltip("Recent rate", new("Rate", $"{recent.PercentPerDay:0.##} %/day"), new("Observed span", Display.Duration(recent.Span)))); Row("Recent", line);
}
if (detail?.Days is { } days)
else Row("Recent", Ui.Text(Display.ForecastWaiting(window, now, clock) is not null && Pace.ForecastStartsAt(w) is { } forecastStart
? "Recent rate from " + Display.Projection(forecastStart, clock) : "Recent rate needs 3 h of samples", 13, "Muted"));
if (w.Length > TimeSpan.FromDays(1))
{
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));
var days = detail?.Days;
var estimated = days?.TodayOrigin == UseOrigin.Estimated || days?.BudgetOrigin == UseOrigin.Estimated;
Row("Today", Ui.Text(days?.Today is { } today
? $"Today {(estimated ? "≈ " : "")}+{today:0.#} %" + (days.TodayBudget is { } budget ? $" of {budget:0.#} % budget" : " of the week") + (estimated ? " (estimated)" : "")
: "Today · collecting a day baseline", 15, days?.Today is null ? "Muted" : "Ink"));
var plan = $"Even pace {days?.EvenPace ?? 100 / w.Length.Value.TotalDays:0.#} %/day";
if (days?.LaterBudget is { } later) plan += $" · from tomorrow {later:0.#} %/day";
else if (days?.TodayBudget is not null && w.ResetsAt is { } lastReset) plan += " · last day, resets " + Display.Time(lastReset, clock);
Row("Plan", Ui.Text(plan, 13, "Secondary"));
}
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, clock) : "Unknown"), new("Sample", w.SampleTime.LocalDateTime.ToString("g")))); return tile;
}
private Control TokenTile(ProviderSnapshot provider, string label, TokenCounts counts)
private Control TokenTile(ProviderSnapshot provider, string label, string caption, 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 });
new CompositionBar(counts, provider.Provider, model.IncludeCacheReads) { Height = 6 }, Ui.Text(caption, 12, "Muted"));
tile.Name = $"TokenTile-{provider.Provider}-{label.Replace(' ', '-')}";
tile.Width = wide ? 164 : 188; tile.Margin = new Thickness(0, 8, 16, 0);
ToolTip.SetTip(tile, DataTooltip.Tokens(provider.Provider + " · " + label, counts)); return tile;
ToolTip.SetTip(tile, DataTooltip.Tokens(provider.Provider + " · " + label + " · " + caption, counts)); return tile;
}
private Control CompositionLegend()
{