Pārlūkot izejas kodu

support for new linux-wallpaperengine-kde added

UwU 1 mēnesi atpakaļ
vecāks
revīzija
2a6cb1ca31
97 mainītis faili ar 2279 papildinājumiem un 783 dzēšanām
  1. 34 8
      .github/workflows/build.yml
  2. 2 1
      .oxlintrc.json
  3. 12 1
      electron.vite.config.ts
  4. 220 161
      package-lock.json
  5. 7 3
      package.json
  6. 256 275
      packaging/flathub/generated-sources.json
  7. 6 3
      patches/steamworks-vote/README.md
  8. 10 0
      patches/steamworks-vote/build.sh
  9. 53 8
      src/main/index.ts
  10. 0 1
      src/main/ipc/backup.handlers.ts
  11. 49 0
      src/main/ipc/shell.handlers.test.ts
  12. 5 1
      src/main/ipc/shell.handlers.ts
  13. 5 1
      src/main/ipc/steam.handlers.ts
  14. 123 0
      src/main/services/backup.service.test.ts
  15. 98 11
      src/main/services/backup.service.ts
  16. 2 5
      src/main/services/config.service.ts
  17. 1 1
      src/main/services/dependency.service.ts
  18. 0 5
      src/main/services/desktop-icons-overlay.py
  19. 2 7
      src/main/services/desktop-icons.service.ts
  20. 12 1
      src/main/services/display.service.ts
  21. 1 1
      src/main/services/gnome-extension.service.ts
  22. 26 1
      src/main/services/library-transfer.service.test.ts
  23. 13 4
      src/main/services/library-transfer.service.ts
  24. 7 7
      src/main/services/library.service.ts
  25. 4 4
      src/main/services/lwe-prebuilt.service.ts
  26. 12 0
      src/main/services/lwe.service.test.ts
  27. 41 58
      src/main/services/lwe.service.ts
  28. 10 4
      src/main/services/playlist-player.service.ts
  29. 2 8
      src/main/services/playlist.service.ts
  30. 13 4
      src/main/services/schedule.service.ts
  31. 0 1
      src/main/services/shortcuts.service.ts
  32. 9 9
      src/main/services/static-wallpaper.service.test.ts
  33. 3 2
      src/main/services/steam-list-cache.ts
  34. 99 0
      src/main/services/steam.service.test.ts
  35. 19 5
      src/main/services/steam.service.ts
  36. 1 1
      src/main/services/update.service.ts
  37. 2 2
      src/main/services/wallpaper-state.service.ts
  38. 5 15
      src/main/services/wallpaper.service.ts
  39. 75 0
      src/main/services/workshop-verify.service.test.ts
  40. 36 3
      src/main/services/workshop-verify.service.ts
  41. 32 0
      src/main/services/workshop.service.test.ts
  42. 12 23
      src/main/services/workshop.service.ts
  43. 44 0
      src/main/utils/buildDir.test.ts
  44. 23 0
      src/main/utils/buildDir.ts
  45. 20 0
      src/main/utils/contained.test.ts
  46. 8 0
      src/main/utils/contained.ts
  47. 68 0
      src/main/utils/engineProcess.test.ts
  48. 16 0
      src/main/utils/engineProcess.ts
  49. 5 5
      src/main/utils/flatpak.ts
  50. 63 0
      src/main/utils/github.test.ts
  51. 11 0
      src/main/utils/github.ts
  52. 0 1
      src/main/utils/paths.ts
  53. 7 14
      src/main/utils/platform.ts
  54. 90 0
      src/main/utils/safeStore.test.ts
  55. 36 0
      src/main/utils/safeStore.ts
  56. 72 0
      src/main/utils/urlPolicy.test.ts
  57. 41 0
      src/main/utils/urlPolicy.ts
  58. 1 4
      src/main/utils/video.ts
  59. 48 0
      src/main/utils/wallpaperScripts.test.ts
  60. 33 0
      src/main/utils/wallpaperScripts.ts
  61. 0 1
      src/renderer/src/App.tsx
  62. 40 76
      src/renderer/src/components/common/DetailSidebar.tsx
  63. 0 1
      src/renderer/src/components/common/FilterPanel.tsx
  64. 1 5
      src/renderer/src/components/common/ShortcutRow.tsx
  65. 6 7
      src/renderer/src/components/library/LibraryView.tsx
  66. 6 5
      src/renderer/src/components/library/WallpaperCard.tsx
  67. 3 2
      src/renderer/src/components/settings/AppearanceSettings.tsx
  68. 0 1
      src/renderer/src/components/settings/SettingsView.tsx
  69. 1 1
      src/renderer/src/components/workshop/WorkshopBrowser.tsx
  70. 0 6
      src/renderer/src/hooks/useContextMenuPosition.ts
  71. 0 1
      src/renderer/src/hooks/useFavorites.ts
  72. 60 0
      src/renderer/src/hooks/useKeyedCommits.ts
  73. 0 1
      src/renderer/src/hooks/usePreviewSize.ts
  74. 0 1
      src/renderer/src/hooks/useSelectableGrid.ts
  75. 3 1
      src/renderer/src/hooks/useSubscriptionQueue.ts
  76. 0 1
      src/renderer/src/hooks/useVotes.ts
  77. 0 2
      src/renderer/src/utils/appearance.ts
  78. 16 0
      src/renderer/src/utils/dom.test.ts
  79. 6 0
      src/renderer/src/utils/dom.ts
  80. 115 0
      src/renderer/src/utils/keyedCommitter.test.ts
  81. 38 0
      src/renderer/src/utils/keyedCommitter.ts
  82. 38 0
      src/shared/csp.test.ts
  83. 13 0
      src/shared/csp.ts
  84. 2 0
      src/shared/i18n/locales/de.ts
  85. 2 0
      src/shared/i18n/locales/en.ts
  86. 2 0
      src/shared/i18n/locales/es.ts
  87. 2 0
      src/shared/i18n/locales/fr.ts
  88. 2 0
      src/shared/i18n/locales/it.ts
  89. 2 0
      src/shared/i18n/locales/ja.ts
  90. 2 0
      src/shared/i18n/locales/ko.ts
  91. 2 0
      src/shared/i18n/locales/pl.ts
  92. 2 0
      src/shared/i18n/locales/pt.ts
  93. 2 0
      src/shared/i18n/locales/ru.ts
  94. 2 0
      src/shared/i18n/locales/tr.ts
  95. 2 0
      src/shared/i18n/locales/zh-CN.ts
  96. 2 0
      src/shared/i18n/locales/zh-TW.ts
  97. 2 2
      src/shared/videoTrim.ts

+ 34 - 8
.github/workflows/build.yml

@@ -7,6 +7,9 @@ on:
   pull_request:
   workflow_dispatch:
 
+permissions:
+  contents: read
+
 jobs:
   steamworks-vote:
     runs-on: ubuntu-latest
@@ -53,6 +56,10 @@ jobs:
 
       - run: npm ci
 
+      - name: Say that the patched steamworks.js is missing
+        if: ${{ needs.steamworks-vote.result != 'success' }}
+        run: echo "::warning::The patched steamworks.js build ended with ${{ needs.steamworks-vote.result }}, this app falls back to unconfirmed votes and favorites"
+
       - uses: actions/download-artifact@v8
         if: ${{ needs.steamworks-vote.result == 'success' }}
         with:
@@ -75,8 +82,9 @@ jobs:
             dist/*.deb
           if-no-files-found: error
 
-  # the engine's portable tarball for the Flatpak: from the newest release that has one, else the newest artifact of the
-  # engine's CMake workflow (a release only gets the tarball at the end of that run)
+  # the engine's portable tarball for the Flatpak. A tag build only takes a released engine: the newest release that has
+  # the tarball, or the one named in the ENGINE_TAG repository variable. Other builds may also take the newest artifact
+  # of the engine's CMake workflow (a release only gets the tarball at the end of that run)
   engine-portable:
     runs-on: ubuntu-latest
     outputs:
@@ -88,25 +96,37 @@ jobs:
           GH_TOKEN: ${{ github.token }}
           ENGINE: WallpaperEngineLover/linux-wallpaperengine-kde
           ASSET: linux-wallpaperengine-kde-portable-x86_64.tar.gz
+          ENGINE_TAG: ${{ vars.ENGINE_TAG }}
+          RELEASE_BUILD: ${{ startsWith(github.ref, 'refs/tags/v') }}
         run: |
           mkdir -p engine
-          tag=$(gh api "repos/$ENGINE/releases?per_page=30" \
-            --jq "[.[] | select(any(.assets[]; .name == \"$ASSET\"))][0].tag_name // empty")
+          tag="$ENGINE_TAG"
+          if [ -z "$tag" ]; then
+            tag=$(gh api "repos/$ENGINE/releases?per_page=30" \
+              --jq "[.[] | select(any(.assets[]; .name == \"$ASSET\"))][0].tag_name // empty")
+          fi
           if [ -n "$tag" ]; then
             echo "using release $tag"
             gh release download "$tag" -R "$ENGINE" -p "$ASSET" -D engine
-          else
+            digest=$(gh api "repos/$ENGINE/releases/tags/$tag" --jq ".assets[] | select(.name == \"$ASSET\") | .digest // empty")
+            case "$digest" in
+              sha256:*) echo "${digest#sha256:}  engine/$ASSET" | sha256sum -c - ;;
+              *) echo "::warning::GitHub gave no sha256 for $ASSET of $tag, it was not checked" ;;
+            esac
+            echo "Flatpak engine: release $tag" >> "$GITHUB_STEP_SUMMARY"
+          elif [ "$RELEASE_BUILD" != "true" ]; then
             # the newest unexpired artifact, also from a run that failed later on or is still going
             run=$(gh api "repos/$ENGINE/actions/artifacts?name=linux-wallpaperengine-kde-portable&per_page=10" \
               --jq '[.artifacts[] | select(.expired | not)][0].workflow_run.id // empty')
             if [ -n "$run" ] && gh run download "$run" -R "$ENGINE" -n linux-wallpaperengine-kde-portable -D engine; then
               echo "using the artifact of CMake run $run"
+              echo "Flatpak engine: artifact of CMake run $run" >> "$GITHUB_STEP_SUMMARY"
             fi
           fi
           if [ -f "engine/$ASSET" ]; then
             echo "found=true" >> "$GITHUB_OUTPUT"
           else
-            echo "::warning::no portable linux-wallpaperengine-kde build in a release or a CMake run artifact, skipping the Flatpak"
+            echo "::warning::no released portable linux-wallpaperengine-kde build, skipping the Flatpak"
             echo "found=false" >> "$GITHUB_OUTPUT"
           fi
 
@@ -141,7 +161,7 @@ jobs:
       - name: Collect sources
         run: cp "$RUNNER_TEMP"/we-manager/*.deb packaging/flatpak/we-manager.deb
 
-      - uses: flatpak/flatpak-github-actions/flatpak-builder@v6
+      - uses: flatpak/flatpak-github-actions/flatpak-builder@79327416609af08178ad73b352877e51450790b3 # v6
         with:
           bundle: we-manager.flatpak
           manifest-path: packaging/flatpak/io.github.WallpaperEngineLover.we_manager.yml
@@ -179,8 +199,14 @@ jobs:
       - name: Create release
         env:
           GH_TOKEN: ${{ github.token }}
+          STEAMWORKS_RESULT: ${{ needs.steamworks-vote.result }}
         run: |
-          gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --generate-notes \
+          notes=()
+          if [ "$STEAMWORKS_RESULT" != "success" ]; then
+            echo "::warning::The patched steamworks.js build ended with $STEAMWORKS_RESULT, this release has unconfirmed votes and favorites"
+            notes=(--notes "> **Built without the patched steamworks.js** (its build ended with \`$STEAMWORKS_RESULT\`): likes, dislikes and favorites are not confirmed by Steam in this release.")
+          fi
+          gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --generate-notes "${notes[@]}" \
             release/*.AppImage release/*.deb $(ls release/steamworks.js-*.tgz release/*.flatpak 2>/dev/null)
 
   aur:

+ 2 - 1
.oxlintrc.json

@@ -13,7 +13,8 @@
     "react/react-in-jsx-scope": "off",
     "unicorn/no-array-sort": "off",
     "no-unused-vars": "warn",
-    "no-control-regex": "off"
+    "no-control-regex": "off",
+    "unicorn/require-post-message-target-origin": "off"
   },
   "ignorePatterns": ["out/**", "dist/**", "node_modules/**", "patches/**"]
 }

+ 12 - 1
electron.vite.config.ts

@@ -2,6 +2,7 @@ import { resolve } from 'path'
 import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
 import react from '@vitejs/plugin-react'
 import tailwindcss from '@tailwindcss/vite'
+import { RENDERER_CSP } from './src/shared/csp'
 
 export default defineConfig({
   main: {
@@ -44,6 +45,16 @@ export default defineConfig({
         '@shared': resolve('src/shared')
       }
     },
-    plugins: [react(), tailwindcss()]
+    plugins: [
+      react(),
+      tailwindcss(),
+      {
+        name: 'renderer-csp',
+        apply: 'build',
+        transformIndexHtml: () => [
+          { tag: 'meta', attrs: { 'http-equiv': 'Content-Security-Policy', content: RENDERER_CSP }, injectTo: 'head-prepend' }
+        ]
+      }
+    ]
   }
 })

+ 220 - 161
package-lock.json

@@ -1,12 +1,12 @@
 {
   "name": "we-manager",
-  "version": "0.7.0",
+  "version": "0.8.5",
   "lockfileVersion": 3,
   "requires": true,
   "packages": {
     "": {
       "name": "we-manager",
-      "version": "0.7.0",
+      "version": "0.8.5",
       "license": "MIT",
       "dependencies": {
         "@tanstack/react-query": "^5.101.4",
@@ -24,7 +24,7 @@
         "@types/react": "^19.2.17",
         "@types/react-dom": "^19.2.3",
         "@vitejs/plugin-react": "^5.2.0",
-        "electron": "^43.2.0",
+        "electron": "^43.7.11",
         "electron-builder": "^26.15.3",
         "electron-vite": "^5.0.0",
         "oxlint": "^1.85.0",
@@ -368,9 +368,9 @@
       "license": "MIT"
     },
     "node_modules/@electron/asar/node_modules/brace-expansion": {
-      "version": "1.1.16",
-      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.16.tgz",
-      "integrity": "sha512-IDw48K2/2kRkg9LdJxurvq3lV3aBgq0REY89duEqFRthjlPdXHKMj7EnQOXVckxzgisinf3nHfrcE2FufFLXMw==",
+      "version": "1.1.21",
+      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz",
+      "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
@@ -523,9 +523,9 @@
       }
     },
     "node_modules/@electron/rebuild": {
-      "version": "4.2.0",
-      "resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-4.2.0.tgz",
-      "integrity": "sha512-RKL/O+jGoXJMxrx/5771y1n0xTKmFuOYGO3gMmwypBM6rsH0kou0mswwdXA2JrhIkE4xyC7v9vGk0n6NPzgOxQ==",
+      "version": "4.2.1",
+      "resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-4.2.1.tgz",
+      "integrity": "sha512-IS4pG3BysRrCLJ8xTAfvg+IQDbiUoAzdJy2SfjcYKnLDy5DpCdjnPdhS5Zf5UMfrkB24xu0KC+TqcOxg+eG+6w==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
@@ -570,9 +570,9 @@
       "license": "MIT"
     },
     "node_modules/@electron/universal/node_modules/brace-expansion": {
-      "version": "2.1.2",
-      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.2.tgz",
-      "integrity": "sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA==",
+      "version": "2.1.7",
+      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz",
+      "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
@@ -580,9 +580,9 @@
       }
     },
     "node_modules/@electron/universal/node_modules/fs-extra": {
-      "version": "11.3.6",
-      "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.6.tgz",
-      "integrity": "sha512-w8ZNZr2mKIc7qeNaQ9AVPT1+iFaI+Avd4xudVOvdDJ8VytREi1Ft5Ih7hd9jjehod8vAM5GMsfQ/TpPf4EyoEA==",
+      "version": "11.4.1",
+      "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz",
+      "integrity": "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
@@ -633,9 +633,9 @@
       }
     },
     "node_modules/@electron/windows-sign/node_modules/fs-extra": {
-      "version": "11.3.6",
-      "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.6.tgz",
-      "integrity": "sha512-w8ZNZr2mKIc7qeNaQ9AVPT1+iFaI+Avd4xudVOvdDJ8VytREi1Ft5Ih7hd9jjehod8vAM5GMsfQ/TpPf4EyoEA==",
+      "version": "11.4.1",
+      "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz",
+      "integrity": "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==",
       "dev": true,
       "license": "MIT",
       "optional": true,
@@ -1450,13 +1450,13 @@
       }
     },
     "node_modules/@noble/hashes": {
-      "version": "2.2.0",
-      "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.2.0.tgz",
-      "integrity": "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==",
+      "version": "1.8.0",
+      "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
+      "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
       "dev": true,
       "license": "MIT",
       "engines": {
-        "node": ">= 20.19.0"
+        "node": "^14.21.3 || >=16"
       },
       "funding": {
         "url": "https://paulmillr.com/funding/"
@@ -1810,15 +1810,18 @@
       }
     },
     "node_modules/@peculiar/asn1-schema": {
-      "version": "2.8.0",
-      "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.8.0.tgz",
-      "integrity": "sha512-7YT0U/ze0tF2QOBbE15gKZwy5tvgGyLRiRHLzhlbOpf7BT032oBSd0haZqXn5W6l26WLlu3dyxzjM+2638/z2Q==",
+      "version": "2.11.0",
+      "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.11.0.tgz",
+      "integrity": "sha512-8xh4avo53/vXO6UEv9yaoJ83hY581geaLTygf61NPIXP5AeIZCPjJhpTaYU23IZkG+NpLN/C9FYzWp7hphIT9A==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
         "@peculiar/utils": "^2.0.2",
         "asn1js": "^3.0.10",
         "tslib": "^2.8.1"
+      },
+      "engines": {
+        "node": ">=14"
       }
     },
     "node_modules/@peculiar/json-schema": {
@@ -2474,6 +2477,72 @@
         "node": ">=14.0.0"
       }
     },
+    "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {
+      "version": "1.11.1",
+      "dev": true,
+      "inBundle": true,
+      "license": "MIT",
+      "optional": true,
+      "dependencies": {
+        "@emnapi/wasi-threads": "1.2.2",
+        "tslib": "^2.4.0"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {
+      "version": "1.11.1",
+      "dev": true,
+      "inBundle": true,
+      "license": "MIT",
+      "optional": true,
+      "dependencies": {
+        "tslib": "^2.4.0"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
+      "version": "1.2.2",
+      "dev": true,
+      "inBundle": true,
+      "license": "MIT",
+      "optional": true,
+      "dependencies": {
+        "tslib": "^2.4.0"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {
+      "version": "1.1.4",
+      "dev": true,
+      "inBundle": true,
+      "license": "MIT",
+      "optional": true,
+      "dependencies": {
+        "@tybys/wasm-util": "^0.10.1"
+      },
+      "funding": {
+        "type": "github",
+        "url": "https://github.com/sponsors/Brooooooklyn"
+      },
+      "peerDependencies": {
+        "@emnapi/core": "^1.7.1",
+        "@emnapi/runtime": "^1.7.1"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": {
+      "version": "0.10.2",
+      "dev": true,
+      "inBundle": true,
+      "license": "MIT",
+      "optional": true,
+      "dependencies": {
+        "tslib": "^2.4.0"
+      }
+    },
+    "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": {
+      "version": "2.8.1",
+      "dev": true,
+      "inBundle": true,
+      "license": "0BSD",
+      "optional": true
+    },
     "node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
       "version": "4.3.3",
       "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz",
@@ -3190,9 +3259,9 @@
       }
     },
     "node_modules/@xmldom/xmldom": {
-      "version": "0.8.13",
-      "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz",
-      "integrity": "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==",
+      "version": "0.8.15",
+      "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.15.tgz",
+      "integrity": "sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==",
       "dev": true,
       "license": "MIT",
       "engines": {
@@ -3279,9 +3348,9 @@
       }
     },
     "node_modules/app-builder-lib": {
-      "version": "26.15.3",
-      "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-26.15.3.tgz",
-      "integrity": "sha512-2VnyWkqsP5v5XbBhL3tD5Syx8iNPBYsoU7kY4S2fz7wg8Rj/nztWKCUzGKaFRTv0Xwf3/H058CR1Kvtd/3lRow==",
+      "version": "26.17.0",
+      "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-26.17.0.tgz",
+      "integrity": "sha512-wfL7EhujuODDW3uMSD8RPcr/MLzmT0dmpVfWV0wFUWXI0rIdaukzAJ7EFUSyHXOpxuBZqaIGlQt6VeQhtHhetw==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
@@ -3293,13 +3362,13 @@
         "@electron/rebuild": "^4.0.4",
         "@electron/universal": "2.0.3",
         "@malept/flatpak-bundler": "^0.4.0",
-        "@noble/hashes": "^2.2.0",
+        "@noble/hashes": "^1.8.0",
         "@peculiar/webcrypto": "^1.7.1",
         "@types/fs-extra": "9.0.13",
         "ajv": "^8.18.0",
         "asn1js": "^3.0.10",
         "async-exit-hook": "^2.0.1",
-        "builder-util": "26.15.3",
+        "builder-util": "26.16.0",
         "builder-util-runtime": "9.7.0",
         "chromium-pickle-js": "^0.2.0",
         "ci-info": "4.3.1",
@@ -3307,7 +3376,7 @@
         "dotenv": "^16.4.5",
         "dotenv-expand": "^11.0.6",
         "ejs": "^3.1.8",
-        "electron-publish": "26.15.3",
+        "electron-publish": "26.16.0",
         "fs-extra": "^10.1.0",
         "hosted-git-info": "^4.1.0",
         "isbinaryfile": "^5.0.0",
@@ -3331,8 +3400,8 @@
         "node": ">=14.0.0"
       },
       "peerDependencies": {
-        "dmg-builder": "26.15.3",
-        "electron-builder-squirrel-windows": "26.15.3"
+        "dmg-builder": "26.17.0",
+        "electron-builder-squirrel-windows": "26.17.0"
       }
     },
     "node_modules/app-builder-lib/node_modules/@electron/get": {
@@ -3449,14 +3518,14 @@
       "license": "Python-2.0"
     },
     "node_modules/asn1js": {
-      "version": "3.0.10",
-      "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz",
-      "integrity": "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==",
+      "version": "3.1.0",
+      "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.1.0.tgz",
+      "integrity": "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA==",
       "dev": true,
       "license": "BSD-3-Clause",
       "dependencies": {
         "pvtsutils": "^1.3.6",
-        "pvutils": "^1.1.5",
+        "pvutils": "^1.2.0",
         "tslib": "^2.8.1"
       },
       "engines": {
@@ -3556,9 +3625,9 @@
       "license": "MIT"
     },
     "node_modules/baseline-browser-mapping": {
-      "version": "2.10.42",
-      "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.42.tgz",
-      "integrity": "sha512-c/jurFrDLyui7o1J86yLkRu4LMsTYcBohveus7/I2Hzdn9KIP2bdJPTue/lR1KH46enoPbD77GKeSYNdyPoD3Q==",
+      "version": "2.11.29",
+      "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.29.tgz",
+      "integrity": "sha512-YeesxhUmR4h5y5V8KF8iBCqJb8YFrBJ++XBTeGcWIaQOYXGN19JM0FoiOjAhwuDoln8owMgXcWBmgHtYSkky2w==",
       "dev": true,
       "license": "Apache-2.0",
       "bin": {
@@ -3585,22 +3654,22 @@
       "optional": true
     },
     "node_modules/brace-expansion": {
-      "version": "5.0.7",
-      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.7.tgz",
-      "integrity": "sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA==",
+      "version": "5.0.12",
+      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
+      "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
         "balanced-match": "^4.0.2"
       },
       "engines": {
-        "node": "18 || 20 || >=22"
+        "node": "20 || >=22"
       }
     },
     "node_modules/browserslist": {
-      "version": "4.28.5",
-      "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.5.tgz",
-      "integrity": "sha512-Cu2E6QejHWzuDMTkuwgpABFgDfZrXLQq5V13YOACZx4mFAG4IwGTbTfHPMr4WtxlHoXSM8FIuRwYYCz5XiabaQ==",
+      "version": "4.29.3",
+      "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.3.tgz",
+      "integrity": "sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==",
       "dev": true,
       "funding": [
         {
@@ -3618,11 +3687,11 @@
       ],
       "license": "MIT",
       "dependencies": {
-        "baseline-browser-mapping": "^2.10.42",
-        "caniuse-lite": "^1.0.30001800",
-        "electron-to-chromium": "^1.5.387",
-        "node-releases": "^2.0.50",
-        "update-browserslist-db": "^1.2.3"
+        "baseline-browser-mapping": "^2.11.26",
+        "caniuse-lite": "^1.0.30001813",
+        "electron-to-chromium": "^1.5.439",
+        "node-releases": "^2.0.57",
+        "update-browserslist-db": "^1.3.3"
       },
       "bin": {
         "browserslist": "cli.js"
@@ -3639,9 +3708,9 @@
       "license": "MIT"
     },
     "node_modules/builder-util": {
-      "version": "26.15.3",
-      "resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.15.3.tgz",
-      "integrity": "sha512-q2hn7Mbo2nFNkVekPiHFx6Nfo3hURmES3tfBn+k5Pqxl2RkmP3QGqZUhH/q9Pch/4G05NRhPjDlVj1O8q4Txvw==",
+      "version": "26.16.0",
+      "resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.16.0.tgz",
+      "integrity": "sha512-RLyJhB7Si3YkzKR9ubQslWuXW3Vhs3CGe1i+SeixBZ0qTd1mk3XBmssvY22TlB6CS5blyko8Gu1JzpYk8UkYAg==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
@@ -3742,9 +3811,9 @@
       }
     },
     "node_modules/caniuse-lite": {
-      "version": "1.0.30001803",
-      "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001803.tgz",
-      "integrity": "sha512-g/uHREV2ZpK9qMalCsWaxmA6ol+DX8GYhuf3T40RKoP+oL7vhRJh8LNt73PCjpnR6l14FzfPrB5Yux4PKm2meg==",
+      "version": "1.0.30001816",
+      "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001816.tgz",
+      "integrity": "sha512-+8Yx7BXCoqk6IF8yTicjfUR6D/ldJzdlsodlEOiOSPmhK844WIgk67/zIQaGAOxNkZyyvBlrRFnLvqKIoqbAFw==",
       "dev": true,
       "funding": [
         {
@@ -4179,9 +4248,9 @@
       "license": "MIT"
     },
     "node_modules/dir-compare/node_modules/brace-expansion": {
-      "version": "1.1.16",
-      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.16.tgz",
-      "integrity": "sha512-IDw48K2/2kRkg9LdJxurvq3lV3aBgq0REY89duEqFRthjlPdXHKMj7EnQOXVckxzgisinf3nHfrcE2FufFLXMw==",
+      "version": "1.1.21",
+      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz",
+      "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
@@ -4203,14 +4272,14 @@
       }
     },
     "node_modules/dmg-builder": {
-      "version": "26.15.3",
-      "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-26.15.3.tgz",
-      "integrity": "sha512-O3zJUFUYHJKgzPqioHxfxzBzlSC1eXCSr79gMSBKBP5AgjjpmrydMsMLotEg9fAJF36vdUncb+4ndRNxoPdlSQ==",
+      "version": "26.17.0",
+      "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-26.17.0.tgz",
+      "integrity": "sha512-EAw1f2iGkICmUvAVBOjm7v5mxJdB7/+OZSycHFhKBimiTkCXtvkCC6wBKzHo7ZQYi58C2MmwIleRbgRnROlK2Q==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
-        "app-builder-lib": "26.15.3",
-        "builder-util": "26.15.3",
+        "app-builder-lib": "26.17.0",
+        "builder-util": "26.16.0",
         "fs-extra": "^10.1.0",
         "js-yaml": "^4.1.0"
       }
@@ -4301,9 +4370,9 @@
       }
     },
     "node_modules/electron": {
-      "version": "43.2.0",
-      "resolved": "https://registry.npmjs.org/electron/-/electron-43.2.0.tgz",
-      "integrity": "sha512-80zvrgG7ZRXD+tD0IyLvrnN9n+veSxadMRsMaC9wKKP3iUbtC7rGM8+dVuCmOb0Rrwwv8ESW4awnUZh9Hbp1fA==",
+      "version": "43.7.11",
+      "resolved": "https://registry.npmjs.org/electron/-/electron-43.7.11.tgz",
+      "integrity": "sha512-wEzOBtconxs86zwFPKCn5OzwGpr/pTAIvNT70aoDYslKlUcc76NbKQr2pqH8IMqL2bnN1K0EfVTREDa6sEp6OQ==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
@@ -4320,18 +4389,18 @@
       }
     },
     "node_modules/electron-builder": {
-      "version": "26.15.3",
-      "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-26.15.3.tgz",
-      "integrity": "sha512-a1KM5heqS3gQCZzizXEI8RjJy3QVogULPdeSknt76uLDpBIW/HDGsMg/XgP0riP6PI9COsRvFITKKGDqA8fJxA==",
+      "version": "26.17.0",
+      "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-26.17.0.tgz",
+      "integrity": "sha512-iYHBRiagS9sDIbZx1ZD113f5rEGQvtpvTvHf70ovHKJ8mRvxwIkWX7JCwfmVQmVS4eX735p7TZmoxHnBPwF3vA==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
-        "app-builder-lib": "26.15.3",
-        "builder-util": "26.15.3",
+        "app-builder-lib": "26.17.0",
+        "builder-util": "26.16.0",
         "builder-util-runtime": "9.7.0",
         "chalk": "^4.1.2",
         "ci-info": "^4.2.0",
-        "dmg-builder": "26.15.3",
+        "dmg-builder": "26.17.0",
         "fs-extra": "^10.1.0",
         "lazy-val": "^1.0.5",
         "simple-update-notifier": "2.0.0",
@@ -4346,28 +4415,28 @@
       }
     },
     "node_modules/electron-builder-squirrel-windows": {
-      "version": "26.15.3",
-      "resolved": "https://registry.npmjs.org/electron-builder-squirrel-windows/-/electron-builder-squirrel-windows-26.15.3.tgz",
-      "integrity": "sha512-Jc19XPV9y9+2bAdZPkXuVNGNIEFBq9poHC61l8Kv6FdK7DRG3+Ic0rerC0DXOaeHNz8yW0fg/JnF8GQROOF5MA==",
+      "version": "26.17.0",
+      "resolved": "https://registry.npmjs.org/electron-builder-squirrel-windows/-/electron-builder-squirrel-windows-26.17.0.tgz",
+      "integrity": "sha512-uyh+D+B0m12qCRp9c/7dwBirHTh7JcvAzj5eTEbb4dXPPGAhYPx1nozzbu1fC6AdULfat6ZNqgWhipTFpb82lQ==",
       "dev": true,
       "license": "MIT",
       "peer": true,
       "dependencies": {
-        "app-builder-lib": "26.15.3",
-        "builder-util": "26.15.3",
+        "app-builder-lib": "26.17.0",
+        "builder-util": "26.16.0",
         "electron-winstaller": "5.4.0"
       }
     },
     "node_modules/electron-publish": {
-      "version": "26.15.3",
-      "resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-26.15.3.tgz",
-      "integrity": "sha512-g/2bn8YTavY4cuS5F+jOS7zmZbXXBV8KZ8yHKfJjFPoKtzBqrpCdNPxBd3tqdBwP7BVd0lGzf7Bk2s0KesWZ4Q==",
+      "version": "26.16.0",
+      "resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-26.16.0.tgz",
+      "integrity": "sha512-Vt3KzQIiw9BImvNOYtndg9Mjki+tl4+1sQiC/+G5j8khWaENOJFWodiB+sUl6yyHwtd37avehskdtPw7f8y/+Q==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
         "@types/fs-extra": "^9.0.11",
         "aws4": "^1.13.2",
-        "builder-util": "26.15.3",
+        "builder-util": "26.16.0",
         "builder-util-runtime": "9.7.0",
         "chalk": "^4.1.2",
         "form-data": "^4.0.5",
@@ -4393,9 +4462,9 @@
       }
     },
     "node_modules/electron-to-chromium": {
-      "version": "1.5.389",
-      "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.389.tgz",
-      "integrity": "sha512-cEto7aeOqBfU1D+c5py5pE+ooscKE75JifxLBdFUZsqAxRS6y7kebtxAZvICszSl05gPjYHDTjY+lXpyGvpJbg==",
+      "version": "1.5.459",
+      "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.459.tgz",
+      "integrity": "sha512-4SC9HHSFjO/liAhifpdOL5hG9b4BP7/5G3y3UPZVO8trlAXr1CaUEEJL0gWK3kOcYcZrOA5rkwG45Gra/lTIgg==",
       "dev": true,
       "license": "ISC"
     },
@@ -4720,9 +4789,9 @@
       "license": "MIT"
     },
     "node_modules/fast-uri": {
-      "version": "3.1.3",
-      "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.3.tgz",
-      "integrity": "sha512-i70LwGWUduXqzicKXWshooq+sWL1K3WUU5rKZNG/0i3a1OSoX3HqhH5WbWwTmqWfor4urUakGPiRQcleRZTwOg==",
+      "version": "3.1.8",
+      "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz",
+      "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==",
       "funding": [
         {
           "type": "github",
@@ -4771,9 +4840,9 @@
       "license": "MIT"
     },
     "node_modules/filelist/node_modules/brace-expansion": {
-      "version": "2.1.2",
-      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.2.tgz",
-      "integrity": "sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA==",
+      "version": "2.1.7",
+      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz",
+      "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
@@ -4962,9 +5031,9 @@
       "license": "MIT"
     },
     "node_modules/glob/node_modules/brace-expansion": {
-      "version": "1.1.16",
-      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.16.tgz",
-      "integrity": "sha512-IDw48K2/2kRkg9LdJxurvq3lV3aBgq0REY89duEqFRthjlPdXHKMj7EnQOXVckxzgisinf3nHfrcE2FufFLXMw==",
+      "version": "1.1.21",
+      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz",
+      "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
@@ -5182,9 +5251,9 @@
       "license": "ISC"
     },
     "node_modules/http-cache-semantics": {
-      "version": "4.2.0",
-      "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",
-      "integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==",
+      "version": "4.3.0",
+      "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.3.0.tgz",
+      "integrity": "sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA==",
       "dev": true,
       "license": "BSD-2-Clause"
     },
@@ -5325,9 +5394,9 @@
       "license": "MIT"
     },
     "node_modules/js-yaml": {
-      "version": "4.3.0",
-      "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
-      "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==",
+      "version": "4.3.2",
+      "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",
+      "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==",
       "dev": true,
       "funding": [
         {
@@ -5847,13 +5916,13 @@
       }
     },
     "node_modules/minimatch": {
-      "version": "10.2.5",
-      "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
-      "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
+      "version": "10.2.6",
+      "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
+      "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
       "dev": true,
       "license": "BlueOak-1.0.0",
       "dependencies": {
-        "brace-expansion": "^5.0.5"
+        "brace-expansion": "^5.0.8"
       },
       "engines": {
         "node": "18 || 20 || >=22"
@@ -5917,9 +5986,9 @@
       "license": "MIT"
     },
     "node_modules/nanoid": {
-      "version": "3.3.15",
-      "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",
-      "integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==",
+      "version": "3.3.20",
+      "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
+      "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
       "dev": true,
       "funding": [
         {
@@ -5936,9 +6005,9 @@
       }
     },
     "node_modules/node-abi": {
-      "version": "4.33.0",
-      "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-4.33.0.tgz",
-      "integrity": "sha512-vLBWCKb+7LWsX+TbfzWOkw0W81m377tyx3hOweBTjO43CXZnRGS1/JPWs20fr0PgZyDXk6ROYrylsEycK8raDA==",
+      "version": "4.38.0",
+      "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-4.38.0.tgz",
+      "integrity": "sha512-suSdznUPfabdaeLiNERA0LHod14RhcEn8wMPUZEQ6bKvajUCZ+aizY4pIvlLU+gImeLKp2bFDHhOc9yonISsXw==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
@@ -6043,9 +6112,9 @@
       }
     },
     "node_modules/node-gyp/node_modules/undici": {
-      "version": "6.27.0",
-      "resolved": "https://registry.npmjs.org/undici/-/undici-6.27.0.tgz",
-      "integrity": "sha512-YmfV3YnEDzXRC5lZ2jWtWWHKGUm1zIt8AhesR1tens+HTNv+YZlN/dp6G727LOvMJ8xjP9Be7Y2Sdr96LDm+pg==",
+      "version": "6.29.1",
+      "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz",
+      "integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==",
       "dev": true,
       "license": "MIT",
       "engines": {
@@ -6076,9 +6145,9 @@
       "license": "MIT"
     },
     "node_modules/node-releases": {
-      "version": "2.0.51",
-      "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.51.tgz",
-      "integrity": "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==",
+      "version": "2.0.59",
+      "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.59.tgz",
+      "integrity": "sha512-5qr2okC4ItAI0hG5SaV0HoYMpnM/Y6+Oqr7AmPYy/2uEoGvS+GbSKLeRxSS1uAdu59yz0ouzcuXievSgg///WA==",
       "dev": true,
       "license": "MIT",
       "engines": {
@@ -6287,13 +6356,16 @@
       }
     },
     "node_modules/pkijs": {
-      "version": "3.4.0",
-      "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.0.tgz",
-      "integrity": "sha512-emEcLuomt2j03vxD54giVB4SxTjnsqkU692xZOZXHDVoYyypEm+b3jpiTcc+Cf+myooc+/Ly0z01jqeNHVgJGw==",
+      "version": "3.4.1",
+      "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.1.tgz",
+      "integrity": "sha512-Oo/NZcSWccq8KyoG7gLE9fnltgHns+pNCjCAp/WmjsUySi+sX7y4z4Xqu4fVb42CDHzRPl33fjzT15V1wvcyhA==",
       "dev": true,
       "license": "BSD-3-Clause",
+      "workspaces": [
+        "website"
+      ],
       "dependencies": {
-        "@noble/hashes": "1.4.0",
+        "@noble/hashes": "1.8.0",
         "asn1js": "^3.0.6",
         "bytestreamjs": "^2.0.1",
         "pvtsutils": "^1.3.6",
@@ -6304,19 +6376,6 @@
         "node": ">=16.0.0"
       }
     },
-    "node_modules/pkijs/node_modules/@noble/hashes": {
-      "version": "1.4.0",
-      "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.4.0.tgz",
-      "integrity": "sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==",
-      "dev": true,
-      "license": "MIT",
-      "engines": {
-        "node": ">= 16"
-      },
-      "funding": {
-        "url": "https://paulmillr.com/funding/"
-      }
-    },
     "node_modules/plist": {
       "version": "3.1.0",
       "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.0.tgz",
@@ -6333,9 +6392,9 @@
       }
     },
     "node_modules/postcss": {
-      "version": "8.5.16",
-      "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz",
-      "integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==",
+      "version": "8.5.30",
+      "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz",
+      "integrity": "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==",
       "dev": true,
       "funding": [
         {
@@ -6353,9 +6412,9 @@
       ],
       "license": "MIT",
       "dependencies": {
-        "nanoid": "^3.3.12",
+        "nanoid": "^3.3.20",
         "picocolors": "^1.1.1",
-        "source-map-js": "^1.2.1"
+        "source-map-js": "^1.2.2"
       },
       "engines": {
         "node": "^10 || ^12 || >=14"
@@ -6466,9 +6525,9 @@
       }
     },
     "node_modules/pvutils": {
-      "version": "1.1.5",
-      "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.1.5.tgz",
-      "integrity": "sha512-KTqnxsgGiQ6ZAzZCVlJH5eOjSnvlyEgx1m8bkRJfOhmGRqfo5KLvmAlACQkrjEtOQ4B7wF9TdSLIs9O90MX9xA==",
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",
+      "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",
       "dev": true,
       "license": "MIT",
       "engines": {
@@ -6712,9 +6771,9 @@
       }
     },
     "node_modules/sax": {
-      "version": "1.6.0",
-      "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.0.tgz",
-      "integrity": "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==",
+      "version": "1.6.1",
+      "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
+      "integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
       "dev": true,
       "license": "BlueOak-1.0.0",
       "engines": {
@@ -6850,9 +6909,9 @@
       }
     },
     "node_modules/source-map-js": {
-      "version": "1.2.1",
-      "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
-      "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+      "version": "1.2.2",
+      "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
+      "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
       "dev": true,
       "license": "BSD-3-Clause",
       "engines": {
@@ -7027,9 +7086,9 @@
       }
     },
     "node_modules/tar": {
-      "version": "7.5.19",
-      "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.19.tgz",
-      "integrity": "sha512-4LeEWl96twnS2Q7Bz4MGqgazLqO+hJN63GZxXoIqh1T3VweYD997gbU1ItNsQafqqXTXd5WFyFdReLtwvRBNiw==",
+      "version": "7.5.22",
+      "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz",
+      "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==",
       "dev": true,
       "license": "BlueOak-1.0.0",
       "dependencies": {
@@ -7243,9 +7302,9 @@
       }
     },
     "node_modules/undici": {
-      "version": "7.28.0",
-      "resolved": "https://registry.npmjs.org/undici/-/undici-7.28.0.tgz",
-      "integrity": "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==",
+      "version": "7.30.1",
+      "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz",
+      "integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==",
       "dev": true,
       "license": "MIT",
       "optional": true,
@@ -7299,9 +7358,9 @@
       }
     },
     "node_modules/update-browserslist-db": {
-      "version": "1.2.3",
-      "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
-      "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==",
+      "version": "1.3.4",
+      "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz",
+      "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==",
       "dev": true,
       "funding": [
         {

+ 7 - 3
package.json

@@ -1,8 +1,9 @@
 {
   "name": "we-manager",
-  "version": "0.8.5",
+  "version": "0.9.0",
   "type": "module",
   "description": "Wallpaper Engine workshop manager",
+  "desktopName": "we-manager.desktop",
   "author": "UwU <260361707+WallpaperEngineLover@users.noreply.github.com>",
   "email": "260361707+WallpaperEngineLover@users.noreply.github.com",
   "license": "MIT",
@@ -33,7 +34,7 @@
     "@types/react": "^19.2.17",
     "@types/react-dom": "^19.2.3",
     "@vitejs/plugin-react": "^5.2.0",
-    "electron": "^43.2.0",
+    "electron": "^43.7.11",
     "electron-builder": "^26.15.3",
     "electron-vite": "^5.0.0",
     "oxlint": "^1.85.0",
@@ -64,7 +65,8 @@
         }
       ],
       "category": "Utility",
-      "icon": "resources/icons/linux"
+      "icon": "resources/icons/linux",
+      "syncDesktopName": true
     },
     "appImage": {
       "artifactName": "WE-Manager-${version}.${ext}"
@@ -72,6 +74,8 @@
     "files": [
       "out/**/*",
       "node_modules/**/*",
