Files
frameledger/tests/FrameLedger.App.Tests/LogsViewModelTests.cs
poli0981andClaude Opus 5.5 fb313ebca6 perf(app): a game's page opens and changes session without freezing the window; a Dashboard or Logs visit no longer stays in memory (beta.23 PR-2) (#309)
The owner asked whether switching pages and tabs is slow (2026-10-14). Measured before
changing anything, with a pre-committed bar - fix what keeps the UI thread busy 50 ms or
more, can block on I/O, or grows with each visit - over the App's own pages in a real
window, Release, a ledger shaped like the owner's (docs/spike-notes.md section 21):

- Open a game with 100 sessions: 1,175-1,507 ms -> 369 ms. The Sessions grid sat in the
  page's own scroller with no height limit and built every row (17 columns each); it is
  bounded now (MaxHeight 520, as Compare's list is), builds the rows on screen, scrolls
  itself and hands the wheel to the page at its ends.
- Choose a 2,000,000-frame session: 843-1,016 ms freeze -> 17 ms. Microsoft.Data.Sqlite
  completes its async calls synchronously, so the blob read, the decode and the stutter
  detection ran on the UI thread whatever ConfigureAwait said; then the Distribution tab
  sorted every frame three times. SessionSeriesLoader reads and decodes on the thread
  pool, and Charts.SeriesDigest works out once, there, what the charts need from the
  whole session (one sort shared by the histogram, the percentile curve and its lows;
  the gap count; the presents line). The charts' public entry points are unchanged and
  compute for themselves on a series without a digest.
- A session ends after 20 Dashboard visits: 20 notices and 20 reloads -> one of each.
  DashboardViewModel and LogsViewModel were IDisposable transients the root container
  kept until exit; every Dashboard stayed subscribed. The Dashboard attaches on Loaded
  and detaches on Unloaded; neither is IDisposable; FR-3.8's in-App notice moves to
  Services.SessionNotices, one subscription for the App's life (it reached other pages
  only through the leak), kept by AgentConnectionHostedService like LiveSessions.

Also: the game page asks whether the .exe is on disk off the UI thread and no longer
reads a drive from a property getter; GameLibrary.LoadAsync stops summarising every
game's sessions for a field nothing read (GameDetail.Summary removed); the Logs tick
reads nothing when the newest file is unchanged and filters off the UI thread; Play
reads the stores' records on the thread pool (Services.StoreRecordsReader, which PR-3's
artwork reuses); at Debug the App logs how long each page took to appear.

Recorded, not fixed (spike-notes section 21): page builds of 600-2,500 visuals still cost
85-370 ms, and the library grid (275 ms at 48 games) is non-virtualizing by the beta.11
decision - a virtualizing one changes the page's look, the owner's call.

Docs: 08_UI (the game page's costs; FR-3.8's snackbar corrected in place), 16_WPFUI_SYNTAX
Gotchas (synchronous SQLite; no IDisposable transient view models), wiki
App-UI-development, spike-notes section 21, CHANGELOG.

Tests: SeriesDigestTests (sorted forms equal the charts' own; the digest of a decoded
series; the read happens off the caller's thread), DashboardViewModelTests (an
off-screen Dashboard hears nothing, one notice per session, a hidden window leaves the
notice to the tray), GameDetailViewModelTests (the executable is looked for off the
opener's thread), LogsViewModelTests (a tick re-reads only a changed file),
PagesLoadTests (the Sessions grid builds the rows on screen and hands the wheel on).
Local gate: ALL GATES PASSED in 355 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 23:24:36 +07:00

145 lines
6.3 KiB
C#

// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.IO;
using System.IO.Compression;
using FluentAssertions;
using FrameLedger.App.Services;
using FrameLedger.App.ViewModels;
using FrameLedger.Application.Settings;
using FrameLedger.Infrastructure.Persistence;
namespace FrameLedger.App.Tests;
/// <summary>08_UI §Logs: the tail of the chosen source through the filters, the status line, and the bug bundle where the user says.</summary>
public sealed class LogsViewModelTests : IDisposable
{
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-logsvm-" + Guid.NewGuid().ToString("N"));
public LogsViewModelTests() => Directory.CreateDirectory(_dir);
public void Dispose() => Directory.Delete(_dir, recursive: true);
private sealed class PathSaver(string? path) : IFileSaver
{
public string? Suggested { get; private set; }
public string? PickSavePath(string filter, string suggestedName)
{
Suggested = suggestedName;
return path;
}
}
private void Write(string name, string text) => File.WriteAllText(Path.Combine(_dir, name), text);
private static string[] Entries(string zip)
{
using ZipArchive archive = ZipFile.OpenRead(zip);
return [.. archive.Entries.Select(static e => e.FullName)];
}
[Fact]
public async Task TailsTheNewestFileOfTheSourceAndFilters()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
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();
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;
vm.TotalCount.Should().Be(2);
vm.Text.Should().Contain("hello").And.Contain("careful");
vm.Status.Should().Contain("ui-20260914.log");
vm.Level = LogLevelFilter.WarningAndAbove;
vm.ShownCount.Should().Be(1);
vm.Text.Should().Be("[12:00:00.001 WRN] careful");
vm.Level = LogLevelFilter.All;
vm.Search = "AGENT";
vm.ShownCount.Should().Be(0);
vm.Source = LogSource.Agent;
Task pending2 = vm.Pending;
await pending2;
vm.ShownCount.Should().Be(1);
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();
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;
vm.CurrentFile.Should().BeNull();
vm.Status.Should().Be(Strings.Logs_Empty);
vm.Text.Should().BeEmpty();
}
[Fact]
public async Task TheBugBundleGoesWhereTheUserSaysAndNowhereElse()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
Write("ui-20260914.log", "[12:00:00.000 INF] hello\n");
string zip = Path.Combine(_dir, "out", "bundle.zip");
Directory.CreateDirectory(Path.GetDirectoryName(zip)!);
var saver = new PathSaver(zip);
var strip = new RecordingStrip();
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;
await vm.ExportBundleCommand.ExecuteAsync(null);
saver.Suggested.Should().StartWith("FrameLedger-bugreport-").And.EndWith(".zip");
File.Exists(zip).Should().BeTrue();
Entries(zip).Should().Contain(["logs/ui-20260914.log", "sysinfo.json", "settings.json"]);
strip.Shown.Should().ContainSingle().Which.Kind.Should().Be("success");
}
[Fact]
public async Task ACancelledSaveWritesNothing()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
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);
await vm.ExportBundleCommand.ExecuteAsync(null);
Directory.EnumerateFiles(_dir, "*.zip").Should().BeEmpty();
strip.Shown.Should().BeEmpty();
}
}