From 47d153bec9ab27a895812fb1ae6016d3287dccb6 Mon Sep 17 00:00:00 2001 From: ilgiova237 Date: Mon, 16 Nov 2026 06:51:31 +0100 Subject: [PATCH 1/3] fix(windows): update the current installation and preserve shortcuts --- .github/workflows/windows-portable.yml | 20 +++ .gitignore | 1 + build.gradle.kts | 13 +- .../kittytune/data/UpdateManager.kt | 94 +++++++----- .../updater/windows-install-support.ps1 | 74 ++++++++++ src/test/kotlin/WindowsUpdateTest.kt | 138 ++++++++++++++++++ 6 files changed, 303 insertions(+), 37 deletions(-) create mode 100644 src/main/resources/updater/windows-install-support.ps1 create mode 100644 src/test/kotlin/WindowsUpdateTest.kt diff --git a/.github/workflows/windows-portable.yml b/.github/workflows/windows-portable.yml index bf8d9578..9c65a8e8 100644 --- a/.github/workflows/windows-portable.yml +++ b/.github/workflows/windows-portable.yml @@ -24,6 +24,26 @@ jobs: - name: Test and package portable Windows app shell: pwsh run: ./scripts/build-windows.ps1 -JavaHome $env:JAVA_HOME + - name: Check packaged version file + shell: pwsh + run: | + Add-Type -AssemblyName System.IO.Compression.FileSystem + $zip = Get-ChildItem release/*-Windows-Portable-x64.zip | Select-Object -First 1 + $archive = [IO.Compression.ZipFile]::OpenRead($zip.FullName) + try { + function Read-Entry($name) { + $entry = $archive.GetEntry($name) + if (!$entry) { throw "Missing archive entry: $name" } + $reader = [IO.StreamReader]::new($entry.Open()) + try { return $reader.ReadToEnd() } finally { $reader.Dispose() } + } + $version = (Read-Entry 'KittyTune/version.txt').Trim() + $config = Read-Entry 'KittyTune/app/KittyTune.cfg' + $match = [regex]::Match($config, '(?m)^java-options=-Djpackage\.app-version=(.+)') + if (!$match.Success -or $version -ne $match.Groups[1].Value.Trim()) { + throw 'version.txt does not match the packaged launcher' + } + } finally { $archive.Dispose() } - name: Test transparent window renderer fallback shell: pwsh run: ./gradlew.bat :test --tests '*TransparentWindowRenderingTest' -PdesktopOnly=true --console=plain diff --git a/.gitignore b/.gitignore index 6cbe3088..0aea43d2 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,7 @@ kotlin-js-store/ *.py !scripts/check-linux-dbus.py *.ps1 +!src/main/resources/updater/*.ps1 !scripts/build-smtc-bridge.ps1 !scripts/build-native-windows.ps1 !scripts/build-windows.ps1 diff --git a/build.gradle.kts b/build.gradle.kts index 57910b7b..c5115569 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -909,8 +909,15 @@ val enableSegmentHeap = tasks.register("enableSegmentHeap mustRunAfter(stripForeignNativesDistributable, stripForeignNativesDistributableMain) } -tasks.matching { it.name in listOf("createDistributable", "createReleaseDistributable") }.configureEach { - if (desktopIsWindows) finalizedBy(enableSegmentHeap) +tasks.withType().configureEach { + if (desktopIsWindows && name in listOf("createDistributable", "createReleaseDistributable")) { + finalizedBy(enableSegmentHeap) + val packagedVersion = project.version.toString() + inputs.property("readableVersion", packagedVersion) + doLast { + destinationDir.get().asFile.resolve("version.txt").writeText("$packagedVersion\n", Charsets.UTF_8) + } + } } tasks.matching { it.name == "zipWindowsPortable" || (it.name.startsWith("package") && it.name.endsWith("Msi")) }.configureEach { @@ -997,7 +1004,7 @@ tasks.register("headlessTest") { "OnnxNativeLoadTest", "ToolWindowStyleRaiseToFrontTest", "*SoundCloudOAuthTest", "ClearStreamFilesTest", "ThemePersistenceTest", "SetupOnboardingTest", "*WindowsProtectedPlaybackTest", "*WindowsProtectedMediaTest", "Issue93BugfixesTest.testWindowsUpdaterScriptConstruction*", "InstallerProcessTest", "*ChromeCdmArchiveTest", "KittyTuneProcessesTest", "*SidecarLockOrderTest", - "*HlsOpeningTest", "*WindowsHeadphoneDetectionTest" + "*HlsOpeningTest", "*WindowsHeadphoneDetectionTest", "*WindowsUpdateTest" ).forEach(::includeTestsMatching) } } diff --git a/src/main/kotlin/com/alananasss/kittytune/data/UpdateManager.kt b/src/main/kotlin/com/alananasss/kittytune/data/UpdateManager.kt index ce5b6a75..0c934619 100644 --- a/src/main/kotlin/com/alananasss/kittytune/data/UpdateManager.kt +++ b/src/main/kotlin/com/alananasss/kittytune/data/UpdateManager.kt @@ -506,7 +506,7 @@ object UpdateManager { } internal fun resolveKittyTuneExe(): File? { - val jpackagePath = System.getProperty("jpackage.app.path") + val jpackagePath = System.getProperty("jpackage.app-path") ?: System.getProperty("jpackage.app.path") val possibleExePaths = mutableListOf() jpackagePath?.let { p -> val f = File(p) @@ -534,36 +534,40 @@ object UpdateManager { val escapedLog = logFile.absolutePath.replace("'", "''") val escapedMsiLog = msiLogFile.absolutePath.replace("'", "''") val isMsi = installerFile.name.endsWith(".msi", ignoreCase = true) + val expectedVersion = releaseInfo?.versionName.orEmpty().replace("'", "''") + val support = requireNotNull(javaClass.getResourceAsStream("/updater/windows-install-support.ps1")).use { + it.bufferedReader(Charsets.UTF_8).readText() + } val installCmd = if (isMsi) { """ Log "Executing msiexec..." - ${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', '/qn', '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru -WindowStyle Hidden + ${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', '/qn', 'REINSTALLMODE=amus', ('INSTALLDIR="{0}"' -f ${'$'}installDir), '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru -WindowStyle Hidden Log "msiexec silent install finished with exit code ${'$'}(${'$'}p.ExitCode)" # Fallback 1: If exit code 1638 (same version already installed), retry with REINSTALL=ALL if (${'$'}p.ExitCode -eq 1638) { Log "Detected exit code 1638 (same version). Retrying silent reinstall..." - ${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', 'REINSTALL=ALL', 'REINSTALLMODE=amus', '/qn', '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru -WindowStyle Hidden + ${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', 'REINSTALL=ALL', '/qn', 'REINSTALLMODE=amus', ('INSTALLDIR="{0}"' -f ${'$'}installDir), '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru -WindowStyle Hidden Log "msiexec silent reinstall finished with exit code ${'$'}(${'$'}p.ExitCode)" } # Fallback 2: If silent install failed (e.g. 1603 due to UAC elevation required), retry with basic UI (/qb) - if (${'$'}p.ExitCode -ne 0) { + if (${'$'}p.ExitCode -notin @(0, 3010, 1641)) { Log "Silent install failed (${'$'}(${'$'}p.ExitCode)). Retrying with basic UI (/qb)..." - ${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', '/qb', '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru + ${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', '/qb', 'REINSTALLMODE=amus', ('INSTALLDIR="{0}"' -f ${'$'}installDir), '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru Log "msiexec basic UI install finished with exit code ${'$'}(${'$'}p.ExitCode)" if (${'$'}p.ExitCode -eq 1638) { Log "Retrying basic UI install with REINSTALL=ALL..." - ${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', 'REINSTALL=ALL', 'REINSTALLMODE=amus', '/qb', '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru + ${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', 'REINSTALL=ALL', '/qb', 'REINSTALLMODE=amus', ('INSTALLDIR="{0}"' -f ${'$'}installDir), '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru Log "msiexec basic UI reinstall finished with exit code ${'$'}(${'$'}p.ExitCode)" } } # Fallback 3: Full interactive wizard if basic UI still failed - if (${'$'}p.ExitCode -ne 0) { + if (${'$'}p.ExitCode -notin @(0, 3010, 1641)) { Log "Basic UI install failed (${'$'}(${'$'}p.ExitCode)). Retrying with interactive installer..." - ${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', '/norestart', '/l*v', '"$escapedMsiLog"') -Wait -PassThru + ${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', '/norestart', 'REINSTALLMODE=amus', ('INSTALLDIR="{0}"' -f ${'$'}installDir), 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru Log "msiexec interactive install finished with exit code ${'$'}(${'$'}p.ExitCode)" } """.trimIndent() @@ -572,7 +576,7 @@ object UpdateManager { Log "Executing setup executable..." ${'$'}p = Start-Process -FilePath '$escapedInstaller' -ArgumentList @('/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/SP-') -Wait -PassThru -WindowStyle Hidden Log "Setup finished with exit code ${'$'}(${'$'}p.ExitCode)" - if (${'$'}p.ExitCode -ne 0) { + if (${'$'}p.ExitCode -notin @(0, 3010, 1641)) { Log "Silent setup failed (${'$'}(${'$'}p.ExitCode)). Retrying with interactive installer..." ${'$'}p = Start-Process -FilePath '$escapedInstaller' -Wait -PassThru Log "Interactive setup finished with exit code ${'$'}(${'$'}p.ExitCode)" @@ -582,13 +586,30 @@ object UpdateManager { return """ # KittyTune Windows Auto-Updater Script + ${'$'}ErrorActionPreference = 'Stop' + $support + ${'$'}exePath = '$escapedTargetExe' ${'$'}logFile = '$escapedLog' function Log(${'$'}msg) { ${'$'}ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss" - "[${'$'}ts] ${'$'}msg" | Out-File -FilePath ${'$'}logFile -Append -Encoding utf8 + "[${'$'}ts] ${'$'}msg" | Out-File -LiteralPath ${'$'}logFile -Append -Encoding utf8 } Log "Starting updater for PID $targetPid" + try { + if (![IO.File]::Exists(${'$'}exePath)) { throw 'Cannot determine the running KittyTune installation.' } + ${'$'}installDir = [IO.Path]::GetDirectoryName(${'$'}exePath) + ${'$'}expectedVersion = '$expectedVersion' + if (![string]::IsNullOrWhiteSpace(${'$'}expectedVersion)) { + ${'$'}expectedKey = Get-KittyTuneVersionKey ${'$'}expectedVersion + } else { + ${'$'}expectedVersion = Get-KittyTuneMsiVersion '$escapedInstaller' + ${'$'}expectedKey = Get-KittyTuneVersionKey ${'$'}expectedVersion + } + } catch { + Log "Cannot start update: ${'$'}(${'$'}_.Exception.Message)" + throw + } ${'$'}targetPid = $targetPid try { ${'$'}proc = Get-Process -Id ${'$'}targetPid -ErrorAction Stop @@ -598,8 +619,11 @@ object UpdateManager { Log "Process ${'$'}targetPid is not running or already exited." } - Log "Ensuring all KittyTune processes are stopped..." - ${'$'}procs = Get-Process -Name "KittyTune", "kittytune", "WindowsSmtcBridge" -ErrorAction SilentlyContinue + Log "Stopping processes for ${'$'}exePath..." + ${'$'}procs = Get-Process -Name "KittyTune", "WindowsSmtcBridge" -ErrorAction SilentlyContinue | Where-Object { + try { [IO.Path]::GetFullPath(${'$'}_.Path).Equals(${'$'}exePath,[StringComparison]::OrdinalIgnoreCase) } + catch { ${'$'}false } + } if (${'$'}procs) { ${'$'}procs | Stop-Process -Force -ErrorAction SilentlyContinue ${'$'}procs | ForEach-Object { @@ -608,29 +632,27 @@ object UpdateManager { } Start-Sleep -Seconds 2 - $installCmd - - ${'$'}exePath = '$escapedTargetExe' - if (-not (Test-Path -Path ${'$'}exePath)) { - ${'$'}candidates = @( - "${'$'}env:LOCALAPPDATA\KittyTune\KittyTune.exe", - "${'$'}env:LOCALAPPDATA\Programs\KittyTune\KittyTune.exe", - "${'$'}env:ProgramFiles\KittyTune\KittyTune.exe", - "${'$'}{env:ProgramFiles(x86)}\KittyTune\KittyTune.exe" - ) - foreach (${'$'}c in ${'$'}candidates) { - if (Test-Path -Path ${'$'}c) { - ${'$'}exePath = ${'$'}c - break - } + ${'$'}shortcuts = @(Save-KittyTuneShortcuts -Executable ${'$'}exePath) + ${'$'}installed = ${'$'}false + try { + $installCmd + if (${'$'}p.ExitCode -notin @(0, 3010, 1641)) { throw "Installer failed with exit code ${'$'}(${'$'}p.ExitCode)." } + if (${'$'}p.ExitCode -in @(3010, 1641)) { Log 'Update installed; Windows restart is required before relaunch.'; return } + ${'$'}actualVersion = Get-KittyTuneVersion ${'$'}exePath + if ((Get-KittyTuneVersionKey ${'$'}actualVersion) -ne ${'$'}expectedKey) { + throw "Expected version ${'$'}expectedVersion at ${'$'}exePath, found ${'$'}actualVersion." } - } - - if (Test-Path -Path ${'$'}exePath) { - Log "Relaunching KittyTune from ${'$'}exePath" + try { + [IO.File]::WriteAllText((Join-Path ${'$'}installDir 'version.txt'), ${'$'}actualVersion + [Environment]::NewLine) + } catch { Log "Could not refresh version.txt: ${'$'}(${'$'}_.Exception.Message)" } + ${'$'}installed = ${'$'}true + } catch { + Log "Update failed: ${'$'}(${'$'}_.Exception.Message)" + throw + } finally { Restore-KittyTuneShortcuts -Snapshot ${'$'}shortcuts } + if (${'$'}installed) { + Log "Relaunching verified version ${'$'}actualVersion from ${'$'}exePath" Start-Process -FilePath ${'$'}exePath - } else { - Log "Could not find KittyTune.exe to relaunch" } Log "Updater script finished." """.trimIndent() @@ -647,6 +669,10 @@ object UpdateManager { if (installer != null && installer.exists()) { val currentPid = runCatching { ProcessHandle.current().pid() }.getOrDefault(0L) val targetExe = resolveKittyTuneExe() + if (targetExe == null) { + _status.value = UpdateStatus.ERROR + return + } val tmpDir = File(System.getProperty("java.io.tmpdir"), "KittyTuneUpdates") tmpDir.mkdirs() val scriptFile = File(tmpDir, "update_install_${System.currentTimeMillis()}.ps1") @@ -659,7 +685,7 @@ object UpdateManager { logFile = logFile, msiLogFile = msiLogFile ) - scriptFile.writeText(scriptContent, Charsets.UTF_8) + scriptFile.writeBytes(byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte()) + scriptContent.toByteArray(Charsets.UTF_8)) ProcessBuilder( "powershell.exe", diff --git a/src/main/resources/updater/windows-install-support.ps1 b/src/main/resources/updater/windows-install-support.ps1 new file mode 100644 index 00000000..f1d25769 --- /dev/null +++ b/src/main/resources/updater/windows-install-support.ps1 @@ -0,0 +1,74 @@ +function Get-KittyTuneVersion([string]$Executable) { + $app = Join-Path ([IO.Path]::GetDirectoryName($Executable)) 'app' + $config = Join-Path $app 'KittyTune.cfg' + if (!(Test-Path -LiteralPath $config -PathType Leaf)) { throw 'Installed launcher configuration is missing.' } + $lines = @(Get-Content -LiteralPath $config -Encoding UTF8) + $version = @($lines | Where-Object { $_ -match '^java-options=-Djpackage\.app-version=' } | ForEach-Object { $_.Substring('java-options=-Djpackage.app-version='.Length) }) + if ($version.Count -ne 1) { throw 'Cannot determine the installed application version.' } + $jars = @($lines | Where-Object { $_.StartsWith('app.classpath=') }) + if (!$jars.Count) { throw 'Installed launcher classpath is missing.' } + foreach ($line in $jars) { + $jar = $line.Substring('app.classpath='.Length).Replace('$APPDIR', $app) + if (!(Test-Path -LiteralPath $jar -PathType Leaf)) { throw "Installed application file is missing: $jar" } + } + return $version[0].Trim() +} + +function Get-KittyTuneVersionKey([string]$Version) { + $number = ($Version.Trim() -replace '^v', '') -replace '-.*$', '' + $parsed = $null + if (![Version]::TryParse($number, [ref]$parsed)) { throw "Invalid application version: $Version" } + return '{0}.{1}.{2}.{3}' -f $parsed.Major, $parsed.Minor, [Math]::Max(0,$parsed.Build), [Math]::Max(0,$parsed.Revision) +} + +function Get-KittyTuneMsiVersion([string]$Package) { + $installer = $database = $view = $record = $null + try { + $installer = New-Object -ComObject WindowsInstaller.Installer + $database = $installer.OpenDatabase($Package, 0) + $view = $database.OpenView("SELECT Value FROM Property WHERE Property = 'ProductVersion'") + [void]$view.Execute() + $record = $view.Fetch() + if (!$record) { throw 'Installer product version is missing.' } + return [string]$record.StringData(1) + } finally { + foreach ($item in @($record,$view,$database,$installer)) { + if ($null -ne $item) { [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($item) } + } + } +} + +function Save-KittyTuneShortcuts { + param([string]$Executable, [string[]]$Folders = @( + [Environment]::GetFolderPath('Desktop'), + [Environment]::GetFolderPath('StartMenu'), + [Environment]::GetFolderPath('CommonDesktopDirectory'), + [Environment]::GetFolderPath('CommonStartMenu'), + (Join-Path $env:APPDATA 'Microsoft/Internet Explorer/Quick Launch/User Pinned/TaskBar') + )) + $shell = New-Object -ComObject WScript.Shell + try { + foreach ($folder in $Folders | Select-Object -Unique) { + if (!$folder -or !(Test-Path -LiteralPath $folder -PathType Container)) { continue } + foreach ($file in Get-ChildItem -LiteralPath $folder -Filter '*.lnk' -File -Recurse -ErrorAction SilentlyContinue) { + $link = $null + try { + $link = $shell.CreateShortcut($file.FullName) + if ($link.TargetPath -and [IO.Path]::GetFullPath($link.TargetPath).Equals($Executable,[StringComparison]::OrdinalIgnoreCase)) { + [pscustomobject]@{Path=$file.FullName; Bytes=[IO.File]::ReadAllBytes($file.FullName)} + } + } catch { Write-Warning "Could not inspect shortcut $($file.FullName): $($_.Exception.Message)" } + finally { if ($null -ne $link) { [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($link) } } + } + } + } finally { [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($shell) } +} + +function Restore-KittyTuneShortcuts([object[]]$Snapshot) { + foreach ($link in $Snapshot) { + try { + [void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($link.Path)) + [IO.File]::WriteAllBytes($link.Path, $link.Bytes) + } catch { Write-Warning "Could not restore shortcut $($link.Path): $($_.Exception.Message)" } + } +} diff --git a/src/test/kotlin/WindowsUpdateTest.kt b/src/test/kotlin/WindowsUpdateTest.kt new file mode 100644 index 00000000..6d2899bb --- /dev/null +++ b/src/test/kotlin/WindowsUpdateTest.kt @@ -0,0 +1,138 @@ +package com.alananasss.kittytune.data + +import com.alananasss.kittytune.data.network.GithubRelease +import java.io.File +import java.util.concurrent.TimeUnit +import org.junit.Test +import org.junit.Assume.assumeTrue +import kotlin.test.* + +class WindowsUpdateTest { + @Test fun `restart resolves the launcher property before installed fallback`() { + val folder = kotlin.io.path.createTempDirectory("kitty portable ").toFile() + val exe = File(folder, "KittyTune.exe").apply { writeText("fixture") } + val before = System.getProperty("jpackage.app-path") + try { + System.setProperty("jpackage.app-path", exe.path) + assertEquals(exe.canonicalFile, UpdateManager.resolveKittyTuneExe()?.canonicalFile) + } finally { + if (before == null) System.clearProperty("jpackage.app-path") else System.setProperty("jpackage.app-path", before) + folder.deleteRecursively() + } + } + + @Test fun `failed install never relaunches the existing exe`() = runInstaller(1603, false, false) + @Test fun `successful exit with stale files is rejected`() = runInstaller(0, false, false) + @Test fun `verified update stays in place and writes its version`() = runInstaller(0, true, true) + @Test fun `missing application jar is rejected`() = runInstaller(0, true, false, missingJar = true) + @Test fun `reboot initiated does not trigger another install`() = runInstaller(1641, true, false, true) + @Test fun `reboot required is success rather than another install attempt`() = runInstaller(3010, true, false, true) + + @Test fun `shortcuts retain their original bytes and unrelated links are untouched`() { + assumeTrue(System.getProperty("os.name").startsWith("Windows")) + val root = kotlin.io.path.createTempDirectory("kitty shortcuts ").toFile() + fun quote(file: File) = file.path.replace("'", "''") + try { + val support = requireNotNull(javaClass.getResourceAsStream("/updater/windows-install-support.ps1")).use { it.bufferedReader().readText() } + val script = support + "\n" + """ + ${'$'}ErrorActionPreference = 'Stop' + ${'$'}root = '${quote(root)}' + ${'$'}exe = Join-Path ${'$'}root 'KittyTune.exe' + ${'$'}path = Join-Path ${'$'}root 'custom.lnk' + ${'$'}otherPath = Join-Path ${'$'}root 'unrelated.lnk' + [IO.File]::WriteAllText(${'$'}exe, 'fixture') + ${'$'}shell = New-Object -ComObject WScript.Shell + try { + ${'$'}link = ${'$'}shell.CreateShortcut(${'$'}path) + ${'$'}link.TargetPath = ${'$'}exe + ${'$'}link.Arguments = '--custom' + ${'$'}link.WorkingDirectory = ${'$'}root + ${'$'}link.IconLocation = "${'$'}env:SystemRoot\system32\shell32.dll,5" + ${'$'}link.Save() + ${'$'}other = ${'$'}shell.CreateShortcut(${'$'}otherPath) + ${'$'}other.TargetPath = Join-Path ${'$'}root 'other.exe' + ${'$'}other.Save() + ${'$'}original = [Convert]::ToBase64String([IO.File]::ReadAllBytes(${'$'}path)) + ${'$'}unrelated = [Convert]::ToBase64String([IO.File]::ReadAllBytes(${'$'}otherPath)) + ${'$'}snapshot = @(Save-KittyTuneShortcuts -Executable ${'$'}exe -Folders @(${'$'}root)) + if (${'$'}snapshot.Count -ne 1) { throw 'Wrong shortcuts selected' } + Remove-Item -LiteralPath ${'$'}path + Restore-KittyTuneShortcuts -Snapshot ${'$'}snapshot + if ([Convert]::ToBase64String([IO.File]::ReadAllBytes(${'$'}path)) -ne ${'$'}original) { throw 'Shortcut bytes changed' } + if ([Convert]::ToBase64String([IO.File]::ReadAllBytes(${'$'}otherPath)) -ne ${'$'}unrelated) { throw 'Unrelated shortcut changed' } + } finally { + foreach (${'$'}item in @(${'$'}link,${'$'}other,${'$'}shell)) { + if (${'$'}null -ne ${'$'}item) { [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject(${'$'}item) } + } + } + """.trimIndent() + val file = File(root, "shortcuts.ps1").apply { writeBytes(byteArrayOf(0xEF.toByte(),0xBB.toByte(),0xBF.toByte())+script.toByteArray()) } + val outputFile = File(root, "powershell-output.log") + val process = ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file.path) + .redirectErrorStream(true).redirectOutput(outputFile).start() + if (!process.waitFor(60, TimeUnit.SECONDS)) { + process.destroyForcibly() + fail("Updater test timed out: ${outputFile.readText()}") + } + val output = outputFile.readText() + assertEquals(0,process.waitFor(),output) + } finally { root.deleteRecursively() } + } + + private fun runInstaller(exit: Int, replace: Boolean, success: Boolean, reboot: Boolean = false, missingJar: Boolean = false) { + assumeTrue(System.getProperty("os.name").startsWith("Windows")) + val root = kotlin.io.path.createTempDirectory("kitty update Ω [mix] O'Brien ").toFile() + val image = File(root, "portable app").apply { mkdirs() } + val app = File(image, "app").apply { mkdirs() } + val exe = File(image, "KittyTune.exe").apply { writeText("fixture") } + File(app, "main.jar").writeText("fixture") + val cfg = File(app, "KittyTune.cfg").apply { writeText("app.classpath=${'$'}APPDIR/main.jar\njava-options=-Djpackage.app-version=1.0.0\n") } + val installer = File(root, "KittyTune installer.msi").apply { writeText("fixture") } + val launched = File(root, "launched") + val arguments = File(root, "arguments.txt") + val prior = UpdateManager.releaseInfo + fun quote(file: File) = file.path.replace("'", "''") + try { + UpdateManager.releaseInfo = GithubRelease(tagName="v2.0.0") + val script = UpdateManager.buildWindowsUpdaterScript(2147483000,installer,exe,File(root, "update.log"),File(root, "msi.log")) + val mocks = """ + function Get-Process { param(${'$'}Id, ${'$'}Name, ${'$'}ErrorAction) return ${'$'}null } + function Start-Sleep { param(${'$'}Seconds, ${'$'}Milliseconds) } + function Start-Process { + param(${'$'}FilePath, ${'$'}ArgumentList, [switch]${'$'}Wait, [switch]${'$'}PassThru, ${'$'}WindowStyle) + if (${'$'}FilePath -eq 'msiexec.exe') { + [IO.File]::AppendAllText('${quote(arguments)}', ((${'$'}ArgumentList -join '|') + "`n")) + ${if(replace) "[IO.File]::WriteAllText('${quote(cfg)}', ('app.classpath=${'$'}APPDIR/main.jar' + [Environment]::NewLine + 'java-options=-Djpackage.app-version=2.0.0'))" else ""} + ${if (missingJar) "Remove-Item -LiteralPath '${quote(File(app, "main.jar"))}' -ErrorAction SilentlyContinue" else ""} + return [pscustomobject]@{ExitCode=$exit} + } + [IO.File]::WriteAllText('${quote(launched)}', [string]${'$'}FilePath) + return [pscustomobject]@{ExitCode=0} + } + """.trimIndent() + val file = File(root, "run.ps1").apply { writeBytes(byteArrayOf(0xEF.toByte(),0xBB.toByte(),0xBF.toByte())+(mocks+"\n"+script).toByteArray()) } + val outputFile = File(root, "powershell-output.log") + val process = ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file.path) + .redirectErrorStream(true).redirectOutput(outputFile).start() + if (!process.waitFor(60, TimeUnit.SECONDS)) { + process.destroyForcibly() + fail("Updater test timed out: ${outputFile.readText()}") + } + val output = outputFile.readText() + assertEquals(success || reboot, process.exitValue() == 0, output) + assertEquals(success, launched.exists(), output) + val attempts = arguments.readLines() + attempts.forEach { + assertTrue(it.contains("INSTALLDIR=\"${image.path}\""),it) + assertTrue(it.contains("REINSTALLMODE=amus"),it) + } + if (reboot) assertEquals(1,attempts.size) + if (success) { + assertEquals(exe.path,launched.readText()) + assertEquals("2.0.0",File(image, "version.txt").readText().trim()) + assertTrue(arguments.readText().contains("INSTALLDIR=\"${image.path}\""), arguments.readText()) + assertEquals(1,arguments.readLines().size) + } + } finally { UpdateManager.releaseInfo = prior; root.deleteRecursively() } + } +} From 8874f1c2d25df286df0d0f5ccb06e3bb67c3a4fe Mon Sep 17 00:00:00 2001 From: ilgiova237 Date: Mon, 16 Nov 2026 06:56:51 +0100 Subject: [PATCH 2/3] fix(packaging): include the prepared Windows image in MSI builds --- build.gradle.kts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/build.gradle.kts b/build.gradle.kts index c5115569..0e1b4fc1 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -915,11 +915,20 @@ tasks.withType().configureEach { + if (desktopIsWindows && name in listOf("packageMsi", "packageReleaseMsi")) { + val imageName = if (name == "packageReleaseMsi") "createReleaseDistributable" else "createDistributable" + val image = tasks.named(imageName) + dependsOn(image) + appImage.set(image.flatMap { it.destinationDir.dir("KittyTune") }) + } +} + tasks.matching { it.name == "zipWindowsPortable" || (it.name.startsWith("package") && it.name.endsWith("Msi")) }.configureEach { if (desktopIsWindows) dependsOn(enableSegmentHeap) } From 6c6c0be988d69153c5c6cbfc3ba738b46b13bae8 Mon Sep 17 00:00:00 2001 From: alan7383 <75907296+alan7383@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:25:52 +0100 Subject: [PATCH 3/3] fix(updater): protect other registered Windows installations --- build.gradle.kts | 4 +- .../kittytune/data/UpdateManager.kt | 11 ++--- .../updater/windows-install-support.ps1 | 42 +++++++++++++++++-- src/test/kotlin/WindowsUpdateTest.kt | 21 +++++++++- 4 files changed, 66 insertions(+), 12 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 0e1b4fc1..9dbdbc79 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1006,14 +1006,14 @@ tasks.register("headlessTest") { "PlayerRemainingTimeTest", "PlaylistTotalDurationTest", "SettingsSearchTest", "VolumeCurveTest", "TrackTrimTest", "TrimTimeParseTest", "SyncMergeTest", "DownloadJobsTest", "DownloadFilesTest", "LyricsMergePerformanceTest", "*LyricsMatcherTest", "WindowBoundsRestorationTest", "TextFieldShortcutGuardTest", "PaletteCacheTest", "PeakLimiterTest", "*FadingEdgeRenderTest", - "WindowsNativeDspTest", "AudioLineCloserTest", "PlaybackDrmSessionTest", "*HlsRetirementTest", "*SoundCloudDrmPipelineTest", "DesktopRenderTest", "DesktopDensityTest", + "*WindowsUpdateTest", "WindowsNativeDspTest", "AudioLineCloserTest", "PlaybackDrmSessionTest", "*HlsRetirementTest", "*SoundCloudDrmPipelineTest", "DesktopRenderTest", "DesktopDensityTest", "ConnectNetworkStateTest", "ConnectRefactorTest", "SyncPlaybackTest", "ConnectWireTest", "ConnectSocketListenerTest", "ConnectHandoffTest", "ConnectLanServerTest", "ConnectRenderTest", "LocalizationParityTest", "PlayerButtonRowsTest", "PlayheadClockTest", "WheelSeekTest", "PlayingBarsTest", "*WslSidecarSetupTest", "*WslUninstallRenderTest", "*ProtectedTracksNoticeTest", "*ProtectedTracksCardsRenderTest", "*MixQueuePlannerTest", "*MixRenderTest", "*AudioPathRenderTest", "*LyricsSweepRenderTest", "*ShareCardTest", "OnnxNativeLoadTest", "ToolWindowStyleRaiseToFrontTest", "*SoundCloudOAuthTest", "ClearStreamFilesTest", "ThemePersistenceTest", "SetupOnboardingTest", "*WindowsProtectedPlaybackTest", "*WindowsProtectedMediaTest", "Issue93BugfixesTest.testWindowsUpdaterScriptConstruction*", "InstallerProcessTest", "*ChromeCdmArchiveTest", "KittyTuneProcessesTest", "*SidecarLockOrderTest", - "*HlsOpeningTest", "*WindowsHeadphoneDetectionTest", "*WindowsUpdateTest" + "*HlsOpeningTest", "*WindowsHeadphoneDetectionTest" ).forEach(::includeTestsMatching) } } diff --git a/src/main/kotlin/com/alananasss/kittytune/data/UpdateManager.kt b/src/main/kotlin/com/alananasss/kittytune/data/UpdateManager.kt index 0c934619..ee13d374 100644 --- a/src/main/kotlin/com/alananasss/kittytune/data/UpdateManager.kt +++ b/src/main/kotlin/com/alananasss/kittytune/data/UpdateManager.kt @@ -507,12 +507,12 @@ object UpdateManager { internal fun resolveKittyTuneExe(): File? { val jpackagePath = System.getProperty("jpackage.app-path") ?: System.getProperty("jpackage.app.path") - val possibleExePaths = mutableListOf() - jpackagePath?.let { p -> - val f = File(p) - if (f.isFile) possibleExePaths.add(f) - else if (f.isDirectory) File(f, "KittyTune.exe").let { if (it.exists()) possibleExePaths.add(it) } + if (jpackagePath != null) { + val path = File(jpackagePath) + val launcher = if (path.isDirectory) File(path, "KittyTune.exe") else path + return launcher.takeIf { it.isAbsolute && it.isFile && it.name.equals("KittyTune.exe", ignoreCase = true) } } + val possibleExePaths = mutableListOf() possibleExePaths.addAll(listOfNotNull( File(System.getenv("LOCALAPPDATA") ?: "", "KittyTune/KittyTune.exe"), File(System.getenv("LOCALAPPDATA") ?: "", "Programs/KittyTune/KittyTune.exe"), @@ -606,6 +606,7 @@ object UpdateManager { ${'$'}expectedVersion = Get-KittyTuneMsiVersion '$escapedInstaller' ${'$'}expectedKey = Get-KittyTuneVersionKey ${'$'}expectedVersion } + ${if (isMsi) "Assert-KittyTuneMsiTarget '$escapedInstaller' ${'$'}installDir" else ""} } catch { Log "Cannot start update: ${'$'}(${'$'}_.Exception.Message)" throw diff --git a/src/main/resources/updater/windows-install-support.ps1 b/src/main/resources/updater/windows-install-support.ps1 index f1d25769..dd011041 100644 --- a/src/main/resources/updater/windows-install-support.ps1 +++ b/src/main/resources/updater/windows-install-support.ps1 @@ -1,4 +1,5 @@ function Get-KittyTuneVersion([string]$Executable) { + if (![IO.File]::Exists($Executable)) { throw 'Installed launcher executable is missing.' } $app = Join-Path ([IO.Path]::GetDirectoryName($Executable)) 'app' $config = Join-Path $app 'KittyTune.cfg' if (!(Test-Path -LiteralPath $config -PathType Leaf)) { throw 'Installed launcher configuration is missing.' } @@ -21,15 +22,15 @@ function Get-KittyTuneVersionKey([string]$Version) { return '{0}.{1}.{2}.{3}' -f $parsed.Major, $parsed.Minor, [Math]::Max(0,$parsed.Build), [Math]::Max(0,$parsed.Revision) } -function Get-KittyTuneMsiVersion([string]$Package) { +function Get-KittyTuneMsiProperty([string]$Package, [string]$Property) { $installer = $database = $view = $record = $null try { $installer = New-Object -ComObject WindowsInstaller.Installer $database = $installer.OpenDatabase($Package, 0) - $view = $database.OpenView("SELECT Value FROM Property WHERE Property = 'ProductVersion'") + $view = $database.OpenView("SELECT Value FROM Property WHERE Property = '$Property'") [void]$view.Execute() $record = $view.Fetch() - if (!$record) { throw 'Installer product version is missing.' } + if (!$record) { throw "Installer property $Property is missing." } return [string]$record.StringData(1) } finally { foreach ($item in @($record,$view,$database,$installer)) { @@ -38,6 +39,41 @@ function Get-KittyTuneMsiVersion([string]$Package) { } } +function Get-KittyTuneMsiVersion([string]$Package) { + Get-KittyTuneMsiProperty $Package 'ProductVersion' +} + +function Get-KittyTuneRelatedInstallLocations([string]$Package) { + $upgradeCode = Get-KittyTuneMsiProperty $Package 'UpgradeCode' + $installer = $products = $null + try { + $installer = New-Object -ComObject WindowsInstaller.Installer + $products = $installer.RelatedProducts($upgradeCode) + for ($i = 0; $i -lt $products.Count; $i++) { + $product = $products.Item($i) + $location = [string]$installer.ProductInfo($product, 'InstallLocation') + if ([string]::IsNullOrWhiteSpace($location) -or ![IO.Path]::IsPathRooted($location)) { + throw "Cannot determine the directory of registered KittyTune installation $product." + } + $location + } + } finally { + foreach ($item in @($products, $installer)) { + if ($null -ne $item) { [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($item) } + } + } +} + +function Assert-KittyTuneMsiTarget([string]$Package, [string]$InstallDir) { + $target = [IO.Path]::GetFullPath($InstallDir).TrimEnd([char[]]'\/') + foreach ($location in Get-KittyTuneRelatedInstallLocations $Package) { + $registered = [IO.Path]::GetFullPath($location).TrimEnd([char[]]'\/') + if (!$target.Equals($registered, [StringComparison]::OrdinalIgnoreCase)) { + throw "KittyTune is registered in '$registered', but the running copy is in '$target'. Start the registered copy to update it, or download the portable ZIP for this copy." + } + } +} + function Save-KittyTuneShortcuts { param([string]$Executable, [string[]]$Folders = @( [Environment]::GetFolderPath('Desktop'), diff --git a/src/test/kotlin/WindowsUpdateTest.kt b/src/test/kotlin/WindowsUpdateTest.kt index 6d2899bb..f4ae255b 100644 --- a/src/test/kotlin/WindowsUpdateTest.kt +++ b/src/test/kotlin/WindowsUpdateTest.kt @@ -15,6 +15,8 @@ class WindowsUpdateTest { try { System.setProperty("jpackage.app-path", exe.path) assertEquals(exe.canonicalFile, UpdateManager.resolveKittyTuneExe()?.canonicalFile) + System.setProperty("jpackage.app-path", File(folder, "missing.exe").path) + assertNull(UpdateManager.resolveKittyTuneExe()) } finally { if (before == null) System.clearProperty("jpackage.app-path") else System.setProperty("jpackage.app-path", before) folder.deleteRecursively() @@ -25,6 +27,9 @@ class WindowsUpdateTest { @Test fun `successful exit with stale files is rejected`() = runInstaller(0, false, false) @Test fun `verified update stays in place and writes its version`() = runInstaller(0, true, true) @Test fun `missing application jar is rejected`() = runInstaller(0, true, false, missingJar = true) + @Test fun `a registered MSI installation in another folder blocks the update`() = + runInstaller(0, true, false, conflictingInstall = true) + @Test fun `missing installed executable is rejected`() = runInstaller(0, true, false, missingExe = true) @Test fun `reboot initiated does not trigger another install`() = runInstaller(1641, true, false, true) @Test fun `reboot required is success rather than another install attempt`() = runInstaller(3010, true, false, true) @@ -79,7 +84,9 @@ class WindowsUpdateTest { } finally { root.deleteRecursively() } } - private fun runInstaller(exit: Int, replace: Boolean, success: Boolean, reboot: Boolean = false, missingJar: Boolean = false) { + private fun runInstaller(exit: Int, replace: Boolean, success: Boolean, reboot: Boolean = false, missingJar: Boolean = false, + conflictingInstall: Boolean = false, missingExe: Boolean = false, + ) { assumeTrue(System.getProperty("os.name").startsWith("Windows")) val root = kotlin.io.path.createTempDirectory("kitty update Ω [mix] O'Brien ").toFile() val image = File(root, "portable app").apply { mkdirs() } @@ -95,6 +102,10 @@ class WindowsUpdateTest { try { UpdateManager.releaseInfo = GithubRelease(tagName="v2.0.0") val script = UpdateManager.buildWindowsUpdaterScript(2147483000,installer,exe,File(root, "update.log"),File(root, "msi.log")) + // Replace only the Windows Installer query. The real guard and generated script still run. + val registered = if (conflictingInstall) File(root, "another installation") else image + val query = "function Get-KittyTuneRelatedInstallLocations { '${quote(registered)}' }" + val scriptWithFixture = script.replaceFirst("Log \"Starting updater", "$query\nLog \"Starting updater") val mocks = """ function Get-Process { param(${'$'}Id, ${'$'}Name, ${'$'}ErrorAction) return ${'$'}null } function Start-Sleep { param(${'$'}Seconds, ${'$'}Milliseconds) } @@ -104,13 +115,14 @@ class WindowsUpdateTest { [IO.File]::AppendAllText('${quote(arguments)}', ((${'$'}ArgumentList -join '|') + "`n")) ${if(replace) "[IO.File]::WriteAllText('${quote(cfg)}', ('app.classpath=${'$'}APPDIR/main.jar' + [Environment]::NewLine + 'java-options=-Djpackage.app-version=2.0.0'))" else ""} ${if (missingJar) "Remove-Item -LiteralPath '${quote(File(app, "main.jar"))}' -ErrorAction SilentlyContinue" else ""} + ${if (missingExe) "Remove-Item -LiteralPath '${quote(exe)}'" else ""} return [pscustomobject]@{ExitCode=$exit} } [IO.File]::WriteAllText('${quote(launched)}', [string]${'$'}FilePath) return [pscustomobject]@{ExitCode=0} } """.trimIndent() - val file = File(root, "run.ps1").apply { writeBytes(byteArrayOf(0xEF.toByte(),0xBB.toByte(),0xBF.toByte())+(mocks+"\n"+script).toByteArray()) } + val file = File(root, "run.ps1").apply { writeBytes(byteArrayOf(0xEF.toByte(),0xBB.toByte(),0xBF.toByte())+(mocks+"\n"+scriptWithFixture).toByteArray()) } val outputFile = File(root, "powershell-output.log") val process = ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file.path) .redirectErrorStream(true).redirectOutput(outputFile).start() @@ -121,6 +133,11 @@ class WindowsUpdateTest { val output = outputFile.readText() assertEquals(success || reboot, process.exitValue() == 0, output) assertEquals(success, launched.exists(), output) + if (conflictingInstall) { + assertFalse(arguments.exists(), "Windows Installer must not be launched for the other copy") + assertContains(File(root, "update.log").readText(), "another installation") + return + } val attempts = arguments.readLines() attempts.forEach { assertTrue(it.contains("INSTALLDIR=\"${image.path}\""),it)