From 33458a40ed76ab697d888233db06d1b758ce98cd Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Thu, 15 Oct 2026 18:58:06 +0200 Subject: [PATCH] fix: forecast windows that are ahead early in their window (D7) 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 --- src/FinalToken.App/AGENTS.md | 3 +- src/FinalToken.App/BurnUpChart.cs | 10 ++- src/FinalToken.App/Charts.cs | 2 +- src/FinalToken.App/PanelViewModel.cs | 7 +- src/FinalToken.App/PanelWindow.cs | 4 +- src/FinalToken.Core/LimitAnalysis.cs | 12 +-- src/FinalToken.Core/Pace.cs | 16 +++- tests/FinalToken.App.Tests/HeadlessTests.cs | 38 +++++++++ tests/FinalToken.App.Tests/ViewModelTests.cs | 22 +++++ .../EarlyForecastTests.cs | 81 +++++++++++++++++++ .../TokenEstimateTests.cs | 6 +- 11 files changed, 180 insertions(+), 21 deletions(-) create mode 100644 tests/FinalToken.Core.Tests/EarlyForecastTests.cs diff --git a/src/FinalToken.App/AGENTS.md b/src/FinalToken.App/AGENTS.md index a1f744e..3f025b8 100644 --- a/src/FinalToken.App/AGENTS.md +++ b/src/FinalToken.App/AGENTS.md @@ -29,7 +29,8 @@ 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; then dates remain visible for every positive pace delta (D7), but + `#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, diff --git a/src/FinalToken.App/BurnUpChart.cs b/src/FinalToken.App/BurnUpChart.cs index 3939b59..3d3aa79 100644 --- a/src/FinalToken.App/BurnUpChart.cs +++ b/src/FinalToken.App/BurnUpChart.cs @@ -5,7 +5,7 @@ using FinalToken.Core; namespace FinalToken.App; -public sealed class BurnUpChart(LimitChart chart) : Control +public sealed class BurnUpChart(LimitChart chart) : Decorator { private Rect plot; private double? crosshair; @@ -13,6 +13,10 @@ public sealed class BurnUpChart(LimitChart chart) : Control 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; @@ -27,7 +31,7 @@ public sealed class BurnUpChart(LimitChart chart) : Control { if (current.ReachedOrigin == UseOrigin.Estimated) { used = 100; source = "Limit reached (estimated)"; } - else if (chart.Window is { } window && LimitAnalysis.AverageUseAtReset(window.Window, chart.Now) is { } forecast) + 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"; @@ -68,7 +72,7 @@ public sealed class BurnUpChart(LimitChart chart) : Control 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) is { } average && instance.Reset > chart.Now) + 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)); diff --git a/src/FinalToken.App/Charts.cs b/src/FinalToken.App/Charts.cs index 33db041..a18310f 100644 --- a/src/FinalToken.App/Charts.cs +++ b/src/FinalToken.App/Charts.cs @@ -150,7 +150,7 @@ public sealed class PaceBar(WindowSnapshot window) : Control 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) is { } forecast && forecast > window.Window.UsedPercent) + 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)); diff --git a/src/FinalToken.App/PanelViewModel.cs b/src/FinalToken.App/PanelViewModel.cs index 69d880c..5c112a4 100644 --- a/src/FinalToken.App/PanelViewModel.cs +++ b/src/FinalToken.App/PanelViewModel.cs @@ -58,7 +58,7 @@ public partial class PanelViewModel : ObservableObject 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), + 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) => @@ -67,7 +67,7 @@ public partial class PanelViewModel : ObservableObject 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) is { } average ? new(reset, p.Provider.ToString(), average) : null, + 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(); var models = Breakdown(true); var projects = Breakdown(false); @@ -96,6 +96,9 @@ public partial class PanelViewModel : ObservableObject 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) diff --git a/src/FinalToken.App/PanelWindow.cs b/src/FinalToken.App/PanelWindow.cs index ac50155..b3e118c 100644 --- a/src/FinalToken.App/PanelWindow.cs +++ b/src/FinalToken.App/PanelWindow.cs @@ -204,8 +204,10 @@ public sealed class PanelWindow : Window } else card.Children.Add(Ui.Text(caption, 13, "Secondary")); } - else if (LimitAnalysis.AverageUseAtReset(w, now) is { } average) + 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"); diff --git a/src/FinalToken.Core/LimitAnalysis.cs b/src/FinalToken.Core/LimitAnalysis.cs index b7e04d3..d4cd7f8 100644 --- a/src/FinalToken.Core/LimitAnalysis.cs +++ b/src/FinalToken.Core/LimitAnalysis.cs @@ -16,16 +16,16 @@ public static partial class LimitAnalysis first.ResetsAt is { } firstReset && second.ResetsAt is { } secondReset && (firstReset - secondReset).Duration() <= TimeSpan.FromMinutes(15); - public static double? AverageUseAtReset(LimitWindow window, DateTimeOffset now) + public static double? AverageUseAtReset(LimitWindow window, DateTimeOffset now, PaceResult? pace = null) { - var pace = Pace.Calculate(window, now); - return Pace.CanForecast(window, now) && pace.ElapsedFraction is > 0 and var elapsed ? window.UsedPercent / elapsed : 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 samples, DateTimeOffset now) + public static RateForecast? Recent(LimitWindow window, IEnumerable samples, DateTimeOffset now, PaceResult? pace = null) { - if (!Pace.CanForecast(window, now) || window.ResetsAt is not { } reset || window.Length is not { Ticks: > 0 } length || reset <= now || - Pace.Calculate(window, now).State == PaceState.Unknown) return 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; diff --git a/src/FinalToken.Core/Pace.cs b/src/FinalToken.Core/Pace.cs index 3de4333..7fc5d96 100644 --- a/src/FinalToken.Core/Pace.cs +++ b/src/FinalToken.Core/Pace.cs @@ -3,9 +3,17 @@ namespace FinalToken.Core; public static class Pace { // D7: use ticks at the boundary so exactly 10% is eligible despite floating-point rounding. - public static bool CanForecast(LimitWindow window, DateTimeOffset now) => - window.Length is { Ticks: > 0 } length && window.ResetsAt is { } reset && - reset - now <= TimeSpan.FromTicks(length.Ticks - length.Ticks / 10); + 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) @@ -19,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 (delta > 0 && window.UsedPercent > 0 && CanForecast(window, now)) + 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); diff --git a/tests/FinalToken.App.Tests/HeadlessTests.cs b/tests/FinalToken.App.Tests/HeadlessTests.cs index 3a8c041..b126bef 100644 --- a/tests/FinalToken.App.Tests/HeadlessTests.cs +++ b/tests/FinalToken.App.Tests/HeadlessTests.cs @@ -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().Single(b => b.Name == "LimitTile-Codex-primary"); + Assert.Contains(aheadTile.GetVisualDescendants().OfType(), t => t.Text?.StartsWith("100 % on ") == true); + Assert.Contains(aheadTile.GetVisualDescendants().OfType(), t => t.Text == "⚠ "); + Assert.NotNull(forecastModel.History.Limits.Single(l => l.Window!.Window.Id == "primary").Forecast); + var waitingTile = forecastPanel.GetVisualDescendants().OfType().Single(b => b.Name == "LimitTile-Codex-secondary"); + var note = Assert.Single(waitingTile.GetVisualDescendants().OfType(), t => t.Text?.StartsWith("Forecast from ") == true).Text; + Assert.Contains(forecastPanel.GetVisualDescendants().OfType(), c => c.GetVisualDescendants().OfType().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(), 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().First(); viewport.Offset = default; + Save(forecastPanel, $"forecast-1280x900-{theme}-limits.png"); + var heading = forecastPanel.GetVisualDescendants().OfType().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().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(); diff --git a/tests/FinalToken.App.Tests/ViewModelTests.cs b/tests/FinalToken.App.Tests/ViewModelTests.cs index 7df9388..ffead62 100644 --- a/tests/FinalToken.App.Tests/ViewModelTests.cs +++ b/tests/FinalToken.App.Tests/ViewModelTests.cs @@ -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 = diff --git a/tests/FinalToken.Core.Tests/EarlyForecastTests.cs b/tests/FinalToken.Core.Tests/EarlyForecastTests.cs new file mode 100644 index 0000000..5bcfbe3 --- /dev/null +++ b/tests/FinalToken.Core.Tests/EarlyForecastTests.cs @@ -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)); + } +} diff --git a/tests/FinalToken.Core.Tests/TokenEstimateTests.cs b/tests/FinalToken.Core.Tests/TokenEstimateTests.cs index 6c2a5df..145f8e7 100644 --- a/tests/FinalToken.Core.Tests/TokenEstimateTests.cs +++ b/tests/FinalToken.Core.Tests/TokenEstimateTests.cs @@ -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 };