Compare commits

...
Author SHA1 Message Date
poli0981andClaude Fable 5.1 830eec4127 feat(app): the bug report's steps 3-4, Help > Documentation, and File > Export as the submenu it was specified as (P4 PR-3)
BugReportFlow is the one flow behind Help > Report a bug... and the
Logs page's button: the zip where the user says, the preview dialog
listing every entry the builder wrote, then "Open GitHub issue" (the
form's real hyphenated field ids prefilled, the OS in the form's own
spelling) or "Copy summary as Markdown". Nothing is ever sent by itself.
Three ports keep it testable without a desktop: IBugReportPreview,
IUrlOpener, IClipboard.

Help > Documentation opens the README. File > Export is the three-leaf
submenu 08_UI specifies: Session CSV / Session JSON for the session last
selected on a Sessions tab or opened in a summary window
(SessionSelection, SessionExportService over the summary window's own
writers), Chart PNG opening that session's summary window.

Tests: BugReportFlowTests, SessionExportServiceTests, LogsViewModelTests
over the flow. 14 App strings en/vi/ja. Docs: 10_LOGGING, 08_UI,
HANDOFF, CHANGELOG.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 20:03:29 +07:00
39 changed files with 1090 additions and 52 deletions

No files matched your search

+18
View File
@@ -19,6 +19,24 @@ GitHub release body, so a missing section will mean an empty release note.
### Added
- **P4 PR-3 — the bug report's steps 3–4, Help ▸ Documentation, and File ▸ Export as the submenu it was specified
as (2026-09-14).** `App/Services/BugReportFlow` is the one flow behind Help ▸ Report a bug… and the Logs page's
button: step 2's zip where the user says, then step 3's `ContentDialog` (`BugReportPreviewPrompt` /
`Dialogs/BugReportPreviewContent`) listing every entry the builder wrote, with "Show the zip in Explorer" and the
drag instruction, then step 4 as its two buttons — **Open GitHub issue** (`IssueLink.NewIssue`:
`issues/new?template=bug_report.yml&title=[Bug]%20&labels=bug&app-version=…&os=…`, the form's real hyphenated
field ids, the OS in the form's own spelling `Windows 11 26100.2314`) and **Copy summary as Markdown**
(`sysinfo.json`'s twelve keys as a table). Nothing is ever sent by itself. Three ports keep it testable without a
desktop: `IBugReportPreview`, `IUrlOpener` (`ShellUrlOpener`), `IClipboard` (`WpfClipboard`). Help ▸
Documentation opens the README (`docs/` is developer-facing). File ▸ Export is now the submenu `08_UI` §Menu bar
specifies: Session CSV / Session JSON for the session last selected on a Sessions tab or opened in a summary
window (`SessionSelection`, written by the game page and the summary opener; `SessionExportService` over the
summary window's own `SessionExporter` writers), Chart PNG opening that session's summary window where the
plot lives; no selection says so in the strip. `BugBundleBuilder.SysInfoOf` is public for the link and the
Markdown. Tests: `BugReportFlowTests` (the zip, the preview's entries against the archive, the exact URL, the
Markdown, close, cancel), `SessionExportServiceTests` (CSV and JSON where the user says, unknown session,
cancelled save, the selection), `LogsViewModelTests` over the flow. 14 App strings en/vi/ja. Docs: `10_LOGGING`
§Bug report flow built note (the crash dialog and minidump stay open), `08_UI` §Shell menu note, HANDOFF §P4.
- **P4 PR-2 — the "is Vulkan" fact, and the layer's registration following the ledger (2026-09-14).** The rule
`12_BUILD` §The Vulkan layer is not registered at install time states — registered only while at least one
Vulkan game has hooking enabled, unregistered when the last is disabled — had no way to know which game was
+8
View File
@@ -28,6 +28,14 @@ WPF + **WPF UI (Wpf.Ui, Fluent)**. Shell = `ui:FluentWindow` with custom `ui:Tit
The Menu sits in its own row **below** the TitleBar (never inside the drag region — 16 §Gotchas).
> **Menu bar as of 2026-09-14 (P4 PR-3).** File ▸ Export is the submenu this section specifies — Session CSV /
> Session JSON write the session last selected on a Sessions tab or opened in a summary window
> (`Services/SessionSelection`, `SessionExportService` over the summary window's own writers; no selection says
> so in the strip), Chart PNG opens that session's summary window, where the plot is. Help ▸ Documentation opens
> the README (`IssueLink.Documentation`; `docs/` is developer-facing). Help ▸ Report a bug… runs
> `BugReportFlow` (`10_LOGGING` §Bug report flow steps 2–4). Tools ▸ Update detection rules is PR-1's. Still
> "later build": File ▸ Import library, Tools ▸ Database maintenance, Help ▸ Check for updates.
>
> **Built 2026-09-13 (P3 PR-2): the shell, and only the shell.** `FluentWindow`, the TitleBar with the
> Agent pill as trailing content, the Menu row (every item that a later slice builds says so in a 4 s
> snackbar rather than doing nothing), the NavigationView with the four items and Settings in the footer,
+14 -2
View File
@@ -45,10 +45,22 @@ Tails the active files (shared read), level filter, text search, pause autoscrol
> PawnIO question) and the disclosure version, plus OS version, bitness, locale and the write time — **no
> CPU/GPU name or driver version**, which live in the ledger's hardware snapshots and are the session
> metadata option this list already has; `settings.json` = every registry key's effective value (there is no
> path-valued key). No session JSON and no dumps. The bundle is written and nothing else happens: no preview
> dialog yet, no browser, no clipboard. Tests: `BugBundleBuilderTests` (the seven-day cut, the overlay cap, a
> path-valued key). No session JSON and no dumps. ~~The bundle is written and nothing else happens: no preview
> dialog yet, no browser, no clipboard.~~ Tests: `BugBundleBuilderTests` (the seven-day cut, the overlay cap, a
> `game-crash.log` beside ours is not shipped, both JSON files), `LogsViewModelTests` (the cancelled save writes
> nothing).
>
> **Steps 1 (the Help menu), 3 and 4 built 2026-09-14 (P4 PR-3)** as `App/Services/BugReportFlow`, the one flow
> behind Help ▸ Report a bug… and the Logs page's button: step 2's zip → step 3's `ContentDialog`
> (`BugReportPreviewPrompt` / `Dialogs/BugReportPreviewContent`) listing every entry `WriteAsync` returned, with
> "Show the zip in Explorer" and the drag instruction → step 4 as the dialog's two buttons: **Open GitHub issue**
> opens `issues/new?template=bug_report.yml&title=[Bug]%20&labels=bug&app-version=…&os=…` — the form's field
> ids are **hyphenated** (`app-version`, `os`), which is what GitHub prefills by, not the underscores step 4
> above spelled; the OS is the form's own spelling (`Windows 11 26100.2314`, `IssueLink.OsText`) — and **Copy
> summary as Markdown** puts `sysinfo.json`'s twelve keys on the clipboard as a table. Both behind ports
> (`IBugReportPreview`, `IUrlOpener`, `IClipboard`) so `BugReportFlowTests` pins the exact URL without a browser.
> Still open from this list: the **crash dialog and the minidump** (§Crash handling, step 1's third entry point)
> and the optional session-metadata / dump checkboxes of step 2.
3. **Preview step:** the dialog lists every file included and lets the user open the zip before continuing. Nothing is ever sent automatically.
4. "Open GitHub issue" → launches browser to
`https://github.com/poli0981/frameledger/issues/new?template=bug_report.yml&title=[Bug]%20&labels=bug&app_version=…&os=…`
+7 -3
View File
@@ -1228,13 +1228,17 @@ schema 0004 for the key's exe half (NOT the consent fingerprint), Tools ▸ Upda
filled — status in `CHANGELOG.md`, the decisions in `05_DETECTION` §Caching's built note; store auto-import (Steam / GOG / Epic /
itch.io — the first-run flow's step 4 and File ▸ Import library both say "later build"), ~~the
capability-vs-measured separation in the UI (the game page's Supports row is empty until this)~~ **(PR-1)**, Velopack +
the updater (`11_UPDATER`; the Settings channel row is stored and unused), the bug-report flow's steps 3–5
(`10_LOGGING`: the preview dialog, the GitHub issue link — step 2's bundle exists), ~~the "is Vulkan" fact the
the updater (`11_UPDATER`; the Settings channel row is stored and unused), ~~the bug-report flow's steps 3–5
(`10_LOGGING`: the preview dialog, the GitHub issue link — step 2's bundle exists)~~ **LANDED 2026-09-14 (P4 PR-3:
`BugReportFlow`, the preview dialog, the issue link with the form's real field ids, the Markdown clipboard fallback;
the crash dialog + minidump stay open — `10_LOGGING` built note)**, ~~the "is Vulkan" fact the
layer's register/unregister-on-consent automation needs (`17_HOOK_ENGINE` §Vulkan built note)~~ **LANDED
2026-09-14 (P4 PR-2): a static PE fact (`PeImports` + the bounded scan) stored as `vulkan` in `capability_flags`,
and `VkLayerReconciler` moving the HKCU registration after every consent change and sweep — the built note
carries it**, the Help menu's
Documentation / Check for updates / Report a bug items, and `legal/licenses/` populated by the license-gathering
~~Documentation~~ / Check for updates / ~~Report a bug~~ items **(Documentation and Report a bug landed with PR-3;
Check for updates waits for the updater; File ▸ Export became the three-leaf submenu `08_UI` specifies)**, and
`legal/licenses/` populated by the license-gathering
script. Decisions that live only here: D11–D17 below still hold; nothing in P4 may add a third writer to
`ledger.db` or a message that carries a safety fact over the pipe.
+9
View File
@@ -262,6 +262,15 @@ public partial class App : System.Windows.Application
services.AddSingleton(static _ => new LogTail(UiPaths.Logs));
services.AddSingleton(static sp => new BugBundleBuilder(UiPaths.Logs, sp.GetRequiredService<RegisteredSettings>()));
// The bug report's steps 3-4 and the shell's Export (P4 PR-3): the preview dialog, the browser, the clipboard,
// the flow over them, the session the shell exports, and the CSV/JSON service the summary window's writers serve.
services.AddSingleton<IUrlOpener, ShellUrlOpener>();
services.AddSingleton<IClipboard, WpfClipboard>();
services.AddSingleton<IBugReportPreview, BugReportPreviewPrompt>();
services.AddSingleton<BugReportFlow>();
services.AddSingleton<SessionSelection>();
services.AddSingleton<SessionExportService>();
// The layer registration and the logon task (P3 PR-8b): read from the machine, written by the Agent's flags.
services.AddSingleton<IMaintenanceState, MaintenanceState>();
services.AddSingleton<IAgentTool, AgentTool>();
@@ -0,0 +1,32 @@
<UserControl x:Class="FrameLedger.App.Dialogs.BugReportPreviewContent"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:vm="clr-namespace:FrameLedger.App.ViewModels"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DataContext="{d:DesignInstance Type=vm:BugReportPreviewViewModel}"
mc:Ignorable="d"
MinWidth="480">
<!--
10_LOGGING §Bug report flow step 3: every file in the zip, listed, before anything else happens. Nothing is
ever sent automatically; the primary button opens the issue form and the zip is dragged in by hand.
-->
<StackPanel>
<ui:TextBlock TextWrapping="Wrap" Text="{Binding Intro}" />
<Border Margin="0,10,0,10" Padding="10,6" CornerRadius="6"
Background="{DynamicResource ControlFillColorDefaultBrush}" BorderBrush="{DynamicResource ControlStrokeColorDefaultBrush}" BorderThickness="1">
<ScrollViewer MaxHeight="220" VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding Entries}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock FontFamily="Consolas" Text="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Border>
<ui:HyperlinkButton Padding="0" Content="{x:Static vm:BugReportPreviewViewModel.ShowZipText}" Command="{Binding ShowZipCommand}" />
<ui:TextBlock Margin="0,10,0,0" Appearance="Secondary" TextWrapping="Wrap" Text="{x:Static vm:BugReportPreviewViewModel.DragInstruction}" />
</StackPanel>
</UserControl>
@@ -0,0 +1,17 @@
using System.Windows.Controls;
using FrameLedger.App.ViewModels;
namespace FrameLedger.App.Dialogs;
/// <summary>The body of the bug report's preview <c>ContentDialog</c> (P4 PR-3).</summary>
public partial class BugReportPreviewContent : UserControl
{
public BugReportPreviewContent(BugReportPreviewViewModel viewModel)
{
ViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel));
DataContext = viewModel;
InitializeComponent();
}
public BugReportPreviewViewModel ViewModel { get; }
}
+7 -3
View File
@@ -38,7 +38,11 @@
<MenuItem Header="{x:Static res:Strings.Menu_File}">
<MenuItem Header="{x:Static res:Strings.Menu_File_AddGame}" Command="{Binding ViewModel.AddGameCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_File_ImportLibrary}" Command="{Binding ViewModel.NotYetCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_File_Export}" Command="{Binding ViewModel.NotYetCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_File_Export}">
<MenuItem Header="{x:Static res:Strings.Menu_File_Export_Csv}" Command="{Binding ViewModel.ExportCsvCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_File_Export_Json}" Command="{Binding ViewModel.ExportJsonCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_File_Export_Png}" Command="{Binding ViewModel.ExportPngCommand}" />
</MenuItem>
<Separator />
<MenuItem Header="{x:Static res:Strings.Menu_File_Exit}" Command="{Binding ViewModel.ExitCommand}" />
</MenuItem>
@@ -51,8 +55,8 @@
</MenuItem>
<MenuItem Header="{x:Static res:Strings.Menu_Help}">
<MenuItem Header="{x:Static res:Strings.Menu_Help_CheckUpdates}" Command="{Binding ViewModel.NotYetCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_Help_ReportBug}" Command="{Binding ViewModel.NotYetCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_Help_Documentation}" Command="{Binding ViewModel.NotYetCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_Help_ReportBug}" Command="{Binding ViewModel.ReportBugCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_Help_Documentation}" Command="{Binding ViewModel.DocumentationCommand}" />
<Separator />
<MenuItem Header="{x:Static res:Strings.Menu_Help_About}" Command="{Binding ViewModel.AboutCommand}" />
</MenuItem>
@@ -83,9 +83,12 @@ public sealed class BugBundleBuilder
written.Add(entryName);
}
private string SysInfo(HelloAck? agent)
private string SysInfo(HelloAck? agent) => JsonSerializer.Serialize(new Dictionary<string, string>(SysInfoOf(agent, _clock.GetUtcNow()), StringComparer.Ordinal), AppJsonContext.Default.DictionaryStringString);
/// <summary>The twelve keys of <c>sysinfo.json</c>, also the issue link's prefill and the clipboard Markdown (P4 PR-3).</summary>
public static IReadOnlyDictionary<string, string> SysInfoOf(HelloAck? agent, DateTimeOffset now)
{
var info = new Dictionary<string, string>(StringComparer.Ordinal)
return new Dictionary<string, string>(StringComparer.Ordinal)
{
["app_version"] = UiIdentity.Version,
["agent_version"] = agent?.AgentVersion ?? "not connected",
@@ -98,9 +101,8 @@ public sealed class BugBundleBuilder
["os"] = Environment.OSVersion.VersionString,
["os_64bit"] = Environment.Is64BitOperatingSystem.ToString(),
["locale"] = CultureInfo.CurrentUICulture.Name,
["written_at"] = _clock.GetUtcNow().ToString("O", CultureInfo.InvariantCulture),
["written_at"] = now.ToString("O", CultureInfo.InvariantCulture),
};
return JsonSerializer.Serialize(info, AppJsonContext.Default.DictionaryStringString);
}
private async Task<string> SettingsJsonAsync(CancellationToken ct)
@@ -0,0 +1,14 @@
namespace FrameLedger.App.Services;
/// <summary>The user's choice on the bug report's preview.</summary>
public enum BugReportChoice
{
/// <summary>Closed: the zip stays where it was written, nothing else happens.</summary>
Close,
/// <summary>Step 4: open the GitHub issue form (the zip is dragged in by hand).</summary>
OpenIssue,
/// <summary>Step 4's fallback: the environment summary as Markdown on the clipboard.</summary>
CopyMarkdown,
}
@@ -0,0 +1,85 @@
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using FrameLedger.Shared.Ipc;
namespace FrameLedger.App.Services;
/// <summary>
/// <c>10_LOGGING</c> §Bug report flow, steps 2–4 in one place (P4 PR-3), reached from Help ▸ Report a bug and the
/// Logs page's button: the zip where the user says (step 2, <see cref="BugBundleBuilder"/>), the preview listing
/// every entry (step 3), then either the GitHub issue form with the two short fields prefilled or the environment
/// summary on the clipboard as Markdown (step 4). Nothing is ever sent automatically; the zip is dragged in by hand.
/// </summary>
[SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format strings are resources that follow the UI culture, which changes at runtime; a cached CompositeFormat would pin the first culture")]
public sealed class BugReportFlow
{
private readonly BugBundleBuilder _bundles;
private readonly IFileSaver _saver;
private readonly IAgentRequests _agent;
private readonly IBugReportPreview _preview;
private readonly IUrlOpener _urls;
private readonly IClipboard _clipboard;
private readonly IMessageStrip _strip;
private readonly TimeProvider _clock;
public BugReportFlow(BugBundleBuilder bundles, IFileSaver saver, IAgentRequests agent, IBugReportPreview preview, IUrlOpener urls, IClipboard clipboard, IMessageStrip strip, TimeProvider? clock = null)
{
_bundles = bundles ?? throw new ArgumentNullException(nameof(bundles));
_saver = saver ?? throw new ArgumentNullException(nameof(saver));
_agent = agent ?? throw new ArgumentNullException(nameof(agent));
_preview = preview ?? throw new ArgumentNullException(nameof(preview));
_urls = urls ?? throw new ArgumentNullException(nameof(urls));
_clipboard = clipboard ?? throw new ArgumentNullException(nameof(clipboard));
_strip = strip ?? throw new ArgumentNullException(nameof(strip));
_clock = clock ?? TimeProvider.System;
}
/// <summary>The whole flow; the outcome says how far it went, for the tests and the caller's log.</summary>
public async Task<BugReportOutcome> RunAsync(CancellationToken ct = default)
{
DateTimeOffset now = _clock.GetUtcNow();
string? path = _saver.PickSavePath("Zip archive (*.zip)|*.zip", BugBundleBuilder.SuggestedName(now));
if (path is null)
{
return new BugReportOutcome(null, BugReportChoice.Close, Written: false);
}
HelloAck? hello = _agent.Hello;
IReadOnlyList<string> entries;
try
{
entries = await _bundles.WriteAsync(path, hello, ct).ConfigureAwait(true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Serilog.Log.Warning(ex, "ui: the bug bundle could not be written");
_strip.Warn(Strings.BugReport_Title, string.Format(CultureInfo.CurrentCulture, Strings.Logs_Bundle_Failed_Format, ex.Message));
return new BugReportOutcome(path, BugReportChoice.Close, Written: false);
}
IReadOnlyDictionary<string, string> sysinfo = BugBundleBuilder.SysInfoOf(hello, now);
Uri issueUrl = IssueLink.NewIssue(sysinfo["app_version"], IssueLink.OsText(Environment.OSVersion.Version));
var model = new BugReportPreviewModel(path, entries, issueUrl, IssueLink.Markdown(sysinfo));
BugReportChoice choice = await _preview.ShowAsync(model, ct).ConfigureAwait(true);
switch (choice)
{
case BugReportChoice.OpenIssue:
if (!_urls.Open(issueUrl))
{
_strip.Warn(Strings.BugReport_Title, Strings.BugReport_BrowserRefused);
}
break;
case BugReportChoice.CopyMarkdown:
_strip.Info(Strings.BugReport_Title, _clipboard.SetText(model.Markdown) ? Strings.BugReport_Copied : Strings.BugReport_ClipboardRefused);
break;
default:
_strip.Success(Strings.BugReport_Title, string.Format(CultureInfo.CurrentCulture, Strings.Logs_Bundle_Exported_Format, path, entries.Count));
break;
}
return new BugReportOutcome(path, choice, Written: true);
}
}
@@ -0,0 +1,4 @@
namespace FrameLedger.App.Services;
/// <summary>Where one run of the flow ended.</summary>
public sealed record BugReportOutcome(string? ZipPath, BugReportChoice Choice, bool Written);
@@ -0,0 +1,4 @@
namespace FrameLedger.App.Services;
/// <summary>What step 3's preview shows (<c>10_LOGGING</c> §Bug report flow): the zip, every entry it holds, and the two ways forward.</summary>
public sealed record BugReportPreviewModel(string ZipPath, IReadOnlyList<string> Entries, Uri IssueUrl, string Markdown);
@@ -0,0 +1,37 @@
using FrameLedger.App.Dialogs;
using FrameLedger.App.ViewModels;
using Wpf.Ui;
using Wpf.Ui.Controls;
namespace FrameLedger.App.Services;
/// <summary>Step 3's preview in WPF UI: a <c>ContentDialog</c> listing the zip's entries, whose primary button is step 4 and whose secondary is the clipboard fallback.</summary>
public sealed class BugReportPreviewPrompt : IBugReportPreview
{
private readonly IContentDialogService _dialogs;
public BugReportPreviewPrompt(IContentDialogService dialogs) => _dialogs = dialogs ?? throw new ArgumentNullException(nameof(dialogs));
public async Task<BugReportChoice> ShowAsync(BugReportPreviewModel model, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(model);
var dialog = new ContentDialog
{
Title = Strings.BugReport_Title,
Content = new BugReportPreviewContent(new BugReportPreviewViewModel(model)),
PrimaryButtonText = Strings.BugReport_OpenIssue,
SecondaryButtonText = Strings.BugReport_CopyMarkdown,
CloseButtonText = Strings.Common_Close,
DefaultButton = ContentDialogButton.Primary,
DialogMaxWidth = 720,
};
ContentDialogResult result = await _dialogs.ShowAsync(dialog, ct).ConfigureAwait(true);
return result switch
{
ContentDialogResult.Primary => BugReportChoice.OpenIssue,
ContentDialogResult.Secondary => BugReportChoice.CopyMarkdown,
_ => BugReportChoice.Close,
};
}
}
@@ -0,0 +1,7 @@
namespace FrameLedger.App.Services;
/// <summary>Step 3's preview dialog as a port, so <see cref="BugReportFlow"/> is testable without a window.</summary>
public interface IBugReportPreview
{
Task<BugReportChoice> ShowAsync(BugReportPreviewModel model, CancellationToken ct = default);
}
@@ -0,0 +1,8 @@
namespace FrameLedger.App.Services;
/// <summary>The clipboard (P4 PR-3, the bug report's Markdown fallback) — a port so the flow is testable without a desktop.</summary>
public interface IClipboard
{
/// <summary>True when the text was placed; false when the clipboard refused (another process holding it), logged by the adapter.</summary>
bool SetText(string text);
}
@@ -0,0 +1,8 @@
namespace FrameLedger.App.Services;
/// <summary>Opens a URL in the user's browser (P4 PR-3) — a port so the shell's Help commands are testable without launching anything.</summary>
public interface IUrlOpener
{
/// <summary>True when the shell accepted the launch; false when it refused (logged by the adapter).</summary>
bool Open(Uri url);
}
+53
View File
@@ -0,0 +1,53 @@
using System.Globalization;
using System.Text;
namespace FrameLedger.App.Services;
/// <summary>
/// The GitHub side of the bug report (<c>10_LOGGING</c> §Bug report flow steps 4–5, P4 PR-3): the issue form's URL
/// with the two short fields it can carry prefilled, the OS line in the form's own spelling, and the environment
/// summary as Markdown for the clipboard fallback. Pure functions, so the flow's tests can pin the exact URL.
/// </summary>
public static class IssueLink
{
public const string Repository = "https://github.com/poli0981/frameledger";
/// <summary>Help ▸ Documentation: the README is the user-facing entry point (`docs/` is developer-facing, README line 126).</summary>
public static readonly Uri Documentation = new(Repository + "#readme");
/// <summary>
/// <c>issues/new</c> with the form's field ids (<c>.github/ISSUE_TEMPLATE/bug_report.yml</c>: <c>app-version</c>,
/// <c>os</c> — hyphenated ids, not the underscores <c>10_LOGGING</c> line 54 spelled) prefilled. GitHub URLs cannot
/// carry logs; the zip is dragged in by hand.
/// </summary>
public static Uri NewIssue(string appVersion, string os)
{
ArgumentNullException.ThrowIfNull(appVersion);
ArgumentNullException.ThrowIfNull(os);
return new Uri(Repository + "/issues/new?template=bug_report.yml&title=" + Uri.EscapeDataString("[Bug] ")
+ "&labels=bug&app-version=" + Uri.EscapeDataString(appVersion) + "&os=" + Uri.EscapeDataString(os));
}
/// <summary>The form's spelling (<c>Windows 11 26100.2314</c>): the product name from the build number, then build and revision.</summary>
public static string OsText(Version version)
{
ArgumentNullException.ThrowIfNull(version);
string product = version.Major >= 10 && version.Build >= 22000 ? "Windows 11" : version.Major >= 10 ? "Windows 10" : "Windows " + version.Major.ToString(CultureInfo.InvariantCulture);
string build = version.Build.ToString(CultureInfo.InvariantCulture);
return version.Revision > 0 ? $"{product} {build}.{version.Revision.ToString(CultureInfo.InvariantCulture)}" : $"{product} {build}";
}
/// <summary>The environment summary as a Markdown table — the same keys <c>sysinfo.json</c> carries, for a paste into the issue.</summary>
public static string Markdown(IReadOnlyDictionary<string, string> sysinfo)
{
ArgumentNullException.ThrowIfNull(sysinfo);
var sb = new StringBuilder();
sb.Append("| Key | Value |\n|---|---|\n");
foreach ((string key, string value) in sysinfo)
{
sb.Append("| `").Append(key).Append("` | ").Append(value.Replace("|", "\\|", StringComparison.Ordinal)).Append(" |\n");
}
return sb.ToString();
}
}
@@ -0,0 +1,100 @@
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Text;
using FrameLedger.App.Charts;
using FrameLedger.Application.Persistence;
using FrameLedger.Domain.Sessions;
namespace FrameLedger.App.Services;
/// <summary>
/// File ▸ Export ▸ Session CSV / Session JSON for a session id (P4 PR-3): the same five loads and the same two
/// <see cref="SessionExporter"/> writers the summary window uses, reachable from the shell for the session the user
/// last selected. The chart PNG is not here — it needs the summary window's live plot, so the shell opens that.
/// </summary>
[SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format strings are resources that follow the UI culture, which changes at runtime; a cached CompositeFormat would pin the first culture")]
public sealed class SessionExportService
{
private readonly ISessionRepository _sessions;
private readonly IGameRepository _games;
private readonly ISessionAnnotationRepository _annotations;
private readonly IHardwareSnapshotRepository _hardware;
private readonly SessionSeriesLoader _loader;
private readonly IFileSaver _saver;
private readonly IMessageStrip _strip;
public SessionExportService(ISessionRepository sessions, IGameRepository games, ISessionAnnotationRepository annotations,
IHardwareSnapshotRepository hardware, SessionSeriesLoader loader, IFileSaver saver, IMessageStrip strip)
{
_sessions = sessions ?? throw new ArgumentNullException(nameof(sessions));
_games = games ?? throw new ArgumentNullException(nameof(games));
_annotations = annotations ?? throw new ArgumentNullException(nameof(annotations));
_hardware = hardware ?? throw new ArgumentNullException(nameof(hardware));
_loader = loader ?? throw new ArgumentNullException(nameof(loader));
_saver = saver ?? throw new ArgumentNullException(nameof(saver));
_strip = strip ?? throw new ArgumentNullException(nameof(strip));
}
public Task<string?> ExportCsvAsync(long sessionId, CancellationToken ct = default) => ExportAsync(sessionId, "csv", "CSV|*.csv", ct);
public Task<string?> ExportJsonAsync(long sessionId, CancellationToken ct = default) => ExportAsync(sessionId, "json", "JSON|*.json", ct);
/// <summary>The suggested file name the summary window uses too: the game, the local start time, the extension.</summary>
public static string SuggestedName(GameRow game, SessionRow row, string extension)
{
ArgumentNullException.ThrowIfNull(game);
ArgumentNullException.ThrowIfNull(row);
string name = string.Concat(game.Name.Select(static c => Path.GetInvalidFileNameChars().Contains(c) ? '_' : c)).Trim();
return (name.Length == 0 ? "session" : name) + "-" + row.StartedAt.ToLocalTime().ToString("yyyyMMdd-HHmm", CultureInfo.InvariantCulture) + "." + extension;
}
/// <summary>The path written, or null when the session was not found or the user cancelled.</summary>
private async Task<string?> ExportAsync(long sessionId, string extension, string filter, CancellationToken ct)
{
SessionRow? row = await _sessions.FindByIdAsync(sessionId, ct).ConfigureAwait(true);
GameRow? game = row is null ? null : await _games.FindByIdAsync(row.GameId, ct).ConfigureAwait(true);
if (row is null || game is null)
{
_strip.Warn(Strings.Menu_File_Export, Strings.Export_NoSelection_Body);
return null;
}
string? path = _saver.PickSavePath(filter, SuggestedName(game, row, extension));
if (path is null)
{
return null;
}
SessionAnnotation? annotation = await _annotations.FindAsync(sessionId, ct).ConfigureAwait(true);
IReadOnlyList<SegmentRow> segments = await _sessions.FindSegmentsAsync(sessionId, ct).ConfigureAwait(true);
HardwareSnapshot? snapshot = await _hardware.FindAsync(row.SnapshotId, ct).ConfigureAwait(true);
SessionSeries? series = string.Equals(extension, "csv", StringComparison.Ordinal) && row.Tier == CaptureTier.Hooked
? await _loader.LoadAsync(sessionId, ct).ConfigureAwait(true)
: null;
try
{
await Task.Run(() =>
{
if (string.Equals(extension, "csv", StringComparison.Ordinal))
{
using var writer = new StreamWriter(path, false, new UTF8Encoding(false));
SessionExporter.WriteCsv(writer, row, game, snapshot, segments, series);
}
else
{
using FileStream stream = File.Create(path);
SessionExporter.WriteJson(stream, SessionExporter.Document(row, game, snapshot, segments, annotation));
}
}, ct).ConfigureAwait(true);
_strip.Success(Strings.Menu_File_Export, string.Format(CultureInfo.CurrentCulture, Strings.Summary_Exported_Format, path));
return path;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
_strip.Warn(Strings.Menu_File_Export, string.Format(CultureInfo.CurrentCulture, Strings.Summary_Export_Failed_Format, ex.Message));
return null;
}
}
}
@@ -0,0 +1,24 @@
namespace FrameLedger.App.Services;
/// <summary>
/// The session the shell's File ▸ Export acts on (P4 PR-3): the one selected on a game's Sessions tab, or the one
/// whose summary window was opened last — whichever happened most recently. A singleton the page and the opener
/// write and the shell reads; null until the user has picked anything.
/// </summary>
public sealed class SessionSelection
{
public long? SessionId { get; private set; }
public event EventHandler? Changed;
public void Set(long? sessionId)
{
if (SessionId == sessionId)
{
return;
}
SessionId = sessionId;
Changed?.Invoke(this, EventArgs.Empty);
}
}
@@ -17,14 +17,18 @@ public sealed class SessionSummaryOpener : ISessionSummaryOpener
private readonly IServiceProvider _services;
private readonly ShellHost _shell;
public SessionSummaryOpener(IServiceProvider services, ShellHost shell)
private readonly SessionSelection _selection;
public SessionSummaryOpener(IServiceProvider services, ShellHost shell, SessionSelection selection)
{
_services = services ?? throw new ArgumentNullException(nameof(services));
_shell = shell ?? throw new ArgumentNullException(nameof(shell));
_selection = selection ?? throw new ArgumentNullException(nameof(selection));
}
public void Open(long sessionId)
{
_selection.Set(sessionId); // File ▸ Export follows the window the user opened last (P4 PR-3)
SessionSummaryWindow? window = null;
var viewModel = new SessionSummaryViewModel(
_services.GetRequiredService<ISessionRepository>(),
@@ -0,0 +1,23 @@
using System.ComponentModel;
using System.Diagnostics;
namespace FrameLedger.App.Services;
/// <summary><see cref="IUrlOpener"/> through the shell (<c>UseShellExecute</c>), the same launch every other link in the App makes; a refusal is logged, never thrown.</summary>
public sealed class ShellUrlOpener : IUrlOpener
{
public bool Open(Uri url)
{
ArgumentNullException.ThrowIfNull(url);
try
{
using Process? _ = Process.Start(new ProcessStartInfo(url.AbsoluteUri) { UseShellExecute = true });
return true;
}
catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)
{
Serilog.Log.Warning(ex, "ui: could not open {Url}", url);
return false;
}
}
}
@@ -0,0 +1,22 @@
using System.Runtime.InteropServices;
namespace FrameLedger.App.Services;
/// <summary><see cref="IClipboard"/> over WPF's; the clipboard can be held by another process, which is a refusal, never a crash.</summary>
public sealed class WpfClipboard : IClipboard
{
public bool SetText(string text)
{
ArgumentNullException.ThrowIfNull(text);
try
{
System.Windows.Clipboard.SetText(text);
return true;
}
catch (ExternalException ex)
{
Serilog.Log.Warning(ex, "ui: the clipboard refused the text");
return false;
}
}
}
+42
View File
@@ -42,6 +42,15 @@ public static class Strings
nameof(Agent_State_Offline),
nameof(Agent_State_Starting),
nameof(App_Title),
nameof(BugReport_BrowserRefused),
nameof(BugReport_ClipboardRefused),
nameof(BugReport_Copied),
nameof(BugReport_CopyMarkdown),
nameof(BugReport_OpenIssue),
nameof(BugReport_OpenZipFolder),
nameof(BugReport_Preview_Drag),
nameof(BugReport_Preview_Intro_Format),
nameof(BugReport_Title),
nameof(Chart_Axis_Count),
nameof(Chart_Axis_Fps),
nameof(Chart_Axis_Frametime),
@@ -142,6 +151,8 @@ public static class Strings
nameof(Exit_Interrupted),
nameof(Exit_Normal),
nameof(Exit_UnhookedSafety),
nameof(Export_NoSelection_Body),
nameof(Export_Png_Body),
nameof(Fg_Active),
nameof(Fg_Factor_NotCounted),
nameof(Fg_None),
@@ -273,6 +284,9 @@ public static class Strings
nameof(Menu_File_AddGame),
nameof(Menu_File_Exit),
nameof(Menu_File_Export),
nameof(Menu_File_Export_Csv),
nameof(Menu_File_Export_Json),
nameof(Menu_File_Export_Png),
nameof(Menu_File_ImportLibrary),
nameof(Menu_Help),
nameof(Menu_Help_About),
@@ -514,6 +528,24 @@ public static class Strings
public static string App_Title => ResourceManager.GetString(nameof(App_Title), Culture) ?? nameof(App_Title);
public static string BugReport_BrowserRefused => ResourceManager.GetString(nameof(BugReport_BrowserRefused), Culture) ?? nameof(BugReport_BrowserRefused);
public static string BugReport_ClipboardRefused => ResourceManager.GetString(nameof(BugReport_ClipboardRefused), Culture) ?? nameof(BugReport_ClipboardRefused);
public static string BugReport_Copied => ResourceManager.GetString(nameof(BugReport_Copied), Culture) ?? nameof(BugReport_Copied);
public static string BugReport_CopyMarkdown => ResourceManager.GetString(nameof(BugReport_CopyMarkdown), Culture) ?? nameof(BugReport_CopyMarkdown);
public static string BugReport_OpenIssue => ResourceManager.GetString(nameof(BugReport_OpenIssue), Culture) ?? nameof(BugReport_OpenIssue);
public static string BugReport_OpenZipFolder => ResourceManager.GetString(nameof(BugReport_OpenZipFolder), Culture) ?? nameof(BugReport_OpenZipFolder);
public static string BugReport_Preview_Drag => ResourceManager.GetString(nameof(BugReport_Preview_Drag), Culture) ?? nameof(BugReport_Preview_Drag);
public static string BugReport_Preview_Intro_Format => ResourceManager.GetString(nameof(BugReport_Preview_Intro_Format), Culture) ?? nameof(BugReport_Preview_Intro_Format);
public static string BugReport_Title => ResourceManager.GetString(nameof(BugReport_Title), Culture) ?? nameof(BugReport_Title);
public static string Chart_Axis_Count => ResourceManager.GetString(nameof(Chart_Axis_Count), Culture) ?? nameof(Chart_Axis_Count);
public static string Chart_Axis_Fps => ResourceManager.GetString(nameof(Chart_Axis_Fps), Culture) ?? nameof(Chart_Axis_Fps);
@@ -714,6 +746,10 @@ public static class Strings
public static string Exit_UnhookedSafety => ResourceManager.GetString(nameof(Exit_UnhookedSafety), Culture) ?? nameof(Exit_UnhookedSafety);
public static string Export_NoSelection_Body => ResourceManager.GetString(nameof(Export_NoSelection_Body), Culture) ?? nameof(Export_NoSelection_Body);
public static string Export_Png_Body => ResourceManager.GetString(nameof(Export_Png_Body), Culture) ?? nameof(Export_Png_Body);
public static string Fg_Active => ResourceManager.GetString(nameof(Fg_Active), Culture) ?? nameof(Fg_Active);
public static string Fg_Factor_NotCounted => ResourceManager.GetString(nameof(Fg_Factor_NotCounted), Culture) ?? nameof(Fg_Factor_NotCounted);
@@ -976,6 +1012,12 @@ public static class Strings
public static string Menu_File_Export => ResourceManager.GetString(nameof(Menu_File_Export), Culture) ?? nameof(Menu_File_Export);
public static string Menu_File_Export_Csv => ResourceManager.GetString(nameof(Menu_File_Export_Csv), Culture) ?? nameof(Menu_File_Export_Csv);
public static string Menu_File_Export_Json => ResourceManager.GetString(nameof(Menu_File_Export_Json), Culture) ?? nameof(Menu_File_Export_Json);
public static string Menu_File_Export_Png => ResourceManager.GetString(nameof(Menu_File_Export_Png), Culture) ?? nameof(Menu_File_Export_Png);
public static string Menu_File_ImportLibrary => ResourceManager.GetString(nameof(Menu_File_ImportLibrary), Culture) ?? nameof(Menu_File_ImportLibrary);
public static string Menu_Help => ResourceManager.GetString(nameof(Menu_Help), Culture) ?? nameof(Menu_Help);
+56
View File
@@ -169,6 +169,62 @@
<value>エクスポート</value>
<comment>review</comment>
</data>
<data name="Menu_File_Export_Csv" xml:space="preserve">
<value>セッション CSV</value>
<comment>review</comment>
</data>
<data name="Menu_File_Export_Json" xml:space="preserve">
<value>セッション JSON</value>
<comment>review</comment>
</data>
<data name="Menu_File_Export_Png" xml:space="preserve">
<value>チャート PNG</value>
<comment>review</comment>
</data>
<data name="Export_NoSelection_Body" xml:space="preserve">
<value>先にゲームのセッションタブでセッションを選ぶか、そのサマリーを開いてください。</value>
<comment>review</comment>
</data>
<data name="Export_Png_Body" xml:space="preserve">
<value>チャートはセッションサマリーウィンドウから書き出します。いま開きました。</value>
<comment>review</comment>
</data>
<data name="BugReport_Title" xml:space="preserve">
<value>バグを報告</value>
<comment>review</comment>
</data>
<data name="BugReport_Preview_Intro_Format" xml:space="preserve">
<value>バンドルを {0} に書き出しました ({1} ファイル)。まだどこにも送信していません。内容:</value>
<comment>review</comment>
</data>
<data name="BugReport_Preview_Drag" xml:space="preserve">
<value>GitHub の issue フォームを開き、zip ファイルを説明欄にドラッグしてください。FrameLedger が代わりにアップロードすることはできず、フォームにはバージョンと Windows ビルドしか載りません。</value>
<comment>review</comment>
</data>
<data name="BugReport_OpenIssue" xml:space="preserve">
<value>GitHub で issue を開く</value>
<comment>review</comment>
</data>
<data name="BugReport_CopyMarkdown" xml:space="preserve">
<value>概要を Markdown でコピー</value>
<comment>review</comment>
</data>
<data name="BugReport_OpenZipFolder" xml:space="preserve">
<value>zip をエクスプローラーで表示</value>
<comment>review</comment>
</data>
<data name="BugReport_Copied" xml:space="preserve">
<value>環境の概要を Markdown としてクリップボードにコピーしました。issue に貼り付けてください。</value>
<comment>review</comment>
</data>
<data name="BugReport_ClipboardRefused" xml:space="preserve">
<value>クリップボードがテキストを受け付けませんでした。他のプログラムが使用中かもしれません。</value>
<comment>review</comment>
</data>
<data name="BugReport_BrowserRefused" xml:space="preserve">
<value>ブラウザーを開けませんでした。</value>
<comment>review</comment>
</data>
<data name="Menu_File_ImportLibrary" xml:space="preserve">
<value>ライブラリをインポート…</value>
<comment>review</comment>
+42
View File
@@ -132,6 +132,48 @@
<data name="Menu_File_Export" xml:space="preserve">
<value>Export</value>
</data>
<data name="Menu_File_Export_Csv" xml:space="preserve">
<value>Session CSV</value>
</data>
<data name="Menu_File_Export_Json" xml:space="preserve">
<value>Session JSON</value>
</data>
<data name="Menu_File_Export_Png" xml:space="preserve">
<value>Chart PNG</value>
</data>
<data name="Export_NoSelection_Body" xml:space="preserve">
<value>Select a session on a game's Sessions tab first, or open its summary.</value>
</data>
<data name="Export_Png_Body" xml:space="preserve">
<value>The chart is exported from the session summary window, which is open now.</value>
</data>
<data name="BugReport_Title" xml:space="preserve">
<value>Report a bug</value>
</data>
<data name="BugReport_Preview_Intro_Format" xml:space="preserve">
<value>The bundle was written to {0} ({1} files). Nothing has been sent. It contains:</value>
</data>
<data name="BugReport_Preview_Drag" xml:space="preserve">
<value>Open the GitHub issue form and drag the zip file into the issue description. FrameLedger cannot upload it for you, and the form carries only the version and Windows build.</value>
</data>
<data name="BugReport_OpenIssue" xml:space="preserve">
<value>Open GitHub issue</value>
</data>
<data name="BugReport_CopyMarkdown" xml:space="preserve">
<value>Copy summary as Markdown</value>
</data>
<data name="BugReport_OpenZipFolder" xml:space="preserve">
<value>Show the zip in Explorer</value>
</data>
<data name="BugReport_Copied" xml:space="preserve">
<value>The environment summary is on the clipboard as Markdown; paste it into the issue.</value>
</data>
<data name="BugReport_ClipboardRefused" xml:space="preserve">
<value>The clipboard refused the text; another program may be holding it.</value>
</data>
<data name="BugReport_BrowserRefused" xml:space="preserve">
<value>The browser could not be opened.</value>
</data>
<data name="Menu_File_ImportLibrary" xml:space="preserve">
<value>Import library…</value>
</data>
+42
View File
@@ -127,6 +127,48 @@
<data name="Menu_File_Export" xml:space="preserve">
<value>Xuất</value>
</data>
<data name="Menu_File_Export_Csv" xml:space="preserve">
<value>CSV phiên</value>
</data>
<data name="Menu_File_Export_Json" xml:space="preserve">
<value>JSON phiên</value>
</data>
<data name="Menu_File_Export_Png" xml:space="preserve">
<value>PNG biểu đồ</value>
</data>
<data name="Export_NoSelection_Body" xml:space="preserve">
<value>Hãy chọn một phiên ở tab Phiên của game trước, hoặc mở bản tóm tắt của nó.</value>
</data>
<data name="Export_Png_Body" xml:space="preserve">
<value>Biểu đồ được xuất từ cửa sổ tóm tắt phiên, đã mở sẵn.</value>
</data>
<data name="BugReport_Title" xml:space="preserve">
<value>Báo lỗi</value>
</data>
<data name="BugReport_Preview_Intro_Format" xml:space="preserve">
<value>Gói đã được ghi vào {0} ({1} tệp). Chưa gửi đi đâu cả. Gói gồm:</value>
</data>
<data name="BugReport_Preview_Drag" xml:space="preserve">
<value>Mở biểu mẫu issue trên GitHub và kéo tệp zip vào phần mô tả. FrameLedger không thể tải lên thay bạn; biểu mẫu chỉ mang phiên bản và bản dựng Windows.</value>
</data>
<data name="BugReport_OpenIssue" xml:space="preserve">
<value>Mở issue trên GitHub</value>
</data>
<data name="BugReport_CopyMarkdown" xml:space="preserve">
<value>Sao chép tóm tắt dạng Markdown</value>
</data>
<data name="BugReport_OpenZipFolder" xml:space="preserve">
<value>Hiện tệp zip trong Explorer</value>
</data>
<data name="BugReport_Copied" xml:space="preserve">
<value>Tóm tắt môi trường đã ở clipboard dạng Markdown; hãy dán vào issue.</value>
</data>
<data name="BugReport_ClipboardRefused" xml:space="preserve">
<value>Clipboard từ chối nhận văn bản; có thể chương trình khác đang giữ nó.</value>
</data>
<data name="BugReport_BrowserRefused" xml:space="preserve">
<value>Không mở được trình duyệt.</value>
</data>
<data name="Menu_File_ImportLibrary" xml:space="preserve">
<value>Nhập thư viện…</value>
</data>
@@ -0,0 +1,43 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using CommunityToolkit.Mvvm.Input;
using FrameLedger.App.Services;
namespace FrameLedger.App.ViewModels;
/// <summary>The preview dialog's state (P4 PR-3): the sentence naming the zip, its entries, the drag instruction, and "show it in Explorer".</summary>
[SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format strings are resources that follow the UI culture, which changes at runtime; a cached CompositeFormat would pin the first culture")]
public sealed partial class BugReportPreviewViewModel
{
private readonly BugReportPreviewModel _model;
public BugReportPreviewViewModel(BugReportPreviewModel model)
{
_model = model ?? throw new ArgumentNullException(nameof(model));
Intro = string.Format(CultureInfo.CurrentCulture, Strings.BugReport_Preview_Intro_Format, model.ZipPath, model.Entries.Count);
}
public string Intro { get; }
public IReadOnlyList<string> Entries => _model.Entries;
public static string DragInstruction => Strings.BugReport_Preview_Drag;
public static string ShowZipText => Strings.BugReport_OpenZipFolder;
/// <summary>Explorer with the zip selected — the file the user is about to drag.</summary>
[RelayCommand]
private void ShowZip()
{
try
{
using Process? _ = Process.Start(new ProcessStartInfo("explorer.exe", "/select,\"" + _model.ZipPath + "\"") { UseShellExecute = true });
}
catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)
{
Serilog.Log.Warning(ex, "ui: could not show the bug bundle in Explorer");
}
}
}
@@ -31,6 +31,7 @@ public sealed partial class GameDetailViewModel : ObservableObject
private readonly ISessionSummaryOpener _summaries;
private readonly SessionSeriesLoader _loader;
private readonly IHardwareSnapshotRepository _hardware;
private readonly SessionSelection _selection;
private readonly long? _gameId;
private GameDetail? _detail;
@@ -114,8 +115,9 @@ public sealed partial class GameDetailViewModel : ObservableObject
public GameDetailViewModel(GameLibrary library, GameSelection selection, HookingConsent consent, IPageNavigator navigator,
IConfirmations confirmations, IEditGamePrompt edit, IMessageStrip strip, ISessionSummaryOpener summaries,
SessionSeriesLoader loader, IHardwareSnapshotRepository hardware)
SessionSeriesLoader loader, IHardwareSnapshotRepository hardware, SessionSelection sessionSelection)
{
_selection = sessionSelection ?? throw new ArgumentNullException(nameof(sessionSelection));
_library = library ?? throw new ArgumentNullException(nameof(library));
ArgumentNullException.ThrowIfNull(selection);
_consent = consent ?? throw new ArgumentNullException(nameof(consent));
@@ -238,7 +240,11 @@ public sealed partial class GameDetailViewModel : ObservableObject
await RebuildTrendAsync(ct).ConfigureAwait(true);
}
partial void OnSelectedSessionChanged(SessionItemViewModel? value) => Pending = LoadSelectedAsync(value);
partial void OnSelectedSessionChanged(SessionItemViewModel? value)
{
_selection.Set(value?.Id); // File ▸ Export acts on this (P4 PR-3)
Pending = LoadSelectedAsync(value);
}
partial void OnTrendMetricChanged(TrendMetric value) => RebuildTrendPoints();
@@ -21,11 +21,9 @@ public sealed partial class LogsViewModel : ObservableObject, IDisposable
public static readonly TimeSpan RefreshPeriod = TimeSpan.FromSeconds(2);
private readonly LogTail _tail;
private readonly BugBundleBuilder _bundles;
private readonly IFileSaver _saver;
private readonly IAgentRequests _agent;
private readonly IMessageStrip _strip;
private readonly BugReportFlow _bugReports;
private readonly TimeProvider _clock;
private readonly IMessageStrip _strip;
private readonly UiThread _ui = new();
private IReadOnlyList<string> _lines = [];
private ITimer? _timer;
@@ -51,12 +49,10 @@ public sealed partial class LogsViewModel : ObservableObject, IDisposable
[ObservableProperty]
private string? _currentFile;
public LogsViewModel(LogTail tail, BugBundleBuilder bundles, IFileSaver saver, IAgentRequests agent, IMessageStrip strip, TimeProvider? clock = null)
public LogsViewModel(LogTail tail, BugReportFlow bugReports, IMessageStrip strip, TimeProvider? clock = null)
{
_tail = tail ?? throw new ArgumentNullException(nameof(tail));
_bundles = bundles ?? throw new ArgumentNullException(nameof(bundles));
_saver = saver ?? throw new ArgumentNullException(nameof(saver));
_agent = agent ?? throw new ArgumentNullException(nameof(agent));
_bugReports = bugReports ?? throw new ArgumentNullException(nameof(bugReports));
_strip = strip ?? throw new ArgumentNullException(nameof(strip));
_clock = clock ?? TimeProvider.System;
Pending = RefreshAsync();
@@ -123,7 +119,7 @@ public sealed partial class LogsViewModel : ObservableObject, IDisposable
}
}
/// <summary><c>10_LOGGING</c> §Bug report flow step 2: the zip, where the user says; nothing is sent (steps 3–4 are P4's).</summary>
/// <summary><c>10_LOGGING</c> §Bug report flow: the zip where the user says, the preview, then the issue form or the clipboard — nothing is ever sent by itself.</summary>
[RelayCommand]
private Task ExportBundleAsync() => Pending = ExportBundleCoreAsync();
@@ -160,24 +156,6 @@ public sealed partial class LogsViewModel : ObservableObject, IDisposable
OnPropertyChanged(nameof(TotalCount));
}
private async Task ExportBundleCoreAsync()
{
DateTimeOffset now = _clock.GetUtcNow();
string? path = _saver.PickSavePath("Zip archive (*.zip)|*.zip", BugBundleBuilder.SuggestedName(now));
if (path is null)
{
return;
}
try
{
IReadOnlyList<string> written = await _bundles.WriteAsync(path, _agent.Hello).ConfigureAwait(true);
_strip.Success(Strings.Logs_ExportBundle, string.Format(CultureInfo.CurrentCulture, Strings.Logs_Bundle_Exported_Format, path, written.Count));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Serilog.Log.Warning(ex, "ui: the bug bundle could not be written");
_strip.Warn(Strings.Logs_ExportBundle, string.Format(CultureInfo.CurrentCulture, Strings.Logs_Bundle_Failed_Format, ex.Message));
}
}
/// <summary><c>10_LOGGING</c> §Bug report flow steps 2–4 (P4 PR-3), the same flow Help ▸ Report a bug runs.</summary>
private async Task ExportBundleCoreAsync() => _ = await _bugReports.RunAsync().ConfigureAwait(true);
}
@@ -35,10 +35,21 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable
private string _agentBannerBody = string.Empty;
private readonly AddGameFlow _addGame;
private readonly BugReportFlow _bugReports;
private readonly IUrlOpener _urls;
private readonly SessionSelection _selection;
private readonly SessionExportService _exports;
private readonly ISessionSummaryOpener _summaries;
public MainWindowViewModel(AgentConnection agent, ISnackbarService snackbar, IShellPresence shell, IPageNavigator navigator, AddGameFlow addGame, SafetyNotices notices)
public MainWindowViewModel(AgentConnection agent, ISnackbarService snackbar, IShellPresence shell, IPageNavigator navigator, AddGameFlow addGame, SafetyNotices notices,
BugReportFlow bugReports, IUrlOpener urls, SessionSelection selection, SessionExportService exports, ISessionSummaryOpener summaries)
{
Notices = notices ?? throw new ArgumentNullException(nameof(notices));
_bugReports = bugReports ?? throw new ArgumentNullException(nameof(bugReports));
_urls = urls ?? throw new ArgumentNullException(nameof(urls));
_selection = selection ?? throw new ArgumentNullException(nameof(selection));
_exports = exports ?? throw new ArgumentNullException(nameof(exports));
_summaries = summaries ?? throw new ArgumentNullException(nameof(summaries));
_agent = agent ?? throw new ArgumentNullException(nameof(agent));
_snackbar = snackbar ?? throw new ArgumentNullException(nameof(snackbar));
_shell = shell ?? throw new ArgumentNullException(nameof(shell));
@@ -145,6 +156,65 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable
}
}
/// <summary>Help ▸ Documentation (P4 PR-3): the README is the user-facing entry point; `docs/` is the developers'.</summary>
[RelayCommand]
private void Documentation()
{
if (!_urls.Open(IssueLink.Documentation))
{
_snackbar.Show(Strings.Menu_Help_Documentation, Strings.BugReport_BrowserRefused, ControlAppearance.Caution, new SymbolIcon(SymbolRegular.Warning24), TimeSpan.FromSeconds(4));
}
}
/// <summary>Help ▸ Report a bug… (P4 PR-3): <c>10_LOGGING</c> §Bug report flow steps 2–4, the same flow the Logs page's button runs.</summary>
[RelayCommand]
private async Task ReportBugAsync() => _ = await _bugReports.RunAsync().ConfigureAwait(true);
/// <summary>File ▸ Export ▸ Session CSV, for the session last selected on a Sessions tab or opened in a summary window.</summary>
[RelayCommand]
private async Task ExportCsvAsync()
{
if (_selection.SessionId is { } id)
{
_ = await _exports.ExportCsvAsync(id).ConfigureAwait(true);
}
else
{
NoSelection();
}
}
[RelayCommand]
private async Task ExportJsonAsync()
{
if (_selection.SessionId is { } id)
{
_ = await _exports.ExportJsonAsync(id).ConfigureAwait(true);
}
else
{
NoSelection();
}
}
/// <summary>File ▸ Export ▸ Chart PNG needs the summary window's live plot, so it opens that window and says so.</summary>
[RelayCommand]
private void ExportPng()
{
if (_selection.SessionId is { } id)
{
_summaries.Open(id);
_snackbar.Show(Strings.Menu_File_Export, Strings.Export_Png_Body, ControlAppearance.Secondary, new SymbolIcon(SymbolRegular.Info24), TimeSpan.FromSeconds(4));
}
else
{
NoSelection();
}
}
private void NoSelection() =>
_snackbar.Show(Strings.Menu_File_Export, Strings.Export_NoSelection_Body, ControlAppearance.Caution, new SymbolIcon(SymbolRegular.Info24), TimeSpan.FromSeconds(4));
/// <summary>Every menu item of <c>08_UI</c> §Menu bar that a later slice builds says so, in a 4 s snackbar, rather than doing nothing.</summary>
[RelayCommand]
private void NotYet() =>
@@ -0,0 +1,123 @@
using System.IO;
using System.IO.Compression;
using FluentAssertions;
using FrameLedger.App.Services;
using FrameLedger.Application.Settings;
using FrameLedger.Infrastructure.Persistence;
using FrameLedger.Shared.Ipc;
namespace FrameLedger.App.Tests;
/// <summary>
/// <c>10_LOGGING</c> §Bug report flow steps 2–4 (P4 PR-3): the zip goes where the user says and the preview lists what
/// it holds; "Open GitHub issue" opens the form with the two short fields prefilled by their real ids; the fallback
/// puts the environment summary on the clipboard as Markdown; a cancelled save does nothing; nothing is ever sent.
/// </summary>
public sealed class BugReportFlowTests : IDisposable
{
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-bugflow-" + Guid.NewGuid().ToString("N"));
public BugReportFlowTests() => Directory.CreateDirectory(_dir);
public void Dispose() => Directory.Delete(_dir, recursive: true);
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private sealed class PathSaver(string? path) : IFileSaver
{
public string? PickSavePath(string filter, string suggestedName) => path;
}
private sealed class RecordingStrip : IMessageStrip
{
public List<(string Kind, string Title, string Body)> Shown { get; } = [];
public void Info(string title, string body) => Shown.Add(("info", title, body));
public void Success(string title, string body) => Shown.Add(("success", title, body));
public void Warn(string title, string body) => Shown.Add(("warn", title, body));
}
private sealed record Harness(BugReportFlow Flow, ClosePreview Preview, NoUrlOpener Urls, NoClipboard Clipboard, RecordingStrip Strip, string Zip);
private async Task<Harness> BuildAsync(ScratchLedger s, BugReportChoice choice, bool cancel = false)
{
await File.WriteAllTextAsync(Path.Combine(_dir, "ui-20260914.log"), "[12:00:00.000 INF] hello\n", Ct).ConfigureAwait(false);
var builder = new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db)));
string zip = Path.Combine(_dir, "bundle.zip");
var preview = new ClosePreview(choice);
var urls = new NoUrlOpener();
var clipboard = new NoClipboard();
var strip = new RecordingStrip();
var agent = new FakeAgentLink { Hello = new HelloAck("9.9.9", IpcProtocol.Version, 4, false, "build-z", false, "l1", false, "consent-dialog/1") };
return new Harness(new BugReportFlow(builder, new PathSaver(cancel ? null : zip), agent, preview, urls, clipboard, strip), preview, urls, clipboard, strip, zip);
}
[Fact]
public async Task TheZipIsWrittenThePreviewListsItAndOpenIssueOpensTheFormPrefilledByFieldId()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
Harness h = await BuildAsync(s, BugReportChoice.OpenIssue);
BugReportOutcome o = await h.Flow.RunAsync(Ct);
o.Written.Should().BeTrue();
o.Choice.Should().Be(BugReportChoice.OpenIssue);
File.Exists(h.Zip).Should().BeTrue();
BugReportPreviewModel shown = h.Preview.Shown.Should().ContainSingle().Subject;
shown.ZipPath.Should().Be(h.Zip);
using (ZipArchive archive = await ZipFile.OpenReadAsync(h.Zip, Ct))
{
shown.Entries.Should().BeEquivalentTo(archive.Entries.Select(static e => e.FullName), "the preview lists exactly what the zip holds");
}
shown.Entries.Should().Contain("logs/ui-20260914.log").And.Contain("sysinfo.json");
h.Urls.Opened.Should().ContainSingle().Which.AbsoluteUri.Should().StartWith(IssueLink.Repository + "/issues/new?template=bug_report.yml&title=%5BBug%5D%20&labels=bug&app-version=")
.And.Contain("&os=Windows%20", "the form's field ids are app-version and os, hyphenated");
h.Clipboard.Texts.Should().BeEmpty();
h.Strip.Shown.Should().BeEmpty("the browser opened; there is nothing to say");
}
[Fact]
public async Task CopyMarkdownPutsTheEnvironmentSummaryOnTheClipboard()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
Harness h = await BuildAsync(s, BugReportChoice.CopyMarkdown);
await h.Flow.RunAsync(Ct);
h.Urls.Opened.Should().BeEmpty();
string md = h.Clipboard.Texts.Should().ContainSingle().Subject;
md.Should().StartWith("| Key | Value |").And.Contain("| `app_version` | ").And.Contain("| `agent_version` | 9.9.9 |").And.Contain("| `overlay_build_id` | build-z |");
h.Strip.Shown.Should().ContainSingle().Which.Kind.Should().Be("info");
}
[Fact]
public async Task ClosingKeepsTheZipAndSaysSoAndACancelledSaveWritesNothing()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
Harness closed = await BuildAsync(s, BugReportChoice.Close);
(await closed.Flow.RunAsync(Ct)).Choice.Should().Be(BugReportChoice.Close);
File.Exists(closed.Zip).Should().BeTrue();
closed.Urls.Opened.Should().BeEmpty();
closed.Strip.Shown.Should().ContainSingle().Which.Kind.Should().Be("success");
Harness cancelled = await BuildAsync(s, BugReportChoice.OpenIssue, cancel: true);
BugReportOutcome o = await cancelled.Flow.RunAsync(Ct);
o.Written.Should().BeFalse();
cancelled.Preview.Shown.Should().BeEmpty("no zip, no preview");
cancelled.Strip.Shown.Should().BeEmpty();
}
[Fact]
public void TheIssueLinkAndTheOsLineAreTheFormsSpelling()
{
IssueLink.NewIssue("0.1.0", "Windows 11 26100.2314").AbsoluteUri.Should().Be(
"https://github.com/poli0981/frameledger/issues/new?template=bug_report.yml&title=%5BBug%5D%20&labels=bug&app-version=0.1.0&os=Windows%2011%2026100.2314");
IssueLink.OsText(new Version(10, 0, 26100, 2314)).Should().Be("Windows 11 26100.2314");
IssueLink.OsText(new Version(10, 0, 19045, 0)).Should().Be("Windows 10 19045");
IssueLink.Documentation.AbsoluteUri.Should().Be("https://github.com/poli0981/frameledger#readme");
IssueLink.Markdown(new Dictionary<string, string>(StringComparer.Ordinal) { ["a"] = "x|y" }).Should().Contain("| `a` | x\\|y |", "a pipe in a value must not break the table");
}
}
@@ -0,0 +1,15 @@
using FrameLedger.App.Services;
namespace FrameLedger.App.Tests;
/// <summary>The bug report flow's three ports, scripted (P4 PR-3): a preview that answers what the test says, a browser and a clipboard that record.</summary>
internal sealed class ClosePreview(BugReportChoice choice = BugReportChoice.Close) : IBugReportPreview
{
public List<BugReportPreviewModel> Shown { get; } = [];
public Task<BugReportChoice> ShowAsync(BugReportPreviewModel model, CancellationToken ct = default)
{
Shown.Add(model);
return Task.FromResult(choice);
}
}
@@ -99,7 +99,7 @@ public sealed class GameDetailViewModelTests
var strip = new FakeStrip();
var vm = new GameDetailViewModel(s.Library, new GameSelection { GameId = gameId }, new HookingConsent(agent, prompt), nav,
new FakeConfirmations(remove), new FakeEdit(edit), strip, new NoSummaries(),
new Charts.SessionSeriesLoader(s.Sessions), new Infrastructure.Persistence.SqliteHardwareSnapshotRepository(s.Db));
new Charts.SessionSeriesLoader(s.Sessions), new Infrastructure.Persistence.SqliteHardwareSnapshotRepository(s.Db), new SessionSelection());
Task pending = vm.Pending;
await pending.ConfigureAwait(false);
return (vm, agent, prompt, nav, strip);
@@ -43,7 +43,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 BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))), new PathSaver(null), new FakeAgentLink(), strip);
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);
Task pending1 = vm.Pending;
await pending1;
@@ -70,7 +70,7 @@ public sealed class LogsViewModelTests : IDisposable
public async Task WithoutAFileTheStatusSaysSo()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
using var vm = new LogsViewModel(new LogTail(_dir), new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))), new PathSaver(null), new FakeAgentLink(), 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(), new RecordingStrip()), new RecordingStrip());
Task pending = vm.Pending;
await pending;
@@ -88,7 +88,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 BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))), saver, new FakeAgentLink(), strip);
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);
Task pending1 = vm.Pending;
await pending1;
@@ -106,7 +106,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 BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))), new PathSaver(null), new FakeAgentLink(), strip);
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);
await vm.ExportBundleCommand.ExecuteAsync(null);
@@ -0,0 +1,14 @@
using FrameLedger.App.Services;
namespace FrameLedger.App.Tests;
internal sealed class NoClipboard(bool accepts = true) : IClipboard
{
public List<string> Texts { get; } = [];
public bool SetText(string text)
{
Texts.Add(text);
return accepts;
}
}
@@ -0,0 +1,14 @@
using FrameLedger.App.Services;
namespace FrameLedger.App.Tests;
internal sealed class NoUrlOpener(bool accepts = true) : IUrlOpener
{
public List<Uri> Opened { get; } = [];
public bool Open(Uri url)
{
Opened.Add(url);
return accepts;
}
}
@@ -208,7 +208,7 @@ public sealed class PagesLoadTests
var settings = new SettingsViewModel(appearance, new NoTheme(), new ShellHost(new ServiceCollection().BuildServiceProvider(), null!, null!, new WindowClosePolicy()), new RegisteredSettings(store), s.Library, consent, new NoAgent(), new NoRun(), strip, new NoMaintenance(), new NoTool(), new WindowClosePolicy(), new NoFirstRun());
Task pending1 = settings.Pending;
await pending1.ConfigureAwait(false);
var logs = new LogsViewModel(new LogTail(Path.Combine(Path.GetTempPath(), "fl-nologs-" + Guid.NewGuid().ToString("N"))), new BugBundleBuilder(Path.GetTempPath(), new RegisteredSettings(store)), new NoSaver(), new NoAgent(), strip);
var logs = new LogsViewModel(new LogTail(Path.Combine(Path.GetTempPath(), "fl-nologs-" + Guid.NewGuid().ToString("N"))), new BugReportFlow(new BugBundleBuilder(Path.GetTempPath(), new RegisteredSettings(store)), new NoSaver(), new NoAgent(), new ClosePreview(), new NoUrlOpener(), new NoClipboard(), strip), strip);
Task pending2 = logs.Pending;
await pending2.ConfigureAwait(false);
return (settings, logs);
@@ -316,7 +316,7 @@ public sealed class PagesLoadTests
Task pending2 = games.Pending;
await pending2;
var detail = new GameDetailViewModel(s.Library, selection, consent, nav, new NoConfirm(), new NoEdit(), strip, new NoSummaries(),
new SessionSeriesLoader(s.Sessions), new Infrastructure.Persistence.SqliteHardwareSnapshotRepository(s.Db));
new SessionSeriesLoader(s.Sessions), new Infrastructure.Persistence.SqliteHardwareSnapshotRepository(s.Db), new SessionSelection());
var compare = new CompareViewModel(s.Library, new SessionSeriesLoader(s.Sessions), new NoMixed(), new NoSaver(), strip);
Task pending3 = detail.Pending;
await pending3;
@@ -0,0 +1,94 @@
using System.IO;
using FluentAssertions;
using FrameLedger.App.Charts;
using FrameLedger.App.Services;
using FrameLedger.Application.Persistence;
using FrameLedger.Infrastructure.Persistence;
namespace FrameLedger.App.Tests;
/// <summary>File ▸ Export from the shell (P4 PR-3): the selected session as CSV or JSON, the same writers the summary window uses; no selection or a cancelled save writes nothing.</summary>
public sealed class SessionExportServiceTests : IDisposable
{
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-export-" + Guid.NewGuid().ToString("N"));
public SessionExportServiceTests() => Directory.CreateDirectory(_dir);
public void Dispose() => Directory.Delete(_dir, recursive: true);
private static CancellationToken Ct => TestContext.Current.CancellationToken;
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 sealed class RecordingStrip : IMessageStrip
{
public List<string> Kinds { get; } = [];
public void Info(string title, string body) => Kinds.Add("info");
public void Success(string title, string body) => Kinds.Add("success");
public void Warn(string title, string body) => Kinds.Add("warn");
}
private static SessionExportService Build(ScratchLedger s, IFileSaver saver, IMessageStrip strip) => new(
s.Sessions, s.Games, new SqliteSessionAnnotationRepository(s.Db), new SqliteHardwareSnapshotRepository(s.Db), new SessionSeriesLoader(s.Sessions), saver, strip);
[Fact]
public async Task TheSelectedSessionIsWrittenAsCsvAndJsonWhereTheUserSays()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow game = await s.GameAsync("Alpha");
long id = await s.SessionAsync(game.Id, DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000), hooked: true, fgMode: "dlssg", native: 62, displayed: 118, factor: 1.9);
var strip = new RecordingStrip();
string csv = Path.Combine(_dir, "out.csv");
var csvSaver = new PathSaver(csv);
(await Build(s, csvSaver, strip).ExportCsvAsync(id, Ct)).Should().Be(csv);
csvSaver.Suggested.Should().StartWith("Alpha-").And.EndWith(".csv");
(await File.ReadAllTextAsync(csv, Ct)).Should().Contain(SessionExporter.CsvColumns, "the same writer the summary window uses");
string json = Path.Combine(_dir, "out.json");
(await Build(s, new PathSaver(json), strip).ExportJsonAsync(id, Ct)).Should().Be(json);
(await File.ReadAllTextAsync(json, Ct)).Should().Contain("\"Alpha\"");
strip.Kinds.Should().Equal("success", "success");
}
[Fact]
public async Task AnUnknownSessionOrACancelledSaveWritesNothing()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow game = await s.GameAsync("Alpha");
long id = await s.SessionAsync(game.Id, DateTimeOffset.UnixEpoch);
var strip = new RecordingStrip();
(await Build(s, new PathSaver(Path.Combine(_dir, "x.csv")), strip).ExportCsvAsync(id + 99, Ct)).Should().BeNull();
strip.Kinds.Should().Equal("warn");
(await Build(s, new PathSaver(null), strip).ExportJsonAsync(id, Ct)).Should().BeNull("cancelled");
Directory.EnumerateFiles(_dir).Should().BeEmpty();
strip.Kinds.Should().Equal("warn"); // a cancelled save says nothing
}
[Fact]
public void TheSelectionRemembersTheLastPickAndRaisesOnce()
{
var selection = new SessionSelection();
int raised = 0;
selection.Changed += (_, _) => raised++;
selection.Set(7);
selection.Set(7);
selection.Set(null);
selection.SessionId.Should().BeNull();
raised.Should().Be(2);
}
}