From 56d57059bf3f0d399feb2c830692a582767c9808 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 13 Nov 2026 09:02:01 +0100 Subject: [PATCH] Capture and apply Windows sound and battery display settings --- TASKS.md | 3 + configs/windows/power.json | 4 + configs/windows/sounds.json | 4 + schemas/profile.schema.json | 2 +- src/Adapters.psm1 | 42 ++++++- src/Configs.psm1 | 51 ++++++-- src/Manifest.psm1 | 2 +- src/WindowsSettings.psm1 | 117 ++++++++++++++++++ tests/WindowsSettings.Tests.ps1 | 205 ++++++++++++++++++++++++++++++++ 9 files changed, 415 insertions(+), 15 deletions(-) create mode 100644 configs/windows/power.json create mode 100644 configs/windows/sounds.json create mode 100644 src/WindowsSettings.psm1 create mode 100644 tests/WindowsSettings.Tests.ps1 diff --git a/TASKS.md b/TASKS.md index d9fc727..cd1dc32 100644 --- a/TASKS.md +++ b/TASKS.md @@ -145,3 +145,6 @@ open until it is run on disposable machines with the required account setups. - [x] Explain first-launch/registry-mode steps for missing MPC-HC capture settings and key-creation failures without suppressing the underlying error. - [x] Continue MPC-HC registry writes after individual failures, warn with key names on partial success, and fail only when no values were written; preserve diagnostics and retry state. - [x] Back up registry value types and presence; restore failed writes or the full managed declaration on operation failure, and report incomplete rollback; verified with mocked rollback and state-failure tests. + +- [x] Add capture/apply adapters for Windows sound-event assignments and the active plan's battery display timeout, with constrained declarations, backups, drift detection, and rollback; validate with Linux mocks. +- [ ] Enable the Windows sound/power defaults in desktop profiles and document the capture/update workflow. diff --git a/configs/windows/power.json b/configs/windows/power.json new file mode 100644 index 0000000..ef5734c --- /dev/null +++ b/configs/windows/power.json @@ -0,0 +1,4 @@ +{ + "schemaVersion": 1, + "batteryDisplayTimeoutSeconds": 0 +} diff --git a/configs/windows/sounds.json b/configs/windows/sounds.json new file mode 100644 index 0000000..5063689 --- /dev/null +++ b/configs/windows/sounds.json @@ -0,0 +1,4 @@ +{ + "schemaVersion": 1, + "disabled": true +} diff --git a/schemas/profile.schema.json b/schemas/profile.schema.json index 2d3d8d6..8355fc8 100644 --- a/schemas/profile.schema.json +++ b/schemas/profile.schema.json @@ -42,7 +42,7 @@ "name": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]*$" }, "source": { "type": "string", "minLength": 1 }, "target": { "type": "string", "minLength": 1 }, - "mode": { "enum": ["copy", "ini-overlay", "registry", "hosts-block"], "default": "copy" }, + "mode": { "enum": ["copy", "ini-overlay", "registry", "hosts-block", "windows-sounds", "windows-power"], "default": "copy" }, "requiresPackage": { "type": "string", "minLength": 1 }, "enabled": { "type": "boolean", "default": true } }, diff --git a/src/Adapters.psm1 b/src/Adapters.psm1 index 583fbac..3a4dd50 100644 --- a/src/Adapters.psm1 +++ b/src/Adapters.psm1 @@ -1,4 +1,5 @@ Set-StrictMode -Version Latest +Import-Module (Join-Path $PSScriptRoot WindowsSettings.psm1) function Get-TextHash { param([AllowEmptyString()][string]$Text) @@ -161,6 +162,23 @@ function Get-AdapterPlan { $current = Get-IniSnapshot -Path $Target -Desired $desired $desiredHash = Get-ObjectHash $desired } + elseif ($Config.mode -in @('windows-sounds', 'windows-power')) { + if ($Config.mode -eq 'windows-sounds') { + if ($Target -ne 'HKCU:\AppEvents\Schemes') { throw 'Invalid Windows sounds target.' } + $desired = Read-SoundDeclaration -Path $Source + $backup = Get-RegistryBackup -Root $Target -Declaration $desired + $actual = @($backup.values | ForEach-Object { [ordered]@{ path = $_.path; name = $_.name; type = $_.type; value = $_.value } }) + $desiredHash = Get-ObjectHash $desired.values + $current = @{ hash = Get-ObjectHash $actual; present = 1 } + } + else { + if ($Target -ne 'active-power-scheme') { throw 'Invalid Windows power target.' } + $desired = Read-PowerDeclaration -Path $Source + $power = Get-PowerSettings + $current = @{ hash = Get-ObjectHash ([ordered]@{ schemaVersion = 1; batteryDisplayTimeoutSeconds = $power.batteryDisplayTimeoutSeconds }); present = 1 } + $desiredHash = Get-ObjectHash $desired + } + } elseif ($Config.mode -eq 'registry') { if (-not $IsWindows) { throw 'Registry configs can only be planned on Windows.' } if ($Target -notmatch '^HKCU:\\Software\\MPC-HC\\MPC-HC(?:\\.*)?$') { throw "Registry target is outside the allowed MPC-HC key: '$Target'." } @@ -220,7 +238,16 @@ function Restore-RegistryDeclaration { $current = Get-RegistryBackup -Root $Root -Declaration ([pscustomobject]@{ values = @($entry) }) $actual = $current.values[0] if (-not $entry.exists) { - if ($actual.exists) { Remove-ItemProperty -LiteralPath $path -Name $entry.name -ErrorAction Stop } + if ($actual.exists) { + if ($entry.name -eq '') { + $key = Get-Item -LiteralPath $path -ErrorAction Stop + try { + $writable = $key.OpenSubKey('', $true) + try { $writable.DeleteValue('') } finally { if ($writable) { $writable.Close() } } + } finally { $key.Close() } + } + else { Remove-ItemProperty -LiteralPath $path -Name $entry.name -ErrorAction Stop } + } } elseif (-not $actual.exists -or $actual.type -ne $entry.type -or (Get-ObjectHash $actual.value) -ne (Get-ObjectHash $entry.value)) { $result = Set-RegistryDeclaration -Root $Root -Declaration ([pscustomobject]@{ values = @($entry) }) @@ -235,7 +262,7 @@ function Restore-RegistryDeclaration { function Set-RegistryDeclaration { param([string]$Root, $Declaration) # Standard x86 and x64 MPC-HC share this HKCU settings store. - if (Get-Process -Name 'mpc-hc', 'mpc-hc64' -ErrorAction SilentlyContinue) { + if ($Root -ne 'HKCU:\AppEvents\Schemes' -and (Get-Process -Name 'mpc-hc', 'mpc-hc64' -ErrorAction SilentlyContinue)) { throw 'Close both MPC-HC and MPC-HC x64 before applying settings, then rerun the update.' } $written = 0 @@ -252,7 +279,16 @@ function Set-RegistryDeclaration { 'MultiString' { ,([string[]]@($entry.value)) } default { [string]$entry.value } } - [void](New-ItemProperty -LiteralPath $path -Name $entry.name -PropertyType $entry.type -Value $value -Force -ErrorAction Stop) + if ($entry.name -eq '') { + $key = Get-Item -LiteralPath $path -ErrorAction Stop + try { + $writable = $key.OpenSubKey('', $true) + try { $writable.SetValue('', $value, [Microsoft.Win32.RegistryValueKind]$entry.type) } + finally { if ($writable) { $writable.Close() } } + } + finally { $key.Close() } + } + else { [void](New-ItemProperty -LiteralPath $path -Name $entry.name -PropertyType $entry.type -Value $value -Force -ErrorAction Stop) } $written++ } catch { diff --git a/src/Configs.psm1 b/src/Configs.psm1 index a579ed0..8d8ba80 100644 --- a/src/Configs.psm1 +++ b/src/Configs.psm1 @@ -1,4 +1,5 @@ Set-StrictMode -Version Latest +Import-Module (Join-Path $PSScriptRoot WindowsSettings.psm1) function Get-UserPathMap { param($Settings) @@ -46,7 +47,7 @@ function Get-ConfigPlan { $plan = [System.Collections.Generic.List[object]]::new() foreach ($config in @($Configs)) { $source = Resolve-ConfigSource -RepositoryRoot $RepositoryRoot -Source $config.source - $target = if ($config.mode -eq 'registry') { [string]$config.target } else { Resolve-ConfigTarget -Target $config.target -PathMap $pathMap } + $target = if ($config.mode -in @('registry', 'windows-sounds', 'windows-power')) { [string]$config.target } else { Resolve-ConfigTarget -Target $config.target -PathMap $pathMap } if (-not $destinations.Add($target)) { throw "Multiple configs resolve to '$target'." } $record = if ($State.configs.Contains($config.name)) { $State.configs[$config.name] } else { $null } if ($config.mode -eq 'copy') { @@ -99,8 +100,8 @@ function Get-ConfigLocations { $locations = [System.Collections.Generic.List[object]]::new() foreach ($config in $selected) { $source = Resolve-ConfigSource -RepositoryRoot $RepositoryRoot -Source $config.source - $target = if ($config.mode -eq 'registry') { [string]$config.target } else { Resolve-ConfigTarget -Target $config.target -PathMap $pathMap } - $targetExists = [bool](Test-Path -LiteralPath $target -ErrorAction SilentlyContinue) + $target = if ($config.mode -in @('registry', 'windows-sounds', 'windows-power')) { [string]$config.target } else { Resolve-ConfigTarget -Target $config.target -PathMap $pathMap } + $targetExists = if ($config.mode -eq 'windows-power') { $IsWindows } else { [bool](Test-Path -LiteralPath $target -ErrorAction SilentlyContinue) } $locations.Add([pscustomobject]@{ kind = 'config'; name = [string]$config.name status = if ($targetExists) { 'Present' } else { 'Missing' } @@ -151,6 +152,21 @@ function Export-ConfigCapture { $operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Missing'; message = $missingMessage }) continue } + if ($config.mode -in @('windows-sounds', 'windows-power')) { + $captured = if ($config.mode -eq 'windows-sounds') { + $sounds = Get-SoundDeclaration + if (@($sounds.values | Where-Object { $_.path -and $_.value }).Count -eq 0) { + [ordered]@{ schemaVersion = 1; disabled = $true } + } else { $sounds } + } else { + $power = Get-PowerSettings + [ordered]@{ schemaVersion = 1; batteryDisplayTimeoutSeconds = $power.batteryDisplayTimeoutSeconds } + } + $destination = Join-Path $captureRoot ([string]$config.source).Replace('/', [IO.Path]::DirectorySeparatorChar) + Write-JsonAtomic -Path $destination -Value $captured + $operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Captured'; message = $destination }) + continue + } if ($config.mode -eq 'copy') { $relative = ([string]$config.source).Replace('/', [IO.Path]::DirectorySeparatorChar) $destination = Join-Path $captureRoot $relative @@ -237,12 +253,23 @@ function Invoke-ConfigOperation { $temporary = $null $registryWarning = $null $registryTouched = $false + $powerTouched = $false + $powerBackup = $null $registryBackup = $null $previousRecord = if ($State.Contains('configs') -and $State.configs.Contains($Operation.name)) { $State.configs[$Operation.name] } else { $null } $deployedHash = $Operation.sourceHash try { if ($Operation.action -ne 'Adopt') { - if ($Operation.mode -eq 'registry') { + if ($Operation.mode -eq 'windows-power') { + if ($Operation.target -ne 'active-power-scheme') { throw 'Invalid Windows power target.' } + $folder = Join-Path $Paths.Backups $Operation.name + $backup = Join-Path $folder "$([DateTimeOffset]::UtcNow.ToString('yyyyMMddTHHmmssfffZ')).json" + $powerBackup = Get-PowerSettings + Write-JsonAtomic -Path $backup -Value $powerBackup + $powerTouched = $true + Set-PowerSettings -Settings ([pscustomobject]@{ scheme = $powerBackup.scheme; batteryDisplayTimeoutSeconds = $Operation.desired.batteryDisplayTimeoutSeconds }) + } + elseif ($Operation.mode -in @('registry', 'windows-sounds')) { $folder = Join-Path $Paths.Backups $Operation.name [void](New-Item -ItemType Directory -Path $folder -Force) $backup = Join-Path $folder "$([DateTimeOffset]::UtcNow.ToString('yyyyMMddTHHmmssfffZ')).json" @@ -253,9 +280,12 @@ function Invoke-ConfigOperation { if ($writes.failures.Count -gt 0) { # Keep detailed causes beside the backup; the terminal gets only key names. Write-JsonAtomic -Path "$backup.write-results.json" -Value $writes - $failedKeys = @($writes.failures | ForEach-Object { if ($_.path) { "$($_.path)\$($_.name)" } else { $_.name } }) + $failedKeys = @($writes.failures | ForEach-Object { + $label = if ($_.name) { $_.name } else { '(Default)' } + if ($_.path) { "$($_.path)\$label" } else { $label } + }) $registryWarning = "Could not write registry key(s): $($failedKeys -join ', ')" - if ($writes.written -eq 0) { throw $registryWarning } + if ($writes.written -eq 0 -or $Operation.mode -eq 'windows-sounds') { throw $registryWarning } Restore-RegistryDeclaration -Root $Operation.target -Backup $registryBackup -Only $writes.failures $deployedHash = (Get-RegistrySnapshot -Root $Operation.target -Declaration $Operation.desired).hash } @@ -287,13 +317,14 @@ function Invoke-ConfigOperation { } catch { $message = $_.Exception.Message - if ($registryTouched) { + if ($registryTouched -or $powerTouched) { if ($null -ne $previousRecord) { $State.configs[$Operation.name] = $previousRecord } elseif ($State.Contains('configs')) { $State.configs.Remove($Operation.name) } try { - Restore-RegistryDeclaration -Root $Operation.target -Backup $registryBackup + if ($registryTouched) { Restore-RegistryDeclaration -Root $Operation.target -Backup $registryBackup } + else { Set-PowerSettings -Settings $powerBackup } Write-JsonAtomic -Path $Paths.State -Value $State - $message += '; previous managed registry values restored' + $message += if ($registryTouched) { '; previous managed registry values restored' } else { '; previous power setting restored' } } catch { $message += "; rollback incomplete. Backup: $backup. $($_.Exception.Message)" @@ -308,7 +339,7 @@ function Restore-ConfigBackup { param([Parameter(Mandatory)][string]$Name, [Parameter(Mandatory)]$Paths, [Parameter(Mandatory)]$State) if (-not $State.Contains('configs') -or -not $State.configs.Contains($Name)) { throw "No managed state exists for config '$Name'." } $mode = if ($State.configs[$Name].Contains('mode')) { [string]$State.configs[$Name].mode } else { 'copy' } - if ($mode -eq 'registry') { throw "Automatic restore is not supported for registry config '$Name'; inspect its JSON backup and restore selected values deliberately." } + if ($mode -in @('registry', 'windows-sounds', 'windows-power')) { throw "Automatic restore is not supported for $mode config '$Name'; inspect its JSON backup and restore selected values deliberately." } if ($mode -eq 'hosts-block') { throw "Automatic restore is not supported for hosts config '$Name'; restore its backup from an administrator shell." } $folder = Join-Path $Paths.Backups $Name $backup = Get-ChildItem -LiteralPath $folder -Filter '*.bak' -File -ErrorAction SilentlyContinue | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1 diff --git a/src/Manifest.psm1 b/src/Manifest.psm1 index 2320792..8d963ca 100644 --- a/src/Manifest.psm1 +++ b/src/Manifest.psm1 @@ -74,7 +74,7 @@ function Assert-ItemList { if ($enabled) { if ([string]::IsNullOrWhiteSpace([string](Get-OptionalProperty $item 'source'))) { throw "$Location[$index].source is required." } if ([string]::IsNullOrWhiteSpace([string](Get-OptionalProperty $item 'target'))) { throw "$Location[$index].target is required." } - if ((Get-OptionalProperty $item 'mode' 'copy') -notin @('copy', 'ini-overlay', 'registry', 'hosts-block')) { throw "Unsupported config mode at $Location[$index]." } + if ((Get-OptionalProperty $item 'mode' 'copy') -notin @('copy', 'ini-overlay', 'registry', 'hosts-block', 'windows-sounds', 'windows-power')) { throw "Unsupported config mode at $Location[$index]." } } } if (-not $keys.Add($key)) { throw "Duplicate $Kind key '$key' in $Location." } diff --git a/src/WindowsSettings.psm1 b/src/WindowsSettings.psm1 new file mode 100644 index 0000000..f4418c7 --- /dev/null +++ b/src/WindowsSettings.psm1 @@ -0,0 +1,117 @@ +Set-StrictMode -Version Latest + +function Initialize-PowerApi { + if (-not $IsWindows) { throw 'Windows settings require Windows.' } + if ('ConfigCentral.PowerApi' -as [type]) { return } + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +namespace ConfigCentral { + public static class PowerApi { + [DllImport("powrprof.dll")] public static extern uint PowerGetActiveScheme(IntPtr root, out IntPtr scheme); + [DllImport("powrprof.dll")] public static extern uint PowerReadDCValueIndex(IntPtr root, ref Guid scheme, ref Guid subgroup, ref Guid setting, out uint value); + [DllImport("powrprof.dll")] public static extern uint PowerWriteDCValueIndex(IntPtr root, ref Guid scheme, ref Guid subgroup, ref Guid setting, uint value); + [DllImport("powrprof.dll")] public static extern uint PowerSetActiveScheme(IntPtr root, ref Guid scheme); + [DllImport("kernel32.dll")] public static extern IntPtr LocalFree(IntPtr memory); + } +} +'@ +} + +function Assert-PowerResult { + param([uint32]$Code) + if ($Code) { throw "Windows power settings: $([ComponentModel.Win32Exception]::new([int]$Code).Message). Check power-policy permissions and retry." } +} + +function Get-PowerSettings { + param([guid]$Scheme = [guid]::Empty) + Initialize-PowerApi + if ($Scheme -eq [guid]::Empty) { + $pointer = [IntPtr]::Zero + Assert-PowerResult ([ConfigCentral.PowerApi]::PowerGetActiveScheme([IntPtr]::Zero, [ref]$pointer)) + try { $Scheme = [Runtime.InteropServices.Marshal]::PtrToStructure($pointer, [type][guid]) } + finally { [void][ConfigCentral.PowerApi]::LocalFree($pointer) } + } + $subgroup = [guid]'7516b95f-f776-4464-8c53-06167f40cc99' + $setting = [guid]'3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e' + $seconds = [uint32]0 + Assert-PowerResult ([ConfigCentral.PowerApi]::PowerReadDCValueIndex([IntPtr]::Zero, [ref]$Scheme, [ref]$subgroup, [ref]$setting, [ref]$seconds)) + [pscustomobject]@{ scheme = $Scheme.ToString(); batteryDisplayTimeoutSeconds = $seconds } +} + +function Set-PowerSettings { + param($Settings) + Initialize-PowerApi + $scheme = [guid]$Settings.scheme + if ((Get-PowerSettings -Scheme $scheme).batteryDisplayTimeoutSeconds -eq $Settings.batteryDisplayTimeoutSeconds) { return } + $subgroup = [guid]'7516b95f-f776-4464-8c53-06167f40cc99' + $setting = [guid]'3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e' + Assert-PowerResult ([ConfigCentral.PowerApi]::PowerWriteDCValueIndex([IntPtr]::Zero, [ref]$scheme, [ref]$subgroup, [ref]$setting, [uint32]$Settings.batteryDisplayTimeoutSeconds)) + # Do not switch plans if the user changed plans during this operation. + if ((Get-PowerSettings).scheme -eq $scheme.ToString()) { + Assert-PowerResult ([ConfigCentral.PowerApi]::PowerSetActiveScheme([IntPtr]::Zero, [ref]$scheme)) + } + if ((Get-PowerSettings -Scheme $scheme).batteryDisplayTimeoutSeconds -ne $Settings.batteryDisplayTimeoutSeconds) { + throw 'Windows did not retain the battery display timeout. Check power-policy permissions and retry.' + } +} + +function Read-PowerDeclaration { + param([string]$Path) + $value = Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json + if (@($value.PSObject.Properties.Name | Where-Object { $_ -notin @('schemaVersion', 'batteryDisplayTimeoutSeconds') }).Count -or + $value.schemaVersion -ne 1 -or $value.batteryDisplayTimeoutSeconds -isnot [long] -and $value.batteryDisplayTimeoutSeconds -isnot [int] -or + $value.batteryDisplayTimeoutSeconds -lt 0 -or $value.batteryDisplayTimeoutSeconds -gt [uint32]::MaxValue) { + throw 'Invalid power settings: specify schemaVersion 1 and batteryDisplayTimeoutSeconds as a nonnegative integer (0 means never).' + } + [ordered]@{ schemaVersion = 1; batteryDisplayTimeoutSeconds = $value.batteryDisplayTimeoutSeconds } +} + +function Get-SoundDeclaration { + # Capture only current event assignments, not all installed sound schemes. + $root = 'HKCU:\AppEvents\Schemes' + $values = [Collections.Generic.List[object]]::new() + $key = Get-Item -LiteralPath $root -ErrorAction Stop + try { $values.Add([pscustomobject]@{ path = ''; name = ''; type = 'String'; value = [string]$key.GetValue('') }) } + finally { $key.Close() } + foreach ($app in @(Get-ChildItem -LiteralPath "$root\Apps" -ErrorAction Stop | Sort-Object PSChildName)) { + foreach ($event in @(Get-ChildItem -LiteralPath $app.PSPath -ErrorAction Stop | Sort-Object PSChildName)) { + $path = "Apps\$($app.PSChildName)\$($event.PSChildName)\.Current" + $key = Get-Item -LiteralPath "$root\$path" -ErrorAction SilentlyContinue + try { + $type = 'String' + $sound = '' + if ($null -ne $key -and ($key.GetValueNames() -contains '')) { + $type = [string]$key.GetValueKind('') + $sound = [string]$key.GetValue('', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + } + $values.Add([pscustomobject]@{ path = $path; name = ''; type = $type; value = $sound }) + } + finally { if ($null -ne $key) { $key.Close() } } + } + } + [pscustomobject]@{ schemaVersion = 1; values = @($values) } +} + +function Read-SoundDeclaration { + param([string]$Path) + $value = Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json + if ($value.schemaVersion -ne 1) { throw 'Invalid sound settings schemaVersion.' } + if ($value.PSObject.Properties['disabled']) { + if ($value.disabled -isnot [bool] -or -not $value.disabled -or @($value.PSObject.Properties.Name | Where-Object { $_ -notin @('schemaVersion', 'disabled') }).Count) { throw 'Sound preset supports only disabled: true.' } + $value = Get-SoundDeclaration + foreach ($entry in $value.values) { $entry.value = if ($entry.path) { '' } else { '.None' } } + return $value + } + if (@($value.PSObject.Properties.Name | Where-Object { $_ -notin @('schemaVersion', 'values') }).Count -or $value.values -isnot [array] -or -not $value.values.Count) { throw 'Invalid sound declaration.' } + $seen = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) + foreach ($entry in $value.values) { + if (@($entry.PSObject.Properties.Name | Where-Object { $_ -notin @('path', 'name', 'type', 'value') }).Count -or + $entry.name -cne '' -or $entry.type -notin @('String', 'ExpandString') -or $entry.value -isnot [string] -or + ($entry.path -cne '' -and $entry.path -notmatch '^Apps\\[^\\/]+\\[^\\/]+\\\.Current$') -or + $entry.path -match '(^|\\)\.\.?($|\\)' -or -not $seen.Add($entry.path)) { throw 'Unsafe or duplicate sound setting; only current sound-event assignments are supported.' } + } + return $value +} + +Export-ModuleMember -Function Get-PowerSettings, Set-PowerSettings, Read-PowerDeclaration, Get-SoundDeclaration, Read-SoundDeclaration diff --git a/tests/WindowsSettings.Tests.ps1 b/tests/WindowsSettings.Tests.ps1 new file mode 100644 index 0000000..84ddc7a --- /dev/null +++ b/tests/WindowsSettings.Tests.ps1 @@ -0,0 +1,205 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../src/State.psm1" -Force + Import-Module "$PSScriptRoot/../src/Repository.psm1" -Force + Import-Module "$PSScriptRoot/../src/WindowsSettings.psm1" -Force + Import-Module "$PSScriptRoot/../src/Adapters.psm1" -Force + Import-Module "$PSScriptRoot/../src/Configs.psm1" -Force +} + +Describe 'Windows setting declarations' { + It 'accepts seconds including never and rejects malformed or additional settings' { + $path = Join-Path $TestDrive power.json + foreach ($json in @('{"schemaVersion":1,"batteryDisplayTimeoutSeconds":0}', '{"schemaVersion":1,"batteryDisplayTimeoutSeconds":90}')) { + $json | Set-Content $path + { Read-PowerDeclaration $path } | Should -Not -Throw + } + foreach ($json in @('{"schemaVersion":1,"batteryDisplayTimeoutSeconds":-1}', '{"schemaVersion":1,"batteryDisplayTimeoutSeconds":"0"}', '{"schemaVersion":1,"batteryDisplayTimeoutSeconds":0.5}', '{"schemaVersion":1,"batteryDisplayTimeoutSeconds":0,"sleep":0}')) { + $json | Set-Content $path + { Read-PowerDeclaration $path } | Should -Throw + } + } + + It 'expands No Sounds into current event assignments without changing other schemes' { + Mock Get-SoundDeclaration { + [pscustomobject]@{ schemaVersion = 1; values = @( + [pscustomobject]@{ path = ''; name = ''; type = 'String'; value = '.Default' }, + [pscustomobject]@{ path = 'Apps\.Default\MailBeep\.Current'; name = ''; type = 'ExpandString'; value = '%WINDIR%\Media\notify.wav' } + ) } + } -ModuleName WindowsSettings + $value = Read-SoundDeclaration "$PSScriptRoot/../configs/windows/sounds.json" + $value.values[0].value | Should -Be '.None' + $value.values[1].value | Should -BeExactly '' + $value.values[1].type | Should -Be 'ExpandString' + } + + It 'accepts captured assignments but rejects arbitrary registry paths' { + $path = Join-Path $TestDrive sounds.json + foreach ($subpath in @('Apps\.Default\MailBeep\.Current', 'Apps\..\MailBeep\.Current', 'Software\Other')) { + @{ schemaVersion = 1; values = @(@{ path = $subpath; name = ''; type = 'String'; value = '' }) } | ConvertTo-Json -Depth 5 | Set-Content $path + if ($subpath -eq 'Apps\.Default\MailBeep\.Current') { { Read-SoundDeclaration $path } | Should -Not -Throw } + else { { Read-SoundDeclaration $path } | Should -Throw } + } + } +} + +Describe 'Windows setting planning and capture' { + BeforeEach { + $script:repo = Join-Path $TestDrive ([guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory "$repo/configs/windows" -Force | Out-Null + Copy-Item "$PSScriptRoot/../configs/windows/power.json" "$repo/configs/windows/power.json" + Copy-Item "$PSScriptRoot/../configs/windows/sounds.json" "$repo/configs/windows/sounds.json" + $script:powerConfig = [pscustomobject]@{ name = 'windows-power'; mode = 'windows-power'; target = 'active-power-scheme'; source = 'configs/windows/power.json' } + $script:soundConfig = [pscustomobject]@{ name = 'windows-sounds'; mode = 'windows-sounds'; target = 'HKCU:\AppEvents\Schemes'; source = 'configs/windows/sounds.json' } + } + + It 'plans power changes without writes and detects local drift and matching state' { + Mock Get-PowerSettings { @{ scheme = 'plan-a'; batteryDisplayTimeoutSeconds = 120 } } -ModuleName Adapters + $first = Get-AdapterPlan $powerConfig "$repo/configs/windows/power.json" 'active-power-scheme' $null + $first.action | Should -Be 'Conflict' + $first.requiresAdmin | Should -BeFalse + $record = @{ deployedHash = $first.currentHash } + (Get-AdapterPlan $powerConfig "$repo/configs/windows/power.json" 'active-power-scheme' $record).action | Should -Be 'Update' + Mock Get-PowerSettings { @{ scheme = 'plan-a'; batteryDisplayTimeoutSeconds = 0 } } -ModuleName Adapters + (Get-AdapterPlan $powerConfig "$repo/configs/windows/power.json" 'active-power-scheme' @{ deployedHash = $first.desiredHash }).action | Should -Be 'None' + (Get-AdapterPlan $powerConfig "$repo/configs/windows/power.json" 'active-power-scheme' $record).action | Should -Be 'Conflict' + } + + It 'treats unchanged sound values as current and preserves types in comparison' { + Mock Read-SoundDeclaration { @{ values = @([pscustomobject]@{ path = ''; name = ''; type = 'String'; value = '.None' }) } } -ModuleName Adapters + Mock Get-RegistryBackup { @{ values = @([pscustomobject]@{ path = ''; name = ''; type = 'String'; value = '.None'; exists = $true }) } } -ModuleName Adapters + $first = Get-AdapterPlan $soundConfig "$repo/configs/windows/sounds.json" $soundConfig.target $null + $first.action | Should -Be 'Adopt' + (Get-AdapterPlan $soundConfig "$repo/configs/windows/sounds.json" $soundConfig.target @{ deployedHash = $first.currentHash }).action | Should -Be 'None' + } + + It 'captures portable silence and power seconds at repository-relative paths without a plan GUID' { + Mock Get-RepositoryRevision { 'abc' } -ModuleName Configs + Mock Get-ConfigLocations { @( + [pscustomobject]@{ name = 'windows-sounds'; targetExists = $true }, + [pscustomobject]@{ name = 'windows-power'; targetExists = $true } + ) } -ModuleName Configs + Mock Get-SoundDeclaration { @{ schemaVersion = 1; values = @(@{ path = ''; name = ''; type = 'String'; value = '.None' }, @{ path = 'Apps\.Default\MailBeep\.Current'; name = ''; type = 'String'; value = '' }) } } -ModuleName Configs + Mock Get-PowerSettings { @{ scheme = 'local-only'; batteryDisplayTimeoutSeconds = 90 } } -ModuleName Configs + $capture = Export-ConfigCapture -Configs @($soundConfig, $powerConfig) -RepositoryRoot $repo -Settings @{} -Machine test -OutputPath "$repo/capture" + $capture.operations.status | Should -Not -Contain 'Failed' + $sounds = Get-Content "$repo/capture/configs/windows/sounds.json" -Raw | ConvertFrom-Json + $sounds.disabled | Should -BeTrue + $power = Read-PowerDeclaration "$repo/capture/configs/windows/power.json" + $power.batteryDisplayTimeoutSeconds | Should -Be 90 + $power.Keys | Should -Not -Contain 'scheme' + } +} + +Describe 'Windows setting backup and rollback' { + BeforeEach { + $script:paths = Get-ConfigCentralPaths -DataRoot (Join-Path $TestDrive ([guid]::NewGuid().ToString('N'))) + Initialize-ConfigCentralData $paths + $script:state = @{ configs = @{} } + $script:operation = [pscustomobject]@{ name = 'windows-power'; action = 'Update'; mode = 'windows-power'; target = 'active-power-scheme'; sourceHash = 'new'; desired = @{ batteryDisplayTimeoutSeconds = 0 } } + Mock Get-PowerSettings { @{ scheme = 'original-plan'; batteryDisplayTimeoutSeconds = 120 } } -ModuleName Configs + Mock Set-PowerSettings {} -ModuleName Configs + } + + It 'backs up the original plan before applying its battery timeout' { + (Invoke-ConfigOperation $operation $paths $state).status | Should -Be 'Succeeded' + $backup = Get-Content $state.configs['windows-power'].lastBackup -Raw | ConvertFrom-Json + $backup.scheme | Should -Be 'original-plan' + $backup.batteryDisplayTimeoutSeconds | Should -Be 120 + Should -Invoke Set-PowerSettings -ModuleName Configs -Times 1 -Exactly -ParameterFilter { $Settings.scheme -eq 'original-plan' -and $Settings.batteryDisplayTimeoutSeconds -eq 0 } + } + + It 'restores the original timeout after a failed write' { + Mock Set-PowerSettings { if ($Settings.batteryDisplayTimeoutSeconds -eq 0) { throw 'Policy denied' } } -ModuleName Configs + $result = Invoke-ConfigOperation $operation $paths $state + $result.status | Should -Be 'Failed' + $result.message | Should -Match 'Policy denied; previous power setting restored' + Should -Invoke Set-PowerSettings -ModuleName Configs -Times 1 -Exactly -ParameterFilter { $Settings.batteryDisplayTimeoutSeconds -eq 120 -and $Settings.scheme -eq 'original-plan' } + $state.configs.ContainsKey('windows-power') | Should -BeFalse + } + + It 'reports failed rollback with its backup location' { + Mock Set-PowerSettings { throw 'Policy denied' } -ModuleName Configs + $result = Invoke-ConfigOperation $operation $paths $state + $result.message | Should -Match 'rollback incomplete. Backup:' + $result.status | Should -Be 'Failed' + } + + It 'does not write if backup persistence fails' { + Mock Write-JsonAtomic { throw 'Disk full' } -ModuleName Configs + (Invoke-ConfigOperation $operation $paths $state).status | Should -Be 'Failed' + Should -Invoke Set-PowerSettings -ModuleName Configs -Times 0 -Exactly + } + + It 'rolls back all sound assignments on any failed sound write' { + $operation.mode = 'windows-sounds'; $operation.name = 'windows-sounds'; $operation.target = 'HKCU:\AppEvents\Schemes' + Mock Get-RegistryBackup { @{ values = @() } } -ModuleName Configs + Mock Set-RegistryDeclaration { @{ written = 2; failures = @(@{ path = 'Apps\.Default\MailBeep\.Current'; name = ''; error = 'Denied' }) } } -ModuleName Configs + Mock Restore-RegistryDeclaration {} -ModuleName Configs + (Invoke-ConfigOperation $operation $paths $state).status | Should -Be 'Failed' + Should -Invoke Restore-RegistryDeclaration -ModuleName Configs -Times 1 -Exactly -ParameterFilter { $null -eq $Only } + } +} + +Describe 'Sound registry edge cases' { + It 'includes events without current keys or default values as silent assignments' { + InModuleScope WindowsSettings { + Mock Get-ChildItem { + param($LiteralPath) + if ($LiteralPath -like '*\Apps') { [pscustomobject]@{ PSChildName = '.Default'; PSPath = 'app' } } + else { @([pscustomobject]@{ PSChildName = 'Missing' }, [pscustomobject]@{ PSChildName = 'Empty' }) } + } + Mock Get-Item { + param($LiteralPath) + if ($LiteralPath -like '*\Missing\.Current') { return $null } + $key = [pscustomobject]@{} + $key | Add-Member ScriptMethod GetValue { param($name) '.None' } + $key | Add-Member ScriptMethod GetValueNames { @() } + $key | Add-Member ScriptMethod Close {} + $key + } + $value = Get-SoundDeclaration + $value.values.Count | Should -Be 3 + $value.values[1].value | Should -BeExactly '' + $value.values[2].value | Should -BeExactly '' + } + } + + It 'writes default registry values through a writable handle and preserves empty strings' { + InModuleScope Adapters { + $script:assigned = $null + Mock Test-Path { $true } + Mock Get-Item { + $key = [pscustomobject]@{} + $key | Add-Member ScriptMethod OpenSubKey { param($path, $writable) + if (-not $writable) { throw 'Read-only handle' } + $this + } + $key | Add-Member ScriptMethod SetValue { param($name, $value, $type) + $script:assigned = @{ name = $name; value = $value; type = $type } + } + $key | Add-Member ScriptMethod Close {} + $key + } + $result = Set-RegistryDeclaration -Root 'HKCU:\AppEvents\Schemes' -Declaration @{ values = @(@{ path = ''; name = ''; type = 'String'; value = '' }) } + $result.written | Should -Be 1 + $result.failures.Count | Should -Be 0 + $script:assigned.name | Should -BeExactly '' + $script:assigned.value | Should -BeExactly '' + } + } + + It 'round trips a custom sound assignment without applying it during capture' { + Mock Get-RepositoryRevision { 'abc' } -ModuleName Configs + Mock Get-ConfigLocations { [pscustomobject]@{ name = 'windows-sounds'; targetExists = $true } } -ModuleName Configs + Mock Get-SoundDeclaration { [pscustomobject]@{ schemaVersion = 1; values = @( + [pscustomobject]@{ path = ''; name = ''; type = 'String'; value = '.Default' }, + [pscustomobject]@{ path = 'Apps\.Default\MailBeep\.Current'; name = ''; type = 'ExpandString'; value = '%WINDIR%\Media\notify.wav' } + ) } } -ModuleName Configs + Mock Set-RegistryDeclaration { throw 'Capture must not write' } -ModuleName Configs + $config = [pscustomobject]@{ name = 'windows-sounds'; mode = 'windows-sounds'; source = 'configs/windows/sounds.json' } + $output = Join-Path $TestDrive custom + $result = Export-ConfigCapture -Configs @($config) -RepositoryRoot $TestDrive -Settings @{} -Machine test -OutputPath $output + (Read-SoundDeclaration "$output/configs/windows/sounds.json").values[1].value | Should -Be '%WINDIR%\Media\notify.wav' + Should -Invoke Set-RegistryDeclaration -ModuleName Configs -Times 0 -Exactly + } +}