+      "!node_modules/steamworks.js/dist/{osx,win64}/**",
+      "!node_modules/@koromix/koffi-linux-x64/musl_x64/**",
       "resources/icon.png"
     ],
     "asarUnpack": [

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 256 - 275
packaging/flathub/generated-sources.json


+ 6 - 3
patches/steamworks-vote/README.md

@@ -37,9 +37,11 @@ only has the older vote-only patch.
   `#[napi]` annotations automatically. Kept here for reference/as a fallback.
 
 All three were generated against and verified (`git apply --check`) to apply cleanly to:
-- `ceifa/steamworks.js` at its current `main` (the version this project's `package.json` pins,
-  `0.4.0`, predates these files slightly - a couple of unrelated functions were added upstream
-  since - but the patch targets are unaffected).
+- `ceifa/steamworks.js` at commit `80c5fd7c4958ba90cf87403c3f967b8a6d748473`, the one `build.sh` checks
+  out (the version this project's `package.json` pins, `0.4.0`, predates these files slightly - a
+  couple of unrelated functions were added upstream since - but the patch targets are unaffected).
+  To move to a newer upstream commit, change `PINNED_JS_REV` in `build.sh` once the patches apply
+  and the addon builds there.
 - `Noxime/steamworks-rs` at the exact commit `steamworks.js`'s own `Cargo.toml` pins
   (`fbb79635b06b4feea8261e5ca3e8ea3ef42facf9`).
 
@@ -55,6 +57,7 @@ clicked against a real Steam account yet.
 cd ~/projects/private
 git clone https://github.com/Noxime/steamworks-rs
 git clone https://github.com/ceifa/steamworks.js steamworksjs
+cd steamworksjs && git checkout 80c5fd7c4958ba90cf87403c3f967b8a6d748473 && cd ..
 cd steamworks-rs && git checkout fbb79635b06b4feea8261e5ca3e8ea3ef42facf9 && cd ..
 
 # 2. Apply the patches

+ 10 - 0
patches/steamworks-vote/build.sh

@@ -12,6 +12,7 @@ PATCHES_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
 STEAMWORKS_RS="$PROJECTS_DIR/steamworks-rs"
 STEAMWORKSJS="$PROJECTS_DIR/steamworksjs"
 PINNED_REV="fbb79635b06b4feea8261e5ca3e8ea3ef42facf9"
+PINNED_JS_REV="80c5fd7c4958ba90cf87403c3f967b8a6d748473"
 
 echo "==> Rust toolchain"
 if ! command -v cargo >/dev/null 2>&1; then
@@ -32,6 +33,15 @@ if [ ! -d "$STEAMWORKSJS" ]; then
   git clone https://github.com/ceifa/steamworks.js "$STEAMWORKSJS"
 fi
 
+# The files this script manages go back to upstream first, so a clone that is patched already can move to the pinned
+# commit. A clone that does not know the commit yet fetches it.
+for managed in src/api/workshop.rs client.d.ts Cargo.toml Cargo.lock; do
+  git -C "$STEAMWORKSJS" ls-files --error-unmatch "$managed" >/dev/null 2>&1 \
+    && git -C "$STEAMWORKSJS" checkout --quiet -- "$managed"
+done
+git -C "$STEAMWORKSJS" cat-file -e "$PINNED_JS_REV^{commit}" 2>/dev/null || git -C "$STEAMWORKSJS" fetch --quiet origin
+git -C "$STEAMWORKSJS" checkout --quiet "$PINNED_JS_REV"
+
 # A clone patched before favorites were added has only the vote half, so anything short of the
 # full patch is reset to upstream first and patched again.
 apply_patch() {

+ 53 - 8
src/main/index.ts

@@ -1,14 +1,14 @@
-import { app, BrowserWindow, net, protocol, shell } from 'electron'
+import { app, BrowserWindow, dialog, net, protocol, shell } from 'electron'
 import path from 'path'
 import { pathToFileURL } from 'url'
 import { IpcChannels } from '@shared/ipc-channels'
 import { isSteamRunning, startUserListSync, onFailedVotesChange, onFavoriteStatusChange, bindSteamToWindow } from './services/steam.service'
 import { initLibrary, checkUnavailableWallpapers, backfillResolutions, onHdrDetected, queueHdrCheck } from './services/library.service'
 import { startWatcher } from './services/watcher.service'
-import { checkOutdatedBackups } from './services/backup.service'
+import { checkOutdatedBackups, recoverInterruptedCopiesIn } from './services/backup.service'
 import { registerAllHandlers } from './ipc'
 import { initDesktopIcons, cleanupDesktopIcons } from './services/desktop-icons.service'
-import { getTrayEnabled, getAutostartPlaylistId, getKillLweOnQuit } from './services/config.service'
+import { getTrayEnabled, getAutostartPlaylistId, getKillLweOnQuit, getConfiguredBackupPath } from './services/config.service'
 import { createTray } from './services/tray.service'
 import { initPlaylistPlayer, startPlaylist } from './services/playlist-player.service'
 import { checkEarlierRunEngines, killAllLweProcesses, getLweStatus } from './services/lwe.service'
@@ -16,6 +16,10 @@ import { initDisplay } from './services/display.service'
 import { initSchedule } from './services/schedule.service'
 import { initUpdates } from './services/update.service'
 import { hasStatusNotifierHost } from './utils/platform'
+import { takeResetStores } from './utils/safeStore'
+import { t } from './i18n'
+import { getExtraLibraryRoots, getPreviewCachePath, getThumbnailsPath, getWorkshopPath } from './utils/paths'
+import { isAppUrl, isSafeExternalUrl, isServablePreview } from './utils/urlPolicy'
 import { attachAppearance, prepareAppearance, windowAppearanceOptions } from './services/appearance.service'
 import appIcon from '../../resources/icon.png?asset'
 
@@ -122,17 +126,33 @@ function createWindow(): BrowserWindow {
       preload: path.join(__dirname, '../preload/index.cjs'),
       contextIsolation: true,
       nodeIntegration: false,
-      sandbox: false
+      // the preload only needs electron's own modules
+      sandbox: true
     }
   })
 
   attachAppearance(win)
 
+  const devUrl = process.env.NODE_ENV === 'development' ? process.env['ELECTRON_RENDERER_URL'] : undefined
+  const appUrl = devUrl ?? pathToFileURL(path.join(__dirname, '../renderer/index.html')).toString()
+
   win.webContents.setWindowOpenHandler(({ url }) => {
-    shell.openExternal(url)
+    if (isSafeExternalUrl(url)) void shell.openExternal(url)
     return { action: 'deny' }
   })
 
