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,10 @@
|
||||
# App
|
||||
Avalonia 12 Fluent host (D8). Views are built in C# without reflection bindings. View-model
|
||||
properties use CommunityToolkit.Mvvm source generators. Custom charts use DrawingContext.
|
||||
Program owns StoreLock for the engine lifetime. DesktopApp marshals Core events to the UI;
|
||||
Program passes its executable path to RefreshEngine for desktop activation through D9 snapshots.
|
||||
history queries run on worker threads and discard superseded results. Keep all writes atomic (D5).
|
||||
Daily charts use local calendar boundaries; never assume a day lasts 24 hours.
|
||||
Stream Deck policy and the real installer come through IPluginInstaller (D11).
|
||||
UsePlatformDetect selects X11 on Linux in the pinned Avalonia version. Keep XWayland support.
|
||||
Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,114 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Styling;
|
||||
using FinalToken.Core;
|
||||
using System.Globalization;
|
||||
|
||||
namespace FinalToken.App;
|
||||
|
||||
public sealed class UsageChart : Control
|
||||
{
|
||||
private static readonly IBrush[] Palette = [Brush.Parse("#3878D4"), Brush.Parse("#B377D1"), Brush.Parse("#249A88"), Brush.Parse("#C98926")];
|
||||
public static IBrush SeriesColour(int index) => Palette[index % Palette.Length];
|
||||
/// <summary>At most five ticks. Token steps are whole numbers rounded up to 1, 2 or 5 times a power of ten.</summary>
|
||||
public static IReadOnlyList<double> AxisTicks(double maximum, bool percent = false)
|
||||
{
|
||||
if (!double.IsFinite(maximum) || maximum <= 0) return [0];
|
||||
if (percent) return [0, 25, 50, 75, 100];
|
||||
var target = Math.Max(1, maximum / 4);
|
||||
var magnitude = Math.Pow(10, Math.Floor(Math.Log10(target)));
|
||||
var fraction = target / magnitude;
|
||||
var step = (fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10) * magnitude;
|
||||
var intervals = (int)Math.Ceiling(maximum / step);
|
||||
return Enumerable.Range(0, intervals + 1).Select(i => i * step).ToArray();
|
||||
}
|
||||
public IReadOnlyList<ChartValue> Values { get; init; } = [];
|
||||
public bool Percent { get; init; }
|
||||
public TimeSpan Interval { get; init; } = TimeSpan.FromHours(1);
|
||||
private readonly List<(Rect Rect, string Text)> hits = [];
|
||||
public UsageChart()
|
||||
{
|
||||
Height = 180;
|
||||
PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Text);
|
||||
PointerExited += (_, _) => ToolTip.SetTip(this, null);
|
||||
}
|
||||
public override void Render(DrawingContext context)
|
||||
{
|
||||
base.Render(context);
|
||||
hits.Clear();
|
||||
var ink = ActualThemeVariant == ThemeVariant.Dark ? Brushes.WhiteSmoke : Brushes.DarkSlateGray;
|
||||
var plot = new Rect(58, 12, Math.Max(1, Bounds.Width - 74), Math.Max(1, Bounds.Height - 46));
|
||||
var groups = Values.GroupBy(v => v.Time).OrderBy(g => g.Key).ToArray();
|
||||
var ticks = AxisTicks(groups.Length == 0 ? 0 : Percent ? 100 : groups.Max(g => g.Sum(v => v.Value)), Percent);
|
||||
var max = Math.Max(1, ticks[^1]);
|
||||
foreach (var tick in ticks)
|
||||
{
|
||||
var y = plot.Bottom - plot.Height * tick / max;
|
||||
context.DrawLine(new Pen(ActualThemeVariant == ThemeVariant.Dark ? Brush.Parse("#354052") : Brush.Parse("#DFE5EE")), new(plot.Left, y), new(plot.Right, y));
|
||||
var label = Percent ? $"{tick:0}%" : tick >= 1e9 ? $"{tick / 1e9:0.#}B" : tick >= 1e6 ? $"{tick / 1e6:0.#}M" : tick >= 1000 ? $"{tick / 1000:0.#}K" : $"{tick:0}";
|
||||
Text(context, label, new(0, y - 8), ink);
|
||||
}
|
||||
if (groups.Length == 0) { Text(context, "No samples in this range", new(plot.Left + 12, plot.Top + 32), ink); return; }
|
||||
var series = Values.Select(v => v.Series).Distinct().ToArray();
|
||||
if (Percent)
|
||||
{
|
||||
ChartValue? previous = null;
|
||||
var minTime = groups[0].Key;
|
||||
var timeSpan = Math.Max(1, (groups[^1].Key - minTime).TotalSeconds);
|
||||
Point Position(ChartValue v, double value) => new(plot.Left + (v.Time - minTime).TotalSeconds / timeSpan * plot.Width, plot.Bottom - Math.Clamp(value, 0, 100) / 100 * plot.Height);
|
||||
foreach (var value in Values.OrderBy(v => v.Time))
|
||||
{
|
||||
var point = Position(value, value.Value);
|
||||
if (previous is { } p && !value.BreakBefore)
|
||||
{
|
||||
context.DrawLine(new Pen(Palette[0], 2), Position(p, p.Value), point);
|
||||
if (p.Expected is { } pe && value.Expected is { } expected)
|
||||
context.DrawLine(new Pen(Palette[2], 1, new DashStyle([4, 3], 0)), Position(p, pe), Position(value, expected));
|
||||
}
|
||||
context.DrawEllipse(Palette[0], null, point, 3, 3);
|
||||
hits.Add((new(point.X - 8, point.Y - 10, 16, 20), $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Value:0.##}% · expected {(value.Expected is { } e ? $"{e:0.##}%" : "unknown")}"));
|
||||
previous = value;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var duration = Math.Max(Interval.TotalSeconds, (groups[^1].Key - groups[0].Key).TotalSeconds + Interval.TotalSeconds);
|
||||
var width = plot.Width * Interval.TotalSeconds / duration;
|
||||
for (var i = 0; i < groups.Length; i++)
|
||||
{
|
||||
var bottom = plot.Bottom;
|
||||
foreach (var value in groups[i])
|
||||
{
|
||||
var height = value.Value / max * plot.Height;
|
||||
var x = plot.Left + (groups[i].Key - groups[0].Key).TotalSeconds / duration * plot.Width;
|
||||
var rect = new Rect(x + Math.Min(1, width / 8), bottom - height, Math.Max(0.5, width - Math.Min(2, width / 4)), height);
|
||||
context.DrawRectangle(Palette[Array.IndexOf(series, value.Series) % Palette.Length], null, rect);
|
||||
hits.Add((rect, $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Series}: {value.Value:N0} tokens"));
|
||||
bottom -= height;
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(context, Display.ChartDateLabel(groups[0].Key, Interval), new(plot.Left, plot.Bottom + 8), ink);
|
||||
Text(context, Display.ChartDateLabel(groups[^1].Key, Interval), new(Math.Max(plot.Left, plot.Right - 110), plot.Bottom + 8), ink);
|
||||
ToolTip.SetShowDelay(this, 0);
|
||||
}
|
||||
private static void Text(DrawingContext context, string text, Point point, IBrush brush) => context.DrawText(
|
||||
new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, Typeface.Default, 11, brush), point);
|
||||
}
|
||||
|
||||
public sealed class PaceBar(WindowSnapshot window) : Control
|
||||
{
|
||||
public static IBrush Colour(PaceState state) => Brush.Parse(state switch
|
||||
{ PaceState.Ahead => "#D98236", PaceState.Behind => "#3A8CCB", PaceState.OnTrack => "#279884", _ => "#8C95A3" });
|
||||
public override void Render(DrawingContext context)
|
||||
{
|
||||
base.Render(context);
|
||||
context.DrawRectangle(Brush.Parse("#338795A5"), null, new Rect(Bounds.Size), 4, 4);
|
||||
context.DrawRectangle(Colour(window.Pace.State), null, new Rect(0, 0, Bounds.Width * Math.Clamp(window.Window.UsedPercent / 100, 0, 1), Bounds.Height), 4, 4);
|
||||
if (window.Pace.ElapsedFraction is { } elapsed)
|
||||
context.DrawLine(new Pen(ActualThemeVariant == ThemeVariant.Dark ? Brushes.White : Brushes.Black, 2), new(Bounds.Width * elapsed, 0), new(Bounds.Width * elapsed, Bounds.Height));
|
||||
ToolTip.SetTip(this, $"Used {window.Window.UsedPercent:0.##}% · expected {window.Pace.ElapsedFraction * 100:0.##}%");
|
||||
}
|
||||
}
|
||||
@@ -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.";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<AssemblyName>FinalToken</AssemblyName>
|
||||
<PublishAot>true</PublishAot>
|
||||
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia.Desktop" />
|
||||
<PackageReference Include="Avalonia.Themes.Fluent" />
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.Runtime.Versioning;
|
||||
using FinalToken.Core;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace FinalToken.App;
|
||||
|
||||
public static class OsStartup
|
||||
{
|
||||
public static string LinuxAutostartPath(string? configHome, string userHome)
|
||||
=> Path.Combine(string.IsNullOrEmpty(configHome) ? Path.Combine(userHome, ".config") : configHome, "autostart", "finaltoken.desktop");
|
||||
public static async Task ApplyAsync(bool enabled, string? executable = null)
|
||||
{
|
||||
executable ??= Environment.ProcessPath ?? throw new InvalidOperationException("Executable path is unavailable.");
|
||||
if (OperatingSystem.IsWindows()) { ApplyWindows(enabled, executable); return; }
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
var path = LinuxAutostartPath(Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"),
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
|
||||
if (!enabled) { if (File.Exists(path)) File.Delete(path); return; }
|
||||
await AtomicFile.WriteAsync(path, DesktopEntry(executable));
|
||||
}
|
||||
public static string DesktopEntry(string executable)
|
||||
{
|
||||
if (executable.IndexOfAny(['\r', '\n', '\0']) >= 0) throw new ArgumentException("Executable path contains invalid characters.", nameof(executable));
|
||||
var quoted = executable.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal)
|
||||
.Replace("`", "\\`", StringComparison.Ordinal).Replace("$", "\\$", StringComparison.Ordinal).Replace("%", "%%", StringComparison.Ordinal);
|
||||
var escaped = quoted.Replace("\\", "\\\\", StringComparison.Ordinal);
|
||||
return $"[Desktop Entry]\nType=Application\nName=FinalToken\nExec=\"{escaped}\"\nTerminal=false\nX-GNOME-Autostart-enabled=true\n";
|
||||
}
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static void ApplyWindows(bool enabled, string executable)
|
||||
{
|
||||
using var key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
|
||||
if (enabled) key.SetValue("FinalToken", "\"" + executable + "\""); else key.DeleteValue("FinalToken", false);
|
||||
}
|
||||
}
|
||||
@@ -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() };
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using FinalToken.Core;
|
||||
|
||||
namespace FinalToken.App;
|
||||
|
||||
public static class Ui
|
||||
{
|
||||
public static TextBlock Text(string text, double size = 13) => new() { Text = text, FontSize = size, TextWrapping = TextWrapping.Wrap };
|
||||
public static StackPanel Stack(params Control[] children)
|
||||
{
|
||||
var stack = new StackPanel { Spacing = 10 };
|
||||
foreach (var child in children) stack.Children.Add(child);
|
||||
return stack;
|
||||
}
|
||||
public static Border Card(Control content) => new() { Child = content, Padding = new Thickness(18), CornerRadius = new CornerRadius(9), BorderThickness = new Thickness(1), BorderBrush = Brush.Parse("#558795A5") };
|
||||
public static Button Button(string text, Action action)
|
||||
{
|
||||
var button = new Button { Content = text };
|
||||
button.Click += (_, _) => action();
|
||||
return button;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class PanelWindow : Window
|
||||
{
|
||||
private readonly PanelViewModel model;
|
||||
private readonly StackPanel body = new() { Spacing = 16, Margin = new Thickness(24) };
|
||||
public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload)
|
||||
{
|
||||
this.model = model;
|
||||
Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}"; Width = 1160; Height = 920; MinWidth = 720; MinHeight = 500;
|
||||
var header = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 };
|
||||
header.Children.Add(Ui.Text("FinalToken", 28));
|
||||
header.Children.Add(Ui.Button("Refresh now", refresh));
|
||||
header.Children.Add(Ui.Button("Settings", settings));
|
||||
header.Children.Add(Ui.Button("Quit", quit));
|
||||
var range = new ComboBox { ItemsSource = new[] { "24 hours", "7 days", "30 days", "90 days", "All history" }, SelectedIndex = (int)model.Range, MinWidth = 150 };
|
||||
range.SelectionChanged += (_, _) => { model.Range = (HistoryRange)range.SelectedIndex; reload(); };
|
||||
var providers = new ComboBox { ItemsSource = new[] { "All providers", "Claude", "Codex" }, SelectedIndex = 0, MinWidth = 150 };
|
||||
providers.SelectionChanged += (_, _) => { model.ProviderFilter = providers.SelectedIndex == 0 ? null : (Provider)(providers.SelectedIndex - 1); reload(); };
|
||||
var filters = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 };
|
||||
filters.Children.Add(range); filters.Children.Add(providers);
|
||||
var dock = new DockPanel { Margin = new Thickness(0, 18, 0, 0) };
|
||||
var top = Ui.Stack(header, filters); top.Margin = new Thickness(24, 0, 24, 0);
|
||||
DockPanel.SetDock(top, Dock.Top); dock.Children.Add(top);
|
||||
dock.Children.Add(new ScrollViewer { Content = body }); Content = dock;
|
||||
model.PropertyChanged += (_, _) => RenderModel();
|
||||
RenderModel();
|
||||
}
|
||||
public void RenderModel()
|
||||
{
|
||||
body.Children.Clear();
|
||||
body.Children.Add(Ui.Text(model.Message));
|
||||
if (model.Snapshot is { } snapshot)
|
||||
{
|
||||
foreach (var provider in snapshot.Providers.Where(p => model.ProviderFilter is null || p.Provider == model.ProviderFilter))
|
||||
{
|
||||
var card = Ui.Stack(Ui.Text(provider.Provider.ToString(), 22), Ui.Text($"{provider.Status} {provider.Reason}"));
|
||||
foreach (var window in provider.Windows)
|
||||
{
|
||||
var w = window.Window; var pace = window.Pace;
|
||||
var title = Ui.Text($"{w.Label} {w.UsedPercent:0.##}% {Display.State(pace.State)} {(pace.Delta is { } d ? $"{d:+0.0;-0.0;0} points" : "")}", 15);
|
||||
title.Foreground = PaceBar.Colour(pace.State);
|
||||
card.Children.Add(title);
|
||||
card.Children.Add(new PaceBar(window) { Height = 14 });
|
||||
card.Children.Add(Ui.Text($"Reset: {(w.ResetsAt is { } reset ? Display.Duration(reset - DateTimeOffset.UtcNow) + " · " + reset.LocalDateTime.ToString("g") : "unknown")} Sample age: {Display.Duration(DateTimeOffset.UtcNow - w.SampleTime)}" +
|
||||
(pace.Projection is { } projection ? $" Reaches 100%: {Display.Projection(projection)}" : "")));
|
||||
}
|
||||
card.Children.Add(Ui.Text("Tokens · provider totals", 15));
|
||||
card.Children.Add(Ui.Text("Today " + Display.Tokens(provider.Today)));
|
||||
card.Children.Add(Ui.Text("Session " + Display.Tokens(provider.Session)));
|
||||
card.Children.Add(Ui.Text("Week " + Display.Tokens(provider.Week)));
|
||||
card.Children.Add(Ui.Text("Cache read is included in Codex input; reasoning is included in output.", 11));
|
||||
body.Children.Add(Ui.Card(card));
|
||||
}
|
||||
}
|
||||
var h = model.History;
|
||||
body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), Legend(h.Hourly), new UsageChart { Values = h.Hourly })));
|
||||
body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per day", 19), Legend(h.Daily), new UsageChart { Values = h.Daily, Interval = TimeSpan.FromDays(1) })));
|
||||
foreach (var limit in h.Limits)
|
||||
body.Children.Add(Ui.Card(Ui.Stack(Ui.Text(limit.Label, 19), Ui.Text("Blue: used · dashed green: expected pace · gaps: window reset", 11), new UsageChart { Values = limit.Values, Percent = true })));
|
||||
body.Children.Add(Breakdown("By model", h.Models));
|
||||
body.Children.Add(Breakdown("By project", h.Projects));
|
||||
var diagnostics = Ui.Stack(Ui.Text("Recent diagnostics", 19));
|
||||
foreach (var d in model.Diagnostics) diagnostics.Children.Add(Ui.Text($"{d.Time.LocalDateTime:g} · {d.Provider} · {d.Code} · {d.Summary}"));
|
||||
if (model.Diagnostics.Count == 0) diagnostics.Children.Add(Ui.Text("No recent problems."));
|
||||
body.Children.Add(Ui.Card(diagnostics));
|
||||
}
|
||||
private static Control Legend(IReadOnlyList<ChartValue> values)
|
||||
{
|
||||
var legend = new WrapPanel { Orientation = Orientation.Horizontal };
|
||||
var index = 0;
|
||||
foreach (var series in values.Select(v => v.Series).Distinct())
|
||||
{
|
||||
var label = Ui.Text("● " + series, 12); label.Foreground = UsageChart.SeriesColour(index++);
|
||||
label.Margin = new Thickness(0, 0, 14, 0); legend.Children.Add(label);
|
||||
}
|
||||
return legend;
|
||||
}
|
||||
private static Border Breakdown(string title, IReadOnlyList<BreakdownRow> rows)
|
||||
{
|
||||
var table = Ui.Stack(Ui.Text(title, 19));
|
||||
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("3*,1*,1*,1*,1*,1*,1*,1*"), MinWidth = 900 };
|
||||
var headers = new[] { "Name", "Total", "Share", "Input", "Cache read", "Cache write", "Output", "Reasoning" };
|
||||
AddRow(headers, 0);
|
||||
var index = 1;
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var c = row.Counts;
|
||||
AddRow([row.Name, c.Total.ToString("N0"), row.Share.ToString("P1"), c.Input.ToString("N0"), c.CacheRead.ToString("N0"),
|
||||
c.CacheWrite.ToString("N0"), c.Output.ToString("N0"), c.ReasoningOutput.ToString("N0")], index++);
|
||||
}
|
||||
table.Children.Add(new ScrollViewer { Content = grid, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
|
||||
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled });
|
||||
if (rows.Count == 0) table.Children.Add(Ui.Text("No tokens in this range."));
|
||||
return Ui.Card(table);
|
||||
void AddRow(string[] values, int row)
|
||||
{
|
||||
grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
|
||||
for (var column = 0; column < values.Length; column++)
|
||||
{
|
||||
var text = Ui.Text(values[column], 11); text.Margin = new Thickness(0, 4, 8, 4);
|
||||
Grid.SetRow(text, row); Grid.SetColumn(text, column); grid.Children.Add(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.Styling;
|
||||
using Avalonia.VisualTree;
|
||||
using FinalToken.Core;
|
||||
|
||||
namespace FinalToken.App;
|
||||
|
||||
public sealed class PopupWindow : Window
|
||||
{
|
||||
public PopupWindow(string title, string message, Action open, string? installLabel = null, Action? install = null, Action? dismiss = null, IBrush? accent = null)
|
||||
{
|
||||
Width = 380; Height = install is null ? 145 : 180;
|
||||
RequestedThemeVariant = ThemeVariant.Dark;
|
||||
WindowDecorations = WindowDecorations.None; CanResize = false; Topmost = true; ShowInTaskbar = false; ShowActivated = false;
|
||||
var body = Ui.Stack(Ui.Text(title, 19), Ui.Text(message));
|
||||
if (install is not null)
|
||||
{
|
||||
var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 };
|
||||
actions.Children.Add(Ui.Button(installLabel ?? "Install", () => { install(); Close(); }));
|
||||
actions.Children.Add(Ui.Button("Not now", () => { dismiss?.Invoke(); Close(); }));
|
||||
body.Children.Add(actions);
|
||||
}
|
||||
var card = Ui.Card(body); card.Background = Brush.Parse("#202C40");
|
||||
body.Resources["TextControlForeground"] = Brushes.WhiteSmoke;
|
||||
foreach (var text in body.Children.OfType<TextBlock>()) text.Foreground = Brushes.WhiteSmoke;
|
||||
((TextBlock)body.Children[0]).Foreground = accent ?? Brushes.WhiteSmoke;
|
||||
Content = card;
|
||||
PointerPressed += (_, e) =>
|
||||
{
|
||||
var source = e.Source as Control;
|
||||
if (source is not Button && source?.FindAncestorOfType<Button>() is null)
|
||||
{ open(); Close(); e.Handled = true; }
|
||||
};
|
||||
}
|
||||
public static PopupWindow Pace(PopupEvent alert, Action open) => new($"{alert.Provider} · {Display.State(alert.State)}",
|
||||
$"{alert.Label}: {alert.Delta:+0.0;-0.0;0} points from pace." +
|
||||
(alert.Projection is { } projection ? $" At this rate: 100% at {Display.Projection(projection)}." : ""), open, accent: PaceBar.Colour(alert.State));
|
||||
}
|
||||
|
||||
public sealed class PopupStack(Action open, TimeProvider? clock = null) : IDisposable
|
||||
{
|
||||
private readonly List<PopupWindow> windows = [];
|
||||
public void Pace(PopupEvent alert) => Show(PopupWindow.Pace(alert, open));
|
||||
public void Show(PopupWindow window)
|
||||
{
|
||||
windows.Add(window);
|
||||
window.Closed += (_, _) => { windows.Remove(window); Position(); };
|
||||
window.Show(); Position();
|
||||
// D8: timer callbacks are off the UI thread; closing always marshals back.
|
||||
var timer = (clock ?? TimeProvider.System).CreateTimer(_ => Dispatcher.UIThread.Post(window.Close),
|
||||
null, TimeSpan.FromSeconds(8), Timeout.InfiniteTimeSpan);
|
||||
window.Closed += (_, _) => timer.Dispose();
|
||||
}
|
||||
private void Position()
|
||||
{
|
||||
var bottom = 0;
|
||||
foreach (var window in windows)
|
||||
{
|
||||
var screen = window.Screens.Primary;
|
||||
if (screen is null) continue;
|
||||
var area = screen.WorkingArea; var scale = screen.Scaling;
|
||||
bottom += (int)(window.Height * scale) + 12;
|
||||
window.Position = new PixelPoint(area.Right - (int)(window.Width * scale) - 16, area.Bottom - bottom - 4);
|
||||
}
|
||||
}
|
||||
public void Dispose() { foreach (var window in windows.ToArray()) window.Close(); }
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Avalonia;
|
||||
using FinalToken.Core;
|
||||
|
||||
namespace FinalToken.App;
|
||||
|
||||
public static class Program
|
||||
{
|
||||
internal static RefreshEngine? Engine { get; private set; }
|
||||
internal static string? StartupError { get; private set; }
|
||||
[STAThread]
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
StoreLock? storeLock = null;
|
||||
try
|
||||
{
|
||||
var directory = DataPaths.DataDirectory;
|
||||
storeLock = StoreLock.TryAcquire(directory);
|
||||
if (storeLock is null)
|
||||
{
|
||||
if (OperatingSystem.IsWindows()) WindowsActivation.AllowRunningInstance();
|
||||
ActivationFile.RequestAsync(directory).GetAwaiter().GetResult(); return 0;
|
||||
}
|
||||
try { Engine = new RefreshEngine(directory, appPath: Environment.ProcessPath); }
|
||||
catch (InvalidDataException e) { StartupError = e.Message; }
|
||||
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||
return StartupError is null ? 0 : 1;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Engine?.DisposeAsync().AsTask().GetAwaiter().GetResult();
|
||||
storeLock?.Dispose();
|
||||
}
|
||||
}
|
||||
// D8: Avalonia 12.1.4's platform detection selects X11 on Linux (XWayland).
|
||||
public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure<DesktopApp>().UsePlatformDetect()
|
||||
.With(new X11PlatformOptions()).LogToTrace();
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using FinalToken.Core;
|
||||
using FinalToken.Core.StreamDeck;
|
||||
|
||||
namespace FinalToken.App;
|
||||
|
||||
public sealed class SettingsWindow : Window
|
||||
{
|
||||
public SettingsWindow(Settings initial, PluginInstallStatus status, Func<Settings, Task> save)
|
||||
{
|
||||
Title = "FinalToken settings"; Width = 620; Height = 800;
|
||||
var body = Ui.Stack(Ui.Text("Settings", 26)); body.Margin = new Thickness(24);
|
||||
var refresh = Number("Token refresh (seconds, 1–60)", (decimal)initial.RefreshInterval.TotalSeconds, 1, 60);
|
||||
var probe = Number("Limit probe (minutes, 1–60)", (decimal)initial.ProbeInterval.TotalMinutes, 1, 60);
|
||||
var threshold = Number("Pace threshold (points)", (decimal)initial.PaceThreshold, 0.1m, 100);
|
||||
var ahead = Check("Ahead popups", initial.PopupAhead); var behind = Check("Behind popups", initial.PopupBehind);
|
||||
var startup = Check("Start with the OS", initial.StartWithOs); var tray = Check("Close to tray", initial.CloseToTray);
|
||||
var claude = ProviderControls("Claude", initial.Claude); var codex = ProviderControls("Codex", initial.Codex);
|
||||
body.Children.Add(Ui.Text("Stream Deck", 19));
|
||||
body.Children.Add(Ui.Text($"{status.State} · shipped {status.ShippedVersion ?? "none"} · installed {status.InstalledVersion ?? "none"}"));
|
||||
var mode = new ComboBox { ItemsSource = new[] { "Off", "Ask", "Automatic" }, SelectedIndex = (int)initial.StreamDeckInstallMode };
|
||||
body.Children.Add(mode);
|
||||
body.Children.Add(Ui.Text("Dismissed plugin version (clear to ask again)"));
|
||||
var dismissed = new TextBox { Text = initial.DismissedPluginVersion ?? "" }; body.Children.Add(dismissed);
|
||||
var error = Ui.Text(""); body.Children.Add(error);
|
||||
var button = new Button { Content = "Save", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right };
|
||||
button.Click += async (_, _) =>
|
||||
{
|
||||
var value = initial with { RefreshInterval = TimeSpan.FromSeconds((double)(refresh.Value ?? 0)), ProbeInterval = TimeSpan.FromMinutes((double)(probe.Value ?? 0)),
|
||||
PaceThreshold = (double)(threshold.Value ?? 0), PopupAhead = ahead.IsChecked == true, PopupBehind = behind.IsChecked == true,
|
||||
StartWithOs = startup.IsChecked == true, CloseToTray = tray.IsChecked == true, Claude = claude(), Codex = codex(),
|
||||
StreamDeckInstallMode = (InstallMode)mode.SelectedIndex, DismissedPluginVersion = string.IsNullOrWhiteSpace(dismissed.Text) ? null : dismissed.Text.Trim() };
|
||||
if (!value.IsValid) { error.Text = "Check the intervals and pace threshold."; return; }
|
||||
button.IsEnabled = false;
|
||||
try { await save(value); Close(); }
|
||||
catch (OperationCanceledException) { error.Text = "Settings save was cancelled."; button.IsEnabled = true; }
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
|
||||
{ error.Text = "Could not apply settings: " + e.Message; button.IsEnabled = true; }
|
||||
};
|
||||
body.Children.Add(button); Content = new ScrollViewer { Content = body };
|
||||
|
||||
NumericUpDown Number(string label, decimal value, decimal min, decimal max)
|
||||
{ body.Children.Add(Ui.Text(label)); var c = new NumericUpDown { Value = value, Minimum = min, Maximum = max }; body.Children.Add(c); return c; }
|
||||
CheckBox Check(string label, bool value)
|
||||
{ var c = new CheckBox { Content = label, IsChecked = value }; body.Children.Add(c); return c; }
|
||||
Func<ProviderSettings> ProviderControls(string name, ProviderSettings config)
|
||||
{
|
||||
body.Children.Add(Ui.Text(name, 19));
|
||||
var enabled = Check("Enabled", config.Enabled); var popups = Check("Popups enabled", config.PopupsEnabled);
|
||||
var pa = Check("Ahead", config.PopupAhead); var pb = Check("Behind", config.PopupBehind);
|
||||
body.Children.Add(Ui.Text("CLI path (empty uses PATH)"));
|
||||
var path = new TextBox { Name = name + "CliPath", Text = config.CliPath ?? "" }; body.Children.Add(path);
|
||||
return () => config with { Enabled = enabled.IsChecked == true, PopupsEnabled = popups.IsChecked == true, PopupAhead = pa.IsChecked == true,
|
||||
PopupBehind = pb.IsChecked == true, CliPath = string.IsNullOrWhiteSpace(path.Text) ? null : path.Text.Trim() };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Versioning;
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace FinalToken.App;
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
internal static partial class WindowsActivation
|
||||
{
|
||||
public static void Activate(Window window)
|
||||
{
|
||||
if (window.TryGetPlatformHandle() is not { } platform) return;
|
||||
var handle = platform.Handle;
|
||||
if (SetForegroundWindow(handle) != 0) return;
|
||||
var foreground = GetForegroundWindow();
|
||||
if (foreground == 0) return;
|
||||
var foregroundThread = GetWindowThreadProcessId(foreground, out _);
|
||||
var ownThread = GetCurrentThreadId();
|
||||
if (foregroundThread == ownThread || AttachThreadInput(ownThread, foregroundThread, 1) == 0) return;
|
||||
try { SetForegroundWindow(handle); }
|
||||
finally { AttachThreadInput(ownThread, foregroundThread, 0); }
|
||||
}
|
||||
// D8: a launcher transfers its foreground permission before the running app activates.
|
||||
public static void AllowRunningInstance()
|
||||
{
|
||||
using var current = Process.GetCurrentProcess();
|
||||
foreach (var candidate in Process.GetProcessesByName(current.ProcessName))
|
||||
{
|
||||
using (candidate)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (candidate.Id != current.Id && candidate.SessionId == current.SessionId &&
|
||||
string.Equals(candidate.MainModule?.FileName, Environment.ProcessPath, StringComparison.OrdinalIgnoreCase))
|
||||
AllowSetForegroundWindow(candidate.Id);
|
||||
}
|
||||
catch (Exception e) when (e is Win32Exception or InvalidOperationException) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial int AllowSetForegroundWindow(int processId);
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial int SetForegroundWindow(nint window);
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial nint GetForegroundWindow();
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial uint GetWindowThreadProcessId(nint window, out uint processId);
|
||||
[LibraryImport("kernel32.dll")]
|
||||
private static partial uint GetCurrentThreadId();
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial int AttachThreadInput(uint first, uint second, int attach);
|
||||
}
|
||||
Reference in New Issue
Block a user