diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..353096f6 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,203 @@ +# FrameLedger release (docs/13_CI_CD.md §release.yml, docs/12_BUILD.md §Publish & package). +# +# On a tag `v*`: the same gate ci.yml runs, then publish → pack → checksums → +# a GitHub Release whose body is CHANGELOG.md's section for the version. Three +# things are refused loudly rather than papered over, because a release is the +# one artefact nobody can re-run: +# - the tag's numeric core must equal the VERSION file (the one version source; +# the native VERSIONINFO blocks are built from it and versioninfo-check +# compares them); +# - CHANGELOG.md must carry a non-empty `## [x.y.z]` section for the tag +# (tools/release-notes.ps1) — an empty release body is a defect, not a default; +# - the published tree must hold both entry points and every shipped native +# binary, checked by name, because `dotnet publish` warns rather than fails +# when a .targets-staged DLL is missing. +# +# Unsigned by policy (11_UPDATER §Unsigned releases): SHA256SUMS.txt is published +# beside the assets and printed into the release body. +# +# A pre-release tag (`v0.1.0-beta.1`, 13_CI_CD §Branch & release policy) marks the +# GitHub release as pre-release; the App's stable channel ignores it and the beta +# channel sees it. The managed assemblies take the tag's full version through +# -p:Version; the native blocks keep the numeric core (CMake's project() accepts +# nothing else). + +name: Release + +on: + push: + tags: ['v*'] + +# The Release API is contents: write; nothing else is needed and nothing else is granted. +permissions: + contents: write + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +jobs: + release: + runs-on: windows-latest + timeout-minutes: 60 + + steps: + - uses: actions/checkout@v7 + + - name: Set up .NET + uses: actions/setup-dotnet@v6 + with: + global-json-file: global.json + + - name: Set up MSVC (x64) + uses: ilammy/msvc-dev-cmd@v1 + with: + arch: x64 + + # Same pin as ci.yml, for the same reason (the gate's clang-format step). + - name: Pin clang-format + shell: pwsh + run: | + pip install --disable-pip-version-check "clang-format==22.1.3" + clang-format --version + + - name: Cache NuGet + uses: actions/cache@v6 + with: + path: ~/.nuget/packages + key: nuget-${{ runner.os }}-${{ hashFiles('**/Directory.Packages.props', 'global.json') }} + restore-keys: nuget-${{ runner.os }}- + + - name: Version gate (tag vs VERSION, CHANGELOG section) + id: version + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $tag = $env:GITHUB_REF_NAME + $m = [regex]::Match($tag, '^v(\d+\.\d+\.\d+)(-[0-9A-Za-z.]+)?$') + if (-not $m.Success) { throw "tag '$tag' is not vMAJOR.MINOR.PATCH[-prerelease]" } + $full = $tag.Substring(1) + $core = $m.Groups[1].Value + $pre = if ($m.Groups[2].Success) { 'true' } else { 'false' } + $file = (Get-Content VERSION -Raw).Trim() + if ($core -ne $file) { throw "tag $tag has numeric core $core but VERSION says $file — bump VERSION in the same commit as the changelog section, then tag" } + New-Item -ItemType Directory -Force out | Out-Null + ./tools/release-notes.ps1 -Version $full -OutFile out/notes.md + if ($LASTEXITCODE -ne 0) { throw 'release notes' } + "version=$full" >> $env:GITHUB_OUTPUT + "prerelease=$pre" >> $env:GITHUB_OUTPUT + Write-Host "releasing $full (pre-release: $pre)" + + # 12_BUILD §Release-time token substitution: the effective date of a legal + # document is the date it ships. The only placeholder that survives into the + # repository, substituted here and nowhere else; the App embeds legal/*.md at + # build time, so this runs BEFORE the build. + - name: Substitute {{RELEASE_DATE}} + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $date = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') + $n = 0 + foreach ($f in Get-ChildItem legal -Filter *.md) { + $t = Get-Content $f.FullName -Raw + if ($t.Contains('{{RELEASE_DATE}}')) { + [System.IO.File]::WriteAllText($f.FullName, $t.Replace('{{RELEASE_DATE}}', $date), [System.Text.UTF8Encoding]::new($false)) + $n++ + } + } + Write-Host "RELEASE_DATE = $date in $n file(s)" + if (Select-String -Path legal/*.md, README.md -Pattern '\{\{' -Quiet) { throw 'a {{ token survived substitution' } + + # The identical gate ci.yml runs — native build, tests, every check including + # versioninfo-check against VERSION. A release never skips it. + - name: Quality gate + shell: pwsh + run: ./build.ps1 check + env: + CI: 'true' + + - name: Publish App + Agent (self-contained, ReadyToRun) + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $v = '${{ steps.version.outputs.version }}' + dotnet publish src/FrameLedger.App -c Release -r win-x64 --self-contained -p:PublishReadyToRun=true -p:Version=$v -o out/app + if ($LASTEXITCODE -ne 0) { throw 'App publish failed' } + dotnet publish src/FrameLedger.Agent -c Release -r win-x64 --self-contained -p:PublishReadyToRun=true -p:Version=$v -o out/app + if ($LASTEXITCODE -ne 0) { throw 'Agent publish failed' } + + # What ships is what matters: the two entry points and the four shipped native + # binaries (versioninfo-check's list) must be in the tree, and the unshipped + # capture host must not be (package-closure-check proves it statically; this + # reads the directory). + - name: Assert the published tree + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $required = 'FrameLedger.exe', 'FrameLedger.Agent.exe', 'FrameLedger.Overlay.dll', 'FrameLedger.VkLayer.dll', 'FrameLedger.Guard.dll', 'FrameLedger.NvapiBridge.dll', 'rules/detection-rules.json' + $missing = @($required | Where-Object { -not (Test-Path (Join-Path out/app $_)) }) + if ($missing.Count -gt 0) { throw "out/app is missing: $($missing -join ', ')" } + if (Test-Path out/app/FrameLedger.CaptureHost.exe) { throw 'out/app contains the unshipped capture host (12_BUILD: exactly two roots)' } + ./tools/versioninfo-check.ps1 -BuildDir out/app + if ($LASTEXITCODE -ne 0) { throw 'versioninfo-check over the published tree' } + $size = (Get-ChildItem out/app -Recurse -File | Measure-Object Length -Sum).Sum / 1MB + Write-Host ("published tree: {0:N0} MB" -f $size) + + # Velopack's packer, pinned to the library version the App references + # (Directory.Packages.props). No --icon: assets/icon.ico does not exist yet + # (12_BUILD §Publish & package says so rather than pointing at a file that is not there). + # + # --packId is FrameLedger.App, NOT FrameLedger, and that is a data-loss rule: + # Velopack installs into %LOCALAPPDATA%\ and deletes that directory on + # uninstall, and %LOCALAPPDATA%\FrameLedger is the DATA folder (LedgerPaths: + # ledger.db, logs, the layer manifest). The same id would put the install inside + # the ledger's folder and have the uninstaller remove every session without the + # question 12_BUILD promises. The title the user sees is still "FrameLedger". + - name: Pack (Velopack) + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + dotnet tool install -g vpk --version 1.2.0 + if ($LASTEXITCODE -ne 0) { throw 'vpk install failed' } + $v = '${{ steps.version.outputs.version }}' + vpk pack --packId FrameLedger.App --packVersion $v --packDir out/app --mainExe FrameLedger.exe --packTitle FrameLedger --packAuthors FrameLedger --releaseNotes out/notes.md --outputDir out/release + if ($LASTEXITCODE -ne 0) { throw 'vpk pack failed' } + Get-ChildItem out/release | ForEach-Object { Write-Host (" {0,-48} {1,12:N0}" -f $_.Name, $_.Length) } + if (-not (Test-Path out/release/FrameLedger.App-win-Setup.exe)) { throw 'vpk did not produce FrameLedger.App-win-Setup.exe (README §Install names it)' } + + - name: Checksums + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $lines = Get-ChildItem out/release -File | Sort-Object Name | ForEach-Object { + '{0} {1}' -f (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant(), $_.Name + } + [System.IO.File]::WriteAllLines('out/release/SHA256SUMS.txt', $lines, [System.Text.UTF8Encoding]::new($false)) + $notes = Get-Content out/notes.md -Raw + $notes += "`n`n## SHA-256`n`nReleases are not code-signed (11_UPDATER). Verify before running:`n`n``````text`n" + ($lines -join "`n") + "`n``````" + [System.IO.File]::WriteAllText('out/notes.md', $notes, [System.Text.UTF8Encoding]::new($false)) + Get-Content out/release/SHA256SUMS.txt + + - name: Create the GitHub Release + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + run: | + $ErrorActionPreference = 'Stop' + $v = '${{ steps.version.outputs.version }}' + $ghArgs = @('release', 'create', $env:GITHUB_REF_NAME, '--title', "FrameLedger $v", '--notes-file', 'out/notes.md', '--verify-tag') + if ('${{ steps.version.outputs.prerelease }}' -eq 'true') { $ghArgs += '--prerelease' } + $ghArgs += Get-ChildItem out/release -File | ForEach-Object { $_.FullName } + gh @ghArgs + if ($LASTEXITCODE -ne 0) { throw 'gh release create failed' } + + - name: Upload the published tree (for the smoke checklist) + if: always() + uses: actions/upload-artifact@v7 + with: + name: release-${{ github.ref_name }} + path: | + out/release/** + out/notes.md + if-no-files-found: warn + retention-days: 30 diff --git a/CHANGELOG.md b/CHANGELOG.md index a4fc2d2d..f47892e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,19 +6,59 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versioning: [Semantic Versioning](https://semver.org/spec/v2.0.0.html) — `MAJOR` bumps for a database schema or IPC protocol break (`docs/11_UPDATER.md`). -`release.yml` **will** read the section for the tag being released and use it as the -GitHub release body, so a missing section will mean an empty release note. +`release.yml` reads the section for the tag being released (`tools/release-notes.ps1`) and +uses it as the GitHub release body. A missing or empty `## [x.y.z]` section is a **red +release**, not an empty note — so cutting a release means moving the `[Unreleased]` entries +under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, then tagging +(`docs/13_CI_CD.md` §Branch & release policy). -> **It does not exist yet** — `.github/workflows/` holds `ci.yml`, `codeql.yml` and -> `rules-publish.yml` only, and `docs/13_CI_CD.md` records that. Written in the future -> tense here from 2026-08-06 rather than describing a workflow nobody has. Note also -> that this file has no `## [x.y.z]` heading yet, so the first release needs one -> created before a tag has anything to find. +> **Built 2026-09-14 (P4 PR-5).** From 2026-08-06 until then this paragraph said the workflow +> "will" exist and that a missing section "will mean an empty release note"; the second half +> was the wrong design and is replaced rather than implemented. This file still has no +> `## [x.y.z]` heading: the first one is the owner's, in the commit that cuts the first tag. ## [Unreleased] ### Added +- **P4 PR-5 — Velopack, the updater, `release.yml`, and one version source (`11_UPDATER`, 2026-09-14).** + `FrameLedger.App/Update/`: `VelopackUpdateClient` behind the `IUpdateClient` port (Velopack's `UpdateManager` over + its GitHub source for this repository; the `stable` channel is the releases GitHub does not mark pre-release, `beta` + adds the ones it does), `UpdateFailureMapper` (the §Error mapping rows from the exception: 404 / 403+429 / 5xx / + transport / checksum / unknown; an HttpClient timeout is Offline, not a cancel), `FrameLedgerFileDownloader` (Velopack's + downloader with `User-Agent: FrameLedger/`), `UpdateService` — the startup silent check 5 s after start when the copy is + installed and the new `update.auto_check` setting (default on) says so, every failure a log line; Help ▸ Check for + updates with the dialogs (`UpdatePrompts` over WPF-UI's `MessageBox`: the offer with the release notes and the + unsigned-release footer, up to date, not an installed copy, the six error rows — a 404 offers the releases page, an + unknown failure offers the bug report); the background download, retried once on a checksum failure; and **FR-12 as the shape of the whole thing**: a + downloaded package is `Ready` only while the Agent reports no session, otherwise `Deferred` until the last + `SessionCompleted`, and the apply itself is refused with a session running. The apply (`Restart to update`, the + shell's new persistent InfoBar) sends `Shutdown` to the Agent, holds the connection's relaunch (`IAgentLink.SetLaunchHold`), + waits for the pipe to drop (an Agent that does not stop in 10 s leaves everything as it was), hands Velopack the + package (`WaitExitThenApplyUpdates`) and ends the host; the restarted App starts the Agent beside itself as always, + and — when Velopack reports the restart — re-validates the logon task's action path (`--install-task` on `Stale`). + `Program.Main` is now hand-written so `VelopackApp.Run()` precedes any window: the uninstall hook (`UninstallHook`, + delegates for the test) asks a running Agent to stop, unregisters the Vulkan layer, removes the logon task and + **asks** about the data folder (deleted on Yes only; unanswered inside Velopack's 30 s budget keeps it); install + registers nothing. The tray raises "update available" as a balloon only while the window is off screen. Settings ▸ + Updates gained the startup-check toggle and the channel row's real text. **One version source:** `VERSION` at the + repository root, read by `Directory.Build.props` (``, SourceLink's `+sha` suffix off) and by + `src/native/CMakeLists.txt`, with `versioninfo-check` comparing every built binary's `FileVersion` against it. + **`release.yml`** on a `v*` tag: the tag's numeric core must equal `VERSION` and `CHANGELOG.md` must carry a + non-empty `## [x.y.z]` section (`tools/release-notes.ps1`, self-tested in `build.ps1`), `{{RELEASE_DATE}}` + substituted before the build, the identical gate, publish App + Agent self-contained + ReadyToRun with + `-p:Version=`, the published tree asserted by name (both entry points, the four shipped natives, the rules + seed, no capture host), `vpk pack`, `SHA256SUMS.txt` printed into the release body, `gh release create` + (`--prerelease` for a `-beta.N` tag). **The package id is `FrameLedger.App`**: Velopack installs into and, on + uninstall, deletes `%LOCALAPPDATA%\`, and `%LOCALAPPDATA%\FrameLedger` is the data folder — the id the docs + named would have removed every user's ledger without asking (`UninstallHook.AreSeparate` now refuses the data delete + if the two ever overlap). Published locally before the PR: 250 MB in 362 files, every assertion of the workflow's + tree step green; `vpk pack` 1.2.0 over it produced `FrameLedger.App-win-Setup.exe` (104 MB) and verified `VelopackApp.Run()` in `Program.Main`. The GitHub release itself is unexercised until a tag. `legal/PRIVACY_POLICY.md` is now **2.1-draft**: the update check and download + rows describe requests the software makes, which is a material change the policy's own rule says re-shows the Legal + Gate. `legal/licenses/velopack-MIT.txt`. Tests: `UpdateServiceTests` (the skips, the channels, Deferred ↔ Ready, + the dialogs and rows, the apply's three endings), `UpdateFailureMapperTests`, `UninstallHookTests`, the + connection's hold, the tray's balloon, the settings toggle. Docs: `11_UPDATER` built note, `12_BUILD` §Version and + §Publish & package, `13_CI_CD` §release.yml, `08_UI`, `06_DATA_MODEL`, HANDOFF §P4, `15_ROADMAP`, README §Privacy. - **P4 PR-4 — the library import: Steam, GOG Galaxy, Epic and itch.io through a review checklist, hooking off for every row (FR-1.2, 2026-09-14).** `Application.Import.LibraryImporter` over four `IStoreLibrarySource` adapters in `Infrastructure.Import`: `SteamLibrarySource` (`libraryfolders.vdf` + `appmanifest_*.acf` through a new diff --git a/Directory.Build.props b/Directory.Build.props index 14620e70..95b0e234 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -54,6 +54,19 @@ en;vi;ja true + + + $(MSBuildThisFileDirectory)VERSION + $([System.IO.File]::ReadAllText('$(FrameLedgerVersionFile)').Trim()) + false + + FrameLedger.App.Program @@ -51,6 +54,7 @@ + diff --git a/src/FrameLedger.App/MainWindow.xaml b/src/FrameLedger.App/MainWindow.xaml index 4a5898ec..f4fee698 100644 --- a/src/FrameLedger.App/MainWindow.xaml +++ b/src/FrameLedger.App/MainWindow.xaml @@ -54,7 +54,7 @@ - + @@ -75,6 +75,22 @@ Content="{x:Static res:Strings.Agent_Banner_Retry}" /> + + + + + + + + + + + + + + diff --git a/src/FrameLedger.App/Program.cs b/src/FrameLedger.App/Program.cs new file mode 100644 index 00000000..9d9286eb --- /dev/null +++ b/src/FrameLedger.App/Program.cs @@ -0,0 +1,23 @@ +using FrameLedger.App.Update; +using Velopack; + +namespace FrameLedger.App; + +/// +/// The entry point, hand-written so Velopack runs first (11_UPDATER): its install, update and uninstall +/// launches re-enter this executable with their own arguments and must be answered before any window, host or +/// ledger exists — handles them and exits the process; on an ordinary launch it +/// returns and the WPF application starts as it always did. StartupObject in the project file names this +/// class over the generated App.Main. +/// +internal static class Program +{ + [STAThread] + private static int Main() + { + VelopackHooks.Configure(VelopackApp.Build()).Run(); + var app = new App(); + app.InitializeComponent(); + return app.Run(); + } +} diff --git a/src/FrameLedger.App/Services/AgentConnection.cs b/src/FrameLedger.App/Services/AgentConnection.cs index d25ad2f5..7e5ea47a 100644 --- a/src/FrameLedger.App/Services/AgentConnection.cs +++ b/src/FrameLedger.App/Services/AgentConnection.cs @@ -27,6 +27,7 @@ public sealed class AgentConnection : IAgentLink, IAsyncDisposable private PipeClient? _client; private long _rounds; private long _launches; + private volatile bool _holdLaunches; public AgentConnection(IAgentLauncher launcher, Func pipes, AgentConnectionOptions options, string appVersion) { @@ -56,6 +57,12 @@ public sealed class AgentConnection : IAgentLink, IAsyncDisposable /// Skip the wait before the next round (the banner's Retry). public void RetryNow() => _retryNow.Release(); + /// True while the update's apply has asked that no Agent be started from beside this executable. + public bool LaunchesHeld => _holdLaunches; + + /// + public void SetLaunchHold(bool hold) => _holdLaunches = hold; + /// Loop until cancelled. public async Task RunAsync(CancellationToken ct) { @@ -129,7 +136,7 @@ public sealed class AgentConnection : IAgentLink, IAsyncDisposable { Set(AgentConnectionState.Connecting, null, null); PipeClient? client = await TryConnectAsync(ct).ConfigureAwait(false); - if (client is null && _launcher.CanLaunch) + if (client is null && _launcher.CanLaunch && !_holdLaunches) { Set(AgentConnectionState.Starting, null, null); if (_launcher.TryStart()) diff --git a/src/FrameLedger.App/Services/IAgentLink.cs b/src/FrameLedger.App/Services/IAgentLink.cs index a27f2905..2d4d92ba 100644 --- a/src/FrameLedger.App/Services/IAgentLink.cs +++ b/src/FrameLedger.App/Services/IAgentLink.cs @@ -16,4 +16,10 @@ public interface IAgentLink : IAgentRequests event EventHandler? Changed; event EventHandler? EventReceived; + + /// + /// While held, a round that finds no Agent does not start one beside this executable (P4 PR-5: the update's + /// apply asks the Agent to stop and must not have it restarted under the updater). Released on a failed apply. + /// + void SetLaunchHold(bool hold); } diff --git a/src/FrameLedger.App/Strings.Designer.cs b/src/FrameLedger.App/Strings.Designer.cs index b184eaa7..b6414a66 100644 --- a/src/FrameLedger.App/Strings.Designer.cs +++ b/src/FrameLedger.App/Strings.Designer.cs @@ -380,6 +380,8 @@ public static class Strings nameof(Settings_Agent_Task_Unknown), nameof(Settings_Appearance_Header), nameof(Settings_Applied), + nameof(Settings_AutoCheck_Body), + nameof(Settings_AutoCheck_Label), nameof(Settings_Background_Body), nameof(Settings_Background_Label), nameof(Settings_Capture_Header), @@ -507,6 +509,34 @@ public static class Strings nameof(Trend_Metric_MaxGpuTemp), nameof(Trend_Metric_P01Low), nameof(Trend_Metric_P1Low), + nameof(Uninstall_DataFolder_Body), + nameof(Uninstall_DataFolder_Title), + nameof(Update_AgentStillRunning), + nameof(Update_Available_Body_Format), + nameof(Update_Available_Title_Format), + nameof(Update_Banner_Applying_Format), + nameof(Update_Banner_Deferred_Format), + nameof(Update_Banner_Downloading_Format), + nameof(Update_Banner_Ready_Format), + nameof(Update_Banner_Restart), + nameof(Update_Banner_Title), + nameof(Update_Download), + nameof(Update_Err_Corrupt), + nameof(Update_Err_Offline), + nameof(Update_Err_RateLimited), + nameof(Update_Err_Server), + nameof(Update_Err_Title), + nameof(Update_Err_Unknown), + nameof(Update_Err404), + nameof(Update_HookedRefused), + nameof(Update_Later), + nameof(Update_Notes_Header), + nameof(Update_NotInstalled), + nameof(Update_OpenReleases), + nameof(Update_Toast_Body_Format), + nameof(Update_Toast_Title), + nameof(Update_Unsigned_Footer), + nameof(Update_UpToDate_Format), nameof(Upscaler_None), nameof(Upscaler_Unknown), ]; @@ -1219,6 +1249,10 @@ public static class Strings public static string Settings_Applied => ResourceManager.GetString(nameof(Settings_Applied), Culture) ?? nameof(Settings_Applied); + public static string Settings_AutoCheck_Body => ResourceManager.GetString(nameof(Settings_AutoCheck_Body), Culture) ?? nameof(Settings_AutoCheck_Body); + + public static string Settings_AutoCheck_Label => ResourceManager.GetString(nameof(Settings_AutoCheck_Label), Culture) ?? nameof(Settings_AutoCheck_Label); + public static string Settings_Background_Body => ResourceManager.GetString(nameof(Settings_Background_Body), Culture) ?? nameof(Settings_Background_Body); public static string Settings_Background_Label => ResourceManager.GetString(nameof(Settings_Background_Label), Culture) ?? nameof(Settings_Background_Label); @@ -1473,6 +1507,62 @@ public static class Strings public static string Trend_Metric_P1Low => ResourceManager.GetString(nameof(Trend_Metric_P1Low), Culture) ?? nameof(Trend_Metric_P1Low); + public static string Uninstall_DataFolder_Body => ResourceManager.GetString(nameof(Uninstall_DataFolder_Body), Culture) ?? nameof(Uninstall_DataFolder_Body); + + public static string Uninstall_DataFolder_Title => ResourceManager.GetString(nameof(Uninstall_DataFolder_Title), Culture) ?? nameof(Uninstall_DataFolder_Title); + + public static string Update_AgentStillRunning => ResourceManager.GetString(nameof(Update_AgentStillRunning), Culture) ?? nameof(Update_AgentStillRunning); + + public static string Update_Available_Body_Format => ResourceManager.GetString(nameof(Update_Available_Body_Format), Culture) ?? nameof(Update_Available_Body_Format); + + public static string Update_Available_Title_Format => ResourceManager.GetString(nameof(Update_Available_Title_Format), Culture) ?? nameof(Update_Available_Title_Format); + + public static string Update_Banner_Applying_Format => ResourceManager.GetString(nameof(Update_Banner_Applying_Format), Culture) ?? nameof(Update_Banner_Applying_Format); + + public static string Update_Banner_Deferred_Format => ResourceManager.GetString(nameof(Update_Banner_Deferred_Format), Culture) ?? nameof(Update_Banner_Deferred_Format); + + public static string Update_Banner_Downloading_Format => ResourceManager.GetString(nameof(Update_Banner_Downloading_Format), Culture) ?? nameof(Update_Banner_Downloading_Format); + + public static string Update_Banner_Ready_Format => ResourceManager.GetString(nameof(Update_Banner_Ready_Format), Culture) ?? nameof(Update_Banner_Ready_Format); + + public static string Update_Banner_Restart => ResourceManager.GetString(nameof(Update_Banner_Restart), Culture) ?? nameof(Update_Banner_Restart); + + public static string Update_Banner_Title => ResourceManager.GetString(nameof(Update_Banner_Title), Culture) ?? nameof(Update_Banner_Title); + + public static string Update_Download => ResourceManager.GetString(nameof(Update_Download), Culture) ?? nameof(Update_Download); + + public static string Update_Err_Corrupt => ResourceManager.GetString(nameof(Update_Err_Corrupt), Culture) ?? nameof(Update_Err_Corrupt); + + public static string Update_Err_Offline => ResourceManager.GetString(nameof(Update_Err_Offline), Culture) ?? nameof(Update_Err_Offline); + + public static string Update_Err_RateLimited => ResourceManager.GetString(nameof(Update_Err_RateLimited), Culture) ?? nameof(Update_Err_RateLimited); + + public static string Update_Err_Server => ResourceManager.GetString(nameof(Update_Err_Server), Culture) ?? nameof(Update_Err_Server); + + public static string Update_Err_Title => ResourceManager.GetString(nameof(Update_Err_Title), Culture) ?? nameof(Update_Err_Title); + + public static string Update_Err_Unknown => ResourceManager.GetString(nameof(Update_Err_Unknown), Culture) ?? nameof(Update_Err_Unknown); + + public static string Update_Err404 => ResourceManager.GetString(nameof(Update_Err404), Culture) ?? nameof(Update_Err404); + + public static string Update_HookedRefused => ResourceManager.GetString(nameof(Update_HookedRefused), Culture) ?? nameof(Update_HookedRefused); + + public static string Update_Later => ResourceManager.GetString(nameof(Update_Later), Culture) ?? nameof(Update_Later); + + public static string Update_Notes_Header => ResourceManager.GetString(nameof(Update_Notes_Header), Culture) ?? nameof(Update_Notes_Header); + + public static string Update_NotInstalled => ResourceManager.GetString(nameof(Update_NotInstalled), Culture) ?? nameof(Update_NotInstalled); + + public static string Update_OpenReleases => ResourceManager.GetString(nameof(Update_OpenReleases), Culture) ?? nameof(Update_OpenReleases); + + public static string Update_Toast_Body_Format => ResourceManager.GetString(nameof(Update_Toast_Body_Format), Culture) ?? nameof(Update_Toast_Body_Format); + + public static string Update_Toast_Title => ResourceManager.GetString(nameof(Update_Toast_Title), Culture) ?? nameof(Update_Toast_Title); + + public static string Update_Unsigned_Footer => ResourceManager.GetString(nameof(Update_Unsigned_Footer), Culture) ?? nameof(Update_Unsigned_Footer); + + public static string Update_UpToDate_Format => ResourceManager.GetString(nameof(Update_UpToDate_Format), Culture) ?? nameof(Update_UpToDate_Format); + public static string Upscaler_None => ResourceManager.GetString(nameof(Upscaler_None), Culture) ?? nameof(Upscaler_None); public static string Upscaler_Unknown => ResourceManager.GetString(nameof(Upscaler_Unknown), Culture) ?? nameof(Upscaler_Unknown); diff --git a/src/FrameLedger.App/Strings.ja.resx b/src/FrameLedger.App/Strings.ja.resx index ed5de45e..de5de26a 100644 --- a/src/FrameLedger.App/Strings.ja.resx +++ b/src/FrameLedger.App/Strings.ja.resx @@ -1714,7 +1714,7 @@ review - 今すぐ保存されます。アップデーターは後のビルドで追加されます。ゲームがフックされている間は更新されません。 + 安定版のみ、または安定版とプレリリース。見つかった更新はバックグラウンドでダウンロードされ、再起動時にのみ適用されます。ゲームがフックされている間は適用されません。 review @@ -1949,4 +1949,124 @@ FrameLedger へようこそ review + + FrameLedger {0} は最新バージョンです。 + review + + + このコピーは FrameLedger のインストーラーで導入されていないため、自動更新できません。GitHub からリリースをダウンロードしてください。 + review + + + アップデート {0} が利用可能です + review + + + バージョン {0}({1} MB)を今すぐダウンロードできます。適用は FrameLedger の再起動時のみで、ゲームがフックされている間は行われません。 + review + + + 変更内容 + review + + + ダウンロード + review + + + 後で + review + + + リリースはコード署名されていないため、SmartScreen が警告する場合があります。各リリースの SHA-256 チェックサムはリリースと一緒に公開されています。 + review + + + 更新の確認に失敗しました + review + + + リリースフィードが見つかりません。リポジトリが移動した可能性があります。 + review + + + GitHub のレート制限に達しました。匿名の確認は 1 時間に 60 回までです。約 1 時間後にもう一度お試しください。 + review + + + GitHub に問題が発生しています。後でもう一度お試しください。 + review + + + GitHub に接続できませんでした。ネットワークがない、DNS の失敗、またはタイムアウトです。 + review + + + ダウンロードしたパッケージのチェックサムが一致せず、破棄されました。もう一度お試しください。2 回続く場合はバグを報告してください。 + review + + + FrameLedger が認識できない理由で更新の確認に失敗しました。詳細はログにあります。 + review + + + リリースページを開く + review + + + アップデート + review + + + バージョン {0} をダウンロード中… {1}% + review + + + バージョン {0} のダウンロードと検証が完了しました。FrameLedger を再起動して適用してください。Agent は先に停止し、その後再び起動します。 + review + + + バージョン {0} のダウンロードが完了しました。セッションが実行中のため、適用はセッション終了後になります。そのときに再起動してください。 + review + + + バージョン {0} を適用しています。Agent を停止してから FrameLedger を再起動します… + review + + + 再起動して更新 + review + + + セッションが実行中です。ゲームがフックまたは記録されている間、FrameLedger は更新しません。更新はセッション終了後に適用されます。 + review + + + Agent が時間内に停止しなかったため、何も適用されませんでした。しばらくしてからもう一度お試しください。 + review + + + アップデートがあります + review + + + FrameLedger {0} をバックグラウンドでダウンロードしています。適用は再起動時のみです。 + review + + + 起動時に更新を確認する + review + + + 起動の数秒後に GitHub Releases へ 1 回だけ要求します(インストール済みのコピーのみ)。見つかった更新はバックグラウンドでダウンロードされ、再起動しない限り適用されません。 + review + + + FrameLedger のデータを削除しますか? + review + + + データフォルダー(%LOCALAPPDATA%\FrameLedger:ライブラリ、すべてのセッション、ログ、設定)も削除しますか?後でインストールするために残す場合は「いいえ」を選んでください。 + review + diff --git a/src/FrameLedger.App/Strings.resx b/src/FrameLedger.App/Strings.resx index 35208303..d70ff9d1 100644 --- a/src/FrameLedger.App/Strings.resx +++ b/src/FrameLedger.App/Strings.resx @@ -1291,7 +1291,7 @@ Start FrameLedger with Windows - Stored now; the updater arrives in a later build. Updates never apply while a game is hooked. + Stable, or stable plus pre-releases. A found update downloads in the background and is applied only when you restart — never while a game is hooked. Channel @@ -1467,4 +1467,94 @@ Welcome to FrameLedger + + FrameLedger {0} is the latest version. + + + This copy was not set up by the FrameLedger installer, so it cannot update itself. Download releases from GitHub. + + + Update {0} is available + + + Version {0} ({1} MB) can be downloaded now. It is applied only when you restart FrameLedger, and never while a game is hooked. + + + What changed + + + Download + + + Later + + + Releases are not code-signed, so SmartScreen may warn. The SHA-256 checksums of every release are published beside it. + + + Update check failed + + + No release feed found. The repository may have moved. + + + GitHub rate limit reached. Anonymous checks allow 60 requests an hour; try again in about an hour. + + + GitHub is having trouble. Try again later. + + + GitHub could not be reached: no network, a DNS failure, or a timeout. + + + The downloaded package failed its checksum and was discarded. Try again; if it happens twice, report a bug. + + + The update check failed for a reason FrameLedger does not recognise. The details are in the log. + + + Open releases page + + + Update + + + Downloading version {0}… {1}% + + + Version {0} is downloaded and verified. Restart FrameLedger to apply it — the Agent is stopped first and started again afterwards. + + + Version {0} is downloaded. A session is running, so it is applied only after the session ends — restart then. + + + Applying version {0}: stopping the Agent, then restarting FrameLedger… + + + Restart to update + + + A session is running. FrameLedger does not update while a game is hooked or recorded; the update is applied after the session ends. + + + The Agent did not stop in time, so nothing was applied. Try again in a moment. + + + Update available + + + FrameLedger {0} is downloading in the background. It is applied only when you restart. + + + Check for updates at startup + + + One request to GitHub Releases a few seconds after start, only for an installed copy. A found update downloads in the background; nothing is applied without your restart. + + + Remove FrameLedger data? + + + Also delete the data folder (%LOCALAPPDATA%\FrameLedger: your library, every session, logs and settings)? Choose No to keep it for a later install. + diff --git a/src/FrameLedger.App/Strings.vi.resx b/src/FrameLedger.App/Strings.vi.resx index 8dc40de1..0ca8fccb 100644 --- a/src/FrameLedger.App/Strings.vi.resx +++ b/src/FrameLedger.App/Strings.vi.resx @@ -1286,7 +1286,7 @@ Khởi động FrameLedger cùng Windows - Lưu ngay; trình cập nhật sẽ có ở bản sau. Không bao giờ cập nhật khi game đang được hook. + Ổn định, hoặc ổn định kèm bản tiền phát hành. Bản cập nhật tìm thấy sẽ tải ở nền và chỉ được áp dụng khi bạn khởi động lại — không bao giờ khi game đang được hook. Kênh @@ -1462,4 +1462,94 @@ Chào mừng đến với FrameLedger + + FrameLedger {0} đã là phiên bản mới nhất. + + + Bản này không được cài bằng trình cài đặt FrameLedger nên không tự cập nhật được. Hãy tải bản phát hành từ GitHub. + + + Có bản cập nhật {0} + + + Có thể tải phiên bản {0} ({1} MB) ngay bây giờ. Bản cập nhật chỉ được áp dụng khi bạn khởi động lại FrameLedger, và không bao giờ khi game đang được hook. + + + Thay đổi + + + Tải về + + + Để sau + + + Bản phát hành không được ký mã nên SmartScreen có thể cảnh báo. Checksum SHA-256 của mỗi bản phát hành được công bố kèm theo. + + + Kiểm tra cập nhật thất bại + + + Không tìm thấy nguồn phát hành. Kho mã có thể đã chuyển đi. + + + Đã chạm giới hạn tần suất của GitHub. Kiểm tra ẩn danh cho phép 60 yêu cầu mỗi giờ; hãy thử lại sau khoảng một giờ. + + + GitHub đang gặp sự cố. Hãy thử lại sau. + + + Không kết nối được GitHub: không có mạng, lỗi DNS, hoặc hết thời gian chờ. + + + Gói tải về không khớp checksum và đã bị loại bỏ. Hãy thử lại; nếu lặp lại lần nữa, hãy báo lỗi. + + + Kiểm tra cập nhật thất bại vì lý do FrameLedger không nhận ra. Chi tiết nằm trong log. + + + Mở trang phát hành + + + Cập nhật + + + Đang tải phiên bản {0}… {1}% + + + Phiên bản {0} đã tải xong và được xác minh. Khởi động lại FrameLedger để áp dụng — Agent sẽ được dừng trước và khởi động lại sau đó. + + + Phiên bản {0} đã tải xong. Đang có phiên chạy nên bản cập nhật chỉ được áp dụng sau khi phiên kết thúc — hãy khởi động lại khi đó. + + + Đang áp dụng phiên bản {0}: dừng Agent, rồi khởi động lại FrameLedger… + + + Khởi động lại để cập nhật + + + Đang có phiên chạy. FrameLedger không cập nhật khi game đang được hook hoặc ghi; bản cập nhật sẽ được áp dụng sau khi phiên kết thúc. + + + Agent không dừng kịp thời nên chưa áp dụng gì. Hãy thử lại sau giây lát. + + + Có bản cập nhật + + + FrameLedger {0} đang được tải ở nền. Chỉ áp dụng khi bạn khởi động lại. + + + Kiểm tra cập nhật khi khởi động + + + Một yêu cầu tới GitHub Releases vài giây sau khi khởi động, chỉ với bản đã cài đặt. Bản cập nhật tìm thấy sẽ tải ở nền; không có gì được áp dụng nếu bạn không khởi động lại. + + + Xoá dữ liệu FrameLedger? + + + Xoá luôn thư mục dữ liệu (%LOCALAPPDATA%\FrameLedger: thư viện, mọi phiên, log và cài đặt)? Chọn Không để giữ lại cho lần cài sau. + diff --git a/src/FrameLedger.App/Update/FrameLedgerFileDownloader.cs b/src/FrameLedger.App/Update/FrameLedgerFileDownloader.cs new file mode 100644 index 00000000..63c2537f --- /dev/null +++ b/src/FrameLedger.App/Update/FrameLedgerFileDownloader.cs @@ -0,0 +1,24 @@ +using System.Net.Http; +using FrameLedger.App.Services; +using Velopack.Sources; + +namespace FrameLedger.App.Update; + +/// +/// Velopack's downloader with this product's User-Agent (11_UPDATER: FrameLedger/{version}) in +/// place of its own Velopack/x.y.z, which is a read-only static there. Nothing else changes: the GitHub source +/// adds no Authorization header for an empty token (measured on 1.2.0), so the request carries the UA and +/// GitHub's own Accept, and nothing that identifies the user. +/// +public sealed class FrameLedgerFileDownloader : HttpClientFileDownloader +{ + public static string UserAgentValue => "FrameLedger/" + UiIdentity.Version; + + protected override HttpClient CreateHttpClient(IDictionary? headers, double timeout) + { + HttpClient client = base.CreateHttpClient(headers, timeout); + client.DefaultRequestHeaders.UserAgent.Clear(); + _ = client.DefaultRequestHeaders.UserAgent.TryParseAdd(UserAgentValue); + return client; + } +} diff --git a/src/FrameLedger.App/Update/IUpdateClient.cs b/src/FrameLedger.App/Update/IUpdateClient.cs new file mode 100644 index 00000000..0d903620 --- /dev/null +++ b/src/FrameLedger.App/Update/IUpdateClient.cs @@ -0,0 +1,26 @@ +namespace FrameLedger.App.Update; + +/// +/// The updater's port (11_UPDATER): what the flow needs from Velopack and nothing it does not, so the flow is +/// tested without a feed. is the one implementation; every failure it reports +/// is an carrying the dialog's row. +/// +public interface IUpdateClient +{ + /// True for a copy the installer laid down; a build run from bin/ cannot update itself and says so. + bool IsInstalled { get; } + + /// The installed version as the package manifest states it, or null when not installed. + string? CurrentVersion { get; } + + /// One feed request; null when the installed version is current. + /// The feed could not be read. + Task CheckAsync(bool includePrereleases, CancellationToken ct = default); + + /// The package into Velopack's staging directory, verified; in percent. + /// The download failed or the checksum did not match. + Task DownloadAsync(UpdateCandidate candidate, IProgress? progress, CancellationToken ct = default); + + /// Hand the downloaded package to the updater, which waits for this process to exit, applies, and restarts the App. + void ApplyOnExit(UpdateCandidate candidate); +} diff --git a/src/FrameLedger.App/Update/IUpdatePrompts.cs b/src/FrameLedger.App/Update/IUpdatePrompts.cs new file mode 100644 index 00000000..8795c4df --- /dev/null +++ b/src/FrameLedger.App/Update/IUpdatePrompts.cs @@ -0,0 +1,16 @@ +namespace FrameLedger.App.Update; + +/// The manual check's dialogs (11_UPDATER §Flow, "Manual check"), behind an interface so the flow is tested without a window. +public interface IUpdatePrompts +{ + /// The release found, its notes, the unsigned-release footer; true when the user chose to download it. + Task OfferAsync(UpdateCandidate candidate, CancellationToken ct = default); + + Task UpToDateAsync(string version, CancellationToken ct = default); + + /// A copy the installer did not lay down cannot update itself. + Task NotInstalledAsync(CancellationToken ct = default); + + /// The mapped dialog for the row, with its extra action where the table names one. + Task FailedAsync(UpdateFailure failure, CancellationToken ct = default); +} diff --git a/src/FrameLedger.App/Update/UninstallHook.cs b/src/FrameLedger.App/Update/UninstallHook.cs new file mode 100644 index 00000000..7390233e --- /dev/null +++ b/src/FrameLedger.App/Update/UninstallHook.cs @@ -0,0 +1,74 @@ +namespace FrameLedger.App.Update; + +/// +/// The uninstall hook's decisions (12_BUILD §Publish & package: "uninstalled → unregister the layer, remove +/// the scheduled task, ask about the data folder"), over delegates so a test runs it without a pipe, a registry, a +/// Task Scheduler or a data folder. Every step is independent: a failure in one is logged and the next still +/// runs, and the data folder is deleted only on an explicit yes — a question that goes unanswered inside +/// Velopack's 30 s budget leaves the folder where it is. +/// +public sealed class UninstallHook( + Func stopAgent, + Func unregisterLayer, + Func removeTask, + Func askDeleteData, + Action deleteData, + Action log) +{ + public UninstallOutcome Run() + { + bool agent = Step("agent shutdown", stopAgent); + bool layer = Step("vulkan layer unregister", unregisterLayer); + bool task = Step("logon task remove", removeTask); + bool asked = false; + bool deleted = false; + if (Step("data folder question", () => + { + asked = true; + return askDeleteData(); + })) + { + deleted = Step("data folder delete", () => + { + deleteData(); + return true; + }); + } + + var outcome = new UninstallOutcome(agent, layer, task, asked, deleted); + log("uninstall: " + outcome); + return outcome; + } + + /// + /// True when neither directory contains the other. The data folder is deleted only then: an install living inside + /// it (a package id equal to the data folder's name — Velopack installs to %LOCALAPPDATA%\<packId>) would + /// have the delete remove the running install, and the question could not honestly be asked. + /// + public static bool AreSeparate(string dataDirectory, string installDirectory) + { + ArgumentException.ThrowIfNullOrWhiteSpace(dataDirectory); + ArgumentException.ThrowIfNullOrWhiteSpace(installDirectory); + string data = Normalise(dataDirectory); + string install = Normalise(installDirectory); + return !data.StartsWith(install, StringComparison.OrdinalIgnoreCase) && !install.StartsWith(data, StringComparison.OrdinalIgnoreCase); + } + + private static string Normalise(string directory) => + System.IO.Path.TrimEndingDirectorySeparator(System.IO.Path.GetFullPath(directory)) + System.IO.Path.DirectorySeparatorChar; + + private bool Step(string name, Func action) + { + try + { + bool done = action(); + log($"uninstall: {name}: {(done ? "done" : "nothing to do")}"); + return done; + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + log($"uninstall: {name} failed: {ex.GetType().Name}: {ex.Message}"); + return false; + } + } +} diff --git a/src/FrameLedger.App/Update/UninstallOutcome.cs b/src/FrameLedger.App/Update/UninstallOutcome.cs new file mode 100644 index 00000000..9f75b22c --- /dev/null +++ b/src/FrameLedger.App/Update/UninstallOutcome.cs @@ -0,0 +1,4 @@ +namespace FrameLedger.App.Update; + +/// What the uninstall hook did, for its log line and its test. +public sealed record UninstallOutcome(bool AgentAsked, bool LayerUnregistered, bool TaskRemoved, bool DataAsked, bool DataDeleted); diff --git a/src/FrameLedger.App/Update/UpdateAvailableEventArgs.cs b/src/FrameLedger.App/Update/UpdateAvailableEventArgs.cs new file mode 100644 index 00000000..f4ad8f77 --- /dev/null +++ b/src/FrameLedger.App/Update/UpdateAvailableEventArgs.cs @@ -0,0 +1,7 @@ +namespace FrameLedger.App.Update; + +/// A newer release was found (08_UI §Notifications policy: "update available" is a tray toast when the window is off screen). +public sealed class UpdateAvailableEventArgs(string version) : EventArgs +{ + public string Version { get; } = version ?? throw new ArgumentNullException(nameof(version)); +} diff --git a/src/FrameLedger.App/Update/UpdateCandidate.cs b/src/FrameLedger.App/Update/UpdateCandidate.cs new file mode 100644 index 00000000..b574e5fe --- /dev/null +++ b/src/FrameLedger.App/Update/UpdateCandidate.cs @@ -0,0 +1,4 @@ +namespace FrameLedger.App.Update; + +/// A release newer than the installed one, as the feed describes it: the version, its notes (the GitHub release body, Markdown), the full package's size. +public sealed record UpdateCandidate(string Version, string? NotesMarkdown, long SizeBytes); diff --git a/src/FrameLedger.App/Update/UpdateException.cs b/src/FrameLedger.App/Update/UpdateException.cs new file mode 100644 index 00000000..eeedd3ea --- /dev/null +++ b/src/FrameLedger.App/Update/UpdateException.cs @@ -0,0 +1,24 @@ +namespace FrameLedger.App.Update; + +/// An update step that did not complete, classified for the dialog (); the cause is the inner exception. +public sealed class UpdateException : Exception +{ + public UpdateException() + { + } + + public UpdateException(string message) + : base(message) + { + } + + public UpdateException(string message, Exception? innerException) + : base(message, innerException) + { + } + + public UpdateException(UpdateFailure failure, string message, Exception? innerException) + : base(message, innerException) => Failure = failure; + + public UpdateFailure Failure { get; } = UpdateFailure.Unknown; +} diff --git a/src/FrameLedger.App/Update/UpdateFailure.cs b/src/FrameLedger.App/Update/UpdateFailure.cs new file mode 100644 index 00000000..cd1081c2 --- /dev/null +++ b/src/FrameLedger.App/Update/UpdateFailure.cs @@ -0,0 +1,23 @@ +namespace FrameLedger.App.Update; + +/// 11_UPDATER §Error mapping, one member per row; the dialog text is the matching Update_Err_* string. +public enum UpdateFailure +{ + /// HTTP 404: no release feed where the client looked. + NotFound = 0, + + /// HTTP 403 / 429: GitHub's anonymous quota. + RateLimited, + + /// HTTP 5xx. + Server, + + /// Timeout, DNS, no network — silent on the startup check. + Offline, + + /// The downloaded package failed its checksum. + Corrupt, + + /// Anything else; the exception is logged. + Unknown, +} diff --git a/src/FrameLedger.App/Update/UpdateFailureMapper.cs b/src/FrameLedger.App/Update/UpdateFailureMapper.cs new file mode 100644 index 00000000..517ef658 --- /dev/null +++ b/src/FrameLedger.App/Update/UpdateFailureMapper.cs @@ -0,0 +1,43 @@ +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using Velopack.Exceptions; + +namespace FrameLedger.App.Update; + +/// +/// 11_UPDATER §Error mapping as a function of the exception Velopack's client threw: the HTTP status when +/// there is one (404 → , 403/429 → , +/// 5xx → ), the transport failures → , a +/// checksum → , the rest → . Walks the inner +/// chain, because the source wraps what its downloader threw. +/// +public static class UpdateFailureMapper +{ + public static UpdateFailure Map(Exception exception) + { + ArgumentNullException.ThrowIfNull(exception); + for (Exception? e = exception; e is not null; e = e.InnerException) + { + if (Classify(e) is { } failure) + { + return failure; + } + } + + return UpdateFailure.Unknown; + } + + private static UpdateFailure? Classify(Exception e) => e switch + { + ChecksumFailedException => UpdateFailure.Corrupt, + HttpRequestException { StatusCode: HttpStatusCode.NotFound } => UpdateFailure.NotFound, + HttpRequestException { StatusCode: HttpStatusCode.Forbidden or HttpStatusCode.TooManyRequests } => UpdateFailure.RateLimited, + HttpRequestException { StatusCode: { } status } when (int)status >= 500 => UpdateFailure.Server, + HttpRequestException { StatusCode: null } => UpdateFailure.Offline, + HttpRequestException => UpdateFailure.Unknown, + TaskCanceledException or TimeoutException or SocketException or IOException => UpdateFailure.Offline, + _ => null, + }; +} diff --git a/src/FrameLedger.App/Update/UpdateHostedService.cs b/src/FrameLedger.App/Update/UpdateHostedService.cs new file mode 100644 index 00000000..fb195306 --- /dev/null +++ b/src/FrameLedger.App/Update/UpdateHostedService.cs @@ -0,0 +1,51 @@ +using FrameLedger.App.Services; +using FrameLedger.Infrastructure.Startup; +using Microsoft.Extensions.Hosting; +using Serilog; + +namespace FrameLedger.App.Update; + +/// +/// The startup leg of 11_UPDATER §Flow: the silent check 5 s after the host is up (the spec's "5 s after UI +/// idle", measured from start because the shell shows synchronously inside it), and — on the first run after an +/// update — the logon task's action path re-validated, because the updater rewrote the install directory +/// (LogonTaskState.Stale is the signal; --install-task the repair, this user's own task). +/// +internal sealed class UpdateHostedService(UpdateService updates, IMaintenanceState maintenance, IAgentTool tool) : BackgroundService +{ + private static readonly TimeSpan _startupDelay = TimeSpan.FromSeconds(5); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + try + { + if (UpdateRestart.Detected) + { + await RepairTaskAsync(stoppingToken).ConfigureAwait(false); + } + + await Task.Delay(_startupDelay, stoppingToken).ConfigureAwait(false); + await updates.CheckSilentlyAsync(stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + Log.Warning(ex, "update: the startup check faulted"); + } + } + + private async Task RepairTaskAsync(CancellationToken ct) + { + MaintenanceSnapshot snapshot = await maintenance.ReadAsync(ct).ConfigureAwait(false); + if (snapshot.Task != LogonTaskState.Stale) + { + Log.Information("update: restarted after an update; the logon task is {State}", snapshot.Task); + return; + } + + AgentToolResult result = await tool.RunAsync("--install-task", ct).ConfigureAwait(false); + Log.Information("update: restarted after an update; the logon task was stale and --install-task exited {Exit}", result.ExitCode); + } +} diff --git a/src/FrameLedger.App/Update/UpdatePrompts.cs b/src/FrameLedger.App/Update/UpdatePrompts.cs new file mode 100644 index 00000000..6ed58eaf --- /dev/null +++ b/src/FrameLedger.App/Update/UpdatePrompts.cs @@ -0,0 +1,116 @@ +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using FrameLedger.App.Services; +using MessageBox = Wpf.Ui.Controls.MessageBox; +using MessageBoxResult = Wpf.Ui.Controls.MessageBoxResult; + +namespace FrameLedger.App.Update; + +/// over WPF-UI's , the way About and the removal confirmation are. +[SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format strings are resources that follow the UI culture, which changes at runtime; a cached CompositeFormat would pin the first culture")] +public sealed class UpdatePrompts(IUrlOpener urls, BugReportFlow bugReports) : IUpdatePrompts +{ + /// Where a 404 sends the user: the releases page itself, which is what a moved feed would have changed. + public static Uri ReleasesPage { get; } = new(VelopackUpdateClient.RepositoryUrl + "/releases"); + + public async Task OfferAsync(UpdateCandidate candidate, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(candidate); + var body = new StackPanel(); + body.Children.Add(new System.Windows.Controls.TextBlock + { + Text = string.Format(CultureInfo.CurrentCulture, Strings.Update_Available_Body_Format, candidate.Version, candidate.SizeBytes / (1024 * 1024)), + TextWrapping = TextWrapping.Wrap, + }); + if (!string.IsNullOrWhiteSpace(candidate.NotesMarkdown)) + { + body.Children.Add(new System.Windows.Controls.TextBlock { Text = Strings.Update_Notes_Header, FontWeight = FontWeights.SemiBold, Margin = new Thickness(0, 12, 0, 4) }); + body.Children.Add(new ScrollViewer + { + MaxHeight = 260, + VerticalScrollBarVisibility = ScrollBarVisibility.Auto, + Content = new System.Windows.Controls.TextBlock { Text = candidate.NotesMarkdown, TextWrapping = TextWrapping.Wrap }, + }); + } + + body.Children.Add(new System.Windows.Controls.TextBlock { Text = Strings.Update_Unsigned_Footer, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 12, 0, 0), Opacity = 0.7 }); + var box = new MessageBox + { + Title = string.Format(CultureInfo.CurrentCulture, Strings.Update_Available_Title_Format, candidate.Version), + Content = body, + PrimaryButtonText = Strings.Update_Download, + CloseButtonText = Strings.Update_Later, + MaxWidth = 640, + }; + MessageBoxResult result = await box.ShowDialogAsync(cancellationToken: ct).ConfigureAwait(true); + return result == MessageBoxResult.Primary; + } + + public Task UpToDateAsync(string version, CancellationToken ct = default) => + ShowAsync(Strings.Menu_Help_CheckUpdates, string.Format(CultureInfo.CurrentCulture, Strings.Update_UpToDate_Format, version), ct); + + public Task NotInstalledAsync(CancellationToken ct = default) => ShowAsync(Strings.Menu_Help_CheckUpdates, Strings.Update_NotInstalled, ct); + + /// The table's extra behaviour: a 404 offers the releases page, an unknown failure offers the bug report. + public async Task FailedAsync(UpdateFailure failure, CancellationToken ct = default) + { + var box = new MessageBox + { + Title = Strings.Update_Err_Title, + Content = new System.Windows.Controls.TextBlock { Text = Text(failure), TextWrapping = TextWrapping.Wrap }, + CloseButtonText = Strings.Common_Ok, + MaxWidth = 560, + }; + switch (failure) + { + case UpdateFailure.NotFound: + box.PrimaryButtonText = Strings.Update_OpenReleases; + break; + case UpdateFailure.Unknown: + box.PrimaryButtonText = Strings.Menu_Help_ReportBug; + break; + default: + break; + } + + MessageBoxResult result = await box.ShowDialogAsync(cancellationToken: ct).ConfigureAwait(true); + if (result != MessageBoxResult.Primary) + { + return; + } + + if (failure == UpdateFailure.NotFound) + { + _ = urls.Open(ReleasesPage); + } + else if (failure == UpdateFailure.Unknown) + { + _ = await bugReports.RunAsync(ct).ConfigureAwait(true); + } + } + + /// The row's string (11_UPDATER §Error mapping). + public static string Text(UpdateFailure failure) => failure switch + { + UpdateFailure.NotFound => Strings.Update_Err404, + UpdateFailure.RateLimited => Strings.Update_Err_RateLimited, + UpdateFailure.Server => Strings.Update_Err_Server, + UpdateFailure.Offline => Strings.Update_Err_Offline, + UpdateFailure.Corrupt => Strings.Update_Err_Corrupt, + _ => Strings.Update_Err_Unknown, + }; + + private static async Task ShowAsync(string title, string body, CancellationToken ct) + { + var box = new MessageBox + { + Title = title, + Content = new System.Windows.Controls.TextBlock { Text = body, TextWrapping = TextWrapping.Wrap }, + CloseButtonText = Strings.Common_Ok, + MaxWidth = 560, + }; + await box.ShowDialogAsync(cancellationToken: ct).ConfigureAwait(true); + } +} diff --git a/src/FrameLedger.App/Update/UpdateRestart.cs b/src/FrameLedger.App/Update/UpdateRestart.cs new file mode 100644 index 00000000..9b803826 --- /dev/null +++ b/src/FrameLedger.App/Update/UpdateRestart.cs @@ -0,0 +1,7 @@ +namespace FrameLedger.App.Update; + +/// Set by Velopack's restarted hook in Program.Main, read once by : this process is the first run after an update. +internal static class UpdateRestart +{ + public static bool Detected { get; set; } +} diff --git a/src/FrameLedger.App/Update/UpdateService.cs b/src/FrameLedger.App/Update/UpdateService.cs new file mode 100644 index 00000000..ba8cb65b --- /dev/null +++ b/src/FrameLedger.App/Update/UpdateService.cs @@ -0,0 +1,341 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using FrameLedger.App.Services; +using FrameLedger.Application.Settings; +using FrameLedger.Infrastructure.Ipc; +using FrameLedger.Shared.Ipc; +using Serilog; + +namespace FrameLedger.App.Update; + +/// +/// 11_UPDATER §Flow over the port: the startup silent check (when the copy is +/// installed and update.auto_check is on), the manual check with its dialogs, the background download, and +/// the one rule that shapes every step — FR-12: nothing is applied while a session runs. A downloaded +/// package is only while the Agent reports no session; otherwise it is +/// and becomes Ready when the last session ends. The apply itself asks the Agent +/// to stop first (it outlives the App and holds the Overlay on disk), holds the connection's relaunch, and ends +/// the host once the pipe has dropped; Velopack waits for the exit, applies, and restarts the App, which starts +/// the Agent beside itself as it always does. +/// +public sealed partial class UpdateService : ObservableObject, IDisposable +{ + /// StatusAck.State when no session runs. + private const string _idleState = "idle"; + + private static readonly TimeSpan _defaultAgentStopTimeout = TimeSpan.FromSeconds(10); + + private readonly TimeSpan _agentStopTimeout; + private readonly IUpdateClient _client; + private readonly IAgentLink _agent; + private readonly RegisteredSettings _settings; + private readonly IUpdatePrompts _prompts; + private readonly IShellPresence _shell; + private readonly IMessageStrip _strip; + private readonly UiThread _ui = new(); + private readonly HashSet _running = []; + private UpdateCandidate? _pending; + + [ObservableProperty] + private UpdateStage _stage; + + [ObservableProperty] + private string? _version; + + [ObservableProperty] + private int _percent; + + /// + /// The flow over its ports; subscribes to the Agent link for the session facts FR-12 needs. The last parameter is + /// how long the apply waits for the pipe to drop after Shutdown (10 s), overridable as a test's clock. + /// + public UpdateService(IUpdateClient client, IAgentLink agent, RegisteredSettings settings, IUpdatePrompts prompts, IShellPresence shell, IMessageStrip strip, TimeSpan? agentStopTimeout = null) + { + _agentStopTimeout = agentStopTimeout ?? _defaultAgentStopTimeout; + _client = client ?? throw new ArgumentNullException(nameof(client)); + _agent = agent ?? throw new ArgumentNullException(nameof(agent)); + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _prompts = prompts ?? throw new ArgumentNullException(nameof(prompts)); + _shell = shell ?? throw new ArgumentNullException(nameof(shell)); + _strip = strip ?? throw new ArgumentNullException(nameof(strip)); + _agent.Changed += OnAgentChanged; + _agent.EventReceived += OnAgentEvent; + } + + /// Raised once per release found, for the tray's toast; the banner follows . + public event EventHandler? Available; + + /// A session runs (hooked or recording): the Agent said so at connect, or a SessionStarted arrived without its SessionCompleted. + public bool IsSessionActive + { + get + { + if (_running.Count > 0) + { + return true; + } + + StatusAck? status = _agent.Status; + return status is not null && (!string.Equals(status.State, _idleState, StringComparison.Ordinal) || status.ActiveSessions.Count > 0); + } + } + + public void Dispose() + { + _agent.Changed -= OnAgentChanged; + _agent.EventReceived -= OnAgentEvent; + } + + /// The startup check: skipped for an uninstalled copy and when the setting is off; every failure is a log line, never a dialog (NFR-10). + public async Task CheckSilentlyAsync(CancellationToken ct = default) + { + if (!_client.IsInstalled) + { + Log.Information("update: not an installed copy; the startup check is skipped"); + return; + } + + if (!await _settings.GetBooleanAsync(SettingsRegistry.UpdateAutoCheck, ct).ConfigureAwait(false)) + { + Log.Information("update: the startup check is off (update.auto_check)"); + return; + } + + if (Stage != UpdateStage.Idle) + { + return; + } + + try + { + UpdateCandidate? candidate = await CheckCoreAsync(ct).ConfigureAwait(false); + if (candidate is null) + { + Log.Information("update: {Version} is current", _client.CurrentVersion); + return; + } + + await DownloadAsync(candidate, ct).ConfigureAwait(false); + } + catch (UpdateException ex) + { + Log.Information("update: the startup check did not complete ({Failure}: {Message})", ex.Failure, ex.Message); + Post(() => Stage = UpdateStage.Idle); + } + } + + /// Help ▸ Check for updates: the dialogs of 11_UPDATER §Flow, "Manual check". + public async Task CheckInteractivelyAsync(CancellationToken ct = default) + { + if (!_client.IsInstalled) + { + await _prompts.NotInstalledAsync(ct).ConfigureAwait(true); + return; + } + + if (Stage is not UpdateStage.Idle and not UpdateStage.Available) + { + // Downloading, Ready or Deferred: the banner already says what is pending. + return; + } + + try + { + UpdateCandidate? candidate = await CheckCoreAsync(ct).ConfigureAwait(true); + if (candidate is null) + { + await _prompts.UpToDateAsync(_client.CurrentVersion ?? UiIdentity.Version, ct).ConfigureAwait(true); + return; + } + + if (await _prompts.OfferAsync(candidate, ct).ConfigureAwait(true)) + { + await DownloadAsync(candidate, ct).ConfigureAwait(true); + } + else + { + Stage = UpdateStage.Idle; + } + } + catch (UpdateException ex) + { + Log.Warning(ex, "update: the manual check did not complete ({Failure})", ex.Failure); + Stage = UpdateStage.Idle; + await _prompts.FailedAsync(ex.Failure, ct).ConfigureAwait(true); + } + catch (Exception ex) when (ex is not OutOfMemoryException && !(ex is OperationCanceledException && ct.IsCancellationRequested)) + { + Log.Error(ex, "update: the manual check faulted"); + Stage = UpdateStage.Idle; + await _prompts.FailedAsync(UpdateFailure.Unknown, ct).ConfigureAwait(true); + } + } + + /// + /// The banner's button. FR-12 first: with a session running nothing is applied and the package stays deferred. + /// Then Shutdown to the Agent, the relaunch held, the pipe watched until it drops, the updater told to + /// wait for this process, and the host ended. An Agent that does not stop in time leaves everything as it was. + /// + public async Task RestartToUpdateAsync(CancellationToken ct = default) + { + UpdateCandidate? pending = _pending; + if (pending is null || Stage is not UpdateStage.Ready and not UpdateStage.Deferred) + { + return; + } + + if (IsSessionActive) + { + Stage = UpdateStage.Deferred; + _strip.Warn(Strings.Update_Banner_Title, Strings.Update_HookedRefused); + return; + } + + Stage = UpdateStage.Applying; + _agent.SetLaunchHold(true); + if (!await StopAgentAsync(ct).ConfigureAwait(true)) + { + _agent.SetLaunchHold(false); + Stage = UpdateStage.Ready; + _strip.Warn(Strings.Update_Banner_Title, Strings.Update_AgentStillRunning); + return; + } + + try + { + Log.Information("update: applying {Version} on exit", pending.Version); + _client.ApplyOnExit(pending); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + Log.Error(ex, "update: the updater could not be started; nothing was applied"); + _agent.SetLaunchHold(false); + Stage = UpdateStage.Ready; + _strip.Warn(Strings.Update_Banner_Title, Strings.Update_Err_Unknown); + return; + } + + _shell.Quit(); + } + + private async Task CheckCoreAsync(CancellationToken ct) + { + Post(() => Stage = UpdateStage.Checking); + bool prereleases = string.Equals(await _settings.GetAsync(SettingsRegistry.UpdateChannel, ct).ConfigureAwait(false), "beta", StringComparison.Ordinal); + UpdateCandidate? candidate = await _client.CheckAsync(prereleases, ct).ConfigureAwait(false); + if (candidate is null) + { + Post(() => Stage = UpdateStage.Idle); + return null; + } + + Log.Information("update: {Version} is available ({Size} bytes)", candidate.Version, candidate.SizeBytes); + Post(() => + { + Version = candidate.Version; + Stage = UpdateStage.Available; + Available?.Invoke(this, new UpdateAvailableEventArgs(candidate.Version)); + }); + return candidate; + } + + private async Task DownloadAsync(UpdateCandidate candidate, CancellationToken ct) + { + Post(() => + { + Percent = 0; + Stage = UpdateStage.Downloading; + }); + var progress = new PostingProgress(this); + try + { + await _client.DownloadAsync(candidate, progress, ct).ConfigureAwait(false); + } + catch (UpdateException ex) when (ex.Failure == UpdateFailure.Corrupt) + { + // 11_UPDATER §Error mapping: a package hash mismatch retries once, then it is the dialog's. + Log.Warning("update: {Version} failed its checksum ({Message}); downloading once more", candidate.Version, ex.Message); + await _client.DownloadAsync(candidate, progress, ct).ConfigureAwait(false); + } + + _pending = candidate; + Log.Information("update: {Version} downloaded and verified", candidate.Version); + Post(Settle); + } + + /// Ready or Deferred, from whether a session runs right now. + private void Settle() + { + if (_pending is null) + { + return; + } + + if (Stage is UpdateStage.Applying) + { + return; + } + + Stage = IsSessionActive ? UpdateStage.Deferred : UpdateStage.Ready; + } + + private async Task StopAgentAsync(CancellationToken ct) + { + if (!_agent.IsConnected) + { + return true; + } + + try + { + await _agent.RequestAsync(IpcMessageType.Shutdown, new ShutdownRequest(), ct).ConfigureAwait(true); + } + catch (Exception ex) when (ex is IpcRequestException or TimeoutException or System.IO.IOException or InvalidOperationException) + { + Log.Warning(ex, "update: the Agent did not acknowledge Shutdown"); + } + + DateTimeOffset deadline = DateTimeOffset.UtcNow + _agentStopTimeout; + while (_agent.IsConnected) + { + if (DateTimeOffset.UtcNow >= deadline) + { + return false; + } + + await Task.Delay(100, ct).ConfigureAwait(true); + } + + return true; + } + + private void OnAgentChanged(object? sender, EventArgs e) => Post(() => + { + _running.Clear(); + Settle(); + }); + + private void OnAgentEvent(object? sender, AgentEventArgs e) => Post(() => + { + switch (e.Envelope.Type) + { + case IpcMessageType.SessionStarted when IpcCodec.Payload(e.Envelope) is { } started: + _running.Add(started.SessionGuid); + break; + case IpcMessageType.SessionCompleted when IpcCodec.Payload(e.Envelope) is { } completed: + _running.Remove(completed.SessionGuid); + break; + default: + return; + } + + Settle(); + }); + + private void Post(Action action) => _ui.Post(action); + + /// The download's percent onto the UI thread, in order; would queue each report to the thread pool when there is no context. + private sealed class PostingProgress(UpdateService owner) : IProgress + { + public void Report(int value) => owner.Post(() => owner.Percent = value); + } +} diff --git a/src/FrameLedger.App/Update/UpdateStage.cs b/src/FrameLedger.App/Update/UpdateStage.cs new file mode 100644 index 00000000..819f3fc7 --- /dev/null +++ b/src/FrameLedger.App/Update/UpdateStage.cs @@ -0,0 +1,24 @@ +namespace FrameLedger.App.Update; + +/// Where the updater is, as the shell's banner shows it (08_UI §Notifications policy: "update downloaded" is a persistent InfoBar). +public enum UpdateStage +{ + /// Nothing pending: no check yet, the installed version is current, or a check failed. + Idle = 0, + + Checking, + + /// A newer release was found; the download has not started (the manual check's offer is open). + Available, + + Downloading, + + /// Downloaded and verified; "Restart to update" is live. + Ready, + + /// Downloaded, but a session is running (FR-12): offered again when it ends. + Deferred, + + /// The Agent has been asked to stop and the updater to wait for this process; the host is ending. + Applying, +} diff --git a/src/FrameLedger.App/Update/VelopackHooks.cs b/src/FrameLedger.App/Update/VelopackHooks.cs new file mode 100644 index 00000000..5dcd37c8 --- /dev/null +++ b/src/FrameLedger.App/Update/VelopackHooks.cs @@ -0,0 +1,127 @@ +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Windows; +using FrameLedger.App.Services; +using FrameLedger.Infrastructure.Ipc; +using FrameLedger.Infrastructure.Startup; +using FrameLedger.Infrastructure.Vulkan; +using FrameLedger.Shared.Ipc; +using Velopack; + +namespace FrameLedger.App.Update; + +/// +/// What runs inside Velopack's own process launches, before exists (Program.Main, first +/// line). Install registers nothing machine-wide — the first-run flow offers the Agent's task and the layer's +/// registration follows the ledger (12_BUILD §The Vulkan layer is not registered at install time). Uninstall +/// is over the real pieces. A restart after an update sets +/// so the host re-validates the logon task's action path. +/// +internal static class VelopackHooks +{ + /// + /// Velopack gives the callback 30 s in all, and the question at the end needs most of them: 1 s to find a pipe + /// (none is the common case), 3 s for the ack, 5 s for the Agent's process to leave. + /// + private static readonly TimeSpan _connectTimeout = TimeSpan.FromSeconds(1); + + private static readonly TimeSpan _requestTimeout = TimeSpan.FromSeconds(3); + + private static readonly TimeSpan _exitTimeout = TimeSpan.FromSeconds(5); + + public static VelopackApp Configure(VelopackApp app) => app + .OnRestarted(static _ => UpdateRestart.Detected = true) + .OnBeforeUninstallFastCallback(static _ => BeforeUninstall()); + + private static void BeforeUninstall() + { + string manifest = Path.Combine(VkLayerLaunchEnvironment.DefaultDirectory, VkLayerLaunchEnvironment.ManifestFileName); + var hook = new UninstallHook( + stopAgent: StopAgent, + unregisterLayer: () => new VkLayerRegistration().Unregister(manifest), + removeTask: static () => new LogonTask().Remove() is null, + askDeleteData: static () => UninstallHook.AreSeparate(UiPaths.DataDirectory, AppContext.BaseDirectory) + ? System.Windows.MessageBox.Show(Strings.Uninstall_DataFolder_Body, Strings.Uninstall_DataFolder_Title, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes + : throw new InvalidOperationException($"the install ({AppContext.BaseDirectory}) and the data folder ({UiPaths.DataDirectory}) overlap; nothing is deleted"), + deleteData: static () => Directory.Delete(UiPaths.DataDirectory, recursive: true), + log: Log); + hook.Run(); + } + + /// + /// The Agent outlives the App and holds the install directory and the ledger; a Shutdown over the pipe, + /// best effort, then a bounded wait for its process to leave — so the uninstaller's file removal and a Yes to the + /// data question do not meet an open ledger.db. Nothing is killed. + /// + [SuppressMessage("Usage", "VSTHRD002:Avoid problematic synchronous waits", Justification = "Velopack's fast callback is synchronous, runs with no dispatcher, and the process exits when it returns; a bounded wait on a pooled task is the only shape available")] + private static bool StopAgent() + { + Task ask = Task.Run(static async () => + { + var client = new PipeClient(); + await using (client.ConfigureAwait(false)) + { + await client.ConnectAsync(_connectTimeout).ConfigureAwait(false); + await client.RequestEnvelopeAsync(IpcMessageType.Shutdown, new ShutdownRequest(), _requestTimeout).ConfigureAwait(false); + return true; + } + }); + bool asked; + try + { + asked = ask.Wait(_connectTimeout + _requestTimeout + _connectTimeout) && ask.Result; + } + catch (AggregateException) + { + // No Agent listening (the common case: nothing was running), or it dropped the pipe on Shutdown. + asked = false; + } + + WaitForAgentExit(); + return asked; + } + + private static void WaitForAgentExit() + { + DateTimeOffset deadline = DateTimeOffset.UtcNow + _exitTimeout; + foreach (Process agent in Process.GetProcessesByName("FrameLedger.Agent")) + { + using (agent) + { + TimeSpan left = deadline - DateTimeOffset.UtcNow; + if (left > TimeSpan.Zero) + { + try + { + _ = agent.WaitForExit(left); + } + catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception) + { + // Gone between the listing and the wait, or not ours to wait on. + } + } + } + } + } + + /// Serilog is not configured this early; the hook's own file under logs/, appended, never thrown from. + private static void Log(string line) + { + try + { + if (!Directory.Exists(UiPaths.DataDirectory)) + { + // Deleted on the user's yes a moment ago; recreating it for a log line would undo their answer. + return; + } + + Directory.CreateDirectory(UiPaths.Logs); + File.AppendAllText(Path.Combine(UiPaths.Logs, "uninstall.log"), $"[{DateTimeOffset.UtcNow:O}] {line}{Environment.NewLine}"); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // The folder may already be gone (the user said yes) — nothing to write to, nothing to do. + } + } +} diff --git a/src/FrameLedger.App/Update/VelopackUpdateClient.cs b/src/FrameLedger.App/Update/VelopackUpdateClient.cs new file mode 100644 index 00000000..0e67145f --- /dev/null +++ b/src/FrameLedger.App/Update/VelopackUpdateClient.cs @@ -0,0 +1,112 @@ +using FrameLedger.App.Services; +using Velopack; +using Velopack.Sources; + +namespace FrameLedger.App.Update; + +/// +/// over Velopack's and its GitHub source for this repository +/// (11_UPDATER): the stable channel is the releases GitHub does not mark pre-release, the beta channel adds the +/// ones it does (13_CI_CD §Branch & release policy — vX.Y.Z-beta.N). One manager per check, because +/// the channel is a constructor argument there; the a check returned is held for the +/// download and the apply that follow it. +/// +public sealed class VelopackUpdateClient : IUpdateClient +{ + /// The one feed (CLAUDE.md rule 8: the GitHub release check is a permitted call). + public const string RepositoryUrl = "https://github.com/poli0981/frameledger"; + + private readonly Lock _lock = new(); + private (UpdateManager Manager, UpdateInfo Info, string Version)? _held; + + public bool IsInstalled => Probe(static m => m.IsInstalled, false); + + public string? CurrentVersion => Probe(static m => m.CurrentVersion?.ToString(), null); + + public async Task CheckAsync(bool includePrereleases, CancellationToken ct = default) + { + ct.ThrowIfCancellationRequested(); + UpdateManager manager = Create(includePrereleases); + try + { + UpdateInfo? info = await manager.CheckForUpdatesAsync().ConfigureAwait(false); + if (info is null) + { + return null; + } + + VelopackAsset target = info.TargetFullRelease; + string version = target.Version.ToString(); + lock (_lock) + { + _held = (manager, info, version); + } + + return new UpdateCandidate(version, target.NotesMarkdown, target.Size); + } + catch (Exception ex) when (IsFailure(ex, ct)) + { + throw new UpdateException(UpdateFailureMapper.Map(ex), ex.Message, ex); + } + } + + public async Task DownloadAsync(UpdateCandidate candidate, IProgress? progress, CancellationToken ct = default) + { + (UpdateManager manager, UpdateInfo info) = Held(candidate); + try + { + await manager.DownloadUpdatesAsync(info, p => progress?.Report(p), ct).ConfigureAwait(false); + } + catch (Exception ex) when (IsFailure(ex, ct)) + { + throw new UpdateException(UpdateFailureMapper.Map(ex), ex.Message, ex); + } + } + + /// Velopack's updater waits up to 60 s for this process to exit; the caller ends the host right after. + public void ApplyOnExit(UpdateCandidate candidate) + { + (UpdateManager manager, UpdateInfo info) = Held(candidate); + manager.WaitExitThenApplyUpdates(info.TargetFullRelease, silent: false, restart: true); + } + + /// + /// Everything but the caller's own cancellation is a failure to classify — including the + /// an HttpClient timeout throws, which is the Offline row, not a cancel. + /// + private static bool IsFailure(Exception ex, CancellationToken ct) => + ex is not OutOfMemoryException && !(ex is OperationCanceledException && ct.IsCancellationRequested); + + private static UpdateManager Create(bool includePrereleases) + { + return new UpdateManager(new GithubSource(RepositoryUrl, string.Empty, includePrereleases, new FrameLedgerFileDownloader())); + } + + /// A manager is cheap to build and never touches the network until asked; the two properties read its locator only. + private static T Probe(Func read, T fallback) + { + try + { + return read(Create(false)); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + Serilog.Log.Debug(ex, "update: the locator could not be read"); + return fallback; + } + } + + private (UpdateManager Manager, UpdateInfo Info) Held(UpdateCandidate candidate) + { + ArgumentNullException.ThrowIfNull(candidate); + lock (_lock) + { + if (_held is { } held && string.Equals(held.Version, candidate.Version, StringComparison.Ordinal)) + { + return (held.Manager, held.Info); + } + } + + throw new InvalidOperationException("no check returned this candidate"); + } +} diff --git a/src/FrameLedger.App/ViewModels/MainWindowViewModel.cs b/src/FrameLedger.App/ViewModels/MainWindowViewModel.cs index 7f1c9f40..cbb0626f 100644 --- a/src/FrameLedger.App/ViewModels/MainWindowViewModel.cs +++ b/src/FrameLedger.App/ViewModels/MainWindowViewModel.cs @@ -6,6 +6,7 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using FrameLedger.App.Pages; using FrameLedger.App.Services; +using FrameLedger.App.Update; using FrameLedger.Infrastructure.Ipc; using FrameLedger.Shared.Ipc; using Wpf.Ui; @@ -34,7 +35,19 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable [ObservableProperty] private string _agentBannerBody = string.Empty; + /// 08_UI §Notifications policy: "update downloaded" is in-app and persistent — the banner follows . + [ObservableProperty] + private bool _isUpdateBannerVisible; + + [ObservableProperty] + private string _updateBannerBody = string.Empty; + + /// FR-12: the button is live only while no session runs; deferred, it stays visible and disabled with the body saying why. + [ObservableProperty] + private bool _canRestartToUpdate; + private readonly AddGameFlow _addGame; + private readonly UpdateService _updates; private readonly BugReportFlow _bugReports; private readonly IUrlOpener _urls; private readonly SessionSelection _selection; @@ -43,9 +56,11 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable private readonly ImportLibraryFlow _import; public MainWindowViewModel(AgentConnection agent, ISnackbarService snackbar, IShellPresence shell, IPageNavigator navigator, AddGameFlow addGame, SafetyNotices notices, - BugReportFlow bugReports, IUrlOpener urls, SessionSelection selection, SessionExportService exports, ISessionSummaryOpener summaries, ImportLibraryFlow import) + BugReportFlow bugReports, IUrlOpener urls, SessionSelection selection, SessionExportService exports, ISessionSummaryOpener summaries, ImportLibraryFlow import, + UpdateService updates) { Notices = notices ?? throw new ArgumentNullException(nameof(notices)); + _updates = updates ?? throw new ArgumentNullException(nameof(updates)); _import = import ?? throw new ArgumentNullException(nameof(import)); _bugReports = bugReports ?? throw new ArgumentNullException(nameof(bugReports)); _urls = urls ?? throw new ArgumentNullException(nameof(urls)); @@ -58,7 +73,9 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable _navigator = navigator ?? throw new ArgumentNullException(nameof(navigator)); _addGame = addGame ?? throw new ArgumentNullException(nameof(addGame)); _agent.Changed += OnAgentChanged; + _updates.PropertyChanged += OnUpdatesChanged; Refresh(); + RefreshUpdate(); } public static string Title => Strings.App_Title; @@ -66,10 +83,39 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable /// 08_UI §Notifications policy: the safety events, as persistent InfoBars above every page — never toasts. public SafetyNotices Notices { get; } - public void Dispose() => _agent.Changed -= OnAgentChanged; + public void Dispose() + { + _agent.Changed -= OnAgentChanged; + _updates.PropertyChanged -= OnUpdatesChanged; + } private void OnAgentChanged(object? sender, EventArgs e) => _ui.Post(Refresh); + private void OnUpdatesChanged(object? sender, PropertyChangedEventArgs e) => RefreshUpdate(); + + /// The banner's three faces: downloading (with the percent), ready (the button live), deferred (FR-12, the button waits). + [SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format strings are resources that follow the UI culture, which changes at runtime; a cached CompositeFormat would pin the first culture")] + private void RefreshUpdate() + { + string version = _updates.Version ?? string.Empty; + (IsUpdateBannerVisible, UpdateBannerBody, CanRestartToUpdate) = _updates.Stage switch + { + UpdateStage.Downloading => (true, string.Format(CultureInfo.CurrentCulture, Strings.Update_Banner_Downloading_Format, version, _updates.Percent), false), + UpdateStage.Ready => (true, string.Format(CultureInfo.CurrentCulture, Strings.Update_Banner_Ready_Format, version), true), + UpdateStage.Deferred => (true, string.Format(CultureInfo.CurrentCulture, Strings.Update_Banner_Deferred_Format, version), false), + UpdateStage.Applying => (true, string.Format(CultureInfo.CurrentCulture, Strings.Update_Banner_Applying_Format, version), false), + _ => (false, string.Empty, false), + }; + } + + /// Help ▸ Check for updates (P4 PR-5): 11_UPDATER §Flow, "Manual check". + [RelayCommand] + private Task CheckForUpdatesAsync() => _updates.CheckInteractivelyAsync(); + + /// The banner's button: the Agent stopped, the updater told to wait for this process, the host ended (FR-12 is checked again inside). + [RelayCommand] + private Task RestartToUpdateAsync() => _updates.RestartToUpdateAsync(); + private void Refresh() { (string text, ControlAppearance appearance) = AgentStatusPresentation.Pill(_agent.State); diff --git a/src/FrameLedger.App/ViewModels/SettingsViewModel.cs b/src/FrameLedger.App/ViewModels/SettingsViewModel.cs index bc6bf9fc..14482089 100644 --- a/src/FrameLedger.App/ViewModels/SettingsViewModel.cs +++ b/src/FrameLedger.App/ViewModels/SettingsViewModel.cs @@ -75,6 +75,10 @@ public sealed partial class SettingsViewModel : ObservableObject [ObservableProperty] private string _updateChannel = "stable"; + /// 11_UPDATER §Flow: the startup silent check, on by default (P4 PR-5). + [ObservableProperty] + private bool _autoCheckUpdates = true; + [ObservableProperty] private bool _logDebug; @@ -268,6 +272,8 @@ public sealed partial class SettingsViewModel : ObservableObject partial void OnUpdateChannelChanged(string value) => Persist(SettingsRegistry.UpdateChannel, value); + partial void OnAutoCheckUpdatesChanged(bool value) => Persist(SettingsRegistry.UpdateAutoCheck, value); + partial void OnStartWithWindowsChanged(bool value) { if (_loading) @@ -329,6 +335,7 @@ public sealed partial class SettingsViewModel : ObservableObject MinimizeToTray = await _settings.GetBooleanAsync(SettingsRegistry.UiMinimizeToTray).ConfigureAwait(true); OnlineMetadata = await _settings.GetBooleanAsync(SettingsRegistry.PrivacyOnlineMetadata).ConfigureAwait(true); UpdateChannel = await _settings.GetAsync(SettingsRegistry.UpdateChannel).ConfigureAwait(true); + AutoCheckUpdates = await _settings.GetBooleanAsync(SettingsRegistry.UpdateAutoCheck).ConfigureAwait(true); LogDebug = await _settings.GetBooleanAsync(SettingsRegistry.LogDebug).ConfigureAwait(true); // The Run entry is the truth for "start with Windows"; the settings row follows it. diff --git a/src/FrameLedger.App/ViewModels/TrayViewModel.cs b/src/FrameLedger.App/ViewModels/TrayViewModel.cs index aefb8e4e..7d848b84 100644 --- a/src/FrameLedger.App/ViewModels/TrayViewModel.cs +++ b/src/FrameLedger.App/ViewModels/TrayViewModel.cs @@ -4,6 +4,7 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using FrameLedger.App.Pages; using FrameLedger.App.Services; +using FrameLedger.App.Update; using FrameLedger.Infrastructure.Ipc; using FrameLedger.Shared.Ipc; @@ -23,6 +24,7 @@ public sealed partial class TrayViewModel : ObservableObject, IDisposable private readonly IShellPresence _shell; private readonly ISessionSummaryOpener _summaries; private readonly IPageNavigator _navigator; + private readonly UpdateService _updates; private readonly UiThread _ui = new(); private readonly Dictionary _running = []; @@ -35,17 +37,28 @@ public sealed partial class TrayViewModel : ObservableObject, IDisposable [NotifyPropertyChangedFor(nameof(Tooltip))] private bool _isPaused; - public TrayViewModel(IAgentLink agent, IShellPresence shell, ISessionSummaryOpener summaries, IPageNavigator navigator) + public TrayViewModel(IAgentLink agent, IShellPresence shell, ISessionSummaryOpener summaries, IPageNavigator navigator, UpdateService updates) { _agent = agent ?? throw new ArgumentNullException(nameof(agent)); _shell = shell ?? throw new ArgumentNullException(nameof(shell)); _summaries = summaries ?? throw new ArgumentNullException(nameof(summaries)); _navigator = navigator ?? throw new ArgumentNullException(nameof(navigator)); + _updates = updates ?? throw new ArgumentNullException(nameof(updates)); _agent.Changed += OnAgentChanged; _agent.EventReceived += OnAgentEvent; + _updates.Available += OnUpdateAvailable; IsPaused = _agent.Status?.Paused ?? false; } + /// 08_UI §Notifications policy: "update available" reaches a minimized app as a balloon; on screen, the shell's banner is the one channel. + private void OnUpdateAvailable(object? sender, UpdateAvailableEventArgs e) + { + if (!_shell.IsShown) + { + ToastRequested?.Invoke(this, new TrayToastEventArgs(Strings.Update_Toast_Title, string.Format(CultureInfo.CurrentCulture, Strings.Update_Toast_Body_Format, e.Version), null)); + } + } + /// A balloon to show (the host decides how); never raised while the window is on screen. public event EventHandler? ToastRequested; @@ -69,6 +82,7 @@ public sealed partial class TrayViewModel : ObservableObject, IDisposable { _agent.Changed -= OnAgentChanged; _agent.EventReceived -= OnAgentEvent; + _updates.Available -= OnUpdateAvailable; } [RelayCommand] diff --git a/src/FrameLedger.Application/Settings/SettingsRegistry.cs b/src/FrameLedger.Application/Settings/SettingsRegistry.cs index 239cab33..e9264750 100644 --- a/src/FrameLedger.Application/Settings/SettingsRegistry.cs +++ b/src/FrameLedger.Application/Settings/SettingsRegistry.cs @@ -91,7 +91,7 @@ public static class SettingsRegistry AgentReads = true, }; - /// 11_UPDATER: the Velopack channel (P4 reads it). + /// 11_UPDATER: the release feed's channel — stable is the releases GitHub does not mark pre-release, beta adds the ones it does (P4 PR-5 reads it). public static readonly SettingDefinition UpdateChannel = new() { Key = "update.channel", @@ -100,6 +100,14 @@ public static class SettingsRegistry Choices = ["stable", "beta"], }; + /// 11_UPDATER §Flow: the startup silent check, "if enabled" — on by default, one request to GitHub Releases after start (P4 PR-5). + public static readonly SettingDefinition UpdateAutoCheck = new() + { + Key = "update.auto_check", + Kind = SettingKind.Boolean, + Default = "1", + }; + /// CLAUDE.md rule 8: the opt-in store-metadata fetch, off by default. public static readonly SettingDefinition PrivacyOnlineMetadata = new() { @@ -121,7 +129,7 @@ public static class SettingsRegistry [ UiLanguage, UiTheme, UiStartWithWindows, UiMinimizeToTray, CaptureBackground, HookingKillSwitch, CaptureMinSessionSeconds, TelemetryIntervalMs, RetentionRawSessionsPerGame, - UpdateChannel, PrivacyOnlineMetadata, LogDebug, + UpdateChannel, UpdateAutoCheck, PrivacyOnlineMetadata, LogDebug, ]; private static readonly Dictionary _byKey = All.ToDictionary(static d => d.Key, StringComparer.Ordinal); diff --git a/src/native/CMakeLists.txt b/src/native/CMakeLists.txt index a2b79724..3296a7c2 100644 --- a/src/native/CMakeLists.txt +++ b/src/native/CMakeLists.txt @@ -5,7 +5,20 @@ # hard to retrofit, and two of them are open questions (see below). cmake_minimum_required(VERSION 3.28) -project(FrameLedgerNative VERSION 0.1.0 LANGUAGES CXX RC) + +# ONE version source (P4 PR-5, docs/12_BUILD.md §Version): the VERSION file at the +# repository root, which Directory.Build.props reads for the managed assemblies. +# tools/versioninfo-check.ps1 compares every built binary's FileVersion against +# the same file, so a read that silently produced 0.0.0 here would be red there. +set(FL_VERSION_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../VERSION") +# Re-configure when the file changes, or a bumped VERSION would ship yesterday's version blocks. +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${FL_VERSION_PATH}") +file(READ "${FL_VERSION_PATH}" FL_VERSION_FILE) +string(STRIP "${FL_VERSION_FILE}" FL_VERSION_FILE) +if(NOT FL_VERSION_FILE MATCHES "^[0-9]+\\.[0-9]+\\.[0-9]+$") + message(FATAL_ERROR "VERSION must be MAJOR.MINOR.PATCH (read '${FL_VERSION_FILE}')") +endif() +project(FrameLedgerNative VERSION ${FL_VERSION_FILE} LANGUAGES CXX RC) if(NOT WIN32) message(FATAL_ERROR "FrameLedger's native layer is Windows-only.") diff --git a/tests/FrameLedger.App.Tests/AgentConnectionTests.cs b/tests/FrameLedger.App.Tests/AgentConnectionTests.cs index a7e9b50f..15976172 100644 --- a/tests/FrameLedger.App.Tests/AgentConnectionTests.cs +++ b/tests/FrameLedger.App.Tests/AgentConnectionTests.cs @@ -109,9 +109,10 @@ public sealed class AgentConnectionTests : IAsyncDisposable _serving = null; } - private AgentConnection Start(FakeLauncher launcher) + private AgentConnection Start(FakeLauncher launcher, bool holdLaunches = false) { _connection = new AgentConnection(launcher, () => new PipeClient(_pipeName), _fast, "app-test"); + _connection.SetLaunchHold(holdLaunches); _connection.Changed += (s, _) => { lock (_seen) @@ -134,6 +135,34 @@ public sealed class AgentConnectionTests : IAsyncDisposable condition().Should().BeTrue(because); } + [Fact] + public async Task WhileLaunchesAreHeldAnAbsentAgentIsNotStartedAndIsStartedOnceReleased() + { + // P4 PR-5: the update's apply asks the Agent to stop and must not have this loop start it again under the updater. + FakeLauncher? launcher = null; + launcher = new FakeLauncher(() => + { + StartServer(); + return true; + }) + { CanLaunch = true }; + AgentConnection c = Start(launcher, holdLaunches: true); + + await WaitForAsync(() => c.Rounds >= 2, "two rounds found nothing").ConfigureAwait(true); + launcher.Starts.Should().Be(0, "held"); + c.LaunchesHeld.Should().BeTrue(); + lock (_seen) + { + _seen.Should().NotContain(AgentConnectionState.Starting, "a held round never says it is starting one"); + _seen.Should().NotContain(AgentConnectionState.Missing, "an Agent could be started, so the pill says Offline, not Missing"); + } + + c.SetLaunchHold(false); + c.RetryNow(); + await WaitForAsync(() => c.State == AgentConnectionState.Connected, "released: started, then connected").ConfigureAwait(true); + launcher.Starts.Should().Be(1); + } + [Fact] public async Task WithNoAgentBesideTheAppTheStateIsMissingAndNothingIsStarted() { diff --git a/tests/FrameLedger.App.Tests/DashboardViewModelTests.cs b/tests/FrameLedger.App.Tests/DashboardViewModelTests.cs index 523e252f..baf856ef 100644 --- a/tests/FrameLedger.App.Tests/DashboardViewModelTests.cs +++ b/tests/FrameLedger.App.Tests/DashboardViewModelTests.cs @@ -30,6 +30,10 @@ public sealed class DashboardViewModelTests where T : class => EventReceived?.Invoke(this, new AgentEventArgs(IpcCodec.Decode(IpcCodec.Encode(type, null, payload)))); public void Change() => Changed?.Invoke(this, EventArgs.Empty); + + public void SetLaunchHold(bool hold) + { + } } private sealed class NoSummaries : ISessionSummaryOpener diff --git a/tests/FrameLedger.App.Tests/FakeAgentLink.cs b/tests/FrameLedger.App.Tests/FakeAgentLink.cs index 9f1583e8..0c19eab4 100644 --- a/tests/FrameLedger.App.Tests/FakeAgentLink.cs +++ b/tests/FrameLedger.App.Tests/FakeAgentLink.cs @@ -16,6 +16,11 @@ internal sealed class FakeAgentLink : IAgentLink public List<(string Type, object Payload)> Sent { get; } = []; + /// Every call, in order (P4 PR-5: the apply holds, a failed apply releases). + public List Holds { get; } = []; + + public void SetLaunchHold(bool hold) => Holds.Add(hold); + public Func Answer { get; set; } = static (_, _) => throw new InvalidOperationException("no answer scripted"); public event EventHandler? Changed; diff --git a/tests/FrameLedger.App.Tests/MemorySettings.cs b/tests/FrameLedger.App.Tests/MemorySettings.cs new file mode 100644 index 00000000..f63fee05 --- /dev/null +++ b/tests/FrameLedger.App.Tests/MemorySettings.cs @@ -0,0 +1,17 @@ +using FrameLedger.Application.Persistence; + +namespace FrameLedger.App.Tests; + +/// An in a dictionary, for a flow that reads a setting or two and has no ledger of its own. +internal sealed class MemorySettings : 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; + } +} diff --git a/tests/FrameLedger.App.Tests/PagesLoadTests.cs b/tests/FrameLedger.App.Tests/PagesLoadTests.cs index 9a3f5e4c..4a2081de 100644 --- a/tests/FrameLedger.App.Tests/PagesLoadTests.cs +++ b/tests/FrameLedger.App.Tests/PagesLoadTests.cs @@ -47,6 +47,10 @@ public sealed class PagesLoadTests public Task RequestAsync(string type, TRequest payload, CancellationToken ct = default) where TRequest : class => throw new NotSupportedException(); + + public void SetLaunchHold(bool hold) + { + } } private sealed class NoNavigation : IPageNavigator diff --git a/tests/FrameLedger.App.Tests/SettingsViewModelTests.cs b/tests/FrameLedger.App.Tests/SettingsViewModelTests.cs index d10c3d09..2144ccc0 100644 --- a/tests/FrameLedger.App.Tests/SettingsViewModelTests.cs +++ b/tests/FrameLedger.App.Tests/SettingsViewModelTests.cs @@ -217,6 +217,23 @@ public sealed class SettingsViewModelTests (await s.Games.FindByIdAsync(on.Id, Ct))!.HookEnabled.Should().BeTrue("a fake Agent wrote nothing — the App itself never touches hook_enabled (D15)"); } + [Fact] + public async Task TheStartupUpdateCheckIsOnByDefaultAndItsToggleIsPersisted() + { + // 11_UPDATER §Flow, "if enabled" (P4 PR-5): update.auto_check, default 1, the row the updater reads. + await using ScratchLedger s = await ScratchLedger.OpenAsync(); + Harness h = await OpenAsync(s); + + h.Vm.AutoCheckUpdates.Should().BeTrue(); + (await new SqliteSettingsStore(s.Db).GetAsync(SettingsRegistry.UpdateAutoCheck.Key, Ct)).Should().BeNull("nothing was written by the load"); + + h.Vm.AutoCheckUpdates = false; + Task pending = h.Vm.Pending; + await pending; + + (await h.Settings.GetBooleanAsync(SettingsRegistry.UpdateAutoCheck, Ct)).Should().BeFalse(); + } + [Fact] public async Task ARevokeTheAgentCannotTakeStaysInTheListAndSaysWhy() { diff --git a/tests/FrameLedger.App.Tests/TrayViewModelTests.cs b/tests/FrameLedger.App.Tests/TrayViewModelTests.cs index 4701a15f..ec341ca0 100644 --- a/tests/FrameLedger.App.Tests/TrayViewModelTests.cs +++ b/tests/FrameLedger.App.Tests/TrayViewModelTests.cs @@ -1,6 +1,9 @@ using FluentAssertions; using FrameLedger.App.Services; +using FrameLedger.App.Tests.Update; +using FrameLedger.App.Update; using FrameLedger.App.ViewModels; +using FrameLedger.Application.Settings; using FrameLedger.Shared.Ipc; namespace FrameLedger.App.Tests; @@ -47,11 +50,40 @@ public sealed class TrayViewModelTests private static SessionCompletedEvent Completed(Guid guid, long? sessionId) => new(guid, sessionId, "normal", 1, "ok", "exit"); + /// An updater over a client that finds , wired to the same link as the tray (P4 PR-5). + private static UpdateService Updates(IAgentLink link, UpdateCandidate? next = null) => + new(new FakeUpdateClient { Next = next }, link, new RegisteredSettings(new MemorySettings()), new FakeUpdatePrompts(), new FakeShell(), new RecordingStrip()); + + [Fact] + public async Task AnUpdateFoundWhileTheWindowIsOffScreenIsABalloonAndOnScreenIsNot() + { + // 08_UI §Notifications policy: "update available" reaches a minimized app as a balloon; on screen the shell's banner is the one channel. + var link = new FakeAgentLink(); + var candidate = new UpdateCandidate("0.2.0", null, 1); + using UpdateService hidden = Updates(link, candidate); + using var vm = new TrayViewModel(link, new FakeShell { IsShown = false }, new FakeSummaries(), new NoNavigation(), hidden); + var toasts = new List(); + vm.ToastRequested += (_, t) => toasts.Add(t); + + await hidden.CheckSilentlyAsync(TestContext.Current.CancellationToken); + + toasts.Should().ContainSingle().Which.Title.Should().Be(Strings.Update_Toast_Title); + toasts[0].SessionId.Should().BeNull("a click reveals the window; there is no session to open"); + + using UpdateService shown = Updates(link, candidate); + using var onScreen = new TrayViewModel(link, new FakeShell { IsShown = true }, new FakeSummaries(), new NoNavigation(), shown); + var none = new List(); + onScreen.ToastRequested += (_, t) => none.Add(t); + await shown.CheckSilentlyAsync(TestContext.Current.CancellationToken); + none.Should().BeEmpty(); + } + [Fact] public void TheStateFollowsTheSessionsAndTheirTier() { var link = new FakeAgentLink(); - using var vm = new TrayViewModel(link, new FakeShell(), new FakeSummaries(), new NoNavigation()); + using UpdateService updates = Updates(link); + using var vm = new TrayViewModel(link, new FakeShell(), new FakeSummaries(), new NoNavigation(), updates); vm.State.Should().Be(TrayState.Idle); vm.Tooltip.Should().Be(Strings.Tray_State_Idle); @@ -74,7 +106,8 @@ public sealed class TrayViewModelTests public async Task PauseIsOneRequestAndTheStateIsTheAgentsAnswer() { var link = new FakeAgentLink { Answer = static (type, _) => FakeAgentLink.Envelope(IpcMessageType.PauseAck, new PauseAck(string.Equals(type, IpcMessageType.PauseCapture, StringComparison.Ordinal))) }; - using var vm = new TrayViewModel(link, new FakeShell(), new FakeSummaries(), new NoNavigation()); + using UpdateService updates = Updates(link); + using var vm = new TrayViewModel(link, new FakeShell(), new FakeSummaries(), new NoNavigation(), updates); link.Raise(IpcMessageType.SessionStarted, Started(Guid.NewGuid(), 1)); await vm.TogglePauseCommand.ExecuteAsync(null); @@ -95,7 +128,8 @@ public sealed class TrayViewModelTests public async Task WithoutAnAgentPauseSendsNothing() { var link = new FakeAgentLink { IsConnected = false }; - using var vm = new TrayViewModel(link, new FakeShell(), new FakeSummaries(), new NoNavigation()); + using UpdateService updates = Updates(link); + using var vm = new TrayViewModel(link, new FakeShell(), new FakeSummaries(), new NoNavigation(), updates); await vm.TogglePauseCommand.ExecuteAsync(null); @@ -109,7 +143,8 @@ public sealed class TrayViewModelTests var link = new FakeAgentLink(); var shell = new FakeShell { IsShown = true }; var summaries = new FakeSummaries(); - using var vm = new TrayViewModel(link, shell, summaries, new NoNavigation()); + using UpdateService updates = Updates(link); + using var vm = new TrayViewModel(link, shell, summaries, new NoNavigation(), updates); var toasts = new List(); vm.ToastRequested += (_, t) => toasts.Add(t); var first = Guid.NewGuid(); @@ -136,7 +171,8 @@ public sealed class TrayViewModelTests public void ADiscardedSessionAndASafetyEventRaiseNoBalloon() { var link = new FakeAgentLink(); - using var vm = new TrayViewModel(link, new FakeShell { IsShown = false }, new FakeSummaries(), new NoNavigation()); + using UpdateService updates = Updates(link); + using var vm = new TrayViewModel(link, new FakeShell { IsShown = false }, new FakeSummaries(), new NoNavigation(), updates); var toasts = new List(); vm.ToastRequested += (_, t) => toasts.Add(t); var guid = Guid.NewGuid(); @@ -155,7 +191,8 @@ public sealed class TrayViewModelTests { var shell = new FakeShell(); var nav = new NoNavigation(); - using var vm = new TrayViewModel(new FakeAgentLink(), shell, new FakeSummaries(), nav); + using UpdateService updates = Updates(new FakeAgentLink()); + using var vm = new TrayViewModel(new FakeAgentLink(), shell, new FakeSummaries(), nav, updates); vm.OpenCommand.Execute(null); vm.AgentStatusCommand.Execute(null); @@ -170,7 +207,8 @@ public sealed class TrayViewModelTests public void ADisconnectClearsTheRunningSessions() { var link = new FakeAgentLink(); - using var vm = new TrayViewModel(link, new FakeShell(), new FakeSummaries(), new NoNavigation()); + using UpdateService updates = Updates(link); + using var vm = new TrayViewModel(link, new FakeShell(), new FakeSummaries(), new NoNavigation(), updates); link.Raise(IpcMessageType.SessionStarted, Started(Guid.NewGuid(), 1)); vm.State.Should().Be(TrayState.Capturing); diff --git a/tests/FrameLedger.App.Tests/Update/FakeUpdateClient.cs b/tests/FrameLedger.App.Tests/Update/FakeUpdateClient.cs new file mode 100644 index 00000000..733d1f38 --- /dev/null +++ b/tests/FrameLedger.App.Tests/Update/FakeUpdateClient.cs @@ -0,0 +1,50 @@ +using FrameLedger.App.Update; + +namespace FrameLedger.App.Tests.Update; + +/// An a test scripts: what the next check finds, what each step throws, and what was asked of it. +internal sealed class FakeUpdateClient : IUpdateClient +{ + public bool IsInstalled { get; set; } = true; + + public string? CurrentVersion { get; set; } = "0.1.0"; + + /// What the next check returns; null is "current". + public UpdateCandidate? Next { get; set; } + + public UpdateException? CheckThrows { get; set; } + + /// One failure per download attempt, in order; an empty queue downloads. + public Queue DownloadThrows { get; } = new(); + + public int DownloadAttempts { get; private set; } + + /// The includePrereleases flag of every check, in order. + public List Checks { get; } = []; + + public List Downloaded { get; } = []; + + public List Applied { get; } = []; + + public Task CheckAsync(bool includePrereleases, CancellationToken ct = default) + { + Checks.Add(includePrereleases); + return CheckThrows is { } ex ? Task.FromException(ex) : Task.FromResult(Next); + } + + public Task DownloadAsync(UpdateCandidate candidate, IProgress? progress, CancellationToken ct = default) + { + DownloadAttempts++; + if (DownloadThrows.TryDequeue(out UpdateException? ex)) + { + return Task.FromException(ex); + } + + progress?.Report(50); + progress?.Report(100); + Downloaded.Add(candidate.Version); + return Task.CompletedTask; + } + + public void ApplyOnExit(UpdateCandidate candidate) => Applied.Add(candidate.Version); +} diff --git a/tests/FrameLedger.App.Tests/Update/FakeUpdatePrompts.cs b/tests/FrameLedger.App.Tests/Update/FakeUpdatePrompts.cs new file mode 100644 index 00000000..d5e1861a --- /dev/null +++ b/tests/FrameLedger.App.Tests/Update/FakeUpdatePrompts.cs @@ -0,0 +1,41 @@ +using FrameLedger.App.Update; + +namespace FrameLedger.App.Tests.Update; + +/// An that answers the offer as scripted and remembers every dialog it would have shown. +internal sealed class FakeUpdatePrompts : IUpdatePrompts +{ + public bool Accept { get; set; } = true; + + public List Offered { get; } = []; + + public List UpToDate { get; } = []; + + public int NotInstalled { get; private set; } + + public List Failed { get; } = []; + + public Task OfferAsync(UpdateCandidate candidate, CancellationToken ct = default) + { + Offered.Add(candidate.Version); + return Task.FromResult(Accept); + } + + public Task UpToDateAsync(string version, CancellationToken ct = default) + { + UpToDate.Add(version); + return Task.CompletedTask; + } + + public Task NotInstalledAsync(CancellationToken ct = default) + { + NotInstalled++; + return Task.CompletedTask; + } + + public Task FailedAsync(UpdateFailure failure, CancellationToken ct = default) + { + Failed.Add(failure); + return Task.CompletedTask; + } +} diff --git a/tests/FrameLedger.App.Tests/Update/UninstallHookTests.cs b/tests/FrameLedger.App.Tests/Update/UninstallHookTests.cs new file mode 100644 index 00000000..2c978604 --- /dev/null +++ b/tests/FrameLedger.App.Tests/Update/UninstallHookTests.cs @@ -0,0 +1,97 @@ +using FluentAssertions; +using FrameLedger.App.Update; + +namespace FrameLedger.App.Tests.Update; + +/// 12_BUILD §Publish & package, the uninstall hook: every step runs, a failing one does not stop the next, and the data folder goes only on an explicit yes. +public sealed class UninstallHookTests +{ + private sealed class Probe + { + public int Agent { get; set; } + + public int Layer { get; set; } + + public int Task { get; set; } + + public int Asked { get; set; } + + public int Deleted { get; set; } + + public List Log { get; } = []; + + public bool Answer { get; set; } + + public Func? LayerBehaviour { get; set; } + + public UninstallHook Hook() => new( + stopAgent: () => + { + Agent++; + return true; + }, + unregisterLayer: () => + { + Layer++; + return LayerBehaviour is { } b ? b() : true; + }, + removeTask: () => + { + Task++; + return true; + }, + askDeleteData: () => + { + Asked++; + return Answer; + }, + deleteData: () => Deleted++, + log: Log.Add); + } + + [Theory] + [InlineData(@"C:\Users\u\AppData\Local\FrameLedger", @"C:\Users\u\AppData\Local\FrameLedger.App\current\", true)] + [InlineData(@"C:\Users\u\AppData\Local\FrameLedger", @"C:\Users\u\AppData\Local\FrameLedger\current\", false)] + [InlineData(@"C:\Users\u\AppData\Local\FrameLedger\current", @"C:\Users\u\AppData\Local\FrameLedger", false)] + [InlineData(@"C:\Users\u\AppData\Local\FrameLedger", @"c:\users\u\appdata\local\frameledger", false)] + [InlineData(@"C:\Users\u\AppData\Local\FrameLedger", @"C:\Users\u\AppData\Local\FrameLedgerX", true)] + public void TheDataFolderIsDeletableOnlyWhenItAndTheInstallAreSeparate(string data, string install, bool separate) => + UninstallHook.AreSeparate(data, install).Should().Be(separate, "a package id equal to the data folder's name puts the install inside the ledger's folder"); + + [Fact] + public void YesRemovesEverythingIncludingTheDataFolder() + { + var p = new Probe { Answer = true }; + + UninstallOutcome outcome = p.Hook().Run(); + + outcome.Should().Be(new UninstallOutcome(true, true, true, true, true)); + (p.Agent, p.Layer, p.Task, p.Asked, p.Deleted).Should().Be((1, 1, 1, 1, 1)); + p.Log.Should().Contain(static l => l.Contains("data folder delete: done", StringComparison.Ordinal)); + } + + [Fact] + public void NoKeepsTheDataFolderAndStillRemovesTheRegistrationAndTheTask() + { + var p = new Probe { Answer = false }; + + UninstallOutcome outcome = p.Hook().Run(); + + outcome.Should().Be(new UninstallOutcome(true, true, true, true, false)); + p.Deleted.Should().Be(0, "the folder is the user's; only a yes removes it"); + (p.Layer, p.Task).Should().Be((1, 1)); + } + + [Fact] + public void AStepThatThrowsIsLoggedAndTheNextStillRuns() + { + var p = new Probe { Answer = false, LayerBehaviour = static () => throw new UnauthorizedAccessException("HKCU") }; + + UninstallOutcome outcome = p.Hook().Run(); + + outcome.LayerUnregistered.Should().BeFalse(); + outcome.TaskRemoved.Should().BeTrue("the task removal does not depend on the layer step"); + outcome.DataAsked.Should().BeTrue(); + p.Log.Should().Contain(static l => l.Contains("vulkan layer unregister failed: UnauthorizedAccessException", StringComparison.Ordinal)); + } +} diff --git a/tests/FrameLedger.App.Tests/Update/UpdateFailureMapperTests.cs b/tests/FrameLedger.App.Tests/Update/UpdateFailureMapperTests.cs new file mode 100644 index 00000000..aec2d8a5 --- /dev/null +++ b/tests/FrameLedger.App.Tests/Update/UpdateFailureMapperTests.cs @@ -0,0 +1,43 @@ +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using FluentAssertions; +using FrameLedger.App.Update; +using Velopack.Exceptions; + +namespace FrameLedger.App.Tests.Update; + +/// 11_UPDATER §Error mapping, row by row, from the exception the client threw — including one wrapped by a source. +public sealed class UpdateFailureMapperTests +{ + public static TheoryData Rows => new() + { + { new HttpRequestException("gone", null, HttpStatusCode.NotFound), UpdateFailure.NotFound }, + { new HttpRequestException("quota", null, HttpStatusCode.Forbidden), UpdateFailure.RateLimited }, + { new HttpRequestException("quota", null, HttpStatusCode.TooManyRequests), UpdateFailure.RateLimited }, + { new HttpRequestException("down", null, HttpStatusCode.ServiceUnavailable), UpdateFailure.Server }, + { new HttpRequestException("down", null, HttpStatusCode.BadGateway), UpdateFailure.Server }, + { new HttpRequestException("no such host"), UpdateFailure.Offline }, + { new TaskCanceledException("timeout"), UpdateFailure.Offline }, + { new SocketException(10060), UpdateFailure.Offline }, + { new TimeoutException(), UpdateFailure.Offline }, + { new InvalidOperationException("wrapped by the source", new HttpRequestException("gone", null, HttpStatusCode.NotFound)), UpdateFailure.NotFound }, + { new HttpRequestException("odd", null, HttpStatusCode.Unauthorized), UpdateFailure.Unknown }, + { new InvalidOperationException("no idea"), UpdateFailure.Unknown }, + { new ChecksumFailedException("FrameLedger-0.2.0-full.nupkg", "hash mismatch"), UpdateFailure.Corrupt }, + }; + + [Theory] + [MemberData(nameof(Rows))] + public void TheExceptionMapsToItsRow(Exception exception, UpdateFailure expected) => UpdateFailureMapper.Map(exception).Should().Be(expected); + + [Fact] + public void TheClientsExceptionCarriesTheRowAndTheCause() + { + var cause = new HttpRequestException("gone", null, HttpStatusCode.NotFound); + var ex = new UpdateException(UpdateFailureMapper.Map(cause), cause.Message, cause); + ex.Failure.Should().Be(UpdateFailure.NotFound); + ex.InnerException.Should().BeSameAs(cause); + new UpdateException("bare").Failure.Should().Be(UpdateFailure.Unknown, "the standard constructors classify nothing"); + } +} diff --git a/tests/FrameLedger.App.Tests/Update/UpdateServiceTests.cs b/tests/FrameLedger.App.Tests/Update/UpdateServiceTests.cs new file mode 100644 index 00000000..eaa8b515 --- /dev/null +++ b/tests/FrameLedger.App.Tests/Update/UpdateServiceTests.cs @@ -0,0 +1,382 @@ +using FluentAssertions; +using FrameLedger.App.Services; +using FrameLedger.App.Update; +using FrameLedger.Application.Settings; +using FrameLedger.Shared.Ipc; + +namespace FrameLedger.App.Tests.Update; + +/// +/// 11_UPDATER §Flow over the port: the startup check's two skips and its silence on failure, the manual +/// check's dialogs and the error rows, the download landing Ready or Deferred by whether a session runs (FR-12), +/// and the apply — Shutdown to the Agent, the relaunch held, the updater told, the host ended — or refused +/// with everything left as it was. +/// +public sealed class UpdateServiceTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private sealed class FakeShell : IShellPresence + { + public bool IsShown { get; set; } = true; + + public int Quits { get; private set; } + + public void Reveal() + { + } + + public void Quit() => Quits++; + } + + private sealed class Harness + { + public FakeUpdateClient Client { get; } = new(); + + public FakeAgentLink Agent { get; } = new(); + + public MemorySettings Store { get; } = new(); + + public FakeUpdatePrompts Prompts { get; } = new(); + + public FakeShell Shell { get; } = new(); + + public RecordingStrip Strip { get; } = new(); + + public List Available { get; } = []; + + public UpdateService Service { get; } + + public Harness(TimeSpan? agentStop = null) + { + Service = new UpdateService(Client, Agent, new RegisteredSettings(Store), Prompts, Shell, Strip, agentStop); + Service.Available += (_, e) => Available.Add(e.Version); + } + } + + private static UpdateCandidate Candidate(string version = "0.2.0") => new(version, "- notes", 42L * 1024 * 1024); + + private static StatusAck Status(string state, int sessions = 0) => + new(state, null, null, [.. Enumerable.Range(0, sessions).Select(static i => new ActiveSession(Guid.NewGuid(), 1, "Title", 100 + i, 1, DateTimeOffset.UtcNow))]); + + [Fact] + public async Task TheStartupCheckIsSkippedForACopyTheInstallerDidNotLayDown() + { + var h = new Harness(); + h.Client.IsInstalled = false; + h.Client.Next = Candidate(); + + await h.Service.CheckSilentlyAsync(Ct); + + h.Client.Checks.Should().BeEmpty("a bin/ build cannot update itself and must not ask the feed"); + h.Service.Stage.Should().Be(UpdateStage.Idle); + } + + [Fact] + public async Task TheStartupCheckIsSkippedWhenTheSettingIsOff() + { + var h = new Harness(); + h.Store.Rows[SettingsRegistry.UpdateAutoCheck.Key] = "0"; + h.Client.Next = Candidate(); + + await h.Service.CheckSilentlyAsync(Ct); + + h.Client.Checks.Should().BeEmpty("11_UPDATER: the startup check runs 'if enabled'"); + } + + [Fact] + public async Task AStartupCheckThatFindsNothingStaysIdleAndShowsNothing() + { + var h = new Harness(); + + await h.Service.CheckSilentlyAsync(Ct); + + h.Client.Checks.Should().ContainSingle().Which.Should().BeFalse("the stable channel asks for no pre-releases"); + h.Service.Stage.Should().Be(UpdateStage.Idle); + h.Prompts.Offered.Should().BeEmpty(); + h.Prompts.UpToDate.Should().BeEmpty("silent means silent"); + h.Available.Should().BeEmpty(); + } + + [Fact] + public async Task AStartupCheckDownloadsInTheBackgroundAndLandsReadyWhenNoSessionRuns() + { + var h = new Harness(); + h.Client.Next = Candidate(); + + await h.Service.CheckSilentlyAsync(Ct); + + h.Available.Should().ContainSingle("the tray's toast is raised once, when found").Which.Should().Be("0.2.0"); + h.Client.Downloaded.Should().Equal("0.2.0"); + h.Service.Stage.Should().Be(UpdateStage.Ready); + h.Service.Version.Should().Be("0.2.0"); + h.Service.Percent.Should().Be(100); + h.Prompts.Offered.Should().BeEmpty("the startup check never asks; the banner offers the restart"); + } + + [Fact] + public async Task TheBetaChannelAsksForPrereleases() + { + var h = new Harness(); + h.Store.Rows[SettingsRegistry.UpdateChannel.Key] = "beta"; + + await h.Service.CheckSilentlyAsync(Ct); + + h.Client.Checks.Should().ContainSingle().Which.Should().BeTrue("beta includes GitHub pre-releases"); + } + + [Fact] + public async Task ADownloadWhileASessionRunsIsDeferredAndBecomesReadyWhenTheSessionEnds() + { + var h = new Harness(); + h.Agent.Status = Status("capturing", 1); + h.Client.Next = Candidate(); + + await h.Service.CheckSilentlyAsync(Ct); + h.Service.Stage.Should().Be(UpdateStage.Deferred, "FR-12: never apply — or offer the apply — while a game is hooked"); + + h.Agent.Status = Status("idle"); + h.Agent.RaiseChanged(); + h.Service.Stage.Should().Be(UpdateStage.Ready); + + var guid = Guid.NewGuid(); + h.Agent.Raise(IpcMessageType.SessionStarted, new SessionStartedEvent(guid, 1, "Title", 100, 1, DateTimeOffset.UtcNow)); + h.Service.Stage.Should().Be(UpdateStage.Deferred, "a session that started after the download defers it again"); + h.Agent.Raise(IpcMessageType.SessionCompleted, new SessionCompletedEvent(guid, 5, "normal", 1, "saved", "exit")); + h.Service.Stage.Should().Be(UpdateStage.Ready); + } + + [Fact] + public async Task AStartupFailureIsALogLineNotADialog() + { + var h = new Harness(); + h.Client.CheckThrows = new UpdateException(UpdateFailure.Offline, "dns", null); + + await h.Service.CheckSilentlyAsync(Ct); + + h.Prompts.Failed.Should().BeEmpty("NFR-10: offline on the startup check is Information, no dialog"); + h.Service.Stage.Should().Be(UpdateStage.Idle); + } + + [Fact] + public async Task TheManualCheckOnAnUninstalledCopySaysSoAndAsksNothing() + { + var h = new Harness(); + h.Client.IsInstalled = false; + + await h.Service.CheckInteractivelyAsync(Ct); + + h.Prompts.NotInstalled.Should().Be(1); + h.Client.Checks.Should().BeEmpty(); + } + + [Fact] + public async Task TheManualCheckSaysUpToDateWithTheInstalledVersion() + { + var h = new Harness(); + + await h.Service.CheckInteractivelyAsync(Ct); + + h.Prompts.UpToDate.Should().Equal("0.1.0"); + h.Service.Stage.Should().Be(UpdateStage.Idle); + } + + [Fact] + public async Task TheManualCheckOffersAndADeclineDownloadsNothing() + { + var h = new Harness(); + h.Client.Next = Candidate(); + h.Prompts.Accept = false; + + await h.Service.CheckInteractivelyAsync(Ct); + + h.Prompts.Offered.Should().Equal("0.2.0"); + h.Client.Downloaded.Should().BeEmpty(); + h.Service.Stage.Should().Be(UpdateStage.Idle); + } + + [Fact] + public async Task TheManualCheckOffersAndAnAcceptDownloadsToReady() + { + var h = new Harness(); + h.Client.Next = Candidate(); + + await h.Service.CheckInteractivelyAsync(Ct); + + h.Client.Downloaded.Should().Equal("0.2.0"); + h.Service.Stage.Should().Be(UpdateStage.Ready); + } + + [Theory] + [InlineData(UpdateFailure.NotFound)] + [InlineData(UpdateFailure.RateLimited)] + [InlineData(UpdateFailure.Server)] + [InlineData(UpdateFailure.Offline)] + [InlineData(UpdateFailure.Unknown)] + public async Task TheManualCheckMapsAFailureToItsRow(UpdateFailure failure) + { + var h = new Harness(); + h.Client.CheckThrows = new UpdateException(failure, "x", null); + + await h.Service.CheckInteractivelyAsync(Ct); + + h.Prompts.Failed.Should().Equal(failure); + h.Service.Stage.Should().Be(UpdateStage.Idle); + } + + [Fact] + public async Task ACorruptDownloadOnTheManualCheckIsItsRow() + { + var h = new Harness(); + h.Client.Next = Candidate(); + h.Client.DownloadThrows.Enqueue(new UpdateException(UpdateFailure.Corrupt, "hash", null)); + h.Client.DownloadThrows.Enqueue(new UpdateException(UpdateFailure.Corrupt, "hash again", null)); + + await h.Service.CheckInteractivelyAsync(Ct); + + h.Client.DownloadAttempts.Should().Be(2, "11_UPDATER: a hash mismatch retries once, then it is the dialog's"); + h.Prompts.Failed.Should().Equal(UpdateFailure.Corrupt); + h.Service.Stage.Should().Be(UpdateStage.Idle); + } + + [Fact] + public async Task OneCorruptDownloadIsRetriedAndTheSecondLandsReady() + { + var h = new Harness(); + h.Client.Next = Candidate(); + h.Client.DownloadThrows.Enqueue(new UpdateException(UpdateFailure.Corrupt, "hash", null)); + + await h.Service.CheckSilentlyAsync(Ct); + + h.Client.DownloadAttempts.Should().Be(2); + h.Client.Downloaded.Should().Equal("0.2.0"); + h.Service.Stage.Should().Be(UpdateStage.Ready); + } + + [Fact] + public async Task ADownloadThatFailsForAnotherReasonIsNotRetried() + { + var h = new Harness(); + h.Client.Next = Candidate(); + h.Client.DownloadThrows.Enqueue(new UpdateException(UpdateFailure.Offline, "dropped", null)); + + await h.Service.CheckSilentlyAsync(Ct); + + h.Client.DownloadAttempts.Should().Be(1); + h.Service.Stage.Should().Be(UpdateStage.Idle); + } + + [Fact] + public async Task AFaultTheClientDidNotClassifyIsTheUnknownRowNotAnUnhandledCommand() + { + var h = new Harness(); + h.Store.Rows[SettingsRegistry.UpdateChannel.Key] = "stable"; + using var faulting = new UpdateService(new ThrowingClient(), h.Agent, new RegisteredSettings(h.Store), h.Prompts, h.Shell, h.Strip); + + await faulting.CheckInteractivelyAsync(Ct); + + h.Prompts.Failed.Should().Equal(UpdateFailure.Unknown); + faulting.Stage.Should().Be(UpdateStage.Idle); + } + + /// A client whose check throws something it did not wrap — the shape a future bug in the adapter would have. + private sealed class ThrowingClient : IUpdateClient + { + public bool IsInstalled => true; + + public string? CurrentVersion => "0.1.0"; + + public Task CheckAsync(bool includePrereleases, CancellationToken ct = default) => + Task.FromException(new InvalidOperationException("not wrapped")); + + public Task DownloadAsync(UpdateCandidate candidate, IProgress? progress, CancellationToken ct = default) => Task.CompletedTask; + + public void ApplyOnExit(UpdateCandidate candidate) + { + } + } + + [Fact] + public async Task RestartToUpdateRefusesWhileASessionRunsAndLeavesThePackageDeferred() + { + var h = new Harness(); + h.Client.Next = Candidate(); + await h.Service.CheckSilentlyAsync(Ct); + h.Service.Stage.Should().Be(UpdateStage.Ready); + h.Agent.Status = Status("capturing", 1); + + await h.Service.RestartToUpdateAsync(Ct); + + h.Service.Stage.Should().Be(UpdateStage.Deferred); + h.Client.Applied.Should().BeEmpty("FR-12"); + h.Agent.Sent.Should().BeEmpty("the Agent is not even asked"); + h.Shell.Quits.Should().Be(0); + h.Strip.Shown.Should().ContainSingle().Which.Kind.Should().Be("warn"); + } + + [Fact] + public async Task RestartToUpdateStopsTheAgentHoldsItsRelaunchAppliesAndEndsTheHost() + { + var h = new Harness(); + h.Client.Next = Candidate(); + await h.Service.CheckSilentlyAsync(Ct); + h.Agent.Answer = (type, _) => + { + type.Should().Be(IpcMessageType.Shutdown); + h.Agent.IsConnected = false; + return FakeAgentLink.Envelope(IpcMessageType.ShutdownAck, new ShutdownAck()); + }; + + await h.Service.RestartToUpdateAsync(Ct); + + h.Agent.Sent.Should().ContainSingle().Which.Type.Should().Be(IpcMessageType.Shutdown); + h.Agent.Holds.Should().ContainSingle("the connection must not start the Agent under the updater").Which.Should().BeTrue(); + h.Client.Applied.Should().Equal("0.2.0"); + h.Shell.Quits.Should().Be(1); + h.Service.Stage.Should().Be(UpdateStage.Applying); + } + + [Fact] + public async Task RestartToUpdateWithNoAgentConnectedAppliesWithoutAsking() + { + var h = new Harness(); + h.Agent.IsConnected = false; + h.Client.Next = Candidate(); + await h.Service.CheckSilentlyAsync(Ct); + + await h.Service.RestartToUpdateAsync(Ct); + + h.Agent.Sent.Should().BeEmpty(); + h.Client.Applied.Should().Equal("0.2.0"); + h.Shell.Quits.Should().Be(1); + } + + [Fact] + public async Task AnAgentThatDoesNotStopInTimeLeavesEverythingAsItWas() + { + var h = new Harness(TimeSpan.FromMilliseconds(300)); + h.Client.Next = Candidate(); + await h.Service.CheckSilentlyAsync(Ct); + h.Agent.Answer = static (_, _) => FakeAgentLink.Envelope(IpcMessageType.ShutdownAck, new ShutdownAck()); + + await h.Service.RestartToUpdateAsync(Ct); + + h.Agent.Holds.Should().Equal([true, false], "held for the attempt, released when it was abandoned"); + h.Client.Applied.Should().BeEmpty("an Agent still holding the install directory would make the apply fail half way"); + h.Shell.Quits.Should().Be(0); + h.Service.Stage.Should().Be(UpdateStage.Ready, "the package is still there for the next try"); + h.Strip.Shown.Should().ContainSingle().Which.Body.Should().Be(Strings.Update_AgentStillRunning); + } + + [Fact] + public async Task RestartToUpdateWithNothingDownloadedDoesNothing() + { + var h = new Harness(); + + await h.Service.RestartToUpdateAsync(Ct); + + h.Client.Applied.Should().BeEmpty(); + h.Shell.Quits.Should().Be(0); + h.Agent.Holds.Should().BeEmpty(); + } +} diff --git a/tools/release-notes.ps1 b/tools/release-notes.ps1 new file mode 100644 index 00000000..ba315cf9 --- /dev/null +++ b/tools/release-notes.ps1 @@ -0,0 +1,130 @@ +#Requires -Version 7.0 +<# +.SYNOPSIS + Extracts one version's section from CHANGELOG.md as the GitHub release body. + +.DESCRIPTION + docs/13_CI_CD.md §release.yml: the release body is the CHANGELOG section for the + tag being released. CHANGELOG.md's own header said for five weeks that a missing + section "will mean an empty release note"; this script makes a missing section a + RED release instead, because a release published with no notes is the thing the + ledger exists to prevent and nobody reads an empty body as a defect. + + The section is everything from the `## [x.y.z]` heading to the next `## ` heading + (or the end of the file), heading excluded, trimmed. The heading may carry a date + (`## [0.1.0] - 2026-09-20`, Keep a Changelog's form) or not. An EMPTY section is + red too — a heading that was moved without its entries is the same defect. + + tools/changelog-check.ps1 asserts a pull request touched the ledger; it does not + look at sections and this script does not look at diffs. Two questions, two tools. + +.PARAMETER Version + The version whose section to extract, without the leading `v` (the workflow strips it). + +.PARAMETER Changelog + Path to CHANGELOG.md. Default: the repository's. + +.PARAMETER OutFile + Where to write the body. Written to stdout when omitted. + +.PARAMETER SelfTest + Runs the fixture cases below and exits 0 only if every one behaves; build.ps1 + runs this on every gate so the script is exercised before a tag depends on it. +#> +[CmdletBinding()] +param( + [string]$Version, + [string]$Changelog = (Join-Path (Split-Path $PSScriptRoot -Parent) 'CHANGELOG.md'), + [string]$OutFile, + [switch]$SelfTest +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +function Get-ReleaseSection { + param([string]$Text, [string]$Ver) + + $lines = $Text -split "`r?`n" + $escaped = [regex]::Escape($Ver) + $start = -1 + for ($i = 0; $i -lt $lines.Count; $i++) { + if ($lines[$i] -match "^## \[$escaped\](\s|$)") { $start = $i; break } + } + if ($start -lt 0) { return $null } + + $body = [System.Collections.Generic.List[string]]::new() + for ($i = $start + 1; $i -lt $lines.Count; $i++) { + if ($lines[$i] -match '^## ') { break } + $body.Add($lines[$i]) + } + return (($body -join "`n").Trim()) +} + +if ($SelfTest) { + $fixture = @" +# Changelog + +## [Unreleased] + +### Added + +- something pending + +## [0.2.0] - 2026-10-01 + +### Added + +- the second thing + +### Fixed + +- a fix + +## [0.1.0] + +### Added + +- the first thing +"@ + $cases = @( + @{ Name = 'a dated heading yields its body only'; Ver = '0.2.0'; Expect = "### Added`n`n- the second thing`n`n### Fixed`n`n- a fix" }, + @{ Name = 'an undated last section runs to the end of file'; Ver = '0.1.0'; Expect = "### Added`n`n- the first thing" }, + @{ Name = 'a missing section is null'; Ver = '0.3.0'; Expect = $null }, + @{ Name = 'a prefix does not match (0.1.0 is not 0.1.0-beta.1)'; Ver = '0.1.0-beta.1'; Expect = $null }, + @{ Name = 'an empty section is empty, not the next one'; Ver = 'x'; Text = "## [x]`n`n## [y]`n- y"; Expect = '' } + ) + $failed = 0 + foreach ($c in $cases) { + $text = if ($c.ContainsKey('Text')) { $c.Text } else { $fixture } + $got = Get-ReleaseSection -Text $text -Ver $c.Ver + $ok = if ($null -eq $c.Expect) { $null -eq $got } else { $got -eq $c.Expect } + Write-Host (" {0,-4} {1}" -f ($(if ($ok) { 'ok' } else { 'FAIL' })), $c.Name) -ForegroundColor ($(if ($ok) { 'DarkGray' } else { 'Red' })) + if (-not $ok) { $failed++ } + } + if ($failed -gt 0) { Write-Host "release-notes self-test FAILED ($failed)" -ForegroundColor Red; exit 1 } + Write-Host 'release-notes self-test OK' -ForegroundColor Green + exit 0 +} + +if (-not $Version) { throw '-Version is required (or -SelfTest)' } +if (-not (Test-Path $Changelog)) { throw "no changelog at $Changelog" } + +$section = Get-ReleaseSection -Text (Get-Content $Changelog -Raw) -Ver $Version +if ($null -eq $section) { + Write-Host "RELEASE NOTES FAILED: CHANGELOG.md has no '## [$Version]' section — add one (move the [Unreleased] entries under it) before tagging" -ForegroundColor Red + exit 1 +} +if ($section.Length -eq 0) { + Write-Host "RELEASE NOTES FAILED: the '## [$Version]' section is empty" -ForegroundColor Red + exit 1 +} + +if ($OutFile) { + [System.IO.File]::WriteAllText($OutFile, $section + "`n", [System.Text.UTF8Encoding]::new($false)) + Write-Host "release notes for $Version written to $OutFile ($($section.Length) chars)" -ForegroundColor Green +} +else { + Write-Output $section +} +exit 0 diff --git a/tools/versioninfo-check.ps1 b/tools/versioninfo-check.ps1 index 69f63bba..b793ea49 100644 --- a/tools/versioninfo-check.ps1 +++ b/tools/versioninfo-check.ps1 @@ -22,7 +22,15 @@ #> [CmdletBinding()] param( - [string]$BuildDir = (Join-Path (Split-Path $PSScriptRoot -Parent) 'build/native/x64-release') + [string]$BuildDir = (Join-Path (Split-Path $PSScriptRoot -Parent) 'build/native/x64-release'), + + # P4 PR-5: the one version source (docs/12_BUILD.md §Version). Every binary's + # FileVersion must be this, with the fourth component the .rc template adds. + # Default: the repository's VERSION file; an empty string skips the comparison. + [string]$ExpectedVersion = $( + $f = Join-Path (Split-Path $PSScriptRoot -Parent) 'VERSION' + if (Test-Path $f) { (Get-Content $f -Raw).Trim() } else { '' } + ) ) Set-StrictMode -Version Latest @@ -82,6 +90,13 @@ foreach ($name in $required) { $errors.Add("$name OriginalFilename is '$($vi.OriginalFilename)' — a renamed binary is harder to identify, which is the wrong direction") } + # The version the binary says is the version the repository says (P4 PR-5). A + # native block reading 0.0.0 beside a managed assembly reading 0.1.0 is two + # products claiming to be one, and the release workflow would ship it. + if ($ExpectedVersion -and $vi.FileVersion.Trim() -ne "$ExpectedVersion.0") { + $errors.Add("$name FileVersion is '$($vi.FileVersion)', expected '$ExpectedVersion.0' — the VERSION file is the one source (12_BUILD §Version)") + } + ++$checked Write-Host (" {0,-28} {1} / {2} / v{3}" -f $name, $vi.CompanyName, $vi.ProductName, $vi.FileVersion) -ForegroundColor DarkGray }