app: redesign the panel and add limit forecasts and daily week use #6

Merged
schmidt.florian merged 14 commits from 5-panel-redesign into master 2026-10-15 19:06:05 +02:00
11 changed files with 1013 additions and 226 deletions
Showing only changes of commit 73f79eb6ac - Show all commits
+39
View File
@@ -8,3 +8,42 @@ 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.
## Panel and visual rules
- Keep this order: fixed 56 px header; Limits; Week use per day; Tokens (totals, hourly and daily
charts); Limit history; Breakdown by model and project; collapsed Diagnostics, hidden when empty.
Preserve scroll offset on snapshots. Sections have two columns from 1200 px content width;
limit tiles have three from 1400 px. Cards align at the top and size to their content.
- Follow the OS light/dark theme through `Ui.Theme` and `Ui.NeutralTheme`. Selection never uses
the OS accent. Selected segments use primary ink, semibold and the neutral selection surface;
checkboxes use primary ink on that surface. Keep all other Fluent accent states neutral too.
- Dark/light tokens: page `#0d0d0d`/`#f9f9f7`; surface `#1a1a19`/`#fcfcfb`;
border white/`#0b0b0b` at 10%; primary ink `#f0efec`/`#0b0b0b`;
secondary `#c3c2b7`/`#52514e`; muted `#898781` on both;
grid `#2c2c2a`/`#e1e0d9`; axis `#383835`/`#c3c2b7`;
neutral selection `#383835`/`#e1e0d9`; cache read `#5c5b57`/`#c3c2b7`.
- Claude is always orange `#d95926`/`#eb6834`; Codex always blue `#3987e5`/`#2a78d6`.
Model breakdown dots use the provider identity returned by the query, never a name heuristic.
Filtered model charts sort names into six categorical slots; later names fold into Other.
Slots in order: dark `#3987e5 #d95926 #199e70 #c98500 #d55181 #9085e9`;
light `#2a78d6 #eb6834 #1baf7a #eda100 #e87ba4 #6250d6`. Other is muted.
- Status chips always have icon and label: `#0ca30c` ✓ On track, `#ec835a` ▲ Ahead,
`#fab219` ▼ Behind. Forecast dates remain visible for every positive pace delta (D7), but
only Ahead gets the critical `#d03b3b` mark and ⚠. Other states say "At this pace 100 % on …"
in secondary ink. Text paragraphs stay in ink colours; colour belongs to marks and meters.
- Spacing is 8/16/24 px; card radius 10, padding 16–20; system sans. Use about 12 px captions,
13 body, 15 card titles, 20 section titles and 32–36 hero numbers. Tabular figures only in
tables and axes. Compact counts use three significant digits; axes omit trailing zeros.
Exact values stay in tooltips.
- Show one composition legend in the Tokens header. Cache reads are neutral; input/output/cache
write use full/65%/40% provider colour. Reasoning is part of output; Codex cache read is part
of input. Never add either subset twice.
- Week charts show dashed muted even pace and thin solid secondary budget, with labels beside
their own right endpoints and separated when close. No known day values means a collecting
message. Use CalendarDays, including partial dates at both ends of a window (D7).
Use `LimitAnalysis.SameInstance` for reset membership, history gaps and previous-window lookup;
resets within 15 minutes belong together, including minute drift in either direction.
- Charts use 2 px lines, hit targets at least 8 px, tooltips and recessive grids. Bars normally
have a 2 px surface gap; below 6 px width remove gaps and snap shared edges to physical pixels.
Breakdowns show eight rows plus Other; keep full project paths and exact counts in tooltips.
+165 -40
View File
@@ -1,8 +1,6 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Styling;
using FinalToken.Core;
using System.Globalization;
@@ -10,9 +8,26 @@ 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 Rect BarBounds(double x, double bottom, double width, double height, double scaling = 1)
{
var gap = width < 6 ? 0 : 2;
if (gap == 0)
{
var left = Math.Round(x * scaling) / scaling;
var right = Math.Round((x + width) * scaling) / scaling;
return new Rect(left, bottom - height, Math.Max(0, right - left), Math.Max(0, height));
}
return new Rect(x + gap / 2, bottom - height, Math.Max(0, width - gap), Math.Max(0, height - gap));
}
public static IBrush SeriesColour(int index) => ModelColour(index, true);
private static IBrush ModelColour(int index, bool dark) => Brush.Parse((dark
? new[] { "#3987e5", "#d95926", "#199e70", "#c98500", "#d55181", "#9085e9" }
: new[] { "#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#6250d6" })[index % 6]);
public static IBrush SeriesColour(string name, IReadOnlyList<string> names, bool dark) => name switch
{
"Claude" => Ui.ProviderColour(Provider.Claude, dark), "Codex" => Ui.ProviderColour(Provider.Codex, dark),
"Other" => Ui.Colour("Muted", dark), _ => ModelColour(Math.Max(0, names.Where(n => n != "Other").Order(StringComparer.Ordinal).ToList().IndexOf(name)), dark)
};
public static IReadOnlyList<double> AxisTicks(double maximum, bool percent = false)
{
if (!double.IsFinite(maximum) || maximum <= 0) return [0];
@@ -21,94 +36,204 @@ public sealed class UsageChart : Control
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();
return Enumerable.Range(0, (int)Math.Ceiling(maximum / step) + 1).Select(i => i * step).ToArray();
}
public IReadOnlyList<ChartValue> Values { get; init; } = [];
public IReadOnlyList<string> SeriesNames { get; init; } = [];
public bool Percent { get; init; }
public Provider LimitProvider { get; init; }
public ChartValue? Forecast { get; init; }
public ChartValue? ForecastStart { get; init; }
public TimeSpan Interval { get; init; } = TimeSpan.FromHours(1);
private readonly List<(Rect Rect, string Text)> hits = [];
public UsageChart()
{
Height = 180;
Height = 208;
ToolTip.SetShowDelay(this, 0);
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));
base.Render(context); hits.Clear();
var dark = Ui.Dark(this); var ink = Ui.Colour("Muted", dark);
var plot = new Rect(50, 16, Math.Max(1, Bounds.Width - 66), Math.Max(1, Bounds.Height - 48));
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);
context.DrawLine(new Pen(Ui.Colour(tick == 0 ? "Axis" : "Grid", dark)), new(plot.Left, y), new(plot.Right, y));
ChartText.Draw(context, Percent ? $"{tick:0}%" : Display.Axis(tick), 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 (groups.Length == 0) { ChartText.Draw(context, "No samples in this range", new(plot.Left + 12, plot.Top + 32), ink); return; }
var series = SeriesNames.Count > 0 ? SeriesNames : Values.Select(v => v.Series).Distinct().Order(StringComparer.Ordinal).ToArray();
var minTime = groups[0].Key;
var lastTime = Forecast is { } f && f.Time > groups[^1].Key ? f.Time : groups[^1].Key;
var duration = Math.Max(Interval.TotalSeconds, (lastTime - minTime).TotalSeconds + (Percent ? 0 : Interval.TotalSeconds));
double X(DateTimeOffset time) => plot.Left + (time - minTime).TotalSeconds / duration * plot.Width;
Point Position(ChartValue v, double value) => new(X(v.Time), plot.Bottom - Math.Clamp(value, 0, max) / max * plot.Height);
if (Percent)
{
var colour = Ui.ProviderColour(LimitProvider, dark);
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);
context.DrawLine(new Pen(colour, 2, lineCap: PenLineCap.Round), 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.DrawLine(new Pen(ink, 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")}"));
context.DrawEllipse(colour, null, point, 2, 2);
hits.Add((new(point.X - 8, point.Y - 10, 16, 20), $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Value:0.##}% · expected {value.Expected:0.##}%"));
previous = value;
}
if (previous is { } tail && Forecast is { } forecast)
{
var start = ForecastStart ?? tail;
context.DrawLine(new Pen(colour, 2, new DashStyle([1, 3], 0)), Position(start, start.Value), Position(forecast, forecast.Value));
hits.Add((new Rect(Position(forecast, forecast.Value) - new Vector(8, 8), new Size(16, 16)), $"Average forecast · {forecast.Time.LocalDateTime:g} · {forecast.Value:0.#}%"));
}
}
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++)
foreach (var group in groups)
{
var bottom = plot.Bottom;
foreach (var value in groups[i])
foreach (var value in group.OrderBy(v => v.Series, StringComparer.Ordinal))
{
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"));
var x = X(group.Key);
var gap = width < 6 ? 0 : 2;
var rect = BarBounds(x, bottom, width, height, TopLevel.GetTopLevel(this)?.RenderScaling ?? 1);
if (height > 0) context.DrawRectangle(SeriesColour(value.Series, series, dark), null, rect, gap == 0 ? 0 : 3, gap == 0 ? 0 : 3);
hits.Add((new(x, bottom - Math.Max(8, height), Math.Max(8, width), Math.Max(8, height)), $"{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);
// Daily calendar ticks remain anchored to local dates through DST.
var spanDays = (lastTime - minTime).TotalDays;
var stride = Math.Max(1, (int)Math.Ceiling(spanDays / Math.Max(2, plot.Width / 70)));
var day = Interval >= TimeSpan.FromDays(1) ? minTime : CalendarDays.Start(minTime);
var index = 0;
while (day <= lastTime)
{
if (day >= minTime && index % stride == 0)
ChartText.Draw(context, day.DateTime.ToString("dd.MM"), new(Math.Clamp(X(day) - 12, plot.Left, plot.Right - 40), plot.Bottom + 8), ink);
day = CalendarDays.NextStart(day); index++;
}
if (spanDays < 1) ChartText.Draw(context, minTime.LocalDateTime.ToString("dd.MM HH:mm"), new(plot.Left, plot.Bottom + 8), ink);
}
}
internal static class ChartText
{
public static void Draw(DrawingContext context, string text, Point point, IBrush brush, double size = 11)
{
var formatted = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, Typeface.Default, size, brush);
formatted.SetFontFeatures(FontFeatureCollection.Parse("tnum")); context.DrawText(formatted, point);
}
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" });
{ PaceState.Ahead => "#ec835a", PaceState.Behind => "#fab219", PaceState.OnTrack => "#0ca30c", _ => "#898781" });
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);
var dark = Ui.Dark(this); var colour = Ui.ProviderColour(window.Window.Provider, dark);
context.DrawRectangle(Ui.Colour("Grid", dark), null, new Rect(Bounds.Size), 3, 3);
var used = Bounds.Width * Math.Clamp(window.Window.UsedPercent / 100, 0, 1);
if (LimitAnalysis.AverageUseAtReset(window.Window, DateTimeOffset.UtcNow) is { } forecast && forecast > window.Window.UsedPercent)
{
using (context.PushOpacity(0.25)) context.DrawRectangle(colour, null, new Rect(used, 0, Math.Max(0, Bounds.Width * Math.Min(1, forecast / 100) - used), Bounds.Height), 3, 3);
if (forecast > 100) context.DrawLine(new Pen(window.Pace.State == PaceState.Ahead ? Brush.Parse("#d03b3b") : Ui.Colour("Secondary", dark), 3), new(Bounds.Width - 2, 0), new(Bounds.Width - 2, Bounds.Height));
}
context.DrawRectangle(colour, null, new Rect(0, 0, used, Bounds.Height), 3, 3);
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));
context.DrawLine(new Pen(Ui.Colour("Ink", dark), 2), new(Bounds.Width * elapsed, -2), new(Bounds.Width * elapsed, Bounds.Height + 2));
ToolTip.SetTip(this, $"Used {window.Window.UsedPercent:0.##}% · expected {window.Pace.ElapsedFraction * 100:0.##}%");
}
}
public sealed class CompositionBar(TokenCounts counts, Provider provider, bool includeCache) : Control
{
public override void Render(DrawingContext context)
{
base.Render(context);
var input = Math.Max(0, counts.Input - (provider == Provider.Codex ? counts.CacheRead : 0));
double[] values = [input, counts.Output, counts.CacheWrite, includeCache ? counts.CacheRead : 0];
var sum = Math.Max(1, values.Sum()); var x = 0d;
for (var i = 0; i < values.Length; i++)
{
var width = Bounds.Width * values[i] / sum;
using (context.PushOpacity(i == 1 ? .65 : i == 2 ? .4 : 1))
context.DrawRectangle(i == 3 ? Ui.Colour("Cache", Ui.Dark(this)) : Ui.ProviderColour(provider, Ui.Dark(this)), null,
new Rect(x, 0, Math.Max(0, width - 2), Bounds.Height), 3, 3);
x += width;
}
ToolTip.SetTip(this, Display.Tokens(counts));
}
}
public sealed class DailyLimitChart(WindowDays days, Provider provider) : Control
{
private readonly List<(Rect Rect, string Text)> hits = [];
public DailyLimitChart() : this(new([], [], null, 0, null), Provider.Claude) { }
protected override void OnInitialized()
{
base.OnInitialized(); Height = 248; ToolTip.SetShowDelay(this, 0);
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 dark = Ui.Dark(this); var ink = Ui.Colour("Muted", dark); var colour = Ui.ProviderColour(provider, dark);
var plot = new Rect(40, 24, Math.Max(1, Bounds.Width - 174), Math.Max(1, Bounds.Height - 60));
var maximum = Math.Max(days.EvenPace, Math.Max(days.DailyBudget ?? 0, days.Current.Concat(days.Previous).Select(d => d.Used ?? 0).DefaultIfEmpty(0).Max()));
var ticks = UsageChart.AxisTicks(maximum * 1.15); var max = Math.Max(1, ticks[^1]);
double Y(double value) => plot.Bottom - value / max * plot.Height;
foreach (var tick in ticks)
{
context.DrawLine(new Pen(Ui.Colour("Grid", dark)), new(plot.Left, Y(tick)), new(plot.Right, Y(tick)));
ChartText.Draw(context, $"{tick:0.#}%", new(0, Y(tick) - 7), ink);
}
var width = plot.Width / Math.Max(1, days.Current.Count);
for (var i = 0; i < days.Current.Count; i++)
{
var day = days.Current[i]; var x = plot.Left + i * width;
if (i < days.Previous.Count && days.Previous[i].Used is { } prior)
using (context.PushOpacity(.18)) context.DrawRectangle(null, new Pen(colour, 2), new Rect(x + 4, Y(prior), width - 8, plot.Bottom - Y(prior)), 3, 3);
if (day.Used is { } use)
{
using (context.PushOpacity(day.IsToday ? 1 : .5)) context.DrawRectangle(colour, null, new Rect(x + 8, Y(use), Math.Max(1, width - 16), plot.Bottom - Y(use)), 3, 3);
if (day.IsToday) ChartText.Draw(context, $"{use:0.#}%", new(x + 8, Y(use) - 18), Ui.Colour("Ink", dark), 12);
}
ChartText.Draw(context, day.Start.DateTime.ToString("ddd"), new(x + 8, plot.Bottom + 8), day.IsToday ? Ui.Colour("Ink", dark) : ink);
hits.Add((new Rect(x, plot.Top, width, plot.Height + 30), $"{day.Start.DateTime:d} · {(day.Used is { } u ? $"{u:0.##}% of week" : day.IsFuture ? "Future day" : "No day baseline")} · cumulative {day.Cumulative:0.##}%"));
}
var evenLabel = Math.Clamp(Y(days.EvenPace) - 7, plot.Top, plot.Bottom - 14);
var budgetLabel = days.DailyBudget is { } b ? Math.Clamp(Y(b) - 7, plot.Top, plot.Bottom - 14) : 0;
if (days.DailyBudget is { } budget && Math.Abs(evenLabel - budgetLabel) < 18)
{
var middle = Math.Clamp((evenLabel + budgetLabel) / 2, plot.Top + 9, plot.Bottom - 23);
evenLabel = middle + (budget >= days.EvenPace ? 9 : -9);
budgetLabel = middle + (budget >= days.EvenPace ? -9 : 9);
}
Reference(days.EvenPace, $"Even {days.EvenPace:0.#}%/day", ink, evenLabel, true);
if (days.DailyBudget is { } dailyBudget) Reference(dailyBudget, $"Budget {dailyBudget:0.#}%/day", Ui.Colour("Secondary", dark), budgetLabel, false);
void Reference(double value, string label, IBrush brush, double labelY, bool dashed)
{
context.DrawLine(new Pen(brush, 1, dashed ? new DashStyle([4, 4], 0) : null), new(plot.Left, Y(value)), new(plot.Right, Y(value)));
if (Math.Abs(labelY + 7 - Y(value)) > 3) context.DrawLine(new Pen(brush, 1), new(plot.Right, Y(value)), new(plot.Right + 6, labelY + 7));
ChartText.Draw(context, label, new(plot.Right + 8, labelY), brush);
}
}
}
+11 -3
View File
@@ -27,7 +27,7 @@ public sealed class DesktopApp : Application
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 Initialize() => Styles.Add(Ui.NeutralTheme());
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime)
@@ -53,6 +53,7 @@ public sealed class DesktopApp : Application
engine.PopupRequested += alert => Dispatcher.UIThread.Post(() => { if (!quitting) popups.Pace(alert); });
engine.ActivationRequested += () => Dispatcher.UIThread.Post(OpenPanel);
model.Snapshot = engine.CurrentSnapshot;
model.ProbeInterval = engine.Settings.ProbeInterval;
ageTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
ageTimer.Tick += (_, _) => { if (panel.IsVisible) model.Diagnostics = engine.RecentDiagnostics; };
ageTimer.Start();
@@ -88,7 +89,13 @@ public sealed class DesktopApp : Application
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 Refresh()
{
if (engine is null || model.Refreshing) return;
model.Refreshing = true;
try { await engine.RefreshNowAsync(); }
finally { model.Refreshing = false; }
}
private async Task LoadHistory()
{
if (engine is null || model.Snapshot is not { } snapshot || quitting) return;
@@ -100,7 +107,7 @@ public sealed class DesktopApp : Application
{
if (engine is null) return;
if (settingsWindow is not null) { settingsWindow.Activate(); return; }
settingsWindow = new SettingsWindow(engine.Settings, pluginStatus, value => settingsSave = SaveSettings(value));
settingsWindow = new SettingsWindow(engine.Settings, pluginStatus, value => settingsSave = SaveSettings(value), () => Run(Quit));
settingsWindow.Closed += (_, _) => settingsWindow = null;
settingsWindow.Show();
}
@@ -113,6 +120,7 @@ public sealed class DesktopApp : Application
try { await engine.UpdateSettingsAsync(value); }
catch { await OsStartup.ApplyAsync(previous.StartWithOs); throw; }
if (quitting) return;
model.ProbeInterval = value.ProbeInterval;
await CheckPlugin();
if (!quitting) await engine.RefreshNowAsync();
}
+59 -22
View File
@@ -4,11 +4,16 @@ 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 ChartValue(DateTimeOffset Time, string Series, double Value, double? Expected = null, bool BreakBefore = false, double CacheRead = 0);
public sealed record BreakdownRow(string Name, TokenCounts Counts, double Share, IReadOnlyList<Provider>? Providers = null);
public sealed record LimitChart(string Label, IReadOnlyList<ChartValue> Values, Provider Provider = Provider.Claude,
DateTimeOffset? Since = null, ChartValue? Forecast = null, ChartValue? ForecastStart = null);
public sealed record LimitDetail(Provider Provider, string Id, RateForecast? Recent, WindowDays? Days, DateTimeOffset? Since = null);
public sealed record HistoryView(IReadOnlyList<ChartValue> Hourly, IReadOnlyList<ChartValue> Daily,
IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> Projects);
IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> Projects)
{
public IReadOnlyList<LimitDetail> Details { get; init; } = [];
}
public partial class PanelViewModel : ObservableObject
{
@@ -18,6 +23,9 @@ public partial class PanelViewModel : ObservableObject
[ObservableProperty] private HistoryView history = new([], [], [], [], []);
[ObservableProperty] private IReadOnlyList<Diagnostic> diagnostics = [];
[ObservableProperty] private string message = "Reading local CLI data…";
[ObservableProperty] private bool includeCacheReads = true;
[ObservableProperty] private bool refreshing;
public TimeSpan ProbeInterval { get; set; } = TimeSpan.FromMinutes(5);
public static DateTimeOffset RangeStart(HistoryRange range, DateTimeOffset now) => range switch
{
@@ -33,33 +41,46 @@ public partial class PanelViewModel : ObservableObject
var providers = snapshot.Providers.Where(p => filter is null || p.Provider == filter).ToArray();
var hourly = Series(SeriesInterval.Hour);
var daily = Series(SeriesInterval.Day);
var details = new List<LimitDetail>();
var limits = providers.SelectMany(p => p.Windows.Select(w =>
{
var samples = store.LimitSamples(p.Provider, w.Window.Id, from, now);
var instanceSamples = store.LimitSamples(p.Provider, w.Window.Id,
w.Window.ResetsAt is { } r && w.Window.Length is { } l ? r - l - l : now.AddDays(-14), now);
details.Add(new(p.Provider, w.Window.Id, LimitAnalysis.Recent(w.Window, instanceSamples, now),
LimitAnalysis.Days(w.Window, instanceSamples, now),
instanceSamples.Where(s => LimitAnalysis.SameInstance(s, w.Window)).Select(s => s.SampleTime).DefaultIfEmpty(w.Window.SampleTime).Min()));
return new LimitChart($"{p.Provider} · {w.Window.Label}", samples.Select((s, i) =>
new ChartValue(s.SampleTime, w.Window.Label, s.UsedPercent,
new ChartValue(s.SampleTime, p.Provider.ToString(), s.UsedPercent,
Pace.Calculate(s, s.SampleTime).ElapsedFraction * 100,
i > 0 && s.ResetsAt != samples[i - 1].ResetsAt)).ToArray());
i > 0 && !LimitAnalysis.SameInstance(s, samples[i - 1]))).ToArray(), p.Provider,
samples.FirstOrDefault()?.SampleTime ?? instanceSamples.FirstOrDefault()?.SampleTime ?? w.Window.SampleTime,
w.Pace.Projection is { } projection ? new(projection, p.Provider.ToString(), 100) :
w.Window.ResetsAt is { } reset && LimitAnalysis.AverageUseAtReset(w.Window, now) is { } average ? new(reset, p.Provider.ToString(), average) : null,
new(now, p.Provider.ToString(), w.Window.UsedPercent));
})).ToArray();
return new(hourly, daily, limits, Breakdown(true), Breakdown(false));
return new(hourly, daily, limits, Breakdown(true), Breakdown(false)) { Details = details };
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)
IReadOnlyList<ChartValue> Series(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));
if (filter is null) return providers.SelectMany(p => store.TokenSeries(p.Provider, from, now, interval)
.Select(point => new ChartValue(point.Time, p.Provider.ToString(), point.Counts.Total, CacheRead: point.Counts.CacheRead))).ToArray();
var points = store.TokenSeriesByModel(filter.Value, from, now, interval);
var names = points.Select(p => p.Model ?? "Unknown model").Distinct().Order(StringComparer.Ordinal).Take(6).ToHashSet();
return points.GroupBy(p => (p.Time, Name: names.Contains(p.Model ?? "Unknown model") ? p.Model ?? "Unknown model" : "Other"))
.Select(g => new ChartValue(g.Key.Time, g.Key.Name, g.Sum(p => (double)p.Counts.Total), CacheRead: g.Sum(p => (double)p.Counts.CacheRead))).ToArray();
}
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 rows = providers.SelectMany(p => (models ? store.ByModel(p.Provider, from, now) : store.ByProject(p.Provider, from, now))
.Select(r => (p.Provider, r.Name, r.Counts)))
.GroupBy(r => r.Name ?? "Unknown").Select(g => new BreakdownRow(g.Key,
g.Aggregate(new TokenCounts(), (sum, r) => sum + r.Counts), 0, g.Select(r => r.Provider).Distinct().Order().ToArray())).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();
var top = rows.Take(8).ToList();
if (rows.Length > 8) top.Add(new($"Other ({rows.Length - 8})", rows.Skip(8).Aggregate(new TokenCounts(), (sum, r) => sum + r.Counts), 0,
rows.Skip(8).SelectMany(r => r.Providers ?? []).Distinct().Order().ToArray()));
return top.Select(r => r with { Share = total == 0 ? 0 : r.Counts.Total / total }).ToArray();
}
}
}
@@ -69,7 +90,7 @@ 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");
=> ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "d" : "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)
@@ -80,9 +101,25 @@ public static class Display
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";
? $"{(int)span.TotalDays} d {span.Hours} h" : span.TotalHours >= 1 ? $"{(int)span.TotalHours} h {span.Minutes} min" : $"{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() };
public static string Compact(double count) => CompactNumber(count, false);
public static string Axis(double count) => CompactNumber(count, true);
private static string CompactNumber(double count, bool trimTrailingZeros)
{
var unit = Math.Abs(count) >= 1e9 ? 3 : Math.Abs(count) >= 1e6 ? 2 : Math.Abs(count) >= 1000 ? 1 : 0;
if (unit == 0) return count.ToString("0");
var value = count / Math.Pow(1000, unit);
var decimals = Math.Max(0, 2 - (int)Math.Floor(Math.Log10(Math.Abs(value))));
value = Math.Round(value, decimals, MidpointRounding.AwayFromZero);
if (Math.Abs(value) >= 1000 && unit < 3) { value /= 1000; unit++; }
decimals = Math.Max(0, 2 - (int)Math.Floor(Math.Log10(Math.Abs(value))));
var format = trimTrailingZeros ? decimals == 0 ? "0" : "0." + new string('#', decimals) : "F" + decimals;
return value.ToString(format) + new[] { "", " K", " M", " B" }[unit];
}
public static string Forecast(DateTimeOffset date, PaceState state) =>
(state == PaceState.Ahead ? "⚠ " : "At this pace ") + $"100 % on {date.LocalDateTime:ddd HH:mm}";
public static string State(PaceState state) => state switch { PaceState.OnTrack => "✓ On track", PaceState.Ahead => "▲ Ahead", PaceState.Behind => "▼ Behind", _ => "? Pace unknown" };
}
+259 -90
View File
@@ -1,130 +1,299 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
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) };
private readonly StackPanel body = new() { Spacing = 24, Margin = new Thickness(24) };
private readonly StackPanel statuses = new() { Orientation = Orientation.Horizontal, Spacing = 8 };
private readonly TextBlock updated = Ui.Text("", 12, "Muted");
private readonly ScrollViewer scroll;
private readonly Button refreshButton;
private bool queued;
private bool wide;
private int limitColumns;
private readonly Dictionary<Provider, string> selectedDailyWindow = [];
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();
Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}";
Width = 1280; Height = 900; MinWidth = 960; MinHeight = 500; Ui.Theme(this);
var brand = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };
brand.Children.Add(Ui.Text("FinalToken", 20));
var version = Ui.Text(typeof(Program).Assembly.GetName().Version?.ToString(3) ?? "", 12, "Muted"); version.VerticalAlignment = VerticalAlignment.Center;
brand.Children.Add(version);
updated.VerticalAlignment = VerticalAlignment.Center; statuses.VerticalAlignment = VerticalAlignment.Center;
var left = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12, VerticalAlignment = VerticalAlignment.Center };
left.Children.Add(brand); left.Children.Add(updated); left.Children.Add(statuses);
var range = Segments(["24 h", "7 d", "30 d", "90 d", "All"], (int)model.Range, i => { model.Range = (HistoryRange)i; reload(); });
var providers = Segments(["All", "Claude", "Codex"], model.ProviderFilter is { } p ? (int)p + 1 : 0,
i => { model.ProviderFilter = i == 0 ? null : (Provider)(i - 1); reload(); });
refreshButton = Ui.Button("↻", refresh); ToolTip.SetTip(refreshButton, "Refresh local data");
var settingsButton = Ui.Button("⚙", settings); ToolTip.SetTip(settingsButton, "Settings");
var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };
actions.Children.Add(range); actions.Children.Add(providers); actions.Children.Add(refreshButton); actions.Children.Add(settingsButton);
var header = new Grid { Name = "PanelHeader", ColumnDefinitions = new ColumnDefinitions("*,Auto"), Margin = new Thickness(24, 0), Height = 56, ColumnSpacing = 16 };
header.Children.Add(left); Grid.SetColumn(actions, 1); header.Children.Add(actions);
var dock = new DockPanel(); DockPanel.SetDock(header, Dock.Top); dock.Children.Add(header);
scroll = new ScrollViewer { Content = body }; dock.Children.Add(scroll); Content = dock;
model.PropertyChanged += (_, _) => QueueRender();
SizeChanged += (_, _) => { if (wide != (Bounds.Width - 48 >= 1200) || limitColumns != LimitColumnCount(Bounds.Width - 48)) QueueRender(); };
ActualThemeVariantChanged += (_, _) => QueueRender();
RenderModel();
}
public static Control Segments(string[] labels, int selected, Action<int> change)
{
var panel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 0 };
var changing = false;
var buttons = labels.Select((label, index) => new ToggleButton { Content = label, IsChecked = index == selected,
Padding = new Thickness(8, 6), FontSize = 12 }).ToArray();
foreach (var button in buttons) button.Classes.Add("segment");
for (var i = 0; i < buttons.Length; i++)
{
var index = i;
buttons[i].IsCheckedChanged += (_, _) =>
{
if (changing) return;
changing = true;
foreach (var other in buttons.Where((_, j) => j != index)) other.IsChecked = false;
buttons[index].IsChecked = true; changing = false; change(index);
};
panel.Children.Add(buttons[i]);
}
return panel;
}
private void QueueRender()
{
if (queued) return; queued = true;
Dispatcher.UIThread.Post(() => { queued = false; RenderModel(); }, DispatcherPriority.Background);
}
public void RenderModel()
{
body.Children.Clear();
body.Children.Add(Ui.Text(model.Message));
var offset = scroll.Offset;
wide = (Bounds.Width > 0 ? Bounds.Width : Width) - 48 >= 1200;
limitColumns = LimitColumnCount((Bounds.Width > 0 ? Bounds.Width : Width) - 48);
var content = new List<Control>();
statuses.Children.Clear(); refreshButton.IsEnabled = !model.Refreshing;
var now = DateTimeOffset.UtcNow;
updated.Text = model.Snapshot is { } s ? "Updated " + (now - s.MadeAt < TimeSpan.FromMinutes(1) ? "just now" : Display.Duration(now - s.MadeAt) + " ago") : model.Message;
ToolTip.SetTip(updated, model.Snapshot?.MadeAt.LocalDateTime.ToString("F"));
if (model.Snapshot is { } snapshot)
{
foreach (var provider in snapshot.Providers.Where(p => model.ProviderFilter is null || p.Provider == model.ProviderFilter))
foreach (var p in snapshot.Providers)
{
var card = Ui.Stack(Ui.Text(provider.Provider.ToString(), 22), Ui.Text($"{provider.Status} {provider.Reason}"));
foreach (var window in provider.Windows)
var label = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 };
label.Children.Add(Ui.Mark("●", p.Status == ProviderStatus.Available ? Ui.ProviderColour(p.Provider, Ui.Dark(this)) : Ui.Colour("Muted", Ui.Dark(this))));
label.Children.Add(Ui.Text(p.Provider.ToString(), 12));
var pill = new Border { Child = label, CornerRadius = new CornerRadius(10), Padding = new Thickness(8, 4), BorderThickness = new Thickness(1), BorderBrush = Ui.Colour("Border", Ui.Dark(this)) };
ToolTip.SetTip(pill, p.Reason ?? p.Status.ToString()); statuses.Children.Add(pill);
}
var providers = snapshot.Providers.Where(p => model.ProviderFilter is null || p.Provider == model.ProviderFilter).ToArray();
content.Add(Ui.Text("Limits", 20));
var tiles = new List<Control>();
foreach (var provider in providers)
{
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)}" : "")));
if (provider.Status != ProviderStatus.Available)
tiles.Add(Ui.Card(Ui.Stack(Ui.Text(provider.Provider + " · " + provider.Status, 15), Ui.Text(provider.Reason ?? "Provider disabled", 13, "Secondary"))));
else foreach (var window in provider.Windows) tiles.Add(LimitTile(window, now));
}
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));
content.Add(Ui.Columns(tiles, limitColumns));
var longWindows = model.History.Details.Where(d => d.Days is not null && providers.Any(p => p.Provider == d.Provider &&
p.Status == ProviderStatus.Available && p.Windows.Any(w => w.Window.Id == d.Id))).ToArray();
if (longWindows.Length > 0)
{
content.Add(Ui.Text("Week use per day", 20));
content.Add(Ui.Columns(longWindows.GroupBy(d => d.Provider).Select(group =>
{
var entries = group.ToArray();
var index = Array.FindIndex(entries, d => d.Id == selectedDailyWindow.GetValueOrDefault(group.Key));
if (index < 0) index = 0;
var labels = entries.Select(d => providers.SelectMany(p => p.Windows).First(w => w.Window.Provider == d.Provider && w.Window.Id == d.Id).Window.Label).ToArray();
Control DayView(LimitDetail item) => item.Days!.Current.Any(d => d.Used is not null)
? new DailyLimitChart(item.Days, item.Provider)
: Ui.Text($"Collecting history since {(item.Since ?? providers.SelectMany(p => p.Windows).First(w => w.Window.Provider == item.Provider && w.Window.Id == item.Id).Window.SampleTime).LocalDateTime:dd.MM. HH:mm}", 12, "Muted");
var chart = new Border { Child = DayView(entries[index]) };
var title = Ui.Text(group.Key + " · " + labels[index], 15);
var stack = Ui.Stack(title);
var explanation = Ui.Text("Filled: this window · outline: previous window", 12, "Muted");
void UpdateExplanation(LimitDetail item) => explanation.IsVisible = item.Days!.Previous.Count > 0 && item.Days.Current.Any(d => d.Used is not null);
UpdateExplanation(entries[index]);
if (entries.Length > 1)
{
var selector = new ComboBox { ItemsSource = labels, SelectedIndex = index };
selector.SelectionChanged += (_, _) =>
{
if (selector.SelectedIndex < 0) return;
var item = entries[selector.SelectedIndex]; selectedDailyWindow[group.Key] = item.Id;
title.Text = group.Key + " · " + labels[selector.SelectedIndex];
chart.Child = DayView(item);
UpdateExplanation(item);
};
stack.Children.Add(selector);
}
stack.Children.Add(explanation);
stack.Children.Add(chart); return Ui.Card(stack);
}), wide));
}
var tokenHeader = new DockPanel();
var toggle = new CheckBox { Content = "Include cache reads", IsChecked = model.IncludeCacheReads, HorizontalAlignment = HorizontalAlignment.Right };
toggle.IsCheckedChanged += (_, _) => model.IncludeCacheReads = toggle.IsChecked == true;
DockPanel.SetDock(toggle, Dock.Right); tokenHeader.Children.Add(toggle);
var tokenTitle = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 24, VerticalAlignment = VerticalAlignment.Center };
tokenTitle.Children.Add(Ui.Text("Tokens", 20)); tokenTitle.Children.Add(CompositionLegend()); tokenHeader.Children.Add(tokenTitle); content.Add(tokenHeader);
var totals = providers.Select(p =>
{
var row = new WrapPanel();
row.Children.Add(TokenTile(p, "Today", p.Today));
if (p.Session is { } session && p.Windows.Any(w => w.Window.Length <= TimeSpan.FromDays(1))) row.Children.Add(TokenTile(p, "Current session", session));
row.Children.Add(TokenTile(p, "This week", p.Week));
return (Control)Ui.Card(Ui.Stack(Ui.Text(p.Provider.ToString(), 15), row));
});
content.Add(Ui.Columns(totals, wide));
}
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));
var seriesNames = h.Hourly.Concat(h.Daily).Select(v => v.Series).Distinct().Order(StringComparer.Ordinal).ToArray();
Control TokenChart(string title, IReadOnlyList<ChartValue> values, bool daily) => Ui.Card(Ui.Stack(Ui.Text(title, 15),
Legend(seriesNames), new UsageChart { Values = values.Select(v => v with { Value = Math.Max(0, v.Value - (model.IncludeCacheReads ? 0 : v.CacheRead)) }).ToArray(),
SeriesNames = seriesNames, Interval = daily ? TimeSpan.FromDays(1) : TimeSpan.FromHours(1) }));
content.Add(Ui.Columns([TokenChart("Tokens per hour", h.Hourly, false), TokenChart("Tokens per day", h.Daily, true)], wide));
content.Add(Ui.Text("Limit history", 20));
foreach (var limit in h.Limits.Where(l => l.Values.Count < 2))
content.Add(Ui.Text($"{limit.Label} · Collecting history since {limit.Since?.LocalDateTime:dd.MM. HH:mm}", 12, "Muted"));
content.Add(Ui.Columns(h.Limits.Where(l => l.Values.Count >= 2).Select(limit => Ui.Card(Ui.Stack(Ui.Text(limit.Label, 15),
Ui.Text("Used · dashed: even pace · dotted: average forecast", 12, "Muted"),
new UsageChart { Values = limit.Values, Percent = true, LimitProvider = limit.Provider, Forecast = limit.Forecast, ForecastStart = limit.ForecastStart }))), wide));
content.Add(Ui.Text("Breakdown", 20));
content.Add(Ui.Columns([Breakdown("By model", h.Models, false), Breakdown("By project", h.Projects, true)], wide));
if (model.Diagnostics.Count > 0)
{
var lines = Ui.Stack();
foreach (var d in model.Diagnostics) lines.Children.Add(Ui.Text($"{d.Time.LocalDateTime:g} · {d.Provider} · {d.Code} · {d.Summary} ({d.Count})", 12, "Secondary"));
content.Add(Ui.Card(new Expander { Header = $"Diagnostics ({model.Diagnostics.Count})", Content = lines, IsExpanded = false }));
}
private static Control Legend(IReadOnlyList<ChartValue> values)
body.Children.Clear(); foreach (var control in content) body.Children.Add(control);
scroll.UpdateLayout(); scroll.Offset = offset;
}
private Control LimitTile(WindowSnapshot window, DateTimeOffset now)
{
var legend = new WrapPanel { Orientation = Orientation.Horizontal };
var index = 0;
foreach (var series in values.Select(v => v.Series).Distinct())
var w = window.Window; var pace = window.Pace;
var detail = model.History.Details.FirstOrDefault(d => d.Provider == w.Provider && d.Id == w.Id);
var title = new DockPanel();
var chip = new Border { Child = Ui.Mark(Display.State(pace.State), Brush.Parse("#0b0b0b")), Background = PaceBar.Colour(pace.State), CornerRadius = new CornerRadius(6), Padding = new Thickness(8, 4) };
DockPanel.SetDock(chip, Dock.Right); title.Children.Add(chip); title.Children.Add(Ui.Text(w.Provider + " · " + w.Label, 15));
var card = Ui.Stack(title, Ui.Text($"{w.UsedPercent:0.#} %", 36), Ui.Text("used", 12, "Muted"), new PaceBar(window) { Height = 10 });
card.Children.Add(Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {reset.LocalDateTime:ddd HH:mm}" : "Reset unknown", 13, "Secondary"));
if (pace.Projection is { } projection)
{
var label = Ui.Text("● " + series, 12); label.Foreground = UsageChart.SeriesColour(index++);
label.Margin = new Thickness(0, 0, 14, 0); legend.Children.Add(label);
var caption = Display.Forecast(projection, pace.State) + $" ({Display.Duration(w.ResetsAt!.Value - projection)} before reset)";
if (pace.State == PaceState.Ahead)
{
var line = new DockPanel(); var mark = Ui.Mark("⚠ ", Brush.Parse("#d03b3b"), 13);
DockPanel.SetDock(mark, Dock.Left); line.Children.Add(mark); line.Children.Add(Ui.Text(caption[2..], 13, "Secondary")); card.Children.Add(line);
}
else card.Children.Add(Ui.Text(caption, 13, "Secondary"));
}
else if (LimitAnalysis.AverageUseAtReset(w, now) is { } average)
card.Children.Add(Ui.Text($"≈ {average:0.#} % at reset", 13, "Secondary"));
if (detail?.Recent is { } recent)
{
var line = Ui.Text($"Last 24 h: +{recent.Increase:0.#} %" + (recent.ReachesLimit is { } date ? $" · 100 % on {date.LocalDateTime:ddd HH:mm}" : $" · ≈ {recent.UseAtReset:0.#} % at reset"), 13, "Secondary");
ToolTip.SetTip(line, $"{recent.PercentPerDay:0.##} %/day over {Display.Duration(recent.Span)} of samples"); card.Children.Add(line);
}
if (detail?.Days is { } days)
{
card.Children.Add(Ui.Text(days.Today is { } today ? $"Today +{today:0.#} % of the week" : "Today · collecting a day baseline", 15));
card.Children.Add(Ui.Text($"Even pace {days.EvenPace:0.#} %/day", 13, "Secondary"));
if (days.DailyBudget is { } budget) card.Children.Add(Ui.Text($"Budget {budget:0.#} %/day for {Display.Duration(w.ResetsAt!.Value - now)}", 15));
}
if (now - w.SampleTime > model.ProbeInterval * 2) card.Children.Add(Ui.Text($"⚠ sample {Display.Duration(now - w.SampleTime)} old", 12, "Muted"));
var tile = Ui.Card(card); tile.Name = $"LimitTile-{w.Provider}-{w.Id}"; return tile;
}
private Control TokenTile(ProviderSnapshot provider, string label, TokenCounts counts)
{
var tile = Ui.Stack(Ui.Text(label, 12, "Secondary"), Ui.Text(Display.Compact(Math.Max(0, counts.Total - (model.IncludeCacheReads ? 0 : counts.CacheRead))), 32),
new CompositionBar(counts, provider.Provider, model.IncludeCacheReads) { Height = 6 });
tile.Width = wide ? 164 : 188; tile.Margin = new Thickness(0, 8, 16, 0);
ToolTip.SetTip(tile, Display.Tokens(counts)); return tile;
}
private Control CompositionLegend()
{
var panel = new WrapPanel { Name = "CompositionLegend", VerticalAlignment = VerticalAlignment.Center }; var colour = model.ProviderFilter is { } provider
? Ui.ProviderColour(provider, Ui.Dark(this)) : Ui.Colour("Secondary", Ui.Dark(this));
var labels = new[] { "Input", "Output", "Cache write", "Cache read" };
for (var i = 0; i < labels.Length; i++)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, Margin = new Thickness(0, 0, 6, 0) };
row.Children.Add(new Border { Background = i == 3 ? Ui.Colour("Cache", Ui.Dark(this)) : colour,
Opacity = i == 1 ? .65 : i == 2 ? .4 : 1, Width = 5, Height = 5, CornerRadius = new CornerRadius(2), VerticalAlignment = VerticalAlignment.Center });
row.Children.Add(Ui.Text(labels[i], 11, "Muted")); panel.Children.Add(row);
}
return panel;
}
private Control Legend(string[] names)
{
var legend = new WrapPanel();
foreach (var name in names)
{
var item = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 };
item.Children.Add(Ui.Mark("●", UsageChart.SeriesColour(name, names, Ui.Dark(this)))); item.Children.Add(Ui.Text(name, 12, "Secondary"));
item.Margin = new Thickness(0, 0, 16, 0); legend.Children.Add(item);
}
return legend;
}
private static Border Breakdown(string title, IReadOnlyList<BreakdownRow> rows)
private Control Breakdown(string title, IReadOnlyList<BreakdownRow> rows, bool projects)
{
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 table = Ui.Stack(Ui.Text(title, 15));
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,90,140"), RowSpacing = 8, ColumnSpacing = 8 };
var names = projects ? ShortProjectNames(rows.Select(r => r.Name).ToArray()) : rows.Select(r => r.Name).ToArray();
Add(Ui.Text("Name", 12, "Muted"), 0, 0); Add(Ui.Text("Total", 12, "Muted"), 0, 1); Add(Ui.Text("Share", 12, "Muted"), 0, 2);
for (var i = 0; i < rows.Count; i++)
{
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++);
var row = rows[i]; var label = Ui.Text(names[i], 13);
label.TextWrapping = TextWrapping.NoWrap; label.TextTrimming = TextTrimming.CharacterEllipsis;
Control nameCell = label;
if (!projects && model.ProviderFilter is null && row.Providers is { Count: > 0 } rowProviders)
{
var cell = new DockPanel();
foreach (var provider in rowProviders)
{
var dot = Ui.Mark("●", Ui.ProviderColour(provider, Ui.Dark(this))); dot.Margin = new Thickness(0, 0, 6, 0);
ToolTip.SetTip(dot, provider.ToString()); DockPanel.SetDock(dot, Dock.Left); cell.Children.Add(dot);
}
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."));
cell.Children.Add(label); nameCell = cell;
}
ToolTip.SetTip(nameCell, row.Name + "\n" + Display.Tokens(row.Counts)); Add(nameCell, i + 1, 0);
var total = Ui.TableNumber(Display.Compact(row.Counts.Total)); ToolTip.SetTip(total, Display.Tokens(row.Counts)); Add(total, i + 1, 1);
var share = new Grid { ColumnDefinitions = new ColumnDefinitions("*,50"), ColumnSpacing = 8 };
share.Children.Add(new ProgressBar { Minimum = 0, Maximum = 1, Value = row.Share, Width = 82, MinWidth = 0, Height = 5, VerticalAlignment = VerticalAlignment.Center,
Foreground = model.ProviderFilter is { } p ? Ui.ProviderColour(p, Ui.Dark(this)) : Ui.Colour("Muted", Ui.Dark(this)) });
var percent = Ui.TableNumber(row.Share.ToString("P1"), 12, "Secondary"); Grid.SetColumn(percent, 1); share.Children.Add(percent);
ToolTip.SetTip(share, row.Name + "\n" + Display.Tokens(row.Counts)); Add(share, i + 1, 2);
}
table.Children.Add(grid); if (rows.Count == 0) table.Children.Add(Ui.Text("No tokens in this range.", 12, "Muted"));
return Ui.Card(table);
void AddRow(string[] values, int row)
void Add(Control c, int row, int col)
{
grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
for (var column = 0; column < values.Length; column++)
while (grid.RowDefinitions.Count <= row) grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
Grid.SetRow(c, row); Grid.SetColumn(c, col); grid.Children.Add(c);
}
}
public static string[] ShortProjectNames(string[] paths)
{
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);
}
}
var parts = paths.Select(p => p.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries)).ToArray();
return parts.Select((p, i) =>
{
var depth = Math.Min(2, p.Length);
while (depth < p.Length && parts.Where((_, j) => j != i).Any(other => string.Join('/', other.TakeLast(depth)) == string.Join('/', p.TakeLast(depth)))) depth++;
return string.Join('/', p.TakeLast(depth));
}).ToArray();
}
public static int LimitColumnCount(double contentWidth) => contentWidth >= 1400 ? 3 : contentWidth >= 1200 ? 2 : 1;
}
+4 -7
View File
@@ -13,8 +13,7 @@ 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;
Width = 400; Height = install is null ? 152 : 184; Ui.Theme(this);
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)
@@ -24,10 +23,8 @@ public sealed class PopupWindow : Window
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;
var card = Ui.Card(body);
if (accent is not null) { card.Resources["Border"] = accent; card.BorderThickness = new Thickness(3, 1, 1, 1); }
Content = card;
PointerPressed += (_, e) =>
{
@@ -38,7 +35,7 @@ public sealed class PopupWindow : Window
}
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));
(alert.Projection is { } projection ? "\n" + Display.Forecast(projection, alert.State) : ""), open, accent: PaceBar.Colour(alert.State));
}
public sealed class PopupStack(Action open, TimeProvider? clock = null) : IDisposable
+81 -35
View File
@@ -1,5 +1,6 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using FinalToken.Core;
using FinalToken.Core.StreamDeck;
@@ -7,30 +8,61 @@ namespace FinalToken.App;
public sealed class SettingsWindow : Window
{
public SettingsWindow(Settings initial, PluginInstallStatus status, Func<Settings, Task> save)
public SettingsWindow(Settings initial, PluginInstallStatus status, Func<Settings, Task> save, Action? quit = null)
{
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 };
Title = "FinalToken settings"; Width = 760; Height = 900; MinWidth = 600; MinHeight = 500; Ui.Theme(this);
var body = new StackPanel { Spacing = 16, Margin = new Thickness(24) };
body.Children.Add(Ui.Text("Settings", 24));
var general = Ui.Stack(Ui.Text("General", 15));
var refresh = Number(general, "Token refresh (seconds, 1–60)", (decimal)initial.RefreshInterval.TotalSeconds, 1, 60);
var probe = Number(general, "Limit probe (minutes, 1–60)", (decimal)initial.ProbeInterval.TotalMinutes, 1, 60);
var threshold = Number(general, "Pace threshold (points)", (decimal)initial.PaceThreshold, 0.1m, 100);
var startup = Check(general, "Start with the OS", initial.StartWithOs);
var tray = Check(general, "Close to tray", initial.CloseToTray);
body.Children.Add(Ui.Card(general));
var popups = Ui.Stack(Ui.Text("Popups", 15));
var ahead = Check(popups, "Ahead popups", initial.PopupAhead);
var behind = Check(popups, "Behind popups", initial.PopupBehind);
var claudePopups = PopupControls(popups, "Claude", initial.Claude);
var codexPopups = PopupControls(popups, "Codex", initial.Codex);
body.Children.Add(Ui.Card(popups));
var providers = Ui.Stack(Ui.Text("Providers", 15));
var claude = ProviderControls(providers, "Claude", initial.Claude);
var codex = ProviderControls(providers, "Codex", initial.Codex);
body.Children.Add(Ui.Card(providers));
var streamDeck = Ui.Stack(Ui.Text("Stream Deck", 15), Ui.Text($"{status.State} · shipped {status.ShippedVersion ?? "none"} · installed {status.InstalledVersion ?? "none"}", 13, "Secondary"));
var selectedMode = initial.StreamDeckInstallMode;
streamDeck.Children.Add(PanelWindow.Segments(["Off", "Ask", "Automatic"], (int)selectedMode, i => selectedMode = (InstallMode)i));
streamDeck.Children.Add(Ui.Text("Dismissed plugin version (clear to ask again)", 12, "Secondary"));
var dismissed = new TextBox { Text = initial.DismissedPluginVersion ?? "" }; streamDeck.Children.Add(dismissed);
body.Children.Add(Ui.Card(streamDeck));
var about = Ui.Stack(Ui.Text("About", 15), Ui.Text("FinalToken " + typeof(Program).Assembly.GetName().Version?.ToString(3)), Ui.Text(DataPaths.DataDirectory, 12, "Secondary"));
var error = Ui.Text("", 12, "Secondary");
about.Children.Add(Ui.Button("Open folder", () =>
{
try
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(DataPaths.DataDirectory) { UseShellExecute = true });
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception or InvalidOperationException)
{ error.Text = "Could not open the data folder."; }
}));
body.Children.Add(Ui.Card(about));
var footer = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto,Auto"), ColumnSpacing = 8, Margin = new Thickness(24, 16) };
var quitButton = Ui.Button("Quit FinalToken", () => quit?.Invoke()); quitButton.IsEnabled = quit is not null;
footer.Children.Add(quitButton);
var cancel = Ui.Button("Cancel", Close); Grid.SetColumn(cancel, 2); footer.Children.Add(cancel);
var button = Ui.Button("Save", () => { }); Grid.SetColumn(button, 3); footer.Children.Add(button);
button.Click += async (_, _) =>
{
var value = initial with { RefreshInterval = TimeSpan.FromSeconds((double)(refresh.Value ?? 0)), ProbeInterval = TimeSpan.FromMinutes((double)(probe.Value ?? 0)),
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() };
StartWithOs = startup.IsChecked == true, CloseToTray = tray.IsChecked == true,
Claude = claudePopups(claude()), Codex = codexPopups(codex()), StreamDeckInstallMode = selectedMode,
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(); }
@@ -38,21 +70,35 @@ public sealed class SettingsWindow : Window
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() };
var dock = new DockPanel();
var bottom = Ui.Stack(error, footer); DockPanel.SetDock(bottom, Dock.Bottom); dock.Children.Add(bottom);
dock.Children.Add(new ScrollViewer { Content = body }); Content = dock;
}
private static NumericUpDown Number(StackPanel parent, string label, decimal value, decimal min, decimal max)
{
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,160"), ColumnSpacing = 16 };
grid.Children.Add(Ui.Text(label, 13, "Secondary"));
var control = new NumericUpDown { Value = value, Minimum = min, Maximum = max }; Grid.SetColumn(control, 1); grid.Children.Add(control);
parent.Children.Add(grid); return control;
}
private static CheckBox Check(StackPanel parent, string label, bool value)
{
var c = new CheckBox { Content = label, IsChecked = value, Name = label.Replace(" ", "") }; parent.Children.Add(c); return c;
}
private static Func<ProviderSettings, ProviderSettings> PopupControls(StackPanel parent, string name, ProviderSettings config)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 16 };
row.Children.Add(Ui.Text(name));
var enabled = Check(row, "Popups enabled", config.PopupsEnabled);
var ahead = Check(row, "Ahead", config.PopupAhead); var behind = Check(row, "Behind", config.PopupBehind);
parent.Children.Add(row);
return value => value with { PopupsEnabled = enabled.IsChecked == true, PopupAhead = ahead.IsChecked == true, PopupBehind = behind.IsChecked == true };
}
private static Func<ProviderSettings> ProviderControls(StackPanel parent, string name, ProviderSettings config)
{
parent.Children.Add(Ui.Text(name)); var enabled = Check(parent, "Enabled", config.Enabled);
parent.Children.Add(Ui.Text("CLI path (empty uses PATH)", 12, "Secondary"));
var path = new TextBox { Name = name + "CliPath", Text = config.CliPath ?? "" }; parent.Children.Add(path);
return () => config with { Enabled = enabled.IsChecked == true, CliPath = string.IsNullOrWhiteSpace(path.Text) ? null : path.Text.Trim() };
}
}
+131
View File
@@ -0,0 +1,131 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Styling;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Templates;
using Avalonia.Markup.Xaml.MarkupExtensions;
using Avalonia.Themes.Fluent;
using FinalToken.Core;
namespace FinalToken.App;
public static class Ui
{
public static IBrush Colour(string role, bool dark) => Brush.Parse(role switch
{
"Page" => dark ? "#0d0d0d" : "#f9f9f7",
"Surface" => dark ? "#1a1a19" : "#fcfcfb",
"Border" => dark ? "#1affffff" : "#1a0b0b0b",
"Ink" => dark ? "#f0efec" : "#0b0b0b",
"Secondary" => dark ? "#c3c2b7" : "#52514e",
"Grid" => dark ? "#2c2c2a" : "#e1e0d9",
"Axis" => dark ? "#383835" : "#c3c2b7",
"Selection" => dark ? "#383835" : "#e1e0d9",
"Claude" => dark ? "#d95926" : "#eb6834",
"Codex" => dark ? "#3987e5" : "#2a78d6",
"Cache" => dark ? "#5c5b57" : "#c3c2b7",
_ => "#898781"
});
public static bool Dark(StyledElement element) => element.ActualThemeVariant == ThemeVariant.Dark;
public static IBrush ProviderColour(Provider provider, bool dark) => Colour(provider.ToString(), dark);
public static void Theme(Window window)
{
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var resources = new ResourceDictionary();
foreach (var role in new[] { "Page", "Surface", "Border", "Ink", "Secondary", "Muted", "Grid", "Axis", "Selection", "Claude", "Codex", "Cache" })
resources[role] = Colour(role, theme == ThemeVariant.Dark);
window.Resources.ThemeDictionaries[theme] = resources;
}
window.Bind(TemplatedControl.BackgroundProperty, window.GetResourceObservable("Page"));
window.Bind(TemplatedControl.ForegroundProperty, window.GetResourceObservable("Ink"));
window.FontSize = 13;
var segments = new Style(s => s.OfType<ToggleButton>().Class("segment"));
segments.Setters.Add(new Setter(TemplatedControl.BackgroundProperty, new DynamicResourceExtension("Surface")));
segments.Setters.Add(new Setter(TemplatedControl.ForegroundProperty, new DynamicResourceExtension("Ink")));
segments.Setters.Add(new Setter(TemplatedControl.TemplateProperty, new FuncControlTemplate<ToggleButton>((button, _) =>
{
var presenter = new ContentPresenter { HorizontalContentAlignment = HorizontalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center };
presenter.Bind(ContentPresenter.ContentProperty, button.GetObservable(ContentControl.ContentProperty));
presenter.Bind(ContentPresenter.ForegroundProperty, button.GetObservable(TemplatedControl.ForegroundProperty));
presenter.Bind(ContentPresenter.FontWeightProperty, button.GetObservable(TemplatedControl.FontWeightProperty));
var border = new Border { Child = presenter, Padding = new Thickness(8, 6), CornerRadius = new CornerRadius(4) };
border.Bind(Border.BackgroundProperty, button.GetObservable(TemplatedControl.BackgroundProperty));
return border;
})));
window.Styles.Add(segments);
var selected = new Style(s => s.OfType<ToggleButton>().Class("segment").Class(":checked"));
selected.Setters.Add(new Setter(TemplatedControl.BackgroundProperty, new DynamicResourceExtension("Selection")));
selected.Setters.Add(new Setter(TemplatedControl.FontWeightProperty, FontWeight.SemiBold)); window.Styles.Add(selected);
var checks = new Style(s => s.OfType<CheckBox>());
checks.Setters.Add(new Setter(TemplatedControl.TemplateProperty, new FuncControlTemplate<CheckBox>((check, _) =>
{
var glyph = Text("✓", 14); glyph.Name = "NeutralCheckGlyph"; glyph.HorizontalAlignment = HorizontalAlignment.Center;
var box = new Border { Name = "NeutralCheckSurface", Child = glyph, Width = 20, Height = 20, CornerRadius = new CornerRadius(4),
BorderThickness = new Thickness(1), VerticalAlignment = VerticalAlignment.Center };
box.Bind(Border.BackgroundProperty, box.GetResourceObservable("Selection")); box.Bind(Border.BorderBrushProperty, box.GetResourceObservable("Axis"));
glyph.IsVisible = check.IsChecked == true; check.IsCheckedChanged += (_, _) => glyph.IsVisible = check.IsChecked == true;
var label = new ContentPresenter { Margin = new Thickness(8, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center };
label.Bind(ContentPresenter.ContentProperty, check.GetObservable(ContentControl.ContentProperty));
label.Bind(ContentPresenter.ForegroundProperty, label.GetResourceObservable("Ink"));
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("20,*"), MinHeight = 32 };
grid.Children.Add(box); Grid.SetColumn(label, 1); grid.Children.Add(label); return grid;
})));
window.Styles.Add(checks);
}
// Explicit palettes keep every remaining Fluent control independent of the OS accent.
public static FluentTheme NeutralTheme()
{
var theme = new FluentTheme();
theme.Palettes[ThemeVariant.Dark] = new ColorPaletteResources { Accent = Color.Parse("#383835") };
theme.Palettes[ThemeVariant.Light] = new ColorPaletteResources { Accent = Color.Parse("#e1e0d9") };
return theme;
}
public static TextBlock Text(string text, double size = 13, string role = "Ink")
{
var block = new TextBlock { Text = text, FontSize = size, TextWrapping = TextWrapping.Wrap };
block.Bind(TextBlock.ForegroundProperty, block.GetResourceObservable(role));
return block;
}
public static TextBlock Mark(string text, IBrush colour, double size = 12) => new() { Text = text, FontSize = size, Foreground = colour };
public static TextBlock TableNumber(string text, double size = 13, string role = "Ink")
{
var block = Text(text, size, role); block.FontFeatures = FontFeatureCollection.Parse("tnum"); return block;
}
public static StackPanel Stack(params Control[] children)
{
var stack = new StackPanel { Spacing = 8 };
foreach (var child in children) stack.Children.Add(child);
return stack;
}
public static Border Card(Control content)
{
var card = new Border { Child = content, Padding = new Thickness(16), CornerRadius = new CornerRadius(10), BorderThickness = new Thickness(1) };
card.Bind(Border.BackgroundProperty, card.GetResourceObservable("Surface"));
card.Bind(Border.BorderBrushProperty, card.GetResourceObservable("Border"));
return card;
}
public static Button Button(string text, Action action)
{
var button = new Button { Content = text, Padding = new Thickness(12, 6) };
button.Click += (_, _) => action();
return button;
}
public static Control Columns(IEnumerable<Control> children, bool wide) => Columns(children, wide ? 2 : 1);
public static Control Columns(IEnumerable<Control> children, int columns)
{
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions(string.Join(',', Enumerable.Repeat("*", columns))), ColumnSpacing = 16, RowSpacing = 16 };
var index = 0;
foreach (var child in children)
{
child.VerticalAlignment = VerticalAlignment.Top;
if (index % columns == 0) grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
Grid.SetColumn(child, index % columns); Grid.SetRow(child, index / columns);
grid.Children.Add(child); index++;
}
return grid;
}
}
+55 -1
View File
@@ -5,13 +5,67 @@ namespace FinalToken.App.Tests;
public sealed class FormattingTests
{
[Theory]
[InlineData(6000000000, "6 B")]
[InlineData(2000000000, "2 B")]
[InlineData(1500000000, "1,5 B")]
[InlineData(600000000, "600 M")]
[InlineData(82500, "82,5 K")]
[InlineData(0, "0")]
public void AxisNumbersDropTrailingZerosWithoutChangingCompactValues(double value, string expected)
{
var previous = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE");
Assert.Equal(expected, Display.Axis(value));
Assert.Equal("2,00 B", Display.Compact(2000000000));
}
finally { CultureInfo.CurrentCulture = previous; }
}
[Theory]
[InlineData(292950000, "293 M")]
[InlineData(2300000000, "2,30 B")]
[InlineData(966690000, "967 M")]
[InlineData(82500, "82,5 K")]
[InlineData(999950, "1,00 M")]
[InlineData(0, "0")]
public void CompactNumbersUseThreeSignificantDigits(double value, string expected)
{
var previous = CultureInfo.CurrentCulture;
try { CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); Assert.Equal(expected, Display.Compact(value)); }
finally { CultureInfo.CurrentCulture = previous; }
}
[Theory]
[InlineData(FinalToken.Core.PaceState.Ahead, true)]
[InlineData(FinalToken.Core.PaceState.OnTrack, false)]
[InlineData(FinalToken.Core.PaceState.Behind, false)]
[InlineData(FinalToken.Core.PaceState.Unknown, false)]
public void ForecastWarningFollowsState(FinalToken.Core.PaceState state, bool warning)
{
var text = Display.Forecast(new(2026, 10, 18, 14, 43, 0, TimeSpan.Zero), state);
Assert.Equal(warning, text.Contains('⚠'));
Assert.StartsWith(warning ? "⚠ 100 % on " : "At this pace 100 % on ", text);
}
[Theory]
[InlineData(1)]
[InlineData(1.25)]
[InlineData(2)]
public void DenseBarEdgesMeetOnPhysicalPixelsWithoutGaps(double scaling)
{
var first = UsageChart.BarBounds(50.13, 100, 3.17, 40, scaling);
var next = UsageChart.BarBounds(53.30, 100, 3.17, 40, scaling);
Assert.Equal(first.Right, next.Left, 6);
Assert.Equal(Math.Round(first.Left * scaling), first.Left * scaling, 6);
Assert.Equal(Math.Round(first.Right * scaling), first.Right * scaling, 6);
}
[Fact]
public void DailyChartLabelAndTooltipUseTheBucketsLocalDate()
{
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
var day = FinalToken.Core.CalendarDays.Start(new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero), zone);
Assert.Equal("10-14", Display.ChartDateLabel(day, TimeSpan.FromDays(1)));
Assert.Equal(day.DateTime.ToString("g"), Display.ChartTimestamp(day, TimeSpan.FromDays(1)));
Assert.Equal(day.DateTime.ToString("d"), Display.ChartTimestamp(day, TimeSpan.FromDays(1)));
}
[Theory]
[InlineData(null)]
+117 -12
View File
@@ -1,5 +1,6 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Headless;
using Avalonia.Interactivity;
using Avalonia.Media.Imaging;
@@ -29,23 +30,122 @@ public sealed class HeadlessTests
var shots = Environment.GetEnvironmentVariable("FINALTOKEN_SCREENSHOT_DIR") ?? Path.Combine(root.Parent!.FullName, "runs", "shots", "app");
Directory.CreateDirectory(shots);
var model = FakeData.Model();
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }) { Height = 2450 };
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { });
panel.Resources["SystemAccentColor"] = Avalonia.Media.Colors.Red;
panel.RequestedThemeVariant = ThemeVariant.Light; panel.Show(); Save(panel, "panel-light.png");
Assert.Equal($"FinalToken {typeof(Program).Assembly.GetName().Version!.ToString(3)}", panel.Title);
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Claude");
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Tokens per day");
var filters = panel.GetVisualDescendants().OfType<ComboBox>().ToArray();
filters[0].SelectedIndex = 4; filters[1].SelectedIndex = 2;
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "●" && t.Foreground?.ToString() == "#ffeb6834");
Assert.All(panel.GetVisualDescendants().OfType<ProgressBar>(), bar => Assert.True(bar.Bounds.Width <= 140, $"Share bar width {bar.Bounds.Width}"));
Assert.Single(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Current session");
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("At this pace 100 % on ", StringComparison.Ordinal) == true);
Assert.Single(panel.GetVisualDescendants().OfType<WrapPanel>(), p => p.Name == "CompositionLegend");
var codexTile = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
Assert.DoesNotContain(codexTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains('⚠') == true || t.Foreground?.ToString() == "#ffd03b3b");
var withCache = panel.GetVisualDescendants().OfType<UsageChart>().Where(c => !c.Percent).Sum(c => c.Values.Sum(v => v.Value));
panel.GetVisualDescendants().OfType<CheckBox>().Single(c => c.Content as string == "Include cache reads").IsChecked = false;
Dispatcher.UIThread.RunJobs();
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == Display.Compact(61000000));
Assert.True(panel.GetVisualDescendants().OfType<UsageChart>().Where(c => !c.Percent).Sum(c => c.Values.Sum(v => v.Value)) < withCache);
model.IncludeCacheReads = true; Dispatcher.UIThread.RunJobs();
var originalSnapshot = model.Snapshot!;
var originalHistory = model.History;
var claude = originalSnapshot.Providers.Single(p => p.Provider == Provider.Claude);
var week = claude.Windows.Single(w => w.Window.Id == "week");
model.Snapshot = originalSnapshot with { Providers = originalSnapshot.Providers.Select(p => p.Provider == Provider.Claude
? p with { Windows = p.Windows.Append(week with { Window = week.Window with { Id = "fable", Label = "Week · Fable" } }).ToArray() } : p).ToArray() };
model.History = originalHistory with { Details = originalHistory.Details.Append(originalHistory.Details.Single(d => d.Provider == Provider.Claude && d.Id == "week") with { Id = "fable" }).ToArray() };
Dispatcher.UIThread.RunJobs();
panel.GetVisualDescendants().OfType<ComboBox>().Single().SelectedIndex = 1;
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Claude · Week · Fable");
model.History = originalHistory;
model.Snapshot = originalSnapshot with { Providers = originalSnapshot.Providers.Select(p => p.Provider == Provider.Claude ? p with { Windows = [] } : p).ToArray() };
Dispatcher.UIThread.RunJobs();
Assert.Single(panel.GetVisualDescendants().OfType<DailyLimitChart>());
model.Snapshot = originalSnapshot; Dispatcher.UIThread.RunJobs();
var filters = panel.GetVisualDescendants().OfType<ToggleButton>().Where(b => b is not CheckBox).ToArray();
filters[4].IsChecked = true; filters[7].IsChecked = true;
Assert.Equal(HistoryRange.All, model.Range); Assert.Equal(Provider.Codex, model.ProviderFilter);
filters[0].SelectedIndex = 1; filters[1].SelectedIndex = 0;
filters[1].IsChecked = true; filters[5].IsChecked = true;
panel.RequestedThemeVariant = ThemeVariant.Dark; Save(panel, "panel-dark.png");
model.Snapshot = FakeData.Snapshot(DateTimeOffset.UtcNow, true); Save(panel, "panel-unavailable.png"); panel.Close();
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.Width = width; panel.Height = height; panel.RequestedThemeVariant = theme;
var stem = $"panel-{width}x{height}-{theme.ToString().ToLowerInvariant()}";
var viewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
viewport.Offset = default; Save(panel, stem + "-limits.png");
var selected = panel.GetVisualDescendants().OfType<ToggleButton>().First(b => b.Classes.Contains("segment") && b.IsChecked == true);
Assert.Equal(theme == ThemeVariant.Dark ? "#ff383835" : "#ffe1e0d9", selected.Background?.ToString());
Assert.Equal(Avalonia.Media.FontWeight.SemiBold, selected.FontWeight);
var glyph = panel.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Name == "NeutralCheckGlyph");
Assert.Equal(theme == ThemeVariant.Dark ? "#fff0efec" : "#ff0b0b0b", glyph.Foreground?.ToString());
Assert.Equal(56, panel.GetVisualDescendants().OfType<Grid>().Single(g => g.Name == "PanelHeader").Bounds.Height);
if (width == 1500)
{
var sessionTile = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Claude-session");
var weekTile = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Claude-week");
var codexLimit = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
Assert.Equal(sessionTile.Bounds.Y, weekTile.Bounds.Y); Assert.Equal(weekTile.Bounds.Y, codexLimit.Bounds.Y);
Assert.True(sessionTile.Bounds.Height < weekTile.Bounds.Height);
}
foreach (var (name, target) in new[] { ("week", "Week use per day"), ("tokens", "Tokens"), ("history", "Limit history"), ("breakdown", "Breakdown") })
{
var text = panel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == target);
var position = text.TranslatePoint(default, viewport)!.Value;
viewport.Offset = new Vector(0, viewport.Offset.Y + position.Y - 16);
Save(panel, stem + "-" + name + ".png");
}
var prior = viewport.Offset;
model.Snapshot = model.Snapshot! with { MadeAt = DateTimeOffset.UtcNow }; Dispatcher.UIThread.RunJobs();
Assert.Equal(prior, viewport.Offset);
}
panel.Width = 1000; panel.Height = 900;
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default; Save(panel, "panel-1000x900-light.png");
panel.Width = 1500; panel.Height = 1000;
model.History = originalHistory with { Details = originalHistory.Details.Select(d => d.Provider == Provider.Claude && d.Days is { } days
? d with { Days = days with { Current = days.Current.Select(day => day with { Used = null }).ToArray(), Today = null } } : d).ToArray() };
Dispatcher.UIThread.RunJobs(); Assert.Single(panel.GetVisualDescendants().OfType<DailyLimitChart>());
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.Width = width; panel.Height = height; panel.RequestedThemeVariant = theme; Dispatcher.UIThread.RunJobs();
var viewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
var heading = panel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "Week use per day");
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(panel, $"panel-{width}x{height}-{theme}-collecting-days.png");
}
model.History = originalHistory;
model.Snapshot = FakeData.Snapshot(DateTimeOffset.UtcNow, true);
Dispatcher.UIThread.RunJobs(); panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
Save(panel, "panel-unavailable.png");
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.Width = width; panel.Height = height; panel.RequestedThemeVariant = theme;
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
Save(panel, $"panel-{width}x{height}-{theme}-unavailable.png");
}
model.Diagnostics = [new(DateTimeOffset.UtcNow, Provider.Claude, "fixture", "Probe timed out. Last good sample retained.")];
Dispatcher.UIThread.RunJobs(); var expander = panel.GetVisualDescendants().OfType<Expander>().Single();
expander.BringIntoView(); Save(panel, "panel-diagnostics-collapsed.png");
expander.IsExpanded = true; panel.UpdateLayout();
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = new Vector(0, 100000);
Save(panel, "panel-diagnostics-expanded.png"); panel.Close();
Settings? saved = null;
var initial = new Settings { StartWithOs = true, StreamDeckInstallMode = InstallMode.Automatic, DismissedPluginVersion = "0.9" };
var settings = new SettingsWindow(initial, new(PluginInstallState.Outdated, "1.0", "0.9"), value => { saved = value; return Task.CompletedTask; }) { Height = 1600 };
var settings = new SettingsWindow(initial, new(PluginInstallState.Outdated, "1.0", "0.9"), value => { saved = value; return Task.CompletedTask; }, () => { });
settings.Show(); Save(settings, "settings.png");
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
settings.RequestedThemeVariant = theme;
var viewport = settings.GetVisualDescendants().OfType<ScrollViewer>().First();
viewport.Offset = default; Save(settings, $"settings-{theme}-general.png");
viewport.Offset = new Vector(0, 10000); Save(settings, $"settings-{theme}-providers.png");
}
var refresh = settings.GetVisualDescendants().OfType<NumericUpDown>().First(); refresh.Value = 25;
settings.GetVisualDescendants().OfType<CheckBox>().First().IsChecked = false;
settings.GetVisualDescendants().OfType<CheckBox>().Single(c => c.Content as string == "Ahead popups").IsChecked = false;
settings.GetVisualDescendants().OfType<TextBox>().Single(t => t.Name == "ClaudeCliPath").Text = "claude-fixture";
settings.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Save").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Assert.NotNull(saved); Assert.Equal(TimeSpan.FromSeconds(25), saved.RefreshInterval); Assert.True(saved.StartWithOs);
@@ -63,13 +163,13 @@ public sealed class HeadlessTests
Assert.Contains(cancelled.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Settings save was cancelled."); cancelled.Close();
var opened = 0;
var ahead = PopupWindow.Pace(new(Provider.Claude, "session", "Session", PaceState.Ahead, 22, DateTimeOffset.UtcNow.AddHours(1)), () => opened++);
ahead.Show(); Save(ahead, "popup-ahead.png"); Assert.False(ahead.ShowActivated);
ahead.Show(); SaveThemes(ahead, "popup-ahead"); Assert.False(ahead.ShowActivated);
ahead.MouseDown(new Point(100, 60), Avalonia.Input.MouseButton.Left); Assert.Equal(1, opened); Assert.False(ahead.IsVisible);
var behind = PopupWindow.Pace(new(Provider.Codex, "primary", "Primary", PaceState.Behind, -18, null), () => { });
behind.Show(); Save(behind, "popup-behind.png"); behind.Close();
behind.Show(); SaveThemes(behind, "popup-behind"); behind.Close();
var installed = 0; var dismissed = 0;
var ask = new PopupWindow("Stream Deck plugin", "Version 1.0 is ready.", () => { }, "Install", () => installed++, () => dismissed++);
ask.Show(); Save(ask, "popup-streamdeck-ask.png");
ask.Show(); SaveThemes(ask, "popup-streamdeck-ask");
ask.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Not now").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Assert.Equal(0, installed); Assert.Equal(1, dismissed);
var install = new PopupWindow("Stream Deck plugin", "Update ready", () => { }, "Update", () => installed++);
@@ -102,11 +202,16 @@ public sealed class HeadlessTests
Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light };
dailyWindow.Show(); Save(dailyWindow, "chart-local-day.png");
dailyWindow.MouseMove(new Point(90, 150));
Assert.Contains(day.DateTime.ToString("g"), ToolTip.GetTip(daily)?.ToString()); dailyWindow.Close();
Assert.Contains(day.DateTime.ToString("d"), ToolTip.GetTip(daily)?.ToString()); dailyWindow.Close();
popupClock.Fire(); Dispatcher.UIThread.RunJobs();
Assert.False(first.IsVisible); Assert.False(second.IsVisible);
Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed));
completion.SetResult();
void SaveThemes(Window window, string stem)
{
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{ window.RequestedThemeVariant = theme; Save(window, stem + "-" + theme + ".png"); }
}
void Save(Window window, string name, string? destination = null)
{
Dispatcher.UIThread.RunJobs();
@@ -121,7 +226,7 @@ public sealed class HeadlessTests
thread.Start(); await completion.Task; thread.Join();
}
public sealed class TestApplication : Application
{ public override void Initialize() => Styles.Add(new FluentTheme()); }
{ public override void Initialize() => Styles.Add(Ui.NeutralTheme()); }
private sealed class PopupClock : TimeProvider
{
public List<PopupTimer> Timers { get; } = [];
+86 -10
View File
@@ -5,6 +5,30 @@ namespace FinalToken.App.Tests;
public sealed class ViewModelTests
{
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void ResetDriftKeepsChartContinuousAndRealResetAddsGap(int minutes)
{
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
var window = new LimitWindow(Provider.Claude, "week", "Week", 60, now.AddDays(4), TimeSpan.FromDays(7), now.AddMinutes(-1), "fixture");
var first = window with { SampleTime = CalendarDays.Start(now).AddHours(-1), UsedPercent = 40, ResetsAt = window.ResetsAt!.Value.AddMinutes(minutes) };
store.AddLimits([first]);
store.AddLimits([window with { SampleTime = now.AddHours(-3), UsedPercent = 50, ResetsAt = window.ResetsAt!.Value.AddMinutes(-minutes) }]);
store.AddLimits([window]);
Snapshot SnapshotFor(LimitWindow w, DateTimeOffset time) => new() { MadeAt = time, RefreshInterval = TimeSpan.FromMinutes(1),
Providers = [new(Provider.Claude, ProviderStatus.Available, null, [new(w, Pace.Calculate(w, time))], new(), null, new())] };
var view = PanelViewModel.QueryHistory(store, SnapshotFor(window, now), HistoryRange.All, null, now);
Assert.All(Assert.Single(view.Limits).Values, v => Assert.False(v.BreakBefore));
var detail = Assert.Single(view.Details);
Assert.Equal(first.SampleTime, detail.Since); Assert.Equal(20, detail.Days!.Today); Assert.NotNull(detail.Recent);
var next = window with { ResetsAt = window.ResetsAt!.Value.AddDays(7), SampleTime = now.AddDays(7).AddMinutes(-1), UsedPercent = 5 };
store.AddLimits([next]);
var nextView = PanelViewModel.QueryHistory(store, SnapshotFor(next, now.AddDays(7)), HistoryRange.All, null, now.AddDays(7));
Assert.Equal(1, Assert.Single(nextView.Limits).Values.Count(v => v.BreakBefore));
Assert.True(Assert.Single(nextView.Limits).Values[^1].BreakBefore);
}
[Theory]
[InlineData(HistoryRange.Hours24, 1)]
[InlineData(HistoryRange.Days7, 7)]
@@ -55,6 +79,43 @@ public sealed class ViewModelTests
}
[Fact] public void DesktopEntryQuotesExecutableAndEscapesFieldCodes()
{ var text = OsStartup.DesktopEntry("/opt/Final Token/100%/app"); Assert.Contains("Exec=\"/opt/Final Token/100%%/app\"", text); Assert.Contains("Terminal=false", text); }
[Fact] public void BreakdownKeepsTopEightAndOtherWithoutLosingCounts()
{
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
for (var i = 0; i < 110; i++) store.Add(new(Provider.Claude, now.AddHours(-1), "model", $"project-{i}", new(Total: i + 1), $"{i}"));
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, null, now);
Assert.Equal(9, view.Projects.Count); Assert.Equal("project-109", view.Projects[0].Name);
Assert.Equal("Other (102)", view.Projects[^1].Name); Assert.Equal(6105, view.Projects.Sum(r => r.Counts.Total));
Assert.Equal(1, view.Projects.Sum(r => r.Share), 8);
}
[Fact] public void FilteredModelSeriesUseSixAlphabeticSlotsAndOther()
{
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
for (var i = 9; i >= 0; i--) store.Add(new(Provider.Claude, now.AddHours(-1), $"model-{i}", "p", new(CacheRead: 2, Total: 10), $"{i}"));
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, Provider.Claude, now);
Assert.Equal(7, view.Hourly.Count); Assert.Equal(40, view.Hourly.Single(p => p.Series == "Other").Value);
Assert.Equal(100, view.Hourly.Sum(p => p.Value)); Assert.Equal(20, view.Hourly.Sum(p => p.CacheRead));
Assert.Equal(view.Hourly.Select(p => p.Series).Order(), view.Daily.Select(p => p.Series).Order());
Assert.DoesNotContain(view.Hourly, p => p.Series == "model-6");
}
[Fact] public void ProjectNamesKeepTwoSegmentsAndDisambiguateCollisions()
{
var names = PanelWindow.ShortProjectNames(["D:/First/Shared/App", "D:/Second/Shared/App", "/work/Only/App", "Unknown"]);
Assert.Equal(["First/Shared/App", "Second/Shared/App", "Only/App", "Unknown"], names);
}
[Fact] public void ModelBreakdownKeepsActualProviderIdentityForDots()
{
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
store.Add(new(Provider.Claude, now.AddHours(-1), "arbitrary-name", "p", new(Total: 10), "a"));
store.Add(new(Provider.Codex, now.AddHours(-1), "shared-name", "p", new(Total: 20), "b"));
store.Add(new(Provider.Claude, now.AddHours(-1), "shared-name", "p", new(Total: 30), "c"));
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, null, now);
Assert.Equal([Provider.Claude], view.Models.Single(r => r.Name == "arbitrary-name").Providers);
Assert.Equal([Provider.Claude, Provider.Codex], view.Models.Single(r => r.Name == "shared-name").Providers);
}
[Fact] public void DesktopEntryRejectsInjectedLine() => Assert.Throws<ArgumentException>(() => OsStartup.DesktopEntry("/app\nExec=other"));
[Fact] public void DesktopEntryEscapesCommandCharactersAtBothParsingLevels()
{
@@ -68,22 +129,37 @@ internal static class FakeData
public static Snapshot Snapshot(DateTimeOffset now, bool unavailable = false) => new()
{
MadeAt = now, RefreshInterval = TimeSpan.FromSeconds(60), Providers =
[new(Provider.Claude, ProviderStatus.Available, null, [Window(Provider.Claude, "session", "Current session", 68, now, 5, 3), Window(Provider.Claude, "week", "Current week", 32, now, 168, 48)],
new(12000, 18000, 2000, 4200, 0, 36200), new(4000, 6000, 1000, 1600, 0, 12600), new(85000, 92000, 16000, 28000, 0, 221000)),
[new(Provider.Claude, ProviderStatus.Available, null, [Window(Provider.Claude, "session", "Session · 5 h", 12, now, 5, 1), Window(Provider.Claude, "week", "Week · all models", 70, now, 168, 84)],
new(12000000, 218000000, 2000000, 47000000, 0, 279000000), new(4000000, 6000000, 1000000, 1600000, 0, 12600000), new(85000000, 1920000000, 16000000, 259000000, 0, 2280000000)),
new(Provider.Codex, unavailable ? ProviderStatus.Unavailable : ProviderStatus.Available, unavailable ? "CLI is not installed. Token history remains available." : null,
[Window(Provider.Codex, "primary", "Primary · 5 hours", 12, now, 5, 1), Window(Provider.Codex, "secondary", "Secondary · 7 days", 62, now, 168, 80)],
new(72000, 42000, 0, 8400, 2100, 80400), new(23000, 10000, 0, 3200, 700, 26200), new(340000, 150000, 0, 38000, 11000, 378000))]
[Window(Provider.Codex, "secondary", "Week", 86, now, 168, 24)],
new(72000000, 42000000, 0, 8400000, 2100000, 80400000), null, new(340000000, 150000000, 0, 38000000, 11000000, 378000000))]
};
private static WindowSnapshot Window(Provider provider, string id, string label, double percent, DateTimeOffset now, int hours, int resetHours)
{ var w = new LimitWindow(provider, id, label, percent, now.AddHours(resetHours), TimeSpan.FromHours(hours), now.AddMinutes(-3), "fixture"); return new(w, Pace.Calculate(w, now)); }
public static PanelViewModel Model(bool unavailable = false)
{
var now = DateTimeOffset.UtcNow;
var hourly = Enumerable.Range(0, 24).SelectMany(i => new[] { new ChartValue(now.AddHours(-24 + i), "Claude", 1000 + i * 210), new ChartValue(now.AddHours(-24 + i), "Codex", 2000 + (i % 5) * 800) }).ToArray();
var daily = Enumerable.Range(0, 7).SelectMany(i => new[] { new ChartValue(now.AddDays(-7 + i), "Claude", 20000 + i * 2000), new ChartValue(now.AddDays(-7 + i), "Codex", 30000 + i * 5000) }).ToArray();
return new() { Snapshot = Snapshot(now, unavailable), Message = "Updated just now · local CLI data", History = new(hourly, daily,
[new("Claude · Current session", Enumerable.Range(0, 8).Select(i => new ChartValue(now.AddMinutes(-140 + i * 20), "session", i * 8 + 12, i * 6)).ToArray())],
[new("claude-sonnet", new(Total: 221000), 0.37), new("gpt-6.1-sol", new(Total: 378000), 0.63)], [new("FinalToken", new(Total: 599000), 1)]),
Diagnostics = [new(now.AddMinutes(-4), Provider.Claude, "sample-age", "Latest limit sample is three minutes old.")] };
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-fake", Guid.NewGuid().ToString("N")), new DiagnosticLog());
var snapshot = Snapshot(now, unavailable);
foreach (var provider in snapshot.Providers)
{
for (var i = 0; i < 168; i++)
{
var input = 1000000 + i * 10000; var cache = input * 8;
store.Add(new(provider.Provider, now.AddHours(-168 + i), provider.Provider == Provider.Claude ? "claude-fable" : "gpt-6.1-sol",
$"D:/Projects/Customer-{i % 110}/Workspace/Project-{i % 110}",
provider.Provider == Provider.Claude ? new(input, cache, 200000, 500000, 0, input + cache + 700000) : new(input + cache, cache, 0, 500000, 100000, input + cache + 500000), $"{provider.Provider}-{i}"));
}
foreach (var ws in provider.Windows.Where(w => w.Window.Length > TimeSpan.FromDays(1)))
{
var w = ws.Window; var start = w.ResetsAt!.Value - w.Length!.Value;
for (var i = 0; i <= (int)(now - start).TotalHours; i += 3)
store.AddLimits([w with { SampleTime = start.AddHours(i), UsedPercent = w.UsedPercent * i / (now - start).TotalHours }]);
for (var i = 0; i < 168; i += 6)
store.AddLimits([w with { ResetsAt = w.ResetsAt.Value.AddDays(-7), SampleTime = start.AddDays(-7).AddHours(i), UsedPercent = i * .5 }]);
}
}
return new() { Snapshot = snapshot, Message = "Updated just now", History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
}
}