fix: forecast windows that are ahead early in their window (D7)
agent-review agent review: pass

The reach date, the dotted forecast and the popup warning showed only
for Claude. Codex had reset its week ten hours before and stood at
39 %, ahead by 33 points, but every forecast shared a gate that
opened only after 10 % of the window. Nothing in the forecast paths
was provider-specific; Codex was just the window early in its week.

The gate now also opens as soon as the window is ahead, with the
configured threshold, so it never disagrees with the chip. Average,
recent and popup forecasts all use it. Until forecasts start, the
tile and the window chart say when they will.

Refs #5
This commit is contained in:
Florian Schmidt
2026-10-15 18:58:06 +02:00
parent 5b42cb8c98
commit 33458a40ed
11 changed files with 180 additions and 21 deletions
@@ -145,6 +145,35 @@ public sealed class HeadlessTests
model.Snapshot = model.Snapshot! with { MadeAt = DateTimeOffset.UtcNow }; Dispatcher.UIThread.RunJobs();
Assert.Equal(prior, viewport.Offset);
}
var forecastModel = FakeData.ForecastModel();
var forecastPanel = new PanelWindow(forecastModel, () => { }, () => { }, () => { }, () => { });
forecastPanel.Show(); Dispatcher.UIThread.RunJobs();
var aheadTile = forecastPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-primary");
Assert.Contains(aheadTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("100 % on ") == true);
Assert.Contains(aheadTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "⚠ ");
Assert.NotNull(forecastModel.History.Limits.Single(l => l.Window!.Window.Id == "primary").Forecast);
var waitingTile = forecastPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
var note = Assert.Single(waitingTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("Forecast from ") == true).Text;
Assert.Contains(forecastPanel.GetVisualDescendants().OfType<BurnUpChart>(), c => c.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text == note));
var aheadWindow = forecastModel.Snapshot!.Providers[0].Windows[0];
var earlyAlert = new PopupDecider().Observe(aheadWindow.Window, aheadWindow.Pace, new Settings());
Assert.NotNull(earlyAlert);
var earlyPopup = PopupWindow.Pace(earlyAlert, () => { }); earlyPopup.Show();
Assert.Contains(earlyPopup.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains("⚠ 100 % on ") == true);
earlyPopup.Close();
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
forecastPanel.Width = 1280; forecastPanel.Height = 900; forecastPanel.RequestedThemeVariant = theme;
var viewport = forecastPanel.GetVisualDescendants().OfType<ScrollViewer>().First(); viewport.Offset = default;
Save(forecastPanel, $"forecast-1280x900-{theme}-limits.png");
var heading = forecastPanel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "Window charts");
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(forecastPanel, $"forecast-1280x900-{theme}-windows.png");
var charts = forecastPanel.GetVisualDescendants().OfType<BurnUpChart>().ToArray();
Assert.Equal(2, charts.Length);
Assert.True(DrawsForecast(charts[0])); Assert.False(DrawsForecast(charts[1]));
}
forecastPanel.Close();
var earlyModel = FakeData.EarlyResetModel();
var earlyPanel = new PanelWindow(earlyModel, () => { }, () => { }, () => { }, () => { });
earlyPanel.Show();
@@ -323,6 +352,15 @@ public sealed class HeadlessTests
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{ window.RequestedThemeVariant = theme; Save(window, stem + "-" + theme + ".png"); }
}
bool DrawsForecast(BurnUpChart chart)
{
var drawing = new Avalonia.Media.DrawingGroup();
using (var context = drawing.Open()) chart.Render(context);
return HasForecast(drawing);
static bool HasForecast(Avalonia.Media.DrawingGroup group) => group.Children.Any(d =>
d is Avalonia.Media.GeometryDrawing { Pen.DashStyle.Dashes: { } dashes } && dashes.SequenceEqual(new double[] { 1, 3 }) ||
d is Avalonia.Media.DrawingGroup nested && HasForecast(nested));
}
void Save(Window window, string name, string? destination = null)
{
Dispatcher.UIThread.RunJobs();
@@ -5,6 +5,15 @@ namespace FinalToken.App.Tests;
public sealed class ViewModelTests
{
[Theory]
[InlineData(10, true)]
[InlineData(40, false)]
public void HistoryForecastsUseTheSnapshotsConfiguredPace(double threshold, bool eligible)
{
var model = FakeData.ForecastModel(threshold);
Assert.Equal(eligible, model.History.Limits.Single(l => l.Window!.Window.Id == "primary").Forecast is not null);
Assert.Equal(eligible, model.History.Details.Single(d => d.Id == "primary").Recent is not null);
}
[Fact] public async Task RefreshIgnoresConcurrentRequestsAndClearsGuardAfterFailure()
{
var model = new PanelViewModel(); var completion = new TaskCompletionSource(); var calls = 0;
@@ -157,6 +166,19 @@ public sealed class ViewModelTests
internal static class FakeData
{
public static PanelViewModel ForecastModel(double threshold = 10)
{
var now = new DateTimeOffset(2026, 10, 15, 16, 45, 0, TimeSpan.Zero);
var ahead = new LimitWindow(Provider.Codex, "primary", "Week", 39,
new(2026, 10, 22, 6, 18, 0, TimeSpan.Zero), TimeSpan.FromDays(7), now, "fixture");
var early = ahead with { Id = "secondary", Label = "Week · early on track", UsedPercent = 1, ResetsAt = now.AddDays(7).AddHours(-1) };
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
store.AddLimits([ahead with { SampleTime = now.AddHours(-4), UsedPercent = 20 }, ahead,
early with { SampleTime = now.AddHours(-1), UsedPercent = 0 }, early]);
var snapshot = Snapshot(now) with { Providers = [Snapshot(now).Providers[1] with
{ Windows = [new(ahead, Pace.Calculate(ahead, now, threshold)), new(early, Pace.Calculate(early, now, threshold))] }] };
return new() { Snapshot = snapshot, History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
}
public static Snapshot Snapshot(DateTimeOffset now, bool unavailable = false) => new()
{
MadeAt = now, RefreshInterval = TimeSpan.FromSeconds(60), Providers =
@@ -0,0 +1,81 @@
using Xunit;
namespace FinalToken.Core.Tests;
public class EarlyForecastTests
{
private static readonly DateTimeOffset Now = new(2026, 10, 15, 16, 45, 0, TimeSpan.Zero);
private static LimitWindow Week(double used = 39) => new(Provider.Codex, "primary", "Week", used,
new(2026, 10, 22, 6, 18, 0, TimeSpan.Zero), TimeSpan.FromDays(7), Now, "fixture");
[Fact] public void AheadCodexWeekProjectsBeforeTenPercent()
{
var window = Week(); var pace = Pace.Calculate(window, Now);
Assert.Equal(PaceState.Ahead, pace.State);
Assert.InRange(pace.ElapsedFraction!.Value, .061, .063);
Assert.NotNull(pace.Projection);
Assert.InRange(pace.Projection.Value, Now, window.ResetsAt!.Value);
}
[Fact] public void AheadCodexWeekHasAverageForecast() => Assert.NotNull(LimitAnalysis.AverageUseAtReset(Week(), Now));
[Fact] public void AheadCodexWeekHasRecentForecast()
{
var window = Week();
var recent = LimitAnalysis.Recent(window, [window with { SampleTime = Now.AddHours(-4), UsedPercent = 20 }], Now);
Assert.NotNull(recent); Assert.NotNull(recent.ReachesLimit);
Assert.Equal(TimeSpan.FromHours(4), recent.Span);
}
[Fact] public void AheadCodexPopupIncludesProjection()
{
var window = Week();
var popup = new PopupDecider().Observe(window, Pace.Calculate(window, Now), new Settings());
Assert.NotNull(popup); Assert.NotNull(popup.Projection);
}
[Fact] public void OnePercentOneHourIntoWeekDoesNotForecast()
{
var window = Week(1) with { ResetsAt = Now.AddDays(7).AddHours(-1) };
Assert.Equal(PaceState.OnTrack, Pace.Calculate(window, Now).State);
Assert.Null(Pace.Calculate(window, Now).Projection);
Assert.Null(LimitAnalysis.AverageUseAtReset(window, Now));
Assert.Null(LimitAnalysis.Recent(window, [], Now));
}
[Theory]
[InlineData(10, true)]
[InlineData(40, false)]
public void AllForecastsFollowConfiguredThreshold(double threshold, bool eligible)
{
var window = Week(); var pace = Pace.Calculate(window, Now, threshold);
Assert.Equal(eligible, pace.State == PaceState.Ahead);
Assert.Equal(eligible, Pace.CanForecast(window, Now, threshold));
Assert.Equal(eligible, pace.Projection is not null);
Assert.Equal(eligible, LimitAnalysis.AverageUseAtReset(window, Now, pace) is not null);
Assert.Equal(eligible, LimitAnalysis.Recent(window,
[window with { SampleTime = Now.AddHours(-4), UsedPercent = 20 }], Now, pace) is not null);
}
[Fact] public void ExactlyAheadThresholdEnablesEarlyForecasts()
{
var window = Week(); var threshold = Pace.Calculate(window, Now).Delta!.Value;
var pace = Pace.Calculate(window, Now, threshold);
Assert.Equal(PaceState.Ahead, pace.State);
Assert.NotNull(pace.Projection);
Assert.NotNull(LimitAnalysis.AverageUseAtReset(window, Now, pace));
Assert.NotNull(LimitAnalysis.Recent(window, [window with { SampleTime = Now.AddHours(-4), UsedPercent = 20 }], Now, pace));
}
[Fact] public void ForecastStartIsTenPercentIntoWindow()
{
var window = Week(1);
Assert.Equal(window.ResetsAt - TimeSpan.FromDays(6.3), Pace.ForecastStartsAt(window));
Assert.Null(Pace.ForecastStartsAt(window with { Length = null }));
Assert.Null(Pace.ForecastStartsAt(window with { ResetsAt = null }));
Assert.Null(Pace.ForecastStartsAt(window with { Length = TimeSpan.Zero }));
var start = Pace.ForecastStartsAt(window)!.Value;
Assert.False(Pace.CanForecast(window, start.AddTicks(-1), 40));
Assert.True(Pace.CanForecast(window, start, 40));
}
}
@@ -139,12 +139,12 @@ public sealed class TokenEstimateTests
var start = Start; var length = TimeSpan.FromHours(hours);
var atThreshold = start + TimeSpan.FromTicks(length.Ticks / 10);
var before = atThreshold.AddTicks(-1);
var window = Window with { ResetsAt = start + length, Length = length, SampleTime = before, UsedPercent = 30 };
Assert.Equal(PaceState.Ahead, Pace.Calculate(window, before).State);
var window = Window with { ResetsAt = start + length, Length = length, SampleTime = before, UsedPercent = 11 };
Assert.Equal(PaceState.OnTrack, Pace.Calculate(window, before).State);
var pace = Pace.Calculate(window, before);
Assert.Null(pace.Projection);
var popup = new PopupDecider().Observe(window, pace, new Settings());
Assert.NotNull(popup); Assert.Null(popup.Projection);
Assert.Null(popup);
Assert.Null(LimitAnalysis.AverageUseAtReset(window, before));
Assert.Null(LimitAnalysis.Recent(window, [window with { SampleTime = start, UsedPercent = 0 }], before));
window = window with { SampleTime = atThreshold };