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,187 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Media.Imaging;
|
||||
using Avalonia.Themes.Fluent;
|
||||
using Avalonia.Threading;
|
||||
using FinalToken.Core;
|
||||
using FinalToken.Core.StreamDeck;
|
||||
|
||||
namespace FinalToken.App;
|
||||
|
||||
public sealed class DesktopApp : Application
|
||||
{
|
||||
private readonly PanelViewModel model = new();
|
||||
private IClassicDesktopStyleApplicationLifetime? desktop;
|
||||
private PanelWindow? panel;
|
||||
private PopupStack? popups;
|
||||
private TrayIcon? tray;
|
||||
private DispatcherTimer? ageTimer;
|
||||
private SettingsWindow? settingsWindow;
|
||||
private Task settingsSave = Task.CompletedTask;
|
||||
private PopupWindow? pluginAsk;
|
||||
private RefreshEngine? engine;
|
||||
private readonly SemaphoreSlim pluginGate = new(1, 1);
|
||||
private int historyRequest;
|
||||
private bool quitting;
|
||||
private PluginInstallStatus pluginStatus = new(PluginInstallState.NoHostFound);
|
||||
public IPluginInstaller PluginInstaller { get; set; } = FinalToken.Core.StreamDeck.PluginInstaller.CreateDefault();
|
||||
public override void Initialize() => Styles.Add(new FluentTheme());
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime)
|
||||
{
|
||||
desktop = lifetime; desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown;
|
||||
engine = Program.Engine;
|
||||
if (Program.StartupError is { } error)
|
||||
{
|
||||
var window = new Window { Title = "FinalToken — history error", Width = 560, Height = 240,
|
||||
Content = Ui.Card(Ui.Stack(Ui.Text("History cannot be loaded", 22), Ui.Text(error), Ui.Button("Quit", () => desktop.Shutdown(1)))) };
|
||||
desktop.MainWindow = window; window.Show();
|
||||
window.Closed += (_, _) => desktop.Shutdown(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
panel = new PanelWindow(model, () => Run(Refresh), OpenSettings, () => Run(Quit), () => Run(LoadHistory));
|
||||
desktop.MainWindow = panel; popups = new(OpenPanel);
|
||||
panel.Closing += (_, e) => { if (!quitting && engine?.Settings.CloseToTray != false) { e.Cancel = true; panel.Hide(); } else if (!quitting) { e.Cancel = true; Run(Quit); } };
|
||||
CreateTray(); panel.Show();
|
||||
if (engine is not null)
|
||||
{
|
||||
engine.SnapshotChanged += snapshot => Dispatcher.UIThread.Post(() => { model.Snapshot = snapshot; model.Diagnostics = engine.RecentDiagnostics; model.Message = "Updated " + snapshot.MadeAt.LocalDateTime.ToString("g"); Run(LoadHistory); });
|
||||
engine.PopupRequested += alert => Dispatcher.UIThread.Post(() => { if (!quitting) popups.Pace(alert); });
|
||||
engine.ActivationRequested += () => Dispatcher.UIThread.Post(OpenPanel);
|
||||
model.Snapshot = engine.CurrentSnapshot;
|
||||
ageTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
|
||||
ageTimer.Tick += (_, _) => { if (panel.IsVisible) model.Diagnostics = engine.RecentDiagnostics; };
|
||||
ageTimer.Start();
|
||||
Run(Start);
|
||||
}
|
||||
}
|
||||
desktop.ShutdownRequested += (_, e) => { if (!quitting && engine is not null) { e.Cancel = true; Run(Quit); } };
|
||||
}
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
private async Task Start()
|
||||
{
|
||||
await engine!.StartAsync();
|
||||
if (engine.Settings.StartWithOs) await OsStartup.ApplyAsync(true);
|
||||
await CheckPlugin();
|
||||
}
|
||||
private void CreateTray()
|
||||
{
|
||||
var menu = new NativeMenu();
|
||||
foreach (var (label, action) in new (string, Action)[] { ("Open", OpenPanel), ("Refresh now", () => Run(Refresh)), ("Settings", OpenSettings), ("Quit", () => Run(Quit)) })
|
||||
{ var item = new NativeMenuItem(label); item.Click += (_, _) => action(); menu.Items.Add(item); }
|
||||
using var bitmap = new RenderTargetBitmap(new PixelSize(32, 32));
|
||||
using (var context = bitmap.CreateDrawingContext())
|
||||
{ context.DrawRectangle(Brush.Parse("#3878D4"), null, new Rect(0, 0, 32, 32), 7, 7); context.DrawLine(new Pen(Brushes.White, 4), new(9, 9), new(23, 9)); context.DrawLine(new Pen(Brushes.White, 4), new(16, 9), new(16, 25)); }
|
||||
using var stream = new MemoryStream(); bitmap.Save(stream, PngBitmapEncoderOptions.Default); stream.Position = 0;
|
||||
tray = new TrayIcon { Icon = new WindowIcon(stream), ToolTipText = "FinalToken", Menu = menu, IsVisible = true };
|
||||
tray.Clicked += (_, _) => OpenPanel();
|
||||
TrayIcon.SetIcons(this, [tray]);
|
||||
}
|
||||
private void OpenPanel()
|
||||
{
|
||||
if (panel is null || quitting) return;
|
||||
panel.Show(); panel.WindowState = WindowState.Normal; panel.Activate();
|
||||
if (OperatingSystem.IsWindows()) WindowsActivation.Activate(panel);
|
||||
}
|
||||
private Task Refresh() => engine is null ? Task.CompletedTask : engine.RefreshNowAsync();
|
||||
private async Task LoadHistory()
|
||||
{
|
||||
if (engine is null || model.Snapshot is not { } snapshot || quitting) return;
|
||||
var request = ++historyRequest; var range = model.Range; var filter = model.ProviderFilter;
|
||||
var history = await Task.Run(() => PanelViewModel.QueryHistory(engine.History, snapshot, range, filter, DateTimeOffset.UtcNow));
|
||||
if (request == historyRequest && !quitting) model.History = history;
|
||||
}
|
||||
private void OpenSettings()
|
||||
{
|
||||
if (engine is null) return;
|
||||
if (settingsWindow is not null) { settingsWindow.Activate(); return; }
|
||||
settingsWindow = new SettingsWindow(engine.Settings, pluginStatus, value => settingsSave = SaveSettings(value));
|
||||
settingsWindow.Closed += (_, _) => settingsWindow = null;
|
||||
settingsWindow.Show();
|
||||
}
|
||||
private async Task SaveSettings(Settings value)
|
||||
{
|
||||
if (engine is null || quitting) return;
|
||||
var previous = engine.Settings;
|
||||
await OsStartup.ApplyAsync(value.StartWithOs);
|
||||
if (quitting) { await OsStartup.ApplyAsync(previous.StartWithOs); return; }
|
||||
try { await engine.UpdateSettingsAsync(value); }
|
||||
catch { await OsStartup.ApplyAsync(previous.StartWithOs); throw; }
|
||||
if (quitting) return;
|
||||
await CheckPlugin();
|
||||
if (!quitting) await engine.RefreshNowAsync();
|
||||
}
|
||||
private async Task CheckPlugin()
|
||||
{
|
||||
if (engine is null || quitting) return;
|
||||
await pluginGate.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (quitting) return;
|
||||
pluginAsk?.Close(); pluginAsk = null;
|
||||
pluginStatus = await PluginInstaller.GetStatusAsync();
|
||||
var action = InstallPolicy.Decide(engine.Settings.StreamDeckInstallMode, pluginStatus, engine.Settings.DismissedPluginVersion);
|
||||
if (action == InstallAction.Install) await InstallPlugin();
|
||||
else if (action == InstallAction.Ask)
|
||||
{
|
||||
var version = pluginStatus.ShippedVersion;
|
||||
pluginAsk = new PopupWindow("Stream Deck plugin", $"Version {version} is ready.", OpenPanel,
|
||||
pluginStatus.State == PluginInstallState.Outdated ? "Update" : "Install", () => Run(() => AcceptPlugin(version)),
|
||||
() => Run(() => DismissPlugin(version)));
|
||||
popups!.Show(pluginAsk);
|
||||
}
|
||||
}
|
||||
finally { pluginGate.Release(); }
|
||||
}
|
||||
private async Task DismissPlugin(string? version)
|
||||
{
|
||||
await pluginGate.WaitAsync();
|
||||
try { if (!quitting && engine is not null) await engine.UpdateSettingsAsync(engine.Settings with { DismissedPluginVersion = version }); }
|
||||
finally { pluginGate.Release(); }
|
||||
}
|
||||
private async Task AcceptPlugin(string? version)
|
||||
{
|
||||
await pluginGate.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (quitting || engine?.Settings.StreamDeckInstallMode == InstallMode.Off) return;
|
||||
var current = await PluginInstaller.GetStatusAsync();
|
||||
if (current.ShippedVersion == version && current.State is PluginInstallState.NotInstalled or PluginInstallState.Outdated)
|
||||
await InstallPlugin();
|
||||
}
|
||||
finally { pluginGate.Release(); }
|
||||
}
|
||||
private async Task InstallPlugin()
|
||||
{
|
||||
try { await PluginInstaller.InstallOrUpdateAsync(); pluginStatus = await PluginInstaller.GetStatusAsync(); if (!quitting) popups!.Show(new PopupWindow("Stream Deck", pluginStatus.State == PluginInstallState.UpToDate ? "Plugin installed successfully." : $"Plugin status: {pluginStatus.State}", OpenPanel)); }
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException)
|
||||
{ if (!quitting) popups!.Show(new PopupWindow("Stream Deck", "Install failed: " + e.Message, OpenPanel)); }
|
||||
}
|
||||
private async Task Quit()
|
||||
{
|
||||
if (quitting) return; quitting = true;
|
||||
ageTimer?.Stop(); tray?.Dispose(); popups?.Dispose(); settingsWindow?.Close();
|
||||
var stopping = engine?.StopAsync() ?? Task.CompletedTask;
|
||||
await pluginGate.WaitAsync(); pluginGate.Release();
|
||||
try { await settingsSave; }
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or OperationCanceledException)
|
||||
{ engine?.Diagnostics.Add(null, "settings-shutdown", "Settings could not finish applying before shutdown."); }
|
||||
await stopping;
|
||||
desktop?.Shutdown();
|
||||
}
|
||||
private async void Run(Func<Task> work)
|
||||
{
|
||||
try { await work(); }
|
||||
catch (OperationCanceledException) { }
|
||||
catch (Exception)
|
||||
{
|
||||
engine?.Diagnostics.Add(null, "host-operation", "A desktop operation failed.");
|
||||
model.Message = "Operation failed. See diagnostics.";
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user