Compare commits

...
Author SHA1 Message Date
poli0981andClaude Opus 5 7889720ba9 fix(app): bug bundles no longer carry the user's name in log paths, as the privacy policy already promised
legal/PRIVACY_POLICY.md section 3 says logs are redacted (user directory paths removed) before bundling, and
10_LOGGING named a RedactingEnricher. Neither existed: BugBundleBuilder copied ui-*.log, agent-*.log and
overlay-*.log verbatim, on the ground that they carry no paths beyond the data directory, which is itself under the
user's profile. On the dev box the profile path appeared 8 times in the UI log, 7 in the Agent's and in 175 overlay
headers.

LogRedactor rewrites every log copy in the zip: the name in each X:\Users\<name> path becomes <user>, and so does a
profile directory's last segment elsewhere, in backslash, doubled-backslash (Serilog's JSON), forward-slash, any-case
and ANSI-question-mark spellings. The file is read through Latin-1, so UTF-8 and ANSI logs come out byte for byte
except the names. The files on disk keep their paths, and the policy's sentence is now true unchanged. The enricher
claim is struck in 10_LOGGING with where the rule is enforced instead.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 20:39:42 +07:00
poli0981andClaude Opus 5 f94687f42f test: the harness's overlay logs leave with the test run that wrote them, and a gate keeps it so (#180)
The injection tests inject the shipped Overlay into hook-harness, and the Overlay logs to the real
%LOCALAPPDATA%\FrameLedger\logs by design (SHGetKnownFolderPath, not the environment, per S21). The owner's folder
held 2506 overlay logs on 2026-09-15, 2492 of them hook-harness's from test runs, beside 14 from real titles.

No switch goes into the injected DLL. Each test binary removes, when its run ends, the logs it caused: an
overlay-*.log created after the run started whose first line names a hook-harness image it owns. Natively a Catch2
listener in guard_test.cpp over src/native/tests/overlay_log_sweep.h (the image must be FL_HARNESS_EXE); in managed
code tests/Shared/HarnessOverlayLogSweep.cs, an xUnit assembly fixture that FrameLedger.DrainFixtures.targets compiles
into every test project staging the harness, with PipeEndToEndTests registering its renamed copy's directory. Parallel
assemblies own different copies, so none removes a log another is about to read, and a game's log is never touched.

tools/test-artifacts-check.ps1 (seven self-test cases) is a new gate step: a hook-harness log created during the gate
and still there fails it, which is what makes a missing sweep red. Existing logs are left for the owner.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 20:33:23 +07:00
poli0981andClaude Opus 5 2519864f2f feat(app): the crash dialog, the minidump in both processes, and the crash dump as the bug report's opt-in (P4 PR-9) (#179)
10_LOGGING's crash handling specified Fatal, MiniDumpWriteDump, a dialog offering the bug report and exit code 1;
only the Fatal line existed. Infrastructure's CrashDumpWriter writes crashdumps\<ui|agent>-<UTC time>-<pid>.dmp with
the spec's two flags, keeps the five newest and never throws.

The App marks a dispatcher exception handled; CrashReporter logs it, writes the dump and shows a Win32 message box
whose Yes runs BugReportFlow, then the host stops and RunAsync exits with code 1. One dialog per process: further
exceptions are logged once and counted, since a layout fault repeats while the dialog pumps. Another thread's
exception is Fatal and a dump only. The Agent logs and dumps from AppDomain.UnhandledException and from Main's own
catch, once, and leaves the exception unhandled.

