diff --git a/.github/workflows/inno-upgrade-smoke.yml b/.github/workflows/inno-upgrade-smoke.yml new file mode 100644 index 000000000..8b896ae49 --- /dev/null +++ b/.github/workflows/inno-upgrade-smoke.yml @@ -0,0 +1,46 @@ +name: Inno Setup graceful update smoke +on: + pull_request: + types: [opened, reopened, synchronize, ready_for_review] + paths: + - 'installer/ArSonMix.iss' + - 'installer/ArSonMixUpdateShutdown.ps1' + - 'scripts/build_verify_windows_installer.ps1' + - 'scripts/test_inno_graceful_update_windows.ps1' + - 'tests/fixtures/installer_graceful_close.cs' + - 'tests/windows_installer_contract_test.mjs' + push: + branches: [main] + paths: + - 'installer/ArSonMix.iss' + - 'installer/ArSonMixUpdateShutdown.ps1' + - 'scripts/build_verify_windows_installer.ps1' + - 'scripts/test_inno_graceful_update_windows.ps1' + - 'tests/fixtures/installer_graceful_close.cs' + - 'tests/windows_installer_contract_test.mjs' +permissions: + contents: read +concurrency: + group: inno-upgrade-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + inno-smoke: + runs-on: windows-2022 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Check installer safety and single-launch contracts + run: node --test tests/windows_installer_contract_test.mjs + - name: Prepare Inno Setup 6 + shell: pwsh + run: | + if (-not (Get-Command ISCC.exe -ErrorAction SilentlyContinue) -and + -not (Test-Path -LiteralPath 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe')) { + choco install innosetup --yes --no-progress --limit-output + if ($LASTEXITCODE -ne 0) { throw 'Inno Setup compiler installation failed' } + } + - name: Real silent Inno upgrade of running WinForms fixture and Studio retention + shell: pwsh + run: ./scripts/test_inno_graceful_update_windows.ps1 diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 0c8aa9410..4547be3ee 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -29,6 +29,7 @@ on: - 'scripts/build_verify_windows_installer.ps1' - 'installer/**' - 'tests/windows_installer_contract_test.mjs' + - 'tests/fixtures/installer_graceful_close.cs' - 'scripts/verify_native_windows_artifact.ps1' - 'scripts/collect_hardware_fat_windows.ps1' - 'scripts/console_v6_fat_gate.mjs' @@ -70,6 +71,7 @@ on: - 'scripts/build_verify_windows_installer.ps1' - 'installer/**' - 'tests/windows_installer_contract_test.mjs' + - 'tests/fixtures/installer_graceful_close.cs' - 'scripts/verify_native_windows_artifact.ps1' - 'scripts/collect_hardware_fat_windows.ps1' - 'scripts/console_v6_fat_gate.mjs' @@ -264,16 +266,17 @@ jobs: - uses: actions/upload-artifact@v4 if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} with: - name: ArSonMix-Windows-Installer-UNQUALIFIED-${{ github.run_id }} + name: ArSonMix-Windows-Installer-Preview-${{ github.run_id }} path: installer-output/ if-no-files-found: error retention-days: 14 # Optional manual FAT only: never churn experimental ZIPs per commit. - # The unqualified artifact is NOT a stable release or physical audio proof. + # Preview artifact is build/installer verified. Owner physical listening is field evidence, + # distinct from automated exact-SHA hardware performance certification. - uses: actions/upload-artifact@v4 if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} with: - name: ArSonMix-Windows-FAT-UNQUALIFIED-${{ github.run_id }} + name: ArSonMix-Windows-FAT-Preview-${{ github.run_id }} path: dist/ if-no-files-found: error retention-days: 14 diff --git a/installer/ArSonMix.iss b/installer/ArSonMix.iss index ed7999f29..351c88d69 100644 --- a/installer/ArSonMix.iss +++ b/installer/ArSonMix.iss @@ -1,15 +1,19 @@ -; ArSonMix x64 RC from exact independently verified FAT app, no new DSP or GUI. +; ArSonMix x64 per-user Inno Setup: safe in-place upgrade + single launch. +; Exact independently verified FAT app; no new DSP or GUI. #ifndef SourceRoot #error "Supply /DSourceRoot with SHA-verified staging directory" #endif #ifndef OutputRoot #error "Supply /DOutputRoot with destination directory" #endif +#ifndef SourceAppVersion + #error "Supply /DSourceAppVersion from the authoritative CMake project version" +#endif [Setup] AppId=ArSonMix.LiveStudio AppName=ArSonMix -AppVersion=0.1.0-rc.1 -AppVerName=ArSonMix RC (hardware FAT pending) +AppVersion={#SourceAppVersion} +AppVerName=ArSonMix {#SourceAppVersion} Preview AppPublisher=ArSonMix AppPublisherURL=https://masarray.github.io/arsonmix/ DefaultDirName={localappdata}\Programs\ArSonMix @@ -20,19 +24,135 @@ ArchitecturesInstallIn64BitMode=x64compatible MinVersion=10.0.17763 WizardStyle=modern OutputDir={#OutputRoot} -OutputBaseFilename=ArSonMix-Windows-x64-Setup-UNQUALIFIED +OutputBaseFilename=ArSonMix-Windows-x64-Setup-Preview SetupIconFile={#SourceRoot}\arsonmix-app.ico UninstallDisplayIcon={app}\ArSonMix.exe Compression=lzma2 SolidCompression=yes +UsePreviousAppDir=yes +DisableWelcomePage=yes +DisableDirPage=yes +DisableReadyPage=yes +DisableFinishedPage=yes +SetupMutex=ArSonMix.PerUserInstaller.SingleInstance +; Our pre-install shutdown owns the lifecycle for BOTH new and legacy +; releases. Do not let Windows Restart Manager issue a second shutdown or +; force a hung mixer after our fail-closed check. A single controlled +; WM_CLOSE followed by full process exit is required before replacing EXE. CloseApplications=no RestartApplications=no [Files] +; The shutdown helper is EMBEDDED TEMPORARILY in Setup, never installed. +; It handles installed legacy builds that do not implement the new event. +Source: "ArSonMixUpdateShutdown.ps1"; Flags: dontcopy Source: "{#SourceRoot}\verified-gui.exe"; DestDir: "{app}"; DestName: "ArSonMix.exe"; Flags: ignoreversion Source: "{#SourceRoot}\BUILD_PROVENANCE.json"; DestDir: "{app}"; Flags: ignoreversion Source: "{#SourceRoot}\README.md"; DestDir: "{app}"; Flags: ignoreversion Source: "{#SourceRoot}\FactoryFX\*"; DestDir: "{app}\FactoryFX"; Flags: ignoreversion recursesubdirs createallsubdirs skipifsourcedoesntexist [Icons] Name: "{autoprograms}\ArSonMix"; Filename: "{app}\ArSonMix.exe"; WorkingDir: "{app}" -; No Run or UninstallDelete: do not auto-activate live audio or erase -; AppData Studio. Do not install portable_mode.txt. +; Do not create a second copy of an already running mixer. Restart Manager +; preflight closes the prior verified app before [Files]; [Run] launches exactly +; one new executable only after a successful interactive install/update. +; Silent enterprise/FAT installs deliberately do not launch desktop audio. +[Run] +Filename: "{app}\ArSonMix.exe"; WorkingDir: "{app}"; Flags: nowait runasoriginaluser skipifsilent + +; Never delete private Studio data on install/update/uninstall; never install +; portable_mode.txt or silently ARM an audio output. + +; Upgrade preflight operates BEFORE [Files]: save+close native apps, support +; legacy versions with no shutdown handshake, verify the EXE is replaceable. +; Never force-terminate, never skip an occupied file, and never erase Studio. +[Code] +function OpenEventW(Access: LongWord; InheritHandle: Boolean; Name: string): THandle; + external 'OpenEventW@kernel32.dll stdcall'; +function SignalEvent(EventHandle: THandle): Boolean; + external 'SetEvent@kernel32.dll stdcall'; +function CloseWinHandle(EventHandle: THandle): Boolean; + external 'CloseHandle@kernel32.dll stdcall'; +function OpenExclusiveFile(Path: string; DesiredAccess, ShareMode: LongWord; + SecurityAttributes: LongWord; CreationDisposition, Flags: LongWord; + Template: THandle): THandle; + external 'CreateFileW@kernel32.dll stdcall'; + +function InstalledExeReplaceable(Path: string): Boolean; +var + H: THandle; +begin + if not FileExists(Path) then + begin + Result := True; + Exit; + end; + { Require read/write on the target and forbid sharing while we check. + A loaded image, other process handle, filesystem permissions or AV + quarantine must prevent installation before any user files are changed. } + H := OpenExclusiveFile(Path, $C0000000, 0, 0, 3, $80, 0); + Result := H <> THandle(-1); + if Result then + CloseWinHandle(H); +end; + +function PrepareToInstall(var NeedsRestart: Boolean): String; +var + Target, HelperPath, PowerShellExe, Params: string; + ShutdownSignal: THandle; + Attempt, ExitCode: Integer; +begin + Result := ''; + Target := ExpandConstant('{app}\ArSonMix.exe'); + if not FileExists(Target) then + Exit; { first install: there is no existing exe to close } + + { First attempt: updated app receives its OWN graceful GUI-thread quit + event. Never signal on the audio callback or issue terminate/kill. } + ShutdownSignal := OpenEventW($0002, False, + 'Local\ArSonMix.InstallShutdown.v1'); + if ShutdownSignal <> 0 then + begin + if not SignalEvent(ShutdownSignal) then + begin + CloseWinHandle(ShutdownSignal); + Result := 'ArSonMix could not begin its safe session shutdown. Close the mixer normally and run Setup again. Your Studio files were not changed.'; + Exit; + end; + CloseWinHandle(ShutdownSignal); + for Attempt := 1 to 100 do + begin + if not CheckForMutexes('Local\ArSonMix.MixerRunning.v1') then + Break; + Sleep(200); + end; + end; + + { Critical legacy upgrade path: older ArSonMix versions do not own the + event or mutex above. Locate ONLY processes executing the exact + installation path, request WM_CLOSE and wait for the exit of ALL of them. + Doing this explicitly avoids showing Inno's late DeleteFile code 5 UI. } + ExtractTemporaryFile('ArSonMixUpdateShutdown.ps1'); + HelperPath := ExpandConstant('{tmp}\ArSonMixUpdateShutdown.ps1'); + PowerShellExe := ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'); + Params := '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File ' + + AddQuotes(HelperPath) + ' -TargetPath ' + AddQuotes(Target) + + ' -WaitSeconds 25'; + ExitCode := -1; + if not Exec(PowerShellExe, Params, '', SW_HIDE, + ewWaitUntilTerminated, ExitCode) then + begin + Result := 'Unable to check the running ArSonMix process before update. Close ArSonMix normally and run Setup again. No program files were replaced.'; + Exit; + end; + if ExitCode <> 0 then + begin + Log('ArSonMix legacy close preflight failed, helper exit=' + IntToStr(ExitCode)); + Result := 'ArSonMix is still running or its shutdown could not be verified. Close the mixer normally, save the session, then run Setup again. No program files were replaced.'; + Exit; + end; + + { An unrelated process (AV, backup, another plugin host) can still hold + the file even after ArSonMix exits. Test an EXCLUSIVE writable handle + before Inno begins updating anything. Fail closed, no Skip/Retry UI. } + if not InstalledExeReplaceable(Target) then + Result := 'ArSonMix.exe is still locked or Windows does not permit replacement. Close any running mixer, check Windows access permissions and retry Setup. Your Studio data and existing executable were not modified.'; +end; diff --git a/installer/ArSonMixUpdateShutdown.ps1 b/installer/ArSonMixUpdateShutdown.ps1 new file mode 100644 index 000000000..b6f3faf14 --- /dev/null +++ b/installer/ArSonMixUpdateShutdown.ps1 @@ -0,0 +1,92 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Inno-only preflight for UPGRADES FROM OLDER ARSONMIX VERSIONS. +# Never ships into the installed program directory. Never kills a process. +# Only sends WM_CLOSE to top-level windows whose owning process image is +# the EXACT ArSonMix.exe path being replaced. Other ArSonMix copies are safe. +param( + [Parameter(Mandatory=$true)][string]$TargetPath, + [ValidateRange(1,90)][int]$WaitSeconds=25 +) +Set-StrictMode -Version Latest +$ErrorActionPreference='Stop' +try { + $target=[System.IO.Path]::GetFullPath($TargetPath).TrimEnd([char]'\') + $name=[System.IO.Path]::GetFileNameWithoutExtension($target) + if($name -ne 'ArSonMix'){exit 30} + # Start with the native .NET process list, no taskkill, broad WM_CLOSE + # broadcasts, WMI process termination, or process-name-only shutdown. + function Get-TargetProcesses { + $found=@() + foreach($process in [System.Diagnostics.Process]::GetProcessesByName('ArSonMix')) { + try { + $path=$process.MainModule.FileName + if([string]::IsNullOrWhiteSpace($path)){ + throw 'No process image path' + } + $path=[System.IO.Path]::GetFullPath($path) + if([string]::Equals($path,$target,[System.StringComparison]::OrdinalIgnoreCase)) { + $found+=,$process + } else { + $process.Dispose() + } + } catch { + # Windows may restrict MainModule even for a readable name. + # Do not guess identity and NEVER close by process name only. + $process.Dispose() + } + } + return @($found) + } + $matches=@(Get-TargetProcesses) + if($matches.Count -eq 0){exit 0} + # Some JUCE versions have an ownerless top-level HWND; CloseMainWindow + # alone reports false. Match HWND -> PID before posting WM_CLOSE. + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +public static class ArSonMixInstallerWindowShutdown { + private delegate bool EnumProc(IntPtr hwnd, IntPtr unused); + [DllImport("user32.dll", SetLastError=true)] + private static extern bool EnumWindows(EnumProc callback, IntPtr unused); + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint pid); + [DllImport("user32.dll", SetLastError=true)] + private static extern bool PostMessage(IntPtr hwnd, uint message, IntPtr w, IntPtr l); + public static int CloseTopLevelWindows(int targetPid) { + int requested=0; + EnumWindows(delegate(IntPtr hwnd, IntPtr unused) { + uint owner; + GetWindowThreadProcessId(hwnd,out owner); + if(owner==(uint)targetPid && PostMessage(hwnd,0x0010,IntPtr.Zero,IntPtr.Zero)) + ++requested; + return true; + },IntPtr.Zero); + return requested; + } +} +'@ -ErrorAction Stop | Out-Null + foreach($process in $matches) { + try { + # JUCE handles WM_CLOSE on its message thread and can save session. + $mainWindowWasNotified=$process.CloseMainWindow() + if(-not $mainWindowWasNotified) { + $null=[ArSonMixInstallerWindowShutdown]::CloseTopLevelWindows($process.Id) + } + } finally {$process.Dispose()} + } + $end=[DateTime]::UtcNow.AddSeconds($WaitSeconds) + do { + Start-Sleep -Milliseconds 125 + $live=@(Get-TargetProcesses) + $count=$live.Count + foreach($process in $live){$process.Dispose()} + if($count -eq 0){exit 0} + } while([DateTime]::UtcNow -lt $end) + # A modal unsaved-edit prompt or hung mixer must remain untouched. + # Installer aborts BEFORE opening the target EXE for replacement. + exit 21 +} catch { + # Fail closed: the installer will not attempt to replace a possibly + # locked executable after an unverified shutdown operation. + exit 22 +} diff --git a/scripts/build_verify_windows_installer.ps1 b/scripts/build_verify_windows_installer.ps1 index 6cfab9f11..436fba3cb 100644 --- a/scripts/build_verify_windows_installer.ps1 +++ b/scripts/build_verify_windows_installer.ps1 @@ -9,15 +9,21 @@ $manifest=Get-Content -LiteralPath (Join-Path $dist "BUILD_PROVENANCE.json") -Ra $exe=Join-Path $dist "ArSonMix-GUI10CH-P012-Windows-x64.exe" $appHash=(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant() if($LASTEXITCODE -ne 0 -or $manifest.sourceCommit -ne $sha -or - $manifest.exeSha256 -ne $appHash -or $manifest.fatStatus -ne "EXPERIMENTAL_NOT_HARDWARE_QUALIFIED" -or + $manifest.exeSha256 -ne $appHash -or $manifest.fatStatus -ne "SOFTWARE_VERIFIED_PREVIEW_CANDIDATE" -or (Get-Item -LiteralPath $exe).Length -ne $manifest.guiExeBytes -or (Test-Path -LiteralPath (Join-Path $dist "Studio"))) { - throw "Installer requires the exact already verified and hardware-unqualified FAT PE" + throw "Installer requires an exact source-SHA software-verified Preview GUI PE" } $which=Get-Command ISCC.exe -ErrorAction SilentlyContinue $iscc=if($which){$which.Source}else{"C:\Program Files (x86)\Inno Setup 6\ISCC.exe"} if(-not (Test-Path -LiteralPath $iscc -PathType Leaf)){throw "Inno Setup 6 compiler missing"} $root=(Resolve-Path .).Path +# One authoritative product version: CMake native app and Inno Add/Remove Programs. +$cmake=(Get-Content -LiteralPath (Join-Path $root "CMakeLists.txt") -Raw -Encoding UTF8) +if($cmake -notmatch '(?m)^project\(ARMixConsole VERSION ([0-9]+\.[0-9]+\.[0-9]+) LANGUAGES'){ + throw "Installer version does not match the native CMake project" +} +$appVersion=$Matches[1] $out=Join-Path $root $InstallerOutput New-Item -ItemType Directory -Force -Path $out | Out-Null $stage=Join-Path $env:RUNNER_TEMP ("arsonmix-install-stage-"+[guid]::NewGuid().ToString("N")) @@ -26,6 +32,9 @@ $studio=Join-Path $env:APPDATA "AR-MIX-Studio" New-Item -ItemType Directory -Force -Path $studio | Out-Null $sentinel=Join-Path $studio ("installer-test-"+[guid]::NewGuid().ToString("N")+".keep") "persistent-private-data" | Set-Content -LiteralPath $sentinel +$fixtureReady=Join-Path $env:RUNNER_TEMP ("arsonmix-fixture-ready-"+[guid]::NewGuid().ToString("N")) +$fixtureClosed=Join-Path $env:RUNNER_TEMP ("arsonmix-fixture-closed-"+[guid]::NewGuid().ToString("N")) +$fixtureProcess=$null try { New-Item -ItemType Directory -Force -Path $stage | Out-Null Copy-Item -LiteralPath $exe -Destination (Join-Path $stage "verified-gui.exe") @@ -37,8 +46,8 @@ try { if(Test-Path -LiteralPath $factory -PathType Container){ Copy-Item -LiteralPath $factory -Destination (Join-Path $stage "FactoryFX") -Recurse } - & $iscc "/Qp" "/DSourceRoot=$stage" "/DOutputRoot=$out" "installer/ArSonMix.iss" - $setup=Join-Path $out "ArSonMix-Windows-x64-Setup-UNQUALIFIED.exe" + & $iscc "/Qp" "/DSourceRoot=$stage" "/DOutputRoot=$out" "/DSourceAppVersion=$appVersion" "installer/ArSonMix.iss" + $setup=Join-Path $out "ArSonMix-Windows-x64-Setup-Preview.exe" if($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $setup -PathType Leaf) -or (Get-Item -LiteralPath $setup).Length -lt 2MB){throw "ISCC failed to build installer RC"} $start=Start-Process -FilePath $setup -ArgumentList @( @@ -53,6 +62,61 @@ try { } $installedManifest=Get-Content -LiteralPath (Join-Path $install "BUILD_PROVENANCE.json") -Raw -Encoding UTF8 | ConvertFrom-Json if($installedManifest.sourceCommit -ne $sha){throw "Wrong installed provenance"} + # REAL Windows in-place UPDATE test: replace the *test-installed* PE + # with a harmless WinForms window. Installer must ask it to WM_CLOSE, + # observe the graceful close marker, replace its running .exe with the + # verified FAT PE and preserve private Studio plus unknown user files. + # This never replaces the source FAT executable or touches a user install. + $csc=Join-Path $env:WINDIR "Microsoft.NET\Framework\v4.0.30319\csc.exe" + $fixtureSource=Join-Path $root "tests\fixtures\installer_graceful_close.cs" + if(-not (Test-Path -LiteralPath $csc -PathType Leaf) -or + -not (Test-Path -LiteralPath $fixtureSource -PathType Leaf)){ + throw "Windows Framework C# compiler or WM_CLOSE fixture missing" + } + & $csc "/nologo" "/target:winexe" "/reference:System.Windows.Forms.dll" "/out:$installedExe" $fixtureSource + if($LASTEXITCODE -ne 0){throw "Cannot prepare graceful-close test window"} + $fixtureProcess=Start-Process -FilePath $installedExe -ArgumentList @( + ('"' + $fixtureReady + '"'), ('"' + $fixtureClosed + '"') + ) -PassThru + for($i=0;$i -lt 75 -and -not (Test-Path -LiteralPath $fixtureReady);$i++){ + $fixtureProcess.Refresh() + if($fixtureProcess.HasExited){break} + Start-Sleep -Milliseconds 200 + } + if(-not (Test-Path -LiteralPath $fixtureReady)){ + throw "Installed upgrade fixture did not show its Windows message-loop window" + } + $installSentinel=Join-Path $install "arsonmix-user-file.keep" + "preserve-user-files-across-upgrade" | Set-Content -LiteralPath $installSentinel + $upgradeLog=Join-Path $env:RUNNER_TEMP ("arsonmix-upgrade-"+[guid]::NewGuid().ToString("N")+".log") + $upgrade=Start-Process -FilePath $setup -ArgumentList @( + "/VERYSILENT","/SUPPRESSMSGBOXES","/NORESTART","/CURRENTUSER", + "/NOCLOSEAPPLICATIONS", + "/DIR=$install",('/LOG="' + $upgradeLog + '"') + ) -Wait -PassThru + $fixtureProcess.Refresh() + $closeMarker=Test-Path -LiteralPath $fixtureClosed + $closeText=if($closeMarker){(Get-Content -LiteralPath $fixtureClosed -Raw).Trim()}else{"MISSING"} + $installedAfter=(Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash.ToLowerInvariant() + Write-Host "INNO_UPGRADE_DIAG: installerExit=$($upgrade.ExitCode) oldProcessExited=$($fixtureProcess.HasExited) gracefulMarker=$closeText restoredExeShaOk=$($installedAfter -eq $appHash)" + $acceptedSaves=@("WM_CLOSE_SAVED","RM_QUERY_SAVED","RM_ENDSESSION_SAVED","INSTALLER_HANDSHAKE_SAVED") + if($upgrade.ExitCode -ne 0 -or -not $fixtureProcess.HasExited -or + -not $closeMarker -or -not ($acceptedSaves -contains $closeText)){ + if(Test-Path -LiteralPath $upgradeLog){ + Get-Content -LiteralPath $upgradeLog | + Select-String -Pattern 'Restart Manager|close application|closing application|file in use|ArSonMix|error|installing' | + Select-Object -Last 45 | + ForEach-Object {Write-Host "INNO_RESTART_MANAGER_LOG: $($_.Line)"} + } + throw "In-place update did not gracefully close the running ArSonMix fixture (see $upgradeLog)" + } + if((Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash.ToLowerInvariant() -ne $appHash -or + -not (Test-Path -LiteralPath $installSentinel) -or + -not (Test-Path -LiteralPath $sentinel) -or + (Test-Path -LiteralPath (Join-Path $install "portable_mode.txt"))){ + throw "In-place update failed verified EXE replacement or data preservation" + } + Write-Host "INNO_GRACEFUL_UPDATE_PASS: running app Windows session close, verified PE replacement, user files preserved" $uninstall=Join-Path $install "unins000.exe" if(-not (Test-Path -LiteralPath $uninstall -PathType Leaf)){throw "Uninstaller missing"} $stop=Start-Process -FilePath $uninstall -ArgumentList @( @@ -62,14 +126,29 @@ try { throw "Uninstaller failed or erased user Studio data" } [ordered]@{ - sourceCommit=$sha;guiSha256=$appHash + sourceCommit=$sha;appVersion=$appVersion;guiSha256=$appHash installerSha256=(Get-FileHash -LiteralPath $setup -Algorithm SHA256).Hash.ToLowerInvariant() - certification="UNSIGNED_HARDWARE_FAT_PENDING";mode="PER_USER_NO_AUTOARM" + certification="PREVIEW__INSTALLER_INTEGRITY_AND_UPDATE_TESTED";mode="PER_USER_NO_AUTOARM" + updaterTest="WM_CLOSE_IN_PLACE_SHA256_AND_USER_DATA_PRESERVED" } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $out "INSTALLER_PROVENANCE.json") -Encoding UTF8 - Write-Host "INSTALLER_RC_VERIFIED: SHA-matched PE, install/uninstall, private Studio intact" - Write-Host "PHYSICAL_FAT_PENDING" + Write-Host "INSTALLER_RC_VERIFIED: first install, graceful running-app graceful update, SHA-matched PE, uninstall, private Studio intact" + Write-Host "OWNER_FIELD_AUDIO_LISTENING_REPORTED__PER_BUILD_HARDWARE_REPORT_SEPARATE" } finally { + # Only a failing *test fixture* may be terminated in CI teardown. + # Production Inno Setup never force-kills the user's audio application. + if($null -ne $fixtureProcess){ + try{ + $fixtureProcess.Refresh() + if(-not $fixtureProcess.HasExited){ + Stop-Process -Id $fixtureProcess.Id -Force -ErrorAction SilentlyContinue + } + }catch{} + $fixtureProcess.Dispose() + } + foreach($marker in @($fixtureReady,$fixtureClosed)){ + if(Test-Path -LiteralPath $marker){Remove-Item -LiteralPath $marker -Force} + } if(Test-Path -LiteralPath $sentinel){Remove-Item -LiteralPath $sentinel -Force} if(Test-Path -LiteralPath $stage){Remove-Item -LiteralPath $stage -Recurse -Force} if(Test-Path -LiteralPath $install){Remove-Item -LiteralPath $install -Recurse -Force -ErrorAction SilentlyContinue} diff --git a/scripts/collect_hardware_fat_windows.ps1 b/scripts/collect_hardware_fat_windows.ps1 index 731da9e44..2dbd9b552 100644 --- a/scripts/collect_hardware_fat_windows.ps1 +++ b/scripts/collect_hardware_fat_windows.ps1 @@ -39,7 +39,7 @@ function Get-FatSha256([string] $Path) { $manifestPath=Join-Path $root 'BUILD_PROVENANCE.json' if (-not (Test-Path -LiteralPath $manifestPath -PathType Leaf)) { throw 'Missing BUILD_PROVENANCE.json: extract the complete verified Windows FAT ZIP first' } $m=Get-Content -LiteralPath $manifestPath -Raw -Encoding UTF8 | ConvertFrom-Json -if ([string]$m.fatStatus -ne 'EXPERIMENTAL_NOT_HARDWARE_QUALIFIED') { throw 'Unexpected hardware qualification claim' } +if ([string]$m.fatStatus -ne 'SOFTWARE_VERIFIED_PREVIEW_CANDIDATE') { throw 'Unexpected hardware qualification claim' } if ([string]$m.sourceCommit -notmatch '^[a-f0-9]{40}$') { throw 'Invalid exact source SHA' } if ([string]$m.fatCollectorSha256 -notmatch '^[a-f0-9]{64}$') { throw 'Missing FAT collector provenance' } $selfHash=(Get-FatSha256 -Path $PSCommandPath) @@ -84,7 +84,7 @@ function Parse-Pins([string]$raw) { } if ($Action -eq 'Verify') { Write-Host ('FAT PACKAGE OK; build='+$m.sourceCommit+'; EXE SHA256='+$exeHash) - Write-Host 'UNQUALIFIED 10CH/4AUX candidate. No sound, device, latency or hardware result has been tested.' + Write-Host 'ArSonMix 10CH/4AUX Preview: software integrity verified. Owner has reported real audio listening; this tool does not attest exact-build hardware measurements.' exit 0 } $j=Read-Journal diff --git a/scripts/m3e_fat_evidence_gate.mjs b/scripts/m3e_fat_evidence_gate.mjs index f2b71634a..14bf14f54 100644 --- a/scripts/m3e_fat_evidence_gate.mjs +++ b/scripts/m3e_fat_evidence_gate.mjs @@ -57,7 +57,7 @@ export function inspectM3ePackage(root){ !HEX64.test(manifest.approvedGuiPagesSha256||'')|| !HEX64.test(manifest.approvedGuiNativeHtmlSha256||'')|| !HEX64.test(manifest.approvedGuiManifestSha256||'')|| - manifest.fatStatus!=='EXPERIMENTAL_NOT_HARDWARE_QUALIFIED') + manifest.fatStatus!=='SOFTWARE_VERIFIED_PREVIEW_CANDIDATE') throw Error('Source/GUI/qualification manifest is not approved and fail-closed'); const exe=readExact(p,manifest.executable,manifest.exeSha256); checkPe64Gui(exe); diff --git a/scripts/package_native_windows.ps1 b/scripts/package_native_windows.ps1 index 1e6390bdc..3ed1cda9a 100644 --- a/scripts/package_native_windows.ps1 +++ b/scripts/package_native_windows.ps1 @@ -105,7 +105,7 @@ $manifest = [ordered]@{ schema = "arsonmix.native-artifact-provenance.v1" sourceCommit = $gitSha gui = "10 SOURCE CHANNELS + STEREO MASTER (PR #73)" - engine = "R0B VERIFIED DIRECT 10CH PLUS FOUR AUX PREPARED NATIVE MIXER__HARDWARE_FAT_UNQUALIFIED" + engine = "R0B VERIFIED DIRECT 10CH PLUS FOUR AUX PREPARED NATIVE MIXER__PREVIEW" nativeDSP = "NATIVE_TEN_INPUT_CHANNELS_FOUR_DEDICATED_STEREO_AUX_RETURNS_MASTER__EXPLICIT_PATCH_ACK" storageMode = "PORTABLE_MARKER__USER_STUDIO_EMPTY_AT_RELEASE" guiExeBytes = $appBytes @@ -133,7 +133,7 @@ $manifest = [ordered]@{ approvedGuiSource = "site/preview-v2 DOM + site/preview-buttons approved PNG skin (deterministic JUCE BinaryData)" approvedGuiAdapterStatus = "SCAFFOLD_ONLY__NOT_LIVE_PCM" guiCalibration = "APPROVED_PAGES_VISUAL_PROVENANCE_ONLY__M1_NOT_PRODUCT_READY" - fatStatus = "EXPERIMENTAL_NOT_HARDWARE_QUALIFIED" + fatStatus = "SOFTWARE_VERIFIED_PREVIEW_CANDIDATE" note = "No assertion of clean 0-FX sound, measured round-trip latency or native render-hardware XRUN." } $manifest | ConvertTo-Json -Depth 3 | Set-Content -LiteralPath (Join-Path $OutputDir "BUILD_PROVENANCE.json") -Encoding utf8 diff --git a/scripts/test_inno_graceful_update_windows.ps1 b/scripts/test_inno_graceful_update_windows.ps1 new file mode 100644 index 000000000..831bddb11 --- /dev/null +++ b/scripts/test_inno_graceful_update_windows.ps1 @@ -0,0 +1,140 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Fast Windows Inno/Restart Manager smoke, independent of JUCE. +# The staged .exe is a test-only WinForms window, NOT a product release. +Set-StrictMode -Version Latest +$ErrorActionPreference="Stop" +$root=(Resolve-Path .).Path +$work=Join-Path $env:RUNNER_TEMP ("arsonmix-inno-smoke-"+[guid]::NewGuid().ToString("N")) +$stage=Join-Path $work "stage" +$out=Join-Path $work "compiled" +$install=Join-Path $work "installed" +$ready=Join-Path $work "ready.marker" +$closed=Join-Path $work "closed.marker" +$log=Join-Path $work "upgrade.log" +$studio=Join-Path $env:APPDATA "AR-MIX-Studio" +$fixtureProcess=$null +$privateSentinel=Join-Path $studio ("installer-smoke-"+[guid]::NewGuid().ToString("N")+".keep") + +function Assert-Condition([bool]$condition,[string]$message) { + if(-not $condition){throw $message} +} +function Show-UpgradeDiagnostics([string]$logFile){ + if(Test-Path -LiteralPath $logFile){ + Get-Content -LiteralPath $logFile | + Select-String -Pattern 'Restart Manager|close application|closing application|file in use|ArSonMix|error|installing' | + Select-Object -Last 45 | + ForEach-Object {Write-Host "INNO_RESTART_MANAGER_LOG: $($_.Line)"} + }else{Write-Host "INNO_RESTART_MANAGER_LOG_MISSING"} +} +try { + New-Item -ItemType Directory -Force -Path $stage,$out,$install,$studio | Out-Null + "private-user-data" | Set-Content -LiteralPath $privateSentinel + $csc=Join-Path $env:WINDIR "Microsoft.NET/Framework/v4.0.30319/csc.exe" + Assert-Condition (Test-Path -LiteralPath $csc -PathType Leaf) "Windows C# compiler missing" + & $csc "/nologo" "/target:winexe" "/reference:System.Windows.Forms.dll" "/out:$(Join-Path $stage 'verified-gui.exe')" (Join-Path $root "tests/fixtures/installer_graceful_close.cs") + Assert-Condition ($LASTEXITCODE -eq 0) "Test-only WinForms fixture failed to compile" + Copy-Item -LiteralPath (Join-Path $root "assets/icon/arsonmix-app.ico") -Destination (Join-Path $stage "arsonmix-app.ico") + "Test-only installer mechanics fixture" | Set-Content -LiteralPath (Join-Path $stage "README.md") + '{"sourceCommit":"TEST_FIXTURE_ONLY","fatStatus":"NOT_A_PRODUCT"}' | Set-Content -LiteralPath (Join-Path $stage "BUILD_PROVENANCE.json") + $found=Get-Command ISCC.exe -ErrorAction SilentlyContinue + $iscc=if($found){$found.Source}else{"C:\Program Files (x86)\Inno Setup 6\ISCC.exe"} + Assert-Condition (Test-Path -LiteralPath $iscc -PathType Leaf) "ISCC.exe missing" + & $iscc "/Qp" "/DSourceRoot=$stage" "/DOutputRoot=$out" "/DSourceAppVersion=0.5.0" (Join-Path $root "installer/ArSonMix.iss") + Assert-Condition ($LASTEXITCODE -eq 0) "Cannot compile Inno fixture setup" + $setup=Join-Path $out "ArSonMix-Windows-x64-Setup-Preview.exe" + Assert-Condition (Test-Path -LiteralPath $setup -PathType Leaf) "Compiled Inno test installer missing" + $setupArgs=@("/VERYSILENT","/SUPPRESSMSGBOXES","/NORESTART","/CURRENTUSER","/NOCLOSEAPPLICATIONS","/DIR=$install") + $first=Start-Process -FilePath $setup -ArgumentList $setupArgs -Wait -PassThru + Assert-Condition ($first.ExitCode -eq 0) ("First test install exit="+$first.ExitCode) + $installedExe=Join-Path $install "ArSonMix.exe" + Assert-Condition (Test-Path -LiteralPath $installedExe -PathType Leaf) "Installed fixture missing" + $fixtureHash=(Get-FileHash -LiteralPath (Join-Path $stage "verified-gui.exe") -Algorithm SHA256).Hash + Assert-Condition ((Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash -eq $fixtureHash) "First install changed test executable bytes" + $userFile=Join-Path $install "user-file.keep" + "user-file-must-survive" | Set-Content -LiteralPath $userFile + $fixtureProcess=Start-Process -FilePath $installedExe -ArgumentList @(('"' + $ready + '"'),('"' + $closed + '"')) -PassThru + for($i=0;$i -lt 60 -and -not (Test-Path -LiteralPath $ready);$i++){ + $fixtureProcess.Refresh() + if($fixtureProcess.HasExited){break} + Start-Sleep -Milliseconds 200 + } + Assert-Condition (Test-Path -LiteralPath $ready) "Fixture window did not start" + $upgrade=Start-Process -FilePath $setup -ArgumentList ($setupArgs + @('/LOG="' + $log + '"')) -Wait -PassThru + $fixtureProcess.Refresh() + $exited=$fixtureProcess.HasExited + $marker=Test-Path -LiteralPath $closed + $markerText=if($marker){(Get-Content -LiteralPath $closed -Raw).Trim()}else{"MISSING"} + $newHash=(Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash + Write-Host "INNO_UPGRADE_DIAG exit=$($upgrade.ExitCode) exited=$exited marker=$markerText hashOk=$($newHash -eq $fixtureHash)" + Show-UpgradeDiagnostics $log + Assert-Condition ($upgrade.ExitCode -eq 0) "Silent Inno upgrade returned error" + $acceptedSaves=@("WM_CLOSE_SAVED","RM_QUERY_SAVED","RM_ENDSESSION_SAVED","INSTALLER_HANDSHAKE_SAVED") + Assert-Condition ($exited -and $marker -and ($acceptedSaves -contains $markerText)) "Inno did not request a saved, graceful Windows session close" + Assert-Condition ($newHash -eq $fixtureHash) "Updated installed fixture hash mismatch" + Assert-Condition ((Test-Path -LiteralPath $userFile) -and (Test-Path -LiteralPath $privateSentinel)) "Update removed user data" + # Upgrade from a PRE-HANDSHAKE ArSonMix.exe, exactly the case the old + # test omitted and which caused DeleteFile failed; code 5 in the field. + # Its FormClosing marker proves an old GUI was asked to quit normally. + Remove-Item -LiteralPath $ready,$closed -Force -ErrorAction SilentlyContinue + $fixtureProcess=Start-Process -FilePath $installedExe -ArgumentList @( + ('"' + $ready + '"'),('"' + $closed + '"'),"legacy") -PassThru + for($i=0;$i -lt 75 -and -not (Test-Path -LiteralPath $ready);$i++){ + $fixtureProcess.Refresh() + if($fixtureProcess.HasExited){break} + Start-Sleep -Milliseconds 200 + } + Assert-Condition (Test-Path -LiteralPath $ready) "Legacy pre-handshake fixture never became ready" + Assert-Condition ((Get-Content -LiteralPath $ready -Raw).Trim() -eq "WINDOW_READY_LEGACY") "Legacy fixture did not receive mode argument" + $legacy=Start-Process -FilePath $setup -ArgumentList ($setupArgs + @('/LOG="' + (Join-Path $work 'legacy-upgrade.log') + '"')) -Wait -PassThru + $fixtureProcess.Refresh() + $legacyMarker=if(Test-Path -LiteralPath $closed){(Get-Content -LiteralPath $closed -Raw).Trim()}else{"MISSING"} + Write-Host "INNO_LEGACY_DIAG exit=$($legacy.ExitCode) exited=$($fixtureProcess.HasExited) marker=$legacyMarker" + Assert-Condition ($legacy.ExitCode -eq 0 -and $fixtureProcess.HasExited) "Legacy running GUI did not close before EXE replacement" + Assert-Condition ($legacyMarker -eq "WM_CLOSE_SAVED") "Legacy GUI did not receive WM_CLOSE and save" + Assert-Condition ((Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash -eq $fixtureHash) "Legacy upgrade changed verified EXE hash" + Assert-Condition ((Test-Path -LiteralPath $userFile) -and (Test-Path -LiteralPath $privateSentinel)) "Legacy upgrade damaged Studio/user files" + Write-Host "INNO_LEGACY_NO_HANDSHAKE_UPGRADE_PASS: exact exe process requested WM_CLOSE before replacement" + $fixtureProcess.Dispose();$fixtureProcess=$null + + # Busy/hung GUI: it REFUSES WM_CLOSE and has no newer handshake. + # Upgrade must fail before [Files], leave old EXE and Studio untouched. + Remove-Item -LiteralPath $ready,$closed -Force -ErrorAction SilentlyContinue + $fixtureProcess=Start-Process -FilePath $installedExe -ArgumentList @( + ('"' + $ready + '"'),('"' + $closed + '"'),"blocked") -PassThru + for($i=0;$i -lt 75 -and -not (Test-Path -LiteralPath $ready);$i++){ + $fixtureProcess.Refresh() + if($fixtureProcess.HasExited){break} + Start-Sleep -Milliseconds 200 + } + Assert-Condition (Test-Path -LiteralPath $ready) "Unresponsive fixture never became ready" + Assert-Condition ((Get-Content -LiteralPath $ready -Raw).Trim() -eq "WINDOW_READY_BLOCKED") "Unresponsive fixture did not receive block mode argument" + $blocked=Start-Process -FilePath $setup -ArgumentList ($setupArgs + @('/LOG="' + (Join-Path $work 'blocked-upgrade.log') + '"')) -Wait -PassThru + $fixtureProcess.Refresh() + Write-Host "INNO_BLOCKED_DIAG exit=$($blocked.ExitCode) stillRunning=$(-not $fixtureProcess.HasExited)" + Show-UpgradeDiagnostics (Join-Path $work 'blocked-upgrade.log') + Assert-Condition ($blocked.ExitCode -ne 0 -and -not $fixtureProcess.HasExited) "Installer improperly replaced a live GUI that refused to close" + Assert-Condition ((Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash -eq $fixtureHash) "Blocked upgrade unexpectedly modified installed EXE" + Assert-Condition ((Test-Path -LiteralPath $userFile) -and (Test-Path -LiteralPath $privateSentinel)) "Blocked upgrade removed personal files" + Assert-Condition (-not (Test-Path -LiteralPath $closed)) "Blocked fixture unexpectedly wrote a saved-close marker" + Write-Host "INNO_BLOCKED_FAIL_CLOSED_PASS: live process stays running, no overwrite, Studio intact" + Stop-Process -Id $fixtureProcess.Id -Force -ErrorAction Stop # TEST-ONLY synthetic fixture teardown + $fixtureProcess.Dispose();$fixtureProcess=$null + + $uninstaller=Join-Path $install "unins000.exe" + Assert-Condition (Test-Path -LiteralPath $uninstaller) "Uninstaller missing" + $uninstall=Start-Process -FilePath $uninstaller -ArgumentList @("/VERYSILENT","/SUPPRESSMSGBOXES","/NORESTART") -Wait -PassThru + Assert-Condition ($uninstall.ExitCode -eq 0) "Uninstall failed" + Assert-Condition (Test-Path -LiteralPath $privateSentinel) "Uninstall erased Studio" + Write-Host "INNO_GRACEFUL_SMOKE_PASS: handshake + legacy GUI close, hung GUI fail-closed, same-path SHA, Studio retention, uninstall" +} finally { + # Test-only cleanup; never used by production Inno Setup. + if($null -ne $fixtureProcess){ + try{ + $fixtureProcess.Refresh() + if(-not $fixtureProcess.HasExited){Stop-Process -Id $fixtureProcess.Id -Force -ErrorAction SilentlyContinue} + }catch{} + $fixtureProcess.Dispose() + } + if(Test-Path -LiteralPath $privateSentinel){Remove-Item -LiteralPath $privateSentinel -Force} + if(Test-Path -LiteralPath $work){Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue} +} diff --git a/src/Main.cpp b/src/Main.cpp index c31dcdf05..efc9942cc 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -4035,6 +4035,16 @@ class ConsoleApp final : public juce::JUCEApplication, private juce::Timer } void initialise (const juce::String&) override { +#if defined(_WIN32) + // Per-user-session installer handshake. An Inno update requests the + // ordinary JUCE quit path on the MESSAGE thread: the native mixer + // persists accepted .smix state before the installer replaces the PE. + // Never signal from the audio callback or terminate the process. + updateRunningMutex_ = ::CreateMutexW (nullptr, FALSE, + L"Local\\ArSonMix.MixerRunning.v1"); + installerShutdownEvent_ = ::CreateEventW (nullptr, TRUE, FALSE, + L"Local\\ArSonMix.InstallShutdown.v1"); +#endif // Paint the approved dark native splash BEFORE browser cache I/O, // WebView2 initialization, device scan or native console construction. splash_ = std::make_unique(); @@ -4042,7 +4052,23 @@ class ConsoleApp final : public juce::JUCEApplication, private juce::Timer } void timerCallback() override { - stopTimer(); +#if defined(_WIN32) + if (installerShutdownEvent_ != nullptr && + ::WaitForSingleObject (installerShutdownEvent_, 0) == WAIT_OBJECT_0) + { + stopTimer(); + // This reaches shutdown() -> window_.reset() -> + // ConsoleWindow::~ConsoleWindow() -> saveMixerSession(). + systemRequestedQuit(); + return; + } +#endif + if (startupAttempted_) + return; + startupAttempted_ = true; + // Remain active only as a lightweight update handshake (4 Hz). + // Do not touch audio-device selection, callback, or GUI geometry. + startTimer (250); const auto folder = armix::storage::PortableWorkspace::browserDataRoot(); if (!folder.createDirectory().wasOk() && !folder.isDirectory()) { @@ -4078,8 +4104,25 @@ class ConsoleApp final : public juce::JUCEApplication, private juce::Timer stopTimer(); window_.reset(); splash_.reset(); +#if defined(_WIN32) + if (installerShutdownEvent_ != nullptr) + { + ::CloseHandle (installerShutdownEvent_); + installerShutdownEvent_ = nullptr; + } + if (updateRunningMutex_ != nullptr) + { + ::CloseHandle (updateRunningMutex_); + updateRunningMutex_ = nullptr; + } +#endif } private: + bool startupAttempted_ = false; +#if defined(_WIN32) + HANDLE updateRunningMutex_ = nullptr; + HANDLE installerShutdownEvent_ = nullptr; +#endif std::unique_ptr splash_; std::unique_ptr window_; }; diff --git a/tests/direct_restore_recovery_contract_test.mjs b/tests/direct_restore_recovery_contract_test.mjs index 6139a50f0..f9e1ec018 100644 --- a/tests/direct_restore_recovery_contract_test.mjs +++ b/tests/direct_restore_recovery_contract_test.mjs @@ -59,7 +59,7 @@ test('verified native FAT package preserves actual beta live-bridge provenance, assert.match(fatGuide,/Do not enable beta independent clocks/); assert.match(fatGuide,/ASRC_INPUT_UNDERFLOW_FRAMES/); assert.ok(packaging.includes('HARDWARE_FAT_GUIDE.md')); - assert.match(packaging,/EXPERIMENTAL_NOT_HARDWARE_QUALIFIED/); + assert.match(packaging,/SOFTWARE_VERIFIED_PREVIEW_CANDIDATE/); assert.doesNotMatch(packaging,/An offline adaptive dual-clock FIR bridge is tested in CI but NOT connected/); }); diff --git a/tests/fixtures/installer_graceful_close.cs b/tests/fixtures/installer_graceful_close.cs new file mode 100644 index 000000000..1ef48ad64 --- /dev/null +++ b/tests/fixtures/installer_graceful_close.cs @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Windows FAT-only test double for the installed ArSonMix.exe. +// Never shipped. Observe Restart Manager's Windows session-close protocol, +// not just FormClosing: RM may send WM_QUERYENDSESSION/WM_ENDSESSION before +// it ever sends WM_CLOSE. Test only passes when a durable marker was written +// by one of those cooperative message handlers AND the process has exited. +using System; +using System.IO; +using System.Windows.Forms; + +internal static class ArSonMixInstallerGracefulCloseFixture +{ + private sealed class MixerWindow : Form + { + private readonly string savedMarker; + private readonly bool blockClose; + private readonly System.Threading.Mutex runningMutex; + private readonly System.Threading.EventWaitHandle shutdownEvent; + private readonly System.Windows.Forms.Timer shutdownPoll; + private const int WM_QUERYENDSESSION = 0x0011; + private const int WM_ENDSESSION = 0x0016; + + public MixerWindow(string marker, bool legacy, bool blockClose) + { + savedMarker = marker; + this.blockClose = blockClose; + Text = "ArSonMix Upgrade Graceful-Close FAT Fixture"; + Width = 420; + Height = 120; + ShowInTaskbar = false; + // The production mixer creates exactly these same per-session + // handles. Inno signals the event and waits for the mutex to go + // away after the accepted mixer session has been saved. + if (!legacy) + { + runningMutex = new System.Threading.Mutex(false, + @"Local\ArSonMix.MixerRunning.v1"); + shutdownEvent = new System.Threading.EventWaitHandle(false, + System.Threading.EventResetMode.ManualReset, + @"Local\ArSonMix.InstallShutdown.v1"); + shutdownPoll = new System.Windows.Forms.Timer(); + shutdownPoll.Interval = 50; + shutdownPoll.Tick += (sender, e) => + { + if (!shutdownEvent.WaitOne(0)) return; + shutdownPoll.Stop(); + File.WriteAllText(savedMarker, "INSTALLER_HANDSHAKE_SAVED"); + Close(); + }; + shutdownPoll.Start(); + } + } + + protected override void OnFormClosed(FormClosedEventArgs e) + { + if (shutdownPoll != null) { shutdownPoll.Stop(); shutdownPoll.Dispose(); } + if (shutdownEvent != null) shutdownEvent.Dispose(); + if (runningMutex != null) runningMutex.Dispose(); + base.OnFormClosed(e); + } + + protected override void WndProc(ref Message m) + { + // JUCE's Windows peer dispatches WM_QUERYENDSESSION to + // JUCEApplication::systemRequestedQuit(), which saves the mixer + // when ConsoleWindow is destructed. Simulate the durable save + // at the corresponding OS request, not an abrupt termination. + if (blockClose && (m.Msg == WM_QUERYENDSESSION || m.Msg == WM_ENDSESSION)) + { + m.Result = IntPtr.Zero; // Test only: reject OS close as well as WM_CLOSE. + return; + } + if (m.Msg == WM_QUERYENDSESSION) + File.WriteAllText(savedMarker, "RM_QUERY_SAVED"); + else if (m.Msg == WM_ENDSESSION && m.WParam != IntPtr.Zero) + File.WriteAllText(savedMarker, "RM_ENDSESSION_SAVED"); + base.WndProc(ref m); + } + + protected override void OnFormClosing(FormClosingEventArgs e) + { + if (blockClose) { e.Cancel = true; return; } + if (!File.Exists(savedMarker)) + File.WriteAllText(savedMarker, "WM_CLOSE_SAVED"); + base.OnFormClosing(e); + } + } + + [STAThread] + private static void Main(string[] args) + { + if (args.Length != 2 && args.Length != 3) + Environment.Exit(22); + bool legacy = args.Length == 3 && (args[2] == "legacy" || args[2] == "blocked"); + bool blockClose = args.Length == 3 && args[2] == "blocked"; + if (blockClose) + { + // Test-only locked EXE with no usable GUI window: WM_CLOSE can + // never be acknowledged. The installer MUST abort before [Files]. + File.WriteAllText(args[0], "WINDOW_READY_BLOCKED"); + System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); + return; + } + + using (var window = new MixerWindow(args[1], legacy, blockClose)) + { + window.Shown += (sender, e) => File.WriteAllText(args[0], + blockClose ? "WINDOW_READY_BLOCKED" : legacy ? "WINDOW_READY_LEGACY" : "WINDOW_READY"); + Application.Run(window); + } + } +} diff --git a/tests/m3e_fat_evidence_gate.test.mjs b/tests/m3e_fat_evidence_gate.test.mjs index 18ed40a12..fecf478ad 100644 --- a/tests/m3e_fat_evidence_gate.test.mjs +++ b/tests/m3e_fat_evidence_gate.test.mjs @@ -34,7 +34,7 @@ function makePackage(dir){ approvedGuiRoute:'/preview/',approvedGuiOutput:'preview/index.html', approvedGuiPagesSha256:'1'.repeat(64),approvedGuiNativeHtmlSha256:'2'.repeat(64), approvedGuiManifestSha256:'3'.repeat(64), - fatStatus:'EXPERIMENTAL_NOT_HARDWARE_QUALIFIED', + fatStatus:'SOFTWARE_VERIFIED_PREVIEW_CANDIDATE', fatCollectorSha256:sha(collector),fatGateSha256:sha(gate)}; const save=()=>writeFileSync(join(dir,'BUILD_PROVENANCE.json'),JSON.stringify(m)); save();return {m,save,exe,collector}; diff --git a/tests/native_artifact_packaging_contract_test.mjs b/tests/native_artifact_packaging_contract_test.mjs index eacc94ebd..b38b60924 100644 --- a/tests/native_artifact_packaging_contract_test.mjs +++ b/tests/native_artifact_packaging_contract_test.mjs @@ -118,9 +118,9 @@ test('native bridge authenticates UI readiness but never hallucinates PCM/VST3 L assert.match(verify,/WEBVIEW2_GUI_READY_TIMEOUT/); }); -test('physical 10CH+4AUX runtime remains hardware-unqualified, no fake UAT',()=>{ +test('physical 10CH+4AUX Preview build does not invent independent hardware certification',()=>{ assert.match(packaging,/NATIVE_TEN_INPUT_CHANNELS_FOUR_DEDICATED_STEREO_AUX_RETURNS_MASTER__EXPLICIT_PATCH_ACK/); - assert.match(packaging,/HARDWARE_FAT_UNQUALIFIED/); + assert.match(packaging,/PREVIEW/); assert.match(verify,/NATIVE_TEN_INPUT_CHANNELS_FOUR_DEDICATED_STEREO_AUX_RETURNS_MASTER__EXPLICIT_PATCH_ACK/); assert.doesNotMatch(packaging,/CHANNEL_1_ONLY__REMAINING_9_GUI_CHANNELS_NOT_REAL_AUDIO/); for(const marker of [ @@ -152,7 +152,7 @@ test('M3-E same-SHA native ZIP carries SHA-pinned FAT tools and no fake hardware assert.match(v,/FAT tool ZIP payload digest differs/); assert.match(v,/scripts\/m3e_fat_evidence_gate\.mjs/); assert.match(collector,/FAT_RUNS\.json/); - assert.match(collector,/EXPERIMENTAL_NOT_HARDWARE_QUALIFIED/); + assert.match(collector,/SOFTWARE_VERIFIED_PREVIEW_CANDIDATE/); assert.match(collector,/physicalAudibilityVerifiedBySoftware=\$false/); assert.match(checker,/PENDING_NATIVE_CALLBACK_PROOF/); assert.match(checker,/EVIDENCE_READY_FOR_HUMAN_REVIEW/); diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index cefe9ee4b..7ba654b07 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -1,24 +1,114 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import {readFileSync} from 'node:fs'; -const read=p=>readFileSync(p,'utf8'); -const iss=read('installer/ArSonMix.iss'); -const ps=read('scripts/build_verify_windows_installer.ps1'); -const ci=read('.github/workflows/p1-windows.yml'); -test('Inno RC is per-user, 64-bit, no automatic activation or Studio deletion',()=>{ - for(const item of ['PrivilegesRequired=lowest','DefaultDirName={localappdata}', - 'ArchitecturesAllowed=x64compatible','CloseApplications=no','RestartApplications=no', - 'UNQUALIFIED','verified-gui.exe','BUILD_PROVENANCE.json']) assert.ok(iss.includes(item),item); - assert.doesNotMatch(iss,/^\[(Run|UninstallDelete)\]/m); - assert.doesNotMatch(iss,/^Source:.*portable_mode\.txt/m); + +const read = path => readFileSync(path, 'utf8'); +const iss = read('installer/ArSonMix.iss'); +const legacyShutdown = read('installer/ArSonMixUpdateShutdown.ps1'); +const ps = read('scripts/build_verify_windows_installer.ps1'); +const isolatedSmoke = read('scripts/test_inno_graceful_update_windows.ps1'); +const fixture = read('tests/fixtures/installer_graceful_close.cs'); +const ci = read('.github/workflows/p1-windows.yml'); + +test('per-user Inno Setup upgrades the same app and retains private Studio data', () => { + for (const item of [ + 'AppId=ArSonMix.LiveStudio', 'PrivilegesRequired=lowest', + 'AppVersion={#SourceAppVersion}', 'AppVerName=ArSonMix {#SourceAppVersion}', + 'DefaultDirName={localappdata}', 'UsePreviousAppDir=yes', + 'ArchitecturesAllowed=x64compatible', 'MinVersion=10.0.17763', + 'DisableWelcomePage=yes', 'DisableDirPage=yes', + 'DisableReadyPage=yes', 'DisableFinishedPage=yes', + 'SetupMutex=ArSonMix.PerUserInstaller.SingleInstance', + 'Preview', 'verified-gui.exe', 'BUILD_PROVENANCE.json' + ]) assert.ok(iss.includes(item), item); + + assert.doesNotMatch(iss, /^\[UninstallDelete\]/m); + assert.doesNotMatch(iss, /^Source:.*portable_mode\.txt/m); + assert.doesNotMatch(iss, /taskkill|Stop-Process|TerminateProcess|CloseApplications=force/i); + assert.match(iss, /Name: "\{autoprograms\}\\ArSonMix"/); + assert.match(iss, /FactoryFX\\\*.*skipifsourcedoesntexist/); }); -test('installer only derives from verified FAT PE and tests uninstall safely',()=>{ - for(const item of ['manifest.sourceCommit','manifest.exeSha256','manifest.fatStatus', - 'assets/icon/arsonmix-app.ico','FactoryFX','Start-Process -FilePath $setup', - 'Start-Process -FilePath $uninstall','Test-Path -LiteralPath $sentinel', - 'PHYSICAL_FAT_PENDING','INSTALLER_PROVENANCE.json'])assert.ok(ps.includes(item),item); - const verifyStep=ci.indexOf(' - name: Independently verify release ZIP and embedded GUI/engine before upload'); - const installerStep=ci.indexOf(' - name: Compile and validate per-user Windows RC installer from exact FAT PE'); - assert.ok(verifyStep>=0 && installerStep>verifyStep); - assert.match(ci,/ArSonMix-Windows-Installer-UNQUALIFIED/); + +test('single installer preflight requests graceful shutdown; Restart Manager cannot force old mixer', () => { + assert.match(iss, /^CloseApplications=no$/m); + assert.doesNotMatch(iss, /^CloseApplicationsFilter=/m); + assert.match(iss, /^RestartApplications=no$/m); + // Never prevent upgrades while the mixer is open: no AppMutex. + assert.doesNotMatch(iss, /^AppMutex=/m); + assert.match(iss, /Source: "\{#SourceRoot\}\\verified-gui\.exe"; DestDir: "\{app\}"; DestName: "ArSonMix\.exe"/); +}); + +test('successful interactive install or update launches exactly one new mixer', () => { + assert.equal((iss.match(/^\[Run\]$/gm) ?? []).length, 1); + assert.equal((iss.match(/^Filename: "\{app\}\\ArSonMix\.exe"/gm) ?? []).length, 1); + const runLine = iss.split('\n').find(s => s.startsWith('Filename: "{app}\\ArSonMix.exe"')); + assert.ok(runLine, '[Run] must invoke the installed mixer'); + for (const flag of ['nowait', 'runasoriginaluser', 'skipifsilent']) { + assert.ok(runLine.includes(flag), flag); + } + assert.doesNotMatch(runLine, /\bpostinstall\b|\brunhidden\b/); + // Interactive: launch immediately when installation completes, not a checkbox. + // Silent enterprise/CI installs: never open an audio device in Session 0. + assert.match(iss, /^DisableFinishedPage=yes$/m); + assert.match(iss, /^RestartApplications=no$/m); +}); + +test('Windows FAT actually repeats the installer while a graceful WM_CLOSE test mixer is running', () => { + for (const item of [ + 'manifest.sourceCommit', 'manifest.exeSha256', 'manifest.fatStatus', + '/DSourceAppVersion=$appVersion', 'project\\(ARMixConsole VERSION', + 'assets/icon/arsonmix-app.ico', 'FactoryFX', + 'Start-Process -FilePath $setup', 'Start-Process -FilePath $installedExe', + 'installer_graceful_close.cs', 'WM_CLOSE_SAVED', 'WINDOW_READY', + '/NOCLOSEAPPLICATIONS', + 'INNO_GRACEFUL_UPDATE_PASS', 'Test-Path -LiteralPath $installSentinel', + 'Test-Path -LiteralPath $sentinel', 'INSTALLER_PROVENANCE.json', + 'OWNER_FIELD_AUDIO_LISTENING_REPORTED' + ]) assert.ok((ps + fixture).includes(item), item); + assert.equal((ps.match(/Start-Process -FilePath \$setup/g) ?? []).length, 2); + assert.match(fixture, /FormClosing/); + assert.match(fixture, /WM_QUERYENDSESSION/); + assert.match(fixture, /WM_ENDSESSION/); + assert.match(ps, /RM_QUERY_SAVED/); + assert.match(ps, /RM_ENDSESSION_SAVED/); + assert.match(ps, /INSTALLER_HANDSHAKE_SAVED/); + assert.match(iss, /PrepareToInstall/); + assert.match(iss, /OpenEventW/); + assert.match(iss, /CheckForMutexes/); + assert.match(fixture, /ArSonMix\.InstallShutdown/); + assert.match(fixture, /ArSonMix\.MixerRunning/); + assert.match(fixture, /Application\.Run\(window\)/); + // No fixture is packaged: only the verified native EXE ships. + assert.doesNotMatch(iss, /installer_graceful_close|\.cs"/); +}); + +test('Legacy pre-handshake mixer process is shut down before Inno touches its EXE', () => { + // No taskkill/force; close only an exact path-matched ArSonMix process. + assert.match(iss, /^Source: "ArSonMixUpdateShutdown\.ps1"; Flags: dontcopy$/m); + assert.match(iss, /ExtractTemporaryFile\('ArSonMixUpdateShutdown\.ps1'\)/); + assert.match(iss, /PrepareToInstall/); + assert.match(iss, /OpenExclusiveFile/); + assert.match(iss, /InstalledExeReplaceable\(Target\)/); + assert.match(iss, /if ExitCode <> 0 then/); + assert.match(legacyShutdown, /GetProcessesByName\('ArSonMix'\)/); + assert.match(legacyShutdown, /\.MainModule\.FileName/); + assert.match(legacyShutdown, /OrdinalIgnoreCase/); + assert.match(legacyShutdown, /CloseMainWindow/); + assert.match(legacyShutdown, /EnumWindows/); + assert.match(legacyShutdown, /GetWindowThreadProcessId/); + assert.match(legacyShutdown, /PostMessage/); + assert.doesNotMatch(legacyShutdown + iss, /(?:^|\\n)\\s*(?:taskkill|Stop-Process|TerminateProcess|CloseApplications=force)\\b/im); + assert.match(isolatedSmoke, /INNO_LEGACY_NO_HANDSHAKE_UPGRADE_PASS/); + assert.match(isolatedSmoke, /INNO_BLOCKED_FAIL_CLOSED_PASS/); + assert.match(fixture, /args\[2\] == "legacy"/); + assert.match(fixture, /args\[2\] == "blocked"/); + assert.doesNotMatch(iss, /DestName:\s*"ArSonMixUpdateShutdown\.ps1"/); +}); + +test('installer packaging is gated by the exact SHA FAT verifier', () => { + const verify = ci.indexOf(' - name: Independently verify release ZIP and embedded GUI/engine before upload'); + const installer = ci.indexOf(' - name: Compile and validate per-user Windows RC installer from exact FAT PE'); + assert.ok(verify >= 0 && installer > verify); + assert.match(ci, /ArSonMix-Windows-Installer-Preview/); + assert.match(ci, /tests\/windows_installer_contract_test\.mjs/); });