diff --git a/src/FinalToken.App/DesktopApp.cs b/src/FinalToken.App/DesktopApp.cs index 9824f35..2147501 100644 --- a/src/FinalToken.App/DesktopApp.cs +++ b/src/FinalToken.App/DesktopApp.cs @@ -46,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; }; @@ -98,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(); } @@ -112,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/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/SettingsWindow.cs b/src/FinalToken.App/SettingsWindow.cs index 0ab765b..8841d67 100644 --- a/src/FinalToken.App/SettingsWindow.cs +++ b/src/FinalToken.App/SettingsWindow.cs @@ -8,7 +8,8 @@ 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); @@ -28,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; @@ -97,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