diff --git a/AGENTS.md b/AGENTS.md index 2965975..a25d1dd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -120,6 +120,8 @@ a screenshot of each changed view: compiling is not working. ## 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 `python -B tools/docs/test_check_docs.py`. - `tools/gitea.sh`: calls the Gitea API with the stored git credential or `GITEA_TOKEN`. diff --git a/docs/decisions.md b/docs/decisions.md index 374615e..1113591 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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 hysteresis of 2 points so a value on the threshold cannot flap. Popups can be turned off per 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 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 -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 diff --git a/src/FinalToken.App/AppIcon.cs b/src/FinalToken.App/AppIcon.cs new file mode 100644 index 0000000..070b5c1 --- /dev/null +++ b/src/FinalToken.App/AppIcon.cs @@ -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); + } +} diff --git a/src/FinalToken.App/Assets/FinalToken.ico b/src/FinalToken.App/Assets/FinalToken.ico new file mode 100644 index 0000000..e64dd3d Binary files /dev/null and b/src/FinalToken.App/Assets/FinalToken.ico differ diff --git a/src/FinalToken.App/Assets/FinalToken.png b/src/FinalToken.App/Assets/FinalToken.png new file mode 100644 index 0000000..5bc8312 Binary files /dev/null and b/src/FinalToken.App/Assets/FinalToken.png differ diff --git a/src/FinalToken.App/DesktopApp.cs b/src/FinalToken.App/DesktopApp.cs index 8da5ca7..2147501 100644 --- a/src/FinalToken.App/DesktopApp.cs +++ b/src/FinalToken.App/DesktopApp.cs @@ -1,9 +1,6 @@ using Avalonia; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Media; -using Avalonia.Media.Imaging; -using Avalonia.Themes.Fluent; using Avalonia.Threading; using FinalToken.Core; using FinalToken.Core.StreamDeck; @@ -49,10 +46,10 @@ public sealed class DesktopApp : Application CreateTray(); panel.Show(); if (engine is not null) { - engine.SnapshotChanged += snapshot => Dispatcher.UIThread.Post(() => { model.Snapshot = snapshot; model.Diagnostics = engine.RecentDiagnostics; model.Message = "Updated " + snapshot.MadeAt.LocalDateTime.ToString("g"); Run(LoadHistory); }); + engine.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.ActivationRequested += () => Dispatcher.UIThread.Post(OpenPanel); - model.Snapshot = engine.CurrentSnapshot; + if (engine.CurrentSnapshot is { } snapshot) model.ApplySnapshot(snapshot, engine.Settings); model.ProbeInterval = engine.Settings.ProbeInterval; ageTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) }; ageTimer.Tick += (_, _) => { if (panel.IsVisible) model.Diagnostics = engine.RecentDiagnostics; }; @@ -75,11 +72,7 @@ public sealed class DesktopApp : Application var menu = new NativeMenu(); foreach (var (label, action) in new (string, Action)[] { ("Open", OpenPanel), ("Refresh now", () => Run(Refresh)), ("Settings", OpenSettings), ("Quit", () => Run(Quit)) }) { var item = new NativeMenuItem(label); item.Click += (_, _) => action(); menu.Items.Add(item); } - using var bitmap = new RenderTargetBitmap(new PixelSize(32, 32)); - using (var context = bitmap.CreateDrawingContext()) - { context.DrawRectangle(Brush.Parse("#3878D4"), null, new Rect(0, 0, 32, 32), 7, 7); context.DrawLine(new Pen(Brushes.White, 4), new(9, 9), new(23, 9)); context.DrawLine(new Pen(Brushes.White, 4), new(16, 9), new(16, 25)); } - using var stream = new MemoryStream(); bitmap.Save(stream, PngBitmapEncoderOptions.Default); stream.Position = 0; - tray = new TrayIcon { Icon = new WindowIcon(stream), ToolTipText = "FinalToken", Menu = menu, IsVisible = true }; + tray = new TrayIcon { Icon = AppIcon.Load(), ToolTipText = "FinalToken", Menu = menu, IsVisible = true }; tray.Clicked += (_, _) => OpenPanel(); TrayIcon.SetIcons(this, [tray]); } @@ -105,7 +98,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), () => Run(Quit)); + settingsWindow = new SettingsWindow(engine.Settings, pluginStatus, value => settingsSave = SaveSettings(value), () => Run(Quit), snapshot: engine.CurrentSnapshot); settingsWindow.Closed += (_, _) => settingsWindow = null; settingsWindow.Show(); } @@ -119,6 +112,8 @@ public sealed class DesktopApp : Application catch { await OsStartup.ApplyAsync(previous.StartWithOs); throw; } if (quitting) return; model.ProbeInterval = value.ProbeInterval; + if (engine.CurrentSnapshot is { } snapshot) model.ApplySnapshot(snapshot, value); + await LoadHistory(); await CheckPlugin(); if (!quitting) await engine.RefreshNowAsync(); } diff --git a/src/FinalToken.App/FinalToken.App.csproj b/src/FinalToken.App/FinalToken.App.csproj index 9704ede..c2c2124 100644 --- a/src/FinalToken.App/FinalToken.App.csproj +++ b/src/FinalToken.App/FinalToken.App.csproj @@ -5,8 +5,10 @@ true true true + Assets/FinalToken.ico + diff --git a/src/FinalToken.App/PanelViewModel.cs b/src/FinalToken.App/PanelViewModel.cs index d39400e..a948b96 100644 --- a/src/FinalToken.App/PanelViewModel.cs +++ b/src/FinalToken.App/PanelViewModel.cs @@ -36,6 +36,22 @@ public partial class PanelViewModel : ObservableObject } 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 { HistoryRange.Hours24 => now.AddHours(-24), HistoryRange.Days7 => now.AddDays(-7), diff --git a/src/FinalToken.App/PanelWindow.cs b/src/FinalToken.App/PanelWindow.cs index b4d2c99..058757e 100644 --- a/src/FinalToken.App/PanelWindow.cs +++ b/src/FinalToken.App/PanelWindow.cs @@ -29,6 +29,7 @@ public sealed class PanelWindow : Window { this.model = model; this.clock = clock ?? TimeProvider.System; + Icon = AppIcon.Load(); 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 }; diff --git a/src/FinalToken.App/SettingsWindow.cs b/src/FinalToken.App/SettingsWindow.cs index ee2c654..8841d67 100644 --- a/src/FinalToken.App/SettingsWindow.cs +++ b/src/FinalToken.App/SettingsWindow.cs @@ -8,8 +8,10 @@ namespace FinalToken.App; public sealed class SettingsWindow : Window { - public SettingsWindow(Settings initial, PluginInstallStatus status, Func save, Action? quit = null, Action? openFolder = null) + public SettingsWindow(Settings initial, PluginInstallStatus status, Func save, Action? quit = null, Action? openFolder = null, + Snapshot? snapshot = null) { + Icon = AppIcon.Load(); 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)); @@ -27,8 +29,8 @@ public sealed class SettingsWindow : Window 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); + var claude = ProviderControls(providers, Provider.Claude, initial.Claude, snapshot); + var codex = ProviderControls(providers, Provider.Codex, initial.Codex, snapshot); 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; @@ -96,12 +98,24 @@ public sealed class SettingsWindow : Window parent.Children.Add(row); return value => value with { PopupsEnabled = enabled.IsChecked == true, PopupAhead = ahead.IsChecked == true, PopupBehind = behind.IsChecked == true }; } - private static Func ProviderControls(StackPanel parent, string name, ProviderSettings config) + private static Func 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); enabled.Name = name + "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() }; + 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() }; } } diff --git a/src/FinalToken.Core/Pace.cs b/src/FinalToken.Core/Pace.cs index 65ff05d..5597f33 100644 --- a/src/FinalToken.Core/Pace.cs +++ b/src/FinalToken.Core/Pace.cs @@ -54,6 +54,7 @@ public sealed class PopupDecider } states[key] = next; 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 || (next == PaceState.Ahead ? !settings.PopupAhead || !settings.For(window.Provider).PopupAhead : !settings.PopupBehind || !settings.For(window.Provider).PopupBehind)) return null; diff --git a/src/FinalToken.Core/Settings.cs b/src/FinalToken.Core/Settings.cs index 86a9cee..75079fb 100644 --- a/src/FinalToken.Core/Settings.cs +++ b/src/FinalToken.Core/Settings.cs @@ -2,6 +2,12 @@ using System.Text.Json; 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 { // 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 PopupBehind { get; set; } = true; public string? CliPath { get; set; } + public IReadOnlyList 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 @@ -30,7 +57,7 @@ public sealed record Settings [System.Text.Json.Serialization.JsonIgnore] public bool IsValid => RefreshInterval > TimeSpan.Zero && RefreshInterval <= TimeSpan.FromSeconds(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); } diff --git a/tests/FinalToken.App.Tests/HeadlessTests.cs b/tests/FinalToken.App.Tests/HeadlessTests.cs index 4886556..c1acfff 100644 --- a/tests/FinalToken.App.Tests/HeadlessTests.cs +++ b/tests/FinalToken.App.Tests/HeadlessTests.cs @@ -435,6 +435,7 @@ public sealed class HeadlessTests Assert.False(first.IsVisible); Assert.False(second.IsVisible); Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed)); ResetViews.Verify((window, name) => Save(window, name)); + HiddenWindowViews.Verify((window, name) => Save(window, name)); completion.SetResult(); void SaveThemes(Window window, string stem) { diff --git a/tests/FinalToken.App.Tests/HiddenWindowViews.cs b/tests/FinalToken.App.Tests/HiddenWindowViews.cs new file mode 100644 index 0000000..cb24eb2 --- /dev/null +++ b/tests/FinalToken.App.Tests/HiddenWindowViews.cs @@ -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 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().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().First(); + foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light }) + { + settings.RequestedThemeVariant = theme; Dispatcher.UIThread.RunJobs(); + var title = settings.GetVisualDescendants().OfType().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