+  // The window only ever shows the app. A file dropped outside the drop targets, a link without a target or a
+  // redirect would load that page with the whole electronAPI in it: links go to the browser, the rest is dropped
+  const keepOnApp = (event: { url: string; preventDefault: () => void }, openLinks: boolean): void => {
+    if (isAppUrl(event.url, appUrl)) return
+    event.preventDefault()
+    if (openLinks && isSafeExternalUrl(event.url)) void shell.openExternal(event.url)
+  }
+  // will-frame-navigate comes first, for the main frame as well, and will-navigate is skipped once that one prevents it
+  win.webContents.on('will-frame-navigate', (event) => keepOnApp(event, event.isMainFrame))
+  win.webContents.on('will-navigate', (event) => keepOnApp(event, true))
+  win.webContents.on('will-redirect', (event) => keepOnApp(event, false))
+
   // closing hides to the tray, or quits without a StatusNotifier host
   win.on('close', (event) => {
     if (getTrayEnabled() && !isQuitting && hasStatusNotifierHost()) {
@@ -141,8 +161,8 @@ function createWindow(): BrowserWindow {
     }
   })
 
-  if (process.env.NODE_ENV === 'development' && process.env['ELECTRON_RENDERER_URL']) {
-    win.loadURL(process.env['ELECTRON_RENDERER_URL'])
+  if (devUrl) {
+    win.loadURL(devUrl)
   } else {
     win.loadFile(path.join(__dirname, '../renderer/index.html'))
   }
@@ -152,9 +172,31 @@ function createWindow(): BrowserWindow {
   return win
 }
 
+function announceResetStores(): void {
+  const reset = takeResetStores()
+  if (reset.length === 0) return
+  void dialog.showMessageBox({
+    type: 'warning',
+    message: t('dialog.storeResetTitle'),
+    detail: reset.map(({ file, keptAs }) => t('dialog.storeReset', { name: path.basename(file), keptAs })).join('\n\n')
+  })
+}
+
 app.whenReady().then(async () => {
   protocol.handle('wallpaper', async (request) => {
-    const filePath = decodeURIComponent(request.url.replace('wallpaper://', ''))
+    let filePath: string
+    try {
+      filePath = decodeURIComponent(request.url.replace('wallpaper://', ''))
+    } catch {
+      return new Response(null, { status: 400 })
+    }
+
+    // previews only: pictures and videos inside the library, backup and thumbnail folders, not any file of the user
+    const roots = [getWorkshopPath(), getConfiguredBackupPath(), ...getExtraLibraryRoots(), getThumbnailsPath(), getPreviewCachePath()]
+    if (request.method !== 'GET' || !isServablePreview(filePath, roots.filter((root): root is string => !!root))) {
+      return new Response(null, { status: 403 })
+    }
+
     try {
       const res = await net.fetch(pathToFileURL(filePath).toString())
       const headers = new Headers(res.headers)
@@ -167,9 +209,12 @@ app.whenReady().then(async () => {
     }
   })
 
+  const copyRoots = [getConfiguredBackupPath(), ...getExtraLibraryRoots()].filter((root): root is string => !!root)
+  await recoverInterruptedCopiesIn(copyRoots)
   initLibrary()
 
   const win = createWindow()
+  announceResetStores()
   bindSteamToWindow(win)
   registerAllHandlers(win)
   startWatcher(win)

+ 0 - 1
src/main/ipc/backup.handlers.ts

@@ -54,7 +54,6 @@ async function backupOne(id: string, win: BrowserWindow): Promise<BackupItemResu
         try {
           await fs.promises.rm(sourcePath, { recursive: true, force: true })
         } catch {
-          /* ignore */
         }
       }
       unsubscribed = true

+ 49 - 0
src/main/ipc/shell.handlers.test.ts

@@ -0,0 +1,49 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import * as fs from 'fs'
+import * as os from 'os'
+import * as path from 'path'
+import { IpcChannels } from '@shared/ipc-channels'
+
+const handlers = new Map<string, (...args: unknown[]) => Promise<{ ok: boolean; error?: string }>>()
+const openPath = vi.fn<(p: string) => Promise<string>>(async () => '')
+const openExternal = vi.fn<(u: string) => Promise<void>>(async () => {})
+
+vi.mock('electron', () => ({
+  ipcMain: { handle: (channel: string, fn: never) => handlers.set(channel, fn) },
+  shell: { openPath: (p: string) => openPath(p), openExternal: (u: string) => openExternal(u), showItemInFolder: vi.fn<(p: string) => void>() }
+}))
+
+const { registerShellHandlers } = await import('./shell.handlers')
+
+function call(channel: string, ...args: unknown[]) {
+  return handlers.get(channel)!({}, ...args)
+}
+
+describe('shell handlers', () => {
+  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wem-shell-'))
+
+  beforeEach(() => {
+    handlers.clear()
+    openPath.mockClear()
+    openExternal.mockClear()
+    registerShellHandlers()
+  })
+
+  it('opens an existing folder', async () => {
+    expect(await call(IpcChannels.SHELL_OPEN_PATH, dir)).toEqual({ ok: true, error: undefined })
+    expect(openPath).toHaveBeenCalledWith(dir)
+  })
+
+  it('does not hand a missing path or a non-string to the opener', async () => {
+    expect((await call(IpcChannels.SHELL_OPEN_PATH, path.join(dir, 'nope'))).ok).toBe(false)
+    expect((await call(IpcChannels.SHELL_OPEN_PATH, '')).ok).toBe(false)
+    expect((await call(IpcChannels.SHELL_OPEN_PATH, { toString: () => dir })).ok).toBe(false)
+    expect(openPath).not.toHaveBeenCalled()
+  })
+
+  it('opens only safe links', async () => {
+    expect((await call(IpcChannels.SHELL_OPEN_EXTERNAL, 'file:///etc/passwd')).ok).toBe(false)
+    expect((await call(IpcChannels.SHELL_OPEN_EXTERNAL, 'https://example.org')).ok).toBe(true)
+    expect(openExternal).toHaveBeenCalledTimes(1)
+  })
+})

+ 5 - 1
src/main/ipc/shell.handlers.ts

@@ -4,6 +4,7 @@ import * as path from 'path'
 import * as fs from 'fs'
 import { spawn } from 'child_process'
 import { isCommandAvailable } from '../utils/platform'
+import { isSafeExternalUrl } from '../utils/urlPolicy'
 
 export function registerShellHandlers(): void {
   ipcMain.handle(IpcChannels.SHELL_OPEN_WITH_DEFAULT, async (_e, filePath: string) => {
@@ -21,12 +22,13 @@ export function registerShellHandlers(): void {
   })
 
   ipcMain.handle(IpcChannels.SHELL_OPEN_PATH, async (_e, targetPath: string) => {
+    if (typeof targetPath !== 'string' || !targetPath) return { ok: false, error: 'Path not found' }
     const resolved = path.resolve(targetPath)
+    if (!fs.existsSync(resolved)) return { ok: false, error: 'Path not found' }
     const result = await shell.openPath(resolved)
     return { ok: !result, error: result || undefined }
   })
 
-  // Open several folders in one file manager window (tabs) instead of one window per path
   ipcMain.handle(IpcChannels.SHELL_OPEN_PATHS, async (_e, targetPaths: string[]) => {
     const resolved = [...new Set(targetPaths.map((p) => path.resolve(p)))].filter((p) =>
       fs.existsSync(p)
@@ -50,6 +52,8 @@ export function registerShellHandlers(): void {
   })
 
   ipcMain.handle(IpcChannels.SHELL_OPEN_EXTERNAL, async (_e, url: string) => {
+    // web links and steam:// only, the opener would run whatever scheme handler a URL names
+    if (!isSafeExternalUrl(url)) return { ok: false, error: 'This kind of link is not opened' }
     try {
       await shell.openExternal(url)
       return { ok: true }

+ 5 - 1
src/main/ipc/steam.handlers.ts

@@ -8,6 +8,7 @@ import * as steam from '../services/steam.service'
 import * as library from '../services/library.service'
 import * as backup from '../services/backup.service'
 import * as verify from '../services/workshop-verify.service'
+import { isWallpaperEngineItem } from '../services/workshop.service'
 import { getWorkshopPath } from '../utils/paths'
 import { setDependencyInstaller } from '../services/dependency.service'
 
@@ -116,6 +117,9 @@ async function startRepair(win: BrowserWindow, itemId: string): Promise<{ done:
   if (entry?.verifyProblem === 'missingDependency' && entry.localPath) {
     const dependency = verify.presetDependency(library.readProjectJson(entry.localPath) ?? {})
     if (dependency) {
+      if (!(await isWallpaperEngineItem(dependency))) {
+        throw new Error(`Dependency ${dependency} is not a Wallpaper Engine workshop item, not subscribing to it`)
+      }
       await subscribeAndDownload(win, dependency)
       library.updateWallpaper(itemId, { verifyProblem: undefined })
       notifyLibrary()
@@ -192,7 +196,7 @@ async function startRepair(win: BrowserWindow, itemId: string): Promise<{ done:
 
 // async so a hung mount doesn't block the main process
 async function removeLocalFiles(dir: string): Promise<void> {
-  try { await fs.promises.rm(dir, { recursive: true, force: true }) } catch { /* ignore */ }
+  try { await fs.promises.rm(dir, { recursive: true, force: true }) } catch { }
 }
 
 export function registerSteamHandlers(win: BrowserWindow): void {

+ 123 - 0
src/main/services/backup.service.test.ts

@@ -43,6 +43,12 @@ function writeFiles(dir: string, files: Record<string, string>): void {
   }
 }
 
+const dest = (): string => path.join(backupRoot, '123')
+const partial = (): string => path.join(backupRoot, '.123.partial')
+const old = (): string => path.join(backupRoot, '.123.old')
+const mark = (): string => path.join(backupRoot, '.123.verified')
+const read = (dir: string): string => fs.readFileSync(path.join(dir, 'project.json'), 'utf8')
+
 beforeEach(() => {
   tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'wem-backup-'))
   backupRoot = path.join(tmp, 'backups')
@@ -87,6 +93,114 @@ describe('backupWallpaper', () => {
   })
 })
 
+describe('interrupted copies', () => {
+  beforeEach(() => fs.mkdirSync(backupRoot, { recursive: true }))
+
+  it('finishes the swap when it died between the two renames after verifying', async () => {
+    writeFiles(old(), { 'project.json': 'previous' })
+    writeFiles(partial(), { 'project.json': 'new' })
+    fs.writeFileSync(mark(), '')
+    await backup.recoverInterruptedCopy(dest())
+    expect(read(dest())).toBe('new')
+    expect(fs.readdirSync(backupRoot)).toEqual(['123'])
+  })
+
+  it('puts the previous backup back when the new copy was never verified', async () => {
+    writeFiles(old(), { 'project.json': 'previous' })
+    writeFiles(partial(), { 'project.json': 'half' })
+    await backup.recoverInterruptedCopy(dest())
+    expect(read(dest())).toBe('previous')
+    expect(fs.readdirSync(backupRoot)).toEqual(['123'])
+  })
+
+  it('puts the previous backup back when nothing else is left', async () => {
+    writeFiles(old(), { 'project.json': 'previous' })
+    await backup.recoverInterruptedCopy(dest())
+    expect(read(dest())).toBe('previous')
+    expect(fs.readdirSync(backupRoot)).toEqual(['123'])
+  })
+
+  it('drops the leftovers of a finished swap and of a copy that died midway', async () => {
+    writeFiles(dest(), { 'project.json': 'current' })
+    writeFiles(old(), { 'project.json': 'previous' })
+    writeFiles(partial(), { 'project.json': 'half' })
+    fs.writeFileSync(mark(), '')
+    await backup.recoverInterruptedCopy(dest())
+    expect(read(dest())).toBe('current')
+    expect(fs.readdirSync(backupRoot)).toEqual(['123'])
+  })
+
+  it('does not promote an unverified first copy', async () => {
+    writeFiles(partial(), { 'project.json': 'half' })
+    await backup.recoverInterruptedCopy(dest())
+    expect(fs.readdirSync(backupRoot)).toEqual([])
+  })
+
+  it('leaves other folders alone', async () => {
+    writeFiles(path.join(backupRoot, '.mine.old'), { 'project.json': 'x' })
+    writeFiles(path.join(backupRoot, '.other'), { 'project.json': 'y' })
+    writeFiles(dest(), { 'project.json': 'current' })
+    await backup.recoverInterruptedCopies(backupRoot)
+    expect(read(dest())).toBe('current')
+    expect(fs.existsSync(path.join(backupRoot, '.other'))).toBe(true)
+    expect(fs.existsSync(path.join(backupRoot, 'mine'))).toBe(true)
+  })
+
+  it('relinks a backup the scan would have lost to the hidden folder', async () => {
+    writeFiles(old(), { 'project.json': '{}', 'a.pkg': 'p' })
+    writeFiles(partial(), { 'project.json': '{}' })
+    wallpapers.set('123', { ...base, id: '123', source: 'workshop', localPath: source, backedUp: true, backupDir: dest() })
+    const result = await backup.scanBackupFolder()
+    expect(result.unlinked).toBe(0)
+    expect(wallpapers.get('123')?.backedUp).toBe(true)
+    expect(fs.existsSync(path.join(dest(), 'a.pkg'))).toBe(true)
+  })
+
+  it('does not touch the staging folder of a copy that is running', async () => {
+    const spy = vi.spyOn(fs.promises, 'rename')
+    let release!: () => void
+    const gate = new Promise<void>((resolve) => (release = resolve))
+    const copyFile = fs.promises.copyFile
+    vi.spyOn(fs.promises, 'copyFile').mockImplementation(async (...args) => {
+      await gate
+      return copyFile(...args)
+    })
+    const running = backup.backupWallpaper('123', source, win)
+    await vi.waitFor(() => expect(fs.existsSync(partial())).toBe(true))
+    await backup.scanBackupFolder()
+    expect(fs.existsSync(partial())).toBe(true)
+    await expect(backup.backupWallpaper('123', source, win)).rejects.toThrow(/already being written/)
+    release()
+    await running
+    expect(read(dest())).toBe('{}')
+    expect(fs.readdirSync(backupRoot)).toEqual(['123'])
+    spy.mockRestore()
+    vi.restoreAllMocks()
+  })
+
+  it('puts the previous backup back when the final rename fails', async () => {
+    const first = await backup.backupWallpaper('123', source, win)
+    fs.writeFileSync(path.join(first, 'marker.txt'), 'previous backup')
+    const rename = fs.promises.rename
+    vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+      if (String(to) === dest() && String(from) === partial()) throw new Error('disk gone')
+      return rename(from, to)
+    })
+    await expect(backup.backupWallpaper('123', source, win)).rejects.toThrow('disk gone')
+    vi.restoreAllMocks()
+    expect(fs.readFileSync(path.join(dest(), 'marker.txt'), 'utf8')).toBe('previous backup')
+    expect(fs.readdirSync(backupRoot)).toEqual(['123'])
+  })
+
+  it('recovers a crashed state before the next copy starts', async () => {
+    writeFiles(old(), { 'project.json': 'previous', 'marker.txt': 'previous backup' })
+    writeFiles(partial(), { 'project.json': 'half' })
+    await backup.backupWallpaper('123', source, win)
+    expect(fs.readdirSync(backupRoot)).toEqual(['123'])
+    expect(await backup.backupMatchesSource(source, dest())).toBe(true)
+  })
+})
+
 describe('backupMatchesSource', () => {
   it('detects missing files and size changes', async () => {
     const dir = await backup.backupWallpaper('123', source, win)
@@ -192,6 +306,15 @@ describe('scanBackupFolder', () => {
     expect(wallpapers.get('123')?.previewLocal).toBe(gone)
   })
 
+  it('does not take a preview that names a file outside the folder', async () => {
+    writeFiles(path.join(tmp, 'outside'), { 'secret.png': 'png' })
+    writeFiles(source, { 'project.json': '{"preview":"../../outside/secret.png"}' })
+    const meta = { ...base, id: '123', source: 'workshop' as const, localPath: source }
+    expect(await backup.previewInBackup(meta, source)).toBeUndefined()
+    writeFiles(source, { 'preview.png': 'png' })
+    expect(await backup.previewInBackup(meta, source)).toBe(path.join(source, 'preview.png'))
+  })
+
   it('moves the preview into the backup folder', async () => {
     writeFiles(source, { 'project.json': '{"preview":"preview.jpg"}', 'preview.jpg': 'jpg' })
     const dir = await backup.backupWallpaper('123', source, win)

+ 98 - 11
src/main/services/backup.service.ts

@@ -7,6 +7,7 @@ import { IpcChannels } from '@shared/ipc-channels'
 import type { BackupProgressEvent, WallpaperMeta } from '@shared/types'
 import { getConfiguredBackupPath } from './config.service'
 import * as library from './library.service'
+import { containedPath } from '../utils/contained'
 import { normalizeType, normalizeRating, type ProjectJson } from './library.service'
 
 export function getBackupDir(id: string): string {
@@ -52,7 +53,8 @@ async function readProjectJson(dir: string): Promise<ProjectJson | null> {
 
 // project.json names come from Windows, where "Preview.JPG" finds preview.jpg
 async function findFileIgnoringCase(dir: string, rel: string): Promise<string | undefined> {
-  const exact = path.join(dir, rel)
+  const exact = containedPath(dir, rel)
+  if (!exact) return undefined
   if (await exists(exact)) return exact
   const parent = path.dirname(exact)
   const name = path.basename(exact).toLowerCase()
@@ -207,7 +209,6 @@ export async function backupMatchesSource(sourcePath: string, backupDir: string)
   return true
 }
 
-// fsync destDir, drop it from the page cache and re-hash every file against the source
 export async function verifyOnDisk(sourcePath: string, destDir: string): Promise<boolean> {
   try {
     for (const file of await walkFiles(destDir)) await fsyncPath(path.join(destDir, file.relPath))
@@ -223,6 +224,68 @@ export async function syncDir(dir: string): Promise<void> {
   await fsyncPath(dir)
 }
 
+function swapPaths(destDir: string): { stagingDir: string; oldDir: string; verifiedMark: string } {
+  const root = path.dirname(destDir)
+  const name = path.basename(destDir)
+  return {
+    stagingDir: path.join(root, `.${name}.partial`),
+    oldDir: path.join(root, `.${name}.old`),
+    verifiedMark: path.join(root, `.${name}.verified`)
+  }
+}
+
+const SWAP_SUFFIX = /^\.(.+)\.(partial|old|verified)$/
+
+const activeCopies = new Set<string>()
+
+export async function recoverInterruptedCopy(destDir: string): Promise<void> {
+  if (activeCopies.has(path.resolve(destDir))) return
+  await recoverSwap(destDir)
+}
+
+function removeTree(p: string): Promise<void> {
+  return fs.promises.rm(p, { recursive: true, force: true })
+}
+
+async function recoverSwap(destDir: string): Promise<void> {
+  const { stagingDir, oldDir, verifiedMark } = swapPaths(destDir)
+  const [hasDest, hasOld, hasStaging, isVerified] = await Promise.all([
+    exists(destDir),
+    exists(oldDir),
+    exists(stagingDir),
+    exists(verifiedMark)
+  ])
+  if (!hasOld && !hasStaging && !isVerified) return
+
+  if (!hasDest && isVerified && hasStaging) {
+    await fs.promises.rename(stagingDir, destDir)
+    console.warn(`[Backup] Finished an interrupted copy of ${destDir}`)
+  } else if (!hasDest && hasOld) {
+    await fs.promises.rename(oldDir, destDir)
+    console.warn(`[Backup] Restored ${destDir} from the copy an interrupted update had set aside`)
+  }
+  await fsyncPath(path.dirname(destDir)).catch(() => {})
+  await Promise.all([removeTree(oldDir), removeTree(stagingDir), removeTree(verifiedMark)])
+}
+
+export async function recoverInterruptedCopies(root: string): Promise<void> {
+  let names: Set<string>
+  try {
+    names = new Set((await fs.promises.readdir(root)).flatMap((entry) => SWAP_SUFFIX.exec(entry)?.[1] ?? []))
+  } catch {
+    return
+  }
+  for (const name of names) {
+    await recoverInterruptedCopy(path.join(root, name)).catch((err) =>
+      console.error(`[Backup] Could not recover ${name} in ${root}:`, err)
+    )
+  }
+}
+
+export async function recoverInterruptedCopiesIn(roots: string[]): Promise<void> {
+  for (const root of new Set(roots)) await recoverInterruptedCopies(root)
+}
+
 export async function backupWallpaper(
   id: string,
   sourcePath: string,
@@ -242,9 +305,26 @@ export async function copyWallpaperFolder(
   destDir: string,
   win: BrowserWindow,
   action: BackupProgressEvent['action']
+): Promise<string> {
+  const key = path.resolve(destDir)
+  if (activeCopies.has(key)) throw new Error(`${destDir} is already being written`)
+  activeCopies.add(key)
+  try {
+    return await stageAndSwap(id, sourcePath, destDir, win, action)
+  } finally {
+    activeCopies.delete(key)
+  }
+}
+
+async function stageAndSwap(
+  id: string,
+  sourcePath: string,
+  destDir: string,
+  win: BrowserWindow,
+  action: BackupProgressEvent['action']
 ): Promise<string> {
   const destRoot = path.dirname(destDir)
-  const name = path.basename(destDir)
+  const { stagingDir, oldDir, verifiedMark } = swapPaths(destDir)
 
   const files = await walkFiles(sourcePath)
   if (!files.some((f) => f.relPath === 'project.json')) {
@@ -253,9 +333,7 @@ export async function copyWallpaperFolder(
   const bytesTotal = files.reduce((sum, f) => sum + f.size, 0)
 
   await fs.promises.mkdir(destRoot, { recursive: true })
-  const stagingDir = path.join(destRoot, `.${name}.partial`)
-  const oldDir = path.join(destRoot, `.${name}.old`)
-  await fs.promises.rm(stagingDir, { recursive: true, force: true })
+  await recoverSwap(destDir)
   await fs.promises.mkdir(stagingDir)
 
   let bytesDone = 0
@@ -317,14 +395,21 @@ export async function copyWallpaperFolder(
       })
     }
 
-    await fs.promises.rm(oldDir, { recursive: true, force: true })
+    await fs.promises.writeFile(verifiedMark, '')
+    await fsyncPath(verifiedMark)
+    await fsyncPath(destRoot)
     const hadOld = await exists(destDir)
     if (hadOld) await fs.promises.rename(destDir, oldDir)
-    await fs.promises.rename(stagingDir, destDir)
+    try {
+      await fs.promises.rename(stagingDir, destDir)
+    } catch (err) {
+      if (hadOld) await fs.promises.rename(oldDir, destDir)
+      throw err
+    }
     await fsyncPath(destRoot)
-    if (hadOld) await fs.promises.rm(oldDir, { recursive: true, force: true })
+    await Promise.all([removeTree(oldDir), removeTree(verifiedMark)])
   } catch (err) {
-    await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {})
+    await Promise.all([removeTree(stagingDir), removeTree(verifiedMark)].map((removal) => removal.catch(() => {})))
     sendProgress(win, {
       itemId: id,
       action,
@@ -383,7 +468,7 @@ async function buildBackupMeta(id: string, localPath: string, existing?: Wallpap
     type: normalizeType(pj?.type),
     contentRating: normalizeRating(pj?.contentrating),
     description: pj?.description ?? existing?.description,
-    previewLocal: pj?.preview ? path.join(localPath, pj.preview) : undefined,
+    previewLocal: containedPath(localPath, pj?.preview),
     localPath,
     file: pj?.file,
     fileSize: files.reduce((sum, f) => sum + f.size, 0),
@@ -465,6 +550,8 @@ export async function scanBackupFolder(): Promise<{
     return result
   }
 
+  await recoverInterruptedCopies(backupPath)
+
   const folderIds = (await fs.promises.readdir(backupPath, { withFileTypes: true }))
     // dot folders are staging copies of an in-progress backup
     .filter((e) => e.isDirectory() && !e.name.startsWith('.'))

+ 2 - 5
src/main/services/config.service.ts

@@ -1,4 +1,4 @@
-import Store from 'electron-store'
+import { openStore } from '../utils/safeStore'
 import * as fs from 'fs'
 import * as path from 'path'
 import { app } from 'electron'
@@ -42,11 +42,9 @@ interface AppConfig {
   recommendedWebFpsEnabled: boolean
   audioScreen: string | null
   ambientVolume: number | null
-  /** --audio-sensitivity default */
   defaultAudioSensitivity: number
   /** --render-debug no-puppet-animation */
   disablePuppetAnimation: boolean
-  /** --disable-animations */
   disableAnimations: boolean
   steamIdentity: SteamIdentity
   /** steamId64s hidden from browsing */
@@ -64,7 +62,7 @@ interface AppConfig {
   dismissedUpdates: Partial<Record<UpdateTarget, string>>
 }
 
-const store = new Store<AppConfig>({
+const store = openStore<AppConfig>({
   name: 'config',
   defaults: {
     workshopPath: null,
@@ -386,7 +384,6 @@ export function getWeConfigPath(): string {
   return path.join(app.getPath('userData'), 'we-config.json')
 }
 
-/** Copies a WE config.json with workshop paths pointed at ours */
 export function importWEConfigFile(sourcePath: string): string {
   const workshopPath = getConfiguredWorkshopPath()
   if (!workshopPath) throw new Error('Workshop path must be configured before importing')

+ 1 - 1
src/main/services/dependency.service.ts

@@ -66,7 +66,7 @@ export async function ensureDependencyInstalled(
     try {
       await installer(dependencyId)
     } catch (err) {
-      throw new Error(t('dependency.subscribeFailed', { id: dependencyId, error: (err as Error).message }))
+      throw new Error(t('dependency.subscribeFailed', { id: dependencyId, error: (err as Error).message }), { cause: err })
     }
     throw new Error(t('dependency.downloading', { id: dependencyId, title }))
   }

+ 0 - 5
src/main/services/desktop-icons-overlay.py

@@ -212,7 +212,6 @@ def detect_kde_settings():
         'font_italic': False,
     }
 
-    # --- Icon size from Folder View config ---
     try:
         config_path = os.path.expanduser(
             '~/.config/plasma-org.kde.plasma.desktop-appletsrc'
@@ -220,7 +219,6 @@ def detect_kde_settings():
         if os.path.exists(config_path):
             cp = configparser.ConfigParser(strict=False)
             cp.read(config_path)
-            # Find the desktop containment's General section
             for section in cp.sections():
                 if 'General' not in section:
                     continue
@@ -232,7 +230,6 @@ def detect_kde_settings():
     except Exception:
         pass
 
-    # --- System font from kreadconfig6 ---
     try:
         result = subprocess.run(
             ['kreadconfig6', '--file', 'kdeglobals',
@@ -355,7 +352,6 @@ def main():
                     Gtk4LayerShell.set_monitor(window, mon)
                     break
 
-        # Fullscreen
         for edge in (Gtk4LayerShell.Edge.TOP, Gtk4LayerShell.Edge.BOTTOM,
                      Gtk4LayerShell.Edge.LEFT, Gtk4LayerShell.Edge.RIGHT):
             Gtk4LayerShell.set_anchor(window, edge, True)
@@ -440,7 +436,6 @@ def main():
                 col, row = 0, len(kde_positions)
                 kde_positions[filename] = (col, row)
 
-            # Top-left alignment within grid cell (matches KDE Folder View)
             x = panel_left + GRID_MARGIN + col * cell_w
             y = panel_top + GRID_MARGIN + row * cell_h
 

+ 2 - 7
src/main/services/desktop-icons.service.ts

@@ -1,7 +1,7 @@
 import { spawn, type ChildProcess } from 'child_process'
 import * as path from 'path'
 import * as fs from 'fs'
-import Store from 'electron-store'
+import { openStore } from '../utils/safeStore'
 import { app } from 'electron'
 import { getConnectedScreens, getWaylandDisplay, getXdgRuntimeDir } from '../utils/platform'
 import { isFlatpak } from '../utils/flatpak'
@@ -10,7 +10,7 @@ interface DesktopIconsStoreSchema {
   desktopIconsEnabled: boolean
 }
 
-const store = new Store<DesktopIconsStoreSchema>({
+const store = openStore<DesktopIconsStoreSchema>({
   defaults: { desktopIconsEnabled: false }
 })
 
@@ -22,7 +22,6 @@ function getOverlayScriptPath(): string {
   const candidates = [
     path.join(__dirname, '..', '..', 'src', 'main', 'services', 'desktop-icons-overlay.py'),
     path.join(process.resourcesPath ?? '', 'desktop-icons-overlay.py'),
-    // Fallback: next to compiled output
     path.join(__dirname, 'desktop-icons-overlay.py')
   ]
   for (const c of candidates) {
@@ -64,10 +63,8 @@ function buildOverlayEnvVars(): string[] {
   const waylandDisplay = getWaylandDisplay()
   if (waylandDisplay) vars.push(`WAYLAND_DISPLAY=${waylandDisplay}`)
 
-  // XDG_RUNTIME_DIR is needed for the Wayland socket
   vars.push(`XDG_RUNTIME_DIR=${getXdgRuntimeDir()}`)
 
-  // DISPLAY for the XWayland fallback
   if (process.env.DISPLAY) vars.push(`DISPLAY=${process.env.DISPLAY}`)
 
   return vars
@@ -112,7 +109,6 @@ export function stopDesktopIconsOverlay(): void {
     try {
       child.kill('SIGTERM')
     } catch {
-      /* already dead */
     }
   }
   overlayProcesses = []
@@ -131,7 +127,6 @@ export function getDesktopIconsEnabled(): boolean {
   return store.get('desktopIconsEnabled', false)
 }
 
-/** Call on app startup to restore overlay if it was enabled. */
 export function initDesktopIcons(): void {
   if (getDesktopIconsEnabled()) {
     startDesktopIconsOverlay()

+ 12 - 1
src/main/services/display.service.ts

@@ -31,7 +31,6 @@ import { ensureDependencyInstalled } from './dependency.service'
 import { getConnectedScreens } from '../utils/platform'
 import { t } from '../i18n'
 
-// how long a fresh launch has to survive before it counts as working
 const LAUNCH_CHECK_MS = 20_000
 // automatic relaunches after a runtime crash, at most one per screen in this window
 const RELAUNCH_COOLDOWN_MS = 60_000
@@ -62,6 +61,18 @@ export function getScreenAssignments(): ScreenAssignment[] {
   return Object.entries(getAssignments()).map(([screen, wallpaperId]) => ({ screen, wallpaperId }))
 }
 
+const busySources = new Map<string, () => string[]>()
+
+export function setBusyWallpaperSource(name: string, source: () => string[]): void {
+  busySources.set(name, source)
+}
+
+export function getWallpapersInUse(): Set<string> {
+  const ids = new Set(getScreenAssignments().map((a) => a.wallpaperId))
+  for (const source of busySources.values()) for (const id of source()) ids.add(id)
+  return ids
+}
+
 /** Live global flags reach running wallpapers without their own */
 export async function pushGlobalEngineFlags(before: EngineFlags, after: EngineFlags): Promise<void> {
   const splitScreens = new Set(getRunningInstances().filter((i) => i.split).map((i) => i.screen))

+ 1 - 1
src/main/services/gnome-extension.service.ts

@@ -24,7 +24,7 @@ function userExtensionDir(): string {
 export function bundledExtensionDir(enginePath = getLweStatus().path): string | undefined {
   if (!enginePath) return undefined
   let real = enginePath
-  try { real = fs.realpathSync(enginePath) } catch { /* keep the path */ }
+  try { real = fs.realpathSync(enginePath) } catch { }
   const dir = path.join(path.dirname(real), 'gnome-shell-extension', GNOME_EXTENSION_UUID)
   return fs.existsSync(path.join(dir, 'metadata.json')) ? dir : undefined
 }

+ 26 - 1
src/main/services/library-transfer.service.test.ts

@@ -6,6 +6,7 @@ import type { WallpaperMeta } from '@shared/types'
 
 let roots: string[] = []
 let onScreen: string[] = []
+let busy: string[] = []
 const wallpapers = new Map<string, WallpaperMeta>()
 const unsubscribe = vi.fn<(id: bigint) => Promise<void>>(async () => {})
 
@@ -13,7 +14,7 @@ vi.mock('electron', () => ({ app: { getPath: () => os.tmpdir() } }))
 vi.mock('./config.service', () => ({ getConfiguredBackupPath: () => null }))
 vi.mock('../utils/paths', () => ({ getExtraLibraryRoots: () => roots }))
 vi.mock('./display.service', () => ({
-  getScreenAssignments: () => onScreen.map((wallpaperId) => ({ screen: 'DP-1', wallpaperId }))
+  getWallpapersInUse: () => new Set([...onScreen, ...busy])
 }))
 vi.mock('./steam.service', () => ({ unsubscribeFromItem: (id: bigint) => unsubscribe(id) }))
 vi.mock('./library.service', () => ({
@@ -57,6 +58,7 @@ beforeEach(() => {
   fs.mkdirSync(target)
   roots = [path.join(tmp, 'ssd'), target]
   onScreen = []
+  busy = []
   wallpapers.clear()
   unsubscribe.mockClear()
 })
@@ -114,6 +116,29 @@ describe('transferWallpapers', () => {
     expect(fs.existsSync(path.join(target, '444', 'other.txt'))).toBe(true)
   })
 
+  it('refuses to move what a playlist or schedule is switching to, but still copies it', async () => {
+    const src = path.join(tmp, 'ssd', '888')
+    addWallpaper('888', src, 'local')
+    busy = ['888']
+
+    const moved = await transferWallpapers(['888'], target, 'move', win)
+    expect(moved.failed.map((f) => f.id)).toEqual(['888'])
+    expect(moved.failed[0].reason).toMatch(/playlist or schedule/)
+    expect(fs.existsSync(src)).toBe(true)
+    expect(wallpapers.get('888')!.localPath).toBe(src)
+
+    expect(await transferWallpapers(['888'], target, 'copy', win)).toMatchObject({ done: 1, failed: [] })
+  })
+
+  it('finishes an interrupted copy in the target before looking at what is there', async () => {
+    const src = path.join(tmp, 'ssd', '999')
+    addWallpaper('999', src, 'local')
+    fs.cpSync(src, path.join(target, '.999.old'), { recursive: true })
+    expect(await transferWallpapers(['999'], target, 'move', win)).toMatchObject({ done: 1, failed: [] })
+    expect(fs.readdirSync(target)).toEqual(['999'])
+    expect(fs.existsSync(src)).toBe(false)
+  })
+
   it('reuses an identical folder left by an earlier copy after checking it on disk', async () => {
     const src = path.join(tmp, 'ssd', '777')
     addWallpaper('777', src, 'local')

+ 13 - 4
src/main/services/library-transfer.service.ts

@@ -3,8 +3,16 @@ import * as fs from 'fs'
 import * as path from 'path'
 import type { WallpaperMeta } from '@shared/types'
 import * as library from './library.service'
-import { copyWallpaperFolder, exists, hasBackupFiles, sameFileList, syncDir, verifyOnDisk } from './backup.service'
-import { getScreenAssignments } from './display.service'
+import {
+  copyWallpaperFolder,
+  exists,
+  hasBackupFiles,
+  recoverInterruptedCopy,
+  sameFileList,
+  syncDir,
+  verifyOnDisk
+} from './backup.service'
+import { getWallpapersInUse } from './display.service'
 import { unsubscribeFromItem } from './steam.service'
 import { getExtraLibraryRoots } from '../utils/paths'
 
@@ -36,11 +44,12 @@ async function transferOne(
     throw new Error('no complete local files')
   }
   if (path.dirname(sourcePath) === root) return false
-  if (mode === 'move' && getScreenAssignments().some((a) => a.wallpaperId === wallpaper.id)) {
-    throw new Error('it is on a screen right now')
+  if (mode === 'move' && getWallpapersInUse().has(wallpaper.id)) {
+    throw new Error('it is on a screen, or a playlist or schedule is switching to it right now')
   }
 
   const destDir = path.join(root, path.basename(sourcePath))
+  await recoverInterruptedCopy(destDir)
   if (await exists(destDir)) {
     // reuse an identical copy from an earlier run, anything else is someone's data
     if (!(await verifyOnDisk(sourcePath, destDir))) {

+ 7 - 7
src/main/services/library.service.ts

@@ -1,7 +1,8 @@
-import Store from 'electron-store'
+import { openStore } from '../utils/safeStore'
 import type { WallpaperMeta, WallpaperType, ContentRating, LibraryFilters, WallpaperFolder } from '@shared/types'
 import { getExtraLibraryRoots, getThumbnailsPath, getWorkshopPath } from '../utils/paths'
 import { findLocalWallpapers, localWallpaperId } from '../utils/localLibrary'
+import { containedPath } from '../utils/contained'
 import * as path from 'path'
 import * as fs from 'fs'
 import { randomUUID } from 'crypto'
@@ -25,7 +26,7 @@ interface LibraryStore {
   resolutionsVersion: number
 }
 
-const store = new Store<LibraryStore>({
+const store = openStore<LibraryStore>({
   name: 'library',
   defaults: {
     wallpapers: {},
@@ -278,10 +279,10 @@ export function getDirSize(dirPath: string): number {
       if (entry.isDirectory()) {
         total += getDirSize(full)
       } else if (entry.isFile()) {
-        try { total += fs.statSync(full).size } catch { /* skip */ }
+        try { total += fs.statSync(full).size } catch { }
       }
     }
-  } catch { /* skip unreadable dirs */ }
+  } catch { }
   return total
 }
 
@@ -299,7 +300,7 @@ export async function getDirSizeAsync(dirPath: string): Promise<number> {
     if (entry.isDirectory()) {
       total += await getDirSizeAsync(full)
     } else if (entry.isFile()) {
-      try { total += (await fs.promises.stat(full)).size } catch { /* skip */ }
+      try { total += (await fs.promises.stat(full)).size } catch { }
     }
   }
   return total
@@ -318,7 +319,7 @@ function buildMeta(
   const now = Date.now()
   const { downloading: _d, downloadFailed: _df, ...existingRest } = existing ?? { appliedCount: 0, categories: [] }
   // the preview can still be downloading, the next scan picks it up
-  const previewPath = pj?.preview ? path.join(localPath, pj.preview) : undefined
+  const previewPath = containedPath(localPath, pj?.preview)
   // Steam can flag an item Mature later, only the live tags show that
   const fromProject = stricterRating(normalizeRating(pj?.contentrating), deriveRatingFromTags(pj?.tags ?? []))
   const contentRating = stricterRating(fromProject, deriveRatingFromTags(liveWorkshopTags ?? []))
@@ -891,7 +892,6 @@ export function cleanupFolders(): number {
 export function importWEConfig(configPath: string): { folders: number; playlists: number } {
   const raw = fs.readFileSync(configPath, 'utf8')
   const data = JSON.parse(raw)
-  const workshopPath = getWorkshopPath()
 
   const imported: WallpaperFolder[] = []
   const existingTitles = new Set(store.get('folders').map((f) => f.title))

+ 4 - 4
src/main/services/lwe-prebuilt.service.ts

@@ -9,7 +9,7 @@ import type { LweInstallProgress, LwePrebuiltTarget } from '@shared/types'
 import { isCommandAvailable } from '../utils/platform'
 import { getLwePrebuiltDir } from '../utils/paths'
 import { isFlatpak } from '../utils/flatpak'
-import { download, fetchLatestRelease } from '../utils/github'
+import { downloadVerified, fetchLatestRelease } from '../utils/github'
 import { buildCleanBuildEnv, isOstreeSystem, parseOsReleaseIds, readPrebuiltRelease, resetLweDetection } from './lwe.service'
 import { t } from '../i18n'
 
@@ -49,7 +49,7 @@ function readOsRelease(): Record<string, string> {
       const match = /^([A-Z_]+)=(.*)$/.exec(line.trim())
       if (match) fields[match[1]] = match[2].replace(/^["']|["']$/g, '')
     }
-  } catch { /* no os-release */ }
+  } catch { }
   return fields
 }
 
@@ -177,7 +177,6 @@ export async function installLwePrebuilt(win: BrowserWindow): Promise<void> {
     send({ stage: 'downloading', message: t('lwe.lookingUpRelease'), percentage: 2 })
     const release = await fetchLatestRelease(LWE_RELEASE_REPO)
     if (!release) throw new Error(`${LWE_RELEASE_REPO} has no releases yet.`)
-    // fall back to the portable build
     const portableAsset = assetName(isKdeSession() ? 'kde' : 'generic', 'portable')
     const asset = release.assets.find(a => a.name === target.asset) ?? release.assets.find(a => a.name === portableAsset)
     if (!asset) throw new Error(`Release ${release.tag_name} has no ${target.asset}.`)
@@ -191,7 +190,8 @@ export async function installLwePrebuilt(win: BrowserWindow): Promise<void> {
       const sizeMb = Math.round(asset.size / 1024 / 1024)
       send({ stage: 'downloading', message: t('lwe.downloadingRelease', { tag: release.tag_name, size: sizeMb }), percentage: 5 })
       fs.mkdirSync(path.dirname(installDir), { recursive: true })
-      await download(asset.browser_download_url, archive, asset.size, fraction => {
+      // checked against the release's size and sha256 before tar sees it
+      await downloadVerified(asset, archive, fraction => {
         send({
           stage: 'downloading',
           message: t('lwe.downloadingRelease', { tag: release.tag_name, size: sizeMb }),

+ 12 - 0
src/main/services/lwe.service.test.ts

@@ -70,6 +70,18 @@ describe('buildHotswapLines', () => {
     expect(buildHotswapLines({})).toEqual([])
   })
 
+  it('leaves out a line whose value would split into two requests', () => {
+    const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+    const lines = buildHotswapLines({
+      propertyOverrides: { title: 'a\npath=/etc/passwd', fine: 'ok', 'bad\rkey': '1' },
+      path: '/wallpapers/1\n/wallpapers/2',
+      volume: 30
+    })
+    expect(lines).toEqual(['volume=30', 'property=fine=ok'])
+    expect(warn).toHaveBeenCalled()
+    warn.mockRestore()
+  })
+
   it('sends the video parts and seeks after setting them', () => {
     expect(
       buildHotswapLines({

+ 41 - 58
src/main/services/lwe.service.ts

@@ -43,6 +43,8 @@ import {
   killHostProcess
 } from '../utils/flatpak'
 import { owningPackage } from '../utils/packages'
+import { isOwnDirectory, lweBuildDir } from '../utils/buildDir'
+import { LWE_PROCESS_PATTERN, isLweCommandLine } from '../utils/engineProcess'
 import {
   getLweRepoUrl,
   getLweRepoBranch,
@@ -99,7 +101,7 @@ function dropPoisonedCmakeCache(cmakeBuild: string): boolean {
 }
 
 const LWE_BINARY = 'linux-wallpaperengine'
-const BUILD_DIR = path.join(os.tmpdir(), 'lwe-build')
+const BUILD_DIR = lweBuildDir()
 
 const LWE_SEARCH_PATHS = [
   path.join(os.homedir(), 'projects', 'private', 'linux-wallpaperengine', 'build', 'output', 'linux-wallpaperengine'),
@@ -123,6 +125,9 @@ async function removeBuildDir(dir: string): Promise<void> {
     const code = (err as NodeJS.ErrnoException).code
     if (code !== 'EACCES' && code !== 'ENOTEMPTY' && code !== 'EPERM') throw err
   }
+  // root only deletes what is ours: files a make install left root-owned inside our folder, not somebody else's
+  // folder or a link
+  if (!isOwnDirectory(dir)) throw new Error(`${dir} is not a folder of yours, not removing it as root.`)
   const elevate = isCommandAvailable('pkexec') ? 'pkexec' : 'sudo'
   await execFileAsync(elevate, ['rm', '-rf', dir], { timeout: 30_000, encoding: 'utf8' })
 }
@@ -143,35 +148,7 @@ function readLweManifest(): LweInstallManifest | undefined {
 function writeLweManifest(manifest: LweInstallManifest): void {
   try {
     fs.writeFileSync(getLweManifestPath(), JSON.stringify(manifest, null, 2), 'utf8')
-  } catch { /* non-fatal */ }
-}
-
-function parseExtraCmakeArgs(raw: string | null): string[] {
-  if (!raw) return []
-  const args: string[] = []
-  let current = ''
-  let quote: string | null = null
-  let inToken = false
-  for (const ch of raw) {
-    if (quote) {
-      if (ch === quote) quote = null
-      else current += ch
-      continue
-    }
-    if (ch === '"' || ch === "'") {
-      quote = ch
-      inToken = true
-      continue
-    }
-    if (/\s/.test(ch)) {
-      if (inToken) { args.push(current); current = ''; inToken = false }
-      continue
-    }
-    current += ch
-    inToken = true
-  }
-  if (inToken) args.push(current)
-  return args
+  } catch { }
 }
 
 const FLATPAK_LWE_BINARY = '/app/bin/linux-wallpaperengine'
@@ -182,7 +159,7 @@ function findLweBinary(): string | undefined {
     try {
       fs.accessSync(p, fs.constants.X_OK)
       return p
-    } catch { /* keep looking */ }
+    } catch { }
   }
   return whichCommand(LWE_BINARY)
 }
@@ -204,7 +181,7 @@ let ownerCache: { path: string; owner: string | undefined } | undefined
 /** Flatpak, Nix profile or distribution package that owns the binary */
 export function lwePackageOwner(binary: string): string | undefined {
   let real = binary
-  try { real = fs.realpathSync(binary) } catch { /* keep the path */ }
+  try { real = fs.realpathSync(binary) } catch { }
   if (ownerCache?.path === real) return ownerCache.owner
   let owner: string | undefined
   if (isFlatpak() && real.startsWith('/app/')) {
@@ -292,8 +269,8 @@ const DEPS_FEDORA = [
 ]
 
 /** Versioned nodejsNN-devel packages conflict: keep an installed one, else match the newest libnode */
-export function nodeDevelPackage(installedNodePackages: string[]): string | null {
-  const names = installedNodePackages.map((name) => name.trim())
+export function nodeDevelPackage(installed: string[]): string | null {
+  const names = installed.map((name) => name.trim())
   if (names.some((name) => /^nodejs\d*-devel$/.test(name))) return null
 
   let best: { name: string; version: number } | undefined
@@ -306,6 +283,10 @@ export function nodeDevelPackage(installedNodePackages: string[]): string | null
   return best?.name ?? 'nodejs-devel'
 }
 
+function quotedPaths(paths: string[]): string {
+  return paths.map((p) => JSON.stringify(p)).join(' ')
+}
+
 function installedNodePackages(): string[] {
   try {
     return execFileSync('rpm', ['-qa', '--qf', '%{NAME}\n', 'nodejs*-libs', 'nodejs*-devel'], {
@@ -455,11 +436,12 @@ export async function installLwe(win: BrowserWindow): Promise<void> {
     if (!canReuseBuildCache) {
       await removeBuildDir(BUILD_DIR)
     }
+    // private, the install runs this tree's make as root
+    fs.mkdirSync(BUILD_DIR, { recursive: true, mode: 0o700 })
 
     if (isLocalDir) {
       // copy the working tree so uncommitted edits are built
       send({ stage: 'cloning', message: t('lwe.copyingSource', { repo }), percentage: 5 })
-      fs.mkdirSync(BUILD_DIR, { recursive: true })
       if (isCommandAvailable('rsync')) {
         // --no-times: old source mtimes could make make skip a changed file in a reused dir
         await execFileAsync('rsync', [
@@ -490,6 +472,9 @@ export async function installLwe(win: BrowserWindow): Promise<void> {
       })
     }
 
+    // rsync -a gave it the source folder's mode
+    fs.chmodSync(BUILD_DIR, 0o700)
+
     const cmakeBuild = path.join(BUILD_DIR, 'build')
     fs.mkdirSync(cmakeBuild, { recursive: true })
     if (dropPoisonedCmakeCache(cmakeBuild)) {
@@ -505,7 +490,7 @@ export async function installLwe(win: BrowserWindow): Promise<void> {
       '-DCMAKE_INSTALL_PREFIX=/usr/local',
       '-DCMAKE_C_FLAGS=-Wno-error',
       '-DCMAKE_CXX_FLAGS=-Wno-error',
-      ...parseExtraCmakeArgs(getLweCmakeArgs())
+      ...parseCustomArgs(getLweCmakeArgs() ?? '')
     ], {
       cwd: cmakeBuild,
       env: buildEnv,
@@ -522,7 +507,7 @@ export async function installLwe(win: BrowserWindow): Promise<void> {
         timeout: 60_000,
         maxBuffer: 10 * 1024 * 1024,
         encoding: 'utf8'
-      }).catch(() => { /* nothing to clean */ })
+      }).catch(() => { })
     }
 
     send({ stage: 'building', message: t('lwe.compiling'), percentage: 40 })
@@ -544,7 +529,6 @@ export async function installLwe(win: BrowserWindow): Promise<void> {
     const pathEnv = process.env.PATH ?? '/usr/local/bin:/usr/bin:/bin'
     // install_manifest.txt lets uninstall remove exactly what was installed
     const manifestMarker = '###LWE_INSTALL_MANIFEST###'
-    // hand a local repo's build dir back to the user
     const reclaim = isLocalDir
       ? `chown -R ${process.getuid!()}:${process.getgid!()} ${JSON.stringify(BUILD_DIR)}`
       : `rm -rf ${JSON.stringify(BUILD_DIR)}`
@@ -586,7 +570,7 @@ export async function installLwe(win: BrowserWindow): Promise<void> {
     if (!isLocalDir) {
       try {
         await removeBuildDir(BUILD_DIR)
-      } catch { /* ignore cleanup errors */ }
+      } catch { }
 
     }
 
@@ -657,7 +641,6 @@ export async function uninstallLwe(): Promise<{ ok: boolean; message: string }>
     // deepest first, so a dir only prunes once its own contents are gone
     dirsToPrune = [...new Set(manifest.files.map(f => path.dirname(f)))].sort((a, b) => b.length - a.length)
   } else {
-    // no manifest: binary + lib dir only
     const binaryPath = status.path
     let realPath: string
     try {
@@ -677,21 +660,20 @@ export async function uninstallLwe(): Promise<{ ok: boolean; message: string }>
         if (entries.some(e => e.includes('cef') || e.includes('wallpaper'))) {
           filesToRemove.push(libDir)
         }
-      } catch { /* ignore */ }
+      } catch { }
     }
   }
 
   try {
-    const quoted = (paths: string[]) => paths.map(p => JSON.stringify(p)).join(' ')
     const script = dirsToPrune.length > 0
-      ? `rm -f ${quoted(filesToRemove)}; rmdir --ignore-fail-on-non-empty -p ${quoted(dirsToPrune)} 2>/dev/null; ldconfig`
-      : `rm -f ${quoted(filesToRemove)}; ldconfig`
+      ? `rm -f ${quotedPaths(filesToRemove)}; rmdir --ignore-fail-on-non-empty -p ${quotedPaths(dirsToPrune)} 2>/dev/null; ldconfig`
+      : `rm -f ${quotedPaths(filesToRemove)}; ldconfig`
     await execFileAsync(elevate, ['bash', '-c', script], {
       timeout: 60_000,
       encoding: 'utf8'
     })
 
-    try { fs.rmSync(getLweManifestPath(), { force: true }) } catch { /* ignore */ }
+    try { fs.rmSync(getLweManifestPath(), { force: true }) } catch { }
 
     resetLweDetection()
 
@@ -1130,7 +1112,7 @@ function isLweProcess(pid: number): boolean {
 
   try {
     const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8')
-    return cmdline.includes(LWE_BINARY)
+    return isLweCommandLine(cmdline)
   } catch {
     // /proc unreadable, it is alive at least
     return true
@@ -1149,7 +1131,7 @@ const HOST_ALIVE_TTL_MS = 5000
 
 function rememberHostAlive(hostPid: number, cmdline: string | null | undefined): boolean {
   // undefined: the host couldn't be asked
-  const alive = cmdline === undefined ? (hostAliveCache.get(hostPid)?.alive ?? true) : !!cmdline?.includes(LWE_BINARY)
+  const alive = cmdline === undefined ? (hostAliveCache.get(hostPid)?.alive ?? true) : !!cmdline && isLweCommandLine(cmdline)
   hostAliveCache.set(hostPid, { alive, at: Date.now() })
   return alive
 }
@@ -1227,7 +1209,6 @@ function readInstanceEntries(): InstanceEntry[] {
   try {
     return JSON.parse(fs.readFileSync(getInstancesFilePath(), 'utf8')) as InstanceEntry[]
   } catch {
-    // nothing running
     return []
   }
 }
@@ -1480,7 +1461,9 @@ export function buildHotswapLines(options: HotswapOptions): string[] {
   for (const [id, volume] of Object.entries(options.soundVolume ?? {})) {
     lines.push(`sound-volume=${id}=${volume}`)
   }
-  return lines
+  const whole = lines.filter((line) => !/[\r\n]/.test(line))
+  if (whole.length !== lines.length) console.warn('[LWE] Left out control lines holding a line break')
+  return whole
 }
 
 // engines sharing the control file must read a request before the next overwrites it
@@ -1754,7 +1737,7 @@ export async function listLweObjects(wallpaperPath: string): Promise<LweSceneObj
   } catch (err) {
     const e = err as Error & { stdout?: string; stderr?: string }
     const msg = (e.stderr || e.stdout || e.message || String(err)).trim().split('\n').slice(0, 3).join('\n')
-    throw new Error(`Failed to list wallpaper objects: ${msg}`)
+    throw new Error(`Failed to list wallpaper objects: ${msg}`, { cause: err })
   }
 }
 
@@ -1793,7 +1776,7 @@ export async function listLweEffects(wallpaperPath: string): Promise<LweSceneEff
   } catch (err) {
     const e = err as Error & { stdout?: string; stderr?: string }
     const msg = (e.stderr || e.stdout || e.message || String(err)).trim().split('\n').slice(0, 3).join('\n')
-    throw new Error(`Failed to list wallpaper effects: ${msg}`)
+    throw new Error(`Failed to list wallpaper effects: ${msg}`, { cause: err })
   }
 }
 
@@ -1843,7 +1826,7 @@ export async function listLweAudioObjects(wallpaperPath: string): Promise<LweAud
   } catch (err) {
     const e = err as Error & { stdout?: string; stderr?: string }
     const msg = (e.stderr || e.stdout || e.message || String(err)).trim().split('\n').slice(0, 3).join('\n')
-    throw new Error(`Failed to list audio-reactive objects: ${msg}`)
+    throw new Error(`Failed to list audio-reactive objects: ${msg}`, { cause: err })
   }
 }
 
@@ -1916,7 +1899,7 @@ export async function listLweProperties(wallpaperPath: string): Promise<LwePrope
   } catch (err) {
     const e = err as Error & { stdout?: string; stderr?: string }
     const msg = (e.stderr || e.stdout || e.message || String(err)).trim().split('\n').slice(0, 3).join('\n')
-    throw new Error(`Failed to list wallpaper properties: ${msg}`)
+    throw new Error(`Failed to list wallpaper properties: ${msg}`, { cause: err })
   }
 }
 
@@ -1948,7 +1931,7 @@ async function waitForExit(target: EngineProcess, timeoutMs = 2000): Promise<voi
 
   try {
     signalEngine(target, 'SIGKILL')
-  } catch { /* already dead */ }
+  } catch { }
   await pollUntilGone(target, 500)
 }
 
@@ -1962,7 +1945,7 @@ export async function stopLwe(screen?: ScreenTarget): Promise<void> {
       inst.stopping = true
       try {
         signalEngine(inst, 'SIGTERM')
-      } catch { /* already dead */ }
+      } catch { }
       await waitForExit(inst)
       if (inst.controlFile) fs.rmSync(inst.controlFile, { force: true })
       fs.rmSync(inputFileFor(inst.screen), { force: true })
@@ -1983,8 +1966,9 @@ export async function killAllLweProcesses(): Promise<{ ok: boolean; message: str
   instances.clear()
   persistInstances()
 
-  // the bracket keeps pkill from matching flatpak-spawn's own command line
-  const [file, args] = hostCommand('pkill', ['-9', '-f', '-c', `${LWE_BINARY.slice(0, -1)}[${LWE_BINARY.slice(-1)}]`])
+  // by the program's own name, not by the name showing up anywhere in a command line (an editor on the repo folder,
+  // git, make): the pattern is anchored, so flatpak-spawn's own command line doesn't match either
+  const [file, args] = hostCommand('pkill', ['-9', '-f', '-c', LWE_PROCESS_PATTERN])
   try {
     const { stdout } = await execFileAsync(file, args)
     const count = parseInt(stdout.trim(), 10) || 0
@@ -2001,7 +1985,6 @@ export async function killAllLweProcesses(): Promise<{ ok: boolean; message: str
 
 const SCREENSHOT_TIMEOUT_MS = 45_000
 
-/** Saves one settled frame to `outPath` */
 export async function captureLweScreenshot(
   wallpaperPath: string,
   options: LweLaunchOptions,

+ 10 - 4
src/main/services/playlist-player.service.ts

@@ -1,4 +1,4 @@
-import Store from 'electron-store'
+import { openStore } from '../utils/safeStore'
 import type { BrowserWindow } from 'electron'
 import { IpcChannels } from '@shared/ipc-channels'
 import type { Playlist, PlaylistItem, PlaylistPlaybackState, ScreenTarget } from '@shared/types'
@@ -9,7 +9,7 @@ import { getWallpaper, updateWallpaper } from './library.service'
 import { getLweStatus, ALL_SCREENS } from './lwe.service'
 import { getAutostartPlaylistId } from './config.service'
 import { getFavoriteItemIds } from './steam.service'
-import { expandScreen, getDisplayTargets, setPlaylistRecovery, showWallpaper } from './display.service'
+import { expandScreen, getDisplayTargets, setBusyWallpaperSource, setPlaylistRecovery, showWallpaper } from './display.service'
 import { findWallpaperVideoFile, getVideoDurationSec } from '../utils/video'
 
 interface SavedPlayer {
@@ -24,7 +24,7 @@ interface PlaybackStore {
   players: Record<ScreenTarget, SavedPlayer> | null
 }
 
-const store = new Store<PlaybackStore>({
+const store = openStore<PlaybackStore>({
   name: 'playlist-playback',
   defaults: { activePlaylistId: null, isPlaying: false, players: null }
 })
@@ -118,12 +118,15 @@ function rotationFilter(playlist: Playlist, order: string[]): (id: string) => bo
   return order.some((id) => favorites.has(id)) ? (id) => favorites.has(id) : () => true
 }
 
+function known(id: string): boolean {
+  return compatStatus(getWallpaper(id)?.compat) !== 'crashes'
+}
+
 /** Skips crashing items and non-favorites while something else is left. `picked` always plays */
 async function applyCurrent(player: Player, playlist: Playlist, picked?: string): Promise<void> {
   const { state } = player
   const count = state.order.length
   const inRotation = rotationFilter(playlist, state.order)
-  const known = (id: string) => compatStatus(getWallpaper(id)?.compat) !== 'crashes'
   const anyPlayable = state.order.some((id) => inRotation(id) && known(id))
 
   player.applying = true
@@ -387,6 +390,9 @@ function savedPlayers(): Record<ScreenTarget, SavedPlayer> {
 
 export function initPlaylistPlayer(window: BrowserWindow): boolean {
   win = window
+  setBusyWallpaperSource('playlist', () =>
+    [...players.values()].flatMap((p) => [p.state.currentItemId, p.applying ? p.state.order[p.state.currentIndex] : null]).filter((id): id is string => !!id)
+  )
   setPlaylistRecovery((screen) => {
     const player = players.get(screen)
     if (!player?.state.isPlaying || player.applying) return false

+ 2 - 8
src/main/services/playlist.service.ts

@@ -1,4 +1,4 @@
-import Store from 'electron-store'
+import { openStore } from '../utils/safeStore'
 import { randomUUID } from 'crypto'
 import type { Playlist, PlaylistItem, PlaylistSettings } from '@shared/types'
 import { findAndMutate } from '../utils/collections'
@@ -15,7 +15,7 @@ const DEFAULT_SETTINGS: PlaylistSettings = {
   defaultVolume: 100
 }
 
-const store = new Store<PlaylistStore>({
+const store = openStore<PlaylistStore>({
   name: 'playlists',
   defaults: { playlists: [] }
 })
@@ -93,7 +93,6 @@ export function removeItemsFromPlaylist(id: string, wallpaperIds: string[]): Pla
   })
 }
 
-/** Reorders items to match the given wallpaperId sequence (used for manual drag-reorder). */
 export function reorderPlaylistItems(id: string, orderedWallpaperIds: string[]): Playlist | null {
   return updatePlaylist(id, (playlist) => {
     const byId = new Map(playlist.items.map((i) => [i.wallpaperId, i]))
@@ -105,7 +104,6 @@ export function reorderPlaylistItems(id: string, orderedWallpaperIds: string[]):
         byId.delete(wallpaperId)
       }
     }
-    // Append anything not mentioned in orderedWallpaperIds (defensive, shouldn't normally happen)
     reordered.push(...byId.values())
     playlist.items = reordered
   })
@@ -124,10 +122,6 @@ export function updatePlaylistItem(
   })
 }
 
-/**
- * Remove playlist item references that don't exist in the library anymore.
- * Returns the number of stale references removed.
- */
 export function cleanupPlaylists(validWallpaperIds: Set<string>): number {
   const playlists = store.get('playlists')
   let removed = 0

+ 13 - 4
src/main/services/schedule.service.ts

@@ -1,4 +1,4 @@
-import Store from 'electron-store'
+import { openStore } from '../utils/safeStore'
 import { nativeTheme, type BrowserWindow } from 'electron'
 import { randomUUID } from 'crypto'
 import { IpcChannels } from '@shared/ipc-channels'
@@ -6,7 +6,7 @@ import type { ScheduleRule } from '@shared/types'
 import { dueTimeRules } from '@shared/schedule'
 import { getWallpaper, updateWallpaper } from './library.service'
 import { getPlaylist } from './playlist.service'
-import { expandScreen, showWallpaper, stopDisplay } from './display.service'
+import { expandScreen, setBusyWallpaperSource, showWallpaper, stopDisplay } from './display.service'
 import { startPlaylist, stopPlaylist } from './playlist-player.service'
 
 interface ScheduleStore {
@@ -15,7 +15,7 @@ interface ScheduleStore {
   lastTick: number | null
 }
 
-const store = new Store<ScheduleStore>({
+const store = openStore<ScheduleStore>({
   name: 'schedule',
   defaults: { rules: [], lastTick: null }
 })
@@ -27,6 +27,7 @@ const MAX_CATCH_UP_MS = 7 * 24 * 60 * 60 * 1000
 let win: BrowserWindow | null = null
 let timer: ReturnType<typeof setInterval> | null = null
 let lastDark: boolean | null = null
+const runningWallpapers = new Map<string, number>()
 
 export function getScheduleRules(): ScheduleRule[] {
   return store.get('rules')
@@ -54,7 +55,14 @@ export async function runRule(rule: ScheduleRule): Promise<void> {
     const wallpaper = getWallpaper(action.wallpaperId)
     if (!wallpaper) throw new Error('The scheduled wallpaper is no longer in the library')
     for (const s of expandScreen(screen)) stopPlaylist(s)
-    await showWallpaper(wallpaper, screen, { dependencyPrompt: 'once' })
+    runningWallpapers.set(wallpaper.id, (runningWallpapers.get(wallpaper.id) ?? 0) + 1)
+    try {
+      await showWallpaper(wallpaper, screen, { dependencyPrompt: 'once' })
+    } finally {
+      const left = (runningWallpapers.get(wallpaper.id) ?? 1) - 1
+      if (left > 0) runningWallpapers.set(wallpaper.id, left)
+      else runningWallpapers.delete(wallpaper.id)
+    }
     updateWallpaper(wallpaper.id, { appliedCount: (wallpaper.appliedCount ?? 0) + 1, lastAppliedAt: Date.now() })
   } else if (action.type === 'playlist') {
     if (!getPlaylist(action.playlistId)) throw new Error('The scheduled playlist no longer exists')
@@ -95,6 +103,7 @@ function onThemeChanged(): void {
 /** Call after the playlist player resumed, so a rule that came due while closed wins over it */
 export function initSchedule(window: BrowserWindow): void {
   win = window
+  setBusyWallpaperSource('schedule', () => [...runningWallpapers.keys()])
   lastDark = nativeTheme.shouldUseDarkColors
   nativeTheme.on('updated', onThemeChanged)
   tick()

+ 0 - 1
src/main/services/shortcuts.service.ts

@@ -53,7 +53,6 @@ export function listDesktopApplications(): DesktopApplication[] {
         if (entry.Type !== 'Application' || entry.NoDisplay === 'true' || entry.Hidden === 'true' || !entry.Name) continue
         result.push({ name: entry.Name, file: path.join(dir, relative) })
       } catch {
-        // unreadable entries are skipped
       }
     }
   }

+ 9 - 9
src/main/services/static-wallpaper.service.test.ts

@@ -100,13 +100,13 @@ describe('applySwww', () => {
   })
 })
 
-describe('applySwaybg', () => {
-  function fakeChild() {
-    const child = new EventEmitter() as ChildProcess & EventEmitter
-    Object.assign(child, { exitCode: null, kill: vi.fn<() => boolean>() })
-    return child
-  }
+function fakeChild() {
+  const child = new EventEmitter() as ChildProcess & EventEmitter
+  Object.assign(child, { exitCode: null, kill: vi.fn<() => boolean>() })
+  return child
+}
 
+describe('applySwaybg', () => {
   it('keeps the new swaybg running and stops the previous one', async () => {
     const first = Object.assign(fakeChild(), { pid: 4242 })
     const second = Object.assign(fakeChild(), { pid: 4243 })
@@ -128,10 +128,10 @@ describe('applySwaybg', () => {
   })
 })
 
-describe('prefersHyprpaper', () => {
-  const installed = (...cmds: string[]) => (cmd: string) => cmds.includes(cmd)
-  const runningOnly = (...names: string[]) => (name: string) => names.includes(name)
+const installed = (...cmds: string[]) => (cmd: string) => cmds.includes(cmd)
+const runningOnly = (...names: string[]) => (name: string) => names.includes(name)
 
+describe('prefersHyprpaper', () => {
   it('takes hyprpaper unless a swww daemon already draws', () => {
     expect(prefersHyprpaper(installed('hyprpaper', 'hyprctl'), runningOnly())).toBe(true)
     expect(prefersHyprpaper(installed('hyprpaper', 'hyprctl', 'swww'), runningOnly())).toBe(true)

+ 3 - 2
src/main/services/steam-list-cache.ts

@@ -1,4 +1,5 @@
-import Store from 'electron-store'
+import type Store from 'electron-store'
+import { openStore } from '../utils/safeStore'
 import { app } from 'electron'
 
 // a Steam Workshop list (liked, favorited) cached on disk, refreshed by a background crawl
@@ -57,7 +58,7 @@ export class SteamListCache {
     storeName: string,
     private source: ListSource
   ) {
-    this.store = new Store<ListCacheStore>({
+    this.store = openStore<ListCacheStore>({
       name: storeName,
       defaults: { accountId: null, up: [], missing: [], lastFullSync: 0, pending: {} }
     })

+ 99 - 0
src/main/services/steam.service.test.ts

@@ -0,0 +1,99 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { EventEmitter } from 'events'
+import { encodeBigInts } from '../steam-host-protocol'
+
+class FakeHost extends EventEmitter {
+  requests: { id: number; method: string }[] = []
+  kill = vi.fn<() => void>(() => {
+    this.emit('exit', null)
+  })
+  postMessage(message: { id: number; method: string }): void {
+    this.requests.push(message)
+  }
+  answer(id: number, result: unknown): void {
+    this.emit('message', encodeBigInts({ id, result }))
+  }
+}
+
+const hosts: FakeHost[] = []
+
+vi.mock('electron', () => ({
+  app: { on: vi.fn<() => void>() },
+  utilityProcess: {
+    fork: () => {
+      const host = new FakeHost()
+      hosts.push(host)
+      return host
+    }
+  }
+}))
+vi.mock('./config.service', () => ({ getSteamIdentity: () => 'wallpaper-engine' }))
+vi.mock('electron-store', () => ({
+  default: class {
+    private data: Record<string, unknown>
+    constructor(opts: { defaults: Record<string, unknown> }) {
+      this.data = structuredClone(opts.defaults)
+    }
+    get(key: string): unknown {
+      return this.data[key]
+    }
+    set(key: string, value: unknown): void {
+      this.data[key] = value
+    }
+  }
+}))
+vi.mock('fs', async (importOriginal) => {
+  const actual = await importOriginal<typeof import('fs')>()
+  return {
+    ...actual,
+    readFileSync: (file: string, ...rest: unknown[]) => {
+      if (String(file).endsWith('steam.pid')) return '4242'
+      if (file === '/proc/4242/comm') return 'steam\n'
+      return (actual.readFileSync as (...args: unknown[]) => unknown)(file, ...rest)
+    }
+  }
+})
+
+const steam = await import('./steam.service')
+
+const window = {
+  isDestroyed: () => false,
+  isVisible: () => true,
+  isMinimized: () => false,
+  on: () => {}
+} as never
+
+async function untilRequest(host: FakeHost, method: string): Promise<{ id: number }> {
+  await vi.waitFor(() => expect(host.requests.some((r) => r.method === method)).toBe(true))
+  return host.requests.find((r) => r.method === method)!
+}
+
+describe('a Steam request that never answers', () => {
+  beforeEach(() => {
+    vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })
+    steam.bindSteamToWindow(window)
+  })
+  afterEach(() => {
+    vi.useRealTimers()
+  })
+
+  it('drops the host that did not answer and starts a new one for the next request', async () => {
+    const first = steam.getLocalAccountId()
+    await vi.waitFor(() => expect(hosts).toHaveLength(1))
+    hosts[0].answer((await untilRequest(hosts[0], 'init')).id, null)
+    await untilRequest(hosts[0], 'workshop.getSubscribedItems').catch(() => undefined)
+    await untilRequest(hosts[0], 'localplayer.getSteamId')
+
+    const failure = first.then(() => new Error('answered'), (err: Error) => err)
+    await vi.advanceTimersByTimeAsync(60_000)
+    expect((await failure).message).toMatch(/timed out/)
+    expect(hosts[0].kill).toHaveBeenCalledTimes(1)
+
+    const second = steam.getLocalAccountId()
+    await vi.waitFor(() => expect(hosts).toHaveLength(2))
+    hosts[1].answer((await untilRequest(hosts[1], 'init')).id, null)
+    const request = await untilRequest(hosts[1], 'localplayer.getSteamId')
+    hosts[1].answer(request.id, { accountId: 7 })
+    expect(await second).toBe(7)
+  })
+})

+ 19 - 5
src/main/services/steam.service.ts

@@ -117,6 +117,7 @@ function send(proc: UtilityProcess, method: string, args: unknown[]): Promise<un
     const timer = setTimeout(() => {
       pendingRequests.delete(id)
       reject(new Error(`Steam ${method} timed out`))
+      if (host === proc) stopHost()
     }, REQUEST_TIMEOUT_MS)
     pendingRequests.set(id, {
       resolve: (v) => {
@@ -176,9 +177,19 @@ function startHost(): Promise<void> {
   )
 }
 
-async function steamCall<T>(method: string, ...args: unknown[]): Promise<T> {
+function assertSteamUsable(): void {
   if (!windowActive) throw new Error('Steam is only used while the window is open')
   if (!isSteamRunning()) throw new Error('Steam not running')
+}
+
+export async function whenHostReady(): Promise<void> {
+  assertSteamUsable()
+  if (!hostReady) hostReady = startHost()
+  await hostReady
+}
+
+async function steamCall<T>(method: string, ...args: unknown[]): Promise<T> {
+  assertSteamUsable()
   inFlight++
   try {
     if (!hostReady) hostReady = startHost()
@@ -437,7 +448,7 @@ export function voteOnItemAndConfirm(itemId: bigint, voteUp: boolean): Promise<b
         up: voteUp,
         message: `${voteUp ? 'Like' : 'Dislike'} failed after ${WRITE_ATTEMPTS} attempts: ${msg}`
       })
-      throw new Error(`Could not reach Steam to ${voteUp ? 'like' : 'dislike'} this wallpaper: ${msg}`)
+      throw new Error(`Could not reach Steam to ${voteUp ? 'like' : 'dislike'} this wallpaper: ${msg}`, { cause: err })
     }
     setVoteFailure(idStr, null)
     likedList.record(idStr, voteUp)
@@ -546,7 +557,7 @@ export function setFavorite(itemId: bigint, add: boolean): Promise<boolean> {
         message: `${add ? 'Adding to' : 'Removing from'} favorites failed after ${WRITE_ATTEMPTS} attempts: ${msg}`
       })
       favoriteStatusChanged()
-      throw new Error(`Could not reach Steam to ${add ? 'favorite' : 'unfavorite'} this wallpaper: ${msg}`)
+      throw new Error(`Could not reach Steam to ${add ? 'favorite' : 'unfavorite'} this wallpaper: ${msg}`, { cause: err })
     }
     failedFavorites.delete(idStr)
     favoriteList.record(idStr, add)
@@ -618,11 +629,15 @@ export async function getInstallInfo(itemId: bigint): Promise<{ folder: string;
 
 // steamworks.js only knows the player and friends, read the public profile XML
 const authorInfoCache = new Map<string, WorkshopAuthorInfo | null>()
+const PROFILE_FETCH_TIMEOUT_MS = 15_000
 
 export async function getAuthorInfo(steamId: string): Promise<WorkshopAuthorInfo | null> {
   if (authorInfoCache.has(steamId)) return authorInfoCache.get(steamId) ?? null
   try {
-    const res = await fetch(`https://steamcommunity.com/profiles/${steamId}?xml=1`)
+    const res = await fetch(`https://steamcommunity.com/profiles/${steamId}?xml=1`, {
+      signal: AbortSignal.timeout(PROFILE_FETCH_TIMEOUT_MS)
+    })
+    if (!res.ok) return null
     const xml = await res.text()
     const name = xml.match(/<steamID><!\[CDATA\[([\s\S]*?)\]\]><\/steamID>/)?.[1]
     const avatarUrl = xml.match(/<avatarFull><!\[CDATA\[([\s\S]*?)\]\]><\/avatarFull>/)?.[1]
@@ -630,7 +645,6 @@ export async function getAuthorInfo(steamId: string): Promise<WorkshopAuthorInfo
     authorInfoCache.set(steamId, info)
     return info
   } catch {
-    authorInfoCache.set(steamId, null)
     return null
   }
 }

+ 1 - 1
src/main/services/update.service.ts

@@ -85,7 +85,7 @@ function evaluateEngine(): void {
   let version: string | null = status.version ?? null
   let managedBy: string | undefined
   let real = status.path
-  try { real = fs.realpathSync(status.path) } catch { /* keep the path */ }
+  try { real = fs.realpathSync(status.path) } catch { }
 
   if (status.version) {
     install = 'prebuilt'

+ 2 - 2
src/main/services/wallpaper-state.service.ts

@@ -1,4 +1,4 @@
-import Store from 'electron-store'
+import { openStore } from '../utils/safeStore'
 import type { ScreenTarget } from '@shared/types'
 
 interface StoreSchema {
@@ -7,7 +7,7 @@ interface StoreSchema {
   assignments?: Record<ScreenTarget, string>
 }
 
-const store = new Store<StoreSchema>()
+const store = openStore<StoreSchema>()
 
 export function getAssignments(): Record<ScreenTarget, string> {
   const assignments = store.get('assignments')

+ 5 - 15
src/main/services/wallpaper.service.ts

@@ -5,6 +5,7 @@ import * as fs from 'fs'
 import * as path from 'path'
 import { detectDisplayServer, detectDesktopEnv } from '../utils/platform'
 import { hostCommand, isHostCommandAvailable } from '../utils/flatpak'
+import { fileUri, finderWallpaperArgs, plasmaWallpaperScript } from '../utils/wallpaperScripts'
 import type { ScreenTarget, WallpaperBackend, WallpaperEnvironment, WallpaperMeta } from '@shared/types'
 import { getLweStatus, launchLweAsync, type LweLaunchOptions } from './lwe.service'
 import { ensureDependencyInstalled } from './dependency.service'
@@ -138,27 +139,17 @@ async function applyWithBackend(backend: WallpaperBackend, imagePath: string): P
         'set',
         'org.gnome.desktop.background',
         'picture-uri',
-        `file://${imagePath}`
+        fileUri(imagePath)
       ]))
       break
-    case 'qdbus': {
-      const script = `
-        var allDesktops = desktops();
-        for (var i = 0; i < allDesktops.length; i++) {
-          var d = allDesktops[i];
-          d.wallpaperPlugin = 'org.kde.image';
-          d.currentConfigGroup = ['Wallpaper', 'org.kde.image', 'General'];
-          d.writeConfig('Image', 'file://${imagePath}');
-        }
-      `
+    case 'qdbus':
       await execFileAsync(...hostCommand('qdbus', [
         'org.kde.plasmashell',
         '/PlasmaShell',
         'org.kde.PlasmaShell.evaluateScript',
-        script
+        plasmaWallpaperScript(imagePath)
       ]))
       break
-    }
     case 'windows':
       await applyWindows(imagePath)
       break
@@ -171,8 +162,7 @@ async function applyWithBackend(backend: WallpaperBackend, imagePath: string): P
 }
 
 async function applyMacOS(imagePath: string): Promise<void> {
-  const script = `tell application "Finder" to set desktop picture to POSIX file "${imagePath}"`
-  await execFileAsync('osascript', ['-e', script])
+  await execFileAsync('osascript', finderWallpaperArgs(imagePath))
 }
 
 async function applyWindows(imagePath: string): Promise<void> {

+ 75 - 0
src/main/services/workshop-verify.service.test.ts

@@ -6,6 +6,8 @@ import type { WallpaperMeta } from '@shared/types'
 
 let state = 0
 let steamDown = false
+let hostBoot: Promise<void> = Promise.resolve()
+let hostRequested = false
 let subscribed: string[] = []
 let installInfo: { folder: string; sizeOnDisk: number } | null = null
 const wallpapers = new Map<string, WallpaperMeta>()
@@ -20,8 +22,15 @@ vi.mock('./steam.service', () => ({
   ITEM_STATE_DOWNLOAD_PENDING: 32,
   isSteamRunning: () => true,
   getSubscribedItems: async () => subscribed,
+  whenHostReady: async () => {
+    hostRequested = true
+    if (steamDown) throw new Error('Steam is only used while the window is open')
+    await hostBoot
+  },
   fetchItemState: async () => {
+    hostRequested = true
     if (steamDown) throw new Error('Steam is only used while the window is open')
+    await hostBoot
     return state
   },
   getInstallInfo: async () => installInfo
@@ -175,6 +184,16 @@ describe('verifyItems', () => {
   })
 })
 
+function stashed(id: string, newFiles: Record<string, string>): { item: string; stash: string } {
+  const item = path.join(dir, id)
+  const stash = verify.repairStashOf(item, id)
+  fs.mkdirSync(stash)
+  fs.writeFileSync(path.join(stash, 'project.json'), '{"old":true}')
+  fs.mkdirSync(item)
+  for (const [name, content] of Object.entries(newFiles)) fs.writeFileSync(path.join(item, name), content)
+  return { item, stash }
+}
+
 describe('settleRepairStash', () => {
   it('puts the old copy back over a folder that is no wallpaper', async () => {
     const item = path.join(dir, '8')
@@ -204,4 +223,60 @@ describe('settleRepairStash', () => {
     expect(fs.existsSync(stash)).toBe(false)
     expect(fs.readFileSync(path.join(item, 'project.json'), 'utf8')).toBe('{"new":true}')
   })
+
+
+  it('keeps the old copy while the new folder only has its project.json so far', async () => {
+    const { item, stash } = stashed('10', { 'project.json': '{"type":"video","file":"clip.mp4"}' })
+
+    expect(await verify.settleRepairStash(item, stash)).toBe(true)
+
+    expect(fs.existsSync(stash)).toBe(false)
+    expect(fs.readFileSync(path.join(item, 'project.json'), 'utf8')).toBe('{"old":true}')
+  })
+
+  it('touches neither folder while Steam is still fetching the item', async () => {
+    const { item, stash } = stashed('11', { 'project.json': '{"type":"video","file":"clip.mp4"}', 'clip.mp4': 'half' })
+    state = 4 | 16
+
+    expect(await verify.settleRepairStash(item, stash)).toBe(false)
+
+    expect(fs.existsSync(path.join(stash, 'project.json'))).toBe(true)
+    expect(fs.existsSync(path.join(item, 'clip.mp4'))).toBe(true)
+  })
+
+  it('starts timing Steam\'s answer once the host is up, a slow start is not an answer', async () => {
+    vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+    try {
+      const { item, stash } = stashed('14', { 'project.json': '{"type":"video","file":"clip.mp4"}', 'clip.mp4': 'half' })
+      state = 4 | 16
+      hostBoot = new Promise((resolve) => setTimeout(resolve, 5000))
+
+      hostRequested = false
+
+      const settled = verify.settleRepairStash(item, stash)
+      await vi.waitFor(() => expect(hostRequested).toBe(true))
+      await vi.advanceTimersByTimeAsync(5000)
+
+      expect(await settled).toBe(false)
+      expect(fs.existsSync(path.join(stash, 'project.json'))).toBe(true)
+      expect(fs.existsSync(path.join(item, 'clip.mp4'))).toBe(true)
+    } finally {
+      vi.useRealTimers()
+      hostBoot = Promise.resolve()
+    }
+  })
+
+  it('does not wait for a Steam that cannot be asked', async () => {
+    const complete = stashed('12', { 'project.json': '{"type":"video","file":"clip.mp4"}', 'clip.mp4': 'video' })
+    steamDown = true
+
+    await verify.settleRepairStash(complete.item, complete.stash)
+
+    expect(fs.existsSync(complete.stash)).toBe(false)
+    expect(fs.existsSync(path.join(complete.item, 'clip.mp4'))).toBe(true)
+
+    const partial = stashed('13', { 'project.json': '{"type":"video","file":"clip.mp4"}' })
+    expect(await verify.settleRepairStash(partial.item, partial.stash)).toBe(true)
+    expect(fs.readFileSync(path.join(partial.item, 'project.json'), 'utf8')).toBe('{"old":true}')
+  })
 })

+ 36 - 3
src/main/services/workshop-verify.service.ts

@@ -59,10 +59,43 @@ export function repairStashOf(dir: string, itemId: string): string {
   return path.join(path.dirname(dir), `.reverify-${itemId}`)
 }
 
-/** after an interrupted repair, restores the old copy (true) unless Steam's folder is readable */
+const STASH_NAME = /^\.reverify-(\d+)$/
+const STATE_CHECK_TIMEOUT_MS = 3000
+const HOST_START_TIMEOUT_MS = 15_000
+
+async function within<T>(promise: Promise<T>, ms: number): Promise<T> {
+  let timer: ReturnType<typeof setTimeout> | undefined
+  try {
+    return await Promise.race([
+      promise,
+      new Promise<never>((_, reject) => {
+        timer = setTimeout(() => reject(new Error('Steam did not answer')), ms)
+      })
+    ])
+  } finally {
+    clearTimeout(timer)
+  }
+}
+
+async function steamIsFetching(itemId: string): Promise<boolean> {
+  try {
+    await within(steam.whenHostReady(), HOST_START_TIMEOUT_MS)
+    const state = await within(steam.fetchItemState(BigInt(itemId)), STATE_CHECK_TIMEOUT_MS)
+    return (state & (steam.ITEM_STATE_DOWNLOADING | steam.ITEM_STATE_DOWNLOAD_PENDING)) !== 0
+  } catch {
+    return false
+  }
+}
+
+/**
+ * After an interrupted repair, restores the old copy (true) unless Steam's folder is complete. While Steam is still
+ * fetching the item neither folder is touched, the old copy may be all there is
+ */
 export async function settleRepairStash(dir: string, stash: string): Promise<boolean> {
   if (!(await exists(stash))) return false
-  if (library.readProjectJson(dir)) {
+  const itemId = STASH_NAME.exec(path.basename(stash))?.[1]
+  if (itemId && (await steamIsFetching(itemId))) return false
+  if (!(await findFolderProblem(dir))) {
     await fs.promises.rm(stash, { recursive: true, force: true })
     return false
   }
@@ -85,7 +118,7 @@ export function restoreRepairStashes(): Promise<void> {
       return
     }
     for (const name of names) {
-      const id = /^\.reverify-(\d+)$/.exec(name)?.[1]
+      const id = STASH_NAME.exec(name)?.[1]
       if (!id) continue
       try {
         await settleRepairStash(path.join(root, id), path.join(root, name))

+ 32 - 0
src/main/services/workshop.service.test.ts

@@ -0,0 +1,32 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const workshopCall = vi.fn<(method: string, ...args: unknown[]) => Promise<unknown>>()
+
+vi.mock('./steam.service', () => ({
+  workshopCall: (method: string, ...args: unknown[]) => workshopCall(method, ...args),
+  getSubscribedItems: async () => []
+}))
+
+const { isWallpaperEngineItem } = await import('./workshop.service')
+
+describe('isWallpaperEngineItem', () => {
+  beforeEach(() => workshopCall.mockReset())
+
+  it('accepts an item made for Wallpaper Engine', async () => {
+    workshopCall.mockResolvedValue({ items: [{ publishedFileId: 5n, consumerAppId: 431960 }] })
+    expect(await isWallpaperEngineItem('5')).toBe(true)
+    expect(workshopCall).toHaveBeenCalledWith('getItems', [5n])
+  })
+
+  it('refuses an item of another app and one Steam does not know', async () => {
+    workshopCall.mockResolvedValue({ items: [{ publishedFileId: 5n, consumerAppId: 730 }] })
+    expect(await isWallpaperEngineItem('5')).toBe(false)
+    workshopCall.mockResolvedValue({ items: [null] })
+    expect(await isWallpaperEngineItem('5')).toBe(false)
+  })
+
+  it('does not guess when Steam reports no app', async () => {
+    workshopCall.mockResolvedValue({ items: [{ publishedFileId: 5n }] })
+    expect(await isWallpaperEngineItem('5')).toBe(true)
+  })
+})

+ 12 - 23
src/main/services/workshop.service.ts

@@ -11,7 +11,6 @@ import { workshopCall, getSubscribedItems } from './steam.service'
 type SteamWorkshopItem = workshop.WorkshopItem
 type WorkshopPage = workshop.WorkshopPaginatedResult
 
-// Maps our string names to steamworks.js UGCQueryType enum values
 const QUERY_TYPE_MAP: Record<string, number> = {
   RankedByVote: 0,
   RankedByPublicationDate: 1,
@@ -21,9 +20,6 @@ const QUERY_TYPE_MAP: Record<string, number> = {
   RankedByLastUpdatedDate: 19
 }
 
-// Maps our string names to steamworks.js UserListOrder enum values, used for
-// UserUGCList queries (querying a specific creator) which don't support the
-// UGCQueryType ranking options above.
 const USER_LIST_ORDER_MAP: Record<string, number> = {
   RankedByVote: 5, // VoteScoreDesc
   RankedByPublicationDate: 1, // CreationOrderDesc
@@ -58,9 +54,7 @@ export async function getWorkshopItem(publishedFileId: string): Promise<Workshop
       includeLongDescription: true
     })
   } catch {
-    // Steam's UGC details lookup throws a generic failure for an id it can no longer resolve
-    // (taken down, banned) rather than returning null the way a batch getItems() call does -
-    // treat it the same way: "we can't tell you about this item" rather than a hard error.
+    // an id Steam can no longer resolve (taken down, banned) throws here instead of returning null like getItems()
     return null
   }
   if (!item) return null
@@ -71,8 +65,6 @@ export async function getWorkshopItem(publishedFileId: string): Promise<Workshop
   return transformed
 }
 
-// UserUGCList lets us query another Steam user's published items directly,
-// unlike getAllItems which only ranks/filters across the whole workshop.
 export async function queryWorkshopByCreator(
   creatorSteamId: string,
   params: CreatorWorkshopQueryParams = {}
@@ -127,11 +119,14 @@ async function getItemsBatched(publishedFileIds: string[]) {
   return items
 }
 
+export async function isWallpaperEngineItem(publishedFileId: string): Promise<boolean> {
+  const [item] = await getItemsBatched([publishedFileId])
+  return !!item && (item.consumerAppId === undefined || item.consumerAppId === WE_APP_ID)
+}
+
 export interface WorkshopDetails {
   timeUpdated: number
-  // Steam tags an item's type ("Video", "Scene", ...) and age rating ("Everyone", ...)
-  // alongside its genre/resolution tags, so this works even for items that never
-  // finished downloading and have no local project.json to read that from.
+  // includes type and age rating, so items without a local project.json can still be classified
   tags: string[]
   authorSteamId: string
 }
@@ -152,23 +147,16 @@ export async function getWorkshopDetails(publishedFileIds: string[]): Promise<Ma
   return map
 }
 
-// Steam returns a null entry for any id that no longer resolves to a workshop
-// item (removed by its author or taken down), so anything missing from the
-// result is treated as unavailable. Lets a request error (network hiccup)
-// propagate rather than swallowing it here - the caller decides what "we
-// couldn't tell" should mean, instead of this silently reporting "all clear".
+// ids missing from the result are unavailable; a request error propagates so the caller doesn't read it as "all clear"
 export async function getUnavailableWorkshopItems(publishedFileIds: string[]): Promise<Set<string>> {
   const details = await getWorkshopDetails(publishedFileIds)
   return new Set(publishedFileIds.filter((id) => !details.has(id)))
 }
 
-// steamworks.js's UGC query bindings don't surface a file's size (the underlying Steamworks SDK
-// struct has it, the napi wrapper just doesn't map that field). Steam's own public web API does,
-// unauthenticated, for any published file regardless of subscription state - this is the exact
-// "File Size" figure shown on the item's Steam Workshop page. Cached per id for the process
-// lifetime since it barely ever changes.
+// steamworks.js doesn't map the file size field; Steam's public web API has the figure shown on the Workshop page
 const fileSizeCache = new Map<string, number>()
 const FILE_SIZE_BATCH = 100
+const FILE_SIZE_TIMEOUT_MS = 15_000
 
 async function fetchFileSizesBatch(ids: string[]): Promise<void> {
   if (ids.length === 0) return
@@ -177,7 +165,8 @@ async function fetchFileSizesBatch(ids: string[]): Promise<void> {
 
   const res = await fetch('https://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v1/', {
     method: 'POST',
-    body
+    body,
+    signal: AbortSignal.timeout(FILE_SIZE_TIMEOUT_MS)
   })
   const data = await res.json()
   const details = data?.response?.publishedfiledetails ?? []

+ 44 - 0
src/main/utils/buildDir.test.ts

@@ -0,0 +1,44 @@
+import * as fs from 'fs'
+import * as os from 'os'
+import * as path from 'path'
+import { afterAll, describe, expect, it } from 'vitest'
+import { isOwnDirectory, lweBuildDir } from './buildDir'
+
+describe('lweBuildDir', () => {
+  it('is in the cache folder of the user, never in /tmp', () => {
+    expect(lweBuildDir({}, '/home/u')).toBe('/home/u/.cache/we-manager/lwe-build')
+    expect(lweBuildDir({ XDG_CACHE_HOME: '/data/cache' }, '/home/u')).toBe('/data/cache/we-manager/lwe-build')
+  })
+
+  it('ignores a cache variable that is not an absolute path', () => {
+    expect(lweBuildDir({ XDG_CACHE_HOME: 'relative/cache' }, '/home/u')).toBe('/home/u/.cache/we-manager/lwe-build')
+    expect(lweBuildDir({ XDG_CACHE_HOME: '' }, '/home/u')).toBe('/home/u/.cache/we-manager/lwe-build')
+  })
+})
+
+describe('isOwnDirectory', () => {
+  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'wem-builddir-'))
+  afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }))
+
+  it('accepts a directory of the user', () => {
+    const dir = path.join(tmp, 'mine')
+    fs.mkdirSync(dir)
+    expect(isOwnDirectory(dir)).toBe(true)
+  })
+
+  it('refuses one that belongs to somebody else', () => {
+    const uid = process.getuid!()
+    expect(isOwnDirectory(tmp, uid + 1)).toBe(false)
+    expect(isOwnDirectory('/', uid === 0 ? 1 : uid)).toBe(false)
+  })
+
+  it('refuses a link, a file and what is not there', () => {
+    const target = path.join(tmp, 'target')
+    fs.mkdirSync(target)
+    fs.symlinkSync(target, path.join(tmp, 'link'))
+    fs.writeFileSync(path.join(tmp, 'file'), '')
+    expect(isOwnDirectory(path.join(tmp, 'link'))).toBe(false)
+    expect(isOwnDirectory(path.join(tmp, 'file'))).toBe(false)
+    expect(isOwnDirectory(path.join(tmp, 'nothing'))).toBe(false)
+  })
+})

+ 23 - 0
src/main/utils/buildDir.ts

@@ -0,0 +1,23 @@
+import * as fs from 'fs'
+import * as os from 'os'
+import * as path from 'path'
+
+/**
+ * Where the engine is built from source: in the user's own cache folder. It used to be /tmp/lwe-build, one name for
+ * everyone on a shared, world writable /tmp, so another user could have made it first, and the install runs the build's
+ * make as root.
+ */
+export function lweBuildDir(env: NodeJS.ProcessEnv = process.env, home: string = os.homedir()): string {
+  const cache = env.XDG_CACHE_HOME && path.isAbsolute(env.XDG_CACHE_HOME) ? env.XDG_CACHE_HOME : path.join(home, '.cache')
+  return path.join(cache, 'we-manager', 'lwe-build')
+}
+
+/** A real directory (not a link to one) that belongs to this user, what root may be asked to delete */
+export function isOwnDirectory(dir: string, uid: number | undefined = process.getuid?.()): boolean {
+  try {
+    const stat = fs.lstatSync(dir)
+    return stat.isDirectory() && !stat.isSymbolicLink() && uid !== undefined && stat.uid === uid
+  } catch {
+    return false
+  }
+}

+ 20 - 0
src/main/utils/contained.test.ts

@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest'
+import { containedPath } from './contained'
+
+describe('containedPath', () => {
+  it('joins a name inside the folder', () => {
+    expect(containedPath('/lib/123', 'preview.jpg')).toBe('/lib/123/preview.jpg')
+    expect(containedPath('/lib/123', 'img/./a.png')).toBe('/lib/123/img/a.png')
+    expect(containedPath('/lib/123', 'a/../b.png')).toBe('/lib/123/b.png')
+  })
+
+  it('keeps an absolute-looking name inside, like path.join does', () => {
+    expect(containedPath('/lib/123', '/etc/passwd')).toBe('/lib/123/etc/passwd')
+  })
+
+  it('refuses names that leave the folder or are not names', () => {
+    for (const rel of ['../other/p.jpg', 'a/../../p.jpg', '..', '.', '', 'a\0b', 5, null, undefined, { x: 1 }]) {
+      expect(containedPath('/lib/123', rel)).toBeUndefined()
+    }
+  })
+})

+ 8 - 0
src/main/utils/contained.ts

@@ -0,0 +1,8 @@
+import * as path from 'path'
+
+export function containedPath(dir: string, rel: unknown): string | undefined {
+  if (typeof rel !== 'string' || !rel || rel.includes('\0')) return undefined
+  const full = path.join(dir, rel)
+  const inside = path.relative(dir, full)
+  return inside && inside.split(path.sep)[0] !== '..' && !path.isAbsolute(inside) ? full : undefined
+}

+ 68 - 0
src/main/utils/engineProcess.test.ts

@@ -0,0 +1,68 @@
+import { execFileSync, spawn } from 'child_process'
+import { describe, expect, it } from 'vitest'
+import { LWE_PROCESS_PATTERN, isLweCommandLine } from './engineProcess'
+
+const engines = [
+  '/usr/local/linux-wallpaperengine --screen-root DP-1 --bg /w/1',
+  'linux-wallpaperengine --silent /w/1',
+  '/opt/linux-wallpaperengine-kde/linux-wallpaperengine',
+  '/home/u/.local/share/linux-wallpaperengine-kde/linux-wallpaperengine.bin --fps 30 /w/1',
+  '/bin/bash /home/u/.local/share/linux-wallpaperengine-kde/linux-wallpaperengine --window 0x0x1280x720',
+  '/nix/store/abc-linux-wallpaperengine/bin/linux-wallpaperengine --list-properties /w/1'
+]
+
+const others = [
+  'vim /home/u/projects/linux-wallpaperengine',
+  '/usr/bin/code /home/u/projects/private/linux-wallpaperengine',
+  'git -C /home/u/projects/linux-wallpaperengine status',
+  'make -C /tmp/lwe-build/build linux-wallpaperengine',
+  '/bin/bash -c cd ~/projects/linux-wallpaperengine && make',
+  'tail -f /home/u/logs/linux-wallpaperengine.log',
+  'less linux-wallpaperengine-kde/README.md',
+  '/home/u/projects/linux-wallpaperengine-kde/build/output/linux-wallpaperengine-web-helper --type=zygote',
+  'grep -r linux-wallpaperengine src',
+  'flatpak-spawn --host pkill -9 -f -c ^((/[^ ]*/)?(ba|da)?sh )?(/[^ ]*/)?linux-wallpaperengine(\\.bin)?( |$)',
+  ''
+]
+
+describe('isLweCommandLine', () => {
+  it.each(engines)('knows the engine as %s', (line) => {
+    expect(isLweCommandLine(line)).toBe(true)
+  })
+
+  it.each(others)('does not take for an engine: %s', (line) => {
+    expect(isLweCommandLine(line)).toBe(false)
+  })
+
+  it('reads /proc style command lines', () => {
+    expect(isLweCommandLine('/usr/local/linux-wallpaperengine\0--silent\0/w/1\0')).toBe(true)
+    expect(isLweCommandLine('vim\0/home/u/linux-wallpaperengine\0')).toBe(false)
+  })
+})
+
+const matching = (): number => {
+  try {
+    return Number(execFileSync('pgrep', ['-f', '-c', LWE_PROCESS_PATTERN]).toString().trim())
+  } catch {
+    return 0 // exit 1: nothing matched
+  }
+}
+
+// the same pattern goes to pkill: POSIX ERE, matched against a space joined command line
+describe('LWE_PROCESS_PATTERN with pkill', () => {
+  it.skipIf(process.platform !== 'linux')('matches the engines and none of the others', () => {
+    // engines of the machine running the test are in the count already
+    const before = matching()
+    // sleeps under a command line of our choosing
+    const children = [...engines, ...others.filter((line) => line && !line.startsWith('flatpak-spawn'))].map((line) =>
+      spawn('bash', ['-c', 'exec -a "$0" sleep 30', line], { stdio: 'ignore' })
+    )
+
+    try {
+      execFileSync('sleep', ['0.3'])
+      expect(matching() - before).toBe(engines.length)
+    } finally {
+      for (const child of children) child.kill('SIGKILL')
+    }
+  })
+})

+ 16 - 0
src/main/utils/engineProcess.ts

@@ -0,0 +1,16 @@
+/**
+ * The command line of a linux-wallpaperengine process: the program is the first word (a path, or the bare name), the
+ * portable build's launcher script runs it as `<shell> <script>` and its binary is `.bin`. Anything else that merely
+ * has the name somewhere in its arguments (an editor on the repo folder, git, make) is not an engine. Words are
+ * separated by single spaces here, a program in a folder with spaces in its name is not matched.
+ *
+ * One pattern for pkill -f (POSIX ERE) and for RegExp, it only uses what both read the same way.
+ */
+export const LWE_PROCESS_PATTERN = '^((/[^ ]*/)?(ba|da)?sh )?(/[^ ]*/)?linux-wallpaperengine(\\.bin)?( |$)'
+
+const LWE_PROCESS_REGEXP = new RegExp(LWE_PROCESS_PATTERN)
+
+/** /proc/<pid>/cmdline (NUL separated) or `ps` output (space separated) */
+export function isLweCommandLine(cmdline: string): boolean {
+  return LWE_PROCESS_REGEXP.test(cmdline.replace(/\0+$/, '').replace(/\0/g, ' '))
+}

+ 5 - 5
src/main/utils/flatpak.ts

@@ -44,18 +44,18 @@ export function isHostCommandAvailable(cmd: string): boolean {
   return found
 }
 
-let info: string | undefined
+let infoCache: string | undefined
 
 // written once when the sandbox starts
 function flatpakInfo(): string {
-  if (info === undefined) {
+  if (infoCache === undefined) {
     try {
-      info = fs.readFileSync('/.flatpak-info', 'utf8')
+      infoCache = fs.readFileSync('/.flatpak-info', 'utf8')
     } catch {
-      info = ''
+      infoCache = ''
     }
   }
-  return info
+  return infoCache
 }
 
 /** The sandbox's /app as the host sees it */

+ 63 - 0
src/main/utils/github.test.ts

@@ -0,0 +1,63 @@
+import * as crypto from 'crypto'
+import * as fs from 'fs'
+import * as http from 'http'
+import type { AddressInfo } from 'net'
+import * as os from 'os'
+import * as path from 'path'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { downloadVerified, type GithubAsset } from './github'
+
+const body = Buffer.from('engine archive bytes '.repeat(500))
+const sha256 = crypto.createHash('sha256').update(body).digest('hex')
+
+let server: http.Server
+let url: string
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'wem-github-'))
+
+beforeAll(async () => {
+  server = http.createServer((_req, res) => {
+    res.writeHead(200, { 'Content-Length': body.length })
+    res.end(body)
+  })
+  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+  url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/engine.tar.gz`
+})
+
+afterAll(() => {
+  server.close()
+  fs.rmSync(tmp, { recursive: true, force: true })
+})
+
+const asset = (extra: Partial<GithubAsset> = {}): GithubAsset => ({
+  name: 'engine.tar.gz',
+  browser_download_url: url,
+  size: body.length,
+  digest: `sha256:${sha256}`,
+  ...extra
+})
+
+describe('downloadVerified', () => {
+  it('keeps a download that matches the release', async () => {
+    const dest = path.join(tmp, 'good')
+    await downloadVerified(asset(), dest, () => {})
+    expect(fs.readFileSync(dest).equals(body)).toBe(true)
+  })
+
+  it('removes a download that does not match its checksum', async () => {
+    const dest = path.join(tmp, 'tampered')
+    await expect(downloadVerified(asset({ digest: `sha256:${'0'.repeat(64)}` }), dest, () => {})).rejects.toThrow(/checksum/)
+    expect(fs.existsSync(dest)).toBe(false)
+  })
+
+  it('removes a download that is not the size the release says', async () => {
+    const dest = path.join(tmp, 'short')
+    await expect(downloadVerified(asset({ size: body.length + 1 }), dest, () => {})).rejects.toThrow(/bytes/)
+    expect(fs.existsSync(dest)).toBe(false)
+  })
+
+  it('accepts an asset GitHub gave no digest for when the size is right', async () => {
+    const dest = path.join(tmp, 'nodigest')
+    await downloadVerified(asset({ digest: null }), dest, () => {})
+    expect(fs.existsSync(dest)).toBe(true)
+  })
+})

+ 11 - 0
src/main/utils/github.ts

@@ -48,6 +48,17 @@ export async function download(url: string, dest: string, total: number, onProgr
   await pipeline(body, fs.createWriteStream(dest))
 }
 
+/** download() and verifyAsset(): a file that doesn't match its release asset is removed and never reaches the caller */
+export async function downloadVerified(asset: GithubAsset, dest: string, onProgress: (fraction: number) => void): Promise<void> {
+  await download(asset.browser_download_url, dest, asset.size, onProgress)
+  try {
+    await verifyAsset(dest, asset)
+  } catch (err) {
+    fs.rmSync(dest, { force: true })
+    throw err
+  }
+}
+
 export async function verifyAsset(file: string, asset: GithubAsset): Promise<void> {
   const size = fs.statSync(file).size
   if (size !== asset.size) throw new Error(`${asset.name} is ${size} bytes, the release says ${asset.size}.`)

+ 0 - 1
src/main/utils/paths.ts

@@ -49,7 +49,6 @@ export function getDefaultWorkshopPath(): string {
     ]
     return candidates.find((p) => fs.existsSync(p)) ?? candidates[0]
   }
-  // macOS
   return path.join(
     home,
     'Library',

+ 7 - 14
src/main/utils/platform.ts

@@ -42,7 +42,7 @@ export function getWaylandDisplay(): string | undefined {
       { encoding: 'utf8', timeout: 3000 }
     ).trim()
     if (sessionType === 'wayland') return 'wayland-0'
-  } catch { /* loginctl not available */ }
+  } catch { }
 
   return undefined
 }
@@ -92,7 +92,6 @@ const COMPOSITOR_QUERIES: { marker: string; command: string; parse: (output: str
   { marker: 'NIRI_SOCKET', command: 'niri msg --json outputs', parse: parseNiriOutputs }
 ]
 
-/** Detect connected screen/output names for use with linux-wallpaperengine --screen-root. */
 export function getConnectedScreens(): string[] {
   if (process.platform !== 'linux') return []
 
@@ -105,10 +104,9 @@ export function getConnectedScreens(): string[] {
         const output = execSync(hostShell(`${command} 2>/dev/null`), { encoding: 'utf8', timeout: 5000 })
         const screens = parse(output)
         if (screens.length > 0) return screens
-      } catch { /* not available */ }
+      } catch { }
     }
 
-    // wlr-randr (wlroots compositors: hyprland, sway, etc.)
     try {
       const output = execSync(hostShell('wlr-randr 2>/dev/null'), { encoding: 'utf8', timeout: 5000 })
       const screens = output
@@ -117,12 +115,10 @@ export function getConnectedScreens(): string[] {
         .map(line => line.split(/\s+/)[0])
         .filter(Boolean)
       if (screens.length > 0) return screens
-    } catch { /* not available */ }
+    } catch { }
 
-    // KDE Plasma Wayland: kscreen-doctor
     try {
       const output = execSync(hostShell('kscreen-doctor --outputs 2>/dev/null'), { encoding: 'utf8', timeout: 5000 })
-      // Strip ANSI color/escape codes before parsing
       const clean = output.replace(/\x1b\[[0-9;]*m/g, '')
       const screens = clean
         .split('\n')
@@ -132,9 +128,8 @@ export function getConnectedScreens(): string[] {
         })
         .filter((s): s is string => s !== null)
       if (screens.length > 0) return screens
-    } catch { /* not available */ }
+    } catch { }
 
-    // GNOME Wayland: gnome-randr or mutter output names via gdbus
     try {
       const output = execSync(
         hostShell("gdbus call --session --dest org.gnome.Mutter.DisplayConfig --object-path /org/gnome/Mutter/DisplayConfig --method org.gnome.Mutter.DisplayConfig.GetCurrentState 2>/dev/null"),
@@ -142,10 +137,9 @@ export function getConnectedScreens(): string[] {
       )
       const screens = [...output.matchAll(/connector:\s*'([^']+)'/gi)].map(m => m[1])
       if (screens.length > 0) return screens
-    } catch { /* not available */ }
+    } catch { }
   }
 
-  // X11: use xrandr
   try {
     const output = execSync(hostShell('xrandr --query 2>/dev/null'), { encoding: 'utf8', timeout: 5000 })
     const screens = output
@@ -154,7 +148,7 @@ export function getConnectedScreens(): string[] {
       .map(line => line.split(/\s+/)[0])
       .filter(Boolean)
     if (screens.length > 0) return screens
-  } catch { /* xrandr not available */ }
+  } catch { }
 
   return []
 }
@@ -190,13 +184,12 @@ export function hasStatusNotifierHost(maxAgeMs = TRAY_HOST_CACHE_MS): boolean {
         value = owned
         break
       }
-    } catch { /* tool missing or no session bus */ }
+    } catch { }
   }
   trayHostCache = { value, at: Date.now() }
   return value
 }
 
-// Cache results so we only call which/where once per session
 const commandCache = new Map<string, boolean>()
 
 export function isCommandAvailable(cmd: string): boolean {

+ 90 - 0
src/main/utils/safeStore.test.ts

@@ -0,0 +1,90 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import * as fs from 'fs'
+import * as os from 'os'
+import * as path from 'path'
+
+let userData = ''
+
+vi.mock('electron', () => ({ app: { getPath: () => userData } }))
+vi.mock('electron-store', async () => {
+  const { default: Conf } = await import('conf')
+  return {
+    default: class extends Conf<Record<string, unknown>> {
+      constructor({ name = 'config', ...options }: { name?: string; defaults?: Record<string, unknown> } = {}) {
+        super({ ...options, configName: name, cwd: userData, projectName: 'we-manager-test' })
+      }
+    }
+  }
+})
+
+const { openStore, setAsideUnreadable, takeResetStores } = await import('./safeStore')
+
+beforeEach(() => {
+  userData = fs.mkdtempSync(path.join(os.tmpdir(), 'wem-store-'))
+  vi.spyOn(console, 'error').mockImplementation(() => {})
+})
+
+afterEach(() => {
+  vi.restoreAllMocks()
+  takeResetStores()
+  fs.rmSync(userData, { recursive: true, force: true })
+})
+
+describe('openStore', () => {
+  it('opens a healthy store untouched', () => {
+    fs.writeFileSync(path.join(userData, 'library.json'), JSON.stringify({ wallpapers: { 1: 'a' } }))
+    const store = openStore<{ wallpapers: Record<string, string> }>({ name: 'library', defaults: { wallpapers: {} } })
+    expect(store.get('wallpapers')).toEqual({ 1: 'a' })
+    expect(takeResetStores()).toEqual([])
+    expect(fs.readdirSync(userData)).toEqual(['library.json'])
+  })
+
+  it('starts with defaults and keeps the unreadable file next to it', () => {
+    const file = path.join(userData, 'playlists.json')
+    fs.writeFileSync(file, '{"playlists": [{"id": "a"')
+    const store = openStore<{ playlists: unknown[] }>({ name: 'playlists', defaults: { playlists: [] } })
+
+    expect(store.get('playlists')).toEqual([])
+    const kept = fs.readdirSync(userData).filter((name) => name.startsWith('playlists.json.corrupt-'))
+    expect(kept).toHaveLength(1)
+    expect(fs.readFileSync(path.join(userData, kept[0]), 'utf8')).toBe('{"playlists": [{"id": "a"')
+
+    store.set('playlists', [{ id: 'b' }])
+    expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toEqual({ playlists: [{ id: 'b' }] })
+    expect(takeResetStores()).toEqual([{ file, keptAs: path.join(userData, kept[0]) }])
+    expect(takeResetStores()).toEqual([])
+  })
+
+  it('treats an empty file the same way', () => {
+    fs.writeFileSync(path.join(userData, 'schedule.json'), '')
+    const store = openStore<{ rules: unknown[] }>({ name: 'schedule', defaults: { rules: [] } })
+    expect(store.get('rules')).toEqual([])
+    expect(takeResetStores()).toHaveLength(1)
+  })
+
+  it('uses config as the default name', () => {
+    fs.writeFileSync(path.join(userData, 'config.json'), 'nope')
+    openStore<{ a: number }>({ defaults: { a: 1 } })
+    expect(fs.readdirSync(userData).some((name) => name.startsWith('config.json.corrupt-'))).toBe(true)
+  })
+
+  it('does not hide other errors', () => {
+    fs.mkdirSync(path.join(userData, 'library.json'))
+    expect(() => openStore({ name: 'library' })).toThrow(/EISDIR/)
+    expect(takeResetStores()).toEqual([])
+  })
+})
+
+describe('setAsideUnreadable', () => {
+  it('never overwrites an earlier copy', () => {
+    const file = path.join(userData, 'x.json')
+    const now = new Date('2026-10-17T10:00:00Z')
+    fs.writeFileSync(file, 'one')
+    const first = setAsideUnreadable(file, now)
+    fs.writeFileSync(file, 'two')
+    const second = setAsideUnreadable(file, now)
+    expect(first).not.toBe(second)
+    expect(fs.readFileSync(first, 'utf8')).toBe('one')
+    expect(fs.readFileSync(second, 'utf8')).toBe('two')
+  })
+})

+ 36 - 0
src/main/utils/safeStore.ts

@@ -0,0 +1,36 @@
+import { app } from 'electron'
+import Store, { type Options } from 'electron-store'
+import * as fs from 'fs'
+import * as path from 'path'
+
+export interface ResetStore {
+  file: string
+  keptAs: string
+}
+
+const resetStores: ResetStore[] = []
+
+export function setAsideUnreadable(file: string, now = new Date()): string {
+  const stamp = now.toISOString().replace(/[:.]/g, '-')
+  let target = `${file}.corrupt-${stamp}`
+  for (let n = 2; fs.existsSync(target); n++) target = `${file}.corrupt-${stamp}-${n}`
+  fs.renameSync(file, target)
+  return target
+}
+
+export function openStore<T extends Record<string, any>>(options?: Options<T>): Store<T> {
+  try {
+    return new Store<T>(options)
+  } catch (err) {
+    if (!(err instanceof SyntaxError)) throw err
+    const file = path.join(app.getPath('userData'), `${options?.name ?? 'config'}.json`)
+    const keptAs = setAsideUnreadable(file)
+    console.error(`[Store] ${file} is not valid JSON, starting with defaults. The old file is kept as ${keptAs}`)
+    resetStores.push({ file, keptAs })
+    return new Store<T>(options)
+  }
+}
+
+export function takeResetStores(): ResetStore[] {
+  return resetStores.splice(0)
+}

+ 72 - 0
src/main/utils/urlPolicy.test.ts

@@ -0,0 +1,72 @@
+import { describe, expect, it } from 'vitest'
+import { isAppUrl, isSafeExternalUrl, isServablePreview } from './urlPolicy'
+
+describe('isSafeExternalUrl', () => {
+  it('lets web links, steam and mail through', () => {
+    for (const url of ['https://steamcommunity.com/id/x', 'http://example.org/a?b=c', 'steam://url/CommunityFilePage/1', 'mailto:a@b.c']) {
+      expect(isSafeExternalUrl(url)).toBe(true)
+    }
+  })
+
+  it('refuses what would start a program or read a file', () => {
+    for (const url of ['file:///etc/passwd', 'javascript:alert(1)', 'data:text/html,hi', 'smb://host/share', 'ssh://host', 'vscode://x', 'ftp://host', '', 'not a url', '//host/path']) {
+      expect(isSafeExternalUrl(url)).toBe(false)
+    }
+  })
+})
+
+describe('isAppUrl', () => {
+  const fileApp = 'file:///opt/we/out/renderer/index.html'
+
+  it('accepts the app page, with or without a query or hash', () => {
+    expect(isAppUrl(fileApp, fileApp)).toBe(true)
+    expect(isAppUrl(`${fileApp}#/library`, fileApp)).toBe(true)
+    expect(isAppUrl(`${fileApp}?x=1`, fileApp)).toBe(true)
+  })
+
+  it('refuses another file, another scheme and a dropped file', () => {
+    expect(isAppUrl('file:///etc/passwd', fileApp)).toBe(false)
+    expect(isAppUrl('file:///opt/we/out/renderer/other.html', fileApp)).toBe(false)
+    expect(isAppUrl('https://example.org/', fileApp)).toBe(false)
+    expect(isAppUrl('file:///home/u/Downloads/a%20b.png', fileApp)).toBe(false)
+    expect(isAppUrl('garbage', fileApp)).toBe(false)
+  })
+
+  it('follows the origin of the dev server', () => {
+    const dev = 'http://localhost:5173/'
+    expect(isAppUrl('http://localhost:5173/index.html', dev)).toBe(true)
+    expect(isAppUrl('http://localhost:5174/', dev)).toBe(false)
+    expect(isAppUrl('http://evil.example/', dev)).toBe(false)
+    expect(isAppUrl('file:///opt/we/out/renderer/index.html', dev)).toBe(false)
+  })
+})
+
+describe('isServablePreview', () => {
+  const roots = ['/mnt/steam/workshop/content/431960', '/home/u/.config/we-manager/thumbnails']
+
+  it('serves media inside a root', () => {
+    expect(isServablePreview('/mnt/steam/workshop/content/431960/123/preview.jpg', roots)).toBe(true)
+    expect(isServablePreview('/mnt/steam/workshop/content/431960/123/sub/preview.GIF', roots)).toBe(true)
+    expect(isServablePreview('/home/u/.config/we-manager/thumbnails/123.png', roots)).toBe(true)
+  })
+
+  it('refuses a path outside the roots, however it is spelled', () => {
+    expect(isServablePreview('/etc/passwd', roots)).toBe(false)
+    expect(isServablePreview('/home/u/.ssh/id_rsa.png', roots)).toBe(false)
+    expect(isServablePreview('/mnt/steam/workshop/content/431960/../../../../../etc/shadow.png', roots)).toBe(false)
+    expect(isServablePreview('/mnt/steam/workshop/content/4319601/x.png', roots)).toBe(false)
+    expect(isServablePreview('/mnt/steam/workshop/content/431960', roots)).toBe(false)
+  })
+
+  it('refuses what is not a picture or video, even inside a root', () => {
+    expect(isServablePreview('/mnt/steam/workshop/content/431960/123/project.json', roots)).toBe(false)
+    expect(isServablePreview('/mnt/steam/workshop/content/431960/123/noextension', roots)).toBe(false)
+    expect(isServablePreview('/mnt/steam/workshop/content/431960/123/page.html', roots)).toBe(false)
+  })
+
+  it('refuses relative paths and null bytes', () => {
+    expect(isServablePreview('preview.jpg', roots)).toBe(false)
+    expect(isServablePreview('/mnt/steam/workshop/content/431960/a\0.png', roots)).toBe(false)
+    expect(isServablePreview('/mnt/steam/workshop/content/431960/123/preview.jpg', [])).toBe(false)
+  })
+})

+ 41 - 0
src/main/utils/urlPolicy.ts

@@ -0,0 +1,41 @@
+import * as path from 'path'
+
+/** What the app hands to the desktop's opener: web links, Steam's own scheme and mail, nothing that runs a program */
+const EXTERNAL_PROTOCOLS = new Set(['http:', 'https:', 'steam:', 'mailto:'])
+
+export function isSafeExternalUrl(url: string): boolean {
+  try {
+    return EXTERNAL_PROTOCOLS.has(new URL(url).protocol)
+  } catch {
+    return false
+  }
+}
+
+/** The page the window is allowed to be on (a reload, the dev server's own paths), anything else is a navigation away */
+export function isAppUrl(url: string, appUrl: string): boolean {
+  try {
+    const target = new URL(url)
+    const app = new URL(appUrl)
+    if (target.protocol !== app.protocol) return false
+    return app.protocol === 'file:' ? target.pathname === app.pathname : target.origin === app.origin
+  } catch {
+    return false
+  }
+}
+
+const MEDIA_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.avif', '.apng', '.mp4', '.webm'])
+
+/**
+ * wallpaper:// serves previews: an image or video inside the library, backup and thumbnail folders. A project.json can
+ * name any path as its preview, and the renderer reads these as bytes
+ */
+export function isServablePreview(filePath: string, roots: readonly string[]): boolean {
+  if (!path.isAbsolute(filePath) || filePath.includes('\0')) return false
+  const resolved = path.resolve(filePath)
+  if (!MEDIA_EXTENSIONS.has(path.extname(resolved).toLowerCase())) return false
+
+  return roots.some((root) => {
+    const relative = path.relative(path.resolve(root), resolved)
+    return relative !== '' && relative.split(path.sep)[0] !== '..' && !path.isAbsolute(relative)
+  })
+}

+ 1 - 4
src/main/utils/video.ts

@@ -8,7 +8,6 @@ const execFileAsync = promisify(execFile)
 
 const VIDEO_EXTENSIONS = ['.mp4', '.webm', '.avi', '.mkv', '.mov', '.m4v']
 
-/** Locate a wallpaper's video file: the project.json `file` entry, or the first video in the folder. */
 export function findWallpaperVideoFile(localPath: string, projectFile?: string): string | undefined {
   if (projectFile) {
     const direct = path.join(localPath, projectFile)
@@ -18,7 +17,7 @@ export function findWallpaperVideoFile(localPath: string, projectFile?: string):
     const files = fs.readdirSync(localPath)
     const video = files.find((f) => VIDEO_EXTENSIONS.includes(path.extname(f).toLowerCase()))
     if (video) return path.join(localPath, video)
-  } catch { /* unreadable dir */ }
+  } catch { }
   return undefined
 }
 
@@ -35,7 +34,6 @@ function parseFrameRate(raw?: string): number | undefined {
 // reapply the same wallpapers repeatedly).
 const fpsCache = new Map<string, number | undefined>()
 
-/** Read a video's native frame rate via ffprobe. Returns undefined if ffprobe is missing or fails. */
 export async function getVideoFps(filePath: string): Promise<number | undefined> {
   if (fpsCache.has(filePath)) return fpsCache.get(filePath)
   if (!isCommandAvailable('ffprobe')) return undefined
@@ -61,7 +59,6 @@ export async function getVideoFps(filePath: string): Promise<number | undefined>
 
 const durationCache = new Map<string, number | undefined>()
 
-/** Read a video's length in seconds via ffprobe. Returns undefined if ffprobe is missing or fails. */
 export async function getVideoDurationSec(filePath: string): Promise<number | undefined> {
   if (durationCache.has(filePath)) return durationCache.get(filePath)
   if (!isCommandAvailable('ffprobe')) return undefined

+ 48 - 0
src/main/utils/wallpaperScripts.test.ts

@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest'
+import { finderWallpaperArgs, fileUri, plasmaWallpaperScript } from './wallpaperScripts'
+
+function configuredImage(script: string): string {
+  const calls: string[] = []
+  const d = {
+    writeConfig: (key: string, value: string) => {
+      if (key === 'Image') calls.push(value)
+    }
+  }
+  new Function('desktops', script)(() => [d])
+  return calls[0]
+}
+
+describe('fileUri', () => {
+  it('encodes what a plain file:// prefix would leave raw', () => {
+    expect(fileUri('/home/u/My Wallpapers/a#b?c.jpg')).toBe('file:///home/u/My%20Wallpapers/a%23b%3Fc.jpg')
+    expect(fileUri('/home/u/100%/x.png')).toBe('file:///home/u/100%25/x.png')
+  })
+})
+
+describe('plasmaWallpaperScript', () => {
+  it('hands a normal path to the script as its file URI', () => {
+    expect(configuredImage(plasmaWallpaperScript('/home/u/pics/a b.png'))).toBe('file:///home/u/pics/a%20b.png')
+  })
+
+  it('does not let an apostrophe end the string and run the rest', () => {
+    const hostile = `/tmp/x');globalThis.pwned = 1;//.png`
+    const script = plasmaWallpaperScript(hostile)
+    expect(configuredImage(script)).toBe(fileUri(hostile))
+    expect((globalThis as Record<string, unknown>).pwned).toBeUndefined()
+  })
+
+  it('survives quotes, backslashes, line breaks and line separators', () => {
+    for (const name of [`/tmp/a"b.png`, `/tmp/a\\b.png`, '/tmp/a\nb.png', '/tmp/a\u2028b.png', '/tmp/a\u2029b.png', `/tmp/'.png`]) {
+      expect(configuredImage(plasmaWallpaperScript(name))).toBe(fileUri(name))
+    }
+  })
+})
+
+describe('finderWallpaperArgs', () => {
+  it('passes the path as an argument, not inside the AppleScript', () => {
+    const path = '/Users/u/a" & (do shell script "id") & ".png'
+    const args = finderWallpaperArgs(path)
+    expect(args.at(-1)).toBe(path)
+    expect(args.filter((_, i) => args[i - 1] === '-e').join('\n')).not.toContain(path)
+  })
+})

+ 33 - 0
src/main/utils/wallpaperScripts.ts

@@ -0,0 +1,33 @@
+import { pathToFileURL } from 'url'
+
+export function fileUri(filePath: string): string {
+  return pathToFileURL(filePath).href
+}
+
+function jsString(value: string): string {
+  return JSON.stringify(value).replace(/[\u2028\u2029]/g, (c) => '\\u' + c.charCodeAt(0).toString(16))
+}
+
+export function plasmaWallpaperScript(imagePath: string): string {
+  return `
+    var allDesktops = desktops();
+    for (var i = 0; i < allDesktops.length; i++) {
+      var d = allDesktops[i];
+      d.wallpaperPlugin = 'org.kde.image';
+      d.currentConfigGroup = ['Wallpaper', 'org.kde.image', 'General'];
+      d.writeConfig('Image', ${jsString(fileUri(imagePath))});
+    }
+  `
+}
+
+export function finderWallpaperArgs(imagePath: string): string[] {
+  return [
+    '-e',
+    'on run argv',
+    '-e',
+    'tell application "Finder" to set desktop picture to POSIX file (item 1 of argv)',
+    '-e',
+    'end run',
+    imagePath
+  ]
+}

+ 0 - 1
src/renderer/src/App.tsx

@@ -79,7 +79,6 @@ export default function App() {
     })
   }, [queryClient])
 
-  // background sync results from main
   useEffect(() => {
     return window.electronAPI.on.votedIdsChanged((ids) => {
       queryClient.setQueryData(['steam-voted-ids'], ids)

+ 40 - 76
src/renderer/src/components/common/DetailSidebar.tsx

@@ -46,9 +46,11 @@ import clsx from 'clsx'
 import { openWorkshopPage, openProfilePage, isWorkshopId } from '../../utils/steam'
 import { WE_TYPES, WE_AGE_RATINGS, canonicalResolutionTag, resolutionsFromTags } from '../../constants/weFilters'
 import { formatFileSize } from '../../utils/format'
+import { isRangeKey } from '../../utils/dom'
 import { useDislikedIds, useVoteAction, useVotedIds } from '../../hooks/useVotes'
 import { useFavoriteAction, useFavoriteIds, useItemFavoriteStatus } from '../../hooks/useFavorites'
 import { useLweInstalled } from '../../hooks/queries'
+import { useKeyedCommits } from '../../hooks/useKeyedCommits'
 import ScreenSelect from './ScreenSelect'
 import { getPreviewSrc } from '../../utils/preview'
 import EngineFlagsSection from './sidebar/EngineFlagsSection'
@@ -209,19 +211,17 @@ function EffectRow({
 function PropertyRow({
   property,
   value,
-  busy,
   onCommit
 }: {
   property: LweProperty
   value: string
-  busy: boolean
   onCommit: (value: string) => void
 }) {
   const [draft, setDraft] = useState<number | null>(null)
   const label = property.text || property.name
 
   if (property.type === 'usershortcut') {
-    return <ShortcutRow property={property} value={value} busy={busy} onCommit={onCommit} />
+    return <ShortcutRow property={property} value={value} onCommit={onCommit} />
   }
 
   if (property.type === 'boolean') {
@@ -229,10 +229,9 @@ function PropertyRow({
     return (
       <button
         onClick={() => onCommit(on ? '0' : '1')}
-        disabled={busy}
         title={property.name}
         className={clsx(
-          'flex w-full items-center gap-2 rounded px-1.5 py-1 text-left text-xs transition-colors hover:bg-fg/5 disabled:opacity-40',
+          'flex w-full items-center gap-2 rounded px-1.5 py-1 text-left text-xs transition-colors hover:bg-fg/5',
           on ? 'text-gray-200' : 'text-gray-500'
         )}
       >
@@ -262,12 +261,11 @@ function PropertyRow({
           max={property.max ?? 100}
           step={property.step || 1}
           value={num}
-          disabled={busy}
           onChange={(e) => setDraft(Number(e.target.value))}
           onMouseUp={(e) => { onCommit(e.currentTarget.value); setDraft(null) }}
           onTouchEnd={(e) => { onCommit(e.currentTarget.value); setDraft(null) }}
-          onKeyUp={(e) => { onCommit(e.currentTarget.value); setDraft(null) }}
-          className="w-full accent-accent-500 disabled:opacity-50"
+          onKeyUp={(e) => { if (!isRangeKey(e.key)) return; onCommit(e.currentTarget.value); setDraft(null) }}
+          className="w-full accent-accent-500"
         />
       </div>
     )
@@ -281,9 +279,8 @@ function PropertyRow({
         </span>
         <select
           value={value}
-          disabled={busy}
           onChange={(e) => onCommit(e.target.value)}
-          className="rounded bg-fg/5 px-1.5 py-0.5 text-xs text-gray-300 outline-none disabled:opacity-50"
+          className="rounded bg-fg/5 px-1.5 py-0.5 text-xs text-gray-300 outline-none"
         >
           {property.options?.map((opt) => (
             <option key={opt.value} value={opt.value}>
@@ -303,13 +300,11 @@ function AudioObjectRow({
   objectName,
   properties,
   multiplier,
-  busy,
   onCommit
 }: {
   objectName: string
   properties: string[]
   multiplier: number
-  busy: boolean
   onCommit: (multiplier: number) => void
 }) {
   const [draft, setDraft] = useState<number | null>(null)
@@ -329,27 +324,23 @@ function AudioObjectRow({
         max={200}
         step={5}
         value={percent}
-        disabled={busy}
         onChange={(e) => setDraft(Number(e.target.value))}
         onMouseUp={(e) => { onCommit(Number(e.currentTarget.value) / 100); setDraft(null) }}
         onTouchEnd={(e) => { onCommit(Number(e.currentTarget.value) / 100); setDraft(null) }}
-        onKeyUp={(e) => { onCommit(Number(e.currentTarget.value) / 100); setDraft(null) }}
-        className="w-full accent-accent-500 disabled:opacity-50"
+        onKeyUp={(e) => { if (!isRangeKey(e.key)) return; onCommit(Number(e.currentTarget.value) / 100); setDraft(null) }}
+        className="w-full accent-accent-500"
       />
     </div>
   )
 }
 
-// one row per Sound object, e.g. alternate music tracks
 function SoundTrackRow({
   trackName,
   volume,
-  busy,
   onCommit
 }: {
   trackName: string
   volume: number
-  busy: boolean
   onCommit: (volume: number) => void
 }) {
   const [draft, setDraft] = useState<number | null>(null)
@@ -369,12 +360,11 @@ function SoundTrackRow({
         max={1}
         step={0.1}
         value={value}
-        disabled={busy}
         onChange={(e) => setDraft(Number(e.target.value))}
         onMouseUp={(e) => { onCommit(Number(e.currentTarget.value)); setDraft(null) }}
         onTouchEnd={(e) => { onCommit(Number(e.currentTarget.value)); setDraft(null) }}
-        onKeyUp={(e) => { onCommit(Number(e.currentTarget.value)); setDraft(null) }}
-        className="w-full accent-accent-500 disabled:opacity-50"
+        onKeyUp={(e) => { if (!isRangeKey(e.key)) return; onCommit(Number(e.currentTarget.value)); setDraft(null) }}
+        className="w-full accent-accent-500"
       />
     </div>
   )
@@ -442,11 +432,8 @@ export default function DetailSidebar({
   const [togglingEffectId, setTogglingEffectId] = useState<string | null>(null)
   const [togglingFog, setTogglingFog] = useState(false)
   const [propertiesOpen, setPropertiesOpen] = useState(false)
-  const [committingProperty, setCommittingProperty] = useState<string | null>(null)
   const [audioOpen, setAudioOpen] = useState(false)
-  const [committingAudioObjectId, setCommittingAudioObjectId] = useState<string | null>(null)
   const [soundTracksOpen, setSoundTracksOpen] = useState(false)
-  const [committingSoundObjectId, setCommittingSoundObjectId] = useState<string | null>(null)
 
   const { data: item } = useQuery({
     queryKey: ['workshop-detail', id],
@@ -477,7 +464,7 @@ export default function DetailSidebar({
   })
 
   const { data: libraryMeta } = useQuery({
-    queryKey: ['library-item', id],
+    queryKey: ['library', 'item', id],
     queryFn: () => window.electronAPI.library.getOne(id)
   })
   const localPath = libraryMeta?.localPath
@@ -498,7 +485,7 @@ export default function DetailSidebar({
   const isActive = activeScreens.length > 0
 
   const { data: objects = [], isLoading: objectsLoading } = useQuery({
-    queryKey: ['lwe-objects', localPath],
+    queryKey: ['lwe-objects', localPath, libraryMeta?.updatedAt],
     queryFn: () => window.electronAPI.lwe.listObjects(localPath!),
     enabled: !!localPath && lweInstalled,
     staleTime: Infinity,
@@ -506,7 +493,7 @@ export default function DetailSidebar({
   })
 
   const { data: effects = [], isLoading: effectsLoading } = useQuery({
-    queryKey: ['lwe-effects', localPath],
+    queryKey: ['lwe-effects', localPath, libraryMeta?.updatedAt],
     queryFn: () => window.electronAPI.lwe.listEffects(localPath!),
     enabled: !!localPath && lweInstalled,
     staleTime: Infinity,
@@ -518,7 +505,7 @@ export default function DetailSidebar({
   const fogDisabled = fogObjects.length > 0 && fogObjects.every((o) => disabledObjects.includes(o.id))
 
   const { data: allProperties = [], isLoading: propertiesLoading } = useQuery({
-    queryKey: ['lwe-properties', localPath],
+    queryKey: ['lwe-properties', localPath, libraryMeta?.updatedAt],
     queryFn: () => window.electronAPI.lwe.listProperties(localPath!),
     enabled: !!localPath && lweInstalled,
     staleTime: Infinity,
@@ -530,7 +517,7 @@ export default function DetailSidebar({
   const propertyOverrides = libraryMeta?.propertyOverrides ?? {}
 
   const { data: audioObjectProperties = [], isLoading: audioObjectsLoading } = useQuery({
-    queryKey: ['lwe-audio-objects', localPath],
+    queryKey: ['lwe-audio-objects', localPath, libraryMeta?.updatedAt],
     queryFn: () => window.electronAPI.lwe.listAudioObjects(localPath!),
     enabled: !!localPath && lweInstalled,
     staleTime: Infinity,
@@ -548,6 +535,16 @@ export default function DetailSidebar({
   const soundObjects = objects.filter((o) => o.type === 'sound')
   const soundVolume = libraryMeta?.soundVolume ?? {}
 
+  const propertyCommits = useKeyedCommits<string>(id, propertyOverrides, (next) =>
+    persistAndMaybeRelaunch({ propertyOverrides: next })
+  )
+  const audioCommits = useKeyedCommits<number>(id, audioSensitivity, (next) =>
+    persistAndMaybeRelaunch({ audioSensitivity: next })
+  )
+  const soundCommits = useKeyedCommits<number>(id, soundVolume, (next) =>
+    persistAndMaybeRelaunch({ soundVolume: next })
+  )
+
   const { data: videoDuration = null } = useQuery({
     queryKey: ['video-duration', localPath],
     queryFn: () => window.electronAPI.lwe.videoDuration(localPath!, libraryMeta?.file),
@@ -559,7 +556,7 @@ export default function DetailSidebar({
   // pushed live when playing, relaunched if the hotswap fails
   async function persistAndMaybeRelaunch(patch: Partial<WallpaperMeta>) {
     const updated = await window.electronAPI.library.update(id, patch)
-    queryClient.setQueryData(['library-item', id], updated)
+    queryClient.setQueryData(['library', 'item', id], updated)
     queryClient.invalidateQueries({ queryKey: ['library'] })
     if (isActive) {
       // customArgs and effect overrides can't be hotswapped
@@ -597,7 +594,7 @@ export default function DetailSidebar({
   // for settings that don't touch the running engine
   async function persistOnly(patch: Partial<WallpaperMeta>) {
     const updated = await window.electronAPI.library.update(id, patch)
-    queryClient.setQueryData(['library-item', id], updated)
+    queryClient.setQueryData(['library', 'item', id], updated)
     queryClient.invalidateQueries({ queryKey: ['library'] })
   }
 
@@ -681,36 +678,6 @@ export default function DetailSidebar({
     }
   }
 
-  async function commitProperty(name: string, value: string) {
-    if (committingProperty) return
-    setCommittingProperty(name)
-    try {
-      await persistAndMaybeRelaunch({ propertyOverrides: { ...propertyOverrides, [name]: value } })
-    } finally {
-      setCommittingProperty(null)
-    }
-  }
-
-  async function commitAudioSensitivity(objectId: string, multiplier: number) {
-    if (committingAudioObjectId) return
-    setCommittingAudioObjectId(objectId)
-    try {
-      await persistAndMaybeRelaunch({ audioSensitivity: { ...audioSensitivity, [objectId]: multiplier } })
-    } finally {
-      setCommittingAudioObjectId(null)
-    }
-  }
-
-  async function commitSoundVolume(objectId: string, volume: number) {
-    if (committingSoundObjectId) return
-    setCommittingSoundObjectId(objectId)
-    try {
-      await persistAndMaybeRelaunch({ soundVolume: { ...soundVolume, [objectId]: volume } })
-    } finally {
-      setCommittingSoundObjectId(null)
-    }
-  }
-
   const [volumeDraft, setVolumeDraft] = useState<number | null>(null)
   const [isCommittingVolume, setIsCommittingVolume] = useState(false)
   const volume = volumeDraft ?? libraryMeta?.volumeOverride ?? 15
@@ -1120,7 +1087,7 @@ export default function DetailSidebar({
               }}
               onMouseUp={(e) => commitZoom(Number(e.currentTarget.value))}
               onTouchEnd={(e) => commitZoom(Number(e.currentTarget.value))}
-              onKeyUp={(e) => commitZoom(Number(e.currentTarget.value))}
+              onKeyUp={(e) => isRangeKey(e.key) && commitZoom(Number(e.currentTarget.value))}
               className="w-full accent-accent-500 disabled:opacity-50"
             />
           </div>
@@ -1154,7 +1121,7 @@ export default function DetailSidebar({
                 }}
                 onMouseUp={(e) => commitOffset(Number(e.currentTarget.value) / 100, offsetY)}
                 onTouchEnd={(e) => commitOffset(Number(e.currentTarget.value) / 100, offsetY)}
-                onKeyUp={(e) => commitOffset(Number(e.currentTarget.value) / 100, offsetY)}
+                onKeyUp={(e) => isRangeKey(e.key) && commitOffset(Number(e.currentTarget.value) / 100, offsetY)}
                 className="w-full accent-accent-500 disabled:opacity-50"
               />
               <span className="w-8 shrink-0 text-right text-[10px] text-gray-400">
@@ -1177,7 +1144,7 @@ export default function DetailSidebar({
                 }}
                 onMouseUp={(e) => commitOffset(offsetX, Number(e.currentTarget.value) / 100)}
                 onTouchEnd={(e) => commitOffset(offsetX, Number(e.currentTarget.value) / 100)}
-                onKeyUp={(e) => commitOffset(offsetX, Number(e.currentTarget.value) / 100)}
+                onKeyUp={(e) => isRangeKey(e.key) && commitOffset(offsetX, Number(e.currentTarget.value) / 100)}
                 className="w-full accent-accent-500 disabled:opacity-50"
               />
               <span className="w-8 shrink-0 text-right text-[10px] text-gray-400">
@@ -1267,7 +1234,7 @@ export default function DetailSidebar({
               }}
               onMouseUp={(e) => commitSpeed(Number(e.currentTarget.value))}
               onTouchEnd={(e) => commitSpeed(Number(e.currentTarget.value))}
-              onKeyUp={(e) => commitSpeed(Number(e.currentTarget.value))}
+              onKeyUp={(e) => isRangeKey(e.key) && commitSpeed(Number(e.currentTarget.value))}
               title={t('detail.speedHint')}
               className="w-full accent-accent-500 disabled:opacity-50"
             />
@@ -1348,7 +1315,7 @@ export default function DetailSidebar({
               }}
               onMouseUp={(e) => commitVolume(Number(e.currentTarget.value))}
               onTouchEnd={(e) => commitVolume(Number(e.currentTarget.value))}
-              onKeyUp={(e) => commitVolume(Number(e.currentTarget.value))}
+              onKeyUp={(e) => isRangeKey(e.key) && commitVolume(Number(e.currentTarget.value))}
               className="w-full accent-accent-500 disabled:opacity-50"
             />
           </div>
@@ -1515,9 +1482,8 @@ export default function DetailSidebar({
                   <PropertyRow
                     key={prop.name}
                     property={prop}
-                    value={propertyOverrides[prop.name] ?? prop.value}
-                    busy={committingProperty === prop.name}
-                    onCommit={(value) => commitProperty(prop.name, value)}
+                    value={propertyCommits.values[prop.name] ?? prop.value}
+                    onCommit={(value) => propertyCommits.commit(prop.name, value)}
                   />
                 ))}
               </div>
@@ -1548,9 +1514,8 @@ export default function DetailSidebar({
                     key={obj.objectId}
                     objectName={obj.objectName}
                     properties={obj.properties}
-                    multiplier={audioSensitivity[obj.objectId] ?? 1}
-                    busy={committingAudioObjectId === obj.objectId}
-                    onCommit={(multiplier) => commitAudioSensitivity(obj.objectId, multiplier)}
+                    multiplier={audioCommits.values[obj.objectId] ?? 1}
+                    onCommit={(multiplier) => audioCommits.commit(obj.objectId, multiplier)}
                   />
                 ))}
               </div>
@@ -1580,9 +1545,8 @@ export default function DetailSidebar({
                   <SoundTrackRow
                     key={obj.id}
                     trackName={obj.name}
-                    volume={soundVolume[obj.id] ?? 0}
-                    busy={committingSoundObjectId === obj.id}
-                    onCommit={(volume) => commitSoundVolume(obj.id, volume)}
+                    volume={soundCommits.values[obj.id] ?? 0}
+                    onCommit={(level) => soundCommits.commit(obj.id, level)}
                   />
                 ))}
               </div>
@@ -1608,7 +1572,7 @@ export default function DetailSidebar({
               wallpaper={libraryMeta}
               canGenerate={lweInstalled && !!localPath && libraryMeta.type !== 'application'}
               onUpdated={(updated) => {
-                queryClient.setQueryData(['library-item', id], updated)
+                queryClient.setQueryData(['library', 'item', id], updated)
                 queryClient.invalidateQueries({ queryKey: ['library'] })
               }}
             />

+ 0 - 1
src/renderer/src/components/common/FilterPanel.tsx

@@ -58,7 +58,6 @@ export function CheckItem({
   )
 }
 
-// children of a CheckItem
 export function CheckGroup({ children }: { children: ReactNode }) {
   return <div className="ml-[6px] pl-2.5">{children}</div>
 }

+ 1 - 5
src/renderer/src/components/common/ShortcutRow.tsx

@@ -54,12 +54,10 @@ function describe(shortcut: Shortcut, apps: DesktopApplication[]): string {
 export function ShortcutRow({
   property,
   value,
-  busy,
   onCommit
 }: {
   property: LweProperty
   value: string
-  busy: boolean
   onCommit: (value: string) => void
 }) {
   const current = parseShortcut(value)
@@ -103,7 +101,6 @@ export function ShortcutRow({
         </span>
         <button
           onClick={() => setDraft(draft ? null : (current ?? { type: 'application', file: '', arguments: '' }))}
-          disabled={busy}
           title={current ? t('shortcut.change') : t('shortcut.assign')}
           className="rounded p-0.5 text-gray-400 hover:bg-fg/10 hover:text-gray-200 disabled:opacity-40"
         >
@@ -112,7 +109,6 @@ export function ShortcutRow({
         {current && (
           <button
             onClick={() => onCommit('')}
-            disabled={busy}
             title={t('shortcut.remove')}
             className="rounded p-0.5 text-gray-400 hover:bg-fg/10 hover:text-gray-200 disabled:opacity-40"
           >
@@ -211,7 +207,7 @@ export function ShortcutRow({
             </button>
             <button
               onClick={save}
-              disabled={!draft.file.trim() || busy}
+              disabled={!draft.file.trim()}
               className="rounded bg-accent-500/80 px-2 py-0.5 text-white hover:bg-accent-500 disabled:opacity-40"
             >
               {t('common.save')}

+ 6 - 7
src/renderer/src/components/library/LibraryView.tsx

@@ -458,13 +458,10 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
         })
       : null
   const [lingeringProgress, setLingeringProgress] = useState<string | null>(null)
+  if (liveProgress && liveProgress !== lingeringProgress) setLingeringProgress(liveProgress)
 
   useEffect(() => {
-    if (liveProgress) {
-      setLingeringProgress(liveProgress)
-      return
-    }
-    if (backupTaskRunning) return
+    if (liveProgress || backupTaskRunning) return
     const timer = setTimeout(() => setLingeringProgress(null), 1500)
     return () => clearTimeout(timer)
   }, [liveProgress, backupTaskRunning])
@@ -605,9 +602,11 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
     setFolderMenu({ folder, x: e.clientX, y: e.clientY })
   }
 
-  useEffect(() => {
+  const [selectionFolder, setSelectionFolder] = useState(activeFolder)
+  if (selectionFolder !== activeFolder) {
+    setSelectionFolder(activeFolder)
     clearSelection()
-  }, [activeFolder, clearSelection])
+  }
 
   useEffect(() => {
     function onKeyDown(e: KeyboardEvent) {

+ 6 - 5
src/renderer/src/components/library/WallpaperCard.tsx

@@ -66,11 +66,8 @@ export default function WallpaperCard({
   const [downloadPercentage, setDownloadPercentage] = useState<number | null>(null)
 
   useEffect(() => {
-    if (!wallpaper.downloading) {
-      setDownloadPercentage(null)
-      return
-    }
-    return window.electronAPI.on.downloadProgress((progress) => {
+    if (!wallpaper.downloading) return
+    const off = window.electronAPI.on.downloadProgress((progress) => {
       if (progress.itemId !== wallpaper.id) return
       if (progress.status === 'downloading') {
         setDownloadPercentage(progress.percentage)
@@ -80,6 +77,10 @@ export default function WallpaperCard({
         queryClient.invalidateQueries({ queryKey: ['library'] })
       }
     })
+    return () => {
+      off()
+      setDownloadPercentage(null)
+    }
   }, [wallpaper.downloading, wallpaper.id, queryClient])
 
   function refreshLibrary() {

+ 3 - 2
src/renderer/src/components/settings/AppearanceSettings.tsx

@@ -15,6 +15,7 @@ import { applyAppearance } from '../../utils/appearance'
 import { t, translatedOr } from '../../i18n'
 import type { MessageKey } from '@shared/i18n'
 import LanguageSelect from './LanguageSelect'
+import { isRangeKey } from '../../utils/dom'
 
 const THEMES: { value: ThemeMode; label: MessageKey; icon: typeof Moon }[] = [
   { value: 'dark', label: 'appearance.dark', icon: Moon },
@@ -128,7 +129,7 @@ export default function AppearanceSettings() {
             value={draft.accentHue}
             onChange={(e) => preview({ accentHue: Number(e.target.value), accentChroma: draft.accentChroma || 1 })}
             onPointerUp={() => save({})}
-            onKeyUp={() => save({})}
+            onKeyUp={(e) => isRangeKey(e.key) && save({})}
             className="hue-slider h-2 w-full cursor-pointer appearance-none rounded-full"
             aria-label={t('appearance.accentHue')}
           />
@@ -161,7 +162,7 @@ export default function AppearanceSettings() {
           value={draft.windowOpacity}
           onChange={(e) => preview({ windowOpacity: Number(e.target.value) })}
           onPointerUp={() => save({})}
-          onKeyUp={() => save({})}
+          onKeyUp={(e) => isRangeKey(e.key) && save({})}
           className="mt-2 w-full accent-accent-500"
           aria-label={t('appearance.opacity')}
         />

+ 0 - 1
src/renderer/src/components/settings/SettingsView.tsx

@@ -118,7 +118,6 @@ export default function SettingsView() {
     window.electronAPI.lwe.listScreens().then(setScreens)
   }, [])
 
-  // refresh the status once the install finished
   useEffect(() => {
     if (lweProgress?.stage === 'done' || lweProgress?.stage === 'error') {
       window.electronAPI.lwe.status().then(setLweStatus)

+ 1 - 1
src/renderer/src/components/workshop/WorkshopBrowser.tsx

@@ -101,7 +101,7 @@ const DEFAULT_STATE: WorkshopFilterState = {
 
 function loadFilters(stored: unknown): WorkshopFilterState {
   const parsed = stored as Partial<WorkshopFilterState>
-  if (parsed._v !== STORAGE_VERSION) return DEFAULT_STATE
+  if (parsed['_v'] !== STORAGE_VERSION) return DEFAULT_STATE
   const state = { ...DEFAULT_STATE, ...parsed }
   if ('resolutions' in parsed) state.resolutions = migrateResolutionSelection(parsed.resolutions)
   return state

+ 0 - 6
src/renderer/src/hooks/useContextMenuPosition.ts

@@ -5,10 +5,6 @@ export interface Point {
   y: number
 }
 
-// Right-click menus anchor at the cursor, which is often close to a window
-// edge - without clamping, the menu overflows the window and its text gets
-// cut off instead of staying fully visible. Measures the menu after it
-// mounts and nudges it back inside the viewport if needed.
 export function useClampedPosition(
   ref: RefObject<HTMLElement | null>,
   point: Point | null | undefined,
@@ -38,8 +34,6 @@ export function useClampedPosition(
   return point
 }
 
-// For a submenu that normally opens to the right of its parent (left-full):
-// flips it to open to the left instead when it would run off the right edge.
 export function useFlipSide(ref: RefObject<HTMLElement | null>, active: boolean, padding = 8): 'left' | 'right' {
   const [side, setSide] = useState<'left' | 'right'>('right')
 

+ 0 - 1
src/renderer/src/hooks/useFavorites.ts

@@ -70,7 +70,6 @@ export function useFavoriteAction(onError?: (message: string) => void) {
   return { setFavorite, isPending: pending }
 }
 
-// whole selection, one toast
 export function useBatchFavorite(): (ids: string[], add: boolean) => Promise<void> {
   const { showToast } = useToast()
   const recordFavorites = useRecordFavorites()

+ 60 - 0
src/renderer/src/hooks/useKeyedCommits.ts

@@ -0,0 +1,60 @@
+import { useEffect, useRef, useState } from 'react'
+import { createKeyedCommitter, type KeyedCommitter } from '../utils/keyedCommitter'
+
+interface Channel<V> {
+  latest: { saved: Record<string, V>; save: (next: Record<string, V>) => Promise<void> }
+  sent: Record<string, V> | null
+  committer: KeyedCommitter<V>
+}
+
+export function useKeyedCommits<V>(
+  scope: string,
+  saved: Record<string, V>,
+  save: (next: Record<string, V>) => Promise<void>
+): { values: Record<string, V>; commit: (key: string, value: V) => void } {
+  const [inFlight, setInFlight] = useState<{ scope: string; values: Record<string, V> }>({ scope, values: {} })
+  const props = useRef({ saved, save })
+  const channels = useRef(new Map<string, Channel<V>>())
+
+  useEffect(() => {
+    props.current = { saved, save }
+    const channel = channels.current.get(scope)
+    if (channel) channel.latest = props.current
+  })
+
+  function openChannel(): Channel<V> {
+    const channel: Channel<V> = {
+      latest: props.current,
+      sent: null,
+      committer: createKeyedCommitter<V>(
+        async (changes) => {
+          const next = { ...(channel.sent ?? channel.latest.saved), ...changes }
+          channel.sent = next
+          await channel.latest.save(next)
+        },
+        (keys, idle) => {
+          if (idle) channel.sent = null
+          setInFlight((current) => {
+            if (current.scope !== scope) return current
+            const rest = { ...current.values }
+            for (const key of keys) delete rest[key]
+            return { scope, values: rest }
+          })
+        }
+      )
+    }
+    return channel
+  }
+
+  function commit(key: string, value: V): void {
+    let channel = channels.current.get(scope)
+    if (!channel) {
+      channel = openChannel()
+      channels.current.set(scope, channel)
+    }
+    setInFlight((current) => ({ scope, values: { ...(current.scope === scope ? current.values : {}), [key]: value } }))
+    channel.committer.commit(key, value)
+  }
+
+  return { values: inFlight.scope === scope ? { ...saved, ...inFlight.values } : saved, commit }
+}

+ 0 - 1
src/renderer/src/hooks/usePreviewSize.ts

@@ -34,7 +34,6 @@ export function usePreviewSize(): [PreviewSize, (size: PreviewSize) => void] {
     try {
       localStorage.setItem(STORAGE_KEY, size)
     } catch {
-      // ignore write failures (e.g. storage disabled)
     }
   }, [size])
 

+ 0 - 1
src/renderer/src/hooks/useSelectableGrid.ts

@@ -189,7 +189,6 @@ export function useSelectableGrid({ ids, dataAttr, onOpenDetail }: UseSelectable
     clearSelection,
     selectForContextMenu,
     handleCardSelect,
-    // spread onto the scrolling grid container
     containerProps: {
       ref: gridRef,
       onMouseDown: handleMarqueeStart,

+ 3 - 1
src/renderer/src/hooks/useSubscriptionQueue.ts

@@ -1,6 +1,8 @@
 import { useCallback, useRef, useState } from 'react'
 import type { DownloadProgressEvent } from '@shared/types'
 
+function noop(): void {}
+
 export type SubscribeState =
   | 'queued'
   | 'subscribing'
@@ -52,7 +54,7 @@ export function useSubscriptionQueue(onSettled?: () => void) {
   const waitForSettled = useCallback((id: string) => {
     return new Promise<'completed' | 'error'>((resolve) => {
       let settled = false
-      let off: () => void = () => {}
+      let off: () => void = noop
       const finish = (status: 'completed' | 'error') => {
         if (settled) return
         settled = true

+ 0 - 1
src/renderer/src/hooks/useVotes.ts

@@ -67,7 +67,6 @@ export function useVoteAction(onError?: (message: string) => void) {
   return { vote, isLiking: pending === 'like', isDisliking: pending === 'dislike' }
 }
 
-// whole selection, one toast
 
 export function useBatchVote(): (ids: string[], up: boolean) => Promise<void> {
   const { showToast } = useToast()

+ 0 - 2
src/renderer/src/utils/appearance.ts

@@ -24,7 +24,6 @@ export function applyAppearance(appearance: Appearance, translucent: boolean): v
   try {
     localStorage.setItem(CACHE_KEY, JSON.stringify({ appearance, translucent }))
   } catch {
-    // storage unavailable
   }
 }
 
@@ -34,7 +33,6 @@ export function applyCachedAppearance(): void {
     const cached = JSON.parse(localStorage.getItem(CACHE_KEY) ?? 'null')
     if (cached) applyAppearance(normalizeAppearance(cached.appearance), cached.translucent === true)
   } catch {
-    // nothing cached
   }
 }
 

+ 16 - 0
src/renderer/src/utils/dom.test.ts

@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest'
+import { isRangeKey } from './dom'
+
+describe('isRangeKey', () => {
+  it('knows the keys that move a slider', () => {
+    for (const key of ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown']) {
+      expect(isRangeKey(key)).toBe(true)
+    }
+  })
+
+  it('ignores the keys that only move focus or modify', () => {
+    for (const key of ['Tab', 'Shift', 'Control', 'Alt', 'Meta', 'Escape', 'Enter', ' ', 'a']) {
+      expect(isRangeKey(key)).toBe(false)
+    }
+  })
+})

+ 6 - 0
src/renderer/src/utils/dom.ts

@@ -3,3 +3,9 @@ export function isEditingText(): boolean {
   const active = document.activeElement
   return !!active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA')
 }
+
+const RANGE_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown'])
+
+export function isRangeKey(key: string): boolean {
+  return RANGE_KEYS.has(key)
+}

+ 115 - 0
src/renderer/src/utils/keyedCommitter.test.ts

@@ -0,0 +1,115 @@
+import { describe, expect, it, vi } from 'vitest'
+import { createKeyedCommitter } from './keyedCommitter'
+
+function gate(): { wait: Promise<void>; open: () => void } {
+  let open!: () => void
+  const wait = new Promise<void>((resolve) => (open = resolve))
+  return { wait, open }
+}
+
+describe('createKeyedCommitter', () => {
+  it('saves a single change at once', async () => {
+    const save = vi.fn<(changes: Record<string, string>) => Promise<void>>(async () => {})
+    const settled = vi.fn<(keys: string[], idle: boolean) => void>()
+    createKeyedCommitter<string>(save, settled).commit('a', '1')
+    await vi.waitFor(() => expect(settled).toHaveBeenCalled())
+    expect(save).toHaveBeenCalledWith({ a: '1' })
+    expect(settled).toHaveBeenCalledWith(['a'], true)
+  })
+
+  it('does not drop a change made to another key while a save runs', async () => {
+    const first = gate()
+    const calls: Record<string, string>[] = []
+    const settled = vi.fn<(keys: string[], idle: boolean) => void>()
+    const committer = createKeyedCommitter<string>(async (changes) => {
+      calls.push(changes)
+      if (calls.length === 1) await first.wait
+    }, settled)
+
+    committer.commit('a', '1')
+    await vi.waitFor(() => expect(calls).toHaveLength(1))
+    committer.commit('b', '2')
+    expect(committer.hasPending('b')).toBe(true)
+    expect(calls).toHaveLength(1)
+
+    first.open()
+    await vi.waitFor(() => expect(settled).toHaveBeenCalledTimes(2))
+    expect(calls).toEqual([{ a: '1' }, { b: '2' }])
+    expect(settled).toHaveBeenNthCalledWith(1, ['a'], false)
+    expect(settled).toHaveBeenNthCalledWith(2, ['b'], true)
+  })
+
+  it('sends only the newest value of a key changed several times meanwhile', async () => {
+    const first = gate()
+    const calls: Record<string, number>[] = []
+    const settled = vi.fn<(keys: string[], idle: boolean) => void>()
+    const committer = createKeyedCommitter<number>(async (changes) => {
+      calls.push(changes)
+      if (calls.length === 1) await first.wait
+    }, settled)
+
+    committer.commit('slider', 10)
+    await vi.waitFor(() => expect(calls).toHaveLength(1))
+    committer.commit('slider', 20)
+    committer.commit('slider', 30)
+    committer.commit('other', 5)
+    first.open()
+    await vi.waitFor(() => expect(settled).toHaveBeenCalledTimes(2))
+    expect(calls).toEqual([{ slider: 10 }, { slider: 30, other: 5 }])
+  })
+
+  it('reports a key as settled only when its newest value has been saved', async () => {
+    const first = gate()
+    const calls: Record<string, number>[] = []
+    const settled = vi.fn<(keys: string[], idle: boolean) => void>()
+    const committer = createKeyedCommitter<number>(async (changes) => {
+      calls.push(changes)
+      if (calls.length === 1) await first.wait
+    }, settled)
+
+    committer.commit('slider', 70)
+    await vi.waitFor(() => expect(calls).toHaveLength(1))
+    committer.commit('slider', 30)
+    first.open()
+    await vi.waitFor(() => expect(settled).toHaveBeenCalledTimes(2))
+
+    expect(settled).toHaveBeenNthCalledWith(1, [], false)
+    expect(settled).toHaveBeenNthCalledWith(2, ['slider'], true)
+  })
+
+  it('never runs two saves at once', async () => {
+    let active = 0
+    let most = 0
+    const settled = vi.fn<(keys: string[], idle: boolean) => void>()
+    const committer = createKeyedCommitter<number>(async () => {
+      active++
+      most = Math.max(most, active)
+      await new Promise((resolve) => setTimeout(resolve, 5))
+      active--
+    }, settled)
+
+    for (let i = 0; i < 6; i++) {
+      committer.commit(`k${i}`, i)
+      await new Promise((resolve) => setTimeout(resolve, 1))
+    }
+    await vi.waitFor(() => expect(settled).toHaveBeenLastCalledWith(expect.anything(), true))
+    expect(most).toBe(1)
+  })
+
+  it('keeps going after a save fails', async () => {
+    const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+    const calls: string[] = []
+    const settled = vi.fn<(keys: string[], idle: boolean) => void>()
+    const committer = createKeyedCommitter<string>(async (changes) => {
+      calls.push(Object.keys(changes).join())
+      if (calls.length === 1) throw new Error('disk full')
+    }, settled)
+
+    committer.commit('a', '1')
+    committer.commit('b', '2')
+    await vi.waitFor(() => expect(settled).toHaveBeenLastCalledWith(expect.anything(), true))
+    expect(calls).toEqual(['a', 'b'])
+    expect(error).toHaveBeenCalled()
+    error.mockRestore()
+  })
+})

+ 38 - 0
src/renderer/src/utils/keyedCommitter.ts

@@ -0,0 +1,38 @@
+export interface KeyedCommitter<V> {
+  commit: (key: string, value: V) => void
+  hasPending: (key: string) => boolean
+}
+
+export function createKeyedCommitter<V>(
+  save: (changes: Record<string, V>) => Promise<void>,
+  onSettled: (keys: string[], idle: boolean) => void
+): KeyedCommitter<V> {
+  const waiting = new Map<string, V>()
+  let running = false
+
+  async function drain(): Promise<void> {
+    running = true
+    try {
+      while (waiting.size > 0) {
+        const changes = Object.fromEntries(waiting) as Record<string, V>
+        waiting.clear()
+        try {
+          await save(changes)
+        } catch (err) {
+          console.error('Saving a change failed:', err)
+        }
+        onSettled(Object.keys(changes).filter((key) => !waiting.has(key)), waiting.size === 0)
+      }
+    } finally {
+      running = false
+    }
+  }
+
+  return {
+    commit(key, value) {
+      waiting.set(key, value)
+      if (!running) void drain()
+    },
+    hasPending: (key) => waiting.has(key)
+  }
+}

+ 38 - 0
src/shared/csp.test.ts

@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest'
+import { RENDERER_CSP } from './csp'
+
+function directives(policy: string): Map<string, string[]> {
+  return new Map(
+    policy.split(';').map((part) => {
+      const [name, ...sources] = part.trim().split(/\s+/)
+      return [name, sources]
+    })
+  )
+}
+
+describe('RENDERER_CSP', () => {
+  const policy = directives(RENDERER_CSP)
+
+  it('runs only the bundled scripts', () => {
+    expect(policy.get('script-src')).toEqual(["'self'"])
+    expect(RENDERER_CSP).not.toMatch(/unsafe-eval|unsafe-hashes|\*(?!\.)/)
+  })
+
+  it('blocks plugins, frames and form posts', () => {
+    expect(policy.get('object-src')).toEqual(["'none'"])
+    expect(policy.get('frame-src')).toEqual(["'none'"])
+    expect(policy.get('form-action')).toEqual(["'none'"])
+    expect(policy.get('base-uri')).toEqual(["'none'"])
+  })
+
+  it('lets previews load from the app scheme and from Steam', () => {
+    expect(policy.get('img-src')).toEqual(expect.arrayContaining(['wallpaper:', 'https:', 'data:']))
+    expect(policy.get('media-src')).toContain('wallpaper:')
+    expect(policy.get('connect-src')).toContain('wallpaper:')
+  })
+
+  it('has no repeated directive', () => {
+    const names = RENDERER_CSP.split(';').map((part) => part.trim().split(/\s+/)[0])
+    expect(new Set(names).size).toBe(names.length)
+  })
+})

+ 13 - 0
src/shared/csp.ts

@@ -0,0 +1,13 @@
+export const RENDERER_CSP = [
+  "default-src 'self'",
+  "script-src 'self'",
+  "style-src 'self' 'unsafe-inline'",
+  "img-src 'self' data: blob: wallpaper: https:",
+  "media-src 'self' blob: wallpaper:",
+  "font-src 'self' data:",
+  "connect-src 'self' wallpaper: https:",
+  "object-src 'none'",
+  "frame-src 'none'",
+  "base-uri 'none'",
+  "form-action 'none'"
+].join('; ')

+ 2 - 0
src/shared/i18n/locales/de.ts

@@ -223,6 +223,8 @@ export const de: Messages = {
   'dialog.pickShortcutFolder': 'Zu öffnenden Ordner wählen',
   'dialog.pickThumbnail': 'Vorschaubild wählen',
   'dialog.pickWorkshopFolder': 'Wallpaper Engine Workshop-Ordner auswählen',
+  'dialog.storeReset': '{name} konnte nicht gelesen werden, deshalb startet die App dafür mit den Standardwerten. Die beschädigte Datei wurde als {keptAs} aufbewahrt.',
+  'dialog.storeResetTitle': 'Eine Einstellungsdatei wurde zurückgesetzt',
 
   'display.description': 'Mit "Jeder Bildschirm für sich" bekommt jeder Bildschirm einen eigenen Hintergrund und eine eigene Playlist, und "Abspielen" fragt nach dem Bildschirm. Ein Wechsel stoppt alles, was gerade läuft.',
   'display.detected': 'Erkannt: {screens}',

+ 2 - 0
src/shared/i18n/locales/en.ts

@@ -221,6 +221,8 @@ export const en = {
   'dialog.pickShortcutFolder': 'Choose a folder to open',
   'dialog.pickThumbnail': 'Choose a thumbnail',
   'dialog.pickWorkshopFolder': 'Select Wallpaper Engine Workshop folder',
+  'dialog.storeReset': '{name} could not be read, so the app started with defaults for it. The damaged file was kept as {keptAs}.',
+  'dialog.storeResetTitle': 'A settings file was reset',
 
   'display.description': 'With each screen on its own, every screen gets its own wallpaper and playlist, and Play asks which screen to use. Switching stops whatever is playing now.',
   'display.detected': 'Detected: {screens}',

+ 2 - 0
src/shared/i18n/locales/es.ts

@@ -223,6 +223,8 @@ export const es: Messages = {
   'dialog.pickShortcutFolder': 'Elige una carpeta para abrir',
   'dialog.pickThumbnail': 'Elige una miniatura',
   'dialog.pickWorkshopFolder': 'Selecciona la carpeta del Workshop de Wallpaper Engine',
+  'dialog.storeReset': 'No se pudo leer {name}, así que la aplicación arrancó con los valores predeterminados para él. El archivo dañado se conservó como {keptAs}.',
+  'dialog.storeResetTitle': 'Se restableció un archivo de ajustes',
 
   'display.description': 'Con "Cada pantalla por separado", cada pantalla tiene su propio fondo y lista de reproducción, y Reproducir pregunta qué pantalla usar. Cambiar detiene lo que se esté reproduciendo.',
   'display.detected': 'Detectadas: {screens}',

+ 2 - 0
src/shared/i18n/locales/fr.ts

@@ -223,6 +223,8 @@ export const fr: Messages = {
   'dialog.pickShortcutFolder': 'Choisir un dossier à ouvrir',
   'dialog.pickThumbnail': 'Choisir une miniature',
   'dialog.pickWorkshopFolder': 'Sélectionner le dossier Workshop de Wallpaper Engine',
+  'dialog.storeReset': '{name} n\'a pas pu être lu, l\'application a donc démarré avec les valeurs par défaut pour ce fichier. Le fichier endommagé a été conservé sous {keptAs}.',
+  'dialog.storeResetTitle': 'Un fichier de réglages a été réinitialisé',
 
   'display.description': 'Avec "Chaque écran séparément", chaque écran a son propre fond d\'écran et sa propre playlist, et Lire demande quel écran utiliser. Changer arrête ce qui est en cours de lecture.',
   'display.detected': 'Détectés : {screens}',

+ 2 - 0
src/shared/i18n/locales/it.ts

@@ -223,6 +223,8 @@ export const it: Messages = {
   'dialog.pickShortcutFolder': 'Scegli una cartella da aprire',
   'dialog.pickThumbnail': 'Scegli una miniatura',
   'dialog.pickWorkshopFolder': 'Seleziona la cartella Workshop di Wallpaper Engine',
+  'dialog.storeReset': 'Non è stato possibile leggere {name}, quindi l\'app è partita con i valori predefiniti per questo file. Il file danneggiato è stato conservato come {keptAs}.',
+  'dialog.storeResetTitle': 'Un file delle impostazioni è stato reimpostato',
 
   'display.description': 'Con "Ogni schermo per conto suo", ogni schermo ha il proprio sfondo e la propria playlist, e Riproduci chiede quale schermo usare. Cambiare ferma ciò che è in riproduzione.',
   'display.detected': 'Rilevati: {screens}',

+ 2 - 0
src/shared/i18n/locales/ja.ts

@@ -209,6 +209,8 @@ export const ja: Messages = {
   'dialog.pickShortcutFolder': '開くフォルダーを選択',
   'dialog.pickThumbnail': 'サムネイルを選択',
   'dialog.pickWorkshopFolder': 'Wallpaper Engine のワークショップフォルダーを選択',
+  'dialog.storeReset': '{name} を読み込めなかったため、このファイルは初期値で起動しました。破損したファイルは {keptAs} として保存されています。',
+  'dialog.storeResetTitle': '設定ファイルを初期化しました',
 
   'display.description': '「画面ごとに個別」では、画面ごとに別の壁紙とプレイリストを使い、再生時にどの画面を使うか尋ねます。切り替えると現在再生中のものは停止します。',
   'display.detected': '検出: {screens}',

+ 2 - 0
src/shared/i18n/locales/ko.ts

@@ -209,6 +209,8 @@ export const ko: Messages = {
   'dialog.pickShortcutFolder': '열 폴더 선택',
   'dialog.pickThumbnail': '썸네일 선택',
   'dialog.pickWorkshopFolder': 'Wallpaper Engine 창작마당 폴더 선택',
+  'dialog.storeReset': '{name} 파일을 읽을 수 없어 이 파일은 기본값으로 시작했습니다. 손상된 파일은 {keptAs} 이름으로 보관되었습니다.',
+  'dialog.storeResetTitle': '설정 파일이 초기화되었습니다',
 
   'display.description': '"화면마다 따로"에서는 화면마다 배경화면과 재생 목록을 따로 쓰고, 재생할 때 어느 화면을 쓸지 묻습니다. 전환하면 지금 재생 중인 것이 멈춥니다.',
   'display.detected': '감지됨: {screens}',

+ 2 - 0
src/shared/i18n/locales/pl.ts

@@ -251,6 +251,8 @@ export const pl: Messages = {
   'dialog.pickShortcutFolder': 'Wybierz folder do otwarcia',
   'dialog.pickThumbnail': 'Wybierz miniaturę',
   'dialog.pickWorkshopFolder': 'Wybierz folder Warsztatu Wallpaper Engine',
+  'dialog.storeReset': 'Nie udało się odczytać pliku {name}, więc aplikacja uruchomiła się z wartościami domyślnymi dla niego. Uszkodzony plik zachowano jako {keptAs}.',
+  'dialog.storeResetTitle': 'Plik ustawień został zresetowany',
 
   'display.description': 'Przy "Każdy ekran osobno" każdy ekran ma własną tapetę i playlistę, a Odtwórz pyta, którego ekranu użyć. Przełączenie zatrzymuje wszystko, co jest teraz odtwarzane.',
   'display.detected': 'Wykryto: {screens}',

+ 2 - 0
src/shared/i18n/locales/pt.ts

@@ -223,6 +223,8 @@ export const pt: Messages = {
   'dialog.pickShortcutFolder': 'Escolha uma pasta para abrir',
   'dialog.pickThumbnail': 'Escolha uma miniatura',
   'dialog.pickWorkshopFolder': 'Selecione a pasta do Workshop do Wallpaper Engine',
+  'dialog.storeReset': 'Não foi possível ler {name}, então o app iniciou com os valores padrão para ele. O arquivo danificado foi guardado como {keptAs}.',
+  'dialog.storeResetTitle': 'Um arquivo de configurações foi redefinido',
 
   'display.description': 'Com "Cada tela separada", cada tela tem seu próprio papel de parede e playlist, e Reproduzir pergunta qual tela usar. Trocar para tudo o que estiver tocando agora.',
   'display.detected': 'Detectadas: {screens}',

+ 2 - 0
src/shared/i18n/locales/ru.ts

@@ -251,6 +251,8 @@ export const ru: Messages = {
   'dialog.pickShortcutFolder': 'Выберите папку для открытия',
   'dialog.pickThumbnail': 'Выберите миниатюру',
   'dialog.pickWorkshopFolder': 'Выберите папку Мастерской Wallpaper Engine',
+  'dialog.storeReset': 'Не удалось прочитать {name}, поэтому приложение запустилось с настройками по умолчанию для него. Повреждённый файл сохранён как {keptAs}.',
+  'dialog.storeResetTitle': 'Файл настроек был сброшен',
 
   'display.description': 'В режиме "Каждый экран отдельно" у каждого экрана свои обои и плейлист, а "Воспроизвести" спрашивает, какой экран использовать. Переключение останавливает всё, что сейчас играет.',
   'display.detected': 'Найдены: {screens}',

+ 2 - 0
src/shared/i18n/locales/tr.ts

@@ -223,6 +223,8 @@ export const tr: Messages = {
   'dialog.pickShortcutFolder': 'Açılacak klasörü seçin',
   'dialog.pickThumbnail': 'Küçük resim seçin',
   'dialog.pickWorkshopFolder': 'Wallpaper Engine Atölye klasörünü seçin',
+  'dialog.storeReset': '{name} okunamadı, bu yüzden uygulama bu dosya için varsayılanlarla başladı. Hasarlı dosya {keptAs} adıyla saklandı.',
+  'dialog.storeResetTitle': 'Bir ayar dosyası sıfırlandı',
 
   'display.description': '"Her ekran ayrı" seçiliyken her ekranın kendi duvar kağıdı ve çalma listesi olur, Oynat hangi ekranın kullanılacağını sorar. Geçiş yapmak şu an oynayan her şeyi durdurur.',
   'display.detected': 'Algılanan: {screens}',

+ 2 - 0
src/shared/i18n/locales/zh-CN.ts

@@ -209,6 +209,8 @@ export const zhCN: Messages = {
   'dialog.pickShortcutFolder': '选择要打开的文件夹',
   'dialog.pickThumbnail': '选择缩略图',
   'dialog.pickWorkshopFolder': '选择 Wallpaper Engine 创意工坊文件夹',
+  'dialog.storeReset': '无法读取 {name},应用已对该文件使用默认值启动。损坏的文件已保存为 {keptAs}。',
+  'dialog.storeResetTitle': '设置文件已重置',
 
   'display.description': '选择"每个屏幕独立"后,每个屏幕有自己的壁纸和播放列表,播放时会询问使用哪个屏幕。切换会停止当前正在播放的内容。',
   'display.detected': '已检测到: {screens}',

+ 2 - 0
src/shared/i18n/locales/zh-TW.ts

@@ -209,6 +209,8 @@ export const zhTW: Messages = {
   'dialog.pickShortcutFolder': '選擇要開啟的資料夾',
   'dialog.pickThumbnail': '選擇縮圖',
   'dialog.pickWorkshopFolder': '選取 Wallpaper Engine 工作坊資料夾',
+  'dialog.storeReset': '無法讀取 {name},應用程式已對此檔案使用預設值啟動。損毀的檔案已另存為 {keptAs}。',
+  'dialog.storeResetTitle': '設定檔已重設',
 
   'display.description': '選擇「每個螢幕各自獨立」後,每個螢幕有自己的桌布和播放清單,播放時會詢問要使用哪個螢幕。切換會停止目前正在播放的內容。',
   'display.detected': '已偵測到: {screens}',

+ 2 - 2
src/shared/videoTrim.ts

@@ -57,12 +57,12 @@ export function normalizeVideoSegments(segments: VideoSegment[], duration?: numb
   return merged
 }
 
-function seconds(value: number): string {
+function wholeSeconds(value: number): string {
   return String(Math.round(value * 1000) / 1000)
 }
 
 export function formatVideoSegments(segments: VideoSegment[]): string {
-  return segments.map((s) => `${seconds(s.start)}-${s.end === undefined ? '' : seconds(s.end)}`).join(',')
+  return segments.map((s) => `${wholeSeconds(s.start)}-${s.end === undefined ? '' : wholeSeconds(s.end)}`).join(',')
 }
 
 export function trimmedVideoLength(duration: number, segments: VideoSegment[]): number {

Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels