core: plan the daily budget per day, start forecasts at 2 % and follow the limit week
agent-review agent review: fail

The budget was the rest of the week over the time left, so each use today
lowered it and a partial first day was held to a full day. Now each day of
the instance has its share, its even pace and its budget. Today's budget
starts from the use at the day start and does not move with today's use
(D7). Forecasts start at 2 % of a window, so an early reset no longer hides
them for most of a day.

Limit tiles of one kind show the same rows, with placeholders that say why
a value is missing. The week chart draws per-day steps and marks the
instance start and reset (D8). Week token totals follow the provider's
limit week and say since when, with the calendar week as fallback (D9).

Refs #13
This commit is contained in:
Florian Schmidt
2026-10-18 09:55:41 +02:00
parent a8785fa453
commit 941a597680
22 changed files with 422 additions and 66 deletions
+58 -1
View File
@@ -146,6 +146,63 @@ public sealed class HeadlessTests
model.Snapshot = model.Snapshot! with { MadeAt = clock.GetUtcNow() }; Dispatcher.UIThread.RunJobs();
Assert.Equal(prior, viewport.Offset);
}
var budgetModel = FakeData.BudgetModel();
var budgetSnapshot = budgetModel.Snapshot!;
var budgetClock = new FixedClock(budgetSnapshot.MadeAt);
var budgetPanel = new PanelWindow(budgetModel, () => { }, () => { }, () => { }, () => { }, budgetClock) { Width = 1280, Height = 1000 };
budgetPanel.Show(); Dispatcher.UIThread.RunJobs();
string[] Rows(Provider provider, string id = "week") => ((StackPanel)budgetPanel.GetVisualDescendants().OfType<Border>()
.Single(b => b.Name == $"LimitTile-{provider}-{id}").Child!).Children.Select(c => c.Name!).ToArray();
string[] longRows = ["Title", "Percent", "Used", "Pace", "Reset", "Forecast", "Recent", "Today", "Plan"];
Assert.Equal(longRows, Rows(Provider.Claude)); Assert.Equal(longRows, Rows(Provider.Codex));
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Limit week");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Calendar week");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "since Mon 00:00");
var tokenTiles = budgetPanel.GetVisualDescendants().OfType<StackPanel>().Where(p => p.Name?.StartsWith("TokenTile-", StringComparison.Ordinal) == true).ToArray();
Assert.All(tokenTiles, tile => Assert.Equal(tokenTiles[0].Bounds.Height, tile.Bounds.Height));
var limitTokens = tokenTiles.Single(t => t.Name == "TokenTile-Claude-Limit-week");
Assert.Contains(limitTokens.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "since " + TimeZoneInfo.ConvertTime(budgetSnapshot.Providers[0].WeekStart, budgetClock.LocalTimeZone).ToString("ddd HH:mm"));
Assert.Contains("Limit week", Assert.IsType<DataTooltip>(ToolTip.GetTip(limitTokens)).Title);
Assert.Contains("since ", Assert.IsType<DataTooltip>(ToolTip.GetTip(limitTokens)).Title);
foreach (var dayChart in budgetPanel.GetVisualDescendants().OfType<DailyLimitChart>())
{
Assert.Contains("from " + Display.Time(budgetSnapshot.Providers[0].WeekStart, budgetClock), dayChart.AxisLabels[0]);
Assert.Contains("reset " + Display.Time(budgetSnapshot.Providers[0].WeekStart.AddDays(7), budgetClock), dayChart.AxisLabels[^1]);
}
var partialDay = budgetModel.History.Details[0].Days!.Current[0];
var partialTip = DataTooltip.Day(partialDay);
Assert.Contains(partialTip.Rows, r => r.Label == "Share");
Assert.Contains(partialTip.Rows, r => r.Label == "Even pace");
Assert.Contains(partialTip.Rows, r => r.Label == "Budget");
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
budgetPanel.RequestedThemeVariant = theme;
var viewport = budgetPanel.GetVisualDescendants().OfType<ScrollViewer>().First(); viewport.Offset = default;
Save(budgetPanel, $"budget-1280x1000-{theme}-limits.png");
foreach (var (name, target) in new[] { ("week", "Week use per day"), ("tokens", "Tokens") })
{
var heading = budgetPanel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == target);
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(budgetPanel, $"budget-1280x1000-{theme}-{name}.png");
}
}
budgetModel.History = new([], [], [], [], []);
budgetModel.Snapshot = budgetSnapshot with { Providers = budgetSnapshot.Providers.Select(p =>
{
var w = p.Windows[0].Window with { UsedPercent = 1, ResetsAt = p.Provider == Provider.Claude ? budgetClock.GetUtcNow().AddDays(7).AddHours(-1) : null };
var shortWindow = w with { Id = "session", Label = "Session", Length = TimeSpan.FromHours(5),
ResetsAt = p.Provider == Provider.Claude ? budgetClock.GetUtcNow().AddHours(5).AddMinutes(-1) : null };
return p with { Windows = [new(w, Pace.Calculate(w, budgetClock.GetUtcNow())), new(shortWindow, Pace.Calculate(shortWindow, budgetClock.GetUtcNow()))] };
}).ToArray() };
Dispatcher.UIThread.RunJobs();
Assert.Equal(longRows, Rows(Provider.Claude)); Assert.Equal(longRows, Rows(Provider.Codex));
Assert.Equal(longRows.Take(7), Rows(Provider.Claude, "session"));
Assert.Equal(Rows(Provider.Claude, "session"), Rows(Provider.Codex, "session"));
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "No forecast: pace unknown");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Recent rate needs 3 h of samples");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("Recent rate from ", StringComparison.Ordinal) == true);
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Today · collecting a day baseline");
budgetPanel.Close();
var forecastModel = FakeData.ForecastModel();
var forecastClock = new FixedClock(forecastModel.Snapshot!.MadeAt);
var forecastPanel = new PanelWindow(forecastModel, () => { }, () => { }, () => { }, () => { }, forecastClock);
@@ -239,7 +296,7 @@ public sealed class HeadlessTests
("future-day", future),
("project", DataTooltip.Tokens("D:/Projects/Customer/Workspace/Project-with-a-long-name", new(100000000, 1900000000, 10000000, 53670717, 1234567, 2063670717))),
("tile", (DataTooltip)ToolTip.GetTip(panel.GetVisualDescendants().OfType<Border>().First(b => b.Name == "LimitTile-Claude-week"))!),
("tokens", DataTooltip.Tokens("Claude - This week", originalSnapshot.Providers[0].Week)),
("tokens", DataTooltip.Tokens("Claude - Calendar week", originalSnapshot.Providers[0].Week)),
};
var limit = originalHistory.Limits.Single(l => l.Provider == Provider.Claude && l.Window!.Window.Id == "week");
CaptureChartTip("burnup", new BurnUpChart(limit, clock), new Point(240, 100));
+22 -3
View File
@@ -10,7 +10,7 @@ public sealed class ViewModelTests
[InlineData(40, false)]
public void HistoryForecastsUseTheSnapshotsConfiguredPace(double threshold, bool eligible)
{
var model = FakeData.ForecastModel(threshold);
var model = FakeData.ForecastModel(threshold, beforeStart: true);
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);
}
@@ -166,12 +166,13 @@ public sealed class ViewModelTests
internal static class FakeData
{
public static PanelViewModel ForecastModel(double threshold = 10)
public static PanelViewModel ForecastModel(double threshold = 10, bool beforeStart = false)
{
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) };
if (beforeStart) ahead = ahead with { Length = TimeSpan.FromDays(28), ResetsAt = now.AddDays(28).AddHours(-4) };
var early = ahead with { Id = "secondary", Length = TimeSpan.FromDays(7), 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(), new FixedClock(now));
store.AddLimits([ahead with { SampleTime = now.AddHours(-4), UsedPercent = 20 }, ahead,
early with { SampleTime = now.AddHours(-1), UsedPercent = 0 }, early]);
@@ -190,6 +191,24 @@ internal static class FakeData
};
private static WindowSnapshot Window(Provider provider, string id, string label, double percent, DateTimeOffset now, int hours, int resetHours)
{ var w = new LimitWindow(provider, id, label, percent, now.AddHours(resetHours), TimeSpan.FromHours(hours), now.AddMinutes(-3), "fixture"); return new(w, Pace.Calculate(w, now)); }
public static PanelViewModel BudgetModel()
{
var now = new FixedClock().GetUtcNow();
var clock = new FixedClock(now);
var start = new DateTimeOffset(2026, 10, 10, 22, 40, 0, clock.LocalTimeZone.BaseUtcOffset);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-budget", Guid.NewGuid().ToString("N")), new DiagnosticLog(), clock);
var snapshot = Snapshot(now);
snapshot = snapshot with { Providers = snapshot.Providers.Select(p =>
{
var w = new LimitWindow(p.Provider, "week", "Week", p.Provider == Provider.Claude ? 40 : 32, start.AddDays(7), TimeSpan.FromDays(7), now, "fixture");
store.AddLimits([w with { SampleTime = CalendarDays.Start(now, clock.LocalTimeZone), UsedPercent = 30 }, w]);
for (var i = 0; i < 4; i++)
store.Add(new(p.Provider, start.AddDays(i), "fixture", "Fixture/Project", new(Input: 100, Total: 100), $"{p.Provider}-{i}"));
return p with { Windows = [new(w, Pace.Calculate(w, now))], Session = null,
WeekStart = start, WeekWindow = p.Provider == Provider.Claude ? "week" : null };
}).ToArray() };
return new() { Snapshot = snapshot, History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
}
public static PanelViewModel EarlyResetModel()
{
var now = new FixedClock().GetUtcNow();
+18
View File
@@ -61,11 +61,29 @@ public class CliTests
Assert.Equal(0, await CliApplication.RunAsync(["status", "--no-probe"], output, error, directory,
path => new(path, claudeDirectory: path, codexDirectory: path, cliDiscovery: (_, _) => new(null, "Fixture CLI missing.")), TestContext.Current.CancellationToken));
Assert.Contains("Tokens today: 0", output.ToString());
Assert.Contains("Calendar week: since ", output.ToString());
Assert.NotNull(SnapshotFile.Read(directory).Snapshot);
}
finally { Directory.Delete(directory, true); }
}
[Fact]
public async Task TextNamesLimitWeekAndItsStart()
{
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(directory);
try
{
using var storeLock = StoreLock.TryAcquire(directory);
var start = new DateTimeOffset(2026, 10, 10, 22, 40, 0, TimeSpan.Zero);
await SnapshotFile.WriteAsync(directory, new Snapshot { MadeAt = DateTimeOffset.UtcNow, RefreshInterval = TimeSpan.FromMinutes(1),
Providers = [new(Provider.Codex, ProviderStatus.Available, null, [], new(), null, new(Total: 30), start, "week")] }, TestContext.Current.CancellationToken);
using var output = new StringWriter(); using var error = new StringWriter();
Assert.Equal(0, await CliApplication.RunAsync(["status"], output, error, directory, cancellationToken: TestContext.Current.CancellationToken));
Assert.Contains($"Limit week: since {start:O} (week)", output.ToString());
}
finally { Directory.Delete(directory, true); }
}
[Fact]
public async Task BusyStoreWithoutSnapshotExitsOne()
{
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
@@ -0,0 +1,98 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class DayBudgetTests
{
private static readonly TimeZoneInfo Zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
private static readonly DateTimeOffset Start = new(2026, 10, 10, 22, 40, 0, TimeSpan.FromHours(2));
private static LimitWindow Week(DateTimeOffset now, double used = 30) => new(Provider.Codex, "week", "Week", used,
Start.AddDays(7), TimeSpan.FromDays(7), now, "fixture");
private static WindowDays Days(DateTimeOffset now, double used, params LimitWindow[] samples) =>
LimitAnalysis.Days(Week(now, used), samples, now, Zone)!;
[Fact] public void EightDatesHaveRealPartialSharesAndEvenPace()
{
var days = Days(Start.AddMinutes(20), 1);
Assert.Equal(8, days.Current.Count);
Assert.Equal(TimeSpan.FromMinutes(80), days.Current[0].Share);
Assert.Equal(TimeSpan.FromHours(22).Add(TimeSpan.FromMinutes(40)), days.Current[^1].Share);
Assert.Equal(TimeSpan.FromDays(7).Ticks, days.Current.Sum(d => d.Share.Ticks));
Assert.Equal(100, days.Current.Sum(d => d.EvenPace), 8);
Assert.Equal(100d * 80 / (7 * 24 * 60), days.Current[0].EvenPace, 8);
Assert.All(days.Current.Skip(1).SkipLast(1), d => Assert.Equal(TimeSpan.FromDays(1), d.Share));
}
[Theory]
[InlineData(3, 29, 23)]
[InlineData(10, 25, 25)]
public void DaylightSavingSharesUseActualHours(int month, int date, int hours)
{
var zone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin");
var day = CalendarDays.Start(new DateTime(2026, month, date), zone);
var now = day.AddHours(12);
var window = Week(now) with { ResetsAt = day.AddDays(3) };
var days = LimitAnalysis.Days(window, [window with { SampleTime = day, UsedPercent = 20 }], now, zone)!;
var today = Assert.Single(days.Current, d => d.IsToday);
Assert.Equal(hours, today.Share.TotalHours);
Assert.Equal(100d * hours / 168, today.EvenPace, 8);
Assert.Equal(80d * hours / 72, today.Budget!.Value, 8);
}
[Fact] public void FirstPartialDayBudgetHoldsWhileSpending()
{
var first = Days(Start.AddMinutes(10), .2);
var later = Days(Start.AddMinutes(50), .7);
Assert.Equal(first.Current[0].EvenPace, first.TodayBudget);
Assert.Equal(first.TodayBudget, later.TodayBudget);
Assert.Equal(first.LaterBudget, later.LaterBudget);
Assert.Equal(UseOrigin.Measured, first.BudgetOrigin);
Assert.Equal(100, first.Current.Sum(d => d.Budget ?? 0), 8);
}
[Fact] public void MeasuredBaselineKeepsTodayAndLaterPlanUntilTodayExceedsBudget()
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var baseline = Week(day, 25);
var first = Days(day.AddHours(2), 26, baseline);
var within = Days(day.AddHours(12), 30, baseline);
var exceeded = Days(day.AddHours(16), 60, baseline);
var expected = 75 / (Start.AddDays(7) - day).TotalDays;
Assert.Equal(expected, first.TodayBudget!.Value, 8);
Assert.Equal(first.TodayBudget, within.TodayBudget);
Assert.Equal(first.TodayBudget, exceeded.TodayBudget);
Assert.Equal(first.LaterBudget, within.LaterBudget);
Assert.True(exceeded.LaterBudget < first.LaterBudget);
Assert.Equal(UseOrigin.Measured, within.BudgetOrigin);
Assert.All(within.Current.Where(d => !d.IsToday && !d.IsFuture), d => Assert.Null(d.Budget));
Assert.Equal(within.TodayBudget, Assert.Single(within.Current, d => d.IsToday).Budget);
Assert.Equal(100 - 25, within.Current.Sum(d => d.Budget ?? 0), 8);
Assert.Equal(0, Days(day.AddHours(17), 100, baseline).LaterBudget);
}
[Fact] public void TokenBaselineIsMarkedEstimated()
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var now = day.AddHours(12); var window = Week(now, 40);
ModelTokenPoint[] tokens = [new(Start, "fixture", new(Input: 100)), new(day, "fixture", new(Input: 100))];
var days = LimitAnalysis.Analyze(window, [], tokens, now, Zone)!.Days!;
Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin);
Assert.Equal(80 / (window.ResetsAt!.Value - day).TotalDays, days.TodayBudget!.Value, 8);
}
[Fact] public void LastDayHasOnlyItsRemainingBudget()
{
var now = Start.AddDays(7).AddHours(-2);
var baseline = Week(CalendarDays.Start(now, Zone), 80);
var days = Days(now, 90, baseline);
Assert.Equal(20, days.TodayBudget);
Assert.Null(days.LaterBudget);
Assert.Equal(20, days.Current[^1].Budget);
Assert.DoesNotContain(days.Current, d => d.IsFuture);
}
[Fact] public void MissingBaselineAndExpiredResetHaveNoBudget()
{
var now = Start.AddDays(3);
var unknown = Days(now, 30);
Assert.Null(unknown.TodayBudget); Assert.Null(unknown.LaterBudget); Assert.Null(unknown.BudgetOrigin);
Assert.All(unknown.Current, d => Assert.Null(d.Budget));
var expired = Days(Start.AddDays(7), 90, Week(Start.AddDays(6), 80));
Assert.Null(expired.TodayBudget); Assert.Null(expired.LaterBudget);
Assert.All(expired.Current, d => Assert.Null(d.Budget));
}
}
@@ -8,7 +8,7 @@ public class EarlyForecastTests
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()
[Fact] public void AheadCodexWeekProjectsEarly()
{
var window = Week(); var pace = Pace.Calculate(window, Now);
Assert.Equal(PaceState.Ahead, pace.State);
@@ -48,7 +48,7 @@ public class EarlyForecastTests
[InlineData(40, false)]
public void AllForecastsFollowConfiguredThreshold(double threshold, bool eligible)
{
var window = Week(); var pace = Pace.Calculate(window, Now, threshold);
var window = Week() with { Length = TimeSpan.FromDays(28), ResetsAt = Now.AddDays(28).AddHours(-4) }; 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);
@@ -67,10 +67,19 @@ public class EarlyForecastTests
Assert.NotNull(LimitAnalysis.Recent(window, [window with { SampleTime = Now.AddHours(-4), UsedPercent = 20 }], Now, pace));
}
[Fact] public void ForecastStartIsTenPercentIntoWindow()
[Fact] public void UnderPaceCodexAtSixPointFourPercentShowsUseAtReset()
{
var window = Week(4) with { ResetsAt = Now + TimeSpan.FromTicks(TimeSpan.FromDays(7).Ticks * 936 / 1000) };
var pace = Pace.Calculate(window, Now);
Assert.Equal(PaceState.OnTrack, pace.State);
Assert.Null(pace.Projection);
Assert.Equal(62.5, LimitAnalysis.AverageUseAtReset(window, Now)!.Value, 8);
}
[Fact] public void ForecastStartIsTwoPercentIntoWindow()
{
var window = Week(1);
Assert.Equal(window.ResetsAt - TimeSpan.FromDays(6.3), Pace.ForecastStartsAt(window));
Assert.Equal(window.ResetsAt - TimeSpan.FromTicks(TimeSpan.FromDays(7).Ticks * 49 / 50), 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 }));
@@ -126,7 +126,7 @@ public sealed class LimitAnalysisTests
{
var w = Window();
var days = LimitAnalysis.Days(w, [w with { SampleTime = Now.AddHours(-14), UsedPercent = 51 }], Now, TimeZoneInfo.Utc)!;
Assert.Equal(9, days.Today); Assert.Equal(100d / 7, days.EvenPace); Assert.Equal(40 / 3.5, days.DailyBudget);
Assert.Equal(9, days.Today); Assert.Equal(100d / 7, days.EvenPace); Assert.Equal(49d / 4, days.TodayBudget);
Assert.Contains(days.Current, d => d.IsFuture && d.Used is null);
Assert.Contains(days.Current, d => d.Start == Now.AddHours(-36) && d.Used is null);
Assert.Null(LimitAnalysis.Days(w, [], Now, TimeZoneInfo.Utc)!.Today);
@@ -134,10 +134,10 @@ public sealed class TokenEstimateTests
[Theory]
[InlineData(5)]
[InlineData(168)]
public void ForecastsBeginAtExactlyTenPercentWithoutChangingState(int hours)
public void ForecastsBeginAtExactlyTwoPercentWithoutChangingState(int hours)
{
var start = Start; var length = TimeSpan.FromHours(hours);
var atThreshold = start + TimeSpan.FromTicks(length.Ticks / 10);
var atThreshold = start + TimeSpan.FromTicks(length.Ticks / 50);
var before = atThreshold.AddTicks(-1);
var window = Window with { ResetsAt = start + length, Length = length, SampleTime = before, UsedPercent = 11 };
Assert.Equal(PaceState.OnTrack, Pace.Calculate(window, before).State);
@@ -0,0 +1,59 @@
using System.Text.Json;
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class WeekTotalsTests
{
[Theory]
[InlineData("limit", true)]
[InlineData("family", false)]
[InlineData("expired", false)]
[InlineData("missing", false)]
[InlineData("mixed", true)]
public async Task EngineSelectsProviderWeekOrCalendarFallback(string kind, bool limit)
{
using var directory = new TestDirectory();
var clock = new WeekClock(); var now = clock.GetUtcNow();
await using var engine = new RefreshEngine(directory.Path, clock, claudeDirectory: directory.Path, codexDirectory: directory.Path,
cliDiscovery: (_, _) => new(null, "Fixture CLI missing."));
var start = new DateTimeOffset(2026, 10, 10, 22, 40, 0, TimeSpan.Zero);
var week = new LimitWindow(Provider.Codex, "week", "Week", 30, start.AddDays(7), TimeSpan.FromDays(7), now, "fixture");
var family = week with { Id = "family", Label = "Week (Fable)", Length = TimeSpan.FromDays(8) };
engine.History.AddLimits(kind switch
{
"limit" => [week], "family" => [family], "expired" => [week with { ResetsAt = now.AddHours(-1) }],
"mixed" => [family, week, week with { Id = "short", Length = TimeSpan.FromDays(2) }], _ => []
});
foreach (var (time, count) in new[] { (now.AddDays(-5), 10), (now.AddDays(-3), 20), (now.AddDays(-1), 30) })
engine.History.Add(new(Provider.Codex, time, "fixture", "fixture", new(Total: count), count.ToString()));
var snapshot = await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken);
var provider = snapshot.Providers.Single(p => p.Provider == Provider.Codex);
Assert.Equal(limit ? 50 : 30, provider.Week.Total);
Assert.Equal(limit ? start : new DateTimeOffset(2026, 10, 12, 0, 0, 0, TimeSpan.Zero), provider.WeekStart);
Assert.Equal(limit ? "week" : null, provider.WeekWindow);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void SourceGeneratedJsonReadsNewAndLegacyWeekFields(bool limit)
{
var start = new DateTimeOffset(2026, 10, 10, 22, 40, 0, TimeSpan.Zero);
var snapshot = new Snapshot { MadeAt = start.AddDays(2), RefreshInterval = TimeSpan.FromMinutes(1),
Providers = [new(Provider.Codex, ProviderStatus.Available, null, [], new(), null, new(Total: 30), start, limit ? "week" : null)] };
var json = JsonSerializer.Serialize(snapshot, CoreJsonContext.Default.Snapshot);
Assert.Contains("\"weekStart\"", json);
Assert.Equal(limit, json.Contains("\"weekWindow\"", StringComparison.Ordinal));
var provider = Assert.Single(JsonSerializer.Deserialize(json, CoreJsonContext.Default.Snapshot)!.Providers);
Assert.Equal(start, provider.WeekStart); Assert.Equal(limit ? "week" : null, provider.WeekWindow);
const string old = """{"v":1,"madeAt":"2026-10-14T16:00:00Z","refreshInterval":"00:01:00","providers":[{"provider":1,"status":0,"windows":[],"today":{},"session":null,"week":{"total":30}}]}""";
var legacy = JsonSerializer.Deserialize(old, CoreJsonContext.Default.Snapshot)!;
Assert.Equal(1, legacy.V); Assert.Equal(30, legacy.Providers[0].Week.Total);
Assert.Equal(default, legacy.Providers[0].WeekStart); Assert.Null(legacy.Providers[0].WeekWindow);
}
private sealed class WeekClock : TimeProvider
{
public override DateTimeOffset GetUtcNow() => new(2026, 10, 14, 16, 0, 0, TimeSpan.Zero);
public override TimeZoneInfo LocalTimeZone => TimeZoneInfo.Utc;
}
}