core: add self-hosted weekly dashboard and machine workers

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
This commit is contained in:
Florian Schmidt
2026-11-15 10:59:39 +01:00
parent cd000437a0
commit ab3dcf64e8
34 changed files with 1981 additions and 13 deletions
+2
View File
@@ -0,0 +1,2 @@
# Fleet tests
Use synthetic metadata and fake CLI adapters. Cover account quota selection, source identity deduplication, reset forecasts, stale data, and session/profile login routing. No live provider credentials or login required.
@@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><IsTestProject>true</IsTestProject><UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner><TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport></PropertyGroup>
<ItemGroup><PackageReference Include="xunit.v3.aot.mtp-v2" /><ProjectReference Include="../../src/FinalToken.Fleet/FinalToken.Fleet.csproj" /></ItemGroup>
</Project>
+200
View File
@@ -0,0 +1,200 @@
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));
}
}
+108
View File
@@ -0,0 +1,108 @@
using FinalToken.Core;
using FinalToken.Core.Processes;
using FinalToken.Fleet;
using Xunit;
namespace FinalToken.Fleet.Tests;
public sealed class LoginTests
{
private static readonly DateTimeOffset Now=new(2026,11,14,12,0,0,TimeSpan.Zero);
private static FleetState State => new([FleetTests.Machine("a",FleetTests.Profile()),FleetTests.Machine("b",FleetTests.Profile())]);
private static WorkerProfile Profile => new("main",Provider.Claude,"[email protected]",Path.GetTempPath(),Path.GetTempPath());
[Fact] public void LoginBelongsToInitiatingBrowserSession()
{
var c=new LoginCoordinator(FleetTests.Config());var p=c.Start("browser-a","a","main",State,Now);
Assert.Throws<KeyNotFoundException>(()=>c.Get(p.Id,"browser-b",Now));
Assert.Throws<KeyNotFoundException>(()=>c.Respond(p.Id,"browser-b","code#state",Now));
Assert.Throws<KeyNotFoundException>(()=>c.Cancel(p.Id,"browser-b",Now));
}
[Fact] public void ResponseTravelsOnlyToExactMachineProfileAndOnceAcknowledgedIsCleared()
{
var c=new LoginCoordinator(FleetTests.Config());var p=c.Start("browser","a","main",State,Now);
c.Exchange("b","boot",[new(p.Id,"main","WaitingForCode")],Now);
Assert.Equal("Queued",c.Get(p.Id,"browser",Now).State);
c.Exchange("a","boot",[new(p.Id,"wrong","WaitingForCode")],Now);
Assert.Equal("Queued",c.Get(p.Id,"browser",Now).State);
c.Exchange("a","boot",[new(p.Id,"main","WaitingForCode","https://claude.ai/oauth/authorize?state=abc")],Now);
c.Respond(p.Id,"browser","code#state",Now);
Assert.Empty(c.Exchange("b","boot",[],Now).Commands);
Assert.Equal("code#state",c.Exchange("a","boot",[],Now).Commands.Single().Response);
Assert.Throws<InvalidDataException>(()=>c.Respond(p.Id,"browser","again",Now));
c.Exchange("a","boot",[new(p.Id,"main","Verifying",InputAccepted:true)],Now);
Assert.Null(c.Exchange("a","boot",[],Now).Commands.Single().Response);
}
[Fact] public void ConcurrentLoginOnOneProfileIsRejectedButOtherMachinesAreIndependent()
{
var c=new LoginCoordinator(FleetTests.Config());c.Start("browser","a","main",State,Now);
Assert.Throws<InvalidDataException>(()=>c.Start("other","a","main",State,Now));
Assert.NotNull(c.Start("browser","b","main",State,Now));
}
[Fact] public void TimeoutAndCancellationSendCancellationWithoutRetainingCode()
{
var c=new LoginCoordinator(FleetTests.Config());var p=c.Start("browser","a","main",State,Now);
Assert.Equal("TimedOut",c.Get(p.Id,"browser",Now.AddMinutes(16)).State);
Assert.True(c.Exchange("a","boot",[],Now.AddMinutes(16)).Commands.Single().Cancel);
var second=c.Start("browser","a","main",State,Now);
c.Cancel(second.Id,"browser",Now);Assert.Equal("Cancelling",c.Get(second.Id,"browser",Now).State);
Assert.True(c.Exchange("a","boot",[],Now).Commands.Single(x=>x.Id==second.Id).Cancel);
c.Exchange("a","boot",[new(second.Id,"main","Cancelled")],Now);
Assert.Equal("Cancelled",c.Get(second.Id,"browser",Now).State);
}
[Fact] public void RestartDoesNotReplayOldLoginAgainstNewWorkerProcess()
{
var c=new LoginCoordinator(FleetTests.Config());var p=c.Start("browser","a","main",State,Now);
Assert.Empty(c.Exchange("a","new-boot",[],Now).Commands);
Assert.Equal("WorkerRestarted",c.Get(p.Id,"browser",Now).State);
}
[Fact] public void WrongAccountIsExplicitFailureEvenIfWorkerClaimsSuccess()
{
var c=new LoginCoordinator(FleetTests.Config());var p=c.Start("browser","a","main",State,Now);
c.Exchange("a","boot",[new(p.Id,"main","Succeeded",Email:"[email protected]")],Now);
Assert.Equal("AccountMismatch",c.Get(p.Id,"browser",Now).State);
}
[Fact] public void OnlyOfficialUrlsReachTheBrowser()
{
Assert.False(LoginOutput.OfficialUrl(Provider.Claude,"https://evil.test/oauth/authorize"));
Assert.False(LoginOutput.OfficialUrl(Provider.Claude,"https://claude.ai.evil.test/oauth/authorize"));
Assert.False(LoginOutput.OfficialUrl(Provider.Codex,"http://auth.openai.com/codex/device"));
Assert.True(LoginOutput.OfficialUrl(Provider.Codex,"https://auth.openai.com/codex/device"));
}
[Fact] public void ClaudePromptWithoutNewlineAndAnsiDeviceOutputAreParsed()
{
var claude=LoginOutput.Parse("id",Profile,"Open https://claude.ai/oauth/authorize?state=abc\nPaste code here if prompted: ",false);
Assert.Equal("WaitingForCode",claude.State);Assert.NotNull(claude.Url);
var codex=LoginOutput.Parse("id",Profile with {Provider=Provider.Codex},"\u001b[94mhttps://auth.openai.com/codex/device\u001b[0m\n\u001b[94mABCD-12345\u001b[0m",false);
Assert.Equal("ABCD-12345",codex.DeviceCode);Assert.Equal("WaitingForBrowser",codex.State);
}
[Fact] public void UnknownExpiryAndWrongIdentityRemainExplicit()
{
var health=CliAuthentication.Parse(Profile,new ProcessResult(0,"{\"loggedIn\":true,\"email\":\"[email protected]\"}"),Now);
Assert.Equal("AccountMismatch",health.State);
Assert.Equal("Unknown",CliAuthentication.Parse(Profile,new(0,"{}"),Now).State);
Assert.Equal("Unknown",CliAuthentication.Parse(Profile,new(0,"{\"loggedIn\":true}"),Now).State);
}
[Fact] public async Task WorkerRetriesCannotStartTwoProcessesOrRouteInputToWrongProfile()
{
var count=0;FakeLogin? fake=null;
await using var worker=new WorkerLogins([Profile],(c,p)=>{count++;return fake=new(c.Id,p.Id);});
var command=new LoginCommand("id","main",Now.AddMinutes(15));
await worker.ApplyAsync(new([command,command]),CancellationToken.None);
Assert.Equal(1,count);
await worker.ApplyAsync(new([command with {ProfileId="wrong",Response="secret"}]),CancellationToken.None);
Assert.Null(fake!.Response);
await worker.ApplyAsync(new([command with {Response="code#state"},command with {Response="code#state"}]),CancellationToken.None);
Assert.Equal(1,fake.Inputs);
fake.State="Succeeded";
Assert.True(worker.TakeIdentityChanges());Assert.False(worker.TakeIdentityChanges());
await worker.ApplyAsync(new([command with {Cancel=true}]),CancellationToken.None);Assert.True(fake.Cancelled);
}
private sealed class FakeLogin(string id,string profile):ILoginProcess
{
public string? Response;public int Inputs;public bool Cancelled;public string State="WaitingForCode";
public LoginUpdate Current=>new(id,profile,State);
public Task SubmitAsync(string response,CancellationToken token){if(Response is null){Response=response;Inputs++;}return Task.CompletedTask;}
public void Cancel()=>Cancelled=true;
public ValueTask DisposeAsync()=>ValueTask.CompletedTask;
}
}