feat: add FinalToken v1 for Claude and Codex usage (#2)
FinalToken v1: a NativeAOT tray app for Windows 11 and CachyOS that tracks Claude Code and Codex usage and limits through their CLIs only, with no provider sign-in and no tokens (R1-R7, D1-D11). - Core: incremental collectors for Claude transcripts and Codex rollouts, limit probes through `claude -p /usage` and `codex app-server`, a journaled history store, the refresh engine, pace and popup decisions, and the snapshot.json contract. - App (Avalonia): stats panel with limit bars, pace, projections, token totals, charts, limit history and breakdowns; tray, settings, non-activating pace popups, single-instance activation, start with the OS, and the Off/Ask/Automatic Stream Deck plugin install. - Stream Deck plugin (SDK v2, NativeAOT) for Elgato and OpenDeck. - finaltoken-cli, tools/publish.py, the documentation check and the agent review workflow. Closes #1
This commit was merged in pull request #2.
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using FinalToken.Core;
|
||||
|
||||
namespace FinalToken.App;
|
||||
|
||||
public enum HistoryRange { Hours24, Days7, Days30, Days90, All }
|
||||
public sealed record ChartValue(DateTimeOffset Time, string Series, double Value, double? Expected = null, bool BreakBefore = false);
|
||||
public sealed record BreakdownRow(string Name, TokenCounts Counts, double Share);
|
||||
public sealed record LimitChart(string Label, IReadOnlyList<ChartValue> Values);
|
||||
public sealed record HistoryView(IReadOnlyList<ChartValue> Hourly, IReadOnlyList<ChartValue> Daily,
|
||||
IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> Projects);
|
||||
|
||||
public partial class PanelViewModel : ObservableObject
|
||||
{
|
||||
[ObservableProperty] private Snapshot? snapshot;
|
||||
[ObservableProperty] private HistoryRange range = HistoryRange.Days7;
|
||||
[ObservableProperty] private Provider? providerFilter;
|
||||
[ObservableProperty] private HistoryView history = new([], [], [], [], []);
|
||||
[ObservableProperty] private IReadOnlyList<Diagnostic> diagnostics = [];
|
||||
[ObservableProperty] private string message = "Reading local CLI data…";
|
||||
|
||||
public static DateTimeOffset RangeStart(HistoryRange range, DateTimeOffset now) => range switch
|
||||
{
|
||||
HistoryRange.Hours24 => now.AddHours(-24), HistoryRange.Days7 => now.AddDays(-7),
|
||||
HistoryRange.Days30 => now.AddDays(-30), HistoryRange.Days90 => now.AddDays(-90),
|
||||
_ => DateTimeOffset.MinValue
|
||||
};
|
||||
|
||||
// D5: queries return copies; the caller runs this on a worker thread.
|
||||
public static HistoryView QueryHistory(HistoryStore store, Snapshot snapshot, HistoryRange range, Provider? filter, DateTimeOffset now)
|
||||
{
|
||||
var from = RangeStart(range, now);
|
||||
var providers = snapshot.Providers.Where(p => filter is null || p.Provider == filter).ToArray();
|
||||
var hourly = Series(SeriesInterval.Hour);
|
||||
var daily = Series(SeriesInterval.Day);
|
||||
var limits = providers.SelectMany(p => p.Windows.Select(w =>
|
||||
{
|
||||
var samples = store.LimitSamples(p.Provider, w.Window.Id, from, now);
|
||||
return new LimitChart($"{p.Provider} · {w.Window.Label}", samples.Select((s, i) =>
|
||||
new ChartValue(s.SampleTime, w.Window.Label, s.UsedPercent,
|
||||
Pace.Calculate(s, s.SampleTime).ElapsedFraction * 100,
|
||||
i > 0 && s.ResetsAt != samples[i - 1].ResetsAt)).ToArray());
|
||||
})).ToArray();
|
||||
return new(hourly, daily, limits, Breakdown(true), Breakdown(false));
|
||||
|
||||
IReadOnlyList<ChartValue> Series(SeriesInterval interval) => providers.SelectMany(p =>
|
||||
store.TokenSeries(p.Provider, from, now, interval).SelectMany(point => filter is null
|
||||
? new[] { new ChartValue(point.Time, p.Provider.ToString(), point.Counts.Total) }
|
||||
: ModelsAtPoint(p.Provider, point.Time, interval))).ToArray();
|
||||
IEnumerable<ChartValue> ModelsAtPoint(Provider provider, DateTimeOffset time, SeriesInterval interval)
|
||||
{
|
||||
var end = interval == SeriesInterval.Hour ? time.AddHours(1) : CalendarDays.NextStart(time);
|
||||
return store.ByModel(provider, time < from ? from : time, end > now ? now : end)
|
||||
.Select(m => new ChartValue(time, m.Name ?? "Unknown model", m.Counts.Total));
|
||||
}
|
||||
IReadOnlyList<BreakdownRow> Breakdown(bool models)
|
||||
{
|
||||
var rows = providers.SelectMany(p => models ? store.ByModel(p.Provider, from, now) : store.ByProject(p.Provider, from, now))
|
||||
.GroupBy(r => r.Name ?? "Unknown").Select(g => new TokenBreakdown(g.Key,
|
||||
g.Aggregate(new TokenCounts(), (sum, r) => sum + r.Counts))).OrderByDescending(r => r.Counts.Total).ToArray();
|
||||
var total = rows.Sum(r => (double)r.Counts.Total);
|
||||
return rows.Select(r => new BreakdownRow(r.Name!, r.Counts, total == 0 ? 0 : r.Counts.Total / total)).ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class Display
|
||||
{
|
||||
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)
|
||||
=> ChartTime(time, interval).ToString("g");
|
||||
private static DateTime ChartTime(DateTimeOffset time, TimeSpan interval)
|
||||
=> interval >= TimeSpan.FromDays(1) ? time.DateTime : time.LocalDateTime;
|
||||
public static string Projection(DateTimeOffset projection, TimeProvider? clock = null, System.Globalization.CultureInfo? culture = null)
|
||||
{
|
||||
clock ??= TimeProvider.System;
|
||||
var local = TimeZoneInfo.ConvertTime(projection, clock.LocalTimeZone);
|
||||
return local.ToString(local.Date == clock.GetLocalNow().Date ? "t" : "g",
|
||||
culture ?? System.Globalization.CultureInfo.CurrentCulture);
|
||||
}
|
||||
public static string Duration(TimeSpan span) => span <= TimeSpan.Zero ? "now" : span.TotalDays >= 1
|
||||
? $"{span.TotalDays:0.0} d" : span.TotalHours >= 1 ? $"{span.TotalHours:0.0} h" : $"{Math.Ceiling(span.TotalMinutes):0} min";
|
||||
public static string Tokens(TokenCounts? counts) => counts is { } c
|
||||
? $"{c.Total:N0} total · input {c.Input:N0} · cache read {c.CacheRead:N0} · cache write {c.CacheWrite:N0} · output {c.Output:N0} · reasoning {c.ReasoningOutput:N0}"
|
||||
: "Unavailable — no known session window";
|
||||
public static string State(PaceState state) => state switch { PaceState.OnTrack => "On track", PaceState.Unknown => "Pace unknown", _ => state.ToString() };
|
||||
}
|
||||
Reference in New Issue
Block a user