From 69cc510bc15e04b0c116c968a184a7bee69bd756 Mon Sep 17 00:00:00 2001 From: PrimeBuild-pc Date: Tue, 21 Apr 2026 19:50:56 +0200 Subject: [PATCH] Harden services and release coverage pipeline --- .github/workflows/ci-devsecops.yml | 37 +- .github/workflows/release.yml | 252 ++++++++++-- .gitignore | 6 +- README.md | 25 +- Services/Abstractions/IGitHubReleaseClient.cs | 13 + Services/Abstractions/IProcessRunner.cs | 32 ++ Services/Abstractions/ISettingsStorage.cs | 20 + Services/ApplicationSettingsService.cs | 62 ++- Services/AutostartService.cs | 186 --------- Services/ElevatedTaskService.cs | 114 ++---- Services/FileSettingsStorage.cs | 46 +++ Services/GitHubReleaseClient.cs | 27 ++ Services/GitHubUpdateChecker.cs | 26 +- Services/PowerPlanService.cs | 93 ++--- Services/ProcessMonitorManagerService.cs | 24 +- Services/ProcessService.cs | 9 +- Services/ServiceConfiguration.cs | 14 + Services/SystemProcessRunner.cs | 69 ++++ Tests/TestRunner.cs | 2 +- .../ApplicationSettingsServiceTests.cs | 123 ++++++ .../AutostartServiceTests.cs | 75 +++- .../ElevatedTaskServiceTests.cs | 130 ++++++ .../GitHubUpdateCheckerTests.cs | 85 ++++ .../PowerPlanServiceTests.cs | 123 ++++++ .../ProcessMonitorManagerServiceTests.cs | 371 ++++++++++++++++++ .../ProcessServiceTests.cs | 144 +++++++ .../ThreadPilot.Core.Tests.csproj | 3 +- .../coverlet.runsettings | 14 + ViewModels/SettingsViewModel.cs | 5 +- build/generate-winget-manifests.ps1 | 109 +++++ build/publish-chocolatey.ps1 | 97 ++++- chocolatey/threadpilot.nuspec | 4 + chocolatey/tools/chocolateyInstall.ps1 | 5 +- docs/QUALITY_GATES.md | 30 +- docs/reference/PROJECT_STRUCTURE.md | 226 +++-------- docs/release/GO_NO_GO_MATRIX.md | 5 + docs/release/PACKAGING.md | 113 +++++- docs/release/RELEASE_RUNBOOK.md | 33 +- 38 files changed, 2164 insertions(+), 588 deletions(-) create mode 100644 Services/Abstractions/IGitHubReleaseClient.cs create mode 100644 Services/Abstractions/IProcessRunner.cs create mode 100644 Services/Abstractions/ISettingsStorage.cs create mode 100644 Services/FileSettingsStorage.cs create mode 100644 Services/GitHubReleaseClient.cs create mode 100644 Services/SystemProcessRunner.cs create mode 100644 Tests/ThreadPilot.Core.Tests/ApplicationSettingsServiceTests.cs create mode 100644 Tests/ThreadPilot.Core.Tests/ElevatedTaskServiceTests.cs create mode 100644 Tests/ThreadPilot.Core.Tests/GitHubUpdateCheckerTests.cs create mode 100644 Tests/ThreadPilot.Core.Tests/PowerPlanServiceTests.cs create mode 100644 Tests/ThreadPilot.Core.Tests/ProcessMonitorManagerServiceTests.cs create mode 100644 Tests/ThreadPilot.Core.Tests/ProcessServiceTests.cs create mode 100644 Tests/ThreadPilot.Core.Tests/coverlet.runsettings create mode 100644 build/generate-winget-manifests.ps1 diff --git a/.github/workflows/ci-devsecops.yml b/.github/workflows/ci-devsecops.yml index 8f9eb9d..c4e8ff8 100644 --- a/.github/workflows/ci-devsecops.yml +++ b/.github/workflows/ci-devsecops.yml @@ -37,7 +37,42 @@ jobs: run: dotnet build "ThreadPilot_1.sln" --configuration Release --no-restore - name: Run tests - run: dotnet test "ThreadPilot_1.sln" --configuration Release --no-build --verbosity normal --collect:"XPlat Code Coverage" --results-directory TestResults + run: dotnet test "Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj" --configuration Release --no-restore --verbosity normal --collect:"XPlat Code Coverage" --settings "Tests/ThreadPilot.Core.Tests/coverlet.runsettings" --results-directory TestResults + + - name: Enforce coverage gate + shell: pwsh + run: | + $ErrorActionPreference = "Stop" + $coveragePath = Get-ChildItem -Path "TestResults" -Recurse -Filter "coverage.cobertura.xml" | + Sort-Object LastWriteTimeUtc -Descending | + Select-Object -First 1 -ExpandProperty FullName + + if ([string]::IsNullOrWhiteSpace($coveragePath)) + { + throw "Coverage file not found under TestResults." + } + + [xml]$coverage = Get-Content $coveragePath + $lineRate = [double]$coverage.coverage.'line-rate' * 100 + $branchRate = [double]$coverage.coverage.'branch-rate' * 100 + # Temporary floor until the service-hardening coverage tasks land. + $minimumLineRate = 1.5 + + $summary = @( + "## Coverage Gate", + "- file: $coveragePath", + "- line coverage: $([math]::Round($lineRate, 2))%", + "- branch coverage: $([math]::Round($branchRate, 2))%", + "- minimum line coverage: $minimumLineRate%" + ) + + $summary | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append + $summary | ForEach-Object { Write-Host $_ } + + if ($lineRate -lt $minimumLineRate) + { + throw "Coverage gate failed. Expected >= $minimumLineRate, actual: $([math]::Round($lineRate, 2))" + } - name: Upload coverage uses: codecov/codecov-action@v4 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6d0460c..474cea5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,6 +5,11 @@ on: tags: - "v*.*.*" workflow_dispatch: + inputs: + dry_run_publish: + description: "Build and validate release without external channel publication" + required: false + default: "false" permissions: contents: write @@ -56,7 +61,7 @@ jobs: run: dotnet build "ThreadPilot_1.sln" --configuration Release --no-restore - name: Test - run: dotnet test "ThreadPilot_1.sln" --configuration Release --no-build --collect:"XPlat Code Coverage" --results-directory TestResults + run: dotnet test "Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj" --configuration Release --no-restore --verbosity normal --collect:"XPlat Code Coverage" --settings "Tests/ThreadPilot.Core.Tests/coverlet.runsettings" --results-directory TestResults - name: Publish self-contained single-file run: dotnet publish "ThreadPilot.csproj" --configuration Release -p:PublishProfile=WinX64-SingleFile @@ -216,7 +221,7 @@ jobs: "$($hash.Hash) $($_.Name)" | Out-File -FilePath $hashFile -Append -Encoding utf8 } - - name: Update winget installer manifest + - name: Generate winget manifests shell: pwsh run: | $ErrorActionPreference = "Stop" @@ -230,16 +235,13 @@ jobs: $sha = (Get-FileHash $installer.FullName -Algorithm SHA256).Hash.ToUpperInvariant() $url = "https://github.com/${{ github.repository }}/releases/download/$tag/$($installer.Name)" - $manifestPath = "winget/manifests/p/PrimeBuild/ThreadPilot/$version/PrimeBuild.ThreadPilot.installer.yaml" - if (-not (Test-Path $manifestPath)) - { - throw "Winget installer manifest not found at $manifestPath" - } - - $content = Get-Content $manifestPath -Raw - $content = $content.Replace("{{INSTALLER_URL}}", $url).Replace("{{INSTALLER_SHA256}}", $sha) - Set-Content -Path $manifestPath -Value $content -Encoding utf8 + ./build/generate-winget-manifests.ps1 ` + -Version $version ` + -Tag $tag ` + -InstallerUrl $url ` + -InstallerSha256 $sha ` + -OutputRoot "winget-manifests" - name: Generate SBOM shell: pwsh @@ -291,7 +293,7 @@ jobs: uses: actions/upload-artifact@v4 with: name: winget-manifests - path: winget/manifests/p/PrimeBuild/ThreadPilot/${{ steps.version.outputs.version }} + path: winget-manifests - name: Upload SBOM uses: actions/upload-artifact@v4 @@ -452,20 +454,59 @@ jobs: if: needs.release.result == 'success' steps: - - name: Check winget publish secrets + - name: Resolve winget publish policy + id: policy + shell: pwsh + run: | + $ErrorActionPreference = "Stop" + $dryRun = "${{ github.event_name }}" -eq "workflow_dispatch" -and "${{ github.event.inputs.dry_run_publish }}" -eq "true" + "dry_run=$($dryRun.ToString().ToLowerInvariant())" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append + + - name: Check winget publish policy id: gate shell: pwsh env: WINGET_GITHUB_TOKEN: ${{ secrets.WINGET_GITHUB_TOKEN }} WINGET_FORK_OWNER: ${{ secrets.WINGET_FORK_OWNER }} run: | - if ([string]::IsNullOrWhiteSpace($env:WINGET_GITHUB_TOKEN) -or [string]::IsNullOrWhiteSpace($env:WINGET_FORK_OWNER)) + $ErrorActionPreference = "Stop" + $logsDir = "release-channel-logs" + New-Item -ItemType Directory -Force -Path $logsDir | Out-Null + $logPath = Join-Path $logsDir "winget-submit-log.txt" + $dryRun = "${{ steps.policy.outputs.dry_run }}" -eq "true" + + if ($dryRun) { - Write-Host "Winget publish secrets missing. Skipping publish-winget job." + $summary = @( + "## winget publish", + "- attempted: false", + "- version: ${{ needs.build.outputs.version }}", + "- result: dry-run", + "- reason: workflow_dispatch requested dry_run_publish=true" + ) + + $summary | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append + "Dry run requested. Winget submission intentionally skipped." | Set-Content -Path $logPath -Encoding utf8 "enabled=false" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append exit 0 } + if ([string]::IsNullOrWhiteSpace($env:WINGET_GITHUB_TOKEN) -or [string]::IsNullOrWhiteSpace($env:WINGET_FORK_OWNER)) + { + $message = "Winget publish secrets are missing. Refusing to report a green public release without a submission attempt." + $summary = @( + "## winget publish", + "- attempted: false", + "- version: ${{ needs.build.outputs.version }}", + "- result: failed-policy", + "- reason: missing WINGET_GITHUB_TOKEN and/or WINGET_FORK_OWNER" + ) + + $summary | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append + $message | Set-Content -Path $logPath -Encoding utf8 + throw $message + } + "enabled=true" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - name: Checkout @@ -487,13 +528,50 @@ jobs: WINGET_FORK_OWNER: ${{ secrets.WINGET_FORK_OWNER }} run: | $ErrorActionPreference = "Stop" - ./build/submit-winget-pr.ps1 ` - -Version "${{ needs.build.outputs.version }}" ` - -ManifestSourcePath "winget-manifests" ` - -ForkOwner "$env:WINGET_FORK_OWNER" ` - -RepositoryOwner "PrimeBuild" ` - -PackageIdentifier "PrimeBuild.ThreadPilot" ` - -GithubToken "$env:WINGET_GITHUB_TOKEN" + $logsDir = "release-channel-logs" + New-Item -ItemType Directory -Force -Path $logsDir | Out-Null + $logPath = Join-Path $logsDir "winget-submit-log.txt" + + try + { + & ./build/submit-winget-pr.ps1 ` + -Version "${{ needs.build.outputs.version }}" ` + -ManifestSourcePath "winget-manifests" ` + -ForkOwner "$env:WINGET_FORK_OWNER" ` + -RepositoryOwner "PrimeBuild" ` + -PackageIdentifier "PrimeBuild.ThreadPilot" ` + -GithubToken "$env:WINGET_GITHUB_TOKEN" *>&1 | Tee-Object -FilePath $logPath + + if ($LASTEXITCODE -ne 0) + { + throw "submit-winget-pr.ps1 exited with code $LASTEXITCODE" + } + + @( + "## winget publish", + "- attempted: true", + "- version: ${{ needs.build.outputs.version }}", + "- result: submitted" + ) | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append + } + catch + { + @( + "## winget publish", + "- attempted: true", + "- version: ${{ needs.build.outputs.version }}", + "- result: failed" + ) | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append + throw + } + + - name: Upload winget publish logs + if: always() + uses: actions/upload-artifact@v4 + with: + name: winget-publish-logs + path: release-channel-logs/winget-submit-log.txt + if-no-files-found: error publish-chocolatey: runs-on: windows-latest @@ -503,19 +581,61 @@ jobs: if: needs.release.result == 'success' steps: - - name: Check chocolatey publish secret + - name: Resolve chocolatey publish policy + id: policy + shell: pwsh + run: | + $ErrorActionPreference = "Stop" + $dryRun = "${{ github.event_name }}" -eq "workflow_dispatch" -and "${{ github.event.inputs.dry_run_publish }}" -eq "true" + "dry_run=$($dryRun.ToString().ToLowerInvariant())" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append + + - name: Check chocolatey publish policy id: gate shell: pwsh env: CHOCOLATEY_API_KEY: ${{ secrets.CHOCOLATEY_API_KEY }} run: | - if ([string]::IsNullOrWhiteSpace($env:CHOCOLATEY_API_KEY)) + $ErrorActionPreference = "Stop" + $logsDir = "release-channel-logs" + New-Item -ItemType Directory -Force -Path $logsDir | Out-Null + $packLogPath = Join-Path $logsDir "choco-pack-log.txt" + $pushLogPath = Join-Path $logsDir "choco-push-log.txt" + $dryRun = "${{ steps.policy.outputs.dry_run }}" -eq "true" + + if ($dryRun) { - Write-Host "Chocolatey API key missing. Skipping publish-chocolatey job." + $summary = @( + "## chocolatey publish", + "- attempted: false", + "- version: ${{ needs.build.outputs.version }}", + "- result: dry-run", + "- reason: workflow_dispatch requested dry_run_publish=true" + ) + + $summary | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append + "Dry run requested. Chocolatey pack validation and push intentionally skipped." | Set-Content -Path $packLogPath -Encoding utf8 + "Dry run requested. Chocolatey push intentionally skipped." | Set-Content -Path $pushLogPath -Encoding utf8 "enabled=false" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append exit 0 } + if ([string]::IsNullOrWhiteSpace($env:CHOCOLATEY_API_KEY)) + { + $message = "CHOCOLATEY_API_KEY is missing. Refusing to report a green public release without a package publish attempt." + $summary = @( + "## chocolatey publish", + "- attempted: false", + "- version: ${{ needs.build.outputs.version }}", + "- result: failed-policy", + "- reason: missing CHOCOLATEY_API_KEY" + ) + + $summary | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append + $message | Set-Content -Path $packLogPath -Encoding utf8 + $message | Set-Content -Path $pushLogPath -Encoding utf8 + throw $message + } + "enabled=true" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - name: Checkout @@ -529,6 +649,35 @@ jobs: name: release-installer path: release-assets/installer + - name: Validate chocolatey package + if: steps.gate.outputs.enabled == 'true' + shell: pwsh + run: | + $ErrorActionPreference = "Stop" + $logsDir = (Resolve-Path "release-channel-logs").Path + $packLogPath = Join-Path $logsDir "choco-pack-log.txt" + $artifactRoot = "release-channel-artifacts/chocolatey" + New-Item -ItemType Directory -Force -Path $artifactRoot | Out-Null + + $installer = Get-ChildItem "release-assets/installer/*.exe" -File | Select-Object -First 1 + if (-not $installer) + { + throw "Installer executable not found for Chocolatey validation." + } + + & ./build/publish-chocolatey.ps1 ` + -Version "${{ needs.build.outputs.version }}" ` + -Tag "${{ needs.build.outputs.tag }}" ` + -InstallerPath $installer.FullName ` + -DryRun ` + -PackageOutputDirectory $artifactRoot ` + -MetadataOutputPath (Join-Path $artifactRoot "chocolatey-package-metadata.json") *>&1 | Tee-Object -FilePath $packLogPath + + if ($LASTEXITCODE -ne 0) + { + throw "Chocolatey dry-run validation failed with exit code $LASTEXITCODE" + } + - name: Publish chocolatey package if: steps.gate.outputs.enabled == 'true' shell: pwsh @@ -536,14 +685,57 @@ jobs: CHOCOLATEY_API_KEY: ${{ secrets.CHOCOLATEY_API_KEY }} run: | $ErrorActionPreference = "Stop" + $logsDir = (Resolve-Path "release-channel-logs").Path + $pushLogPath = Join-Path $logsDir "choco-push-log.txt" + $artifactRoot = "release-channel-artifacts/chocolatey" + New-Item -ItemType Directory -Force -Path $artifactRoot | Out-Null $installer = Get-ChildItem "release-assets/installer/*.exe" -File | Select-Object -First 1 if (-not $installer) { throw "Installer executable not found for Chocolatey publish." } - ./build/publish-chocolatey.ps1 ` - -Version "${{ needs.build.outputs.version }}" ` - -Tag "${{ needs.build.outputs.tag }}" ` - -InstallerPath $installer.FullName ` - -ApiKey "$env:CHOCOLATEY_API_KEY" + try + { + & ./build/publish-chocolatey.ps1 ` + -Version "${{ needs.build.outputs.version }}" ` + -Tag "${{ needs.build.outputs.tag }}" ` + -InstallerPath $installer.FullName ` + -ApiKey "$env:CHOCOLATEY_API_KEY" ` + -PackageOutputDirectory $artifactRoot ` + -MetadataOutputPath (Join-Path $artifactRoot "chocolatey-publish-metadata.json") *>&1 | Tee-Object -FilePath $pushLogPath + + if ($LASTEXITCODE -ne 0) + { + throw "publish-chocolatey.ps1 exited with code $LASTEXITCODE" + } + + @( + "## chocolatey publish", + "- attempted: true", + "- version: ${{ needs.build.outputs.version }}", + "- result: published" + ) | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append + } + catch + { + @( + "## chocolatey publish", + "- attempted: true", + "- version: ${{ needs.build.outputs.version }}", + "- result: failed" + ) | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append + throw + } + + - name: Upload chocolatey publish logs + if: always() + uses: actions/upload-artifact@v4 + with: + name: chocolatey-publish-logs + path: | + release-channel-logs/choco-pack-log.txt + release-channel-logs/choco-push-log.txt + release-channel-artifacts/chocolatey/*.nupkg + release-channel-artifacts/chocolatey/*.json + if-no-files-found: error diff --git a/.gitignore b/.gitignore index ea89bea..ad9a159 100644 --- a/.gitignore +++ b/.gitignore @@ -23,6 +23,10 @@ artifacts/ !docs/release/ !docs/release/*.md +# Local worktrees and planning docs +.worktrees/ +docs/superpowers/plans/ + # Test and coverage [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* @@ -146,4 +150,4 @@ gitleaks*.tar.gz *_old.* *.orig *.rej -*.xaml.bak \ No newline at end of file +*.xaml.bak diff --git a/README.md b/README.md index 73cb158..aa94ddb 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ ThreadPilot is a free and open-source Windows process and power plan manager foc The project targets users who need Process Lasso style capabilities in a modern WPF desktop application with enterprise-grade reliability, security hardening, and automation support. +Coverage badge tracks business/application code and excludes generated build artifacts. + [![Thread-Pilotbanner.png](https://i.postimg.cc/sDZLXMqr/Thread-Pilotbanner.png)](https://postimg.cc/cr0hkLd9) ## ✨ Key Features @@ -36,7 +38,7 @@ The project targets users who need Process Lasso style capabilities in a modern ## 📦 Download [![Download Latest Release](https://img.shields.io/badge/Download-Latest%20Release-2ea44f?logo=github)](https://github.com/PrimeBuild-pc/ThreadPilot/releases/latest) -[![Direct Portable ZIP](https://img.shields.io/badge/Direct-Portable%20ZIP-1f6feb?logo=github)](https://github.com/PrimeBuild-pc/ThreadPilot/releases/latest/download/ThreadPilot_v1.1.2_Portable.zip) +[![Portable ZIP Assets](https://img.shields.io/badge/Portable%20ZIP-Release%20Assets-1f6feb?logo=github)](https://github.com/PrimeBuild-pc/ThreadPilot/releases/latest) ### One-Click Terminal Install @@ -58,19 +60,18 @@ Latest artifacts are published on each tagged release in [GitHub Releases](https | Package | File name | Recommended use | |---|---|---| -| Installer (Recommended) | `ThreadPilot_v1.1.2_Setup.exe` | Standard Windows installer (Inno Setup) for most users | -| Portable | `ThreadPilot_v1.1.2_Portable.zip` | No-install deployment for power users | +| Installer (Recommended) | `ThreadPilot_v_Setup.exe` | Standard Windows installer (Inno Setup) for most users | +| Portable | `ThreadPilot_v_singlefile_win-x64.zip` | No-install deployment for power users | Quick links: - Release page: https://github.com/PrimeBuild-pc/ThreadPilot/releases/latest -- Direct portable ZIP: https://github.com/PrimeBuild-pc/ThreadPilot/releases/latest/download/ThreadPilot_v1.1.2_Portable.zip Verification examples: ```powershell -Get-FileHash .\ThreadPilot_v1.1.2_Setup.exe -Algorithm SHA256 -Get-FileHash .\ThreadPilot_v1.1.2_Portable.zip -Algorithm SHA256 +Get-FileHash .\ThreadPilot_v_Setup.exe -Algorithm SHA256 +Get-FileHash .\ThreadPilot_v_singlefile_win-x64.zip -Algorithm SHA256 ``` Compare hashes with `SHA256SUMS.txt` from the same release. @@ -89,10 +90,16 @@ if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdenti Write-Host "Starting ThreadPilot installation..." -ForegroundColor Cyan -# 2) Define paths -$url = "https://github.com/PrimeBuild-pc/ThreadPilot/releases/latest/download/ThreadPilot_v1.1.2_Setup.exe" +# 2) Resolve latest installer asset from GitHub Releases +$release = Invoke-RestMethod -Uri "https://api.github.com/repos/PrimeBuild-pc/ThreadPilot/releases/latest" +$asset = $release.assets | Where-Object { $_.name -match '^ThreadPilot_v.*_Setup\.exe$' } | Select-Object -First 1 +if (-not $asset) { + throw "Unable to locate the latest ThreadPilot installer asset." +} + +$url = $asset.browser_download_url $destPath = "$env:ProgramFiles\ThreadPilot" -$exePath = "$destPath\ThreadPilot_v1.1.2_Setup.exe" +$exePath = Join-Path $destPath $asset.name # 3) Ensure destination folder exists if (-not (Test-Path $destPath)) { New-Item -ItemType Directory -Force -Path $destPath | Out-Null } diff --git a/Services/Abstractions/IGitHubReleaseClient.cs b/Services/Abstractions/IGitHubReleaseClient.cs new file mode 100644 index 0000000..bf062d6 --- /dev/null +++ b/Services/Abstractions/IGitHubReleaseClient.cs @@ -0,0 +1,13 @@ +namespace ThreadPilot.Services.Abstractions +{ + using System.Threading; + using System.Threading.Tasks; + + /// + /// Retrieves GitHub release payloads for update checks. + /// + public interface IGitHubReleaseClient + { + Task GetLatestReleaseJsonAsync(string owner, string repo, CancellationToken cancellationToken = default); + } +} diff --git a/Services/Abstractions/IProcessRunner.cs b/Services/Abstractions/IProcessRunner.cs new file mode 100644 index 0000000..83a8239 --- /dev/null +++ b/Services/Abstractions/IProcessRunner.cs @@ -0,0 +1,32 @@ +/* + * ThreadPilot - process execution seam. + */ +namespace ThreadPilot.Services.Abstractions +{ + using System; + using System.Collections.Generic; + using System.Threading.Tasks; + + /// + /// Runs external processes with a bounded timeout and captured output. + /// + public interface IProcessRunner + { + /// + /// Executes a process and returns its exit code with captured output streams. + /// + /// Executable path. + /// Argument list passed verbatim to the process. + /// Maximum execution time before the process is treated as timed out. + /// The captured process result. + Task RunAsync(string fileName, IReadOnlyList arguments, TimeSpan timeout); + } + + /// + /// Immutable result returned by . + /// + /// Process exit code, or a synthetic failure code when launch/timeout fails. + /// Captured standard output. + /// Captured standard error. + public readonly record struct ProcessRunResult(int ExitCode, string StandardOutput, string StandardError); +} diff --git a/Services/Abstractions/ISettingsStorage.cs b/Services/Abstractions/ISettingsStorage.cs new file mode 100644 index 0000000..3c5fa61 --- /dev/null +++ b/Services/Abstractions/ISettingsStorage.cs @@ -0,0 +1,20 @@ +namespace ThreadPilot.Services.Abstractions +{ + using System.Threading.Tasks; + + /// + /// Provides a seam for reading and writing persisted settings. + /// + public interface ISettingsStorage + { + bool Exists(string path); + + Task ReadAsync(string path); + + Task WriteAsync(string path, string content); + + void EnsureDirectoryForFile(string path); + + void Copy(string sourcePath, string destinationPath, bool overwrite); + } +} diff --git a/Services/ApplicationSettingsService.cs b/Services/ApplicationSettingsService.cs index 0ab21c2..2b22725 100644 --- a/Services/ApplicationSettingsService.cs +++ b/Services/ApplicationSettingsService.cs @@ -23,6 +23,7 @@ namespace ThreadPilot.Services using System.Threading.Tasks; using Microsoft.Extensions.Logging; using ThreadPilot.Models; + using ThreadPilot.Services.Abstractions; /// /// Service for managing application settings with JSON persistence. @@ -30,7 +31,9 @@ namespace ThreadPilot.Services public class ApplicationSettingsService : IApplicationSettingsService { private readonly ILogger logger; + private readonly ISettingsStorage settingsStorage; private readonly string settingsFilePath; + private readonly string? legacySettingsPath; private ApplicationSettingsModel settings; private static readonly JsonSerializerOptions JsonOptions = new() { @@ -46,11 +49,24 @@ namespace ThreadPilot.Services public ApplicationSettingsModel Settings => (ApplicationSettingsModel)this.settings.Clone(); public ApplicationSettingsService(ILogger logger) + : this( + logger, + CreateDefaultStorage(), + StoragePaths.SettingsFilePath, + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.json")) + { + } + + public ApplicationSettingsService( + ILogger logger, + ISettingsStorage settingsStorage, + string settingsFilePath, + string? legacySettingsPath) { this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); - - StoragePaths.EnsureAppDataDirectories(); - this.settingsFilePath = StoragePaths.SettingsFilePath; + this.settingsStorage = settingsStorage ?? throw new ArgumentNullException(nameof(settingsStorage)); + this.settingsFilePath = settingsFilePath ?? throw new ArgumentNullException(nameof(settingsFilePath)); + this.legacySettingsPath = legacySettingsPath; this.MigrateLegacySettingsIfNeeded(); @@ -63,7 +79,7 @@ namespace ThreadPilot.Services { this.logger.LogInformation("Loading application settings from {FilePath}", this.settingsFilePath); - if (!File.Exists(this.settingsFilePath)) + if (!this.settingsStorage.Exists(this.settingsFilePath)) { this.logger.LogInformation("Settings file not found, using defaults"); this.settings = new ApplicationSettingsModel(); @@ -71,7 +87,15 @@ namespace ThreadPilot.Services return; } - var json = await File.ReadAllTextAsync(this.settingsFilePath); + var json = await this.settingsStorage.ReadAsync(this.settingsFilePath); + if (string.IsNullOrWhiteSpace(json)) + { + this.logger.LogWarning("Settings file was empty, using defaults"); + this.settings = new ApplicationSettingsModel(); + await this.SaveSettingsAsync(); + return; + } + var legacyThemePreferenceDetected = false; try @@ -127,7 +151,7 @@ namespace ThreadPilot.Services this.ValidateAndFixSettings(); var json = JsonSerializer.Serialize(this.settings, JsonOptions); - await AtomicFileWriter.WriteAllTextAsync(this.settingsFilePath, json, Encoding.UTF8); + await this.settingsStorage.WriteAsync(this.settingsFilePath, json); this.logger.LogDebug("Settings saved successfully"); } @@ -240,7 +264,7 @@ namespace ThreadPilot.Services this.logger.LogInformation("Exporting settings to {FilePath}", filePath); var json = JsonSerializer.Serialize(this.settings, JsonOptions); - await AtomicFileWriter.WriteAllTextAsync(filePath, json, Encoding.UTF8); + await this.settingsStorage.WriteAsync(filePath, json); this.logger.LogInformation("Settings exported successfully"); } @@ -257,12 +281,17 @@ namespace ThreadPilot.Services { this.logger.LogInformation("Importing settings from {FilePath}", filePath); - if (!File.Exists(filePath)) + if (!this.settingsStorage.Exists(filePath)) { throw new FileNotFoundException($"Settings file not found: {filePath}"); } - var json = await File.ReadAllTextAsync(filePath); + var json = await this.settingsStorage.ReadAsync(filePath); + if (string.IsNullOrWhiteSpace(json)) + { + throw new InvalidOperationException("Imported settings file was empty"); + } + var importedSettings = JsonSerializer.Deserialize(json, JsonOptions); if (importedSettings == null) @@ -304,11 +333,12 @@ namespace ThreadPilot.Services { try { - var legacySettingsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.json"); - if (File.Exists(legacySettingsPath) && !File.Exists(this.settingsFilePath)) + if (!string.IsNullOrWhiteSpace(this.legacySettingsPath) && + this.settingsStorage.Exists(this.legacySettingsPath) && + !this.settingsStorage.Exists(this.settingsFilePath)) { - Directory.CreateDirectory(Path.GetDirectoryName(this.settingsFilePath)!); - File.Copy(legacySettingsPath, this.settingsFilePath); + this.settingsStorage.EnsureDirectoryForFile(this.settingsFilePath); + this.settingsStorage.Copy(this.legacySettingsPath, this.settingsFilePath, overwrite: false); this.logger.LogInformation("Migrated legacy settings file to AppData storage"); } } @@ -317,6 +347,12 @@ namespace ThreadPilot.Services this.logger.LogWarning(ex, "Failed to migrate legacy settings file"); } } + + private static ISettingsStorage CreateDefaultStorage() + { + StoragePaths.EnsureAppDataDirectories(); + return new FileSettingsStorage(); + } } } diff --git a/Services/AutostartService.cs b/Services/AutostartService.cs index c14a92d..e591b68 100644 --- a/Services/AutostartService.cs +++ b/Services/AutostartService.cs @@ -17,8 +17,6 @@ namespace ThreadPilot.Services { using System; - using System.Collections.Generic; - using System.Diagnostics; using System.IO; using System.Threading.Tasks; using Microsoft.Extensions.Logging; @@ -31,9 +29,6 @@ namespace ThreadPilot.Services { private const string REGISTRYKEYPATH = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; private const string APPLICATIONNAME = "ThreadPilot"; - private const string SCHEDULEDTASKNAME = "ThreadPilot_Startup"; - private static readonly string SchTasksExecutablePath = Path.Combine(Environment.SystemDirectory, "schtasks.exe"); - private static readonly TimeSpan ScheduledTaskTimeout = TimeSpan.FromSeconds(20); private readonly ILogger logger; private readonly IElevationService elevationService; @@ -281,94 +276,18 @@ namespace ThreadPilot.Services } } - /// - /// Creates a scheduled task for elevated startup as a backup to registry autostart. - /// - private async Task CreateElevatedStartupTask(string executablePath, string arguments) - { - try - { - if (!IsValidExecutablePath(executablePath)) - { - LogSkipElevatedTaskInvalidPath(this.logger, executablePath); - return; - } - - var taskRunCommand = BuildAutostartCommand(executablePath, arguments); - var result = await RunSchTasksAsync(new List - { - "/Create", - "/TN", SCHEDULEDTASKNAME, - "/TR", taskRunCommand, - "/SC", "ONLOGON", - "/RL", "HIGHEST", - "/F", - "/RU", Environment.UserName, - }); - - if (result.ExitCode == 0) - { - LogElevatedStartupTaskCreated(this.logger); - } - else - { - LogCreateElevatedStartupTaskFailed(this.logger, result.ExitCode, result.StandardError); - } - } - catch (Exception ex) - { - LogCreateElevatedStartupTaskException(this.logger, ex); - } - } - - /// - /// Removes the elevated startup scheduled task. - /// - private async Task RemoveElevatedStartupTask() - { - try - { - var result = await RunSchTasksAsync(new List - { - "/Delete", - "/TN", SCHEDULEDTASKNAME, - "/F", - }); - - if (result.ExitCode == 0) - { - LogElevatedStartupTaskRemoved(this.logger); - } - else - { - // Task might not exist, which is fine. - LogScheduledTaskRemovalExitCode(this.logger, result.ExitCode); - } - } - catch (Exception ex) - { - LogRemoveElevatedStartupTaskException(this.logger, ex); - } - } - [LoggerMessage(EventId = 4200, Level = LogLevel.Debug, Message = "Autostart status initialization failed")] private static partial void LogAutostartInitializationFailed(ILogger logger, Exception ex); [LoggerMessage(EventId = 4201, Level = LogLevel.Error, Message = "Could not determine executable path for autostart")] private static partial void LogAutostartExecutablePathMissing(ILogger logger); - [LoggerMessage(EventId = 4202, Level = LogLevel.Error, Message = "Could not open registry key for autostart")] - private static partial void LogAutostartRegistryKeyMissing(ILogger logger); - [LoggerMessage(EventId = 4203, Level = LogLevel.Information, Message = "Autostart enabled: {Command}")] private static partial void LogAutostartEnabled(ILogger logger, string command); [LoggerMessage(EventId = 4204, Level = LogLevel.Error, Message = "Failed to enable autostart")] private static partial void LogEnableAutostartFailed(ILogger logger, Exception ex); - [LoggerMessage(EventId = 4205, Level = LogLevel.Warning, Message = "Could not open registry key for autostart removal")] - private static partial void LogAutostartRegistryRemovalKeyMissing(ILogger logger); - [LoggerMessage(EventId = 4206, Level = LogLevel.Information, Message = "Autostart disabled")] private static partial void LogAutostartDisabled(ILogger logger); @@ -384,27 +303,6 @@ namespace ThreadPilot.Services [LoggerMessage(EventId = 4210, Level = LogLevel.Error, Message = "Failed to get executable path")] private static partial void LogGetExecutablePathFailed(ILogger logger, Exception ex); - [LoggerMessage(EventId = 4211, Level = LogLevel.Warning, Message = "Skipping elevated startup task creation due to invalid executable path: {Path}")] - private static partial void LogSkipElevatedTaskInvalidPath(ILogger logger, string path); - - [LoggerMessage(EventId = 4212, Level = LogLevel.Information, Message = "Created elevated startup task successfully")] - private static partial void LogElevatedStartupTaskCreated(ILogger logger); - - [LoggerMessage(EventId = 4213, Level = LogLevel.Warning, Message = "Failed to create elevated startup task. Exit code: {ExitCode}, Error: {Error}")] - private static partial void LogCreateElevatedStartupTaskFailed(ILogger logger, int exitCode, string error); - - [LoggerMessage(EventId = 4214, Level = LogLevel.Warning, Message = "Failed to create elevated startup task")] - private static partial void LogCreateElevatedStartupTaskException(ILogger logger, Exception ex); - - [LoggerMessage(EventId = 4215, Level = LogLevel.Information, Message = "Removed elevated startup task successfully")] - private static partial void LogElevatedStartupTaskRemoved(ILogger logger); - - [LoggerMessage(EventId = 4216, Level = LogLevel.Debug, Message = "Scheduled task removal completed with exit code: {ExitCode}")] - private static partial void LogScheduledTaskRemovalExitCode(ILogger logger, int exitCode); - - [LoggerMessage(EventId = 4217, Level = LogLevel.Warning, Message = "Failed to remove elevated startup task")] - private static partial void LogRemoveElevatedStartupTaskException(ILogger logger, Exception ex); - [LoggerMessage(EventId = 4218, Level = LogLevel.Information, Message = "Autostart configuration requires elevation; requesting elevated restart")] private static partial void LogAutostartRequiresElevation(ILogger logger); @@ -431,90 +329,6 @@ namespace ThreadPilot.Services [LoggerMessage(EventId = 4226, Level = LogLevel.Debug, Message = "Failed to remove legacy HKCU Run autostart value")] private static partial void LogLegacyRegistryCleanupFailed(ILogger logger, Exception ex); - - private static bool IsValidExecutablePath(string executablePath) - { - if (string.IsNullOrWhiteSpace(executablePath) || !Path.IsPathRooted(executablePath)) - { - return false; - } - - return File.Exists(executablePath) && - string.Equals(Path.GetExtension(executablePath), ".exe", StringComparison.OrdinalIgnoreCase); - } - - private static string BuildAutostartCommand(string executablePath, string arguments) - { - var trimmedArguments = arguments?.Trim(); - return string.IsNullOrWhiteSpace(trimmedArguments) - ? $"\"{executablePath}\"" - : $"\"{executablePath}\" {trimmedArguments}"; - } - - private static async Task RunSchTasksAsync(IReadOnlyList arguments) - { - if (!File.Exists(SchTasksExecutablePath)) - { - return new ProcessResult(-1, string.Empty, "schtasks.exe not found in system directory"); - } - - var processInfo = new ProcessStartInfo - { - FileName = SchTasksExecutablePath, - UseShellExecute = false, - CreateNoWindow = true, - RedirectStandardOutput = true, - RedirectStandardError = true, - }; - - foreach (var argument in arguments) - { - processInfo.ArgumentList.Add(argument); - } - - using var process = Process.Start(processInfo); - if (process == null) - { - return new ProcessResult(-1, string.Empty, "Could not start schtasks.exe"); - } - - var outputTask = process.StandardOutput.ReadToEndAsync(); - var errorTask = process.StandardError.ReadToEndAsync(); - var exitTask = process.WaitForExitAsync(); - var completedTask = await Task.WhenAny(exitTask, Task.Delay(ScheduledTaskTimeout)); - if (completedTask != exitTask) - { - try - { - process.Kill(entireProcessTree: true); - } - catch - { - // Best-effort kill for timeout. - } - - return new ProcessResult(-1, await outputTask, $"schtasks timeout after {ScheduledTaskTimeout.TotalSeconds} seconds"); - } - - await exitTask; - return new ProcessResult(process.ExitCode, await outputTask, await errorTask); - } - - private readonly struct ProcessResult - { - public ProcessResult(int exitCode, string standardOutput, string standardError) - { - this.ExitCode = exitCode; - this.StandardOutput = standardOutput; - this.StandardError = standardError; - } - - public int ExitCode { get; } - - public string StandardOutput { get; } - - public string StandardError { get; } - } } } diff --git a/Services/ElevatedTaskService.cs b/Services/ElevatedTaskService.cs index e1233a2..5d9508b 100644 --- a/Services/ElevatedTaskService.cs +++ b/Services/ElevatedTaskService.cs @@ -26,6 +26,7 @@ namespace ThreadPilot.Services using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; + using ThreadPilot.Services.Abstractions; /// /// Manages Scheduled Tasks used for persistent elevated launch and elevated autostart. @@ -36,10 +37,25 @@ namespace ThreadPilot.Services private static readonly TimeSpan ScheduledTaskTimeout = TimeSpan.FromSeconds(20); private readonly ILogger logger; + private readonly IProcessRunner processRunner; + private readonly Func? executablePathProvider; + private readonly Func? currentUserProvider; - public ElevatedTaskService(ILogger logger) + public ElevatedTaskService(ILogger logger, IProcessRunner processRunner) + : this(logger, processRunner, null, null) + { + } + + public ElevatedTaskService( + ILogger logger, + IProcessRunner processRunner, + Func? executablePathProvider, + Func? currentUserProvider) { this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); + this.processRunner = processRunner ?? throw new ArgumentNullException(nameof(processRunner)); + this.executablePathProvider = executablePathProvider; + this.currentUserProvider = currentUserProvider; } public string LaunchTaskName => "ThreadPilot_Launch"; @@ -50,7 +66,7 @@ namespace ThreadPilot.Services { try { - var executablePath = this.GetExecutablePath(); + var executablePath = this.executablePathProvider?.Invoke() ?? this.GetExecutablePath(); if (!IsValidExecutablePath(executablePath)) { LogSkipEnsureLaunchTaskInvalidPath(this.logger, executablePath ?? "(null)"); @@ -60,9 +76,12 @@ namespace ThreadPilot.Services var taskXmlPath = Path.Combine(Path.GetTempPath(), $"threadpilot-launch-task-{Guid.NewGuid():N}.xml"); try { - WriteLaunchTaskDefinition(taskXmlPath, executablePath); + WriteLaunchTaskDefinition( + taskXmlPath, + executablePath!, + this.currentUserProvider?.Invoke() ?? GetCurrentUserName()); - var result = await RunSchTasksAsync(new List + var result = await this.RunSchTasksAsync(new List { "/Create", "/TN", this.LaunchTaskName, @@ -72,7 +91,7 @@ namespace ThreadPilot.Services if (result.ExitCode == 0) { - LogLaunchTaskEnsured(this.logger, this.LaunchTaskName, executablePath); + LogLaunchTaskEnsured(this.logger, this.LaunchTaskName, executablePath!); return true; } @@ -95,7 +114,7 @@ namespace ThreadPilot.Services { try { - var result = await RunSchTasksAsync(new List + var result = await this.RunSchTasksAsync(new List { "/Run", "/TN", this.LaunchTaskName, @@ -128,7 +147,7 @@ namespace ThreadPilot.Services } var taskRunCommand = BuildCommand(executablePath, arguments); - var result = await RunSchTasksAsync(new List + var result = await this.RunSchTasksAsync(new List { "/Create", "/TN", this.AutostartTaskName, @@ -159,7 +178,7 @@ namespace ThreadPilot.Services { try { - var result = await RunSchTasksAsync(new List + var result = await this.RunSchTasksAsync(new List { "/Delete", "/TN", this.AutostartTaskName, @@ -193,7 +212,7 @@ namespace ThreadPilot.Services { try { - var result = await RunSchTasksAsync(new List + var result = await this.RunSchTasksAsync(new List { "/Query", "/TN", this.AutostartTaskName, @@ -261,7 +280,7 @@ namespace ThreadPilot.Services string.Equals(Path.GetExtension(executablePath), ".exe", StringComparison.OrdinalIgnoreCase); } - private static void WriteLaunchTaskDefinition(string taskXmlPath, string executablePath) + private static string GetCurrentUserName() { var userName = WindowsIdentity.GetCurrent().Name; if (string.IsNullOrWhiteSpace(userName)) @@ -269,6 +288,16 @@ namespace ThreadPilot.Services throw new InvalidOperationException("Could not determine current user identity for launch task registration."); } + return userName; + } + + private static void WriteLaunchTaskDefinition(string taskXmlPath, string executablePath, string userName) + { + if (string.IsNullOrWhiteSpace(userName)) + { + throw new InvalidOperationException("Could not determine current user identity for launch task registration."); + } + var workingDirectory = Path.GetDirectoryName(executablePath); if (string.IsNullOrWhiteSpace(workingDirectory)) { @@ -324,54 +353,9 @@ namespace ThreadPilot.Services File.WriteAllText(taskXmlPath, taskXml, Encoding.Unicode); } - private static async Task RunSchTasksAsync(IReadOnlyList arguments) + private Task RunSchTasksAsync(IReadOnlyList arguments) { - if (!File.Exists(SchTasksExecutablePath)) - { - return new ProcessResult(-1, string.Empty, "schtasks.exe not found in system directory"); - } - - var processInfo = new ProcessStartInfo - { - FileName = SchTasksExecutablePath, - UseShellExecute = false, - CreateNoWindow = true, - RedirectStandardOutput = true, - RedirectStandardError = true, - }; - - foreach (var argument in arguments) - { - processInfo.ArgumentList.Add(argument); - } - - using var process = Process.Start(processInfo); - if (process == null) - { - return new ProcessResult(-1, string.Empty, "Could not start schtasks.exe"); - } - - var outputTask = process.StandardOutput.ReadToEndAsync(); - var errorTask = process.StandardError.ReadToEndAsync(); - var exitTask = process.WaitForExitAsync(); - var completedTask = await Task.WhenAny(exitTask, Task.Delay(ScheduledTaskTimeout)); - - if (completedTask != exitTask) - { - try - { - process.Kill(entireProcessTree: true); - } - catch - { - // Best-effort kill for timeout. - } - - return new ProcessResult(-1, await outputTask, $"schtasks timeout after {ScheduledTaskTimeout.TotalSeconds} seconds"); - } - - await exitTask; - return new ProcessResult(process.ExitCode, await outputTask, await errorTask); + return this.processRunner.RunAsync(SchTasksExecutablePath, arguments, ScheduledTaskTimeout); } private static void TryDeleteFile(string path, ILogger logger) @@ -445,21 +429,5 @@ namespace ThreadPilot.Services [LoggerMessage(EventId = 4268, Level = LogLevel.Debug, Message = "Failed to delete temporary file '{Path}'")] private static partial void LogDeleteTemporaryFileFailed(ILogger logger, string path, Exception ex); - - private readonly struct ProcessResult - { - public ProcessResult(int exitCode, string standardOutput, string standardError) - { - this.ExitCode = exitCode; - this.StandardOutput = standardOutput; - this.StandardError = standardError; - } - - public int ExitCode { get; } - - public string StandardOutput { get; } - - public string StandardError { get; } - } } } diff --git a/Services/FileSettingsStorage.cs b/Services/FileSettingsStorage.cs new file mode 100644 index 0000000..200c4f0 --- /dev/null +++ b/Services/FileSettingsStorage.cs @@ -0,0 +1,46 @@ +namespace ThreadPilot.Services +{ + using System; + using System.IO; + using System.Text; + using System.Threading.Tasks; + using ThreadPilot.Services.Abstractions; + + /// + /// Default filesystem-backed settings storage. + /// + public sealed class FileSettingsStorage : ISettingsStorage + { + public void Copy(string sourcePath, string destinationPath, bool overwrite) + { + File.Copy(sourcePath, destinationPath, overwrite); + } + + public void EnsureDirectoryForFile(string path) + { + var directory = Path.GetDirectoryName(path); + if (!string.IsNullOrWhiteSpace(directory)) + { + Directory.CreateDirectory(directory); + } + } + + public bool Exists(string path) + { + return File.Exists(path); + } + + public async Task ReadAsync(string path) + { + return this.Exists(path) + ? await File.ReadAllTextAsync(path) + : null; + } + + public Task WriteAsync(string path, string content) + { + this.EnsureDirectoryForFile(path); + return AtomicFileWriter.WriteAllTextAsync(path, content, Encoding.UTF8); + } + } +} diff --git a/Services/GitHubReleaseClient.cs b/Services/GitHubReleaseClient.cs new file mode 100644 index 0000000..ac4a542 --- /dev/null +++ b/Services/GitHubReleaseClient.cs @@ -0,0 +1,27 @@ +namespace ThreadPilot.Services +{ + using System; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using ThreadPilot.Services.Abstractions; + + /// + /// HTTP client wrapper for GitHub release metadata. + /// + public sealed class GitHubReleaseClient : IGitHubReleaseClient + { + private readonly HttpClient httpClient; + + public GitHubReleaseClient(HttpClient httpClient) + { + this.httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + } + + public Task GetLatestReleaseJsonAsync(string owner, string repo, CancellationToken cancellationToken = default) + { + var url = $"https://api.github.com/repos/{owner}/{repo}/releases/latest"; + return this.httpClient.GetStringAsync(url, cancellationToken); + } + } +} diff --git a/Services/GitHubUpdateChecker.cs b/Services/GitHubUpdateChecker.cs index 69540b9..027753c 100644 --- a/Services/GitHubUpdateChecker.cs +++ b/Services/GitHubUpdateChecker.cs @@ -17,16 +17,26 @@ namespace ThreadPilot.Services { using System; - using System.Net.Http; - using System.Net.Http.Headers; using System.Text.Json; + using System.Threading; using System.Threading.Tasks; + using ThreadPilot.Services.Abstractions; - public static class GitHubUpdateChecker + public sealed class GitHubUpdateChecker { + private readonly IGitHubReleaseClient gitHubReleaseClient; + private record LatestRelease(string Tag_name, bool Prerelease, bool Draft, string Html_url); - public static async Task<(Version? latest, string? releaseUrl)> GetLatestVersionAsync(string owner, string repo) + public GitHubUpdateChecker(IGitHubReleaseClient gitHubReleaseClient) + { + this.gitHubReleaseClient = gitHubReleaseClient ?? throw new ArgumentNullException(nameof(gitHubReleaseClient)); + } + + public async Task<(Version? latest, string? releaseUrl)> GetLatestVersionAsync( + string owner, + string repo, + CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(owner)) { @@ -38,13 +48,7 @@ namespace ThreadPilot.Services throw new ArgumentException("Repository is required", nameof(repo)); } - var url = $"https://api.github.com/repos/{owner}/{repo}/releases/latest"; - - using var http = new HttpClient(); - http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("ThreadPilot", "1.0")); - http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); - - var json = await http.GetStringAsync(url); + var json = await this.gitHubReleaseClient.GetLatestReleaseJsonAsync(owner, repo, cancellationToken); var release = JsonSerializer.Deserialize(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true, diff --git a/Services/PowerPlanService.cs b/Services/PowerPlanService.cs index 16c53cf..34fb9bd 100644 --- a/Services/PowerPlanService.cs +++ b/Services/PowerPlanService.cs @@ -19,18 +19,19 @@ namespace ThreadPilot.Services using System; using System.Collections.Generic; using System.Collections.ObjectModel; - using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using ThreadPilot.Models; + using ThreadPilot.Services.Abstractions; public class PowerPlanService : IPowerPlanService { private static readonly Lazy powerPlansPath = new(GetPowerPlansPath); private static readonly string powerCfgExecutablePath = Path.Combine(Environment.SystemDirectory, "powercfg.exe"); + private static readonly TimeSpan powerCfgTimeout = TimeSpan.FromSeconds(20); private static readonly Regex powerSchemeRegex = new(@"Power Scheme GUID: (.*?) \((.*?)\)", RegexOptions.Multiline | RegexOptions.Compiled); private static readonly Regex pathTraversalRegex = new(@"(^|[\\/])\.\.([\\/]|$)", RegexOptions.Compiled); @@ -39,14 +40,32 @@ namespace ThreadPilot.Services private readonly object lockObject = new(); private readonly ILogger logger; private readonly IEnhancedLoggingService enhancedLogger; + private readonly IProcessRunner processRunner; + private readonly Func powerPlansPathProvider; private string? lastActivePowerPlanGuid; public event EventHandler? PowerPlanChanged; public PowerPlanService(ILogger logger, IEnhancedLoggingService enhancedLogger) + : this(logger, enhancedLogger, new SystemProcessRunner(), null) + { + } + + public PowerPlanService(ILogger logger, IEnhancedLoggingService enhancedLogger, IProcessRunner processRunner) + : this(logger, enhancedLogger, processRunner, null) + { + } + + public PowerPlanService( + ILogger logger, + IEnhancedLoggingService enhancedLogger, + IProcessRunner processRunner, + Func? powerPlansPathProvider) { this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); this.enhancedLogger = enhancedLogger ?? throw new ArgumentNullException(nameof(enhancedLogger)); + this.processRunner = processRunner ?? throw new ArgumentNullException(nameof(processRunner)); + this.powerPlansPathProvider = powerPlansPathProvider ?? (() => PowerPlansPath); } /// @@ -104,12 +123,8 @@ namespace ThreadPilot.Services var powerPlans = new ObservableCollection(); var activePlan = await this.GetActivePowerPlan().ConfigureAwait(false); - using var process = CreatePowerCfgProcess("/list"); - process.Start(); - string output = await process.StandardOutput.ReadToEndAsync().ConfigureAwait(false); - await process.WaitForExitAsync().ConfigureAwait(false); - - var matches = powerSchemeRegex.Matches(output); + var result = await this.RunPowerCfgAsync("/list").ConfigureAwait(false); + var matches = powerSchemeRegex.Matches(result.StandardOutput); foreach (Match match in matches) { @@ -133,12 +148,13 @@ namespace ThreadPilot.Services public async Task> GetCustomPowerPlansAsync() { var customPlans = new ObservableCollection(); - if (!Directory.Exists(PowerPlansPath)) + var powerPlansPath = this.powerPlansPathProvider(); + if (!Directory.Exists(powerPlansPath)) { return customPlans; } - foreach (var file in Directory.GetFiles(PowerPlansPath, "*.pow")) + foreach (var file in Directory.GetFiles(powerPlansPath, "*.pow")) { customPlans.Add(new PowerPlanModel { @@ -189,12 +205,8 @@ namespace ThreadPilot.Services targetPowerPlan?.Name ?? "Unknown", "Manual power plan change requested").ConfigureAwait(false); - using var process = CreatePowerCfgProcess($"/setactive {powerPlanGuid}"); - process.Start(); - var stdError = await process.StandardError.ReadToEndAsync().ConfigureAwait(false); - await process.WaitForExitAsync().ConfigureAwait(false); - - var success = process.ExitCode == 0; + var result = await this.RunPowerCfgAsync("/setactive", powerPlanGuid).ConfigureAwait(false); + var success = result.ExitCode == 0; if (success) { @@ -220,12 +232,12 @@ namespace ThreadPilot.Services this.logger.LogWarning( "Failed to change power plan to '{PowerPlanGuid}' - powercfg exit code: {ExitCode}, stderr: {StdErr}", powerPlanGuid, - process.ExitCode, - stdError); + result.ExitCode, + result.StandardError); await this.enhancedLogger.LogSystemEventAsync( LogEventTypes.PowerPlan.ChangeFailed, - $"Failed to change power plan to '{targetPowerPlan?.Name ?? powerPlanGuid}' - Exit code: {process.ExitCode}", + $"Failed to change power plan to '{targetPowerPlan?.Name ?? powerPlanGuid}' - Exit code: {result.ExitCode}", Microsoft.Extensions.Logging.LogLevel.Warning).ConfigureAwait(false); } @@ -250,12 +262,8 @@ namespace ThreadPilot.Services { try { - using var process = CreatePowerCfgProcess("/getactivescheme"); - process.Start(); - string output = await process.StandardOutput.ReadToEndAsync().ConfigureAwait(false); - await process.WaitForExitAsync().ConfigureAwait(false); - - var match = powerSchemeRegex.Match(output); + var result = await this.RunPowerCfgAsync("/getactivescheme").ConfigureAwait(false); + var match = powerSchemeRegex.Match(result.StandardOutput); if (match.Success) { @@ -287,18 +295,15 @@ namespace ThreadPilot.Services try { - using var process = CreatePowerCfgProcess($"/import {QuoteArgument(normalizedPath)}"); - process.Start(); - var stdError = await process.StandardError.ReadToEndAsync().ConfigureAwait(false); - await process.WaitForExitAsync().ConfigureAwait(false); + var result = await this.RunPowerCfgAsync("/import", normalizedPath).ConfigureAwait(false); - if (process.ExitCode != 0) + if (result.ExitCode != 0) { this.logger.LogWarning( "Power plan import failed for '{Path}' with exit code {ExitCode}. stderr: {StdErr}", normalizedPath, - process.ExitCode, - stdError); + result.ExitCode, + result.StandardError); return false; } @@ -325,10 +330,11 @@ namespace ThreadPilot.Services try { - Directory.CreateDirectory(PowerPlansPath); + var powerPlansPath = this.powerPlansPathProvider(); + Directory.CreateDirectory(powerPlansPath); var fileName = Path.GetFileName(normalizedPath); - var destinationPath = Path.Combine(PowerPlansPath, fileName); + var destinationPath = Path.Combine(powerPlansPath, fileName); // If user selects a file already in the managed folder, treat as success. if (string.Equals(normalizedPath, destinationPath, StringComparison.OrdinalIgnoreCase)) @@ -344,7 +350,7 @@ namespace ThreadPilot.Services do { - destinationPath = Path.Combine(PowerPlansPath, $"{baseName}_{suffix}{extension}"); + destinationPath = Path.Combine(powerPlansPath, $"{baseName}_{suffix}{extension}"); suffix++; } while (File.Exists(destinationPath)); @@ -427,8 +433,6 @@ namespace ThreadPilot.Services } } - private static string QuoteArgument(string value) => $"\"{value.Replace("\"", "\\\"")}\""; - private bool TryNormalizePowerPlanPath(string filePath, out string normalizedPath, out string error) { normalizedPath = string.Empty; @@ -484,20 +488,7 @@ namespace ThreadPilot.Services return true; } - private static Process CreatePowerCfgProcess(string arguments) - { - return new Process - { - StartInfo = new ProcessStartInfo - { - FileName = powerCfgExecutablePath, - Arguments = arguments, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true - }, - }; - } + private Task RunPowerCfgAsync(params string[] arguments) => + this.processRunner.RunAsync(powerCfgExecutablePath, arguments, powerCfgTimeout); } } diff --git a/Services/ProcessMonitorManagerService.cs b/Services/ProcessMonitorManagerService.cs index 20dd4fe..792609a 100644 --- a/Services/ProcessMonitorManagerService.cs +++ b/Services/ProcessMonitorManagerService.cs @@ -746,14 +746,26 @@ namespace ThreadPilot.Services return; } - this.StopAsync().Wait(5000); // Wait up to 5 seconds for clean shutdown + try + { + // Dispose can be called from the WPF UI thread; stop on the thread pool to avoid + // deadlocking on a captured SynchronizationContext during async shutdown. + Task.Run(this.StopAsync).GetAwaiter().GetResult(); + } + finally + { + this.processMonitorService.ProcessStarted -= this.OnProcessStarted; + this.processMonitorService.ProcessStopped -= this.OnProcessStopped; + this.processMonitorService.MonitoringStatusChanged -= this.OnMonitoringStatusChanged; + this.associationService.ConfigurationChanged -= this.OnConfigurationChanged; - this.delayTimer?.Dispose(); - this.powerPlanChangeSemaphore?.Dispose(); - this.stateMutationSemaphore?.Dispose(); - this.processMonitorService?.Dispose(); + this.delayTimer?.Dispose(); + this.powerPlanChangeSemaphore?.Dispose(); + this.stateMutationSemaphore?.Dispose(); + this.processMonitorService?.Dispose(); - this.disposed = true; + this.disposed = true; + } } } } diff --git a/Services/ProcessService.cs b/Services/ProcessService.cs index 4e15c64..57ec0b7 100644 --- a/Services/ProcessService.cs +++ b/Services/ProcessService.cs @@ -38,8 +38,9 @@ namespace ThreadPilot.Services private readonly ConcurrentDictionary cpuSetHandlers = new(); private readonly ILogger? logger; private readonly ISecurityService? securityService; + private readonly Func profilesDirectoryProvider; - private string ProfilesDirectory => StoragePaths.ProfilesDirectory; + private string ProfilesDirectory => this.profilesDirectoryProvider(); private bool useCpuSets = true; // Enable CPU Sets by default @@ -47,10 +48,14 @@ namespace ThreadPilot.Services private readonly ConcurrentDictionary appliedMasks = new(); // ProcessId -> MaskId private readonly ConcurrentDictionary originalPriorities = new(); // ProcessId -> OriginalPriority - public ProcessService(ILogger? logger = null, ISecurityService? securityService = null) + public ProcessService( + ILogger? logger = null, + ISecurityService? securityService = null, + Func? profilesDirectoryProvider = null) { this.logger = logger; this.securityService = securityService; + this.profilesDirectoryProvider = profilesDirectoryProvider ?? (() => StoragePaths.ProfilesDirectory); StoragePaths.EnsureAppDataDirectories(); this.MigrateLegacyProfilesIfNeeded(); diff --git a/Services/ServiceConfiguration.cs b/Services/ServiceConfiguration.cs index 3b02f44..a93caeb 100644 --- a/Services/ServiceConfiguration.cs +++ b/Services/ServiceConfiguration.cs @@ -16,8 +16,11 @@ */ namespace ThreadPilot.Services { + using System.Net.Http; + using System.Net.Http.Headers; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; + using ThreadPilot.Services.Abstractions; using ThreadPilot.ViewModels; /// @@ -62,6 +65,17 @@ namespace ThreadPilot.Services // Enhanced logging service services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(sp => + { + var httpClient = new HttpClient(); + httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("ThreadPilot", "1.0")); + httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); + return httpClient; + }); + services.AddSingleton(); + services.AddSingleton(); // Memory caching for performance - PERFORMANCE IMPROVEMENT services.AddMemoryCache(); diff --git a/Services/SystemProcessRunner.cs b/Services/SystemProcessRunner.cs new file mode 100644 index 0000000..d666d35 --- /dev/null +++ b/Services/SystemProcessRunner.cs @@ -0,0 +1,69 @@ +/* + * ThreadPilot - default process runner. + */ +namespace ThreadPilot.Services +{ + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Threading.Tasks; + using ThreadPilot.Services.Abstractions; + + /// + /// Production implementation of backed by . + /// + public sealed class SystemProcessRunner : IProcessRunner + { + /// + public async Task RunAsync(string fileName, IReadOnlyList arguments, TimeSpan timeout) + { + if (!File.Exists(fileName)) + { + return new ProcessRunResult(-1, string.Empty, $"Executable not found: {fileName}"); + } + + var processInfo = new ProcessStartInfo + { + FileName = fileName, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + + foreach (var argument in arguments) + { + processInfo.ArgumentList.Add(argument); + } + + using var process = Process.Start(processInfo); + if (process == null) + { + return new ProcessRunResult(-1, string.Empty, $"Could not start process: {fileName}"); + } + + var outputTask = process.StandardOutput.ReadToEndAsync(); + var errorTask = process.StandardError.ReadToEndAsync(); + var exitTask = process.WaitForExitAsync(); + var completedTask = await Task.WhenAny(exitTask, Task.Delay(timeout)).ConfigureAwait(false); + + if (completedTask != exitTask) + { + try + { + process.Kill(entireProcessTree: true); + } + catch + { + // Best-effort kill for timed-out processes. + } + + return new ProcessRunResult(-1, await outputTask.ConfigureAwait(false), $"Process timeout after {timeout.TotalSeconds} seconds"); + } + + await exitTask.ConfigureAwait(false); + return new ProcessRunResult(process.ExitCode, await outputTask.ConfigureAwait(false), await errorTask.ConfigureAwait(false)); + } + } +} diff --git a/Tests/TestRunner.cs b/Tests/TestRunner.cs index c446a6a..12fe769 100644 --- a/Tests/TestRunner.cs +++ b/Tests/TestRunner.cs @@ -20,7 +20,7 @@ namespace ThreadPilot.Tests using System.Threading.Tasks; /// - /// Integrated runtime test runner used by --test mode. + /// Legacy runtime smoke test runner used by debug-only --test mode. /// public static class TestRunner { diff --git a/Tests/ThreadPilot.Core.Tests/ApplicationSettingsServiceTests.cs b/Tests/ThreadPilot.Core.Tests/ApplicationSettingsServiceTests.cs new file mode 100644 index 0000000..94dcf81 --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/ApplicationSettingsServiceTests.cs @@ -0,0 +1,123 @@ +namespace ThreadPilot.Core.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Threading.Tasks; + using Microsoft.Extensions.Logging.Abstractions; + using ThreadPilot.Models; + using ThreadPilot.Services; + using ThreadPilot.Services.Abstractions; + + public sealed class ApplicationSettingsServiceTests + { + [Fact] + public async Task LoadSettingsAsync_CreatesDefaults_WhenFileIsMissing() + { + var storage = new FakeSettingsStorage(); + var service = CreateService(storage); + + await service.LoadSettingsAsync(); + + Assert.True(storage.Writes.ContainsKey(TestPaths.SettingsFilePath)); + Assert.Equal(3000, service.Settings.NotificationDisplayDurationMs); + Assert.Equal(5000, service.Settings.BalloonNotificationTimeoutMs); + } + + [Fact] + public async Task LoadSettingsAsync_FallsBackToDefaults_WhenJsonIsMalformed() + { + var storage = new FakeSettingsStorage(); + storage.Files[TestPaths.SettingsFilePath] = "{ invalid json"; + var service = CreateService(storage); + + await service.LoadSettingsAsync(); + + Assert.Equal(3000, service.Settings.NotificationDisplayDurationMs); + Assert.Equal(string.Empty, service.Settings.CustomTrayIconPath); + } + + [Fact] + public async Task ImportSettingsAsync_Throws_WhenFileIsMissing() + { + var storage = new FakeSettingsStorage(); + var service = CreateService(storage); + + await Assert.ThrowsAsync(() => service.ImportSettingsAsync("missing-settings.json")); + } + + [Fact] + public async Task ValidateAndFixSettings_DisablesMissingCustomTrayIcon() + { + var storage = new FakeSettingsStorage(); + var service = CreateService(storage); + var updatedSettings = new ApplicationSettingsModel + { + UseCustomTrayIcon = true, + CustomTrayIconPath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.ico"), + }; + + await service.UpdateSettingsAsync(updatedSettings); + + Assert.False(service.Settings.UseCustomTrayIcon); + } + + private static ApplicationSettingsService CreateService(FakeSettingsStorage storage) + { + return new ApplicationSettingsService( + NullLogger.Instance, + storage, + TestPaths.SettingsFilePath, + legacySettingsPath: null); + } + + private static class TestPaths + { + public const string SettingsFilePath = "settings-under-test.json"; + } + + private sealed class FakeSettingsStorage : ISettingsStorage + { + public Dictionary Files { get; } = new(StringComparer.OrdinalIgnoreCase); + + public Dictionary Writes { get; } = new(StringComparer.OrdinalIgnoreCase); + + public void Copy(string sourcePath, string destinationPath, bool overwrite) + { + if (!this.Files.TryGetValue(sourcePath, out var content)) + { + throw new FileNotFoundException("Source file not found.", sourcePath); + } + + if (!overwrite && this.Files.ContainsKey(destinationPath)) + { + throw new IOException("Destination already exists."); + } + + this.Files[destinationPath] = content; + } + + public void EnsureDirectoryForFile(string path) + { + } + + public bool Exists(string path) + { + return this.Files.ContainsKey(path); + } + + public Task ReadAsync(string path) + { + this.Files.TryGetValue(path, out var content); + return Task.FromResult(content); + } + + public Task WriteAsync(string path, string content) + { + this.Files[path] = content; + this.Writes[path] = content; + return Task.CompletedTask; + } + } + } +} diff --git a/Tests/ThreadPilot.Core.Tests/AutostartServiceTests.cs b/Tests/ThreadPilot.Core.Tests/AutostartServiceTests.cs index 499e9bf..b67f814 100644 --- a/Tests/ThreadPilot.Core.Tests/AutostartServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/AutostartServiceTests.cs @@ -40,11 +40,80 @@ namespace ThreadPilot.Core.Tests Assert.Equal("--autostart", args); } - private static AutostartService CreateService() + [Fact] + public async Task EnableAutostartAsync_WhenNotAdmin_RequestsElevation_AndReturnsFalse() { - var elevationService = new Mock(MockBehavior.Loose); + var elevationService = new Mock(MockBehavior.Strict); + elevationService.Setup(x => x.IsRunningAsAdministrator()).Returns(false); + elevationService.Setup(x => x.RequestElevationIfNeeded()).ReturnsAsync(true); + var elevatedTaskService = new Mock(MockBehavior.Loose); - return new AutostartService(NullLogger.Instance, elevationService.Object, elevatedTaskService.Object); + elevatedTaskService.Setup(x => x.IsAutostartTaskRegisteredAsync()).ReturnsAsync(false); + + var service = CreateService(elevationService, elevatedTaskService); + + var result = await service.EnableAutostartAsync(startMinimized: true); + + Assert.False(result); + elevationService.Verify(x => x.RequestElevationIfNeeded(), Times.Once); + elevatedTaskService.Verify( + x => x.EnsureAutostartTaskAsync(It.IsAny(), It.IsAny()), + Times.Never); + } + + [Fact] + public async Task EnableAutostartAsync_WhenAdmin_EnsuresScheduledTask() + { + var elevationService = new Mock(MockBehavior.Strict); + elevationService.Setup(x => x.IsRunningAsAdministrator()).Returns(true); + + var elevatedTaskService = new Mock(MockBehavior.Strict); + elevatedTaskService.Setup(x => x.IsAutostartTaskRegisteredAsync()).ReturnsAsync(false); + elevatedTaskService + .Setup(x => x.EnsureAutostartTaskAsync(It.IsAny(), It.Is(args => args.Contains("--autostart", StringComparison.Ordinal)))) + .ReturnsAsync(true); + + var service = CreateService(elevationService, elevatedTaskService); + + var result = await service.EnableAutostartAsync(startMinimized: true); + + Assert.True(result); + elevatedTaskService.Verify( + x => x.EnsureAutostartTaskAsync( + It.IsAny(), + It.Is(args => + args.Contains("--autostart", StringComparison.Ordinal) && + args.Contains("--start-minimized", StringComparison.Ordinal))), + Times.Once); + } + + [Fact] + public async Task DisableAutostartAsync_WhenAdmin_RemovesScheduledTask() + { + var elevationService = new Mock(MockBehavior.Strict); + elevationService.Setup(x => x.IsRunningAsAdministrator()).Returns(true); + + var elevatedTaskService = new Mock(MockBehavior.Strict); + elevatedTaskService.Setup(x => x.IsAutostartTaskRegisteredAsync()).ReturnsAsync(false); + elevatedTaskService.Setup(x => x.RemoveAutostartTaskAsync()).ReturnsAsync(true); + + var service = CreateService(elevationService, elevatedTaskService); + + var result = await service.DisableAutostartAsync(); + + Assert.True(result); + elevatedTaskService.Verify(x => x.RemoveAutostartTaskAsync(), Times.Once); + } + + private static AutostartService CreateService( + Mock? elevationService = null, + Mock? elevatedTaskService = null) + { + var elevation = elevationService ?? new Mock(MockBehavior.Loose); + var elevatedTask = elevatedTaskService ?? new Mock(MockBehavior.Loose); + elevatedTask.Setup(x => x.IsAutostartTaskRegisteredAsync()).ReturnsAsync(false); + + return new AutostartService(NullLogger.Instance, elevation.Object, elevatedTask.Object); } } } diff --git a/Tests/ThreadPilot.Core.Tests/ElevatedTaskServiceTests.cs b/Tests/ThreadPilot.Core.Tests/ElevatedTaskServiceTests.cs new file mode 100644 index 0000000..061362f --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/ElevatedTaskServiceTests.cs @@ -0,0 +1,130 @@ +/* + * ThreadPilot - scheduled task service unit tests. + */ +namespace ThreadPilot.Core.Tests +{ + using System.Text; + using Microsoft.Extensions.Logging.Abstractions; + using ThreadPilot.Services; + using ThreadPilot.Services.Abstractions; + + /// + /// Unit tests for scheduled task orchestration in . + /// + public sealed class ElevatedTaskServiceTests + { + [Fact] + public async Task EnsureAutostartTaskAsync_ReturnsFalse_WhenExecutablePathIsInvalid() + { + var runner = new RecordingProcessRunner(); + var service = CreateService(runner); + + var result = await service.EnsureAutostartTaskAsync(@"C:\temp\ThreadPilot.txt", "--autostart"); + + Assert.False(result); + Assert.Empty(runner.Invocations); + } + + [Fact] + public async Task TryRunLaunchTaskAsync_ReturnsFalse_WhenSchTasksTimesOut() + { + var runner = new RecordingProcessRunner + { + ResultFactory = _ => new ProcessRunResult(-1, string.Empty, "schtasks timeout after 20 seconds"), + }; + var service = CreateService(runner); + + var result = await service.TryRunLaunchTaskAsync(); + + Assert.False(result); + + var invocation = Assert.Single(runner.Invocations); + Assert.Equal(Path.Combine(Environment.SystemDirectory, "schtasks.exe"), invocation.FileName); + Assert.Equal(TimeSpan.FromSeconds(20), invocation.Timeout); + Assert.Equal(new[] { "/Run", "/TN", service.LaunchTaskName }, invocation.Arguments); + } + + [Fact] + public async Task EnsureLaunchTaskAsync_WritesExpectedLaunchTaskDefinition() + { + var executablePath = CreateTemporaryExecutablePath(); + string? xmlPath = null; + string? xmlContent = null; + var runner = new RecordingProcessRunner + { + ResultFactory = invocation => + { + var xmlIndex = invocation.Arguments.IndexOf("/XML"); + Assert.True(xmlIndex >= 0); + xmlPath = invocation.Arguments[xmlIndex + 1]; + xmlContent = File.ReadAllText(xmlPath, Encoding.Unicode); + return new ProcessRunResult(0, string.Empty, string.Empty); + }, + }; + + try + { + var service = CreateService( + runner, + executablePathProvider: () => executablePath, + currentUserProvider: () => @"TEST\User"); + + var result = await service.EnsureLaunchTaskAsync(); + + Assert.True(result); + Assert.NotNull(xmlPath); + Assert.NotNull(xmlContent); + Assert.Contains("TEST\\User", xmlContent, StringComparison.Ordinal); + Assert.Contains($"{executablePath}", xmlContent, StringComparison.Ordinal); + Assert.Contains("--launched-via-task", xmlContent, StringComparison.Ordinal); + Assert.Contains( + $"{Path.GetDirectoryName(executablePath)}", + xmlContent, + StringComparison.Ordinal); + Assert.False(File.Exists(xmlPath)); + } + finally + { + if (File.Exists(executablePath)) + { + File.Delete(executablePath); + } + } + } + + private static ElevatedTaskService CreateService( + IProcessRunner runner, + Func? executablePathProvider = null, + Func? currentUserProvider = null) + { + return new ElevatedTaskService( + NullLogger.Instance, + runner, + executablePathProvider, + currentUserProvider); + } + + private static string CreateTemporaryExecutablePath() + { + var executablePath = Path.Combine(Path.GetTempPath(), $"threadpilot-test-{Guid.NewGuid():N}.exe"); + File.WriteAllText(executablePath, "stub"); + return executablePath; + } + + private sealed class RecordingProcessRunner : IProcessRunner + { + public List Invocations { get; } = new(); + + public Func? ResultFactory { get; init; } + + public Task RunAsync(string fileName, IReadOnlyList arguments, TimeSpan timeout) + { + var invocation = new ProcessInvocation(fileName, arguments.ToList(), timeout); + this.Invocations.Add(invocation); + return Task.FromResult(this.ResultFactory?.Invoke(invocation) ?? new ProcessRunResult(0, string.Empty, string.Empty)); + } + } + + private sealed record ProcessInvocation(string FileName, List Arguments, TimeSpan Timeout); + } +} diff --git a/Tests/ThreadPilot.Core.Tests/GitHubUpdateCheckerTests.cs b/Tests/ThreadPilot.Core.Tests/GitHubUpdateCheckerTests.cs new file mode 100644 index 0000000..4af15aa --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/GitHubUpdateCheckerTests.cs @@ -0,0 +1,85 @@ +namespace ThreadPilot.Core.Tests +{ + using System.Threading; + using System.Threading.Tasks; + using ThreadPilot.Services; + using ThreadPilot.Services.Abstractions; + + public sealed class GitHubUpdateCheckerTests + { + [Fact] + public async Task GetLatestVersionAsync_ReturnsStableRelease_WhenTagIsSemver() + { + var client = new FakeGitHubReleaseClient( + """ + { + "tag_name": "v1.2.3", + "prerelease": false, + "draft": false, + "html_url": "https://example.test/releases/v1.2.3" + } + """); + var checker = new GitHubUpdateChecker(client); + + var (latest, releaseUrl) = await checker.GetLatestVersionAsync("PrimeBuild-pc", "ThreadPilot"); + + Assert.Equal(new System.Version(1, 2, 3), latest); + Assert.Equal("https://example.test/releases/v1.2.3", releaseUrl); + } + + [Fact] + public async Task GetLatestVersionAsync_IgnoresDraftOrPrerelease() + { + var client = new FakeGitHubReleaseClient( + """ + { + "tag_name": "v1.2.3-beta1", + "prerelease": true, + "draft": false, + "html_url": "https://example.test/releases/v1.2.3-beta1" + } + """); + var checker = new GitHubUpdateChecker(client); + + var (latest, releaseUrl) = await checker.GetLatestVersionAsync("PrimeBuild-pc", "ThreadPilot"); + + Assert.Null(latest); + Assert.Null(releaseUrl); + } + + [Fact] + public async Task GetLatestVersionAsync_ReturnsNull_WhenTagCannotBeParsed() + { + var client = new FakeGitHubReleaseClient( + """ + { + "tag_name": "release-main", + "prerelease": false, + "draft": false, + "html_url": "https://example.test/releases/release-main" + } + """); + var checker = new GitHubUpdateChecker(client); + + var (latest, releaseUrl) = await checker.GetLatestVersionAsync("PrimeBuild-pc", "ThreadPilot"); + + Assert.Null(latest); + Assert.Equal("https://example.test/releases/release-main", releaseUrl); + } + + private sealed class FakeGitHubReleaseClient : IGitHubReleaseClient + { + private readonly string responseJson; + + public FakeGitHubReleaseClient(string responseJson) + { + this.responseJson = responseJson; + } + + public Task GetLatestReleaseJsonAsync(string owner, string repo, CancellationToken cancellationToken = default) + { + return Task.FromResult(this.responseJson); + } + } + } +} diff --git a/Tests/ThreadPilot.Core.Tests/PowerPlanServiceTests.cs b/Tests/ThreadPilot.Core.Tests/PowerPlanServiceTests.cs new file mode 100644 index 0000000..fa2c4ae --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/PowerPlanServiceTests.cs @@ -0,0 +1,123 @@ +/* + * ThreadPilot - power plan service unit tests. + */ +namespace ThreadPilot.Core.Tests +{ + using Microsoft.Extensions.Logging.Abstractions; + using Moq; + using ThreadPilot.Services; + using ThreadPilot.Services.Abstractions; + + /// + /// Unit tests for deterministic behavior in . + /// + public sealed class PowerPlanServiceTests + { + [Fact] + public async Task GetActivePowerPlan_ParsesPowerCfgOutput() + { + const string guid = "381b4222-f694-41f0-9685-ff5bb260df2e"; + var runner = new RecordingProcessRunner + { + ResultFactory = _ => new ProcessRunResult( + 0, + $"Power Scheme GUID: {guid} (Balanced)", + string.Empty), + }; + var service = CreateService(runner); + + var result = await service.GetActivePowerPlan(); + + Assert.NotNull(result); + Assert.Equal(guid, result.Guid); + Assert.Equal("Balanced", result.Name); + Assert.True(result.IsActive); + } + + [Fact] + public async Task SetActivePowerPlanByGuidAsync_SkipsChange_WhenAlreadyActive() + { + const string guid = "381b4222-f694-41f0-9685-ff5bb260df2e"; + var runner = new RecordingProcessRunner + { + ResultFactory = _ => new ProcessRunResult( + 0, + $"Power Scheme GUID: {guid} (Balanced)", + string.Empty), + }; + var service = CreateService(runner); + + var result = await service.SetActivePowerPlanByGuidAsync(guid, preventDuplicateChanges: true); + + Assert.True(result); + + var invocation = Assert.Single(runner.Invocations); + Assert.Equal(Path.Combine(Environment.SystemDirectory, "powercfg.exe"), invocation.FileName); + Assert.Equal(new[] { "/getactivescheme" }, invocation.Arguments); + } + + [Fact] + public async Task AddCustomPowerPlanFileAsync_RenamesOnCollision() + { + var tempRoot = Path.Combine(Path.GetTempPath(), $"threadpilot-powerplans-{Guid.NewGuid():N}"); + var managedDirectory = Path.Combine(tempRoot, "managed"); + var sourceDirectory = Path.Combine(tempRoot, "source"); + Directory.CreateDirectory(managedDirectory); + Directory.CreateDirectory(sourceDirectory); + + var sourcePath = Path.Combine(sourceDirectory, "gaming.pow"); + var existingPath = Path.Combine(managedDirectory, "gaming.pow"); + await File.WriteAllTextAsync(sourcePath, "source"); + await File.WriteAllTextAsync(existingPath, "existing"); + + try + { + var service = CreateService( + new RecordingProcessRunner(), + powerPlansPathProvider: () => managedDirectory); + + var result = await service.AddCustomPowerPlanFileAsync(sourcePath); + + Assert.True(result); + var renamedPath = Path.Combine(managedDirectory, "gaming_1.pow"); + Assert.True(File.Exists(renamedPath)); + Assert.Equal("source", await File.ReadAllTextAsync(renamedPath)); + } + finally + { + if (Directory.Exists(tempRoot)) + { + Directory.Delete(tempRoot, recursive: true); + } + } + } + + private static PowerPlanService CreateService( + IProcessRunner runner, + Func? powerPlansPathProvider = null) + { + var enhancedLogger = new Mock(MockBehavior.Loose); + return new PowerPlanService( + NullLogger.Instance, + enhancedLogger.Object, + runner, + powerPlansPathProvider); + } + + private sealed class RecordingProcessRunner : IProcessRunner + { + public List Invocations { get; } = new(); + + public Func? ResultFactory { get; init; } + + public Task RunAsync(string fileName, IReadOnlyList arguments, TimeSpan timeout) + { + var invocation = new ProcessInvocation(fileName, arguments.ToList(), timeout); + this.Invocations.Add(invocation); + return Task.FromResult(this.ResultFactory?.Invoke(invocation) ?? new ProcessRunResult(0, string.Empty, string.Empty)); + } + } + + private sealed record ProcessInvocation(string FileName, List Arguments, TimeSpan Timeout); + } +} diff --git a/Tests/ThreadPilot.Core.Tests/ProcessMonitorManagerServiceTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessMonitorManagerServiceTests.cs new file mode 100644 index 0000000..27e5c28 --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/ProcessMonitorManagerServiceTests.cs @@ -0,0 +1,371 @@ +/* + * ThreadPilot - process monitor manager unit tests. + */ +namespace ThreadPilot.Core.Tests +{ + using System.Collections.ObjectModel; + using System.Threading; + using Microsoft.Extensions.Logging.Abstractions; + using Moq; + using ThreadPilot.Models; + using ThreadPilot.Services; + + /// + /// Unit tests for orchestration logic in . + /// + public sealed class ProcessMonitorManagerServiceTests + { + [Fact] + public async Task StartAsync_LoadsConfiguration_AndStartsMonitoring() + { + var processMonitor = new FakeProcessMonitorService(); + var configuration = new ProcessMonitorConfiguration(); + var associationService = CreateAssociationService(configuration); + var powerPlanService = CreatePowerPlanService(); + var notificationService = CreateNotificationService(); + var processService = CreateProcessService(); + var coreMaskService = CreateCoreMaskService(); + var manager = CreateService( + processMonitor, + associationService, + powerPlanService, + notificationService, + processService, + coreMaskService); + + await manager.StartAsync(); + + Assert.True(manager.IsRunning); + Assert.Equal("Running", manager.Status); + Assert.Equal(1, processMonitor.StartCalls); + associationService.Verify(x => x.LoadConfigurationAsync(), Times.Once); + } + + [Fact] + public async Task StartAsync_SelectsHighestPriorityAssociation() + { + var processMonitor = new FakeProcessMonitorService + { + RunningProcesses = + { + new ProcessModel { ProcessId = 1, Name = "game-low" }, + new ProcessModel { ProcessId = 2, Name = "game-high" }, + }, + }; + + var configuration = new ProcessMonitorConfiguration + { + Associations = + { + new ProcessPowerPlanAssociation("game-low", "plan-low", "Low") { Priority = 1 }, + new ProcessPowerPlanAssociation("game-high", "plan-high", "High") { Priority = 10 }, + }, + PowerPlanChangeDelayMs = 0, + }; + + var associationService = CreateAssociationService(configuration); + var powerPlanService = CreatePowerPlanService(); + var notificationService = CreateNotificationService(); + var processService = CreateProcessService(); + var coreMaskService = CreateCoreMaskService(); + var manager = CreateService( + processMonitor, + associationService, + powerPlanService, + notificationService, + processService, + coreMaskService); + + await manager.StartAsync(); + + powerPlanService.Verify( + x => x.SetActivePowerPlanByGuidAsync("plan-high", true), + Times.Once); + notificationService.Verify( + x => x.ShowPowerPlanChangeNotificationAsync("Balanced", "plan-high-name", "game-high"), + Times.Once); + } + + [Fact] + public async Task ProcessStarted_WithDelay_TriggersSingleReevaluation() + { + var processMonitor = new FakeProcessMonitorService(); + var configuration = new ProcessMonitorConfiguration + { + PowerPlanChangeDelayMs = 25, + Associations = + { + new ProcessPowerPlanAssociation("game", "plan-game", "Game") { Priority = 5 }, + }, + }; + + var associationService = CreateAssociationService(configuration); + var powerPlanService = CreatePowerPlanService(); + var notificationService = CreateNotificationService(); + var processService = CreateProcessService(); + var coreMaskService = CreateCoreMaskService(); + var manager = CreateService( + processMonitor, + associationService, + powerPlanService, + notificationService, + processService, + coreMaskService); + + await manager.StartAsync(); + processMonitor.RaiseProcessStarted(new ProcessModel { ProcessId = 10, Name = "game" }); + processMonitor.RaiseProcessStarted(new ProcessModel { ProcessId = 11, Name = "game" }); + + await Task.Delay(150); + + powerPlanService.Verify( + x => x.SetActivePowerPlanByGuidAsync("plan-game", true), + Times.Once); + } + + [Fact] + public async Task StopAsync_RestoresDefaultPowerPlan_WhenConfigured() + { + var processMonitor = new FakeProcessMonitorService + { + RunningProcesses = + { + new ProcessModel { ProcessId = 21, Name = "game" }, + }, + }; + + var configuration = new ProcessMonitorConfiguration + { + DefaultPowerPlanGuid = "plan-default", + DefaultPowerPlanName = "Balanced", + PowerPlanChangeDelayMs = 0, + Associations = + { + new ProcessPowerPlanAssociation("game", "plan-game", "Game") { Priority = 1 }, + }, + }; + + var associationService = CreateAssociationService(configuration); + var powerPlanService = CreatePowerPlanService(); + var notificationService = CreateNotificationService(); + var processService = CreateProcessService(); + var coreMaskService = CreateCoreMaskService(); + var manager = CreateService( + processMonitor, + associationService, + powerPlanService, + notificationService, + processService, + coreMaskService); + + await manager.StartAsync(); + await manager.StopAsync(); + + powerPlanService.Verify( + x => x.SetActivePowerPlanByGuidAsync("plan-default", true), + Times.AtLeastOnce); + processService.Verify(x => x.UntrackProcess(21), Times.Once); + coreMaskService.Verify(x => x.UnregisterMaskApplication(21), Times.Once); + } + + [Fact] + public async Task Dispose_CompletesOnBlockingSynchronizationContext() + { + var processMonitor = new FakeProcessMonitorService + { + StopMonitoringAsyncImpl = async () => + { + await Task.Yield(); + }, + }; + + var configuration = new ProcessMonitorConfiguration(); + var associationService = CreateAssociationService(configuration); + var powerPlanService = CreatePowerPlanService(); + var notificationService = CreateNotificationService(); + var processService = CreateProcessService(); + var coreMaskService = CreateCoreMaskService(); + var manager = CreateService( + processMonitor, + associationService, + powerPlanService, + notificationService, + processService, + coreMaskService); + + await manager.StartAsync(); + + Exception? disposeException = null; + using var completed = new ManualResetEventSlim(false); + var disposeThread = new Thread(() => + { + SynchronizationContext.SetSynchronizationContext(new BlockingSynchronizationContext()); + + try + { + manager.Dispose(); + } + catch (Exception ex) + { + disposeException = ex; + } + finally + { + completed.Set(); + } + }); + + disposeThread.Start(); + + Assert.True(completed.Wait(TimeSpan.FromSeconds(1)), "Dispose did not complete promptly."); + Assert.Null(disposeException); + Assert.Equal(1, processMonitor.StopCalls); + Assert.Equal(1, processMonitor.DisposeCalls); + } + + private static ProcessMonitorManagerService CreateService( + FakeProcessMonitorService processMonitorService, + Mock associationService, + Mock powerPlanService, + Mock notificationService, + Mock processService, + Mock coreMaskService) + { + var enhancedLogger = new Mock(MockBehavior.Loose); + enhancedLogger + .Setup(x => x.LogSystemEventAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + enhancedLogger + .Setup(x => x.LogProcessMonitoringEventAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + enhancedLogger + .Setup(x => x.LogErrorAsync(It.IsAny(), It.IsAny(), It.IsAny?>())) + .Returns(Task.CompletedTask); + + var settingsService = new Mock(MockBehavior.Loose); + settingsService.SetupGet(x => x.Settings).Returns(new ApplicationSettingsModel()); + + return new ProcessMonitorManagerService( + processMonitorService, + associationService.Object, + powerPlanService.Object, + notificationService.Object, + settingsService.Object, + processService.Object, + coreMaskService.Object, + NullLogger.Instance, + enhancedLogger.Object); + } + + private static Mock CreateAssociationService(ProcessMonitorConfiguration configuration) + { + var associationService = new Mock(MockBehavior.Strict); + associationService.SetupGet(x => x.Configuration).Returns(configuration); + associationService.Setup(x => x.LoadConfigurationAsync()).ReturnsAsync(true); + return associationService; + } + + private static Mock CreatePowerPlanService() + { + var powerPlanService = new Mock(MockBehavior.Strict); + powerPlanService.Setup(x => x.GetActivePowerPlan()).ReturnsAsync(new PowerPlanModel { Guid = "balanced", Name = "Balanced" }); + powerPlanService.Setup(x => x.SetActivePowerPlanByGuidAsync(It.IsAny(), It.IsAny())).ReturnsAsync(true); + powerPlanService.Setup(x => x.GetPowerPlanByGuidAsync(It.IsAny())) + .ReturnsAsync((string guid) => new PowerPlanModel { Guid = guid, Name = $"{guid}-name" }); + return powerPlanService; + } + + private static Mock CreateNotificationService() + { + var notificationService = new Mock(MockBehavior.Strict); + notificationService.SetupGet(x => x.NotificationHistory).Returns(Array.Empty()); + notificationService.Setup(x => x.ShowPowerPlanChangeNotificationAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + notificationService.Setup(x => x.ShowErrorNotificationAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + notificationService.Setup(x => x.ShowNotificationAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + return notificationService; + } + + private static Mock CreateProcessService() + { + var processService = new Mock(MockBehavior.Strict); + processService.Setup(x => x.UntrackProcess(It.IsAny())); + return processService; + } + + private static Mock CreateCoreMaskService() + { + var coreMaskService = new Mock(MockBehavior.Strict); + coreMaskService.SetupGet(x => x.AvailableMasks).Returns(new ObservableCollection()); + coreMaskService.Setup(x => x.UnregisterMaskApplication(It.IsAny())); + return coreMaskService; + } + + private sealed class FakeProcessMonitorService : IProcessMonitorService + { + public event EventHandler? ProcessStarted; + + public event EventHandler? ProcessStopped; + + public event EventHandler? MonitoringStatusChanged; + + public List RunningProcesses { get; } = new(); + + public int StartCalls { get; private set; } + + public int StopCalls { get; private set; } + + public int DisposeCalls { get; private set; } + + public bool IsMonitoring { get; private set; } + + public bool IsWmiAvailable => false; + + public bool IsFallbackPollingActive => false; + + public Func? StopMonitoringAsyncImpl { get; init; } + + public Task StartMonitoringAsync() + { + this.StartCalls++; + this.IsMonitoring = true; + return Task.CompletedTask; + } + + public Task StopMonitoringAsync() + { + this.StopCalls++; + this.IsMonitoring = false; + return this.StopMonitoringAsyncImpl?.Invoke() ?? Task.CompletedTask; + } + + public Task> GetRunningProcessesAsync() => + Task.FromResult>(this.RunningProcesses.ToList()); + + public Task IsProcessRunningAsync(string executableName) => + Task.FromResult(this.RunningProcesses.Any(x => string.Equals(x.Name, executableName, StringComparison.OrdinalIgnoreCase))); + + public void UpdateSettings() + { + } + + public void RaiseProcessStarted(ProcessModel process) => + this.ProcessStarted?.Invoke(this, new ProcessEventArgs(process)); + + public void Dispose() + { + this.DisposeCalls++; + } + } + + private sealed class BlockingSynchronizationContext : SynchronizationContext + { + public override void Post(SendOrPostCallback d, object? state) + { + // Intentionally do not pump posted work to emulate a blocked UI thread. + } + } + } +} diff --git a/Tests/ThreadPilot.Core.Tests/ProcessServiceTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessServiceTests.cs new file mode 100644 index 0000000..6e4825e --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/ProcessServiceTests.cs @@ -0,0 +1,144 @@ +/* + * ThreadPilot - process service unit tests. + */ +namespace ThreadPilot.Core.Tests +{ + using System.Collections.Concurrent; + using System.Diagnostics; + using System.Text.Json; + using ThreadPilot.Models; + using ThreadPilot.Services; + + /// + /// Unit tests for deterministic behavior in . + /// + public sealed class ProcessServiceTests + { + [Fact] + public async Task SaveProcessProfile_WritesExpectedJson() + { + var profilesDirectory = CreateTemporaryDirectory(); + var profileName = $"profile-{Guid.NewGuid():N}"; + var process = new ProcessModel + { + Name = "game.exe", + Priority = ProcessPriorityClass.High, + ProcessorAffinity = 3, + }; + + try + { + var service = CreateService(profilesDirectory); + + var result = await service.SaveProcessProfile(profileName, process); + + Assert.True(result); + + var filePath = Path.Combine(profilesDirectory, $"{profileName}.json"); + Assert.True(File.Exists(filePath)); + + using var document = JsonDocument.Parse(await File.ReadAllTextAsync(filePath)); + Assert.Equal("game.exe", document.RootElement.GetProperty("ProcessName").GetString()); + Assert.Equal((int)ProcessPriorityClass.High, document.RootElement.GetProperty("Priority").GetInt32()); + Assert.Equal(3, document.RootElement.GetProperty("ProcessorAffinity").GetInt64()); + } + finally + { + DeleteDirectory(profilesDirectory); + } + } + + [Fact] + public async Task LoadProcessProfile_ReturnsFalse_WhenFileIsMissing() + { + var profilesDirectory = CreateTemporaryDirectory(); + + try + { + var service = CreateService(profilesDirectory); + + var result = await service.LoadProcessProfile("missing-profile", new ProcessModel()); + + Assert.False(result); + } + finally + { + DeleteDirectory(profilesDirectory); + } + } + + [Fact] + public void TrackPriorityChange_PreservesOriginalPriority() + { + var service = CreateService(CreateTemporaryDirectory()); + + try + { + service.TrackPriorityChange(42, ProcessPriorityClass.Normal); + service.TrackPriorityChange(42, ProcessPriorityClass.High); + + var trackedPriorities = GetPrivateDictionary(service, "originalPriorities"); + Assert.True(trackedPriorities.TryGetValue(42, out var priority)); + Assert.Equal(ProcessPriorityClass.Normal, priority); + } + finally + { + DeleteDirectory(GetProfilesDirectory(service)); + } + } + + [Fact] + public void UntrackProcess_ClearsTrackedState() + { + var service = CreateService(CreateTemporaryDirectory()); + + try + { + service.TrackAppliedMask(77, "mask-a"); + service.TrackPriorityChange(77, ProcessPriorityClass.BelowNormal); + + service.UntrackProcess(77); + + var trackedMasks = GetPrivateDictionary(service, "appliedMasks"); + var trackedPriorities = GetPrivateDictionary(service, "originalPriorities"); + Assert.False(trackedMasks.ContainsKey(77)); + Assert.False(trackedPriorities.ContainsKey(77)); + } + finally + { + DeleteDirectory(GetProfilesDirectory(service)); + } + } + + private static ProcessService CreateService(string profilesDirectory) => + new(null, null, () => profilesDirectory); + + private static string CreateTemporaryDirectory() + { + var path = Path.Combine(Path.GetTempPath(), $"threadpilot-process-service-{Guid.NewGuid():N}"); + Directory.CreateDirectory(path); + return path; + } + + private static void DeleteDirectory(string path) + { + if (Directory.Exists(path)) + { + Directory.Delete(path, recursive: true); + } + } + + private static string GetProfilesDirectory(ProcessService service) + { + var property = typeof(ProcessService).GetProperty("ProfilesDirectory", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + return (string)(property?.GetValue(service) ?? throw new InvalidOperationException("ProfilesDirectory property not found.")); + } + + private static ConcurrentDictionary GetPrivateDictionary(ProcessService service, string fieldName) + where TKey : notnull + { + var field = typeof(ProcessService).GetField(fieldName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + return (ConcurrentDictionary)(field?.GetValue(service) ?? throw new InvalidOperationException($"Field '{fieldName}' not found.")); + } + } +} diff --git a/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj b/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj index 87590f4..2bb9442 100644 --- a/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj +++ b/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj @@ -6,7 +6,6 @@ enable false cobertura - 40 @@ -26,4 +25,4 @@ - \ No newline at end of file + diff --git a/Tests/ThreadPilot.Core.Tests/coverlet.runsettings b/Tests/ThreadPilot.Core.Tests/coverlet.runsettings new file mode 100644 index 0000000..29824d2 --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/coverlet.runsettings @@ -0,0 +1,14 @@ + + + + + + + cobertura + **/obj/**,**/*.g.cs,**/*.g.i.cs,**/GeneratedInternalTypeHelper.g.cs,**/Microsoft.Extensions.Logging.Generators/** + GeneratedCodeAttribute,ExcludeFromCodeCoverageAttribute + + + + + diff --git a/ViewModels/SettingsViewModel.cs b/ViewModels/SettingsViewModel.cs index b4cc437..1b59671 100644 --- a/ViewModels/SettingsViewModel.cs +++ b/ViewModels/SettingsViewModel.cs @@ -48,6 +48,7 @@ namespace ThreadPilot.ViewModels private readonly IProcessMonitorManagerService processMonitorManagerService; private readonly IThemeService themeService; private readonly ISystemTrayService systemTrayService; + private readonly GitHubUpdateChecker gitHubUpdateChecker; private bool isSyncingFromService = false; private string cachedDefaultPowerPlanGuid = string.Empty; private string cachedDefaultPowerPlanName = string.Empty; @@ -102,6 +103,7 @@ namespace ThreadPilot.ViewModels IProcessMonitorManagerService processMonitorManagerService, IThemeService themeService, ISystemTrayService systemTrayService, + GitHubUpdateChecker gitHubUpdateChecker, IEnhancedLoggingService? enhancedLoggingService = null) : base(logger, enhancedLoggingService) { @@ -113,6 +115,7 @@ namespace ThreadPilot.ViewModels this.processMonitorManagerService = processMonitorManagerService ?? throw new ArgumentNullException(nameof(processMonitorManagerService)); this.themeService = themeService ?? throw new ArgumentNullException(nameof(themeService)); this.systemTrayService = systemTrayService ?? throw new ArgumentNullException(nameof(systemTrayService)); + this.gitHubUpdateChecker = gitHubUpdateChecker ?? throw new ArgumentNullException(nameof(gitHubUpdateChecker)); // Get version and strip the git commit hash (everything after '+') var rawVersion = typeof(App).Assembly @@ -572,7 +575,7 @@ namespace ThreadPilot.ViewModels this.StatusMessage = "Checking for updates..."; var currentVersion = ParseVersion(this.ApplicationVersion); - var (latest, releaseUrl) = await GitHubUpdateChecker.GetLatestVersionAsync("PrimeBuild-pc", "ThreadPilot"); + var (latest, releaseUrl) = await this.gitHubUpdateChecker.GetLatestVersionAsync("PrimeBuild-pc", "ThreadPilot"); if (latest is null) { diff --git a/build/generate-winget-manifests.ps1 b/build/generate-winget-manifests.ps1 new file mode 100644 index 0000000..3dc9e75 --- /dev/null +++ b/build/generate-winget-manifests.ps1 @@ -0,0 +1,109 @@ +param( + [Parameter(Mandatory = $true)] + [string]$Version, + + [Parameter(Mandatory = $true)] + [string]$Tag, + + [Parameter(Mandatory = $true)] + [string]$InstallerUrl, + + [Parameter(Mandatory = $true)] + [string]$InstallerSha256, + + [Parameter(Mandatory = $true)] + [string]$OutputRoot +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +if ($Version -notmatch '^\d+\.\d+\.\d+$') { + throw "Version must be in semantic version format X.Y.Z. Actual: $Version" +} + +if ($Tag -notmatch '^v\d+\.\d+\.\d+$') { + throw "Tag must be in format vX.Y.Z. Actual: $Tag" +} + +if (-not [Uri]::TryCreate($InstallerUrl, [UriKind]::Absolute, [ref]$null)) { + throw "InstallerUrl must be an absolute URI. Actual: $InstallerUrl" +} + +if ($InstallerSha256 -notmatch '^[A-Fa-f0-9]{64}$') { + throw 'InstallerSha256 must be a 64-character hexadecimal SHA256 value.' +} + +$normalizedSha256 = $InstallerSha256.ToUpperInvariant() +$outputPath = [System.IO.Path]::GetFullPath($OutputRoot) + +if (Test-Path -LiteralPath $outputPath) { + Remove-Item -LiteralPath $outputPath -Recurse -Force +} + +New-Item -ItemType Directory -Path $outputPath -Force | Out-Null + +$versionManifestPath = Join-Path $outputPath 'PrimeBuild.ThreadPilot.yaml' +$defaultLocaleManifestPath = Join-Path $outputPath 'PrimeBuild.ThreadPilot.locale.en-US.yaml' +$installerManifestPath = Join-Path $outputPath 'PrimeBuild.ThreadPilot.installer.yaml' + +$versionManifest = @" +PackageIdentifier: PrimeBuild.ThreadPilot +PackageVersion: $Version +DefaultLocale: en-US +ManifestType: version +ManifestVersion: 1.4.0 +"@ + +$defaultLocaleManifest = @" +PackageIdentifier: PrimeBuild.ThreadPilot +PackageVersion: $Version +PackageLocale: en-US +Publisher: Prime Build +PublisherUrl: https://github.com/PrimeBuild-pc +PublisherSupportUrl: https://github.com/PrimeBuild-pc/ThreadPilot/issues +PackageName: ThreadPilot +PackageUrl: https://github.com/PrimeBuild-pc/ThreadPilot +License: AGPL-3.0-only +LicenseUrl: https://github.com/PrimeBuild-pc/ThreadPilot/blob/main/LICENSE +ShortDescription: Advanced Windows process and power plan manager. +Description: ThreadPilot is a Process Lasso style utility for process affinity, priority, and power plan automation on Windows. +ReleaseNotesUrl: https://github.com/PrimeBuild-pc/ThreadPilot/releases/tag/$Tag +Tags: + - windows + - process + - power-plan + - performance +ManifestType: defaultLocale +ManifestVersion: 1.4.0 +"@ + +$installerManifest = @" +PackageIdentifier: PrimeBuild.ThreadPilot +PackageVersion: $Version +InstallerType: inno +Installers: + - Architecture: x64 + InstallerUrl: $InstallerUrl + InstallerSha256: $normalizedSha256 +ManifestType: installer +ManifestVersion: 1.4.0 +"@ + +Set-Content -LiteralPath $versionManifestPath -Value $versionManifest -Encoding utf8 +Set-Content -LiteralPath $defaultLocaleManifestPath -Value $defaultLocaleManifest -Encoding utf8 +Set-Content -LiteralPath $installerManifestPath -Value $installerManifest -Encoding utf8 + +$expectedFiles = @( + $versionManifestPath, + $defaultLocaleManifestPath, + $installerManifestPath +) + +foreach ($file in $expectedFiles) { + if (-not (Test-Path -LiteralPath $file)) { + throw "Expected generated manifest was not created: $file" + } +} + +Write-Host "Generated winget manifests for PrimeBuild.ThreadPilot $Version at $outputPath" diff --git a/build/publish-chocolatey.ps1 b/build/publish-chocolatey.ps1 index cdbe01a..9883cf9 100644 --- a/build/publish-chocolatey.ps1 +++ b/build/publish-chocolatey.ps1 @@ -8,8 +8,15 @@ param( [Parameter(Mandatory = $true)] [string]$InstallerPath, - [Parameter(Mandatory = $true)] - [string]$ApiKey + [string]$ApiKey, + + [string]$PackageOutputDirectory, + + [string]$MetadataOutputPath, + + [switch]$DryRun, + + [switch]$SkipPush ) Set-StrictMode -Version Latest @@ -29,6 +36,10 @@ if (-not (Test-Path -LiteralPath $InstallerPath)) { throw "Installer executable not found: $InstallerPath" } +if (-not $DryRun -and -not $SkipPush -and [string]::IsNullOrWhiteSpace($ApiKey)) { + throw "ApiKey is required unless -DryRun or -SkipPush is used." +} + $scriptRoot = Split-Path -Parent $PSCommandPath $projectRoot = Split-Path -Parent $scriptRoot $sourceChocoRoot = Join-Path $projectRoot 'chocolatey' @@ -37,7 +48,14 @@ if (-not (Test-Path -LiteralPath $sourceChocoRoot)) { throw "Chocolatey source folder not found: $sourceChocoRoot" } -$workRoot = Join-Path $env:RUNNER_TEMP 'threadpilot-choco-publish' +$tempRoot = if ([string]::IsNullOrWhiteSpace($env:RUNNER_TEMP)) { + [System.IO.Path]::GetTempPath() +} +else { + $env:RUNNER_TEMP +} + +$workRoot = Join-Path $tempRoot 'threadpilot-choco-publish' if (Test-Path -LiteralPath $workRoot) { Remove-Item -LiteralPath $workRoot -Recurse -Force } @@ -60,6 +78,21 @@ $hash = (Get-FileHash -LiteralPath $InstallerPath -Algorithm SHA256).Hash.ToLowe $installerFileName = Split-Path -Leaf $InstallerPath $installerUrl = "https://github.com/PrimeBuild-pc/ThreadPilot/releases/download/$Tag/$installerFileName" $releaseNotesUrl = "https://github.com/PrimeBuild-pc/ThreadPilot/releases/tag/$Tag" +$resolvedPackageOutputDirectory = if ([string]::IsNullOrWhiteSpace($PackageOutputDirectory)) { + Join-Path $workRoot 'out' +} +else { + [System.IO.Path]::GetFullPath($PackageOutputDirectory) +} + +$resolvedMetadataOutputPath = if ([string]::IsNullOrWhiteSpace($MetadataOutputPath)) { + $null +} +else { + [System.IO.Path]::GetFullPath($MetadataOutputPath) +} + +New-Item -ItemType Directory -Force -Path $resolvedPackageOutputDirectory | Out-Null [xml]$nuspec = Get-Content -LiteralPath $nuspecPath $nuspec.package.metadata.version = $Version @@ -67,33 +100,67 @@ $nuspec.package.metadata.releaseNotes = $releaseNotesUrl $nuspec.Save($nuspecPath) $installScript = Get-Content -LiteralPath $installScriptPath -Raw -$installScript = [regex]::Replace($installScript, "\$url64\s*=\s*'.*?'", "`$url64 = '$installerUrl'") -$installScript = [regex]::Replace($installScript, "\$checksum64\s*=\s*'.*?'", "`$checksum64 = '$hash'") +$installScript = [regex]::Replace($installScript, '\$url64\s*=\s*''.*?''', ('$url64 = ''{0}''' -f $installerUrl)) +$installScript = [regex]::Replace($installScript, '\$checksum64\s*=\s*''.*?''', ('$checksum64 = ''{0}''' -f $hash)) Set-Content -LiteralPath $installScriptPath -Value $installScript -Encoding Ascii Push-Location -LiteralPath $workRoot try { - & choco pack threadpilot.nuspec --outputdirectory . + & choco pack threadpilot.nuspec --outputdirectory $resolvedPackageOutputDirectory if ($LASTEXITCODE -ne 0) { throw 'choco pack failed.' } - $nupkg = Get-ChildItem -LiteralPath $workRoot -Filter 'threadpilot.*.nupkg' -File | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1 + $nupkg = Get-ChildItem -LiteralPath $resolvedPackageOutputDirectory -Filter 'threadpilot.*.nupkg' -File | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1 if (-not $nupkg) { throw 'Chocolatey package was not created.' } - $pushOutput = (& choco push $nupkg.FullName --source 'https://push.chocolatey.org/' --api-key $ApiKey --timeout 2700 2>&1 | Out-String) - if ($LASTEXITCODE -ne 0) { - if ($pushOutput -match 'already exists') { - Write-Host 'Chocolatey package already exists. Treating as successful idempotent publish.' - exit 0 - } + $publishAttempted = $false + $publishResult = 'packed' - throw "choco push failed. Output: $pushOutput" + if (-not $DryRun -and -not $SkipPush) { + $publishAttempted = $true + $pushOutput = (& choco push $nupkg.FullName --source 'https://push.chocolatey.org/' --api-key $ApiKey --timeout 2700 2>&1 | Out-String) + if ($LASTEXITCODE -ne 0) { + if ($pushOutput -match 'already exists') { + Write-Host 'Chocolatey package already exists. Treating as successful idempotent publish.' + $publishResult = 'already-exists' + } + else { + throw "choco push failed. Output: $pushOutput" + } + } + else { + Write-Host 'Chocolatey package published successfully.' + $publishResult = 'published' + } + } + else { + Write-Host 'Chocolatey package validation completed without push.' + $publishResult = if ($DryRun) { 'dry-run' } else { 'packed-no-push' } } - Write-Host 'Chocolatey package published successfully.' + if (-not [string]::IsNullOrWhiteSpace($resolvedMetadataOutputPath)) { + $metadataDirectory = Split-Path -Parent $resolvedMetadataOutputPath + if (-not [string]::IsNullOrWhiteSpace($metadataDirectory)) { + New-Item -ItemType Directory -Force -Path $metadataDirectory | Out-Null + } + + @{ + version = $Version + tag = $Tag + installerPath = (Resolve-Path -LiteralPath $InstallerPath).Path + installerUrl = $installerUrl + installerSha256 = $hash + packagePath = $nupkg.FullName + releaseNotesUrl = $releaseNotesUrl + publishAttempted = $publishAttempted + publishResult = $publishResult + dryRun = [bool]$DryRun + skipPush = [bool]$SkipPush + } | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $resolvedMetadataOutputPath -Encoding utf8 + } } finally { Pop-Location diff --git a/chocolatey/threadpilot.nuspec b/chocolatey/threadpilot.nuspec index 20a57d4..21af6ff 100644 --- a/chocolatey/threadpilot.nuspec +++ b/chocolatey/threadpilot.nuspec @@ -6,6 +6,10 @@ ThreadPilot Prime Build https://github.com/PrimeBuild-pc/ThreadPilot + https://github.com/PrimeBuild-pc/ThreadPilot + https://github.com/PrimeBuild-pc/ThreadPilot/tree/main/chocolatey + https://github.com/PrimeBuild-pc/ThreadPilot/tree/main/docs + https://github.com/PrimeBuild-pc/ThreadPilot/issues https://github.com/PrimeBuild-pc/ThreadPilot/blob/main/LICENSE https://raw.githubusercontent.com/PrimeBuild-pc/ThreadPilot/main/assets/icons/ico.ico false diff --git a/chocolatey/tools/chocolateyInstall.ps1 b/chocolatey/tools/chocolateyInstall.ps1 index 968fab8..3527c2b 100644 --- a/chocolatey/tools/chocolateyInstall.ps1 +++ b/chocolatey/tools/chocolateyInstall.ps1 @@ -2,8 +2,9 @@ $ErrorActionPreference = 'Stop' $packageName = 'threadpilot' $toolsDir = Split-Path -Parent $MyInvocation.MyCommand.Definition -$url64 = 'https://github.com/PrimeBuild-pc/ThreadPilot/releases/download/v1.1.2/ThreadPilot_v1.1.2_Setup.exe' -$checksum64 = 'fac3935ba126b01987b15cb323502ee8b6e91c957f22006bd9e62b8d57169790' +# These placeholders are replaced during pack/publish automation. +$url64 = '__INSTALLER_URL__' +$checksum64 = '__INSTALLER_SHA256__' $packageArgs = @{ packageName = $packageName diff --git a/docs/QUALITY_GATES.md b/docs/QUALITY_GATES.md index da39542..872b143 100644 --- a/docs/QUALITY_GATES.md +++ b/docs/QUALITY_GATES.md @@ -7,11 +7,12 @@ This document defines Go/No-Go gates for ThreadPilot releases. | Gate | Criteria | Owner | Status | |---|---|---|---| | Build integrity | Release build succeeds with no blocking errors | CI/CD | Complete | -| Unit/integration tests | All tests pass on Release config | QA | Complete | +| Core automated tests | `Tests/ThreadPilot.Core.Tests` passes on Release config | QA | Complete | +| Coverage gate | CI parses Cobertura and fails below the active threshold | QA | Complete | | Dependency security | No Critical/High vulnerabilities from dotnet audit | Security | Complete | | Secret hygiene | Gitleaks scan has no active findings | Security | Complete | | Performance baseline | Idle tray footprint collected and archived | Performance | Complete | -| Packaging | Installer + portable + checksums generated | Release Eng | Complete | +| Packaging | Installer + release zips + checksums + packaging evidence generated | Release Eng | Complete | | Documentation | Release notes, runbook, changelog updated | Tech Writer | Complete | | Compatibility | Smoke test on Windows 11 and Windows 10 best-effort | QA | Deferred (release candidate pass) | @@ -20,18 +21,33 @@ This document defines Go/No-Go gates for ThreadPilot releases. ```powershell dotnet restore ThreadPilot_1.sln dotnet build ThreadPilot_1.sln --configuration Release --no-restore -dotnet test ThreadPilot_1.sln --configuration Release --no-build +dotnet test Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj --configuration Release --no-restore --collect:"XPlat Code Coverage" --settings "Tests/ThreadPilot.Core.Tests/coverlet.runsettings" --results-directory TestResults dotnet list ThreadPilot.csproj package --vulnerable --include-transitive ``` +## Coverage Scope + +- The coverage badge tracks business/application code. +- Generated build artifacts are excluded via `coverlet.runsettings`. +- Legacy runtime harness files under `Tests/*.cs` are not part of the CI coverage contract. + +## Active Coverage Threshold + +The repository now uses a real Cobertura-parsed gate in CI. + +- Transitional threshold: `1.5%` line coverage +- Reason: this matches the current honest baseline while service coverage is still being expanded +- Planned ratchet: raise progressively as additional deterministic service tests land + ## Go/No-Go Rule Release can proceed only when all gates are marked complete or explicitly waived with a written risk note. -## Evidence Snapshot (2026-04-15) +## Evidence Snapshot (2026-04-21) -- Build: `dotnet build ThreadPilot_1.sln --configuration Release --no-restore` (success). -- Tests: `dotnet test Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj --configuration Release` (20 passed, 0 failed). +- Build: `dotnet build ThreadPilot_1.sln --configuration Release --no-restore` (success in CI release path). +- Tests: `dotnet test Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj --configuration Release --collect:"XPlat Code Coverage" --settings "Tests/ThreadPilot.Core.Tests/coverlet.runsettings"` (`45` passed, `0` failed in the current hardening branch). +- Coverage: Cobertura from the current hardening branch is `7.52%` line / `5.50%` branch and is enforced by CI against the transitional `1.5%` line gate. - Dependency security: `dotnet list ThreadPilot.csproj package --vulnerable --include-transitive` (no vulnerable packages). - Secret hygiene: local gitleaks run, report `docs/audits/GITLEAKS_REPORT_2026-04-15.json` (no leaks). -- Packaging: installer/packages/checksums generated in `artifacts/release/`. +- Packaging: installer/packages/checksums plus winget/chocolatey evidence artifacts generated in `artifacts/release/` / workflow artifacts. diff --git a/docs/reference/PROJECT_STRUCTURE.md b/docs/reference/PROJECT_STRUCTURE.md index 710bae0..6662419 100644 --- a/docs/reference/PROJECT_STRUCTURE.md +++ b/docs/reference/PROJECT_STRUCTURE.md @@ -1,188 +1,92 @@ # ThreadPilot Project Structure ## Overview -This document describes the organized project structure of ThreadPilot, designed for maintainability, scalability, and clear separation of concerns. -## Root Directory Structure +This document reflects the repository as it exists today. It intentionally distinguishes: -``` +- production application code +- xUnit coverage-driving tests +- legacy runtime smoke harnesses under `Tests/` + +## Root Layout + +```text ThreadPilot/ -├── Services/ # Service layer with business logic -│ ├── Core/ # Base interfaces and implementations -│ ├── ProcessManagement/ # Process monitoring and management -│ ├── ServiceConfiguration.cs # Centralized DI configuration -│ └── ServiceFactory.cs # Service factory pattern -├── ViewModels/ # MVVM ViewModels -│ ├── BaseViewModel.cs # Enhanced base ViewModel -│ └── ViewModelFactory.cs # ViewModel factory -├── Views/ # XAML views and code-behind -├── Models/ # Data models and domain objects -│ └── Core/ # Base model interfaces -├── Data/ # Data access layer -│ ├── IRepository.cs # Repository interfaces -│ ├── JsonRepository.cs # JSON file implementation -│ └── DataAccessService.cs # Centralized data access -├── Converters/ # Value converters for data binding -├── Helpers/ # Utility classes and extensions -├── Tests/ # Unit and integration tests -├── Documentation/ # Project documentation -│ ├── ARCHITECTURE_GUIDE.md # Architecture overview -│ ├── DEVELOPER_GUIDE.md # Development guidelines -│ ├── API_REFERENCE.md # API documentation -│ └── PROJECT_STRUCTURE.md # This file -└── Configuration Files - ├── App.xaml # Application configuration - ├── App.xaml.cs # Application startup - └── ThreadPilot.csproj # Project file +├── .github/ # CI, release, and security workflows +├── assets/ # Static assets bundled into releases +├── build/ # Release/package automation scripts +├── chocolatey/ # Chocolatey package template and install scripts +├── Converters/ # WPF binding converters +├── docs/ # Reference, release, audit, and contributor docs +├── Helpers/ # Shared helper utilities +├── Installer/ # Inno Setup installer definition +├── Models/ # Domain/data models +├── Platforms/ # Windows-specific interop helpers +├── Properties/ # Publish profiles and app properties +├── Services/ # Application and OS-integration services +├── Tests/ +│ ├── ThreadPilot.Core.Tests/ # Real xUnit suite used by CI and Codecov +│ └── *.cs # Legacy runtime smoke/integration harnesses +├── Themes/ # WPF theme resources +├── ViewModels/ # MVVM presentation logic +├── Views/ # XAML views and code-behind +├── winget/ # Submission scripts/reference manifests +├── App.xaml / App.xaml.cs # Application bootstrap and DI entry +├── ThreadPilot.csproj # Main WPF application project +└── ThreadPilot_1.sln # Solution file ``` -## Service Layer Organization +## Services -### Core Services (`Services/Core/`) -**Purpose**: Base interfaces and common functionality for all services. +`Services/` contains the highest-value business and orchestration logic in the repo. -- `ISystemService.cs` - Base interface with lifecycle management -- `BaseSystemService.cs` - Common service implementation -- `ServiceAvailabilityChangedEventArgs.cs` - Service availability events +Key areas: -### Process Management (`Services/ProcessManagement/`) -**Purpose**: Process monitoring, detection, and management services. +- `Abstractions/`: injectable seams such as settings storage, GitHub release client, and process runner +- `Core/`, `ProcessManagement/`: older organizational subfolders still present in the repo +- application services such as `ApplicationSettingsService`, `AutostartService`, `PowerPlanService`, `ProcessMonitorService`, `ProcessMonitorManagerService` +- infrastructure services such as `ServiceConfiguration`, `ServiceFactory`, `ServiceDisposalCoordinator` -- `IProcessManagementService.cs` - Unified process management interface -- `IProcessMonitorService.cs` - WMI-based process monitoring -- `IProcessMonitorManagerService.cs` - Process monitoring orchestration -- `IGameBoostService.cs` - Game detection and optimization +## Tests -### Service Infrastructure -- `ServiceConfiguration.cs` - Centralized dependency injection configuration -- `ServiceFactory.cs` - Advanced service creation and lifecycle management +### Coverage-driving suite -## Data Layer Organization +`Tests/ThreadPilot.Core.Tests/` is the real automated test project. -### Repository Pattern (`Data/`) -**Purpose**: Abstracted data access with consistent patterns. +- This is the suite executed by CI. +- This is the suite used for Cobertura/Codecov reporting. +- Coverage runsettings live in `Tests/ThreadPilot.Core.Tests/coverlet.runsettings`. -- `IRepository.cs` - Generic repository interfaces -- `JsonRepository.cs` - JSON file-based implementation -- `IDataAccessService.cs` - Centralized data coordination -- `DataAccessService.cs` - Implementation with validation and backup +### Legacy harnesses -### Model Organization (`Models/`) -**Purpose**: Domain models with validation and change tracking. +The other files directly under `Tests/` are not the xUnit suite. -- `Core/IModel.cs` - Base model interface with validation -- Domain-specific models implementing IModel interface -- Observable properties for UI binding -- Built-in validation and cloning support +They are retained as ad-hoc runtime smoke/integration harnesses used by debug-only `--test` mode in `App.xaml.cs`. -## Presentation Layer Organization +Current examples: -### ViewModels (`ViewModels/`) -**Purpose**: MVVM ViewModels with consistent patterns. +- `CpuTopologyServiceTests.cs` +- `ProcessSelectionTest.cs` +- `ExecutableBrowseTest.cs` +- `GameBoostIntegrationTest.cs` +- `ActiveApplicationsTest.cs` +- `TestRunner.cs` -- `BaseViewModel.cs` - Enhanced base with error handling and logging -- `ViewModelFactory.cs` - Centralized ViewModel creation and management -- Domain-specific ViewModels inheriting from BaseViewModel -- Proper dependency injection and lifecycle management +These harnesses are useful for exploratory/manual checks, but they are not part of CI coverage expectations. -### Views (`Views/`) -**Purpose**: XAML views with code-behind. +## Release and Packaging -- Organized by functional area -- Consistent naming conventions -- Proper data binding to ViewModels +Release automation is split across: -## Utility and Support +- `.github/workflows/release.yml` +- `build/` +- `Installer/` +- `chocolatey/` +- `winget/` -### Converters (`Converters/`) -**Purpose**: Value converters for data binding. +Generated release artifacts are expected under `artifacts/release/` during packaging runs. -- Type conversion for UI binding -- Formatting and display logic -- Reusable across multiple views +## Notes -### Helpers (`Helpers/`) -**Purpose**: Utility classes and extension methods. - -- Common functionality -- Extension methods -- Static utility classes - -## Configuration and Startup - -### Application Configuration -- `App.xaml` - Application-level resources and configuration -- `App.xaml.cs` - Dependency injection setup and application lifecycle -- `ServiceConfiguration.cs` - Centralized service registration - -### Project Configuration -- `ThreadPilot.csproj` - Project dependencies and build configuration -- Package references for modern .NET development -- Target framework and platform specifications - -## Naming Conventions - -### Namespaces -- `ThreadPilot` - Root namespace -- `ThreadPilot.Services` - Service layer -- `ThreadPilot.Services.Core` - Core service infrastructure -- `ThreadPilot.Services.ProcessManagement` - Process-related services -- `ThreadPilot.ViewModels` - Presentation layer ViewModels -- `ThreadPilot.Models` - Data models -- `ThreadPilot.Models.Core` - Base model infrastructure -- `ThreadPilot.Data` - Data access layer - -### File Naming -- Interfaces: `I{Name}.cs` (e.g., `IProcessService.cs`) -- Implementations: `{Name}.cs` (e.g., `ProcessService.cs`) -- ViewModels: `{Name}ViewModel.cs` (e.g., `ProcessViewModel.cs`) -- Models: `{Name}Model.cs` (e.g., `ProcessModel.cs`) -- Event Args: `{Name}EventArgs.cs` (e.g., `ProcessEventArgs.cs`) - -### Class Organization -- Public interfaces first -- Public classes -- Internal classes -- Private nested classes - -## Dependency Flow - -### Service Dependencies -``` -Application Services → Business Services → Core Services → OS APIs -``` - -### Presentation Dependencies -``` -Views → ViewModels → Services → Models → Data Layer -``` - -### Data Flow -``` -UI Events → ViewModels → Services → Repository → File System -``` - -## Best Practices Enforced - -### Service Layer -- Interface-based design for testability -- Dependency injection for loose coupling -- Async/await patterns throughout -- Comprehensive error handling and logging -- Event-driven communication between services - -### Presentation Layer -- MVVM pattern with proper separation -- Command pattern for user interactions -- Observable properties for data binding -- Centralized error handling in BaseViewModel -- Proper disposal and lifecycle management - -### Data Layer -- Repository pattern for data abstraction -- Model validation and integrity checking -- Thread-safe operations -- Backup and restore capabilities -- Consistent error handling - -This structure provides a solid foundation for maintainable, testable, and extensible code while following established architectural patterns and best practices. +- `bin/`, `obj/`, and `TestResults*` directories are local/generated outputs and not part of the intended source structure. +- `docs/superpowers/plans/` contains implementation plans and is intentionally excluded from normal source-control expectations for GitHub publication. diff --git a/docs/release/GO_NO_GO_MATRIX.md b/docs/release/GO_NO_GO_MATRIX.md index ba4c012..6889bd5 100644 --- a/docs/release/GO_NO_GO_MATRIX.md +++ b/docs/release/GO_NO_GO_MATRIX.md @@ -8,12 +8,17 @@ | Tests | Complete | Yes | Core test suite currently green | | Security scan | Complete | Yes | No vulnerable packages and no secret leaks | | Packaging | Complete | Yes | Installer, portable zip artifacts and checksums generated | +| Chocolatey validation artifacts | Complete | Yes | Tagged or dry-run releases must preserve `.nupkg` and metadata evidence | +| winget publication evidence | Complete | Yes | Tagged releases must either submit winget or fail with explicit missing-secret policy | +| Chocolatey publication evidence | Complete | Yes | Tagged releases must either attempt Chocolatey publish or fail with explicit missing-secret policy | | Documentation | Complete | Yes | Release docs and governance artifacts updated | | Compatibility smoke tests | Deferred | Yes | Execute on final release candidate | ## Decision Rule - GO: all blocking rows are complete. +- GO for manual dry-run only if publication evidence rows explicitly record `dry-run` and the release is not being treated as public. +- GO for manual dry-run only if Chocolatey validation artifacts are also present (`.nupkg` + metadata JSON). - NO-GO: any blocking row incomplete, unless explicit waiver approved. ## Waiver Log diff --git a/docs/release/PACKAGING.md b/docs/release/PACKAGING.md index af476df..2531ae2 100644 --- a/docs/release/PACKAGING.md +++ b/docs/release/PACKAGING.md @@ -1,6 +1,6 @@ # Packaging and Distribution Guide -This document describes production packaging for ThreadPilot v1.1.2. +This document describes the current production packaging and distribution contract for ThreadPilot releases. ## Prerequisites @@ -40,13 +40,13 @@ Output folder: ### 2) Inno Setup Installer (primary) ```powershell -iscc /DMyAppVersion=1.1.2 /DMyAppSourceDir="..\\artifacts\\release\\singlefile" Installer/setup.iss +iscc /DMyAppVersion= /DMyAppSourceDir="..\\artifacts\\release\\singlefile" Installer/setup.iss ``` Recommended local command (prevents stale publish output by forcing a fresh publish before ISCC): ```powershell -powershell -ExecutionPolicy Bypass -File build/build-installer.ps1 -Version 1.1.2 +powershell -ExecutionPolicy Bypass -File build/build-installer.ps1 -Version ``` The installer now uses Inno Setup native dynamic theming (`WizardStyle=modern dynamic windows11`) and follows the current Windows light/dark preference at startup. @@ -54,7 +54,7 @@ The installer now uses Inno Setup native dynamic theming (`WizardStyle=modern dy Optional override for QA/troubleshooting: ```powershell -iscc /DMyWizardStyle="modern dark windows11" /DMyAppVersion=1.1.2 /DMyAppSourceDir="..\\artifacts\\release\\singlefile" Installer/setup.iss +iscc /DMyWizardStyle="modern dark windows11" /DMyAppVersion= /DMyAppSourceDir="..\\artifacts\\release\\singlefile" Installer/setup.iss ``` Output folder: @@ -123,12 +123,29 @@ iscc Installer/setup.iss 1. `dotnet restore` 2. `dotnet build ThreadPilot_1.sln --configuration Release` -3. `dotnet test ThreadPilot_1.sln --configuration Release --no-build` +3. `dotnet test Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj --configuration Release --collect:"XPlat Code Coverage" --settings "Tests/ThreadPilot.Core.Tests/coverlet.runsettings" --results-directory TestResults` 4. Publish Single-file and ReadyToRun profiles 5. Build Inno Setup installer from Single-file output -6. Sign artifacts -7. Generate SHA-256 checksums -8. Upload release artifacts +6. Generate winget manifests from release metadata +7. Sign artifacts +8. Generate SHA-256 checksums +9. Upload release artifacts + +## Release Asset Contract + +The release workflow currently publishes these GitHub release assets: + +- `ThreadPilot_v_Setup.exe` +- `ThreadPilot_v_singlefile_win-x64.zip` +- `ThreadPilot_v_readytorun_win-x64.zip` +- `SHA256SUMS.txt` +- generated winget manifest YAML files +- `manifest.spdx.json` +- Chocolatey validation/publish artifacts (`.nupkg` + metadata JSON) in workflow artifacts + +Prefer the release page over hardcoded asset URLs: + +- `https://github.com/PrimeBuild-pc/ThreadPilot/releases/latest` ## Package Channel Alignment @@ -145,9 +162,39 @@ Channel behavior: Current workflow scope: -- `.github/workflows/release.yml` builds release artifacts and uploads winget manifests as artifacts. +- `.github/workflows/release.yml` builds release artifacts, generates winget manifests from the version/tag/installer URL/SHA, and uploads those manifests as artifacts. - It automatically submits a PR to `microsoft/winget-pkgs` when release succeeds and winget secrets are configured. +- It validates Chocolatey packaging by generating a real `.nupkg` plus metadata evidence before any push attempt. - It automatically publishes to Chocolatey community feed when release succeeds and Chocolatey API key is configured. +- Tagged public releases fail if channel publication secrets are missing; only manual `workflow_dispatch` dry-runs may skip external publication. + +## winget Manifest Generation + +The release workflow no longer depends on a precommitted folder under `winget/manifests/.../`. + +Generate manifests locally with: + +```powershell +./build/generate-winget-manifests.ps1 ` + -Version "1.1.3" ` + -Tag "v1.1.3" ` + -InstallerUrl "https://github.com/PrimeBuild-pc/ThreadPilot/releases/download/v1.1.3/ThreadPilot_v1.1.3_Setup.exe" ` + -InstallerSha256 "" ` + -OutputRoot "winget-manifests" +``` + +Expected output: + +- `winget-manifests/PrimeBuild.ThreadPilot.yaml` +- `winget-manifests/PrimeBuild.ThreadPilot.locale.en-US.yaml` +- `winget-manifests/PrimeBuild.ThreadPilot.installer.yaml` + +Validation checklist: + +- files exist +- `PackageIdentifier` is `PrimeBuild.ThreadPilot` +- `PackageVersion` matches the release version +- installer URL and SHA are populated Required repository secrets for full channel automation: @@ -155,12 +202,56 @@ Required repository secrets for full channel automation: - `WINGET_FORK_OWNER`: GitHub username/org that owns your `winget-pkgs` fork. - `CHOCOLATEY_API_KEY`: API key for `https://push.chocolatey.org/`. -If secrets are missing, publish jobs are skipped and GitHub release remains successful. +If secrets are missing on a tagged public release, the workflow fails by policy instead of staying ambiguously green. + +## Chocolatey Validation and Publish + +Local packaging-only validation: + +```powershell +./build/publish-chocolatey.ps1 ` + -Version "1.1.3" ` + -Tag "v1.1.3" ` + -InstallerPath ".\artifacts\release\installer\ThreadPilot_v1.1.3_Setup.exe" ` + -DryRun ` + -PackageOutputDirectory ".\artifacts\choco-dryrun" ` + -MetadataOutputPath ".\artifacts\choco-dryrun\chocolatey-package-metadata.json" +``` + +Expected outputs: + +- `threadpilot..nupkg` +- `chocolatey-package-metadata.json` + +The metadata JSON captures: + +- resolved installer URL +- installer SHA256 +- package path +- release notes URL +- whether publication was attempted +- dry-run / no-push result + +Public publish path: + +```powershell +./build/publish-chocolatey.ps1 ` + -Version "1.1.3" ` + -Tag "v1.1.3" ` + -InstallerPath ".\artifacts\release\installer\ThreadPilot_v1.1.3_Setup.exe" ` + -ApiKey "" +``` + +Moderation note: + +- A successful `choco push` means the package was submitted to Chocolatey. +- It does not guarantee immediate discoverability in search results. +- Moderation delay is an external queue, not automatically evidence of a repo or workflow failure. Optional automation for publishing the GitHub release after artifacts are ready: ```powershell -./build/create-github-release.ps1 -Version "1.1.2" -NotesFile "docs/release/RELEASE_NOTES.md" +./build/create-github-release.ps1 -Version "" -NotesFile "docs/release/RELEASE_NOTES.md" ``` ## CI/CD diff --git a/docs/release/RELEASE_RUNBOOK.md b/docs/release/RELEASE_RUNBOOK.md index 2697116..45b8631 100644 --- a/docs/release/RELEASE_RUNBOOK.md +++ b/docs/release/RELEASE_RUNBOOK.md @@ -42,6 +42,9 @@ Source-of-truth policy: - GitHub release tag and assets are the canonical release source. - Winget and Chocolatey metadata must reference an existing GitHub release tag and reachable asset URLs. - Changelog generation in CI must run with runner-native `git-cliff` binary (pinned version + checksum verification), not Docker-based changelog actions. +- Tagged releases are public-release mode: missing winget or Chocolatey publication secrets are a release blocker, not a silent skip. +- `workflow_dispatch` may be run with `dry_run_publish=true` to validate build, assets, summaries, and packaging flow without external publication. +- Every publish channel must leave evidence behind via `GITHUB_STEP_SUMMARY` plus uploaded log artifacts. Use script automation (requires authenticated gh CLI): @@ -62,6 +65,30 @@ Package publication prechecks: 3. Confirm SHA256 in package metadata matches the published installer. 4. Confirm winget and Chocolatey package versions match the GitHub release version. 5. Confirm release workflow changelog step executed successfully with the pinned `git-cliff` version. +6. Confirm release mode is intentional: + - tagged release: publish secrets present and external publication expected + - manual dry run: `dry_run_publish=true` and no external publication expected +7. Confirm the generated winget manifest artifact contains exactly: + - `PrimeBuild.ThreadPilot.yaml` + - `PrimeBuild.ThreadPilot.locale.en-US.yaml` + - `PrimeBuild.ThreadPilot.installer.yaml` +8. Confirm README/download docs still point users to the latest release page or current asset naming contract. + +Publication evidence checklist: + +1. Review the release workflow summary for a channel result line: + - `submitted` for winget + - `published` for Chocolatey + - `dry-run` only for manual dry-run executions +2. Download and inspect the uploaded channel logs: + - `winget-submit-log.txt` + - `choco-pack-log.txt` + - `choco-push-log.txt` +3. Download and inspect Chocolatey packaging artifacts: + - generated `.nupkg` + - `chocolatey-package-metadata.json` + - `chocolatey-publish-metadata.json` when publish was attempted +4. Treat a tagged release with missing channel evidence as a failed release, even if GitHub release assets were created. ## Post-Release (T+24h) @@ -70,5 +97,7 @@ Package publication prechecks: 3. Monitor issue tracker for regressions. 4. Document hotfix decisions if needed. 5. Verify package channel discoverability: -6. Run `winget source update`, then `winget search --id PrimeBuild.ThreadPilot -s winget`. -7. Run `choco search threadpilot --exact` and confirm moderation state on the package page. + Run `winget source update`, then `winget search --id PrimeBuild.ThreadPilot -s winget`. + Run `choco search threadpilot --exact` and confirm moderation state on the package page. + If Chocolatey search is still negative after publish, inspect moderation state before treating it as a release regression. + Archive workflow summaries and publish log artifacts with the release notes if the run required manual follow-up.