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:
@@ -5,6 +5,70 @@ 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;
|
||||
var first = model.RefreshAsync(() => { calls++; return completion.Task; });
|
||||
Assert.True(model.Refreshing);
|
||||
await model.RefreshAsync(() => { calls++; return Task.CompletedTask; });
|
||||
Assert.Equal(1, calls); completion.SetResult(); await first; Assert.False(model.Refreshing);
|
||||
await Assert.ThrowsAsync<IOException>(() => model.RefreshAsync(() => throw new IOException("fixture")));
|
||||
Assert.False(model.Refreshing);
|
||||
}
|
||||
[Theory]
|
||||
[InlineData(-1, "now")]
|
||||
[InlineData(0, "now")]
|
||||
[InlineData(59, "1 min")]
|
||||
[InlineData(3600, "1 h 0 min")]
|
||||
[InlineData(90061, "1 d 1 h")]
|
||||
public void DurationUsesDaysHoursAndRoundedMinutes(int seconds, string expected)
|
||||
=> Assert.Equal(expected, Display.Duration(TimeSpan.FromSeconds(seconds)));
|
||||
[Theory]
|
||||
[InlineData(PaceState.Ahead, "\u25b2 Ahead")]
|
||||
[InlineData(PaceState.Behind, "\u25bc Behind")]
|
||||
[InlineData(PaceState.OnTrack, "\u2713 On track")]
|
||||
[InlineData(PaceState.Unknown, "? Pace unknown")]
|
||||
public void StatusChipsAlwaysNameTheirState(PaceState state, string expected) => Assert.Equal(expected, Display.State(state));
|
||||
[Fact] public void BreakdownSortingUsesTheSelectedNumericColumn()
|
||||
{
|
||||
BreakdownRow[] rows = [new("a", new(Input: 30, Output: 2, Total: 32), .4), new("b", new(Input: 10, Output: 40, Total: 50), .6)];
|
||||
Assert.Equal("b", BreakdownTable.SortRows(rows, BreakdownColumn.Total, true).First().Name);
|
||||
Assert.Equal("a", BreakdownTable.SortRows(rows, BreakdownColumn.Input, true).First().Name);
|
||||
Assert.Equal("a", BreakdownTable.SortRows(rows, BreakdownColumn.Output, false).First().Name);
|
||||
}
|
||||
[Theory]
|
||||
[InlineData(-1)]
|
||||
[InlineData(1)]
|
||||
public void ResetDriftKeepsChartContinuousAndRealResetAddsGap(int minutes)
|
||||
{
|
||||
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
|
||||
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
|
||||
var window = new LimitWindow(Provider.Claude, "week", "Week", 60, now.AddDays(4), TimeSpan.FromDays(7), now.AddMinutes(-1), "fixture");
|
||||
var first = window with { SampleTime = CalendarDays.Start(now).AddHours(-1), UsedPercent = 40, ResetsAt = window.ResetsAt!.Value.AddMinutes(minutes) };
|
||||
store.AddLimits([first]);
|
||||
store.AddLimits([window with { SampleTime = now.AddHours(-3), UsedPercent = 50, ResetsAt = window.ResetsAt!.Value.AddMinutes(-minutes) }]);
|
||||
store.AddLimits([window]);
|
||||
Snapshot SnapshotFor(LimitWindow w, DateTimeOffset time) => new() { MadeAt = time, RefreshInterval = TimeSpan.FromMinutes(1),
|
||||
Providers = [new(Provider.Claude, ProviderStatus.Available, null, [new(w, Pace.Calculate(w, time))], new(), null, new())] };
|
||||
var view = PanelViewModel.QueryHistory(store, SnapshotFor(window, now), HistoryRange.All, null, now);
|
||||
Assert.All(Assert.Single(view.Limits).Values, v => Assert.False(v.BreakBefore));
|
||||
var detail = Assert.Single(view.Details);
|
||||
Assert.Equal(first.SampleTime, detail.Since); Assert.Equal(20, detail.Days!.Today); Assert.NotNull(detail.Recent);
|
||||
var next = window with { ResetsAt = window.ResetsAt!.Value.AddDays(7), SampleTime = now.AddDays(7).AddMinutes(-1), UsedPercent = 5 };
|
||||
store.AddLimits([next]);
|
||||
var nextView = PanelViewModel.QueryHistory(store, SnapshotFor(next, now.AddDays(7)), HistoryRange.All, null, now.AddDays(7));
|
||||
Assert.Equal(1, Assert.Single(nextView.Limits).Values.Count(v => v.BreakBefore));
|
||||
Assert.True(Assert.Single(nextView.Limits).Values[^1].BreakBefore);
|
||||
}
|
||||
[Theory]
|
||||
[InlineData(HistoryRange.Hours24, 1)]
|
||||
[InlineData(HistoryRange.Days7, 7)]
|
||||
@@ -55,6 +119,43 @@ public sealed class ViewModelTests
|
||||
}
|
||||
[Fact] public void DesktopEntryQuotesExecutableAndEscapesFieldCodes()
|
||||
{ var text = OsStartup.DesktopEntry("/opt/Final Token/100%/app"); Assert.Contains("Exec=\"/opt/Final Token/100%%/app\"", text); Assert.Contains("Terminal=false", text); }
|
||||
[Fact] public void BreakdownQueryReturnsEveryRowAndItsShareWithoutPrebuildingOther()
|
||||
{
|
||||
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
|
||||
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
|
||||
for (var i = 0; i < 110; i++) store.Add(new(Provider.Claude, now.AddHours(-1), "model", $"project-{i}", new(Total: i + 1), $"{i}"));
|
||||
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, null, now);
|
||||
Assert.Equal(110, view.Projects.Count); Assert.Equal("project-109", view.Projects[0].Name);
|
||||
Assert.Equal("project-0", view.Projects[^1].Name); Assert.Equal(6105, view.Projects.Sum(r => r.Counts.Total));
|
||||
Assert.Equal(1, view.Projects.Sum(r => r.Share), 8);
|
||||
}
|
||||
[Fact] public void FilteredModelSeriesUseSixAlphabeticSlotsAndOther()
|
||||
{
|
||||
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
|
||||
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
|
||||
for (var i = 9; i >= 0; i--) store.Add(new(Provider.Claude, now.AddHours(-1), $"model-{i}", "p", new(CacheRead: 2, Total: 10), $"{i}"));
|
||||
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, Provider.Claude, now);
|
||||
Assert.Equal(7, view.Hourly.Count); Assert.Equal(40, view.Hourly.Single(p => p.Series == "Other").Value);
|
||||
Assert.Equal(100, view.Hourly.Sum(p => p.Value)); Assert.Equal(20, view.Hourly.Sum(p => p.CacheRead));
|
||||
Assert.Equal(view.Hourly.Select(p => p.Series).Order(), view.Daily.Select(p => p.Series).Order());
|
||||
Assert.DoesNotContain(view.Hourly, p => p.Series == "model-6");
|
||||
}
|
||||
[Fact] public void ProjectNamesKeepTwoSegmentsAndDisambiguateCollisions()
|
||||
{
|
||||
var names = PanelWindow.ShortProjectNames(["D:/First/Shared/App", "D:/Second/Shared/App", "/work/Only/App", "Unknown"]);
|
||||
Assert.Equal(["First/Shared/App", "Second/Shared/App", "Only/App", "Unknown"], names);
|
||||
}
|
||||
[Fact] public void ModelBreakdownKeepsActualProviderIdentityForDots()
|
||||
{
|
||||
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
|
||||
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
|
||||
store.Add(new(Provider.Claude, now.AddHours(-1), "arbitrary-name", "p", new(Total: 10), "a"));
|
||||
store.Add(new(Provider.Codex, now.AddHours(-1), "shared-name", "p", new(Total: 20), "b"));
|
||||
store.Add(new(Provider.Claude, now.AddHours(-1), "shared-name", "p", new(Total: 30), "c"));
|
||||
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, null, now);
|
||||
Assert.Equal([Provider.Claude], view.Models.Single(r => r.Name == "arbitrary-name").Providers);
|
||||
Assert.Equal([Provider.Claude, Provider.Codex], view.Models.Single(r => r.Name == "shared-name").Providers);
|
||||
}
|
||||
[Fact] public void DesktopEntryRejectsInjectedLine() => Assert.Throws<ArgumentException>(() => OsStartup.DesktopEntry("/app\nExec=other"));
|
||||
[Fact] public void DesktopEntryEscapesCommandCharactersAtBothParsingLevels()
|
||||
{
|
||||
@@ -65,25 +166,70 @@ 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 =
|
||||
[new(Provider.Claude, ProviderStatus.Available, null, [Window(Provider.Claude, "session", "Current session", 68, now, 5, 3), Window(Provider.Claude, "week", "Current week", 32, now, 168, 48)],
|
||||
new(12000, 18000, 2000, 4200, 0, 36200), new(4000, 6000, 1000, 1600, 0, 12600), new(85000, 92000, 16000, 28000, 0, 221000)),
|
||||
[new(Provider.Claude, ProviderStatus.Available, null, [Window(Provider.Claude, "session", "Session · 5 h", 12, now, 5, 1), Window(Provider.Claude, "week", "Week · all models", 98, now, 168, 24)],
|
||||
new(12000000, 218000000, 2000000, 47000000, 0, 279000000), new(4000000, 6000000, 1000000, 1600000, 0, 12600000), new(85000000, 1920000000, 16000000, 259000000, 0, 2280000000)),
|
||||
new(Provider.Codex, unavailable ? ProviderStatus.Unavailable : ProviderStatus.Available, unavailable ? "CLI is not installed. Token history remains available." : null,
|
||||
[Window(Provider.Codex, "primary", "Primary · 5 hours", 12, now, 5, 1), Window(Provider.Codex, "secondary", "Secondary · 7 days", 62, now, 168, 80)],
|
||||
new(72000, 42000, 0, 8400, 2100, 80400), new(23000, 10000, 0, 3200, 700, 26200), new(340000, 150000, 0, 38000, 11000, 378000))]
|
||||
[Window(Provider.Codex, "secondary", "Week", 86, now, 168, 24)],
|
||||
new(72000000, 42000000, 0, 8400000, 2100000, 80400000), null, new(340000000, 150000000, 0, 38000000, 11000000, 378000000))]
|
||||
};
|
||||
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 EarlyResetModel()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var transition = now.AddHours(-1);
|
||||
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-early", Guid.NewGuid().ToString("N")), new DiagnosticLog());
|
||||
var snapshot = Snapshot(now);
|
||||
var codex = snapshot.Providers.Single(p => p.Provider == Provider.Codex);
|
||||
var window = codex.Windows[0].Window with { UsedPercent = 2, ResetsAt = transition.AddDays(7), SampleTime = now };
|
||||
var previous = window with { ResetsAt = transition.AddDays(5), SampleTime = transition.AddDays(-1), UsedPercent = 40 };
|
||||
store.AddLimits([previous, window with { SampleTime = transition, UsedPercent = 1 }, window]);
|
||||
var start = previous.ResetsAt!.Value - previous.Length!.Value;
|
||||
void Add(DateTimeOffset time, long input, string id) => store.Add(new(Provider.Codex, time, "gpt-6.1-sol", "Fixture/Project", new(Input: input, Total: input), id));
|
||||
Add(start, 1000000, "a"); Add(previous.SampleTime.AddHours(1), 5000000, "b"); Add(transition, 100000, "c");
|
||||
snapshot = snapshot with { Providers = [codex with { Windows = [new(window, Pace.Calculate(window, now))] }] };
|
||||
return new() { Snapshot = snapshot, History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
|
||||
}
|
||||
public static PanelViewModel Model(bool unavailable = false)
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var hourly = Enumerable.Range(0, 24).SelectMany(i => new[] { new ChartValue(now.AddHours(-24 + i), "Claude", 1000 + i * 210), new ChartValue(now.AddHours(-24 + i), "Codex", 2000 + (i % 5) * 800) }).ToArray();
|
||||
var daily = Enumerable.Range(0, 7).SelectMany(i => new[] { new ChartValue(now.AddDays(-7 + i), "Claude", 20000 + i * 2000), new ChartValue(now.AddDays(-7 + i), "Codex", 30000 + i * 5000) }).ToArray();
|
||||
return new() { Snapshot = Snapshot(now, unavailable), Message = "Updated just now · local CLI data", History = new(hourly, daily,
|
||||
[new("Claude · Current session", Enumerable.Range(0, 8).Select(i => new ChartValue(now.AddMinutes(-140 + i * 20), "session", i * 8 + 12, i * 6)).ToArray())],
|
||||
[new("claude-sonnet", new(Total: 221000), 0.37), new("gpt-6.1-sol", new(Total: 378000), 0.63)], [new("FinalToken", new(Total: 599000), 1)]),
|
||||
Diagnostics = [new(now.AddMinutes(-4), Provider.Claude, "sample-age", "Latest limit sample is three minutes old.")] };
|
||||
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-fake", Guid.NewGuid().ToString("N")), new DiagnosticLog());
|
||||
var snapshot = Snapshot(now, unavailable);
|
||||
foreach (var provider in snapshot.Providers)
|
||||
{
|
||||
for (var i = 0; i < 336; i++)
|
||||
{
|
||||
var input = 1000000 + i * 10000; var cache = input * 8;
|
||||
store.Add(new(provider.Provider, now.AddHours(-336 + i), provider.Provider == Provider.Claude ? "claude-fable" : "gpt-6.1-sol",
|
||||
$"D:/Projects/Customer-{i % 110}/Workspace/Project-{i % 110}",
|
||||
provider.Provider == Provider.Claude ? new(input, cache, 200000, 500000, 0, input + cache + 700000) : new(input + cache, cache, 0, 500000, 100000, input + cache + 500000), $"{provider.Provider}-{i}"));
|
||||
}
|
||||
foreach (var ws in provider.Windows)
|
||||
{
|
||||
var w = ws.Window; var start = w.ResetsAt!.Value - w.Length!.Value;
|
||||
for (var i = provider.Provider == Provider.Claude && w.Length > TimeSpan.FromDays(1) ? (int)(now - start).TotalHours - 24 : 0; i <= (int)(now - start).TotalHours; i += w.Length > TimeSpan.FromDays(1) ? 3 : 1)
|
||||
store.AddLimits([w with { SampleTime = start.AddHours(i), UsedPercent = w.UsedPercent * i / (now - start).TotalHours }]);
|
||||
var previousReset = start - (w.Length > TimeSpan.FromDays(1) ? TimeSpan.Zero : TimeSpan.FromHours(6));
|
||||
for (var i = 0; i < (int)w.Length!.Value.TotalHours; i += w.Length > TimeSpan.FromDays(1) ? 6 : 1)
|
||||
store.AddLimits([w with { ResetsAt = previousReset, SampleTime = previousReset - w.Length.Value + TimeSpan.FromHours(i), UsedPercent = 100.0 * i / w.Length.Value.TotalHours }]);
|
||||
}
|
||||
}
|
||||
return new() { Snapshot = snapshot, Message = "Updated just now", History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user