The bug report offers the newest dump of the last seven days before the save dialog as a checkbox that starts clear,
with its size and what a dump can hold, which is what PRIVACY_POLICY section 3 already promised; Cancel writes
nothing and WriteAsync refuses a dump from outside crashdumps\. Crash_Body becomes Crash_Body_Format; seven more
strings in en/vi/ja.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 09:22:29 +07:00
poli0981andClaude Opus 5 f7f7195d69 feat(app): the accessibility pass -- Ctrl+1..5, Esc closes dialogs, an automation name on every textless input (P4 PR-8) (#178)
08_UI gains an Accessibility section first, then the build it describes. Ctrl+1..5 (and the keypad)
open Dashboard, Games, Compare, Logs and Settings through ShellShortcuts, the one place that knows
which number is which page. Esc closes the open ContentDialog or MessageBox with no result through
the dialog's own Close path, and never one that offers no Close button: WPF UI 4.3.0 handles no key
in either, ContentDialog.CloseButtonText defaults to "Close", and MessageBox.Close() is obsolete, so
DialogKeyboard uses the Close button's TemplateButtonCommand from one class handler on Window.

Thirty controls that announced only their type carry an AutomationProperties.Name from .resx; four
new strings (en/vi/ja) name the ones with no label to borrow. The maintenance dialog's status line is
a polite live region. AccessibilityTests hold all of it: every textless input is named (proven red on
the kill switch), no XAML hard-codes a colour, the manifest is Per-Monitor V2, the shortcuts follow the
NavigationView's order, and Esc closes a real ContentDialog with no result.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 01:25:10 +07:00
63 changed files with 2569 additions and 84 deletions

No files matched your search

+66
View File
@@ -21,6 +21,46 @@ under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, the
### Added
- **P4 PR-9 — the crash dialog, the minidump in both processes, and the crash dump as the bug report's opt-in
(2026-09-15).** `10_LOGGING` §Crash handling specified Fatal → `MiniDumpWriteDump` → a dialog offering the bug report
→ exit code 1; only the Fatal line existed, and `Crash_Title` / `Crash_Body` were translated for a dialog nothing
showed. `Infrastructure/Diagnostics/CrashDumpWriter` writes `crashdumps\<ui|agent>-<UTC time>-<pid>.dmp` through
CsWin32 with `MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithThreadInfo`, keeps the five newest and never
throws. **The App** marks a dispatcher exception handled; `CrashReporter` logs it, writes the dump and shows
`CrashDialog` — a Win32 message box, because a crash cannot vouch for the shell's dialog host — whose Yes reveals the
shell window (one hidden in the tray would hold the report's dialogs unseen) and runs `BugReportFlow`; the host then stops and `RunAsync` exits with code 1 after the normal teardown. One dialog per
process: a further exception while it is up is logged once and counted, since a layout fault repeats on every pass
the dialog's message loop runs. An exception on any other thread is Fatal + dump only. **The Agent** logs and dumps
from `AppDomain.UnhandledException` and from `Main`'s own catch (whose `finally` would otherwise close the logger
first), once, and leaves the exception unhandled. **The bug report** offers the newest dump of the last seven days
before the save dialog, as a checkbox that starts clear, labelled with its time and size, with a line saying a dump
can hold file paths, game names and settings (`Dialogs/BugBundleOptionsContent`) — what `legal/PRIVACY_POLICY.md` §3
already promised; Cancel writes nothing, and `BugBundleBuilder.WriteAsync` refuses a dump from anywhere but
`crashdumps\`. `Crash_Body` becomes `Crash_Body_Format` and keeps its one fact (the capture agent keeps running);
seven more strings (en/vi/ja). Tests: `CrashDumpWriterTests` (a real dump of the test process starts `MDMP`; the
prune keeps five and touches nothing else; an unusable directory is null and a line), `CrashReporterTests` (the order,
no report on No, three further exceptions show nothing, a failed dump still asks, a failed report is not a second
crash), `BugBundleBuilderTests`, `BugReportFlowTests` (no dump no question; left clear, ticked, cancelled),
`BugBundleOptionsViewModelTests`, `PagesLoadTests`. Docs: `10_LOGGING` §Crash handling and §Bug report flow,
`15_ROADMAP`, HANDOFF §P4.
- **P4 PR-8 — the accessibility pass, with the section it passes against written first (NFR-9, 2026-09-15).**
NFR-9 was one sentence and `08_UI` one bullet ("Ctrl+1…5; grids fully navigable; Esc closes flyouts/dialogs"), none
of it built. `08_UI` §Accessibility now says what each clause means here and names the check: **Ctrl+1 … Ctrl+5**
and the keypad open Dashboard / Games / Compare / Logs / Settings (`MainWindow` `InputBindings` →
`MainWindowViewModel.NavigateToCommand` → `ShellShortcuts`), and `AccessibilityTests` holds the bindings, the map and
the NavigationView's order together; **Esc closes the open `ContentDialog` or `MessageBox` with no result**, through
its own Close path, and never a dialog that offers no Close button (`Services/DialogKeyboard`, one class handler on
`Window` registered in `App.OnStartup`, bubbling so a dropdown's Esc wins) — WPF UI 4.3.0 handles no key in either
dialog, measured in its source; **every input that shows no text of its own has an `AutomationProperties.Name`** —
thirty controls had none (every Settings toggle, number box and choice box, the hooking switch, the trend metric,
the Games and Logs filters and search boxes, the log tail, the edit-game and consent text boxes, the Legal Gate's
document, the summary window's tags and notes, and the icon-only close button in the `InfoBar` template), a scan of
the App's XAML goes red on the next one (proven by removing one name), and four new strings name the controls that
had no label to borrow (en/vi/ja); **no XAML hard-codes a colour** (a second scan), so contrast is the Fluent
themes'; the manifest is Per-Monitor V2 (a third). Known gaps are stated there: ScottPlot plots are not
keyboard-operable, and no Narrator pass has been done. Docs: `08_UI` §Accessibility and §UX rules, `02_SPEC` NFR-9,
`16_WPFUI_SYNTAX` §Gotchas (no Esc in 4.3.0, `CloseButtonText` defaults to "Close", the obsolete `MessageBox.Close`),
`15_ROADMAP`, HANDOFF §P4. The Database maintenance dialog's status line is `LiveSetting="Polite"`, so a result is read out.
- **P4 PR-7 — Tools ▸ Database maintenance: integrity check, backup, the retention sweep on demand, compaction
(2026-09-15).** `06_DATA_MODEL` §Retention promised the four since P0; the menu item said "not built yet". **The
sweep is the Agent's**, because `frame_blobs` and `sensor_blobs` are (§Writer ownership): the App sends the new
@@ -201,6 +241,32 @@ under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, the
### Fixed
- **Bug bundles no longer carry the user's name in log paths, which the privacy policy already promised
(2026-09-15).** `legal/PRIVACY_POLICY.md` §3 says "logs are redacted (user directory paths removed) before
bundling" and `10_LOGGING` named a `RedactingEnricher`; neither existed, and `BugBundleBuilder` copied `ui-*.log`,
`agent-*.log` and `overlay-*.log` verbatim on the stated ground that they carry no paths beyond the data directory,
which is itself under the user's profile. On the dev box the profile path appeared 8 times in the UI log, 7 in the
Agent's and in 175 overlay headers. `App/Services/LogRedactor` now rewrites every log copy in the zip: the name in
each `X:\Users\<name>` path becomes `<user>`, and so does a profile directory's last segment elsewhere, in
backslash, doubled-backslash (Serilog's JSON), forward-slash, any-case and ANSI-`?` spellings, byte for byte
otherwise (Latin-1 round trip, so UTF-8 and ANSI logs both survive). The files on disk keep their paths; the policy's
sentence is now true without a word of it changing. Tests: `LogRedactorTests`, `BugBundleBuilderTests`. Docs:
`10_LOGGING` §Serilog configuration (the enricher claim struck, with where the rule is enforced) and §Bug report
flow step 2.
- **Test runs stop filling the real data folder with hook-harness logs (2026-09-15).** The injection tests inject the
shipped Overlay, whose log goes to `%LOCALAPPDATA%\FrameLedger\logs` by design (§S21: not the environment, and no
switch in the injected DLL), so the owner's folder held 2506 overlay logs, 2492 of them hook-harness's from test
runs since 2026-09-06, beside 14 from real titles. Each test binary now removes, when its run ends, exactly the logs
it caused: an `overlay-*.log` created after the run started whose first line names a hook-harness image it owns. A
Catch2 listener in `guard_test.cpp` does it natively (`src/native/tests/overlay_log_sweep.h`, the image must be this build's
`FL_HARNESS_EXE`), and `tests/Shared/HarnessOverlayLogSweep.cs`, an xUnit assembly fixture that
`FrameLedger.DrainFixtures.targets` compiles into every test project staging the harness, does it for the managed
suites (the copy beside the test binary, plus the renamed copy `PipeEndToEndTests` registers). Assemblies run in
parallel with their own copies, so none removes a log another is about to read, and a game's log is never touched.
The new `test-artifacts` gate (`tools/test-artifacts-check.ps1`, seven self-test cases) fails for a harness log
created during the gate and still there, which is red on the unswept tree. Tests: `[sweep]` in `fl_guard_test`,
`HarnessOverlayLogSweepTests`. The logs from before this change are left for the owner. Docs: `17_HOOK_ENGINE`
§Native logging, `12_BUILD` gate list, `14_TESTING`, HANDOFF §Traps. No Overlay change, so no hook-path overhead.
- **The native log test read another process's log, and was filed as a flake four times (2026-09-14).**
`guard_test.cpp`'s `FindOverlayLog` took the first `overlay-<pid>-*.log` by name in the real
`%LOCALAPPDATA%\FrameLedger\logs`, which keeps every run's log — 2130 on the dev box. A harness that drew a
+12
View File
@@ -39,6 +39,18 @@
</None>
</ItemGroup>
<!--
THE HARNESS'S LOGS LEAVE WITH THE ASSEMBLY THAT CAUSED THEM. The Overlay logs to the real
%LOCALAPPDATA%\FrameLedger\logs by design (§S21), so every TEST project that stages hook-harness
compiles tests/Shared/HarnessOverlayLogSweep.cs, an xUnit assembly fixture that removes, when the
assembly finishes, the overlay logs of the harness copies it owns (17_HOOK_ENGINE §Native logging).
The CaptureHost imports this file too and is not a test project, so it does not get the sweep.
tools/test-artifacts-check.ps1 is what makes a missing sweep red.
-->
<ItemGroup Condition="'$(IsTestProject)' == 'true'">
<Compile Include="$(MSBuildThisFileDirectory)tests\Shared\HarnessOverlayLogSweep.cs" Link="Shared\HarnessOverlayLogSweep.cs" />
</ItemGroup>
<!--
Warn at build, fail at test. build.ps1 runs the native build first, so by the
time this evaluates both exist; a hard error here would break `dotnet build` on
+11
View File
@@ -488,6 +488,15 @@ function Invoke-ProjectGates {
}
Write-Host " $($mirrorResults.Count) mirror assertion(s) executed and passed (fl_shm.h vs FrameLedger.Shared)" -ForegroundColor DarkGray
# Test hygiene (17_HOOK_ENGINE §Native logging). The injection tests use the shipped Overlay, whose log goes to the
# real data folder by design (§S21), and 2492 hook-harness logs had piled up there by 2026-09-15. Each test binary
# that starts the harness now removes the logs it caused; this is what makes a missing sweep red: a hook-harness
# overlay log created since this gate started and still there after the tests fails it. A game's log never counts.
Write-Step 'test-artifacts'
$artifactsTool = Join-Path $repo 'tools/test-artifacts-check.ps1'
Invoke-Checked 'test-artifacts (self-test)' { & $artifactsTool -SelfTest }
Invoke-Checked 'test-artifacts' { & $artifactsTool -SinceUtc $script:GateStartedUtc }
Write-Step 'placeholder guard'
# {{RELEASE_DATE}} is substituted at release time and is the only token
# allowed to survive. Anything else in a document FR-11 displays for
@@ -503,6 +512,8 @@ function Invoke-ProjectGates {
# --- Entry point ------------------------------------------------------------
$sw = [Diagnostics.Stopwatch]::StartNew()
# The test-artifacts gate counts only what this run could have written.
$script:GateStartedUtc = [DateTime]::UtcNow
switch ($Task) {
'native' { Invoke-Native $false }
'managed' { Invoke-Managed $false }
+1 -1
View File
@@ -100,7 +100,7 @@ Draw live FPS/frametime/upscaler info inside the game. Only for games already ho
- **NFR-6 Accuracy:** per `03_METRICS` §Accuracy budget, stated per tier.
- **NFR-7 Resilience:** power loss loses at most the last 60 s of raw data; DB never corrupts (WAL + transactions); Agent restart recovers `.partial` sessions as `interrupted`.
- **NFR-8 OS support:** Windows 10 22H2+ and Windows 11, x64. No ARM64 in v1.
- **NFR-9 Accessibility:** full keyboard navigation, adequate contrast in both Fluent themes, Per-Monitor V2 DPI awareness.
- **NFR-9 Accessibility:** full keyboard navigation, adequate contrast in both Fluent themes, Per-Monitor V2 DPI awareness. *(What each clause means for this app, and the check that holds it: `08_UI` §Accessibility, P4 PR-8.)*
- **NFR-10 Offline-first:** everything except updates and opt-in metadata works with zero connectivity.
- **NFR-11 Auditability:** the entire set of hooks is enumerable in `17_HOOK_ENGINE` §Hook inventory and matches the code; a reviewer must be able to verify in minutes that nothing reads game memory.
+51 -1
View File
@@ -324,6 +324,56 @@ Agent section: elevation state with a plain explanation of what elevation *optio
- Empty states for every list ("No sessions yet — launch a tracked game and FrameLedger will do the rest").
- All destructive actions confirm via `Wpf.Ui.Controls.MessageBox` (async — 16 §Dialogs): delete game/sessions, DB maintenance.
- Notifications strictly per the policy above (snackbar / InfoBar / tray).
- Keyboard: NavigationView items Ctrl+1…5; grids fully navigable; Esc closes flyouts/dialogs.
- Keyboard: ~~NavigationView items Ctrl+1…5; grids fully navigable; Esc closes flyouts/dialogs~~ — §Accessibility below, since P4 PR-8 (2026-09-15); this bullet named three behaviours and none of them was built or checked.
- No blocking dialogs during capture; errors surface as InfoBars/tray toasts.
- Charts and stat numbers use culture-aware formatting per active UI culture (09); colors only from theme resources or the per-theme chart palette (16 §ScottPlot).
## Accessibility
NFR-9 names three things — full keyboard navigation, adequate contrast in both Fluent themes, Per-Monitor V2 DPI —
and this section is what they mean for this app, each with the test that holds it (P4 PR-8, 2026-09-15). Until then
the requirement was one bullet under §UX rules, and nothing checked it.
### Keyboard
| Keys | Does | Where |
|---|---|---|
| **Ctrl+1 … Ctrl+5** (and the numeric keypad's 1–5) | Dashboard · Games · Compare · Logs · Settings | `MainWindow` `InputBindings` → `MainWindowViewModel.NavigateToCommand` → `ShellShortcuts` |
| **Alt**, **F10** | Focuses the menu bar; arrows and Enter walk File / Tools / Help | WPF `Menu`, nothing custom |
| **Tab / Shift+Tab** | Moves through a page in reading order | layout order; no `TabIndex` overrides |
| **Arrows, Home/End, Page Up/Down** | Move within a `DataGrid` (Sessions, Compare picker, Import checklist) | `DataGrid` defaults |
| **Esc** | Closes the open `ContentDialog` or `MessageBox` with no result — the same as its Close/Cancel button | `DialogKeyboard`, one class handler per dialog type registered at start-up |
**Esc is the Close button, never the primary one.** On the consent dialog (FR-2.1) that is "Keep it off": nothing is
stamped. A dialog that offers no Close button is not dismissed by Esc, and the Legal Gate (FR-11) is a window of its own
(`FirstRunWindow`) with explicit Decline and Accept, on which Esc does nothing. WPF UI 4.3.0 handles no key in
either dialog type (its `ContentDialog.cs` and `MessageBox.cs` at tag 4.3.0 have no key handler — read 2026-09-15),
which is why the handler is ours.
### Screen readers
- Every interactive control that shows no text of its own carries `AutomationProperties.Name` from `.resx` — the
toggles and choice boxes on Settings, the hooking switch on a game's page, and the icon-only close button in the
`InfoBar` template. A control *with* visible text needs nothing: its text is its name.
- `PagesLoadTests`-style scan (`AccessibilityTests.EveryTextlessControlHasAName`): every `Button`, `ToggleSwitch`,
`ToggleButton`, `CheckBox`, `ComboBox` and `HyperlinkButton` in the App's XAML either has content or a name. A new
unnamed one is red.
- Status lines that change after an action (the Database maintenance result) are `AutomationProperties.LiveSetting="Polite"`.
### Contrast
Colours come from the WPF UI theme dictionaries and nothing else, so contrast is the Fluent themes' — both of which
meet it — and cannot be broken locally: `AccessibilityTests.NoXamlHardCodesAColour` fails on any `#RRGGBB` or named
colour in the App's XAML. The chart palette is the one deliberate exception (`16_WPFUI_SYNTAX` §ScottPlot: one
palette per theme, chosen with the theme).
### DPI
`app.manifest` declares Per-Monitor V2 (`AccessibilityTests.TheManifestIsPerMonitorV2`).
### Known gaps, stated
- ScottPlot plots are not keyboard-operable (no focus, no pan/zoom by keys). The numbers behind them are on the
session summary's stat cards and in File ▸ Export (CSV/JSON).
- No screen-reader pass with Narrator has been done; the names above are necessary, not proven sufficient. That pass
is the owner's.
+64 -7
View File
@@ -2,11 +2,11 @@
## Serilog configuration
- Sinks: rolling file per process — `logs/ui-.log`, `logs/agent-.log` (`rollingInterval: Day`, `retainedFileCountLimit: 7`, `fileSizeLimitBytes: 10 MB`, `rollOnFileSizeLimit: true`). Console sink in DEBUG builds. *(`ui-.log` is written since 2026-09-13, P3 PR-2, with `Process=ui` enriched and every unhandled path — Dispatcher, AppDomain, unobserved task — logged as Fatal/Error; the crash dialog and minidump of §Crash handling are still P4's.)*
- Sinks: rolling file per process — `logs/ui-.log`, `logs/agent-.log` (`rollingInterval: Day`, `retainedFileCountLimit: 7`, `fileSizeLimitBytes: 10 MB`, `rollOnFileSizeLimit: true`). Console sink in DEBUG builds. *(`ui-.log` is written since 2026-09-13, P3 PR-2, with `Process=ui` enriched and every unhandled path — Dispatcher, AppDomain, unobserved task — logged as Fatal/Error; ~~the crash dialog and minidump of §Crash handling are still P4's~~ — built 2026-09-15, P4 PR-9, §Crash handling's note.)*
- Minimum level `Information` (`Debug` toggle in Settings → applies live via `LoggingLevelSwitch`).
- Enrichers: process name, version, `SessionGuid` and `GamePid` scoped properties during capture (`LogContext.PushProperty`).
- Template: `[{Timestamp:HH:mm:ss.fff} {Level:u3}] {SourceContext} {Message:lj} {Properties:j}{NewLine}{Exception}`.
- **Never log:** full user paths outside `%LOCALAPPDATA%\FrameLedger` (redact to `<user>`), machine name, any exe arguments of games. A `RedactingEnricher` enforces the path rule.
- **Never log:** full user paths outside `%LOCALAPPDATA%\FrameLedger` (redact to `<user>`), machine name, any exe arguments of games. ~~A `RedactingEnricher` enforces the path rule.~~ *(No such enricher was ever written: found 2026-09-15, checking `legal/PRIVACY_POLICY.md` §3's "logs are redacted (user directory paths removed) before bundling" against the bundle, which copied the logs verbatim. An enricher could not have kept the rule anyway: exception text and the Overlay's native log never pass through one, and the data directory itself sits under the user's profile, so every run logs a user name. The rule is enforced where a log leaves the machine instead: `App/Services/LogRedactor` over every log copy in the bug bundle, §Bug report flow step 2. The files in `logs\` keep their full paths; they leave the PC only if the user copies them.)*
- Capture hot path logs nothing per-frame; counters summarized at finalize.
## Crash handling (the app's own crashes)
@@ -15,6 +15,36 @@
- On fatal: Serilog `Fatal` with full exception → write minidump via `MiniDumpWriteDump` (CsWin32, `MiniDumpWithIndirectlyReferencedMemory | WithThreadInfo`) to `crashdumps/` (keep last 5) → UI shows crash dialog offering the bug-report flow → exit code 1.
- Agent crash mid-session → `.partial` recovery path (04_CAPTURE) on next start finalizes an `interrupted` session.
> **Built 2026-09-15 (P4 PR-9).** `Infrastructure/Diagnostics/CrashDumpWriter` writes
> `crashdumps\<ui|agent>-<yyyyMMdd-HHmmss, UTC>-<pid>.dmp` through CsWin32's `MiniDumpWriteDump` with exactly the two
> flags above, keeps the five newest `*.dmp` of either process after each write, and never throws: a failure is a null
> path and a Warning line, and the partial file is removed.
>
> **The App.** A `DispatcherUnhandledException` is marked handled, so the process lives long enough to ask; then
> `Services/CrashReporter` runs Fatal → dump → `Services/CrashDialog` → on Yes, the shell window revealed (a window
> hidden in the tray would hold the report's dialogs where nobody sees them) and `BugReportFlow` → the host's
> `StopApplication`, and `RunAsync` exits with code 1 after the normal teardown (with no host yet, `Shutdown(1)`
> directly). The dialog is a **Win32 `MessageBox`**, not a WPF UI one: the shell's dialog host, theme and dispatcher are
> what a crash cannot vouch for. It says where the dump is (or that none could be written), that the capture agent keeps
> running, and that the report shows every file and includes the dump only when ticked. **One report per process**: a
> further exception while the dialog is up shows nothing; the first of those is logged whole and the rest are counted,
> because a fault in a layout pass repeats on every pass the dialog's own message loop runs and would flood
> `ui-*.log`. A failed dump still asks; a failed report is an Error line, not a second crash. An
> `AppDomain.UnhandledException` (any other thread) is Fatal + dump only: the runtime is already ending the process and
> no dialog can be relied on to appear, so the next bug report offers that dump instead. An unobserved task stays an
> Error line. A startup failure `RunAsync` catches itself (the ledger will not open, the host will not start) is not an
> unhandled exception: it is still a Fatal line and exit code 1 with no dialog.
>
> **The Agent** (no window, so no dialog): the same Fatal + dump from `AppDomain.UnhandledException` and from `Main`'s
> own catch, once per process whichever sees it first, then the exception stays unhandled, so the exit is the runtime's
> and never the Agent's usage code 1. The catch exists because an exception escaping `Main` runs `Main`'s `finally`
> first, which closes the logger; the AppDomain handler alone would dump with no Fatal line.
>
> Tests: `CrashDumpWriterTests` (a real dump of the test process starts `MDMP` and carries the UTC time in its name; the
> prune keeps five and touches no other file; an unusable directory is null and one line), `CrashReporterTests` (the
> order, no report on No, three further exceptions show nothing and are counted, a failed dump still asks, a failed
> report does not throw, the dialog's text with and without a dump).
## In-app log viewer (Logs screen)
Tails the active files (shared read), level filter, text search, pause autoscroll, "Open logs folder", "Export bug bundle". Reads at most last 2 MB per file into the view.
@@ -37,15 +67,16 @@ Tails the active files (shared read), level filter, text search, pause autoscrol
> **Step 2 built 2026-09-14 (P3 PR-8a), narrower than this list; steps 1 (Help menu, crash dialog), 3, 4 and 5
> are P4's.** `App/Services/BugBundleBuilder` writes the zip where the Logs page's save dialog says
> (`FrameLedger-bugreport-YYYYMMDD-HHmm.zip`): `logs/` = every `ui-*.log` and `agent-*.log` modified in the last
> seven days, **copied verbatim, not redacted** — the files carry no paths beyond the data directory and no
> game data, and a redaction pass that nobody has specified would be a claim; `overlay/` = the five newest
> seven days, ~~**copied verbatim, not redacted** — the files carry no paths beyond the data directory and no
> game data, and a redaction pass that nobody has specified would be a claim~~ **redacted since 2026-09-15, note
> below** (the data directory is under the user's profile, so the claim was false on every machine); `overlay/` = the five newest
> `overlay-<pid>-*.log` (the ring's counters and the `FAULT`/`UNHOOK_*` lines are in those files, not
> separately); `sysinfo.json` = app version, and from the Agent's `HelloAck` when connected its version, the
> overlay build id, telemetry source, Vulkan layer state, elevation, CPU-temperature availability (the
> 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
> path-valued key). No session JSON ~~and no dumps~~ (PR-9 below). ~~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).
@@ -59,8 +90,34 @@ Tails the active files (shared read), level filter, text search, pause autoscrol
> 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.
> ~~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.~~ PR-9 below; the session-metadata checkbox is open.
>
> **The log copies are redacted since 2026-09-15.** `App/Services/LogRedactor` is what the list's "redacted copies"
> and `legal/PRIVACY_POLICY.md` §3 promised: in every `logs/` and `overlay/` entry the name in each
> `X:\Users\<name>` path becomes `<user>`, and so does the last segment of this user's profile directory when it
> lives elsewhere (`D:\Profiles\<name>`). Every spelling a log carries is covered: backslashes, the doubled
> backslashes of Serilog's JSON properties, forward slashes, any case, a name with spaces, and the `?` the Overlay's
> ANSI image path writes for a letter its code page lacks. The file is read as bytes through Latin-1, so a UTF-8
> log and an ANSI one both come out byte for byte except the names. Over-redaction is the chosen failure:
> `C:\Users\Public` reads `<user>` too. The measured need on the dev box: the profile path appeared 8 times in
> `ui-*.log`, 7 in `agent-*.log` and in 175 overlay headers; no machine name or bare user name did. A crash dump is
> memory and cannot be redacted, which its checkbox says. Tests: `LogRedactorTests` (fifteen cases, both
> directions, UTF-8 and ANSI bytes), `BugBundleBuilderTests` (the copies carry no user name, the file on disk is
> untouched).
>
> **The crash dump's checkbox and step 1's third entry point built 2026-09-15 (P4 PR-9).** When
> `BugBundleBuilder.LatestCrashDump` finds a `*.dmp` written in the last seven days under `crashdumps\` (either
> process's), the flow shows **Optional items** before the save dialog (`BugReportPreviewPrompt.AskCrashDumpAsync` →
> `Dialogs/BugBundleOptionsContent`): one checkbox, **clear**, labelled with the dump's local time and its size in MB
> (the size warning), and a line saying a dump is FrameLedger's own memory and can hold file paths, game names and
> settings. Continue with the box clear writes the bundle without it; ticked, `crashdumps/<name>.dmp` goes in;
> Cancel writes nothing. `WriteAsync` refuses a dump from anywhere but that directory, before the zip is created. It
> is a dialog before the save rather than a box on step 3's preview because the preview lists a zip that is already
> written. The crash dialog (§Crash handling) is step 1's third entry point. Still open: the session-metadata
> checkbox. Tests: `BugBundleBuilderTests` (only when passed, only from the directory, the newest of the week),
> `BugReportFlowTests` (no dump no question; left clear, ticked, cancelled), `BugBundleOptionsViewModelTests`,
> `PagesLoadTests`.
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=…`
+1
View File
@@ -241,6 +241,7 @@ document the app displays for acceptance (FR-11) is a defect, not a template.
14b. `tools/release-notes.ps1 -SelfTest` — five cases over a fixture changelog (a dated and an undated section, a missing one, a prefix that must not match, an empty one). The live half needs a tag's version and runs in `release.yml`, where a missing or empty section is a red release (P4 PR-5)
15. `tools/resx-audit.ps1` — ~~**skipped loudly; it does not exist, and no `.resx` file does either**~~ **built 2026-09-13 (P3 PR-2)**: `-SelfTest` first (11 fixture cases, both directions), then the live pass over every `Strings.resx` family under `src/` — key sets equal across en/vi/ja, `Safety_*` in `ja` marked for review or signed, `Strings.Designer.cs` current with `tools/resx-gen.ps1`. A tree with no family is red (`09_I18N` §Translation workflow)
16. **struct-mirror** — reads this run's `.trx` and fails when `ShmLayoutMirrorTests` did not execute, so deleting the mirror test is red as well as breaking it
16b. **`tools/test-artifacts-check.ps1`** — `-SelfTest` first (seven cases, two RED), then live: an `overlay-*.log` created since this gate started, still in the real `%LOCALAPPDATA%\FrameLedger\logs` after the tests, whose first line names a `hook-harness*` image, fails the gate. It is what makes a test binary without its log sweep red (`17_HOOK_ENGINE` §Native logging, 2026-09-15); a game's log never counts
17. Placeholder guard — fails if any `{{` token other than `{{RELEASE_DATE}}` survives in `README.md` or `legal/*.md`
> **This list was wrong in two ways until 2026-08-06 and both were the same kind of wrong.** Step 6
+5
View File
@@ -56,6 +56,11 @@ The anti-cheat guard is the one component where a bug can cost someone an accoun
into an `interrupted` row whose `frame_count` IS the prefix, deletes the file, and finds nothing on a
second pass. `PartialSessionFileTests` already kills at every byte offset; what this adds is that the
Agent wrote a recoverable prefix *on its own* before it died.
- **Test hygiene: the harness's overlay logs leave with the run.** The Overlay logs to the real
`%LOCALAPPDATA%\FrameLedger\logs` by design, so every test binary that starts hook-harness removes the logs it
caused when its run ends, and `tools/test-artifacts-check.ps1` fails the gate for one left behind
(`17_HOOK_ENGINE` §Native logging, 2026-09-15). A new native test binary that starts the harness needs the listener;
a managed test project that stages it gets the sweep from `FrameLedger.DrainFixtures.targets`.
- Guard integration: harness loads a **dummy DLL named like an anti-cheat module** → injection refused pre-launch; loaded late → safety unhook. (A renamed harmless DLL, not real anti-cheat software.)
## Hook overhead measurement (NFR-1, per release)
+1 -1
View File
@@ -317,7 +317,7 @@ Agent: watcher, tier selection, injection orchestration, shm drain, telemetry po
WPF UI shell (`16_WPFUI_SYNTAX`), library, per-game hooking consent flow, Dashboard live card showing *measured* settings, session summary, ScottPlot charts, game detail tabs, Compare with tier guarding, segment ribbon, tri-state chips with override, refusal/degradation/unhook notices as first-class UI. **Plus, moved here from P4 on 2026-09-13 (owner):** the command pipe (`07_IPC` §C — P2's decision D10 put it here), i18n en/vi/ja with `tools/resx-audit` (the consent dialog is the first thing that needs a reviewed `.resx`, so it cannot wait), the Legal Gate (FR-11), Settings (FR-10, the kill switch first), the Logs page, tray + toasts. The owner chose the whole of `08_UI` over a shell-first cut; HANDOFF §P3 carries the slice order and the decisions (D11–D17). *Not started as of 2026-09-13: `FrameLedger.App` is the scaffold, `FrameLedger.Shared` has no IPC type, and no `.resx` exists in the tree.*
## P4 — Detection & product polish (1 week)
~~Static rules engine + `detection-rules.json` (engines, platforms, capabilities, **anticheat blocklist**) + validator + fixtures~~ **landed 2026-09-14 (P4 PR-1: the engine existed since P0; the Agent's `DetectionSweep` is its first caller, `ApplyDetectionAsync` its first writer — HANDOFF §P4)**; ~~store auto-import~~ **landed 2026-09-14 (P4 PR-4)**; ~~capability-vs-measured UI separation~~ **(PR-1: the Supports row reads the sweep's flags)**; ~~i18n en/vi/ja; Legal Gate;~~ ~~Velopack + updater (with the hooked-session deferral)~~ **landed 2026-09-14 (P4 PR-5 — the deferral is `UpdateService`'s shape, not a flag)**; bug bundle incl. overlay logs; ~~tray + toasts; Settings;~~ ~~DB maintenance~~ **landed 2026-09-15 (P4 PR-7: the sweep is the Agent's over `SweepRetention`; integrity, backup and compaction in the App)**; accessibility pass; ~~the scheduled task (`--install-task`)~~ (P3 PR-8b) and ~~the Velopack install hooks~~ **(PR-5: the uninstall hook; install registers nothing, by design — `12_BUILD` §The Vulkan layer is not registered at install time)**. *(The struck items moved to P3 on 2026-09-13 — see §P3.)*
~~Static rules engine + `detection-rules.json` (engines, platforms, capabilities, **anticheat blocklist**) + validator + fixtures~~ **landed 2026-09-14 (P4 PR-1: the engine existed since P0; the Agent's `DetectionSweep` is its first caller, `ApplyDetectionAsync` its first writer — HANDOFF §P4)**; ~~store auto-import~~ **landed 2026-09-14 (P4 PR-4)**; ~~capability-vs-measured UI separation~~ **(PR-1: the Supports row reads the sweep's flags)**; ~~i18n en/vi/ja; Legal Gate;~~ ~~Velopack + updater (with the hooked-session deferral)~~ **landed 2026-09-14 (P4 PR-5 — the deferral is `UpdateService`'s shape, not a flag)**; ~~bug bundle incl. overlay logs~~ **landed (overlay logs since P3 PR-8a; 2026-09-15, P4 PR-9: the crash dialog, the minidump in both processes and the dump as the bundle's opt-in — `10_LOGGING` built notes)**; ~~tray + toasts; Settings;~~ ~~DB maintenance~~ **landed 2026-09-15 (P4 PR-7: the sweep is the Agent's over `SweepRetention`; integrity, backup and compaction in the App)**; ~~accessibility pass~~ **landed 2026-09-15 (P4 PR-8: `08_UI` §Accessibility written first — Ctrl+1…5, Esc on every dialog, an automation name on every textless input, theme colours only — each held by `AccessibilityTests`)**; ~~the scheduled task (`--install-task`)~~ (P3 PR-8b) and ~~the Velopack install hooks~~ **(PR-5: the uninstall hook; install registers nothing, by design — `12_BUILD` §The Vulkan layer is not registered at install time)**. *(The struck items moved to P3 on 2026-09-13 — see §P3.)*
## P5 — Ship (3–4 days)
CI/CD with the native build (`release.yml` exists since P4 PR-5, 2026-09-14 — untested by a tag yet); CodeQL (C# + C++); Dependabot; CHANGELOG; README with the P0 accuracy comparison — **which is not a percentage, and this line used to send its author looking for one**. The decision is recorded under item 3 and in `spike-notes.md` §8: the baseline can answer **none** of item 4's four runtime questions, so the defensible claim is *"the baseline cannot answer four of these five questions at all"*, not *"N% more accurate"*. Overhead + tier cross-validation measurements; release smoke on clean VMs; `v0.1.0-beta.1`.
+6
View File
@@ -205,3 +205,9 @@ On startup and on `ApplicationThemeManager.Changed`: for every live plot set fig
bar with no exit, which is exactly how the safety notices shipped (2026-09-14). `Styles/FrameLedger.xaml` carries
the upstream template plus one presenter column; `PagesLoadTests.TheInfoBarTemplateRendersItsContent` renders both
templates and turns red when upstream gains a presenter, which is when the copy comes out.
- [ ] **No dialog in 4.3.0 closes on Esc.** Neither `ContentDialog.cs` nor `MessageBox.cs` at the 4.3.0 tag handles a
key (read 2026-09-15), and `ContentDialog.CloseButtonText` DEFAULTS to "Close" — an empty string is how a dialog
says it has no Close button. `MessageBox.Close()` is `[Obsolete("Use Close with MessageBoxResult instead")]` while no
such overload is public; the Close button's own path is `TemplateButtonCommand.Execute(MessageBoxButton.Close)`.
`Services/DialogKeyboard` registers one class handler on `Window` (bubbling `KeyDown`, so a dropdown's Esc wins) and
closes through those paths; `AccessibilityTests.EscapeClosesTheOpenDialogWithNoResult` holds it (`08_UI` §Accessibility).
+14
View File
@@ -688,6 +688,20 @@ No logging in hook bodies. A small fixed-size in-memory ring of structured event
> `UNHOOK_*` / `SYMBOL_MISSING` / `SUPERVISION_LOST` lines at the end of every session
> (`Consume/OverlayLog.cs`).
> **Tests and the real logs folder (2026-09-15).** The injection tests use the shipped Overlay, so their harness
> logs land in the user's real `logs\` too: measured that day, 2506 overlay logs, **2492 of them hook-harness's**,
> left by test runs since 2026-09-06, beside the owner's 14 from real titles. **The path stays not-a-parameter**: an
> environment variable or any other switch in the injected DLL would reopen the per-launch vector §S21 closed, and a
> test build of the Overlay would stop testing the binary that ships. Instead **each test binary removes what it
> caused** when its run ends: an `overlay-*.log` created after the run started whose first line names a hook-harness
> image that binary owns. Natively a Catch2 listener in `guard_test.cpp` over `src/native/tests/overlay_log_sweep.h` (the image
> must be this build's `FL_HARNESS_EXE`); in managed code `tests/Shared/HarnessOverlayLogSweep.cs`, an xUnit assembly
> fixture that `FrameLedger.DrainFixtures.targets` compiles into every test project staging the harness (the copy
> beside the test binary, plus directories a test registers — `PipeEndToEndTests` runs a renamed copy from its
> scratch directory). Test assemblies run in parallel with their own copies, so none removes a log another is about
> to read; a game's log names the game. **`tools/test-artifacts-check.ps1` makes a missing sweep red**: a harness log
> created during the gate and still there fails it. The logs from before this change are the owner's to delete.
## Test harness
`src/native/tools/hook-harness` — a minimal D3D11 app that presents at a controlled rate. It lets CI and local dev exercise hook paths with **no game and no anti-cheat surface at all** (`14_TESTING`).
+10 -3
View File
@@ -1212,7 +1212,7 @@ election are **F** and **G**; the ⏳ feature rows in `17_HOOK_ENGINE` §Hook in
their columns (`hdr_flag`, `pt_confidence`, `pso_stutter_pct`, `vram_proc*`, `latency_*`) are an
honest NULL in P2's schema, never a 0.
## P4 — **START HERE** (2026-09-14: P3 is code-complete; the stack awaits the owner's merges)
## P4 — **START HERE** (2026-09-14: P3 is code-complete; the stack awaits the owner's merges) — **code-complete 2026-09-15 with PR-9**: every item below is struck; what follows is `15_ROADMAP` §P5 and §Owner-only
P3's slices are all struck below. What is left of P3 is not code: the owner merges #154 → #155 → #156 → #158 →
#159 → #160 → #161 → #162 → #163 → PR-9 in order (squash; after each merge the next branch is rebased
@@ -1233,7 +1233,7 @@ capability-vs-measured separation in the UI (the game page's Supports row is emp
the updater (`11_UPDATER`; the Settings channel row is stored and unused)~~ **LANDED 2026-09-14 (P4 PR-5: `App/Update/` — `VelopackUpdateClient` behind `IUpdateClient`, `UpdateService` with FR-12 as its shape, the banner, the install/uninstall hooks in `Program.Main`, `release.yml`, one `VERSION` source — `11_UPDATER` built note)**, ~~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
~~the crash dialog + minidump stay open~~ — they landed 2026-09-15 with PR-9, and the dump is the bundle's opt-in — `10_LOGGING` built notes)**, ~~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
@@ -1247,7 +1247,7 @@ script~~ **LANDED 2026-09-15 (P4 PR-6: `tools/license-gather.ps1` → `legal/lic
`15_ROADMAP` §P4's last two items were not in the list above: ~~DB maintenance~~ **LANDED 2026-09-15 (P4 PR-7:
Tools ▸ Database maintenance — the retention sweep on demand is the Agent's, over a new `SweepRetention` command with
no payload; integrity check, `VACUUM INTO` backup and compaction run in the App and change no row — `06_DATA_MODEL`
§Retention built note)**, and the accessibility pass, which needs `08_UI` §Accessibility written before any code.
§Retention built note)**, and ~~the accessibility pass, which needs `08_UI` §Accessibility written before any code~~ **LANDED 2026-09-15 (P4 PR-8: the section first, then `AccessibilityTests` — Ctrl+1…5, Esc on every dialog, an automation name on every textless input, theme colours only)**.
## P3 — ~~**START HERE**~~ (2026-09-13, owner-approved plan; **code-complete 2026-09-14** — every row below is struck with its PR)
@@ -1410,6 +1410,13 @@ deferred with a written rationale.
The mechanical ones live in the toolchain notes; these are the ones that cost a *wrong
diagnosis*.
- **THE TESTS WRITE INTO THE REAL DATA FOLDER, AND THAT IS NOT A SWITCH TO ADD.** The Overlay's log path is
`SHGetKnownFolderPath`, never the environment (§S21), and the tests inject the shipped DLL, so 2492 hook-harness
logs had piled up in the owner's `%LOCALAPPDATA%\FrameLedger\logs` by 2026-09-15. Each test binary now sweeps the
harness logs it caused (`17_HOOK_ENGINE` §Native logging) and the `test-artifacts` gate is red for one left behind.
A new native test executable that starts hook-harness needs the Catch2 listener from `guard_test.cpp`; do not "fix"
a red `test-artifacts` by pointing the Overlay somewhere else.
- **A CHROMIUM-BASED TITLE IS SEVERAL PROCESSES WITH ONE IMAGE PATH.** *Flower in Us* (NW.js /
RPG Maker) returned `TargetAmbiguous`, exit 6, on 2026-09-03: three processes match the
consented path. The presenting one is the GPU process, which owns no window — so do not "fix"
+3
View File
@@ -26,6 +26,9 @@ internal sealed record AgentPaths(string DataDirectory)
public string Logs => Path.Combine(DataDirectory, "logs");
/// <summary><c>10_LOGGING</c> §Crash handling: the minidumps of both processes' crashes (P4 PR-9), the newest five kept.</summary>
public string CrashDumps => Path.Combine(DataDirectory, "crashdumps");
public string VkLayerDirectory => Path.Combine(DataDirectory, "vklayer");
/// <summary>§S22: the payload must resolve into the guard's own directory, so it is beside this binary and nowhere else.</summary>
+49 -6
View File
@@ -17,6 +17,7 @@ using FrameLedger.Agent.Composition;
using FrameLedger.Agent.Hosting;
using FrameLedger.Application.Ipc;
using FrameLedger.Application.Rules;
using FrameLedger.Infrastructure.Diagnostics;
using FrameLedger.Infrastructure.Persistence;
using FrameLedger.Infrastructure.Rules;
using Microsoft.Extensions.DependencyInjection;
@@ -32,6 +33,8 @@ internal static class Program
private const int _exitNotImplemented = 2;
private const int _exitRulesFailed = 3;
private static int _crashReported;
private static async Task<int> Main(string[] args)
{
ArgumentNullException.ThrowIfNull(args);
@@ -50,12 +53,8 @@ internal static class Program
}
AgentPaths paths = cmd.DataDirectory is { } dir ? new AgentPaths(Path.GetFullPath(dir)) : AgentPaths.Default;
Directory.CreateDirectory(paths.Logs);
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.File(Path.Combine(paths.Logs, "agent-.log"), formatProvider: System.Globalization.CultureInfo.InvariantCulture,
rollingInterval: RollingInterval.Day, retainedFileCountLimit: 14)
.CreateLogger();
ConfigureLogging(paths);
HookCrashHandlers(paths);
try
{
@@ -83,12 +82,56 @@ internal static class Program
};
}
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// The same report as another thread's, while the logger is still open; the exception stays unhandled, so the
// exit is the runtime's, never one of this binary's own codes.
ReportCrash(ex, paths, "Main");
throw;
}
finally
{
await Log.CloseAndFlushAsync().ConfigureAwait(false);
}
}
private static void ConfigureLogging(AgentPaths paths)
{
Directory.CreateDirectory(paths.Logs);
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.File(Path.Combine(paths.Logs, "agent-.log"), formatProvider: System.Globalization.CultureInfo.InvariantCulture,
rollingInterval: RollingInterval.Day, retainedFileCountLimit: 14)
.CreateLogger();
}
/// <summary>
/// <c>10_LOGGING</c> §Crash handling, in both processes (P4 PR-9): Fatal with the whole exception, then a minidump under
/// <c>crashdumps\</c>. The Agent has no window, so there is no dialog; the App's bug report offers the dump.
/// </summary>
private static void HookCrashHandlers(AgentPaths paths)
{
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
{
ReportCrash(e.ExceptionObject as Exception, paths, "AppDomain");
Log.CloseAndFlush();
};
TaskScheduler.UnobservedTaskException += static (_, e) => Log.Error(e.Exception, "agent: unobserved task exception");
}
/// <summary><c>10_LOGGING</c> §Crash handling: Fatal, then the minidump; once per process, whichever path sees the exception first.</summary>
private static void ReportCrash(Exception? exception, AgentPaths paths, string source)
{
if (Interlocked.Exchange(ref _crashReported, 1) == 1)
{
return;
}
Log.Fatal(exception, "agent: unhandled exception ({Source}); the Agent exits", source);
string? dump = CrashDumpWriter.TryWrite(paths.CrashDumps, "agent", DateTimeOffset.UtcNow, static line => Log.Warning("{Line}", line));
Log.Information("agent: crash dump {Dump}", dump ?? "not written");
}
/// <summary>The product's mode: a Generic Host around the watcher, stopped by Ctrl+C or the service manager.</summary>
private static async Task<int> ServeAsync(LedgerDatabase db, AgentPaths paths)
{
+61 -6
View File
@@ -10,6 +10,7 @@ using FrameLedger.Application.Import;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Settings;
using FrameLedger.Application.Watch;
using FrameLedger.Infrastructure.Diagnostics;
using FrameLedger.Infrastructure.Import;
using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Infrastructure.Persistence;
@@ -35,6 +36,17 @@ namespace FrameLedger.App;
/// </remarks>
public partial class App : System.Windows.Application
{
/// <summary><c>10_LOGGING</c> §Crash handling (P4 PR-9): Fatal, the minidump, the crash dialog offering the bug report.</summary>
private readonly CrashReporter _crashes = new(
static () => CrashDumpWriter.TryWrite(UiPaths.CrashDumps, "ui", DateTimeOffset.UtcNow, static line => Log.Warning("{Line}", line)),
CrashDialog.AskToReport,
static () =>
{
// The report's dialogs live in the shell window; one hidden in the tray would wait for a click nobody can give.
Services.GetRequiredService<IShellPresence>().Reveal();
return Services.GetRequiredService<BugReportFlow>().RunAsync();
});
private IHost? _host;
private LedgerDatabase? _db;
private Task? _run;
@@ -55,6 +67,8 @@ public partial class App : System.Windows.Application
UiPaths.EnsureDirectories();
ConfigureLogging();
HookCrashHandlers();
// 08_UI §Accessibility (P4 PR-8): Esc closes the open ContentDialog or MessageBox, before any window exists.
DialogKeyboard.Register();
_run = DiagReport.Requested(e.Args) ? DiagAsync() : RunAsync();
}
@@ -93,7 +107,8 @@ public partial class App : System.Windows.Application
finally
{
await TearDownAsync().ConfigureAwait(true);
Shutdown(exitCode);
// 10_LOGGING §Crash handling: a reported crash still ends in exit code 1, after the normal teardown.
Shutdown(_crashes.Crashed ? 1 : exitCode);
}
}
@@ -265,7 +280,7 @@ public partial class App : System.Windows.Application
services.AddSingleton<IRunAtLogon, RunAtLogonRegistry>();
services.AddSingleton<SafetyNotices>();
services.AddSingleton(static _ => new LogTail(UiPaths.Logs));
services.AddSingleton(static sp => new BugBundleBuilder(UiPaths.Logs, sp.GetRequiredService<RegisteredSettings>()));
services.AddSingleton(static sp => new BugBundleBuilder(UiPaths.Logs, sp.GetRequiredService<RegisteredSettings>(), crashDumpDirectory: UiPaths.CrashDumps, redactor: LogRedactor.ForCurrentUser()));
// 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.
@@ -341,14 +356,54 @@ public partial class App : System.Windows.Application
outputTemplate: "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {SourceContext} {Message:lj} {Properties:j}{NewLine}{Exception}")
.CreateLogger();
/// <summary><c>10_LOGGING</c> §Crash handling: every unhandled path is logged as Fatal. The dialog and the minidump are P4's.</summary>
/// <summary>
/// <c>10_LOGGING</c> §Crash handling (P4 PR-9). An exception on the dispatcher is reported: Fatal, the minidump, the
/// crash dialog offering the bug report; the App then closes with exit code 1 through the host's own teardown. One on
/// any other thread is logged and dumped only, because the runtime is already ending the process and no dialog can be
/// relied on to appear; the bug report offers that dump the next time it runs. An unobserved task is not fatal and
/// stays an Error line.
/// </summary>
private void HookCrashHandlers()
{
DispatcherUnhandledException += OnDispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += static (_, args) => Log.Fatal(args.ExceptionObject as Exception, "ui: unhandled exception (AppDomain)");
AppDomain.CurrentDomain.UnhandledException += static (_, args) =>
{
Log.Fatal(args.ExceptionObject as Exception, "ui: unhandled exception (AppDomain, terminating {Terminating})", args.IsTerminating);
string? dump = CrashDumpWriter.TryWrite(UiPaths.CrashDumps, "ui", DateTimeOffset.UtcNow, static line => Log.Warning("{Line}", line));
Log.Information("ui: crash dump {Dump}", dump ?? "not written");
Log.CloseAndFlush();
};
TaskScheduler.UnobservedTaskException += static (_, args) => Log.Error(args.Exception, "ui: unobserved task exception");
}
private static void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) =>
Log.Fatal(e.Exception, "ui: unhandled exception (Dispatcher)");
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
// Handled, so the process lives long enough to ask; the exit code is still 1.
e.Handled = true;
_ = ReportCrashAsync(e.Exception);
}
/// <summary>The report, then the host's stop (<see cref="RunAsync"/> tears down and exits with 1); with no host, straight to the exit.</summary>
private async Task ReportCrashAsync(Exception exception)
{
try
{
if (!await _crashes.HandleAsync(exception, "Dispatcher").ConfigureAwait(true))
{
return;
}
if (_host is not null)
{
_host.Services.GetRequiredService<IHostApplicationLifetime>().StopApplication();
return;
}
}
catch (Exception ex) when (ex is ObjectDisposedException or InvalidOperationException)
{
Log.Warning(ex, "ui: the host could not be stopped after the crash report");
}
Shutdown(1);
}
}
@@ -44,6 +44,7 @@
Icon="{ui:SymbolIcon Open24}" />
</StackPanel>
<TextBox Grid.Row="1"
AutomationProperties.Name="{Binding ViewModel.SelectedDocument.Title}"
AcceptsReturn="True"
IsReadOnly="True"
IsReadOnlyCaretVisible="True"
@@ -0,0 +1,21 @@
<UserControl x:Class="FrameLedger.App.Dialogs.BugBundleOptionsContent"
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:BugBundleOptionsViewModel}"
mc:Ignorable="d"
MinWidth="480">
<!--
10_LOGGING §Bug report flow step 2's optional item (P4 PR-9): the crash dump goes in only when it is ticked
(legal/PRIVACY_POLICY.md §3). The box starts clear, and its label and the line under it say how large the dump is
and what it can hold before anyone ticks it.
-->
<StackPanel>
<ui:TextBlock TextWrapping="Wrap" Text="{x:Static vm:BugBundleOptionsViewModel.Intro}" />
<CheckBox Margin="0,12,0,0" IsChecked="{Binding IncludeCrashDump}" Content="{Binding DumpLabel}" />
<ui:TextBlock Margin="28,4,0,0" Appearance="Secondary" TextWrapping="Wrap" Text="{x:Static vm:BugBundleOptionsViewModel.DumpDetail}" />
</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 optional-items <c>ContentDialog</c> (P4 PR-9): the crash dump's checkbox.</summary>
public partial class BugBundleOptionsContent : UserControl
{
public BugBundleOptionsContent(BugBundleOptionsViewModel viewModel)
{
ViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel));
DataContext = viewModel;
InitializeComponent();
}
public BugBundleOptionsViewModel ViewModel { get; }
}
@@ -31,6 +31,7 @@
<ui:TextBlock Margin="0,18,0,6" Appearance="Secondary" Text="{Binding TypeToConfirm}" TextWrapping="Wrap" />
<ui:TextBox x:Name="Acknowledgement"
AutomationProperties.Name="{Binding TypeToConfirm}"
Text="{Binding Typed, UpdateSourceTrigger=PropertyChanged}"
PlaceholderText="{x:Static vm:ConsentDialogViewModel.Phrase}" />
</StackPanel>
@@ -60,7 +60,7 @@
<DockPanel Margin="0,12,0,0">
<ui:ProgressRing Width="16" Height="16" Margin="0,0,8,0" DockPanel.Dock="Left" IsIndeterminate="True"
Visibility="{Binding IsBusy, Converter={StaticResource BoolToVis}}" />
<ui:TextBlock MaxWidth="680" HorizontalAlignment="Left" Text="{Binding Status}" TextWrapping="Wrap" />
<ui:TextBlock MaxWidth="680" HorizontalAlignment="Left" AutomationProperties.LiveSetting="Polite" Text="{Binding Status}" TextWrapping="Wrap" />
</DockPanel>
</StackPanel>
</UserControl>
@@ -15,23 +15,23 @@
Visibility="{Binding NameDetected, Converter={StaticResource BoolToVis}}" />
<ui:TextBlock Appearance="Secondary" Text="{x:Static vm:EditGameViewModel.NameLabel}" />
</DockPanel>
<ui:TextBox Margin="0,4,0,12" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
<ui:TextBox Margin="0,4,0,12" AutomationProperties.Name="{x:Static vm:EditGameViewModel.NameLabel}" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
<DockPanel>
<ui:Badge DockPanel.Dock="Right" Margin="8,0,0,0" Appearance="Info" Content="{x:Static vm:EditGameViewModel.DetectedBadge}"
Visibility="{Binding PublisherDetected, Converter={StaticResource BoolToVis}}" />
<ui:TextBlock Appearance="Secondary" Text="{x:Static vm:EditGameViewModel.PublisherLabel}" />
</DockPanel>
<ui:TextBox Margin="0,4,0,12" Text="{Binding Publisher, UpdateSourceTrigger=PropertyChanged}" />
<ui:TextBox Margin="0,4,0,12" AutomationProperties.Name="{x:Static vm:EditGameViewModel.PublisherLabel}" Text="{Binding Publisher, UpdateSourceTrigger=PropertyChanged}" />
<DockPanel>
<ui:Badge DockPanel.Dock="Right" Margin="8,0,0,0" Appearance="Info" Content="{x:Static vm:EditGameViewModel.DetectedBadge}"
Visibility="{Binding VersionDetected, Converter={StaticResource BoolToVis}}" />
<ui:TextBlock Appearance="Secondary" Text="{x:Static vm:EditGameViewModel.VersionLabel}" />
</DockPanel>
<ui:TextBox Margin="0,4,0,12" Text="{Binding Version, UpdateSourceTrigger=PropertyChanged}" />
<ui:TextBox Margin="0,4,0,12" AutomationProperties.Name="{x:Static vm:EditGameViewModel.VersionLabel}" Text="{Binding Version, UpdateSourceTrigger=PropertyChanged}" />
<ui:TextBlock Appearance="Secondary" Text="{x:Static vm:EditGameViewModel.NotesLabel}" />
<ui:TextBox Margin="0,4,0,0" MinHeight="72" AcceptsReturn="True" TextWrapping="Wrap" Text="{Binding Notes, UpdateSourceTrigger=PropertyChanged}" />
<ui:TextBox Margin="0,4,0,0" MinHeight="72" AutomationProperties.Name="{x:Static vm:EditGameViewModel.NotesLabel}" AcceptsReturn="True" TextWrapping="Wrap" Text="{Binding Notes, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</UserControl>
+14
View File
@@ -13,6 +13,20 @@
WindowBackdropType="Mica"
WindowCornerPreference="Round"
WindowStartupLocation="CenterScreen">
<!-- 08_UI §Accessibility (P4 PR-8): Ctrl+1…5 open the NavigationView's pages in its order; ShellShortcuts holds the map. -->
<ui:FluentWindow.InputBindings>
<KeyBinding Command="{Binding ViewModel.NavigateToCommand}" CommandParameter="1" Key="D1" Modifiers="Control" />
<KeyBinding Command="{Binding ViewModel.NavigateToCommand}" CommandParameter="2" Key="D2" Modifiers="Control" />
<KeyBinding Command="{Binding ViewModel.NavigateToCommand}" CommandParameter="3" Key="D3" Modifiers="Control" />
<KeyBinding Command="{Binding ViewModel.NavigateToCommand}" CommandParameter="4" Key="D4" Modifiers="Control" />
<KeyBinding Command="{Binding ViewModel.NavigateToCommand}" CommandParameter="5" Key="D5" Modifiers="Control" />
<KeyBinding Command="{Binding ViewModel.NavigateToCommand}" CommandParameter="1" Key="NumPad1" Modifiers="Control" />
<KeyBinding Command="{Binding ViewModel.NavigateToCommand}" CommandParameter="2" Key="NumPad2" Modifiers="Control" />
<KeyBinding Command="{Binding ViewModel.NavigateToCommand}" CommandParameter="3" Key="NumPad3" Modifiers="Control" />
<KeyBinding Command="{Binding ViewModel.NavigateToCommand}" CommandParameter="4" Key="NumPad4" Modifiers="Control" />
<KeyBinding Command="{Binding ViewModel.NavigateToCommand}" CommandParameter="5" Key="NumPad5" Modifiers="Control" />
</ui:FluentWindow.InputBindings>
<!--
docs/16_WPFUI_SYNTAX.md §Main window skeleton: TitleBar row, a classic Menu row BELOW it (never inside the
drag region), then the NavigationView. Every string is a resx key; every colour a theme brush.
@@ -108,7 +108,8 @@
<ui:CardControl Margin="0,12,0,0" Header="{x:Static vm:GameDetailViewModel.HookingHeader}" Icon="{ui:SymbolIcon ShieldTask24}">
<StackPanel Orientation="Horizontal">
<ui:TextBlock Appearance="Secondary" VerticalAlignment="Center" Margin="0,0,12,0" Text="{Binding ViewModel.HookStatusText}" />
<ui:ToggleSwitch IsChecked="{Binding ViewModel.HookEnabled, Mode=OneWay}"
<ui:ToggleSwitch AutomationProperties.Name="{x:Static vm:GameDetailViewModel.HookingHeader}"
IsChecked="{Binding ViewModel.HookEnabled, Mode=OneWay}"
IsEnabled="{Binding ViewModel.HookToggleEnabled}"
Command="{Binding ViewModel.ToggleHookingCommand}" />
</StackPanel>
@@ -232,7 +233,7 @@
<StackPanel Margin="0,12,0,0">
<StackPanel Orientation="Horizontal">
<ui:TextBlock Appearance="Secondary" VerticalAlignment="Center" Margin="0,0,8,0" Text="{x:Static vm:GameDetailViewModel.TrendMetricLabel}" />
<ComboBox MinWidth="180" DisplayMemberPath="Label" ItemsSource="{x:Static vm:GameDetailViewModel.TrendMetrics}"
<ComboBox MinWidth="180" AutomationProperties.Name="{x:Static vm:GameDetailViewModel.TrendMetricLabel}" DisplayMemberPath="Label" ItemsSource="{x:Static vm:GameDetailViewModel.TrendMetrics}"
SelectedValue="{Binding ViewModel.TrendMetric, Mode=TwoWay}" SelectedValuePath="Value" />
<CheckBox Margin="16,0,0,0" VerticalAlignment="Center" Content="{x:Static vm:GameDetailViewModel.IncludeMidSessionText}"
IsChecked="{Binding ViewModel.IncludeMidSession}" />
+2
View File
@@ -19,10 +19,12 @@
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Column="0" FontTypography="Title" Text="{x:Static vm:GamesViewModel.Header}" />
<ui:TextBox Grid.Column="1" MinWidth="220" Margin="0,0,12,0" VerticalAlignment="Center"
AutomationProperties.Name="{x:Static vm:GamesViewModel.SearchPlaceholder}"
Icon="{ui:SymbolIcon Search24}"
PlaceholderText="{x:Static vm:GamesViewModel.SearchPlaceholder}"
Text="{Binding ViewModel.Search, UpdateSourceTrigger=PropertyChanged}" />
<ComboBox Grid.Column="2" MinWidth="150" Margin="0,0,12,0" VerticalAlignment="Center"
AutomationProperties.Name="{x:Static res:Strings.A11y_Games_Sort}"
DisplayMemberPath="Label"
ItemsSource="{x:Static vm:GamesViewModel.Sorts}"
SelectedValue="{Binding ViewModel.Sort, Mode=TwoWay}"
+4
View File
@@ -19,18 +19,21 @@
<WrapPanel Grid.Row="1" Margin="0,12,0,8" Orientation="Horizontal">
<ComboBox MinWidth="120"
Margin="0,0,8,4"
AutomationProperties.Name="{x:Static res:Strings.A11y_Logs_Source}"
DisplayMemberPath="Label"
ItemsSource="{x:Static vm:LogsViewModel.Sources}"
SelectedValue="{Binding ViewModel.Source, Mode=TwoWay}"
SelectedValuePath="Value" />
<ComboBox MinWidth="170"
Margin="0,0,8,4"
AutomationProperties.Name="{x:Static res:Strings.A11y_Logs_Level}"
DisplayMemberPath="Label"
ItemsSource="{x:Static vm:LogsViewModel.Levels}"
SelectedValue="{Binding ViewModel.Level, Mode=TwoWay}"
SelectedValuePath="Value" />
<ui:TextBox MinWidth="220"
Margin="0,0,8,4"
AutomationProperties.Name="{x:Static res:Strings.Logs_Search_Placeholder}"
Icon="{ui:SymbolIcon Search24}"
PlaceholderText="{x:Static res:Strings.Logs_Search_Placeholder}"
Text="{Binding ViewModel.Search, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
@@ -51,6 +54,7 @@
<TextBox x:Name="Tail"
Grid.Row="2"
AutomationProperties.Name="{x:Static res:Strings.A11y_Logs_Tail}"
AcceptsReturn="True"
FontFamily="Consolas"
FontSize="12"
+13 -7
View File
@@ -22,7 +22,7 @@
<ui:TextBlock FontTypography="BodyStrong" Text="{x:Static res:Strings.Settings_KillSwitch_Label}" />
<ui:TextBlock Appearance="Secondary" Text="{Binding ViewModel.KillSwitchState}" />
</StackPanel>
<ui:ToggleSwitch Grid.Column="1" Margin="12,0" IsChecked="{Binding ViewModel.KillSwitch, Mode=TwoWay}" />
<ui:ToggleSwitch Grid.Column="1" Margin="12,0" AutomationProperties.Name="{x:Static res:Strings.Settings_KillSwitch_Label}" IsChecked="{Binding ViewModel.KillSwitch, Mode=TwoWay}" />
</Grid>
</ui:CardExpander.Header>
<ui:TextBlock Appearance="Secondary" Text="{x:Static res:Strings.Settings_KillSwitch_Body}" TextWrapping="Wrap" />
@@ -94,6 +94,7 @@
</StackPanel>
</ui:CardControl.Header>
<ui:NumberBox MinWidth="140"
AutomationProperties.Name="{x:Static res:Strings.Settings_MinSession_Label}"
Maximum="{x:Static vm:SettingsViewModel.MinSessionMaximum}"
Minimum="{x:Static vm:SettingsViewModel.MinSessionMinimum}"
SpinButtonPlacementMode="Inline"
@@ -107,6 +108,7 @@
</StackPanel>
</ui:CardControl.Header>
<ui:NumberBox MinWidth="140"
AutomationProperties.Name="{x:Static res:Strings.Settings_Interval_Label}"
Maximum="{x:Static vm:SettingsViewModel.IntervalMaximum}"
Minimum="{x:Static vm:SettingsViewModel.IntervalMinimum}"
SpinButtonPlacementMode="Inline"
@@ -120,6 +122,7 @@
</StackPanel>
</ui:CardControl.Header>
<ui:NumberBox MinWidth="140"
AutomationProperties.Name="{x:Static res:Strings.Settings_Retention_Label}"
Maximum="{x:Static vm:SettingsViewModel.RetentionMaximum}"
Minimum="0"
SpinButtonPlacementMode="Inline"
@@ -132,7 +135,7 @@
<ui:TextBlock MaxWidth="560" HorizontalAlignment="Left" Appearance="Secondary" Text="{x:Static res:Strings.Settings_Background_Body}" TextWrapping="Wrap" />
</StackPanel>
</ui:CardControl.Header>
<ui:ToggleSwitch IsChecked="{Binding ViewModel.BackgroundCapture, Mode=TwoWay}" />
<ui:ToggleSwitch AutomationProperties.Name="{x:Static res:Strings.Settings_Background_Label}" IsChecked="{Binding ViewModel.BackgroundCapture, Mode=TwoWay}" />
</ui:CardControl>
<!-- Agent: elevation is optional and no tier needs it; the logon task arrives with the tray build. -->
@@ -175,6 +178,7 @@
<ui:TextBlock FontTypography="Subtitle" Margin="0,20,0,8" Text="{x:Static vm:SettingsViewModel.AppearanceHeader}" />
<ui:CardControl Margin="0,4,0,0" Header="{x:Static vm:SettingsViewModel.ThemeLabel}" Icon="{ui:SymbolIcon Color24}">
<ComboBox MinWidth="180"
AutomationProperties.Name="{x:Static vm:SettingsViewModel.ThemeLabel}"
DisplayMemberPath="Label"
ItemsSource="{x:Static vm:SettingsViewModel.Themes}"
SelectedValue="{Binding ViewModel.SelectedTheme, Mode=TwoWay}"
@@ -182,6 +186,7 @@
</ui:CardControl>
<ui:CardControl Margin="0,8,0,0" Header="{x:Static vm:SettingsViewModel.LanguageLabel}" Icon="{ui:SymbolIcon LocalLanguage24}">
<ComboBox MinWidth="180"
AutomationProperties.Name="{x:Static vm:SettingsViewModel.LanguageLabel}"
DisplayMemberPath="Label"
ItemsSource="{x:Static vm:SettingsViewModel.Languages}"
SelectedValue="{Binding ViewModel.SelectedLanguage, Mode=TwoWay}"
@@ -197,7 +202,7 @@
<ui:TextBlock Appearance="Secondary" Text="{x:Static res:Strings.Settings_StartWithWindows_Body}" />
</StackPanel>
</ui:CardControl.Header>
<ui:ToggleSwitch IsChecked="{Binding ViewModel.StartWithWindows, Mode=TwoWay}" />
<ui:ToggleSwitch AutomationProperties.Name="{x:Static res:Strings.Settings_StartWithWindows_Label}" IsChecked="{Binding ViewModel.StartWithWindows, Mode=TwoWay}" />
</ui:CardControl>
<ui:CardControl Margin="0,8,0,0" Icon="{ui:SymbolIcon ArrowMinimize24}">
<ui:CardControl.Header>
@@ -206,7 +211,7 @@
<ui:TextBlock Appearance="Secondary" Text="{x:Static res:Strings.Settings_MinimizeToTray_Body}" />
</StackPanel>
</ui:CardControl.Header>
<ui:ToggleSwitch IsChecked="{Binding ViewModel.MinimizeToTray, Mode=TwoWay}" />
<ui:ToggleSwitch AutomationProperties.Name="{x:Static res:Strings.Settings_MinimizeToTray_Label}" IsChecked="{Binding ViewModel.MinimizeToTray, Mode=TwoWay}" />
</ui:CardControl>
<!-- Privacy, updates, logging, legal. -->
@@ -218,7 +223,7 @@
<ui:TextBlock MaxWidth="560" HorizontalAlignment="Left" Appearance="Secondary" Text="{x:Static res:Strings.Settings_OnlineMetadata_Body}" TextWrapping="Wrap" />
</StackPanel>
</ui:CardControl.Header>
<ui:ToggleSwitch IsChecked="{Binding ViewModel.OnlineMetadata, Mode=TwoWay}" />
<ui:ToggleSwitch AutomationProperties.Name="{x:Static res:Strings.Settings_OnlineMetadata_Label}" IsChecked="{Binding ViewModel.OnlineMetadata, Mode=TwoWay}" />
</ui:CardControl>
<ui:TextBlock FontTypography="Subtitle" Margin="0,20,0,8" Text="{x:Static res:Strings.Settings_Updates_Header}" />
@@ -230,6 +235,7 @@
</StackPanel>
</ui:CardControl.Header>
<ComboBox MinWidth="140"
AutomationProperties.Name="{x:Static res:Strings.Settings_UpdateChannel_Label}"
DisplayMemberPath="Label"
ItemsSource="{x:Static vm:SettingsViewModel.UpdateChannels}"
SelectedValue="{Binding ViewModel.UpdateChannel, Mode=TwoWay}"
@@ -243,7 +249,7 @@
<ui:TextBlock MaxWidth="560" HorizontalAlignment="Left" Appearance="Secondary" Text="{x:Static res:Strings.Settings_AutoCheck_Body}" TextWrapping="Wrap" />
</StackPanel>
</ui:CardControl.Header>
<ui:ToggleSwitch IsChecked="{Binding ViewModel.AutoCheckUpdates, Mode=TwoWay}" />
<ui:ToggleSwitch AutomationProperties.Name="{x:Static res:Strings.Settings_AutoCheck_Label}" IsChecked="{Binding ViewModel.AutoCheckUpdates, Mode=TwoWay}" />
</ui:CardControl>
<ui:TextBlock FontTypography="Subtitle" Margin="0,20,0,8" Text="{x:Static res:Strings.Settings_Logging_Header}" />
@@ -254,7 +260,7 @@
<ui:TextBlock Appearance="Secondary" Text="{x:Static res:Strings.Settings_LogDebug_Body}" />
</StackPanel>
</ui:CardControl.Header>
<ui:ToggleSwitch IsChecked="{Binding ViewModel.LogDebug, Mode=TwoWay}" />
<ui:ToggleSwitch AutomationProperties.Name="{x:Static res:Strings.Settings_LogDebug_Label}" IsChecked="{Binding ViewModel.LogDebug, Mode=TwoWay}" />
</ui:CardControl>
<ui:TextBlock FontTypography="Subtitle" Margin="0,20,0,8" Text="{x:Static res:Strings.Settings_Legal_Header}" />
@@ -4,16 +4,18 @@ using System.IO.Compression;
using System.Text;
using System.Text.Json;
using FrameLedger.Application.Settings;
using FrameLedger.Infrastructure.Diagnostics;
using FrameLedger.Shared.Ipc;
namespace FrameLedger.App.Services;
/// <summary>
/// <c>10_LOGGING</c> §Bug report flow, step 2 — the bundle: <c>logs/</c> (this app's and the Agent's files of the
/// last seven days), the last <c>overlay-*.log</c> files, <c>sysinfo.json</c> (app, agent, overlay build id, OS,
/// locale, telemetry source, Vulkan layer state, elevation), and <c>settings.json</c> (the registry's keys and values —
/// no paths). We ship our logs only, never a game's; nothing is sent anywhere (step 3's preview dialog and step
/// 4's GitHub link arrive with P4's bug-report flow).
/// last seven days) and the last <c>overlay-*.log</c> files, both as copies with every user name in a path replaced
/// (<see cref="LogRedactor"/>), <c>sysinfo.json</c> (app, agent, overlay build id, OS,
/// locale, telemetry source, Vulkan layer state, elevation), <c>settings.json</c> (the registry's keys and values —
/// no paths), and <c>crashdumps/</c> with one minidump only when the user ticked it (P4 PR-9). We ship our files only,
/// never a game's; nothing is sent anywhere (<see cref="BugReportFlow"/> is steps 3 and 4).
/// </summary>
public sealed class BugBundleBuilder
{
@@ -22,18 +24,55 @@ public sealed class BugBundleBuilder
private readonly string _logs;
private readonly RegisteredSettings _settings;
private readonly TimeProvider _clock;
private readonly string? _crashDumps;
private readonly LogRedactor _redactor;
public BugBundleBuilder(string logsDirectory, RegisteredSettings settings, TimeProvider? clock = null)
/// <summary>A builder over the logs directory, the settings registry and, when given, the crash dump directory.</summary>
/// <param name="logsDirectory">The logs directory: ours and the Overlay's.</param>
/// <param name="settings">The registry the bundle's <c>settings.json</c> reads.</param>
/// <param name="clock">The seven-day cut's clock.</param>
/// <param name="crashDumpDirectory">The minidumps' directory (P4 PR-9); null offers none.</param>
/// <param name="redactor">What the log copies pass through; the current user's by default.</param>
public BugBundleBuilder(string logsDirectory, RegisteredSettings settings, TimeProvider? clock = null, string? crashDumpDirectory = null, LogRedactor? redactor = null)
{
_logs = logsDirectory ?? throw new ArgumentNullException(nameof(logsDirectory));
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
_clock = clock ?? TimeProvider.System;
_crashDumps = crashDumpDirectory;
_redactor = redactor ?? LogRedactor.ForCurrentUser();
}
/// <summary>Writes the zip at <paramref name="path"/>; returns the entry names written.</summary>
public async Task<IReadOnlyList<string>> WriteAsync(string path, HelloAck? agent, CancellationToken ct = default)
/// <summary>
/// The newest minidump written in the last seven days, or null: what the bug report offers to include (P4 PR-9). Either
/// process's dump qualifies; both write to the same directory.
/// </summary>
public CrashDumpInfo? LatestCrashDump()
{
if (_crashDumps is null || !Directory.Exists(_crashDumps))
{
return null;
}
DateTime cutoff = _clock.GetUtcNow().UtcDateTime.AddDays(-7);
FileInfo? newest = new DirectoryInfo(_crashDumps).EnumerateFiles(CrashDumpWriter.Pattern)
.Where(f => f.LastWriteTimeUtc >= cutoff)
.OrderByDescending(static f => f.LastWriteTimeUtc)
.FirstOrDefault();
return newest is null ? null : new CrashDumpInfo(newest.FullName, new DateTimeOffset(newest.LastWriteTimeUtc, TimeSpan.Zero), newest.Length);
}
/// <summary>
/// Writes the zip at <paramref name="path"/>; returns the entry names written. <paramref name="crashDump"/> goes in only
/// when the caller passes one, which is the user's tick (P4 PR-9), and only from the crash dump directory.
/// </summary>
public async Task<IReadOnlyList<string>> WriteAsync(string path, HelloAck? agent, CrashDumpInfo? crashDump = null, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
if (crashDump is not null && !IsOurDump(crashDump.Path))
{
throw new ArgumentException("a crash dump is taken from the crash dump directory only", nameof(crashDump));
}
var written = new List<string>();
DateTime cutoff = _clock.GetUtcNow().UtcDateTime.AddDays(-7);
using FileStream file = File.Create(path);
@@ -42,15 +81,21 @@ public sealed class BugBundleBuilder
{
foreach (string log in Directory.EnumerateFiles(_logs, "*.log").Where(f => IsOurs(f) && File.GetLastWriteTimeUtc(f) >= cutoff))
{
AddFile(zip, log, "logs/" + Path.GetFileName(log), written);
AddRedactedFile(zip, log, "logs/" + Path.GetFileName(log), written);
}
foreach (string overlay in Directory.EnumerateFiles(_logs, "overlay-*.log").OrderByDescending(File.GetLastWriteTimeUtc).Take(OverlayLogsKept))
{
AddFile(zip, overlay, "overlay/" + Path.GetFileName(overlay), written);
AddRedactedFile(zip, overlay, "overlay/" + Path.GetFileName(overlay), written);
}
}
// Step 2's optional item: the one dump the user ticked, nothing else from that directory.
if (crashDump is not null)
{
AddFile(zip, crashDump.Path, "crashdumps/" + Path.GetFileName(crashDump.Path), written);
}
AddText(zip, "sysinfo.json", SysInfo(agent), written);
AddText(zip, "settings.json", await SettingsJsonAsync(ct).ConfigureAwait(false), written);
return written;
@@ -58,6 +103,12 @@ public sealed class BugBundleBuilder
public static string SuggestedName(DateTimeOffset now) => "FrameLedger-bugreport-" + now.ToLocalTime().ToString("yyyyMMdd-HHmm", CultureInfo.InvariantCulture) + ".zip";
/// <summary>A <c>.dmp</c> directly under the crash dump directory: no other file reaches the zip under that entry.</summary>
private bool IsOurDump(string dumpPath) =>
_crashDumps is not null
&& string.Equals(Path.GetExtension(dumpPath), ".dmp", StringComparison.OrdinalIgnoreCase)
&& string.Equals(Path.GetDirectoryName(Path.GetFullPath(dumpPath)), Path.TrimEndingDirectorySeparator(Path.GetFullPath(_crashDumps)), StringComparison.OrdinalIgnoreCase);
private static bool IsOurs(string path)
{
string name = Path.GetFileName(path);
@@ -74,6 +125,25 @@ public sealed class BugBundleBuilder
written.Add(entryName);
}
// legal/PRIVACY_POLICY.md §3: a log leaves this machine only as a copy with the user names in its paths replaced. A log is
// at most 10 MB (Serilog's roll size), so it is read whole; a crash dump is memory and goes in as it is, behind its box.
private void AddRedactedFile(ZipArchive zip, string source, string entryName, List<string> written)
{
byte[] bytes;
using (var stream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
using (var buffer = new MemoryStream())
{
stream.CopyTo(buffer);
bytes = buffer.ToArray();
}
byte[] redacted = _redactor.Redact(bytes);
ZipArchiveEntry entry = zip.CreateEntry(entryName, CompressionLevel.Optimal);
using Stream target = entry.Open();
target.Write(redacted, 0, redacted.Length);
written.Add(entryName);
}
private static void AddText(ZipArchive zip, string entryName, string text, List<string> written)
{
ZipArchiveEntry entry = zip.CreateEntry(entryName, CompressionLevel.Optimal);
+28 -5
View File
@@ -6,10 +6,11 @@ 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.
/// <c>10_LOGGING</c> §Bug report flow, steps 2–4 in one place (P4 PR-3), reached from Help ▸ Report a bug, the Logs
/// page's button and the crash dialog (P4 PR-9): a recent crash dump offered as a checkbox that starts clear, 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
@@ -39,6 +40,12 @@ public sealed class BugReportFlow
public async Task<BugReportOutcome> RunAsync(CancellationToken ct = default)
{
DateTimeOffset now = _clock.GetUtcNow();
(bool cancelled, CrashDumpInfo? dump) = await ChooseCrashDumpAsync(ct).ConfigureAwait(true);
if (cancelled)
{
return new BugReportOutcome(null, BugReportChoice.Close, Written: false);
}
string? path = _saver.PickSavePath("Zip archive (*.zip)|*.zip", BugBundleBuilder.SuggestedName(now));
if (path is null)
{
@@ -49,7 +56,7 @@ public sealed class BugReportFlow
IReadOnlyList<string> entries;
try
{
entries = await _bundles.WriteAsync(path, hello, ct).ConfigureAwait(true);
entries = await _bundles.WriteAsync(path, hello, dump, ct).ConfigureAwait(true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
@@ -82,4 +89,20 @@ public sealed class BugReportFlow
return new BugReportOutcome(path, choice, Written: true);
}
/// <summary>
/// Step 2's optional item (P4 PR-9): a crash dump of the last seven days is offered before the save dialog, in a
/// checkbox that starts clear. No dump, no question; the dump comes back only when it was ticked.
/// </summary>
private async Task<(bool Cancelled, CrashDumpInfo? Dump)> ChooseCrashDumpAsync(CancellationToken ct)
{
CrashDumpInfo? dump = _bundles.LatestCrashDump();
if (dump is null)
{
return (false, null);
}
CrashDumpChoice answer = await _preview.AskCrashDumpAsync(dump, ct).ConfigureAwait(true);
return (answer == CrashDumpChoice.Cancel, answer == CrashDumpChoice.Include ? dump : null);
}
}
@@ -5,7 +5,10 @@ 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>
/// <summary>
/// The bug report's dialogs in WPF UI: step 3's <c>ContentDialog</c> listing the zip's entries, whose primary button is
/// step 4 and whose secondary is the clipboard fallback; and step 2's optional crash dump, a checkbox (P4 PR-9).
/// </summary>
public sealed class BugReportPreviewPrompt : IBugReportPreview
{
private readonly IContentDialogService _dialogs;
@@ -34,4 +37,22 @@ public sealed class BugReportPreviewPrompt : IBugReportPreview
_ => BugReportChoice.Close,
};
}
public async Task<CrashDumpChoice> AskCrashDumpAsync(CrashDumpInfo dump, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(dump);
var viewModel = new BugBundleOptionsViewModel(dump);
var dialog = new ContentDialog
{
Title = BugBundleOptionsViewModel.Title,
Content = new BugBundleOptionsContent(viewModel),
PrimaryButtonText = Strings.BugReport_Options_Continue,
CloseButtonText = Strings.Common_Cancel,
DefaultButton = ContentDialogButton.Primary,
DialogMaxWidth = 640,
};
ContentDialogResult result = await _dialogs.ShowAsync(dialog, ct).ConfigureAwait(true);
return viewModel.Choice(result == ContentDialogResult.Primary);
}
}
@@ -0,0 +1,24 @@
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Windows;
namespace FrameLedger.App.Services;
/// <summary>
/// The crash dialog of <c>10_LOGGING</c> §Crash handling (P4 PR-9). A Win32 message box on purpose, not a WPF UI one: it
/// runs after an exception nobody handled, when the shell's dialog host, the theme and the dispatcher's state are exactly
/// what cannot be trusted. Yes opens the bug-report flow; No closes FrameLedger.
/// </summary>
internal static class CrashDialog
{
public static bool AskToReport(string? dump) =>
MessageBox.Show(Body(dump), Strings.Crash_Title, MessageBoxButton.YesNo, MessageBoxImage.Error, MessageBoxResult.No) == MessageBoxResult.Yes;
/// <summary>The dialog's text: what happened, where the dump is (or that there is none), and what the report does.</summary>
[SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format strings are resources that follow the UI culture")]
public static string Body(string? dump)
{
string where = dump is null ? Strings.Crash_NoDump : string.Format(CultureInfo.CurrentCulture, Strings.Crash_Dump_Format, dump);
return string.Format(CultureInfo.CurrentCulture, Strings.Crash_Body_Format, where);
}
}
@@ -0,0 +1,14 @@
namespace FrameLedger.App.Services;
/// <summary>The answer to the bug report's optional crash dump (P4 PR-9, <c>10_LOGGING</c> §Bug report flow step 2).</summary>
public enum CrashDumpChoice
{
/// <summary>The dialog was closed: no bundle is written.</summary>
Cancel,
/// <summary>Continue without the dump: the checkbox was left clear, which is how it starts.</summary>
LeaveOut,
/// <summary>Continue with the dump: the user ticked it.</summary>
Include,
}
@@ -0,0 +1,4 @@
namespace FrameLedger.App.Services;
/// <summary>The newest minidump the bug bundle could carry (P4 PR-9): where it is, when it was written, how big it is.</summary>
public sealed record CrashDumpInfo(string Path, DateTimeOffset WrittenAt, long Bytes);
@@ -0,0 +1,93 @@
using Serilog;
namespace FrameLedger.App.Services;
/// <summary>
/// <c>10_LOGGING</c> §Crash handling for the App's own fatal exceptions (P4 PR-9): Serilog <c>Fatal</c> with the whole
/// exception, a minidump, the crash dialog offering the bug-report flow; the caller then ends the process with exit code
/// 1. The three effects are delegates so the order and the one-dialog rule are tested without a crash.
/// </summary>
/// <remarks>
/// A second fatal exception while the first is being reported shows nothing: a dialog loop over a broken dispatcher is
/// the failure this prevents. Only the first of those is logged whole. A fault in a layout pass repeats on every pass,
/// and the dialog's own message loop keeps running passes, so logging each would flood <c>ui-*.log</c>; the rest are
/// counted and the count is logged when the report ends.
/// </remarks>
public sealed class CrashReporter
{
private readonly Func<string?> _writeDump;
private readonly Func<string?, bool> _askToReport;
private readonly Func<Task> _report;
private int _handling;
private int _further;
/// <summary>A reporter over the three effects, in the order they run.</summary>
/// <param name="writeDump">Writes the minidump; the path, or null when none was written.</param>
/// <param name="askToReport">The crash dialog, given the dump's path; true when the user wants the bug report.</param>
/// <param name="report">The bug-report flow (<c>10_LOGGING</c> §Bug report flow).</param>
public CrashReporter(Func<string?> writeDump, Func<string?, bool> askToReport, Func<Task> report)
{
_writeDump = writeDump ?? throw new ArgumentNullException(nameof(writeDump));
_askToReport = askToReport ?? throw new ArgumentNullException(nameof(askToReport));
_report = report ?? throw new ArgumentNullException(nameof(report));
}
/// <summary>True once the first fatal exception is being reported; the caller shuts the App down with exit code 1.</summary>
public bool Crashed => Volatile.Read(ref _handling) == 1;
/// <summary>How many further fatal exceptions arrived while the first was being reported.</summary>
public int FurtherExceptions => Volatile.Read(ref _further);
/// <summary>
/// Reports <paramref name="exception"/>. True when this call reported it (the first); false when a crash was already
/// being reported, in which case nothing is shown.
/// </summary>
public async Task<bool> HandleAsync(Exception exception, string source)
{
ArgumentNullException.ThrowIfNull(exception);
if (Interlocked.Exchange(ref _handling, 1) == 1)
{
if (Interlocked.Increment(ref _further) == 1)
{
Log.Fatal(exception, "ui: a further unhandled exception ({Source}) while the first was being reported; later ones are counted", source);
}
return false;
}
Log.Fatal(exception, "ui: unhandled exception ({Source}); FrameLedger closes with exit code 1", source);
string? dump = null;
try
{
dump = _writeDump();
}
catch (Exception dumpFailure) when (dumpFailure is not OutOfMemoryException)
{
// The dialog still comes: a report without a dump is worth more than no report.
Log.Error(dumpFailure, "ui: the crash dump was not written");
}
Log.Information("ui: crash dump {Dump}", dump ?? "not written");
try
{
if (_askToReport(dump))
{
await _report().ConfigureAwait(true);
}
}
catch (Exception reportFailure) when (reportFailure is not OutOfMemoryException)
{
// The report is a courtesy after a crash; its own failure must not become a second crash.
Log.Error(reportFailure, "ui: the crash report did not complete (dump {Dump})", dump ?? "not written");
}
int further = FurtherExceptions;
if (further > 0)
{
Log.Warning("ui: {Count} further unhandled exception(s) arrived while the crash was reported", further);
}
// No CloseAndFlush here: the file sink is unbuffered, the teardown that follows still logs, and OnExit closes it.
return true;
}
}
@@ -0,0 +1,102 @@
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Wpf.Ui.Controls;
namespace FrameLedger.App.Services;
/// <summary>
/// <c>08_UI</c> §Accessibility: Esc closes the open dialog with no result — the same as its Close or Cancel button.
/// WPF UI 4.3.0 handles no key in <c>ContentDialog</c> or <c>MessageBox</c> (both sources at the 4.3.0 tag, read
/// 2026-09-15), so one class handler on <see cref="Window"/> does it for every window this app opens: a
/// <c>MessageBox</c> closes itself; any other window hides the <c>ContentDialog</c> its <see cref="ContentDialogHost"/>
/// is showing.
/// </summary>
/// <remarks>
/// The BUBBLING key event, not the preview: a control that uses Esc itself — a dropdown closing its list, a text box
/// with an IME composition — handles it first, and only an Esc nobody wanted reaches the window. Esc is never an
/// acceptance: the consent dialog and the Legal Gate already treat a close without a result as the refusal.
/// </remarks>
public static class DialogKeyboard
{
private static int _registered;
/// <summary>Once per process, before the first window (<c>App.OnStartup</c>).</summary>
public static void Register()
{
if (Interlocked.Exchange(ref _registered, 1) == 1)
{
return;
}
EventManager.RegisterClassHandler(typeof(Window), UIElement.KeyDownEvent, new KeyEventHandler(OnKeyDown));
}
/// <summary>
/// Hides the dialog <paramref name="host"/> shows, with no result; false when it shows none, or when the dialog offers
/// no Close button — a dialog built to be answered is not dismissed by a key it never offered.
/// </summary>
public static bool CloseOpenDialog(ContentDialogHost? host)
{
if (host?.Content is not ContentDialog dialog || string.IsNullOrEmpty(dialog.CloseButtonText))
{
return false;
}
dialog.Hide(ContentDialogResult.None);
return true;
}
/// <summary>The message box's own Close button, pressed: the path its template takes, so the result is the one a click gives.</summary>
public static bool CloseMessageBox(Wpf.Ui.Controls.MessageBox box)
{
ArgumentNullException.ThrowIfNull(box);
if (string.IsNullOrEmpty(box.CloseButtonText) || !box.IsCloseButtonEnabled)
{
return false;
}
box.TemplateButtonCommand.Execute(Wpf.Ui.Controls.MessageBoxButton.Close);
return true;
}
private static void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Escape || e.Handled)
{
return;
}
if (sender is Wpf.Ui.Controls.MessageBox box)
{
e.Handled = CloseMessageBox(box);
return;
}
if (sender is Window window && CloseOpenDialog(ContentDialogHost.GetForWindow(window) ?? FindHost(window)))
{
e.Handled = true;
}
}
/// <summary>The host by walking the visual tree, for a window whose host has not registered itself yet.</summary>
private static ContentDialogHost? FindHost(DependencyObject root)
{
int count = VisualTreeHelper.GetChildrenCount(root);
for (int i = 0; i < count; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(root, i);
if (child is ContentDialogHost host)
{
return host;
}
if (FindHost(child) is { } found)
{
return found;
}
}
return null;
}
}
@@ -1,7 +1,14 @@
namespace FrameLedger.App.Services;
/// <summary>Step 3's preview dialog as a port, so <see cref="BugReportFlow"/> is testable without a window.</summary>
/// <summary>The bug report's dialogs as a port, so <see cref="BugReportFlow"/> is testable without a window.</summary>
public interface IBugReportPreview
{
/// <summary>Step 3: every entry of the written zip, then step 4's choice.</summary>
Task<BugReportChoice> ShowAsync(BugReportPreviewModel model, CancellationToken ct = default);
/// <summary>
/// Step 2's optional item (P4 PR-9): the crash dump's checkbox, clear until the user ticks it
/// (<c>legal/PRIVACY_POLICY.md</c> §3). Closing the dialog is <see cref="CrashDumpChoice.Cancel"/>.
/// </summary>
Task<CrashDumpChoice> AskCrashDumpAsync(CrashDumpInfo dump, CancellationToken ct = default);
}
@@ -0,0 +1,77 @@
using System.Text;
using System.Text.RegularExpressions;
namespace FrameLedger.App.Services;
/// <summary>
/// The "redacted copies" of <c>10_LOGGING</c> §Bug report flow step 2, and what makes <c>legal/PRIVACY_POLICY.md</c> §3's
/// "logs are redacted (user directory paths removed) before bundling" true: the name in every <c>X:\Users\&lt;name&gt;</c>
/// path becomes <c>&lt;user&gt;</c>, and so does the last segment of this user's own profile directory when it lives
/// somewhere else. Applied to the bundle's copies only; the files in <c>logs\</c> keep their paths.
/// </summary>
/// <remarks>
/// Every spelling a log carries: backslashes, the doubled backslashes of Serilog's JSON properties, forward slashes, any
/// case, a name with spaces, and a name the Overlay's ANSI header could only spell with <c>?</c>. Files are read as bytes
/// through Latin-1, which maps each byte to one character and back, so a UTF-8 log (Serilog) and an ANSI one (the Overlay's
/// image path) both come out byte for byte except the names. Over-redaction is the failure direction chosen: another
/// account's folder, or <c>C:\Users\Public</c>, reads <c>&lt;user&gt;</c> too.
/// </remarks>
public sealed partial class LogRedactor
{
/// <summary>What a user name in a path becomes.</summary>
public const string Placeholder = "<user>";
private const string _separator = @"(?:\\{1,2}|/)";
private const string _end = @"(?=[\\/""'<>|\r\n\t]|\z)";
private readonly Regex? _profile;
/// <summary>A redactor for <paramref name="profileDirectory"/>'s owner; null or empty redacts <c>X:\Users\&lt;name&gt;</c> paths only.</summary>
public LogRedactor(string? profileDirectory)
{
_profile = ProfilePattern(profileDirectory);
}
/// <summary>The redactor for the user running FrameLedger.</summary>
public static LogRedactor ForCurrentUser() => new(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
/// <summary>The text with every user name in a path replaced by <see cref="Placeholder"/>.</summary>
public string Redact(string text)
{
ArgumentNullException.ThrowIfNull(text);
string result = UsersPath().Replace(text, "${prefix}" + Placeholder);
return _profile is null ? result : _profile.Replace(result, "${prefix}" + Placeholder);
}
/// <summary>A log file's bytes, redacted, and otherwise byte for byte what was read.</summary>
public byte[] Redact(byte[] bytes)
{
ArgumentNullException.ThrowIfNull(bytes);
return Encoding.Latin1.GetBytes(Redact(Encoding.Latin1.GetString(bytes)));
}
[GeneratedRegex(@"(?<prefix>\b[A-Za-z]:" + _separator + "Users" + _separator + @")(?<name>[^\\/""'<>|\r\n\t]+?)" + _end, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture, matchTimeoutMilliseconds: 2000)]
private static partial Regex UsersPath();
// A profile outside X:\Users (a redirected or a domain-managed one): its own parent, then its name. The name is matched
// as its UTF-8 bytes read through Latin-1, which is how Redact(byte[]) sees a Serilog log.
private static Regex? ProfilePattern(string? profileDirectory)
{
if (string.IsNullOrWhiteSpace(profileDirectory))
{
return null;
}
string[] segments = profileDirectory.Split(['\\', '/'], StringSplitOptions.RemoveEmptyEntries);
if (segments.Length < 2 || segments[0].Length != 2 || segments[0][1] != ':'
|| (segments.Length == 3 && string.Equals(segments[1], "Users", StringComparison.OrdinalIgnoreCase)))
{
return null;
}
static string Escaped(string segment) => Regex.Escape(Encoding.Latin1.GetString(Encoding.UTF8.GetBytes(segment)));
string parent = string.Join(_separator, segments[..^1].Select(Escaped));
string pattern = @"(?<prefix>\b" + parent + _separator + ")" + Escaped(segments[^1]) + _end;
return new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture, TimeSpan.FromSeconds(2));
}
}
@@ -0,0 +1,38 @@
using FrameLedger.App.Pages;
namespace FrameLedger.App.Services;
/// <summary>
/// <c>08_UI</c> §Accessibility, keyboard: Ctrl+1 … Ctrl+5 (and the numeric keypad) open the NavigationView's pages in
/// the order the shell lists them — Dashboard, Games, Compare, Logs, Settings. The key bindings live in
/// <c>MainWindow.xaml</c>; this is the one place that knows which number is which page, and a test holds the two
/// orders together.
/// </summary>
public static class ShellShortcuts
{
/// <summary>Navigates for <paramref name="key"/> ("1" … "5"); false for anything else, which does nothing.</summary>
public static bool Navigate(IPageNavigator navigator, string? key)
{
ArgumentNullException.ThrowIfNull(navigator);
switch (key)
{
case "1":
navigator.Navigate<DashboardPage>();
return true;
case "2":
navigator.Navigate<GamesPage>();
return true;
case "3":
navigator.Navigate<ComparePage>();
return true;
case "4":
navigator.Navigate<LogsPage>();
return true;
case "5":
navigator.Navigate<SettingsPage>();
return true;
default:
return false;
}
}
}
+3
View File
@@ -16,6 +16,9 @@ internal static class UiPaths
public static string Logs => Path.Combine(DataDirectory, "logs");
/// <summary><c>10_LOGGING</c> §Crash handling: the minidumps of both processes' crashes (P4 PR-9), the newest five kept.</summary>
public static string CrashDumps => Path.Combine(DataDirectory, "crashdumps");
public static void EnsureDirectories()
{
Directory.CreateDirectory(DataDirectory);
+35 -2
View File
@@ -26,6 +26,10 @@ public static class Strings
/// <summary>Every key, for an audit that walks them.</summary>
public static IReadOnlyList<string> Keys { get; } =
[
nameof(A11y_Games_Sort),
nameof(A11y_Logs_Level),
nameof(A11y_Logs_Source),
nameof(A11y_Logs_Tail),
nameof(About_Body_Format),
nameof(About_Title),
nameof(AddGame_Added_Format),
@@ -48,6 +52,11 @@ public static class Strings
nameof(BugReport_CopyMarkdown),
nameof(BugReport_OpenIssue),
nameof(BugReport_OpenZipFolder),
nameof(BugReport_Options_Continue),
nameof(BugReport_Options_Dump_Detail),
nameof(BugReport_Options_Dump_Format),
nameof(BugReport_Options_Intro),
nameof(BugReport_Options_Title),
nameof(BugReport_Preview_Drag),
nameof(BugReport_Preview_Intro_Format),
nameof(BugReport_Title),
@@ -112,7 +121,9 @@ public static class Strings
nameof(Compare_Table_Header),
nameof(Compare_Table_Metric),
nameof(Compare_TooMany),
nameof(Crash_Body),
nameof(Crash_Body_Format),
nameof(Crash_Dump_Format),
nameof(Crash_NoDump),
nameof(Crash_Title),
nameof(Dashboard_Agent_Elevated),
nameof(Dashboard_Agent_Header),
@@ -571,6 +582,14 @@ public static class Strings
nameof(Upscaler_Unknown),
];
public static string A11y_Games_Sort => ResourceManager.GetString(nameof(A11y_Games_Sort), Culture) ?? nameof(A11y_Games_Sort);
public static string A11y_Logs_Level => ResourceManager.GetString(nameof(A11y_Logs_Level), Culture) ?? nameof(A11y_Logs_Level);
public static string A11y_Logs_Source => ResourceManager.GetString(nameof(A11y_Logs_Source), Culture) ?? nameof(A11y_Logs_Source);
public static string A11y_Logs_Tail => ResourceManager.GetString(nameof(A11y_Logs_Tail), Culture) ?? nameof(A11y_Logs_Tail);
public static string About_Body_Format => ResourceManager.GetString(nameof(About_Body_Format), Culture) ?? nameof(About_Body_Format);
public static string About_Title => ResourceManager.GetString(nameof(About_Title), Culture) ?? nameof(About_Title);
@@ -615,6 +634,16 @@ public static class Strings
public static string BugReport_OpenZipFolder => ResourceManager.GetString(nameof(BugReport_OpenZipFolder), Culture) ?? nameof(BugReport_OpenZipFolder);
public static string BugReport_Options_Continue => ResourceManager.GetString(nameof(BugReport_Options_Continue), Culture) ?? nameof(BugReport_Options_Continue);
public static string BugReport_Options_Dump_Detail => ResourceManager.GetString(nameof(BugReport_Options_Dump_Detail), Culture) ?? nameof(BugReport_Options_Dump_Detail);
public static string BugReport_Options_Dump_Format => ResourceManager.GetString(nameof(BugReport_Options_Dump_Format), Culture) ?? nameof(BugReport_Options_Dump_Format);
public static string BugReport_Options_Intro => ResourceManager.GetString(nameof(BugReport_Options_Intro), Culture) ?? nameof(BugReport_Options_Intro);
public static string BugReport_Options_Title => ResourceManager.GetString(nameof(BugReport_Options_Title), Culture) ?? nameof(BugReport_Options_Title);
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);
@@ -743,7 +772,11 @@ public static class Strings
public static string Compare_TooMany => ResourceManager.GetString(nameof(Compare_TooMany), Culture) ?? nameof(Compare_TooMany);
public static string Crash_Body => ResourceManager.GetString(nameof(Crash_Body), Culture) ?? nameof(Crash_Body);
public static string Crash_Body_Format => ResourceManager.GetString(nameof(Crash_Body_Format), Culture) ?? nameof(Crash_Body_Format);
public static string Crash_Dump_Format => ResourceManager.GetString(nameof(Crash_Dump_Format), Culture) ?? nameof(Crash_Dump_Format);
public static string Crash_NoDump => ResourceManager.GetString(nameof(Crash_NoDump), Culture) ?? nameof(Crash_NoDump);
public static string Crash_Title => ResourceManager.GetString(nameof(Crash_Title), Culture) ?? nameof(Crash_Title);
+52 -4
View File
@@ -93,10 +93,6 @@
<value>比較</value>
<comment>review</comment>
</data>
<data name="Crash_Body" xml:space="preserve">
<value>FrameLedger は回復できないエラーに遭遇しました。詳細はログフォルダーにあります。キャプチャエージェントは動作を続けます。</value>
<comment>review</comment>
</data>
<data name="Crash_Title" xml:space="preserve">
<value>FrameLedger が予期せず停止しました</value>
<comment>review</comment>
@@ -2187,6 +2183,58 @@
</data>
<data name="Maintenance_Status_Working" xml:space="preserve">
<value>実行中…</value>
</data>
<data name="A11y_Games_Sort" xml:space="preserve">
<value>ゲームの並べ替え</value>
<comment>review</comment>
</data>
<data name="A11y_Logs_Source" xml:space="preserve">
<value>ログのソース</value>
<comment>review</comment>
</data>
<data name="A11y_Logs_Level" xml:space="preserve">
<value>最小ログレベル</value>
<comment>review</comment>
</data>
<data name="A11y_Logs_Tail" xml:space="preserve">
<value>ログの行</value>
<comment>review</comment>
</data>
<data name="Crash_Body_Format" xml:space="preserve">
<value>FrameLedger は回復できないエラーに遭遇したため、終了します。キャプチャエージェントは動作を続けます。
{0}
今すぐバグを報告しますか? zip に含まれるすべてのファイルが表示され、自動では何も送信されません。クラッシュダンプはチェックを入れた場合にのみ含まれます。</value>
<comment>review</comment>
</data>
<data name="Crash_Dump_Format" xml:space="preserve">
<value>クラッシュダンプをこの PC に保存しました:
{0}</value>
<comment>review</comment>
</data>
<data name="Crash_NoDump" xml:space="preserve">
<value>クラッシュダンプを書き込めませんでした。</value>
<comment>review</comment>
</data>
<data name="BugReport_Options_Title" xml:space="preserve">
<value>オプション項目</value>
<comment>review</comment>
</data>
<data name="BugReport_Options_Intro" xml:space="preserve">
<value>zip には常に FrameLedger 自身のログ、sysinfo.json、settings.json が含まれます。以下の項目はチェックを入れた場合にのみ含まれます。</value>
<comment>review</comment>
</data>
<data name="BugReport_Options_Dump_Format" xml:space="preserve">
<value>{0} のクラッシュダンプ ({1:0.0} MB)</value>
<comment>review</comment>
</data>
<data name="BugReport_Options_Dump_Detail" xml:space="preserve">
<value>クラッシュ時の FrameLedger 自身のメモリのスナップショットです。原因の特定に役立ちますが、この PC のファイルパス、ゲーム名、設定が含まれる場合があります。</value>
<comment>review</comment>
</data>
<data name="BugReport_Options_Continue" xml:space="preserve">
<value>続行</value>
<comment>review</comment>
</data>
</root>
+41 -3
View File
@@ -75,9 +75,6 @@
<data name="Compare_Header" xml:space="preserve">
<value>Compare</value>
</data>
<data name="Crash_Body" xml:space="preserve">
<value>FrameLedger hit an error it could not recover from. The details are in the log folder; the capture agent keeps running.</value>
</data>
<data name="Crash_Title" xml:space="preserve">
<value>FrameLedger stopped unexpectedly</value>
</data>
@@ -1647,4 +1644,45 @@
<data name="Maintenance_Status_Working" xml:space="preserve">
<value>Working…</value>
</data>
<data name="A11y_Games_Sort" xml:space="preserve">
<value>Sort games</value>
</data>
<data name="A11y_Logs_Source" xml:space="preserve">
<value>Log source</value>
</data>
<data name="A11y_Logs_Level" xml:space="preserve">
<value>Minimum log level</value>
</data>
<data name="A11y_Logs_Tail" xml:space="preserve">
<value>Log lines</value>
</data>
<data name="Crash_Body_Format" xml:space="preserve">
<value>FrameLedger hit an error it could not recover from and will close. The capture agent keeps running.
{0}
Open the bug report now? It shows you every file in the zip, sends nothing by itself, and includes the crash dump only if you tick it.</value>
</data>
<data name="Crash_Dump_Format" xml:space="preserve">
<value>A crash dump was saved on this PC:
{0}</value>
</data>
<data name="Crash_NoDump" xml:space="preserve">
<value>No crash dump could be written.</value>
</data>
<data name="BugReport_Options_Title" xml:space="preserve">
<value>Optional items</value>
</data>
<data name="BugReport_Options_Intro" xml:space="preserve">
<value>The zip always holds FrameLedger's own logs, sysinfo.json and settings.json. What follows goes in only if you tick it.</value>
</data>
<data name="BugReport_Options_Dump_Format" xml:space="preserve">
<value>The crash dump of {0} ({1:0.0} MB)</value>
</data>
<data name="BugReport_Options_Dump_Detail" xml:space="preserve">
<value>A snapshot of FrameLedger's own memory when it crashed. It helps find the cause, and it can contain file paths, game names and settings from this PC.</value>
</data>
<data name="BugReport_Options_Continue" xml:space="preserve">
<value>Continue</value>
</data>
</root>
+41 -3
View File
@@ -70,9 +70,6 @@
<data name="Compare_Header" xml:space="preserve">
<value>So sánh</value>
</data>
<data name="Crash_Body" xml:space="preserve">
<value>FrameLedger gặp lỗi không khôi phục được. Chi tiết nằm trong thư mục log; capture agent vẫn chạy.</value>
</data>
<data name="Crash_Title" xml:space="preserve">
<value>FrameLedger dừng đột ngột</value>
</data>
@@ -1642,4 +1639,45 @@
<data name="Maintenance_Status_Working" xml:space="preserve">
<value>Đang thực hiện…</value>
</data>
<data name="A11y_Games_Sort" xml:space="preserve">
<value>Sắp xếp game</value>
</data>
<data name="A11y_Logs_Source" xml:space="preserve">
<value>Nguồn log</value>
</data>
<data name="A11y_Logs_Level" xml:space="preserve">
<value>Mức log tối thiểu</value>
</data>
<data name="A11y_Logs_Tail" xml:space="preserve">
<value>Các dòng log</value>
</data>
<data name="Crash_Body_Format" xml:space="preserve">
<value>FrameLedger gặp lỗi không khôi phục được và sẽ đóng lại. Capture agent vẫn chạy.
{0}
Mở báo cáo lỗi ngay bây giờ? Báo cáo cho bạn xem mọi tệp trong gói zip, không tự gửi đi đâu, và chỉ đưa crash dump vào nếu bạn tick chọn.</value>
</data>
<data name="Crash_Dump_Format" xml:space="preserve">
<value>Một crash dump đã được lưu trên máy này:
{0}</value>
</data>
<data name="Crash_NoDump" xml:space="preserve">
<value>Không ghi được crash dump.</value>
</data>
<data name="BugReport_Options_Title" xml:space="preserve">
<value>Mục tuỳ chọn</value>
</data>
<data name="BugReport_Options_Intro" xml:space="preserve">
<value>Gói zip luôn gồm log của chính FrameLedger, sysinfo.json và settings.json. Mục bên dưới chỉ được đưa vào nếu bạn tick chọn.</value>
</data>
<data name="BugReport_Options_Dump_Format" xml:space="preserve">
<value>Crash dump lúc {0} ({1:0.0} MB)</value>
</data>
<data name="BugReport_Options_Dump_Detail" xml:space="preserve">
<value>Ảnh chụp bộ nhớ của chính FrameLedger lúc bị lỗi. Nó giúp tìm nguyên nhân, và có thể chứa đường dẫn tệp, tên game và cài đặt trên máy này.</value>
</data>
<data name="BugReport_Options_Continue" xml:space="preserve">
<value>Tiếp tục</value>
</data>
</root>
+3 -1
View File
@@ -2,7 +2,8 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:controls="clr-namespace:FrameLedger.App.Controls"
xmlns:converters="clr-namespace:FrameLedger.App.Converters">
xmlns:converters="clr-namespace:FrameLedger.App.Converters"
xmlns:res="clr-namespace:FrameLedger.App">
<!--
Our styles, merged LAST (16_WPFUI_SYNTAX §App bootstrap). Colours only through theme brushes with
DynamicResource; the chart palette (16 §Theming) arrives with the charts (P3 PR-6) as its own dictionary.
@@ -102,6 +103,7 @@
HorizontalAlignment="Right" />
<Border Grid.Column="3" Margin="12,-2,0,0" VerticalAlignment="Top">
<ui:Button x:Name="CloseButton" Padding="4" Background="Transparent" BorderThickness="0" IsEnabled="True"
AutomationProperties.Name="{x:Static res:Strings.Common_Close}"
Command="{Binding Path=TemplateButtonCommand, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}">
<ui:Button.Icon>
<ui:SymbolIcon Symbol="Dismiss24" />
@@ -0,0 +1,48 @@
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using FrameLedger.App.Services;
namespace FrameLedger.App.ViewModels;
/// <summary>
/// The bug report's optional crash dump (P4 PR-9, <c>10_LOGGING</c> §Bug report flow step 2): one checkbox, clear until the
/// user ticks it (<c>legal/PRIVACY_POLICY.md</c> §3), labelled with the dump's time and size, and a line saying what a
/// dump can hold.
/// </summary>
[SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format string is a resource that follows the UI culture, which changes at runtime")]
public sealed partial class BugBundleOptionsViewModel : ObservableObject
{
[ObservableProperty]
private bool _includeCrashDump;
public BugBundleOptionsViewModel(CrashDumpInfo dump)
{
ArgumentNullException.ThrowIfNull(dump);
DumpLabel = string.Format(
CultureInfo.CurrentCulture,
Strings.BugReport_Options_Dump_Format,
dump.WrittenAt.ToLocalTime().ToString("g", CultureInfo.CurrentCulture),
dump.Bytes / (1024.0 * 1024.0));
}
public static string Title => Strings.BugReport_Options_Title;
public static string Intro => Strings.BugReport_Options_Intro;
public static string DumpDetail => Strings.BugReport_Options_Dump_Detail;
/// <summary>The checkbox's text: the dump's local time and its size in MB.</summary>
public string DumpLabel { get; }
/// <summary>The answer, once the dialog closed: <paramref name="continued"/> is its primary button.</summary>
public CrashDumpChoice Choice(bool continued)
{
if (!continued)
{
return CrashDumpChoice.Cancel;
}
return IncludeCrashDump ? CrashDumpChoice.Include : CrashDumpChoice.LeaveOut;
}
}
@@ -143,6 +143,10 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable
[RelayCommand]
private void Exit() => _shell.Quit();
/// <summary>08_UI §Accessibility: Ctrl+1…5 (and the keypad) — the NavigationView's pages in its order.</summary>
[RelayCommand]
private void NavigateTo(string? key) => _ = ShellShortcuts.Navigate(_navigator, key);
/// <summary>Tools ▸ Agent status… is the Dashboard's Agent card.</summary>
[RelayCommand]
private void AgentStatus() => _navigator.Navigate<DashboardPage>();
@@ -101,8 +101,9 @@
<!-- annotations -->
<ui:TextBlock Margin="0,16,0,0" FontTypography="Subtitle" Text="{x:Static vm:SessionSummaryViewModel.AnnotationsHeader}" />
<ui:TextBox Margin="0,6,0,0" PlaceholderText="{x:Static vm:SessionSummaryViewModel.TagsPlaceholder}" Text="{Binding ViewModel.Tags, UpdateSourceTrigger=PropertyChanged}" />
<ui:TextBox Margin="0,6,0,0" AutomationProperties.Name="{x:Static vm:SessionSummaryViewModel.TagsPlaceholder}" PlaceholderText="{x:Static vm:SessionSummaryViewModel.TagsPlaceholder}" Text="{Binding ViewModel.Tags, UpdateSourceTrigger=PropertyChanged}" />
<ui:TextBox Margin="0,6,0,0" MinHeight="72" AcceptsReturn="True" TextWrapping="Wrap"
AutomationProperties.Name="{x:Static vm:SessionSummaryViewModel.NotesPlaceholder}"
PlaceholderText="{x:Static vm:SessionSummaryViewModel.NotesPlaceholder}" Text="{Binding ViewModel.Notes, UpdateSourceTrigger=PropertyChanged}" />
<StackPanel Orientation="Horizontal" Margin="0,8,0,0">
<ui:Button Appearance="Primary" Command="{Binding ViewModel.SaveAnnotationCommand}" Content="{x:Static vm:SessionSummaryViewModel.SaveText}" Icon="{ui:SymbolIcon Save24}" />
@@ -0,0 +1,106 @@
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.System.Diagnostics.Debug;
namespace FrameLedger.Infrastructure.Diagnostics;
/// <summary>
/// <c>10_LOGGING</c> §Crash handling: on a fatal exception, a minidump of this process through <c>MiniDumpWriteDump</c>
/// (<c>MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithThreadInfo</c>) into <c>crashdumps\</c>, the newest five kept
/// (P4 PR-9). Called from a crash path, so it never throws: every failure is a null path and a line for the caller's log.
/// The dump stays on this machine; a bug bundle carries it only when the user says so (<c>legal/PRIVACY_POLICY.md</c> §3).
/// </summary>
public static class CrashDumpWriter
{
/// <summary>How many dumps the directory keeps; the oldest beyond this go after each write.</summary>
public const int Kept = 5;
/// <summary>The dump file pattern; <see cref="Prune"/> and the bug bundle read nothing else from the directory.</summary>
public const string Pattern = "*.dmp";
/// <summary>
/// Writes <c>&lt;process&gt;-&lt;yyyyMMdd-HHmmss&gt;-&lt;pid&gt;.dmp</c> (UTC) under <paramref name="directory"/> and prunes to
/// <see cref="Kept"/>. Returns the path, or null when nothing usable was written (the partial file is removed).
/// </summary>
public static unsafe string? TryWrite(string directory, string process, DateTimeOffset now, Action<string>? log = null)
{
string? path = null;
try
{
ArgumentException.ThrowIfNullOrWhiteSpace(directory);
ArgumentException.ThrowIfNullOrWhiteSpace(process);
Directory.CreateDirectory(directory);
path = Path.Combine(directory, string.Create(CultureInfo.InvariantCulture, $"{process}-{now.UtcDateTime:yyyyMMdd-HHmmss}-{Environment.ProcessId}.dmp"));
bool written;
using (var file = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
using (Process self = Process.GetCurrentProcess())
{
written = PInvoke.MiniDumpWriteDump(
new HANDLE(self.Handle),
(uint)self.Id,
new HANDLE(file.SafeFileHandle.DangerousGetHandle()),
MINIDUMP_TYPE.MiniDumpWithIndirectlyReferencedMemory | MINIDUMP_TYPE.MiniDumpWithThreadInfo,
null,
null,
null);
}
if (!written)
{
log?.Invoke($"crash dump: MiniDumpWriteDump failed (Win32 error {Marshal.GetLastPInvokeError()})");
TryDelete(path);
return null;
}
Prune(directory, log);
return path;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException or System.ComponentModel.Win32Exception or InvalidOperationException)
{
log?.Invoke($"crash dump: not written ({ex.GetType().Name}: {ex.Message})");
if (path is not null)
{
TryDelete(path);
}
return null;
}
}
/// <summary>Keeps the <see cref="Kept"/> newest dumps in <paramref name="directory"/>; a file that cannot be removed stays.</summary>
public static void Prune(string directory, Action<string>? log = null)
{
if (!Directory.Exists(directory))
{
return;
}
foreach (FileInfo old in new DirectoryInfo(directory).EnumerateFiles(Pattern).OrderByDescending(static f => f.LastWriteTimeUtc).Skip(Kept))
{
try
{
old.Delete();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
log?.Invoke($"crash dump: could not prune {old.Name} ({ex.Message})");
}
}
}
private static void TryDelete(string path)
{
try
{
File.Delete(path);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Nothing more a crash path can do; the next prune gets another chance.
}
}
}
@@ -28,3 +28,7 @@ NAMED_PIPE_MODE
EnumDisplaySettings
DEVMODEW
ENUM_DISPLAY_SETTINGS_MODE
// The crash path's minidump (10_LOGGING §Crash handling, P4 PR-9, Diagnostics.CrashDumpWriter): the process's own
// memory into a file under crashdumps\, never another process's.
MiniDumpWriteDump
MINIDUMP_TYPE
+157
View File
@@ -14,6 +14,9 @@
#include <algorithm>
#include <catch2/catch_test_macros.hpp>
#include <catch2/reporters/catch_reporter_event_listener.hpp>
#include <catch2/reporters/catch_reporter_registrars.hpp>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <fl_ac_rules.h>
@@ -25,6 +28,8 @@
#include <utility>
#include <vector>
#include "overlay_log_sweep.h"
using namespace fl::guard;
namespace {
@@ -4822,3 +4827,155 @@ TEST_CASE("the injected Overlay records ray-tracing work, and an AS-build-only t
CHECK(rayquery.withDispatch == 0u);
CHECK(rayquery.volume == 0u);
}
// ===========================================================================
// Test hygiene: the harness's overlay logs leave with the run that wrote them.
// ===========================================================================
namespace {
// Every run of this binary -- the full fl_guard run and the [prescan] selection alike -- removes, when it ends, the
// hook-harness overlay logs it created under the real data folder. overlay_log_sweep.h says why a sweep and not a
// redirect: the shipped Overlay is the one under test, and its log path is not a parameter by design (§S21).
class HarnessLogSweepListener final : public Catch::EventListenerBase {
public:
using Catch::EventListenerBase::EventListenerBase;
void testRunStarting(const Catch::TestRunInfo& /*info*/) override { GetSystemTimeAsFileTime(&started_); }
void testRunEnded(const Catch::TestRunStats& /*stats*/) override {
std::wstring logs;
if (!fl::testing::RealOverlayLogsDir(logs)) {
return;
}
const fl::testing::SweepCount count = fl::testing::SweepHarnessLogs(logs, started_, FL_HARNESS_EXE);
std::printf("harness log sweep: removed %d hook-harness overlay log(s) this run created; left %d other(s)\n",
count.removed, count.kept);
}
private:
FILETIME started_{};
};
std::string NarrowAnsi(const std::wstring& text) {
const int n =
WideCharToMultiByte(CP_ACP, 0, text.c_str(), static_cast<int>(text.size()), nullptr, 0, nullptr, nullptr);
std::string out(static_cast<std::size_t>(n > 0 ? n : 0), '\0');
if (n > 0) {
WideCharToMultiByte(CP_ACP, 0, text.c_str(), static_cast<int>(text.size()), out.data(), n, nullptr, nullptr);
}
return out;
}
void WriteText(const std::wstring& path, const std::string& text) {
HANDLE h = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
REQUIRE(h != INVALID_HANDLE_VALUE);
DWORD written = 0;
const BOOL ok = WriteFile(h, text.data(), static_cast<DWORD>(text.size()), &written, nullptr);
CloseHandle(h);
REQUIRE(ok);
}
// A creation time in 1999: a log an earlier run left behind.
void Backdate(const std::wstring& path) {
HANDLE h =
CreateFileW(path.c_str(), FILE_WRITE_ATTRIBUTES, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
REQUIRE(h != INVALID_HANDLE_VALUE);
SYSTEMTIME then{};
then.wYear = 1999;
then.wMonth = 1;
then.wDay = 1;
FILETIME old{};
const bool ok = SystemTimeToFileTime(&then, &old) != FALSE && SetFileTime(h, &old, &old, &old) != FALSE;
CloseHandle(h);
REQUIRE(ok);
}
bool FileExists(const std::wstring& path) {
return GetFileAttributesW(path.c_str()) != INVALID_FILE_ATTRIBUTES;
}
struct ScratchLogsDir {
std::wstring path;
std::vector<std::wstring> files;
ScratchLogsDir() {
wchar_t temp[MAX_PATH]{};
REQUIRE(GetTempPathW(MAX_PATH, temp) != 0);
path = std::wstring(temp) + L"fl-sweep-" + std::to_wstring(GetCurrentProcessId()) + L"-" +
std::to_wstring(GetTickCount64());
REQUIRE(CreateDirectoryW(path.c_str(), nullptr));
}
ScratchLogsDir(const ScratchLogsDir&) = delete;
ScratchLogsDir& operator=(const ScratchLogsDir&) = delete;
~ScratchLogsDir() {
for (const std::wstring& file : files) {
static_cast<void>(DeleteFileW(file.c_str()));
}
static_cast<void>(RemoveDirectoryW(path.c_str()));
}
std::wstring Add(const wchar_t* name) {
files.push_back(path + L"\\" + name);
return files.back();
}
};
} // namespace
CATCH_REGISTER_LISTENER(HarnessLogSweepListener)
TEST_CASE("the harness log sweep removes this run's harness logs and nothing else", "[sweep]") {
ScratchLogsDir dir;
// One second before now: the files below are created within the same clock tick as the start.
FILETIME since{};
GetSystemTimeAsFileTime(&since);
ULARGE_INTEGER t{};
t.LowPart = since.dwLowDateTime;
t.HighPart = since.dwHighDateTime;
t.QuadPart -= 10000000ULL;
since.dwLowDateTime = t.LowPart;
since.dwHighDateTime = t.HighPart;
// The image as the Overlay spells it: GetModuleFileNameA, backslashes, while CMake names the harness with '/'.
std::wstring harness = FL_HARNESS_EXE;
for (wchar_t& ch : harness) {
if (ch == L'/') {
ch = L'\\';
}
}
const std::string image = NarrowAnsi(harness);
std::string shouted = image;
CharUpperBuffA(shouted.data(), static_cast<DWORD>(shouted.size()));
const auto header = [](const std::string& path) {
return "# FrameLedger.Overlay build test pid 101 layout v9 image " + path + "\r\n";
};
const std::wstring ours = dir.Add(L"overlay-101-20260915-010101.log");
const std::wstring oursShouted = dir.Add(L"overlay-102-20260915-010101.log");
const std::wstring game = dir.Add(L"overlay-103-20260915-010101.log");
const std::wstring earlier = dir.Add(L"overlay-104-19990101-000000.log");
const std::wstring stranger = dir.Add(L"overlay-105-20260915-010101.log");
const std::wstring agent = dir.Add(L"agent-20260915.log");
WriteText(ours, header(image) + "RING_CREATED\n");
WriteText(oursShouted, header(shouted));
WriteText(game, header("C:\\Games\\Title\\title.exe"));
WriteText(earlier, header(image));
Backdate(earlier);
WriteText(stranger, "# a file that is not an overlay log\n");
WriteText(agent, header(image));
const fl::testing::SweepCount count = fl::testing::SweepHarnessLogs(dir.path, since, FL_HARNESS_EXE);
CHECK(count.removed == 2);
CHECK(count.kept == 2); // the game's and the stranger; the 1999 log predates the run, agent-* is not overlay-*
CHECK_FALSE(FileExists(ours));
CHECK_FALSE(FileExists(oursShouted));
CHECK(FileExists(game));
CHECK(FileExists(earlier));
CHECK(FileExists(stranger));
CHECK(FileExists(agent));
std::string parsed;
CHECK(fl::testing::OverlayLogImage(header("C:\\x\\hook-harness.exe"), parsed));
CHECK(parsed == "C:\\x\\hook-harness.exe");
CHECK_FALSE(fl::testing::OverlayLogImage("# a stale log planted by guard_test\r\n", parsed));
}
+134
View File
@@ -0,0 +1,134 @@
// Test-only. The hook-harness's overlay logs, removed when a test binary's run ends.
//
// The Overlay writes %LOCALAPPDATA%\FrameLedger\logs\overlay-<pid>-<stamp>.log: the real per-user data folder,
// resolved by SHGetKnownFolderPath and deliberately NOT by the environment (§S21), and the shipped DLL is the one
// under test, so a test cannot point it anywhere else and the DLL gets no switch that could. Measured 2026-09-15:
// that folder held 2506 overlay logs, 2492 of them hook-harness's, left by test runs since 2026-09-06.
//
// So a test binary removes, when its run ends, exactly what it caused: a log CREATED at or after the run started
// whose first line names this build's hook-harness as the image. A game's log names the game and is never touched;
// a log from an earlier run predates the start and stays, the owner's to delete (17_HOOK_ENGINE §Native logging).
#ifndef FL_OVERLAY_LOG_SWEEP_H
#define FL_OVERLAY_LOG_SWEEP_H
#include <windows.h>
#include <fl_ac_rules.h>
#include <string>
namespace fl::testing {
struct SweepCount {
int removed = 0;
int kept = 0; // created during the run but not a harness log, or could not be removed
};
// "# FrameLedger.Overlay build <id> pid <n> layout v<k> image <path>" (dllmain.cpp FlushLog) -> <path>.
inline bool OverlayLogImage(const std::string& firstLine, std::string& image) {
static const char kPrefix[] = "# FrameLedger.Overlay build ";
if (firstLine.rfind(kPrefix, 0) != 0) {
return false;
}
const std::string::size_type at = firstLine.find(" image ");
if (at == std::string::npos) {
return false;
}
image = firstLine.substr(at + 7);
while (!image.empty() && (image.back() == '\r' || image.back() == '\n' || image.back() == ' ')) {
image.pop_back();
}
return !image.empty();
}
// The header's image comes from GetModuleFileNameA, so it is in the ANSI code page.
inline std::wstring WidenAnsi(const std::string& text) {
if (text.empty()) {
return {};
}
const int n = MultiByteToWideChar(CP_ACP, 0, text.data(), static_cast<int>(text.size()), nullptr, 0);
if (n <= 0) {
return {};
}
std::wstring out(static_cast<std::size_t>(n), L'\0');
MultiByteToWideChar(CP_ACP, 0, text.data(), static_cast<int>(text.size()), out.data(), n);
return out;
}
// CMake's $<TARGET_FILE> spells '/', GetModuleFileNameA spells '\'; neither separator nor case tells two paths apart.
inline bool SamePath(std::wstring a, std::wstring b) {
for (wchar_t& ch : a) {
if (ch == L'/') {
ch = L'\\';
}
}
for (wchar_t& ch : b) {
if (ch == L'/') {
ch = L'\\';
}
}
return CompareStringOrdinal(a.c_str(), static_cast<int>(a.size()), b.c_str(), static_cast<int>(b.size()), TRUE) ==
CSTR_EQUAL;
}
// The first line of a file, from its first 1 KiB; empty when it cannot be read.
inline std::string FirstLine(const std::wstring& path) {
HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) {
return {};
}
char buf[1024];
DWORD n = 0;
const BOOL ok = ReadFile(h, buf, sizeof(buf), &n, nullptr);
CloseHandle(h);
if (!ok) {
return {};
}
const std::string text(buf, n);
const std::string::size_type nl = text.find('\n');
return nl == std::string::npos ? text : text.substr(0, nl);
}
// Removes every overlay-*.log directly under `logsDir` that was created at or after `since` and whose header names
// `harness` as the image. Anything else is left where it is.
inline SweepCount SweepHarnessLogs(const std::wstring& logsDir, const FILETIME& since, const std::wstring& harness) {
SweepCount count;
const std::wstring pattern = logsDir + L"\\overlay-*.log";
WIN32_FIND_DATAW fd{};
HANDLE find = FindFirstFileW(pattern.c_str(), &fd);
if (find == INVALID_HANDLE_VALUE) {
return count;
}
do {
if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 || CompareFileTime(&fd.ftCreationTime, &since) < 0) {
continue;
}
const std::wstring path = logsDir + L"\\" + fd.cFileName;
std::string image;
if (!OverlayLogImage(FirstLine(path), image) || !SamePath(WidenAnsi(image), harness)) {
++count.kept;
continue;
}
if (DeleteFileW(path.c_str())) {
++count.removed;
} else {
++count.kept;
}
} while (FindNextFileW(find, &fd));
FindClose(find);
return count;
}
// %LOCALAPPDATA%\FrameLedger\logs, resolved the way the Overlay resolves it.
inline bool RealOverlayLogsDir(std::wstring& out) {
wchar_t base[fl::guard::kMaxRulesPathLen]{};
if (!fl::guard::LocalAppDataDir(base, fl::guard::kMaxRulesPathLen)) {
return false;
}
out = std::wstring(base) + L"\\FrameLedger\\logs";
return true;
}
} // namespace fl::testing
#endif // FL_OVERLAY_LOG_SWEEP_H
@@ -10,6 +10,7 @@ using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Infrastructure.Persistence;
using FrameLedger.Shared.Ipc;
using FrameLedger.Shared.Safety;
using FrameLedger.Testing;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
@@ -121,6 +122,8 @@ public sealed class PipeEndToEndTests : IDisposable
{
File.Exists(Harness).Should().BeTrue("hook-harness.exe must be staged beside the test binary (FrameLedger.DrainFixtures.targets)");
Directory.CreateDirectory(_dataDir);
// The copy's overlay logs are this assembly's to remove when it finishes (17_HOOK_ENGINE §Native logging).
HarnessOverlayLogSweep.Own(_dataDir);
File.Copy(Harness, ConsentedExecutable, overwrite: true);
// The composition logs through Serilog's static logger; in this process nothing configures it, so the
// orchestrator's and the pipe's lines would vanish. A file in the scratch directory is what a hang leaves behind.
@@ -0,0 +1,219 @@
using System.IO;
using System.Text.RegularExpressions;
using System.Windows;
using System.Xml.Linq;
using FluentAssertions;
using FrameLedger.App.Pages;
using FrameLedger.App.Services;
using Wpf.Ui.Controls;
namespace FrameLedger.App.Tests;
/// <summary>
/// NFR-9 as <c>08_UI</c> §Accessibility states it (P4 PR-8), each clause held by a check that goes red on a regression:
/// every input that shows no text of its own carries an automation name, no XAML hard-codes a colour (contrast is the
/// Fluent themes'), the manifest is Per-Monitor V2, Ctrl+1…5 follow the NavigationView's order, and Esc closes the open
/// dialog with no result.
/// </summary>
public sealed class AccessibilityTests
{
private static readonly XNamespace _x = "http://schemas.microsoft.com/winfx/2006/xaml";
/// <summary>The input controls a screen reader announces by name; a textless one without a name is announced as its type alone.</summary>
private static readonly HashSet<string> _namedControls = new(StringComparer.Ordinal)
{
"Button", "ToggleButton", "ToggleSwitch", "CheckBox", "RadioButton", "ComboBox", "TextBox", "NumberBox", "PasswordBox", "Slider", "HyperlinkButton",
};
private static readonly HashSet<string> _colourProperties = new(StringComparer.Ordinal)
{
"Foreground", "Background", "BorderBrush", "Fill", "Stroke", "Color", "CaretBrush", "SelectionBrush",
};
private static string RepoRoot()
{
for (DirectoryInfo? dir = new(AppContext.BaseDirectory); dir is not null; dir = dir.Parent)
{
if (File.Exists(Path.Combine(dir.FullName, "FrameLedger.slnx")))
{
return dir.FullName;
}
}
throw new InvalidOperationException("the repository root (FrameLedger.slnx) is not above " + AppContext.BaseDirectory);
}
private static IEnumerable<(string File, XDocument Xaml)> AppXaml()
{
string app = Path.Combine(RepoRoot(), "src", "FrameLedger.App");
foreach (string file in Directory.EnumerateFiles(app, "*.xaml", SearchOption.AllDirectories)
.Where(static f => !f.Contains(Path.DirectorySeparatorChar + "obj" + Path.DirectorySeparatorChar, StringComparison.Ordinal)
&& !f.Contains(Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar, StringComparison.Ordinal)))
{
yield return (Path.GetRelativePath(app, file), XDocument.Load(file));
}
}
private static bool HasVisibleText(XElement element)
{
if (element.Attribute("Content") is not null || element.Attribute("Header") is not null)
{
return true;
}
// Content as a child element — anything that is not a property element such as <ui:Button.Icon>.
return element.Elements().Any(child => !child.Name.LocalName.Contains('.', StringComparison.Ordinal));
}
private static bool HasAutomationName(XElement element) =>
element.Attributes().Any(static a => a.Name.LocalName is "AutomationProperties.Name" or "AutomationProperties.LabeledBy");
[Fact]
public void EveryInputThatShowsNoTextHasAnAutomationName()
{
var unnamed = new List<string>();
foreach ((string file, XDocument xaml) in AppXaml())
{
foreach (XElement element in xaml.Descendants().Where(e => _namedControls.Contains(e.Name.LocalName)))
{
if (!HasVisibleText(element) && !HasAutomationName(element))
{
string where = element.Attribute(_x + "Name")?.Value ?? string.Join(" ", element.Attributes().Where(static a => a.Name.LocalName is "Command" or "IsChecked" or "Text" or "SelectedValue" or "Value").Select(static a => a.Value));
unnamed.Add($"{file}: <{element.Name.LocalName}> {where}");
}
}
}
unnamed.Should().BeEmpty("08_UI §Accessibility: a control with no text of its own is announced by AutomationProperties.Name, from .resx");
}
[Fact]
public void NoXamlHardCodesAColour()
{
HashSet<string> named = new(typeof(System.Windows.Media.Colors).GetProperties().Select(static p => p.Name), StringComparer.OrdinalIgnoreCase);
named.Remove("Transparent");
var hex = new Regex("^#[0-9A-Fa-f]{3,8}$", RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1));
var found = new List<string>();
foreach ((string file, XDocument xaml) in AppXaml())
{
foreach (XAttribute attribute in xaml.Descendants().Attributes().Where(a => _colourProperties.Contains(a.Name.LocalName)))
{
if (hex.IsMatch(attribute.Value) || named.Contains(attribute.Value))
{
found.Add($"{file}: {attribute.Parent!.Name.LocalName}.{attribute.Name.LocalName}=\"{attribute.Value}\"");
}
}
}
found.Should().BeEmpty("08_UI §Accessibility, contrast: colours come from the WPF UI theme dictionaries, whose Fluent themes meet contrast in both modes");
}
[Fact]
public void TheManifestIsPerMonitorV2()
{
string manifest = File.ReadAllText(Path.Combine(RepoRoot(), "src", "FrameLedger.App", "app.manifest"));
manifest.Should().Contain("PerMonitorV2", "NFR-9: Per-Monitor V2 DPI awareness");
}
private sealed class RecordingNavigator : IPageNavigator
{
public List<string> Pages { get; } = [];
public void Navigate<TPage>()
where TPage : class => Pages.Add(typeof(TPage).Name);
public void GoBack()
{
}
}
[Fact]
public void CtrlOneToFiveOpenTheNavigationViewsPagesInItsOrder()
{
XDocument shell = XDocument.Load(Path.Combine(RepoRoot(), "src", "FrameLedger.App", "MainWindow.xaml"));
string[] navigationOrder = [.. shell.Descendants().Where(static e => string.Equals(e.Name.LocalName, "NavigationViewItem", StringComparison.Ordinal))
.Select(static e => e.Attribute("TargetPageType")?.Value ?? string.Empty)
.Select(static v => Regex.Match(v, @"pages:(?<page>\w+)\}", RegexOptions.ExplicitCapture, TimeSpan.FromSeconds(1)).Groups["page"].Value)];
var bindings = shell.Descendants().Where(static e => string.Equals(e.Name.LocalName, "KeyBinding", StringComparison.Ordinal))
.Select(static e => (Key: e.Attribute("Key")?.Value, Modifiers: e.Attribute("Modifiers")?.Value, Parameter: e.Attribute("CommandParameter")?.Value, Command: e.Attribute("Command")?.Value))
.ToList();
var navigator = new RecordingNavigator();
for (int i = 1; i <= 5; i++)
{
string parameter = i.ToString(System.Globalization.CultureInfo.InvariantCulture);
bindings.Should().Contain((Key: "D" + parameter, Modifiers: "Control", Parameter: parameter, Command: "{Binding ViewModel.NavigateToCommand}"));
bindings.Should().Contain((Key: "NumPad" + parameter, Modifiers: "Control", Parameter: parameter, Command: "{Binding ViewModel.NavigateToCommand}"));
ShellShortcuts.Navigate(navigator, parameter).Should().BeTrue();
}
navigator.Pages.Should().Equal(navigationOrder);
navigationOrder.Should().Equal(nameof(DashboardPage), nameof(GamesPage), nameof(ComparePage), nameof(LogsPage), nameof(SettingsPage));
ShellShortcuts.Navigate(navigator, "6").Should().BeFalse();
ShellShortcuts.Navigate(navigator, null).Should().BeFalse();
}
/// <summary>
/// An STA thread with a running dispatcher: <c>ContentDialog.ShowAsync</c> clears its host in a <c>finally</c> that
/// resumes on the captured context, so the thread that showed the dialog must still be pumping when it closes.
/// </summary>
private static Task<T> OnDispatcherAsync<T>(Func<Task<T>> work)
{
var tcs = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
var thread = new Thread(() =>
{
System.Windows.Threading.Dispatcher dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.DispatcherSynchronizationContext(dispatcher));
#pragma warning disable VSTHRD001 // a test's own dispatcher thread: no JoinableTaskFactory exists here, and this posts the work rather than blocking on it
_ = dispatcher.InvokeAsync(async () =>
{
try
{
tcs.SetResult(await work().ConfigureAwait(true));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
tcs.SetException(ex);
}
finally
{
dispatcher.InvokeShutdown();
}
});
#pragma warning restore VSTHRD001
System.Windows.Threading.Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
return tcs.Task;
}
[Fact]
public async Task EscapeClosesTheOpenDialogWithNoResult()
{
(ContentDialogResult Result, bool EmptyHost) outcome = await OnDispatcherAsync(async () =>
{
var host = new ContentDialogHost();
bool closedNothing = !DialogKeyboard.CloseOpenDialog(host);
var dialog = new ContentDialog(host) { Title = "t", PrimaryButtonText = "accept", CloseButtonText = "close" };
Task<ContentDialogResult> shown = dialog.ShowAsync();
DialogKeyboard.CloseOpenDialog(host).Should().BeTrue();
ContentDialogResult result = await shown.ConfigureAwait(true);
// WPF UI's CloseButtonText defaults to "Close"; a dialog without one says so with an empty text.
var answerOnly = new ContentDialog(host) { Title = "t", PrimaryButtonText = "accept", CloseButtonText = string.Empty };
Task<ContentDialogResult> mustAnswer = answerOnly.ShowAsync();
DialogKeyboard.CloseOpenDialog(host).Should().BeFalse("a dialog with no Close button is not dismissed by Esc");
answerOnly.Hide(ContentDialogResult.Primary);
(await mustAnswer.ConfigureAwait(true)).Should().Be(ContentDialogResult.Primary);
return (result, closedNothing);
});
outcome.Result.Should().Be(ContentDialogResult.None, "Esc is the Close button, never the primary one — the consent dialog and the Legal Gate read None as a refusal");
outcome.EmptyHost.Should().BeTrue("with no dialog open, Esc is left to whoever else wants it");
}
}
@@ -47,7 +47,7 @@ public sealed class BugBundleBuilderTests : IDisposable
await settings.SetAsync(SettingsRegistry.HookingKillSwitch, true, Ct);
string zip = Path.Combine(_dir, "bundle.zip");
IReadOnlyList<string> written = await new BugBundleBuilder(_dir, settings, clock).WriteAsync(zip, agent: null, Ct);
IReadOnlyList<string> written = await new BugBundleBuilder(_dir, settings, clock).WriteAsync(zip, agent: null, ct: Ct);
written.Should().Contain(["logs/ui-20260914.log", "logs/agent-20260914.log", "sysinfo.json", "settings.json"]);
written.Should().NotContain("logs/ui-20260901.log", "older than seven days");
@@ -71,7 +71,7 @@ public sealed class BugBundleBuilderTests : IDisposable
string zip = Path.Combine(_dir, "bundle.zip");
var hello = new HelloAck("1.2.3", IpcProtocol.Version, 4, true, "build-x", true, "l3", true, "consent-dialog/1");
await new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))).WriteAsync(zip, hello, Ct);
await new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db))).WriteAsync(zip, hello, ct: Ct);
Dictionary<string, string> sysinfo = ReadJson(zip, "sysinfo.json");
sysinfo["agent_version"].Should().Be("1.2.3");
@@ -80,12 +80,99 @@ public sealed class BugBundleBuilderTests : IDisposable
sysinfo["telemetry_source"].Should().Be("l3");
}
[Fact]
public async Task TheLogCopiesCarryNoUserNameAndTheFilesOnDiskAreUntouched()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var clock = new FixedClock(new DateTimeOffset(2026, 9, 15, 12, 0, 0, TimeSpan.Zero));
DateTime now = clock.GetUtcNow().UtcDateTime;
string ui = Path.Combine(_dir, "ui-20260915.log");
await File.WriteAllTextAsync(ui, "[12:00:00.000 INF] ui: started (0.1.0), ledger C:\\Users\\tester\\AppData\\Local\\FrameLedger\\ledger.db {\"Path\":\"C:\\\\Users\\\\tester\\\\AppData\"}\r\n", Ct);
File.SetLastWriteTimeUtc(ui, now);
string overlay = Path.Combine(_dir, "overlay-4242-20260915-120000.log");
await File.WriteAllTextAsync(overlay, "# FrameLedger.Overlay build x pid 4242 layout v9 image C:\\Users\\tester\\Games\\title.exe\nSTOP\n", Ct);
File.SetLastWriteTimeUtc(overlay, now);
string zip = Path.Combine(_dir, "bundle.zip");
await new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db)), clock, redactor: new LogRedactor(@"C:\Users\tester")).WriteAsync(zip, agent: null, ct: Ct);
string uiCopy = ReadEntry(zip, "logs/ui-20260915.log");
string overlayCopy = ReadEntry(zip, "overlay/overlay-4242-20260915-120000.log");
uiCopy.Should().NotContain("tester").And.Contain(@"C:\Users\<user>\AppData\Local\FrameLedger\ledger.db").And.Contain(@"C:\\Users\\<user>\\AppData");
overlayCopy.Should().NotContain("tester").And.StartWith(@"# FrameLedger.Overlay build x pid 4242 layout v9 image C:\Users\<user>\Games\title.exe");
(await File.ReadAllTextAsync(ui, Ct)).Should().Contain("tester", "the redaction is the bundle's copy, never the log on disk");
}
[Fact]
public void TheSuggestedNameIsTheDocsFormat()
{
BugBundleBuilder.SuggestedName(new DateTimeOffset(2026, 9, 14, 12, 34, 0, TimeSpan.Zero).ToLocalTime()).Should().MatchRegex(@"^FrameLedger-bugreport-\d{8}-\d{4}\.zip$");
}
[Fact]
public async Task TheCrashDumpGoesInOnlyWhenPassedAndOnlyFromTheDumpDirectory()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var clock = new FixedClock(new DateTimeOffset(2026, 9, 15, 12, 0, 0, TimeSpan.Zero));
string dumps = Path.Combine(_dir, "crashdumps");
string dump = WriteDump(dumps, "ui-20260915-100000-42.dmp", clock.GetUtcNow().UtcDateTime.AddHours(-2), bytes: 3000);
var builder = new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db)), clock, dumps);
CrashDumpInfo latest = builder.LatestCrashDump()!;
latest.Path.Should().Be(dump);
latest.Bytes.Should().Be(3000);
IReadOnlyList<string> without = await builder.WriteAsync(Path.Combine(_dir, "without.zip"), agent: null, ct: Ct);
IReadOnlyList<string> with = await builder.WriteAsync(Path.Combine(_dir, "with.zip"), agent: null, latest, Ct);
without.Should().NotContain(static e => e.StartsWith("crashdumps/", StringComparison.Ordinal), "a dump goes in only when the user ticked it");
with.Should().Contain("crashdumps/ui-20260915-100000-42.dmp");
string foreign = Path.Combine(_dir, "game.dmp");
await File.WriteAllTextAsync(foreign, "MDMP", Ct);
Func<Task> outside = () => builder.WriteAsync(Path.Combine(_dir, "foreign.zip"), agent: null, latest with { Path = foreign }, Ct);
await outside.Should().ThrowAsync<ArgumentException>("the bundle never carries a file from outside the dump directory");
File.Exists(Path.Combine(_dir, "foreign.zip")).Should().BeFalse("refused before the zip is created");
}
[Fact]
public async Task TheOfferedDumpIsTheNewestOfTheLastSevenDays()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var settings = new RegisteredSettings(new SqliteSettingsStore(s.Db));
var clock = new FixedClock(new DateTimeOffset(2026, 9, 15, 12, 0, 0, TimeSpan.Zero));
DateTime now = clock.GetUtcNow().UtcDateTime;
string dumps = Path.Combine(_dir, "crashdumps");
new BugBundleBuilder(_dir, settings, clock).LatestCrashDump().Should().BeNull("no dump directory was given");
new BugBundleBuilder(_dir, settings, clock, dumps).LatestCrashDump().Should().BeNull("the directory does not exist yet");
WriteDump(dumps, "ui-old.dmp", now.AddDays(-8), bytes: 10);
new BugBundleBuilder(_dir, settings, clock, dumps).LatestCrashDump().Should().BeNull("older than seven days");
WriteDump(dumps, "agent-older.dmp", now.AddDays(-2), bytes: 20);
WriteDump(dumps, "ui-newest.dmp", now.AddHours(-1), bytes: 30);
WriteDump(dumps, "ui-notes.txt", now, bytes: 40);
CrashDumpInfo? latest = new BugBundleBuilder(_dir, settings, clock, dumps).LatestCrashDump();
latest.Should().NotBeNull();
Path.GetFileName(latest!.Path).Should().Be("ui-newest.dmp", "the newest dump of either process; a .txt is not a dump");
latest.WrittenAt.Should().Be(new DateTimeOffset(now.AddHours(-1), TimeSpan.Zero));
latest.Bytes.Should().Be(30);
}
private static string WriteDump(string directory, string name, DateTime mtimeUtc, int bytes)
{
Directory.CreateDirectory(directory);
string path = Path.Combine(directory, name);
File.WriteAllBytes(path, new byte[bytes]);
File.SetLastWriteTimeUtc(path, mtimeUtc);
return path;
}
private static string ReadEntry(string zip, string entry)
{
using ZipArchive archive = ZipFile.OpenRead(zip);
using var reader = new StreamReader(archive.GetEntry(entry)!.Open());
return reader.ReadToEnd();
}
private static Dictionary<string, string> ReadJson(string zip, string entry)
{
using ZipArchive archive = ZipFile.OpenRead(zip);
@@ -0,0 +1,27 @@
using System.Globalization;
using FluentAssertions;
using FrameLedger.App.Services;
using FrameLedger.App.ViewModels;
namespace FrameLedger.App.Tests;
/// <summary>
/// The bug report's optional crash dump (P4 PR-9): the box starts clear (<c>legal/PRIVACY_POLICY.md</c> §3, only when
/// ticked), closing the dialog never includes it, and the label carries the dump's size.
/// </summary>
public sealed class BugBundleOptionsViewModelTests
{
[Fact]
public void TheBoxStartsClearAndOnlyATickAndContinueIncludesTheDump()
{
var vm = new BugBundleOptionsViewModel(new CrashDumpInfo(@"C:\data\crashdumps\ui-1.dmp", new DateTimeOffset(2026, 9, 15, 1, 2, 3, TimeSpan.Zero), 1536 * 1024));
vm.IncludeCrashDump.Should().BeFalse();
vm.Choice(continued: true).Should().Be(CrashDumpChoice.LeaveOut);
vm.Choice(continued: false).Should().Be(CrashDumpChoice.Cancel);
vm.IncludeCrashDump = true;
vm.Choice(continued: true).Should().Be(CrashDumpChoice.Include);
vm.Choice(continued: false).Should().Be(CrashDumpChoice.Cancel, "closing the dialog never includes the dump");
vm.DumpLabel.Should().Contain(string.Format(CultureInfo.CurrentCulture, "{0:0.0}", 1.5), "the size is in the label, in MB");
}
}
@@ -41,12 +41,12 @@ public sealed class BugReportFlowTests : IDisposable
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)
private async Task<Harness> BuildAsync(ScratchLedger s, BugReportChoice choice, bool cancel = false, CrashDumpChoice dumpChoice = CrashDumpChoice.LeaveOut)
{
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)));
var builder = new BugBundleBuilder(_dir, new RegisteredSettings(new SqliteSettingsStore(s.Db)), crashDumpDirectory: Path.Combine(_dir, "crashdumps"));
string zip = Path.Combine(_dir, "bundle.zip");
var preview = new ClosePreview(choice);
var preview = new ClosePreview(choice, dumpChoice);
var urls = new NoUrlOpener();
var clipboard = new NoClipboard();
var strip = new RecordingStrip();
@@ -77,6 +77,57 @@ public sealed class BugReportFlowTests : IDisposable
.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");
h.Preview.DumpsOffered.Should().BeEmpty("no crash dump, no question");
}
[Theory]
[InlineData(CrashDumpChoice.LeaveOut, false)]
[InlineData(CrashDumpChoice.Include, true)]
public async Task ARecentCrashDumpIsOfferedAndGoesInOnlyWhenTicked(CrashDumpChoice answer, bool included)
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
string dump = WriteDump();
Harness h = await BuildAsync(s, BugReportChoice.Close, dumpChoice: answer);
BugReportOutcome o = await h.Flow.RunAsync(Ct);
o.Written.Should().BeTrue();
h.Preview.DumpsOffered.Should().ContainSingle().Which.Path.Should().Be(dump);
IReadOnlyList<string> entries = h.Preview.Shown.Should().ContainSingle().Subject.Entries;
string entry = "crashdumps/" + Path.GetFileName(dump);
if (included)
{
entries.Should().Contain(entry);
}
else
{
entries.Should().NotContain(entry, "the box starts clear and was left so");
}
}
[Fact]
public async Task ClosingTheCrashDumpQuestionWritesNothing()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
WriteDump();
Harness h = await BuildAsync(s, BugReportChoice.OpenIssue, dumpChoice: CrashDumpChoice.Cancel);
BugReportOutcome o = await h.Flow.RunAsync(Ct);
o.Written.Should().BeFalse();
o.ZipPath.Should().BeNull();
File.Exists(h.Zip).Should().BeFalse("the question comes before the save dialog");
h.Preview.Shown.Should().BeEmpty();
h.Urls.Opened.Should().BeEmpty();
}
private string WriteDump()
{
string dumps = Path.Combine(_dir, "crashdumps");
Directory.CreateDirectory(dumps);
string path = Path.Combine(dumps, "ui-20260915-010203-42.dmp");
File.WriteAllBytes(path, "MDMP"u8.ToArray());
return path;
}
[Fact]
+13 -2
View File
@@ -2,14 +2,25 @@ 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
/// <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. The crash dump question (P4 PR-9) answers <paramref name="dumpChoice"/> and records each offer.
/// </summary>
internal sealed class ClosePreview(BugReportChoice choice = BugReportChoice.Close, CrashDumpChoice dumpChoice = CrashDumpChoice.LeaveOut) : IBugReportPreview
{
public List<BugReportPreviewModel> Shown { get; } = [];
public List<CrashDumpInfo> DumpsOffered { get; } = [];
public Task<BugReportChoice> ShowAsync(BugReportPreviewModel model, CancellationToken ct = default)
{
Shown.Add(model);
return Task.FromResult(choice);
}
public Task<CrashDumpChoice> AskCrashDumpAsync(CrashDumpInfo dump, CancellationToken ct = default)
{
DumpsOffered.Add(dump);
return Task.FromResult(dumpChoice);
}
}
@@ -0,0 +1,114 @@
using System.IO;
using FluentAssertions;
using FrameLedger.App.Services;
namespace FrameLedger.App.Tests;
/// <summary>
/// <c>10_LOGGING</c> §Crash handling in the App (P4 PR-9): the dump before the dialog, the report only on yes, one dialog
/// however many exceptions follow, and neither a failed dump nor a failed report becoming a second crash.
/// </summary>
public sealed class CrashReporterTests
{
private sealed class Script
{
public List<string> Steps { get; } = [];
public string? Dump { get; init; } = @"C:\data\crashdumps\ui-20260915-010203-42.dmp";
public bool Yes { get; init; } = true;
public Func<Task>? Report { get; init; }
public CrashReporter Build() => new(
() =>
{
Steps.Add("dump");
return Dump;
},
dump =>
{
Steps.Add("ask:" + (dump ?? "none"));
return Yes;
},
() =>
{
Steps.Add("report");
return Report?.Invoke() ?? Task.CompletedTask;
});
}
[Fact]
public async Task TheFirstExceptionIsDumpedThenAskedThenReported()
{
var script = new Script();
CrashReporter reporter = script.Build();
reporter.Crashed.Should().BeFalse();
bool reported = await reporter.HandleAsync(new InvalidOperationException("boom"), "Dispatcher");
reported.Should().BeTrue();
reporter.Crashed.Should().BeTrue("the caller exits with code 1");
script.Steps.Should().Equal("dump", @"ask:C:\data\crashdumps\ui-20260915-010203-42.dmp", "report");
}
[Fact]
public async Task NoMeansNoReportAndTheExitCodeIsStillOne()
{
var script = new Script { Yes = false };
CrashReporter reporter = script.Build();
(await reporter.HandleAsync(new InvalidOperationException("boom"), "Dispatcher")).Should().BeTrue();
script.Steps.Should().Equal("dump", @"ask:C:\data\crashdumps\ui-20260915-010203-42.dmp");
reporter.Crashed.Should().BeTrue();
}
[Fact]
public async Task FurtherExceptionsWhileTheFirstIsReportedShowNothingAndAreCounted()
{
using var gate = new SemaphoreSlim(0);
var script = new Script { Report = () => gate.WaitAsync(TestContext.Current.CancellationToken) };
CrashReporter reporter = script.Build();
Task<bool> first = reporter.HandleAsync(new InvalidOperationException("layout"), "Dispatcher");
for (int i = 0; i < 3; i++)
{
(await reporter.HandleAsync(new InvalidOperationException("layout again"), "Dispatcher")).Should().BeFalse("a dialog loop over a broken dispatcher is what this prevents");
}
gate.Release();
(await first).Should().BeTrue();
script.Steps.Should().Equal("dump", @"ask:C:\data\crashdumps\ui-20260915-010203-42.dmp", "report");
reporter.FurtherExceptions.Should().Be(3);
}
[Fact]
public async Task AFailedDumpStillAsksAndAFailedReportIsNotASecondCrash()
{
var steps = new List<string>();
var reporter = new CrashReporter(
() => throw new IOException("disk full"),
dump =>
{
steps.Add("ask:" + (dump ?? "none"));
return true;
},
() => throw new InvalidOperationException("no dialog host"));
Func<Task<bool>> handle = () => reporter.HandleAsync(new InvalidOperationException("boom"), "Dispatcher");
(await handle.Should().NotThrowAsync()).Which.Should().BeTrue();
steps.Should().Equal("ask:none");
}
[Fact]
public void TheDialogSaysWhereTheDumpIsOrThatThereIsNone()
{
const string dump = @"C:\data\crashdumps\ui-20260915-010203-42.dmp";
CrashDialog.Body(dump).Should().Contain(dump).And.NotContain(Strings.Crash_NoDump);
CrashDialog.Body(null).Should().Contain(Strings.Crash_NoDump);
CrashDialog.Body(null).Should().NotContain("{0}", "both formats are filled");
}
}
@@ -0,0 +1,60 @@
using System.Text;
using FluentAssertions;
using FrameLedger.App.Services;
namespace FrameLedger.App.Tests;
/// <summary>
/// <c>legal/PRIVACY_POLICY.md</c> §3 (P4 follow-up, 2026-09-15): a user name in a path never leaves the machine in a log
/// copy, in any spelling a log carries, and nothing else in the file changes.
/// </summary>
public sealed class LogRedactorTests
{
private static readonly LogRedactor _redactor = new(@"C:\Users\kuujo");
[Theory]
[InlineData(@"ledger C:\Users\kuujo\AppData\Local\FrameLedger\ledger.db", @"ledger C:\Users\<user>\AppData\Local\FrameLedger\ledger.db")]
[InlineData(@"{""Path"":""C:\\Users\\kuujo\\AppData\\Local""}", @"{""Path"":""C:\\Users\\<user>\\AppData\\Local""}")]
[InlineData("file:///c:/users/KUUJO/Documents/x.txt", "file:///c:/users/<user>/Documents/x.txt")]
[InlineData(@"C:\Users\John Smith\Documents", @"C:\Users\<user>\Documents")]
[InlineData(@"'C:\Users\kuujo'", @"'C:\Users\<user>'")]
[InlineData("profile C:\\Users\\kuujo\r\nnext", "profile C:\\Users\\<user>\r\nnext")]
[InlineData(@"image C:\Users\Nguy?n\Games\title.exe", @"image C:\Users\<user>\Games\title.exe")]
[InlineData(@"two C:\Users\a\x and D:\Users\b\y", @"two C:\Users\<user>\x and D:\Users\<user>\y")]
public void TheNameInAUsersPathBecomesThePlaceholderInEverySpelling(string log, string expected)
{
_redactor.Redact(log).Should().Be(expected);
_redactor.Redact(_redactor.Redact(log)).Should().Be(expected, "redacting a copy twice changes nothing more");
}
[Theory]
[InlineData(@"C:\Program Files\FrameLedger\FrameLedger.exe")]
[InlineData(@"D:\Games\Users\title.exe")]
[InlineData(@"C:\Userspace\x")]
[InlineData("Users: 3, sessions: 12")]
[InlineData(@"C:\Users\")]
public void TextThatNamesNoUserIsUnchanged(string log) => _redactor.Redact(log).Should().Be(log);
[Fact]
public void AProfileOutsideTheUsersFolderIsRedactedByItsOwnPath()
{
var redirected = new LogRedactor(@"D:\Profiles\kuujo");
redirected.Redact(@"ledger D:\Profiles\kuujo\AppData\Local\FrameLedger\ledger.db").Should().Be(@"ledger D:\Profiles\<user>\AppData\Local\FrameLedger\ledger.db");
redirected.Redact(@"{""P"":""d:\\profiles\\KUUJO\\x""}").Should().Be(@"{""P"":""d:\\profiles\\<user>\\x""}");
redirected.Redact(@"D:\Profiles\kuujo2\x").Should().Be(@"D:\Profiles\kuujo2\x", "another folder that merely starts with the name");
new LogRedactor(null).Redact(@"D:\Profiles\kuujo\x").Should().Be(@"D:\Profiles\kuujo\x", "without a profile only X:\\Users paths are known");
}
[Fact]
public void BytesOutsideTheNamesAreKeptExactlyInUtf8AndInAnsi()
{
byte[] utf8 = Encoding.UTF8.GetBytes("[12:00:00.000 INF] Thiết lập đã lưu C:\\Users\\Nguyễn\\AppData\r\n");
byte[] expectedUtf8 = Encoding.UTF8.GetBytes("[12:00:00.000 INF] Thiết lập đã lưu C:\\Users\\<user>\\AppData\r\n");
byte[] ansi = [.. Encoding.ASCII.GetBytes("# image C:\\Users\\Jos"), 0xE9, .. Encoding.ASCII.GetBytes("\\Games\\t.exe\n")];
byte[] expectedAnsi = Encoding.ASCII.GetBytes("# image C:\\Users\\<user>\\Games\\t.exe\n");
_redactor.Redact(utf8).Should().Equal(expectedUtf8);
_redactor.Redact(ansi).Should().Equal(expectedAnsi);
}
}
+24 -8
View File
@@ -243,14 +243,6 @@ public sealed class PagesLoadTests
element.UpdateLayout();
}
/// <summary>
/// WPF UI 4.3.0's <c>InfoBar</c> template has no <c>ContentPresenter</c>, so the action button 08_UI
/// §Notifications policy puts on every persistent banner — the one dismissal of a safety notice, since the X is
/// off by design — was never rendered: a refusal was a red bar nobody could close. <c>Styles/FrameLedger.xaml</c>
/// re-templates the control with the presenter. Both halves are asserted: the app's template renders the
/// Content, the library's does not — so this turns red the day upstream renders it, which is the day the
/// override comes out rather than staying by habit.
/// </summary>
/// <summary>Tools ▸ Database maintenance's dialog body (P4 PR-7) under the real dictionaries: its icons, the converter key, every binding.</summary>
[Fact]
public async Task TheDatabaseMaintenanceDialogLoads()
@@ -275,6 +267,30 @@ public sealed class PagesLoadTests
public Task<bool> ConfirmSweepAsync(int keep, CancellationToken ct = default) => Task.FromResult(false);
}
/// <summary>The bug report's optional crash dump (P4 PR-9) under the real dictionaries: the checkbox and both texts bind.</summary>
[Fact]
public async Task TheBundleOptionsDialogLoads()
{
var vm = new BugBundleOptionsViewModel(new CrashDumpInfo(@"C:\data\crashdumps\ui-20260915-010203-42.dmp", DateTimeOffset.UtcNow, 2 * 1024 * 1024));
double width = await OnStaAsync(() =>
{
var content = new Dialogs.BugBundleOptionsContent(vm);
Render(content);
return content.ActualWidth;
});
width.Should().BeGreaterThan(0);
}
/// <summary>
/// WPF UI 4.3.0's <c>InfoBar</c> template has no <c>ContentPresenter</c>, so the action button 08_UI
/// §Notifications policy puts on every persistent banner — the one dismissal of a safety notice, since the X is
/// off by design — was never rendered: a refusal was a red bar nobody could close. <c>Styles/FrameLedger.xaml</c>
/// re-templates the control with the presenter. Both halves are asserted: the app's template renders the
/// Content, the library's does not — so this turns red the day upstream renders it, which is the day the
/// override comes out rather than staying by habit.
/// </summary>
[Fact]
public async Task TheInfoBarTemplateRendersItsContent()
{
@@ -0,0 +1,82 @@
using FluentAssertions;
using FrameLedger.Infrastructure.Diagnostics;
namespace FrameLedger.Infrastructure.Tests.Diagnostics;
/// <summary>
/// <c>10_LOGGING</c> §Crash handling's minidump (P4 PR-9): a real <c>MiniDumpWriteDump</c> of this test process under the
/// directory, named in the invariant culture; the newest five kept and nothing else touched; a directory that cannot be
/// used is a null path and a line, never an exception on a crash path.
/// </summary>
public sealed class CrashDumpWriterTests : IDisposable
{
private static readonly string[] _fiveNewest = ["ui-0.dmp", "ui-1.dmp", "ui-2.dmp", "ui-3.dmp", "ui-4.dmp"];
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-dumps-" + Guid.NewGuid().ToString("N"));
public void Dispose()
{
if (Directory.Exists(_dir))
{
Directory.Delete(_dir, recursive: true);
}
}
[Fact]
public void WritesAMinidumpOfThisProcessNamedByProcessUtcTimeAndPid()
{
var lines = new List<string>();
var now = new DateTimeOffset(2026, 9, 15, 1, 2, 3, TimeSpan.FromHours(7));
string? path = CrashDumpWriter.TryWrite(_dir, "test", now, lines.Add);
path.Should().NotBeNull("MiniDumpWriteDump of our own process succeeds: {0}", string.Join(" | ", lines));
Path.GetFileName(path).Should().Be($"test-20260914-180203-{Environment.ProcessId}.dmp", "the name carries the UTC time");
Path.GetDirectoryName(path).Should().Be(_dir);
byte[] head = new byte[4];
using (var file = new FileStream(path!, FileMode.Open, FileAccess.Read, FileShare.Read))
{
file.ReadExactly(head);
}
head.Should().Equal("MDMP"u8.ToArray(), "a minidump starts with its signature");
lines.Should().BeEmpty();
}
[Fact]
public void PruneKeepsTheFiveNewestDumpsAndNothingElseIsTouched()
{
Directory.CreateDirectory(_dir);
DateTime now = DateTime.UtcNow;
for (int i = 0; i < CrashDumpWriter.Kept + 2; i++)
{
string dump = Path.Combine(_dir, $"ui-{i}.dmp");
File.WriteAllText(dump, "MDMP");
File.SetLastWriteTimeUtc(dump, now.AddMinutes(-i));
}
string notes = Path.Combine(_dir, "notes.txt");
File.WriteAllText(notes, "not a dump");
File.SetLastWriteTimeUtc(notes, now.AddDays(-30));
CrashDumpWriter.Prune(_dir);
Directory.EnumerateFiles(_dir, "*.dmp").Select(Path.GetFileName).Should().BeEquivalentTo(_fiveNewest);
File.Exists(notes).Should().BeTrue("the prune reads *.dmp only");
}
[Fact]
public void ADirectoryThatCannotBeUsedIsNullAndALineNotAnException()
{
Directory.CreateDirectory(_dir);
string occupied = Path.Combine(_dir, "crashdumps");
File.WriteAllText(occupied, "a file where the directory should be");
var lines = new List<string>();
string? path = CrashDumpWriter.TryWrite(occupied, "ui", DateTimeOffset.UtcNow, lines.Add);
path.Should().BeNull();
lines.Should().ContainSingle().Which.Should().StartWith("crash dump: not written");
CrashDumpWriter.Prune(Path.Combine(_dir, "absent"));
}
}
@@ -0,0 +1,69 @@
using FluentAssertions;
using FrameLedger.Testing;
namespace FrameLedger.Infrastructure.Tests;
/// <summary>
/// The assembly-end sweep of the hook-harness's overlay logs (<c>17_HOOK_ENGINE</c> §Native logging): it removes this
/// assembly's harness logs from the run, and never a game's log, another assembly's harness log, or an earlier run's.
/// </summary>
public sealed class HarnessOverlayLogSweepTests : IDisposable
{
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-sweep-" + Guid.NewGuid().ToString("N"));
public HarnessOverlayLogSweepTests() => Directory.CreateDirectory(_dir);
public void Dispose() => Directory.Delete(_dir, recursive: true);
[Fact]
public void RemovesThisAssemblysHarnessLogsFromTheRunAndNothingElse()
{
DateTime since = DateTime.UtcNow.AddSeconds(-1);
string bin = Path.Combine(_dir, "bin");
string copies = Path.Combine(_dir, "copies");
string[] owned = [bin, copies];
string ours = Plant("overlay-101-20260915-010101.log", Path.Combine(bin, "hook-harness.exe"));
string ourCopy = Plant("overlay-102-20260915-010101.log", Path.Combine(copies, "HOOK-HARNESS-abc.exe"));
string otherAssembly = Plant("overlay-103-20260915-010101.log", @"C:\elsewhere\bin\hook-harness.exe");
string game = Plant("overlay-104-20260915-010101.log", Path.Combine(bin, "title.exe"));
string earlier = Plant("overlay-105-19990101-000000.log", Path.Combine(bin, "hook-harness.exe"));
File.SetCreationTimeUtc(earlier, new DateTime(1999, 1, 1, 0, 0, 0, DateTimeKind.Utc));
string stranger = Path.Combine(_dir, "overlay-106-20260915-010101.log");
File.WriteAllText(stranger, "# a file that is not an overlay log\r\n");
string agent = Path.Combine(_dir, "agent-20260915.log");
File.WriteAllText(agent, Header(Path.Combine(bin, "hook-harness.exe")));
(int removed, int kept) = HarnessOverlayLogSweep.Sweep(_dir, since, image => HarnessOverlayLogSweep.IsHarnessUnder(image, owned));
removed.Should().Be(2);
kept.Should().Be(3, "another assembly's harness, a game and a stranger were created in the window and left");
File.Exists(ours).Should().BeFalse();
File.Exists(ourCopy).Should().BeFalse("a copy under a registered directory is ours, whatever its case");
File.Exists(otherAssembly).Should().BeTrue("a parallel assembly may still read its own log");
File.Exists(game).Should().BeTrue("a game's log is never a test's to remove");
File.Exists(earlier).Should().BeTrue("a log from an earlier run is the owner's");
File.Exists(stranger).Should().BeTrue();
File.Exists(agent).Should().BeTrue("only overlay-*.log is read");
}
[Fact]
public void TheHeaderImageIsReadFromTheOverlaysOwnFirstLine()
{
HarnessOverlayLogSweep.OverlayLogImage(@"# FrameLedger.Overlay build 1a2b pid 42 layout v9 image C:\x\hook-harness.exe" + "\r").Should().Be(@"C:\x\hook-harness.exe");
HarnessOverlayLogSweep.OverlayLogImage("# a stale log planted by guard_test").Should().BeNull();
HarnessOverlayLogSweep.OverlayLogImage(null).Should().BeNull();
HarnessOverlayLogSweep.IsHarnessUnder(@"C:\x\bin\hook-harness.exe", [@"C:/x/bin/"]).Should().BeTrue("separators and a trailing one do not matter");
HarnessOverlayLogSweep.IsHarnessUnder(@"C:\x\binary\hook-harness.exe", [@"C:\x\bin"]).Should().BeFalse("a sibling directory is not under it");
HarnessOverlayLogSweep.IsHarnessUnder(@"C:\x\bin\game.exe", [@"C:\x\bin"]).Should().BeFalse();
HarnessOverlayLogSweep.RealLogsDirectory.Should().EndWith(Path.Combine("FrameLedger", "logs"));
}
private static string Header(string image) => "# FrameLedger.Overlay build test pid 101 layout v9 image " + image + "\n";
private string Plant(string name, string image)
{
string path = Path.Combine(_dir, name);
File.WriteAllText(path, Header(image) + "RING_CREATED\n");
return path;
}
}
+147
View File
@@ -0,0 +1,147 @@
using System.Diagnostics.CodeAnalysis;
using System.Text;
[assembly: AssemblyFixture(typeof(FrameLedger.Testing.HarnessOverlayLogSweep))]
namespace FrameLedger.Testing;
/// <summary>
/// The hook-harness's overlay logs, removed when this test assembly finishes (<c>17_HOOK_ENGINE</c> §Native logging).
/// </summary>
/// <remarks>
/// The Overlay writes <c>%LOCALAPPDATA%\FrameLedger\logs\overlay-&lt;pid&gt;-&lt;stamp&gt;.log</c>: the real data folder,
/// resolved by the shell and deliberately not by the environment (§S21), and the injection tests use the shipped Overlay,
/// so no test can point it elsewhere. Measured 2026-09-15, that folder held 2506 overlay logs, 2492 of them hook-harness's.
/// <c>FrameLedger.DrainFixtures.targets</c> compiles this file into every test project that stages hook-harness, and at the
/// end of the assembly it removes exactly what the assembly caused: an overlay log created after the assembly started
/// whose first line names a hook-harness image this assembly owns — the copy beside its binary, or a copy under a
/// directory a test registered with <see cref="Own"/>. Test assemblies run in parallel with their own copies, so one
/// never removes a log another is about to read. A game's log names the game; a log from an earlier run predates the
/// start and stays.
/// </remarks>
[SuppressMessage("Performance", "CA1812:Avoid uninstantiated internal classes", Justification = "xUnit creates the assembly fixture by reflection")]
internal sealed class HarnessOverlayLogSweep : IDisposable
{
private static readonly Lock _gate = new();
private static readonly List<string> _owned = [];
private readonly DateTime _startedUtc = DateTime.UtcNow;
/// <summary>The Overlay's log directory, resolved the way the Overlay resolves it (the shell's Local AppData).</summary>
public static string RealLogsDirectory =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FrameLedger", "logs");
/// <summary>Registers a directory a test copies hook-harness into, so the copy's logs are this assembly's too.</summary>
public static void Own(string directory)
{
ArgumentException.ThrowIfNullOrWhiteSpace(directory);
lock (_gate)
{
_owned.Add(Path.GetFullPath(directory));
}
}
public void Dispose()
{
string[] owned;
lock (_gate)
{
owned = [AppContext.BaseDirectory, .. _owned];
}
_ = Sweep(RealLogsDirectory, _startedUtc, image => IsHarnessUnder(image, owned));
}
/// <summary>
/// Removes each <c>overlay-*.log</c> directly under <paramref name="logsDirectory"/> created at or after
/// <paramref name="sinceUtc"/> whose header image <paramref name="isOurs"/> accepts. Everything else stays.
/// </summary>
/// <returns>How many were removed, and how many created in the window were left (not ours, or in use).</returns>
public static (int Removed, int Kept) Sweep(string logsDirectory, DateTime sinceUtc, Func<string, bool> isOurs)
{
ArgumentNullException.ThrowIfNull(isOurs);
if (!Directory.Exists(logsDirectory))
{
return (0, 0);
}
int removed = 0;
int kept = 0;
foreach (FileInfo log in new DirectoryInfo(logsDirectory).EnumerateFiles("overlay-*.log"))
{
if (log.CreationTimeUtc < sinceUtc)
{
continue;
}
string? image = OverlayLogImage(FirstLine(log.FullName));
if (image is null || !isOurs(image))
{
kept++;
continue;
}
try
{
log.Delete();
removed++;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
kept++;
}
}
return (removed, kept);
}
/// <summary>The image path of an Overlay log's first line (<c># FrameLedger.Overlay build … image &lt;path&gt;</c>), or null.</summary>
public static string? OverlayLogImage(string? firstLine)
{
const string prefix = "# FrameLedger.Overlay build ";
if (firstLine is null || !firstLine.StartsWith(prefix, StringComparison.Ordinal))
{
return null;
}
int at = firstLine.IndexOf(" image ", StringComparison.Ordinal);
if (at < 0)
{
return null;
}
string image = firstLine[(at + " image ".Length)..].TrimEnd('\r', '\n', ' ');
return image.Length == 0 ? null : image;
}
/// <summary>True for a <c>hook-harness*.exe</c> directly or deeper under one of <paramref name="directories"/>.</summary>
public static bool IsHarnessUnder(string image, IEnumerable<string> directories)
{
ArgumentNullException.ThrowIfNull(image);
ArgumentNullException.ThrowIfNull(directories);
string name = Path.GetFileName(image);
if (!name.StartsWith("hook-harness", StringComparison.OrdinalIgnoreCase) || !name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
return false;
}
string full = Normalised(image);
return directories.Any(directory => full.StartsWith(Normalised(directory) + "\\", StringComparison.OrdinalIgnoreCase));
}
private static string Normalised(string path) => path.Replace('/', '\\').TrimEnd('\\');
// The header's image comes from GetModuleFileNameA (the ANSI code page); Latin-1 reads its bytes without failing.
private static string? FirstLine(string path)
{
try
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
using var reader = new StreamReader(stream, Encoding.Latin1);
return reader.ReadLine();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return null;
}
}
}
+113
View File
@@ -0,0 +1,113 @@
#Requires -Version 7.0
<#
.SYNOPSIS
Fails when a test run left hook-harness overlay logs in the real FrameLedger data folder.
.DESCRIPTION
docs/17_HOOK_ENGINE.md §Native logging. The injection tests use the shipped Overlay, and the Overlay writes its log
to %LOCALAPPDATA%\FrameLedger\logs\overlay-<pid>-<stamp>.log: the real per-user data folder, by design (§S21, not a
parameter). Measured 2026-09-15, that folder held 2506 overlay logs, 2492 of them hook-harness's, left by test runs.
So every test binary that starts hook-harness removes, when its run ends, the logs it caused: the Catch2 listener in
src/native/tests/guard_test.cpp and tests/Shared/HarnessOverlayLogSweep.cs, which FrameLedger.DrainFixtures.targets
compiles into each managed test project that stages the harness. This gate is what makes a missing sweep red: an
overlay log created since the gate started whose first line names a hook-harness image, still there after the tests,
fails it. A game's log names the game and never counts; a log from before the gate never counts.
.PARAMETER SinceUtc
The gate's start. Only logs created at or after it count.
.PARAMETER LogsDirectory
The directory to read. Default: the Overlay's own, %LOCALAPPDATA%\FrameLedger\logs.
.PARAMETER SelfTest
Runs the fixture cases below, in scratch directories, and exits 0 only if every one behaves.
#>
[CmdletBinding()]
param(
[DateTime]$SinceUtc = [DateTime]::UtcNow,
[string]$LogsDirectory = (Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'FrameLedger\logs'),
[switch]$SelfTest
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
function Get-LeftHarnessLog {
param([string]$Directory, [DateTime]$Since)
$left = [System.Collections.Generic.List[string]]::new()
if (-not (Test-Path -LiteralPath $Directory -PathType Container)) { return , $left.ToArray() }
foreach ($file in Get-ChildItem -LiteralPath $Directory -Filter 'overlay-*.log' -File) {
if ($file.CreationTimeUtc -lt $Since) { continue }
$first = $null
try {
$stream = [IO.FileStream]::new($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]'ReadWrite, Delete')
try {
# The image comes from GetModuleFileNameA, in the ANSI code page; Latin-1 reads any byte.
$reader = [IO.StreamReader]::new($stream, [Text.Encoding]::Latin1)
$first = $reader.ReadLine()
}
finally { $stream.Dispose() }
}
catch [IO.IOException] { continue }
if ($null -eq $first) { continue }
$m = [regex]::Match($first, '^# FrameLedger\.Overlay build .*? image (?<image>.+?)\s*$', 'CultureInvariant')
if (-not $m.Success) { continue }
$image = $m.Groups['image'].Value
$name = [IO.Path]::GetFileName($image)
if ($name.StartsWith('hook-harness', [StringComparison]::OrdinalIgnoreCase)) {
$left.Add("$($file.Name) (image $image)")
}
}
return , $left.ToArray()
}
if ($SelfTest) {
$root = Join-Path ([IO.Path]::GetTempPath()) ('fl-artifacts-selftest-' + [guid]::NewGuid().ToString('N'))
$since = [DateTime]::UtcNow.AddSeconds(-1)
$header = '# FrameLedger.Overlay build test pid 101 layout v9 image '
$cases = @(
@{ Name = "a harness log created during the run FAILS"; File = 'overlay-1-20260915-010101.log'; Text = "${header}C:\build\tools\hook-harness\hook-harness.exe`nRING_CREATED`n"; Left = 1 },
@{ Name = "a renamed harness copy's log FAILS"; File = 'overlay-2-20260915-010101.log'; Text = "${header}C:\Temp\fl-pipe-e2e-1\HOOK-HARNESS-fl-pipe-e2e-1.exe`r`n"; Left = 1 },
@{ Name = "a game's log passes"; File = 'overlay-3-20260915-010101.log'; Text = "${header}D:\Games\Title\title.exe`n"; Left = 0 },
@{ Name = 'a harness log from before the run passes'; File = 'overlay-4-19990101-000000.log'; Text = "${header}C:\build\hook-harness.exe`n"; Old = $true; Left = 0 },
@{ Name = 'an overlay-named file with no Overlay header passes'; File = 'overlay-5-20260915-010101.log'; Text = "# planted by guard_test`n"; Left = 0 },
@{ Name = 'a non-overlay log with a harness header passes'; File = 'agent-20260915.log'; Text = "${header}C:\build\hook-harness.exe`n"; Left = 0 },
@{ Name = 'a directory that does not exist passes'; File = $null; Left = 0 }
)
$failed = 0
try {
$i = 0
foreach ($c in $cases) {
$i++
$dir = Join-Path $root "case$i"
if ($c.File) {
New-Item -ItemType Directory -Path $dir -Force | Out-Null
$path = Join-Path $dir $c.File
[IO.File]::WriteAllText($path, $c.Text)
if ($c.ContainsKey('Old')) { [IO.File]::SetCreationTimeUtc($path, [DateTime]::new(1999, 1, 1, 0, 0, 0, [DateTimeKind]::Utc)) }
}
$got = Get-LeftHarnessLog -Directory $dir -Since $since
$ok = $got.Count -eq $c.Left
Write-Host (" {0,-4} {1}" -f ($(if ($ok) { 'ok' } else { 'FAIL' })), $c.Name) -ForegroundColor ($(if ($ok) { 'DarkGray' } else { 'Red' }))
if (-not $ok) { $failed++ }
}
}
finally {
if (Test-Path -LiteralPath $root) { Remove-Item -LiteralPath $root -Recurse -Force }
}
if ($failed -gt 0) { Write-Host "test-artifacts self-test FAILED ($failed)" -ForegroundColor Red; exit 1 }
Write-Host "test-artifacts self-test: $($cases.Count) cases, both directions" -ForegroundColor Green
exit 0
}
$left = Get-LeftHarnessLog -Directory $LogsDirectory -Since $SinceUtc
if ($left.Count -gt 0) {
$left | Select-Object -First 20 | ForEach-Object { Write-Host " $_" -ForegroundColor Red }
if ($left.Count -gt 20) { Write-Host " ... and $($left.Count - 20) more" -ForegroundColor Red }
Write-Host ("test-artifacts: {0} hook-harness overlay log(s) created during this run are still in the data folder. A test binary that starts hook-harness is missing its sweep (17_HOOK_ENGINE §Native logging)." -f $left.Count) -ForegroundColor Red
exit 1
}
Write-Host 'test-artifacts: ok - no hook-harness overlay log from this run is left in the data folder' -ForegroundColor Green
exit 0