diff --git a/CHANGELOG.md b/CHANGELOG.md index bf9c8036..7900036d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,31 @@ GitHub release body, so a missing section will mean an empty release note. ### Added +- **P3 PR-2 — the first `.resx` family, its generator and its gate, and the App shell (2026-09-13).** + `src/FrameLedger.App/Strings.resx` + `.vi` + `.ja` (65 keys, `ja` machine-drafted and marked `review`), + `tools/resx-gen.ps1` writing the committed `Strings.Designer.cs` (the SDK-style WPF project runs no + `ResXFileCodeGenerator`), and `tools/resx-audit.ps1` as `build.ps1` step 15 — self-test (11 fixture + cases, both directions) then live: identifier keys, exact key sets across the three files, `Safety_*` + in `ja` marked `safety: human review required` with the English verbatim or `safety: reviewed by `, + the accessor current; a tree with no family is red. `09_I18N` §Translation workflow and §Safety-critical + strings, `12_BUILD` line 15, `13_CI_CD` and `CLAUDE.md` stop saying the tool does not exist. The App is a + Generic Host under `16_WPFUI_SYNTAX` §App bootstrap: `FluentWindow`, TitleBar with the Agent pill, the + Menu row (unbuilt items say so in a snackbar), NavigationView (Dashboard · Games · Compare · Logs, Settings + in the footer), the offline `InfoBar` with Retry, `SnackbarPresenter`, `ContentDialogHost`; theme + (Light/Dark/System with `SystemThemeWatcher`) and language (rebuilds the shell in the new culture) both + persisted in `settings` under D16's `ui.theme`/`ui.language` through `SqliteSettingsStore` — the App opens + `ledger.db` directly per `06_DATA_MODEL` §Writer ownership (D15). `Services.AgentConnection` is `07_IPC` + §Client behavior as a state machine over `PipeClient`: 8 × 250 ms connect, start `FrameLedger.Agent.exe + --serve` beside the App when absent, `Hello`/`GetStatus`, keepalive pings, the event stream, retry every + 5 s; the Dashboard's Agent card shows `HelloAck`/`StatusAck` with `N/A` until answered. Serilog + `logs/ui-.log` per `10_LOGGING`. `tests/FrameLedger.App.Tests` (16): every key resolves in en/vi/ja and + the satellites really load, the accessor's keys are the resx's, appearance settings round-trip, and the + connection against an in-process `PipeServer` — Missing with nothing to start, Connected on `Hello`, + Starting → Connected through a launcher that brings the server up, Offline then Connected again when it + returns. Measured: first window at 1.3 s. Three things `16_WPFUI` now records: `MainWindow` is transient + with `ShutdownMode=OnExplicitShutdown` and the host lifetime ending the process; the run is one task from + a synchronous `OnStartup`; and `ApplicationThemeManager.Apply(…, updateAccent: true)` must precede the + first window's XAML or the accent resources are missing at first Measure (`XamlParseException`). - **P3 PR-1b — the command pipe, command half: `SetWatchlist`, `LaunchGame`, `SetHookEnabled` (pre-scan, no stamp yet), pause/resume, `StopSession`, `UpdateRules`, `Shutdown` (2026-09-13).** `Application.Ipc.AgentCommandHandler` answers every UI → Agent row of `07_IPC` §Messages under the one rule of §The pipe is not a trust boundary — the diff --git a/CLAUDE.md b/CLAUDE.md index e69e8172..d87ae913 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -88,7 +88,11 @@ src/ # `--console` = the operator's verbs incl. `consent grant` (decision D4, # ConsentProvenance.AgentConsoleOperator) and `killswitch` (FR-2.4, # the gate's FOURTH input, decision D7). --data-dir under --console only. - FrameLedger.App/ # WPF UI + FrameLedger.App/ # WPF UI — the SHELL since 2026-09-13 (P3 PR-2): Generic Host, + # FluentWindow + TitleBar/Menu/NavigationView, theme + language + # persisted in `settings`, the Agent pill over the pipe (starts + # `FrameLedger.Agent.exe --serve` beside itself when absent), + # five pages of which four are empty states; Strings.resx en/vi/ja FrameLedger.CaptureHost/ # UNSHIPPED, and since P2 PR-C (2026-09-09) a THIN SHELL: verbs, # the operator disclosure, the report consumer, and the composition # of Application.Capture.CaptureSession over Infrastructure's @@ -108,7 +112,8 @@ tools/ # changelog-check, chokepoint-check, coverage-gat # rules-validate, vendor-exports, versioninfo-check, # vklayer-blastradius # (PowerShell). This line used to name three, one of which - # — resx-audit — does not exist. + # — resx-audit — ~~does not exist~~ exists since 2026-09-13 with + # resx-gen (the committed Strings.Designer.cs generator). # native tooling lives under src/native/tools: # fl-layout-dump -> struct offsets for the C# mirror test # hook-harness -> dummy D3D11 + D3D12 + Vulkan + OpenGL app diff --git a/FrameLedger.slnx b/FrameLedger.slnx index 64f6b287..b4928048 100644 --- a/FrameLedger.slnx +++ b/FrameLedger.slnx @@ -10,6 +10,7 @@ + diff --git a/build.ps1 b/build.ps1 index 2018afb3..be1a33d1 100644 --- a/build.ps1 +++ b/build.ps1 @@ -426,13 +426,17 @@ function Invoke-ProjectGates { Skip-Gate 'changelog-check' 'tools/changelog-check.ps1 not implemented yet' } + # 09_I18N's gate, built with the first .resx family (P3 PR-2, 2026-09-13): every key in en/vi/ja, ja + # Safety_* marked for human review, the generated accessor current. Self-test first (at least four + # cases must go red), then the live pass; a tree with no family is red, not skipped. Write-Step 'resx-audit' - $resxTool = Join-Path $repo 'tools/resx-audit' + $resxTool = Join-Path $repo 'tools/resx-audit.ps1' if (Test-Path $resxTool) { - Invoke-Checked 'resx-audit' { & $resxTool } + Invoke-Checked 'resx-audit (self-test)' { & $resxTool -SelfTest } + Invoke-Checked 'resx-audit' { & $resxTool -Root $repo } } else { - Skip-Gate 'resx-audit' 'tools/resx-audit not implemented yet (no .resx files exist)' + throw 'resx-audit: tools/resx-audit.ps1 is missing — 09_I18N names it and build.ps1 used to skip it loudly' } # The shared-memory struct mirror. CLAUDE.md §Struct mirroring calls this the diff --git a/docs/08_UI.md b/docs/08_UI.md index 0ee52e56..533ee423 100644 --- a/docs/08_UI.md +++ b/docs/08_UI.md @@ -28,6 +28,16 @@ WPF + **WPF UI (Wpf.Ui, Fluent)**. Shell = `ui:FluentWindow` with custom `ui:Tit The Menu sits in its own row **below** the TitleBar (never inside the drag region — 16 §Gotchas). +> **Built 2026-09-13 (P3 PR-2): the shell, and only the shell.** `FluentWindow`, the TitleBar with the +> Agent pill as trailing content, the Menu row (every item that a later slice builds says so in a 4 s +> snackbar rather than doing nothing), the NavigationView with the four items and Settings in the footer, +> the offline `InfoBar` with Retry, `SnackbarPresenter` and `ContentDialogHost`. The Dashboard shows the +> Agent status card (`HelloAck`/`StatusAck`, every value `N/A` until answered); Games, Compare and Logs +> are empty states; Settings has Appearance (theme + language, both persisted in `settings` — D16's +> `ui.theme`/`ui.language`). The App starts `FrameLedger.Agent.exe --serve` beside itself when the pipe +> is absent (`07_IPC` §Client behavior, 8 × 250 ms) and shows **Missing** when there is no Agent to start. +> Measured on the dev box: first window at 1.3 s from process start (NFR-4's 2 s). The tray is PR-8's. + **Tray (H.NotifyIcon):** icon states idle / ● capturing (T1 hooked) / ◐ recording only (T2 — nothing measured) / ⏸ paused; menu: Open, Pause/Resume capture, Agent status, Exit. Closing the window minimizes to tray when enabled. ## Notifications policy diff --git a/docs/09_I18N.md b/docs/09_I18N.md index 864914d0..5fb6b694 100644 --- a/docs/09_I18N.md +++ b/docs/09_I18N.md @@ -4,7 +4,7 @@ Languages: **en** (neutral/default) · **vi** · **ja**. Same `.resx` pattern as ## Mechanics -- One `Strings.resx` (+ `Strings.vi.resx`, `Strings.ja.resx`) per assembly that has user-visible text (`App`, `Shared` for error codes). Access through a generated strongly-typed class; **no string literals in XAML/C# for user-visible text** (analyzer TODO: Meziantou MA0011/manual review in PR checklist). +- One `Strings.resx` (+ `Strings.vi.resx`, `Strings.ja.resx`) per assembly that has user-visible text (`App`, `Shared` for error codes). Access through a generated strongly-typed class; **no string literals in XAML/C# for user-visible text** (analyzer TODO: Meziantou MA0011/manual review in PR checklist). **As built (P3 PR-2, 2026-09-13):** the class is `Strings.Designer.cs`, written by `tools/resx-gen.ps1 -Resx ` and **committed** — not the SDK's `ResXFileCodeGenerator`, which the SDK-style WPF project does not run — with `Culture`, `ResourceManager`, `Keys`, and one property per key; the audit below fails when it is stale. The first family is `src/FrameLedger.App/Strings.resx` (65 keys); `Shared`'s arrives with PR-4's `Safety_*` text, because an empty family is what the audit refuses. - XAML binding via `{x:Static res:Strings.Key}` plus a `LocalizeExtension` for the few dynamic cases. - **Runtime switching:** setting change → set `CultureInfo.CurrentUICulture` + `Thread` defaults → re-create the main window shell (cheap; state preserved via VM). Persist in `settings`. - `SatelliteResourceLanguages` = `en;vi;ja` in the App csproj to keep publish size down. @@ -25,7 +25,7 @@ Languages: **en** (neutral/default) · **vi** · **ja**. Same `.resx` pattern as - `en` written first, is authoritative. - `vi` authored by the maintainer. - `ja` machine-drafted, each entry marked with `review` until reviewed; the About dialog credits reviewers. -- CI check (`tools/resx-audit`): every key present in all three files; missing → build warning list artifact. +- CI check (`tools/resx-audit`): every key present in all three files; ~~missing → build warning list artifact~~ **missing is RED (2026-09-13)**: `tools/resx-audit.ps1` exists since P3 PR-2 as `build.ps1` step 15, self-test first (11 fixture cases, at least four must go red) then the live pass over every `Strings.resx` under `src/`. Per family it requires C#-identifier keys with non-empty neutral values, **exactly** the neutral key set in `vi` and `ja` (a missing key would fall back to English silently; an extra one is dead text), the `Safety_*` rule below, and a current `Strings.Designer.cs`. A tree with no family is red, not green — the gate must not be vacuous. ## Glossary (fixed translations) @@ -52,7 +52,7 @@ Technical benchmark vocabulary stays in English across all locales where the com Consent, refusal, and safety-unhook text (FR-2.1, `19_SAFETY`) is **reviewed like legal text, not like UI text**: -- No machine-drafted `ja` in this category — a mistranslated ban warning is a real harm. These keys are marked `safety: human review required` and the `ja` build fails the resx audit until a human reviewer signs off; until then the `en` string is shown as fallback rather than an unreviewed translation. +- No machine-drafted `ja` in this category — a mistranslated ban warning is a real harm. These keys are marked `safety: human review required` and ~~the `ja` build fails the resx audit until a human reviewer signs off; until then the `en` string is shown as fallback rather than an unreviewed translation~~ **as built (2026-09-13): the audit is red on a `Safety_*` key in `ja` that carries neither `safety: human review required` nor `safety: reviewed by `, and red on one marked review-required whose value is anything but the `en` string verbatim** — the key-set rule forbids leaving it out, so "shown as `en` until signed" is true by construction (the value IS the English), not by a runtime fallback. Signing = replacing the comment with `safety: reviewed by ` beside the reviewed text. - Never soften the wording per locale. "May result in a permanent ban of your account" must survive translation with the same force in all three languages. - Key prefix `Safety_*` so they are easy to audit as a group. @@ -66,12 +66,13 @@ Consent, refusal, and safety-unhook text (FR-2.1, `19_SAFETY`) is **reviewed lik > **It is also why `ConsentProvenance` has no FR-2.1 member.** The host writes a consent record on > the strength of an operator acknowledgement whose first line states, in substance, that it is > *not* the FR-2.1 dialog. Drafting that dialog's wording English-only inside a developer tool -> would manufacture the reviewed artifact without the review this section requires — no `.resx` -> file exists anywhere in the tree yet, and `tools/resx-audit` does not exist either. The enum has +> would manufacture the reviewed artifact without the review this section requires — ~~no `.resx` +> file exists anywhere in the tree yet, and `tools/resx-audit` does not exist either~~ (both exist +> since P3 PR-2, 2026-09-13; the App's family holds shell text and no `Safety_*` key yet). The enum has > ~~exactly two members~~ **exactly three members since 2026-09-10** (P2 PR-F added > `AgentConsoleOperator`, the shipped Agent's console verb — HANDOFF §P2 decision D4 — which is > likewise *not* FR-2.1 and says so in its first line; this sentence said "two" for three days after > that) and a test asserts the list, so adding the FR-2.1 value is a deliberate act that arrives with > its reviewed strings or not at all. **P3 is where it arrives** (HANDOFF §P3): `Safety_*` in `en` and -> `vi`, `ja` marked for human review and shown as `en` until signed, and `tools/resx-audit` built in -> the same phase. +> `vi`, `ja` marked for human review and shown as `en` until signed, and `tools/resx-audit` ~~built in +> the same phase~~ built first (PR-2), so PR-4's family lands under a gate that already exists. diff --git a/docs/10_LOGGING_AND_BUG_REPORTS.md b/docs/10_LOGGING_AND_BUG_REPORTS.md index 0f0ed94a..a9811e75 100644 --- a/docs/10_LOGGING_AND_BUG_REPORTS.md +++ b/docs/10_LOGGING_AND_BUG_REPORTS.md @@ -2,7 +2,7 @@ ## 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. +- 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.)* - 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}`. diff --git a/docs/12_BUILD.md b/docs/12_BUILD.md index d9317b33..07f2f65b 100644 --- a/docs/12_BUILD.md +++ b/docs/12_BUILD.md @@ -196,7 +196,7 @@ document the app displays for acceptance (FR-11) is a defect, not a template. 13. `tools/license-check.ps1` — asserts every vendored third-party has a licence copy in `legal/licenses/`, and that no Intel IGCL / AMD ADLX material has appeared in the tree 13b. `tools/accuracy-check.ps1 -SelfTest`, then live — the accuracy block is ONE text (`legal/ACCURACY.md`) embedded verbatim in `README.md` and `legal/DISCLAIMER.md` §4; a copy that drifted, a copy with no markers, or an empty source is red. Four self-test cases, both directions (§S23-6, 2026-09-06) 14. `tools/changelog-check.ps1 -SelfTest` — nine cases, five expected RED. The live half needs a pull request's changed-file list and is supplied by `ci.yml` -15. `tools/resx-audit` — **skipped loudly; it does not exist, and no `.resx` file does either** +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 17. Placeholder guard — fails if any `{{` token other than `{{RELEASE_DATE}}` survives in `README.md` or `legal/*.md` diff --git a/docs/13_CI_CD.md b/docs/13_CI_CD.md index 6f46a5c8..a6de0e76 100644 --- a/docs/13_CI_CD.md +++ b/docs/13_CI_CD.md @@ -47,8 +47,9 @@ FrameLedger uses the **`poli0981/.github` ops repo** where its templates fit, an - **Changelog gate**, on pull requests only: the changed-file list comes from GitHub's own view of the PR — not `git diff`, so a shallow checkout cannot silently produce a short one — and an empty list is refused rather than read as "no `src/` changes". It is a **step of the required `check` job** and deliberately not a job of its own: `main`'s required contexts are exactly `check` and the two `analyze` jobs, so a new job would go red while the merge button stayed green, which is what already makes `Rules / validate` advisory (§S23-2). > **Three claims in this section were false and are corrected 2026-08-06.** There is no Vulkan SDK -> step and there will not be one — the Khronos headers are vendored. `resx-audit` does not exist and -> is skipped loudly, so no artifact of it is uploaded. And the struct-mirror parenthesis — *"that +> step and there will not be one — the Khronos headers are vendored. `resx-audit` ~~does not exist and +> is skipped loudly, so no artifact of it is uploaded~~ (exists since 2026-09-13, P3 PR-2, as a hard step +> of the gate — red on a missing key, never an artifact; `12_BUILD` line 15). And the struct-mirror parenthesis — *"that > gate does not exist and `build.ps1` skips it loudly"* — has been false since 2026-08-05: > `build.ps1` implements it as a hard throwing gate that reads the run's `.trx` and fails when > `ShmLayoutMirrorTests` did not execute. `12_BUILD` carried the identical stale sentence and is diff --git a/docs/16_WPFUI_SYNTAX.md b/docs/16_WPFUI_SYNTAX.md index 15d2fc59..23299a46 100644 --- a/docs/16_WPFUI_SYNTAX.md +++ b/docs/16_WPFUI_SYNTAX.md @@ -57,10 +57,12 @@ private static readonly IHost _host = Host.CreateDefaultBuilder() .Build(); ``` +**As built (P3 PR-2, 2026-09-13), three deviations from the sketch above:** `Host.CreateApplicationBuilder()` rather than `CreateDefaultBuilder`; `MainWindow` is **transient** (a language change rebuilds it in the new culture — `09_I18N` §Mechanics — and `Services.ShellHost` tracks the live one), so `App.xaml` sets `ShutdownMode="OnExplicitShutdown"` and the host's `IHostApplicationLifetime` is what ends the process (the shell host stops it when the live window closes; the old window of a rebuild closing is not an exit); and the run is one `Task` started from a synchronous `OnStartup` (`async void` overrides are VSTHRD100 under this repo's analyzers) that opens the ledger, starts the host, awaits its shutdown, tears down, and only then calls `Shutdown()`. + Theme rules: - Manual Light/Dark: `ApplicationThemeManager.Apply(ApplicationTheme.Dark)`. - System: `SystemThemeWatcher.Watch(mainWindow)` — call it in the window's `Loaded` handler (needs an HWND), and unwatch when switching to manual. -- Persist the choice in `settings`; re-apply before the main window shows to avoid a flash. +- Persist the choice in `settings`; re-apply before the main window shows to avoid a flash. **Measured 2026-09-13: this is a correctness rule, not a cosmetic one** — `ApplicationThemeManager.Apply(theme, backdrop, updateAccent: true)` is what registers the `SystemAccentColor*` resources the control templates `StaticResource` at first Measure; a `FluentWindow` shown before any `Apply` throws `XamlParseException: Cannot find resource named 'SystemAccentColorPrimary'`. The shell applies the theme in its constructor before `InitializeComponent()` and again from `Loaded` for the watcher. - Subscribe `ApplicationThemeManager.Changed` once, centrally, to re-theme ScottPlot (below). ## Main window skeleton @@ -167,7 +169,7 @@ var result = await box.ShowDialogAsync(); // Wpf.Ui.Controls.MessageBoxResult.Pr ``` ⚠ Name clash with `System.Windows.MessageBox` — in App code, `using MessageBox = Wpf.Ui.Controls.MessageBox;` and ban the System one (BannedSymbols/analyzer note). -- Rich in-flow dialogs: `IContentDialogService` (host wired in MainWindow). +- Rich in-flow dialogs: `IContentDialogService` (host wired in MainWindow — a `ui:ContentDialogHost`, since 4.3.0 marks `SetDialogHost(ContentPresenter)` obsolete). - Transient in-app: `ISnackbarService.Show(title, message, ControlAppearance.Success, new SymbolIcon(SymbolRegular.Checkmark24), TimeSpan.FromSeconds(4))`. - System/tray notifications: H.NotifyIcon only (08_UI §Notifications policy). @@ -178,7 +180,7 @@ On startup and on `ApplicationThemeManager.Changed`: for every live plot set fig ## Gotchas checklist - [ ] Dictionaries order: `ThemesDictionary` → `ControlsDictionary` → app styles. Wrong order = default-looking controls. -- [ ] `SystemThemeWatcher.Watch` after HWND exists (`Loaded`), not in the constructor. +- [ ] `SystemThemeWatcher.Watch` after HWND exists (`Loaded`), not in the constructor — but `ApplicationThemeManager.Apply(…, updateAccent: true)` BEFORE the first window's XAML loads, or the accent resources are missing at first Measure (§App bootstrap). - [ ] Menu row lives **outside** `ui:TitleBar` (its area is the drag region; a Menu inside becomes undraggable/unclickable territory). - [ ] Don't set `AllowsTransparency`/`WindowStyle` on `FluentWindow` — it manages its own chrome. - [ ] Mica is Win 11-only: leave `WindowBackdropType="Mica"`; the library falls back on Win 10 — verify visuals in the Win 10 VM pass (14_TESTING matrix). diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 332c3948..b2edfb3d 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1226,8 +1226,9 @@ first, and both are *replacements* rather than new ground: what makes the Dashboard's live card worth having. 2. **FR-2.1's consent dialog, which retires `ConsentProvenance.AgentConsoleOperator`.** The console verb exists because the reviewed wording does not: `09_I18N` reviews `Safety_*` strings as legal - text in en/vi/ja, and no `.resx` exists anywhere in this tree. The dialog is the first thing that - needs one. When it lands, the enum gains its FR-2.1 member, the console verb becomes the + text in en/vi/ja, and ~~no `.resx` exists anywhere in this tree~~ (the App's shell family exists + since PR-2, 2026-09-13, under the audit; `Shared`'s `Safety_*` family is still this item's). The + dialog is the first thing that needs a REVIEWED one. When it lands, the enum gains its FR-2.1 member, the console verb becomes the developer path it always said it was, and `19_SAFETY` §User-facing consent stops carrying an exception. **Do not add the enum member before the reviewed text exists** — a declared value no code can produce is the §S29(c) shape, and `GameConsentRecordTests` turns red on purpose. @@ -1250,7 +1251,7 @@ because a criterion already true on `main` is decoration. | 0 | P2 sweep: the doc/tool drift PR-G left (`coverage-gate.ps1` prose, `13_CI_CD`'s count and its signer-probe claim, `09_I18N`'s member count, `17_HOOK_ENGINE`'s §H9 cite, this file's D-labels, `ci.yml`'s census comment), this head, the roadmap amendment | `grep -n "exactly two members" docs/09_I18N.md` matched; `§H9` resolved to nothing; two START HEREs | | ~~1~~ | ~~**The pipe, read half**: `Shared.Ipc` contracts + `JsonSerializerContext`; the Agent's `PipeServerHostedService`; `Hello`/`HelloAck`, `GetStatus`/`StatusAck`, `Ping`/`Pong`; the events (`SessionStarted`/`Progress`/`Completed`/`CaptureRefused`/`CaptureDegraded`/`SafetyUnhook`/`CaptureError`); a 1 Hz `SessionProgress` publisher; `Infrastructure.Ipc.PipeClient`~~ **LANDED 2026-09-13** — status in `CHANGELOG.md`; `07_IPC` §C carries what was built and the one deviation (`etwAvailable` struck) | ~~`grep -rn NamedPipeServerStream src` is empty; `FrameLedger.Shared` holds no JSON type; `04_CAPTURE` §Live progress has no producer~~ | | ~~1b~~ | ~~**The pipe, command half**: `SetWatchlist` (identity only), `SetHookEnabled` (the Agent re-scans and stamps), `LaunchGame`, `PauseCapture`/`ResumeCapture`, `StopSession`, `UpdateRules` (a trigger, no payload), `Shutdown`~~ **LANDED 2026-09-13** — status in `CHANGELOG.md`; `07_IPC` §Messages carries each row as built. **One thing stayed with PR-4 on purpose:** `SetHookEnabled true` stamps nothing — the pre-scan runs and a block is recorded, then `Error DisclosureUnavailable` — because the reviewed text it would stamp against does not exist, and a member no code can produce is the §S29(c) shape | ~~the Agent accepts no command from outside; `CaptureOrchestrator` has no stop/pause surface; `SetHookEnabled` has no handler~~ | -| 2 | **resx + the App shell**: `Strings.resx` en/vi/ja for App and Shared, the generated class, `tools/resx-audit.ps1` (+`-SelfTest`) as `build.ps1` step 15; the Generic Host bootstrap, `FluentWindow`, TitleBar/Menu/NavigationView, theme + persistence, `INavigationService`, Serilog `ui-*.log`, five empty pages, the Agent status pill over `Hello`, auto-start of `--serve` on connect failure; `tests/FrameLedger.App.Tests` | `find . -name '*.resx'` is empty; step 15 prints "skipped loudly"; `App.xaml` uses `StartupUri` and `MainWindow` is a plain `Window` | +| ~~2~~ | ~~**resx + the App shell**: `Strings.resx` en/vi/ja for App and Shared, the generated class, `tools/resx-audit.ps1` (+`-SelfTest`) as `build.ps1` step 15; the Generic Host bootstrap, `FluentWindow`, TitleBar/Menu/NavigationView, theme + persistence, `INavigationService`, Serilog `ui-*.log`, five empty pages, the Agent status pill over `Hello`, auto-start of `--serve` on connect failure; `tests/FrameLedger.App.Tests`~~ **LANDED 2026-09-13** — status in `CHANGELOG.md`; `08_UI` §Shell and `16_WPFUI_SYNTAX` §App bootstrap carry what was built and the deviations. **Two things moved on purpose:** `Shared`'s family waits for PR-4 (it would hold only `Safety_*`, and an empty family is what the audit refuses), and the generator is ours (`tools/resx-gen.ps1`, committed output) because the SDK-style WPF project runs no `ResXFileCodeGenerator` | ~~`find . -name '*.resx'` is empty; step 15 prints "skipped loudly"; `App.xaml` uses `StartupUri` and `MainWindow` is a plain `Window`~~ | | 2b *(owner decides)* | `FL_MOCK=1` / `Agent --serve --mock`, `--data-dir` only: a `MockSessionSource` hosted service that emits pipe events and inserts synthesised sessions through `ISessionRepository` — and can never resolve `HookedCaptureGate` (asserted) | CLAUDE.md says "specified but not implemented"; `grep FL_MOCK src` is empty | | 3 | **Ports the UI reads and writes**: `ISessionRepository.ListByGameAsync` / segments / sensors, `ISessionAnnotationRepository`, `ILegalAcceptanceStore.RecordAsync`, `IGameRepository.UpdateMetadataAsync` / `RemoveAsync`, the **settings registry** (closes §G's row — D16 below), `IRtOverrideRepository` (FR-8.3), `display_res`/`display_hz` producer; tests for the four PR-B adapters that have none | no port lists sessions by game; `session_annotations` has no repository; `legal_acceptance` has no writer; `ISettingsStore`'s own doc calls the registry open | | 4 | **FR-2.1's consent dialog**: `Safety_*` en + vi (ja marked `safety: human review required`, shown as en) in `Shared`, `SafetyDisclosureVersion`; `ConsentProvenance.ConsentDialog` whose only producer is the Agent's `SetHookEnabled` handler; `HelloAck.disclosureVersion` and the App **refusing to open the dialog** on mismatch (§S23-1's shape); the dialog itself per `19_SAFETY` §User-facing consent; FR-2.2's disabled toggle with the reason inline; FR-2.5's InfoBar; `GameConsentRecordTests`, `19_SAFETY`, `09_I18N` and item 2 above updated | `Enum.GetNames()` has three names; no `Safety_*` key exists; `19_SAFETY` still carries the console exception | diff --git a/src/FrameLedger.App/App.xaml b/src/FrameLedger.App/App.xaml index 6b8fe3b1..7f39077d 100644 --- a/src/FrameLedger.App/App.xaml +++ b/src/FrameLedger.App/App.xaml @@ -1,9 +1,21 @@ - + xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml" + ShutdownMode="OnExplicitShutdown"> + - + + + + + + + diff --git a/src/FrameLedger.App/App.xaml.cs b/src/FrameLedger.App/App.xaml.cs index beeb2786..26a66500 100644 --- a/src/FrameLedger.App/App.xaml.cs +++ b/src/FrameLedger.App/App.xaml.cs @@ -1,28 +1,191 @@ +using System.Globalization; +using System.IO; using System.Windows; +using System.Windows.Threading; +using FrameLedger.App.Pages; +using FrameLedger.App.Services; +using FrameLedger.App.ViewModels; +using FrameLedger.Application.Persistence; +using FrameLedger.Infrastructure.Ipc; +using FrameLedger.Infrastructure.Persistence; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Serilog; +using Wpf.Ui; +using Wpf.Ui.DependencyInjection; namespace FrameLedger.App; /// -/// Application entry point. +/// The application (P3 PR-2): a .NET Generic Host owns everything, per docs/16_WPFUI_SYNTAX.md §App +/// bootstrap. Startup opens the ledger the Agent owns (06_DATA_MODEL §Writer ownership: the App reads it +/// all and writes only its own tables), reads the UI culture from settings BEFORE any window exists, +/// then starts the host; shows the shell. /// /// -/// Scaffold only. The real bootstrap owns everything through a .NET Generic -/// Host and must follow docs/16_WPFUI_SYNTAX.md exactly: -/// -/// merged dictionaries in order ThemesDictionary → -/// ControlsDictionary → our styles — wrong order silently yields -/// default-looking controls; -/// SystemThemeWatcher.Watch from the window's Loaded -/// handler, never the constructor (it needs an HWND); -/// navigation only via INavigationService, with every page -/// registered in DI. -/// +/// FULLY QUALIFIED base type, deliberately: this project's namespace is FrameLedger.App and there is a +/// FrameLedger.Application namespace beside it, so the bare name Application resolves to that +/// NAMESPACE rather than to the WPF type (CS0118) — sibling namespaces win over a using. /// -// FULLY QUALIFIED, deliberately. This project's namespace is FrameLedger.App -// and there is now a FrameLedger.Application namespace beside it, so the bare -// name `Application` resolves to that NAMESPACE rather than to the WPF type -// (CS0118) — sibling namespaces win over a `using`. Anything here that means -// the WPF Application must say so in full. public partial class App : System.Windows.Application { + private IHost? _host; + private LedgerDatabase? _db; + private Task? _run; + + /// The composition, for the few places XAML cannot reach DI (the shell rebuild, the crash path). + public static IServiceProvider Services => + ((App)Current)._host?.Services ?? throw new InvalidOperationException("the host is not started"); + + /// + /// WPF's startup is synchronous and the host's is not, so the whole run is one task on the dispatcher: + /// open, start, wait for the host's shutdown (the shell host requests it when the live window closes, the + /// Exit command requests it directly), tear down, and only then . + /// + protected override void OnStartup(StartupEventArgs e) + { + base.OnStartup(e); + UiPaths.EnsureDirectories(); + ConfigureLogging(); + HookCrashHandlers(); + _run = RunAsync(); + } + + protected override void OnExit(ExitEventArgs e) + { + ArgumentNullException.ThrowIfNull(e); + Log.Information("ui: exit {Code} (run {Status})", e.ApplicationExitCode, _run?.Status); + Log.CloseAndFlush(); + base.OnExit(e); + } + + private async Task RunAsync() + { + int exitCode = 0; + try + { + _db = await LedgerDatabase.OpenAsync(UiPaths.Database).ConfigureAwait(true); + var appearance = new AppearanceSettings(new SqliteSettingsStore(_db)); + await appearance.LoadAsync().ConfigureAwait(true); + ApplyCulture(appearance.Language); + + _host = BuildHost(_db, appearance); + await _host.StartAsync().ConfigureAwait(true); + Log.Information("ui: started ({Version}), ledger {Ledger}", UiIdentity.Version, UiPaths.Database); + await _host.WaitForShutdownAsync().ConfigureAwait(true); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + Log.Fatal(ex, "ui: the run ended in an exception"); + exitCode = 1; + } + finally + { + await TearDownAsync().ConfigureAwait(true); + Shutdown(exitCode); + } + } + + private async Task TearDownAsync() + { + try + { + if (_host is not null) + { + await _host.StopAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(true); + _host.Dispose(); + _host = null; + } + + if (_db is not null) + { + await _db.DisposeAsync().ConfigureAwait(true); + _db = null; + } + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + Log.Warning(ex, "ui: shutdown was not clean"); + } + } + + /// The UI culture, once, before the first window: resources are read at XAML load. + public static void ApplyCulture(string language) + { + var culture = CultureInfo.GetCultureInfo(language); + CultureInfo.DefaultThreadCurrentUICulture = culture; + CultureInfo.CurrentUICulture = culture; + Strings.Culture = culture; + } + + private static IHost BuildHost(LedgerDatabase db, AppearanceSettings appearance) + { + HostApplicationBuilder builder = Host.CreateApplicationBuilder(); + builder.Services.AddSerilog(); + + // WPF UI: the page provider resolves pages from DI, the three services are the shell's (16 §Main window skeleton). + builder.Services.AddNavigationViewPageProvider(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + + // The ledger and the App's own settings (06_DATA_MODEL §Writer ownership: the App writes `settings`). + builder.Services.AddSingleton(db); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(appearance); + builder.Services.AddSingleton(); + + // The Agent over the pipe (07_IPC §Client behavior): connect, start it when it is not there, tell the shell. + builder.Services.AddSingleton(); + builder.Services.AddSingleton(static sp => new AgentConnection( + sp.GetRequiredService(), + static () => new PipeClient(), + new AgentConnectionOptions(), + UiIdentity.Version)); + builder.Services.AddHostedService(); + + // The shell: the window is TRANSIENT because a language change rebuilds it (09_I18N §Mechanics); the + // shell host tracks the live one. Pages and their view models are transient (16 §Navigation). + builder.Services.AddSingleton(); + builder.Services.AddTransient(); + builder.Services.AddSingleton(); + builder.Services.AddTransient(); + builder.Services.AddTransient(); + builder.Services.AddTransient(); + builder.Services.AddTransient(); + builder.Services.AddTransient(); + builder.Services.AddTransient(); + builder.Services.AddTransient(); + builder.Services.AddTransient(); + builder.Services.AddTransient(); + builder.Services.AddTransient(); + builder.Services.AddHostedService(); + return builder.Build(); + } + + /// 10_LOGGING §Serilog configuration: logs/ui-.log, daily, 7 kept, 10 MB, the one template. + private static void ConfigureLogging() => + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Information() + .Enrich.WithProperty("Process", "ui") + .WriteTo.File( + Path.Combine(UiPaths.Logs, "ui-.log"), + rollingInterval: RollingInterval.Day, + retainedFileCountLimit: 7, + fileSizeLimitBytes: 10 * 1024 * 1024, + rollOnFileSizeLimit: true, + formatProvider: CultureInfo.InvariantCulture, + outputTemplate: "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {SourceContext} {Message:lj} {Properties:j}{NewLine}{Exception}") + .CreateLogger(); + + /// 10_LOGGING §Crash handling: every unhandled path is logged as Fatal. The dialog and the minidump are P4's. + private void HookCrashHandlers() + { + DispatcherUnhandledException += OnDispatcherUnhandledException; + AppDomain.CurrentDomain.UnhandledException += static (_, args) => Log.Fatal(args.ExceptionObject as Exception, "ui: unhandled exception (AppDomain)"); + 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)"); } diff --git a/src/FrameLedger.App/FrameLedger.App.csproj b/src/FrameLedger.App/FrameLedger.App.csproj index e0eb2186..a6ad44d6 100644 --- a/src/FrameLedger.App/FrameLedger.App.csproj +++ b/src/FrameLedger.App/FrameLedger.App.csproj @@ -4,6 +4,12 @@ WPF UI (docs/08_UI.md). All XAML follows docs/16_WPFUI_SYNTAX.md — read it before writing any view. All user-visible strings come from .resx (docs/09_I18N.md); no string literals in XAML or C#. + + The strongly-typed accessor Strings.Designer.cs is GENERATED from Strings.resx by + tools/resx-gen.ps1 and committed; tools/resx-audit.ps1 (build.ps1 step 15) fails the + build when it is stale or when Strings.vi.resx / Strings.ja.resx drift from the + neutral key set. The SDK embeds the resx as FrameLedger.App.Strings.resources and + builds the vi/ja satellites on its own (SatelliteResourceLanguages in Directory.Build.props). --> @@ -23,6 +29,11 @@ + + + + + diff --git a/src/FrameLedger.App/MainWindow.xaml b/src/FrameLedger.App/MainWindow.xaml index adc24ac6..c1725a7a 100644 --- a/src/FrameLedger.App/MainWindow.xaml +++ b/src/FrameLedger.App/MainWindow.xaml @@ -1,12 +1,103 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + diff --git a/src/FrameLedger.App/MainWindow.xaml.cs b/src/FrameLedger.App/MainWindow.xaml.cs index 6dbc0301..c66b02ae 100644 --- a/src/FrameLedger.App/MainWindow.xaml.cs +++ b/src/FrameLedger.App/MainWindow.xaml.cs @@ -1,21 +1,51 @@ -using System.Windows; +using FrameLedger.App.Services; +using FrameLedger.App.ViewModels; +using Wpf.Ui; +using Wpf.Ui.Abstractions; +using Wpf.Ui.Controls; namespace FrameLedger.App; /// -/// Shell window. +/// The shell (P3 PR-2, docs/08_UI.md §Shell): wires the three WPF UI services to its own controls once, +/// applies the theme (and with it the accent resources) before its XAML loads, and re-applies it from +/// Loaded so the System watcher gets its HWND (16_WPFUI_SYNTAX §Gotchas). /// -/// -/// Scaffold only. The real shell is a ui:FluentWindow with a custom -/// ui:TitleBar, a classic Menu row **outside** the title bar's -/// drag region, and a left ui:NavigationView -/// (docs/08_UI.md, docs/16_WPFUI_SYNTAX.md §Main window skeleton). -/// -public partial class MainWindow : Window +public partial class MainWindow : FluentWindow { - /// Initializes the shell window. - public MainWindow() + public MainWindow( + MainWindowViewModel viewModel, + INavigationService navigation, + ISnackbarService snackbar, + IContentDialogService dialogs, + INavigationViewPageProvider pages, + IThemeApplier theme, + AppearanceSettings appearance) { + ArgumentNullException.ThrowIfNull(navigation); + ArgumentNullException.ThrowIfNull(snackbar); + ArgumentNullException.ThrowIfNull(dialogs); + ArgumentNullException.ThrowIfNull(pages); + ArgumentNullException.ThrowIfNull(theme); + ArgumentNullException.ThrowIfNull(appearance); + + ViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel)); + DataContext = this; + + // Before the XAML loads: ApplicationThemeManager.Apply(…, updateAccent: true) is what registers the + // SystemAccentColor* resources the control templates StaticResource at first Measure (measured 2026-09-13: + // without it the first Show() throws XamlParseException "Cannot find resource named + // 'SystemAccentColorPrimary'"). The watcher half needs the HWND and runs from Loaded. + theme.Apply(appearance.Theme, null); InitializeComponent(); + + RootNavigation.SetPageProviderService(pages); + navigation.SetNavigationControl(RootNavigation); + snackbar.SetSnackbarPresenter(SnackbarPresenter); + dialogs.SetDialogHost(DialogHost); + + Loaded += (_, _) => theme.Apply(appearance.Theme, this); } + + public MainWindowViewModel ViewModel { get; } } diff --git a/src/FrameLedger.App/Pages/ComparePage.xaml b/src/FrameLedger.App/Pages/ComparePage.xaml new file mode 100644 index 00000000..d20cc125 --- /dev/null +++ b/src/FrameLedger.App/Pages/ComparePage.xaml @@ -0,0 +1,12 @@ + + + + + + diff --git a/src/FrameLedger.App/Pages/ComparePage.xaml.cs b/src/FrameLedger.App/Pages/ComparePage.xaml.cs new file mode 100644 index 00000000..021303ce --- /dev/null +++ b/src/FrameLedger.App/Pages/ComparePage.xaml.cs @@ -0,0 +1,16 @@ +using FrameLedger.App.ViewModels; +using Wpf.Ui.Abstractions.Controls; + +namespace FrameLedger.App.Pages; + +public partial class ComparePage : INavigableView +{ + public ComparePage(CompareViewModel viewModel) + { + ViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel)); + DataContext = this; + InitializeComponent(); + } + + public CompareViewModel ViewModel { get; } +} diff --git a/src/FrameLedger.App/Pages/DashboardPage.xaml b/src/FrameLedger.App/Pages/DashboardPage.xaml new file mode 100644 index 00000000..5dd8deda --- /dev/null +++ b/src/FrameLedger.App/Pages/DashboardPage.xaml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/FrameLedger.App/Pages/DashboardPage.xaml.cs b/src/FrameLedger.App/Pages/DashboardPage.xaml.cs new file mode 100644 index 00000000..23f0b65e --- /dev/null +++ b/src/FrameLedger.App/Pages/DashboardPage.xaml.cs @@ -0,0 +1,16 @@ +using FrameLedger.App.ViewModels; +using Wpf.Ui.Abstractions.Controls; + +namespace FrameLedger.App.Pages; + +public partial class DashboardPage : INavigableView +{ + public DashboardPage(DashboardViewModel viewModel) + { + ViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel)); + DataContext = this; + InitializeComponent(); + } + + public DashboardViewModel ViewModel { get; } +} diff --git a/src/FrameLedger.App/Pages/GamesPage.xaml b/src/FrameLedger.App/Pages/GamesPage.xaml new file mode 100644 index 00000000..193a5e47 --- /dev/null +++ b/src/FrameLedger.App/Pages/GamesPage.xaml @@ -0,0 +1,12 @@ + + + + + + diff --git a/src/FrameLedger.App/Pages/GamesPage.xaml.cs b/src/FrameLedger.App/Pages/GamesPage.xaml.cs new file mode 100644 index 00000000..b5b2335c --- /dev/null +++ b/src/FrameLedger.App/Pages/GamesPage.xaml.cs @@ -0,0 +1,16 @@ +using FrameLedger.App.ViewModels; +using Wpf.Ui.Abstractions.Controls; + +namespace FrameLedger.App.Pages; + +public partial class GamesPage : INavigableView +{ + public GamesPage(GamesViewModel viewModel) + { + ViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel)); + DataContext = this; + InitializeComponent(); + } + + public GamesViewModel ViewModel { get; } +} diff --git a/src/FrameLedger.App/Pages/LogsPage.xaml b/src/FrameLedger.App/Pages/LogsPage.xaml new file mode 100644 index 00000000..50f4f15d --- /dev/null +++ b/src/FrameLedger.App/Pages/LogsPage.xaml @@ -0,0 +1,12 @@ + + + + + + diff --git a/src/FrameLedger.App/Pages/LogsPage.xaml.cs b/src/FrameLedger.App/Pages/LogsPage.xaml.cs new file mode 100644 index 00000000..c44e7a09 --- /dev/null +++ b/src/FrameLedger.App/Pages/LogsPage.xaml.cs @@ -0,0 +1,16 @@ +using FrameLedger.App.ViewModels; +using Wpf.Ui.Abstractions.Controls; + +namespace FrameLedger.App.Pages; + +public partial class LogsPage : INavigableView +{ + public LogsPage(LogsViewModel viewModel) + { + ViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel)); + DataContext = this; + InitializeComponent(); + } + + public LogsViewModel ViewModel { get; } +} diff --git a/src/FrameLedger.App/Pages/SettingsPage.xaml b/src/FrameLedger.App/Pages/SettingsPage.xaml new file mode 100644 index 00000000..d2d3bdf7 --- /dev/null +++ b/src/FrameLedger.App/Pages/SettingsPage.xaml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/FrameLedger.App/Pages/SettingsPage.xaml.cs b/src/FrameLedger.App/Pages/SettingsPage.xaml.cs new file mode 100644 index 00000000..d24ec2ce --- /dev/null +++ b/src/FrameLedger.App/Pages/SettingsPage.xaml.cs @@ -0,0 +1,16 @@ +using FrameLedger.App.ViewModels; +using Wpf.Ui.Abstractions.Controls; + +namespace FrameLedger.App.Pages; + +public partial class SettingsPage : INavigableView +{ + public SettingsPage(SettingsViewModel viewModel) + { + ViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel)); + DataContext = this; + InitializeComponent(); + } + + public SettingsViewModel ViewModel { get; } +} diff --git a/src/FrameLedger.App/Services/AgentConnection.cs b/src/FrameLedger.App/Services/AgentConnection.cs new file mode 100644 index 00000000..d6055103 --- /dev/null +++ b/src/FrameLedger.App/Services/AgentConnection.cs @@ -0,0 +1,225 @@ +using System.IO; +using FrameLedger.Infrastructure.Ipc; +using FrameLedger.Shared.Ipc; +using Serilog; + +namespace FrameLedger.App.Services; + +/// +/// The App's end of the pipe as a long-running state machine (07_IPC §Client behavior): a connect +/// round of × backoff; on failure start the Agent beside +/// this executable and try again; then Hello, GetStatus, keepalive pings, and the event stream +/// until the pipe drops — then the next round. "Treat the pipe as unreliable": everything persisted comes from +/// SQLite, and this class only ever degrades the live status. +/// +/// +/// Runs on the thread pool; and fire there, and a view model +/// marshals to the dispatcher. Nothing here touches WPF. +/// +public sealed class AgentConnection : IAsyncDisposable +{ + private readonly IAgentLauncher _launcher; + private readonly Func _pipes; + private readonly AgentConnectionOptions _options; + private readonly string _appVersion; + private readonly Lock _lock = new(); + private readonly SemaphoreSlim _retryNow = new(0); + private PipeClient? _client; + private long _rounds; + private long _launches; + + public AgentConnection(IAgentLauncher launcher, Func pipes, AgentConnectionOptions options, string appVersion) + { + _launcher = launcher ?? throw new ArgumentNullException(nameof(launcher)); + _pipes = pipes ?? throw new ArgumentNullException(nameof(pipes)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion)); + } + + public event EventHandler? Changed; + + /// Every Agent → UI event, as it arrives; the payload is decoded by whoever needs it. + public event EventHandler? EventReceived; + + public AgentConnectionState State { get; private set; } = AgentConnectionState.Connecting; + + public HelloAck? Hello { get; private set; } + + public StatusAck? Status { get; private set; } + + /// Connect rounds completed (a test's clock). + public long Rounds => Interlocked.Read(ref _rounds); + + /// How many times the Agent was started from beside this executable. + public long Launches => Interlocked.Read(ref _launches); + + /// Skip the wait before the next round (the banner's Retry). + public void RetryNow() => _retryNow.Release(); + + /// Loop until cancelled. + public async Task RunAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + try + { + await RoundAsync(ct).ConfigureAwait(false); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + break; + } + finally + { + Interlocked.Increment(ref _rounds); + } + + await WaitForRetryAsync(ct).ConfigureAwait(false); + } + } + + /// Ask the Agent for its status now; null when not connected or when the request failed. + public async Task RefreshStatusAsync(CancellationToken ct = default) + { + PipeClient? client = _client; + if (client is null || State != AgentConnectionState.Connected) + { + return null; + } + + try + { + StatusAck status = await client.GetStatusAsync(_options.RequestTimeout, ct).ConfigureAwait(false); + Set(AgentConnectionState.Connected, Hello, status); + return status; + } + catch (Exception ex) when (ex is IOException or TimeoutException or IpcRequestException or ObjectDisposedException) + { + return null; + } + } + + public async ValueTask DisposeAsync() + { + PipeClient? client = Interlocked.Exchange(ref _client, null); + if (client is not null) + { + await client.DisposeAsync().ConfigureAwait(false); + } + + _retryNow.Dispose(); + } + + private async Task RoundAsync(CancellationToken ct) + { + Set(AgentConnectionState.Connecting, null, null); + PipeClient? client = await TryConnectAsync(ct).ConfigureAwait(false); + if (client is null && _launcher.CanLaunch) + { + Set(AgentConnectionState.Starting, null, null); + if (_launcher.TryStart()) + { + Interlocked.Increment(ref _launches); + client = await TryConnectAsync(ct).ConfigureAwait(false); + } + } + + if (client is null) + { + Set(_launcher.CanLaunch ? AgentConnectionState.Offline : AgentConnectionState.Missing, null, null); + return; + } + + _client = client; + try + { + HelloAck hello = await client.HelloAsync(_appVersion, _options.RequestTimeout, ct).ConfigureAwait(false); + StatusAck status = await client.GetStatusAsync(_options.RequestTimeout, ct).ConfigureAwait(false); + Set(AgentConnectionState.Connected, hello, status); + Log.Information("agent: connected (agent {Version}, pid {Pid}, telemetry {Telemetry})", hello.AgentVersion, hello.Pid, hello.TelemetrySource); + await PumpAsync(client, ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or TimeoutException or IpcRequestException or ObjectDisposedException or IpcFramingException) + { + Log.Warning("agent: connection lost ({Kind}: {Message})", ex.GetType().Name, ex.Message); + } + finally + { + _client = null; + await client.DisposeAsync().ConfigureAwait(false); + Set(AgentConnectionState.Offline, null, null); + } + } + + private async Task TryConnectAsync(CancellationToken ct) + { + for (int attempt = 0; attempt < _options.ConnectAttempts; attempt++) + { + PipeClient client = _pipes(); + try + { + await client.ConnectAsync(_options.ConnectTimeout, ct).ConfigureAwait(false); + return client; + } + catch (Exception ex) when (ex is TimeoutException or IOException or UnauthorizedAccessException) + { + await client.DisposeAsync().ConfigureAwait(false); + } + + await Task.Delay(_options.ConnectBackoff, ct).ConfigureAwait(false); + } + + return null; + } + + /// Events until the pipe drops, with a keepalive ping whenever the stream has been quiet for the interval. + private async Task PumpAsync(PipeClient client, CancellationToken ct) + { + while (true) + { + ValueTask read = client.Events.ReadAsync(ct); + Task readTask = read.AsTask(); + Task first = await Task.WhenAny(readTask, Task.Delay(_options.Keepalive, ct)).ConfigureAwait(false); + if (first != readTask) + { + await client.PingAsync(_options.RequestTimeout, ct).ConfigureAwait(false); + continue; + } + + IpcEnvelope envelope; + try + { + envelope = await readTask.ConfigureAwait(false); + } + catch (System.Threading.Channels.ChannelClosedException) + { + return; + } + + EventReceived?.Invoke(this, new AgentEventArgs(envelope)); + } + } + + private async Task WaitForRetryAsync(CancellationToken ct) + { + try + { + await _retryNow.WaitAsync(_options.RetryInterval, ct).ConfigureAwait(false); + } + catch (ObjectDisposedException) + { + } + } + + private void Set(AgentConnectionState state, HelloAck? hello, StatusAck? status) + { + lock (_lock) + { + State = state; + Hello = hello; + Status = status; + } + + Changed?.Invoke(this, EventArgs.Empty); + } +} diff --git a/src/FrameLedger.App/Services/AgentConnectionHostedService.cs b/src/FrameLedger.App/Services/AgentConnectionHostedService.cs new file mode 100644 index 00000000..df794831 --- /dev/null +++ b/src/FrameLedger.App/Services/AgentConnectionHostedService.cs @@ -0,0 +1,15 @@ +using Microsoft.Extensions.Hosting; + +namespace FrameLedger.App.Services; + +/// Runs for the life of the host. +internal sealed class AgentConnectionHostedService(AgentConnection connection) : BackgroundService +{ + protected override Task ExecuteAsync(CancellationToken stoppingToken) => connection.RunAsync(stoppingToken); + + public override async Task StopAsync(CancellationToken cancellationToken) + { + await base.StopAsync(cancellationToken).ConfigureAwait(false); + await connection.DisposeAsync().ConfigureAwait(false); + } +} diff --git a/src/FrameLedger.App/Services/AgentConnectionOptions.cs b/src/FrameLedger.App/Services/AgentConnectionOptions.cs new file mode 100644 index 00000000..1894b72b --- /dev/null +++ b/src/FrameLedger.App/Services/AgentConnectionOptions.cs @@ -0,0 +1,20 @@ +namespace FrameLedger.App.Services; + +/// 07_IPC §Client behavior's numbers, overridable so a test does not wait on the product's clock. +public sealed record AgentConnectionOptions +{ + /// "Connect with 250 ms × 8 backoff". + public int ConnectAttempts { get; init; } = 8; + + public TimeSpan ConnectBackoff { get; init; } = TimeSpan.FromMilliseconds(250); + + public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(2); + + /// After a round that found no Agent (started or not): how long before the next round. + public TimeSpan RetryInterval { get; init; } = TimeSpan.FromSeconds(5); + + /// Ping cadence while connected (07_IPC: 15 s keepalive, client-driven). + public TimeSpan Keepalive { get; init; } = TimeSpan.FromSeconds(15); + + public TimeSpan RequestTimeout { get; init; } = TimeSpan.FromSeconds(10); +} diff --git a/src/FrameLedger.App/Services/AgentConnectionState.cs b/src/FrameLedger.App/Services/AgentConnectionState.cs new file mode 100644 index 00000000..a35bb846 --- /dev/null +++ b/src/FrameLedger.App/Services/AgentConnectionState.cs @@ -0,0 +1,20 @@ +namespace FrameLedger.App.Services; + +/// What the status pill and the banner show (08_UI §Shell: "Agent state shown as a pill"). +public enum AgentConnectionState +{ + /// A connect round is in progress. + Connecting = 0, + + /// No Agent answered; it was started from beside this executable and a new round runs. + Starting, + + /// Hello answered. + Connected, + + /// An Agent exists beside this executable and is not answering; rounds continue. + Offline, + + /// No Agent executable is beside this one; nothing to start, rounds continue in case one appears. + Missing, +} diff --git a/src/FrameLedger.App/Services/AgentEventArgs.cs b/src/FrameLedger.App/Services/AgentEventArgs.cs new file mode 100644 index 00000000..efaa5812 --- /dev/null +++ b/src/FrameLedger.App/Services/AgentEventArgs.cs @@ -0,0 +1,9 @@ +using FrameLedger.Shared.Ipc; + +namespace FrameLedger.App.Services; + +/// One Agent → UI event off the pipe, undecoded: the envelope's type says which record the payload is. +public sealed class AgentEventArgs(IpcEnvelope envelope) : EventArgs +{ + public IpcEnvelope Envelope { get; } = envelope ?? throw new ArgumentNullException(nameof(envelope)); +} diff --git a/src/FrameLedger.App/Services/AgentLauncher.cs b/src/FrameLedger.App/Services/AgentLauncher.cs new file mode 100644 index 00000000..d8a93895 --- /dev/null +++ b/src/FrameLedger.App/Services/AgentLauncher.cs @@ -0,0 +1,39 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using Serilog; + +namespace FrameLedger.App.Services; + +/// Starts the Agent beside this executable, as its own process — it must outlive the App (background capture). +public sealed class AgentLauncher : IAgentLauncher +{ + private static string AgentPath => Path.Combine(AppContext.BaseDirectory, "FrameLedger.Agent.exe"); + + public bool CanLaunch => File.Exists(AgentPath); + + public bool TryStart() + { + if (!CanLaunch) + { + return false; + } + + try + { + using Process? started = Process.Start(new ProcessStartInfo(AgentPath, "--serve") + { + UseShellExecute = false, + CreateNoWindow = true, + WorkingDirectory = AppContext.BaseDirectory, + }); + Log.Information("agent: started {Path} --serve (pid {Pid})", AgentPath, started?.Id); + return started is not null; + } + catch (Exception ex) when (ex is Win32Exception or InvalidOperationException or IOException) + { + Log.Warning(ex, "agent: could not start {Path}", AgentPath); + return false; + } + } +} diff --git a/src/FrameLedger.App/Services/AgentStatusPresentation.cs b/src/FrameLedger.App/Services/AgentStatusPresentation.cs new file mode 100644 index 00000000..543f3ef9 --- /dev/null +++ b/src/FrameLedger.App/Services/AgentStatusPresentation.cs @@ -0,0 +1,26 @@ +using Wpf.Ui.Controls; + +namespace FrameLedger.App.Services; + +/// How the pill and the banner show — one table, so the view models agree. +public static class AgentStatusPresentation +{ + /// The pill's text and colour. + public static (string Text, ControlAppearance Appearance) Pill(AgentConnectionState state) => state switch + { + AgentConnectionState.Connected => (Strings.Agent_State_Connected, ControlAppearance.Success), + AgentConnectionState.Connecting => (Strings.Agent_State_Connecting, ControlAppearance.Info), + AgentConnectionState.Starting => (Strings.Agent_State_Starting, ControlAppearance.Info), + AgentConnectionState.Offline => (Strings.Agent_State_Offline, ControlAppearance.Caution), + AgentConnectionState.Missing => (Strings.Agent_State_Missing, ControlAppearance.Danger), + _ => throw new ArgumentOutOfRangeException(nameof(state), state, "not a connection state"), + }; + + /// The persistent InfoBar's body (08_UI §Notifications: "Agent offline" is in-app, persistent), or null when no banner is due. + public static string? Banner(AgentConnectionState state) => state switch + { + AgentConnectionState.Offline => Strings.Agent_Banner_Offline_Body, + AgentConnectionState.Missing => Strings.Agent_Banner_Missing_Body, + _ => null, + }; +} diff --git a/src/FrameLedger.App/Services/AppTheme.cs b/src/FrameLedger.App/Services/AppTheme.cs new file mode 100644 index 00000000..e654feee --- /dev/null +++ b/src/FrameLedger.App/Services/AppTheme.cs @@ -0,0 +1,9 @@ +namespace FrameLedger.App.Services; + +/// FR-10's theme choice, as settings.ui.theme stores it. +public enum AppTheme +{ + System = 0, + Light, + Dark, +} diff --git a/src/FrameLedger.App/Services/AppearanceSettings.cs b/src/FrameLedger.App/Services/AppearanceSettings.cs new file mode 100644 index 00000000..2571db95 --- /dev/null +++ b/src/FrameLedger.App/Services/AppearanceSettings.cs @@ -0,0 +1,57 @@ +using FrameLedger.Application.Persistence; + +namespace FrameLedger.App.Services; + +/// +/// The two appearance keys of the settings registry (HANDOFF §P3 decision D16): ui.theme — +/// system · light · dark — and ui.language — en · vi · ja. +/// Read once at startup (before any window, because resources are read at XAML load), written by the Settings +/// page. The App owns settings under 06_DATA_MODEL §Writer ownership. +/// +public sealed class AppearanceSettings(ISettingsStore settings) +{ + public const string ThemeKey = "ui.theme"; + public const string LanguageKey = "ui.language"; + + public static IReadOnlyList Languages { get; } = ["en", "vi", "ja"]; + + public AppTheme Theme { get; private set; } = AppTheme.System; + + public string Language { get; private set; } = "en"; + + public async Task LoadAsync(CancellationToken ct = default) + { + Theme = ParseTheme(await settings.GetAsync(ThemeKey, ct).ConfigureAwait(false)); + Language = ParseLanguage(await settings.GetAsync(LanguageKey, ct).ConfigureAwait(false)); + } + + public async Task SetThemeAsync(AppTheme theme, CancellationToken ct = default) + { + Theme = theme; + await settings.SetAsync(ThemeKey, ThemeText(theme), ct).ConfigureAwait(false); + } + + public async Task SetLanguageAsync(string language, CancellationToken ct = default) + { + Language = ParseLanguage(language); + await settings.SetAsync(LanguageKey, Language, ct).ConfigureAwait(false); + } + + /// An unknown or absent value is the default, never an exception: a hand-edited row must not stop the App. + public static AppTheme ParseTheme(string? value) => value switch + { + "light" => AppTheme.Light, + "dark" => AppTheme.Dark, + _ => AppTheme.System, + }; + + public static string ThemeText(AppTheme theme) => theme switch + { + AppTheme.Light => "light", + AppTheme.Dark => "dark", + _ => "system", + }; + + public static string ParseLanguage(string? value) => + value is not null && Languages.Contains(value, StringComparer.Ordinal) ? value : "en"; +} diff --git a/src/FrameLedger.App/Services/ApplicationHostService.cs b/src/FrameLedger.App/Services/ApplicationHostService.cs new file mode 100644 index 00000000..53674452 --- /dev/null +++ b/src/FrameLedger.App/Services/ApplicationHostService.cs @@ -0,0 +1,21 @@ +using System.Windows; +using Microsoft.Extensions.Hosting; + +namespace FrameLedger.App.Services; + +/// Shows the shell once the host is up (the WPF UI template's idiom, under our own ). +internal sealed class ApplicationHostService(ShellHost shell) : IHostedService +{ + public Task StartAsync(CancellationToken cancellationToken) + { + if (System.Windows.Application.Current.Windows.OfType().Any()) + { + return Task.CompletedTask; + } + + shell.Show(); + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} diff --git a/src/FrameLedger.App/Services/IAgentLauncher.cs b/src/FrameLedger.App/Services/IAgentLauncher.cs new file mode 100644 index 00000000..7a46e9a4 --- /dev/null +++ b/src/FrameLedger.App/Services/IAgentLauncher.cs @@ -0,0 +1,15 @@ +namespace FrameLedger.App.Services; + +/// +/// 07_IPC §Client behavior: "on failure start the Agent, retry". The Agent is the one beside this +/// executable — 12_BUILD publishes both roots into one directory — and nothing else; the App never +/// searches for one. +/// +public interface IAgentLauncher +{ + /// Whether an Agent executable is beside this one at all. + bool CanLaunch { get; } + + /// Start FrameLedger.Agent.exe --serve, detached; false when it could not be started. + bool TryStart(); +} diff --git a/src/FrameLedger.App/Services/IThemeApplier.cs b/src/FrameLedger.App/Services/IThemeApplier.cs new file mode 100644 index 00000000..be6fd6a7 --- /dev/null +++ b/src/FrameLedger.App/Services/IThemeApplier.cs @@ -0,0 +1,13 @@ +using System.Windows; + +namespace FrameLedger.App.Services; + +/// +/// The WPF UI theme calls behind a seam, so a view model is testable without an Application +/// (ApplicationThemeManager touches Application.Current.Resources). +/// +public interface IThemeApplier +{ + /// Apply ; is watched for system changes when the choice is System, and unwatched otherwise. + void Apply(AppTheme theme, Window? window); +} diff --git a/src/FrameLedger.App/Services/ShellHost.cs b/src/FrameLedger.App/Services/ShellHost.cs new file mode 100644 index 00000000..a0f6d9a1 --- /dev/null +++ b/src/FrameLedger.App/Services/ShellHost.cs @@ -0,0 +1,52 @@ +using System.Windows; +using FrameLedger.App.Pages; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Wpf.Ui; + +namespace FrameLedger.App.Services; + +/// +/// Owns the live : shows the first one, rebuilds it on a language change +/// (09_I18N §Mechanics: "re-create the main window shell; state preserved via VM"), and turns the +/// user closing the live one into a host shutdown. The window is a transient service so a rebuild is a fresh +/// XAML load in the new culture; the application's ShutdownMode is explicit so that closing the OLD +/// window of a rebuild does not end the process. +/// +public sealed class ShellHost(IServiceProvider services, INavigationService navigation, IHostApplicationLifetime lifetime) +{ + private MainWindow? _current; + private Type _page = typeof(DashboardPage); + + public void Show() + { + MainWindow window = services.GetRequiredService(); + window.Closed += OnClosed; + _current = window; + window.Show(); + navigation.Navigate(_page); + } + + /// The page the shell will open on, kept across a rebuild. + public void Remember(Type page) => _page = page; + + /// A new window in the current UI culture; the old one closes after the new one is up. + public void Rebuild() + { + MainWindow? old = _current; + Show(); + old?.Close(); + } + + public Window? Current => _current; + + private void OnClosed(object? sender, EventArgs e) + { + // Only the live window's close is the user leaving; a rebuild's old window is not. + if (ReferenceEquals(sender, _current)) + { + _current = null; + lifetime.StopApplication(); + } + } +} diff --git a/src/FrameLedger.App/Services/UiIdentity.cs b/src/FrameLedger.App/Services/UiIdentity.cs new file mode 100644 index 00000000..0f8192b8 --- /dev/null +++ b/src/FrameLedger.App/Services/UiIdentity.cs @@ -0,0 +1,12 @@ +using System.Reflection; + +namespace FrameLedger.App.Services; + +/// What the App says about itself in Hello and in About. +internal static class UiIdentity +{ + public static string Version { get; } = + typeof(UiIdentity).Assembly.GetCustomAttribute()?.InformationalVersion + ?? typeof(UiIdentity).Assembly.GetName().Version?.ToString() + ?? "0.0.0"; +} diff --git a/src/FrameLedger.App/Services/UiPaths.cs b/src/FrameLedger.App/Services/UiPaths.cs new file mode 100644 index 00000000..83865d4b --- /dev/null +++ b/src/FrameLedger.App/Services/UiPaths.cs @@ -0,0 +1,24 @@ +using System.IO; +using FrameLedger.Infrastructure.Persistence; + +namespace FrameLedger.App.Services; + +/// +/// Where the App reads and logs: the Agent's data directory (01_ARCHITECTURE §Data directory — +/// ledger.db beside logs\ui-*.log). The App never chooses another location; the ledger is the +/// Agent's, and 06_DATA_MODEL §Writer ownership says which tables the App may write. +/// +internal static class UiPaths +{ + public static string DataDirectory => LedgerPaths.DefaultDirectory; + + public static string Database => LedgerPaths.DefaultDatabase; + + public static string Logs => Path.Combine(DataDirectory, "logs"); + + public static void EnsureDirectories() + { + Directory.CreateDirectory(DataDirectory); + Directory.CreateDirectory(Logs); + } +} diff --git a/src/FrameLedger.App/Services/UiThread.cs b/src/FrameLedger.App/Services/UiThread.cs new file mode 100644 index 00000000..2a8cabe4 --- /dev/null +++ b/src/FrameLedger.App/Services/UiThread.cs @@ -0,0 +1,27 @@ +using System.Diagnostics.CodeAnalysis; + +namespace FrameLedger.App.Services; + +/// +/// The thread a view model was built on, captured as its : the pipe's +/// events arrive on the thread pool, and property changes have to land on the dispatcher. Under WPF the +/// context is the dispatcher's; in a test without one the action runs inline, so a view model can be exercised +/// with no Application at all. +/// +public sealed class UiThread +{ + private readonly SynchronizationContext? _context = SynchronizationContext.Current; + + [SuppressMessage("Usage", "VSTHRD001:Avoid legacy thread switching APIs", Justification = "a WPF application has no JoinableTaskFactory; posting to the captured context is the documented way to reach the dispatcher from the thread pool, and it never blocks")] + public void Post(Action action) + { + ArgumentNullException.ThrowIfNull(action); + if (_context is null) + { + action(); + return; + } + + _context.Post(static state => ((Action)state!)(), action); + } +} diff --git a/src/FrameLedger.App/Services/WpfThemeApplier.cs b/src/FrameLedger.App/Services/WpfThemeApplier.cs new file mode 100644 index 00000000..6639b448 --- /dev/null +++ b/src/FrameLedger.App/Services/WpfThemeApplier.cs @@ -0,0 +1,41 @@ +using System.Windows; +using Wpf.Ui.Appearance; +using Wpf.Ui.Controls; + +namespace FrameLedger.App.Services; + +/// +/// 16_WPFUI_SYNTAX §Theme rules: manual Light/Dark through ApplicationThemeManager.Apply; System +/// through SystemThemeWatcher.Watch on the window — which needs an HWND, so the caller passes the window +/// from its Loaded handler and never from a constructor — and UnWatch when switching to manual. +/// +public sealed class WpfThemeApplier : IThemeApplier +{ + public void Apply(AppTheme theme, Window? window) + { + switch (theme) + { + case AppTheme.System: + ApplicationThemeManager.Apply(SystemIsDark() ? ApplicationTheme.Dark : ApplicationTheme.Light, WindowBackdropType.Mica, true); + if (window is { IsLoaded: true }) + { + SystemThemeWatcher.Watch(window, WindowBackdropType.Mica, true); + } + + break; + case AppTheme.Light: + case AppTheme.Dark: + if (window is not null) + { + SystemThemeWatcher.UnWatch(window); + } + + ApplicationThemeManager.Apply(theme == AppTheme.Dark ? ApplicationTheme.Dark : ApplicationTheme.Light, WindowBackdropType.Mica, true); + break; + default: + throw new ArgumentOutOfRangeException(nameof(theme), theme, "not a theme"); + } + } + + private static bool SystemIsDark() => ApplicationThemeManager.GetSystemTheme() is SystemTheme.Dark or SystemTheme.HCBlack or SystemTheme.Glow or SystemTheme.CapturedMotion; +} diff --git a/src/FrameLedger.App/Strings.Designer.cs b/src/FrameLedger.App/Strings.Designer.cs new file mode 100644 index 00000000..4ee2ceb7 --- /dev/null +++ b/src/FrameLedger.App/Strings.Designer.cs @@ -0,0 +1,225 @@ +// +// Generated by tools/resx-gen.ps1 from Strings.resx. DO NOT EDIT BY HAND: +// run the tool, or `./build.ps1 check` will fail the resx-audit gate on the drift. +// + +#nullable enable + +using System.CodeDom.Compiler; +using System.Globalization; +using System.Resources; + +namespace FrameLedger.App; + +/// The user-visible strings (docs/09_I18N.md), one property per key, read through the current UI culture. +[GeneratedCode("tools/resx-gen.ps1", "1")] +public static class Strings +{ + private static ResourceManager? _resourceManager; + + /// The culture the properties read with; null means the current UI culture. + public static CultureInfo? Culture { get; set; } + + public static ResourceManager ResourceManager => + _resourceManager ??= new ResourceManager("FrameLedger.App.Strings", typeof(Strings).Assembly); + + /// Every key, for an audit that walks them. + public static IReadOnlyList Keys { get; } = + [ + nameof(About_Body_Format), + nameof(About_Title), + nameof(Agent_Banner_Missing_Body), + nameof(Agent_Banner_Offline_Body), + nameof(Agent_Banner_Offline_Title), + nameof(Agent_Banner_Retry), + nameof(Agent_State_Connected), + nameof(Agent_State_Connecting), + nameof(Agent_State_Missing), + nameof(Agent_State_Offline), + nameof(Agent_State_Starting), + nameof(App_Title), + nameof(Common_Cancel), + nameof(Common_No), + nameof(Common_NotAvailable), + nameof(Common_Ok), + nameof(Common_Yes), + nameof(Compare_Empty), + nameof(Compare_Header), + nameof(Crash_Body), + nameof(Crash_Title), + nameof(Dashboard_Agent_Elevated), + nameof(Dashboard_Agent_Header), + nameof(Dashboard_Agent_Overlay), + nameof(Dashboard_Agent_Sessions), + nameof(Dashboard_Agent_State), + nameof(Dashboard_Agent_Telemetry), + nameof(Dashboard_Agent_Version), + nameof(Dashboard_Empty), + nameof(Dashboard_Header), + nameof(Games_Empty), + nameof(Games_Header), + nameof(Logs_Empty), + nameof(Logs_Header), + nameof(Menu_File), + nameof(Menu_File_AddGame), + nameof(Menu_File_Exit), + nameof(Menu_File_Export), + nameof(Menu_File_ImportLibrary), + nameof(Menu_Help), + nameof(Menu_Help_About), + nameof(Menu_Help_CheckUpdates), + nameof(Menu_Help_Documentation), + nameof(Menu_Help_ReportBug), + nameof(Menu_Tools), + nameof(Menu_Tools_AgentStatus), + nameof(Menu_Tools_DbMaintenance), + nameof(Menu_Tools_OpenDataFolder), + nameof(Menu_Tools_UpdateRules), + nameof(Menu_Tools_VulkanLayer), + nameof(Nav_Compare), + nameof(Nav_Dashboard), + nameof(Nav_Games), + nameof(Nav_Logs), + nameof(Nav_Settings), + nameof(NotYet_Body), + nameof(NotYet_Title), + nameof(Settings_Appearance_Header), + nameof(Settings_Header), + nameof(Settings_Language_Label), + nameof(Settings_Language_Note), + nameof(Settings_Theme_Dark), + nameof(Settings_Theme_Label), + nameof(Settings_Theme_Light), + nameof(Settings_Theme_System), + ]; + + 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); + + public static string Agent_Banner_Missing_Body => ResourceManager.GetString(nameof(Agent_Banner_Missing_Body), Culture) ?? nameof(Agent_Banner_Missing_Body); + + public static string Agent_Banner_Offline_Body => ResourceManager.GetString(nameof(Agent_Banner_Offline_Body), Culture) ?? nameof(Agent_Banner_Offline_Body); + + public static string Agent_Banner_Offline_Title => ResourceManager.GetString(nameof(Agent_Banner_Offline_Title), Culture) ?? nameof(Agent_Banner_Offline_Title); + + public static string Agent_Banner_Retry => ResourceManager.GetString(nameof(Agent_Banner_Retry), Culture) ?? nameof(Agent_Banner_Retry); + + public static string Agent_State_Connected => ResourceManager.GetString(nameof(Agent_State_Connected), Culture) ?? nameof(Agent_State_Connected); + + public static string Agent_State_Connecting => ResourceManager.GetString(nameof(Agent_State_Connecting), Culture) ?? nameof(Agent_State_Connecting); + + public static string Agent_State_Missing => ResourceManager.GetString(nameof(Agent_State_Missing), Culture) ?? nameof(Agent_State_Missing); + + public static string Agent_State_Offline => ResourceManager.GetString(nameof(Agent_State_Offline), Culture) ?? nameof(Agent_State_Offline); + + public static string Agent_State_Starting => ResourceManager.GetString(nameof(Agent_State_Starting), Culture) ?? nameof(Agent_State_Starting); + + public static string App_Title => ResourceManager.GetString(nameof(App_Title), Culture) ?? nameof(App_Title); + + public static string Common_Cancel => ResourceManager.GetString(nameof(Common_Cancel), Culture) ?? nameof(Common_Cancel); + + public static string Common_No => ResourceManager.GetString(nameof(Common_No), Culture) ?? nameof(Common_No); + + public static string Common_NotAvailable => ResourceManager.GetString(nameof(Common_NotAvailable), Culture) ?? nameof(Common_NotAvailable); + + public static string Common_Ok => ResourceManager.GetString(nameof(Common_Ok), Culture) ?? nameof(Common_Ok); + + public static string Common_Yes => ResourceManager.GetString(nameof(Common_Yes), Culture) ?? nameof(Common_Yes); + + public static string Compare_Empty => ResourceManager.GetString(nameof(Compare_Empty), Culture) ?? nameof(Compare_Empty); + + public static string Compare_Header => ResourceManager.GetString(nameof(Compare_Header), Culture) ?? nameof(Compare_Header); + + public static string Crash_Body => ResourceManager.GetString(nameof(Crash_Body), Culture) ?? nameof(Crash_Body); + + public static string Crash_Title => ResourceManager.GetString(nameof(Crash_Title), Culture) ?? nameof(Crash_Title); + + public static string Dashboard_Agent_Elevated => ResourceManager.GetString(nameof(Dashboard_Agent_Elevated), Culture) ?? nameof(Dashboard_Agent_Elevated); + + public static string Dashboard_Agent_Header => ResourceManager.GetString(nameof(Dashboard_Agent_Header), Culture) ?? nameof(Dashboard_Agent_Header); + + public static string Dashboard_Agent_Overlay => ResourceManager.GetString(nameof(Dashboard_Agent_Overlay), Culture) ?? nameof(Dashboard_Agent_Overlay); + + public static string Dashboard_Agent_Sessions => ResourceManager.GetString(nameof(Dashboard_Agent_Sessions), Culture) ?? nameof(Dashboard_Agent_Sessions); + + public static string Dashboard_Agent_State => ResourceManager.GetString(nameof(Dashboard_Agent_State), Culture) ?? nameof(Dashboard_Agent_State); + + public static string Dashboard_Agent_Telemetry => ResourceManager.GetString(nameof(Dashboard_Agent_Telemetry), Culture) ?? nameof(Dashboard_Agent_Telemetry); + + public static string Dashboard_Agent_Version => ResourceManager.GetString(nameof(Dashboard_Agent_Version), Culture) ?? nameof(Dashboard_Agent_Version); + + public static string Dashboard_Empty => ResourceManager.GetString(nameof(Dashboard_Empty), Culture) ?? nameof(Dashboard_Empty); + + public static string Dashboard_Header => ResourceManager.GetString(nameof(Dashboard_Header), Culture) ?? nameof(Dashboard_Header); + + public static string Games_Empty => ResourceManager.GetString(nameof(Games_Empty), Culture) ?? nameof(Games_Empty); + + public static string Games_Header => ResourceManager.GetString(nameof(Games_Header), Culture) ?? nameof(Games_Header); + + public static string Logs_Empty => ResourceManager.GetString(nameof(Logs_Empty), Culture) ?? nameof(Logs_Empty); + + public static string Logs_Header => ResourceManager.GetString(nameof(Logs_Header), Culture) ?? nameof(Logs_Header); + + public static string Menu_File => ResourceManager.GetString(nameof(Menu_File), Culture) ?? nameof(Menu_File); + + public static string Menu_File_AddGame => ResourceManager.GetString(nameof(Menu_File_AddGame), Culture) ?? nameof(Menu_File_AddGame); + + public static string Menu_File_Exit => ResourceManager.GetString(nameof(Menu_File_Exit), Culture) ?? nameof(Menu_File_Exit); + + public static string Menu_File_Export => ResourceManager.GetString(nameof(Menu_File_Export), Culture) ?? nameof(Menu_File_Export); + + public static string Menu_File_ImportLibrary => ResourceManager.GetString(nameof(Menu_File_ImportLibrary), Culture) ?? nameof(Menu_File_ImportLibrary); + + public static string Menu_Help => ResourceManager.GetString(nameof(Menu_Help), Culture) ?? nameof(Menu_Help); + + public static string Menu_Help_About => ResourceManager.GetString(nameof(Menu_Help_About), Culture) ?? nameof(Menu_Help_About); + + public static string Menu_Help_CheckUpdates => ResourceManager.GetString(nameof(Menu_Help_CheckUpdates), Culture) ?? nameof(Menu_Help_CheckUpdates); + + public static string Menu_Help_Documentation => ResourceManager.GetString(nameof(Menu_Help_Documentation), Culture) ?? nameof(Menu_Help_Documentation); + + public static string Menu_Help_ReportBug => ResourceManager.GetString(nameof(Menu_Help_ReportBug), Culture) ?? nameof(Menu_Help_ReportBug); + + public static string Menu_Tools => ResourceManager.GetString(nameof(Menu_Tools), Culture) ?? nameof(Menu_Tools); + + public static string Menu_Tools_AgentStatus => ResourceManager.GetString(nameof(Menu_Tools_AgentStatus), Culture) ?? nameof(Menu_Tools_AgentStatus); + + public static string Menu_Tools_DbMaintenance => ResourceManager.GetString(nameof(Menu_Tools_DbMaintenance), Culture) ?? nameof(Menu_Tools_DbMaintenance); + + public static string Menu_Tools_OpenDataFolder => ResourceManager.GetString(nameof(Menu_Tools_OpenDataFolder), Culture) ?? nameof(Menu_Tools_OpenDataFolder); + + public static string Menu_Tools_UpdateRules => ResourceManager.GetString(nameof(Menu_Tools_UpdateRules), Culture) ?? nameof(Menu_Tools_UpdateRules); + + public static string Menu_Tools_VulkanLayer => ResourceManager.GetString(nameof(Menu_Tools_VulkanLayer), Culture) ?? nameof(Menu_Tools_VulkanLayer); + + public static string Nav_Compare => ResourceManager.GetString(nameof(Nav_Compare), Culture) ?? nameof(Nav_Compare); + + public static string Nav_Dashboard => ResourceManager.GetString(nameof(Nav_Dashboard), Culture) ?? nameof(Nav_Dashboard); + + public static string Nav_Games => ResourceManager.GetString(nameof(Nav_Games), Culture) ?? nameof(Nav_Games); + + public static string Nav_Logs => ResourceManager.GetString(nameof(Nav_Logs), Culture) ?? nameof(Nav_Logs); + + public static string Nav_Settings => ResourceManager.GetString(nameof(Nav_Settings), Culture) ?? nameof(Nav_Settings); + + public static string NotYet_Body => ResourceManager.GetString(nameof(NotYet_Body), Culture) ?? nameof(NotYet_Body); + + public static string NotYet_Title => ResourceManager.GetString(nameof(NotYet_Title), Culture) ?? nameof(NotYet_Title); + + public static string Settings_Appearance_Header => ResourceManager.GetString(nameof(Settings_Appearance_Header), Culture) ?? nameof(Settings_Appearance_Header); + + public static string Settings_Header => ResourceManager.GetString(nameof(Settings_Header), Culture) ?? nameof(Settings_Header); + + public static string Settings_Language_Label => ResourceManager.GetString(nameof(Settings_Language_Label), Culture) ?? nameof(Settings_Language_Label); + + public static string Settings_Language_Note => ResourceManager.GetString(nameof(Settings_Language_Note), Culture) ?? nameof(Settings_Language_Note); + + public static string Settings_Theme_Dark => ResourceManager.GetString(nameof(Settings_Theme_Dark), Culture) ?? nameof(Settings_Theme_Dark); + + public static string Settings_Theme_Label => ResourceManager.GetString(nameof(Settings_Theme_Label), Culture) ?? nameof(Settings_Theme_Label); + + public static string Settings_Theme_Light => ResourceManager.GetString(nameof(Settings_Theme_Light), Culture) ?? nameof(Settings_Theme_Light); + + public static string Settings_Theme_System => ResourceManager.GetString(nameof(Settings_Theme_System), Culture) ?? nameof(Settings_Theme_System); +} diff --git a/src/FrameLedger.App/Strings.ja.resx b/src/FrameLedger.App/Strings.ja.resx new file mode 100644 index 00000000..e44517d1 --- /dev/null +++ b/src/FrameLedger.App/Strings.ja.resx @@ -0,0 +1,280 @@ + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + FrameLedger {0} — 明示的に有効化したゲーム内でグラフィックス API をフックし、ゲーム性能を計測します。GPLv3。 + review + + + FrameLedger について + review + + + このアプリの隣に FrameLedger.Agent.exe が見つかりません。セッションは閲覧できますが、ライブ状態とキャプチャ操作は利用できません。 + review + + + キャプチャエージェントが応答しません。ライブラリ、履歴、グラフは引き続き使えます。ライブ状態のみ利用できません。 + review + + + キャプチャエージェントがオフライン + review + + + 再試行 + review + + + エージェント接続済み + review + + + エージェントに接続中… + review + + + エージェント未インストール + review + + + エージェントはオフライン + review + + + エージェントを起動中… + review + + + FrameLedger + review + + + キャンセル + review + + + いいえ + review + + + N/A + review + + + OK + review + + + はい + review + + + 比較するセッションを 2〜5 個選んでください。ゲームが異なっても構いません。計測ティアが異なる場合は先に確認します。 + review + + + 比較 + review + + + FrameLedger は回復できないエラーに遭遇しました。詳細はログフォルダーにあります。キャプチャエージェントは動作を続けます。 + review + + + FrameLedger が予期せず停止しました + review + + + 管理者権限 + review + + + キャプチャエージェント + review + + + オーバーレイのビルド + review + + + 実行中のセッション + review + + + 状態 + review + + + テレメトリソース + review + + + エージェントのバージョン + review + + + まだセッションがありません。追跡中のゲームを起動すれば、あとは FrameLedger が行います。 + review + + + ダッシュボード + review + + + まだゲームがありません。「ファイル ▸ ゲームを追加…」から追加してください。 + review + + + ゲーム + review + + + ログビューアーは後のビルドで提供されます。ファイルはデータフォルダーの logs にあります。 + review + + + ログ + review + + + ファイル(_F) + review + + + ゲームを追加… + review + + + 終了(_X) + review + + + エクスポート + review + + + ライブラリをインポート… + review + + + ヘルプ(_H) + review + + + FrameLedger について + review + + + 更新を確認 + review + + + ドキュメント + review + + + 不具合を報告… + review + + + ツール(_T) + review + + + エージェントの状態… + review + + + データベースのメンテナンス… + review + + + データフォルダーを開く + review + + + 検出ルールを更新 + review + + + Vulkan レイヤーの登録… + review + + + 比較 + review + + + ダッシュボード + review + + + ゲーム + review + + + ログ + review + + + 設定 + review + + + この機能は後のビルドで提供されます。 + review + + + 未実装 + review + + + 外観 + review + + + 設定 + review + + + 言語 + review + + + すぐに適用されます。ウィンドウは新しい言語で再構築されます。 + review + + + ダーク + review + + + テーマ + review + + + ライト + review + + + システムに従う + review + + diff --git a/src/FrameLedger.App/Strings.resx b/src/FrameLedger.App/Strings.resx new file mode 100644 index 00000000..90412921 --- /dev/null +++ b/src/FrameLedger.App/Strings.resx @@ -0,0 +1,216 @@ + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + FrameLedger {0} — measures game performance by hooking graphics APIs inside games you explicitly enabled. GPLv3. + + + About FrameLedger + + + FrameLedger.Agent.exe was not found beside this application. Sessions are still readable; live status and capture control are not. + + + The capture agent is not answering. Your library, history and charts still work; only live status is unavailable. + + + Capture agent offline + + + Retry + + + Agent connected + + + Connecting to agent… + + + Agent not installed + + + Agent offline + + + Starting agent… + + + FrameLedger + + + Cancel + + + No + + + N/A + + + OK + + + Yes + + + Pick two to five sessions to compare — cross-game is fine; mixed capture tiers ask first. + + + Compare + + + FrameLedger hit an error it could not recover from. The details are in the log folder; the capture agent keeps running. + + + FrameLedger stopped unexpectedly + + + Elevated + + + Capture agent + + + Overlay build + + + Running sessions + + + State + + + Telemetry source + + + Agent version + + + No sessions yet — launch a tracked game and FrameLedger will do the rest. + + + Dashboard + + + No games yet — add one with File ▸ Add game… + + + Games + + + The log viewer arrives with a later build; the files are in the data folder under logs. + + + Logs + + + _File + + + Add game… + + + E_xit + + + Export + + + Import library… + + + _Help + + + About FrameLedger + + + Check for updates + + + Documentation + + + Report a bug… + + + _Tools + + + Agent status… + + + Database maintenance… + + + Open data folder + + + Update detection rules + + + Vulkan layer registration… + + + Compare + + + Dashboard + + + Games + + + Logs + + + Settings + + + This part of FrameLedger arrives with a later build. + + + Not built yet + + + Appearance + + + Settings + + + Language + + + Applies at once; the window is rebuilt in the new language. + + + Dark + + + Theme + + + Light + + + Follow system + + diff --git a/src/FrameLedger.App/Strings.vi.resx b/src/FrameLedger.App/Strings.vi.resx new file mode 100644 index 00000000..87f1ef25 --- /dev/null +++ b/src/FrameLedger.App/Strings.vi.resx @@ -0,0 +1,211 @@ + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + FrameLedger {0} — đo hiệu năng game bằng cách hook API đồ hoạ bên trong những game bạn đã bật rõ ràng. GPLv3. + + + Giới thiệu FrameLedger + + + Không tìm thấy FrameLedger.Agent.exe cạnh ứng dụng. Vẫn đọc được các phiên chơi; trạng thái trực tiếp và điều khiển thu thập thì không. + + + Capture agent không phản hồi. Thư viện, lịch sử và biểu đồ vẫn hoạt động; chỉ trạng thái trực tiếp là không có. + + + Capture agent ngoại tuyến + + + Thử lại + + + Đã kết nối agent + + + Đang kết nối agent… + + + Chưa cài agent + + + Agent ngoại tuyến + + + Đang khởi động agent… + + + FrameLedger + + + Huỷ + + + Không + + + N/A + + + OK + + + Có + + + Chọn hai đến năm phiên chơi để so sánh — khác game vẫn được; khác mức thu thập sẽ hỏi trước. + + + So sánh + + + 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. + + + FrameLedger dừng đột ngột + + + Quyền nâng cao + + + Capture agent + + + Bản build overlay + + + Phiên chơi đang chạy + + + Trạng thái + + + Nguồn telemetry + + + Phiên bản agent + + + Chưa có phiên chơi nào — khởi chạy một game đang theo dõi, FrameLedger sẽ lo phần còn lại. + + + Bảng điều khiển + + + Chưa có game nào — thêm bằng Tệp ▸ Thêm game… + + + Game + + + Trình xem log sẽ có ở bản sau; các tệp nằm trong thư mục dữ liệu, mục logs. + + + Log + + + _Tệp + + + Thêm game… + + + T_hoát + + + Xuất + + + Nhập thư viện… + + + Trợ _giúp + + + Giới thiệu FrameLedger + + + Kiểm tra cập nhật + + + Tài liệu + + + Báo lỗi… + + + _Công cụ + + + Trạng thái agent… + + + Bảo trì cơ sở dữ liệu… + + + Mở thư mục dữ liệu + + + Cập nhật quy tắc nhận diện + + + Đăng ký Vulkan layer… + + + So sánh + + + Bảng điều khiển + + + Game + + + Log + + + Cài đặt + + + Phần này của FrameLedger sẽ có ở bản sau. + + + Chưa xây dựng + + + Giao diện + + + Cài đặt + + + Ngôn ngữ + + + Áp dụng ngay; cửa sổ được dựng lại bằng ngôn ngữ mới. + + + Tối + + + Chủ đề + + + Sáng + + + Theo hệ thống + + diff --git a/src/FrameLedger.App/Styles/FrameLedger.xaml b/src/FrameLedger.App/Styles/FrameLedger.xaml new file mode 100644 index 00000000..2bd5c372 --- /dev/null +++ b/src/FrameLedger.App/Styles/FrameLedger.xaml @@ -0,0 +1,21 @@ + + + + + + + + diff --git a/src/FrameLedger.App/ViewModels/Choice.cs b/src/FrameLedger.App/ViewModels/Choice.cs new file mode 100644 index 00000000..a2255e8d --- /dev/null +++ b/src/FrameLedger.App/ViewModels/Choice.cs @@ -0,0 +1,4 @@ +namespace FrameLedger.App.ViewModels; + +/// A value and the text it shows as, for a ComboBox bound by value. +public sealed record Choice(T Value, string Label); diff --git a/src/FrameLedger.App/ViewModels/CompareViewModel.cs b/src/FrameLedger.App/ViewModels/CompareViewModel.cs new file mode 100644 index 00000000..f417f2bf --- /dev/null +++ b/src/FrameLedger.App/ViewModels/CompareViewModel.cs @@ -0,0 +1,11 @@ +using CommunityToolkit.Mvvm.ComponentModel; + +namespace FrameLedger.App.ViewModels; + +/// Compare (08_UI §Compare) arrives with P3 PR-7; until then the page is its empty state. +public sealed class CompareViewModel : ObservableObject +{ + public static string Header => Strings.Compare_Header; + + public static string EmptyText => Strings.Compare_Empty; +} diff --git a/src/FrameLedger.App/ViewModels/DashboardViewModel.cs b/src/FrameLedger.App/ViewModels/DashboardViewModel.cs new file mode 100644 index 00000000..e41420bb --- /dev/null +++ b/src/FrameLedger.App/ViewModels/DashboardViewModel.cs @@ -0,0 +1,63 @@ +using System.Globalization; +using CommunityToolkit.Mvvm.ComponentModel; +using FrameLedger.App.Services; +using FrameLedger.Shared.Ipc; + +namespace FrameLedger.App.ViewModels; + +/// +/// The Dashboard's Agent status card (08_UI §Dashboard): what HelloAck and StatusAck said, every +/// value N/A until the Agent answered — never a placeholder that reads as a measurement. +/// +public sealed partial class DashboardViewModel : ObservableObject, IDisposable +{ + private readonly AgentConnection _agent; + private readonly UiThread _ui = new(); + + [ObservableProperty] + private string _agentState = Strings.Agent_State_Connecting; + + [ObservableProperty] + private string _agentVersion = Strings.Common_NotAvailable; + + [ObservableProperty] + private string _telemetrySource = Strings.Common_NotAvailable; + + [ObservableProperty] + private string _overlayBuildId = Strings.Common_NotAvailable; + + [ObservableProperty] + private string _elevated = Strings.Common_NotAvailable; + + [ObservableProperty] + private string _runningSessions = Strings.Common_NotAvailable; + + public DashboardViewModel(AgentConnection agent) + { + _agent = agent ?? throw new ArgumentNullException(nameof(agent)); + _agent.Changed += OnAgentChanged; + Refresh(); + } + + public static string Header => Strings.Dashboard_Header; + + public static string AgentHeader => Strings.Dashboard_Agent_Header; + + public static string EmptyText => Strings.Dashboard_Empty; + + public void Dispose() => _agent.Changed -= OnAgentChanged; + + private void OnAgentChanged(object? sender, EventArgs e) => _ui.Post(Refresh); + + private void Refresh() + { + AgentState = AgentStatusPresentation.Pill(_agent.State).Text; + HelloAck? hello = _agent.Hello; + StatusAck? status = _agent.Status; + AgentVersion = hello?.AgentVersion ?? Strings.Common_NotAvailable; + TelemetrySource = hello?.TelemetrySource ?? Strings.Common_NotAvailable; + OverlayBuildId = hello?.OverlayBuildId ?? Strings.Common_NotAvailable; + Elevated = hello is null ? Strings.Common_NotAvailable : hello.Elevated ? Strings.Common_Yes : Strings.Common_No; + RunningSessions = status?.ActiveSessions.Count.ToString(CultureInfo.CurrentCulture) ?? Strings.Common_NotAvailable; + } +} diff --git a/src/FrameLedger.App/ViewModels/GamesViewModel.cs b/src/FrameLedger.App/ViewModels/GamesViewModel.cs new file mode 100644 index 00000000..cd32ff3a --- /dev/null +++ b/src/FrameLedger.App/ViewModels/GamesViewModel.cs @@ -0,0 +1,11 @@ +using CommunityToolkit.Mvvm.ComponentModel; + +namespace FrameLedger.App.ViewModels; + +/// Games (08_UI §Games) arrives with P3 PR-5; this build shows the empty state so the shell is honest about what it has. +public sealed class GamesViewModel : ObservableObject +{ + public static string Header => Strings.Games_Header; + + public static string EmptyText => Strings.Games_Empty; +} diff --git a/src/FrameLedger.App/ViewModels/LogsViewModel.cs b/src/FrameLedger.App/ViewModels/LogsViewModel.cs new file mode 100644 index 00000000..4fa68633 --- /dev/null +++ b/src/FrameLedger.App/ViewModels/LogsViewModel.cs @@ -0,0 +1,11 @@ +using CommunityToolkit.Mvvm.ComponentModel; + +namespace FrameLedger.App.ViewModels; + +/// Logs (08_UI §Logs) arrives with P3 PR-8; until then the page is its empty state. +public sealed class LogsViewModel : ObservableObject +{ + public static string Header => Strings.Logs_Header; + + public static string EmptyText => Strings.Logs_Empty; +} diff --git a/src/FrameLedger.App/ViewModels/MainWindowViewModel.cs b/src/FrameLedger.App/ViewModels/MainWindowViewModel.cs new file mode 100644 index 00000000..bc2df567 --- /dev/null +++ b/src/FrameLedger.App/ViewModels/MainWindowViewModel.cs @@ -0,0 +1,96 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using FrameLedger.App.Services; +using Microsoft.Extensions.Hosting; +using Wpf.Ui; +using Wpf.Ui.Controls; + +namespace FrameLedger.App.ViewModels; + +/// The shell's state: the Agent pill, the offline banner, and the menu commands that exist in this build. +public sealed partial class MainWindowViewModel : ObservableObject, IDisposable +{ + private readonly AgentConnection _agent; + private readonly ISnackbarService _snackbar; + private readonly IHostApplicationLifetime _lifetime; + private readonly UiThread _ui = new(); + + [ObservableProperty] + private string _agentStatusText = Strings.Agent_State_Connecting; + + [ObservableProperty] + private ControlAppearance _agentStatusAppearance = ControlAppearance.Info; + + [ObservableProperty] + private bool _isAgentBannerVisible; + + [ObservableProperty] + private string _agentBannerBody = string.Empty; + + public MainWindowViewModel(AgentConnection agent, ISnackbarService snackbar, IHostApplicationLifetime lifetime) + { + _agent = agent ?? throw new ArgumentNullException(nameof(agent)); + _snackbar = snackbar ?? throw new ArgumentNullException(nameof(snackbar)); + _lifetime = lifetime ?? throw new ArgumentNullException(nameof(lifetime)); + _agent.Changed += OnAgentChanged; + Refresh(); + } + + public static string Title => Strings.App_Title; + + public void Dispose() => _agent.Changed -= OnAgentChanged; + + private void OnAgentChanged(object? sender, EventArgs e) => _ui.Post(Refresh); + + private void Refresh() + { + (string text, ControlAppearance appearance) = AgentStatusPresentation.Pill(_agent.State); + AgentStatusText = text; + AgentStatusAppearance = appearance; + string? banner = AgentStatusPresentation.Banner(_agent.State); + AgentBannerBody = banner ?? string.Empty; + IsAgentBannerVisible = banner is not null; + } + + [RelayCommand] + private void RetryAgent() => _agent.RetryNow(); + + /// Exit is a host shutdown (App.RunAsync tears down and then ends the process), not a bare Application.Shutdown. + [RelayCommand] + private void Exit() => _lifetime.StopApplication(); + + [RelayCommand] + private static void OpenDataFolder() + { + try + { + using Process? _ = Process.Start(new ProcessStartInfo("explorer.exe", UiPaths.DataDirectory) { UseShellExecute = true }); + } + catch (Exception ex) when (ex is Win32Exception or InvalidOperationException) + { + Serilog.Log.Warning(ex, "ui: could not open the data folder"); + } + } + + [RelayCommand] + [SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format string is a resource that follows the UI culture, which changes at runtime; a cached CompositeFormat would pin the first culture")] + private static async Task AboutAsync() + { + var box = new MessageBox + { + Title = Strings.About_Title, + Content = string.Format(CultureInfo.CurrentCulture, Strings.About_Body_Format, UiIdentity.Version), + CloseButtonText = Strings.Common_Ok, + }; + await box.ShowDialogAsync().ConfigureAwait(true); + } + + /// Every menu item of 08_UI §Menu bar that a later slice builds says so, in a 4 s snackbar, rather than doing nothing. + [RelayCommand] + private void NotYet() => + _snackbar.Show(Strings.NotYet_Title, Strings.NotYet_Body, ControlAppearance.Secondary, new SymbolIcon(SymbolRegular.Info24), TimeSpan.FromSeconds(4)); +} diff --git a/src/FrameLedger.App/ViewModels/SettingsViewModel.cs b/src/FrameLedger.App/ViewModels/SettingsViewModel.cs new file mode 100644 index 00000000..d948fa56 --- /dev/null +++ b/src/FrameLedger.App/ViewModels/SettingsViewModel.cs @@ -0,0 +1,87 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using FrameLedger.App.Services; + +namespace FrameLedger.App.ViewModels; + +/// +/// Settings, the part this build has (08_UI §Settings — Appearance): theme applies at once and persists; +/// language persists and rebuilds the shell in the new culture (09_I18N §Mechanics). +/// +public sealed partial class SettingsViewModel : ObservableObject +{ + private readonly AppearanceSettings _appearance; + private readonly IThemeApplier _themes; + private readonly ShellHost _shell; + private readonly bool _loading = true; + + [ObservableProperty] + private AppTheme _selectedTheme; + + [ObservableProperty] + private string _selectedLanguage = "en"; + + public SettingsViewModel(AppearanceSettings appearance, IThemeApplier theme, ShellHost shell) + { + _appearance = appearance ?? throw new ArgumentNullException(nameof(appearance)); + _themes = theme ?? throw new ArgumentNullException(nameof(theme)); + _shell = shell ?? throw new ArgumentNullException(nameof(shell)); + SelectedTheme = appearance.Theme; + SelectedLanguage = appearance.Language; + _loading = false; + } + + public static string Header => Strings.Settings_Header; + + public static string AppearanceHeader => Strings.Settings_Appearance_Header; + + public static string ThemeLabel => Strings.Settings_Theme_Label; + + public static string LanguageLabel => Strings.Settings_Language_Label; + + public static string LanguageNote => Strings.Settings_Language_Note; + + public static IReadOnlyList> Themes { get; } = + [ + new(AppTheme.System, Strings.Settings_Theme_System), + new(AppTheme.Light, Strings.Settings_Theme_Light), + new(AppTheme.Dark, Strings.Settings_Theme_Dark), + ]; + + public static IReadOnlyList> Languages { get; } = + [ + new("en", "English"), + new("vi", "Tiếng Việt"), + new("ja", "日本語"), + ]; + + /// A pending write, for a test to await; the UI does not. + public Task Pending { get; private set; } = Task.CompletedTask; + + partial void OnSelectedThemeChanged(AppTheme value) + { + if (_loading) + { + return; + } + + _themes.Apply(value, _shell.Current); + Pending = _appearance.SetThemeAsync(value); + } + + partial void OnSelectedLanguageChanged(string value) + { + if (_loading || string.Equals(value, _appearance.Language, StringComparison.Ordinal)) + { + return; + } + + Pending = ApplyLanguageAsync(value); + } + + private async Task ApplyLanguageAsync(string value) + { + await _appearance.SetLanguageAsync(value).ConfigureAwait(true); + App.ApplyCulture(_appearance.Language); + _shell.Rebuild(); + } +} diff --git a/tests/FrameLedger.App.Tests/AgentConnectionTests.cs b/tests/FrameLedger.App.Tests/AgentConnectionTests.cs new file mode 100644 index 00000000..a7e9b50f --- /dev/null +++ b/tests/FrameLedger.App.Tests/AgentConnectionTests.cs @@ -0,0 +1,205 @@ +using FluentAssertions; +using FrameLedger.App.Services; +using FrameLedger.Application.Ipc; +using FrameLedger.Infrastructure.Ipc; +using FrameLedger.Shared.Ipc; + +namespace FrameLedger.App.Tests; + +/// +/// 07_IPC §Client behavior as a state machine, against a real in this process on +/// a test-named pipe: connect rounds, starting the Agent when it is absent, Hello on connect, offline +/// when the server goes, and connected again when it returns. The launcher is a fake that can start the server. +/// +public sealed class AgentConnectionTests : IAsyncDisposable +{ + private static readonly TimeSpan _wait = TimeSpan.FromSeconds(15); + private static readonly AgentIdentity _identity = new("agent-test", Environment.ProcessId, Elevated: false, "build-x", VulkanLayerRegistered: false, CpuTempAvailable: false); + private static readonly AgentConnectionOptions _fast = new() + { + ConnectAttempts = 3, + ConnectBackoff = TimeSpan.FromMilliseconds(30), + ConnectTimeout = TimeSpan.FromMilliseconds(300), + RetryInterval = TimeSpan.FromMilliseconds(200), + Keepalive = TimeSpan.FromMilliseconds(400), + RequestTimeout = TimeSpan.FromSeconds(5), + }; + + private readonly string _pipeName = "FrameLedger.test." + Guid.NewGuid().ToString("N"); + private readonly CancellationTokenSource _stop = new(); + private readonly List _seen = []; + private PipeServer? _server; + private Task? _serving; + private CancellationTokenSource? _serverStop; + private AgentConnection? _connection; + private Task? _running; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + /// A launcher that can be told whether an Agent is beside the App, and whose start brings the server up. + private sealed class FakeLauncher(Func start) : IAgentLauncher + { + public bool CanLaunch { get; set; } + + public int Starts { get; private set; } + + public bool TryStart() + { + Starts++; + return start(); + } + } + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync().ConfigureAwait(false); + if (_running is not null) + { + Task running = _running; + try + { + await running.ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + } + + if (_connection is not null) + { + await _connection.DisposeAsync().ConfigureAwait(false); + } + + await StopServerAsync().ConfigureAwait(false); + _stop.Dispose(); + } + + private void StartServer() + { + _serverStop = new CancellationTokenSource(); + _server = new PipeServer(new PipeServerOptions { PipeName = _pipeName }, + new AgentRequestHandler(_identity, static () => "l1", static () => AgentStatus.Idle)); + _serving = _server.RunAsync(_serverStop.Token); + } + + private async Task StopServerAsync() + { + if (_serverStop is null) + { + return; + } + + await _serverStop.CancelAsync().ConfigureAwait(false); + Task? serving = _serving; + if (serving is not null) + { + try + { + await serving.ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + } + + _server?.Dispose(); + _serverStop.Dispose(); + _serverStop = null; + _server = null; + _serving = null; + } + + private AgentConnection Start(FakeLauncher launcher) + { + _connection = new AgentConnection(launcher, () => new PipeClient(_pipeName), _fast, "app-test"); + _connection.Changed += (s, _) => + { + lock (_seen) + { + _seen.Add(((AgentConnection)s!).State); + } + }; + _running = _connection.RunAsync(_stop.Token); + return _connection; + } + + private static async Task WaitForAsync(Func condition, string because) + { + DateTimeOffset deadline = DateTimeOffset.UtcNow + _wait; + while (!condition() && DateTimeOffset.UtcNow < deadline) + { + await Task.Delay(25, Ct).ConfigureAwait(false); + } + + condition().Should().BeTrue(because); + } + + [Fact] + public async Task WithNoAgentBesideTheAppTheStateIsMissingAndNothingIsStarted() + { + var launcher = new FakeLauncher(static () => false) { CanLaunch = false }; + AgentConnection c = Start(launcher); + + await WaitForAsync(() => c.State == AgentConnectionState.Missing, "three attempts × 30 ms, nothing to start").ConfigureAwait(true); + await WaitForAsync(() => c.Rounds >= 2, "rounds continue in case an Agent appears").ConfigureAwait(true); + launcher.Starts.Should().Be(0); + c.Hello.Should().BeNull(); + } + + [Fact] + public async Task ARunningAgentIsFoundHelloedAndReportedConnected() + { + StartServer(); + var launcher = new FakeLauncher(static () => false) { CanLaunch = true }; + AgentConnection c = Start(launcher); + + await WaitForAsync(() => c.State == AgentConnectionState.Connected, "the server is up").ConfigureAwait(true); + c.Hello!.AgentVersion.Should().Be("agent-test"); + c.Status!.State.Should().Be(AgentStatus.IdleState); + launcher.Starts.Should().Be(0, "an answering Agent is never restarted"); + + // Keepalive: after a few intervals the connection is still connected (a ping that failed would drop it). + await Task.Delay(_fast.Keepalive * 3, Ct).ConfigureAwait(true); + c.State.Should().Be(AgentConnectionState.Connected); + (await c.RefreshStatusAsync(Ct).ConfigureAwait(true)).Should().NotBeNull(); + } + + [Fact] + public async Task WhenTheAgentIsAbsentItIsStartedFromBesideTheAppAndThenConnected() + { + // The fake launcher's "start" brings the server up, the way FrameLedger.Agent.exe --serve would. + FakeLauncher? launcher = null; + launcher = new FakeLauncher(() => + { + StartServer(); + return true; + }) + { CanLaunch = true }; + AgentConnection c = Start(launcher); + + await WaitForAsync(() => c.State == AgentConnectionState.Connected, "started, then connected on the second try").ConfigureAwait(true); + launcher.Starts.Should().Be(1); + c.Launches.Should().Be(1); + lock (_seen) + { + _seen.Should().Contain(AgentConnectionState.Starting, "the pill said so on the way"); + } + } + + [Fact] + public async Task ALostAgentIsOfflineAndAReturningOneIsConnectedAgain() + { + StartServer(); + var launcher = new FakeLauncher(static () => false) { CanLaunch = true }; + AgentConnection c = Start(launcher); + await WaitForAsync(() => c.State == AgentConnectionState.Connected, "up").ConfigureAwait(true); + + await StopServerAsync().ConfigureAwait(true); + await WaitForAsync(() => c.State is AgentConnectionState.Offline or AgentConnectionState.Connecting or AgentConnectionState.Starting, "the pipe dropped").ConfigureAwait(true); + await WaitForAsync(() => c.Rounds >= 1, "a new round ran").ConfigureAwait(true); + + StartServer(); + c.RetryNow(); + await WaitForAsync(() => c.State == AgentConnectionState.Connected && c.Hello is not null, "back").ConfigureAwait(true); + } +} diff --git a/tests/FrameLedger.App.Tests/AppearanceSettingsTests.cs b/tests/FrameLedger.App.Tests/AppearanceSettingsTests.cs new file mode 100644 index 00000000..11337bfc --- /dev/null +++ b/tests/FrameLedger.App.Tests/AppearanceSettingsTests.cs @@ -0,0 +1,69 @@ +using FluentAssertions; +using FrameLedger.App.Services; +using FrameLedger.Application.Persistence; + +namespace FrameLedger.App.Tests; + +/// The two appearance keys (settings registry, D16): tolerant reads, exact writes. +public sealed class AppearanceSettingsTests +{ + private sealed class FakeSettings : ISettingsStore + { + public Dictionary Rows { get; } = new(StringComparer.Ordinal); + + public ValueTask GetAsync(string key, CancellationToken ct = default) => ValueTask.FromResult(Rows.GetValueOrDefault(key)); + + public ValueTask SetAsync(string key, string value, CancellationToken ct = default) + { + Rows[key] = value; + return ValueTask.CompletedTask; + } + } + + [Fact] + public async Task NoRowsMeansSystemThemeAndEnglish() + { + var settings = new AppearanceSettings(new FakeSettings()); + await settings.LoadAsync(TestContext.Current.CancellationToken); + settings.Theme.Should().Be(AppTheme.System); + settings.Language.Should().Be("en"); + } + + [Fact] + public async Task AHandEditedUnknownValueIsTheDefaultNotAnException() + { + var store = new FakeSettings(); + store.Rows[AppearanceSettings.ThemeKey] = "purple"; + store.Rows[AppearanceSettings.LanguageKey] = "klingon"; + var settings = new AppearanceSettings(store); + await settings.LoadAsync(TestContext.Current.CancellationToken); + settings.Theme.Should().Be(AppTheme.System); + settings.Language.Should().Be("en"); + } + + [Fact] + public async Task WritesLandUnderTheRegistrysKeysAndReadBack() + { + var store = new FakeSettings(); + var settings = new AppearanceSettings(store); + await settings.SetThemeAsync(AppTheme.Dark, TestContext.Current.CancellationToken); + await settings.SetLanguageAsync("ja", TestContext.Current.CancellationToken); + + store.Rows.Should().Contain(AppearanceSettings.ThemeKey, "dark").And.Contain(AppearanceSettings.LanguageKey, "ja"); + + var again = new AppearanceSettings(store); + await again.LoadAsync(TestContext.Current.CancellationToken); + again.Theme.Should().Be(AppTheme.Dark); + again.Language.Should().Be("ja"); + } + + [Theory] + [InlineData(AppTheme.System, "system")] + [InlineData(AppTheme.Light, "light")] + [InlineData(AppTheme.Dark, "dark")] + public void ThemeTextRoundTrips(AppTheme theme, string text) + { + AppearanceSettings.ThemeText(theme).Should().Be(text); + AppearanceSettings.ParseTheme(text).Should().Be(theme); + } +} diff --git a/tests/FrameLedger.App.Tests/FrameLedger.App.Tests.csproj b/tests/FrameLedger.App.Tests/FrameLedger.App.Tests.csproj new file mode 100644 index 00000000..1fd1a1b8 --- /dev/null +++ b/tests/FrameLedger.App.Tests/FrameLedger.App.Tests.csproj @@ -0,0 +1,27 @@ + + + + false + FrameLedger.App.Tests + + true + win-x64 + + + + + + + + + + + + + + + + + + + diff --git a/tests/FrameLedger.App.Tests/StringsTests.cs b/tests/FrameLedger.App.Tests/StringsTests.cs new file mode 100644 index 00000000..0e964fbc --- /dev/null +++ b/tests/FrameLedger.App.Tests/StringsTests.cs @@ -0,0 +1,76 @@ +using System.Globalization; +using System.IO; +using System.Xml.Linq; +using FluentAssertions; + +namespace FrameLedger.App.Tests; + +/// +/// The generated accessor against the satellites the build produced: every key resolves in en, vi and ja +/// (a missing satellite would fall back to English silently, and this is the one place that would show), and +/// the accessor's key list is the resx's — the audit gate checks the same from the outside. +/// +public sealed class StringsTests +{ + private static readonly string[] _cultures = ["en", "vi", "ja"]; + + [Theory] + [InlineData("en")] + [InlineData("vi")] + [InlineData("ja")] + public void EveryKeyResolvesToANonEmptyStringIn(string culture) + { + var ci = CultureInfo.GetCultureInfo(culture); + foreach (string key in Strings.Keys) + { + Strings.ResourceManager.GetString(key, ci).Should().NotBeNullOrWhiteSpace($"{key} in {culture}"); + } + } + + [Fact] + public void TheSatellitesAreReallyLoadedNotTheEnglishFallback() + { + string en = Strings.ResourceManager.GetString(nameof(Strings.Nav_Settings), CultureInfo.GetCultureInfo("en"))!; + string vi = Strings.ResourceManager.GetString(nameof(Strings.Nav_Settings), CultureInfo.GetCultureInfo("vi"))!; + string ja = Strings.ResourceManager.GetString(nameof(Strings.Nav_Settings), CultureInfo.GetCultureInfo("ja"))!; + vi.Should().NotBe(en, "vi/FrameLedger.resources.dll must be beside the assembly"); + ja.Should().NotBe(en, "ja/FrameLedger.resources.dll must be beside the assembly"); + _cultures.Should().HaveCount(3); + } + + [Fact] + public void TheAccessorsKeysAreTheResxsKeys() + { + string resx = Path.Combine(RepoRoot(), "src", "FrameLedger.App", "Strings.resx"); + string[] keys = XDocument.Load(resx).Root!.Elements("data").Select(d => (string)d.Attribute("name")!).ToArray(); + Strings.Keys.Should().BeEquivalentTo(keys, "Strings.Designer.cs is generated from Strings.resx and committed; tools/resx-audit.ps1 fails on drift"); + } + + [Fact] + public void TheCulturePropertyOverridesTheThread() + { + CultureInfo? previous = Strings.Culture; + try + { + Strings.Culture = CultureInfo.GetCultureInfo("vi"); + Strings.Nav_Settings.Should().Be("Cài đặt"); + Strings.Culture = CultureInfo.GetCultureInfo("en"); + Strings.Nav_Settings.Should().Be("Settings"); + } + finally + { + Strings.Culture = previous; + } + } + + private static string RepoRoot() + { + string? dir = AppContext.BaseDirectory; + while (dir is not null && !File.Exists(Path.Combine(dir, "FrameLedger.slnx"))) + { + dir = Path.GetDirectoryName(dir); + } + + return dir ?? throw new InvalidOperationException("FrameLedger.slnx not found above the test binary"); + } +} diff --git a/tools/resx-audit.ps1 b/tools/resx-audit.ps1 new file mode 100644 index 00000000..29b7c3d1 --- /dev/null +++ b/tools/resx-audit.ps1 @@ -0,0 +1,238 @@ +#Requires -Version 7.0 +<# +.SYNOPSIS + The resx gate docs/09_I18N.md promised: every key in every language, safety strings reviewed as legal + text, and the generated accessor current. + +.DESCRIPTION + 09_I18N §Translation workflow: "CI check (tools/resx-audit): every key present in all three files". + This script did not exist for the first fourteen months the document named it; build.ps1 skipped the + step loudly, and 13_CI_CD and CLAUDE.md both recorded the absence. It exists as of P3 PR-2 (2026-09-13), + with the first .resx family. + + Per FAMILY (a neutral Strings.resx and its Strings..resx beside it, under src/): + 1. every key is a C# identifier, unique, and has a non-empty neutral value; + 2. every required culture file exists and carries EXACTLY the neutral key set — a missing key would + silently fall back to English, an extra one would be dead text nobody can reach; + 3. 09_I18N §Safety-critical strings: a `Safety_*` key in `ja` must carry a comment saying either + `safety: human review required` — and then its VALUE MUST BE THE ENGLISH VERBATIM, which is how + "shown as en until signed" is true by construction rather than by a runtime fallback the key-set + rule (2) forbids — or `safety: reviewed by `; a machine-drafted ban warning with neither is + the harm that section names, and it is red here; + 4. the committed Strings.Designer.cs is what tools/resx-gen.ps1 would write (the accessor is + generated and committed; drift is the silent failure mode of "generated"). + + FAIL-CLOSED WHEN NOTHING IS FOUND: no family under src/ means the gate would be vacuous, so it is red + rather than green — the same rule tools/package-closure-check.ps1 applies to a closure of two. + +.PARAMETER SelfTest + Runs the decision table in both directions on fixtures in a temp directory; at least four cases must + go RED for the run to pass, so a check that stopped checking cannot report a clean self-test. +#> +[CmdletBinding(DefaultParameterSetName = 'Check')] +param( + [Parameter(ParameterSetName = 'Check')] + [string]$Root = (Split-Path $PSScriptRoot -Parent), + + [Parameter(ParameterSetName = 'Check')] + [string[]]$Cultures = @('vi', 'ja'), + + [Parameter(ParameterSetName = 'SelfTest', Mandatory = $true)] + [switch]$SelfTest +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$script:Gen = Join-Path $PSScriptRoot 'resx-gen.ps1' +$script:ReviewRequired = 'safety: human review required' +$script:ReviewedBy = 'safety: reviewed by ' +$script:SafetyPrefix = 'Safety_' +$script:ReviewedCulture = 'ja' + +function Read-Resx([string]$path) { + [xml]$doc = Get-Content -Raw $path + $entries = @{} + $order = New-Object System.Collections.Generic.List[string] + $dups = New-Object System.Collections.Generic.List[string] + foreach ($d in @($doc.root.data)) { + if ($null -eq $d) { continue } + $name = [string]$d.name + if ($entries.ContainsKey($name)) { $dups.Add($name); continue } + $value = if ($null -ne $d.value) { [string]$d.value } else { '' } + $comment = if ($d.PSObject.Properties['comment'] -and $null -ne $d.comment) { [string]$d.comment } else { '' } + $entries[$name] = @{ Value = $value; Comment = $comment } + $order.Add($name) + } + return @{ Entries = $entries; Order = $order; Duplicates = $dups } +} + +<# + Returns the list of problems for one family; empty means it passes. A list, not a boolean, so the + live run can print every defect at once rather than the first one per build. +#> +function Test-ResxFamily([string]$neutralPath, [string[]]$cultures) { + $problems = New-Object System.Collections.Generic.List[string] + $rel = $neutralPath + $neutral = Read-Resx $neutralPath + foreach ($d in $neutral.Duplicates) { $problems.Add("$rel`: key '$d' appears twice") } + foreach ($k in $neutral.Order) { + if ($k -notmatch '^[A-Za-z][A-Za-z0-9_]*$') { $problems.Add("$rel`: key '$k' is not a C# identifier (09_I18N: Area_Element_Qualifier)") } + if ([string]::IsNullOrWhiteSpace($neutral.Entries[$k].Value)) { $problems.Add("$rel`: key '$k' has an empty neutral value") } + } + + if ($neutral.Order.Count -eq 0) { $problems.Add("$rel`: no keys at all") } + + $dir = Split-Path $neutralPath -Parent + $base = [IO.Path]::GetFileNameWithoutExtension($neutralPath) + foreach ($culture in $cultures) { + $culturePath = Join-Path $dir "$base.$culture.resx" + if (-not (Test-Path $culturePath)) { + $problems.Add("$rel`: no $culture file ($base.$culture.resx) — 09_I18N requires en, vi, ja") + continue + } + + $translated = Read-Resx $culturePath + foreach ($d in $translated.Duplicates) { $problems.Add("$culturePath`: key '$d' appears twice") } + foreach ($k in $neutral.Order) { + if (-not $translated.Entries.ContainsKey($k)) { $problems.Add("$culturePath`: key '$k' is missing (it would fall back to English silently)") } + } + + foreach ($k in $translated.Order) { + if (-not $neutral.Entries.ContainsKey($k)) { $problems.Add("$culturePath`: key '$k' does not exist in the neutral file (dead text)") } + } + + if ($culture -eq $script:ReviewedCulture) { + foreach ($k in $neutral.Order) { + if (-not $k.StartsWith($script:SafetyPrefix, [StringComparison]::Ordinal)) { continue } + if (-not $translated.Entries.ContainsKey($k)) { continue } + $comment = $translated.Entries[$k].Comment + $pending = $comment.Contains($script:ReviewRequired, [StringComparison]::Ordinal) + $reviewed = $comment.Contains($script:ReviewedBy, [StringComparison]::Ordinal) + if (-not ($pending -or $reviewed)) { + $problems.Add("$culturePath`: safety key '$k' carries neither '$($script:ReviewRequired)' nor '$($script:ReviewedBy)' — 09_I18N §Safety-critical strings: a mistranslated ban warning is a real harm") + } + elseif ($pending -and -not $reviewed -and $translated.Entries[$k].Value -cne $neutral.Entries[$k].Value) { + $problems.Add("$culturePath`: safety key '$k' is marked '$($script:ReviewRequired)' but carries text other than the English — until a reviewer signs, the value must be the en string verbatim (that is the fallback)") + } + } + } + } + + if (Test-Path $script:Gen) { + # The generator throws on a key it cannot name (caught above as a non-identifier) and exits 1 on drift. + try { + & $script:Gen -Resx $neutralPath -Check *> $null + if ($LASTEXITCODE -ne 0) { $problems.Add("$rel`: $base.Designer.cs is missing or stale — run tools/resx-gen.ps1 -Resx $rel") } + } + catch { + $problems.Add("$rel`: $($_.Exception.Message)") + } + } + else { + $problems.Add("tools/resx-gen.ps1 is missing, so the accessor cannot be checked") + } + + # Callers wrap this in @(): PowerShell unrolls a returned List, and an empty one becomes $null. + return $problems +} + +function Find-Families([string]$root) { + $src = Join-Path $root 'src' + if (-not (Test-Path $src)) { return @() } + return @(Get-ChildItem $src -Recurse -Filter '*.resx' -File | + Where-Object { $_.FullName -notmatch '\\(obj|bin)\\' } | + Where-Object { $_.Name -notmatch '\.[a-z]{2}(-[A-Za-z]{2,4})?\.resx$' }) +} + +function New-Fixture([string]$dir, [hashtable]$files) { + New-Item -ItemType Directory -Force $dir | Out-Null + foreach ($name in $files.Keys) { + $data = ($files[$name] | ForEach-Object { + $c = if ($_.ContainsKey('Comment')) { "$($_.Comment)" } else { '' } + " $($_.Value)$c" + }) -join "`n" + $xml = "`n`n text/microsoft-resx`n 2.0`n$data`n`n" + [IO.File]::WriteAllText((Join-Path $dir $name), $xml, [Text.UTF8Encoding]::new($false)) + } +} + +if ($SelfTest) { + $temp = Join-Path ([IO.Path]::GetTempPath()) ("fl-resx-audit-" + [Guid]::NewGuid().ToString('N')) + try { + $en = @(@{ Key = 'Nav_Home'; Value = 'Home' }, @{ Key = 'Safety_Warn'; Value = 'May result in a permanent ban.' }) + $vi = @(@{ Key = 'Nav_Home'; Value = 'Trang chủ' }, @{ Key = 'Safety_Warn'; Value = 'Có thể dẫn đến khoá tài khoản vĩnh viễn.' }) + $jaMarked = @(@{ Key = 'Nav_Home'; Value = 'ホーム'; Comment = 'review' }, @{ Key = 'Safety_Warn'; Value = 'May result in a permanent ban.'; Comment = 'safety: human review required' }) + $jaMarkedButTranslated = @(@{ Key = 'Nav_Home'; Value = 'ホーム' }, @{ Key = 'Safety_Warn'; Value = '機械翻訳'; Comment = 'safety: human review required' }) + $jaReviewed = @(@{ Key = 'Nav_Home'; Value = 'ホーム' }, @{ Key = 'Safety_Warn'; Value = '永久BANの可能性があります。'; Comment = 'safety: reviewed by A. Reviewer' }) + $jaUnmarked = @(@{ Key = 'Nav_Home'; Value = 'ホーム' }, @{ Key = 'Safety_Warn'; Value = '機械翻訳' }) + + $cases = @( + @{ Name = 'a complete family with the ja safety key marked for review passes'; Files = @{ 'Strings.resx' = $en; 'Strings.vi.resx' = $vi; 'Strings.ja.resx' = $jaMarked }; Gen = $true; ExpectFailure = $false } + @{ Name = 'a reviewed ja safety key passes'; Files = @{ 'Strings.resx' = $en; 'Strings.vi.resx' = $vi; 'Strings.ja.resx' = $jaReviewed }; Gen = $true; ExpectFailure = $false } + @{ Name = 'a ja safety key with no review comment FAILS'; Files = @{ 'Strings.resx' = $en; 'Strings.vi.resx' = $vi; 'Strings.ja.resx' = $jaUnmarked }; Gen = $true; ExpectFailure = $true } + @{ Name = 'a ja safety key marked for review that is not the English verbatim FAILS'; Files = @{ 'Strings.resx' = $en; 'Strings.vi.resx' = $vi; 'Strings.ja.resx' = $jaMarkedButTranslated }; Gen = $true; ExpectFailure = $true } + @{ Name = 'a key missing from vi FAILS'; Files = @{ 'Strings.resx' = $en; 'Strings.vi.resx' = @($vi[0]); 'Strings.ja.resx' = $jaMarked }; Gen = $true; ExpectFailure = $true } + @{ Name = 'a key only ja has FAILS'; Files = @{ 'Strings.resx' = $en; 'Strings.vi.resx' = $vi; 'Strings.ja.resx' = $jaMarked + @(@{ Key = 'Nav_Extra'; Value = 'x' }) }; Gen = $true; ExpectFailure = $true } + @{ Name = 'a missing culture file FAILS'; Files = @{ 'Strings.resx' = $en; 'Strings.vi.resx' = $vi }; Gen = $true; ExpectFailure = $true } + @{ Name = 'an empty neutral value FAILS'; Files = @{ 'Strings.resx' = @(@{ Key = 'Nav_Home'; Value = '' }); 'Strings.vi.resx' = @(@{ Key = 'Nav_Home'; Value = 'x' }); 'Strings.ja.resx' = @(@{ Key = 'Nav_Home'; Value = 'x' }) }; Gen = $true; ExpectFailure = $true } + @{ Name = 'a key that is not an identifier FAILS'; Files = @{ 'Strings.resx' = @(@{ Key = 'Nav-Home'; Value = 'x' }); 'Strings.vi.resx' = @(@{ Key = 'Nav-Home'; Value = 'x' }); 'Strings.ja.resx' = @(@{ Key = 'Nav-Home'; Value = 'x' }) }; Gen = $false; ExpectFailure = $true } + @{ Name = 'a stale Designer FAILS'; Files = @{ 'Strings.resx' = $en; 'Strings.vi.resx' = $vi; 'Strings.ja.resx' = $jaMarked }; Gen = $true; Stale = $true; ExpectFailure = $true } + @{ Name = 'a missing Designer FAILS'; Files = @{ 'Strings.resx' = $en; 'Strings.vi.resx' = $vi; 'Strings.ja.resx' = $jaMarked }; Gen = $false; ExpectFailure = $true } + ) + + $failures = 0 + $reds = 0 + $i = 0 + foreach ($case in $cases) { + $dir = Join-Path $temp ("case" + ($i++)) + New-Fixture $dir $case.Files + # No -Namespace: the check side derives it the same way (no csproj -> the directory name). + if ($case.Gen) { & $script:Gen -Resx (Join-Path $dir 'Strings.resx') *> $null } + if ($case.ContainsKey('Stale') -and $case.Stale) { Add-Content (Join-Path $dir 'Strings.Designer.cs') '// edited by hand' } + $problems = @(Test-ResxFamily (Join-Path $dir 'Strings.resx') @('vi', 'ja')) + $failed = $problems.Count -gt 0 + if ($failed) { $reds++ } + if ($failed -eq $case.ExpectFailure) { + Write-Host " ok $($case.Name)" -ForegroundColor DarkGray + } + else { + $expected = if ($case.ExpectFailure) { 'a failure' } else { 'a pass' } + Write-Host " FAIL $($case.Name) — expected $expected, got: $($problems -join '; ')" -ForegroundColor Red + $failures++ + } + } + + if ($failures -gt 0 -or $reds -lt 4) { + Write-Host "RESX AUDIT SELF-TEST FAILED: $failures wrong verdict(s), $reds red case(s) (at least 4 required)" -ForegroundColor Red + exit 1 + } + + Write-Host "resx-audit self-test: $($cases.Count) cases, $reds red, both directions" -ForegroundColor Green + exit 0 + } + finally { + Remove-Item -Recurse -Force $temp -ErrorAction SilentlyContinue + } +} + +$families = @(Find-Families $Root) +if ($families.Count -eq 0) { + Write-Host 'RESX AUDIT FAILED: no .resx family under src/ — the gate would be vacuous (09_I18N names three languages; the first family arrived with P3 PR-2)' -ForegroundColor Red + exit 1 +} + +$all = New-Object System.Collections.Generic.List[string] +foreach ($f in $families) { + $problems = @(Test-ResxFamily $f.FullName $Cultures) + foreach ($p in $problems) { $all.Add($p) } +} + +if ($all.Count -gt 0) { + Write-Host "RESX AUDIT FAILED: $($all.Count) problem(s)" -ForegroundColor Red + foreach ($p in $all) { Write-Host " $p" -ForegroundColor Red } + exit 1 +} + +Write-Host "resx-audit: ok — $($families.Count) family(ies), cultures $($Cultures -join ', '), accessors current" -ForegroundColor Green +exit 0 diff --git a/tools/resx-gen.ps1 b/tools/resx-gen.ps1 new file mode 100644 index 00000000..5165c723 --- /dev/null +++ b/tools/resx-gen.ps1 @@ -0,0 +1,121 @@ +#Requires -Version 7.0 +<# +.SYNOPSIS + Generates the strongly-typed accessor (Strings.Designer.cs) for a neutral .resx, or checks that the + committed one is current. + +.DESCRIPTION + docs/09_I18N.md: user-visible text is reached "through a generated strongly-typed class; no string + literals in XAML/C#". Visual Studio's ResXFileCodeGenerator is a design-time tool and `dotnet build` + never runs it, and MSBuild on .NET Core cannot generate the class itself (GenerateResource's + StronglyTypedLanguage is unsupported there). So the accessor is GENERATED BY THIS SCRIPT AND COMMITTED, + and tools/resx-audit.ps1 fails the build when the committed file is not what this script would write — + which is what makes "generated" true rather than a word in a comment. + + One property per key, sorted, `ResourceManager.GetString(key, Culture)`. The resource base name is + `.`, which is what the SDK embeds a `.resx` sitting in the project + directory as. The namespace comes from the csproj in the same directory (, else the + project file name); a directory with no csproj — the audit's self-test fixtures — uses the directory name. + +.PARAMETER Resx + The NEUTRAL resx (Strings.resx, never Strings.vi.resx). + +.PARAMETER Check + Do not write; exit 1 when the committed Designer differs from what would be written (or is absent). +#> +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [string]$Resx, + + [string]$Namespace, + + [string]$ClassName, + + [switch]$Check +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$resxPath = (Resolve-Path $Resx).Path +$dir = Split-Path $resxPath -Parent +if (-not $ClassName) { $ClassName = [IO.Path]::GetFileNameWithoutExtension($resxPath) } +if ($ClassName -match '\.') { throw "resx-gen: '$Resx' looks like a culture-specific file; pass the neutral one" } + +if (-not $Namespace) { + $csproj = Get-ChildItem $dir -Filter '*.csproj' -File | Select-Object -First 1 + if ($csproj) { + [xml]$proj = Get-Content -Raw $csproj.FullName + $rootNs = $proj.SelectSingleNode('//RootNamespace') + $Namespace = if ($rootNs -and $rootNs.InnerText.Trim()) { $rootNs.InnerText.Trim() } else { [IO.Path]::GetFileNameWithoutExtension($csproj.Name) } + } + else { + $Namespace = Split-Path $dir -Leaf + } +} + +[xml]$doc = Get-Content -Raw $resxPath +$keys = @($doc.root.data | ForEach-Object { $_.name } | Sort-Object -Culture 'en-US' -CaseSensitive) +foreach ($k in $keys) { + if ($k -notmatch '^[A-Za-z][A-Za-z0-9_]*$') { throw "resx-gen: key '$k' is not a C# identifier" } +} + +$lines = New-Object System.Collections.Generic.List[string] +$lines.Add('// ') +$lines.Add("// Generated by tools/resx-gen.ps1 from $([IO.Path]::GetFileName($resxPath)). DO NOT EDIT BY HAND:") +$lines.Add('// run the tool, or `./build.ps1 check` will fail the resx-audit gate on the drift.') +$lines.Add('// ') +$lines.Add('') +$lines.Add('#nullable enable') +$lines.Add('') +$lines.Add('using System.CodeDom.Compiler;') +$lines.Add('using System.Globalization;') +$lines.Add('using System.Resources;') +$lines.Add('') +$lines.Add("namespace $Namespace;") +$lines.Add('') +$lines.Add('/// The user-visible strings (docs/09_I18N.md), one property per key, read through the current UI culture.') +$lines.Add('[GeneratedCode("tools/resx-gen.ps1", "1")]') +$lines.Add("public static class $ClassName") +$lines.Add('{') +$lines.Add(' private static ResourceManager? _resourceManager;') +$lines.Add('') +$lines.Add(' /// The culture the properties read with; null means the current UI culture.') +$lines.Add(' public static CultureInfo? Culture { get; set; }') +$lines.Add('') +$lines.Add(' public static ResourceManager ResourceManager =>') +$lines.Add(" _resourceManager ??= new ResourceManager(""$Namespace.$ClassName"", typeof($ClassName).Assembly);") +$lines.Add('') +$lines.Add(' /// Every key, for an audit that walks them.') +$lines.Add(' public static IReadOnlyList Keys { get; } =') +$lines.Add(' [') +foreach ($k in $keys) { $lines.Add(" nameof($k),") } +$lines.Add(' ];') +foreach ($k in $keys) { + $lines.Add('') + $lines.Add(" public static string $k => ResourceManager.GetString(nameof($k), Culture) ?? nameof($k);") +} +$lines.Add('}') +$text = ($lines -join "`r`n") + "`r`n" + +$outPath = Join-Path $dir "$ClassName.Designer.cs" +if ($Check) { + if (-not (Test-Path $outPath)) { + Write-Host "resx-gen: $outPath is missing — run tools/resx-gen.ps1 -Resx $Resx" -ForegroundColor Red + exit 1 + } + + $existing = [IO.File]::ReadAllText($outPath) -replace "`r`n", "`n" + if ($existing -ne ($text -replace "`r`n", "`n")) { + Write-Host "resx-gen: $outPath is not what $([IO.Path]::GetFileName($resxPath)) generates — run tools/resx-gen.ps1 -Resx $Resx" -ForegroundColor Red + exit 1 + } + + Write-Host "resx-gen: $outPath is current ($($keys.Count) key(s))" -ForegroundColor DarkGray + exit 0 +} + +[IO.File]::WriteAllText($outPath, $text, [Text.UTF8Encoding]::new($false)) +Write-Host "resx-gen: wrote $outPath ($($keys.Count) key(s), namespace $Namespace)" -ForegroundColor Green +exit 0