app: let the settings hide limit windows and give the app an icon #18

Merged
schmidt.florian merged 3 commits from 17-hide-limits-icon into master 2026-11-04 19:41:46 +01:00
17 changed files with 384 additions and 19 deletions
+2
View File
@@ -120,6 +120,8 @@ a screenshot of each changed view: compiling is not working.
## Tools ## Tools
- `tools/icon/make_icon.py`: renders the shared app icon with development-only Pillow 11.3.0.
Run `python -B tools/icon/make_icon.py`; test with `python -B tools/icon/test_make_icon.py`.
- `tools/docs/check_docs.py`: the documentation check; its tests are - `tools/docs/check_docs.py`: the documentation check; its tests are
`python -B tools/docs/test_check_docs.py`. `python -B tools/docs/test_check_docs.py`.
- `tools/gitea.sh`: calls the Gitea API with the stored git credential or `GITEA_TOKEN`. - `tools/gitea.sh`: calls the Gitea API with the stored git credential or `GITEA_TOKEN`.
+12 -2
View File
@@ -270,13 +270,23 @@ better, and overstates `u₀` by the use in that sample's hour before the sample
ahead or behind, at most once per window and state until the state changes again, with ahead or behind, at most once per window and state until the state changes again, with
hysteresis of 2 points so a value on the threshold cannot flap. Popups can be turned off per hysteresis of 2 points so a value on the threshold cannot flap. Popups can be turned off per
provider and per state. provider and per state.
- **Hidden windows.** The settings can hide single limit windows, such as Claude's Fable week.
A hidden window is a window series ([D7](#d7--pace)), so it stays hidden when Codex moves it to
another slot. It leaves every part of the panel and gives no popups. Its samples are still
recorded, and the snapshot still carries it
([D9](#d9--the-snapshot-file-is-the-apps-only-output-to-other-processes)). Nothing is hidden
by default.
- **Icon.** One icon, rendered from a committed source by a repository tool, is the Windows
executable's icon, the window icon and the tray icon.
- **Linux.** The app runs on Avalonia's X11 backend, under XWayland on CachyOS's KDE Plasma - **Linux.** The app runs on Avalonia's X11 backend, under XWayland on CachyOS's KDE Plasma
Wayland session, because Wayland clients cannot place their own windows. Wayland session, because Wayland clients cannot place their own windows.
**Why.** R1, R4, R5. Avalonia is the cross-platform .NET UI toolkit with NativeAOT support. A **Why.** R1, R4, R5. Avalonia is the cross-platform .NET UI toolkit with NativeAOT support. A
chart library would add reflection and size for three chart types. chart library would add reflection and size for three chart types. A limit that a user does not
use only adds noise to the panel, and an app without its own icon is hard to find in the taskbar.
**Gives up.** Native OS notification styling, and a native Wayland window. **Gives up.** Native OS notification styling, and a native Wayland window. A hidden window's
pace goes unnoticed until it is shown again.
## D9 — The snapshot file is the app's only output to other processes ## D9 — The snapshot file is the app's only output to other processes
+15
View File
@@ -0,0 +1,15 @@
using Avalonia.Controls;
using Avalonia.Platform;
namespace FinalToken.App;
public static class AppIcon
{
// Keep the ICO's multiple sizes on Windows; X11 uses the same artwork as a PNG (D8).
public static WindowIcon Load()
{
var extension = OperatingSystem.IsWindows() ? "ico" : "png";
using var stream = AssetLoader.Open(new Uri($"avares://FinalToken/Assets/FinalToken.{extension}"));
return new WindowIcon(stream);
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

+6 -11
View File
@@ -1,9 +1,6 @@
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using Avalonia.Themes.Fluent;
using Avalonia.Threading; using Avalonia.Threading;
using FinalToken.Core; using FinalToken.Core;
using FinalToken.Core.StreamDeck; using FinalToken.Core.StreamDeck;
@@ -49,10 +46,10 @@ public sealed class DesktopApp : Application
CreateTray(); panel.Show(); CreateTray(); panel.Show();
if (engine is not null) if (engine is not null)
{ {
engine.SnapshotChanged += snapshot => Dispatcher.UIThread.Post(() => { model.Snapshot = snapshot; model.Diagnostics = engine.RecentDiagnostics; model.Message = "Updated " + snapshot.MadeAt.LocalDateTime.ToString("g"); Run(LoadHistory); }); engine.SnapshotChanged += snapshot => Dispatcher.UIThread.Post(() => { model.ApplySnapshot(snapshot, engine.Settings); model.Diagnostics = engine.RecentDiagnostics; model.Message = "Updated " + snapshot.MadeAt.LocalDateTime.ToString("g"); Run(LoadHistory); });
engine.PopupRequested += alert => Dispatcher.UIThread.Post(() => { if (!quitting) popups.Pace(alert); }); engine.PopupRequested += alert => Dispatcher.UIThread.Post(() => { if (!quitting) popups.Pace(alert); });
engine.ActivationRequested += () => Dispatcher.UIThread.Post(OpenPanel); engine.ActivationRequested += () => Dispatcher.UIThread.Post(OpenPanel);
model.Snapshot = engine.CurrentSnapshot; if (engine.CurrentSnapshot is { } snapshot) model.ApplySnapshot(snapshot, engine.Settings);
model.ProbeInterval = engine.Settings.ProbeInterval; model.ProbeInterval = engine.Settings.ProbeInterval;
ageTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) }; ageTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
ageTimer.Tick += (_, _) => { if (panel.IsVisible) model.Diagnostics = engine.RecentDiagnostics; }; ageTimer.Tick += (_, _) => { if (panel.IsVisible) model.Diagnostics = engine.RecentDiagnostics; };
@@ -75,11 +72,7 @@ public sealed class DesktopApp : Application
var menu = new NativeMenu(); var menu = new NativeMenu();
foreach (var (label, action) in new (string, Action)[] { ("Open", OpenPanel), ("Refresh now", () => Run(Refresh)), ("Settings", OpenSettings), ("Quit", () => Run(Quit)) }) foreach (var (label, action) in new (string, Action)[] { ("Open", OpenPanel), ("Refresh now", () => Run(Refresh)), ("Settings", OpenSettings), ("Quit", () => Run(Quit)) })
{ var item = new NativeMenuItem(label); item.Click += (_, _) => action(); menu.Items.Add(item); } { var item = new NativeMenuItem(label); item.Click += (_, _) => action(); menu.Items.Add(item); }
using var bitmap = new RenderTargetBitmap(new PixelSize(32, 32)); tray = new TrayIcon { Icon = AppIcon.Load(), ToolTipText = "FinalToken", Menu = menu, IsVisible = true };
using (var context = bitmap.CreateDrawingContext())
{ context.DrawRectangle(Brush.Parse("#3878D4"), null, new Rect(0, 0, 32, 32), 7, 7); context.DrawLine(new Pen(Brushes.White, 4), new(9, 9), new(23, 9)); context.DrawLine(new Pen(Brushes.White, 4), new(16, 9), new(16, 25)); }
using var stream = new MemoryStream(); bitmap.Save(stream, PngBitmapEncoderOptions.Default); stream.Position = 0;
tray = new TrayIcon { Icon = new WindowIcon(stream), ToolTipText = "FinalToken", Menu = menu, IsVisible = true };
tray.Clicked += (_, _) => OpenPanel(); tray.Clicked += (_, _) => OpenPanel();
TrayIcon.SetIcons(this, [tray]); TrayIcon.SetIcons(this, [tray]);
} }
@@ -105,7 +98,7 @@ public sealed class DesktopApp : Application
{ {
if (engine is null) return; if (engine is null) return;
if (settingsWindow is not null) { settingsWindow.Activate(); return; } if (settingsWindow is not null) { settingsWindow.Activate(); return; }
settingsWindow = new SettingsWindow(engine.Settings, pluginStatus, value => settingsSave = SaveSettings(value), () => Run(Quit)); settingsWindow = new SettingsWindow(engine.Settings, pluginStatus, value => settingsSave = SaveSettings(value), () => Run(Quit), snapshot: engine.CurrentSnapshot);
settingsWindow.Closed += (_, _) => settingsWindow = null; settingsWindow.Closed += (_, _) => settingsWindow = null;
settingsWindow.Show(); settingsWindow.Show();
} }
@@ -119,6 +112,8 @@ public sealed class DesktopApp : Application
catch { await OsStartup.ApplyAsync(previous.StartWithOs); throw; } catch { await OsStartup.ApplyAsync(previous.StartWithOs); throw; }
if (quitting) return; if (quitting) return;
model.ProbeInterval = value.ProbeInterval; model.ProbeInterval = value.ProbeInterval;
if (engine.CurrentSnapshot is { } snapshot) model.ApplySnapshot(snapshot, value);
await LoadHistory();
await CheckPlugin(); await CheckPlugin();
if (!quitting) await engine.RefreshNowAsync(); if (!quitting) await engine.RefreshNowAsync();
} }
+2
View File
@@ -5,8 +5,10 @@
<PublishAot>true</PublishAot> <PublishAot>true</PublishAot>
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault> <AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationIcon>Assets/FinalToken.ico</ApplicationIcon>
</PropertyGroup> </PropertyGroup>
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup> <ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
<ItemGroup><AvaloniaResource Include="Assets/*" /></ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Avalonia.Desktop" /> <PackageReference Include="Avalonia.Desktop" />
<PackageReference Include="Avalonia.Themes.Fluent" /> <PackageReference Include="Avalonia.Themes.Fluent" />
+16
View File
@@ -36,6 +36,22 @@ public partial class PanelViewModel : ObservableObject
} }
public TimeSpan ProbeInterval { get; set; } = TimeSpan.FromMinutes(5); public TimeSpan ProbeInterval { get; set; } = TimeSpan.FromMinutes(5);
// D8: only the panel's copy loses hidden windows; D9 totals and the engine snapshot stay intact.
public void ApplySnapshot(Snapshot snapshot, Settings settings)
{
var visible = snapshot with { Providers = snapshot.Providers.Select(p => p with
{ Windows = p.Windows.Where(w => !settings.For(p.Provider).IsHidden(w.Window)).ToArray() }).ToArray() };
var windows = visible.Providers.SelectMany(p => p.Windows).Select(w => w.Window).ToArray();
// Retire old window views immediately, before the replacement history query finishes.
History = History with
{
Limits = History.Limits.Where(l => l.Window is { } w && windows.Any(v => WindowSeries.For(v).Matches(w.Window))).ToArray(),
Details = History.Details.Where(d => windows.Any(w => w.Provider == d.Provider && w.Id == d.Id)).ToArray(),
Resets = History.Resets.Where(r => windows.Any(w => WindowSeries.For(w).Matches(r.Window))).ToArray()
};
Snapshot = visible;
}
public static DateTimeOffset RangeStart(HistoryRange range, DateTimeOffset now) => range switch public static DateTimeOffset RangeStart(HistoryRange range, DateTimeOffset now) => range switch
{ {
HistoryRange.Hours24 => now.AddHours(-24), HistoryRange.Days7 => now.AddDays(-7), HistoryRange.Hours24 => now.AddHours(-24), HistoryRange.Days7 => now.AddDays(-7),
+1
View File
@@ -29,6 +29,7 @@ public sealed class PanelWindow : Window
{ {
this.model = model; this.model = model;
this.clock = clock ?? TimeProvider.System; this.clock = clock ?? TimeProvider.System;
Icon = AppIcon.Load();
Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}"; Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}";
Width = 1280; Height = 900; MinWidth = 960; MinHeight = 500; Ui.Theme(this); Width = 1280; Height = 900; MinWidth = 960; MinHeight = 500; Ui.Theme(this);
var brand = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center }; var brand = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };
+19 -5
View File
@@ -8,8 +8,10 @@ namespace FinalToken.App;
public sealed class SettingsWindow : Window public sealed class SettingsWindow : Window
{ {
public SettingsWindow(Settings initial, PluginInstallStatus status, Func<Settings, Task> save, Action? quit = null, Action<string>? openFolder = null) public SettingsWindow(Settings initial, PluginInstallStatus status, Func<Settings, Task> save, Action? quit = null, Action<string>? openFolder = null,
Snapshot? snapshot = null)
{ {
Icon = AppIcon.Load();
Title = "FinalToken settings"; Width = 760; Height = 900; MinWidth = 600; MinHeight = 500; Ui.Theme(this); Title = "FinalToken settings"; Width = 760; Height = 900; MinWidth = 600; MinHeight = 500; Ui.Theme(this);
var body = new StackPanel { Spacing = 16, Margin = new Thickness(24) }; var body = new StackPanel { Spacing = 16, Margin = new Thickness(24) };
body.Children.Add(Ui.Text("Settings", 24)); body.Children.Add(Ui.Text("Settings", 24));
@@ -27,8 +29,8 @@ public sealed class SettingsWindow : Window
var codexPopups = PopupControls(popups, "Codex", initial.Codex); var codexPopups = PopupControls(popups, "Codex", initial.Codex);
body.Children.Add(Ui.Card(popups)); body.Children.Add(Ui.Card(popups));
var providers = Ui.Stack(Ui.Text("Providers", 15)); var providers = Ui.Stack(Ui.Text("Providers", 15));
var claude = ProviderControls(providers, "Claude", initial.Claude); var claude = ProviderControls(providers, Provider.Claude, initial.Claude, snapshot);
var codex = ProviderControls(providers, "Codex", initial.Codex); var codex = ProviderControls(providers, Provider.Codex, initial.Codex, snapshot);
body.Children.Add(Ui.Card(providers)); 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 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; var selectedMode = initial.StreamDeckInstallMode;
@@ -96,12 +98,24 @@ public sealed class SettingsWindow : Window
parent.Children.Add(row); parent.Children.Add(row);
return value => value with { PopupsEnabled = enabled.IsChecked == true, PopupAhead = ahead.IsChecked == true, PopupBehind = behind.IsChecked == true }; 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) private static Func<ProviderSettings> ProviderControls(StackPanel parent, Provider provider, ProviderSettings config, Snapshot? snapshot)
{ {
var name = provider.ToString();
parent.Children.Add(Ui.Text(name)); var enabled = Check(parent, "Enabled", config.Enabled); parent.Children.Add(Ui.Text(name)); var enabled = Check(parent, "Enabled", config.Enabled);
enabled.Name = name + "Enabled"; enabled.Name = name + "Enabled";
parent.Children.Add(Ui.Text("CLI path (empty uses PATH)", 12, "Secondary")); 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); 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() }; var known = (snapshot?.Providers.Where(p => p.Provider == provider).SelectMany(p => p.Windows).Select(w => HiddenLimitWindow.For(w.Window)) ?? [])
.Concat(config.HiddenWindows).DistinctBy(w => w.Series(provider)).ToArray();
var windows = new List<(HiddenLimitWindow Window, CheckBox Show)>();
foreach (var window in known)
{
var show = Check(parent, "Show " + window.Label, !config.IsHidden(window.Series(provider)));
show.Name = name + "Window" + windows.Count;
windows.Add((window, show));
}
if (known.Length == 0) parent.Children.Add(Ui.Text("No known limit windows", 12, "Muted"));
return () => config with { Enabled = enabled.IsChecked == true, CliPath = string.IsNullOrWhiteSpace(path.Text) ? null : path.Text.Trim(),
HiddenWindows = windows.Where(w => w.Show.IsChecked != true).Select(w => w.Window).ToArray() };
} }
} }
+1
View File
@@ -54,6 +54,7 @@ public sealed class PopupDecider
} }
states[key] = next; states[key] = next;
if (previous == next || next is not (PaceState.Ahead or PaceState.Behind) || if (previous == next || next is not (PaceState.Ahead or PaceState.Behind) ||
settings.For(window.Provider).IsHidden(window) ||
!settings.For(window.Provider).Enabled || !settings.For(window.Provider).PopupsEnabled || !settings.For(window.Provider).Enabled || !settings.For(window.Provider).PopupsEnabled ||
(next == PaceState.Ahead ? !settings.PopupAhead || !settings.For(window.Provider).PopupAhead : (next == PaceState.Ahead ? !settings.PopupAhead || !settings.For(window.Provider).PopupAhead :
!settings.PopupBehind || !settings.For(window.Provider).PopupBehind)) return null; !settings.PopupBehind || !settings.For(window.Provider).PopupBehind)) return null;
+28 -1
View File
@@ -2,6 +2,12 @@ using System.Text.Json;
namespace FinalToken.Core; namespace FinalToken.Core;
public sealed record HiddenLimitWindow(string Name, TimeSpan? Length, string Label)
{
public static HiddenLimitWindow For(LimitWindow window) => new(WindowSeries.For(window).Name, window.Length, window.Label);
public WindowSeries Series(Provider provider) => new(provider, Name, Length);
}
public sealed record ProviderSettings public sealed record ProviderSettings
{ {
// Setters let source-generated JSON construct defaults before assigning present properties. // Setters let source-generated JSON construct defaults before assigning present properties.
@@ -10,6 +16,27 @@ public sealed record ProviderSettings
public bool PopupAhead { get; set; } = true; public bool PopupAhead { get; set; } = true;
public bool PopupBehind { get; set; } = true; public bool PopupBehind { get; set; } = true;
public string? CliPath { get; set; } public string? CliPath { get; set; }
public IReadOnlyList<HiddenLimitWindow> HiddenWindows { get; set; } = [];
// D8: visibility follows the D7 series, never a Codex slot or the current reset.
public bool IsHidden(LimitWindow window) => IsHidden(WindowSeries.For(window));
public bool IsHidden(WindowSeries series) => HiddenWindows.Any(hidden => hidden.Series(series.Provider) == series);
[System.Text.Json.Serialization.JsonIgnore]
public bool IsValid => HiddenWindows is not null && HiddenWindows.All(hidden => hidden is not null &&
!string.IsNullOrWhiteSpace(hidden.Name) && !string.IsNullOrWhiteSpace(hidden.Label) &&
(hidden.Length is null || hidden.Length > TimeSpan.Zero));
public bool Equals(ProviderSettings? other) => other is not null && Enabled == other.Enabled &&
PopupsEnabled == other.PopupsEnabled && PopupAhead == other.PopupAhead && PopupBehind == other.PopupBehind &&
CliPath == other.CliPath && (ReferenceEquals(HiddenWindows, other.HiddenWindows) ||
HiddenWindows is not null && other.HiddenWindows is not null && HiddenWindows.SequenceEqual(other.HiddenWindows));
public override int GetHashCode()
{
var hash = new HashCode();
hash.Add(Enabled); hash.Add(PopupsEnabled); hash.Add(PopupAhead); hash.Add(PopupBehind); hash.Add(CliPath);
if (HiddenWindows is not null) foreach (var window in HiddenWindows) hash.Add(window);
return hash.ToHashCode();
}
} }
public sealed record Settings public sealed record Settings
@@ -30,7 +57,7 @@ public sealed record Settings
[System.Text.Json.Serialization.JsonIgnore] [System.Text.Json.Serialization.JsonIgnore]
public bool IsValid => RefreshInterval > TimeSpan.Zero && RefreshInterval <= TimeSpan.FromSeconds(60) && public bool IsValid => RefreshInterval > TimeSpan.Zero && RefreshInterval <= TimeSpan.FromSeconds(60) &&
ProbeInterval >= TimeSpan.FromMinutes(1) && ProbeInterval <= TimeSpan.FromMinutes(60) && ProbeInterval >= TimeSpan.FromMinutes(1) && ProbeInterval <= TimeSpan.FromMinutes(60) &&
double.IsFinite(PaceThreshold) && PaceThreshold is > 0 and <= 100 && Claude is not null && Codex is not null && double.IsFinite(PaceThreshold) && PaceThreshold is > 0 and <= 100 && Claude is { IsValid: true } && Codex is { IsValid: true } &&
Enum.IsDefined(StreamDeckInstallMode); Enum.IsDefined(StreamDeckInstallMode);
} }
@@ -435,6 +435,7 @@ public sealed class HeadlessTests
Assert.False(first.IsVisible); Assert.False(second.IsVisible); Assert.False(first.IsVisible); Assert.False(second.IsVisible);
Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed)); Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed));
ResetViews.Verify((window, name) => Save(window, name)); ResetViews.Verify((window, name) => Save(window, name));
HiddenWindowViews.Verify((window, name) => Save(window, name));
completion.SetResult(); completion.SetResult();
void SaveThemes(Window window, string stem) void SaveThemes(Window window, string stem)
{ {
@@ -0,0 +1,107 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Styling;
using Avalonia.Threading;
using Avalonia.VisualTree;
using FinalToken.Core;
using FinalToken.Core.StreamDeck;
using Xunit;
namespace FinalToken.App.Tests;
internal static class HiddenWindowViews
{
// Called by the shared headless fixture on its dedicated UI thread.
public static void Verify(Action<Window, string> save)
{
var clock = new FixedClock();
var now = clock.GetUtcNow();
var all = new LimitWindow(Provider.Claude, "week (all models)", "Current week (all models)", 60,
now.AddDays(3), TimeSpan.FromDays(7), now, "fixture");
var fable = all with { Id = "week (fable)", Label = "Current week (Fable)", UsedPercent = 30 };
var codex = all with { Provider = Provider.Codex, Id = "codex:primary", Label = "Week", UsedPercent = 40 };
var session = new HiddenLimitWindow("session", TimeSpan.FromHours(5), "Current session");
var snapshot = new Snapshot { MadeAt = now, RefreshInterval = TimeSpan.FromMinutes(1), Providers =
[new(Provider.Claude, ProviderStatus.Available, null, [View(all), View(fable)], new(Total: 100), null, new(Total: 500), now.AddDays(-4), all.Id),
new(Provider.Codex, ProviderStatus.Available, null, [View(codex)], new(Total: 200), null, new(Total: 800), now.AddDays(-4), codex.Id)] };
var initial = new Settings { Claude = new() { HiddenWindows = [HiddenLimitWindow.For(fable), session] },
Codex = new() { HiddenWindows = [HiddenLimitWindow.For(codex with { Id = "codex:secondary" })] } };
Settings? saved = null;
var settings = new SettingsWindow(initial, new(PluginInstallState.NoHostFound), value => { saved = value; return Task.CompletedTask; }, snapshot: snapshot);
settings.Show(); Dispatcher.UIThread.RunJobs();
Assert.NotNull(settings.Icon);
var choices = settings.GetVisualDescendants().OfType<NeutralCheckBox>().Where(c => c.Content is string text && text.StartsWith("Show ", StringComparison.Ordinal)).ToArray();
Assert.Equal(["Show Current week (all models)", "Show Current week (Fable)", "Show Current session", "Show Week"], choices.Select(c => c.Content as string));
Assert.True(choices[0].IsChecked); Assert.All(choices.Skip(1), c => Assert.False(c.IsChecked));
var viewport = settings.GetVisualDescendants().OfType<ScrollViewer>().First();
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
settings.RequestedThemeVariant = theme; Dispatcher.UIThread.RunJobs();
var title = settings.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Text == "Providers");
viewport.Offset = new Vector(0, viewport.Offset.Y + title.TranslatePoint(default, viewport)!.Value.Y - 16);
save(settings, $"hidden-settings-providers-{theme}.png");
}
choices[0].IsChecked = false; choices[1].IsChecked = true; choices[2].IsChecked = true;
settings.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Save").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Assert.NotNull(saved);
Assert.Equal(HiddenLimitWindow.For(all), Assert.Single(saved.Claude.HiddenWindows));
Assert.True(saved.Codex.IsHidden(codex));
Assert.Equal(2, initial.Claude.HiddenWindows.Count); // Cancel/save must not mutate the caller's value.
var emptySettings = new SettingsWindow(new(), new(PluginInstallState.NoHostFound), _ => Task.CompletedTask);
emptySettings.Show(); Dispatcher.UIThread.RunJobs();
Assert.Equal(2, emptySettings.GetVisualDescendants().OfType<TextBlock>().Count(t => t.Text == "No known limit windows"));
emptySettings.Close();
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-hidden", Guid.NewGuid().ToString("N")), new(), clock);
foreach (var window in new[] { all, fable, codex })
store.AddLimits([window with { SampleTime = now.AddHours(-30), UsedPercent = 10 }, window]);
var model = new PanelViewModel { Snapshot = snapshot,
History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }, clock);
panel.Show(); Dispatcher.UIThread.RunJobs();
Assert.NotNull(panel.Icon); Assert.Equal(3, panel.GetVisualDescendants().OfType<BurnUpChart>().Count());
Assert.Equal(2, panel.GetVisualDescendants().OfType<ComboBox>().Count());
// Select Fable in both selectors before hiding it, exercising stale selection/history retirement.
foreach (var selector in panel.GetVisualDescendants().OfType<ComboBox>()) selector.SelectedIndex = 1;
var hidden = new Settings { Claude = initial.Claude };
model.ApplySnapshot(snapshot, hidden); Dispatcher.UIThread.RunJobs();
VerifyNoFable(); // Applies at once, even while the replacement history is pending.
model.History = PanelViewModel.QueryHistory(store, model.Snapshot!, HistoryRange.Days7, null, now);
Dispatcher.UIThread.RunJobs(); VerifyNoFable();
Assert.Equal(2, model.History.Limits.Count); Assert.Equal(2, model.History.Resets.Count); Assert.Equal(2, model.History.Details.Count);
Assert.Equal(snapshot.Providers[0].Week, model.Snapshot!.Providers[0].Week);
Assert.Equal(snapshot.Providers[0].WeekStart, model.Snapshot.Providers[0].WeekStart);
Assert.Equal(all.Id, model.Snapshot.Providers[0].WeekWindow);
Assert.Equal(2, snapshot.Providers[0].Windows.Count);
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.RequestedThemeVariant = theme;
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
save(panel, $"hidden-panel-top-{theme}.png");
}
model.ApplySnapshot(snapshot, hidden with { Claude = new() { HiddenWindows = [HiddenLimitWindow.For(all), HiddenLimitWindow.For(fable)] } });
Dispatcher.UIThread.RunJobs();
Assert.DoesNotContain(panel.GetVisualDescendants().OfType<Border>(), b => b.Name?.StartsWith("LimitTile-Claude-", StringComparison.Ordinal) == true);
Assert.Single(panel.GetVisualDescendants().OfType<BurnUpChart>());
Assert.Single(panel.GetVisualDescendants().OfType<DailyLimitChart>());
Assert.Single(panel.GetVisualDescendants().OfType<ResetCard>());
model.ApplySnapshot(snapshot, new());
model.History = PanelViewModel.QueryHistory(store, model.Snapshot!, HistoryRange.Days7, null, now);
Dispatcher.UIThread.RunJobs();
Assert.Equal(3, panel.GetVisualDescendants().OfType<BurnUpChart>().Count());
Assert.Equal(2, panel.GetVisualDescendants().OfType<ComboBox>().Count());
panel.Close();
WindowSnapshot View(LimitWindow w) => new(w, Pace.Calculate(w, now));
void VerifyNoFable()
{
Assert.DoesNotContain(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains("Fable", StringComparison.Ordinal) == true);
Assert.DoesNotContain(panel.GetVisualDescendants().OfType<Border>(), b => b.Name == "LimitTile-Claude-week (fable)");
Assert.Contains(panel.GetVisualDescendants().OfType<Border>(), b => b.Name == "LimitTile-Claude-week (all models)");
Assert.Empty(panel.GetVisualDescendants().OfType<ComboBox>());
Assert.Equal(2, panel.GetVisualDescendants().OfType<BurnUpChart>().Count());
Assert.Equal(2, panel.GetVisualDescendants().OfType<ResetCard>().Count());
}
}
}
@@ -0,0 +1,77 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class HiddenWindowTests
{
private static readonly DateTimeOffset Now = new(2026, 10, 18, 12, 0, 0, TimeSpan.Zero);
private static LimitWindow Week => new(Provider.Codex, "codex:secondary", "Week", 80,
Now.AddDays(3.5), TimeSpan.FromDays(7), Now, "fixture");
[Fact]
public async Task HiddenWindowsRoundTripWithSeriesLengthAndAbsentLabel()
{
using var directory = new TestDirectory();
var settings = new Settings
{
Claude = new() { HiddenWindows = [new("week (fable)", TimeSpan.FromDays(7), "Current week (Fable)"), new("session", null, "Session")] },
Codex = new() { HiddenWindows = [HiddenLimitWindow.For(Week)] }
};
await SettingsFile.SaveAsync(directory.Path, settings, TestContext.Current.CancellationToken);
var diagnostics = new DiagnosticLog();
var loaded = SettingsFile.Load(directory.Path, diagnostics);
Assert.Equal(settings, loaded); Assert.Equal(settings.GetHashCode(), loaded.GetHashCode());
Assert.Equal(settings.Claude.HiddenWindows, loaded.Claude.HiddenWindows);
Assert.Equal(settings.Codex.HiddenWindows, loaded.Codex.HiddenWindows);
Assert.Empty(diagnostics.Recent);
}
[Fact]
public void OldFileHidesNothing()
{
using var directory = new TestDirectory();
directory.Write("settings.json", """{"claude":{"enabled":true},"codex":{"popupAhead":false}}""");
var diagnostics = new DiagnosticLog();
var settings = SettingsFile.Load(directory.Path, diagnostics);
Assert.Empty(settings.Claude.HiddenWindows); Assert.Empty(settings.Codex.HiddenWindows);
Assert.False(settings.Codex.PopupAhead); Assert.False(settings.Codex.IsHidden(Week));
Assert.Empty(diagnostics.Recent);
}
[Fact]
public void CodexWeekStaysHiddenAcrossSlotResetAndLabelChangesButNotLengthOrName()
{
var config = new ProviderSettings { HiddenWindows = [HiddenLimitWindow.For(Week)] };
Assert.True(config.IsHidden(Week));
Assert.True(config.IsHidden(Week with { Id = "codex:primary", ResetsAt = Now.AddDays(7), Label = "Renamed week" }));
Assert.False(config.IsHidden(Week with { Id = "codex:primary", Length = TimeSpan.FromHours(5) }));
Assert.False(config.IsHidden(Week with { Id = "other:secondary" }));
}
[Theory]
[InlineData(80)]
[InlineData(10)]
public void HiddenWindowHasNoAheadOrBehindPopupAcrossSlotMove(double used)
{
var window = Week with { UsedPercent = used, Id = "codex:primary" };
var pace = Pace.Calculate(window, Now);
Assert.NotNull(new PopupDecider().Observe(window, pace, new Settings()));
var settings = new Settings { Codex = new() { HiddenWindows = [HiddenLimitWindow.For(Week)] } };
Assert.Null(new PopupDecider().Observe(window, pace, settings));
Assert.NotNull(new PopupDecider().Observe(window with { Provider = Provider.Claude }, pace, settings));
}
[Theory]
[InlineData("null")]
[InlineData("[null]")]
[InlineData("[{\"name\":\"\",\"label\":\"Week\"}]")]
[InlineData("[{\"name\":\"week\",\"label\":\"Week\",\"length\":\"00:00:00\"}]")]
public void MalformedHiddenWindowsFallBackWithDiagnostic(string hidden)
{
using var directory = new TestDirectory();
directory.Write("settings.json", "{\"claude\":{\"hiddenWindows\":" + hidden + "}}");
var diagnostics = new DiagnosticLog();
Assert.Empty(SettingsFile.Load(directory.Path, diagnostics).Claude.HiddenWindows);
Assert.Equal("settings-defaults", Assert.Single(diagnostics.Recent).Code);
}
}
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""D8: render the shared usage gauge. Requires development-only Pillow 11.3.0."""
import argparse
from pathlib import Path
from PIL import Image, ImageDraw
SIZES = (16, 20, 24, 32, 40, 48, 64, 128, 256)
ASSETS = Path(__file__).resolve().parents[2] / 'src' / 'FinalToken.App' / 'Assets'
def render(size):
scale = size * 8
image = Image.new('RGBA', (scale, scale))
draw = ImageDraw.Draw(image)
def box(a, b, c, d):
return tuple(round(n * scale) for n in (a, b, c, d))
draw.rounded_rectangle(box(.025, .025, .975, .975), radius=round(.20 * scale),
fill='#1a1a19', outline='#52514e', width=round(.025 * scale))
gauge = box(.17, .17, .83, .83)
width = round(.115 * scale)
draw.arc(gauge, 135, 405, fill='#383835', width=width)
draw.arc(gauge, 135, 265, fill='#d95926', width=width)
draw.arc(gauge, 267, 353, fill='#3987e5', width=width)
# One chunky pointer survives the 16 px downsample; there are no small-size hairlines.
draw.line(box(.50, .53, .64, .37), fill='#f0efec', width=round(.075 * scale))
draw.ellipse(box(.445, .475, .555, .585), fill='#f0efec')
return image.resize((size, size), Image.Resampling.LANCZOS)
def write_assets(output):
output.mkdir(parents=True, exist_ok=True)
images = [render(size) for size in SIZES]
images[-1].save(output / 'FinalToken.ico', sizes=[(s, s) for s in SIZES], append_images=images[:-1])
images[-1].save(output / 'FinalToken.png')
def contact_sheet(path):
sizes = (16, 24, 32, 48, 256)
sheet = Image.new('RGB', (512, 640))
draw = ImageDraw.Draw(sheet)
for column, background in enumerate(('#f9f9f7', '#0d0d0d')):
left = column * 256
draw.rectangle((left, 0, left + 255, 639), fill=background)
y = 24
for size in sizes:
icon = render(size)
sheet.paste(icon, (left + (256 - size) // 2, y), icon)
y += size + 32
path.parent.mkdir(parents=True, exist_ok=True)
sheet.save(path)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--out', type=Path, default=ASSETS)
parser.add_argument('--contact-sheet', type=Path)
args = parser.parse_args()
write_assets(args.out)
if args.contact_sheet:
contact_sheet(args.contact_sheet)
if __name__ == '__main__':
main()
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
"""Check all ICO frames and reproducible committed icon assets."""
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from PIL import Image
from make_icon import ASSETS, SIZES, render
class IconTests(unittest.TestCase):
def test_ico_contains_every_size_and_its_rendered_pixels(self):
with Image.open(ASSETS / 'FinalToken.ico') as icon:
self.assertEqual({(s, s) for s in SIZES}, icon.ico.sizes())
for size in SIZES:
frame = icon.ico.getimage((size, size))
self.assertEqual(render(size).tobytes(), frame.tobytes())
def test_fresh_run_reproduces_committed_files_byte_for_byte(self):
with tempfile.TemporaryDirectory() as temporary:
subprocess.run([sys.executable, '-B', str(Path(__file__).with_name('make_icon.py')),
'--out', temporary], check=True)
for name in ('FinalToken.ico', 'FinalToken.png'):
self.assertEqual((ASSETS / name).read_bytes(), (Path(temporary) / name).read_bytes(), name)
if __name__ == '__main__':
unittest.main()