// SPDX-License-Identifier: GPL-3.0-only // Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE using System.Globalization; using FluentAssertions; using FrameLedger.App.Charts; using FrameLedger.App.Services; using FrameLedger.App.ViewModels; using FrameLedger.Application.Persistence; using FrameLedger.Application.TriState; using FrameLedger.Domain.Metrics; using FrameLedger.Infrastructure.Persistence; namespace FrameLedger.App.Tests; /// The summary over a scratch ledger: stat cards from the stored aggregates, the override writing the annotation (and the game default), tags/notes saved, exports through a scripted saver. [Collection(StringsCultureCollection.Name)] public sealed class SessionSummaryViewModelTests { private static CancellationToken Ct => TestContext.Current.CancellationToken; private sealed class ScriptedOverride(TriStateOverrideChoice? answer) : ITriStateOverridePrompt { public Task AskAsync(TriStateChipModel chip, CancellationToken ct = default) => Task.FromResult(answer); } private sealed class ScriptedSaver(string? path) : IFileSaver { public string? PickSavePath(string filter, string suggestedName) => path; } private sealed class FakeStrip : IMessageStrip { public List Lines { get; } = []; public void Info(string title, string body) => Lines.Add("info:" + body); public void Success(string title, string body) => Lines.Add("success:" + body); public void Warn(string title, string body) => Lines.Add("warn:" + body); } private static SessionSummaryViewModel Build(ScratchLedger s, TriStateOverrideChoice? overrideAnswer = null, string? savePath = null, FakeStrip? strip = null) => new(s.Sessions, s.Games, s.Annotations, new SqliteHardwareSnapshotRepository(s.Db), new SessionSeriesLoader(s.Sessions), new ScriptedOverride(overrideAnswer), new ScriptedSaver(savePath), strip ?? new FakeStrip()); [Fact] public async Task StatCardsComeFromTheStoredRowAndATierTwoSessionSaysSo() { CultureInfo? previous = Strings.Culture; Strings.Culture = CultureInfo.GetCultureInfo("en"); try { await using ScratchLedger s = await ScratchLedger.OpenAsync(); GameRow game = await s.GameAsync("Alpha"); long hooked = await s.SessionWithFramesAsync(game.Id, DateTimeOffset.UtcNow, frames: 300, spikeEvery: 0); long tier2 = await s.SessionAsync(game.Id, DateTimeOffset.UtcNow.AddHours(-1), hooked: false); SessionSummaryViewModel vm = Build(s); await vm.LoadAsync(hooked, Ct); vm.NotFound.Should().BeFalse(); vm.IsHooked.Should().BeTrue(); vm.Series.Should().NotBeNull(); vm.Stats.Should().HaveCount(21, "eight frame statistics, the display mode (beta.10), pacing, VSync, focus and capture quality (beta.14), " + "the machine: GPU and CPU (2026-09-21), the game's own memory (beta.12), then the card's clocks, its limits and frames per watt (beta.14)"); vm.Stats.Single(c => string.Equals(c.Label, "CPU", StringComparison.Ordinal)).Value.Should().Be("N/A avg · N/A max", "this row carries no CPU reading: N/A, never 0%"); vm.Stats.Single(c => string.Equals(c.Label, "Median", StringComparison.Ordinal)).Value.Should().Be("60"); vm.Stats.Single(c => string.Equals(c.Label, "1% Low", StringComparison.Ordinal)).Value.Should().Be("48"); vm.Stats.Single(c => string.Equals(c.Label, "Duration", StringComparison.Ordinal)).Value.Should().Be(Formats.Duration(vm.Row!.DurationSeconds)); vm.Chips.Should().HaveCount(3); vm.Chips[0].IsYes.Should().BeTrue(); vm.DecimationNote.Should().Contain("300"); vm.HasSensors.Should().BeTrue("the blob says where the first present is, so the overlay is drawn in step"); vm.HasSensorCharts.Should().BeTrue(); SessionSummaryViewModel two = Build(s); await two.LoadAsync(tier2, Ct); two.IsHooked.Should().BeFalse(); two.Series.Should().BeNull(); two.Stats.Single(c => string.Equals(c.Label, "Median", StringComparison.Ordinal)).Value.Should().Be("N/A"); two.Stats.Single(c => string.Equals(c.Label, "Average", StringComparison.Ordinal)).Value.Should().Be("N/A"); two.HasSensorCharts.Should().BeFalse("this Tier-2 row recorded no sensor"); // beta.8: a Tier-2 session with sensors charts them — no overlay, there are no frames to lay them over. long sensed = await s.NotHookedWithSensorsAsync(game.Id, DateTimeOffset.UtcNow.AddHours(-2)); SessionSummaryViewModel three = Build(s); await three.LoadAsync(sensed, Ct); three.Series.Should().BeNull(); three.HasSensors.Should().BeFalse(); three.HasSensorCharts.Should().BeTrue(); three.SensorSeries!.Sensors.Should().HaveCount(2); SessionSummaryViewModel missing = Build(s); await missing.LoadAsync(tier2 + 99, Ct); missing.NotFound.Should().BeTrue(); } finally { Strings.Culture = previous; } } /// /// beta.14 (D49): the new cards read the stored row — pacing with the display's own share named for the display, VSync and /// tearing, ray tracing where it was measured, focus, capture quality, the card's clocks and limits, frames per watt — and /// where frames were generated the displayed 1% low stands beside the game's own (rule 6), never instead of it. /// [Fact] public async Task TheBetaFourteenCardsReadTheStoredRowAndTheDisplayedLowStandsBesideTheGamesOwn() { CultureInfo? previous = Strings.Culture; CultureInfo previousCulture = CultureInfo.CurrentCulture; Strings.Culture = CultureInfo.GetCultureInfo("en"); CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en"); try { await using ScratchLedger s = await ScratchLedger.OpenAsync(); GameRow game = await s.GameAsync("Beta"); long id = await s.SessionAsync(game.Id, DateTimeOffset.UtcNow, fgMode: "dlssg", native: 60, displayed: 118, factor: 1.97, shape: static r => r with { FgFactorScope = "session", DisplayedP1LowFps = 101, TimeBelow30Pct = 1.25, TimeBelow60Pct = 9.62, TimeBelowRefreshPct = 3.5, DisplayMonitorHz = 144, FrametimeDeltaMeanMs = 0.875, VsyncPresentPct = 100, TearingAllowedPct = 0, RtFramePct = 45.5, RaysPerPixel = 0.82, DrainTicks = 1000, ForegroundTicks = 950, GapCount = 2, AvgGpuCoreClockMhz = 2655.4, AvgGpuMemClockMhz = 15001, AvgGpuFanRpm = 1450.4, MaxGpuMemTemp = 78, PowerLimitPct = 33.3, ThermalLimitPct = 0, AppFramesPerJoule = 0.3125, }); SessionSummaryViewModel vm = Build(s); await vm.LoadAsync(id, Ct); StatCardModel Card(string label) => vm.Stats.Single(c => string.Equals(c.Label, label, StringComparison.Ordinal)); vm.Readout.Kind.Should().Be(FpsReadoutKind.Generated); Card("1% Low").Suffix.Should().Be("displayed: 101", "rule 6: the presents' low beside the game's own, never instead"); Card("Time below 60 FPS").Should().Be(new StatCardModel("Time below 60 FPS", "9.6%", "below 30: 1.3% · display under 144 Hz: 3.5%")); Card("Frame to frame").Value.Should().Be("0.88 ms"); Card("VSync").Should().Be(new StatCardModel("VSync", "100.0% of frames", "tearing allowed: 0.0%")); Card("Ray tracing").Should().Be(new StatCardModel("Ray tracing", "45.5% of frames", "0.82 rays per pixel")); Card("Game in focus").Value.Should().Be("95.0% of the time"); Card("Capture quality").Value.Should().Be("2 gaps · 0 lost · 0 faults"); Card("GPU clocks").Should().Be(new StatCardModel("GPU clocks", "2,655 MHz core · 15,001 MHz memory", "fan 1,450 RPM · memory 78 °C")); Card("GPU held back").Value.Should().Be("power 33.3% · heat 0.0%"); Card("Frames per watt").Should().Be(new StatCardModel("Frames per watt", "0.31 FPS/W", "the game's own frames, GPU power only")); } finally { Strings.Culture = previous; CultureInfo.CurrentCulture = previousCulture; } } /// /// beta.24 (D62): the stored mix as a block — a row per state with its own Native → Displayed and its share, the time with /// no frame generation, the time no state claims —, the NVIDIA App setting above it, and for a session that counted frame /// generation before the mix was stored, one line saying so rather than an empty block. /// [Fact] public async Task TheStoredMixIsShownWithItsSettingAndAnOlderSessionSaysItHasNone() { CultureInfo? previous = Strings.Culture; CultureInfo previousCulture = CultureInfo.CurrentCulture; Strings.Culture = CultureInfo.GetCultureInfo("en"); CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en"); try { await using ScratchLedger s = await ScratchLedger.OpenAsync(); GameRow game = await s.GameAsync("Gamma"); string mix = Application.Recording.FgMixRecord.ToJson(new FgMix( [ new FgMixRow(FgMixKind.Generated, 2.0, 62, 124, 120, 0.2, 24), new FgMixRow(FgMixKind.Generated, 6.0, 48, 288, 360, 0.6, 72), new FgMixRow(FgMixKind.Unclassified, null, null, null, 120, 0.2, 24), ]))!; string profile = Application.Recording.DriverProfileRecord.Serialize(new Application.Capture.DriverProfileReading { Outcome = Application.Capture.DriverProfileOutcome.Application, ProfileName = "Gamma", Settings = [ new Application.Capture.DriverSettingReading(Application.Capture.NvidiaDriverSettings.DlssgMode, 4, Application.Capture.DriverSettingLocation.Profile, false), new Application.Capture.DriverSettingReading(Application.Capture.NvidiaDriverSettings.DlssgDynamicMultiFrameCountMax, 5, Application.Capture.DriverSettingLocation.Profile, false), ], })!; long withMix = await s.SessionAsync(game.Id, DateTimeOffset.UtcNow, fgMode: "dlssg", native: 48, displayed: 288, factor: 6.0, shape: r => r with { FgFactorScope = "steady", FgSteadyShare = 0.6, FgMixJson = mix, DriverProfileJson = profile, }); long older = await s.SessionAsync(game.Id, DateTimeOffset.UtcNow.AddHours(-1), fgMode: "dlssg", native: 60, displayed: 118, factor: 1.97); SessionSummaryViewModel vm = Build(s); await vm.LoadAsync(withMix, Ct); vm.HasFgMix.Should().BeTrue(); vm.FgMix.Select(static r => r.Label).Should().Equal("×2.0 frame generation", "×6.0 frame generation", "Not classified"); vm.FgMix.Select(static r => r.Share).Should().Equal("20.00%", "60.00%", "20.00%"); vm.FgMixSegments.Select(static g => g.Share).Should().Equal(0.2, 0.6, 0.2); vm.FgMixContext.Should().Be("Set in the NVIDIA App: Dynamic, up to ×6"); vm.FgMixUnclassifiedNote.Should().Be(Strings.FgMix_Unclassified_Note); vm.FgMixName.Should().StartWith("Share of the session's time by frame-generation state: ×2.0 frame generation 20.00%"); vm.FgMixMissing.Should().BeNull(); await vm.LoadAsync(older, Ct); vm.HasFgMix.Should().BeFalse("the block is cleared, not left from the session before"); vm.FgMix.Should().BeEmpty(); vm.FgMixSegments.Should().BeEmpty(); vm.FgMixContext.Should().BeNull(); vm.FgMixUnclassifiedNote.Should().BeNull(); vm.FgMixMissing.Should().Be(Strings.FgMix_NotStored, "it counted frame generation before the mix was stored"); } finally { Strings.Culture = previous; CultureInfo.CurrentCulture = previousCulture; } } /// A session recorded before beta.14 has none of schema 0019's values: every new card reads N/A, never a zero. [Fact] public async Task ARowRecordedBeforeBetaFourteenReadsNotAvailableOnTheNewCards() { CultureInfo? previous = Strings.Culture; Strings.Culture = CultureInfo.GetCultureInfo("en"); try { await using ScratchLedger s = await ScratchLedger.OpenAsync(); GameRow game = await s.GameAsync("Old"); SessionSummaryViewModel vm = Build(s); await vm.LoadAsync(await s.SessionAsync(game.Id, DateTimeOffset.UtcNow), Ct); foreach (string label in new[] { "Time below 60 FPS", "Frame to frame", "VSync", "Game in focus", "GPU clocks", "GPU held back", "Frames per watt" }) { vm.Stats.Single(c => string.Equals(c.Label, label, StringComparison.Ordinal)).Value.Should().Be("N/A", label + " was not recorded before beta.14"); } vm.Stats.Should().NotContain(c => string.Equals(c.Label, "Ray tracing", StringComparison.Ordinal), "the card appears only where ray tracing was measured"); } finally { Strings.Culture = previous; } } /// A session recorded before beta.12 has its sensors and no stored statistics: N/A cards and one sentence, nothing computed here. [Fact] public async Task ASessionRecordedBeforeBetaTwelveSaysItsStatisticsWereNotStored() { CultureInfo? previous = Strings.Culture; Strings.Culture = CultureInfo.GetCultureInfo("en"); try { await using ScratchLedger s = await ScratchLedger.OpenAsync(); GameRow game = await s.GameAsync("Alpha"); long hooked = await s.SessionWithFramesAsync(game.Id, DateTimeOffset.UtcNow, frames: 300, spikeEvery: 0); SessionSummaryViewModel vm = Build(s); await vm.LoadAsync(hooked, Ct); vm.Stats.Single(c => string.Equals(c.Label, "VRAM (this game)", StringComparison.Ordinal)).Value.Should().Be("N/A", "this row predates the game's memory: N/A, never 0"); vm.Stats.Single(c => string.Equals(c.Label, "RAM (this game)", StringComparison.Ordinal)).Value.Should().Be("N/A"); vm.HasSensorCharts.Should().BeTrue(); vm.HasSensorStats.Should().BeFalse(); vm.SensorStats.Should().BeEmpty(); vm.SensorStatsMissing.Should().Be(Strings.SensorStats_NotStored, "it has sensors and no stored statistics: recorded before beta.12"); } finally { Strings.Culture = previous; } } /// /// beta.12 (D43): a session that was NOT hooked has the game's memory too — read from outside the game — and the summary /// shows it from the stored columns, with every series' stored statistics in the table, none recomputed. /// [Fact] public async Task TheGamesMemoryAndTheStoredStatisticsAreShownForASessionThatWasNotHooked() { CultureInfo? previous = Strings.Culture; CultureInfo previousCulture = CultureInfo.CurrentCulture; Strings.Culture = CultureInfo.GetCultureInfo("en"); CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en"); try { await using ScratchLedger s = await ScratchLedger.OpenAsync(); GameRow game = await s.GameAsync("Alpha"); string json = "{\"gpu_temp\":{\"N\":3,\"Mean\":56,\"Median\":56,\"Min\":55,\"Max\":57},\"game_vram_dedicated\":{\"N\":3,\"Mean\":6000,\"Median\":6144,\"Min\":5120,\"Max\":7168}}"; long id = await s.SessionAsync(game.Id, DateTimeOffset.UtcNow, hooked: false, shape: r => r with { GameVramDedicatedAvgMb = 6000, GameVramDedicatedMedianMb = 6144, GameVramDedicatedMaxMb = 7168, GameVramSharedMaxMb = 256, GameRamPrivateMedianMb = 2048, GameRamPrivateMaxMb = 2560, GameCommitMaxMb = 4096, GameMemoryProcesses = 2, SensorStatsJson = json, }); SessionSummaryViewModel vm = Build(s); await vm.LoadAsync(id, Ct); vm.IsHooked.Should().BeFalse(); vm.Stats.Single(c => string.Equals(c.Label, "VRAM (this game)", StringComparison.Ordinal)).Should().Be( new StatCardModel("VRAM (this game)", "6.00 GB", "median · peak 7.00 GB · shared 256 MB · 2 processes running the game's executable, added together")); vm.Stats.Single(c => string.Equals(c.Label, "RAM (this game)", StringComparison.Ordinal)).Value.Should().Be("2.00 GB"); vm.HasSensorStats.Should().BeTrue(); vm.SensorStatsMissing.Should().BeNull(); vm.SensorStats.Select(static r => r.Series).Should().Equal("GPU core °C", "VRAM, this game (dedicated)"); vm.SensorStats[1].Should().Be(new SensorStatRowModel("VRAM, this game (dedicated)", "5.86 GB", "6.00 GB", "5.00 GB", "7.00 GB", "3")); } finally { Strings.Culture = previous; CultureInfo.CurrentCulture = previousCulture; } } [Fact] public async Task AnOverrideWritesTheAnnotationBesideTheMeasurementAndOptionallyTheGameDefault() { await using ScratchLedger s = await ScratchLedger.OpenAsync(); GameRow game = await s.GameAsync("Alpha"); long id = await s.SessionWithFramesAsync(game.Id, DateTimeOffset.UtcNow, frames: 40, spikeEvery: 0); SessionSummaryViewModel vm = Build(s, overrideAnswer: new TriStateOverrideChoice(Tri.No, SetAsGameDefault: true)); await vm.LoadAsync(id, Ct); vm.Chips[0].Source.Should().Be(TriStateSource.Measured); vm.OverrideCommand.Execute(vm.Chips[0]); Task pending = vm.Pending; await pending; vm.Chips[0].Should().BeEquivalentTo(new { Value = Tri.No, Source = TriStateSource.Manual }); (await s.Annotations.FindAsync(id, Ct))!.RtOverride.Should().Be(Tri.No); (await s.Sessions.FindByIdAsync(id, Ct))!.RtFlag.Should().Be("yes", "the measurement stays"); (await s.Games.FindByIdAsync(game.Id, Ct))!.RtDefault.Should().Be(Tri.No); SessionSummaryViewModel clear = Build(s, overrideAnswer: new TriStateOverrideChoice(null, false)); await clear.LoadAsync(id, Ct); clear.OverrideCommand.Execute(clear.Chips[0]); Task pending2 = clear.Pending; await pending2; clear.Chips[0].Source.Should().Be(TriStateSource.Measured, "clearing restores the measurement"); } [Fact] public async Task TagsAndNotesSaveAndTheExportsWriteWhereTheSaverSays() { await using ScratchLedger s = await ScratchLedger.OpenAsync(); GameRow game = await s.GameAsync("Alpha"); long id = await s.SessionWithFramesAsync(game.Id, DateTimeOffset.UtcNow, frames: 40, spikeEvery: 0); string dir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "fl-export-" + Guid.NewGuid().ToString("N")); System.IO.Directory.CreateDirectory(dir); try { var strip = new FakeStrip(); SessionSummaryViewModel vm = Build(s, savePath: System.IO.Path.Combine(dir, "out.csv"), strip: strip); await vm.LoadAsync(id, Ct); vm.Tags = "bench, 1440p, bench"; vm.Notes = " clean run "; vm.SaveAnnotationCommand.Execute(null); Task pending = vm.Pending; await pending; SessionAnnotation saved = (await s.Annotations.FindAsync(id, Ct))!; saved.Tags.Should().Equal("bench", "1440p"); saved.Notes.Should().Be("clean run"); vm.ExportCsvCommand.Execute(null); Task pending2 = vm.Pending; await pending2; (await System.IO.File.ReadAllTextAsync(System.IO.Path.Combine(dir, "out.csv"), Ct)).Should().Contain(SessionExporter.CsvColumns); strip.Lines.Should().Contain(static l => l.StartsWith("success:", StringComparison.Ordinal)); SessionSummaryViewModel cancelled = Build(s, savePath: null, strip: strip); await cancelled.LoadAsync(id, Ct); cancelled.ExportJsonCommand.Execute(null); Task pending3 = cancelled.Pending; await pending3; System.IO.Directory.GetFiles(dir).Should().HaveCount(1, "a cancelled picker writes nothing"); } finally { System.IO.Directory.Delete(dir, recursive: true); } } /// /// beta.8: the runtime libraries a hooked session loaded (runtime_modules, written since P2 and shown nowhere) as /// one line, sorted — each beside the copy the game ships when the two differ, the shape a DLSS the NVIDIA App or the /// driver substituted has. A row with none has no line. /// [Fact] public void TheLoadedLibrariesNameAnotherCopyWhereTheGameShipsADifferentOne() { CultureInfo? previous = Strings.Culture; Strings.Culture = CultureInfo.GetCultureInfo("en"); try { IReadOnlyList shipped = [ new("dlss", "Engine/Plugins/nvngx_dlss.dll", "3.7.10.0", null), new("streamline", "sl.interposer.dll", "2.8.0.0", null), ]; string? line = SessionSummaryViewModel.LoadedLibraries( "{\"sl.interposer.dll\":\"2,8,0,0\",\"nvngx_dlss.dll\":\"310.2.1.0\",\"ffx_fsr3_x64.dll\":null}", shipped); line.Should().StartWith("Loaded: "); line.Should().Contain("nvngx_dlss.dll 310.2.1.0 (the game ships 3.7.10.0: another copy was loaded"); line.Should().Contain("sl.interposer.dll 2,8,0,0").And.NotContain("sl.interposer.dll 2,8,0,0 (", "the same four numbers"); line.Should().Contain("ffx_fsr3_x64.dll " + Strings.Common_NotAvailable, "a module with no version resource"); line.IndexOf("ffx_fsr3", StringComparison.Ordinal).Should().BeLessThan(line.IndexOf("nvngx", StringComparison.Ordinal), "sorted by name"); SessionSummaryViewModel.LoadedLibraries(null, shipped).Should().BeNull(); SessionSummaryViewModel.LoadedLibraries("{}", shipped).Should().BeNull(); SessionSummaryViewModel.LoadedLibraries("not json", shipped).Should().BeNull(); } finally { Strings.Culture = previous; } } /// /// beta.10 (03_METRICS §Display mode): the Display card and line, in either tier — the mode shown longest with its /// share, every share, the window on its monitor and what it rested on. A window nothing could ask about is "Fullscreen or /// borderless", never either. /// [Fact] public async Task TheDisplayCardAndLineSayHowTheGameWasShownInEitherTier() { CultureInfo? previous = Strings.Culture; Strings.Culture = CultureInfo.GetCultureInfo("en"); try { await using ScratchLedger s = await ScratchLedger.OpenAsync(); GameRow game = await s.GameAsync("Alpha"); long tier2 = await s.SessionAsync(game.Id, DateTimeOffset.UtcNow, hooked: false, display: new Domain.Display.DisplaySummary { CoversMs = 90_000, MinimizedMs = 10_000, NoWindowMs = 5_000, Changes = 1, Source = Domain.Display.DisplaySource.Window, WindowWidth = 1920, WindowHeight = 1080, MonitorWidth = 1920, MonitorHeight = 1080, MonitorHz = 144, }); SessionSummaryViewModel vm = Build(s); await vm.LoadAsync(tier2, Ct); StatCardModel card = vm.Stats.Single(c => string.Equals(c.Label, "Display", StringComparison.Ordinal)); card.Value.Should().Be("Fullscreen or borderless 90%", "time without a window is outside every share"); card.Suffix.Should().Be("1920×1080"); vm.DisplayLine.Should().Be("Display: Fullscreen or borderless 90% · Minimized 10% · changed once · window 1920×1080 on a 1920×1080 monitor at 144 Hz" + " · from the window alone: exclusive fullscreen cannot be told from borderless"); SessionSummaryViewModel before = Build(s); await before.LoadAsync(await s.SessionAsync(game.Id, DateTimeOffset.UtcNow.AddHours(-1)), Ct); before.Stats.Single(c => string.Equals(c.Label, "Display", StringComparison.Ordinal)).Value.Should().Be("N/A", "a row without display facts reads N/A"); before.DisplayLine.Should().BeNull(); } finally { Strings.Culture = previous; } } }