Reuse the existing weekly pace, reset history and daily budgets across multiple machines without multiplying shared account quota. Coordinate profile-bound official CLI logins through transient authorization responses while keeping provider credentials local to each CLI. Release as version 1.2.0. Refs #19
201 lines
13 KiB
C#
201 lines
13 KiB
C#
using System.Text.Json;
|
|
using FinalToken.Core;
|
|
using FinalToken.Fleet;
|
|
using Xunit;
|
|
|
|
namespace FinalToken.Fleet.Tests;
|
|
|
|
public sealed class FleetTests
|
|
{
|
|
private static readonly DateTimeOffset Now = new(2026, 11, 14, 12, 0, 0, TimeSpan.Zero);
|
|
internal static ServerConfig Config(Provider provider = Provider.Claude) => new(
|
|
[new("personal", provider, "Personal", "[email protected]")],
|
|
[new("a", "Desktop", "tester", [new("main", "personal")]), new("b", "LXC", "tester", [new("main", "personal")])]);
|
|
internal static LimitWindow Week(double used = 60, DateTimeOffset? sample = null) => new(Provider.Claude, "week", "Week", used,
|
|
Now.AddDays(3.5), TimeSpan.FromDays(7), sample ?? Now, "fixture");
|
|
internal static ProfileReport Profile(IReadOnlyList<SourceUsage>? usage = null, IReadOnlyList<LimitWindow>? limits = null, Provider provider = Provider.Claude) =>
|
|
new("main", provider, new("Healthy", "[email protected]", Now, "CLI identity"), new(), usage ?? [], limits ?? [], [], DataEmail: "[email protected]");
|
|
internal static MachineState Machine(string id, ProfileReport profile, DateTimeOffset? seen = null, string boot = "boot") =>
|
|
new(id, seen ?? Now, new(id, "tester", boot, Now, [profile], []));
|
|
private static AccountView Analyze(ProfileReport a, ProfileReport? b = null, ServerConfig? config = null, DateTimeOffset? now = null) =>
|
|
FleetAnalysis.Build(config ?? Config(a.Provider), new(b is null ? [Machine("a", a)] : [Machine("a", a), Machine("b", b)]), now ?? Now).Accounts.Single();
|
|
|
|
[Fact] public void SameAccountQuotaIsNeverSummedAcrossMachines()
|
|
{
|
|
var a = Profile(limits: [Week(60)]); var b = Profile(limits: [Week(59, Now.AddMinutes(-1))]);
|
|
var view = Analyze(a, b);
|
|
Assert.Single(view.Windows); Assert.Equal(60, view.Windows[0].Window.UsedPercent);
|
|
Assert.Equal(120d, view.Windows[0].UseAtReset); Assert.Equal(-20d, view.Windows[0].RemainingAtReset);
|
|
Assert.Equal(Now.AddDays(7d / 3), view.Windows[0].Pace.Projection);
|
|
}
|
|
[Fact] public void ClaudeResponseIsCountedOnceAcrossMachinesAndRetries()
|
|
{
|
|
SourceUsage u = new("response-1", null, Now, "claude-opus-4-6", new(Input: 100, Total: 100));
|
|
var account = Analyze(Profile([u, u]), Profile([u]));
|
|
Assert.Equal(100, account.Total.Total); Assert.Equal(.0005m, account.ApiValue);
|
|
}
|
|
[Fact] public void CodexSessionCopiesUseOrderedCumulativeIncreases()
|
|
{
|
|
SourceUsage first = new("s:100", "s", Now.AddHours(-2), "gpt-5.4", new(Input: 100, Total: 100));
|
|
var second = first with { Key = "s:180", Time = Now.AddHours(-1), Counts = new(Input: 180, Total: 180) };
|
|
var view = Analyze(Profile([second, first], provider: Provider.Codex), Profile([first, second], provider: Provider.Codex));
|
|
Assert.Equal(180, view.Total.Total);
|
|
}
|
|
[Fact] public void CodexCounterResetDoesNotEraseLaterUsage()
|
|
{
|
|
SourceUsage first = new("one", "s", Now.AddHours(-3), "gpt-5.4", new(Input: 100, Total: 100));
|
|
var reset = first with { Key = "two", Time = Now.AddHours(-2), Counts = new(Input: 10, Total: 10) };
|
|
var next = first with { Key = "three", Time = Now.AddHours(-1), Counts = new(Input: 30, Total: 30) };
|
|
Assert.Equal(120, Analyze(Profile([first, reset, next], provider: Provider.Codex)).Total.Total);
|
|
}
|
|
[Fact] public void ConflictingResponseMetadataIsExcludedAndDiagnosed()
|
|
{
|
|
SourceUsage u = new("same", null, Now, null, new(Total: 10));
|
|
var view = Analyze(Profile([u]), Profile([u with { Counts = new(Total: 20) }]));
|
|
Assert.Equal(0, view.Total.Total); Assert.Contains(view.Warnings, w => w.Contains("Conflicting"));
|
|
}
|
|
[Fact] public void StaleQuotaDoesNotFabricateForecastOrZero()
|
|
{
|
|
var view = Analyze(Profile(limits: [Week(75, Now.AddHours(-1))]));
|
|
Assert.True(view.Windows[0].Stale); Assert.Equal(75, view.Windows[0].Window.UsedPercent);
|
|
Assert.Null(view.Windows[0].UseAtReset); Assert.Null(view.Windows[0].Analysis);
|
|
}
|
|
[Fact] public void ExpiredResetHasNoFutureProjection()
|
|
{
|
|
var view = Analyze(Profile(limits: [Week() with { ResetsAt = Now }]));
|
|
Assert.True(view.Windows[0].Stale); Assert.Null(view.Windows[0].Pace.Projection);
|
|
}
|
|
[Fact] public void EarlyForecastRemainsUnknownBelowEligibility()
|
|
{
|
|
var week = Week(1) with { ResetsAt = Now.AddDays(7).AddMinutes(-10) };
|
|
Assert.Null(Analyze(Profile(limits: [week])).Windows[0].UseAtReset);
|
|
}
|
|
[Fact] public void AheadEarlyWeekRetainsExistingD7Warning()
|
|
{
|
|
var week = Week(39) with { ResetsAt = Now.AddDays(7).AddHours(-10) };
|
|
var view = Analyze(Profile(limits: [week])).Windows[0];
|
|
Assert.Equal(PaceState.Ahead, view.Pace.State); Assert.NotNull(view.Pace.Projection);
|
|
}
|
|
[Fact] public void RecentForecastRequiresThreeHoursAndSameReset()
|
|
{
|
|
var week = Week(60);
|
|
var view = Analyze(Profile(limits: [week with { UsedPercent = 50, SampleTime = Now.AddHours(-3) }, week])).Windows[0];
|
|
Assert.NotNull(view.Recent); Assert.Equal(80, view.Recent.PercentPerDay);
|
|
var shortSpan = Analyze(Profile(limits: [week with { UsedPercent = 50, SampleTime = Now.AddHours(-2) }, week])).Windows[0];
|
|
Assert.Null(shortSpan.Recent);
|
|
}
|
|
[Fact] public void DailyBudgetAndPartialDaysComeFromExistingAnalysis()
|
|
{
|
|
var week = Week(); var midnight = new DateTimeOffset(2026, 11, 14, 0, 0, 0, TimeSpan.Zero);
|
|
var view = Analyze(Profile(limits: [week with { UsedPercent = 50, SampleTime = midnight }, week])).Windows[0];
|
|
Assert.NotNull(view.Analysis?.Days); Assert.Equal(12.5, view.Analysis.Days.TodayBudget);
|
|
Assert.Equal(10, view.Analysis.Days.Today); Assert.Equal(7, view.Analysis.Days.Current.Count);
|
|
}
|
|
[Fact] public void LoggedOutProfileRetainsAttributedHistoryAndWithholdsForecast()
|
|
{
|
|
var p = Profile([new("one", null, Now, null, new(Total: 42))], [Week()]) with { Auth = new("Unavailable", null, Now, "Signed out") };
|
|
var view = Analyze(p); Assert.Equal(42, view.Total.Total); Assert.True(view.Windows[0].Stale);
|
|
}
|
|
[Fact] public void WrongAccountCannotContributeToConfiguredAccount()
|
|
{
|
|
var p = Profile([new("one", null, Now, null, new(Total: 42))], [Week()]) with { DataEmail = "[email protected]" };
|
|
var view = Analyze(p); Assert.Empty(view.Windows); Assert.Equal(0, view.Total.Total);
|
|
Assert.False(view.HasConsumptionData);
|
|
}
|
|
[Fact] public void UnknownModelsRemainUnpricedAndDoNotImplyAllowance()
|
|
{
|
|
var view = Analyze(Profile([new("one", null, Now, "unknown-model", new(Total: 42))]));
|
|
Assert.Null(view.ApiValue); Assert.Equal(42, view.UnpricedTokens); Assert.Empty(view.Windows);
|
|
}
|
|
[Fact] public void LegacyHistoryUsesOneSourceAndNonOverlappingCutoff()
|
|
{
|
|
var cutoff = Now.AddDays(-1); var cfg = Config();
|
|
cfg = cfg with { Accounts = [cfg.Accounts[0] with { LegacyMachine = "a", LegacyProfile = "main", HistoryBefore = cutoff }] };
|
|
var raw = new SourceUsage("one", null, cutoff, null, new(Total: 7));
|
|
var a = Profile([raw, raw with { Key = "old", Time = cutoff.AddHours(-1) }]) with { LegacyTokens = [new(cutoff.AddHours(-1), null, new(Total: 100)), new(cutoff, null, new(Total: 999))] };
|
|
var b = Profile([raw]) with { LegacyTokens = [new(cutoff.AddHours(-1), null, new(Total: 200))] };
|
|
Assert.Equal(107, Analyze(a,b,cfg).Total.Total);
|
|
}
|
|
[Fact] public void DashboardJsonRoundTripsWithoutReflection()
|
|
{
|
|
var view = FleetAnalysis.Build(Config(),new([Machine("a",Profile(limits:[Week()]))]),Now);
|
|
var json = JsonSerializer.Serialize(view,FleetJsonContext.Default.DashboardView);
|
|
Assert.Contains("useAtReset",json); Assert.Contains("Ahead",json);
|
|
Assert.NotNull(JsonSerializer.Deserialize(json,FleetJsonContext.Default.DashboardView));
|
|
}
|
|
[Fact] public async Task StorePersistsOfflineMetadataButNeverLoginPayloads()
|
|
{
|
|
var path = Path.Combine(Path.GetTempPath(), "finaltoken-fleet-" + Guid.NewGuid().ToString("N"));
|
|
try
|
|
{
|
|
var store = new FleetStore(path, Config()); var report = Machine("a",Profile()).Report with { Logins = [new("id","main","WaitingForCode","https://claude.ai/oauth/authorize?state=secret")] };
|
|
await store.AcceptAsync(report,"a",Now,TestContext.Current.CancellationToken);
|
|
Assert.DoesNotContain("secret",File.ReadAllText(Path.Combine(path,"fleet.json")));
|
|
var loaded = new FleetStore(path,Config()).Dashboard(Now.AddMinutes(2));
|
|
Assert.False(loaded.Machines[0].Online); Assert.NotNull(loaded.Machines[0].SeenAt);
|
|
}
|
|
finally { if(Directory.Exists(path)) Directory.Delete(path,true); }
|
|
}
|
|
[Fact] public void MachineUserAndProfileAreValidatedAtTrustBoundary()
|
|
{
|
|
var path=Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString("N")); var store=new FleetStore(path,Config());
|
|
var report=Machine("a",Profile()).Report;
|
|
Assert.Throws<InvalidDataException>(()=>store.Validate(report,"b",Now));
|
|
Assert.Throws<InvalidDataException>(()=>store.Validate(report with {OsUser="root"},"a",Now));
|
|
Assert.Throws<InvalidDataException>(()=>store.Validate(report with {Profiles=[Profile() with {Id="other"}]},"a",Now));
|
|
}
|
|
[Fact] public async Task EmptyRestartHeartbeatCannotErasePreviouslyAttributedHistory()
|
|
{
|
|
var path=Path.Combine(Path.GetTempPath(),"finaltoken-fleet-"+Guid.NewGuid().ToString("N"));
|
|
try
|
|
{
|
|
var store=new FleetStore(path,Config());
|
|
var original=Machine("a",Profile([new("one",null,Now,null,new(Total:42))],[Week()])).Report;
|
|
await store.AcceptAsync(original,"a",Now,TestContext.Current.CancellationToken);
|
|
var restart=original with {BootId="new",CollectedAt=Now.AddSeconds(1),Profiles=[Profile() with {DataEmail=null,Auth=new("Unknown",null,Now,"Starting")}]};
|
|
await store.AcceptAsync(restart,"a",Now.AddSeconds(1),TestContext.Current.CancellationToken);
|
|
var account=store.Dashboard(Now.AddSeconds(1)).Accounts.Single();
|
|
Assert.Equal(42,account.Total.Total);Assert.True(account.Windows.Single().Stale);
|
|
}
|
|
finally {if(Directory.Exists(path))Directory.Delete(path,true);}
|
|
}
|
|
[Fact] public void CodexLegacyCutoffMustRetainPreCutoffCumulativeBaseline()
|
|
{
|
|
var cutoff=Now.AddDays(-1);var cfg=Config(Provider.Codex);
|
|
cfg=cfg with {Accounts=[cfg.Accounts[0] with {LegacyMachine="a",LegacyProfile="main",HistoryBefore=cutoff}]};
|
|
SourceUsage old=new("old","session",cutoff.AddHours(-1),null,new(Total:100));
|
|
var next=old with {Key="next",Time=cutoff,Counts=new(Total:180)};
|
|
var p=Profile([old,next],provider:Provider.Codex) with {LegacyTokens=[new(cutoff.AddHours(-1),null,new(Total:100))]};
|
|
Assert.Equal(180,Analyze(p,config:cfg).Total.Total);
|
|
}
|
|
[Fact] public void SharedResponseSessionAttributionDoesNotMultiplyAccountConsumption()
|
|
{
|
|
SourceUsage u=new("response","session-a",Now,null,new(Total:100));
|
|
var view=Analyze(Profile([u]),Profile([u with {Session="session-b"}]));
|
|
Assert.Equal(100,view.Total.Total);Assert.Single(view.Sessions);Assert.Equal(100,view.Sessions[0].Tokens.Total);
|
|
}
|
|
[Fact] public void DisabledProfileCannotPresentLiveForecast()
|
|
{
|
|
var settings=new Settings {Claude=new ProviderSettings {Enabled=false}};
|
|
var view=Analyze(Profile(limits:[Week()]) with {Settings=settings});
|
|
Assert.True(view.Windows.Single().Stale);Assert.Null(view.Windows.Single().UseAtReset);
|
|
}
|
|
[Fact] public void MissingCodexMigrationBaselineCannotDoubleChargeUnknownPreCutoffUsage()
|
|
{
|
|
var cutoff=Now.AddDays(-1);var cfg=Config(Provider.Codex);
|
|
cfg=cfg with {Accounts=[cfg.Accounts[0] with {LegacyMachine="a",LegacyProfile="main",HistoryBefore=cutoff}]};
|
|
SourceUsage first=new("first","session",cutoff,null,new(Total:180));
|
|
var next=first with {Key="next",Time=cutoff.AddHours(1),Counts=new(Total:200)};
|
|
var p=Profile([first,next],provider:Provider.Codex) with {LegacyTokens=[new(cutoff.AddHours(-1),null,new(Total:100))]};
|
|
var view=Analyze(p,config:cfg);
|
|
Assert.Equal(120,view.Total.Total);Assert.Contains(view.Warnings,w=>w.Contains("baseline"));
|
|
}
|
|
[Fact] public void MalformedNestedMetadataIsRejectedBeforePersistence()
|
|
{
|
|
var store=new FleetStore(Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString("N")),Config());
|
|
var report=Machine("a",Profile()).Report;
|
|
Assert.Throws<InvalidDataException>(()=>store.Validate(report with {Profiles=[Profile() with {Auth=new("Healthy",null,Now,null!)}]},"a",Now));
|
|
Assert.Throws<InvalidDataException>(()=>store.Validate(report with {Logins=[null!]},"a",Now));
|
|
}
|
|
}
|