Compare commits
1
Commits
alpha
...
beta23/pr2-perf
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
08d29563ff |
No files matched your search
@@ -30,6 +30,21 @@ numeric core and does not move; the heading is the full version — corrected 20
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A game's page opens and changes session without freezing the window** (owner request 2026-10-14). Measured on the
|
||||
dev PC over a ledger shaped like the owner's (`docs/spike-notes.md` §21): a game with 100 sessions took 1.2–1.5 s to
|
||||
open — its Sessions list built every row, now only the rows on screen (it scrolls itself and hands the wheel to the
|
||||
page at its ends) — 0.37 s now; choosing a two-million-frame session froze the window 0.8–1.0 s — the session was read
|
||||
and decoded on the UI thread, then sorted three times for the Distribution tab — 17 ms now: it is read on the thread
|
||||
pool and what the charts need from all of it is worked out there once. The page also asks whether the game's `.exe` is
|
||||
on disk off the UI thread (a USB drive that sleeps answered on it), and no longer summarises every game to show one.
|
||||
- **Each visit to the Dashboard or Logs no longer stays in memory.** Every Dashboard ever opened stayed alive and kept
|
||||
listening to the capture agent, so at each session's end each one reloaded its lists and raised its own "Session
|
||||
saved" notice — twenty visits, twenty notices, the last one shown. The Dashboard listens only while it is on screen,
|
||||
and the notice has one home for the App's life, shown once whichever page is open; each Logs page kept its tail of up
|
||||
to 2 MB, twice.
|
||||
- **The Logs page reads its file only when it changed**, not every two seconds, and filters it off the UI thread; **Play**
|
||||
reads the stores' lists of installed games off the UI thread (Steam's manifests sit on whatever drive its libraries
|
||||
are on). At Debug level the App now logs how long each page took to appear (`ui: page … shown … ms`).
|
||||
- **The native ring-buffer tests no longer pass or fail by the scheduler's luck** (developers only). The
|
||||
hammering-writer test required the reader to keep more than half of the stream, which measured how the operating
|
||||
system scheduled two threads: on a hybrid Intel processor it failed 5 of 200 runs with the ring correct every time.
|
||||
|
||||
+17
-2
@@ -128,8 +128,12 @@ The Menu sits in its own row **below** the TitleBar (never inside the drag regio
|
||||
> Dashboard), Exit (a real exit through `ShellHost.Quit`, whatever minimize-to-tray says); a left click opens the
|
||||
> window. **Minimize to tray on close** hides the live window when `ui.minimize_to_tray` is on and a tray icon
|
||||
> exists (`WindowClosePolicy`); a language rebuild's old window is unaffected. **FR-3.8's balloon** — "Session
|
||||
> saved — <game> — click to view" — is raised only while the window is off screen; on screen, the Dashboard's
|
||||
> snackbar carries the same event (one event, exactly one channel), and its click opens the summary window.
|
||||
> saved — <game> — click to view" — is raised only while the window is off screen; on screen, ~~the Dashboard's~~ the
|
||||
> App's snackbar carries the same event (one event, exactly one channel), and its click opens the summary window.
|
||||
> *(Corrected 2026-10-14, beta.23: the snackbar's notice was raised by the Dashboard's view model, and it reached the
|
||||
> other pages only because no Dashboard ever went away — each visit made one, the root container kept every one, each
|
||||
> subscribed, so twenty visits were twenty notices for one session. It is `Services.SessionNotices` now, one
|
||||
> subscription for the App's life; the Dashboard listens only while it is on screen.)*
|
||||
> A safety event is never a balloon (`TrayViewModelTests` asserts it). Tools ▸ Agent status… and Tools ▸ Vulkan
|
||||
> layer registration… now navigate (Dashboard, Settings) instead of saying "not yet".
|
||||
|
||||
@@ -305,6 +309,17 @@ All screens are `Page`s registered with the navigation page provider and navigat
|
||||
- **Last session measured** — accent chips with real values ("DLSS Quality · 1440p → 2160p", "Frame Generation DLSS-G ×1.9", "Ray Tracing: Yes"). Measured.
|
||||
- **Hooking control** (`ui:CardControl` with `ToggleSwitch`): off by default. Turning it on opens the consent dialog (FR-2.1). When the static anti-cheat pre-scan blocked it, the switch is **disabled** with the reason shown inline and no way to force it. When auto-disabled after crashes, an `InfoBar` explains and offers manual re-enable.
|
||||
|
||||
> **What opening the page and choosing a session cost, beta.23 (owner request 2026-10-14; `spike-notes` §21).** The
|
||||
> Sessions grid is bounded (`MaxHeight` 520, as Compare's list is): inside the page's own scroller it was measured with no
|
||||
> height limit and built every row — 100 sessions were 100 rows of 17 columns, 1.2–1.5 s to open the page; it builds the
|
||||
> rows on screen now, scrolls itself, and hands the wheel to the page at its ends
|
||||
> (`PagesLoadTests.TheSessionsGridBuildsTheRowsOnScreenAndHandsTheWheelOnAtItsEnd`). A session's series is read and
|
||||
> decoded on the thread pool — Microsoft.Data.Sqlite completes its asynchronous calls synchronously, so the decode of a
|
||||
> two-million-frame session ran on the UI thread whatever `ConfigureAwait` said — and what the charts derive from the whole
|
||||
> session (one sort of its frames where the Distribution tab did three, the histogram, the percentile curve, the presents
|
||||
> line) is worked out there once (`Charts.SeriesDigest`): choosing such a session froze the window 0.8–1.0 s, 17 ms now.
|
||||
> Whether the executable is on disk is asked off the UI thread, as the library page has asked since beta.19.
|
||||
|
||||
> **Built 2026-09-14 (P3 PR-5): the grid, the detail page's header, the two rows, the hooking control and
|
||||
> the Sessions tab.** Grid: `ui:CardAction` cards with platform / engine / hooking badges, sessions, playtime,
|
||||
> last played (~~the sparkline is PR-6's~~ no sparkline was built — corrected 2026-10-04); search and sort in memory; FR-1.1 by File ▸ Add game…, the page's
|
||||
|
||||
@@ -255,6 +255,15 @@ On startup and on `ApplicationThemeManager.Changed`: for every live plot set fig
|
||||
ignores Windows' *lines to scroll*, and a precision touchpad's small deltas each jump the whole step — a long document
|
||||
read as slow and jerky while its layout cost about a millisecond a step. `Controls/MarkdownView` handles
|
||||
`PreviewMouseWheel` itself (beta.21): the delta in proportion at Windows' lines, eased, unhandled at its ends.
|
||||
- [ ] **Microsoft.Data.Sqlite completes its "async" calls synchronously** (measured 2026-10-14, beta.23): a
|
||||
`ConfigureAwait(false)` after a ledger read does not leave the thread that asked, so a view model's load, a session's
|
||||
decode, a sort over its frames all ran on the UI thread. Work that must not run there goes in `Task.Run` —
|
||||
`Charts.SessionSeriesLoader`, the game page's executable check (`spike-notes` §21).
|
||||
- [ ] **A transient page's view model is never `IDisposable`** (beta.23). Pages and their view models are transient, and
|
||||
the root container keeps every transient disposable it makes until the App exits: every Dashboard and Logs page ever
|
||||
opened stayed in memory, and each Dashboard stayed subscribed to the Agent — at a session's end every one reloaded its
|
||||
lists on the UI thread and raised its own notice. Listen on Loaded and stop on Unloaded (`Attach`/`Detach`, as Games,
|
||||
the game page and the Dashboard do); `DashboardViewModelTests.ADashboardOffScreenHearsNothing…`.
|
||||
- [ ] **ScottPlot 5 zooms on every wheel and never marks it handled.** Without `Charts/ChartWheel` a wheel over a chart
|
||||
zoomed it and scrolled the page at once; a plain wheel is the page's, Ctrl+wheel the chart's, for every plot that
|
||||
`ChartTheme.Attach` registers.
|
||||
|
||||
@@ -2772,3 +2772,44 @@ entry, and the HELLO, HELLO WORLD! row of `LIST_GAME_TESTED.md`; `LIMITATIONS.md
|
||||
game from an unsafe one.
|
||||
|
||||
- **Not measured, and not to be:** what the payload does. Nothing here was run, decrypted or uploaded anywhere.
|
||||
|
||||
## 21 · Opening pages and switching tabs in the App *(2026-10-14, beta.23)*
|
||||
|
||||
The owner asked whether switching pages and tabs is slow. Measured with a harness over the App's own pages and view
|
||||
models — not committed: it times, and a timing assertion in CI is a flake — on the dev PC (i7-14700KF, RTX 5080, Windows
|
||||
11 29648), Release build, each page shown in WPF UI's `NavigationViewContentPresenter` in a real, off-screen window. The
|
||||
ledger is a scratch one shaped like the owner's (its counts read from the owner's ledger without writing to it): 48 games, one with 100 sessions (NFR-4's
|
||||
"opening a game with 100 sessions ≤ 500 ms"), one with a 2,000,000-frame session (the owner's longest: WALTO, 2,057,022
|
||||
frames, with noisy frame times so a sort is a real sort). **Freeze** is the longest stretch the UI thread did not answer
|
||||
(a probe re-posted at idle priority); median of 10 runs, 5 for the selection; *before* is two runs of `main` (2982679).
|
||||
|
||||
**The decision table, written before the first run:** fix what keeps the UI thread busy 50 ms or more, what can block
|
||||
on I/O, and what grows with each visit; record the rest.
|
||||
|
||||
| What | Freeze before | Freeze after | Why it was slow |
|
||||
|---|---|---|---|
|
||||
| Open a game with 100 sessions | 1,175–1,507 ms | 369 ms | the Sessions grid inside the page's scroller had no height limit and built every row: 100 rows of 17 columns |
|
||||
| Choose the 2,000,000-frame session | 843–1,016 ms | 17 ms | the blob read, its decode and the stutter detection ran on the UI thread (Microsoft.Data.Sqlite's async is synchronous), then three sorts of every frame for the Distribution tab (its histogram, its percentile curve, the curve's lows) and two walks for the Frametime chart — for tabs not even shown. The series is ready 0.85 s after the click either way; the window answers meanwhile now |
|
||||
| A session ends after 20 visits to the Dashboard | 46–60 ms, **20 notices** | 18 ms, 1 notice | every Dashboard ever opened stayed alive (a transient `IDisposable` the root container keeps) and subscribed: each reloaded its lists and raised FR-3.8's notice |
|
||||
| Open the library (48 games) | 265–404 ms | 275 ms | not fixed — below |
|
||||
| Open a game with 9 sessions | 148–203 ms | 210 ms | building ≈ 1,750 visuals, the grid's 9 rows ≈ 130 each |
|
||||
| Open Compare | 66–82 ms | 87 ms | building its visuals |
|
||||
| Open Settings | 75–99 ms | 85 ms | building its visuals |
|
||||
| Open the Dashboard | 48–61 ms | 46 ms | — |
|
||||
| Open Logs | 16–23 ms | 23 ms | — |
|
||||
| Switch a game page's tab (Frametime, Distribution, Trend, Sensors, Latency, back) | 1–25 ms | 1–24 ms | already cheap: a hidden tab is not in the visual tree, and its plot renders once when shown |
|
||||
|
||||
Also changed, and held by tests rather than by these numbers: the game page asks whether its executable is on disk off
|
||||
the UI thread (a USB drive that sleeps answered on it — 39 of the owner's 41 Steam games are on one); the Logs page's
|
||||
two-second tick reads nothing when the newest file has not changed (it re-read up to 2 MB and replaced the whole text);
|
||||
Play reads the stores' records on the thread pool (every press listed Steam's manifests and copied itch's database on
|
||||
the UI thread); the game page no longer summarises every game's sessions to show one.
|
||||
|
||||
**Above the bar, and not fixed.** A page that builds 600–2,500 visuals costs 85–370 ms whatever it reads — about 0.1 ms a
|
||||
visual on this PC — and the remaining cost of the game page is its grid's rows (≈ 130 visuals each). The library is the
|
||||
one that grows with the data: 275 ms at 48 games, about 5.7 ms a card, so about 0.6 s at 100. Its grid is a
|
||||
non-virtualizing panel by decision (beta.11, `Controls/UniformWrapPanel`: cards an equal share of the width, each row as
|
||||
tall as its tallest card); a virtualizing one builds only the cards on screen but makes every card one height and the
|
||||
grid scroll under a fixed header — a change to how the page looks, offered to the owner instead of made here. Nor was a
|
||||
schema migration added for an index on `sessions.started_at` (the Dashboard sorts the table): at the owner's 41 sessions
|
||||
it costs nothing measurable, and a new schema version locks the ledger out of every earlier build.
|
||||
@@ -18,7 +18,6 @@ namespace FrameLedger.App.Charts;
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format strings are resources that follow the UI culture, which changes at runtime")]
|
||||
public partial class DistributionChart : UserControl
|
||||
{
|
||||
private const int _bins = 60;
|
||||
|
||||
public DistributionChart()
|
||||
{
|
||||
@@ -51,7 +50,8 @@ public partial class DistributionChart : UserControl
|
||||
int outside = 0;
|
||||
if (series is { AppFrameTimesMs.Length: > 1 })
|
||||
{
|
||||
FpsHistogram histogram = FpsHistogram.Of(series.AppFrameTimesMs, _bins);
|
||||
// beta.23: the decoded series carries it, worked out off the UI thread (SeriesDigest).
|
||||
FpsHistogram histogram = series.Digest?.Histogram ?? FpsHistogram.OfSorted(SeriesDigest.SortedOf(series), SeriesDigest.HistogramBins);
|
||||
if (histogram.Centers.Length > 0)
|
||||
{
|
||||
BarPlot bars = plot.Add.Bars(histogram.Centers, histogram.Counts);
|
||||
@@ -80,7 +80,8 @@ public partial class DistributionChart : UserControl
|
||||
plot.YLabel(Strings.Chart_Axis_Fps);
|
||||
if (series is { AppFrameTimesMs.Length: > 1 })
|
||||
{
|
||||
(double[] xs, double[] ys) = PercentileCurve.Of(series.AppFrameTimesMs);
|
||||
IReadOnlyList<double>? sorted = series.Digest is null ? SeriesDigest.SortedOf(series) : null;
|
||||
(double[] xs, double[] ys) = series.Digest?.Percentiles ?? PercentileCurve.OfSorted(sorted!);
|
||||
if (xs.Length > 0)
|
||||
{
|
||||
Scatter line = plot.Add.ScatterLine(xs, ys, ChartTheme.Current.Percentile);
|
||||
@@ -88,7 +89,7 @@ public partial class DistributionChart : UserControl
|
||||
line.LegendText = Strings.Chart_Series_Percentile;
|
||||
}
|
||||
|
||||
foreach ((double x, double fps, bool pointOne) in PercentileCurve.Lows(series.AppFrameTimesMs))
|
||||
foreach ((double x, double fps, bool pointOne) in series.Digest?.Lows ?? PercentileCurve.LowsOfSorted(sorted!))
|
||||
{
|
||||
Scatter low = plot.Add.ScatterPoints(new[] { x }, new[] { fps }, ChartTheme.Current.Stutter);
|
||||
low.MarkerSize = 7;
|
||||
|
||||
@@ -23,24 +23,52 @@ public sealed record FpsHistogram(double[] Centers, double[] Counts, double BinW
|
||||
ArgumentNullException.ThrowIfNull(appFrameTimesMs);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bins);
|
||||
double[] fps = [.. appFrameTimesMs.Where(static f => f > 0).Select(static f => 1000.0 / f)];
|
||||
if (fps.Length == 0)
|
||||
return FromSortedRates(Percentile.Sorted(fps), bins);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Of"/> over frame times already sorted ascending (beta.23, <see cref="SeriesDigest"/>): the positive ones are
|
||||
/// the tail, and their rates read backwards ascend — the same rates <see cref="Of"/> sorts, without a sort of its own.
|
||||
/// </summary>
|
||||
public static FpsHistogram OfSorted(IReadOnlyList<double> sortedAppFrameTimesMs, int bins = 60)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sortedAppFrameTimesMs);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bins);
|
||||
int count = sortedAppFrameTimesMs.Count;
|
||||
int first = 0;
|
||||
while (first < count && !(sortedAppFrameTimesMs[first] > 0))
|
||||
{
|
||||
first++;
|
||||
}
|
||||
|
||||
var fps = new double[count - first];
|
||||
for (int i = 0; i < fps.Length; i++)
|
||||
{
|
||||
fps[i] = 1000.0 / sortedAppFrameTimesMs[count - 1 - i];
|
||||
}
|
||||
|
||||
return FromSortedRates(fps, bins);
|
||||
}
|
||||
|
||||
private static FpsHistogram FromSortedRates(IReadOnlyList<double> sorted, int bins)
|
||||
{
|
||||
if (sorted.Count == 0)
|
||||
{
|
||||
return new FpsHistogram([], [], 0, 0);
|
||||
}
|
||||
|
||||
IReadOnlyList<double> sorted = Percentile.Sorted(fps);
|
||||
double lo = Percentile.Linear(sorted, TailFraction) ?? sorted[0];
|
||||
double hi = Percentile.Linear(sorted, 1 - TailFraction) ?? sorted[^1];
|
||||
if (hi - lo < 1e-9)
|
||||
{
|
||||
// Every frame at one rate: one bar, a frame per second wide, centred on it.
|
||||
return new FpsHistogram([lo], [fps.Length], 1, 0);
|
||||
return new FpsHistogram([lo], [sorted.Count], 1, 0);
|
||||
}
|
||||
|
||||
double width = (hi - lo) / bins;
|
||||
var counts = new double[bins];
|
||||
int outside = 0;
|
||||
foreach (double v in fps)
|
||||
foreach (double v in sorted)
|
||||
{
|
||||
if (v < lo || v > hi)
|
||||
{
|
||||
|
||||
@@ -82,7 +82,7 @@ public partial class FrametimeChart : UserControl
|
||||
lines.Add(Strings.Chart_Note_PresentsTiming);
|
||||
}
|
||||
|
||||
int gaps = series.Gap.Skip(1).Count(static g => g);
|
||||
int gaps = series.Digest?.GapsAfterFirst ?? series.Gap.Skip(1).Count(static g => g);
|
||||
if (sensors && series.SensorsAligned && gaps > 0)
|
||||
{
|
||||
lines.Add(string.Format(CultureInfo.CurrentCulture, Strings.Chart_Note_GapsClosed_Format, gaps));
|
||||
@@ -128,9 +128,9 @@ public partial class FrametimeChart : UserControl
|
||||
Plot.Refresh();
|
||||
}
|
||||
|
||||
private void DrawSeries(ScottPlot.Plot plot, IReadOnlyList<double> xs, IReadOnlyList<double> ys, Color color, string label)
|
||||
private void DrawSeries(ScottPlot.Plot plot, double[] xs, double[] ys, Color color, string label)
|
||||
{
|
||||
if (xs.Count == 0)
|
||||
if (xs.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -145,17 +145,8 @@ public partial class FrametimeChart : UserControl
|
||||
/// <summary>Every present but those after a gap, whose stored interval is 0 — not a frame, and it was drawn as a 0 ms one.</summary>
|
||||
private void DrawPresents(ScottPlot.Plot plot, ChartPalette p)
|
||||
{
|
||||
var xs = new List<double>(_series!.Presents);
|
||||
var ys = new List<double>(_series.Presents);
|
||||
for (int i = 0; i < _series.Presents; i++)
|
||||
{
|
||||
if (!_series.Gap[i])
|
||||
{
|
||||
xs.Add(_series.TimesS[i]);
|
||||
ys.Add(_series.FrameTimesMs[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// beta.23: the decoded series carries the line (SeriesDigest), so the Displayed toggle no longer walks every present.
|
||||
(double[] xs, double[] ys) = _series!.Digest?.Presents ?? SeriesDigest.PresentsWithoutGaps(_series.TimesS, _series.FrameTimesMs, _series.Gap);
|
||||
DrawSeries(plot, xs, ys, p.Displayed, Strings.Chart_Series_Displayed);
|
||||
}
|
||||
|
||||
|
||||
@@ -24,12 +24,18 @@ public static class PercentileCurve
|
||||
public static (double[] Xs, double[] Ys) Of(IReadOnlyList<double> appFrameTimesMs)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(appFrameTimesMs);
|
||||
if (appFrameTimesMs.Count < 2)
|
||||
return appFrameTimesMs.Count < 2 ? ([], []) : OfSorted(Percentile.Sorted(appFrameTimesMs));
|
||||
}
|
||||
|
||||
/// <summary><see cref="Of"/> over frame times already sorted ascending (beta.23, <see cref="SeriesDigest"/>).</summary>
|
||||
public static (double[] Xs, double[] Ys) OfSorted(IReadOnlyList<double> sorted)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sorted);
|
||||
if (sorted.Count < 2)
|
||||
{
|
||||
return ([], []);
|
||||
}
|
||||
|
||||
IReadOnlyList<double> sorted = Percentile.Sorted(appFrameTimesMs);
|
||||
var xs = new List<double>(103);
|
||||
var ys = new List<double>(103);
|
||||
foreach (double p in Percents())
|
||||
@@ -48,7 +54,13 @@ public static class PercentileCurve
|
||||
public static IReadOnlyList<(double X, double Fps, bool PointOne)> Lows(IReadOnlyList<double> appFrameTimesMs)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(appFrameTimesMs);
|
||||
IReadOnlyList<double> sorted = Percentile.Sorted(appFrameTimesMs);
|
||||
return LowsOfSorted(Percentile.Sorted(appFrameTimesMs));
|
||||
}
|
||||
|
||||
/// <summary><see cref="Lows"/> over frame times already sorted ascending (beta.23, <see cref="SeriesDigest"/>).</summary>
|
||||
public static IReadOnlyList<(double X, double Fps, bool PointOne)> LowsOfSorted(IReadOnlyList<double> sorted)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sorted);
|
||||
var lows = new List<(double, double, bool)>(2);
|
||||
if (Supported(sorted.Count, 99) && Fps(sorted, 99) is double p1)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using FrameLedger.Domain.Metrics;
|
||||
|
||||
namespace FrameLedger.App.Charts;
|
||||
|
||||
/// <summary>
|
||||
/// What the charts derive from a whole session, worked out ONCE where the series is decoded — off the UI thread since
|
||||
/// beta.23 (<see cref="SessionSeriesLoader.LoadAsync"/>) — instead of on every draw. Measured on 2026-10-14 over a
|
||||
/// two-million-frame session: selecting it froze the window for 0.8–1.0 s, most of it the Distribution tab sorting every
|
||||
/// application frame three times (its histogram, its percentile curve and the curve's lows each sorted their own copy) and
|
||||
/// the Frametime chart counting gaps and copying the presents line, all on the UI thread and for tabs not even shown
|
||||
/// (<c>spike-notes</c> §21). A series a test builds by hand has none: each chart then computes what it needs itself.
|
||||
/// </summary>
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1819:Properties should not return arrays", Justification = "a data carrier for ScottPlot, which draws double[]")]
|
||||
public sealed record SeriesDigest
|
||||
{
|
||||
/// <summary>The bins of <see cref="Histogram"/> — the Distribution tab's.</summary>
|
||||
public const int HistogramBins = 60;
|
||||
|
||||
/// <summary>The application frames' times, ms, ascending.</summary>
|
||||
public required double[] SortedAppFrameTimesMs { get; init; }
|
||||
|
||||
/// <summary><see cref="FpsHistogram.Of"/> over the application frames, at <see cref="HistogramBins"/>.</summary>
|
||||
public required FpsHistogram Histogram { get; init; }
|
||||
|
||||
/// <summary><see cref="PercentileCurve.Of"/> over the application frames.</summary>
|
||||
public required (double[] Xs, double[] Ys) Percentiles { get; init; }
|
||||
|
||||
/// <summary><see cref="PercentileCurve.Lows"/> over the application frames.</summary>
|
||||
public required IReadOnlyList<(double X, double Fps, bool PointOne)> Lows { get; init; }
|
||||
|
||||
/// <summary>How many presents after the first follow a gap.</summary>
|
||||
public required int GapsAfterFirst { get; init; }
|
||||
|
||||
/// <summary>How many presents were generated.</summary>
|
||||
public required int GeneratedCount { get; init; }
|
||||
|
||||
/// <summary>Every present's time and interval but those after a gap — the Frametime chart's presents line; null when nothing was generated, where it is never drawn.</summary>
|
||||
public (double[] TimesS, double[] FrameTimesMs)? Presents { get; init; }
|
||||
|
||||
/// <summary>The digest of a decoded series' arrays.</summary>
|
||||
public static SeriesDigest Of(double[] appFrameTimesMs, double[] timesS, float[] frameTimesMs, bool[] generated, bool[] gap, bool noApplicationFrames)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(appFrameTimesMs);
|
||||
ArgumentNullException.ThrowIfNull(timesS);
|
||||
ArgumentNullException.ThrowIfNull(frameTimesMs);
|
||||
ArgumentNullException.ThrowIfNull(generated);
|
||||
ArgumentNullException.ThrowIfNull(gap);
|
||||
double[] sorted = (double[])appFrameTimesMs.Clone();
|
||||
Array.Sort(sorted);
|
||||
int gaps = 0;
|
||||
int generatedCount = 0;
|
||||
for (int i = 0; i < gap.Length; i++)
|
||||
{
|
||||
if (i > 0 && gap[i])
|
||||
{
|
||||
gaps++;
|
||||
}
|
||||
|
||||
if (i < generated.Length && generated[i])
|
||||
{
|
||||
generatedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return new SeriesDigest
|
||||
{
|
||||
SortedAppFrameTimesMs = sorted,
|
||||
Histogram = FpsHistogram.OfSorted(sorted, HistogramBins),
|
||||
Percentiles = PercentileCurve.OfSorted(sorted),
|
||||
Lows = PercentileCurve.LowsOfSorted(sorted),
|
||||
GapsAfterFirst = gaps,
|
||||
GeneratedCount = generatedCount,
|
||||
Presents = generatedCount > 0 && !noApplicationFrames ? PresentsWithoutGaps(timesS, frameTimesMs, gap) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Every present but those after a gap, whose stored interval is 0 — not a frame.</summary>
|
||||
internal static (double[] TimesS, double[] FrameTimesMs) PresentsWithoutGaps(double[] timesS, float[] frameTimesMs, bool[] gap)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(timesS);
|
||||
ArgumentNullException.ThrowIfNull(frameTimesMs);
|
||||
ArgumentNullException.ThrowIfNull(gap);
|
||||
int n = Math.Min(timesS.Length, Math.Min(frameTimesMs.Length, gap.Length));
|
||||
var xs = new List<double>(n);
|
||||
var ys = new List<double>(n);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
if (!gap[i])
|
||||
{
|
||||
xs.Add(timesS[i]);
|
||||
ys.Add(frameTimesMs[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return ([.. xs], [.. ys]);
|
||||
}
|
||||
|
||||
/// <summary>The ascending application frame times of <paramref name="series"/>: its digest's, or sorted now for a series without one.</summary>
|
||||
internal static IReadOnlyList<double> SortedOf(SessionSeries series)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(series);
|
||||
return series.Digest?.SortedAppFrameTimesMs ?? Percentile.Sorted(series.AppFrameTimesMs);
|
||||
}
|
||||
}
|
||||
@@ -81,9 +81,15 @@ public sealed record SessionSeries
|
||||
/// </summary>
|
||||
public bool SensorsAligned { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// What the charts derive from the whole session, worked out where it was decoded (beta.23); null on a series built by
|
||||
/// hand, whose charts compute it themselves.
|
||||
/// </summary>
|
||||
public SeriesDigest? Digest { get; init; }
|
||||
|
||||
public int Presents => TimesS.Length;
|
||||
|
||||
public bool HasGenerated => Generated.Any(static g => g);
|
||||
public bool HasGenerated => Digest is { } digest ? digest.GeneratedCount > 0 : Generated.Any(static g => g);
|
||||
|
||||
public double DurationS => TimesS.Length == 0 ? 0 : TimesS[^1];
|
||||
|
||||
|
||||
@@ -21,7 +21,23 @@ public sealed class SessionSeriesLoader
|
||||
|
||||
public SessionSeriesLoader(ISessionRepository sessions) => _sessions = sessions ?? throw new ArgumentNullException(nameof(sessions));
|
||||
|
||||
public async Task<SessionSeries?> LoadAsync(long sessionId, CancellationToken ct = default)
|
||||
/// <summary>
|
||||
/// The session's series, read and decoded on the thread pool (beta.23). Microsoft.Data.Sqlite runs its asynchronous
|
||||
/// methods synchronously, so before this the blob read, the decode and the stutter detection of a two-million-frame
|
||||
/// session all ran on the UI thread of whoever asked — the game page, a session's summary, Compare, an export — whatever
|
||||
/// <c>ConfigureAwait</c> said (<c>spike-notes</c> §21).
|
||||
/// </summary>
|
||||
public Task<SessionSeries?> LoadAsync(long sessionId, CancellationToken ct = default) => Task.Run(() => ReadAndDecodeAsync(sessionId, ct), ct);
|
||||
|
||||
/// <summary>
|
||||
/// The sensor series alone, timed from the session's start — what a session that was not hooked has to chart (beta.8: the
|
||||
/// Tier-2 row has kept its sensors since 2026-09-22, and no chart read them). Empty when none were recorded. On the
|
||||
/// thread pool, as <see cref="LoadAsync"/>.
|
||||
/// </summary>
|
||||
public Task<IReadOnlyList<SensorSeries>> LoadSensorsAsync(long sessionId, CancellationToken ct = default) =>
|
||||
Task.Run(async () => (IReadOnlyList<SensorSeries>)DecodeSensors(await _sessions.FindSensorsAsync(sessionId, ct).ConfigureAwait(false), offsetS: 0), ct);
|
||||
|
||||
private async Task<SessionSeries?> ReadAndDecodeAsync(long sessionId, CancellationToken ct)
|
||||
{
|
||||
FrameBlobs? frames = await _sessions.FindFramesAsync(sessionId, ct).ConfigureAwait(false);
|
||||
if (frames is null || !string.Equals(frames.Codec, SeriesCodec.Tag, StringComparison.Ordinal))
|
||||
@@ -34,13 +50,6 @@ public sealed class SessionSeriesLoader
|
||||
return Decode(frames, segments, sensors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sensor series alone, timed from the session's start — what a session that was not hooked has to chart (beta.8: the
|
||||
/// Tier-2 row has kept its sensors since 2026-09-22, and no chart read them). Empty when none were recorded.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<SensorSeries>> LoadSensorsAsync(long sessionId, CancellationToken ct = default) =>
|
||||
DecodeSensors(await _sessions.FindSensorsAsync(sessionId, ct).ConfigureAwait(false), offsetS: 0);
|
||||
|
||||
public static SessionSeries Decode(FrameBlobs frames, IReadOnlyList<SegmentRow> segments, IReadOnlyList<SensorBlob> sensors)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frames);
|
||||
@@ -71,6 +80,7 @@ public sealed class SessionSeriesLoader
|
||||
StutterResult? stutter = StutterDetector.Detect(appFrametimes);
|
||||
uint[]? frameIndex = frames.FrameIndex is { } fi ? PickOptional(SeriesCodec.DecodeUInt32(fi.ToArray()), keep) : null;
|
||||
double? offsetS = frames.FirstPresentMs / 1000.0;
|
||||
double[] appFrameTimesMs = [.. appFrametimes];
|
||||
return new SessionSeries
|
||||
{
|
||||
TimesS = times,
|
||||
@@ -85,13 +95,14 @@ public sealed class SessionSeriesLoader
|
||||
LatencyUs = frames.LatencyUs is { } lat ? PickOptional(SeriesCodec.DecodeUInt32(lat.ToArray()), keep) : null,
|
||||
RenderRes = frames.RenderRes is { } rr ? PickQuads(SeriesCodec.DecodeUInt16(rr.ToArray()), keep) : null,
|
||||
AppTimesS = [.. appIndex.Select(i => times[i])],
|
||||
AppFrameTimesMs = [.. appFrametimes],
|
||||
AppFrameTimesMs = appFrameTimesMs,
|
||||
AppPresentIndex = [.. appIndex],
|
||||
NoApplicationFrames = noApplicationFrames,
|
||||
Stutter = stutter is null ? null : [.. stutter.IsStutter],
|
||||
Segments = MapSegments([.. segments.Where(s => swapchain is null || s.SwapchainId == swapchain.Value)], times, frameIndex),
|
||||
Sensors = DecodeSensors(sensors, offsetS ?? 0),
|
||||
SensorsAligned = offsetS is not null,
|
||||
Digest = SeriesDigest.Of(appFrameTimesMs, times, frametimes, generated, gap, noApplicationFrames),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Diagnostics;
|
||||
using System.Windows.Threading;
|
||||
using FrameLedger.App.Services;
|
||||
using FrameLedger.App.ViewModels;
|
||||
using Serilog;
|
||||
using Wpf.Ui;
|
||||
using Wpf.Ui.Abstractions;
|
||||
using Wpf.Ui.Controls;
|
||||
@@ -48,6 +51,27 @@ public partial class MainWindow : FluentWindow
|
||||
dialogs.SetDialogHost(DialogHost);
|
||||
|
||||
Loaded += (_, _) => theme.Apply(appearance.Theme, this);
|
||||
TimeNavigations();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// beta.23 (<c>spike-notes</c> §21): how long each page takes to be on screen once WPF UI navigates to it — its layout,
|
||||
/// its templates, its first render — logged at Debug (Settings ▸ Logging), so a slow page on a real PC says which it is.
|
||||
/// </summary>
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD001:Avoid legacy thread switching APIs", Justification = "a WPF application has no JoinableTaskFactory; this posts to the window's own dispatcher from its own thread, at the priority after rendering, and never waits (ScrollBarHiding does the same)")]
|
||||
private void TimeNavigations()
|
||||
{
|
||||
long navigating = 0;
|
||||
RootNavigation.Navigating += (_, _) => navigating = Stopwatch.GetTimestamp();
|
||||
RootNavigation.Navigated += (_, e) =>
|
||||
{
|
||||
long from = navigating;
|
||||
string page = e.Page?.GetType().Name ?? "?";
|
||||
DispatcherOperation logged = Dispatcher.InvokeAsync(
|
||||
() => Log.Debug("ui: page {Page} shown {Ms:0} ms after its navigation", page, Stopwatch.GetElapsedTime(from).TotalMilliseconds),
|
||||
DispatcherPriority.ContextIdle);
|
||||
GC.KeepAlive(logged);
|
||||
};
|
||||
}
|
||||
|
||||
public MainWindowViewModel ViewModel { get; }
|
||||
|
||||
@@ -13,6 +13,10 @@ public partial class DashboardPage : INavigableView<DashboardViewModel>
|
||||
ViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel));
|
||||
DataContext = this;
|
||||
InitializeComponent();
|
||||
|
||||
// beta.23: the view model hears the Agent while this page is on screen, never after (each visit makes a new one).
|
||||
Loaded += (_, _) => ViewModel.Attach();
|
||||
Unloaded += (_, _) => ViewModel.Detach();
|
||||
}
|
||||
|
||||
public DashboardViewModel ViewModel { get; }
|
||||
|
||||
@@ -239,7 +239,12 @@
|
||||
Content="{x:Static vm:GameDetailViewModel.DeleteAllSessionsText}" Icon="{ui:SymbolIcon Delete24}"
|
||||
IsEnabled="{Binding ViewModel.ActsOnThisPc}" />
|
||||
</StackPanel>
|
||||
<DataGrid x:Name="SessionsGrid" AutoGenerateColumns="False" CanUserAddRows="False" IsReadOnly="True" HeadersVisibility="Column"
|
||||
<!--
|
||||
beta.23: bounded, as Compare's list is, so the grid scrolls itself and builds only the rows on screen. Inside
|
||||
the page's own scroller it was measured with no height limit and built every row — up to 500 rows of 17
|
||||
columns; 1.2 s to open a game with 100 sessions (spike-notes §21).
|
||||
-->
|
||||
<DataGrid x:Name="SessionsGrid" MaxHeight="520" AutoGenerateColumns="False" CanUserAddRows="False" IsReadOnly="True" HeadersVisibility="Column"
|
||||
ItemsSource="{Binding ViewModel.Sessions}" SelectionMode="Extended" MouseDoubleClick="OnSessionDoubleClick"
|
||||
SelectedItem="{Binding ViewModel.SelectedSession, Mode=TwoWay}">
|
||||
<DataGrid.Columns>
|
||||
|
||||
@@ -6,13 +6,14 @@ using Microsoft.Extensions.Hosting;
|
||||
namespace FrameLedger.App.Services;
|
||||
|
||||
/// <summary>Runs <see cref="AgentConnection"/> for the life of the host.</summary>
|
||||
internal sealed class AgentConnectionHostedService(AgentConnection connection, LiveSessions sessions) : BackgroundService
|
||||
internal sealed class AgentConnectionHostedService(AgentConnection connection, LiveSessions sessions, SessionNotices notices) : BackgroundService
|
||||
{
|
||||
// The running-session view is built with this service, before the first round, so the first connect's status seeds
|
||||
// it and no event after it is missed (2026-09-23).
|
||||
// it and no event after it is missed (2026-09-23); so is FR-3.8's notice (beta.23), on the UI thread the host starts on.
|
||||
protected override Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
GC.KeepAlive(sessions);
|
||||
GC.KeepAlive(notices);
|
||||
return connection.RunAsync(stoppingToken);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,9 +5,12 @@ using FrameLedger.Application.Persistence;
|
||||
|
||||
namespace FrameLedger.App.Services;
|
||||
|
||||
/// <summary>Everything the detail page shows for one game, loaded in one pass: the row, its sessions newest first, their annotations, the aggregate.</summary>
|
||||
/// <summary>
|
||||
/// Everything the detail page shows for one game, loaded in one pass: the row, its sessions newest first, their annotations.
|
||||
/// (It carried the library's aggregate too, read by summarising EVERY game's sessions to keep one, and read by nothing — gone
|
||||
/// in beta.23.)
|
||||
/// </summary>
|
||||
public sealed record GameDetail(
|
||||
GameRow Row,
|
||||
IReadOnlyList<SessionRow> Sessions,
|
||||
IReadOnlyDictionary<long, SessionAnnotation> Annotations,
|
||||
GameSessionSummary? Summary);
|
||||
IReadOnlyDictionary<long, SessionAnnotation> Annotations);
|
||||
@@ -50,8 +50,7 @@ public sealed class GameLibrary
|
||||
|
||||
IReadOnlyList<SessionRow> sessions = await _sessions.ListByGameAsync(gameId, sessionLimit, ct).ConfigureAwait(false);
|
||||
IReadOnlyList<SessionAnnotation> annotations = await _annotations.ListByGameAsync(gameId, ct).ConfigureAwait(false);
|
||||
GameSessionSummary? summary = (await _sessions.SummariseByGameAsync(ct).ConfigureAwait(false)).FirstOrDefault(s => s.GameId == gameId);
|
||||
return new GameDetail(row, sessions, annotations.ToDictionary(static a => a.SessionId), summary);
|
||||
return new GameDetail(row, sessions, annotations.ToDictionary(static a => a.SessionId));
|
||||
}
|
||||
|
||||
/// <summary>FR-1.1: the executable becomes a <c>games</c> row, hooking off; null when the file cannot be read.</summary>
|
||||
|
||||
@@ -27,7 +27,7 @@ namespace FrameLedger.App.Services;
|
||||
public sealed class GamePlayer
|
||||
{
|
||||
private readonly RegisteredSettings _settings;
|
||||
private readonly IReadOnlyList<IStoreLibrarySource> _stores;
|
||||
private readonly StoreRecordsReader _stores;
|
||||
private readonly IGogGalaxyLocator _galaxy;
|
||||
private readonly IShellStarter _shell;
|
||||
private readonly IAgentRequests _agent;
|
||||
@@ -38,7 +38,7 @@ public sealed class GamePlayer
|
||||
{
|
||||
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||||
ArgumentNullException.ThrowIfNull(stores);
|
||||
_stores = [.. stores];
|
||||
_stores = new StoreRecordsReader(stores);
|
||||
_galaxy = galaxy ?? throw new ArgumentNullException(nameof(galaxy));
|
||||
_shell = shell ?? throw new ArgumentNullException(nameof(shell));
|
||||
_agent = agent ?? throw new ArgumentNullException(nameof(agent));
|
||||
@@ -61,7 +61,7 @@ public sealed class GamePlayer
|
||||
}
|
||||
else
|
||||
{
|
||||
StoreGame? record = StoreRecords.Owning(game.Fingerprint.ExePath, game.StoreId, await RecordsAsync(ct).ConfigureAwait(false));
|
||||
StoreGame? record = StoreRecords.Owning(game.Fingerprint.ExePath, game.StoreId, await _stores.ReadAsync("play", ct: ct).ConfigureAwait(false));
|
||||
if (record is null)
|
||||
{
|
||||
fallback = PlayFallback.NoStore;
|
||||
@@ -139,25 +139,6 @@ public sealed class GamePlayer
|
||||
return PlayFallback.NoLink;
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<StoreGame>> RecordsAsync(CancellationToken ct)
|
||||
{
|
||||
List<StoreGame> all = [];
|
||||
foreach (IStoreLibrarySource store in _stores)
|
||||
{
|
||||
try
|
||||
{
|
||||
all.AddRange(await store.ListAsync(ct).ConfigureAwait(false));
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
// One store's records that cannot be read are that store's, never the press's.
|
||||
Log.Warning("play: {Store}'s records could not be read ({Message})", store.Platform, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
return all;
|
||||
}
|
||||
|
||||
private async Task<PlayResult> StartDirectlyAsync(GameRow game, PlayFallback fallback, CancellationToken ct)
|
||||
{
|
||||
if (!_agent.IsConnected)
|
||||
|
||||
@@ -50,6 +50,9 @@ internal static class MachineFacingServices
|
||||
services.AddSingleton<IAgentRequests>(static sp => sp.GetRequiredService<AgentConnection>());
|
||||
services.AddSingleton<IAgentLink>(static sp => sp.GetRequiredService<AgentConnection>());
|
||||
|
||||
// FR-3.8's post-session notice (beta.23): one subscription for the App's life, built with the connection's service.
|
||||
services.AddSingleton(static sp => new SessionNotices(sp.GetRequiredService<IAgentLink>(), sp.GetRequiredService<IMessageStrip>(), sp.GetService<IShellPresence>()));
|
||||
|
||||
services.AddSingleton<IRunAtLogon, RunAtLogonRegistry>();
|
||||
services.AddSingleton<IAgentTool, AgentTool>();
|
||||
// beta.21 (D59): Play hands a game to its store's app.
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Globalization;
|
||||
using FrameLedger.Shared.Ipc;
|
||||
|
||||
namespace FrameLedger.App.Services;
|
||||
|
||||
/// <summary>
|
||||
/// FR-3.8's post-session notice inside the App: "saved" or "discarded" in the snackbar while the window is on screen — the
|
||||
/// tray's balloon carries it otherwise (P3 PR-8b, one event → one channel), and a safety stop is never a toast (08_UI
|
||||
/// §Notifications policy). One subscription for the App's life (beta.23).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It lived in the Dashboard's view model, and it reached every page only because no Dashboard ever went away: each visit
|
||||
/// made a new one, the root container kept every one of them (a transient <see cref="IDisposable"/>), and each stayed
|
||||
/// subscribed — twenty visits were twenty notices for one session, of which WPF UI's snackbar showed the last, and twenty
|
||||
/// reloads of the Dashboard's lists on the UI thread (<c>spike-notes</c> §21). The Dashboard now listens only while it is on
|
||||
/// screen, so the notice has its own home.
|
||||
/// </remarks>
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format strings are resources that follow the UI culture, which changes at runtime")]
|
||||
public sealed class SessionNotices : IDisposable
|
||||
{
|
||||
private readonly IAgentLink _agent;
|
||||
private readonly IMessageStrip _strip;
|
||||
private readonly IShellPresence? _presence;
|
||||
private readonly UiThread _ui = new();
|
||||
private readonly Lock _lock = new();
|
||||
|
||||
// The names the start events gave, for a completion that carries none (an Agent before 2026-09-23 sent none).
|
||||
private readonly Dictionary<Guid, string> _names = [];
|
||||
|
||||
public SessionNotices(IAgentLink agent, IMessageStrip strip, IShellPresence? presence = null)
|
||||
{
|
||||
_agent = agent ?? throw new ArgumentNullException(nameof(agent));
|
||||
_strip = strip ?? throw new ArgumentNullException(nameof(strip));
|
||||
_presence = presence;
|
||||
_agent.EventReceived += OnAgentEvent;
|
||||
}
|
||||
|
||||
public void Dispose() => _agent.EventReceived -= OnAgentEvent;
|
||||
|
||||
private void OnAgentEvent(object? sender, AgentEventArgs e)
|
||||
{
|
||||
IpcEnvelope envelope = e.Envelope;
|
||||
if (string.Equals(envelope.Type, IpcMessageType.SessionStarted, StringComparison.Ordinal)
|
||||
&& IpcCodec.Payload<SessionStartedEvent>(envelope) is { GameName: { Length: > 0 } started } start)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_names[start.SessionGuid] = started;
|
||||
}
|
||||
}
|
||||
else if (string.Equals(envelope.Type, IpcMessageType.SessionCompleted, StringComparison.Ordinal)
|
||||
&& IpcCodec.Payload<SessionCompletedEvent>(envelope) is { } completed)
|
||||
{
|
||||
string? known;
|
||||
lock (_lock)
|
||||
{
|
||||
_ = _names.Remove(completed.SessionGuid, out known);
|
||||
}
|
||||
|
||||
// The session's own name (2026-09-23): the Dashboard's card may show another session, and a Tier-2 one had none.
|
||||
string? name = completed.GameName is { Length: > 0 } given ? given : known;
|
||||
_ui.Post(() => Notice(completed, name));
|
||||
}
|
||||
}
|
||||
|
||||
private void Notice(SessionCompletedEvent completed, string? name)
|
||||
{
|
||||
// A faulted session is the strip's CaptureError already; "discarded" would say something that did not happen.
|
||||
if (_presence is { IsShown: false } || string.Equals(completed.Finalize, "faulted", StringComparison.Ordinal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
string game = name is { Length: > 0 } ? name : Strings.Common_NotAvailable;
|
||||
if (completed.SessionId is not null)
|
||||
{
|
||||
_strip.Success(Strings.Dashboard_Live_Header, string.Format(CultureInfo.CurrentCulture, Strings.Dashboard_SessionSaved_Format, game));
|
||||
}
|
||||
else
|
||||
{
|
||||
_strip.Info(Strings.Dashboard_Live_Header, string.Format(CultureInfo.CurrentCulture, Strings.Dashboard_SessionDiscarded_Format, game));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using FrameLedger.Application.Import;
|
||||
using Serilog;
|
||||
|
||||
namespace FrameLedger.App.Services;
|
||||
|
||||
/// <summary>
|
||||
/// The stores' own records of what they installed (beta.23), the lists Play reads to find the store that installed a game
|
||||
/// (<c>StoreRecords.Owning</c>): read on the thread pool. Every store's reader is synchronous work — Steam's manifests are
|
||||
/// files on whatever drive its libraries are on (the owner's: a USB drive), itch's database is copied before it is read —
|
||||
/// and Play ran all of it on the UI thread at every press.
|
||||
/// </summary>
|
||||
public sealed class StoreRecordsReader
|
||||
{
|
||||
private readonly IReadOnlyList<IStoreLibrarySource> _stores;
|
||||
|
||||
public StoreRecordsReader(IEnumerable<IStoreLibrarySource> stores)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stores);
|
||||
_stores = [.. stores];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every record of the stores named in <paramref name="platforms"/> (every store when null), read now. One store whose
|
||||
/// records cannot be read is that store's, logged under <paramref name="purpose"/>, never the caller's.
|
||||
/// </summary>
|
||||
public Task<IReadOnlyList<StoreGame>> ReadAsync(string purpose, IReadOnlyCollection<string>? platforms = null, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(purpose);
|
||||
IStoreLibrarySource[] stores = [.. _stores.Where(s => platforms is null || platforms.Contains(s.Platform, StringComparer.Ordinal))];
|
||||
return Task.Run(async () =>
|
||||
{
|
||||
List<StoreGame> all = [];
|
||||
foreach (IStoreLibrarySource store in stores)
|
||||
{
|
||||
try
|
||||
{
|
||||
all.AddRange(await store.ListAsync(ct).ConfigureAwait(false));
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("{Purpose}: {Store}'s records could not be read ({Message})", purpose, store.Platform, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
return (IReadOnlyList<StoreGame>)all;
|
||||
}, ct);
|
||||
}
|
||||
}
|
||||
@@ -159,7 +159,7 @@ public sealed partial class CompareViewModel : ObservableObject
|
||||
SessionSeries? series = await _loader.LoadAsync(c.Id).ConfigureAwait(true);
|
||||
if (series is not null)
|
||||
{
|
||||
(double[] xs, double[] ys) = PercentileCurve.Of(series.AppFrameTimesMs);
|
||||
(double[] xs, double[] ys) = series.Digest?.Percentiles ?? PercentileCurve.Of(series.AppFrameTimesMs);
|
||||
curves.Add(new CompareCurve(c.Label, xs, ys));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,15 +16,21 @@ namespace FrameLedger.App.ViewModels;
|
||||
/// value <c>N/A</c> until the Agent answered — never a placeholder that reads as a measurement), the live capture
|
||||
/// card fed by the pipe's events, the recent sessions, and the totals strip.
|
||||
/// </summary>
|
||||
public sealed partial class DashboardViewModel : ObservableObject, IDisposable
|
||||
/// <remarks>
|
||||
/// <b>It listens only while its page is on screen (beta.23):</b> <see cref="Attach"/> on Loaded, <see cref="Detach"/> on
|
||||
/// Unloaded, as the Games and game pages do. It subscribed in its constructor and unsubscribed in a Dispose nothing called —
|
||||
/// the root container kept every Dashboard ever opened, each answering every event and reloading its lists on the UI thread
|
||||
/// at every session's end. FR-3.8's notice, which it raised, is <see cref="SessionNotices"/>'s.
|
||||
/// </remarks>
|
||||
public sealed partial class DashboardViewModel : ObservableObject
|
||||
{
|
||||
private readonly IAgentLink _agent;
|
||||
private readonly GameLibrary _library;
|
||||
private readonly GameSelection _selection;
|
||||
private readonly IPageNavigator _navigator;
|
||||
private readonly ISessionSummaryOpener _summaries;
|
||||
private readonly IMessageStrip _strip;
|
||||
private readonly UiThread _ui = new();
|
||||
private bool _attached;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _agentState = Strings.Agent_State_Connecting;
|
||||
@@ -56,27 +62,17 @@ public sealed partial class DashboardViewModel : ObservableObject, IDisposable
|
||||
[ObservableProperty]
|
||||
private bool _recentEmpty = true;
|
||||
|
||||
private readonly IShellPresence? _presence;
|
||||
private readonly LiveSessions? _sessions;
|
||||
|
||||
public DashboardViewModel(IAgentLink agent, GameLibrary library, GameSelection selection, IPageNavigator navigator, ISessionSummaryOpener summaries, IMessageStrip strip, IShellPresence? presence = null,
|
||||
public DashboardViewModel(IAgentLink agent, GameLibrary library, GameSelection selection, IPageNavigator navigator, ISessionSummaryOpener summaries,
|
||||
LiveSessions? sessions = null)
|
||||
{
|
||||
_presence = presence;
|
||||
_sessions = sessions;
|
||||
_agent = agent ?? throw new ArgumentNullException(nameof(agent));
|
||||
_library = library ?? throw new ArgumentNullException(nameof(library));
|
||||
_selection = selection ?? throw new ArgumentNullException(nameof(selection));
|
||||
_navigator = navigator ?? throw new ArgumentNullException(nameof(navigator));
|
||||
_summaries = summaries ?? throw new ArgumentNullException(nameof(summaries));
|
||||
_strip = strip ?? throw new ArgumentNullException(nameof(strip));
|
||||
_agent.Changed += OnAgentChanged;
|
||||
_agent.EventReceived += OnAgentEvent;
|
||||
if (_sessions is not null)
|
||||
{
|
||||
_sessions.Changed += OnSessionsChanged;
|
||||
}
|
||||
|
||||
Refresh();
|
||||
SeedLive();
|
||||
Pending = LoadAsync();
|
||||
@@ -103,14 +99,44 @@ public sealed partial class DashboardViewModel : ObservableObject, IDisposable
|
||||
/// <summary>The load in flight, for a test to await.</summary>
|
||||
public Task Pending { get; private set; }
|
||||
|
||||
public void Dispose()
|
||||
/// <summary>
|
||||
/// Listens to the Agent and to the running sessions while the page is on screen (beta.23): the page calls it on Loaded
|
||||
/// and <see cref="Detach"/> on Unloaded. What changed before it listened is read again here.
|
||||
/// </summary>
|
||||
public void Attach()
|
||||
{
|
||||
if (_attached)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_agent.Changed += OnAgentChanged;
|
||||
_agent.EventReceived += OnAgentEvent;
|
||||
if (_sessions is not null)
|
||||
{
|
||||
_sessions.Changed += OnSessionsChanged;
|
||||
}
|
||||
|
||||
_attached = true;
|
||||
Refresh();
|
||||
SeedLive();
|
||||
}
|
||||
|
||||
public void Detach()
|
||||
{
|
||||
if (!_attached)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_agent.Changed -= OnAgentChanged;
|
||||
_agent.EventReceived -= OnAgentEvent;
|
||||
if (_sessions is not null)
|
||||
{
|
||||
_sessions.Changed -= OnSessionsChanged;
|
||||
}
|
||||
|
||||
_attached = false;
|
||||
}
|
||||
|
||||
public async Task LoadAsync(CancellationToken ct = default)
|
||||
@@ -191,10 +217,8 @@ public sealed partial class DashboardViewModel : ObservableObject, IDisposable
|
||||
Live.Hold(held);
|
||||
break;
|
||||
case IpcMessageType.SessionCompleted when IpcCodec.Payload<SessionCompletedEvent>(envelope) is { } completed:
|
||||
// The session's own name (2026-09-23): the card may show another session, and a Tier-2 one had none here.
|
||||
string? name = completed.GameName ?? (Live.SessionGuid == completed.SessionGuid ? Live.GameName : null);
|
||||
// FR-3.8's notice is SessionNotices' (beta.23); the card and the lists are this page's.
|
||||
Live.Stop(completed);
|
||||
Notice(completed, name);
|
||||
SeedLive();
|
||||
Pending = LoadAsync();
|
||||
break;
|
||||
@@ -203,27 +227,6 @@ public sealed partial class DashboardViewModel : ObservableObject, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>FR-3.8's post-session notice, in-app while the window is on screen; the tray's balloon carries it otherwise (P3 PR-8b, one event → one channel). A safety stop is never a toast (08_UI §Notifications policy) — the shell's notices carry those.</summary>
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format string is a resource that follows the UI culture, which changes at runtime")]
|
||||
private void Notice(SessionCompletedEvent completed, string? name)
|
||||
{
|
||||
// A faulted session is the strip's CaptureError already; "discarded" would say something that did not happen.
|
||||
if (_presence is { IsShown: false } || string.Equals(completed.Finalize, "faulted", StringComparison.Ordinal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
string game = name is { Length: > 0 } ? name : Strings.Common_NotAvailable;
|
||||
if (completed.SessionId is not null)
|
||||
{
|
||||
_strip.Success(Strings.Dashboard_Live_Header, string.Format(CultureInfo.CurrentCulture, Strings.Dashboard_SessionSaved_Format, game));
|
||||
}
|
||||
else
|
||||
{
|
||||
_strip.Info(Strings.Dashboard_Live_Header, string.Format(CultureInfo.CurrentCulture, Strings.Dashboard_SessionDiscarded_Format, game));
|
||||
}
|
||||
}
|
||||
|
||||
private void Refresh()
|
||||
{
|
||||
AgentState = AgentStatusPresentation.Pill(_agent.State).Text;
|
||||
|
||||
@@ -49,6 +49,7 @@ public sealed partial class GameDetailViewModel : ObservableObject
|
||||
private readonly RegisteredSettings? _settings;
|
||||
private readonly AntiCheatExceptions? _exceptions;
|
||||
private readonly SessionDeletion? _deletion;
|
||||
private readonly Func<string, bool> _exists;
|
||||
private readonly long? _gameId;
|
||||
|
||||
// ui.hide_anticheat_hooking (2026-09-25), read at each load; on until the settings say otherwise, as its default is.
|
||||
@@ -76,6 +77,17 @@ public sealed partial class GameDetailViewModel : ObservableObject
|
||||
[NotifyCanExecuteChangedFor(nameof(PlayCommand))]
|
||||
private bool _executableMissing;
|
||||
|
||||
/// <summary>
|
||||
/// The missing executable's bar (beta.8): the page's sentence, then whether the DRIVE is not connected or the file is gone
|
||||
/// from its path — the two need different things of the user. Worked out with the check, off the UI thread (beta.23): it
|
||||
/// asked the drive from this property's getter, on the UI thread, at every read.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _executableMissingMessage = ExecutableMissingText;
|
||||
|
||||
// Why the executable is missing, from the last load's check (beta.23); null while it was found.
|
||||
private string? _executableMissingWhy;
|
||||
|
||||
/// <summary>What Play will do, in the mode Settings ▸ Games has now (beta.21, D59).</summary>
|
||||
[ObservableProperty]
|
||||
private string _playToolTip = Strings.Play_ToolTip_Store;
|
||||
@@ -233,8 +245,11 @@ public sealed partial class GameDetailViewModel : ObservableObject
|
||||
IConfirmations confirmations, IEditGamePrompt edit, IMessageStrip strip, ISessionSummaryOpener summaries,
|
||||
SessionSeriesLoader loader, IHardwareSnapshotRepository hardware, SessionSelection sessionSelection, IGamePicker picker,
|
||||
RegisteredSettings? settings = null, IAgentLink? agent = null, AntiCheatExceptions? exceptions = null, SessionDeletion? deletion = null,
|
||||
UiMode? mode = null, GamePlayer? player = null)
|
||||
UiMode? mode = null, GamePlayer? player = null, Func<string, bool>? executableExists = null)
|
||||
{
|
||||
// beta.23: whether the executable is on disk is a question for its drive, which can take seconds to answer (the
|
||||
// owner's games are on a USB drive), so it is asked off the UI thread, as the library page has asked since beta.19.
|
||||
_exists = executableExists ?? GameLibrary.ExecutableExists;
|
||||
// beta.15 (D52): a viewer over a copy has no Agent to ask; a composition without a mode (a test) is the profile's App.
|
||||
_player = player;
|
||||
_mode = mode ?? UiMode.Profile;
|
||||
@@ -282,14 +297,6 @@ public sealed partial class GameDetailViewModel : ObservableObject
|
||||
|
||||
public static string ExecutableMissingText => Strings.GameDetail_ExeMissing;
|
||||
|
||||
/// <summary>
|
||||
/// The missing executable's bar (beta.8): the page's sentence, then whether the DRIVE is not connected or the file is gone
|
||||
/// from its path — the two need different things of the user.
|
||||
/// </summary>
|
||||
public string ExecutableMissingMessage => Game is null
|
||||
? ExecutableMissingText
|
||||
: ExecutableMissingText + " " + Formats.ExecutableMissingText(Game.Fingerprint.ExePath);
|
||||
|
||||
public static string LifetimeLabel => Strings.GameDetail_LifetimeAvg;
|
||||
|
||||
public static string SupportsHeader => Strings.GameDetail_Supports_Header;
|
||||
@@ -455,6 +462,10 @@ public sealed partial class GameDetailViewModel : ObservableObject
|
||||
return;
|
||||
}
|
||||
|
||||
string exePath = detail.Row.Fingerprint.ExePath;
|
||||
Func<string, bool> exists = _exists;
|
||||
_executableMissingWhy = await Task.Run(() => exists(exePath) ? null : Formats.ExecutableMissingText(exePath), ct).ConfigureAwait(true);
|
||||
|
||||
Game = detail.Row;
|
||||
_detail = detail;
|
||||
NotFound = false;
|
||||
@@ -1019,7 +1030,7 @@ public sealed partial class GameDetailViewModel : ObservableObject
|
||||
HookingConsentOutcome.Unanswered => (Strings.Agent_Unanswered, InfoBarSeverity.Warning),
|
||||
// The Agent could not read the executable (beta.8): say whether its drive or the file is missing, not the IPC code.
|
||||
HookingConsentOutcome.Failed when string.Equals(result.Detail, Shared.Ipc.IpcErrorCode.ExecutableUnreadable, StringComparison.Ordinal) && Game is not null
|
||||
=> (Formats.ExecutableMissingText(Game.Fingerprint.ExePath), InfoBarSeverity.Warning),
|
||||
=> (_executableMissingWhy ?? Formats.ExecutableMissingText(Game.Fingerprint.ExePath), InfoBarSeverity.Warning),
|
||||
HookingConsentOutcome.Failed => (result.Detail ?? Strings.Common_NotAvailable, InfoBarSeverity.Warning),
|
||||
_ => (null, InfoBarSeverity.Informational),
|
||||
};
|
||||
@@ -1037,8 +1048,8 @@ public sealed partial class GameDetailViewModel : ObservableObject
|
||||
: [row.Publisher, row.GameVersion, Formats.Platform(row.Platform), EngineText(row)];
|
||||
Subtitle = string.Join(" · ", subtitle.Where(static s => !string.IsNullOrWhiteSpace(s)));
|
||||
ExecutableText = row.Fingerprint.ExePath;
|
||||
ExecutableMissing = !GameLibrary.ExecutableExists(row.Fingerprint.ExePath);
|
||||
OnPropertyChanged(nameof(ExecutableMissingMessage));
|
||||
ExecutableMissing = _executableMissingWhy is not null;
|
||||
ExecutableMissingMessage = _executableMissingWhy is { } why ? ExecutableMissingText + " " + why : ExecutableMissingText;
|
||||
|
||||
SessionRow? last = detail.Sessions.Count > 0 ? detail.Sessions[0] : null;
|
||||
SessionRow? lastHooked = detail.Sessions.FirstOrDefault(static s => s.Tier == CaptureTier.Hooked && s.FrameCount > 0);
|
||||
|
||||
@@ -19,7 +19,7 @@ namespace FrameLedger.App.ViewModels;
|
||||
/// Loaded/Unloaded) and never while paused; the read runs off the UI thread and the result lands on it.
|
||||
/// </summary>
|
||||
[SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format strings are resources that follow the UI culture, which changes at runtime")]
|
||||
public sealed partial class LogsViewModel : ObservableObject, IDisposable
|
||||
public sealed partial class LogsViewModel : ObservableObject
|
||||
{
|
||||
public static readonly TimeSpan RefreshPeriod = TimeSpan.FromSeconds(2);
|
||||
|
||||
@@ -31,6 +31,9 @@ public sealed partial class LogsViewModel : ObservableObject, IDisposable
|
||||
private IReadOnlyList<string> _lines = [];
|
||||
private ITimer? _timer;
|
||||
|
||||
// What the last read read (beta.23): a tick that finds the newest file unchanged reads nothing and redraws nothing.
|
||||
private (string? File, long Length, DateTime WrittenUtc) _read;
|
||||
|
||||
[ObservableProperty]
|
||||
private LogSource _source = LogSource.Ui;
|
||||
|
||||
@@ -93,15 +96,17 @@ public sealed partial class LogsViewModel : ObservableObject, IDisposable
|
||||
_timer = _clock.CreateTimer(_ => _ui.Post(Tick), null, RefreshPeriod, RefreshPeriod);
|
||||
}
|
||||
|
||||
/// <summary>Stops it (the page's Unloaded) — a page that is not shown reads nothing.</summary>
|
||||
/// <summary>
|
||||
/// Stops it (the page's Unloaded) — a page that is not shown reads nothing. Not <see cref="IDisposable"/> (beta.23): the
|
||||
/// root container kept every transient disposable it made, so every Logs page ever opened stayed in memory with its
|
||||
/// up-to-2-MB tail, twice (the lines and the text).
|
||||
/// </summary>
|
||||
public void Stop()
|
||||
{
|
||||
_timer?.Dispose();
|
||||
_timer = null;
|
||||
}
|
||||
|
||||
public void Dispose() => Stop();
|
||||
|
||||
public Task RefreshAsync() => Pending = RefreshCoreAsync();
|
||||
|
||||
partial void OnSourceChanged(LogSource value) => Pending = RefreshCoreAsync();
|
||||
@@ -131,28 +136,83 @@ public sealed partial class LogsViewModel : ObservableObject, IDisposable
|
||||
{
|
||||
if (!IsPaused)
|
||||
{
|
||||
Pending = RefreshCoreAsync();
|
||||
Pending = RefreshIfChangedAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RefreshCoreAsync()
|
||||
/// <summary>What a tick does: the tail again only when the newest file changed since the last read.</summary>
|
||||
internal Task RefreshIfChangedAsync() => RefreshCoreAsync(unlessUnchanged: true);
|
||||
|
||||
/// <summary>
|
||||
/// Reads the newest file's tail and shows it through the filters. A tick (<paramref name="unlessUnchanged"/>) whose file
|
||||
/// has the length and the write time of the last read stops there (beta.23): it re-read up to 2 MB and replaced the whole
|
||||
/// text every two seconds while nothing had been written. The filtering and the joining happen off the UI thread too.
|
||||
/// </summary>
|
||||
private async Task RefreshCoreAsync(bool unlessUnchanged = false)
|
||||
{
|
||||
LogSource source = Source;
|
||||
(string? file, IReadOnlyList<string> lines) = await Task.Run(() =>
|
||||
LogLevelFilter level = Level;
|
||||
string search = Search;
|
||||
(string? File, long Length, DateTime WrittenUtc) last = _read;
|
||||
(bool unchanged, (string? File, long Length, DateTime WrittenUtc) read, IReadOnlyList<string> lines, IReadOnlyList<string> shown, string text) = await Task.Run(() =>
|
||||
{
|
||||
string? newest = _tail.NewestFile(source);
|
||||
return (newest, newest is null ? [] : LogTail.ReadLines(newest));
|
||||
(string? File, long Length, DateTime WrittenUtc) stamp = Stamp(newest);
|
||||
if (unlessUnchanged && stamp.File is not null && stamp == last)
|
||||
{
|
||||
return (true, stamp, (IReadOnlyList<string>)[], (IReadOnlyList<string>)[], string.Empty);
|
||||
}
|
||||
|
||||
IReadOnlyList<string> all = newest is null ? [] : LogTail.ReadLines(newest);
|
||||
IReadOnlyList<string> filtered = LogTail.Filter(all, level, search);
|
||||
return (false, stamp, all, filtered, string.Join(Environment.NewLine, filtered));
|
||||
}).ConfigureAwait(true);
|
||||
CurrentFile = file;
|
||||
if (unchanged)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_read = read;
|
||||
CurrentFile = read.File;
|
||||
_lines = lines;
|
||||
Apply();
|
||||
if (level == Level && string.Equals(search, Search, StringComparison.Ordinal))
|
||||
{
|
||||
Show(shown, text);
|
||||
}
|
||||
else
|
||||
{
|
||||
Apply(); // the filters changed while the file was read
|
||||
}
|
||||
}
|
||||
|
||||
private static (string? File, long Length, DateTime WrittenUtc) Stamp(string? file)
|
||||
{
|
||||
if (file is null)
|
||||
{
|
||||
return (null, 0, default);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var info = new FileInfo(file);
|
||||
return info.Exists ? (file, info.Length, info.LastWriteTimeUtc) : (file, -1, default);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return (file, -1, default);
|
||||
}
|
||||
}
|
||||
|
||||
private void Apply()
|
||||
{
|
||||
IReadOnlyList<string> shown = LogTail.Filter(_lines, Level, Search);
|
||||
Show(shown, string.Join(Environment.NewLine, shown));
|
||||
}
|
||||
|
||||
private void Show(IReadOnlyList<string> shown, string text)
|
||||
{
|
||||
ShownCount = shown.Count;
|
||||
Text = string.Join(Environment.NewLine, shown);
|
||||
Text = text;
|
||||
Status = CurrentFile is null
|
||||
? Strings.Logs_Empty
|
||||
: string.Format(CultureInfo.CurrentCulture, Strings.Logs_Showing_Format, ShownCount, TotalCount, Path.GetFileName(CurrentFile));
|
||||
|
||||
@@ -47,21 +47,6 @@ public sealed class DashboardViewModelTests
|
||||
public void Open(long sessionId) => Opened.Add(sessionId);
|
||||
}
|
||||
|
||||
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 FakeNavigator : IPageNavigator
|
||||
{
|
||||
public List<string> Pages { get; } = [];
|
||||
@@ -83,7 +68,8 @@ public sealed class DashboardViewModelTests
|
||||
var nav = new FakeNavigator();
|
||||
|
||||
var summaries = new NoSummaries();
|
||||
using var vm = new DashboardViewModel(link, s.Library, selection, nav, summaries, new NoStrip());
|
||||
var vm = new DashboardViewModel(link, s.Library, selection, nav, summaries);
|
||||
vm.Attach();
|
||||
Task pending1 = vm.Pending;
|
||||
await pending1;
|
||||
|
||||
@@ -111,7 +97,8 @@ public sealed class DashboardViewModelTests
|
||||
await using ScratchLedger s = await ScratchLedger.OpenAsync();
|
||||
GameRow game = await s.GameAsync("Alpha");
|
||||
var link = new FakeLink();
|
||||
using var vm = new DashboardViewModel(link, s.Library, new GameSelection(), new FakeNavigator(), new NoSummaries(), new NoStrip());
|
||||
var vm = new DashboardViewModel(link, s.Library, new GameSelection(), new FakeNavigator(), new NoSummaries());
|
||||
vm.Attach();
|
||||
Task pending2 = vm.Pending;
|
||||
await pending2;
|
||||
vm.Live.IsActive.Should().BeFalse();
|
||||
@@ -178,7 +165,9 @@ public sealed class DashboardViewModelTests
|
||||
};
|
||||
using var sessions = new LiveSessions(link);
|
||||
var strip = new RecordingStrip();
|
||||
using var vm = new DashboardViewModel(link, s.Library, new GameSelection(), new FakeNavigator(), new NoSummaries(), strip, sessions: sessions);
|
||||
using var notices = new SessionNotices(link, strip);
|
||||
var vm = new DashboardViewModel(link, s.Library, new GameSelection(), new FakeNavigator(), new NoSummaries(), sessions: sessions);
|
||||
vm.Attach();
|
||||
Task loaded = vm.Pending;
|
||||
await loaded;
|
||||
|
||||
@@ -207,7 +196,9 @@ public sealed class DashboardViewModelTests
|
||||
var link = new FakeLink();
|
||||
using var sessions = new LiveSessions(link);
|
||||
var strip = new RecordingStrip();
|
||||
using var vm = new DashboardViewModel(link, s.Library, new GameSelection(), new FakeNavigator(), new NoSummaries(), strip, sessions: sessions);
|
||||
using var notices = new SessionNotices(link, strip);
|
||||
var vm = new DashboardViewModel(link, s.Library, new GameSelection(), new FakeNavigator(), new NoSummaries(), sessions: sessions);
|
||||
vm.Attach();
|
||||
Task loaded = vm.Pending;
|
||||
await loaded;
|
||||
var hooked = Guid.NewGuid();
|
||||
@@ -228,4 +219,74 @@ public sealed class DashboardViewModelTests
|
||||
strip.Shown.Should().ContainSingle("a faulted session is the strip's CaptureError already; \"discarded\" would say what did not happen");
|
||||
vm.Live.IsActive.Should().BeFalse();
|
||||
}
|
||||
/// <summary>
|
||||
/// beta.23: a Dashboard hears the Agent only while its page is on screen. Every visit made a new one and none went
|
||||
/// away — the root container kept them all, each subscribed — so each session's end reloaded every Dashboard ever
|
||||
/// opened, on the UI thread, and raised one notice apiece.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ADashboardOffScreenHearsNothingAndASessionHasOneNoticeHoweverManyWereOpened()
|
||||
{
|
||||
await using ScratchLedger s = await ScratchLedger.OpenAsync();
|
||||
GameRow game = await s.GameAsync("Alpha");
|
||||
var link = new FakeLink();
|
||||
var strip = new RecordingStrip();
|
||||
using var notices = new SessionNotices(link, strip);
|
||||
var visits = new List<DashboardViewModel>();
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
// What navigating does: the page on screen is attached, the one it replaced detached.
|
||||
visits.LastOrDefault()?.Detach();
|
||||
var vm = new DashboardViewModel(link, s.Library, new GameSelection(), new FakeNavigator(), new NoSummaries());
|
||||
vm.Attach();
|
||||
visits.Add(vm);
|
||||
Task pending = vm.Pending;
|
||||
await pending;
|
||||
}
|
||||
|
||||
var guid = Guid.NewGuid();
|
||||
link.Raise(IpcMessageType.SessionStarted, new SessionStartedEvent(guid, game.Id, "Alpha", 4242, 1, DateTimeOffset.UtcNow));
|
||||
visits[^1].Live.IsActive.Should().BeTrue("the Dashboard on screen follows the session");
|
||||
visits.Take(4).Should().OnlyContain(static v => !v.Live.IsActive, "a Dashboard that was navigated away from hears nothing");
|
||||
|
||||
long id = await s.SessionAsync(game.Id, DateTimeOffset.UtcNow.AddMinutes(-2), seconds: 65);
|
||||
link.Raise(IpcMessageType.SessionCompleted, new SessionCompletedEvent(guid, id, "normal", 1, "saved", "TargetExited"));
|
||||
Task reloaded = visits[^1].Pending;
|
||||
await reloaded;
|
||||
|
||||
strip.Shown.Should().ContainSingle("one session, one notice — it was one per Dashboard ever opened")
|
||||
.Which.Body.Should().Contain("Alpha", "the name the start gave, for a completion that carries none");
|
||||
visits[^1].Recent.Should().ContainSingle();
|
||||
visits.Take(4).Should().OnlyContain(static v => v.Recent.Count == 0, "only the Dashboard on screen reloads its lists");
|
||||
}
|
||||
|
||||
/// <summary>FR-3.8 (beta.23): the notice is the window's while it is shown; a hidden window leaves it to the tray's balloon.</summary>
|
||||
[Fact]
|
||||
public void ANoticeWaitsForTheWindowAndATrayBalloonCarriesItWhenHidden()
|
||||
{
|
||||
var link = new FakeLink();
|
||||
var strip = new RecordingStrip();
|
||||
var presence = new Presence { IsShown = false };
|
||||
using var notices = new SessionNotices(link, strip, presence);
|
||||
|
||||
link.Raise(IpcMessageType.SessionCompleted, new SessionCompletedEvent(Guid.NewGuid(), 7, "normal", 1, "saved", "TargetExited", 1, "Alpha"));
|
||||
strip.Shown.Should().BeEmpty("the window is hidden: TrayViewModel's balloon says it");
|
||||
|
||||
presence.IsShown = true;
|
||||
link.Raise(IpcMessageType.SessionCompleted, new SessionCompletedEvent(Guid.NewGuid(), 8, "normal", 1, "saved", "TargetExited", 1, "Alpha"));
|
||||
strip.Shown.Should().ContainSingle().Which.Kind.Should().Be("success");
|
||||
}
|
||||
|
||||
private sealed class Presence : IShellPresence
|
||||
{
|
||||
public bool IsShown { get; set; }
|
||||
|
||||
public void Reveal()
|
||||
{
|
||||
}
|
||||
|
||||
public void Quit()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1032,6 +1032,47 @@ public sealed class GameDetailViewModelTests
|
||||
vm.Sessions.Should().HaveCount(2, "the page left: nothing listens");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// beta.23: whether the executable is on disk is asked off the UI thread — a USB drive that sleeps, or one that fails,
|
||||
/// answered on the UI thread while the page opened (the library page has asked off it since beta.19) — and the bar says
|
||||
/// why from that one answer, with no drive asked again by a property getter.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task TheExecutableIsLookedForOffTheThreadThatOpensThePage()
|
||||
{
|
||||
await using ScratchLedger s = await ScratchLedger.OpenAsync();
|
||||
GameRow game = await s.GameAsync("Alpha");
|
||||
var asked = new List<int>();
|
||||
bool Exists(string path)
|
||||
{
|
||||
lock (asked)
|
||||
{
|
||||
asked.Add(Environment.CurrentManagedThreadId);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
int opener = 0;
|
||||
GameDetailViewModel? vm = null;
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
opener = Environment.CurrentManagedThreadId;
|
||||
vm = new GameDetailViewModel(s.Library, new GameSelection { GameId = game.Id }, new HookingConsent(new FakeAgent(), new FakePrompt()), new FakeNavigator(),
|
||||
new FakeConfirmations(RemoveGameChoice.Cancel), new FakeEdit(null), new FakeStrip(), new NoSummaries(),
|
||||
new Charts.SessionSeriesLoader(s.Sessions), new Infrastructure.Persistence.SqliteHardwareSnapshotRepository(s.Db), new SessionSelection(),
|
||||
new FakePicker(null), executableExists: Exists);
|
||||
});
|
||||
thread.Start();
|
||||
thread.Join();
|
||||
Task loaded = vm!.Pending;
|
||||
await loaded;
|
||||
|
||||
asked.Should().ContainSingle().Which.Should().NotBe(opener, "the drive is asked on the thread pool, never on the thread that opens the page");
|
||||
vm.ExecutableMissing.Should().BeTrue();
|
||||
vm.ExecutableMissingMessage.Should().StartWith(GameDetailViewModel.ExecutableMissingText).And.Contain(Path.GetFileName(game.Fingerprint.ExePath));
|
||||
}
|
||||
|
||||
/// <summary>beta.8: a session that was not hooked has its sensors, and the Sensors tab draws them instead of saying "not hooked".</summary>
|
||||
[Fact]
|
||||
public async Task ATierTwoSessionsSensorsAreTheSensorsTabs()
|
||||
|
||||
@@ -46,7 +46,7 @@ public sealed class LogsViewModelTests : IDisposable
|
||||
Write("ui-20260914.log", "[12:00:00.000 INF] hello\n[12:00:00.001 WRN] careful\n");
|
||||
Write("agent-20260914.log", "[12:00:00.000 INF] agent here\n");
|
||||
var strip = new RecordingStrip();
|
||||
using var vm = new LogsViewModel(new LogTail(_dir), new BugReportFlow(new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))), new PathSaver(null), new FakeAgentLink(), new ClosePreview(), new NoUrlOpener(), new NoClipboard(), strip), strip);
|
||||
var vm = new LogsViewModel(new LogTail(_dir), new BugReportFlow(new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))), new PathSaver(null), new FakeAgentLink(), new ClosePreview(), new NoUrlOpener(), new NoClipboard(), strip), strip);
|
||||
Task pending1 = vm.Pending;
|
||||
await pending1;
|
||||
|
||||
@@ -69,11 +69,36 @@ public sealed class LogsViewModelTests : IDisposable
|
||||
vm.Text.Should().Contain("agent here");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// beta.23: the tail's two-second tick re-read up to 2 MB and replaced the whole text while nothing had been written; it
|
||||
/// reads again only when the newest file's length or write time changed.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ATickReadsTheTailAgainOnlyWhenTheFileChanged()
|
||||
{
|
||||
await using ScratchLedger s = await ScratchLedger.OpenAsync();
|
||||
Write("ui-20260914.log", "[12:00:00.000 INF] one\n");
|
||||
var strip = new RecordingStrip();
|
||||
var vm = new LogsViewModel(new LogTail(_dir), new BugReportFlow(new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))), new PathSaver(null), new FakeAgentLink(), new ClosePreview(), new NoUrlOpener(), new NoClipboard(), strip), strip);
|
||||
Task first = vm.Pending;
|
||||
await first;
|
||||
vm.Text.Should().Be("[12:00:00.000 INF] one");
|
||||
|
||||
vm.Text = "drawn";
|
||||
await vm.RefreshIfChangedAsync();
|
||||
vm.Text.Should().Be("drawn", "nothing was written since the last read: a tick reads nothing and redraws nothing");
|
||||
|
||||
await File.AppendAllTextAsync(Path.Combine(_dir, "ui-20260914.log"), "[12:00:01.000 INF] two\n", TestContext.Current.CancellationToken);
|
||||
await vm.RefreshIfChangedAsync();
|
||||
vm.Text.Should().Contain("two").And.Contain("one");
|
||||
vm.TotalCount.Should().Be(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WithoutAFileTheStatusSaysSo()
|
||||
{
|
||||
await using ScratchLedger s = await ScratchLedger.OpenAsync();
|
||||
using var vm = new LogsViewModel(new LogTail(_dir), new BugReportFlow(new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))), new PathSaver(null), new FakeAgentLink(), new ClosePreview(), new NoUrlOpener(), new NoClipboard(), new RecordingStrip()), new RecordingStrip());
|
||||
var vm = new LogsViewModel(new LogTail(_dir), new BugReportFlow(new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))), new PathSaver(null), new FakeAgentLink(), new ClosePreview(), new NoUrlOpener(), new NoClipboard(), new RecordingStrip()), new RecordingStrip());
|
||||
Task pending = vm.Pending;
|
||||
await pending;
|
||||
|
||||
@@ -91,7 +116,7 @@ public sealed class LogsViewModelTests : IDisposable
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(zip)!);
|
||||
var saver = new PathSaver(zip);
|
||||
var strip = new RecordingStrip();
|
||||
using var vm = new LogsViewModel(new LogTail(_dir), new BugReportFlow(new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))), saver, new FakeAgentLink(), new ClosePreview(), new NoUrlOpener(), new NoClipboard(), strip), strip);
|
||||
var vm = new LogsViewModel(new LogTail(_dir), new BugReportFlow(new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))), saver, new FakeAgentLink(), new ClosePreview(), new NoUrlOpener(), new NoClipboard(), strip), strip);
|
||||
Task pending1 = vm.Pending;
|
||||
await pending1;
|
||||
|
||||
@@ -109,7 +134,7 @@ public sealed class LogsViewModelTests : IDisposable
|
||||
{
|
||||
await using ScratchLedger s = await ScratchLedger.OpenAsync();
|
||||
var strip = new RecordingStrip();
|
||||
using var vm = new LogsViewModel(new LogTail(_dir), new BugReportFlow(new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))), new PathSaver(null), new FakeAgentLink(), new ClosePreview(), new NoUrlOpener(), new NoClipboard(), strip), strip);
|
||||
var vm = new LogsViewModel(new LogTail(_dir), new BugReportFlow(new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))), new PathSaver(null), new FakeAgentLink(), new ClosePreview(), new NoUrlOpener(), new NoClipboard(), strip), strip);
|
||||
|
||||
await vm.ExportBundleCommand.ExecuteAsync(null);
|
||||
|
||||
|
||||
@@ -5,9 +5,11 @@ using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.App.Charts;
|
||||
using FrameLedger.App.Pages;
|
||||
using FrameLedger.App.Services;
|
||||
using FrameLedger.App.ViewModels;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Infrastructure.Persistence;
|
||||
using Wpf.Ui.Controls;
|
||||
|
||||
@@ -49,7 +51,6 @@ public sealed partial class PagesLoadTests
|
||||
await using ScratchLedger s = await ScratchLedger.OpenAsync();
|
||||
var consent = new HookingConsent(new NoAgent(), new NoPrompt());
|
||||
(SettingsViewModel settings, LogsViewModel logs) = await SettingsAndLogsAsync(s, consent, new NoStrip());
|
||||
using LogsViewModel ownedLogs = logs;
|
||||
|
||||
(bool Wrapped, double Offset) result = await OnStaAsync(() =>
|
||||
{
|
||||
@@ -71,7 +72,6 @@ public sealed partial class PagesLoadTests
|
||||
await using ScratchLedger s = await ScratchLedger.OpenAsync();
|
||||
var consent = new HookingConsent(new NoAgent(), new NoPrompt());
|
||||
(_, LogsViewModel logs) = await SettingsAndLogsAsync(s, consent, new NoStrip());
|
||||
using LogsViewModel ownedLogs = logs;
|
||||
|
||||
(double Height, double Offset) tail = await OnStaAsync(() =>
|
||||
{
|
||||
@@ -87,4 +87,46 @@ public sealed partial class PagesLoadTests
|
||||
tail.Height.Should().BeLessThan(500, "the tail has the height the page leaves it, not one tall enough for every line");
|
||||
tail.Offset.Should().BeGreaterThan(0, "so it scrolls, and ScrollToEnd (autoscroll) shows the newest line");
|
||||
}
|
||||
/// <summary>
|
||||
/// beta.23: the game page's Sessions grid is bounded, so it builds the rows on screen and scrolls itself. Inside the page's
|
||||
/// own scroller it was measured with no height limit and built every row - 100 sessions were 100 rows of 17 columns at
|
||||
/// every open, 1.2 s (spike-notes 21). The wheel over it still reaches the page once the grid can scroll no further.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task TheSessionsGridBuildsTheRowsOnScreenAndHandsTheWheelOnAtItsEnd()
|
||||
{
|
||||
await using ScratchLedger s = await ScratchLedger.OpenAsync();
|
||||
GameRow game = await s.GameAsync("Alpha");
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
await s.SessionAsync(game.Id, DateTimeOffset.UtcNow.AddHours(-i - 1));
|
||||
}
|
||||
|
||||
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 Rows, double PageBefore, double PageAfter, double GridOffset) result = await OnStaAsync(() =>
|
||||
{
|
||||
var page = new GameDetailPage(detail);
|
||||
NavigationViewContentPresenter presenter = Navigated(page, 900);
|
||||
int rows = Visuals.FindAll<DataGridRow>(page).Count();
|
||||
System.Windows.Controls.DataGrid grid = Visuals.Find<System.Windows.Controls.DataGrid>(page)!;
|
||||
System.Windows.Controls.ScrollViewer gridScroller = Visuals.Find<System.Windows.Controls.ScrollViewer>(grid)!;
|
||||
System.Windows.Controls.ScrollViewer root = Visuals.Find<System.Windows.Controls.ScrollViewer>(page)!;
|
||||
gridScroller.ScrollToEnd();
|
||||
presenter.UpdateLayout();
|
||||
double before = root.VerticalOffset;
|
||||
Wheel(Visuals.Leaf(Visuals.FindAll<DataGridRow>(grid).Last()), -120);
|
||||
presenter.UpdateLayout();
|
||||
return (rows, before, root.VerticalOffset, gridScroller.VerticalOffset);
|
||||
});
|
||||
|
||||
detail.Sessions.Should().HaveCount(100);
|
||||
result.Rows.Should().BeInRange(1, 40, "only the rows the bounded grid shows are built");
|
||||
result.GridOffset.Should().BeGreaterThan(0, "the grid scrolls its own rows");
|
||||
result.PageAfter.Should().BeGreaterThan(result.PageBefore, "at the grid's end the wheel scrolls the page");
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,7 @@ public sealed partial class PagesLoadTests
|
||||
var consent = new HookingConsent(new NoAgent(), new NoPrompt());
|
||||
|
||||
// The view models load off the STA thread; the pages bind to them on it.
|
||||
Dashboard = Own(new DashboardViewModel(new NoAgent(), s.Library, selection, nav, new NoSummaries(), strip));
|
||||
Dashboard = new DashboardViewModel(new NoAgent(), s.Library, selection, nav, new NoSummaries());
|
||||
Task pending1 = Dashboard.Pending;
|
||||
await pending1.ConfigureAwait(false);
|
||||
Games = new GamesViewModel(s.Library, selection, nav, new AddGameFlow(s.Library, new NoPicker(), selection, nav, strip));
|
||||
@@ -95,7 +95,7 @@ public sealed partial class PagesLoadTests
|
||||
await pending4.ConfigureAwait(false);
|
||||
(SettingsViewModel settings, LogsViewModel logs) = await SettingsAndLogsAsync(s, consent, strip).ConfigureAwait(false);
|
||||
Settings = settings;
|
||||
Logs = Own(logs);
|
||||
Logs = logs;
|
||||
}
|
||||
|
||||
/// <summary>Every surface by name, each with a builder to call on the STA thread.</summary>
|
||||
|
||||
@@ -547,7 +547,7 @@ public sealed partial class PagesLoadTests
|
||||
var consent = new HookingConsent(new NoAgent(), new NoPrompt());
|
||||
|
||||
// The view models load off the STA thread; the pages bind to them on it.
|
||||
using var dashboard = new DashboardViewModel(new NoAgent(), s.Library, selection, nav, new NoSummaries(), strip);
|
||||
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);
|
||||
@@ -561,7 +561,6 @@ public sealed partial class PagesLoadTests
|
||||
Task pending4 = compare.Pending;
|
||||
await pending4;
|
||||
(SettingsViewModel settings, LogsViewModel logs) = await SettingsAndLogsAsync(s, consent, strip);
|
||||
using LogsViewModel _ = logs;
|
||||
|
||||
(string loaded, List<string> wrapped) = await OnStaAsync(() =>
|
||||
{
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using FluentAssertions;
|
||||
using FrameLedger.App.Charts;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Infrastructure.Blobs;
|
||||
|
||||
namespace FrameLedger.App.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// beta.23 (<c>spike-notes</c> §21): what the charts derive from a whole session is worked out once, off the UI thread, and
|
||||
/// it is exactly what each chart computed for itself before — one sort where there were three.
|
||||
/// </summary>
|
||||
public sealed class SeriesDigestTests
|
||||
{
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
/// <summary>Frame times with what a real stream has: zeros after gaps, ties, a long tail, one negative a corrupt blob could hold.</summary>
|
||||
private static double[] Noisy(int count, int seed)
|
||||
{
|
||||
// A fixed scramble, the same on every run (a Random would be CA5394 here and adds nothing).
|
||||
uint state = (uint)seed | 1;
|
||||
var times = new double[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
state = (state * 1_664_525) + 1_013_904_223;
|
||||
double jitter = (state >> 8) / (double)(1 << 24);
|
||||
times[i] = i % 97 == 0 ? 0 : i % 211 == 0 ? 6.25 : 4 + (jitter * 3) + (i % 503 == 0 ? 40 : 0);
|
||||
}
|
||||
|
||||
times[count / 2] = -1;
|
||||
return times;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(2)]
|
||||
[InlineData(1_000)]
|
||||
[InlineData(25_000)]
|
||||
public void TheSortedFormsAreTheSameAsTheChartsOwn(int count)
|
||||
{
|
||||
double[] times = Noisy(count, count);
|
||||
double[] sorted = (double[])times.Clone();
|
||||
Array.Sort(sorted);
|
||||
|
||||
FpsHistogram own = FpsHistogram.Of(times, SeriesDigest.HistogramBins);
|
||||
FpsHistogram fromSorted = FpsHistogram.OfSorted(sorted, SeriesDigest.HistogramBins);
|
||||
fromSorted.Centers.Should().Equal(own.Centers);
|
||||
fromSorted.Counts.Should().Equal(own.Counts);
|
||||
fromSorted.BinWidth.Should().Be(own.BinWidth);
|
||||
fromSorted.Outside.Should().Be(own.Outside);
|
||||
|
||||
(double[] xs, double[] ys) = PercentileCurve.Of(times);
|
||||
(double[] sortedXs, double[] sortedYs) = PercentileCurve.OfSorted(sorted);
|
||||
sortedXs.Should().Equal(xs);
|
||||
sortedYs.Should().Equal(ys);
|
||||
PercentileCurve.LowsOfSorted(sorted).Should().Equal(PercentileCurve.Lows(times));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OneRateAndNoFramesStayWhatTheyWere()
|
||||
{
|
||||
double[] flat = [5, 5, 5, 5];
|
||||
FpsHistogram.OfSorted(flat).Should().BeEquivalentTo(FpsHistogram.Of(flat));
|
||||
FpsHistogram.OfSorted([0, 0]).Should().BeEquivalentTo(FpsHistogram.Of([0, 0]));
|
||||
FpsHistogram.OfSorted([]).Centers.Should().BeEmpty();
|
||||
PercentileCurve.OfSorted([7]).Xs.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDecodedSeriesCarriesItsDigest()
|
||||
{
|
||||
// 6 presents: the first and the fifth follow a gap, the third is generated.
|
||||
float[] frametimes = [0, 10, 10, 10, 0, 40];
|
||||
byte[] flags = [4, 0, 1, 0, 4, 0];
|
||||
var frames = new FrameBlobs
|
||||
{
|
||||
Codec = SeriesCodec.Tag,
|
||||
SampleCount = 6,
|
||||
FrameTimes = SeriesCodec.EncodeFloat32(frametimes),
|
||||
FrameFlags = SeriesCodec.EncodeBytes(flags),
|
||||
};
|
||||
|
||||
SessionSeries s = SessionSeriesLoader.Decode(frames, [], []);
|
||||
|
||||
SeriesDigest digest = s.Digest!;
|
||||
digest.SortedAppFrameTimesMs.Should().Equal(10, 20, 40);
|
||||
digest.GapsAfterFirst.Should().Be(1, "the first present's gap is every stream's start, not one the chart notes");
|
||||
digest.GeneratedCount.Should().Be(1);
|
||||
s.HasGenerated.Should().BeTrue();
|
||||
(double[] presentTimes, double[] presentIntervals) = digest.Presents!.Value;
|
||||
presentTimes.Should().Equal(0.01, 0.02, 0.03, 0.07);
|
||||
presentIntervals.Should().Equal(10, 10, 10, 40);
|
||||
FrametimeChart.NoteFor(s, displayed: false, sensors: false).Should().Be(FrametimeChart.NoteFor(s with { Digest = null }, displayed: false, sensors: false));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Microsoft.Data.Sqlite completes its "async" calls synchronously, so whatever ConfigureAwait said, the blob read and the
|
||||
/// decode ran on the caller's thread — the UI's (beta.23). They run on the thread pool now.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task TheBlobIsReadAndDecodedOffTheCallersThread()
|
||||
{
|
||||
await using ScratchLedger s = await ScratchLedger.OpenAsync();
|
||||
GameRow game = await s.GameAsync("Alpha");
|
||||
long id = await s.SessionWithFramesAsync(game.Id, DateTimeOffset.UtcNow.AddHours(-1), frames: 600, spikeEvery: 200);
|
||||
var reads = new ThreadRecordingSessions(s.Sessions);
|
||||
var loader = new SessionSeriesLoader(reads);
|
||||
|
||||
int caller = 0;
|
||||
Task<SessionSeries?>? loading = null;
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
caller = Environment.CurrentManagedThreadId;
|
||||
loading = loader.LoadAsync(id, Ct);
|
||||
});
|
||||
thread.Start();
|
||||
thread.Join();
|
||||
SessionSeries? series = await loading!;
|
||||
|
||||
series.Should().NotBeNull();
|
||||
reads.Threads.Should().NotBeEmpty().And.NotContain(caller, "the read and the decode happen on the thread pool, never on the thread that asked");
|
||||
}
|
||||
|
||||
/// <summary>The scratch ledger's repository, noting the thread each blob read runs on.</summary>
|
||||
private sealed class ThreadRecordingSessions(ISessionRepository inner) : ISessionRepository
|
||||
{
|
||||
public List<int> Threads { get; } = [];
|
||||
|
||||
public ValueTask<FrameBlobs?> FindFramesAsync(long sessionId, CancellationToken ct = default)
|
||||
{
|
||||
lock (Threads)
|
||||
{
|
||||
Threads.Add(Environment.CurrentManagedThreadId);
|
||||
}
|
||||
|
||||
return inner.FindFramesAsync(sessionId, ct);
|
||||
}
|
||||
|
||||
public ValueTask<IReadOnlyList<SegmentRow>> FindSegmentsAsync(long sessionId, CancellationToken ct = default) => inner.FindSegmentsAsync(sessionId, ct);
|
||||
|
||||
public ValueTask<IReadOnlyList<SensorBlob>> FindSensorsAsync(long sessionId, CancellationToken ct = default) => inner.FindSensorsAsync(sessionId, ct);
|
||||
|
||||
public ValueTask<long> InsertFinalizedAsync(FinalizedSession session, CancellationToken ct = default) => inner.InsertFinalizedAsync(session, ct);
|
||||
|
||||
public ValueTask<long?> ResolveOwnerAsync(long gameId, string? exePath, DateTimeOffset startedAt, CancellationToken ct = default) => inner.ResolveOwnerAsync(gameId, exePath, startedAt, ct);
|
||||
|
||||
public ValueTask<bool> ExistsAsync(Guid sessionGuid, CancellationToken ct = default) => inner.ExistsAsync(sessionGuid, ct);
|
||||
|
||||
public ValueTask<SessionRow?> FindAsync(Guid sessionGuid, CancellationToken ct = default) => inner.FindAsync(sessionGuid, ct);
|
||||
|
||||
public ValueTask<SessionRow?> FindByIdAsync(long sessionId, CancellationToken ct = default) => inner.FindByIdAsync(sessionId, ct);
|
||||
|
||||
public ValueTask<IReadOnlyList<SessionRow>> ListRecentAsync(int count, CancellationToken ct = default) => inner.ListRecentAsync(count, ct);
|
||||
|
||||
public ValueTask<IReadOnlyList<SessionRow>> ListByGameAsync(long gameId, int limit, CancellationToken ct = default) => inner.ListByGameAsync(gameId, limit, ct);
|
||||
|
||||
public ValueTask<IReadOnlyList<GameSessionSummary>> SummariseByGameAsync(CancellationToken ct = default) => inner.SummariseByGameAsync(ct);
|
||||
|
||||
public ValueTask<long> CountSinceAsync(DateTimeOffset since, CancellationToken ct = default) => inner.CountSinceAsync(since, ct);
|
||||
|
||||
public ValueTask<int> CountSuccessfulUnderGrantAsync(long gameId, string family, DateTimeOffset grantedAt, CancellationToken ct = default) => inner.CountSuccessfulUnderGrantAsync(gameId, family, grantedAt, ct);
|
||||
|
||||
public ValueTask<int> SweepRetentionAsync(long gameId, int keep, CancellationToken ct = default) => inner.SweepRetentionAsync(gameId, keep, ct);
|
||||
|
||||
public ValueTask<RetentionSweepResult> SweepRetentionAllAsync(int keep, CancellationToken ct = default) => inner.SweepRetentionAllAsync(keep, ct);
|
||||
|
||||
public ValueTask<RetentionSweepResult> DeleteSessionsAsync(long? gameId, CancellationToken ct = default) => inner.DeleteSessionsAsync(gameId, ct);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,11 @@ WPF UI 4.3.0 (pinned), CommunityToolkit.Mvvm, ScottPlot for charts and Markdig f
|
||||
## How it is put together
|
||||
|
||||
- A .NET Generic Host with dependency injection. Pages and their view models are transient — a page is made again on
|
||||
every navigation, so state lives in the view models' services and the database, never in a page.
|
||||
every navigation, so state lives in the view models' services and the database, never in a page. A view model that
|
||||
listens to a service attaches on its page's Loaded and detaches on Unloaded, and is never `IDisposable`: the container
|
||||
keeps every transient disposable it makes until the App exits.
|
||||
- The ledger's reads run on the thread that calls them (Microsoft.Data.Sqlite completes its asynchronous calls
|
||||
synchronously): anything heavy after one — decoding a session, sorting its frames — is put on the thread pool.
|
||||
- Navigation goes only through WPF UI's `INavigationService`; a page implements `INavigableView<TViewModel>`.
|
||||
- The App opens `ledger.db` itself to read; anything that acts on the PC — hooking, deleting sessions, pausing — is a
|
||||
request to the agent over the pipe.
|
||||
|
||||
Reference in new issue
Block a user