Files
poli0981andClaude Fable 5.2 1342979353 ci: Qodana - JetBrains' code analysis from a workflow of its own, and what its first run reported settled (D93) (#373)
* ci: Qodana - a workflow of its own from JetBrains' template, Qodana Community for .NET over FrameLedger.slnx (D93)

The first run: the linter in its Linux container, EnableWindowsTargeting passed
to it, no quality gate yet - what it builds and what it reports decides the rest.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* ci: Qodana's gate is zero problems, and the inspections this project argues with are off in .editorconfig, each with its reason (D93)

Pushed before the fixes on purpose: the run this starts has the settings and
none of the fixes, so it shows the gate failing on what is left.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix: what Qodana's first run reported, settled - about 400 fixes in 181 files, none changing behaviour; the documents (D93)

Redundant qualifiers, casts, using directives, nullable suppressions and unsafe
modifiers removed from the report's own positions; var for built-in types and
one-line block bodies brought to .editorconfig's style by dotnet format; every
XAML item template names its DataType and a binding that reached its page through
DataContext.ViewModel names the page's type; two unread fields, two overwritten
initialisers and an unused parameter removed; SpokenTextAutomationPeer no longer
assumes the base peer's name is a string.

docs/13_CI_CD.md §Qodana, CLAUDE.md, the wiki's workflow table, HANDOFF's
decisions index (D93) and the changelog entry.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 16:13:04 +00:00

740 lines
34 KiB
C#

// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.IO;
using System.Windows;
using System.Windows.Automation;
using FluentAssertions;
using FrameLedger.App.Charts;
using FrameLedger.App.Controls;
using FrameLedger.App.Pages;
using FrameLedger.App.Services;
using FrameLedger.App.ViewModels;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Settings;
using FrameLedger.Domain.Metrics;
using FrameLedger.Infrastructure.Persistence;
using FrameLedger.Shared.Ipc;
using Microsoft.Extensions.DependencyInjection;
using Wpf.Ui.Markup;
namespace FrameLedger.App.Tests;
/// <summary>
/// Every page's XAML and the two control templates load under the real theme dictionaries — the failure a
/// binding typo or a missing resource key produces is a XamlParseException at first navigation, which no
/// view-model test sees. Runs on an STA thread with an <c>Application</c> of its own.
/// </summary>
public sealed partial class PagesLoadTests
{
private sealed class NoAgent : IAgentLink
{
public AgentConnectionState State => AgentConnectionState.Missing;
public StatusAck? Status => null;
public HelloAck? Hello => null;
public bool IsConnected => false;
public event EventHandler? Changed
{
add { }
remove { }
}
public event EventHandler<AgentEventArgs>? EventReceived
{
add { }
remove { }
}
public Task<IpcEnvelope> RequestAsync<TRequest>(string type, TRequest payload, CancellationToken ct = default)
where TRequest : class => throw new NotSupportedException();
public void SetLaunchHold(bool hold)
{
}
}
private sealed class NoNavigation : IPageNavigator
{
public void Navigate<TPage>()
where TPage : class
{
}
public void GoBack()
{
}
}
private sealed class NoPrompt : IConsentPrompt
{
public Task<bool> ShowAsync(string gameName, CancellationToken ct = default) => Task.FromResult(false);
}
private sealed class NoConfirm : IConfirmations
{
public Task<bool> DeleteSessionsAsync(string? gameName, long sessions, CancellationToken ct = default) => Task.FromResult(false);
public Task<RemoveGameChoice> RemoveGameAsync(string gameName, CancellationToken ct = default) => Task.FromResult(RemoveGameChoice.Cancel);
}
private sealed class NoEdit : IEditGamePrompt
{
public Task<GameEdit?> EditAsync(GameMetadata current, string? provenanceJson, EditImage? image = null, CancellationToken ct = default) => Task.FromResult<GameEdit?>(null);
}
private sealed class NoStrip : IMessageStrip
{
public void Info(string title, string body)
{
}
public void Success(string title, string body)
{
}
public void Warn(string title, string body)
{
}
}
private sealed class NoSummaries : ISessionSummaryOpener
{
public void Open(long sessionId)
{
}
}
private sealed class NoMixed : IMixedTierPrompt
{
public Task<bool> AcknowledgeAsync(CancellationToken ct = default) => Task.FromResult(true);
}
private sealed class NoSaver : IFileSaver
{
public string? PickSavePath(string filter, string suggestedName) => null;
}
private sealed class FixedHardware : Application.Recording.IHardwareSnapshotSource
{
public HardwareSnapshot Take() => new() { CpuName = "Test CPU", GpuName = "Test GPU", GpuDriver = "1.2.3", RamGb = 32, OsBuild = "26100", DisplayRes = "2560x1440", DisplayHz = 165 };
}
private sealed class NoClipboard : IClipboard
{
public bool SetText(string text) => true;
}
private sealed class NoPicker : IGamePicker
{
public string? PickExecutable(string? initialDirectory = null) => null;
}
private sealed class NoImages : IImagePicker
{
public string? PickImage() => null;
}
private sealed class NoTheme : IThemeApplier
{
public void Apply(AppTheme theme, Window? window)
{
}
}
private sealed class NoRun : IRunAtLogon
{
public bool IsSet => false;
public void Apply(bool enabled)
{
}
}
private sealed class NoMaintenance : IMaintenanceState
{
public Task<MaintenanceSnapshot> ReadAsync(CancellationToken ct = default) => Task.FromResult(new MaintenanceSnapshot(false, false, Infrastructure.Startup.LogonTaskState.NotInstalled));
}
private sealed class NoTool : IAgentTool
{
public Task<AgentToolResult> RunAsync(string flag, CancellationToken ct = default) => Task.FromResult(new AgentToolResult(-1, "no agent in this test"));
}
private sealed class NoFirstRun : IFirstRunFlow
{
public Task<bool> IsRequiredAsync(CancellationToken ct = default) => Task.FromResult(false);
public Task<bool> RunAsync(CancellationToken ct = default) => Task.FromResult(true);
public Task ShowDocumentsAsync(CancellationToken ct = default) => Task.CompletedTask;
}
/// <summary>
/// ONE STA thread with a running dispatcher for the whole class. The <c>Application</c> and its merged
/// dictionaries are created on it once; every render is queued to it. A thread per test used to work only
/// while a single test touched a given style: a Setter's <c>SolidColorBrush</c> with a <c>DynamicResource</c>
/// colour cannot be frozen, so the first thread to instantiate it owns it and the second thread's
/// <c>Measure</c> throws "Cannot access Freezable across threads" (measured 2026-09-14 when a second test
/// rendered a <c>ui:Button</c>).
/// </summary>
private static readonly System.Collections.Concurrent.BlockingCollection<Action> _staQueue = StartSta();
private static System.Collections.Concurrent.BlockingCollection<Action> StartSta()
{
var queue = new System.Collections.Concurrent.BlockingCollection<Action>();
var thread = new Thread(() =>
{
foreach (Action job in queue.GetConsumingEnumerable())
{
job();
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
return queue;
}
internal static Task<T> OnStaAsync<T>(Func<T> work)
{
var tcs = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
_staQueue.Add(() =>
{
try
{
if (System.Windows.Application.Current is null)
{
var app = new System.Windows.Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
app.Resources.MergedDictionaries.Add(new ThemesDictionary { Theme = Wpf.Ui.Appearance.ApplicationTheme.Dark });
app.Resources.MergedDictionaries.Add(new ControlsDictionary());
app.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/FrameLedger;component/Styles/FrameLedger.xaml") });
}
tcs.SetResult(work());
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
tcs.SetException(ex);
}
});
return tcs.Task;
}
/// <summary>The two PR-8a pages' view models, loaded (the Logs tail over a directory with no file).</summary>
private static async Task<(SettingsViewModel Settings, LogsViewModel Logs)> SettingsAndLogsAsync(ScratchLedger s, HookingConsent consent, IMessageStrip strip)
{
var store = new SqliteSettingsStore(s.Db);
var appearance = new AppearanceSettings(store);
await appearance.LoadAsync().ConfigureAwait(false);
var settings = new SettingsViewModel(appearance, new NoTheme(), new ShellHost(new ServiceCollection().BuildServiceProvider(), null!, null!, new WindowClosePolicy()), new RegisteredSettings(store), s.Library, consent, new NoAgent(), new NoRun(), strip, new NoMaintenance(), new NoTool(), new WindowClosePolicy(), new NoFirstRun());
Task pending1 = settings.Pending;
await pending1.ConfigureAwait(false);
var logs = new LogsViewModel(new LogTail(Path.Combine(Path.GetTempPath(), "fl-nologs-" + Guid.NewGuid().ToString("N"))), new BugReportFlow(new BugBundleBuilder(Path.GetTempPath(), new RegisteredSettings(store)), new NoSaver(), new NoAgent(), new ClosePreview(), new NoUrlOpener(), new NoClipboard(), strip), strip);
Task pending2 = logs.Pending;
await pending2.ConfigureAwait(false);
return (settings, logs);
}
/// <summary>The first-run steps (PR-9): the gate, then the Agent step, under the same dictionaries.</summary>
private static void RenderFirstRun(ScratchLedger s)
{
using var firstRun = new FirstRunViewModel(new LegalGate(new SqliteLegalAcceptanceStore(s.Db), LegalDocuments.Load()), new NoAgent(), readOnly: false);
Render(new FirstRunContent(firstRun));
firstRun.NextCommand.Execute(null);
Render(new FirstRunContent(firstRun));
}
/// <summary>The two control templates (PR-5), rendered on the STA thread.</summary>
private static void RenderControls(GameDetailViewModel detail)
{
var readout = new FpsReadout { Model = FpsPresentation.FromRow(detail.Sessions[0].Row) };
Render(readout);
var chip = new TriStateChip { Model = new TriStateChipModel("RT", Tri.Yes, Application.TriState.TriStateSource.Measured) };
Render(chip);
}
private static void Render(FrameworkElement element)
{
element.Measure(new Size(1200, 900));
element.Arrange(new Rect(0, 0, 1200, 900));
element.UpdateLayout();
}
/// <summary>
/// beta.11 (owner request 2026-10-03: "the empty band on the right"): the library's cards share the whole width — every
/// card in a row as wide as the others, the row as wide as the panel — and the list view renders with the grid gone, the
/// choice remembered. Under the real dictionaries, so a style or binding typo is red here.
/// </summary>
[Fact]
public async Task TheLibraryGridFillsItsWidthAndTheListViewReplacesIt()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
foreach (string name in new[] { "Alpha", "Bravo", "Charlie", "Delta", "Echo" })
{
_ = await s.GameAsync(name);
}
var selection = new GameSelection();
var nav = new NoNavigation();
var strip = new NoStrip();
var settings = new MemorySettings();
var games = new GamesViewModel(s.Library, selection, nav, new AddGameFlow(s.Library, new NoPicker(), selection, nav, strip),
settings: new RegisteredSettings(settings));
Task pending = games.Pending;
await pending;
games.HeaderText.Should().EndWith("5");
games.Games.Should().OnlyContain(static g => g.NotInstalled, "the scratch entries point at files that do not exist");
(double PanelWidth, double[] CardWidths, int Columns) grid = await OnStaAsync(() =>
{
var page = new GamesPage(games);
Render(page);
UniformWrapPanel panel = Find<UniformWrapPanel>(page)!;
double[] widths = [.. panel.Children.Cast<FrameworkElement>().Select(static c => c.ActualWidth)];
return (panel.ActualWidth, widths, UniformWrapPanel.ColumnsFor(panel.ActualWidth, panel.MinItemWidth, panel.Spacing));
});
grid.Columns.Should().BeGreaterThan(1);
grid.CardWidths.Should().OnlyContain(w => Math.Abs(w - grid.CardWidths[0]) < 0.5, "every card is an equal share");
((grid.Columns * grid.CardWidths[0]) + ((grid.Columns - 1) * 12)).Should().BeApproximately(grid.PanelWidth, 1, "a full row leaves no band unused");
games.ShowListCommand.Execute(null);
(bool ListShown, bool GridShown) list = await OnStaAsync(() =>
{
var page = new GamesPage(games);
Render(page);
return (((FrameworkElement)page.FindName("GameList")).Visibility == Visibility.Visible,
((FrameworkElement)page.FindName("CardGrid")).Visibility == Visibility.Visible);
});
list.ListShown.Should().BeTrue();
list.GridShown.Should().BeFalse();
settings.Rows.Should().ContainKey("ui.library_view").WhoseValue.Should().Be("list", "the choice is remembered");
}
/// <summary>beta.11: the import checklist renders with the rows already in the library shown, dimmed, under the real dictionaries.</summary>
[Fact]
public async Task TheImportChecklistRendersWithTheExistingRowsShown()
{
var vm = new ImportReviewViewModel(
[
new Application.Import.ImportCandidate(new Application.Import.StoreGame("steam", "1", "A", @"C:\a", @"C:\a\a.exe", null), @"C:\a\a.exe",
AlreadyInLibrary: false, ExecutableGuessed: false),
new Application.Import.ImportCandidate(new Application.Import.StoreGame("steam", "2", "B", @"C:\b", @"C:\b\b.exe", null), @"C:\b\b.exe",
AlreadyInLibrary: true, ExecutableGuessed: false),
])
{ ShowExisting = true };
int rows = await OnStaAsync(() =>
{
var content = new Dialogs.ImportReviewContent(vm);
Render(content);
return Find<System.Windows.Controls.DataGrid>(content)!.Items.Count;
});
rows.Should().Be(2);
}
/// <summary>The first descendant of <paramref name="root"/> of type <typeparamref name="T"/> in the visual tree, or null.</summary>
private static T? Find<T>(DependencyObject root)
where T : DependencyObject
{
for (int i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(root); i++)
{
DependencyObject child = System.Windows.Media.VisualTreeHelper.GetChild(root, i);
if (child is T hit)
{
return hit;
}
if (Find<T>(child) is { } deeper)
{
return deeper;
}
}
return null;
}
/// <summary>
/// beta.8 (owner request 2026-09-25): an anti-cheat game's page under the real dictionaries — the finding's card is
/// rendered, and the Hooking card, whose switch could only be refused, is not while <c>ui.hide_anticheat_hooking</c> is
/// on (its default).
/// </summary>
[Fact]
public async Task AnAntiCheatGamesPageRendersTheFindingInPlaceOfTheHookingCard()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow game = await s.GameAsync("Alpha");
await s.Db.WriteAsync((c, tx, ct) => Dapper.SqlMapper.ExecuteAsync(c, new Dapper.CommandDefinition(
"UPDATE games SET hook_blocked_reason = 'BlockedModule|BattlEye|BEClient_x64.dll', hook_prescan_state = 'blocked' WHERE id = @id",
new { id = game.Id }, tx, cancellationToken: ct)), TestContext.Current.CancellationToken);
var detail = new GameDetailViewModel(s.Library, new GameSelection { GameId = game.Id }, new HookingConsent(new NoAgent(), new NoPrompt()),
new NoNavigation(), new NoConfirm(), new NoEdit(), new NoStrip(), new NoSummaries(), new SessionSeriesLoader(s.Sessions),
new SqliteHardwareSnapshotRepository(s.Db), new SessionSelection(), new NoPicker(),
new RegisteredSettings(new MemorySettings()));
Task pending = detail.Pending;
await pending;
List<string> shown = await OnStaAsync(() =>
{
var page = new GameDetailPage(detail);
Render(page);
List<string> texts = [];
CollectShownTexts(page, texts);
return texts;
});
detail.AntiCheatText.Should().NotBeNull();
shown.Should().Contain(detail.AntiCheatText).And.Contain(GameDetailViewModel.AntiCheatHeader);
shown.Should().NotContain(GameDetailViewModel.HookingHeader, "the Hooking card is hidden");
shown.Should().NotContain(GameDetailViewModel.HookingBody);
}
/// <summary>The text of every TextBlock under <paramref name="root"/> that no collapsed or hidden element hides.</summary>
private static void CollectShownTexts(DependencyObject root, List<string> texts)
{
if (root is UIElement { Visibility: not Visibility.Visible })
{
return;
}
if (root is System.Windows.Controls.TextBlock { Text: { Length: > 0 } text })
{
texts.Add(text);
}
int count = System.Windows.Media.VisualTreeHelper.GetChildrenCount(root);
for (int i = 0; i < count; i++)
{
CollectShownTexts(System.Windows.Media.VisualTreeHelper.GetChild(root, i), texts);
}
}
/// <summary>
/// beta.8: the Trend tab is drawn when the page is made — the view model's load finished before the page subscribed, so
/// every first open was blank — and on a date axis that keeps its label (the axis was replaced after the label was set).
/// </summary>
[Fact]
public async Task TheTrendIsDrawnWhenThePageIsMadeOnADateAxisThatKeepsItsLabel()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow game = await s.GameAsync("Alpha");
await s.SessionAsync(game.Id, DateTimeOffset.UtcNow.AddDays(-2), native: 60);
await s.SessionAsync(game.Id, DateTimeOffset.UtcNow.AddDays(-1), native: 64);
var detail = new GameDetailViewModel(s.Library, new GameSelection { GameId = game.Id }, new HookingConsent(new NoAgent(), new NoPrompt()),
new NoNavigation(), new NoConfirm(), new NoEdit(), new NoStrip(), new NoSummaries(), new SessionSeriesLoader(s.Sessions),
new SqliteHardwareSnapshotRepository(s.Db), new SessionSelection(), new NoPicker());
Task pending = detail.Pending;
await pending;
(int Drawn, string? Label) chart = await OnStaAsync(() =>
{
var page = new GameDetailPage(detail);
Render(page);
return (page.Trend.DrawnPoints, page.Trend.ScottPlot.Axes.Bottom.Label.Text);
});
chart.Drawn.Should().Be(2, "drawn on the first open, not only after a later load");
chart.Label.Should().Be(Strings.Trend_Axis_Date);
}
/// <summary>Tools ▸ Database maintenance's dialog body (P4 PR-7) under the real dictionaries: its icons, the converter key, every binding.</summary>
[Fact]
public async Task TheDatabaseMaintenanceDialogLoads()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var vm = new DatabaseMaintenanceViewModel(new LedgerMaintenance(s.Db), s.Db.Path, new NoAgent(), new NoSaver(), new NoMaintenancePrompts(), new RegisteredSettings(new SqliteSettingsStore(s.Db)));
double width = await OnStaAsync(() =>
{
var content = new Dialogs.DatabaseMaintenanceContent(vm);
Render(content);
return content.ActualWidth;
});
width.Should().BeGreaterThan(0);
}
private sealed class NoMaintenancePrompts : IDatabaseMaintenancePrompts
{
public Task ShowAsync(CancellationToken ct = default) => Task.CompletedTask;
public Task<bool> ConfirmSweepAsync(int keep, CancellationToken ct = default) => Task.FromResult(false);
}
/// <summary>The bug report's optional items under the real dictionaries: both checkboxes, their texts, the visibility converter.</summary>
[Fact]
public async Task TheBundleOptionsDialogLoads()
{
var vm = new BugBundleOptionsViewModel(new BugBundleOffer(new CrashDumpInfo(@"C:\data\crashdumps\ui-20260915-010203-42.dmp", DateTimeOffset.UtcNow, 2 * 1024 * 1024), new LastSessionInfo(1, "Title", DateTimeOffset.UtcNow)));
double width = await OnStaAsync(() =>
{
var content = new Dialogs.BugBundleOptionsContent(vm);
Render(content);
return content.ActualWidth;
});
width.Should().BeGreaterThan(0);
}
/// <summary>
/// WPF UI 4.3.0's <c>InfoBar</c> template has no <c>ContentPresenter</c>, so the action button 08_UI
/// §Notifications policy puts on every persistent banner — the one dismissal of a safety notice, since the X is
/// off by design — was never rendered: a refusal was a red bar nobody could close. <c>Styles/FrameLedger.xaml</c>
/// re-templates the control with the presenter. Both halves are asserted: the app's template renders the
/// Content, the library's does not — so this turns red the day upstream renders it, which is the day the
/// override comes out rather than staying by habit.
/// </summary>
[Fact]
public async Task TheInfoBarTemplateRendersItsContent()
{
(bool ours, bool library) = await OnStaAsync(() =>
{
Wpf.Ui.Controls.InfoBar ours = NoticeWithAction();
Render(ours);
Wpf.Ui.Controls.InfoBar library = NoticeWithAction();
library.Style = (Style)new ControlsDictionary()[typeof(Wpf.Ui.Controls.InfoBar)];
Render(library);
return (HasRenderedActionButton(ours), HasRenderedActionButton(library));
});
ours.Should().BeTrue("the app's InfoBar template must render the action button, or a safety notice cannot be dismissed");
library.Should().BeFalse("WPF UI 4.3.0 drops InfoBar.Content; when this turns true the override in Styles/FrameLedger.xaml is no longer needed");
}
private static Wpf.Ui.Controls.InfoBar NoticeWithAction() => new()
{
IsOpen = true,
IsClosable = false,
Severity = Wpf.Ui.Controls.InfoBarSeverity.Error,
Title = "Game: hooking refused",
Message = "Easy Anti-Cheat was detected in this game.",
Content = new Wpf.Ui.Controls.Button { Content = "Record this session without measuring it" },
};
private static bool HasRenderedActionButton(DependencyObject root)
{
if (root is Wpf.Ui.Controls.Button { Content: string, Visibility: Visibility.Visible, ActualWidth: > 0 })
{
return true;
}
int count = System.Windows.Media.VisualTreeHelper.GetChildrenCount(root);
for (int i = 0; i < count; i++)
{
if (HasRenderedActionButton(System.Windows.Media.VisualTreeHelper.GetChild(root, i)))
{
return true;
}
}
return false;
}
/// <summary>
/// beta.23 (D60): the game page's artwork is drawn — the banner and the cover are each a WPF UI <c>Image</c>, whose
/// template holds the picture. A <c>ui:Image</c> given a Style of its own that is not based on WPF UI's
/// <c>DefaultImageStyle</c> has no template: it takes its place and draws nothing. The cover did exactly that — an empty
/// space beside the game's name, the banner above it drawn — and no text check can see a picture.
/// </summary>
[Fact]
public async Task TheGamePagesArtworkIsDrawn()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
using Surfaces surfaces = await Surfaces.LoadAsync(s);
List<string> images = await OnStaAsync(() =>
{
(Window host, FrameworkElement root) = Hosted(() => new GameDetailPage(surfaces.Detail));
try
{
Lay(root);
return Visuals.FindAll<Wpf.Ui.Controls.Image>(root)
.Select(static image => AutomationProperties.GetName(image) + (Visuals.Find<System.Windows.Controls.Image>(image) is { Source: not null, ActualWidth: > 0, ActualHeight: > 0 }
? ": drawn" : ": nothing drawn"))
.ToList();
}
finally
{
host.Close();
}
});
images.Should().Equal([Strings.Art_Banner_Name + ": drawn", Strings.Art_Cover_Name + ": drawn"], "the surfaces' game has a banner and a cover, and both are on its page");
}
[Fact]
public async Task EveryPageLoadsUnderTheThemeDictionaries()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow game = await s.GameAsync("Alpha");
await s.SessionAsync(game.Id, DateTimeOffset.UtcNow.AddHours(-1), fgMode: "dlssg", native: 62, displayed: 118, factor: 1.9);
await s.SessionAsync(game.Id, DateTimeOffset.UtcNow.AddHours(-3), hooked: false);
var selection = new GameSelection { GameId = game.Id };
var nav = new NoNavigation();
var strip = new NoStrip();
var addGame = new AddGameFlow(s.Library, new NoPicker(), selection, nav, strip);
var consent = new HookingConsent(new NoAgent(), new NoPrompt());
// The view models load off the STA thread; the pages bind to them on it.
var dashboard = new DashboardViewModel(new NoAgent(), s.Library, selection, nav, new NoSummaries());
Task pending1 = dashboard.Pending;
await pending1;
var games = new GamesViewModel(s.Library, selection, nav, addGame);
Task pending2 = games.Pending;
await pending2;
var detail = new GameDetailViewModel(s.Library, selection, consent, nav, new NoConfirm(), new NoEdit(), strip, new NoSummaries(),
new SessionSeriesLoader(s.Sessions), new SqliteHardwareSnapshotRepository(s.Db), new SessionSelection(), new NoPicker());
var compare = new CompareViewModel(s.Library, new SessionSeriesLoader(s.Sessions), new NoMixed(), new NoSaver(), strip);
Task pending3 = detail.Pending;
await pending3;
Task pending4 = compare.Pending;
await pending4;
(SettingsViewModel settings, LogsViewModel logs) = await SettingsAndLogsAsync(s, consent, strip);
(string loaded, List<string> wrapped) = await OnStaAsync(() =>
{
// WPF UI changes ScrollViewer.CanContentScroll's default for Page to true when its content presenter is first
// used, as the App's NavigationView does at start-up; a page that keeps it is wrapped in a scroller (beta.14).
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(Wpf.Ui.Controls.NavigationViewContentPresenter).TypeHandle);
System.Windows.Controls.Page[] pages =
[
new DashboardPage(dashboard), new GamesPage(games), new GameDetailPage(detail), new ComparePage(compare),
new SettingsPage(settings, new SystemInfoViewModel(new FixedHardware(), new NoClipboard(), strip)), new LogsPage(logs),
];
foreach (System.Windows.Controls.Page page in pages)
{
Render(page);
}
RenderFirstRun(s);
RenderControls(detail);
return ("dashboard,games,detail,settings,logs,firstrun,readout,chip",
pages.Where(static p => System.Windows.Controls.ScrollViewer.GetCanContentScroll(p)).Select(static p => p.GetType().Name).ToList());
});
loaded.Should().Be("dashboard,games,detail,settings,logs,firstrun,readout,chip");
wrapped.Should().BeEmpty("every page sets ScrollViewer.CanContentScroll=\"False\", or WPF UI wraps it in a scroller its own root swallows the wheel for (16_WPFUI_SYNTAX §Gotchas)");
settings.MinSessionSeconds.Should().Be(30);
games.Games.Should().ContainSingle();
detail.Sessions.Should().HaveCount(2);
detail.Sessions.Should().Contain(static r => r.TierText == Strings.Tier_NotHooked);
}
[Fact]
public async Task TheChartsDrawThroughSkiaUnderTheThemeDictionaries()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow game = await s.GameAsync("Alpha");
long withFrames = await s.SessionWithFramesAsync(game.Id, DateTimeOffset.UtcNow.AddHours(-2), frames: 3000, spikeEvery: 400);
SessionSeries series = (await new SessionSeriesLoader(s.Sessions).LoadAsync(withFrames, TestContext.Current.CancellationToken))!;
// A missing native library or a wrong ScottPlot member is red here, not at the first summary window.
int drawn = await OnStaAsync(() =>
{
var frametime = new FrametimeChart();
frametime.Show(series, displayed: true, sensors: true);
Render(frametime);
using ScottPlot.Image image = frametime.ScottPlot.GetImage(640, 320);
var distribution = new DistributionChart();
distribution.Show(series);
Render(distribution);
using ScottPlot.Image histogram = distribution.HistogramPlot.GetImage(320, 240);
var trend = new TrendChart();
trend.Show([new TrendPoint(DateTimeOffset.UtcNow.AddDays(-1), 60, 1, false), new TrendPoint(DateTimeOffset.UtcNow, 65, 2, false)], [new ChangeMarker(1, DateTimeOffset.UtcNow, ["GPU driver: a → b"])], "avg");
Render(trend);
using ScottPlot.Image trendImage = trend.ScottPlot.GetImage(640, 320);
var sensors = new SensorsChart();
sensors.Show(series);
Render(sensors);
var latency = new LatencyChart();
latency.Show(series, 12_000, 18_000);
Render(latency);
var compareChart = new CompareChart();
compareChart.Show([new CompareCurve("a", [0, 50, 100], [30, 60, 90])], Strings.Compare_Mixed_Legend);
Render(compareChart);
using ScottPlot.Image compareImage = compareChart.ScottPlot.GetImage(640, 320);
return frametime.DrawnPoints + (sensors.DrawnSeries > 0 ? 0 : 1_000_000) + (trend.DrawnPoints == 2 ? 0 : 1_000_000) + (compareChart.DrawnCurves == 1 ? 0 : 1_000_000);
});
drawn.Should().BeGreaterThan(0).And.BeLessThanOrEqualTo(Decimator.DefaultBuckets * 2 + 2100, "FR-5.3: decimated per draw (the series, the markers, the sensors)");
series.Stutter!.Count(static f => f).Should().Be(7);
}
/// <summary>
/// beta.27: the owner opened one session twice from the dashboard and had two summary windows of it side by side
/// (2026-10-20). A session has one summary window — opening it again brings that one forward —, another session gets
/// its own, and a closed window lets the next open build a new one.
/// </summary>
[Fact]
public async Task OpeningAnOpenSessionAgainBringsItsOneWindowForward()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow game = await s.GameAsync("Silent Hill 2");
long first = await s.SessionWithFramesAsync(game.Id, DateTimeOffset.UtcNow.AddMinutes(-10), frames: 120, spikeEvery: 60);
long second = await s.SessionWithFramesAsync(game.Id, DateTimeOffset.UtcNow, frames: 120, spikeEvery: 60);
await using ServiceProvider services = new ServiceCollection()
.AddSingleton<ISessionRepository>(s.Sessions)
.AddSingleton<IGameRepository>(s.Games)
.AddSingleton<ISessionAnnotationRepository>(s.Annotations)
.AddSingleton<IHardwareSnapshotRepository>(new SqliteHardwareSnapshotRepository(s.Db))
.AddSingleton(new SessionSeriesLoader(s.Sessions))
.AddSingleton<IFileSaver>(new NoSaver())
.AddSingleton<IMessageStrip>(new NoStrip())
.AddSingleton<IThemeApplier>(new NoTheme())
.AddSingleton(new AppearanceSettings(new MemorySettings()))
.BuildServiceProvider();
(IReadOnlyList<long> Twice, int Windows, IReadOnlyList<long> AfterClose) seen = await OnStaAsync(() =>
{
var shell = new ShellHost(new ServiceCollection().BuildServiceProvider(), null!, null!, new WindowClosePolicy());
var opener = new SessionSummaryOpener(services, shell, new SessionSelection());
opener.Open(first);
opener.Open(first);
opener.Open(second);
opener.Open(first);
IReadOnlyList<long> twice = opener.OpenSessions;
List<Windows.SessionSummaryWindow> shown = [.. System.Windows.Application.Current.Windows.OfType<Windows.SessionSummaryWindow>()];
shown.ForEach(static w => w.Close());
opener.Open(first);
IReadOnlyList<long> afterClose = opener.OpenSessions;
System.Windows.Application.Current.Windows.OfType<Windows.SessionSummaryWindow>().ToList().ForEach(static w => w.Close());
return (twice, shown.Count, afterClose);
});
seen.Twice.Should().Equal([first, second], "a session's second open brings its window forward instead of a copy");
seen.Windows.Should().Be(2);
seen.AfterClose.Should().Equal([first], "a closed window is forgotten, and the next open builds a new one");
}
/// <summary>
/// beta.34 (owner request 2026-11-06, D86): the selected page keeps its name in the pane. WPF UI's LeftFluent template
/// animates the label to height 0 when an item becomes active; ours is the same template without that.
/// </summary>
[Fact]
public async Task TheSelectedPaneItemKeepsItsLabel()
{
(double Height, double Opacity, double LabelHeight) seen = await OnStaAsync(() =>
{
var template = (System.Windows.Controls.ControlTemplate)System.Windows.Application.Current.FindResource("FlLeftFluentNavigationViewItemTemplate");
var item = new Wpf.Ui.Controls.NavigationViewItem { Content = "Compare", Template = template };
item.SetValue(Wpf.Ui.Controls.NavigationViewItem.IsActiveProperty, true);
Render(item);
var grid = (FrameworkElement)template.FindName("ContentGrid", item);
var label = (FrameworkElement)template.FindName("ElementContentPresenter", item);
return (grid.ActualHeight, grid.Opacity, label.ActualHeight);
});
seen.Height.Should().BeGreaterThan(0, "the label's row keeps its height while the item is selected");
seen.Opacity.Should().Be(1);
seen.LabelHeight.Should().BeGreaterThan(0);
}
}