Эх сурвалжийг харах

Add playlist clock modes, app rules, profiles and video tools (0.9.10)

- Playlists: daytime, day of week, never and logon modes, schedule
  helpers in shared/playlistSchedule
- Application rules and profiles, with rule actions shared with the
  schedule
- Audio input device setting, background and quick video optimize,
  video tools and defaults in settings
- Kill all: optional pausing of playlists, and a separate switch for
  the integration branch's behavior (suspend, stop the playlists and
  forget the wallpapers); both off keeps the plain kill
- Process lookup helpers for the app rules
- Packaging: local rpm build script, release notes for 0.9.8 to 0.9.10,
  electron 45.2.3

Merged onto the integration branch: the clock modes sit on top of its
showCurrent/resumePlayer playlist player, and the rule actions use its
isShownOn check for the applied counter.
WallpaperEngineLover 2 долоо хоног өмнө
parent
commit
e27ab42b6d
100 өөрчлөгдсөн 6415 нэмэгдсэн , 1157 устгасан
  1. 6 84
      package-lock.json
  2. 3 2
      package.json
  3. 240 240
      packaging/flathub/generated-sources.json
  4. 7 5
      packaging/flathub/io.github.WallpaperEngineLover.we_manager.yml
  5. 3 0
      packaging/flatpak/io.github.WallpaperEngineLover.we_manager.metainfo.xml
  6. 21 0
      packaging/rpm/build-local.sh
  7. 6 3
      src/main/index.ts
  8. 49 0
      src/main/ipc/app-rules.handlers.ts
  9. 16 0
      src/main/ipc/config.handlers.ts
  10. 8 1
      src/main/ipc/desktop-icons.handlers.ts
  11. 4 0
      src/main/ipc/index.ts
  12. 17 2
      src/main/ipc/lwe.handlers.ts
  13. 25 12
      src/main/ipc/playlist.handlers.ts
  14. 43 1
      src/main/ipc/steam.handlers.ts
  15. 48 0
      src/main/ipc/video-tools.handlers.ts
  16. 264 0
      src/main/services/app-rules.service.ts
  17. 33 0
      src/main/services/backup.service.test.ts
  18. 71 21
      src/main/services/backup.service.ts
  19. 36 0
      src/main/services/config.service.ts
  20. 65 6
      src/main/services/desktop-icons.service.ts
  21. 4 6
      src/main/services/diagnostics.service.ts
  22. 1 4
      src/main/services/gnome-extension.service.ts
  23. 1 4
      src/main/services/graphics.service.ts
  24. 199 21
      src/main/services/library.service.ts
  25. 1 4
      src/main/services/lwe-libnode.service.ts
  26. 9 14
      src/main/services/lwe-prebuilt.service.ts
  27. 19 0
      src/main/services/lwe.service.test.ts
  28. 66 10
      src/main/services/lwe.service.ts
  29. 175 16
      src/main/services/playlist-player.service.ts
  30. 2 1
      src/main/services/playlist.service.ts
  31. 57 0
      src/main/services/profile.service.ts
  32. 78 0
      src/main/services/rule-actions.service.ts
  33. 5 32
      src/main/services/schedule.service.ts
  34. 2 4
      src/main/services/static-wallpaper.service.ts
  35. 36 0
      src/main/services/steam.service.test.ts
  36. 47 21
      src/main/services/steam.service.ts
  37. 5 6
      src/main/services/update.service.ts
  38. 1075 0
      src/main/services/video-tools.service.ts
  39. 1 4
      src/main/services/wallpaper.service.ts
  40. 21 1
      src/main/services/workshop-verify.service.test.ts
  41. 21 6
      src/main/services/workshop-verify.service.ts
  42. 82 0
      src/main/utils/audio-activity.ts
  43. 4 0
      src/main/utils/exec.ts
  44. 9 2
      src/main/utils/flatpak.ts
  45. 18 20
      src/main/utils/github.ts
  46. 1 4
      src/main/utils/hdr.ts
  47. 87 0
      src/main/utils/loginSession.ts
  48. 6 0
      src/main/utils/paths.ts
  49. 41 0
      src/main/utils/processes.test.ts
  50. 123 0
      src/main/utils/processes.ts
  51. 21 0
      src/main/utils/projectJson.ts
  52. 4 0
      src/main/utils/shaderCache.ts
  53. 7 4
      src/main/utils/video.ts
  54. 75 3
      src/preload/index.ts
  55. 10 0
      src/renderer/src/App.tsx
  56. 68 0
      src/renderer/src/components/common/BackgroundOptimizeNotice.tsx
  57. 228 0
      src/renderer/src/components/common/CutRangesEditor.tsx
  58. 4 3
      src/renderer/src/components/common/DetailSidebar.tsx
  59. 4 18
      src/renderer/src/components/common/FontNotice.tsx
  60. 548 0
      src/renderer/src/components/common/OptimizeVideoModal.tsx
  61. 75 0
      src/renderer/src/components/common/QuickOptimizeNotice.tsx
  62. 32 15
      src/renderer/src/components/common/WallpaperContextMenu.tsx
  63. 2 0
      src/renderer/src/components/common/inputClass.ts
  64. 29 0
      src/renderer/src/components/common/sidebar/CommitRange.tsx
  65. 55 67
      src/renderer/src/components/common/sidebar/CompatSection.tsx
  66. 88 103
      src/renderer/src/components/common/sidebar/EngineFlagsSection.tsx
  67. 34 0
      src/renderer/src/components/common/sidebar/SidebarSection.tsx
  68. 53 66
      src/renderer/src/components/common/sidebar/ThumbnailSection.tsx
  69. 50 44
      src/renderer/src/components/library/LibraryView.tsx
  70. 7 19
      src/renderer/src/components/library/WallpaperCard.tsx
  71. 71 19
      src/renderer/src/components/playlist/PlaylistItemRow.tsx
  72. 46 4
      src/renderer/src/components/playlist/PlaylistsView.tsx
  73. 5 17
      src/renderer/src/components/playlist/WallpaperPickerModal.tsx
  74. 147 0
      src/renderer/src/components/settings/ActionPicker.tsx
  75. 172 0
      src/renderer/src/components/settings/AppRuleSettings.tsx
  76. 107 0
      src/renderer/src/components/settings/AudioInputSettings.tsx
  77. 8 12
      src/renderer/src/components/settings/DiagnosticsTargetModal.tsx
  78. 4 22
      src/renderer/src/components/settings/FontSettings.tsx
  79. 86 0
      src/renderer/src/components/settings/ProfileSettings.tsx
  80. 113 0
      src/renderer/src/components/settings/RuleParts.tsx
  81. 36 151
      src/renderer/src/components/settings/ScheduleSettings.tsx
  82. 27 6
      src/renderer/src/components/settings/SettingsTabs.tsx
  83. 58 0
      src/renderer/src/components/settings/SettingsView.tsx
  84. 172 0
      src/renderer/src/components/settings/VideoDefaultsSettings.tsx
  85. 77 0
      src/renderer/src/components/settings/VideoToolsSettings.tsx
  86. 11 11
      src/renderer/src/components/workshop/WorkshopCard.tsx
  87. 8 1
      src/renderer/src/constants/engineFlags.ts
  88. 19 0
      src/renderer/src/hooks/externalStore.ts
  89. 21 1
      src/renderer/src/hooks/queries.ts
  90. 53 0
      src/renderer/src/hooks/useBackgroundOptimize.ts
  91. 27 0
      src/renderer/src/hooks/useFontAdd.ts
  92. 34 0
      src/renderer/src/hooks/useLibraryTasks.ts
  93. 87 0
      src/renderer/src/hooks/useQuickOptimize.ts
  94. 15 14
      src/renderer/src/hooks/useSelectableGrid.ts
  95. 4 0
      src/renderer/src/utils/wallpaper.ts
  96. 135 0
      src/shared/appRules.test.ts
  97. 126 0
      src/shared/appRules.ts
  98. 8 0
      src/shared/engineFlags.test.ts
  99. 5 0
      src/shared/engineFlags.ts
  100. 178 0
      src/shared/i18n/locales/de.ts

+ 6 - 84
package-lock.json

@@ -1,12 +1,12 @@
 {
   "name": "we-manager",
-  "version": "0.9.9",
+  "version": "0.9.10",
   "lockfileVersion": 3,
   "requires": true,
   "packages": {
     "": {
       "name": "we-manager",
-      "version": "0.9.9",
+      "version": "0.9.10",
       "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": "^6.1.2",
-        "electron": "^45.1.0",
+        "electron": "^45.2.3",
         "electron-builder": "^26.15.3",
         "electron-vite": "^6.0.0",
         "oxlint": "^1.90.0",
@@ -1205,9 +1205,6 @@
         "arm64"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1225,9 +1222,6 @@
         "arm64"
       ],
       "dev": true,
-      "libc": [
-        "musl"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1245,9 +1239,6 @@
         "ppc64"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1265,9 +1256,6 @@
         "riscv64"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1285,9 +1273,6 @@
         "riscv64"
       ],
       "dev": true,
-      "libc": [
-        "musl"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1305,9 +1290,6 @@
         "s390x"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1325,9 +1307,6 @@
         "x64"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1345,9 +1324,6 @@
         "x64"
       ],
       "dev": true,
-      "libc": [
-        "musl"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1590,9 +1566,6 @@
         "arm64"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1610,9 +1583,6 @@
         "arm64"
       ],
       "dev": true,
-      "libc": [
-        "musl"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1630,9 +1600,6 @@
         "ppc64"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1650,9 +1617,6 @@
         "s390x"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1670,9 +1634,6 @@
         "x64"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1690,9 +1651,6 @@
         "x64"
       ],
       "dev": true,
-      "libc": [
-        "musl"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1919,9 +1877,6 @@
         "arm64"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1939,9 +1894,6 @@
         "arm64"
       ],
       "dev": true,
-      "libc": [
-        "musl"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1959,9 +1911,6 @@
         "x64"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -1979,9 +1928,6 @@
         "x64"
       ],
       "dev": true,
-      "libc": [
-        "musl"
-      ],
       "license": "MIT",
       "optional": true,
       "os": [
@@ -3834,9 +3780,9 @@
       }
     },
     "node_modules/electron": {
-      "version": "45.1.0",
-      "resolved": "https://registry.npmjs.org/electron/-/electron-45.1.0.tgz",
-      "integrity": "sha512-i7qKVAh/KR5v1pf56NhGGX2QYHcdjvLgS7koL6ui50c+zUDGLRunR95nXcTpHPURKOQ4GDBG8BmXiDgOQ8DD0A==",
+      "version": "45.2.3",
+      "resolved": "https://registry.npmjs.org/electron/-/electron-45.2.3.tgz",
+      "integrity": "sha512-Vurzu5UOA5nTGT4LqIwXD16QFGrOZdiXxF+1UP4KNsAOo/YtDcT3/u0jhP4WSwNJ0iLrLDi85hzBJ0arnGDhyw==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
@@ -5119,9 +5065,6 @@
         "arm64"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MPL-2.0",
       "optional": true,
       "os": [
@@ -5143,9 +5086,6 @@
         "arm64"
       ],
       "dev": true,
-      "libc": [
-        "musl"
-      ],
       "license": "MPL-2.0",
       "optional": true,
       "os": [
@@ -5167,9 +5107,6 @@
         "x64"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MPL-2.0",
       "optional": true,
       "os": [
@@ -5191,9 +5128,6 @@
         "x64"
       ],
       "dev": true,
-      "libc": [
-        "musl"
-      ],
       "license": "MPL-2.0",
       "optional": true,
       "os": [
@@ -7042,9 +6976,6 @@
         "arm64"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MPL-2.0",
       "optional": true,
       "os": [
@@ -7066,9 +6997,6 @@
         "arm64"
       ],
       "dev": true,
-      "libc": [
-        "musl"
-      ],
       "license": "MPL-2.0",
       "optional": true,
       "os": [
@@ -7090,9 +7018,6 @@
         "x64"
       ],
       "dev": true,
-      "libc": [
-        "glibc"
-      ],
       "license": "MPL-2.0",
       "optional": true,
       "os": [
@@ -7114,9 +7039,6 @@
         "x64"
       ],
       "dev": true,
-      "libc": [
-        "musl"
-      ],
       "license": "MPL-2.0",
       "optional": true,
       "os": [

+ 3 - 2
package.json

@@ -1,6 +1,6 @@
 {
   "name": "we-manager",
-  "version": "0.9.9",
+  "version": "0.9.10",
   "type": "module",
   "description": "Wallpaper Engine workshop manager",
   "desktopName": "we-manager.desktop",
@@ -14,6 +14,7 @@
     "preview": "electron-vite preview",
     "dist": "npm run build && electron-builder",
     "dist:linux": "npm run build && electron-builder --linux",
+    "dist:rpm": "sh packaging/rpm/build-local.sh",
     "lint": "oxlint",
     "test": "vitest run",
     "typecheck": "tsc -p tsconfig.node.json --noEmit && tsc -p tsconfig.web.json --noEmit"
@@ -34,7 +35,7 @@
     "@types/react": "^19.2.17",
     "@types/react-dom": "^19.2.3",
     "@vitejs/plugin-react": "^6.1.2",
-    "electron": "^45.1.0",
+    "electron": "^45.2.3",
     "electron-builder": "^26.15.3",
     "electron-vite": "^6.0.0",
     "oxlint": "^1.90.0",

+ 240 - 240
packaging/flathub/generated-sources.json

@@ -1,23 +1,23 @@
 [
     {
         "type": "archive",
-        "url": "https://www.electronjs.org/headers/v45.0.0/node-v45.0.0-headers.tar.gz",
+        "url": "https://www.electronjs.org/headers/v45.1.0/node-v45.1.0-headers.tar.gz",
         "strip-components": 1,
-        "sha256": "bf3ec8efe30aa2d66759f2e9e8afd05182f656edb09478424d8fb5bcddfae4f6",
-        "dest": "flatpak-node/cache/node-gyp/45.0.0"
+        "sha256": "f0ae8b907889783b88e264e6fb234f78408218717f3836cb92261df9da91d236",
+        "dest": "flatpak-node/cache/node-gyp/45.1.0"
     },
     {
         "type": "file",
-        "url": "https://github.com/electron/electron/releases/download/v45.0.0/SHASUMS256.txt",
-        "sha256": "5882ee4d3f943f567cdb6df9bf86e78de9c369e41d9093daaa2e3acaa630093b",
-        "dest-filename": "SHASUMS256.txt-45.0.0",
+        "url": "https://github.com/electron/electron/releases/download/v45.1.0/SHASUMS256.txt",
+        "sha256": "af5e45cd87fb17b9eafafd74feab5a74fbfddeb5f150e3e25ae8cd6107bb6a99",
+        "dest-filename": "SHASUMS256.txt-45.1.0",
         "dest": "flatpak-node/cache/electron"
     },
     {
         "type": "file",
-        "url": "https://github.com/electron/electron/releases/download/v45.0.0/electron-v45.0.0-linux-arm64.zip",
-        "sha256": "a80d92b1ad6c111545a12632b8a75cedce614a41866e500810d4050d947f90e9",
-        "dest-filename": "electron-v45.0.0-linux-arm64.zip",
+        "url": "https://github.com/electron/electron/releases/download/v45.1.0/electron-v45.1.0-linux-arm64.zip",
+        "sha256": "64b78d93d1129ab805cdc0f2710f446716afbe814a1d08e639dab3175d2285a1",
+        "dest-filename": "electron-v45.1.0-linux-arm64.zip",
         "dest": "flatpak-node/cache/electron",
         "only-arches": [
             "aarch64"
@@ -25,9 +25,9 @@
     },
     {
         "type": "file",
-        "url": "https://github.com/electron/electron/releases/download/v45.0.0/electron-v45.0.0-linux-x64.zip",
-        "sha256": "22f6a10bd3f7fef987ddbb379d3375ce664ad0c98a9a50f80c89f1718a0c3e3a",
-        "dest-filename": "electron-v45.0.0-linux-x64.zip",
+        "url": "https://github.com/electron/electron/releases/download/v45.1.0/electron-v45.1.0-linux-x64.zip",
+        "sha256": "9dafab2c57ce209f8f716f8f3e4fddd8ffe0820e2455bfbbfc00b0fc13e03a3b",
+        "dest-filename": "electron-v45.1.0-linux-x64.zip",
         "dest": "flatpak-node/cache/electron",
         "only-arches": [
             "x86_64"
@@ -441,136 +441,136 @@
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.89.0.tgz",
-        "sha512": "3df9696dae45de0440435dac5a0951c6f5931c4740bac343be68b86393754f9498d401a433b022c4e9c44fcaa4ae72c9fc5df6a8094da243ba7829274fcb669f",
-        "dest-filename": "696dae45de0440435dac5a0951c6f5931c4740bac343be68b86393754f9498d401a433b022c4e9c44fcaa4ae72c9fc5df6a8094da243ba7829274fcb669f",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/3d/f9"
+        "url": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.90.0.tgz",
+        "sha512": "b207da95bd47bb16238806b8c04499eb6eb3d451aeb2a35c5d81f2079a08384a6b4b6b1b3e0d146047e8f37b85d46346ef40c87d9c47917b84e8a16b952767f1",
+        "dest-filename": "da95bd47bb16238806b8c04499eb6eb3d451aeb2a35c5d81f2079a08384a6b4b6b1b3e0d146047e8f37b85d46346ef40c87d9c47917b84e8a16b952767f1",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/b2/07"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.89.0.tgz",
-        "sha512": "7589b20f5c7b2da3e56fbf6f65651ca534a193c748f73d48f88b9bb6aac1c5634968385074f1f072cbe0eeae52b53538c56c9df40c0f7cb693605658f0d660b5",
-        "dest-filename": "b20f5c7b2da3e56fbf6f65651ca534a193c748f73d48f88b9bb6aac1c5634968385074f1f072cbe0eeae52b53538c56c9df40c0f7cb693605658f0d660b5",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/75/89"
+        "url": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.90.0.tgz",
+        "sha512": "45c2a1cf511332af9f6b313d4ca4b6fb9348446c22826fe75bc7a0a85d0b23e03c630da25b9af413f0b75c03d18b0226fef70f8aeb484486ba2100882a166c4d",
+        "dest-filename": "a1cf511332af9f6b313d4ca4b6fb9348446c22826fe75bc7a0a85d0b23e03c630da25b9af413f0b75c03d18b0226fef70f8aeb484486ba2100882a166c4d",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/45/c2"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.89.0.tgz",
-        "sha512": "67fa3138f888aa24bb7c8b5177169a3840bee860f73a91a2d08c6847474c79fcd01e896c28bcd2730d8335cbbfe6050fa24dedbfe1bd9ac96f601e5ba378b4aa",
-        "dest-filename": "3138f888aa24bb7c8b5177169a3840bee860f73a91a2d08c6847474c79fcd01e896c28bcd2730d8335cbbfe6050fa24dedbfe1bd9ac96f601e5ba378b4aa",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/67/fa"
+        "url": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.90.0.tgz",
+        "sha512": "3d2af132f3fa9b1fa9d646ab65c5312ddcbd96968ff895903ed8b86a5f4581368f87113ea53fc18e1184c65a155525a066021f3a52ce8d5cb2abc0579687612d",
+        "dest-filename": "f132f3fa9b1fa9d646ab65c5312ddcbd96968ff895903ed8b86a5f4581368f87113ea53fc18e1184c65a155525a066021f3a52ce8d5cb2abc0579687612d",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/3d/2a"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.89.0.tgz",
-        "sha512": "7808d39074a3031add08f2713bacb9b0f40be6960b29bda4bf1673f5453bb579ce664f48fc72ed92fc7d4bb18763cf3793e0262ff782ee6a85b7ec3b582c24d3",
-        "dest-filename": "d39074a3031add08f2713bacb9b0f40be6960b29bda4bf1673f5453bb579ce664f48fc72ed92fc7d4bb18763cf3793e0262ff782ee6a85b7ec3b582c24d3",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/78/08"
+        "url": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.90.0.tgz",
+        "sha512": "38b6d4f6ab2b57643c4314f6384cce3dd3bccc20a9c88f2a07e84323ccabe91b1810bb647f414066125d7e333f4672c72b3b78e075b000f9e4f76bc1b4aa1fbf",
+        "dest-filename": "d4f6ab2b57643c4314f6384cce3dd3bccc20a9c88f2a07e84323ccabe91b1810bb647f414066125d7e333f4672c72b3b78e075b000f9e4f76bc1b4aa1fbf",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/38/b6"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.89.0.tgz",
-        "sha512": "d2534203d4e5d67d452a9ab2dbff5c929d2422e4abb49fe5f5b31181a1213ad33b4ec387b2116ec0e72f5bca00f6d7972cc3894fad4b8c429689a1c3146c45ff",
-        "dest-filename": "4203d4e5d67d452a9ab2dbff5c929d2422e4abb49fe5f5b31181a1213ad33b4ec387b2116ec0e72f5bca00f6d7972cc3894fad4b8c429689a1c3146c45ff",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/d2/53"
+        "url": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.90.0.tgz",
+        "sha512": "7c1038a56c950c046636e710aa9c85b8f0b8f7161fd6bfac5fb7713cbe5f34f42b48c2ee9b7f529f9ead67d24f95e582ec5ccb3f0490ee995861f8ab6011c5f0",
+        "dest-filename": "38a56c950c046636e710aa9c85b8f0b8f7161fd6bfac5fb7713cbe5f34f42b48c2ee9b7f529f9ead67d24f95e582ec5ccb3f0490ee995861f8ab6011c5f0",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/7c/10"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.89.0.tgz",
-        "sha512": "393144be2f56f897336990f509a8f5ed2182a16f07ed313e7efc740fb0131166b52e8867f7550cc4543aaf5e394a21b2ff20b1788c29b4ccacfd100cee049549",
-        "dest-filename": "44be2f56f897336990f509a8f5ed2182a16f07ed313e7efc740fb0131166b52e8867f7550cc4543aaf5e394a21b2ff20b1788c29b4ccacfd100cee049549",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/39/31"
+        "url": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.90.0.tgz",
+        "sha512": "ce1c47efc78fda747afe919d84173b3087e38617200137aef1f92690525bbb37e4e828f4173071c8484bf39c83aab0b26e3c7e1b6603cd91acc483bd92f3b823",
+        "dest-filename": "47efc78fda747afe919d84173b3087e38617200137aef1f92690525bbb37e4e828f4173071c8484bf39c83aab0b26e3c7e1b6603cd91acc483bd92f3b823",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/ce/1c"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.89.0.tgz",
-        "sha512": "7d1c60347bc12ecc23e8cae15b6b81ab950384f4509426c77aafcd7fccae1bdccec610ec5ea5ff9a2d8f5f56b182c431326f3c7a5ec72e2240ce09409df958c7",
-        "dest-filename": "60347bc12ecc23e8cae15b6b81ab950384f4509426c77aafcd7fccae1bdccec610ec5ea5ff9a2d8f5f56b182c431326f3c7a5ec72e2240ce09409df958c7",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/7d/1c"
+        "url": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.90.0.tgz",
+        "sha512": "32f626a47c89a9426312f9196c91ddc1f74be397069fc115064626a17162698156f6cba80f775b265e6605da72d0356076397275d9a575b46d9377028044da75",
+        "dest-filename": "26a47c89a9426312f9196c91ddc1f74be397069fc115064626a17162698156f6cba80f775b265e6605da72d0356076397275d9a575b46d9377028044da75",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/32/f6"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.89.0.tgz",
-        "sha512": "bfd10dcc7bf0ad0a184964edbe21f5a4e61ced1f54a2f0f15687e7724e7470d98f8a14514dcae0e57d149516cb399ec856dc4f3a587685bee40cef85a44f127d",
-        "dest-filename": "0dcc7bf0ad0a184964edbe21f5a4e61ced1f54a2f0f15687e7724e7470d98f8a14514dcae0e57d149516cb399ec856dc4f3a587685bee40cef85a44f127d",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/bf/d1"
+        "url": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.90.0.tgz",
+        "sha512": "2f5dd2cbe2a0d27661c13b13a278aa8d414f0364ee33af7adaa099e56a7929e079d7b4f0ec0a5d2d34ed95bf9b17ce9f71965ad84b6f095bc02719380f26bf31",
+        "dest-filename": "d2cbe2a0d27661c13b13a278aa8d414f0364ee33af7adaa099e56a7929e079d7b4f0ec0a5d2d34ed95bf9b17ce9f71965ad84b6f095bc02719380f26bf31",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/2f/5d"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.89.0.tgz",
-        "sha512": "bdf7df7bc990e3ce00cd569d954385a602fe243c21becf61af3c538103f51557e2e1911451879f7d79730bd74557b0e09eee6cfcaacd2af7e61ba1f105dfc849",
-        "dest-filename": "df7bc990e3ce00cd569d954385a602fe243c21becf61af3c538103f51557e2e1911451879f7d79730bd74557b0e09eee6cfcaacd2af7e61ba1f105dfc849",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/bd/f7"
+        "url": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.90.0.tgz",
+        "sha512": "c050dd6561a9cc83c574916348b5a7281d131b316b89329422b974e2232a33233d0412094ee7ab7c21d86b45a90d28ebe71de5716fc21cbc9a712b7cf3a5a91a",
+        "dest-filename": "dd6561a9cc83c574916348b5a7281d131b316b89329422b974e2232a33233d0412094ee7ab7c21d86b45a90d28ebe71de5716fc21cbc9a712b7cf3a5a91a",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/c0/50"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.89.0.tgz",
-        "sha512": "06ea27969e21552ed118d3f933b6cfa46350ade9f2cc0d82eb825c3bfa33f42d5ce9d18e5c9ed51009da880318eefa28bb4258c8225dbc35651507390d95f70d",
-        "dest-filename": "27969e21552ed118d3f933b6cfa46350ade9f2cc0d82eb825c3bfa33f42d5ce9d18e5c9ed51009da880318eefa28bb4258c8225dbc35651507390d95f70d",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/06/ea"
+        "url": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.90.0.tgz",
+        "sha512": "151cb07e7f8ca0a9fcc69052ce037035596248a448d905e4c62fe217ba3a14442cf0187ccf646955368501c3b7a5c8578ef0767863452282cb40004843ebbb54",
+        "dest-filename": "b07e7f8ca0a9fcc69052ce037035596248a448d905e4c62fe217ba3a14442cf0187ccf646955368501c3b7a5c8578ef0767863452282cb40004843ebbb54",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/15/1c"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.89.0.tgz",
-        "sha512": "d5e570249ac9de56083d3f9c9bb05c0416595d8e884193ffa32a276abb93a2bfccad5c963a9be7c2dd680f908b76c1e0e5a5412315e87504afb7ed602ba724e7",
-        "dest-filename": "70249ac9de56083d3f9c9bb05c0416595d8e884193ffa32a276abb93a2bfccad5c963a9be7c2dd680f908b76c1e0e5a5412315e87504afb7ed602ba724e7",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/d5/e5"
+        "url": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.90.0.tgz",
+        "sha512": "212d8f69482973fa9e2c00d3ca150d99dc77c788a3b3da6325d3ca0581da4fe98013b93716c8e71cf4e3869b1a9356fefa1e8220f86fe965fd67ecbb3f0d2fa1",
+        "dest-filename": "8f69482973fa9e2c00d3ca150d99dc77c788a3b3da6325d3ca0581da4fe98013b93716c8e71cf4e3869b1a9356fefa1e8220f86fe965fd67ecbb3f0d2fa1",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/21/2d"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.89.0.tgz",
-        "sha512": "7d1410b0a5064a17442f9165f68f6e863de0ae465b79728bbf489c439b6ca5408d6120f2f30cf311c3f5582d9b29d4d0d2b4accdb2a53b78a21ce471576d832e",
-        "dest-filename": "10b0a5064a17442f9165f68f6e863de0ae465b79728bbf489c439b6ca5408d6120f2f30cf311c3f5582d9b29d4d0d2b4accdb2a53b78a21ce471576d832e",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/7d/14"
+        "url": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.90.0.tgz",
+        "sha512": "b3b2452919064bc3bb8b66553837ee3bef8d0bbb07e870eaa4c9fc958c70f75c3449724ec670158d0f2eb6f983c0b30c4f48da4a4b8e2ae518243183b6ee2c1d",
+        "dest-filename": "452919064bc3bb8b66553837ee3bef8d0bbb07e870eaa4c9fc958c70f75c3449724ec670158d0f2eb6f983c0b30c4f48da4a4b8e2ae518243183b6ee2c1d",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/b3/b2"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.89.0.tgz",
-        "sha512": "744b588c8cbaf9f1dc8ca925b26b663246518701ebd946f38e6a6fb8fb5061278df5ac10da1c7924b9ace56beb8bef0ffcd66d0fcbf985f80700b52a97efd872",
-        "dest-filename": "588c8cbaf9f1dc8ca925b26b663246518701ebd946f38e6a6fb8fb5061278df5ac10da1c7924b9ace56beb8bef0ffcd66d0fcbf985f80700b52a97efd872",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/74/4b"
+        "url": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.90.0.tgz",
+        "sha512": "6f41b1ace42be5538d0a477b28b4aa98fe9bea7a99b93a6e4bc40f407ce5b66a9d5cfe5b634265d026744269424eb4b713168b61b8a815838047335b62f700a5",
+        "dest-filename": "b1ace42be5538d0a477b28b4aa98fe9bea7a99b93a6e4bc40f407ce5b66a9d5cfe5b634265d026744269424eb4b713168b61b8a815838047335b62f700a5",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/6f/41"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.89.0.tgz",
-        "sha512": "86a8f0223e4a39833c5a379ffe9ec8aee362d620722e14b36cc064eb6cb6d8ffc4f2aec98f43e9f837944ca4d1632658083b54d7010696758e9edb476f2348c3",
-        "dest-filename": "f0223e4a39833c5a379ffe9ec8aee362d620722e14b36cc064eb6cb6d8ffc4f2aec98f43e9f837944ca4d1632658083b54d7010696758e9edb476f2348c3",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/86/a8"
+        "url": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.90.0.tgz",
+        "sha512": "89a25e4a126d814a7cad96edf5851d4c018ea665f92a88022db6b5ec9a75b56749dc5e0cdc3da0d93294c88d453131f1287f4d347b9072e0b6919460e8857bc9",
+        "dest-filename": "5e4a126d814a7cad96edf5851d4c018ea665f92a88022db6b5ec9a75b56749dc5e0cdc3da0d93294c88d453131f1287f4d347b9072e0b6919460e8857bc9",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/89/a2"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.89.0.tgz",
-        "sha512": "88040dddeea8f5481409c746c2a471fe361c29b1b71caeeeaf7ac7ea54ea55c41e34667ce40796220e9c827fde770150d287c465922d330933c825536a19ef10",
-        "dest-filename": "0dddeea8f5481409c746c2a471fe361c29b1b71caeeeaf7ac7ea54ea55c41e34667ce40796220e9c827fde770150d287c465922d330933c825536a19ef10",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/88/04"
+        "url": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.90.0.tgz",
+        "sha512": "fda6685e72f95812c25eecdf1eabc4157726e22c189abfdc601c870d35f32c5cc9744e430bb6e6ea98695aa1efe817aaa55818f48a41031183bf6584925e490a",
+        "dest-filename": "685e72f95812c25eecdf1eabc4157726e22c189abfdc601c870d35f32c5cc9744e430bb6e6ea98695aa1efe817aaa55818f48a41031183bf6584925e490a",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/fd/a6"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.89.0.tgz",
-        "sha512": "30dc63101cb3dcdffb438a8542e3d6bdcd784e937d2e80f7a440840ec25365b3ffc3207b53e85db945c497b4006db8157b3170b1bf6c5ad3543ba5d506774e86",
-        "dest-filename": "63101cb3dcdffb438a8542e3d6bdcd784e937d2e80f7a440840ec25365b3ffc3207b53e85db945c497b4006db8157b3170b1bf6c5ad3543ba5d506774e86",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/30/dc"
+        "url": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.90.0.tgz",
+        "sha512": "48c864ee8cf0a3160329f62a19909011f50b38a0e7785f6e85aa087f69dea032d6bcdb6363dc9578bed81e61392fd59d2af32958dc3067185e9f106ee8081f3a",
+        "dest-filename": "64ee8cf0a3160329f62a19909011f50b38a0e7785f6e85aa087f69dea032d6bcdb6363dc9578bed81e61392fd59d2af32958dc3067185e9f106ee8081f3a",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/48/c8"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.89.0.tgz",
-        "sha512": "c717be8bdc1fb85b28fd59e82f899f8f4525cc4f9c7c2162501d3abe45c233241d81556622d17915f005e2d013024b5253ab87aee591f858eabc04fd707659ce",
-        "dest-filename": "be8bdc1fb85b28fd59e82f899f8f4525cc4f9c7c2162501d3abe45c233241d81556622d17915f005e2d013024b5253ab87aee591f858eabc04fd707659ce",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/c7/17"
+        "url": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.90.0.tgz",
+        "sha512": "281bd1dc0f5f3bb7c28b6bc23fc89f5af9626bbb4611057d35a621f881b06bfec6ae8cb8f0cb7f51a62a30af7fcceb405a5db405409fe913eacc9df67d1c37dd",
+        "dest-filename": "d1dc0f5f3bb7c28b6bc23fc89f5af9626bbb4611057d35a621f881b06bfec6ae8cb8f0cb7f51a62a30af7fcceb405a5db405409fe913eacc9df67d1c37dd",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/28/1b"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.89.0.tgz",
-        "sha512": "b1a172d3b70ef7813aeb8825c202e628b238d078132f53d8f3acb84fafae7789e25f81f429daa3726aa68e9b3b99035d072b55e60b866d70ddc90b517de2db2c",
-        "dest-filename": "72d3b70ef7813aeb8825c202e628b238d078132f53d8f3acb84fafae7789e25f81f429daa3726aa68e9b3b99035d072b55e60b866d70ddc90b517de2db2c",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/b1/a1"
+        "url": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.90.0.tgz",
+        "sha512": "fb1e36ac31d019b4c2b93dc4ce9580ce13f736854f13f709b06e209eb6a4392834a2557e18274ca4f536dcdbeb977cd93275f1159753b43bf80f74ae680e5979",
+        "dest-filename": "36ac31d019b4c2b93dc4ce9580ce13f736854f13f709b06e209eb6a4392834a2557e18274ca4f536dcdbeb977cd93275f1159753b43bf80f74ae680e5979",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/fb/1e"
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.89.0.tgz",
-        "sha512": "84b149fe8d1ffdd4c987f116d2f99c6d11184903bdb5881f880025b0e9222c5889b91456bd8b4510b517379a368a3a52a3fb653b59fe62558de7cb59c0f1b5f0",
-        "dest-filename": "49fe8d1ffdd4c987f116d2f99c6d11184903bdb5881f880025b0e9222c5889b91456bd8b4510b517379a368a3a52a3fb653b59fe62558de7cb59c0f1b5f0",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/84/b1"
+        "url": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.90.0.tgz",
+        "sha512": "df4262685101501f6978439cbd533c820a3cf12a0dfc8752afd0d6e74e497418e2fd1e9d33aea0284886eb9870eaa71a1767f898ed1c109f91c11669ae6ba7f6",
+        "dest-filename": "62685101501f6978439cbd533c820a3cf12a0dfc8752afd0d6e74e497418e2fd1e9d33aea0284886eb9870eaa71a1767f898ed1c109f91c11669ae6ba7f6",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/df/42"
     },
     {
         "type": "file",
@@ -1680,10 +1680,10 @@
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/electron/-/electron-45.0.0.tgz",
-        "sha512": "ca3cf8ba130170ee8be57ec25a044ca1b7f610c24f9dbf63e33b9ffa7bbf4d4ffa1384aa7f1edf9ff6b67800a8e2a9e08e697fd099eca1987162ba092f12dddb",
-        "dest-filename": "f8ba130170ee8be57ec25a044ca1b7f610c24f9dbf63e33b9ffa7bbf4d4ffa1384aa7f1edf9ff6b67800a8e2a9e08e697fd099eca1987162ba092f12dddb",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/ca/3c"
+        "url": "https://registry.npmjs.org/electron/-/electron-45.1.0.tgz",
+        "sha512": "8bba8a54087f291e6fd697f9e8d846197d9060771d8ef2e04bb9282faba2e7473ecd40c62d1ba747de675dc4e91cf51128e438183046f0199788380e43c0c3d0",
+        "dest-filename": "8a54087f291e6fd697f9e8d846197d9060771d8ef2e04bb9282faba2e7473ecd40c62d1ba747de675dc4e91cf51128e438183046f0199788380e43c0c3d0",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/8b/ba"
     },
     {
         "type": "file",
@@ -2429,10 +2429,10 @@
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.61.0.tgz",
-        "sha512": "bf64903cf3cd8e7afe06584bf52a6ece6a39c91fa12e47ed7ee1381378dac5d34f8121f484928f70b2413fbc80b5af3b8d034fb121114b9f4f263089fc2a2b04",
-        "dest-filename": "903cf3cd8e7afe06584bf52a6ece6a39c91fa12e47ed7ee1381378dac5d34f8121f484928f70b2413fbc80b5af3b8d034fb121114b9f4f263089fc2a2b04",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/bf/64"
+        "url": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.62.0.tgz",
+        "sha512": "da2f10659864818300de826f298a4296d1e1e785674ffdeb20f9032c76f3af7209401682cfcfbb8fb576936adccd8776682a9c05a326365590d8a29e0df7319b",
+        "dest-filename": "10659864818300de826f298a4296d1e1e785674ffdeb20f9032c76f3af7209401682cfcfbb8fb576936adccd8776682a9c05a326365590d8a29e0df7319b",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/da/2f"
     },
     {
         "type": "file",
@@ -2646,10 +2646,10 @@
     },
     {
         "type": "file",
-        "url": "https://registry.npmjs.org/oxlint/-/oxlint-1.89.0.tgz",
-        "sha512": "6b6e6191fa3ad689063ef273e37d9f4483e8c652ad367395cbdc38af3ae61a0366e225533f0a5242599da8d5a7a7aa7d432c8f55f0194609dfe57bd2059164fc",
-        "dest-filename": "6191fa3ad689063ef273e37d9f4483e8c652ad367395cbdc38af3ae61a0366e225533f0a5242599da8d5a7a7aa7d432c8f55f0194609dfe57bd2059164fc",
-        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/6b/6e"
+        "url": "https://registry.npmjs.org/oxlint/-/oxlint-1.90.0.tgz",
+        "sha512": "4644cdf449a0214a4bba13682e13b73a588c18996f6f70e4ed75630599dfa0c087ad5a6ecf911277dee495f8b261e57b5df03694d2e70c23cc91423e430e47a3",
+        "dest-filename": "cdf449a0214a4bba13682e13b73a588c18996f6f70e4ed75630599dfa0c087ad5a6ecf911277dee495f8b261e57b5df03694d2e70c23cc91423e430e47a3",
+        "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/46/44"
     },
     {
         "type": "file",
@@ -3400,6 +3400,12 @@
         "dest-filename": "2cbec9cd09d27fa2119ceb180fc3237c7a1782c6c88b33c9b1b84fedfe6395a897b03ee3b59a22e94c74224604ca08b7b12f831e00555a82db3b1e6359d9",
         "dest": "flatpak-node/npm-cache/_cacache/content-v2/sha512/ad/59"
     },
+    {
+        "type": "inline",
+        "contents": "00a0ba6d7e106afffd494d8c60592bcacd09c5f4\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.90.0.tgz\", \"integrity\": \"sha512-wFDdZWGpzIPFdJFjSLWnKB0TGzFriTKUIrl04iMqMyM9BBIJTuerfCHYa0WpDSjr5x3lcW/CHLyacSt886WpGg==\", \"time\": 0, \"size\": 6030123, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "4f50cb177ca1f341c7095824b7c9c4dba1449b36e3c1869c42bb7fa9aa70",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/e5/82"
+    },
     {
         "type": "inline",
         "contents": "0156728a0a4f984abb4bb968cda97ec607780983\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/when-exit/-/when-exit-2.1.5.tgz\", \"integrity\": \"sha512-VGkKJ564kzt6Ms1dbgPP/yuIoQCrsFAnRbptpC5wOEsDaNsbCB2bnfnaA8i/vRs5tjUSEOtIuvl9/MyVsvQZCg==\", \"time\": 0, \"size\": 2811, \"metadata\": {\"url\": \"https://registry.npmjs.org/when-exit/-/when-exit-2.1.5.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -3442,12 +3448,6 @@
         "dest-filename": "18f75527ac37299e70f06aad31fb38c55d9ffb7d576a3961d46b9f85720a",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/2d/ea"
     },
-    {
-        "type": "inline",
-        "contents": "08e31786b4ac6b4846dd01fec65a29490d31e9ec\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.89.0.tgz\", \"integrity\": \"sha512-xxe+i9wfuFso/VnoL4mfj0UlzE+cfCFiUB06vkXCMyQdgVVmItF5FfAF4tATAktSU6uHruWR+FjqvAT9cHZZzg==\", \"time\": 0, \"size\": 5617911, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "27165e24ad45028e29a280feab545defabf22cfb9a52651fe6b8cc1e56b3",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/02/01"
-    },
     {
         "type": "inline",
         "contents": "08f70474f0a819721a36f4141d951f4775819862\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz\", \"integrity\": \"sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==\", \"time\": 0, \"size\": 15520, \"metadata\": {\"url\": \"https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -3544,11 +3544,23 @@
         "dest-filename": "8400f74b1ddbcf714d834ce28e24c13824435ec6eb966ebc341ce5460e5c",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/cf/30"
     },
+    {
+        "type": "inline",
+        "contents": "0feb783e0b79cba11bc6766e756a0f177a9dd04b\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.90.0.tgz\", \"integrity\": \"sha512-fBA4pWyVDARmNucQqpyFuPC49xYf1r+sX7dxPL5fNPQrSMLum39Sn56tZ9JPleWC7FzLPwSQ7plYYfirYBHF8A==\", \"time\": 0, \"size\": 6136161, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "0a2a223457e64fd07f9a773560031717e0e4e60f8234878f9415db4ab59e",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/c8/39"
+    },
+    {
+        "type": "inline",
+        "contents": "0ff4d85c7f55d5197d190997ff5894cb4d5188a4\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/lucide-react/-/lucide-react-1.62.0.tgz\", \"integrity\": \"sha512-2i8QZZhkgYMA3oJvKYpCltHh54VnT/3rIPkDLHbzr3IJQBaCz8+7j7V2k2rczYd2aCqcBaMmNlWQ2KKeDfcxmw==\", \"time\": 0, \"size\": 3189386, \"metadata\": {\"url\": \"https://registry.npmjs.org/lucide-react/-/lucide-react-1.62.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "04d385bb303fa28be4ef3e81870a588c2a3c3c348f849e07e5969a39194f",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/2d/e0"
+    },
     {
         "type": "inline",
         "contents": "11",
         "dest-filename": "installVersion",
-        "dest": "flatpak-node/cache/node-gyp/45.0.0"
+        "dest": "flatpak-node/cache/node-gyp/45.1.0"
     },
     {
         "type": "inline",
@@ -3658,12 +3670,6 @@
         "dest-filename": "b3d5fbbe79a2c6cd5b94ec69720d4f24fc018b06a7746ba9ac2191471286",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/ee/06"
     },
-    {
-        "type": "inline",
-        "contents": "1b62855545889647e8a482e8c95beb296dc76942\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.89.0.tgz\", \"integrity\": \"sha512-1eVwJJrJ3lYIPT+cm7BcBBZZXY6IQZP/oyonaruTor/MrVyWOpvnwt1oD5CLdsHg5aVBIxXodQSvt+1gK6ck5w==\", \"time\": 0, \"size\": 6283795, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "2186eb4f1fe22889cd1e8d20b0120c22ef94fc09d24c6259f417183f3151",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/0f/f2"
-    },
     {
         "type": "inline",
         "contents": "1c3336e13f2249925aacbb17bf3089539229a1d3\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz\", \"integrity\": \"sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==\", \"time\": 0, \"size\": 155326, \"metadata\": {\"url\": \"https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -3688,12 +3694,6 @@
         "dest-filename": "c98f1cdf494d5afde6448966f8b5b9ae83d1b42c6702670e15e8a7f68552",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/49/61"
     },
-    {
-        "type": "inline",
-        "contents": "1e4667f74409e0eb4e59f152be763c654587b89d\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/oxlint/-/oxlint-1.89.0.tgz\", \"integrity\": \"sha512-a25hkfo61okGPvJz432fRIPoxlKtNnOVy9w4rzrmGgNm4iVTPwpSQlmdqNWnp6p9QyyPVfAZRgnf5XvSBZFk/A==\", \"time\": 0, \"size\": 378899, \"metadata\": {\"url\": \"https://registry.npmjs.org/oxlint/-/oxlint-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "214155fc71a058904fb61d43dcfe1927fbbdac1cb6523f25604e6a955440",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/8e/23"
-    },
     {
         "type": "inline",
         "contents": "1ea75376a6a62476972c6217d4bb12b40dcc818c\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz\", \"integrity\": \"sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==\", \"time\": 0, \"size\": 3855795, \"metadata\": {\"url\": \"https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -3742,12 +3742,6 @@
         "dest-filename": "131084e0d9ff68269a05db059393ef8aba3f18fdcad6263fd5524888646f",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/fc/2c"
     },
-    {
-        "type": "inline",
-        "contents": "243f6d92aeb26c625367f1d298b1cefdd83a1de2\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.89.0.tgz\", \"integrity\": \"sha512-hLFJ/o0f/dTJh/EW0vmcbREYSQO9tYgfiAAlsOkiLFiJuRRWvYtFELUXN5o2ijpSo/tlO1n+YlWN58tZwPG18A==\", \"time\": 0, \"size\": 5867388, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "e1c9845ffccb47a2368dd4f0178690b9286dbb71b916bb485c837c41ab3a",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/98/66"
-    },
     {
         "type": "inline",
         "contents": "247ea258c7d8b5616935ee277c18b10138a7bac4\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz\", \"integrity\": \"sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==\", \"time\": 0, \"size\": 9669334, \"metadata\": {\"url\": \"https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -3850,6 +3844,12 @@
         "dest-filename": "696b37e693f5198fc88aebd258fd275cc77c3296538e4694b4eefbc6adcb",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/2c/33"
     },
+    {
+        "type": "inline",
+        "contents": "2bbdb083b23ffe65d5497d3d72f3972426ed2d70\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.90.0.tgz\", \"integrity\": \"sha512-b0GxrOQr5VONCkd7KLSqmP6b6nqZuTpuS8QPQHzltmqdXP5bY0Jl0CZ0QmlCTrS3ExaLYbioFYOARzNbYvcApQ==\", \"time\": 0, \"size\": 6657927, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "9a222bd60f077ad3a3938ee32cba842ee5cdd32346b5a736c9091472a8f4",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/44/8b"
+    },
     {
         "type": "inline",
         "contents": "2bdf558ae872100445d39c9d6fac55b69312f3f4\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz\", \"integrity\": \"sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==\", \"time\": 0, \"size\": 5596, \"metadata\": {\"url\": \"https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -3934,6 +3934,12 @@
         "dest-filename": "e26899816618f2bacbdee6728758987638ef78abd3419cee1800fc3bc317",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/0c/46"
     },
+    {
+        "type": "inline",
+        "contents": "343100e18873e68cb86ea541d324fa1b23bec91b\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.90.0.tgz\", \"integrity\": \"sha512-L13Sy+Kg0nZhwTsToniqjUFPA2TuM6962qCZ5Wp5KeB517Tw7ApdLTTtlb+bF86fcZZa2EtvCVvAJxk4Dya/MQ==\", \"time\": 0, \"size\": 6038978, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "313a23e9863cf301e8ae63f793d07b578777850d2974866862ac80c023ab",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/aa/f4"
+    },
     {
         "type": "inline",
         "contents": "343923512bb0ad67c0cad9b79866a8f4653bb4fc\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/which/-/which-6.0.1.tgz\", \"integrity\": \"sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==\", \"time\": 0, \"size\": 3349, \"metadata\": {\"url\": \"https://registry.npmjs.org/which/-/which-6.0.1.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -3970,6 +3976,12 @@
         "dest-filename": "f5acfff641af22eac533faec1f3c1ea6c932ae6e0c3e6e55f92f1b1dbea5",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/1d/ea"
     },
+    {
+        "type": "inline",
+        "contents": "3700fc29997ba039c9cf09df840bb0471499661c\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.90.0.tgz\", \"integrity\": \"sha512-IS2PaUgpc/qeLADTyhUNmdx3x4ijs9pjJdPKBYHaT+mAE7k3FsjnHPTjhpsak1b++h6CIPhv6WX9Z+y7Pw0voQ==\", \"time\": 0, \"size\": 6300611, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "2f79a40ede88b2577bcb25533521c20580c8eff2433428f6d2d24a483ef2",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/b9/74"
+    },
     {
         "type": "inline",
         "contents": "3843564a59d93133fac7d1ce00eae6b37bb8cf67\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz\", \"integrity\": \"sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==\", \"time\": 0, \"size\": 4584, \"metadata\": {\"url\": \"https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -4048,12 +4060,6 @@
         "dest-filename": "ee9ea01b8bd417c97675454bc90c31ad692db5824efd81a2f68e50aead91",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/20/f3"
     },
-    {
-        "type": "inline",
-        "contents": "3d5b7f5e4dd972f5e9f82f181d3a62449747ba61\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.89.0.tgz\", \"integrity\": \"sha512-MNxjEByz3N/7Q4qFQuPWvc14TpN9LoD3pECEDsJTZbP/wyB7U+hduUXEl7QAbbgVezFwsb9sWtNUO6XVBndOhg==\", \"time\": 0, \"size\": 6032861, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "4b95ad00833d0dec7e51a24bc3ebc94e31d943c8237842e774d6361b4309",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/e3/4f"
-    },
     {
         "type": "inline",
         "contents": "3e1f8aa853af6960e1a881ffe691dc2494393991\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/once/-/once-1.4.0.tgz\", \"integrity\": \"sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==\", \"time\": 0, \"size\": 1979, \"metadata\": {\"url\": \"https://registry.npmjs.org/once/-/once-1.4.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -4084,6 +4090,12 @@
         "dest-filename": "71b2d1452a6c218b9b534041f2e2b4b9ce6235c552e2515e16f03820d00e",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/12/80"
     },
+    {
+        "type": "inline",
+        "contents": "400f7e88eb4ad74a9586b22a318282b51c1ff5bc\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.90.0.tgz\", \"integrity\": \"sha512-iaJeShJtgUp8rZbt9YUdTAGOpmX5KogCLba17Jp1tWdJ3F4M3D2g2TKUyI1FMTHxKH9NNHuQcuC2kZRg6IV7yQ==\", \"time\": 0, \"size\": 6401249, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "c252a518b7240553e8c20e96f4bcd14b5780b609527bfa0f2b1b646941e1",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/3d/3c"
+    },
     {
         "type": "inline",
         "contents": "404631371bc60fc5d707e0ffaf61fe52063a5ae5\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz\", \"integrity\": \"sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==\", \"time\": 0, \"size\": 1405830, \"metadata\": {\"url\": \"https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -4102,6 +4114,12 @@
         "dest-filename": "6b5f901e14b049b2e340d9f19d64bc3a4440272cb7bc50d2227d76805d70",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/c8/91"
     },
+    {
+        "type": "inline",
+        "contents": "4170d8074c01111b63790175f551c7dc459fbba5\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.90.0.tgz\", \"integrity\": \"sha512-KBvR3A9fO7fCi2vCP8ifWvlia7tGEQV9NaYh+IGwa/7Groy48Mt/UaYqMK9/zOtAWl20BUCf6RPqzJ32fRw33Q==\", \"time\": 0, \"size\": 5630245, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "8a58913d5541d8563bdfdaa2fa74b88bbbbe2fe8a3646a4bd2a2ae764cdb",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/fd/37"
+    },
     {
         "type": "inline",
         "contents": "424424bf943ac060b021ce3d522e0cc1236ee893\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@electron/get/-/get-3.1.0.tgz\", \"integrity\": \"sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==\", \"time\": 0, \"size\": 22554, \"metadata\": {\"url\": \"https://registry.npmjs.org/@electron/get/-/get-3.1.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -4174,12 +4192,6 @@
         "dest-filename": "e08f3dfa5d00cabec76b3a947effc9e3d49e62b94e985db850a84c753e5d",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/d6/11"
     },
-    {
-        "type": "inline",
-        "contents": "4ced6a6021daea653bd8922e40266aeae5c2972e\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.89.0.tgz\", \"integrity\": \"sha512-0lNCA9Tl1n1FKpqy2/9ckp0kIuSrtJ/l9bMRgaEhOtM7TsOHshFuwOcvW8oA9teXLMOJT61LjEKWiaHDFGxF/w==\", \"time\": 0, \"size\": 6121840, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "a819f158a75da27aaa671261578932f89ae29b4e7b17fbbefff985f29939",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/4d/4f"
-    },
     {
         "type": "inline",
         "contents": "4d28bf1a2b925691ade5e3c9c2eca4e67150280e\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz\", \"integrity\": \"sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==\", \"time\": 0, \"size\": 17325, \"metadata\": {\"url\": \"https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -4246,6 +4258,12 @@
         "dest-filename": "b26c31e0da3d9323f2596c2a445ed29a5583dc964d85ab673976029ed2d9",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/53/ed"
     },
+    {
+        "type": "inline",
+        "contents": "52e2056084219e569d73559b2687f22304ded0a7\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.90.0.tgz\", \"integrity\": \"sha512-MvYmpHyJqUJjEvkZbJHdwfdL45cGn8EVBkYmoXFiaYFW9suoD3dbJl5mBdpy0DVgdjlyddmldbRtk3cCgETadQ==\", \"time\": 0, \"size\": 5721774, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "7830e9f49f12aceb8b701ef758922ae9577ec4e72d02a6da3b1428d881f7",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/e8/93"
+    },
     {
         "type": "inline",
         "contents": "54692f9439030ea2c2c32aa9671f5c44dbace583\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@types/fs-extra/-/fs-extra-9.0.13.tgz\", \"integrity\": \"sha512-nEnwB++1u5lVDM2UI4c1+5R+FYaKfaAzS4OococimjVm3nQw3TuzH5UNsocrcTBbhnerblyHj4A49qXbIiZdpA==\", \"time\": 0, \"size\": 4927, \"metadata\": {\"url\": \"https://registry.npmjs.org/@types/fs-extra/-/fs-extra-9.0.13.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -4258,6 +4276,12 @@
         "dest-filename": "cd7674b822df1345c9c34d1a695ac98c2b5e5dd34568a18c67c4e675fbc5",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/92/94"
     },
+    {
+        "type": "inline",
+        "contents": "55719042e9cf56ded8da29927749b687771728f8\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/oxlint/-/oxlint-1.90.0.tgz\", \"integrity\": \"sha512-RkTN9EmgIUpLuhNoLhO3OliMGJlvb3Dk7XVjBZnfoMCHrVpuz5ESd97klfiyYeV7XfA2lNLnDCPMkUI+Qw5How==\", \"time\": 0, \"size\": 379152, \"metadata\": {\"url\": \"https://registry.npmjs.org/oxlint/-/oxlint-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "8ff2c0c17ae1549ac9ec7d41e55b317e1331a35c7084c954bef25b937441",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/76/8d"
+    },
     {
         "type": "inline",
         "contents": "55dc518ad4ed2a09b7c89ca41ae70c63b34d4aeb\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz\", \"integrity\": \"sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==\", \"time\": 0, \"size\": 2313, \"metadata\": {\"url\": \"https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -4270,18 +4294,18 @@
         "dest-filename": "0aaef637f012513ca7b7eca7959e6c40b888a50bbb93b50ab0809258813e",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/56/79"
     },
-    {
-        "type": "inline",
-        "contents": "57a8af8d3ba85b444c56b42d37e756457d224be5\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/electron/-/electron-45.0.0.tgz\", \"integrity\": \"sha512-yjz4uhMBcO6L5X7CWgRMobf2EMJPnb9j4zuf+nu/TU/6E4Sqfx7fn/a2eACo4qngjml/0JnsoZhxYroJLxLd2w==\", \"time\": 0, \"size\": 208744, \"metadata\": {\"url\": \"https://registry.npmjs.org/electron/-/electron-45.0.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "cc526362ce11b8f98bb66ee49eb0203d8b1cb92223a39028c55aefe9bc95",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/85/59"
-    },
     {
         "type": "inline",
         "contents": "586ef380d7bc535bcc2adb1d700dab73012b72c8\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz\", \"integrity\": \"sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==\", \"time\": 0, \"size\": 73972, \"metadata\": {\"url\": \"https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
         "dest-filename": "cbc6649f11de3ace7a33d2b87588072d82973673c2fe9cd893d6f5522dca",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/83/ee"
     },
+    {
+        "type": "inline",
+        "contents": "58e6d0c1be33f878332dd3a794a919e8d06994fe\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.90.0.tgz\", \"integrity\": \"sha512-s7JFKRkGS8O7i2ZVODfuO++NC7sH6HDqpMn8lYxw91w0SXJOxnAVjQ8utvmDwLMMT0jaSkuOKuUYJDGDtu4sHQ==\", \"time\": 0, \"size\": 6334084, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "a33ab2c5e2f364b87260df7b83bcaba601190a5aa1694e1a4616e532607c",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/84/36"
+    },
     {
         "type": "inline",
         "contents": "59235edf7a1e8614b263822c258c0cab9b63e42a\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@peculiar/webcrypto/-/webcrypto-1.7.1.tgz\", \"integrity\": \"sha512-ODOov0sGMJMf3jPonOkgGqPknTsu+DdQ7kD++gz8aI+aFMOMHFbWAA2taqXXVTdP+OTOQR/znGvSpmkeI0WTYQ==\", \"time\": 0, \"size\": 24482, \"metadata\": {\"url\": \"https://registry.npmjs.org/@peculiar/webcrypto/-/webcrypto-1.7.1.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -4312,12 +4336,6 @@
         "dest-filename": "1ab49e0883765a03dfb82a4ab3189fc482997b02db84778b7ecf8abaa279",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/e5/40"
     },
-    {
-        "type": "inline",
-        "contents": "5ae766c97c46dc92836c44a2ca4c861bc3e68754\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.89.0.tgz\", \"integrity\": \"sha512-hqjwIj5KOYM8Wjef/p7IruNi1iByLhSzbMBk62y22P/E8q7Jj0Pp+DeUTKTRYyZYCDtU1wEGlnWOnttHbyNIww==\", \"time\": 0, \"size\": 6385883, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "539667771f9af93db4ac5dcbf4b73c837b22b9892090d23989ebb7ca42b8",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/83/b7"
-    },
     {
         "type": "inline",
         "contents": "5b47f212fe504b3658e482fb881c82c2016419c3\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz\", \"integrity\": \"sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==\", \"time\": 0, \"size\": 9804, \"metadata\": {\"url\": \"https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -4420,12 +4438,6 @@
         "dest-filename": "5191a0c12d46dc1642126a7c79ac5b744e6f31560e96058cc7bf29781390",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/ab/d6"
     },
-    {
-        "type": "inline",
-        "contents": "64c647b3479fa13be393c3639146606bbcf834c5\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.89.0.tgz\", \"integrity\": \"sha512-fRxgNHvBLswj6MrhW2uBq5UDhPRQlCbHeq/Nf8yuG9zOxhDsXqX/mi2PX1axgsQxMm88el7HLiJAzglAnflYxw==\", \"time\": 0, \"size\": 5700337, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "ab3e70c65cb81b3faa2ea2f6fa67270f67a53b5254167f1d488fdbded19c",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/a9/c6"
-    },
     {
         "type": "inline",
         "contents": "64c7a3a0f94b9bddc92702fa72506dfaf25a7cc3\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz\", \"integrity\": \"sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==\", \"time\": 0, \"size\": 1654, \"metadata\": {\"url\": \"https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -4528,6 +4540,12 @@
         "dest-filename": "8879c3cd1412a0890461590276aa13d0344cb4e09494a4b3d854a7c7660a",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/34/f7"
     },
+    {
+        "type": "inline",
+        "contents": "6f0e7ac6056234d60cddba9266983b540d1e9829\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.90.0.tgz\", \"integrity\": \"sha512-30JiaFEBUB9peEOcvVM8ggo88SoN/IdSr9DW505JdBji/R6dM66gKEiG65hw6qcaF2f4mO0cEJ+RwRZprmun9g==\", \"time\": 0, \"size\": 5880580, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "42ae2aff710e939c63b01f87f6797d1b746f45f8456937a75f7f0939acb9",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/b4/fb"
+    },
     {
         "type": "inline",
         "contents": "6f827b3d1ebd0431d861176dbedafa02ff912cc3\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz\", \"integrity\": \"sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==\", \"time\": 0, \"size\": 1410652, \"metadata\": {\"url\": \"https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -4782,9 +4800,9 @@
     },
     {
         "type": "inline",
-        "contents": "81415774ceacee8fb8b44a9bc76d6272425f5ce5\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.89.0.tgz\", \"integrity\": \"sha512-iAQN3e6o9UgUCcdGwqRx/jYcKbG3HK7ur3rH6lTqVcQeNGZ85AeWIg6cgn/edwFQ0ofEZZItMwkzyCVTahnvEA==\", \"time\": 0, \"size\": 6331038, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "cac4f67cc1c788774d50e808960773110769081403bf62bff6e1972f46f3",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/bf/f0"
+        "contents": "81ce1aad5fc25cb576aa8803946f4ee8b4c681ad\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/electron/-/electron-45.1.0.tgz\", \"integrity\": \"sha512-i7qKVAh/KR5v1pf56NhGGX2QYHcdjvLgS7koL6ui50c+zUDGLRunR95nXcTpHPURKOQ4GDBG8BmXiDgOQ8DD0A==\", \"time\": 0, \"size\": 209684, \"metadata\": {\"url\": \"https://registry.npmjs.org/electron/-/electron-45.1.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "2b80efe8e1d90cbe7674450cbf819069cfbd30219a31f489c1d7db86f7bd",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/67/42"
     },
     {
         "type": "inline",
@@ -4876,12 +4894,6 @@
         "dest-filename": "9ab1c6f038ad7b494b6eb7a84c201472f144ba29a8eb15caea1b186a2f83",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/3a/62"
     },
-    {
-        "type": "inline",
-        "contents": "8b0b567abf681d2f17d077f566645824160c7464\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.89.0.tgz\", \"integrity\": \"sha512-eAjTkHSjAxrdCPJxO6y5sPQL5pYLKb2kvxZz9UU7tXnOZk9I/HLtkvx9S7GHY883k+AmL/eC7mqFt+w7WCwk0w==\", \"time\": 0, \"size\": 5934699, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "ca0e7e5eec91832d668c8b3ab3363572e467aede46895d7421f6f7fd4ffe",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/e4/b1"
-    },
     {
         "type": "inline",
         "contents": "8b0f4837a51e8bb8c44a5b81e1fdddb9cfa14aa6\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.3.tgz\", \"integrity\": \"sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ==\", \"time\": 0, \"size\": 1142922, \"metadata\": {\"url\": \"https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.3.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -4942,6 +4954,12 @@
         "dest-filename": "8a67a6a69c573e507dac8723fa56c0451c1ebb42aa08925c3bd37a8435c3",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/75/e3"
     },
+    {
+        "type": "inline",
+        "contents": "8e9916b5e2fb63c8877fc7f6e0c562c2d466c77f\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.90.0.tgz\", \"integrity\": \"sha512-+x42rDHQGbTCuT3EzpWAzhP3NoVPE/cJsG4gnrakOSg0olV+GCdMpPU23Nvrl3zZMnXxFZdTtDv4D3SuaA5ZeQ==\", \"time\": 0, \"size\": 5591585, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "f7eb932bf01ed5500c01c4a90b9f77c53fb714d48833a2ac1bcd8b6a5433",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/16/dd"
+    },
     {
         "type": "inline",
         "contents": "8f498db3c301f6f442fccce923dbf96a93ff776f\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/plist/-/plist-3.1.0.tgz\", \"integrity\": \"sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==\", \"time\": 0, \"size\": 145420, \"metadata\": {\"url\": \"https://registry.npmjs.org/plist/-/plist-3.1.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5032,6 +5050,12 @@
         "dest-filename": "ea55e4e584609a1f0ba14a730391c0b04141931864f08f4172886bec44f9",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/ab/7c"
     },
+    {
+        "type": "inline",
+        "contents": "93de1e31973ecb9fcd66602260ffe099a498e8ee\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.90.0.tgz\", \"integrity\": \"sha512-RcKhz1ETMq+fazE9TKS2+5NIRGwigm/nW8egqF0LI+A8Yw2iW5r0E/C3XAPRiwIm/vcPiutIRIa6IQCIKhZsTQ==\", \"time\": 0, \"size\": 6036349, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "f393c445e3fcb8b8e481be733c5f491761902303c25ca995f63138d6897e",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/d5/4c"
+    },
     {
         "type": "inline",
         "contents": "94b8d6a4c5f1545ef6e579d9f7fde82cc95af232\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz\", \"integrity\": \"sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==\", \"time\": 0, \"size\": 3756, \"metadata\": {\"url\": \"https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5044,12 +5068,6 @@
         "dest-filename": "a226542737e4671ba53cd16b801e1e25dc408658da27fed7c7d9efdee475",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/ec/bd"
     },
-    {
-        "type": "inline",
-        "contents": "96129f3e6cac21759a6e4229ac8da16e8af406d3\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.89.0.tgz\", \"integrity\": \"sha512-vfffe8mQ484AzVadlUOFpgL+JDwhvs9hrzxTgQP1FVfi4ZEUUYeffXlzC9dFV7Dgnu5s/KrNKvfmG6HxBd/ISQ==\", \"time\": 0, \"size\": 6013925, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "04c1119c1aef5963441472ef05429238e837bae61c270f004cdbe8e51d48",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/eb/91"
-    },
     {
         "type": "inline",
         "contents": "9654fcdde73e24dcc9d5ded221cb4a7e4e55a73b\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001819.tgz\", \"integrity\": \"sha512-LFUqIIAwpzsIuevnKnsR9qnStBcgzPShTX61lBwN9uFkkf8o8zLiebEjbW8AYtZiF+1YKDWfdt/pWDtMuG8Xwg==\", \"time\": 0, \"size\": 349323, \"metadata\": {\"url\": \"https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001819.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5062,6 +5080,12 @@
         "dest-filename": "f72ca78510367cd14d8e5a1b6cf300fe4a58e7e28d7f696a7f9fcfb8395f",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/09/b7"
     },
+    {
+        "type": "inline",
+        "contents": "97f3a346808e33cc988ccfcea7f89b640d38a894\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.90.0.tgz\", \"integrity\": \"sha512-/aZoXnL5WBLCXuzfHqvEFXcm4iwYmr/cYByHDTXzLFzJdE5DC7bm6phpWqHv6BeqpVgY9IpBAxGDv2WEkl5JCg==\", \"time\": 0, \"size\": 6346568, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "9d067e4837fdbe16afa230622bf6a6769817efdd1d74430b95dbbcbe24ba",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/0b/bc"
+    },
     {
         "type": "inline",
         "contents": "988c93cd389e354cc0d5d850c56085e3e1e2b8b2\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz\", \"integrity\": \"sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==\", \"time\": 0, \"size\": 6834015, \"metadata\": {\"url\": \"https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5176,6 +5200,12 @@
         "dest-filename": "f7d95a8e3571758f8b5d095a21909a8f6cdfe7fd2349f7f72b2801eef079",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/ba/d5"
     },
+    {
+        "type": "inline",
+        "contents": "a1748a28d2e12e73beb5c5d5e4265b79b19ce3cb\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.90.0.tgz\", \"integrity\": \"sha512-zhxH78eP2nR6/pGdhBc7MIfjhhcgATeu8fkmkFJbuzfk6Cj0FzBxyEhL85yDqrCybjx+G2YDzZGsxIO9kvO4Iw==\", \"time\": 0, \"size\": 5697956, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "e85cb10e62a8bd41b2f130ead84f05dbc4fc9af8ce79499dbb20952f86c4",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/ae/95"
+    },
     {
         "type": "inline",
         "contents": "a1898018ce183e4d9f6886d5a671cb07477cee89\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz\", \"integrity\": \"sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==\", \"time\": 0, \"size\": 7371, \"metadata\": {\"url\": \"https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5260,12 +5290,6 @@
         "dest-filename": "936a1a6b862b9bf76e7bc62b3af6e5fc5e8bcc38116b9d011e890cd8a86a",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/f1/3d"
     },
-    {
-        "type": "inline",
-        "contents": "a4e186998a3a6cac18d7dd800659e5aec8dcc450\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.89.0.tgz\", \"integrity\": \"sha512-Pflpba5F3gRAQ12sWglRxvWTHEdAusNDvmi4Y5N1T5SY1AGkM7AixOnET8qkrnLJ/F32qAlNokO6eCknT8tmnw==\", \"time\": 0, \"size\": 5048363, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "3a9d68929cee6eaf513464585b264d707f1ad1af78804b1d62580bcf68aa",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/e7/8e"
-    },
     {
         "type": "inline",
         "contents": "a4e302a96332d176614e0d0cebed06805008297e\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@electron/asar/-/asar-3.4.1.tgz\", \"integrity\": \"sha512-i4/rNPRS84t0vSRa2HorerGRXWyF4vThfHesw0dmcWHp+cspK743UanA0suA5Q5y8kzY2y6YKrvbIUn69BCAiA==\", \"time\": 0, \"size\": 25591, \"metadata\": {\"url\": \"https://registry.npmjs.org/@electron/asar/-/asar-3.4.1.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5296,6 +5320,12 @@
         "dest-filename": "fe34e86449b27a938bd4a20bff5470f22e6d63f9809807f7539b7b84a7d2",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/4a/43"
     },
+    {
+        "type": "inline",
+        "contents": "a705e5552b872a3e9902e58c78ec40362e10e295\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.90.0.tgz\", \"integrity\": \"sha512-sgfalb1HuxYjiAa4wESZ626z1FGusqNcXYHyB5oIOEprS2sbPg0UYEfo83uF1GNG70DIfZxHkXuE6KFrlSdn8Q==\", \"time\": 0, \"size\": 5064340, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "e30555acfb52089654237784b108261c372fa337dcede79ef53a3544379c",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/c0/76"
+    },
     {
         "type": "inline",
         "contents": "a77dc4f36db035b4739642c20c8adff108f378c9\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/react/-/react-19.3.1.tgz\", \"integrity\": \"sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==\", \"time\": 0, \"size\": 26394, \"metadata\": {\"url\": \"https://registry.npmjs.org/react/-/react-19.3.1.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5332,12 +5362,6 @@
         "dest-filename": "438e07ca3052f7665f29e4ad20fb3c8babd18c56606d133cf27b7de4a35c",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/4a/bf"
     },
-    {
-        "type": "inline",
-        "contents": "aac1b22543b3f732842827d7c931baf91e4e9d3b\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.89.0.tgz\", \"integrity\": \"sha512-v9ENzHvwrQoYSWTtviH1pOYc7R9UovDxVofnck50cNmPihRRTcrg5X0UlRbLOZ7IVtxPOlh2hb7kDO+FpE8SfQ==\", \"time\": 0, \"size\": 6023743, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "3d045b2506c177e1cce26f1000a2fdce916693cbb6cf5a6adc2d8d0017bf",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/02/bc"
-    },
     {
         "type": "inline",
         "contents": "ab07e82d2dbf1e8335d08c667924e00504d8a9bb\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz\", \"integrity\": \"sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==\", \"time\": 0, \"size\": 5266, \"metadata\": {\"url\": \"https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5410,12 +5434,6 @@
         "dest-filename": "bdfa5ddf727069eac8a23761bb83e0befe6e18626e3b77a96a8fa8ef4d38",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/0e/b2"
     },
-    {
-        "type": "inline",
-        "contents": "b344e69707c5a763c45916408b270d30a7ce5cee\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.89.0.tgz\", \"integrity\": \"sha512-dYmyD1x7LaPlb79vZWUcpTShk8dI9z1I+IubtqrBxWNJaDhQdPHwcsvg7q5StTU4xWyd9AwPfLaTYFZY8NZgtQ==\", \"time\": 0, \"size\": 6022789, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "c4d07873c14691b1823cdad658e6b47d104cdff6fed6b23a20955b755ab2",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/77/7c"
-    },
     {
         "type": "inline",
         "contents": "b3867782eee3da7d53505bbb6847faaa9a5924ee\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/pump/-/pump-3.0.4.tgz\", \"integrity\": \"sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==\", \"time\": 0, \"size\": 3806, \"metadata\": {\"url\": \"https://registry.npmjs.org/pump/-/pump-3.0.4.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5530,6 +5548,12 @@
         "dest-filename": "a105e3f3b6ccfc2beed11576834b20e4729aec847effbde4599b6860802b",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/30/db"
     },
+    {
+        "type": "inline",
+        "contents": "c26af8b1c0ceea6c76a054b6323dae40ac7c7e89\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.90.0.tgz\", \"integrity\": \"sha512-OLbU9qsrV2Q8QxT2OEzOPdO8zCCpyI8qB+hDI8yr6RsYELtkf0FAZhJdfjM/RnLHKzt44HWwAPnk92vBtKofvw==\", \"time\": 0, \"size\": 5946785, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "b2201ef7d8f41c82f08a72c891f46110b0f3dee7f79e513eb3de6ff18721",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/cb/4a"
+    },
     {
         "type": "inline",
         "contents": "c2a2aaf04639112e3420b6ae6b4c479b72b0c974\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz\", \"integrity\": \"sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==\", \"time\": 0, \"size\": 3421578, \"metadata\": {\"url\": \"https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5578,12 +5602,6 @@
         "dest-filename": "51151580349c403e9dfbbdd5e40201a21b074f7cdf8417861f9ee32280c4",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/93/1e"
     },
-    {
-        "type": "inline",
-        "contents": "c59f51129f031b87e3f78324369e7b7b73428e91\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/lucide-react/-/lucide-react-1.61.0.tgz\", \"integrity\": \"sha512-v2SQPPPNjnr+BlhL9Spuzmo5yR+hLkftfuE4E3jaxdNPgSH0hJKPcLJBP7yAta87jQNPsSERS59PJjCJ/CorBA==\", \"time\": 0, \"size\": 3177974, \"metadata\": {\"url\": \"https://registry.npmjs.org/lucide-react/-/lucide-react-1.61.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "84e3e220555ce93f6db2ca2cb5cdb45e926e0af477e29d28f795e09864c2",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/33/ed"
-    },
     {
         "type": "inline",
         "contents": "c5afc2fc15efcac8fffd79449e4fb03aad38d40b\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/utf8-byte-length/-/utf8-byte-length-1.0.5.tgz\", \"integrity\": \"sha512-Xn0w3MtiQ6zoz2vFyUVruaCL53O/DwUvkEeOvj+uulMm0BkUGYWmBYVyElqZaSLhY6ZD0ulfU3aBra2aVT4xfA==\", \"time\": 0, \"size\": 3003, \"metadata\": {\"url\": \"https://registry.npmjs.org/utf8-byte-length/-/utf8-byte-length-1.0.5.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5614,12 +5632,6 @@
         "dest-filename": "4ead7ee719c83964143f0cf588e2b7cdd8a117c7ac5b02cc8a433c10d703",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/cb/0e"
     },
-    {
-        "type": "inline",
-        "contents": "c85fd350da208e3e4da27d4da6611c4b9e0f5e47\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.89.0.tgz\", \"integrity\": \"sha512-saFy07cO94E664glwgLmKLI40HgTL1PY86y4T6+ud4niX4H0Kdqjcmqmjps7mQNdBytV5guGbXDdyQtRfeLbLA==\", \"time\": 0, \"size\": 5574162, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "21f6c07612ddbdc82443d018accbdb6ecef5b0757a3df6b18d77af281ee1",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/f0/06"
-    },
     {
         "type": "inline",
         "contents": "c8a5706006c7272b34109041e53fbf4865386e30\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz\", \"integrity\": \"sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==\", \"time\": 0, \"size\": 11577, \"metadata\": {\"url\": \"https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5692,12 +5704,6 @@
         "dest-filename": "c662626ec8eafafa54476678b9f71799a74ee368f2b7845a6ec9f9174a4d",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/f2/1f"
     },
-    {
-        "type": "inline",
-        "contents": "cd97bf96ade0491c982234acae3e9ab46210a704\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.89.0.tgz\", \"integrity\": \"sha512-Buonlp4hVS7RGNP5M7bPpGNQrenyzA2C64JcO/oz9C1c6dGOXJ7VEAnaiAMY7voou0JYyCJdvDVlFQc5DZX3DQ==\", \"time\": 0, \"size\": 7414004, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "d5cb05748b06b8e9565e69cd96a9820d82f40a1d0f667d80fc5fa7fe5b50",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/58/00"
-    },
     {
         "type": "inline",
         "contents": "ce0190e6df90ccc1a9357350e6cd69fb98d27da8\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz\", \"integrity\": \"sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==\", \"time\": 0, \"size\": 6067, \"metadata\": {\"url\": \"https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5716,12 +5722,6 @@
         "dest-filename": "c03134d3b6216050d19cb8276cd28d5ae942c859d0bc3758b53face0594c",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/cf/bb"
     },
-    {
-        "type": "inline",
-        "contents": "cf37e8cc9131bf339a4cdb8dfd709f8464fa4969\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.89.0.tgz\", \"integrity\": \"sha512-OTFEvi9W+JczaZD1Caj17SGCoW8H7TE+fvx0D7ATEWa1Lohn91UMxFQ6r145SiGy/yCxeIwptMys/RAM7gSVSQ==\", \"time\": 0, \"size\": 5677375, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "3de516e8e25c1beeda4f5b493f3b01b21024fdf476de8716b8bd11d41c9e",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/c4/48"
-    },
     {
         "type": "inline",
         "contents": "cfcbabf6eb8e12f4219143ac261291e022381411\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz\", \"integrity\": \"sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==\", \"time\": 0, \"size\": 227545, \"metadata\": {\"url\": \"https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5818,6 +5818,12 @@
         "dest-filename": "43b89d1c15ce8a3c5d1add3132f3c3d0fc8ae221a195e331cb84d785ed88",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/aa/65"
     },
+    {
+        "type": "inline",
+        "contents": "d7eed0e684427366906ba2f6fa4d3c0ae750c148\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.90.0.tgz\", \"integrity\": \"sha512-PSrxMvP6mx+p1karZcUxLdy9lpaP+JWQPti4al9FgTaPhxE+pT/BjhGExloVVSWgZgIfOlLOjVyyq8BXlodhLQ==\", \"time\": 0, \"size\": 5559967, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "91761b1bfa20535e7d482763c90404fa1d58845199bf2e3a6efa10b54b66",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/42/51"
+    },
     {
         "type": "inline",
         "contents": "d7f65475b438093e8952272a9fe0d5ca6db26942\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz\", \"integrity\": \"sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==\", \"time\": 0, \"size\": 2638, \"metadata\": {\"url\": \"https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -5998,12 +6004,6 @@
         "dest-filename": "72adca232a03beb43a8b72dac70aea04b97a0bf6b9fefbbe65e78ce2ab06",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/93/09"
     },
-    {
-        "type": "inline",
-        "contents": "e64ecfe0a346c352b4382cfff5300d27f264ce98\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.89.0.tgz\", \"integrity\": \"sha512-Z/oxOPiIqiS7fItRdxaaOEC+6GD3OpGi0IxoR0dMefzQHolsKLzScw2DNcu/5gUPok3tv+G9mslvYB5bo3i0qg==\", \"time\": 0, \"size\": 5546683, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "4a9388644b069d4a8700e3a40f4bed4b9e2b57b4349c0fcf6aaf3d89fd9c",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/8b/e9"
-    },
     {
         "type": "inline",
         "contents": "e6b4f5680bc5ef3590e72095689a92be9b3eedf1\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz\", \"integrity\": \"sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==\", \"time\": 0, \"size\": 3429085, \"metadata\": {\"url\": \"https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -6106,6 +6106,18 @@
         "dest-filename": "ec73cb10b2f32d6e39ab917041d3bb996ae7791a73f4dfdfe4d81b144894",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/5e/1e"
     },
+    {
+        "type": "inline",
+        "contents": "ef87e6abfbb9dfeb7276686437570f6f0b1cbcf2\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.90.0.tgz\", \"integrity\": \"sha512-SMhk7ozwoxYDKfYqGZCQEfULOKDneF9uhaoIf2neoDLWvNtjY9yVeL7YHmE5L9WdKvMpWNwwZxhenxBu6AgfOg==\", \"time\": 0, \"size\": 6046202, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "f70d3be5b36a797830f81cb9e2767d1548ff943b2007738dd1c3ea7d478a",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/10/cc"
+    },
+    {
+        "type": "inline",
+        "contents": "efccd4b6528e1487ecd16b9b9a620efad0fb43fe\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.90.0.tgz\", \"integrity\": \"sha512-FRywfn+MoKn8xpBSzgNwNVliSKRI2QXkxi/iF7o6FEQs8Bh8z2RpVTaFAcO3pchXjvB2eGNFIoLLQABIQ+u7VA==\", \"time\": 0, \"size\": 7422975, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.90.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
+        "dest-filename": "1f007ef4b2ca5369705c214ee1b7bfa561e35c80ffcce34ecbb37a0b6c4e",
+        "dest": "flatpak-node/npm-cache/_cacache/index-v5/76/9c"
+    },
     {
         "type": "inline",
         "contents": "f1083394f1c7ac7e42b46a1f625f1b28f779b75c\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz\", \"integrity\": \"sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==\", \"time\": 0, \"size\": 3294, \"metadata\": {\"url\": \"https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -6232,12 +6244,6 @@
         "dest-filename": "4bfc45edf23b391d38ade0404c82bcaff9c533e9439737ddd2ee71dec344",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/fb/07"
     },
-    {
-        "type": "inline",
-        "contents": "fbb05e2031e9b07b81d19aa75709924854c40424\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.89.0.tgz\", \"integrity\": \"sha512-fRQQsKUGShdEL5Fl9o9uhj3grkZbeXKLv0icQ5tspUCNYSDy8wzzEcP1WC2bKdTQ0rSszbKlO3iiHORxV22DLg==\", \"time\": 0, \"size\": 6315884, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "9f413cd4dc77404ed72c746e7e5213e8ffac92efb62240a2c5a9c94a0286",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/aa/89"
-    },
     {
         "type": "inline",
         "contents": "fc1beb25b4ec3568f3f97849a16f14d629543639\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz\", \"integrity\": \"sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==\", \"time\": 0, \"size\": 6656, \"metadata\": {\"url\": \"https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -6268,12 +6274,6 @@
         "dest-filename": "4bf03fefa3636b0b7dd4fca36f1a16887620d5b02638e2e348b43ed7c180",
         "dest": "flatpak-node/npm-cache/_cacache/index-v5/1d/1c"
     },
-    {
-        "type": "inline",
-        "contents": "fecbbacde2a53d078a8b19610de80988de8be92e\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.89.0.tgz\", \"integrity\": \"sha512-dEtYjIy6+fHcjKklsmtmMkZRhwHr2UbzjmpvuPtQYSeN9awQ2hx5JLms5Wvri+8P/NZtD8v5hfgHALUql+/Ycg==\", \"time\": 0, \"size\": 6640645, \"metadata\": {\"url\": \"https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.89.0.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
-        "dest-filename": "6d5c6a9c2264d10910836a7867dee1030191c409b1924cf0620ffbe05d6f",
-        "dest": "flatpak-node/npm-cache/_cacache/index-v5/0d/15"
-    },
     {
         "type": "inline",
         "contents": "ff5b89a7df152a16323c20e9901af813fdd1888a\t{\"key\": \"make-fetch-happen:request-cache:https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz\", \"integrity\": \"sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==\", \"time\": 0, \"size\": 3722, \"metadata\": {\"url\": \"https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz\", \"reqHeaders\": {}, \"resHeaders\": {}}}",
@@ -6334,16 +6334,16 @@
     {
         "type": "shell",
         "commands": [
-            "mkdir -p \"f22ed746d6afe4413723c1ec95408e33d6635bf7d817a70edb1df9220a236ab0\"",
-            "ln -s \"../SHASUMS256.txt-45.0.0\" \"f22ed746d6afe4413723c1ec95408e33d6635bf7d817a70edb1df9220a236ab0/SHASUMS256.txt\""
+            "mkdir -p \"aaf6f0d50457ca990261d018944055084f99ff44386590983c0cfac6a979c69d\"",
+            "ln -s \"../SHASUMS256.txt-45.1.0\" \"aaf6f0d50457ca990261d018944055084f99ff44386590983c0cfac6a979c69d/SHASUMS256.txt\""
         ],
         "dest": "flatpak-node/cache/electron"
     },
     {
         "type": "shell",
         "commands": [
-            "mkdir -p \"f22ed746d6afe4413723c1ec95408e33d6635bf7d817a70edb1df9220a236ab0\"",
-            "ln -s \"../electron-v45.0.0-linux-arm64.zip\" \"f22ed746d6afe4413723c1ec95408e33d6635bf7d817a70edb1df9220a236ab0/electron-v45.0.0-linux-arm64.zip\""
+            "mkdir -p \"aaf6f0d50457ca990261d018944055084f99ff44386590983c0cfac6a979c69d\"",
+            "ln -s \"../electron-v45.1.0-linux-arm64.zip\" \"aaf6f0d50457ca990261d018944055084f99ff44386590983c0cfac6a979c69d/electron-v45.1.0-linux-arm64.zip\""
         ],
         "dest": "flatpak-node/cache/electron",
         "only-arches": [
@@ -6353,8 +6353,8 @@
     {
         "type": "shell",
         "commands": [
-            "mkdir -p \"f22ed746d6afe4413723c1ec95408e33d6635bf7d817a70edb1df9220a236ab0\"",
-            "ln -s \"../electron-v45.0.0-linux-x64.zip\" \"f22ed746d6afe4413723c1ec95408e33d6635bf7d817a70edb1df9220a236ab0/electron-v45.0.0-linux-x64.zip\""
+            "mkdir -p \"aaf6f0d50457ca990261d018944055084f99ff44386590983c0cfac6a979c69d\"",
+            "ln -s \"../electron-v45.1.0-linux-x64.zip\" \"aaf6f0d50457ca990261d018944055084f99ff44386590983c0cfac6a979c69d/electron-v45.1.0-linux-x64.zip\""
         ],
         "dest": "flatpak-node/cache/electron",
         "only-arches": [
@@ -6364,8 +6364,8 @@
     {
         "type": "shell",
         "commands": [
-            "mkdir -p \"httpsgithub.comelectronelectronreleasesdownloadv45.0.0electron-v45.0.0-linux-arm64.zip\"",
-            "ln -s \"../electron-v45.0.0-linux-arm64.zip\" \"httpsgithub.comelectronelectronreleasesdownloadv45.0.0electron-v45.0.0-linux-arm64.zip/electron-v45.0.0-linux-arm64.zip\""
+            "mkdir -p \"httpsgithub.comelectronelectronreleasesdownloadv45.1.0electron-v45.1.0-linux-arm64.zip\"",
+            "ln -s \"../electron-v45.1.0-linux-arm64.zip\" \"httpsgithub.comelectronelectronreleasesdownloadv45.1.0electron-v45.1.0-linux-arm64.zip/electron-v45.1.0-linux-arm64.zip\""
         ],
         "dest": "flatpak-node/cache/electron",
         "only-arches": [
@@ -6375,8 +6375,8 @@
     {
         "type": "shell",
         "commands": [
-            "mkdir -p \"httpsgithub.comelectronelectronreleasesdownloadv45.0.0electron-v45.0.0-linux-x64.zip\"",
-            "ln -s \"../electron-v45.0.0-linux-x64.zip\" \"httpsgithub.comelectronelectronreleasesdownloadv45.0.0electron-v45.0.0-linux-x64.zip/electron-v45.0.0-linux-x64.zip\""
+            "mkdir -p \"httpsgithub.comelectronelectronreleasesdownloadv45.1.0electron-v45.1.0-linux-x64.zip\"",
+            "ln -s \"../electron-v45.1.0-linux-x64.zip\" \"httpsgithub.comelectronelectronreleasesdownloadv45.1.0electron-v45.1.0-linux-x64.zip/electron-v45.1.0-linux-x64.zip\""
         ],
         "dest": "flatpak-node/cache/electron",
         "only-arches": [

+ 7 - 5
packaging/flathub/io.github.WallpaperEngineLover.we_manager.yml

@@ -208,12 +208,13 @@ modules:
     sources:
       - type: git
         url: https://github.com/WallpaperEngineLover/linux-wallpaperengine-kde.git
-        commit: 85ebc97f0114a9a248b5c8ef8eec9d4aab5b31a5
+        tag: v0.9.9
+        commit: 4ccdfaf3cf11e18c01c23522089d0d9993c33506
       - type: file
-        url: https://cef-builds.spotifycdn.com/cef_binary_146.0.11%2Bg3a0fcf1%2Bchromium-146.0.7680.179_linux64_minimal.tar.bz2
-        sha256: 4320d0a18a8d7fbae1e2539030a9315094b34af8a2000999ad8caa7befda7625
+        url: https://cef-builds.spotifycdn.com/cef_binary_156.0.14%2Bg4fa4ab5%2Bchromium-156.0.8078.48_linux64_minimal.tar.bz2
+        sha256: 4191ac920a91a052eba04afb6ed830d47aed46a3e246c434a2f062c23588dc8a
         dest: cef-archive
-        dest-filename: cef_binary_146.0.11+g3a0fcf1+chromium-146.0.7680.179_linux64_minimal.tar.bz2
+        dest-filename: cef_binary_156.0.14+g4fa4ab5+chromium-156.0.8078.48_linux64_minimal.tar.bz2
 
   - name: we-manager
     buildsystem: simple
@@ -247,7 +248,8 @@ modules:
     sources:
       - type: git
         url: https://github.com/WallpaperEngineLover/we_manager.git
-        commit: 33dd52c33472d89f12636b3cef5ba9c22bfac407
+        tag: v0.9.9
+        commit: e2f20e91f601b0b09e7583ea9a18314d372d776a
       - generated-sources.json
       - type: git
         url: https://github.com/Noxime/steamworks-rs.git

+ 3 - 0
packaging/flatpak/io.github.WallpaperEngineLover.we_manager.metainfo.xml

@@ -78,6 +78,9 @@
     <content_attribute id="social-info">mild</content_attribute>
   </content_rating>
   <releases>
+    <release version="0.9.10" date="2026-11-01" />
+    <release version="0.9.9" date="2026-10-31" />
+    <release version="0.9.8" date="2026-10-28" />
     <release version="0.9.3" date="2026-10-21" />
     <release version="0.8.1" date="2026-10-09" />
   </releases>

+ 21 - 0
packaging/rpm/build-local.sh

@@ -0,0 +1,21 @@
+#!/bin/sh
+# build-local.sh: builds the rpm from the .deb in dist/ the way the CI job does; run `npm run dist:linux` first.
+# The rpm ends up in dist/.
+
+set -e
+root=$(cd "$(dirname "$0")/../.." && pwd)
+version=$(node -p "require('$root/package.json').version")
+deb="$root/dist/we-manager_${version}_amd64.deb"
+[ -f "$deb" ] || { echo "$deb not found, run npm run dist:linux first" >&2; exit 1; }
+command -v rpmbuild >/dev/null || { echo "rpmbuild is not installed" >&2; exit 1; }
+
+top=$(mktemp -d)
+trap 'rm -rf "$top"' EXIT
+mkdir -p "$top/SOURCES"
+cp "$deb" "$top/SOURCES/"
+sed "s/^Version:.*/Version:        $(echo "$version" | tr - '~')/; s/^%global upstream_version .*/%global upstream_version $version/" \
+  "$root/packaging/rpm/we-manager.spec" > "$top/we-manager.spec"
+
+rpmbuild -bb --define "_topdir $top" --define "_build_id_links none" "$top/we-manager.spec"
+cp "$top"/RPMS/x86_64/*.rpm "$root/dist/"
+ls -l "$root"/dist/*.rpm

+ 6 - 3
src/main/index.ts

@@ -16,6 +16,7 @@ import { checkEarlierRunEngines, blockLaunches, killAllLweProcesses, getLweStatu
 import { cancelRestore, expandScreen, getDisplayTargets, initDisplay, restoreAssignedWallpapers } from './services/display.service'
 import { mergeSkipScreens } from './services/restore-plan'
 import { initSchedule, takeCatchUp } from './services/schedule.service'
+import { initAppRules } from './services/app-rules.service'
 import { initUpdates } from './services/update.service'
 import { detectDesktopEnv, hasStatusNotifierHost } from './utils/platform'
 import { needsSoftwareCompositing, readGpuVendors } from './utils/gpuWorkaround'
@@ -33,7 +34,7 @@ if (needsSoftwareCompositing(detectDesktopEnv(), process.env.WAYLAND_DISPLAY, re
 }
 
 // fetch() for GIF still frames in PreviewImage.tsx
-protocol.registerSchemesAsPrivileged([{ scheme: 'wallpaper', privileges: { supportFetchAPI: true, corsEnabled: true } }])
+protocol.registerSchemesAsPrivileged([{ scheme: 'wallpaper', privileges: { supportFetchAPI: true, corsEnabled: true, stream: true } }])
 let isQuitting = false
 let hasKilledLweOnQuit = false
 
@@ -220,7 +221,8 @@ app.whenReady().then(async () => {
     }
 
     try {
-      const res = await net.fetch(pathToFileURL(filePath).toString())
+      const range = request.headers.get('range')
+      const res = await net.fetch(pathToFileURL(filePath).toString(), range ? { headers: { range } } : undefined)
       const headers = new Headers(res.headers)
       headers.set('Access-Control-Allow-Origin', '*')
       return new Response(res.body, { status: res.status, headers })
@@ -241,8 +243,8 @@ app.whenReady().then(async () => {
   registerAllHandlers(win)
   startWatcher(win)
   startBackgroundSync(win)
-  initDesktopIcons()
   await checkEarlierRunEngines()
+  initDesktopIcons()
   initDisplay(win)
   const resumed = initPlaylistPlayer(win)
   const targets = getDisplayTargets()
@@ -264,6 +266,7 @@ app.whenReady().then(async () => {
   const catchUp = takeCatchUp()
   const scheduleScreens = catchUp.flatMap((rule) => expandScreen(rule.screen, targets))
   initSchedule(win, catchUp)
+  initAppRules(win)
   initUpdates(win)
 
   const playlistScreens = playlistRestoreSkipScreens().flatMap((screen) => expandScreen(screen, targets))

+ 49 - 0
src/main/ipc/app-rules.handlers.ts

@@ -0,0 +1,49 @@
+import { ipcMain } from 'electron'
+import { IpcChannels } from '@shared/ipc-channels'
+import type { AppRule } from '@shared/types'
+import { deleteAppRule, getActiveRuleIds, getAppRules, saveAppRule } from '../services/app-rules.service'
+import { captureProfile, deleteProfile, getProfiles } from '../services/profile.service'
+import { isAudioDetectionAvailable } from '../utils/audio-activity'
+import { applyProfile } from '../services/rule-actions.service'
+import { getScheduleRules, saveScheduleRule } from '../services/schedule.service'
+
+export function registerAppRuleHandlers(): void {
+  ipcMain.handle(IpcChannels.APP_RULES_GET_ALL, () => getAppRules())
+
+  ipcMain.handle(IpcChannels.APP_RULES_SAVE, (_e, rule: Omit<AppRule, 'id'> & { id?: string }) => saveAppRule(rule))
+
+  ipcMain.handle(IpcChannels.APP_RULES_DELETE, (_e, id: string) => {
+    deleteAppRule(id)
+    return { ok: true }
+  })
+
+  ipcMain.handle(IpcChannels.APP_RULES_ACTIVE, () => getActiveRuleIds())
+
+  ipcMain.handle(IpcChannels.APP_RULES_AUDIO_AVAILABLE, () => isAudioDetectionAvailable())
+
+  ipcMain.handle(IpcChannels.PROFILES_GET_ALL, () => getProfiles())
+
+  ipcMain.handle(IpcChannels.PROFILES_CAPTURE, (_e, name: string) => captureProfile(name))
+
+  ipcMain.handle(IpcChannels.PROFILES_DELETE, (_e, id: string) => {
+    // rules that load the profile would only fail from now on
+    let disabled = 0
+    for (const rule of getAppRules()) {
+      if (!rule.enabled || rule.action.type !== 'profile' || rule.action.profileId !== id) continue
+      saveAppRule({ ...rule, enabled: false })
+      disabled++
+    }
+    for (const rule of getScheduleRules()) {
+      if (!rule.enabled || rule.action.type !== 'profile' || rule.action.profileId !== id) continue
+      saveScheduleRule({ ...rule, enabled: false })
+      disabled++
+    }
+    deleteProfile(id)
+    return { ok: true, disabled }
+  })
+
+  ipcMain.handle(IpcChannels.PROFILES_APPLY, async (_e, id: string) => {
+    await applyProfile(id)
+    return { ok: true }
+  })
+}

+ 16 - 0
src/main/ipc/config.handlers.ts

@@ -44,6 +44,10 @@ import {
   setSkipPlaylistResume,
   getFreshProcessOnPathChange,
   setFreshProcessOnPathChange,
+  getStopPlaylistsOnKillAll,
+  setStopPlaylistsOnKillAll,
+  getForgetOnKillAll,
+  setForgetOnKillAll,
   getCardBorders,
   getCardBadges,
   getAppearance,
@@ -129,6 +133,8 @@ export function registerConfigHandlers(): void {
     killLweOnQuit: getKillLweOnQuit(),
     skipPlaylistResume: getSkipPlaylistResume(),
     freshProcessOnPathChange: getFreshProcessOnPathChange(),
+    stopPlaylistsOnKillAll: getStopPlaylistsOnKillAll(),
+    forgetOnKillAll: getForgetOnKillAll(),
     cardBorders: getCardBorders(),
     cardBadges: getCardBadges(),
     audioScreen: getAudioScreen(),
@@ -192,6 +198,16 @@ export function registerConfigHandlers(): void {
     return { ok: true }
   })
 
+  ipcMain.handle(IpcChannels.CONFIG_SET_STOP_PLAYLISTS_ON_KILL_ALL, (_e, enabled: boolean) => {
+    setStopPlaylistsOnKillAll(enabled)
+    return { ok: true }
+  })
+
+  ipcMain.handle(IpcChannels.CONFIG_SET_FORGET_ON_KILL_ALL, (_e, enabled: boolean) => {
+    setForgetOnKillAll(enabled)
+    return { ok: true }
+  })
+
   ipcMain.handle(IpcChannels.CONFIG_SET_CARD_BORDERS, (_e, borders: CardBorders) => {
     return setCardBorders(borders)
   })

+ 8 - 1
src/main/ipc/desktop-icons.handlers.ts

@@ -1,6 +1,6 @@
 import { ipcMain } from 'electron'
 import { IpcChannels } from '@shared/ipc-channels'
-import { setDesktopIconsEnabled, getDesktopIconsEnabled, getDesktopIconsStatus, installDesktopIconsDependencies } from '../services/desktop-icons.service'
+import { setDesktopIconsEnabled, getDesktopIconsEnabled, setDesktopIconsAuto, getDesktopIconsAuto, getDesktopIconsStatus, installDesktopIconsDependencies } from '../services/desktop-icons.service'
 
 export function registerDesktopIconsHandlers(): void {
   ipcMain.handle(IpcChannels.DESKTOP_ICONS_SET_ENABLED, (_e, enabled: boolean) => {
@@ -8,6 +8,13 @@ export function registerDesktopIconsHandlers(): void {
     return { ok: true, enabled }
   })
 
+  ipcMain.handle(IpcChannels.DESKTOP_ICONS_SET_AUTO, (_e, auto: boolean) => {
+    setDesktopIconsAuto(auto)
+    return { ok: true }
+  })
+
+  ipcMain.handle(IpcChannels.DESKTOP_ICONS_GET_AUTO, () => getDesktopIconsAuto())
+
   ipcMain.handle(IpcChannels.DESKTOP_ICONS_GET_STATUS, () => getDesktopIconsStatus())
 
   ipcMain.handle(IpcChannels.DESKTOP_ICONS_INSTALL_DEPS, () => installDesktopIconsDependencies())

+ 4 - 0
src/main/ipc/index.ts

@@ -10,7 +10,9 @@ import { registerLweHandlers } from './lwe.handlers'
 import { registerDesktopIconsHandlers } from './desktop-icons.handlers'
 import { registerGnomeExtensionHandlers } from './gnome-extension.handlers'
 import { registerBackupHandlers } from './backup.handlers'
+import { registerVideoToolsHandlers } from './video-tools.handlers'
 import { registerPlaylistHandlers } from './playlist.handlers'
+import { registerAppRuleHandlers } from './app-rules.handlers'
 import { registerScheduleHandlers } from './schedule.handlers'
 import { registerUpdateHandlers } from './update.handlers'
 import { registerDiagnosticsHandlers } from './diagnostics.handlers'
@@ -27,8 +29,10 @@ export function registerAllHandlers(win: BrowserWindow): void {
   registerDesktopIconsHandlers()
   registerGnomeExtensionHandlers()
   registerBackupHandlers(win)
+  registerVideoToolsHandlers(win)
   registerPlaylistHandlers()
   registerScheduleHandlers()
+  registerAppRuleHandlers()
   registerUpdateHandlers()
   registerDiagnosticsHandlers(win)
 }

+ 17 - 2
src/main/ipc/lwe.handlers.ts

@@ -1,11 +1,12 @@
 import { BrowserWindow, dialog, ipcMain } from 'electron'
 import { IpcChannels } from '@shared/ipc-channels'
-import { getLweStatus, detectDistro, installLweDeps, installLwe, uninstallLwe, launchLweAsync, isLweRunning, killAllLweProcesses, listLweObjects, hotswapLweSettings, listLweProperties, listLweAudioObjects, listLweEffects, listLweFonts, listInputFiles, type HotswapOptions } from '../services/lwe.service'
+import { getLweStatus, detectDistro, installLweDeps, installLwe, uninstallLwe, launchLweAsync, isLweRunning, killAllLweProcesses, listLweObjects, hotswapLweSettings, listLweProperties, listLweAudioObjects, listLweEffects, listLweFonts, listAudioInputs, listInputFiles, type HotswapOptions } from '../services/lwe.service'
 import { getPrebuiltTarget, installLwePrebuilt } from '../services/lwe-prebuilt.service'
 import { installLibnode, libnodeNeeded } from '../services/lwe-libnode.service'
 import { addUserFonts, listUserFonts, removeUserFont } from '../services/fonts.service'
 import { forgetAssignments, stopDisplay } from '../services/display.service'
-import { getPlaybackStates, stopPlaylist, suspendPlaylist } from '../services/playlist-player.service'
+import { getPlaybackStates, pausePlaylist, stopPlaylist, suspendPlaylist } from '../services/playlist-player.service'
+import { getForgetOnKillAll, getStopPlaylistsOnKillAll } from '../services/config.service'
 import type { ScreenTarget } from '@shared/types'
 import { invalidateEnvCache } from '../services/wallpaper.service'
 import { refreshEngineUpdate } from '../services/update.service'
@@ -27,6 +28,15 @@ export function registerLweHandlers(win: BrowserWindow): void {
     return { ok: await installLweDeps(win) }
   })
 
+  ipcMain.handle(IpcChannels.LWE_LIST_AUDIO_INPUTS, async () => {
+    try {
+      return await listAudioInputs()
+    } catch (err) {
+      console.warn('[LWE] list-audio-inputs failed:', (err as Error).message)
+      return []
+    }
+  })
+
   ipcMain.handle(IpcChannels.LWE_LIST_FONTS, async (_e, wallpaperPath: string) => {
     try {
       return await listLweFonts(wallpaperPath)
@@ -95,6 +105,11 @@ export function registerLweHandlers(win: BrowserWindow): void {
   })
 
   ipcMain.handle(IpcChannels.LWE_KILL_ALL, async () => {
+    if (!getForgetOnKillAll()) {
+      if (getStopPlaylistsOnKillAll()) pausePlaylist()
+      return await killAllLweProcesses()
+    }
+
     const resumes = getPlaybackStates().filter((state) => state.isPlaying).map((state) => suspendPlaylist(state.screen))
     const result = await killAllLweProcesses()
     if (result.ok) {

+ 25 - 12
src/main/ipc/playlist.handlers.ts

@@ -27,28 +27,41 @@ export function registerPlaylistHandlers(): void {
 
   ipcMain.handle(
     IpcChannels.PLAYLIST_UPDATE_SETTINGS,
-    (_e, id: string, patch: Partial<PlaylistSettings>) =>
-      playlists.updatePlaylistSettings(id, patch)
+    (_e, id: string, patch: Partial<PlaylistSettings>) => {
+      const updated = playlists.updatePlaylistSettings(id, patch)
+      player.playlistEdited(id)
+      return updated
+    }
   )
 
-  ipcMain.handle(IpcChannels.PLAYLIST_ADD_ITEMS, (_e, id: string, wallpaperIds: string[]) =>
-    playlists.addItemsToPlaylist(id, wallpaperIds)
-  )
+  ipcMain.handle(IpcChannels.PLAYLIST_ADD_ITEMS, (_e, id: string, wallpaperIds: string[]) => {
+    const updated = playlists.addItemsToPlaylist(id, wallpaperIds)
+    player.playlistEdited(id)
+    return updated
+  })
 
-  ipcMain.handle(IpcChannels.PLAYLIST_REMOVE_ITEMS, (_e, id: string, wallpaperIds: string[]) =>
-    playlists.removeItemsFromPlaylist(id, wallpaperIds)
-  )
+  ipcMain.handle(IpcChannels.PLAYLIST_REMOVE_ITEMS, (_e, id: string, wallpaperIds: string[]) => {
+    const updated = playlists.removeItemsFromPlaylist(id, wallpaperIds)
+    player.playlistEdited(id)
+    return updated
+  })
 
   ipcMain.handle(
     IpcChannels.PLAYLIST_REORDER_ITEMS,
-    (_e, id: string, orderedWallpaperIds: string[]) =>
-      playlists.reorderPlaylistItems(id, orderedWallpaperIds)
+    (_e, id: string, orderedWallpaperIds: string[]) => {
+      const updated = playlists.reorderPlaylistItems(id, orderedWallpaperIds)
+      player.playlistEdited(id)
+      return updated
+    }
   )
 
   ipcMain.handle(
     IpcChannels.PLAYLIST_UPDATE_ITEM,
-    (_e, id: string, wallpaperId: string, patch: { volume?: number; durationSec?: number }) =>
-      playlists.updatePlaylistItem(id, wallpaperId, patch)
+    (_e, id: string, wallpaperId: string, patch: { volume?: number; durationSec?: number; endMinute?: number }) => {
+      const updated = playlists.updatePlaylistItem(id, wallpaperId, patch)
+      player.playlistEdited(id)
+      return updated
+    }
   )
 
   ipcMain.handle(IpcChannels.PLAYLIST_START, (_e, id: string, screen?: ScreenTarget) =>

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

@@ -87,7 +87,10 @@ function startDownloadPoll(win: BrowserWindow, itemId: string, intervalMs = 1000
   })
 }
 
+const pendingRemoval = new Map<string, symbol>()
+
 async function subscribeAndDownload(win: BrowserWindow, itemId: string): Promise<void> {
+  pendingRemoval.delete(itemId)
   await steam.subscribeToItem(BigInt(itemId))
   // subscribing doesn't always start the download
   await steam.downloadItem(BigInt(itemId))
@@ -113,6 +116,7 @@ const REPAIR_POLL_MS = 3000
 async function repairItem(win: BrowserWindow, itemId: string): Promise<{ done: Promise<void> } | null> {
   if (repairing.has(itemId)) return null
   repairing.add(itemId)
+  pendingRemoval.delete(itemId)
   let started: { done: Promise<void> } | null = null
   try {
     started = await startRepair(win, itemId)
@@ -214,6 +218,37 @@ async function removeLocalFiles(dir: string): Promise<void> {
   try { await fs.promises.rm(dir, { recursive: true, force: true }) } catch { }
 }
 
+// Steam still works on the folder for a moment after an unsubscribe and can put files back
+async function removeUnsubscribedFiles(itemId: string, dir: string): Promise<void> {
+  const mine = Symbol(itemId)
+  pendingRemoval.set(itemId, mine)
+  const current = (): boolean => pendingRemoval.get(itemId) === mine
+  let missing = 0
+  try {
+    for (let attempt = 0; attempt < 6 && current(); attempt++) {
+      await sleep(2000)
+      if (!current()) return
+      let subscribed: string[]
+      try {
+        subscribed = await steam.getSubscribedItems()
+      } catch {
+        continue
+      }
+      if (!current()) return
+      if (subscribed.includes(itemId)) continue
+      await removeLocalFiles(dir)
+      missing = fs.existsSync(dir) ? 0 : missing + 1
+      if (missing >= 2) return
+    }
+    if (fs.existsSync(dir) && current()) console.warn(`[Steam] Could not remove ${dir} after unsubscribing`)
+  } finally {
+    if (current()) pendingRemoval.delete(itemId)
+  }
+}
+
+// every item reports, which re-rendered the whole library thousands of times a second
+const VERIFY_PROGRESS_INTERVAL_MS = 150
+
 export function registerSteamHandlers(win: BrowserWindow): void {
   setDependencyInstaller((itemId) => subscribeAndDownload(win, itemId))
   void verify.restoreRepairStashes()
@@ -235,7 +270,10 @@ export function registerSteamHandlers(win: BrowserWindow): void {
       library.updateWallpaper(itemId, { subscribed: false, downloading: false, downloadFailed: false })
       return { ok: true }
     }
-    if (wallpaper?.localPath) await removeLocalFiles(wallpaper.localPath)
+    if (wallpaper?.localPath) {
+      await removeLocalFiles(wallpaper.localPath)
+      void removeUnsubscribedFiles(itemId, wallpaper.localPath)
+    }
     const backupDir = wallpaper?.backedUp ? backup.resolveBackupDir(wallpaper) : null
     if (wallpaper && backupDir && (await backup.hasBackupFiles(backupDir))) {
       library.updateWallpaper(itemId, {
@@ -260,7 +298,11 @@ export function registerSteamHandlers(win: BrowserWindow): void {
   })
 
   ipcMain.handle(IpcChannels.STEAM_VERIFY, (_e, itemIds?: string[]) => {
+    let lastSent = 0
     return verify.verifyItems(itemIds, (done, total) => {
+      const now = Date.now()
+      if (done > 0 && done < total && now - lastSent < VERIFY_PROGRESS_INTERVAL_MS) return
+      lastSent = now
       if (!win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_VERIFY_PROGRESS, { done, total })
     })
   })

+ 48 - 0
src/main/ipc/video-tools.handlers.ts

@@ -0,0 +1,48 @@
+import { app, ipcMain, BrowserWindow } from 'electron'
+import { IpcChannels } from '@shared/ipc-channels'
+import type { OptimizeOptions } from '@shared/video-tools'
+import * as tools from '../services/video-tools.service'
+import { getVideoToolSettings, setVideoToolSettings } from '../services/config.service'
+
+export function registerVideoToolsHandlers(win: BrowserWindow): void {
+  app.on('will-quit', tools.discardStagedOnExit)
+  setTimeout(() => { void tools.sweepOptimizeLeftovers() }, 20_000)
+  win.webContents.on('did-start-navigation', (details) => {
+    if (details.isMainFrame && !details.isSameDocument) tools.abandonOptimize()
+  })
+
+  ipcMain.handle(IpcChannels.VIDEO_TOOLS_STATUS, () => tools.getVideoToolsStatus())
+
+  ipcMain.handle(IpcChannels.VIDEO_TOOLS_DOWNLOAD, async () => {
+    await tools.downloadFfmpeg(win)
+    return { ok: true }
+  })
+
+  ipcMain.handle(IpcChannels.VIDEO_TOOLS_REMOVE, async () => {
+    await tools.removeDownloadedFfmpeg()
+    return { ok: true }
+  })
+
+  ipcMain.handle(IpcChannels.VIDEO_TOOLS_PROBE, (_e, itemId: string) => tools.probeWallpaper(itemId))
+
+  ipcMain.handle(IpcChannels.VIDEO_TOOLS_START, (_e, itemId: string, options: OptimizeOptions) =>
+    tools.startOptimize(itemId, options, win)
+  )
+
+  ipcMain.handle(IpcChannels.VIDEO_TOOLS_CANCEL, () => {
+    tools.cancelOptimize()
+    return { ok: true }
+  })
+
+  ipcMain.handle(IpcChannels.VIDEO_TOOLS_FINISH, async (_e, itemId: string, keep: boolean) => {
+    await tools.finishOptimize(itemId, keep)
+    return { ok: true }
+  })
+
+  ipcMain.handle(IpcChannels.VIDEO_TOOLS_GET_SETTINGS, () => getVideoToolSettings())
+
+  ipcMain.handle(IpcChannels.VIDEO_TOOLS_SET_SETTINGS, (_e, settings: unknown) => setVideoToolSettings(settings))
+
+  ipcMain.handle(IpcChannels.VIDEO_TOOLS_QUICK, (_e, ids: string[], trim?: boolean) => tools.quickOptimize(ids, win, trim === true))
+  ipcMain.handle(IpcChannels.VIDEO_TOOLS_QUICK_TRIMS, (_e, ids: string[]) => tools.quickTrims(ids))
+}

+ 264 - 0
src/main/services/app-rules.service.ts

@@ -0,0 +1,264 @@
+import { randomUUID } from 'crypto'
+import path from 'path'
+import type { BrowserWindow } from 'electron'
+import { IpcChannels } from '@shared/ipc-channels'
+import type { AppRule, ScreenAction } from '@shared/types'
+import {
+  popLayers,
+  pushLayer,
+  stepAppRules,
+  type Observation,
+  type RuleStates,
+  type ScreenLayers
+} from '@shared/appRules'
+import { openStore } from '../utils/safeStore'
+import { listProcessNames } from '../utils/processes'
+import { isAudioPlaying } from '../utils/audio-activity'
+import { hostPidOf, isFlatpak } from '../utils/flatpak'
+import { getRunningInstances, isLweRunning } from './lwe.service'
+import { captureScreens } from './profile.service'
+import { getWallpaper } from './library.service'
+import { actionScreens, runAction, runScreenAction } from './rule-actions.service'
+
+interface AppRuleStore {
+  rules: AppRule[]
+  /** what each screen showed before the rules that are on it, so a restart does not forget where to go back to */
+  layers: ScreenLayers<ScreenAction>
+  active: string[]
+}
+
+const store = openStore<AppRuleStore>({
+  name: 'app-rules',
+  defaults: { rules: [], layers: {}, active: [] }
+})
+
+// every check inside a Flatpak is a round trip through flatpak-spawn to the host
+const TICK_MS = isFlatpak() ? 5000 : 2000
+const MAX_RESTORE_ATTEMPTS = 3
+
+let win: BrowserWindow | null = null
+let timer: ReturnType<typeof setInterval> | null = null
+let states: RuleStates = Object.fromEntries(store.get('active').map((id) => [id, { active: true, unmetSince: null }]))
+let ticking = false
+let rulesCache: AppRule[] = store.get('rules')
+let savedActive = store.get('active').join()
+let layersCache = store.get('layers')
+
+function setLayers(layers: ScreenLayers<ScreenAction>): void {
+  layersCache = layers
+  store.set('layers', layers)
+}
+
+let resumePending = new Set(store.get('active'))
+const restoreAttempts = new Map<string, number>()
+const reapply = new Set<string>()
+
+export function getAppRules(): AppRule[] {
+  return rulesCache
+}
+
+function setRules(rules: AppRule[]): void {
+  rulesCache = rules
+  store.set('rules', rules)
+  syncTimer()
+}
+
+export function saveAppRule(rule: Omit<AppRule, 'id'> & { id?: string }): AppRule {
+  const saved: AppRule = { ...rule, id: rule.id ?? randomUUID() }
+  const rules = [...rulesCache]
+  const index = rules.findIndex((r) => r.id === saved.id)
+  if (index === -1) {
+    rules.push(saved)
+  } else {
+    const old = rules[index]
+    if (states[saved.id]?.active && (!sameAction(old, saved) || old.revert !== saved.revert)) reapply.add(saved.id)
+    rules[index] = saved
+  }
+  setRules(rules)
+  return saved
+}
+
+function sameAction(a: AppRule, b: AppRule): boolean {
+  return a.screen === b.screen && JSON.stringify(a.action) === JSON.stringify(b.action)
+}
+
+export function deleteAppRule(id: string): void {
+  setRules(rulesCache.filter((r) => r.id !== id))
+}
+
+export function getActiveRuleIds(): string[] {
+  return Object.entries(states)
+    .filter(([, state]) => state.active)
+    .map(([id]) => id)
+}
+
+let ownHostPid: Promise<number | undefined> | undefined
+
+function ownHostPidOnce(): Promise<number | undefined> {
+  if (!isFlatpak()) return Promise.resolve(undefined)
+  ownHostPid ??= hostPidOf(process.pid)
+  return ownHostPid
+}
+
+async function observe(rules: AppRule[]): Promise<Observation> {
+  const enabled = rules.filter((r) => r.enabled)
+  const processes = enabled.some((r) => r.condition.type === 'process') ? await listProcessNames() : new Set<string>()
+  const owners = new Set([process.pid, ...getRunningInstances().flatMap((i) => (i.hostPid === null ? [i.pid] : [i.pid, i.hostPid]))])
+  const hostPid = await ownHostPidOnce()
+  if (hostPid) owners.add(hostPid)
+  const audioPlaying = enabled.some((r) => r.condition.type === 'audio') ? await isAudioPlaying(owners) : false
+  return { processes, audioPlaying }
+}
+
+function notify(name: string, state: 'started' | 'ended' | 'restoreFailed' | 'failed'): void {
+  if (win && !win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_APP_RULE, { name, state })
+}
+
+async function fire(rule: AppRule): Promise<void> {
+  console.log(`[AppRules] "${rule.name}" started`)
+  if (rule.revert) {
+    try {
+      const screens = actionScreens(rule.action, rule.screen)
+      const before = captureScreens(screens)
+      let layers = layersCache
+      for (const screen of screens) {
+        if (layers[screen]?.some((entry) => entry.ruleId === rule.id)) continue
+        layers = pushLayer(layers, screen, rule.id, before[screen])
+      }
+      setLayers(layers)
+    } catch (err) {
+      console.error(`[AppRules] could not remember what "${rule.name}" replaces:`, err)
+    }
+  }
+
+  try {
+    await runAction(rule.action, rule.screen)
+  } catch (err) {
+    console.error(`[AppRules] "${rule.name}" failed:`, err)
+    if (rule.revert) setLayers(popLayers(layersCache, rule.id).layers)
+    notify(rule.name, 'failed')
+    return
+  }
+  notify(rule.name, 'started')
+}
+
+function showsRuleWallpaper(action: AppRule['action'], screen: string): boolean {
+  if (action.type !== 'wallpaper') return true
+  const dir = getWallpaper(action.wallpaperId)?.localPath
+  if (!dir) return true
+  const shown = getRunningInstances().find((i) => i.screen === screen)
+  if (!shown) return false
+  const root = path.resolve(dir)
+  const current = path.resolve(shown.wallpaperPath)
+  return current === root || current.startsWith(root + path.sep)
+}
+
+async function resumeAfterRestart(rule: AppRule): Promise<void> {
+  const screens = actionScreens(rule.action, rule.screen)
+  if (screens.every((screen) => isLweRunning(screen) && showsRuleWallpaper(rule.action, screen))) return
+  console.log(`[AppRules] "${rule.name}" was active at the last close and still holds`)
+  await runAction(rule.action, rule.screen)
+}
+
+async function release(id: string): Promise<void> {
+  console.log(`[AppRules] rule ${id} ended`)
+  const before = layersCache
+  const { layers, restore } = popLayers(before, id)
+
+  const failed: string[] = []
+  for (const [screen, action] of Object.entries(restore)) {
+    try {
+      await runScreenAction(action, screen)
+    } catch (err) {
+      console.error(`[AppRules] going back on ${screen} failed:`, err)
+      failed.push(screen)
+    }
+  }
+
+  const attempts = (restoreAttempts.get(id) ?? 0) + 1
+  let kept = layers
+  if (failed.length > 0 && attempts < MAX_RESTORE_ATTEMPTS) {
+    for (const screen of failed) kept = { ...kept, [screen]: before[screen] }
+    restoreAttempts.set(id, attempts)
+  } else {
+    restoreAttempts.delete(id)
+    const name = rulesCache.find((r) => r.id === id)?.name
+    if (name && Object.keys(restore).length > 0) notify(name, failed.length > 0 ? 'restoreFailed' : 'ended')
+  }
+  setLayers(kept)
+}
+
+function endedRulesWithLayers(): string[] {
+  const ids = new Set<string>()
+  for (const entries of Object.values(layersCache)) {
+    for (const entry of entries) {
+      if (!states[entry.ruleId]?.active) ids.add(entry.ruleId)
+    }
+  }
+  return [...ids]
+}
+
+async function guarded(label: string, work: () => Promise<void>): Promise<void> {
+  try {
+    await work()
+  } catch (err) {
+    console.error(`[AppRules] ${label} failed:`, err)
+  }
+}
+
+async function tick(): Promise<void> {
+  if (ticking) return
+  ticking = true
+  try {
+    for (const id of reapply) {
+      reapply.delete(id)
+      delete states[id]
+      await guarded(`ending ${id}`, () => release(id))
+    }
+    const result = stepAppRules(states, rulesCache, await observe(rulesCache), Date.now())
+    states = result.next
+
+    for (const id of result.deactivate) await guarded(`ending ${id}`, () => release(id))
+    for (const id of endedRulesWithLayers()) {
+      if (!result.deactivate.includes(id)) await guarded(`going back for ${id}`, () => release(id))
+    }
+    for (const rule of result.activate) await guarded(`starting "${rule.name}"`, () => fire(rule))
+
+    if (resumePending.size > 0) {
+      const pending = rulesCache.filter((rule) => resumePending.has(rule.id) && states[rule.id]?.active && states[rule.id].unmetSince === null)
+      resumePending = new Set()
+      for (const rule of pending) await guarded(`resuming "${rule.name}"`, () => resumeAfterRestart(rule))
+    }
+
+    const active = getActiveRuleIds().join()
+    if (active !== savedActive) {
+      savedActive = active
+      store.set('active', getActiveRuleIds())
+    }
+  } catch (err) {
+    console.error('[AppRules] check failed:', err)
+  } finally {
+    ticking = false
+    syncTimer()
+  }
+}
+
+function needsTimer(): boolean {
+  return rulesCache.some((rule) => rule.enabled) || Object.keys(states).length > 0 || Object.keys(layersCache).length > 0
+}
+
+function syncTimer(): void {
+  if (needsTimer()) {
+    timer ??= setInterval(() => void tick(), TICK_MS)
+  } else if (timer) {
+    clearInterval(timer)
+    timer = null
+  }
+}
+
+/** Call after the playlist player and the schedule are up, so a rule that holds at start wins over both */
+export function initAppRules(window: BrowserWindow): void {
+  win = window
+  void tick()
+  syncTimer()
+}

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

@@ -25,6 +25,27 @@ vi.mock('./library.service', () => ({
     for (const { id, patch } of c.patches ?? []) wallpapers.set(id, { ...wallpapers.get(id)!, ...patch })
     for (const id of c.deletes ?? []) wallpapers.delete(id)
   },
+  getDirSizeAsync: async function size(dir: string): Promise<number> {
+    let total = 0
+    for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
+      total += e.isDirectory() ? await size(path.join(dir, e.name)) : fs.statSync(path.join(dir, e.name)).size
+    }
+    return total
+  },
+  sizeRepairs: async (list: WallpaperMeta[]) => {
+    const dirSize = (dir: string): number =>
+      fs.readdirSync(dir, { withFileTypes: true }).reduce(
+        (total, e) => total + (e.isDirectory() ? dirSize(path.join(dir, e.name)) : fs.statSync(path.join(dir, e.name)).size),
+        0
+      )
+    const patches: { id: string; patch: Partial<WallpaperMeta> }[] = []
+    for (const w of list) {
+      if (w.source === 'workshop' || w.downloading || !w.localPath || !fs.existsSync(w.localPath)) continue
+      const fileSize = dirSize(w.localPath)
+      if (fileSize > 0 && fileSize !== w.fileSize) patches.push({ id: w.id, patch: { fileSize } })
+    }
+    return patches
+  },
   normalizeType: (t?: string) => t ?? 'scene',
   normalizeRating: () => 'everyone',
 }))
@@ -262,6 +283,18 @@ describe('scanBackupFolder', () => {
     expect(again.skipped).toBe(3)
   })
 
+  it('reads the file sizes again', async () => {
+    writeFiles(path.join(backupRoot, 'sized'), { 'project.json': '{"type":"video","file":"a.mp4"}', 'a.mp4': '12345' })
+    const local = path.join(tmp, 'local-copy')
+    writeFiles(local, { 'project.json': '{"type":"video","file":"a.mp4"}', 'a.mp4': '1234567' })
+    wallpapers.set('sized', { ...base, id: 'sized', source: 'backup', localPath: path.join(backupRoot, 'sized'), backedUp: true, fileSize: 1 })
+    wallpapers.set('123', { ...base, id: '123', source: 'local', localPath: local, fileSize: 99999 })
+    await backup.scanBackupFolder()
+    const jsonSize = fs.statSync(path.join(local, 'project.json')).size
+    expect(wallpapers.get('sized')?.fileSize).toBe(jsonSize + 5)
+    expect(wallpapers.get('123')?.fileSize).toBe(jsonSize + 7)
+  })
+
   it('re-imports a backup entry that pointed at a folder in the old backup location', async () => {
     writeFiles(path.join(backupRoot, 'moved'), { 'project.json': '{}' })
     fs.mkdirSync(path.join(tmp, 'old-backups'))

+ 71 - 21
src/main/services/backup.service.ts

@@ -7,8 +7,10 @@ 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 { isShaderCache } from '../utils/shaderCache'
 import { containedPath } from '../utils/contained'
-import { normalizeType, normalizeRating, type ProjectJson } from './library.service'
+import { readProjectJson } from '../utils/projectJson'
+import { normalizeType, normalizeRating } from './library.service'
 
 function getBackupDir(id: string): string {
   const backupPath = getConfiguredBackupPath()
@@ -43,14 +45,6 @@ export async function exists(p: string): Promise<boolean> {
   }
 }
 
-async function readProjectJson(dir: string): Promise<ProjectJson | null> {
-  try {
-    return JSON.parse(await fs.promises.readFile(path.join(dir, 'project.json'), 'utf8')) as ProjectJson
-  } catch {
-    return 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 = containedPath(dir, rel)
@@ -122,11 +116,6 @@ function hashFile(filePath: string): Promise<string> {
   })
 }
 
-// WE writes compiled shaders into the folder
-function isShaderCache(relPath: string): boolean {
-  return /^shaders[\\/]blobs/i.test(relPath)
-}
-
 async function walkFiles(dirPath: string, baseDir = dirPath): Promise<{ relPath: string; size: number }[]> {
   const entries = await fs.promises.readdir(dirPath, { withFileTypes: true })
   const nested = await Promise.all(
@@ -156,7 +145,7 @@ export async function forEachLimit<T>(items: T[], limit: number, fn: (item: T) =
   await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
 }
 
-async function fsyncPath(p: string): Promise<void> {
+export async function fsyncPath(p: string): Promise<void> {
   const handle = await fs.promises.open(p, 'r')
   try {
     await handle.sync()
@@ -165,6 +154,63 @@ async function fsyncPath(p: string): Promise<void> {
   }
 }
 
+const SYNC_TIMEOUT_MS = 120_000
+
+// fsync leaves atime updates from the hash reads, unlinks and directory changes in the journal, so the whole
+// filesystem is flushed (sync -f), with a plain sync where that flag is missing
+function syncOnce(target: string): Promise<void> {
+  const run = (args: string[]): Promise<{ code: number | null; timedOut: boolean }> =>
+    new Promise((resolve) => {
+      const child = spawn('sync', args, { stdio: 'ignore' })
+      // a sync stuck in uninterruptible I/O ignores signals, so the wait ends here and not on the exit
+      const giveUp = setTimeout(() => {
+        child.kill('SIGKILL')
+        resolve({ code: null, timedOut: true })
+      }, SYNC_TIMEOUT_MS)
+      child.on('error', () => {
+        clearTimeout(giveUp)
+        resolve({ code: null, timedOut: false })
+      })
+      child.on('close', (code, signal) => {
+        clearTimeout(giveUp)
+        resolve({ code, timedOut: code === null && signal !== null })
+      })
+    })
+  return run(['-f', target]).then(async (first) => {
+    if (first.timedOut) {
+      console.warn(`[Backup] sync of ${target} did not finish in ${SYNC_TIMEOUT_MS / 1000} s`)
+      return
+    }
+    if (first.code !== null && first.code !== 0) await run([])
+  })
+}
+
+interface SyncSlot {
+  running: Promise<void>
+  queued: Promise<void> | null
+}
+
+const syncSlots = new Map<number, SyncSlot>()
+
+function startSync(dev: number, target: string): Promise<void> {
+  const slot: SyncSlot = { running: syncOnce(target), queued: null }
+  syncSlots.set(dev, slot)
+  void slot.running.then(() => {
+    if (syncSlots.get(dev) === slot) syncSlots.delete(dev)
+  })
+  return slot.running
+}
+
+// copies run side by side and a sync flushes the whole filesystem: callers that arrive while one is running share
+// the next one, which starts after theirs wrote everything
+async function syncFilesystem(target: string): Promise<void> {
+  const dev = await fs.promises.stat(target).then((st) => st.dev, () => -1)
+  const slot = syncSlots.get(dev)
+  if (!slot) return startSync(dev, target)
+  slot.queued ??= slot.running.then(() => startSync(dev, target))
+  return slot.queued
+}
+
 // fsynced pages are clean, so iflag=nocache can evict them and the hash check reads the disk
 function dropPageCache(dir: string): Promise<void> {
   return new Promise((resolve) => {
@@ -216,6 +262,7 @@ export async function verifyOnDisk(sourcePath: string, destDir: string): Promise
   } catch {
     return false
   }
+  await syncFilesystem(destDir)
   await dropPageCache(destDir)
   return backupMatchesSource(sourcePath, destDir)
 }
@@ -365,6 +412,7 @@ async function stageAndSwap(
       })
     }
     for (const dir of await walkDirs(stagingDir)) await fsyncPath(dir)
+    await syncFilesystem(stagingDir)
     await dropPageCache(stagingDir)
 
     bytesDone = 0
@@ -407,6 +455,7 @@ async function stageAndSwap(
     }
     await fsyncPath(destRoot)
     await Promise.all([removeTree(oldDir), removeTree(verifiedMark)])
+    await syncFilesystem(destRoot)
   } catch (err) {
     await Promise.all([removeTree(stagingDir), removeTree(verifiedMark)].map((removal) => removal.catch(() => {})))
     sendProgress(win, {
@@ -543,9 +592,9 @@ export async function scanBackupFolder(): Promise<{
   const backupPath = getConfiguredBackupPath()
   const wallpapers = new Map(library.getAllWallpapers().map((w) => [w.id, w]))
   if (!backupPath || !(await isDir(backupPath))) {
-    const patches = await previewRepairs([...wallpapers.values()])
-    library.applyWallpaperChanges({ patches })
-    result.previewsFixed = patches.length
+    const previewPatches = await previewRepairs([...wallpapers.values()])
+    library.applyWallpaperChanges({ patches: [...previewPatches, ...(await library.sizeRepairs([...wallpapers.values()]))] })
+    result.previewsFixed = previewPatches.length
     return result
   }
 
@@ -619,11 +668,12 @@ export async function scanBackupFolder(): Promise<{
   })
 
   const reimported = new Set(upserts.map((m) => m.id))
-  const previewPatches = await previewRepairs(
-    [...wallpapers.values()].filter((w) => !reimported.has(w.id) && !deletes.includes(w.id))
-  )
+  const deleted = new Set(deletes)
+  const untouched = [...wallpapers.values()].filter((w) => !reimported.has(w.id) && !deleted.has(w.id))
+  const previewPatches = await previewRepairs(untouched)
   patches.push(...previewPatches)
   result.previewsFixed = previewPatches.length
+  patches.push(...(await library.sizeRepairs(untouched)))
 
   library.applyWallpaperChanges({
     upserts,

+ 36 - 0
src/main/services/config.service.ts

@@ -9,6 +9,7 @@ import { normalizeCardBadges, type CardBadges } from '@shared/cardBadges'
 import { normalizeLanguagePreference, type LanguagePreference } from '@shared/i18n'
 import { normalizeUpdateChecks } from '@shared/updates'
 import { DEFAULT_LOADER, normalizeLoader } from '@shared/loader'
+import { DEFAULT_VIDEO_SETTINGS, normalizeVideoSettings, type VideoToolSettings } from '@shared/video-tools'
 import type {
   DisplayMode,
   EngineFlagPreset,
@@ -39,6 +40,9 @@ interface AppConfig {
   killLweOnQuit: boolean
   skipPlaylistResume: boolean
   freshProcessOnPathChange: boolean
+  stopPlaylistsOnKillAll: boolean
+  forgetOnKillAll: boolean
+  videoTools: VideoToolSettings
   /** Legacy, only read to migrate into cardBorders */
   voteBorders: boolean
   cardBorders: CardBorders | null
@@ -93,6 +97,9 @@ const store = openStore<AppConfig>({
     killLweOnQuit: false,
     skipPlaylistResume: false,
     freshProcessOnPathChange: false,
+    stopPlaylistsOnKillAll: false,
+    forgetOnKillAll: false,
+    videoTools: DEFAULT_VIDEO_SETTINGS,
     voteBorders: true,
     cardBorders: null,
     cardBadges: null,
@@ -213,6 +220,32 @@ export function setSkipPlaylistResume(enabled: boolean): void {
   store.set('skipPlaylistResume', enabled)
 }
 
+export function getStopPlaylistsOnKillAll(): boolean {
+  return store.get('stopPlaylistsOnKillAll')
+}
+
+export function setStopPlaylistsOnKillAll(enabled: boolean): void {
+  store.set('stopPlaylistsOnKillAll', enabled)
+}
+
+export function getForgetOnKillAll(): boolean {
+  return store.get('forgetOnKillAll')
+}
+
+export function setForgetOnKillAll(enabled: boolean): void {
+  store.set('forgetOnKillAll', enabled)
+}
+
+export function getVideoToolSettings(): VideoToolSettings {
+  return normalizeVideoSettings(store.get('videoTools'))
+}
+
+export function setVideoToolSettings(settings: unknown): VideoToolSettings {
+  const clean = normalizeVideoSettings(settings)
+  store.set('videoTools', clean)
+  return clean
+}
+
 export function getAppearance(): Appearance {
   return normalizeAppearance(store.get('appearance'))
 }
@@ -402,6 +435,9 @@ const RESETS_WITH_ENGINE_SETTINGS: Record<keyof AppConfig, boolean> = {
   killLweOnQuit: false,
   skipPlaylistResume: false,
   freshProcessOnPathChange: true,
+  stopPlaylistsOnKillAll: false,
+  forgetOnKillAll: false,
+  videoTools: false,
   voteBorders: false,
   cardBorders: false,
   cardBadges: false,

+ 65 - 6
src/main/services/desktop-icons.service.ts

@@ -5,11 +5,12 @@ import { openStore } from '../utils/safeStore'
 import { app } from 'electron'
 import { detectDesktopEnv, getWaylandDisplay, getXdgRuntimeDir, isCommandAvailable, isWaylandSession } from '../utils/platform'
 import { hostCommand, isFlatpak, isHostCommandAvailable } from '../utils/flatpak'
-import { distroFromIds, getActiveScreens, isOstreeSystem, parseOsReleaseIds, onLweLaunched } from './lwe.service'
+import { distroFromIds, getActiveScreens, getRunningInstances, isLweRunning, isOstreeSystem, parseOsReleaseIds, onLweLaunched } from './lwe.service'
 import type { DesktopIconsStatus, LinuxDistro } from '@shared/types'
 
 interface DesktopIconsStoreSchema {
   desktopIconsEnabled: boolean
+  desktopIconsAuto?: boolean
 }
 
 const store = openStore<DesktopIconsStoreSchema>({
@@ -121,7 +122,7 @@ export function installDesktopIconsDependencies(): Promise<{ ok: boolean; error?
         resolve({ ok: false, error: stderr.trim().split('\n').slice(-4).join('\n') || err.message }); return;
       }
       startFailure = null
-      if (getDesktopIconsEnabled()) startDesktopIconsOverlay()
+      if (overlayWanted()) startDesktopIconsOverlay()
       resolve({ ok: true })
     })
   })
@@ -280,7 +281,7 @@ function startDesktopIconsOverlay(): void {
       if (code === EXIT_MONITORS_CHANGED) {
         clearTimeout(restartTimer)
         restartTimer = setTimeout(() => {
-          if (getDesktopIconsEnabled()) startDesktopIconsOverlay()
+          if (overlayWanted()) startDesktopIconsOverlay()
         }, 500)
         return
       }
@@ -308,7 +309,9 @@ function stopDesktopIconsOverlay(): void {
 
 export function setDesktopIconsEnabled(enabled: boolean): void {
   store.set('desktopIconsEnabled', enabled)
-  if (enabled) {
+  lastRunning = getDesktopIconsEnabled() && getDesktopIconsAuto() && isLweRunning()
+  syncRunningPoll()
+  if (overlayWanted()) {
     startDesktopIconsOverlay()
   } else {
     startFailure = null
@@ -316,9 +319,59 @@ export function setDesktopIconsEnabled(enabled: boolean): void {
   }
 }
 
+export function getDesktopIconsAuto(): boolean {
+  return store.get('desktopIconsAuto', true)
+}
+
+export function setDesktopIconsAuto(auto: boolean): void {
+  store.set('desktopIconsAuto', auto)
+  lastRunning = isLweRunning()
+  syncRunningPoll()
+  if (overlayWanted()) {
+    if (overlayProcesses.length === 0) startDesktopIconsOverlay()
+  } else {
+    stopDesktopIconsOverlay()
+  }
+}
+
+/** With the auto mode on the overlay only lives while an engine runs, otherwise it draws the icons over a bare desktop */
+function overlayWanted(): boolean {
+  if (!getDesktopIconsEnabled()) return false
+  return !getDesktopIconsAuto() || isLweRunning()
+}
+
+let lastRunning = false
+let runningPoll: NodeJS.Timeout | undefined
+
+// an engine this app launched itself is handled by onLweLaunched once its surface is up
+const LAUNCH_HOOK_GRACE_MS = 15_000
+
+function syncRunningPoll(): void {
+  const needed = getDesktopIconsEnabled() && getDesktopIconsAuto()
+  if (needed && !runningPoll) {
+    runningPoll = setInterval(pollEngineState, 2000)
+    runningPoll.unref()
+  } else if (!needed && runningPoll) {
+    clearInterval(runningPoll)
+    runningPoll = undefined
+  }
+}
+
+function pollEngineState(): void {
+  const running = isLweRunning()
+  if (running === lastRunning) return
+  lastRunning = running
+  if (!running) {
+    stopDesktopIconsOverlay()
+    return
+  }
+  const adopted = getRunningInstances().some((i) => Date.now() - i.startedAt > LAUNCH_HOOK_GRACE_MS)
+  if (adopted) startDesktopIconsOverlay()
+}
+
 /** The engine and the overlay share the bottom layer and the later surface is drawn on top, so the overlay has to map after the wallpaper */
 function raiseDesktopIconsOverlay(): void {
-  if (getDesktopIconsEnabled()) startDesktopIconsOverlay()
+  if (overlayWanted()) startDesktopIconsOverlay()
 }
 
 export function getDesktopIconsEnabled(): boolean {
@@ -326,12 +379,18 @@ export function getDesktopIconsEnabled(): boolean {
 }
 
 export function initDesktopIcons(): void {
+  // an overlay that was on before the option existed keeps drawing without an engine of this app
+  if (store.get('desktopIconsAuto') === undefined) store.set('desktopIconsAuto', !getDesktopIconsEnabled())
   onLweLaunched(raiseDesktopIconsOverlay)
-  if (getDesktopIconsEnabled()) {
+  lastRunning = isLweRunning()
+  syncRunningPoll()
+  if (overlayWanted()) {
     startDesktopIconsOverlay()
   }
 }
 
 export function cleanupDesktopIcons(): void {
+  clearInterval(runningPoll)
+  runningPoll = undefined
   stopDesktopIconsOverlay()
 }

+ 4 - 6
src/main/services/diagnostics.service.ts

@@ -1,5 +1,3 @@
-import { execFile } from 'child_process'
-import { promisify } from 'util'
 import * as fs from 'fs'
 import * as os from 'os'
 import { app } from 'electron'
@@ -18,8 +16,8 @@ import { stopDisplay } from './display.service'
 import { getPlaybackStates, restoreVolume, suspendPlaylist } from './playlist-player.service'
 import { detectDesktopEnv, detectDisplayServer, getConnectedScreens, runningAppImage } from '../utils/platform'
 import { hostCommand, hostAppPath, isFlatpak } from '../utils/flatpak'
-
-const execFileAsync = promisify(execFile)
+import { setTimeout as sleep } from 'timers/promises'
+import { execFileAsync } from '../utils/exec'
 
 const DEFAULT_SECONDS = 20
 const SOFTWARE_RENDERER = /llvmpipe|softpipe|swrast/i
@@ -237,7 +235,7 @@ async function runTarget(target: DiagnosticsTarget, seconds: number, notes: stri
     }
     const deadline = Date.now() + seconds * 1000
     while (Date.now() < deadline && !(exit.at && Date.now() - exit.at > 1500)) {
-      await new Promise((resolve) => setTimeout(resolve, 250))
+      await sleep(250)
     }
     histories = getEngineHistory().filter((h) => h.screen === target.screen)
     if (histories.length > 0) snapshot = await snapshotInstances()
@@ -268,7 +266,7 @@ export async function collectDiagnostics(seconds = DEFAULT_SECONDS, target?: Dia
     setDiagnosticStats(true)
     try {
       notes.push(...(await restartPlaying()))
-      await new Promise((resolve) => setTimeout(resolve, seconds * 1000))
+      await sleep(seconds * 1000)
       histories = getEngineHistory()
       snapshot = await snapshotInstances()
     } finally {

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

@@ -1,15 +1,12 @@
-import { execFile } from 'child_process'
 import * as fs from 'fs'
 import * as os from 'os'
 import * as path from 'path'
-import { promisify } from 'util'
 import type { GnomeExtensionStatus } from '@shared/types'
 import { detectDesktopEnv, isWaylandSession } from '../utils/platform'
 import { hostCommand, isFlatpak, toHostPath } from '../utils/flatpak'
 import { getLweStatus } from './lwe.service'
 import { t } from '../i18n'
-
-const execFileAsync = promisify(execFile)
+import { execFileAsync } from '../utils/exec'
 
 /** GNOME has no layer-shell, the engine's extension makes desktop windows. A fresh install needs a re-login */
 const GNOME_EXTENSION_UUID = 'linux-wallpaperengine@wallpaperenginelover.github.io'

+ 1 - 4
src/main/services/graphics.service.ts

@@ -1,12 +1,9 @@
-import { execFile } from 'child_process'
-import { promisify } from 'util'
 import * as fs from 'fs'
 import * as os from 'os'
 import type { GraphicsWarning } from '@shared/types'
 import { getEngineRenderer } from './lwe.service'
 import { hostAppPath, hostCommand, isFlatpak } from '../utils/flatpak'
-
-const execFileAsync = promisify(execFile)
+import { execFileAsync } from '../utils/exec'
 
 const SOFTWARE_RENDERER = /llvmpipe|softpipe|swrast/i
 const GLVND_DIR = '/usr/share/glvnd/egl_vendor.d'

+ 199 - 21
src/main/services/library.service.ts

@@ -3,10 +3,14 @@ import type { WallpaperMeta, WallpaperType, ContentRating, LibraryFilters, Wallp
 import { getExtraLibraryRoots, getThumbnailsPath, getWorkshopPath } from '../utils/paths'
 import { findLocalWallpapers, localWallpaperId } from '../utils/localLibrary'
 import { containedPath } from '../utils/contained'
+import { readProjectJsonSync } from '../utils/projectJson'
 import * as path from 'path'
 import * as fs from 'fs'
 import { randomUUID } from 'crypto'
+import { getSteamIdentity } from './config.service'
+import { isShaderCache } from '../utils/shaderCache'
 import { cleanupPlaylists } from './playlist.service'
+import { backupMatchesSource, hasBackupFiles } from './backup.service'
 import { getWorkshopDetails, getUnavailableWorkshopItems, type WorkshopDetails } from './workshop.service'
 import { findAndMutate } from '../utils/collections'
 import { resolutionsFromTags } from '@shared/resolutions'
@@ -239,14 +243,7 @@ export interface ProjectJson {
   dependency?: string | number
 }
 
-export function readProjectJson(localPath: string): ProjectJson | null {
-  try {
-    const raw = fs.readFileSync(path.join(localPath, 'project.json'), 'utf8')
-    return JSON.parse(raw) as ProjectJson
-  } catch {
-    return null
-  }
-}
+export const readProjectJson = readProjectJsonSync
 
 export function normalizeType(raw?: string): WallpaperType {
   switch (raw?.toLowerCase()) {
@@ -318,8 +315,10 @@ function getDirSize(dirPath: string): number {
   return total
 }
 
+const SIZE_CHECK_BATCH = 4
+
 // extra folders are often on HDDs, don't block the main process
-export async function getDirSizeAsync(dirPath: string): Promise<number> {
+export async function getDirSizeAsync(dirPath: string, skipShaderCache = false, baseDir = dirPath): Promise<number> {
   let total = 0
   let entries: fs.Dirent[]
   try {
@@ -330,7 +329,8 @@ export async function getDirSizeAsync(dirPath: string): Promise<number> {
   for (const entry of entries) {
     const full = path.join(dirPath, entry.name)
     if (entry.isDirectory()) {
-      total += await getDirSizeAsync(full)
+      if (skipShaderCache && isShaderCache(path.relative(baseDir, full))) continue
+      total += await getDirSizeAsync(full, skipShaderCache, baseDir)
     } else if (entry.isFile()) {
       try { total += (await fs.promises.stat(full)).size } catch { }
     }
@@ -450,7 +450,7 @@ async function buildLocalMeta(
 ): Promise<WallpaperMeta | null> {
   const pj = readProjectJson(localPath)
   if (!pj) return null
-  const fileSize = await getDirSizeAsync(localPath)
+  const fileSize = await getDirSizeAsync(localPath, true)
   const authorSteamId = existing?.authorSteamId ?? details?.authorSteamId
   return {
     ...buildMeta(id, localPath, pj, existing, details?.timeUpdated, authorSteamId, details?.tags, fileSize),
@@ -479,6 +479,97 @@ export async function importLocalWallpaper(localPath: string): Promise<Wallpaper
   return meta
 }
 
+const backupChecks = new Map<string, { sourceDir: string; backupDir: string; stamp: string; holds: boolean }>()
+
+async function folderStamp(dir: string): Promise<string> {
+  const stat = await fs.promises.stat(dir).catch(() => null)
+  return stat ? `${stat.mtimeMs}:${await newestEntryMtime(dir, stat.mtimeMs)}` : ''
+}
+
+// a folder that did not match is looked at again only after one of the two changed, hashing takes minutes
+async function backupHoldsEverything(id: string, sourceDir: string, backupDir: string): Promise<boolean> {
+  const stamp = `${await folderStamp(sourceDir)}|${await folderStamp(backupDir)}`
+  const known = backupChecks.get(id)
+  if (known && known.sourceDir === sourceDir && known.backupDir === backupDir && known.stamp === stamp) return known.holds
+  const holds = (await hasBackupFiles(backupDir)) && (await backupMatchesSource(sourceDir, backupDir))
+  backupChecks.set(id, { sourceDir, backupDir, stamp, holds })
+  return holds
+}
+
+interface SizeSeen {
+  mtimeMs: number
+  projectMtimeMs: number
+  size: number
+}
+
+const sizeStore = openStore<{ seen: Record<string, SizeSeen> }>({ name: 'size-cache', defaults: { seen: {} } })
+const sizeSeen = new Map<string, SizeSeen>(Object.entries(sizeStore.get('seen')))
+
+const NEWEST_MTIME_DEPTH = 3
+
+async function newestEntryMtime(dir: string, folderMtimeMs: number, depth = NEWEST_MTIME_DEPTH): Promise<number> {
+  let newest = folderMtimeMs
+  const entries = await fs.promises.readdir(dir).catch(() => [] as string[])
+  const stats = await Promise.all(entries.map((name) => fs.promises.stat(path.join(dir, name)).catch(() => null)))
+  const nested: Promise<number>[] = []
+  stats.forEach((stat, i) => {
+    if (!stat) return
+    if (stat.mtimeMs > newest) newest = stat.mtimeMs
+    if (depth > 1 && stat.isDirectory()) nested.push(newestEntryMtime(path.join(dir, entries[i]), stat.mtimeMs, depth - 1))
+  })
+  for (const mtime of await Promise.all(nested)) if (mtime > newest) newest = mtime
+  return newest
+}
+
+type SizePatches = { id: string; patch: Partial<WallpaperMeta> }[]
+
+// scans and backup scans can overlap, one run at a time keeps them from repeating the walk and overwriting each other's cache
+let sizeQueue: Promise<unknown> = Promise.resolve()
+
+export function sizeRepairs(list: WallpaperMeta[], pruneUnlisted = false): Promise<SizePatches> {
+  const run = sizeQueue.then(() => measureSizes(list, pruneUnlisted))
+  sizeQueue = run.catch(() => undefined)
+  return run
+}
+
+async function measureSizes(list: WallpaperMeta[], pruneUnlisted: boolean): Promise<SizePatches> {
+  const patches: SizePatches = []
+  const measured = list.filter((w) => w.source !== 'workshop' && !w.downloading && w.localPath)
+  let cacheChanged = false
+  if (pruneUnlisted) {
+    const listed = new Set(measured.map((w) => w.localPath))
+    for (const dir of sizeSeen.keys()) {
+      if (listed.has(dir)) continue
+      sizeSeen.delete(dir)
+      cacheChanged = true
+    }
+  }
+  for (let i = 0; i < measured.length; i += SIZE_CHECK_BATCH) {
+    await Promise.all(
+      measured.slice(i, i + SIZE_CHECK_BATCH).map(async (w) => {
+        const dir = w.localPath!
+        const [stat, project] = await Promise.all([
+          fs.promises.stat(dir).catch(() => null),
+          fs.promises.stat(path.join(dir, 'project.json')).catch(() => null)
+        ])
+        if (!stat?.isDirectory()) return
+        const projectMtimeMs = project?.mtimeMs ?? 0
+        const mtimeMs = await newestEntryMtime(dir, stat.mtimeMs)
+        const seen = sizeSeen.get(dir)
+        if (seen && seen.mtimeMs === mtimeMs && seen.projectMtimeMs === projectMtimeMs && seen.size === w.fileSize) return
+        const fileSize = await getDirSizeAsync(dir, true)
+        // a folder that could not be read comes back as 0
+        if (fileSize <= 0) return
+        sizeSeen.set(dir, { mtimeMs, projectMtimeMs, size: fileSize })
+        cacheChanged = true
+        if (fileSize !== w.fileSize) patches.push({ id: w.id, patch: { fileSize } })
+      })
+    )
+  }
+  if (cacheChanged) sizeStore.set('seen', Object.fromEntries(sizeSeen))
+  return patches
+}
+
 export async function scanLibrary(): Promise<{ imported: number; skipped: number; removed: number }> {
   const workshopPath = getWorkshopPath()
   // unmounted drive must not empty the library
@@ -487,10 +578,33 @@ export async function scanLibrary(): Promise<{ imported: number; skipped: number
   const entries = workshopMounted
     ? fs.readdirSync(workshopPath, { withFileTypes: true }).filter((e) => !e.name.startsWith('.'))
     : []
-  const onDisk = new Set(entries.filter(e => e.isDirectory()).map(e => e.name))
-  const subscribedIds = isSteamRunning()
-    ? new Set(await getSubscribedItems().catch(() => []))
-    : new Set<string>()
+  let subscriptionsKnown = false
+  const subscribedIds = new Set<string>()
+  if (isSteamRunning()) {
+    try {
+      for (const id of await getSubscribedItems()) subscribedIds.add(id)
+      // an empty answer is what Steam gives before it has synced, it must not read as "unsubscribed from everything",
+      // and as Spacewar the list is not Wallpaper Engine's
+      subscriptionsKnown = subscribedIds.size > 0 && getSteamIdentity() === 'wallpaper-engine'
+    } catch {
+      // unknown, keep every folder
+    }
+  }
+  // folders Steam left behind after an unsubscribe
+  const leftovers = new Set(
+    subscriptionsKnown ? entries.filter((e) => e.isDirectory() && !subscribedIds.has(e.name)).map((e) => e.name) : []
+  )
+  const onDisk = new Set(entries.filter((e) => e.isDirectory()).map((e) => e.name))
+
+  // hashing both folders can take minutes, so it happens before the library is read for this scan
+  const backupComplete = new Map<string, boolean>()
+  const stored = store.get('wallpapers')
+  for (const id of leftovers) {
+    const w = stored[id]
+    const dir = path.join(workshopPath, id)
+    if ((w?.source !== 'backup' && w?.source !== 'workshop') || !w.backedUp || !w.backupDir || path.resolve(w.backupDir) === path.resolve(dir)) continue
+    backupComplete.set(id, await backupHoldsEverything(id, dir, w.backupDir))
+  }
 
   const wallpapers = { ...store.get('wallpapers') }
   let imported = 0
@@ -498,6 +612,30 @@ export async function scanLibrary(): Promise<{ imported: number; skipped: number
   let removed = 0
   let resynced = false
 
+  if (subscriptionsKnown) {
+    for (const [id, w] of Object.entries(wallpapers)) {
+      if (w.source !== 'workshop' || subscribedIds.has(id)) continue
+      const backupDir = w.backedUp ? w.backupDir : undefined
+      if (backupDir && fs.existsSync(path.join(backupDir, 'project.json'))) {
+        const pj = readProjectJson(backupDir)
+        const preview = containedPath(backupDir, pj?.preview)
+        wallpapers[id] = {
+          ...w,
+          source: 'backup',
+          localPath: backupDir,
+          previewLocal: preview && fs.existsSync(preview) ? preview : w.previewLocal,
+          subscribed: false,
+          downloading: false,
+          downloadFailed: false
+        }
+        resynced = true
+      } else if (w.subscribed) {
+        wallpapers[id] = { ...w, subscribed: false }
+        resynced = true
+      }
+    }
+  }
+
   // drop workshop items whose folder is gone, unless still subscribed (tracked below)
   for (const id of Object.keys(wallpapers)) {
     if (wallpapers[id].source !== 'workshop' || !workshopMounted) continue
@@ -507,17 +645,39 @@ export async function scanLibrary(): Promise<{ imported: number; skipped: number
     }
   }
 
+  // Steam leaves the folder behind after an unsubscribe, the backup is the copy to keep
+  const backedUpLeftovers = new Set<string>()
+  let subscribedNow: Set<string> | null | undefined
+  for (const id of leftovers) {
+    const w = wallpapers[id]
+    const dir = path.join(workshopPath, id)
+    if (w?.source !== 'backup' || !w.backedUp || !w.backupDir || path.resolve(w.backupDir) === path.resolve(dir)) continue
+    if (!backupComplete.get(id)) continue
+    if (subscribedNow === undefined) {
+      subscribedNow = await getSubscribedItems().then((ids) => new Set(ids)).catch(() => null)
+    }
+    if (!subscribedNow || subscribedNow.has(id)) continue
+    backedUpLeftovers.add(id)
+    try {
+      await fs.promises.rm(dir, { recursive: true, force: true })
+      console.log(`[Library] Removed ${dir}, ${id} is unsubscribed and backed up`)
+    } catch (err) {
+      console.warn(`[Library] Could not remove ${dir}:`, err)
+    }
+  }
+
   const incomplete: { id: string; localPath: string }[] = []
   const toRebuild: { entry: fs.Dirent; localPath: string; pj: ProjectJson }[] = []
   const cacheHits: string[] = []
   for (const entry of entries) {
-    if (!entry.isDirectory()) continue
+    if (!entry.isDirectory() || backedUpLeftovers.has(entry.name)) continue
+    if (leftovers.has(entry.name) && wallpapers[entry.name]?.source === 'backup') continue
 
     const localPath = path.join(workshopPath, entry.name)
     const pj = readProjectJson(localPath)
 
     if (!pj) {
-      incomplete.push({ id: entry.name, localPath })
+      if (!leftovers.has(entry.name)) incomplete.push({ id: entry.name, localPath })
       continue
     }
 
@@ -662,6 +822,9 @@ export async function scanLibrary(): Promise<{ imported: number; skipped: number
         patch.contentRating = stricter
       }
     }
+    if (subscriptionsKnown && subscribedIds.has(id) && wallpapers[id].source === 'workshop' && !wallpapers[id].subscribed) {
+      patch.subscribed = true
+    }
     if (live) {
       const resolutions = resolutionsFromTags(live)
       if (!sameTags(wallpapers[id].resolutions, resolutions)) {
@@ -674,10 +837,24 @@ export async function scanLibrary(): Promise<{ imported: number; skipped: number
     }
   }
 
+  for (const id of leftovers) {
+    const w = wallpapers[id]
+    if (w?.source === 'workshop' && w.subscribed) {
+      wallpapers[id] = { ...w, subscribed: false }
+      resynced = true
+    }
+  }
+
   if (imported > 0 || removed > 0 || resynced) {
     store.set('wallpapers', wallpapers)
   }
 
+  void sizeRepairs(Object.values(wallpapers), true)
+    .then((sizePatches) => {
+      if (sizePatches.length > 0) applyWallpaperChanges({ patches: sizePatches })
+    })
+    .catch((err: unknown) => { console.warn('[Library] Size check failed:', err) })
+
   console.log(`[Library] Scan complete: ${imported} imported, ${skipped} skipped, ${removed} removed`)
 
   cleanupFolders()
@@ -692,20 +869,21 @@ export async function checkUnavailableWallpapers(): Promise<{
   checked: number
   unavailable: number
   changed: boolean
+  failed: boolean
 }> {
-  if (!isSteamRunning()) return { checked: 0, unavailable: 0, changed: false }
+  if (!isSteamRunning()) return { checked: 0, unavailable: 0, changed: false, failed: true }
 
   const wallpapers = store.get('wallpapers')
   const candidates = Object.values(wallpapers).filter(
     (w) => w.source === 'workshop' && !!w.localPath && !w.downloading
   )
-  if (candidates.length === 0) return { checked: 0, unavailable: 0, changed: false }
+  if (candidates.length === 0) return { checked: 0, unavailable: 0, changed: false, failed: false }
 
   let unavailableIds: Set<string>
   try {
     unavailableIds = await getUnavailableWorkshopItems(candidates.map((w) => w.id))
   } catch {
-    return { checked: 0, unavailable: 0, changed: false }
+    return { checked: 0, unavailable: 0, changed: false, failed: true }
   }
 
   let changed = false
@@ -718,7 +896,7 @@ export async function checkUnavailableWallpapers(): Promise<{
   }
   if (changed) store.set('wallpapers', wallpapers)
 
-  return { checked: candidates.length, unavailable: unavailableIds.size, changed }
+  return { checked: candidates.length, unavailable: unavailableIds.size, changed, failed: false }
 }
 
 function isFromWorkshop(w: WallpaperMeta): boolean {

+ 1 - 4
src/main/services/lwe-libnode.service.ts

@@ -1,5 +1,3 @@
-import { execFile } from 'child_process'
-import { promisify } from 'util'
 import * as fs from 'fs'
 import * as os from 'os'
 import * as path from 'path'
@@ -12,8 +10,7 @@ import { isFlatpak } from '../utils/flatpak'
 import { downloadVerified, fetchReleaseByTag, type GithubAsset } from '../utils/github'
 import { detectDistro } from './lwe.service'
 import { t } from '../i18n'
-
-const execFileAsync = promisify(execFile)
+import { execFileAsync } from '../utils/exec'
 
 const LIBNODE_RELEASE_TAG = 'libnode-arch'
 const LIBNODE_ASSET = /^libnode-.+-x86_64\.pkg\.tar\.zst$/

+ 9 - 14
src/main/services/lwe-prebuilt.service.ts

@@ -1,5 +1,3 @@
-import { execFile } from 'child_process'
-import { promisify } from 'util'
 import * as fs from 'fs'
 import * as path from 'path'
 import type { BrowserWindow } from 'electron'
@@ -12,8 +10,7 @@ import { isFlatpak } from '../utils/flatpak'
 import { downloadVerified, fetchLatestRelease, fetchReleaseByTag, isVersionTag, type GithubRelease } from '../utils/github'
 import { buildCleanBuildEnv, isOstreeSystem, pacmanHasSyncDatabases, parseOsReleaseIds, readPrebuiltRelease, resetLweDetection } from './lwe.service'
 import { t } from '../i18n'
-
-const execFileAsync = promisify(execFile)
+import { execFileAsync } from '../utils/exec'
 
 /** bundles all but desktop libraries, needs glibc 2.35+ */
 type PrebuiltDistro = 'ubuntu-24.04' | 'fedora-44' | 'portable'
@@ -197,6 +194,10 @@ async function findMissingLibraries(binary: string): Promise<string[]> {
   return [...missing]
 }
 
+function manualInstallError(missing: string[]): Error {
+  return new Error(`These system libraries are missing: ${missing.join(', ')}. Install the packages providing them with your package manager.`)
+}
+
 /** true when layered with rpm-ostree, which needs a reboot */
 async function installMissingLibraries(distro: PrebuiltDistro, missing: string[]): Promise<boolean> {
   const ids = parseOsReleaseIds(fs.existsSync('/etc/os-release') ? fs.readFileSync('/etc/os-release', 'utf8') : '')
@@ -211,9 +212,7 @@ async function installMissingLibraries(distro: PrebuiltDistro, missing: string[]
   let command: string[]
   if (distro === 'ubuntu-24.04') {
     const absent = await absentDebianPackages(RUNTIME_DEPS_UBUNTU.map(name => [name]))
-    if (absent.length === 0) {
-      throw new Error(`These system libraries are missing: ${missing.join(', ')}. Install the packages providing them with your package manager.`)
-    }
+    if (absent.length === 0) throw manualInstallError(missing)
     command = ['apt-get', 'install', '-y', ...absent]
   } else if (ids.includes('fedora') && isCommandAvailable('dnf')) {
     command = ['dnf', 'install', '-y', ...bySoname]
@@ -222,18 +221,14 @@ async function installMissingLibraries(distro: PrebuiltDistro, missing: string[]
   } else if (ids.includes('arch') && isCommandAvailable('pacman')) {
     // only what is absent: asking for installed ones would pull newer versions of core packages (a partial upgrade)
     const absent = await absentPacmanPackages(RUNTIME_DEPS_ARCH)
-    if (absent.length === 0) {
-      throw new Error(`These system libraries are missing: ${missing.join(', ')}. Install the packages providing them with your package manager.`)
-    }
+    if (absent.length === 0) throw manualInstallError(missing)
     command = ['pacman', pacmanHasSyncDatabases() ? '-S' : '-Sy', '--noconfirm', '--needed', ...absent]
   } else if (ids.includes('debian') && isCommandAvailable('apt-get')) {
     const absent = await absentDebianPackages(RUNTIME_DEPS_DEBIAN)
-    if (absent.length === 0) {
-      throw new Error(`These system libraries are missing: ${missing.join(', ')}. Install the packages providing them with your package manager.`)
-    }
+    if (absent.length === 0) throw manualInstallError(missing)
     command = ['apt-get', 'install', '-y', ...absent]
   } else {
-    throw new Error(`These system libraries are missing: ${missing.join(', ')}. Install the packages providing them with your package manager.`)
+    throw manualInstallError(missing)
   }
   await execFileAsync(elevate, command, { timeout: 600_000, maxBuffer: 10 * 1024 * 1024 })
   return false

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

@@ -34,6 +34,7 @@ const {
   nodeDevelPackage,
   parsePacmanRepos,
   parseCustomArgs,
+  parseAudioInputList,
   parseOsReleaseIds
 } = await import('./lwe.service')
 
@@ -108,6 +109,24 @@ describe('buildLweArgs', () => {
   })
 })
 
+describe('audio input', () => {
+  it('writes the hotswap keys', () => {
+    expect(buildHotswapLines({ audioInput: 'default', audioInputVolume: 50, audioInputThreshold: 0 })).toEqual([
+      'audio-input=default',
+      'audio-input-volume=50',
+      'audio-input-threshold=0'
+    ])
+  })
+
+  it('reads the engine list', () => {
+    const out = 'a.monitor\tmonitor\tMonitor of A\nmic\tinput\tUSB\tMic\n\nbroken line\nx\tother\ty\n'
+    expect(parseAudioInputList(out)).toEqual([
+      { name: 'a.monitor', description: 'Monitor of A', monitor: true },
+      { name: 'mic', description: 'USB\tMic', monitor: false }
+    ])
+  })
+})
+
 describe('buildHotswapLines', () => {
   it('writes only the fields that were given', () => {
     expect(buildHotswapLines({ volume: 40, xray: 'normal' })).toEqual(['volume=40', 'xray=off'])

+ 66 - 10
src/main/services/lwe.service.ts

@@ -1,5 +1,4 @@
-import { execFile, execFileSync, spawn, type ChildProcess } from 'child_process'
-import { promisify } from 'util'
+import { execFileSync, spawn, type ChildProcess } from 'child_process'
 import * as fs from 'fs'
 import * as path from 'path'
 import * as os from 'os'
@@ -21,6 +20,7 @@ import type {
   ScreenTarget,
   HwdecBackend,
   HrtfMode,
+  AudioInputDevice,
   TransitionDuration,
   TransitionMode,
   BatteryFps,
@@ -71,11 +71,11 @@ import { engineFlagArgs, filterSupportedArgs } from '@shared/engineFlags'
 import { imageAdjustmentArgs, imageAdjustmentLines, type ImageAdjustments } from '@shared/imageAdjustments'
 import { formatVideoSegments, type VideoSegment } from '@shared/videoTrim'
 import { t } from '../i18n'
+import { setTimeout as sleep } from 'timers/promises'
+import { execFileAsync } from '../utils/exec'
 
 export const ALL_SCREENS: ScreenTarget = '*'
 
-const execFileAsync = promisify(execFile)
-
 // AppRun points LD_LIBRARY_PATH etc. into /tmp/.mount_*, which CMake would cache
 const APPIMAGE_MOUNT = /^\/tmp\/\.mount_[^/]+(\/|$)/
 
@@ -1494,16 +1494,18 @@ export interface RunningInstance {
   pid: number
   startedAt: number
   swappedAt: number | null
+  hostPid: number | null
 }
 
 export function getRunningInstances(): RunningInstance[] {
-  return liveInstances().map(({ screen, wallpaperPath, split, pid, startedAt, swappedAt }) => ({
+  return liveInstances().map(({ screen, wallpaperPath, split, pid, startedAt, swappedAt, hostPid }) => ({
     screen,
     wallpaperPath,
     split,
     pid,
     startedAt,
-    swappedAt
+    swappedAt,
+    hostPid
   }))
 }
 
@@ -1552,6 +1554,10 @@ function supportsHrtfHotswap(): boolean {
   return supportsFlag('hrtf=<mode>')
 }
 
+function supportsAudioInputHotswap(): boolean {
+  return supportsFlag('audio-input=<source>')
+}
+
 function supportsTransitionHotswap(): boolean {
   return supportsFlag('transition=<kind>')
 }
@@ -1579,6 +1585,9 @@ function launchKey(options: LweLaunchOptions): string {
       ...flags,
       ...(supportsHwdecHotswap() ? { hwdec: undefined } : {}),
       ...(supportsHrtfHotswap() ? { hrtf: undefined } : {}),
+      ...(supportsAudioInputHotswap()
+        ? { audioInput: undefined, audioInputVolume: undefined, audioInputThreshold: undefined }
+        : {}),
       ...(supportsTransitionHotswap() ? { transition: undefined, transitionDuration: undefined } : {}),
       ...(supportsPowerHotswap() ? { batteryFps: undefined, idlePause: undefined } : {})
     })
@@ -1594,6 +1603,9 @@ export interface HotswapOptions extends HotswapSettings {
   disableAnimations?: boolean
   hwdec?: HwdecBackend
   hrtf?: HrtfMode
+  audioInput?: string
+  audioInputVolume?: number
+  audioInputThreshold?: number
   transition?: TransitionMode
   transitionDuration?: TransitionDuration
   batteryFps?: BatteryFps
@@ -1617,6 +1629,9 @@ export function buildHotswapLines(options: HotswapOptions): string[] {
   if (options.disableAnimations !== undefined) lines.push(`disable-animations=${options.disableAnimations ? 'on' : 'off'}`)
   if (options.hwdec !== undefined) lines.push(`hwdec=${options.hwdec}`)
   if (options.hrtf !== undefined) lines.push(`hrtf=${options.hrtf}`)
+  if (options.audioInput !== undefined) lines.push(`audio-input=${options.audioInput}`)
+  if (options.audioInputVolume !== undefined) lines.push(`audio-input-volume=${options.audioInputVolume}`)
+  if (options.audioInputThreshold !== undefined) lines.push(`audio-input-threshold=${options.audioInputThreshold}`)
   if (options.transition !== undefined) lines.push(`transition=${options.transition}`)
   if (options.transitionDuration !== undefined) lines.push(`transition-duration=${options.transitionDuration}`)
   if (options.batteryFps !== undefined) lines.push(`fps-battery=${options.batteryFps}`)
@@ -1670,7 +1685,7 @@ function signalInstance(inst: LweInstance, lines: string[]): Promise<boolean> {
   const send = async (): Promise<boolean> => {
     if (lastSignal && lastSignal.pid !== inst.pid && lastSignal.file === file) {
       const wait = lastSignal.at + HOTSWAP_SETTLE_MS - Date.now()
-      if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait))
+      if (wait > 0) await sleep(wait)
     }
     try {
       fs.writeFileSync(file, lines.join('\n') + '\n')
@@ -1720,10 +1735,28 @@ export async function hotswapLweSettings(
 
 export function liveEngineFlagOptions(
   flags: EngineFlags
-): Pick<HotswapOptions, 'hwdec' | 'hrtf' | 'transition' | 'transitionDuration' | 'batteryFps' | 'idlePause'> {
+): Pick<
+  HotswapOptions,
+  | 'hwdec'
+  | 'hrtf'
+  | 'audioInput'
+  | 'audioInputVolume'
+  | 'audioInputThreshold'
+  | 'transition'
+  | 'transitionDuration'
+  | 'batteryFps'
+  | 'idlePause'
+> {
   return {
     ...(supportsHwdecHotswap() ? { hwdec: flags.hwdec ?? 'auto' } : {}),
     ...(supportsHrtfHotswap() ? { hrtf: flags.hrtf ?? 'auto' } : {}),
+    ...(supportsAudioInputHotswap()
+      ? {
+          audioInput: flags.audioInput ?? 'default',
+          audioInputVolume: flags.audioInputVolume ?? 50,
+          audioInputThreshold: flags.audioInputThreshold ?? 0
+        }
+      : {}),
     ...(supportsTransitionHotswap()
       ? { transition: flags.transition ?? 'none', transitionDuration: flags.transitionDuration ?? '600' }
       : {}),
@@ -1999,6 +2032,29 @@ export async function listLweFonts(wallpaperPath: string): Promise<LweFontNeed[]
   return parseLweFontList(stdout)
 }
 
+/** `name<TAB>input|monitor<TAB>description` per line */
+export function parseAudioInputList(output: string): AudioInputDevice[] {
+  const devices: AudioInputDevice[] = []
+  for (const line of output.split('\n')) {
+    const [name, kind, ...description] = line.split('\t')
+    if (!name || (kind !== 'input' && kind !== 'monitor')) continue
+    devices.push({ name, description: description.join('\t'), monitor: kind === 'monitor' })
+  }
+  return devices
+}
+
+export async function listAudioInputs(): Promise<AudioInputDevice[]> {
+  const status = getLweStatus()
+  if (!status.installed || !supportsFlag('--list-audio-inputs')) return []
+
+  const { stdout } = await execFileAsync('env', [...buildLweEnvVars(), getLweBinaryPath(), '--list-audio-inputs'], {
+    timeout: 10_000,
+    maxBuffer: 1024 * 1024,
+    encoding: 'utf8'
+  })
+  return parseAudioInputList(stdout)
+}
+
 // `  42 - Bloom (object=17 objectName="body" group="Lighting")`
 const EFFECT_LINE_RE = /^\s*(\S+)\s-\s(.*)\s\(object=(\S+)\sobjectName="(.*)"\sgroup="(.*)"\)\s*$/
 
@@ -2111,7 +2167,7 @@ async function pollUntilGone(target: EngineProcess, timeoutMs: number): Promise<
       }
     }
     // every check of another sandbox's engine is a flatpak-spawn round trip
-    await new Promise((resolve) => setTimeout(resolve, other ? 100 : 25))
+    await sleep(other ? 100 : 25)
   }
   return false
 }
@@ -2209,7 +2265,7 @@ export async function captureLweScreenshot(
     const deadline = Date.now() + SCREENSHOT_TIMEOUT_MS
     let lastSize = -1
     while (Date.now() < deadline) {
-      await new Promise((resolve) => setTimeout(resolve, 250))
+      await sleep(250)
       if (child.exitCode !== null || child.signalCode !== null) {
         const msg = stderr.join('').trim().split('\n').slice(-3).join('\n')
         throw new Error(`linux-wallpaperengine exited before taking the screenshot${msg ? `: ${msg}` : ''}`)

+ 175 - 16
src/main/services/playlist-player.service.ts

@@ -2,6 +2,14 @@ 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'
+import {
+  dayOfWeekEnds,
+  daytimeEnds,
+  logonIndex,
+  scheduledIndexNow,
+  type LogonEntry,
+  type ScheduledMode
+} from '@shared/playlistSchedule'
 import { compatStatus } from '@shared/compat'
 import { trimmedVideoLength, videoSegmentsOf } from '@shared/videoTrim'
 import { getAllPlaylists, getPlaylist } from './playlist.service'
@@ -12,6 +20,7 @@ import { mergePlayers, playlistSkipScreens, savedScreensFor } from './restore-pl
 import { getAssignments } from './wallpaper-state.service'
 import { getFavoriteItemIds } from './steam.service'
 import { expandScreen, getDisplayTargets, setBusyWallpaperSource, setPlaylistRecovery, setVolumeSource, showWallpaper } from './display.service'
+import { loginSessionToken } from '../utils/loginSession'
 import { findWallpaperVideoFile, getVideoDurationSec } from '../utils/video'
 
 interface SavedPlayer {
@@ -25,11 +34,13 @@ interface PlaybackStore {
   activePlaylistId: string | null
   isPlaying: boolean
   players: Record<ScreenTarget, SavedPlayer> | null
+  /** per playlist: the item the last login session started with */
+  logon: Record<string, LogonEntry>
 }
 
 const store = openStore<PlaybackStore>({
   name: 'playlist-playback',
-  defaults: { activePlaylistId: null, isPlaying: false, players: null }
+  defaults: { activePlaylistId: null, isPlaying: false, players: null, logon: {} }
 })
 
 interface Player {
@@ -41,6 +52,11 @@ interface Player {
   /** The item the playlist itself put on the screen last, the playlist goes on from there after a restart */
   lastShown: string | null
   suspended: boolean
+  /** clock modes: the item the clock chose last, so a manual pick holds until the clock moves on */
+  clockItem: number | null
+  clockWallpaper: string | null
+  clockRetryAt: number
+  scheduledMode: string | null
 }
 
 let win: BrowserWindow | null = null
@@ -65,7 +81,48 @@ function shuffle<T>(arr: T[]): T[] {
   return copy
 }
 
+/** The clock modes need two or more items, a single wallpaper just stays */
+function clockMode(playlist: Playlist): ScheduledMode | null {
+  const mode = playlist.settings.mode
+  return (mode === 'daytime' || mode === 'dayofweek') && playlist.items.length > 1 ? mode : null
+}
+
+function fixedOrder(playlist: Playlist): boolean {
+  return clockMode(playlist) !== null || (playlist.settings.mode === 'logon' && playlist.items.length > 1)
+}
+
+function firstWeekday(): number {
+  const tag = [process.env.LC_ALL, process.env.LC_TIME, process.env.LANG].find((v) => v)
+  const name = tag?.split('.')[0].split('@')[0].replace('_', '-')
+  if (!name || name === 'C' || name === 'POSIX') return 0
+  try {
+    const locale = new Intl.Locale(name) as Intl.Locale & { getWeekInfo?: () => { firstDay: number } }
+    return (locale.getWeekInfo?.().firstDay ?? 7) % 7
+  } catch {
+    return 0
+  }
+}
+
+/** The item the clock wants now, an index into the playlist's items (which is also the order of these modes) */
+function clockIndex(playlist: Playlist, mode: ScheduledMode, now = new Date()): number {
+  const ends =
+    mode === 'daytime'
+      ? daytimeEnds(playlist.items.map((item) => (item.endMinute ?? 0) / 1440))
+      : dayOfWeekEnds(playlist.items.length)
+  return Math.min(scheduledIndexNow(ends, mode, now, firstWeekday()), playlist.items.length - 1)
+}
+
+function logonItem(playlist: Playlist): number {
+  const saved = store.get('logon')
+  const entry = logonIndex(saved[playlist.id], playlist.items.length, loginSessionToken())
+  if (saved[playlist.id]?.index !== entry.index || saved[playlist.id]?.session !== entry.session) {
+    store.set('logon', { ...saved, [playlist.id]: entry })
+  }
+  return entry.index
+}
+
 function buildOrder(playlist: Playlist): string[] {
+  if (fixedOrder(playlist)) return playlist.items.map((i) => i.wallpaperId)
   if (playlist.settings.randomize) {
     return shuffle(playlist.items.map((i) => i.wallpaperId))
   }
@@ -137,8 +194,13 @@ function known(id: string): boolean {
   return compatStatus(getWallpaper(id)?.compat) !== 'crashes'
 }
 
+/** True when applyCurrent would not have skipped this item on purpose, so not showing it means the launch failed */
+function wasPlayable(playlist: Playlist, order: string[], id: string): boolean {
+  return rotationFilter(playlist, order)(id) && known(id)
+}
+
 /** 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> {
+async function applyCurrent(player: Player, playlist: Playlist, picked?: string): Promise<boolean> {
   const { state } = player
   const count = state.order.length
   const inRotation = rotationFilter(playlist, state.order)
@@ -150,7 +212,7 @@ async function applyCurrent(player: Player, playlist: Playlist, picked?: string)
   player.applying = true
   try {
     for (let tries = 0; tries < count; tries++, state.currentIndex = (state.currentIndex + 1) % count) {
-      if (stale()) return
+      if (stale()) return false
       const wallpaper = getWallpaper(state.order[state.currentIndex])
       if (!wallpaper) continue
       if (wallpaper.id !== picked && (!inRotation(wallpaper.id) || (anyPlayable && !known(wallpaper.id)))) continue
@@ -165,7 +227,7 @@ async function applyCurrent(player: Player, playlist: Playlist, picked?: string)
         console.error('[PlaylistPlayer] Failed to apply wallpaper:', err)
         continue
       }
-      if (stale()) return
+      if (stale()) return false
       // a launch that something newer overtook is not what the screen shows
       if (assignedId(state.screen) === wallpaper.id) {
         updateWallpaper(wallpaper.id, {
@@ -174,18 +236,21 @@ async function applyCurrent(player: Player, playlist: Playlist, picked?: string)
         })
         state.currentItemId = wallpaper.id
         player.lastShown = wallpaper.id
+        return true
       }
-      return
+      return false
     }
+    return false
   } finally {
     if (player.applyId === mine) player.applying = false
   }
 }
 
-async function showCurrent(player: Player, playlist: Playlist, picked?: string): Promise<void> {
+async function showCurrent(player: Player, playlist: Playlist, picked?: string, applied?: (shown: boolean) => void): Promise<void> {
   const state = player.state
-  await applyCurrent(player, playlist, picked)
+  const shown = await applyCurrent(player, playlist, picked)
   if (player.state !== state) return
+  applied?.(shown)
   scheduleNext(player, playlist)
   try {
     persist([], false)
@@ -206,9 +271,22 @@ async function getVideoLengthSec(wallpaperId: string): Promise<number | undefine
   return duration === undefined ? undefined : trimmedVideoLength(duration, videoSegmentsOf(wallpaper))
 }
 
-function scheduleNext(player: Player, playlist: Playlist): void {
+function scheduleNext(player: Player, stale: Playlist): void {
   clearTimer(player)
   if (!player.state.isPlaying) return
+  const playlist = getPlaylist(stale.id) ?? stale
+  player.scheduledMode = playlist.settings.mode ?? 'timer'
+
+  const mode = clockMode(playlist)
+  if (mode) {
+    player.timer = setTimeout(() => {
+      void followClock(player, playlist, mode)
+    }, CLOCK_CHECK_MS)
+    return
+  }
+  // a logon playlist stays on its item until the next session
+  if (playlist.settings.mode === 'logon' && playlist.items.length > 1) return
+  if (playlist.items.length <= 1 && playlist.settings.mode && playlist.settings.mode !== 'timer') return
 
   const wallpaperId = player.state.order[player.state.currentIndex]
   const item = wallpaperId ? findItem(playlist, wallpaperId) : undefined
@@ -236,8 +314,60 @@ function scheduleNext(player: Player, playlist: Playlist): void {
   })
 }
 
+const CLOCK_CHECK_MS = 5000
+const CLOCK_RETRY_MS = 60_000
+
+async function followClock(player: Player, playlist: Playlist, mode: ScheduledMode): Promise<void> {
+  if (players.get(player.state.screen) !== player || !player.state.isPlaying) return
+  const current = getPlaylist(playlist.id)
+  if (!current) {
+    stopPlaylist(player.state.screen)
+    return
+  }
+  if (clockMode(current) !== mode) {
+    startOn(player.state.screen, current)
+    return
+  }
+
+  const target = clockIndex(current, mode)
+  const targetWallpaper = current.items[target]?.wallpaperId ?? null
+  if ((target !== player.clockItem || targetWallpaper !== player.clockWallpaper) && !player.applying && Date.now() >= player.clockRetryAt) {
+    const token = player.scheduleToken
+    player.state.order = buildOrder(current)
+    player.state.currentIndex = target
+    const shown = await applyCurrent(player, current)
+    const fellBack = shown && targetWallpaper !== null && player.state.currentItemId !== targetWallpaper && wasPlayable(current, player.state.order, targetWallpaper)
+    if (shown && !fellBack) {
+      player.clockItem = target
+      player.clockWallpaper = targetWallpaper
+    } else player.clockRetryAt = Date.now() + CLOCK_RETRY_MS
+    if (token !== player.scheduleToken || players.get(player.state.screen) !== player) return
+    emitState()
+  }
+  scheduleNext(player, current)
+}
+
+/** Only a shown item counts as the clock's position, a failed one is tried again after a while */
+function noteClockApply(player: Player, playlist: Playlist, target: number, shown: boolean): void {
+  if (shown) {
+    player.clockItem = target
+    player.clockWallpaper = playlist.items[target]?.wallpaperId ?? null
+  } else {
+    player.clockItem = null
+    player.clockWallpaper = null
+    player.clockRetryAt = Date.now() + CLOCK_RETRY_MS
+  }
+}
+
+/** A manual pick holds until the clock moves on from where it is now */
+function holdClock(player: Player, playlist: Playlist): void {
+  const mode = clockMode(playlist)
+  player.clockItem = mode ? clockIndex(playlist, mode) : null
+  player.clockWallpaper = player.clockItem === null ? null : (playlist.items[player.clockItem]?.wallpaperId ?? null)
+}
+
 async function advance(player: Player): Promise<void> {
-  if (!player.state.playlistId || player.applying) return
+  if (!player.state.playlistId || player.applying || players.get(player.state.screen) !== player) return
   const playlist = getPlaylist(player.state.playlistId)
   if (!playlist || playlist.items.length === 0) {
     stopPlaylist(player.state.screen)
@@ -250,7 +380,7 @@ async function advance(player: Player): Promise<void> {
     player.state.currentIndex = 0
   }
 
-  await showCurrent(player, playlist)
+  await showCurrent(player, playlist, undefined, () => holdClock(player, playlist))
 }
 
 function playerFor(screen: ScreenTarget): Player {
@@ -263,7 +393,11 @@ function playerFor(screen: ScreenTarget): Player {
       applying: false,
       applyId: 0,
       lastShown: null,
-      suspended: false
+      suspended: false,
+      clockItem: null,
+      clockWallpaper: null,
+      clockRetryAt: 0,
+      scheduledMode: null
     }
     players.set(screen, player)
   }
@@ -292,21 +426,28 @@ function startOn(screen: ScreenTarget, playlist: Playlist, paused = false, shown
   clearTimer(player)
   const order = buildOrder(playlist)
   const at = paused && shownId ? order.indexOf(shownId) : -1
+  const mode = clockMode(playlist)
+  const clock = mode ? clockIndex(playlist, mode) : null
   player.lastShown = at >= 0 ? order[at] : null
   player.suspended = false
   player.applying = false
   player.applyId++
+  player.clockItem = null
+  player.clockWallpaper = null
+  player.clockRetryAt = 0
   player.state = {
     screen,
     playlistId: playlist.id,
     currentItemId: owns(player) ? player.lastShown : null,
-    currentIndex: Math.max(at, 0),
+    currentIndex: clock ?? (at >= 0 ? at : playlist.settings.mode === 'logon' && playlist.items.length > 1 ? logonItem(playlist) : 0),
     isPlaying: !paused,
     order
   }
   if (paused) return player.state
 
-  void showCurrent(player, playlist)
+  void showCurrent(player, playlist, undefined, (shown) => {
+    if (clock !== null) noteClockApply(player, playlist, clock, shown)
+  })
   return player.state
 }
 
@@ -348,7 +489,7 @@ export async function playItem(playlistId: string, wallpaperId: string, screen?:
       player.applying = false
       player.applyId++
     }
-
+    holdClock(player, playlist)
     let index = player.state.order.indexOf(wallpaperId)
     if (index === -1) {
       player.state.order = buildOrder(playlist)
@@ -363,6 +504,16 @@ export async function playItem(playlistId: string, wallpaperId: string, screen?:
   return getPlaybackStates()
 }
 
+export function playlistEdited(id: string): void {
+  const playlist = getPlaylist(id)
+  if (!playlist) return
+  for (const player of players.values()) {
+    if (player.state.playlistId !== id || !player.state.isPlaying || player.applying) continue
+    if (player.timer && player.scheduledMode === (playlist.settings.mode ?? 'timer')) continue
+    scheduleNext(player, playlist)
+  }
+}
+
 export function stopPlaylist(screen?: ScreenTarget): PlaylistPlaybackState[] {
   const stopped: ScreenTarget[] = []
 
@@ -421,7 +572,15 @@ function resumePlayer(player: Player, playlist: Playlist): void {
 
   if (!owns(player) && !player.applying) {
     clearTimer(player)
-    void showCurrent(player, playlist)
+    const mode = clockMode(playlist)
+    const clock = mode ? clockIndex(playlist, mode) : null
+    if (clock !== null) {
+      player.state.order = buildOrder(playlist)
+      player.state.currentIndex = clock
+    }
+    void showCurrent(player, playlist, undefined, (shown) => {
+      if (clock !== null) noteClockApply(player, playlist, clock, shown)
+    })
   } else {
     scheduleNext(player, playlist)
   }
@@ -461,7 +620,7 @@ export async function previousItem(screen?: ScreenTarget): Promise<PlaylistPlayb
       if (inRotation(order[player.state.currentIndex])) break
     }
 
-    await showCurrent(player, playlist)
+    await showCurrent(player, playlist, undefined, () => holdClock(player, playlist))
   }
   return getPlaybackStates()
 }

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

@@ -112,13 +112,14 @@ export function reorderPlaylistItems(id: string, orderedWallpaperIds: string[]):
 export function updatePlaylistItem(
   id: string,
   wallpaperId: string,
-  patch: { volume?: number; durationSec?: number }
+  patch: { volume?: number; durationSec?: number; endMinute?: number }
 ): Playlist | null {
   return updatePlaylist(id, (playlist) => {
     const item = playlist.items.find((i) => i.wallpaperId === wallpaperId)
     if (!item) return false
     if ('volume' in patch) item.volume = patch.volume
     if ('durationSec' in patch) item.durationSec = patch.durationSec
+    if ('endMinute' in patch) item.endMinute = patch.endMinute
   })
 }
 

+ 57 - 0
src/main/services/profile.service.ts

@@ -0,0 +1,57 @@
+import { randomUUID } from 'crypto'
+import type { Profile, ScreenAction, ScreenTarget } from '@shared/types'
+import { openStore } from '../utils/safeStore'
+import { getWallpaper } from './library.service'
+import { getPlaybackStates } from './playlist-player.service'
+import { getDisplayTargets } from './display.service'
+import { getAssignments } from './wallpaper-state.service'
+
+interface ProfileStore {
+  profiles: Profile[]
+}
+
+const store = openStore<ProfileStore>({
+  name: 'profiles',
+  defaults: { profiles: [] }
+})
+
+export function getProfiles(): Profile[] {
+  return store.get('profiles')
+}
+
+export function getProfile(id: string): Profile | undefined {
+  return getProfiles().find((p) => p.id === id)
+}
+
+export function saveProfile(profile: Omit<Profile, 'id'> & { id?: string }): Profile {
+  const saved: Profile = { ...profile, id: profile.id ?? randomUUID() }
+  const profiles = getProfiles()
+  const index = profiles.findIndex((p) => p.id === saved.id)
+  if (index === -1) profiles.push(saved)
+  else profiles[index] = saved
+  store.set('profiles', profiles)
+  return saved
+}
+
+export function deleteProfile(id: string): void {
+  store.set('profiles', getProfiles().filter((p) => p.id !== id))
+}
+
+/** What a screen shows now: its playlist while one plays, else its wallpaper, else nothing */
+export function currentScreenAction(screen: ScreenTarget): ScreenAction {
+  const playing = getPlaybackStates().find((s) => s.screen === screen && s.playlistId && s.isPlaying)
+  if (playing?.playlistId) return { type: 'playlist', playlistId: playing.playlistId }
+
+  const assignments = getAssignments()
+  const wallpaperId = assignments[screen] ?? assignments['*']
+  if (wallpaperId && getWallpaper(wallpaperId)) return { type: 'wallpaper', wallpaperId }
+  return { type: 'stop' }
+}
+
+export function captureScreens(screens: ScreenTarget[]): Record<ScreenTarget, ScreenAction> {
+  return Object.fromEntries(screens.map((screen) => [screen, currentScreenAction(screen)]))
+}
+
+export function captureProfile(name: string): Profile {
+  return saveProfile({ name, screens: captureScreens(getDisplayTargets()) })
+}

+ 78 - 0
src/main/services/rule-actions.service.ts

@@ -0,0 +1,78 @@
+import type { Profile, ScheduleAction, ScreenAction, ScreenTarget } from '@shared/types'
+import { getWallpaper, updateWallpaper } from './library.service'
+import { getPlaylist } from './playlist.service'
+import { expandScreen, getDisplayTargets, isShownOn, showWallpaper, stopDisplay } from './display.service'
+import { startPlaylist, stopPlaylist } from './playlist-player.service'
+import { getProfile } from './profile.service'
+import { t } from '../i18n'
+
+const runningWallpapers = new Map<string, number>()
+
+/** Wallpapers a rule is in the middle of starting, so they are not optimized or deleted under it */
+export function runningWallpaperIds(): string[] {
+  return [...runningWallpapers.keys()]
+}
+
+export async function runScreenAction(action: ScreenAction, screen: ScreenTarget): Promise<void> {
+  if (action.type === 'wallpaper') {
+    const wallpaper = getWallpaper(action.wallpaperId)
+    if (!wallpaper) throw new Error(t('rules.wallpaperGone'))
+    for (const s of expandScreen(screen)) stopPlaylist(s)
+    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)
+    }
+    if (isShownOn(wallpaper.id, screen)) {
+      updateWallpaper(wallpaper.id, { appliedCount: (wallpaper.appliedCount ?? 0) + 1, lastAppliedAt: Date.now() })
+    }
+  } else if (action.type === 'playlist') {
+    if (!getPlaylist(action.playlistId)) throw new Error(t('rules.playlistGone'))
+    startPlaylist(action.playlistId, screen)
+  } else {
+    stopPlaylist(screen)
+    await stopDisplay(screen)
+  }
+}
+
+/**
+ * What a profile does on the screens there are now: a '*' entry goes first so an entry for one screen can follow it.
+ * A profile from the other display mode or with a monitor that is gone is not lost: entries for screens that are
+ * not there are skipped, and in shared mode (one '*' target) the first of them stands in for all screens
+ */
+function profileEntries(profile: Profile): [ScreenTarget, ScreenAction][] {
+  const targets = getDisplayTargets()
+  const entries = Object.entries(profile.screens)
+  const known = entries.filter(([screen]) => screen === '*' || targets.includes(screen))
+  if (known.length === 0 && targets.includes('*') && entries.length > 0) known.push(['*', entries[0][1]])
+  return known.sort(([a], [b]) => Number(b === '*') - Number(a === '*'))
+}
+
+/** The screens an action touches: a profile names its own, anything else the screen of the rule */
+export function actionScreens(action: ScheduleAction, screen: ScreenTarget): ScreenTarget[] {
+  if (action.type !== 'profile') return expandScreen(screen)
+  const profile = getProfile(action.profileId)
+  return profile ? profileEntries(profile).flatMap(([s]) => expandScreen(s)) : []
+}
+
+export async function applyProfile(profileId: string): Promise<void> {
+  const profile = getProfile(profileId)
+  if (!profile) throw new Error(t('profiles.gone'))
+
+  const failed: string[] = []
+  for (const [screen, action] of profileEntries(profile)) {
+    await runScreenAction(action, screen).catch((err: unknown) => {
+      console.error(`[Profile] "${profile.name}" failed on ${screen}:`, err)
+      failed.push(screen)
+    })
+  }
+  if (failed.length > 0) throw new Error(t('profiles.failedOn', { name: profile.name, screens: failed.join(', ') }))
+}
+
+export async function runAction(action: ScheduleAction, screen: ScreenTarget): Promise<void> {
+  if (action.type === 'profile') await applyProfile(action.profileId)
+  else await runScreenAction(action, screen)
+}

+ 5 - 32
src/main/services/schedule.service.ts

@@ -4,10 +4,8 @@ import { randomUUID } from 'crypto'
 import { IpcChannels } from '@shared/ipc-channels'
 import type { ScheduleRule } from '@shared/types'
 import { dueTimeRules } from '@shared/schedule'
-import { getWallpaper, updateWallpaper } from './library.service'
-import { getPlaylist } from './playlist.service'
-import { expandScreen, isShownOn, setBusyWallpaperSource, showWallpaper, stopDisplay } from './display.service'
-import { startPlaylist, stopPlaylist } from './playlist-player.service'
+import { setBusyWallpaperSource } from './display.service'
+import { runAction, runningWallpaperIds } from './rule-actions.service'
 
 interface ScheduleStore {
   rules: ScheduleRule[]
@@ -27,7 +25,6 @@ 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')
@@ -48,32 +45,8 @@ export function deleteScheduleRule(id: string): void {
 }
 
 export async function runRule(rule: ScheduleRule): Promise<void> {
-  const { action, screen } = rule
-  console.log(`[Schedule] Running "${rule.name}" on ${screen}`)
-
-  if (action.type === 'wallpaper') {
-    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)
-    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)
-    }
-    if (isShownOn(wallpaper.id, screen)) {
-      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')
-    startPlaylist(action.playlistId, screen)
-  } else {
-    stopPlaylist(screen)
-    await stopDisplay(screen)
-  }
-
+  console.log(`[Schedule] Running "${rule.name}" on ${rule.screen}`)
+  await runAction(rule.action, rule.screen)
   if (win && !win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_SCHEDULE_FIRED, rule.name)
 }
 
@@ -115,7 +88,7 @@ export function takeCatchUp(now = Date.now()): ScheduleRule[] {
 /** Call after the playlist player resumed, so a rule that came due while closed (takeCatchUp) wins over it */
 export function initSchedule(window: BrowserWindow, catchUp: readonly ScheduleRule[]): void {
   win = window
-  setBusyWallpaperSource('schedule', () => [...runningWallpapers.keys()])
+  setBusyWallpaperSource('schedule', runningWallpaperIds)
   lastDark = nativeTheme.shouldUseDarkColors
   nativeTheme.on('updated', onThemeChanged)
   void runAll(catchUp)

+ 2 - 4
src/main/services/static-wallpaper.service.ts

@@ -1,9 +1,7 @@
-import { execFile, execFileSync, spawn, type ChildProcess } from 'child_process'
+import { execFileSync, spawn, type ChildProcess } from 'child_process'
 import { setTimeout as sleep } from 'timers/promises'
-import { promisify } from 'util'
 import { hostCommand, isHostCommandAvailable } from '../utils/flatpak'
-
-const execFileAsync = promisify(execFile)
+import { execFileAsync } from '../utils/exec'
 
 export interface CommandResult {
   ok: boolean

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

@@ -97,3 +97,39 @@ describe('a Steam request that never answers', () => {
     expect(await second).toBe(7)
   })
 })
+
+describe('author lookups under a Steam rate limit', () => {
+  const xml = '<steamID><![CDATA[Maker]]></steamID><avatarFull><![CDATA[https://x/a.jpg]]></avatarFull>'
+
+  beforeEach(() => {
+    vi.useFakeTimers({ toFake: ['Date'] })
+    steam.resetAuthorThrottle()
+  })
+  afterEach(() => {
+    vi.useRealTimers()
+    vi.unstubAllGlobals()
+  })
+
+  it('stops asking after a 429 and answers null until the cooldown ends', async () => {
+    const fetchMock = vi.fn<() => Promise<Response>>(() =>
+      Promise.resolve(new Response('', { status: 429, headers: { 'retry-after': '120' } }))
+    )
+    vi.stubGlobal('fetch', fetchMock)
+    expect(await steam.getAuthorInfo('76561190000000001')).toBeNull()
+    expect(await steam.getAuthorInfo('76561190000000002')).toBeNull()
+    expect(fetchMock).toHaveBeenCalledTimes(1)
+
+    vi.setSystemTime(Date.now() + 121_000)
+    fetchMock.mockImplementation(() => Promise.resolve(new Response(xml, { status: 200 })))
+    expect(await steam.getAuthorInfo('76561190000000002')).toMatchObject({ name: 'Maker' })
+    expect(fetchMock).toHaveBeenCalledTimes(2)
+  })
+
+  it('does not refetch an author whose lookup failed a moment ago', async () => {
+    const fetchMock = vi.fn<() => Promise<Response>>(() => Promise.resolve(new Response('', { status: 500 })))
+    vi.stubGlobal('fetch', fetchMock)
+    await expect(steam.getAuthorInfo('76561190000000003')).rejects.toThrow('HTTP 500')
+    expect(await steam.getAuthorInfo('76561190000000003')).toBeNull()
+    expect(fetchMock).toHaveBeenCalledTimes(1)
+  })
+})

+ 47 - 21
src/main/services/steam.service.ts

@@ -237,8 +237,13 @@ export async function downloadItem(itemId: bigint, highPriority = true): Promise
   }
 }
 
-export async function unsubscribeFromItem(itemId: bigint): Promise<void> {
-  await steamCall('workshop.unsubscribe', itemId)
+// Steam drops overlapping workshop calls, so unsubscribes go one after another
+let unsubscribeQueue: Promise<unknown> = Promise.resolve()
+
+export function unsubscribeFromItem(itemId: bigint): Promise<void> {
+  const turn = unsubscribeQueue.then(() => steamCall<void>('workshop.unsubscribe', itemId))
+  unsubscribeQueue = turn.catch(() => {})
+  return turn
 }
 
 function isSteamOnline(): Promise<boolean> {
@@ -640,17 +645,45 @@ function authorInfoCache(): ReturnType<typeof openStore<{ authors: Record<string
 }
 const PROFILE_FETCH_TIMEOUT_MS = 15_000
 
-const authorInfoInflight = new Map<string, Promise<WorkshopAuthorInfo>>()
+const authorInfoInflight = new Map<string, Promise<WorkshopAuthorInfo | null>>()
+
+const PROFILE_COOLDOWN_BASE_MS = 5 * 60_000
+const PROFILE_COOLDOWN_MAX_MS = 60 * 60_000
+const PROFILE_FAIL_TTL_MS = 60_000
+let profileCooldownUntil = 0
+let profileCooldownMs = 0
+const profileFailedAt = new Map<string, number>()
+
+class ProfileThrottledError extends Error {}
+
+function startProfileCooldown(retryAfterSeconds: number): void {
+  profileCooldownMs =
+    retryAfterSeconds > 0
+      ? Math.min(retryAfterSeconds * 1000, PROFILE_COOLDOWN_MAX_MS)
+      : Math.min(profileCooldownMs ? profileCooldownMs * 2 : PROFILE_COOLDOWN_BASE_MS, PROFILE_COOLDOWN_MAX_MS)
+  profileCooldownUntil = Date.now() + profileCooldownMs
+}
+
+/** test hook */
+export function resetAuthorThrottle(): void {
+  profileCooldownUntil = 0
+  profileCooldownMs = 0
+  profileFailedAt.clear()
+}
 
-// throws on any failure (429 when Steam rate limits, timeouts, private profile without avatar),
-// so the renderer retries instead of caching a null forever
-export function getAuthorInfo(steamId: string): Promise<WorkshopAuthorInfo> {
+// null = no profile for now (Steam is rate limiting, or the lookup failed a moment ago), the UI shows the SteamID
+export function getAuthorInfo(steamId: string): Promise<WorkshopAuthorInfo | null> {
   const cached = authorInfoCache().get('authors')[steamId]
   if (cached?.fetchedAt && Date.now() - cached.fetchedAt < AUTHOR_CACHE_TTL_MS) return Promise.resolve(cached)
+  if (Date.now() < profileCooldownUntil) return Promise.resolve(cached ?? null)
+  const failedAt = profileFailedAt.get(steamId)
+  if (failedAt !== undefined && Date.now() - failedAt < PROFILE_FAIL_TTL_MS) return Promise.resolve(cached ?? null)
   let pending = authorInfoInflight.get(steamId)
   if (!pending) {
     pending = queueProfileFetch(steamId)
       .catch((err: unknown) => {
+        if (err instanceof ProfileThrottledError) return cached ?? null
+        profileFailedAt.set(steamId, Date.now())
         if (cached) return cached
         throw err
       })
@@ -661,37 +694,28 @@ export function getAuthorInfo(steamId: string): Promise<WorkshopAuthorInfo> {
 }
 
 const PROFILE_GAP_MS = 1000
-const PROFILE_MAX_RETRY_WAIT_MS = 10_000
 let profileQueue: Promise<unknown> = Promise.resolve()
 
 function queueProfileFetch(steamId: string): Promise<WorkshopAuthorInfo> {
   const run = profileQueue.then(async () => {
+    if (Date.now() < profileCooldownUntil) throw new ProfileThrottledError()
     try {
       return await fetchAuthorInfo(steamId)
     } finally {
-      await new Promise((resolve) => setTimeout(resolve, PROFILE_GAP_MS))
+      await sleep(PROFILE_GAP_MS)
     }
   })
   profileQueue = run.catch(() => undefined)
   return run
 }
 
-async function fetchProfileXml(steamId: string): Promise<Response> {
+async function fetchAuthorInfo(steamId: string): Promise<WorkshopAuthorInfo> {
   const url = `https://steamcommunity.com/profiles/${steamId}?xml=1`
-  let res = await fetch(url, { signal: AbortSignal.timeout(PROFILE_FETCH_TIMEOUT_MS) })
+  const res = await fetch(url, { signal: AbortSignal.timeout(PROFILE_FETCH_TIMEOUT_MS) })
   if (res.status === 429) {
-    const retryAfter = Number(res.headers.get('retry-after'))
-    const waitMs = retryAfter > 0 ? retryAfter * 1000 : 3000
-    if (waitMs <= PROFILE_MAX_RETRY_WAIT_MS) {
-      await new Promise((resolve) => setTimeout(resolve, waitMs))
-      res = await fetch(url, { signal: AbortSignal.timeout(PROFILE_FETCH_TIMEOUT_MS) })
-    }
+    startProfileCooldown(Number(res.headers.get('retry-after')))
+    throw new ProfileThrottledError()
   }
-  return res
-}
-
-async function fetchAuthorInfo(steamId: string): Promise<WorkshopAuthorInfo> {
-  const res = await fetchProfileXml(steamId)
   if (!res.ok) throw new Error(`Steam profile ${steamId}: HTTP ${res.status}`)
   const xml = await res.text()
   const name = xml.match(/<steamID><!\[CDATA\[([\s\S]*?)\]\]><\/steamID>/)?.[1]
@@ -699,6 +723,8 @@ async function fetchAuthorInfo(steamId: string): Promise<WorkshopAuthorInfo> {
   if (!name || !avatarUrl) throw new Error(`Steam profile ${steamId}: no ${name ? 'avatar' : 'name'} in response`)
   const info = { steamId, name, avatarUrl }
   authorInfoCache().set(`authors.${steamId}`, { ...info, fetchedAt: Date.now() })
+  profileCooldownMs = 0
+  profileFailedAt.delete(steamId)
   return info
 }
 

+ 5 - 6
src/main/services/update.service.ts

@@ -1,5 +1,3 @@
-import { execFile } from 'child_process'
-import { promisify } from 'util'
 import * as fs from 'fs'
 import * as os from 'os'
 import * as path from 'path'
@@ -24,8 +22,7 @@ import { isCommandAvailable, runningAppImage } from '../utils/platform'
 import { relaunchApp } from '../utils/relaunch'
 import { getDismissedUpdates, getUpdateChecks, setDismissedUpdates, setUpdateChecks } from './config.service'
 import { getLweStatus } from './lwe.service'
-
-const execFileAsync = promisify(execFile)
+import { execFileAsync } from '../utils/exec'
 
 const FIRST_CHECK_DELAY_MS = 15_000
 const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000
@@ -245,8 +242,10 @@ async function installDeb(release: GithubRelease): Promise<void> {
     await verifyAsset(file, asset)
     setAppProgress({ stage: 'installing', percentage: 85 })
     // dpkg alone wouldn't resolve new dependencies
-    // apt refuses to go back to an older version unless told to, but only for a deliberate downgrade
-    const downgrade = (compareVersions(release.tag_name, app.getVersion()) ?? 0) < 0
+    // apt refuses to go back to an older version unless told to, but only for a deliberate downgrade. The installed
+    // package can be newer than the running app (updated, not restarted yet), so it is the one to compare against
+    const installed = packageVersion({ manager: 'dpkg', name: 'we-manager' }) ?? app.getVersion()
+    const downgrade = (compareVersions(release.tag_name, installed) ?? 0) < 0
     const command = isCommandAvailable('apt-get')
       ? ['apt-get', 'install', '-y', ...(downgrade ? ['--allow-downgrades'] : []), file]
       : ['dpkg', '-i', file]

+ 1075 - 0
src/main/services/video-tools.service.ts

@@ -0,0 +1,1075 @@
+import { execFile, spawn, type ChildProcess } from 'child_process'
+import * as fs from 'fs'
+import * as path from 'path'
+import { screen, type BrowserWindow } from 'electron'
+import { IpcChannels } from '@shared/ipc-channels'
+import type { WallpaperMeta } from '@shared/types'
+import {
+  ENCODER_RANKING,
+  buildFfmpegArgs,
+  encoderArgs,
+  fpsFilter,
+  isHevc,
+  outputDuration,
+  colorsMatch,
+  ENCODER_LABELS,
+  type FrameColor,
+  outputExtension,
+  parseFrameColor,
+  parseProgressSeconds,
+  pickEncoder,
+  planQuickOptimize,
+  scaleFilter,
+  cutRanges,
+  cutRangesProblem,
+  sourceTimeAt,
+  type EncoderOption,
+  type HevcEncoder,
+  type OptimizeOptions,
+  type OptimizeProgress,
+  type OptimizeResult,
+  type QuickLine,
+  type QuickReport,
+  type QuickTrim,
+  type ScreenSize,
+  type VideoInfo,
+  type VideoProbe,
+  type VideoToolsStatus
+} from '@shared/video-tools'
+import { getAllWallpapers, getDirSizeAsync, getWallpaper, updateWallpaper } from './library.service'
+import { fsyncPath, syncDir } from './backup.service'
+import { getWallpapersInUse } from './display.service'
+import { getConfiguredWorkshopPath, getVideoToolSettings } from './config.service'
+import { getDataPath, getFfmpegDir } from '../utils/paths'
+import { hostCommand, invalidateHostCommandCache, isFlatpak, isHostCommandAvailable } from '../utils/flatpak'
+import { invalidateCommandCache, isCommandAvailable } from '../utils/platform'
+import { downloadVerified, fetchLatestRelease, type GithubAsset } from '../utils/github'
+import { forgetVideoProbe } from '../utils/video'
+import { t } from '../i18n'
+import { trimAsCut, trimAsCuts, videoSegmentsOf } from '@shared/videoTrim'
+import { execFileAsync } from '../utils/exec'
+
+const FFMPEG_BUILDS_REPO = 'BtbN/FFmpeg-Builds'
+
+type Source = 'system' | 'downloaded'
+
+type Tool = 'ffmpeg' | 'ffprobe'
+
+function downloadedBinary(tool: Tool): string {
+  return path.join(getFfmpegDir(), tool)
+}
+
+function systemHas(tool: Tool): boolean {
+  return isFlatpak() ? isHostCommandAvailable(tool) : isCommandAvailable(tool)
+}
+
+function hasSource(source: Source): boolean {
+  return source === 'downloaded' ? fs.existsSync(downloadedBinary('ffmpeg')) : systemHas('ffmpeg')
+}
+
+function command(source: Source, tool: Tool, args: string[], lowPriority = false): [string, string[]] {
+  const program = source === 'downloaded' ? downloadedBinary(tool) : tool
+  const argv = lowPriority ? ['nice', '-n', '10', program, ...args] : [program, ...args]
+  return source === 'downloaded' ? [argv[0], argv.slice(1)] : hostCommand(argv[0], argv.slice(1), { dieWithApp: true })
+}
+
+function run(source: Source, tool: Tool, args: string[], timeout: number, owner?: Job): Promise<string> {
+  const [file, fileArgs] = command(source, tool, args)
+  return new Promise((resolve, reject) => {
+    const child = execFile(
+      file,
+      fileArgs,
+      { timeout, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 },
+      (err, stdout) => {
+        owner?.helpers.delete(child)
+        if (err) reject(err)
+        else resolve(stdout)
+      }
+    )
+    owner?.helpers.add(child)
+  })
+}
+
+function renderDevices(): string[] {
+  try {
+    return fs
+      .readdirSync('/dev/dri')
+      .filter((n) => n.startsWith('renderD'))
+      .sort()
+      .map((n) => `/dev/dri/${n}`)
+  } catch {
+    return []
+  }
+}
+
+/** average colour of one frame, scaled down so the whole picture counts and bit depth does not matter */
+async function frameColor(
+  source: Source,
+  input: string[],
+  at = 0,
+  filters: string[] = [],
+  owner?: Job
+): Promise<FrameColor | null> {
+  const vf = [...filters, 'format=yuv420p', 'scale=16:16:flags=area', 'signalstats', 'metadata=print:file=-'].join(',')
+  const out = await run(
+    source,
+    'ffmpeg',
+    ['-hide_banner', '-nostdin', '-loglevel', 'error', ...(at > 0 ? ['-ss', String(at)] : []), ...input, '-vf', vf, '-frames:v', '1', '-an', '-f', 'null', '-'],
+    60_000,
+    owner
+  )
+  return parseFrameColor(out)
+}
+
+/**
+ * Short test files go under the app's data folder, not /tmp: inside a Flatpak ffmpeg runs on the host, whose /tmp is a
+ * different one, but the data folder has the same path on both sides.
+ */
+let scratchSwept = false
+
+async function scratchDir(): Promise<string> {
+  const dir = path.join(getDataPath(), 'video-tmp')
+  await fs.promises.mkdir(dir, { recursive: true })
+  if (!scratchSwept) {
+    scratchSwept = true
+    const stale = await fs.promises.readdir(dir).catch(() => [])
+    await Promise.all(stale.map((name) => fs.promises.rm(path.join(dir, name), { force: true })))
+  }
+  return dir
+}
+
+type ProbeVerdict = 'ok' | 'wrong' | 'error'
+
+async function probeEncoder(source: Source, encoder: HevcEncoder, device?: string): Promise<ProbeVerdict> {
+  const enc = encoderArgs(encoder, 8, device)
+  let probe: string
+  try {
+    probe = path.join(await scratchDir(), `probe-${process.pid}-${encoder}.mkv`)
+  } catch {
+    return 'error'
+  }
+  const lavfi = 'testsrc2=s=640x360:d=1:r=10'
+  const args = [
+    '-hide_banner',
+    '-nostdin',
+    '-loglevel',
+    'error',
+    '-y',
+    ...enc.input,
+    '-f',
+    'lavfi',
+    '-i',
+    lavfi,
+    ...(enc.filter ? ['-vf', enc.filter] : []),
+    ...enc.output,
+    probe
+  ]
+  try {
+    await run(source, 'ffmpeg', args, 20_000)
+    const [want, got] = await Promise.all([
+      frameColor(source, ['-f', 'lavfi', '-i', lavfi]),
+      frameColor(source, ['-i', probe])
+    ])
+    return want && got && colorsMatch(want, got) ? 'ok' : 'wrong'
+  } catch {
+    return 'error'
+  } finally {
+    await fs.promises.rm(probe, { force: true })
+  }
+}
+
+interface EncoderProbe {
+  working: EncoderOption[]
+  wrong: EncoderOption[]
+}
+
+/**
+ * ffmpeg lists encoders it was built with, whether this machine can use them is only known by trying one.
+ * VAAPI is tried on every render node: a machine with an iGPU and a graphics card has two, and only one may encode correctly.
+ */
+async function workingEncoders(source: Source): Promise<EncoderProbe> {
+  const result: EncoderProbe = { working: [], wrong: [] }
+  let listed: string
+  try {
+    listed = await run(source, 'ffmpeg', ['-hide_banner', '-encoders'], 15_000)
+  } catch {
+    return result
+  }
+  for (const encoder of ENCODER_RANKING) {
+    if (!new RegExp(`\\s${encoder}\\s`).test(listed)) continue
+    const devices: (string | undefined)[] = encoder === 'hevc_vaapi' ? renderDevices() : [undefined]
+    let sawWrong = false
+    let works = false
+    for (const device of devices) {
+      const verdict = await probeEncoder(source, encoder, device)
+      if (verdict === 'ok') {
+        result.working.push({ encoder, source, device })
+        works = true
+        break
+      }
+      if (verdict === 'wrong') {
+        sawWrong = true
+        console.warn(`[VideoTools] ${encoder}${device ? ` on ${device}` : ''} writes a wrong picture`)
+      }
+    }
+    if (!works && sawWrong) result.wrong.push({ encoder, source })
+  }
+  return result
+}
+
+const badEncoders = new Set<string>()
+const pictureFailures = new Map<string, number>()
+const PICTURE_FAILURES_TO_BAN = 2
+
+function badKey(source: Source, encoder: HevcEncoder): string {
+  return `${source}:${encoder}`
+}
+
+const EMPTY_PROBE_KEPT_MS = 60_000
+const encoderCache = new Map<Source, Promise<EncoderProbe>>()
+
+function encodersOf(source: Source): Promise<EncoderProbe> {
+  const cached = encoderCache.get(source)
+  if (cached) return cached
+  if (source === 'system') {
+    for (const tool of ['ffmpeg', 'ffprobe']) {
+      invalidateCommandCache(tool)
+      invalidateHostCommandCache(tool)
+    }
+  }
+  if (!hasSource(source)) return Promise.resolve({ working: [], wrong: [] })
+  const probing = workingEncoders(source).then(
+    (probe) => {
+      if (probe.working.length === 0 && probe.wrong.length === 0) {
+        setTimeout(() => { if (encoderCache.get(source) === probing) encoderCache.delete(source) }, EMPTY_PROBE_KEPT_MS).unref()
+      }
+      return probe
+    },
+    (err: unknown) => {
+      encoderCache.delete(source)
+      throw err
+    }
+  )
+  encoderCache.set(source, probing)
+  return probing
+}
+
+function ffprobeSource(): Source | undefined {
+  if (fs.existsSync(downloadedBinary('ffprobe'))) return 'downloaded'
+  return systemHas('ffprobe') ? 'system' : undefined
+}
+
+function assetPattern(): RegExp | null {
+  const arch = process.arch === 'x64' ? 'linux64' : process.arch === 'arm64' ? 'linuxarm64' : null
+  return arch ? new RegExp(`^ffmpeg-n(\\d+)\\.(\\d+)-latest-${arch}-gpl-\\d+\\.\\d+\\.tar\\.xz$`) : null
+}
+
+export async function getVideoToolsStatus(): Promise<VideoToolsStatus> {
+  const options: EncoderOption[] = []
+  const wrong: EncoderOption[] = []
+  for (const source of ['system', 'downloaded'] as const) {
+    const probe = await encodersOf(source)
+    for (const option of probe.working) {
+      if (badEncoders.has(badKey(source, option.encoder))) {
+        wrong.push({ encoder: option.encoder, source })
+        continue
+      }
+      if (!options.some((o) => o.encoder === option.encoder)) options.push(option)
+    }
+    wrong.push(...probe.wrong)
+  }
+  return {
+    encoders: options,
+    wrong: wrong.filter((w) => !options.some((o) => o.encoder === w.encoder)),
+    downloaded: hasSource('downloaded'),
+    canDownload: assetPattern() !== null
+  }
+}
+
+function newestAsset(assets: GithubAsset[]): GithubAsset | undefined {
+  const pattern = assetPattern()
+  if (!pattern) return undefined
+  let best: { asset: GithubAsset; version: number } | undefined
+  for (const asset of assets) {
+    const m = pattern.exec(asset.name)
+    if (!m) continue
+    const version = Number(m[1]) * 1000 + Number(m[2])
+    if (!best || version > best.version) best = { asset, version }
+  }
+  return best?.asset
+}
+
+let downloading = false
+
+export async function downloadFfmpeg(win: BrowserWindow): Promise<void> {
+  if (downloading) throw new OptimizeError('busy', t('optimize.errBusy'))
+  downloading = true
+  const send = (progress: Omit<OptimizeProgress, 'itemId'>) => {
+    if (!win.isDestroyed())
+      win.webContents.send(IpcChannels.EVENT_VIDEO_TOOLS_PROGRESS, {
+        itemId: 'ffmpeg',
+        ...progress
+      })
+  }
+  const dir = getFfmpegDir()
+  const archive = `${dir}.download.tar.xz`
+  const staging = `${dir}.staging`
+  try {
+    const release = await fetchLatestRelease(FFMPEG_BUILDS_REPO)
+    const asset = release && newestAsset(release.assets)
+    if (!asset) throw new Error(t('optimize.errNoBuild'))
+    const sizeMb = Math.round(asset.size / 1_048_576)
+    send({
+      stage: 'downloading',
+      percentage: 0,
+      message: t('optimize.downloading', { size: sizeMb })
+    })
+    await fs.promises.mkdir(path.dirname(dir), { recursive: true })
+    await downloadVerified(asset, archive, (fraction) => {
+      send({
+        stage: 'downloading',
+        percentage: Math.round(fraction * 90),
+        message: t('optimize.downloading', { size: sizeMb })
+      })
+    })
+
+    send({
+      stage: 'unpacking',
+      percentage: 92,
+      message: t('optimize.unpacking')
+    })
+    await fs.promises.rm(staging, { recursive: true, force: true })
+    await fs.promises.mkdir(staging, { recursive: true })
+    await execFileAsync(
+      'tar',
+      ['-xJf', archive, '-C', staging, '--strip-components=2', '--wildcards', '*/bin/ffmpeg', '*/bin/ffprobe'],
+      { timeout: 600_000 }
+    )
+    for (const tool of ['ffmpeg', 'ffprobe']) {
+      await fs.promises.chmod(path.join(staging, tool), 0o755)
+    }
+    await execFileAsync(path.join(staging, 'ffmpeg'), ['-version'], {
+      timeout: 15_000
+    })
+
+    await fs.promises.rm(dir, { recursive: true, force: true })
+    await fs.promises.rename(staging, dir)
+    encoderCache.delete('downloaded')
+    send({ stage: 'done', percentage: 100 })
+  } catch (err) {
+    send({ stage: 'error', percentage: 0, message: (err as Error).message })
+    throw err
+  } finally {
+    downloading = false
+    await fs.promises.rm(archive, { force: true })
+    await fs.promises.rm(staging, { recursive: true, force: true })
+  }
+}
+
+export async function removeDownloadedFfmpeg(): Promise<void> {
+  await fs.promises.rm(getFfmpegDir(), { recursive: true, force: true })
+  encoderCache.delete('downloaded')
+}
+
+interface FfprobeStream {
+  codec_type?: string
+  codec_name?: string
+  width?: number
+  height?: number
+  r_frame_rate?: string
+  avg_frame_rate?: string
+  pix_fmt?: string
+}
+
+function frameRate(raw?: string): number {
+  const [num, den] = (raw ?? '').split('/').map(Number)
+  return num && den ? num / den : 0
+}
+
+export async function probeFile(file: string, owner?: Job): Promise<VideoInfo> {
+  const source = ffprobeSource()
+  if (!source) throw new Error(t('optimize.errNoFfmpeg'))
+  const out = await run(
+    source,
+    'ffprobe',
+    [
+      '-v',
+      'error',
+      '-show_entries',
+      'stream=codec_type,codec_name,width,height,r_frame_rate,avg_frame_rate,pix_fmt:format=duration,size',
+      '-of',
+      'json',
+      file
+    ],
+    30_000,
+    owner
+  )
+  const parsed = JSON.parse(out) as {
+    streams?: FfprobeStream[]
+    format?: { duration?: string; size?: string }
+  }
+  const video = parsed.streams?.find((s) => s.codec_type === 'video')
+  if (!video?.width || !video.height) throw new OptimizeError('skip', t('optimize.errNotVideo'))
+  return {
+    codec: video.codec_name ?? '',
+    width: video.width,
+    height: video.height,
+    fps: frameRate(video.avg_frame_rate) || frameRate(video.r_frame_rate),
+    duration: Number(parsed.format?.duration) || 0,
+    size: Number(parsed.format?.size) || (await fs.promises.stat(file)).size,
+    bitDepth: /p1[0-6]|10(le|be)/.test(video.pix_fmt ?? '') ? 10 : 8,
+    hasAudio: !!parsed.streams?.some((s) => s.codec_type === 'audio')
+  }
+}
+
+/** Steam validates its workshop folders and puts the files back, anything inside one is off limits */
+export function isSteamManagedPath(dir: string): boolean {
+  const resolved = path.resolve(dir)
+  const parts = resolved.split(path.sep)
+  if (parts.some((part, i) => part.toLowerCase() === 'steamapps' && parts[i + 1]?.toLowerCase() === 'workshop'))
+    return true
+  const workshop = getConfiguredWorkshopPath()
+  if (!workshop) return false
+  const rel = path.relative(path.resolve(workshop), resolved)
+  return !rel.startsWith('..') && !path.isAbsolute(rel)
+}
+
+function requireVideo(id: string): {
+  wallpaper: WallpaperMeta
+  dir: string
+  file: string
+} {
+  const wallpaper = getWallpaper(id)
+  if (!wallpaper) throw new OptimizeError('skip', t('optimize.errNotVideo'))
+  if (wallpaper.type !== 'video' || !wallpaper.localPath || !wallpaper.file || wallpaper.downloading) {
+    throw new OptimizeError('skip', t('optimize.errNotVideo'))
+  }
+  if (wallpaper.source === 'workshop' || isSteamManagedPath(wallpaper.localPath))
+    throw new OptimizeError('skip', t('optimize.errSteam'))
+  const dir = path.resolve(wallpaper.localPath)
+  const file = path.resolve(dir, wallpaper.file)
+  if (!file.startsWith(dir + path.sep)) throw new OptimizeError('skip', t('optimize.errNotVideo'))
+  return { wallpaper, dir, file }
+}
+
+function screenSizes(): ScreenSize[] {
+  const seen = new Set<string>()
+  const sizes: ScreenSize[] = []
+  for (const display of screen.getAllDisplays()) {
+    const width = Math.round(display.size.width * display.scaleFactor)
+    const height = Math.round(display.size.height * display.scaleFactor)
+    if (seen.has(`${width}x${height}`)) continue
+    seen.add(`${width}x${height}`)
+    sizes.push({ name: display.label || String(display.id), width, height })
+  }
+  return sizes
+}
+
+export async function probeWallpaper(id: string): Promise<VideoProbe> {
+  const { file, wallpaper } = requireVideo(id)
+  const info = await probeFile(file)
+  const playable = ['.mp4', '.webm'].includes(path.extname(file).toLowerCase())
+  const previewUrl = playable ? `wallpaper://${file.split(path.sep).map(encodeURIComponent).join('/')}` : null
+  return { info, screens: screenSizes(), trim: trimAsCuts(wallpaper, info.duration), previewUrl }
+}
+
+/** The videos among `ids` that have a trim an optimize can cut out (Steam's own are never offered) */
+export async function quickTrims(ids: string[]): Promise<QuickTrim[]> {
+  const found: QuickTrim[] = []
+  for (const id of ids) {
+    try {
+      const { file, wallpaper } = requireVideo(id)
+      if (videoSegmentsOf(wallpaper).length === 0) continue
+      const cut = trimAsCut(wallpaper, (await probeFile(file)).duration)
+      if (cut) found.push({ id, title: wallpaper.title, ...cut })
+    } catch {}
+  }
+  return found
+}
+
+interface Job {
+  id: string
+  child?: ChildProcess
+  helpers: Set<ChildProcess>
+  temp?: string
+  cancelled: boolean
+}
+
+interface Staged {
+  id: string
+  root: string
+  temp: string
+  original: string
+  final: string
+  info: VideoInfo
+  cutApplied: boolean
+}
+
+let job: Job | null = null
+let staged: Staged | null = null
+let finishing = false
+
+function freeFinalName(file: string, ext: string): string {
+  const parsed = path.parse(file)
+  const plain = path.join(parsed.dir, parsed.name + ext)
+  // the same name as the video is the video itself, anything else already there is somebody else's file
+  if (plain.toLowerCase() === file.toLowerCase() || !fs.existsSync(plain)) return plain
+  for (let n = 2; ; n++) {
+    const candidate = path.join(parsed.dir, `${parsed.name} (${n})${ext}`)
+    if (!fs.existsSync(candidate)) return candidate
+  }
+}
+
+const LEFTOVER_TEMP = /^\..+\.optimizing\.[^.]+$/
+
+/** temp files of an encode that never got to clean up (crash, kill, power loss) */
+function isBeingOptimized(root: string): boolean {
+  const inside = (file: string): boolean => path.resolve(file).startsWith(root + path.sep)
+  return (!!job?.temp && inside(job.temp)) || (!!staged && path.resolve(staged.root) === root)
+}
+
+export async function sweepOptimizeLeftovers(): Promise<void> {
+  for (const w of getAllWallpapers()) {
+    if (w.source === 'workshop' || w.type !== 'video' || !w.localPath || !w.file) continue
+    const dir = path.dirname(path.resolve(w.localPath, w.file))
+    const names = await fs.promises.readdir(dir).catch(() => [] as string[])
+    for (const name of names.filter((n) => LEFTOVER_TEMP.test(n))) {
+      if (isBeingOptimized(path.resolve(w.localPath))) break
+      await fs.promises.rm(path.join(dir, name), { force: true }).catch(() => undefined)
+    }
+  }
+}
+
+function tempNameFor(file: string, ext: string): string {
+  const parsed = path.parse(file)
+  return path.join(parsed.dir, `.${parsed.name}.optimizing${ext}`)
+}
+
+export function validateOptions(info: VideoInfo, options: OptimizeOptions): void {
+  const { scale, cut, fps } = options
+  if (scale && !scaleFilter(info, scale, scale.mode)) throw new OptimizeError('skip', t('optimize.errScale'))
+  if (fps !== undefined && !fpsFilter(info, fps)) throw new OptimizeError('skip', t('optimize.errFps'))
+  if (cut) {
+    const problem = cutRangesProblem(cutRanges(cut), info.duration)
+    if (problem === 'range') throw new Error(t('optimize.errCut'))
+    if (problem === 'order') throw new Error(t('optimize.errCutOrder'))
+    if (cut.more?.length && cut.copy) throw new Error(t('optimize.errCut'))
+  }
+  if (!scale && !cut && !fps && !options.force && isHevc(info.codec)) throw new OptimizeError('skip', t('optimize.errNothing'))
+}
+
+/**
+ * The start-up test only uses a small test picture, but some hardware encoders go wrong only at the video's own size.
+ * A couple of seconds of the real video are encoded and compared with the source before the whole job commits to an encoder.
+ */
+async function trialPasses(
+  current: Job,
+  candidate: EncoderOption,
+  file: string,
+  info: VideoInfo,
+  options: OptimizeOptions,
+  failures: string[]
+): Promise<EncoderOption | null> {
+  const start = options.cut?.start ?? 0
+  const length = Math.min(2, Math.max(0.5, info.duration - start))
+  const trial = path.join(await scratchDir(), `trial-${process.pid}.mkv`)
+  const scaled = options.scale ? scaleFilter(info, options.scale, options.scale.mode) : null
+  const devices: (string | undefined)[] =
+    candidate.encoder === 'hevc_vaapi'
+      ? [candidate.device, ...renderDevices().filter((d) => d !== candidate.device)]
+      : [undefined]
+  for (const device of devices) {
+    // the GPU decoder first, software decoding when that fails or draws a wrong picture
+    for (const hwDecode of [true, false]) {
+      if (current.cancelled) break
+      const label = `${device ?? candidate.encoder}${hwDecode ? ' + hw decode' : ''}`
+      try {
+        const args = buildFfmpegArgs({
+          source: file,
+          dest: trial,
+          info,
+          options: { ...options, cut: { start, end: start + length } },
+          encoder: candidate.encoder,
+          vaapiDevice: device,
+          hwDecode
+        })
+        await run(candidate.source, 'ffmpeg', args, 120_000, current)
+        const at = Math.min(0.3, length / 2)
+        const [want, got] = await Promise.all([
+          frameColor(candidate.source, ['-i', file], start + at, scaled ? [scaled] : [], current),
+          frameColor(candidate.source, ['-i', trial], at, [], current)
+        ])
+        if (want && got && colorsMatch(want, got)) return { ...candidate, device, hwDecode }
+        const why = `trial failed at ${info.width}x${info.height}, ${describeColors(want, got)}`
+        failures.push(`${label}: ${why}`)
+        console.warn(`[VideoTools] ${candidate.encoder}${device ? ` on ${device}` : ''}${hwDecode ? ' with hw decode' : ''} ${why}`)
+      } catch (err) {
+        const why = (err as Error).message.split('\n')[0]
+        failures.push(`${label}: ${why}`)
+        console.warn(`[VideoTools] ${label} failed on a trial: ${why}`)
+      } finally {
+        await fs.promises.rm(trial, { force: true })
+      }
+    }
+  }
+  return null
+}
+
+class OptimizeError extends Error {
+  constructor(readonly kind: 'busy' | 'cancelled' | 'skip', message: string) {
+    super(message)
+  }
+}
+
+class WrongPictureError extends Error {
+  kept?: string
+
+  constructor(
+    readonly encoder: HevcEncoder,
+    detail: string
+  ) {
+    super(`${t('optimize.errPicture', { encoder: ENCODER_LABELS[encoder] })} (${detail})`)
+  }
+}
+
+function describeColors(want: FrameColor | null, got: FrameColor | null): string {
+  const show = (c: FrameColor | null): string => (c ? `${c.y.toFixed(0)}/${c.u.toFixed(0)}/${c.v.toFixed(0)}` : 'no frame')
+  return `Y/U/V source ${show(want)}, result ${show(got)}`
+}
+
+/** On "auto" an encoder whose finished file turns out wrong is dropped and the job runs again with the next one */
+export async function startOptimize(
+  id: string,
+  options: OptimizeOptions,
+  win: BrowserWindow,
+  exclude: HevcEncoder[] = []
+): Promise<OptimizeResult> {
+  try {
+    const result = await runOptimize(id, options, win, exclude)
+    return { ...result, skipped: [...new Set([...exclude, ...result.skipped])] }
+  } catch (err) {
+    if (err instanceof WrongPictureError && options.encoder === 'auto') {
+      // the next encoder's result is what counts, the rejected file would only sit in the folder
+      if (err.kept) await fs.promises.rm(err.kept, { force: true }).catch(() => undefined)
+      return startOptimize(id, options, win, [...exclude, err.encoder])
+    }
+    throw err
+  }
+}
+
+async function runOptimize(
+  id: string,
+  options: OptimizeOptions,
+  win: BrowserWindow,
+  exclude: HevcEncoder[]
+): Promise<OptimizeResult> {
+  if (job || staged || downloading) throw new OptimizeError('busy', t('optimize.errBusy'))
+  const current: Job = { id, helpers: new Set(), cancelled: quickRunning && quickCancelled }
+  job = current
+  try {
+    return await runOptimizeJob(current, id, options, win, exclude)
+  } finally {
+    job = null
+  }
+}
+
+async function runOptimizeJob(
+  current: Job,
+  id: string,
+  options: OptimizeOptions,
+  win: BrowserWindow,
+  exclude: HevcEncoder[]
+): Promise<OptimizeResult> {
+  const stopIfCancelled = (): void => {
+    if (current.cancelled) throw new OptimizeError('cancelled', t('optimize.errCancelled'))
+  }
+  const { dir, file } = requireVideo(id)
+  if (getWallpapersInUse().has(id)) throw new OptimizeError('skip', t('optimize.errInUse'))
+  const info = await probeFile(file, current)
+  stopIfCancelled()
+  validateOptions(info, options)
+
+  const copyOnly = !!options.cut?.copy && !options.scale && !options.fps
+  let chosen: EncoderOption | undefined
+  const skipped: HevcEncoder[] = []
+  const trialFailures: string[] = []
+  if (!copyOnly) {
+    const available = (await getVideoToolsStatus()).encoders
+    const candidates =
+      options.encoder === 'auto'
+        ? ENCODER_RANKING.filter((e) => !exclude.includes(e)).flatMap((e) => available.filter((o) => o.encoder === e).slice(0, 1))
+        : [pickEncoder(options.encoder, available)].filter((o): o is EncoderOption => !!o)
+    if (candidates.length === 0) throw new OptimizeError('skip', t('optimize.errNoEncoder'))
+    for (const candidate of candidates) {
+      const passed = await trialPasses(current, candidate, file, info, options, trialFailures)
+      stopIfCancelled()
+      if (passed) {
+        chosen = passed
+        break
+      }
+      skipped.push(candidate.encoder)
+    }
+    if (!chosen) {
+      const label = t('optimize.errPicture', { encoder: ENCODER_LABELS[candidates[candidates.length - 1].encoder] })
+      throw new Error(trialFailures.length ? `${label} (${trialFailures.join('; ')})` : label)
+    }
+  }
+
+  stopIfCancelled()
+  const stats = await fs.promises.statfs(dir)
+  // the copy of the original lives next to the video as well
+  const room = getVideoToolSettings().backupOriginal ? 2.2 : 1.2
+  if (stats.bavail * stats.bsize < info.size * room) throw new Error(t('optimize.errSpace'))
+
+  const sourceExt = path.extname(file)
+  const ext = chosen ? outputExtension(sourceExt) : sourceExt
+  const temp = tempNameFor(file, ext)
+  current.temp = temp
+  await fs.promises.rm(temp, { force: true })
+
+  const args = buildFfmpegArgs({
+    source: file,
+    dest: temp,
+    info,
+    options,
+    encoder: chosen?.encoder,
+    vaapiDevice: chosen?.device,
+    hwDecode: chosen?.hwDecode
+  })
+  const [bin, binArgs] = command(
+    chosen?.source ?? (hasSource('system') ? 'system' : 'downloaded'),
+    'ffmpeg',
+    args,
+    true
+  )
+  const total = outputDuration(info, options.cut)
+
+  const send = (progress: Omit<OptimizeProgress, 'itemId'>) => {
+    if (!win.isDestroyed())
+      win.webContents.send(IpcChannels.EVENT_VIDEO_TOOLS_PROGRESS, {
+        itemId: id,
+        ...progress
+      })
+  }
+
+  try {
+    await new Promise<void>((resolve, reject) => {
+      if (current.cancelled) {
+        reject(new OptimizeError('cancelled', t('optimize.errCancelled')))
+        return
+      }
+      const child = spawn(bin, binArgs, { stdio: ['ignore', 'pipe', 'pipe'] })
+      current.child = child
+      let errorTail = ''
+      let lastSent = 0
+      child.stdout.on('data', (chunk: Buffer) => {
+        const seconds = parseProgressSeconds(chunk.toString())
+        if (seconds === undefined || total <= 0 || Date.now() - lastSent < 400) return
+        lastSent = Date.now()
+        send({
+          stage: 'encoding',
+          percentage: Math.min(99, Math.round((seconds / total) * 100))
+        })
+      })
+      child.stderr.on('data', (chunk: Buffer) => {
+        errorTail = (errorTail + chunk.toString()).slice(-1500)
+      })
+      child.on('error', reject)
+      child.on('close', (code) => {
+        if (current.cancelled) reject(new OptimizeError('cancelled', t('optimize.errCancelled')))
+        else if (code === 0) resolve()
+        else
+          reject(
+            new Error(
+              t('optimize.errFailed', {
+                detail: errorTail.trim().split('\n').slice(-3).join(' ')
+              })
+            )
+          )
+      })
+    })
+    const newSize = (await fs.promises.stat(temp)).size
+    if (newSize === 0) throw new Error(t('optimize.errFailed', { detail: t('optimize.detailEmpty') }))
+    if (chosen) {
+      const scaled = options.scale ? scaleFilter(info, options.scale, options.scale.mode) : null
+      // a hardware encoder can go wrong part way through, so three places of the finished file are compared
+      for (const fraction of [0.15, 0.5, 0.85]) {
+        const at = total * fraction
+        const sourceAt = sourceTimeAt(options.cut, at, info.duration)
+        const [want, got] = await Promise.all([
+          frameColor(chosen.source, ['-i', file], sourceAt, scaled ? [scaled] : [], current).catch((err: Error) => {
+            console.warn(`[VideoTools] source frame at ${sourceAt.toFixed(1)} s is unreadable: ${err.message.slice(0, 200)}`)
+            return null
+          }),
+          frameColor(chosen.source, ['-i', temp], at, [], current)
+        ])
+        stopIfCancelled()
+        // no source frame there (the container is longer than its video, or the source is damaged): nothing to compare against
+        if (!want) continue
+        if (!got || !colorsMatch(want, got)) {
+          const detail = `at ${at.toFixed(1)} s, ${describeColors(want, got)}`
+          console.warn(`[VideoTools] ${chosen.encoder} picture check failed ${detail}`)
+          const key = badKey(chosen.source, chosen.encoder)
+          const failures = (pictureFailures.get(key) ?? 0) + 1
+          pictureFailures.set(key, failures)
+          if (failures >= PICTURE_FAILURES_TO_BAN) badEncoders.add(key)
+          throw new WrongPictureError(chosen.encoder, detail)
+        }
+      }
+    }
+    stopIfCancelled()
+    if (chosen) pictureFailures.delete(badKey(chosen.source, chosen.encoder))
+    await fsyncPath(temp)
+    // closing the dialog during the flush cancels the job, and nobody is left to decide about a staged result
+    stopIfCancelled()
+    staged = {
+      id,
+      root: dir,
+      temp,
+      original: file,
+      final: freeFinalName(file, ext),
+      info,
+      cutApplied: !!options.cut
+    }
+    send({ stage: 'done', percentage: 100 })
+    return { originalSize: info.size, newSize, encoder: chosen?.encoder, skipped }
+  } catch (err) {
+    if (err instanceof WrongPictureError) {
+      // kept next to the video so the file can be looked at, the picture check may be wrong as well
+      const parsed = path.parse(file)
+      const kept = path.join(parsed.dir, `${parsed.name} (${err.encoder} rejected)${path.extname(temp)}`)
+      try {
+        await fs.promises.rm(kept, { force: true })
+        await fs.promises.rename(temp, kept)
+        err.kept = kept
+        err.message += ` ${t('optimize.keptRejected', { path: kept })}`
+        console.warn(`[VideoTools] kept the rejected file as ${kept}`)
+      } catch {
+        await fs.promises.rm(temp, { force: true })
+      }
+    } else {
+      await fs.promises.rm(temp, { force: true })
+    }
+    send({ stage: 'error', percentage: 0, message: (err as Error).message })
+    throw err
+  }
+}
+
+export function cancelOptimize(): void {
+  if (quickRunning) quickCancelled = true
+  if (!job) return
+  job.cancelled = true
+  job.child?.kill('SIGTERM')
+  for (const helper of job.helpers) helper.kill('SIGTERM')
+}
+
+async function writeJsonAtomic(file: string, data: unknown): Promise<void> {
+  const tmp = `${file}.tmp`
+  try {
+    await fs.promises.writeFile(tmp, JSON.stringify(data, null, 2))
+    await fsyncPath(tmp)
+    await fs.promises.rename(tmp, file)
+    await syncDir(path.dirname(file)).catch(() => undefined)
+  } catch (err) {
+    await fs.promises.rm(tmp, { force: true })
+    throw err
+  }
+}
+
+/** "name (original).mp4" next to the video, flushed to disk so a crash right after the swap cannot leave a broken copy */
+async function copyOriginal(file: string): Promise<string> {
+  const parsed = path.parse(file)
+  let target = path.join(parsed.dir, `${parsed.name} (original)${parsed.ext}`)
+  for (let n = 2; fs.existsSync(target); n++) {
+    target = path.join(parsed.dir, `${parsed.name} (original ${n})${parsed.ext}`)
+  }
+  try {
+    await fs.promises.copyFile(file, target, fs.constants.COPYFILE_EXCL)
+    await fsyncPath(target)
+    const [want, got] = await Promise.all([fs.promises.stat(file), fs.promises.stat(target)])
+    if (want.size !== got.size) throw new Error(t('optimize.detailCopySize'))
+    // a directory can't be flushed on every filesystem, the file itself already is
+    await syncDir(parsed.dir).catch(() => undefined)
+  } catch (err) {
+    await fs.promises.rm(target, { force: true })
+    throw new Error(t('optimize.errBackup', { detail: (err as Error).message }), { cause: err })
+  }
+  return target
+}
+
+export async function finishOptimize(id: string, keep: boolean): Promise<void> {
+  if (finishing) {
+    if (!keep) return
+    throw new OptimizeError('busy', t('optimize.errBusy'))
+  }
+  finishing = true
+  try {
+    await finishStaged(id, keep)
+  } finally {
+    finishing = false
+  }
+}
+
+async function finishStaged(id: string, keep: boolean): Promise<void> {
+  const pending = staged
+  if (!pending || pending.id !== id) {
+    // discarding what is already gone is fine, the dialog does it again when it closes
+    if (!keep) return
+    throw new Error(t('optimize.errNoResult'))
+  }
+  if (!keep) {
+    staged = null
+    await fs.promises.rm(pending.temp, { force: true })
+    return
+  }
+  if (getWallpapersInUse().has(id)) throw new OptimizeError('skip', t('optimize.errInUse'))
+  const projectFile = path.join(pending.root, 'project.json')
+  const renamed = pending.final !== pending.original
+  const project = renamed ? (JSON.parse(await fs.promises.readFile(projectFile, 'utf8')) as Record<string, unknown>) : null
+  // nothing is replaced until the copy is on disk, a failure here leaves the result staged and the video untouched
+  const originalCopy = getVideoToolSettings().backupOriginal ? await copyOriginal(pending.original) : null
+
+  const sameName = pending.final.toLowerCase() === pending.original.toLowerCase()
+  let movedToFinal = false
+  try {
+    if (project) {
+      await fs.promises.rename(pending.temp, pending.final)
+      movedToFinal = true
+      await writeJsonAtomic(projectFile, {
+        ...project,
+        file: path.relative(pending.root, pending.final).split(path.sep).join('/')
+      })
+      if (!sameName) {
+        await fs.promises.rm(pending.original, { force: true }).catch((err: unknown) => {
+          console.warn(`[VideoTools] Could not remove ${pending.original}:`, err)
+        })
+      }
+    } else {
+      await fs.promises.rename(pending.temp, pending.original)
+    }
+  } catch (err) {
+    // the video is still the old one, so the encode stays staged and the copy made for it goes
+    if (movedToFinal && !sameName) await fs.promises.rename(pending.final, pending.temp).catch(() => undefined)
+    const replacedOriginal = movedToFinal && sameName
+    if (originalCopy && !replacedOriginal) await fs.promises.rm(originalCopy, { force: true }).catch(() => undefined)
+    if (!fs.existsSync(pending.temp)) staged = null
+    throw err
+  }
+  staged = null
+
+  forgetVideoProbe(pending.original)
+  forgetVideoProbe(pending.final)
+  const patch: Partial<WallpaperMeta> = {
+    file: path.relative(pending.root, pending.final).split(path.sep).join('/'),
+    fileSize: await getDirSizeAsync(pending.root, true)
+  }
+  if (pending.cutApplied) {
+    patch.videoSegments = undefined
+    patch.videoStart = undefined
+    patch.videoEnd = undefined
+  }
+  updateWallpaper(id, patch)
+}
+
+let quickRunning = false
+let quickCancelled = false
+
+/**
+ * "Quick optimize": every given video gets the default render settings when that makes sense, one after the other,
+ * and the result replaces the video (with the copy of the original when that is on). Videos it leaves alone are
+ * listed with the reason. The size never grows: a video that is not larger than the target keeps its size.
+ */
+export async function quickOptimize(ids: string[], win: BrowserWindow, trimAnswer = false): Promise<QuickReport> {
+  if (quickRunning) throw new OptimizeError('busy', t('optimize.errBusy'))
+  quickRunning = true
+  quickCancelled = false
+  const report: QuickReport = { lines: [], optimized: 0, savedBytes: 0, originalsKept: false }
+  let settings = getVideoToolSettings()
+  const trim = settings.trimMode === 'auto' || (settings.trimMode === 'ask' && trimAnswer)
+  try {
+    const { encoders } = await getVideoToolsStatus()
+    if (settings.encoder !== 'auto' && !encoders.some((o) => o.encoder === settings.encoder)) {
+      settings = { ...settings, encoder: 'auto' }
+    }
+    for (const [index, id] of ids.entries()) {
+      if (quickCancelled) break
+      const title = getWallpaper(id)?.title ?? id
+      const line = (kind: QuickLine['kind'], text: string): void => {
+        report.lines.push({ id, title, kind, text })
+      }
+      const skip = (reason: string): void => {
+        line('skipped', t('quick.skipped', { title, id, reason }))
+      }
+      if (!win.isDestroyed()) {
+        win.webContents.send(IpcChannels.EVENT_VIDEO_TOOLS_QUICK, { done: index, total: ids.length, id, title })
+      }
+      if (job || staged || downloading) {
+        skip(t('quick.reasonBusy'))
+        continue
+      }
+      try {
+        const { file, wallpaper } = requireVideo(id)
+        if (getWallpapersInUse().has(id)) {
+          skip(t('optimize.errInUse'))
+          continue
+        }
+        const info = await probeFile(file)
+        const plan = planQuickOptimize(info, settings, trim ? trimAsCut(wallpaper, info.duration) : null)
+        if ('skip' in plan) {
+          skip(plan.skip === 'hevc' ? t('quick.reasonHevc') : t('quick.reasonHevcSize', { size: plan.size }))
+          continue
+        }
+        const result = await startOptimize(id, plan.options, win)
+        if (result.newSize >= result.originalSize) {
+          await finishOptimize(id, false)
+          skip(t('quick.reasonBigger'))
+          continue
+        }
+        await finishOptimize(id, true)
+        report.optimized++
+        report.savedBytes += result.originalSize - result.newSize
+        if (getVideoToolSettings().backupOriginal) report.originalsKept = true
+      } catch (err) {
+        const message = (err as Error).message
+        if (hasStagedResult() === id) await finishOptimize(id, false).catch(() => undefined)
+        const kind = err instanceof OptimizeError ? err.kind : null
+        if (quickCancelled && kind === 'cancelled') break
+        if (kind === 'busy') skip(t('quick.reasonBusy'))
+        else if (kind === 'skip') skip(message)
+        else line('failed', t('quick.failed', { title, id, error: message }))
+      }
+    }
+  } finally {
+    quickRunning = false
+  }
+  return report
+}
+
+export function abandonOptimize(): void {
+  cancelOptimize()
+  if (!staged || finishing) return
+  fs.rmSync(staged.temp, { force: true })
+  staged = null
+}
+
+export function discardStagedOnExit(): void {
+  if (job) {
+    job.cancelled = true
+    job.child?.kill('SIGKILL')
+    for (const helper of job.helpers) helper.kill('SIGKILL')
+    if (job.temp) {
+      try {
+        fs.rmSync(job.temp, { force: true })
+      } catch {}
+    }
+  }
+  if (!staged) return
+  try {
+    fs.rmSync(staged.temp, { force: true })
+  } catch {}
+  staged = null
+}
+
+export function hasStagedResult(): string | null {
+  return staged?.id ?? null
+}

+ 1 - 4
src/main/services/wallpaper.service.ts

@@ -1,5 +1,3 @@
-import { execFile } from 'child_process'
-import { promisify } from 'util'
 import * as os from 'os'
 import * as fs from 'fs'
 import * as path from 'path'
@@ -21,8 +19,7 @@ import { resolveEngineFlags } from '@shared/engineFlags'
 import { needsFreshLaunch } from '@shared/compat'
 import { videoSegmentsOf } from '@shared/videoTrim'
 import { applyHyprpaper, applySwaybg, applySwww, hasHyprpaper, prefersHyprpaper, swwwCommand } from './static-wallpaper.service'
-
-const execFileAsync = promisify(execFile)
+import { execFileAsync } from '../utils/exec'
 
 let envCache: WallpaperEnvironment | null = null
 

+ 21 - 1
src/main/services/workshop-verify.service.test.ts

@@ -13,7 +13,8 @@ let installInfo: { folder: string; sizeOnDisk: number } | null = null
 const wallpapers = new Map<string, WallpaperMeta>()
 
 vi.mock('electron', () => ({ app: { getPath: () => os.tmpdir() } }))
-vi.mock('./config.service', () => ({ getConfiguredBackupPath: () => null }))
+let identity = 'wallpaper-engine'
+vi.mock('./config.service', () => ({ getConfiguredBackupPath: () => null, getSteamIdentity: () => identity }))
 vi.mock('../utils/paths', () => ({ getWorkshopPath: () => dir }))
 vi.mock('./steam.service', () => ({
   ITEM_STATE_INSTALLED: 4,
@@ -146,6 +147,8 @@ describe('verifyItems', () => {
     wallpapers.set('2', wallpaper('2', { localPath: path.join(dir, 'gone') }))
     wallpapers.set('3', wallpaper('3', { downloading: true }))
     wallpapers.set('4', wallpaper('4', { source: 'local' }))
+    wallpapers.set('8', wallpaper('8', { localPath: path.join(dir, 'empty') }))
+    subscribed = ['1', '2', '3']
     installInfo = null
 
     const progress: number[] = []
@@ -159,6 +162,7 @@ describe('verifyItems', () => {
 
   it('skips items Steam could not be asked about instead of calling them not installed', async () => {
     wallpapers.set('1', wallpaper('1'))
+    subscribed = ['1']
     steamDown = true
 
     const result = await verify.verifyItems(undefined, () => {})
@@ -182,6 +186,22 @@ describe('verifyItems', () => {
     expect(wallpapers.get('5')!.verifyProblem).toBeUndefined()
     expect(wallpapers.has('6')).toBe(false)
   })
+
+  it('does not read the Spacewar subscriptions as the whole list', async () => {
+    identity = 'standalone'
+    try {
+      wallpapers.set('1', wallpaper('1', { verifyProblem: 'missingFolder' }))
+      subscribed = ['999']
+      installInfo = null
+      state = 0
+
+      await verify.verifyItems(['1'], () => {})
+
+      expect(wallpapers.get('1')!.verifyProblem).toBeDefined()
+    } finally {
+      identity = 'wallpaper-engine'
+    }
+  })
 })
 
 function stashed(id: string, newFiles: Record<string, string>): { item: string; stash: string } {

+ 21 - 6
src/main/services/workshop-verify.service.ts

@@ -3,6 +3,7 @@ import * as path from 'path'
 import type { VerifyProblem, VerifyResult, WallpaperMeta } from '@shared/types'
 import * as library from './library.service'
 import * as steam from './steam.service'
+import { getSteamIdentity } from './config.service'
 import { exists, findFolderProblem, forEachLimit } from './backup.service'
 import { getWorkshopPath } from '../utils/paths'
 
@@ -132,15 +133,21 @@ export function restoreRepairStashes(): Promise<void> {
 
 // subscriptions too, which may have no workshop entry yet
 
-async function verifiableItems(ids?: string[]): Promise<{ wallpaper: WallpaperMeta; inLibrary: boolean }[]> {
+async function verifiableItems(
+  ids?: string[]
+): Promise<{ items: { wallpaper: WallpaperMeta; inLibrary: boolean }[]; stale: string[] }> {
   const wanted = ids ? new Set(ids) : null
   const all = library.getAllWallpapers()
   const byId = new Map(all.map((w) => [w.id, w]))
+  const subscribed = await steam.getSubscribedItems()
+  const subscribedIds = new Set(subscribed)
+  // an unsubscribed item can leave an empty folder behind, which is not damage; an empty answer is Steam not synced yet,
+  // and as Spacewar the list is not Wallpaper Engine's
+  const listKnown = subscribedIds.size > 0 && getSteamIdentity() === 'wallpaper-engine'
   const items = all
-    .filter((w) => w.source === 'workshop' && (!wanted || wanted.has(w.id)))
+    .filter((w) => w.source === 'workshop' && (!listKnown || subscribedIds.has(w.id)) && (!wanted || wanted.has(w.id)))
     .map((wallpaper) => ({ wallpaper, inLibrary: true }))
 
-  const subscribed = await steam.getSubscribedItems()
   for (const id of subscribed) {
     const existing = byId.get(id)
     if (existing?.source === 'workshop' || (wanted && !wanted.has(id))) continue
@@ -162,7 +169,12 @@ async function verifiableItems(ids?: string[]): Promise<{ wallpaper: WallpaperMe
       inLibrary: false
     })
   }
-  return items
+  const stale = listKnown
+    ? all
+        .filter((w) => w.source === 'workshop' && w.verifyProblem && !subscribedIds.has(w.id) && (!wanted || wanted.has(w.id)))
+        .map((w) => w.id)
+    : []
+  return { items, stale }
 }
 
 export async function verifyItems(
@@ -170,8 +182,11 @@ export async function verifyItems(
   onProgress: (done: number, total: number) => void
 ): Promise<VerifyResult> {
   if (!steam.isSteamRunning()) throw new Error('Steam is not running')
-  const items = await verifiableItems(ids)
-  const patches: { id: string; patch: Partial<WallpaperMeta> }[] = []
+  const { items, stale } = await verifiableItems(ids)
+  const patches: { id: string; patch: Partial<WallpaperMeta> }[] = stale.map((id) => ({
+    id,
+    patch: { verifyProblem: undefined }
+  }))
   const damaged: string[] = []
   let skipped = 0
   let done = 0

+ 82 - 0
src/main/utils/audio-activity.ts

@@ -0,0 +1,82 @@
+import { hostCommand, isFlatpak } from './flatpak'
+import { parentPid, parentSnapshot } from './processes'
+import { execFileAsync } from './exec'
+
+interface SinkInput {
+  corked?: boolean
+  mute?: boolean
+  properties?: Record<string, string>
+}
+
+/** The streams that are playing right now, with the process each belongs to (0 when the server does not say) */
+export function playingStreams(json: string): { pid: number; binary: string }[] {
+  let inputs: unknown
+  try {
+    inputs = JSON.parse(json)
+  } catch {
+    return []
+  }
+  if (!Array.isArray(inputs)) return []
+
+  return (inputs as SinkInput[])
+    .filter((input) => input.corked === false && input.mute !== true)
+    .map((input) => ({
+      pid: Number(input.properties?.['application.process.id']) || 0,
+      binary: input.properties?.['application.process.binary'] ?? input.properties?.['application.name'] ?? ''
+    }))
+}
+
+async function descendsFrom(pid: number, owners: ReadonlySet<number>, snapshot: Map<number, number> | null): Promise<boolean> {
+  let current = pid
+  for (let depth = 0; depth < 12 && current > 1; depth++) {
+    if (owners.has(current)) return true
+    current = snapshot ? (snapshot.get(current) ?? 0) : await parentPid(current)
+  }
+  return false
+}
+
+let warned = false
+
+const SINK_INPUT_ARGS = ['--format=json', 'list', 'sink-inputs']
+
+function pactl(): [string, string[]] {
+  return hostCommand('pactl', SINK_INPUT_ARGS)
+}
+
+export async function isAudioDetectionAvailable(): Promise<boolean> {
+  try {
+    await execFileAsync(...pactl(), { timeout: 3000, maxBuffer: 4 * 1024 * 1024 })
+    return true
+  } catch {
+    return false
+  }
+}
+
+/**
+ * Whether anything but the wallpaper engines (and this app) is playing sound. `owners` are the pids whose sound does not
+ * count, their children are skipped too (the web wallpaper host, Chromium's audio process).
+ */
+export async function isAudioPlaying(owners: ReadonlySet<number>): Promise<boolean> {
+  let stdout: string
+  try {
+    ;({ stdout } = await execFileAsync(...pactl(), {
+      timeout: 3000,
+      maxBuffer: 4 * 1024 * 1024,
+      encoding: 'utf8'
+    }))
+  } catch (err) {
+    if (!warned) {
+      warned = true
+      console.warn('[AppRules] cannot ask the sound server for playing streams (pactl):', (err as Error).message)
+    }
+    return false
+  }
+
+  const snapshot = isFlatpak() ? await parentSnapshot() : null
+  for (const stream of playingStreams(stdout)) {
+    if (/wallpaperengine/i.test(stream.binary)) continue
+    if (stream.pid > 0 && (await descendsFrom(stream.pid, owners, snapshot))) continue
+    return true
+  }
+  return false
+}

+ 4 - 0
src/main/utils/exec.ts

@@ -0,0 +1,4 @@
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+
+export const execFileAsync = promisify(execFile)

+ 9 - 2
src/main/utils/flatpak.ts

@@ -17,12 +17,19 @@ function sessionEnvArgs(env: NodeJS.ProcessEnv = process.env): string[] {
 }
 
 /** Runs on the host, through flatpak-spawn inside a Flatpak */
-export function hostCommand(cmd: string, args: string[] = []): [string, string[]] {
-  return isFlatpak() ? ['flatpak-spawn', ['--host', ...sessionEnvArgs(), cmd, ...args]] : [cmd, args]
+export function hostCommand(cmd: string, args: string[] = [], opts: { dieWithApp?: boolean } = {}): [string, string[]] {
+  if (!isFlatpak()) return [cmd, args]
+  // SIGKILL cannot reach the host through flatpak-spawn, --watch-bus ends the command when this app's bus connection goes
+  const watch = opts.dieWithApp ? ['--watch-bus'] : []
+  return ['flatpak-spawn', ['--host', ...watch, ...sessionEnvArgs(), cmd, ...args]]
 }
 
 const hostCommandCache = new Map<string, boolean>()
 
+export function invalidateHostCommandCache(cmd: string): void {
+  hostCommandCache.delete(cmd)
+}
+
 export function isHostCommandAvailable(cmd: string): boolean {
   const cached = hostCommandCache.get(cmd)
   if (cached !== undefined) return cached

+ 18 - 20
src/main/utils/github.ts

@@ -30,37 +30,35 @@ export function selectableReleases(releases: GithubRelease[]): GithubRelease[] {
   return releases.filter((r) => !r.draft && isVersionTag(r.tag_name))
 }
 
-export async function fetchLatestRelease(repo: string): Promise<GithubRelease | null> {
-  const res = await fetch(`https://api.github.com/repos/${repo}/releases/latest`, {
-    headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'we-manager' },
+const USER_AGENT = 'we-manager'
+
+async function githubGet(url: string, what: string, allowMissing: boolean): Promise<Response | null> {
+  const res = await fetch(url, {
+    headers: { Accept: 'application/vnd.github+json', 'User-Agent': USER_AGENT },
     signal: AbortSignal.timeout(20_000)
   })
-  if (res.status === 404) return null
-  if (!res.ok) throw new Error(`GitHub answered ${res.status} ${res.statusText} for the latest release of ${repo}.`)
-  return (await res.json()) as GithubRelease
+  if (allowMissing && res.status === 404) return null
+  if (!res.ok) throw new Error(`GitHub answered ${res.status} ${res.statusText} for ${what}.`)
+  return res
+}
+
+export async function fetchLatestRelease(repo: string): Promise<GithubRelease | null> {
+  const res = await githubGet(`https://api.github.com/repos/${repo}/releases/latest`, `the latest release of ${repo}`, true)
+  return res && ((await res.json()) as GithubRelease)
 }
 
 export async function fetchReleases(repo: string): Promise<GithubRelease[]> {
-  const res = await fetch(`https://api.github.com/repos/${repo}/releases?per_page=100`, {
-    headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'we-manager' },
-    signal: AbortSignal.timeout(20_000)
-  })
-  if (!res.ok) throw new Error(`GitHub answered ${res.status} ${res.statusText} for the releases of ${repo}.`)
-  return selectableReleases((await res.json()) as GithubRelease[])
+  const res = await githubGet(`https://api.github.com/repos/${repo}/releases?per_page=100`, `the releases of ${repo}`, false)
+  return selectableReleases((await res!.json()) as GithubRelease[])
 }
 
 export async function fetchReleaseByTag(repo: string, tag: string): Promise<GithubRelease | null> {
-  const res = await fetch(`https://api.github.com/repos/${repo}/releases/tags/${encodeURIComponent(tag)}`, {
-    headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'we-manager' },
-    signal: AbortSignal.timeout(20_000)
-  })
-  if (res.status === 404) return null
-  if (!res.ok) throw new Error(`GitHub answered ${res.status} ${res.statusText} for the ${tag} release of ${repo}.`)
-  return (await res.json()) as GithubRelease
+  const res = await githubGet(`https://api.github.com/repos/${repo}/releases/tags/${encodeURIComponent(tag)}`, `the ${tag} release of ${repo}`, true)
+  return res && ((await res.json()) as GithubRelease)
 }
 
 export async function download(url: string, dest: string, total: number, onProgress: (fraction: number) => void): Promise<void> {
-  const res = await fetch(url, { headers: { 'User-Agent': 'we-manager' } })
+  const res = await fetch(url, { headers: { 'User-Agent': USER_AGENT } })
   if (!res.ok || !res.body) throw new Error(`Download failed: ${res.status} ${res.statusText}`)
 
   const size = Number(res.headers.get('content-length')) || total

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

@@ -1,12 +1,9 @@
 import * as fs from 'fs'
 import * as path from 'path'
-import { execFile } from 'child_process'
-import { promisify } from 'util'
 import type { WallpaperMeta } from '@shared/types'
 import { isCommandAvailable } from './platform'
 import { findWallpaperVideoFile } from './video'
-
-const execFileAsync = promisify(execFile)
+import { execFileAsync } from './exec'
 
 // .pkg files can be huge, read only the entry table (64KB covers most) and one entry
 const PKG_HEADER_CHUNK = 64 * 1024

+ 87 - 0
src/main/utils/loginSession.ts

@@ -0,0 +1,87 @@
+import { randomBytes } from 'crypto'
+import { readFileSync, realpathSync, writeFileSync } from 'fs'
+import path from 'path'
+import { isFlatpak } from './flatpak'
+
+function bootId(): string {
+  try {
+    return readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim()
+  } catch {
+    return String(Math.round(Date.now() / 1000 - process.uptime()))
+  }
+}
+
+function runtimeDir(): string {
+  const dir = process.env.XDG_RUNTIME_DIR
+  return dir && dir.startsWith('/') ? dir : `/run/user/${process.getuid?.() ?? 0}`
+}
+
+function unescapeMountPoint(text: string): string {
+  return text.replace(/\\([0-7]{3})/g, (_m, octal: string) => String.fromCharCode(parseInt(octal, 8)))
+}
+
+/** The id of the mount the runtime dir sits on: a tmpfs of its own from the first login to the last logout */
+function runtimeMountId(dir: string): string {
+  let resolved = dir
+  try {
+    resolved = realpathSync(dir)
+  } catch {
+    return ''
+  }
+  let best = ''
+  let bestLength = -1
+  try {
+    for (const line of readFileSync('/proc/self/mountinfo', 'utf8').split('\n')) {
+      const fields = line.split(' ')
+      if (fields.length < 5) continue
+      const point = unescapeMountPoint(fields[4])
+      const inside = point === '/' || resolved === point || resolved.startsWith(`${point}/`)
+      if (inside && point.length >= bestLength) {
+        best = fields[0]
+        bestLength = point.length
+      }
+    }
+  } catch {
+    return ''
+  }
+  return best
+}
+
+/** Inside a Flatpak the runtime dir is a new tmpfs for every run, the app's folder in it is the host's */
+function flatpakLoginMarker(): string {
+  const appId = process.env.FLATPAK_ID
+  if (!appId) return ''
+  const file = path.join(runtimeDir(), 'app', appId, 'we-manager-login')
+  try {
+    const saved = readFileSync(file, 'utf8').trim()
+    if (saved) return saved
+  } catch {
+    // not written yet
+  }
+  const id = randomBytes(16).toString('hex')
+  try {
+    writeFileSync(file, `${id}\n`, { flag: 'wx', mode: 0o600 })
+  } catch {
+    try {
+      return readFileSync(file, 'utf8').trim()
+    } catch {
+      return ''
+    }
+  }
+  return id
+}
+
+/**
+ * Tells two login sessions apart, the way the engine's PlaylistSchedule does: XDG_SESSION_ID is missing for
+ * autostart entries and user services, the runtime dir's mount is not
+ */
+export function loginSessionToken(): string {
+  const boot = bootId()
+  if (isFlatpak()) {
+    const marker = flatpakLoginMarker()
+    if (marker) return `${boot}:f${marker}`
+  }
+  const mount = runtimeMountId(runtimeDir())
+  if (mount) return `${boot}:m${mount}`
+  return `${boot}:${process.env.XDG_SESSION_ID ?? ''}`
+}

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

@@ -75,6 +75,12 @@ export function getLwePrebuiltDir(): string {
   return path.join(dataHome, 'linux-wallpaperengine-kde')
 }
 
+/** Where the downloaded ffmpeg lives, outside the app's own data so the AppImage and .deb share it */
+export function getFfmpegDir(): string {
+  const dataHome = process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share')
+  return path.join(dataHome, 'we-manager', 'ffmpeg')
+}
+
 export function getLweManifestPath(): string {
   return path.join(getDataPath(), 'lwe-install-manifest.json')
 }

+ 41 - 0
src/main/utils/processes.test.ts

@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest'
+import { processNames } from './processes'
+import { playingStreams } from './audio-activity'
+
+describe('processNames', () => {
+  it('uses comm, the program and the first arguments', () => {
+    expect(processNames('firefox\n', 'firefox\0--new-window\0', '/usr/lib64/firefox/firefox')).toEqual(['firefox'])
+  })
+
+  it('finds a Windows program run by Wine', () => {
+    const names = processNames('game.exe\n', 'Z:\\games\\Game.exe\0', '/usr/bin/wine64-preloader')
+    expect(names).toContain('game')
+    expect(names).toContain('wine64-preloader')
+  })
+
+  it('ignores empty fields', () => {
+    expect(processNames('', '', '')).toEqual([])
+  })
+})
+
+describe('playingStreams', () => {
+  const streams = JSON.stringify([
+    { corked: false, mute: false, properties: { 'application.process.id': '42', 'application.process.binary': 'mpv' } },
+    { corked: true, properties: { 'application.process.id': '43', 'application.process.binary': 'paused' } },
+    { corked: false, mute: true, properties: { 'application.process.id': '44' } },
+    { corked: false, properties: { 'application.name': 'Some Player' } }
+  ])
+
+  it('keeps streams that are neither corked nor muted', () => {
+    expect(playingStreams(streams)).toEqual([
+      { pid: 42, binary: 'mpv' },
+      { pid: 0, binary: 'Some Player' }
+    ])
+  })
+
+  it('survives output that is not a list', () => {
+    expect(playingStreams('')).toEqual([])
+    expect(playingStreams('{}')).toEqual([])
+    expect(playingStreams('Sink Input #1')).toEqual([])
+  })
+})

+ 123 - 0
src/main/utils/processes.ts

@@ -0,0 +1,123 @@
+import { readdir, readFile, readlink } from 'fs/promises'
+import { normalizeProcessName } from '@shared/appRules'
+import { hostCommand, isFlatpak } from './flatpak'
+import { execFileAsync } from './exec'
+
+/** The names a process goes by: its comm, the program it runs and, for Wine, the .exe on its command line */
+export function processNames(comm: string, cmdline: string, exe: string): string[] {
+  const names = new Set<string>()
+  const add = (name: string) => {
+    const normalized = normalizeProcessName(name)
+    if (normalized !== '') names.add(normalized)
+  }
+
+  add(comm)
+  add(exe)
+  const args = cmdline.split('\0').filter((arg) => arg !== '')
+  if (args.length > 0) add(args[0])
+  for (const arg of args.slice(0, 4)) {
+    if (/\.exe$/i.test(arg)) add(arg)
+  }
+  return [...names]
+}
+
+async function readOr(read: () => Promise<string>): Promise<string> {
+  try {
+    return await read()
+  } catch {
+    return ''
+  }
+}
+
+// the kernel cuts comm at 15 characters
+const COMM_WIDTH = 15
+
+const namesByPid = new Map<string, { comm: string; names: string[] }>()
+
+/** Every process the user can see, by normalized name. Empty where /proc cannot be read */
+export async function listProcessNames(): Promise<Set<string>> {
+  const found = new Set<string>()
+  if (isFlatpak()) {
+    try {
+      const [file, args] = hostCommand('ps', ['-eo', `comm:${COMM_WIDTH}=,args=`])
+      const { stdout } = await execFileAsync(file, args, { timeout: 5000, maxBuffer: 8 * 1024 * 1024, encoding: 'utf8' })
+      for (const line of stdout.split('\n')) {
+        const comm = line.slice(0, COMM_WIDTH).trim()
+        if (!comm) continue
+        const rest = line.slice(COMM_WIDTH).trim().split(/\s+/)
+        for (const name of processNames(comm, rest.join('\0'), rest[0] ?? '')) found.add(name)
+      }
+    } catch {
+      return found
+    }
+    return found
+  }
+  let entries: string[]
+  try {
+    entries = (await readdir('/proc')).filter((entry) => /^\d+$/.test(entry))
+  } catch {
+    return found
+  }
+
+  const CHUNK = 64
+  const alive = new Set(entries)
+  for (const pid of namesByPid.keys()) {
+    if (!alive.has(pid)) namesByPid.delete(pid)
+  }
+  for (let i = 0; i < entries.length; i += CHUNK) {
+    await Promise.all(
+      entries.slice(i, i + CHUNK).map(async (pid) => {
+        const base = `/proc/${pid}`
+        const comm = await readOr(() => readFile(`${base}/comm`, 'utf8'))
+        let known = namesByPid.get(pid)
+        if (!known || known.comm !== comm) {
+          const [cmdline, exe] = await Promise.all([
+            readOr(() => readFile(`${base}/cmdline`, 'utf8')),
+            readOr(() => readlink(`${base}/exe`))
+          ])
+          known = { comm, names: processNames(comm, cmdline, exe) }
+          namesByPid.set(pid, known)
+        }
+        for (const name of known.names) found.add(name)
+      })
+    )
+  }
+  return found
+}
+
+/** Every process's parent from one `ps` call on the host, for walking several ancestries without a spawn per step */
+export async function parentSnapshot(): Promise<Map<number, number>> {
+  const parents = new Map<number, number>()
+  try {
+    const [file, args] = hostCommand('ps', ['-eo', 'pid=,ppid='])
+    const { stdout } = await execFileAsync(file, args, { timeout: 3000, encoding: 'utf8', maxBuffer: 8 * 1024 * 1024 })
+    for (const line of stdout.split('\n')) {
+      const [pid, ppid] = line.trim().split(/\s+/).map(Number)
+      if (pid && ppid >= 0) parents.set(pid, ppid)
+    }
+  } catch {
+    // an empty snapshot makes every stream count as foreign
+  }
+  return parents
+}
+
+/** The parent of a process, 0 when it is gone or unreadable */
+export async function parentPid(pid: number): Promise<number> {
+  if (isFlatpak()) {
+    try {
+      const [file, args] = hostCommand('ps', ['-o', 'ppid=', '-p', String(pid)])
+      const { stdout } = await execFileAsync(file, args, { timeout: 3000, encoding: 'utf8' })
+      return Number(stdout.trim()) || 0
+    } catch {
+      return 0
+    }
+  }
+  try {
+    const stat = await readFile(`/proc/${pid}/stat`, 'utf8')
+    // the name in parentheses may hold spaces and parentheses, the fields follow the last one
+    const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ')
+    return Number(fields[1]) || 0
+  } catch {
+    return 0
+  }
+}

+ 21 - 0
src/main/utils/projectJson.ts

@@ -0,0 +1,21 @@
+import * as fs from 'fs'
+import * as path from 'path'
+import type { ProjectJson } from '../services/library.service'
+
+const projectFile = (dir: string): string => path.join(dir, 'project.json')
+
+export function readProjectJsonSync(dir: string): ProjectJson | null {
+  try {
+    return JSON.parse(fs.readFileSync(projectFile(dir), 'utf8')) as ProjectJson
+  } catch {
+    return null
+  }
+}
+
+export async function readProjectJson(dir: string): Promise<ProjectJson | null> {
+  try {
+    return JSON.parse(await fs.promises.readFile(projectFile(dir), 'utf8')) as ProjectJson
+  } catch {
+    return null
+  }
+}

+ 4 - 0
src/main/utils/shaderCache.ts

@@ -0,0 +1,4 @@
+// WE writes compiled shaders into the folder
+export function isShaderCache(relPath: string): boolean {
+  return /^shaders[\\/]blobs/i.test(relPath)
+}

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

@@ -1,10 +1,7 @@
-import { execFile } from 'child_process'
-import { promisify } from 'util'
 import * as fs from 'fs'
 import * as path from 'path'
 import { isCommandAvailable } from './platform'
-
-const execFileAsync = promisify(execFile)
+import { execFileAsync } from './exec'
 
 const VIDEO_EXTENSIONS = ['.mp4', '.webm', '.avi', '.mkv', '.mov', '.m4v']
 
@@ -80,3 +77,9 @@ export async function getVideoDurationSec(filePath: string): Promise<number | un
     return undefined
   }
 }
+
+/** the file was replaced, what was probed about it is stale */
+export function forgetVideoProbe(filePath: string): void {
+  fpsCache.delete(filePath)
+  durationCache.delete(filePath)
+}

+ 75 - 3
src/preload/index.ts

@@ -1,4 +1,15 @@
 import { contextBridge, ipcRenderer } from 'electron'
+import type {
+  OptimizeOptions,
+  OptimizeProgress,
+  OptimizeResult,
+  QuickProgress,
+  QuickReport,
+  QuickTrim,
+  VideoProbe,
+  VideoToolSettings,
+  VideoToolsStatus
+} from '@shared/video-tools'
 import { IpcChannels } from '../shared/ipc-channels'
 import type { Appearance } from '../shared/appearance'
 import type { Language, LanguagePreference } from '../shared/i18n'
@@ -28,6 +39,9 @@ import type {
   LweAudioObject,
   LweSceneEffect,
   LweFontNeed,
+  AudioInputDevice,
+  AppRule,
+  Profile,
   UserFont,
   DesktopApplication,
   BackupProgressEvent,
@@ -105,7 +119,7 @@ const api = {
       ipcRenderer.invoke(IpcChannels.STEAM_GET_FAVORITE_IDS),
     getFavoriteStatus: (): Promise<FavoriteStatus> =>
       ipcRenderer.invoke(IpcChannels.STEAM_GET_FAVORITE_STATUS),
-    getAuthorInfo: (steamId: string): Promise<WorkshopAuthorInfo> =>
+    getAuthorInfo: (steamId: string): Promise<WorkshopAuthorInfo | null> =>
       ipcRenderer.invoke(IpcChannels.STEAM_GET_AUTHOR_INFO, steamId)
   },
 
@@ -131,7 +145,7 @@ const api = {
       ipcRenderer.invoke(IpcChannels.LIBRARY_DISTINCT_TAGS),
     resetFpsOverrides: (): Promise<{ count: number }> =>
       ipcRenderer.invoke(IpcChannels.LIBRARY_RESET_FPS_OVERRIDES),
-    checkUnavailable: (): Promise<{ checked: number; unavailable: number; changed: boolean }> =>
+    checkUnavailable: (): Promise<{ checked: number; unavailable: number; changed: boolean; failed: boolean }> =>
       ipcRenderer.invoke(IpcChannels.LIBRARY_CHECK_UNAVAILABLE),
     transfer: (
       ids: string[],
@@ -187,6 +201,10 @@ const api = {
       ipcRenderer.invoke(IpcChannels.CONFIG_SET_SKIP_PLAYLIST_RESUME, enabled),
     setFreshProcessOnPathChange: (enabled: boolean): Promise<{ ok: boolean }> =>
       ipcRenderer.invoke(IpcChannels.CONFIG_SET_FRESH_PROCESS_ON_PATH_CHANGE, enabled),
+    setStopPlaylistsOnKillAll: (enabled: boolean): Promise<{ ok: boolean }> =>
+      ipcRenderer.invoke(IpcChannels.CONFIG_SET_STOP_PLAYLISTS_ON_KILL_ALL, enabled),
+    setForgetOnKillAll: (enabled: boolean): Promise<{ ok: boolean }> =>
+      ipcRenderer.invoke(IpcChannels.CONFIG_SET_FORGET_ON_KILL_ALL, enabled),
     setCardBorders: (borders: CardBorders): Promise<CardBorders> =>
       ipcRenderer.invoke(IpcChannels.CONFIG_SET_CARD_BORDERS, borders),
     setCardBadges: (badges: CardBadges): Promise<CardBadges> =>
@@ -245,7 +263,7 @@ const api = {
     updateItem: (
       id: string,
       wallpaperId: string,
-      patch: { volume?: number; durationSec?: number }
+      patch: { volume?: number; durationSec?: number; endMinute?: number }
     ): Promise<Playlist | null> =>
       ipcRenderer.invoke(IpcChannels.PLAYLIST_UPDATE_ITEM, id, wallpaperId, patch),
     start: (id: string, screen?: ScreenTarget): Promise<PlaylistPlaybackState[]> =>
@@ -356,6 +374,7 @@ const api = {
       ipcRenderer.invoke(IpcChannels.LWE_LIST_AUDIO_OBJECTS, wallpaperPath),
     listEffects: (wallpaperPath: string): Promise<LweSceneEffect[]> =>
       ipcRenderer.invoke(IpcChannels.LWE_LIST_EFFECTS, wallpaperPath),
+    listAudioInputs: (): Promise<AudioInputDevice[]> => ipcRenderer.invoke(IpcChannels.LWE_LIST_AUDIO_INPUTS),
     listFonts: (wallpaperPath: string): Promise<LweFontNeed[]> =>
       ipcRenderer.invoke(IpcChannels.LWE_LIST_FONTS, wallpaperPath),
     listApplications: (): Promise<DesktopApplication[]> =>
@@ -372,6 +391,22 @@ const api = {
     run: (id: string): Promise<{ ok: boolean }> => ipcRenderer.invoke(IpcChannels.SCHEDULE_RUN, id)
   },
 
+  appRules: {
+    getAll: (): Promise<AppRule[]> => ipcRenderer.invoke(IpcChannels.APP_RULES_GET_ALL),
+    save: (rule: Omit<AppRule, 'id'> & { id?: string }): Promise<AppRule> =>
+      ipcRenderer.invoke(IpcChannels.APP_RULES_SAVE, rule),
+    delete: (id: string): Promise<{ ok: boolean }> => ipcRenderer.invoke(IpcChannels.APP_RULES_DELETE, id),
+    active: (): Promise<string[]> => ipcRenderer.invoke(IpcChannels.APP_RULES_ACTIVE),
+    audioAvailable: (): Promise<boolean> => ipcRenderer.invoke(IpcChannels.APP_RULES_AUDIO_AVAILABLE)
+  },
+
+  profiles: {
+    getAll: (): Promise<Profile[]> => ipcRenderer.invoke(IpcChannels.PROFILES_GET_ALL),
+    capture: (name: string): Promise<Profile> => ipcRenderer.invoke(IpcChannels.PROFILES_CAPTURE, name),
+    delete: (id: string): Promise<{ ok: boolean; disabled: number }> => ipcRenderer.invoke(IpcChannels.PROFILES_DELETE, id),
+    apply: (id: string): Promise<{ ok: boolean }> => ipcRenderer.invoke(IpcChannels.PROFILES_APPLY, id)
+  },
+
   backup: {
     item: (itemId: string): Promise<{ ok: boolean; alreadyBackedUp: boolean; unsubscribed: boolean }> =>
       ipcRenderer.invoke(IpcChannels.BACKUP_ITEM, itemId),
@@ -392,11 +427,33 @@ const api = {
       ipcRenderer.invoke(IpcChannels.BACKUP_REMOVE, itemIds)
   },
 
+  videoTools: {
+    status: (): Promise<VideoToolsStatus> => ipcRenderer.invoke(IpcChannels.VIDEO_TOOLS_STATUS),
+    download: (): Promise<{ ok: boolean }> => ipcRenderer.invoke(IpcChannels.VIDEO_TOOLS_DOWNLOAD),
+    remove: (): Promise<{ ok: boolean }> => ipcRenderer.invoke(IpcChannels.VIDEO_TOOLS_REMOVE),
+    probe: (itemId: string): Promise<VideoProbe> => ipcRenderer.invoke(IpcChannels.VIDEO_TOOLS_PROBE, itemId),
+    start: (itemId: string, options: OptimizeOptions): Promise<OptimizeResult> =>
+      ipcRenderer.invoke(IpcChannels.VIDEO_TOOLS_START, itemId, options),
+    cancel: (): Promise<{ ok: boolean }> => ipcRenderer.invoke(IpcChannels.VIDEO_TOOLS_CANCEL),
+    finish: (itemId: string, keep: boolean): Promise<{ ok: boolean }> =>
+      ipcRenderer.invoke(IpcChannels.VIDEO_TOOLS_FINISH, itemId, keep),
+    getSettings: (): Promise<VideoToolSettings> => ipcRenderer.invoke(IpcChannels.VIDEO_TOOLS_GET_SETTINGS),
+    setSettings: (settings: VideoToolSettings): Promise<VideoToolSettings> =>
+      ipcRenderer.invoke(IpcChannels.VIDEO_TOOLS_SET_SETTINGS, settings),
+    quick: (ids: string[], trim?: boolean): Promise<QuickReport> =>
+      ipcRenderer.invoke(IpcChannels.VIDEO_TOOLS_QUICK, ids, trim),
+    quickTrims: (ids: string[]): Promise<QuickTrim[]> => ipcRenderer.invoke(IpcChannels.VIDEO_TOOLS_QUICK_TRIMS, ids)
+  },
+
   desktopIcons: {
     setEnabled: (enabled: boolean): Promise<{ ok: boolean; enabled: boolean }> =>
       ipcRenderer.invoke(IpcChannels.DESKTOP_ICONS_SET_ENABLED, enabled),
     getEnabled: (): Promise<boolean> =>
       ipcRenderer.invoke(IpcChannels.DESKTOP_ICONS_GET_ENABLED),
+    setAuto: (auto: boolean): Promise<{ ok: boolean }> =>
+      ipcRenderer.invoke(IpcChannels.DESKTOP_ICONS_SET_AUTO, auto),
+    getAuto: (): Promise<boolean> =>
+      ipcRenderer.invoke(IpcChannels.DESKTOP_ICONS_GET_AUTO),
     getStatus: (): Promise<DesktopIconsStatus> => ipcRenderer.invoke(IpcChannels.DESKTOP_ICONS_GET_STATUS),
     installDeps: (): Promise<{ ok: boolean; error?: string }> =>
       ipcRenderer.invoke(IpcChannels.DESKTOP_ICONS_INSTALL_DEPS)
@@ -487,6 +544,16 @@ const api = {
       ipcRenderer.on(IpcChannels.EVENT_REPAIR_PROGRESS, listener)
       return () => ipcRenderer.off(IpcChannels.EVENT_REPAIR_PROGRESS, listener)
     },
+    videoToolsProgress: (cb: (progress: OptimizeProgress) => void): (() => void) => {
+      const listener = (_: Electron.IpcRendererEvent, progress: OptimizeProgress) => { cb(progress) }
+      ipcRenderer.on(IpcChannels.EVENT_VIDEO_TOOLS_PROGRESS, listener)
+      return () => ipcRenderer.off(IpcChannels.EVENT_VIDEO_TOOLS_PROGRESS, listener)
+    },
+    videoToolsQuick: (cb: (progress: QuickProgress) => void): (() => void) => {
+      const listener = (_: Electron.IpcRendererEvent, progress: QuickProgress) => { cb(progress) }
+      ipcRenderer.on(IpcChannels.EVENT_VIDEO_TOOLS_QUICK, listener)
+      return () => ipcRenderer.off(IpcChannels.EVENT_VIDEO_TOOLS_QUICK, listener)
+    },
     backupProgress: (cb: (progress: BackupProgressEvent) => void): (() => void) => {
       const listener = (_: Electron.IpcRendererEvent, progress: BackupProgressEvent) => { cb(progress) }
       ipcRenderer.on(IpcChannels.EVENT_BACKUP_PROGRESS, listener)
@@ -542,6 +609,11 @@ const api = {
       ipcRenderer.on(IpcChannels.EVENT_SCHEDULE_FIRED, listener)
       return () => ipcRenderer.off(IpcChannels.EVENT_SCHEDULE_FIRED, listener)
     },
+    appRule: (cb: (event: { name: string; state: 'started' | 'ended' | 'restoreFailed' | 'failed' }) => void): (() => void) => {
+      const listener = (_: Electron.IpcRendererEvent, event: { name: string; state: 'started' | 'ended' | 'restoreFailed' | 'failed' }) => { cb(event) }
+      ipcRenderer.on(IpcChannels.EVENT_APP_RULE, listener)
+      return () => ipcRenderer.off(IpcChannels.EVENT_APP_RULE, listener)
+    },
     updateStatus: (cb: (status: UpdateStatus) => void): (() => void) => {
       const listener = (_: Electron.IpcRendererEvent, status: UpdateStatus) => { cb(status) }
       ipcRenderer.on(IpcChannels.EVENT_UPDATE_STATUS, listener)

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

@@ -17,6 +17,9 @@ import { useToast } from './components/common/Toast'
 import { screenLabel } from './utils/screens'
 import { UPDATE_STATUS_KEY, useConfig } from './hooks/queries'
 import { FAVORITE_STATUS_KEY } from './hooks/useFavorites'
+import { OptimizeVideoHost } from './components/common/OptimizeVideoModal'
+import QuickOptimizeNotice from './components/common/QuickOptimizeNotice'
+import BackgroundOptimizeNotice from './components/common/BackgroundOptimizeNotice'
 import { DISLIKED_IDS_KEY } from './hooks/useVotes'
 import { applyAppearance, onSystemThemeChange } from './utils/appearance'
 import { currentLanguage, setLanguage, t } from './i18n'
@@ -143,6 +146,10 @@ export default function App() {
     })
   }, [showToast])
 
+  useEffect(() => {
+    return window.electronAPI.on.appRule(({ name, state }) => { showToast(t(`appRule.${state}`, { name })) })
+  }, [showToast])
+
   useEffect(() => {
     return window.electronAPI.on.updateStatus((status) => {
       queryClient.setQueryData(UPDATE_STATUS_KEY, status)
@@ -170,6 +177,8 @@ export default function App() {
         <GnomeExtensionNotice />
         <GraphicsNotice />
         <UpdateNotice />
+        <QuickOptimizeNotice />
+        <BackgroundOptimizeNotice />
         <div className="flex flex-1 overflow-hidden">
           <Sidebar activeView={activeView} onNavigate={setActiveView} />
           <main className="flex-1 overflow-hidden">
@@ -190,6 +199,7 @@ export default function App() {
         <StatusBar />
         <UpdatePrompt />
         <PlayScreenPrompt />
+        <OptimizeVideoHost />
       </div>
     </ErrorBoundary>
   )

+ 68 - 0
src/renderer/src/components/common/BackgroundOptimizeNotice.tsx

@@ -0,0 +1,68 @@
+import { Loader2, X } from 'lucide-react'
+import { useQueryClient } from '@tanstack/react-query'
+import { cancelBackgroundOptimize, dismissBackgroundError, finishBackgroundOptimize, useBackgroundOptimize } from '../../hooks/useBackgroundOptimize'
+import { useToast } from './Toast'
+import { formatFileSize } from '../../utils/format'
+import { t } from '../../i18n'
+
+export default function BackgroundOptimizeNotice() {
+  const { phase, percent, result, error, finishing } = useBackgroundOptimize()
+  const queryClient = useQueryClient()
+  const { showToast } = useToast()
+  if (!phase && !error) return null
+
+  const grew = !!result && result.newSize >= result.originalSize
+  const finish = (keep: boolean): void => {
+    void finishBackgroundOptimize(keep, () => {
+      showToast(t('optimize.applied'))
+      void queryClient.invalidateQueries({ queryKey: ['library'] })
+    })
+  }
+
+  return (
+    <div className="flex items-center gap-3 border-b border-fg/10 bg-pane px-4 py-2 text-sm">
+      <div className="flex flex-1 flex-col gap-1">
+        {phase === 'running' && (
+          <span className="flex items-center gap-2 text-gray-300">
+            <Loader2 size={14} className="shrink-0 animate-spin text-accent-400" />
+            {t('optimize.bgRunning', { percent })}
+          </span>
+        )}
+        {phase === 'review' && result && (
+          <span className="text-gray-200">
+            {t('optimize.bgDone', { before: formatFileSize(result.originalSize) ?? '', after: formatFileSize(result.newSize) ?? '' })}
+          </span>
+        )}
+        {error && <span className="text-red-400">{error}</span>}
+      </div>
+      {phase === 'running' && (
+        <button onClick={cancelBackgroundOptimize} className="rounded-lg bg-fg/5 px-3 py-1 text-xs text-gray-300 hover:bg-fg/10">
+          {t('common.cancel')}
+        </button>
+      )}
+      {phase === 'review' && (
+        <>
+          <button
+            onClick={() => { finish(false) }}
+            disabled={finishing}
+            className={grew ? 'rounded-lg bg-accent-600 px-3 py-1 text-xs font-medium text-white hover:bg-accent-500' : 'rounded-lg bg-fg/5 px-3 py-1 text-xs text-gray-300 hover:bg-fg/10'}
+          >
+            {t('optimize.discard')}
+          </button>
+          <button
+            onClick={() => { finish(true) }}
+            disabled={finishing}
+            className={grew ? 'rounded-lg bg-fg/5 px-3 py-1 text-xs text-gray-300 hover:bg-fg/10' : 'rounded-lg bg-accent-600 px-3 py-1 text-xs font-medium text-white hover:bg-accent-500'}
+          >
+            {grew ? t('optimize.keepAnyway') : t('optimize.keep')}
+          </button>
+        </>
+      )}
+      {!phase && error && (
+        <button onClick={dismissBackgroundError} className="rounded p-1 text-gray-500 hover:bg-fg/5 hover:text-gray-300">
+          <X size={14} />
+        </button>
+      )}
+    </div>
+  )
+}

+ 228 - 0
src/renderer/src/components/common/CutRangesEditor.tsx

@@ -0,0 +1,228 @@
+import { useEffect, useRef, useState } from 'react'
+import { Plus, SkipForward, X } from 'lucide-react'
+import { cutRangesProblem, type CutRange } from '@shared/video-tools'
+import { formatVideoTimeExact, parseVideoTime } from '@shared/videoTrim'
+import Toggle from './Toggle'
+import { inputClass } from './inputClass'
+import { t } from '../../i18n'
+
+export interface CutPartText {
+  start: string
+  end: string
+}
+
+export function partsFromRanges(ranges: CutRange[]): CutPartText[] {
+  return ranges.map((r) => ({ start: formatVideoTimeExact(r.start), end: formatVideoTimeExact(r.end) }))
+}
+
+export function parseParts(parts: CutPartText[]): (CutRange | null)[] {
+  return parts.map((p) => {
+    const start = parseVideoTime(p.start)
+    const end = parseVideoTime(p.end)
+    return start === null || end === null ? null : { start, end }
+  })
+}
+
+export function cutProblem(parts: CutPartText[], duration: number): 'range' | 'order' | null {
+  const parsed = parseParts(parts)
+  if (parsed.some((r) => r === null)) return 'range'
+  return cutRangesProblem(parsed as CutRange[], duration)
+}
+
+const SEAM_LEAD = 2
+const SLIDER_STEP = 10
+
+interface Props {
+  parts: CutPartText[]
+  duration: number
+  previewUrl: string | null
+  onChange: (parts: CutPartText[]) => void
+}
+
+export default function CutRangesEditor({ parts, duration, previewUrl, onChange }: Props) {
+  const [selected, setSelected] = useState(0)
+  const [previewOn, setPreviewOn] = useState(false)
+  const [playError, setPlayError] = useState(false)
+  const video = useRef<HTMLVideoElement>(null)
+  const index = Math.min(selected, parts.length - 1)
+  const parsed = parseParts(parts)
+  const problem = cutProblem(parts, duration)
+  const valid = parsed.filter((r): r is CutRange => r !== null && r.end > r.start)
+  const kept = valid.reduce((sum, r) => sum + Math.min(r.end, duration) - r.start, 0)
+  const validRef = useRef<CutRange[]>([])
+  const validKey = valid.map((r) => `${r.start}-${r.end}`).join(',')
+  useEffect(() => {
+    validRef.current = valid
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [validKey])
+
+  function setPart(i: number, patch: Partial<CutPartText>) {
+    onChange(parts.map((p, j) => (j === i ? { ...p, ...patch } : p)))
+  }
+
+  function addPart() {
+    const last = parsed[parsed.length - 1]
+    const from = last ? Math.min(last.end, duration) : 0
+    if (from >= duration - 0.5) return
+    const to = Math.min(duration, from + Math.max(1, Math.round(duration / 10)))
+    setSelected(parts.length)
+    onChange([...parts, { start: formatVideoTimeExact(from), end: formatVideoTimeExact(to) }])
+  }
+
+  function removePart(i: number) {
+    setSelected(Math.max(0, i - 1))
+    onChange(parts.filter((_, j) => j !== i))
+  }
+
+  function playFrom(seconds: number) {
+    const el = video.current
+    if (!el) return
+    el.currentTime = seconds
+    void el.play().catch(() => { setPlayError(true) })
+  }
+
+  useEffect(() => {
+    const el = video.current
+    if (!previewOn || !el) return
+    let frame = 0
+    const tick = () => {
+      const ranges = validRef.current
+      if (!el.paused && ranges.length > 0) {
+        const now = el.currentTime
+        const inside = ranges.some((r) => now >= r.start && now < r.end)
+        if (!inside) {
+          const next = ranges.find((r) => r.start > now)
+          // past the last part the preview starts over
+          el.currentTime = (next ?? ranges[0]).start
+        }
+      }
+      frame = requestAnimationFrame(tick)
+    }
+    const start = () => {
+      cancelAnimationFrame(frame)
+      frame = requestAnimationFrame(tick)
+    }
+    const stop = () => { cancelAnimationFrame(frame) }
+    el.addEventListener('play', start)
+    el.addEventListener('pause', stop)
+    el.addEventListener('ended', stop)
+    if (!el.paused) start()
+    return () => {
+      stop()
+      el.removeEventListener('play', start)
+      el.removeEventListener('pause', stop)
+      el.removeEventListener('ended', stop)
+    }
+  }, [previewOn])
+
+  const part = index >= 0 ? parsed[index] : null
+
+  return (
+    <div className="flex flex-col gap-2 text-sm text-gray-400">
+      <div className="relative h-3 overflow-hidden rounded bg-fg/10" title={t('optimize.cutJoinHint')}>
+        {valid.map((r, i) => (
+          <div
+            key={i}
+            className="absolute inset-y-0 bg-accent-500/80"
+            style={{ left: `${(r.start / duration) * 100}%`, width: `${((Math.min(r.end, duration) - r.start) / duration) * 100}%` }}
+          />
+        ))}
+      </div>
+
+      {parts.map((p, i) => (
+        <div
+          key={i}
+          onClick={() => { setSelected(i) }}
+          className={`flex items-center gap-2 rounded px-1 py-0.5 ${i === index ? 'bg-fg/5' : ''}`}
+        >
+          <span className="w-14 text-xs text-gray-500">{t('optimize.cutPartLabel', { n: i + 1 })}</span>
+          <input value={p.start} onChange={(e) => { setPart(i, { start: e.target.value }) }} className={`${inputClass} w-24`} />
+          <span>-</span>
+          <input value={p.end} onChange={(e) => { setPart(i, { end: e.target.value }) }} className={`${inputClass} w-24`} />
+          {i === 0 && <span className="text-xs text-gray-500">/ {formatVideoTimeExact(duration)}</span>}
+          {previewOn && i < parts.length - 1 && parsed[i] && (
+            <button
+              type="button"
+              title={t('optimize.cutSeam')}
+              onClick={() => { playFrom(Math.max(parsed[i]!.start, parsed[i]!.end - SEAM_LEAD)) }}
+              className="rounded p-1 text-gray-400 hover:bg-fg/10"
+            >
+              <SkipForward size={14} />
+            </button>
+          )}
+          {parts.length > 1 && (
+            <button
+              type="button"
+              title={t('optimize.cutRemovePart')}
+              onClick={(e) => { e.stopPropagation(); removePart(i) }}
+              className="ml-auto rounded p-1 text-gray-400 hover:bg-fg/10"
+            >
+              <X size={14} />
+            </button>
+          )}
+        </div>
+      ))}
+
+      {part && index >= 0 && (
+        <>
+          <input
+            type="range"
+            min={0}
+            max={Math.max(1, Math.floor(duration * SLIDER_STEP))}
+            value={Math.round(part.start * SLIDER_STEP)}
+            onChange={(e) => { setPart(index, { start: formatVideoTimeExact(Number(e.target.value) / SLIDER_STEP) }) }}
+            className="w-full"
+          />
+          <input
+            type="range"
+            min={0}
+            max={Math.max(1, Math.floor(duration * SLIDER_STEP))}
+            value={Math.round(part.end * SLIDER_STEP)}
+            onChange={(e) => { setPart(index, { end: formatVideoTimeExact(Number(e.target.value) / SLIDER_STEP) }) }}
+            className="w-full"
+          />
+        </>
+      )}
+
+      <div className="flex items-center gap-3">
+        <button
+          type="button"
+          onClick={addPart}
+          className="flex items-center gap-1 rounded bg-fg/5 px-2 py-1 text-xs text-gray-300 hover:bg-fg/10"
+        >
+          <Plus size={12} />
+          {t('optimize.cutAddPart')}
+        </button>
+        {!problem && <span className="text-xs text-gray-500">{t('optimize.cutResult', { length: formatVideoTimeExact(kept), parts: valid.length })}</span>}
+        <label className="ml-auto flex items-center gap-2 text-xs text-gray-300">
+          {t('optimize.cutPreview')}
+          <Toggle on={previewOn && !!previewUrl} onClick={() => { setPreviewOn(!previewOn); setPlayError(false) }} disabled={!previewUrl} />
+        </label>
+      </div>
+
+      {problem === 'range' && <p className="text-xs text-red-400">{t('optimize.errCut')}</p>}
+      {problem === 'order' && <p className="text-xs text-red-400">{t('optimize.errCutOrder')}</p>}
+      {!previewUrl && <p className="text-xs text-gray-500">{t('optimize.cutPreviewUnsupported')}</p>}
+
+      {previewOn && previewUrl && (
+        <div className="flex flex-col gap-1">
+          <video
+            ref={video}
+            src={previewUrl}
+            controls
+            muted
+            onPlay={() => {
+              const el = video.current
+              if (el && valid.length > 0 && !valid.some((r) => el.currentTime >= r.start && el.currentTime < r.end)) {
+                el.currentTime = (valid.find((r) => r.start > el.currentTime) ?? valid[0]).start
+              }
+            }}
+            onError={() => { setPlayError(true) }}
+            className="w-full rounded bg-black"
+          />
+          {playError && <p className="text-xs text-red-400">{t('optimize.cutPreviewUnsupported')}</p>}
+        </div>
+      )}
+    </div>
+  )
+}

+ 4 - 3
src/renderer/src/components/common/DetailSidebar.tsx

@@ -460,9 +460,10 @@ export default function DetailSidebar({
     queryKey: ['author-info', creatorSteamId],
     queryFn: () => window.electronAPI.steam.getAuthorInfo(creatorSteamId!),
     enabled: !!creatorSteamId,
-    staleTime: Infinity,
-    retry: 3,
-    retryDelay: (attempt) => Math.min(2000 * 2 ** attempt, 15_000)
+    staleTime: (query) => (query.state.data ? Infinity : 5 * 60_000),
+    refetchInterval: (query) => (query.state.data === null ? 60_000 : false),
+    retry: 1,
+    retryDelay: 30_000
   })
 
   const { data: libraryMeta } = useQuery({

+ 4 - 18
src/renderer/src/components/common/FontNotice.tsx

@@ -1,11 +1,10 @@
-import { useState } from 'react'
-import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { useQuery } from '@tanstack/react-query'
 import { Type } from 'lucide-react'
+import { useFontAdd } from '../../hooks/useFontAdd'
 import { t } from '../../i18n'
 
 export default function FontNotice({ wallpaperPath, revision }: { wallpaperPath: string; revision?: number }) {
-  const queryClient = useQueryClient()
-  const [status, setStatus] = useState<string | null>(null)
+  const { status, add } = useFontAdd(() => t('fonts.addedNotice'))
   const { data: needs = [] } = useQuery({
     queryKey: ['lwe-fonts', wallpaperPath, revision],
     queryFn: () => window.electronAPI.lwe.listFonts(wallpaperPath),
@@ -16,19 +15,6 @@ export default function FontNotice({ wallpaperPath, revision }: { wallpaperPath:
 
   if (missing.length === 0) return null
 
-  async function handleAdd() {
-    const result = await window.electronAPI.fonts.add()
-    setStatus(
-      result.rejected.length > 0
-        ? t('fonts.rejected', { files: result.rejected.join(', ') })
-        : result.added.length > 0
-          ? t('fonts.addedNotice')
-          : null
-    )
-    await queryClient.invalidateQueries({ queryKey: ['user-fonts'] })
-    await queryClient.invalidateQueries({ queryKey: ['lwe-fonts'] })
-  }
-
   return (
     <div className="border-t border-fg/5 pt-3">
       <div className="mb-1.5 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-yellow-500/80">
@@ -47,7 +33,7 @@ export default function FontNotice({ wallpaperPath, revision }: { wallpaperPath:
         ))}
       </ul>
       <button
-        onClick={() => void handleAdd()}
+        onClick={() => void add()}
         className="mt-2 flex items-center gap-1.5 rounded bg-fg/10 px-2 py-1 text-xs text-gray-300 hover:bg-fg/15"
       >
         <Type size={11} />

+ 548 - 0
src/renderer/src/components/common/OptimizeVideoModal.tsx

@@ -0,0 +1,548 @@
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { useQueryClient } from '@tanstack/react-query'
+import { Loader2, X } from 'lucide-react'
+import {
+  ENCODER_LABELS,
+  SCALE_TARGETS,
+  isHevc,
+  targetSize,
+  CRF_DEFAULT,
+  CRF_MAX,
+  CRF_MIN,
+  FPS_TARGETS,
+  clampCrf,
+  fpsFilter,
+  normalizeFps,
+  FPS_MAX,
+  type HevcEncoder,
+  type OptimizeOptions,
+  type OptimizeProgress,
+  type OptimizeResult,
+  type ScaleMode,
+  type TrimMode,
+  type VideoProbe,
+  type VideoToolsStatus
+} from '@shared/video-tools'
+import { formatVideoTimeExact } from '@shared/videoTrim'
+import CutRangesEditor, { cutProblem, parseParts, partsFromRanges, type CutPartText } from './CutRangesEditor'
+import Toggle from './Toggle'
+import { useToast } from './Toast'
+import { formatFileSize } from '../../utils/format'
+import { inputClass } from './inputClass'
+import { ProgressBar } from './GridCard'
+import { detachOptimize } from '../../hooks/useBackgroundOptimize'
+import { t } from '../../i18n'
+
+export const OPTIMIZE_VIDEO_EVENT = 'we:optimize-video'
+
+export function openOptimizeVideo(id: string): void {
+  window.dispatchEvent(new CustomEvent(OPTIMIZE_VIDEO_EVENT, { detail: id }))
+}
+
+const PRESETS = Object.values(SCALE_TARGETS).map((p) => ({ name: p.label, width: p.width, height: p.height }))
+
+type Phase = 'loading' | 'ready' | 'running' | 'review' | 'error' | 'background'
+
+export function OptimizeVideoHost() {
+  const [id, setId] = useState<string | null>(null)
+  useEffect(() => {
+    const open = (e: Event): void => { setId((e as CustomEvent<string>).detail) }
+    window.addEventListener(OPTIMIZE_VIDEO_EVENT, open)
+    return () => { window.removeEventListener(OPTIMIZE_VIDEO_EVENT, open) }
+  }, [])
+  return id ? <OptimizeVideoModal key={id} id={id} onClose={() => { setId(null) }} /> : null
+}
+
+function Row({ label, hint, on, onToggle, disabled, children }: {
+  label: string
+  hint?: string
+  on: boolean
+  onToggle?: () => void
+  disabled?: boolean
+  children?: React.ReactNode
+}) {
+  return (
+    <div className="rounded-lg bg-fg/5 p-3">
+      <div className="flex items-center gap-3">
+        <Toggle on={on} onClick={() => { onToggle?.() }} disabled={disabled || !onToggle} />
+        <span className="text-sm text-gray-200">{label}</span>
+      </div>
+      {hint && <p className="mt-1 pl-12 text-xs text-gray-500">{hint}</p>}
+      {on && children && <div className="mt-3 space-y-2 pl-12">{children}</div>}
+    </div>
+  )
+}
+
+function OptimizeVideoModal({ id, onClose }: { id: string; onClose: () => void }) {
+  const queryClient = useQueryClient()
+  const { showToast } = useToast()
+  const [phase, setPhase] = useState<Phase>('loading')
+  const [error, setError] = useState('')
+  const [probe, setProbe] = useState<VideoProbe | null>(null)
+  const [trimMode, setTrimMode] = useState<TrimMode>('ask')
+  const [status, setStatus] = useState<VideoToolsStatus | null>(null)
+  const [progress, setProgress] = useState<OptimizeProgress | null>(null)
+  const [result, setResult] = useState<OptimizeResult | null>(null)
+  const [encoder, setEncoder] = useState<HevcEncoder | 'auto'>('auto')
+  const [crf, setCrf] = useState(CRF_DEFAULT)
+  const [force, setForce] = useState(false)
+  const [convert, setConvert] = useState(true)
+  const [scaleOn, setScaleOn] = useState(false)
+  const [target, setTarget] = useState('')
+  const [customW, setCustomW] = useState('1920')
+  const [customH, setCustomH] = useState('1080')
+  const [mode, setMode] = useState<ScaleMode>('fit')
+  const [fpsOn, setFpsOn] = useState(false)
+  const [fpsPick, setFpsPick] = useState('30')
+  const [fpsText, setFpsText] = useState('30')
+  const [cutOn, setCutOn] = useState(false)
+  const [cutParts, setCutParts] = useState<CutPartText[]>([{ start: '0:00', end: '' }])
+  const [fastCut, setFastCut] = useState(false)
+  const [downloading, setDownloading] = useState(false)
+  const [finishing, setFinishing] = useState(false)
+  const phaseRef = useRef<Phase>('loading')
+  const jobRef = useRef<Promise<OptimizeResult> | null>(null)
+  phaseRef.current = phase
+
+  async function load() {
+    setPhase('loading')
+    setError('')
+    try {
+      const [st, defaults, pr] = await Promise.all([
+        window.electronAPI.videoTools.status().then((value) => {
+          setStatus(value)
+          return value
+        }),
+        window.electronAPI.videoTools.getSettings(),
+        window.electronAPI.videoTools.probe(id)
+      ])
+      setEncoder(defaults.encoder !== 'auto' && !st.encoders.some((o) => o.encoder === defaults.encoder) ? 'auto' : defaults.encoder)
+      setCrf(defaults.crf)
+      setProbe(pr)
+      setTrimMode(defaults.trimMode)
+      const preset = defaults.scaleTo === 'none' ? null : SCALE_TARGETS[defaults.scaleTo]
+      setMode(defaults.scaleMode)
+      if (preset && targetSize(pr.info, preset, defaults.scaleMode)) {
+        setScaleOn(true)
+        setTarget(`preset:${preset.label}`)
+      }
+      if (defaults.maxFps && fpsFilter(pr.info, defaults.maxFps)) {
+        setFpsOn(true)
+        setFpsText(String(defaults.maxFps))
+        setFpsPick(FPS_TARGETS.includes(defaults.maxFps) ? String(defaults.maxFps) : 'custom')
+      }
+      if (pr.trim.length > 0 && defaults.trimMode !== 'never') {
+        setCutParts(partsFromRanges(pr.trim))
+        setCutOn(defaults.trimMode === 'auto')
+      } else {
+        setCutParts([{ start: '0:00', end: formatVideoTimeExact(pr.info.duration) }])
+      }
+      setConvert(!isHevc(pr.info.codec))
+      setPhase('ready')
+    } catch (err) {
+      setError((err as Error).message)
+      setPhase('error')
+    }
+  }
+
+  useEffect(() => {
+    void load()
+    const off = window.electronAPI.on.videoToolsProgress((p) => {
+      if (p.itemId === id || p.itemId === 'ffmpeg') setProgress(p)
+    })
+    return () => {
+      off()
+      // a result nobody decided on would keep the next job from starting
+      if (phaseRef.current === 'running') {
+        void window.electronAPI.videoTools.cancel().then(() => window.electronAPI.videoTools.finish(id, false)).catch(() => undefined)
+      }
+      if (phaseRef.current === 'review' || phaseRef.current === 'error') void window.electronAPI.videoTools.finish(id, false)
+    }
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [id])
+
+  const info = probe?.info
+  const hevc = info ? isHevc(info.codec) : false
+
+  const choices = useMemo(() => {
+    if (!probe) return []
+    const list = [
+      ...probe.screens.map((s) => ({ key: `screen:${s.width}x${s.height}`, label: `${s.name} (${t('optimize.dimensions', { width: s.width, height: s.height })})`, width: s.width, height: s.height })),
+      ...PRESETS.map((p) => ({ key: `preset:${p.name}`, label: `${p.name} (${t('optimize.dimensions', { width: p.width, height: p.height })})`, width: p.width, height: p.height }))
+    ]
+    return list.filter((c) => targetSize(probe.info, c, mode))
+  }, [probe, mode])
+
+  const picked = target === 'custom' ? 'custom' : (choices.find((c) => c.key === target) ?? choices[0])?.key ?? 'custom'
+
+  const box = useMemo(() => {
+    if (picked === 'custom') return { width: Number(customW), height: Number(customH) }
+    const hit = choices.find((c) => c.key === picked)
+    return hit ? { width: hit.width, height: hit.height } : null
+  }, [picked, choices, customW, customH])
+
+  const outSize = info && box ? targetSize(info, box, mode) : null
+  const cutValid = !!info && cutProblem(cutParts, info.duration) === null
+  const cutCount = cutParts.length
+  const fpsChoices = info ? FPS_TARGETS.filter((n) => fpsFilter(info, n)) : []
+  const fpsCanLower = !!info && !!fpsFilter(info, 1)
+  const fpsShown = fpsPick === 'custom' || fpsChoices.includes(Number(fpsPick)) ? fpsPick : fpsChoices.length > 0 ? String(fpsChoices[0]) : 'custom'
+  const fpsValue = fpsShown === 'custom' ? normalizeFps(Number(fpsText)) : Number(fpsShown)
+  const fpsValid = !!info && !!fpsFilter(info, fpsValue)
+  const fpsActive = fpsOn && fpsCanLower && fpsValid
+  const fastCutAllowed = cutOn && cutCount === 1 && !scaleOn && !fpsActive && !(hevc && force)
+  const copying = fastCut && fastCutAllowed
+  const reencode = !hevc && (convert || scaleOn || fpsActive || (cutOn && !copying))
+  const needsEncoder = scaleOn || fpsActive || reencode || (hevc && (force || (cutOn && !copying)))
+  const noEncoder = !!status && status.encoders.length === 0
+  const nothingToDo = !scaleOn && !fpsActive && !cutOn && (hevc ? !force : !convert)
+  const canStart =
+    phase === 'ready' && !nothingToDo && !(fpsOn && fpsCanLower && !fpsValid) && (!scaleOn || !!outSize) && (!cutOn || cutValid) && !(needsEncoder && noEncoder)
+
+  async function runJob() {
+    if (!info) return
+    const options: OptimizeOptions = { encoder, crf, force: hevc && force }
+    if (scaleOn && box) options.scale = { ...box, mode }
+    if (fpsActive) options.fps = fpsValue
+    if (cutOn && cutValid) {
+      const ranges = parseParts(cutParts).map((r) => ({ start: r!.start, end: Math.min(r!.end, info.duration) }))
+      const [first, ...more] = ranges
+      options.cut = { ...first, copy: fastCut && fastCutAllowed, ...(more.length > 0 ? { more } : {}) }
+    }
+    setProgress(null)
+    setError('')
+    setPhase('running')
+    const job = window.electronAPI.videoTools.start(id, options)
+    jobRef.current = job
+    try {
+      const res = await job
+      if (phaseRef.current === 'background') return
+      setResult(res)
+      setPhase('review')
+    } catch (err) {
+      if (phaseRef.current === 'background') return
+      setError((err as Error).message)
+      setPhase('ready')
+    }
+  }
+
+  function toBackground() {
+    if (!jobRef.current) return
+    phaseRef.current = 'background'
+    detachOptimize(id, jobRef.current)
+    onClose()
+  }
+
+  async function finish(keep: boolean) {
+    if (finishing) return
+    setFinishing(true)
+    try {
+      await window.electronAPI.videoTools.finish(id, keep)
+      if (keep) {
+        showToast(t('optimize.applied'))
+        void queryClient.invalidateQueries({ queryKey: ['library'] })
+      }
+      phaseRef.current = 'ready'
+      setPhase('ready')
+      onClose()
+    } catch (err) {
+      setError((err as Error).message)
+    } finally {
+      setFinishing(false)
+    }
+  }
+
+  async function download() {
+    setDownloading(true)
+    setProgress(null)
+    try {
+      await window.electronAPI.videoTools.download()
+      await load()
+    } catch (err) {
+      setError((err as Error).message)
+    } finally {
+      setDownloading(false)
+    }
+  }
+
+  function close() {
+    if (phase === 'running' && jobRef.current) toBackground()
+    else onClose()
+  }
+
+  const grew = !!result && result.newSize >= result.originalSize
+  const delta = result ? Math.abs(result.newSize - result.originalSize) : 0
+  const percent = result && result.originalSize > 0 ? Math.round((delta / result.originalSize) * 100) : 0
+
+  return (
+    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-8">
+      <div className="flex max-h-full w-full max-w-xl flex-col rounded-xl border border-fg/10 bg-popup shadow-2xl">
+        <div className="flex items-center justify-between border-b border-fg/5 px-4 py-3">
+          <h3 className="text-sm font-semibold text-gray-100">{t('optimize.title')}</h3>
+          <button onClick={close} className="rounded p-1 text-gray-500 hover:bg-fg/5 hover:text-gray-300">
+            <X size={16} />
+          </button>
+        </div>
+
+        <div className="space-y-3 overflow-y-auto px-4 py-3">
+          {phase === 'loading' && (
+            <div className="flex items-center gap-2 py-6 text-sm text-gray-400">
+              <Loader2 size={14} className="animate-spin" /> {t('optimize.checking')}
+            </div>
+          )}
+
+          {info && (
+            <p className="text-xs text-gray-400">
+              {info.codec.toUpperCase()} · {t('optimize.dimensions', { width: info.width, height: info.height })} · {t('optimize.fpsValue', { fps: Math.round(info.fps) })} · {formatVideoTimeExact(info.duration)} · {formatFileSize(info.size)}
+            </p>
+          )}
+
+          {status && status.wrong.length > 0 && phase !== 'running' && !downloading && (
+            <div className="rounded-lg bg-amber-500/10 p-3 text-xs text-amber-300">
+              {status.wrong.map((w) => (
+                <p key={`${w.source}-${w.encoder}`}>
+                  {t('optimize.wrongEncoder', {
+                    encoder: ENCODER_LABELS[w.encoder],
+                    source: t(w.source === 'system' ? 'optimize.srcSystem' : 'optimize.srcDownloaded')
+                  })}
+                </p>
+              ))}
+              <p className="mt-1 text-amber-300/80">{t('optimize.wrongEncoderHint')}</p>
+              {status.canDownload && !status.downloaded && status.wrong.some((w) => w.source === 'system') && (
+                <button
+                  onClick={() => void download()}
+                  className="mt-2 rounded-lg bg-accent-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-500"
+                >
+                  {t('optimize.tryDownloaded')}
+                </button>
+              )}
+            </div>
+          )}
+
+          {(noEncoder || phase === 'error') && !downloading && (
+            <div className="rounded-lg bg-amber-500/10 p-3 text-xs text-amber-300">
+              <p>{phase === 'error' ? error : t('optimize.noEncoder')}</p>
+              {status?.canDownload && !status.downloaded && (
+                <button
+                  onClick={() => void download()}
+                  className="mt-2 rounded-lg bg-accent-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-500"
+                >
+                  {t('optimize.download')}
+                </button>
+              )}
+            </div>
+          )}
+
+          {downloading && (
+            <div className="space-y-1">
+              <p className="text-xs text-gray-400">{progress?.message ?? t('optimize.checking')}</p>
+              <ProgressBar percentage={progress?.percentage ?? 0} className="h-1.5 rounded bg-fg/10" />
+            </div>
+          )}
+
+          {phase === 'ready' && info && (
+            <>
+              {error && <p className="text-xs text-red-400">{error}</p>}
+
+              {hevc && (
+                <Row
+                  label={t('optimize.force')}
+                  hint={t('optimize.forceHint')}
+                  on={force}
+                  onToggle={() => { setForce(!force); if (!force) setFastCut(false) }}
+                >
+                  <p className="text-xs text-amber-300">{t('optimize.forceWarn')}</p>
+                </Row>
+              )}
+
+              {!hevc && (
+                <Row
+                  label={t('optimize.convert')}
+                  hint={t('optimize.convertHint')}
+                  on={reencode}
+                  onToggle={scaleOn || fpsActive || (cutOn && !copying) ? undefined : () => { setConvert(!convert); if (!convert) setFastCut(false) }}
+                />
+              )}
+
+              <Row
+                label={t('optimize.downscale')}
+                hint={choices.length === 0 && picked !== 'custom' ? t('optimize.nothingSmaller') : t('optimize.downscaleHint')}
+                on={scaleOn}
+                onToggle={() => { setScaleOn(!scaleOn); if (!scaleOn) setFastCut(false) }}
+              >
+                <div className="flex flex-wrap items-center gap-2">
+                  <select value={picked} onChange={(e) => { setTarget(e.target.value) }} className={inputClass}>
+                    {choices.map((c) => <option key={c.key} value={c.key}>{c.label}</option>)}
+                    <option value="custom">{t('optimize.custom')}</option>
+                  </select>
+                  {picked === 'custom' && (
+                    <span className="flex items-center gap-1 text-sm text-gray-400">
+                      <input value={customW} onChange={(e) => { setCustomW(e.target.value.replace(/\D/g, '')) }} className={`${inputClass} w-20`} />
+                      x
+                      <input value={customH} onChange={(e) => { setCustomH(e.target.value.replace(/\D/g, '')) }} className={`${inputClass} w-20`} />
+                    </span>
+                  )}
+                </div>
+                <div className="flex gap-4 text-xs text-gray-300">
+                  <label className="flex items-center gap-1.5">
+                    <input type="radio" checked={mode === 'fit'} onChange={() => { setMode('fit') }} />
+                    {t('optimize.fit')}
+                  </label>
+                  <label className="flex items-center gap-1.5">
+                    <input type="radio" checked={mode === 'fill'} onChange={() => { setMode('fill') }} />
+                    {t('optimize.fill')}
+                  </label>
+                </div>
+                <p className="text-xs text-gray-500">
+                  {outSize ? t('optimize.resultSize', { width: outSize.width, height: outSize.height }) : t('optimize.nothingSmaller')}
+                </p>
+              </Row>
+
+              <Row
+                label={t('optimize.fps')}
+                hint={fpsCanLower ? t('optimize.fpsHint') : t('optimize.fpsNothing', { fps: Math.round(info.fps) })}
+                on={fpsOn && fpsCanLower}
+                onToggle={fpsCanLower ? () => { setFpsOn(!fpsOn); if (!fpsOn) setFastCut(false) } : undefined}
+              >
+                <div className="flex flex-wrap items-center gap-2 text-sm text-gray-400">
+                  <select value={fpsShown} onChange={(e) => { setFpsPick(e.target.value) }} className={inputClass}>
+                    {fpsChoices.map((n) => <option key={n} value={n}>{t('optimize.fpsValue', { fps: n })}</option>)}
+                    <option value="custom">{t('optimize.custom')}</option>
+                  </select>
+                  {fpsShown === 'custom' && (
+                    <span className="flex items-center gap-1">
+                      <input value={fpsText} onChange={(e) => { setFpsText(e.target.value.replace(/\D/g, '').slice(0, 3)) }} className={`${inputClass} w-16`} />
+                      {t('optimize.fpsUnit')}
+                    </span>
+                  )}
+                </div>
+                {fpsShown === 'custom' && !fpsValid && (
+                  <p className="text-xs text-red-400">{t('optimize.errFpsValue', { fps: Math.round(info.fps), max: FPS_MAX })}</p>
+                )}
+              </Row>
+
+              <Row
+                label={t('optimize.cut')}
+                hint={
+                  probe && probe.trim.length > 0 && trimMode !== 'never'
+                    ? probe.trim.length === 1
+                      ? t('optimize.cutTrimHint', { start: formatVideoTimeExact(probe.trim[0].start), end: formatVideoTimeExact(probe.trim[0].end) })
+                      : t('optimize.cutTrimPartsHint', { parts: probe.trim.length })
+                    : t('optimize.cutHint')
+                }
+                on={cutOn}
+                onToggle={() => { setCutOn(!cutOn) }}
+              >
+                <CutRangesEditor parts={cutParts} duration={info.duration} previewUrl={probe?.previewUrl ?? null} onChange={setCutParts} />
+                {fastCutAllowed && (
+                  <label className="flex items-center gap-1.5 text-xs text-gray-300">
+                    <input type="checkbox" checked={fastCut} onChange={() => { setFastCut(!fastCut); setConvert(fastCut) }} />
+                    {t('optimize.fastCut')}
+                  </label>
+                )}
+                {cutOn && cutCount > 1 && <p className="text-xs text-gray-500">{t('optimize.fastCutSingle')}</p>}
+              </Row>
+
+              {needsEncoder && status && status.encoders.length > 0 && (
+                <div className="flex items-center gap-2 text-sm text-gray-300">
+                  <span>{t('optimize.encoder')}</span>
+                  <select value={encoder} onChange={(e) => { setEncoder(e.target.value as HevcEncoder | 'auto') }} className={inputClass}>
+                    <option value="auto">{t('optimize.auto')}</option>
+                    {status.encoders.map((o) => <option key={o.encoder} value={o.encoder}>{ENCODER_LABELS[o.encoder]}</option>)}
+                  </select>
+                </div>
+              )}
+
+              {needsEncoder && status && status.encoders.length > 0 && (
+                <div className="flex items-center gap-2 text-sm text-gray-300">
+                  <span>{t('optimize.quality')}</span>
+                  <input type="range" min={CRF_MIN} max={CRF_MAX} step={1} value={crf} onChange={(e) => { setCrf(clampCrf(Number(e.target.value))) }} className="w-40" />
+                  <span className="w-6 text-right tabular-nums">{crf}</span>
+                </div>
+              )}
+              {needsEncoder && status && status.encoders.length > 0 && (
+                <p className="text-xs text-gray-500">{t('optimize.qualityHint', { min: CRF_MIN, max: CRF_MAX })}</p>
+              )}
+            </>
+          )}
+
+          {phase === 'running' && (
+            <div className="space-y-2 py-4">
+              <p className="flex items-center gap-2 text-sm text-gray-300">
+                <Loader2 size={14} className="animate-spin" /> {t('optimize.encoding', { percent: progress?.percentage ?? 0 })}
+              </p>
+              <ProgressBar percentage={progress?.percentage ?? 0} className="h-1.5 rounded bg-fg/10" />
+            </div>
+          )}
+
+          {phase === 'review' && result && (
+            <div className="space-y-2 py-2">
+              <p className="text-sm text-gray-200">
+                {formatFileSize(result.originalSize)} {'->'} {formatFileSize(result.newSize)}
+              </p>
+              {error && <p className="text-xs text-red-400">{error}</p>}
+              {result.skipped.length > 0 && (
+                <p className="text-xs text-amber-300">
+                  {t('optimize.skipped', {
+                    skipped: result.skipped.map((e) => ENCODER_LABELS[e]).join(', '),
+                    used: result.encoder ? ENCODER_LABELS[result.encoder] : ''
+                  })}
+                </p>
+              )}
+              <p className={`text-xs ${grew ? 'text-red-300' : 'text-green-300'}`}>
+                {grew ? t('optimize.bigger', { size: formatFileSize(delta) ?? '', percent }) : t('optimize.smaller', { size: formatFileSize(delta) ?? '', percent })}
+              </p>
+            </div>
+          )}
+        </div>
+
+        <div className="flex justify-end gap-2 border-t border-fg/5 px-4 py-3">
+          {phase === 'running' && (
+            <button onClick={toBackground} className="rounded-lg bg-fg/5 px-4 py-2 text-sm text-gray-300 hover:bg-fg/10">
+              {t('optimize.background')}
+            </button>
+          )}
+          {phase === 'running' && (
+            <button onClick={() => void window.electronAPI.videoTools.cancel()} className="rounded-lg bg-fg/5 px-4 py-2 text-sm text-gray-300 hover:bg-fg/10">
+              {t('common.cancel')}
+            </button>
+          )}
+          {phase === 'review' && (
+            <>
+              <button
+                onClick={() => void finish(false)}
+                disabled={finishing}
+                className={grew ? 'rounded-lg bg-accent-600 px-4 py-2 text-sm font-medium text-white hover:bg-accent-500' : 'rounded-lg bg-fg/5 px-4 py-2 text-sm text-gray-300 hover:bg-fg/10'}
+              >
+                {t('optimize.discard')}
+              </button>
+              <button
+                onClick={() => void finish(true)}
+                disabled={finishing}
+                className={grew ? 'rounded-lg bg-fg/5 px-4 py-2 text-sm text-gray-300 hover:bg-fg/10' : 'rounded-lg bg-accent-600 px-4 py-2 text-sm font-medium text-white hover:bg-accent-500'}
+              >
+                {grew ? t('optimize.keepAnyway') : t('optimize.keep')}
+              </button>
+            </>
+          )}
+          {(phase === 'ready' || phase === 'error' || phase === 'loading') && (
+            <>
+              <button onClick={close} className="rounded-lg bg-fg/5 px-4 py-2 text-sm text-gray-300 hover:bg-fg/10">
+                {t('common.close')}
+              </button>
+              {phase === 'ready' && (
+                <button
+                  onClick={() => void runJob()}
+                  disabled={!canStart}
+                  className="rounded-lg bg-accent-600 px-4 py-2 text-sm font-medium text-white hover:bg-accent-500 disabled:opacity-50"
+                >
+                  {t('optimize.start')}
+                </button>
+              )}
+            </>
+          )}
+        </div>
+      </div>
+    </div>
+  )
+}

+ 75 - 0
src/renderer/src/components/common/QuickOptimizeNotice.tsx

@@ -0,0 +1,75 @@
+import { Film, Loader2, X } from 'lucide-react'
+import { formatVideoTime } from '@shared/videoTrim'
+import { answerQuickTrim, dismissQuickOptimize, useQuickOptimize } from '../../hooks/useQuickOptimize'
+import { t } from '../../i18n'
+
+export default function QuickOptimizeNotice() {
+  const { running, progress, percent, lines, summary, error, question } = useQuickOptimize()
+  if (question) {
+    return (
+      <div className="flex flex-col gap-2 border-b border-fg/10 bg-pane px-4 py-2 text-sm">
+        <span className="font-medium text-gray-200">{t('quick.trimTitle')}</span>
+        <span className="text-gray-400">{t('quick.trimText')}</span>
+        <ul className="max-h-32 overflow-y-auto text-xs text-gray-300">
+          {question.map((item) => (
+            <li key={item.id}>{`${item.title}: ${formatVideoTime(item.start)} - ${formatVideoTime(item.end)}`}</li>
+          ))}
+        </ul>
+        <div className="flex gap-2">
+          <button onClick={() => { answerQuickTrim('trim') }} className="rounded-lg bg-accent-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-500">
+            {t('quick.trimYes')}
+          </button>
+          <button onClick={() => { answerQuickTrim('keep') }} className="rounded-lg bg-fg/5 px-3 py-1.5 text-xs text-gray-300 hover:bg-fg/10">
+            {t('quick.trimNo')}
+          </button>
+          <button onClick={() => { answerQuickTrim('cancel') }} className="rounded-lg bg-fg/5 px-3 py-1.5 text-xs text-gray-300 hover:bg-fg/10">
+            {t('common.cancel')}
+          </button>
+        </div>
+      </div>
+    )
+  }
+  if (!running && lines.length === 0 && !summary && !error) return null
+
+  return (
+    <div className="flex flex-col gap-1 border-b border-fg/10 bg-pane px-4 py-2 text-sm">
+      <div className="flex items-start gap-3">
+        <div className="flex flex-1 flex-col gap-1">
+          {running && (
+            <span className="flex items-center gap-2 text-gray-300">
+              <Loader2 size={14} className="shrink-0 animate-spin text-accent-400" />
+              {progress
+                ? t('quick.running', { done: progress.done + 1, total: progress.total, title: progress.title, percent })
+                : t('quick.action')}
+            </span>
+          )}
+          {lines.map((line) => (
+            <span key={`${line.id}-${line.kind}`} className={line.kind === 'failed' ? 'text-red-400' : 'text-amber-300'}>
+              {line.text}
+            </span>
+          ))}
+          {error && <span className="text-red-400">{error}</span>}
+          {summary && (
+            <span className="flex items-center gap-2 text-green-300">
+              <Film size={14} className="shrink-0" />
+              {summary}
+            </span>
+          )}
+        </div>
+        {running && (
+          <button
+            onClick={() => void window.electronAPI.videoTools.cancel()}
+            className="rounded-lg bg-fg/5 px-3 py-1 text-xs text-gray-300 hover:bg-fg/10"
+          >
+            {t('common.cancel')}
+          </button>
+        )}
+        {!running && (
+          <button onClick={dismissQuickOptimize} className="rounded p-1 text-gray-500 hover:bg-fg/5 hover:text-gray-300">
+            <X size={14} />
+          </button>
+        )}
+      </div>
+    </div>
+  )
+}

+ 32 - 15
src/renderer/src/components/common/WallpaperContextMenu.tsx

@@ -6,12 +6,14 @@ import {
   ExternalLink,
   Eye,
   FolderOpen,
+  Film,
   HardDrive,
   Monitor,
   MoveRight,
   ShieldCheck,
   Trash2,
-  User
+  User,
+  Zap
 } from 'lucide-react'
 import type { ExtraLibrary, WallpaperMeta } from '@shared/types'
 import {
@@ -24,6 +26,8 @@ import {
   VoteMenuItems,
   FavoriteMenuItems
 } from './ContextMenu'
+import { openOptimizeVideo } from './OptimizeVideoModal'
+import { runQuickOptimize, useQuickOptimizeRunning } from '../../hooks/useQuickOptimize'
 import { useToast } from './Toast'
 import { useConfig, useFolders } from '../../hooks/queries'
 import { useDisplayTargets } from '../../hooks/useDisplayTargets'
@@ -35,6 +39,7 @@ import {
   backupSummary,
   canBrowseCreator,
   hasBackup,
+  isOptimizableVideo,
   isPlayable,
   resolveCreatorSteamId,
   transferSummary,
@@ -75,6 +80,10 @@ export default function WallpaperContextMenu({
   const backupable = wallpapers.filter((w) => w.source === 'workshop')
   const transferable = wallpapers.filter(isPlayable)
   const backups = wallpapers.filter(hasBackup)
+  // Steam puts workshop folders back when it validates them, only copies outside it can be changed
+  const optimizable = wallpapers.length === 1 && isOptimizableVideo(wallpapers[0]) && isPlayable(wallpapers[0]) ? wallpapers[0] : undefined
+  const quickable = wallpapers.filter(isOptimizableVideo)
+  const quickRunning = useQuickOptimizeRunning()
   const video = wallpapers.map(videoPath).find(Boolean)
   const splittable = wallpapers.filter((w) => isPlayable(w) && ['scene', 'video', 'web'].includes(w.type))
   const creatorSource = wallpapers.length === 1 && canBrowseCreator(wallpapers[0]) ? wallpapers[0] : undefined
@@ -182,6 +191,19 @@ export default function WallpaperContextMenu({
           {t('backup.delete')}
         </MenuItem>
       )}
+      {optimizable && !quickRunning && (
+        <MenuItem icon={Film} onClick={run(() => { openOptimizeVideo(optimizable.id) })}>
+          {t('optimize.action')}
+        </MenuItem>
+      )}
+      {quickable.length > 0 && !quickRunning && (
+        <MenuItem
+          icon={Zap}
+          onClick={run(() => runQuickOptimize(quickable.map((w) => w.id), () => { void queryClient.invalidateQueries({ queryKey: ['library'] }) }))}
+        >
+          {t('quick.action')}
+        </MenuItem>
+      )}
       {backupable.length > 0 && (
         <MenuItem icon={ShieldCheck} onClick={run(async () => { showToast(await verifyFiles(backupable.map((w) => w.id), () => {})); })}>
           {t('verify.action')}
@@ -231,20 +253,15 @@ export default function WallpaperContextMenu({
       {libraries.length > 0 && transferable.length > 0 && (
         <>
           <MenuSeparator />
-          <SubMenu icon={Copy} label={t('transfer.copyTo')}>
-            {libraries.map((l) => (
-              <MenuItem key={l.path} icon={HardDrive} onClick={run(() => transfer(l, 'copy'))}>
-                <span title={l.path}>{l.name}</span>
-              </MenuItem>
-            ))}
-          </SubMenu>
-          <SubMenu icon={MoveRight} label={t('transfer.moveTo')}>
-            {libraries.map((l) => (
-              <MenuItem key={l.path} icon={HardDrive} onClick={run(() => transfer(l, 'move'))}>
-                <span title={l.path}>{l.name}</span>
-              </MenuItem>
-            ))}
-          </SubMenu>
+          {([['copy', Copy, 'transfer.copyTo'], ['move', MoveRight, 'transfer.moveTo']] as const).map(([action, icon, label]) => (
+            <SubMenu key={action} icon={icon} label={t(label)}>
+              {libraries.map((l) => (
+                <MenuItem key={l.path} icon={HardDrive} onClick={run(() => transfer(l, action))}>
+                  <span title={l.path}>{l.name}</span>
+                </MenuItem>
+              ))}
+            </SubMenu>
+          ))}
         </>
       )}
 

+ 2 - 0
src/renderer/src/components/common/inputClass.ts

@@ -0,0 +1,2 @@
+export const inputClass =
+  'rounded-lg bg-fg/5 px-2 py-1.5 text-sm text-gray-200 outline-none focus:ring-1 focus:ring-accent-500'

+ 29 - 0
src/renderer/src/components/common/sidebar/CommitRange.tsx

@@ -0,0 +1,29 @@
+interface Props {
+  min: number
+  max: number
+  step?: number
+  value: number
+  disabled: boolean
+  title?: string
+  onSlide: (value: number) => void
+  onCommit: () => void
+}
+
+export default function CommitRange({ min, max, step, value, disabled, title, onSlide, onCommit }: Props) {
+  return (
+    <input
+      type="range"
+      min={min}
+      max={max}
+      step={step}
+      value={value}
+      disabled={disabled}
+      title={title}
+      onChange={(e) => { onSlide(Number(e.target.value)) }}
+      onMouseUp={onCommit}
+      onTouchEnd={onCommit}
+      onKeyUp={onCommit}
+      className="w-full accent-accent-500 disabled:opacity-50"
+    />
+  )
+}

+ 55 - 67
src/renderer/src/components/common/sidebar/CompatSection.tsx

@@ -1,11 +1,12 @@
 import { useState } from 'react'
-import { Bug, ChevronDown, ChevronRight, FlaskConical, Loader2, Undo2 } from 'lucide-react'
+import { Bug, FlaskConical, Loader2, Undo2 } from 'lucide-react'
 import type { WallpaperCompat, WallpaperMeta } from '@shared/types'
 import { COMPAT_LABELS, compatStatus } from '@shared/compat'
 import { CompatStatusIcon } from '../CompatBadge'
 import { useToast } from '../Toast'
 import { screenLabel } from '../../../utils/screens'
 import { t, currentLanguage } from '../../../i18n'
+import SidebarSection from './SidebarSection'
 import type { MessageKey } from '@shared/i18n'
 
 interface Props {
@@ -24,7 +25,6 @@ const LAST_CRASH: Record<'launch' | 'hotswap' | 'runtime', MessageKey> = {
 export default function CompatSection({ wallpaper, canTest, onChange, onTest }: Props) {
   const compat = wallpaper.compat
   const status = compatStatus(compat)
-  const [open, setOpen] = useState(status !== 'ok')
   const [noteDraft, setNoteDraft] = useState<string | null>(null)
   const [showLog, setShowLog] = useState(false)
   const [testing, setTesting] = useState(false)
@@ -55,76 +55,64 @@ export default function CompatSection({ wallpaper, canTest, onChange, onTest }:
   }
 
   return (
-    <div className="border-t border-fg/5 pt-3">
-      <button
-        onClick={() => { setOpen((v) => !v) }}
-        className="flex w-full items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-gray-500 hover:text-gray-300"
-      >
-        {open ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
-        <Bug size={12} />
-        <span className="flex-1 text-left">{t('compat.title')}</span>
-        <CompatStatusIcon status={status} />
-      </button>
+    <SidebarSection icon={Bug} title={t('compat.title')} defaultOpen={status !== 'ok'} badge={<CompatStatusIcon status={status} />}>
+      <div className="mt-2 flex flex-col gap-2 text-xs">
+        <p className="flex items-center gap-1.5 text-gray-300">
+          <CompatStatusIcon status={status} />
+          {t(COMPAT_LABELS[status])}
+        </p>
 
-      {open && (
-        <div className="mt-2 flex flex-col gap-2 text-xs">
-          <p className="flex items-center gap-1.5 text-gray-300">
-            <CompatStatusIcon status={status} />
-            {t(COMPAT_LABELS[status])}
-          </p>
-
-          {compat?.lastCrash && (
-            <div className="text-gray-500">
-              {t(LAST_CRASH[compat.lastCrash.phase])}
-              {compat.lastCrash.screen !== '*' && ` ${t('status.onScreen', { screen: screenLabel(compat.lastCrash.screen) })}`},{' '}
-              {new Date(compat.lastCrash.at).toLocaleString(currentLanguage())}
-              {compat.runtimeCrashes ? ` ${t('compat.runtimeCount', { count: compat.runtimeCrashes })}` : ''}
-              {compat.lastCrash.log.length > 0 && (
-                <button onClick={() => { setShowLog((v) => !v) }} className="ml-1 text-accent-300 hover:text-accent-200">
-                  {showLog ? t('compat.hideLog') : t('compat.showLog')}
-                </button>
-              )}
-              {showLog && (
-                <pre className="mt-1 max-h-40 overflow-auto whitespace-pre-wrap rounded bg-black/40 p-2 text-[10px] text-gray-400">
-                  {compat.lastCrash.log.join('\n')}
-                </pre>
-              )}
-            </div>
-          )}
-
-          <textarea
-            value={note}
-            onChange={(e) => { setNoteDraft(e.target.value) }}
-            onBlur={(e) => void commitNote(e.target.value)}
-            rows={2}
-            placeholder={t('compat.notePlaceholder')}
-            className="w-full resize-y rounded border border-fg/10 bg-black/30 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600 focus:border-accent-500/50 focus:outline-none"
-          />
-
-          <div className="flex gap-1.5">
-            {canTest && (
-              <button
-                onClick={() => void test()}
-                disabled={testing}
-                title={t('compat.testHint')}
-                className="flex items-center gap-1 rounded bg-fg/5 px-2 py-1 text-gray-300 hover:bg-fg/10 disabled:opacity-50"
-              >
-                {testing ? <Loader2 size={11} className="animate-spin" /> : <FlaskConical size={11} />}
-                {t('compat.test')}
+        {compat?.lastCrash && (
+          <div className="text-gray-500">
+            {t(LAST_CRASH[compat.lastCrash.phase])}
+            {compat.lastCrash.screen !== '*' && ` ${t('status.onScreen', { screen: screenLabel(compat.lastCrash.screen) })}`},{' '}
+            {new Date(compat.lastCrash.at).toLocaleString(currentLanguage())}
+            {compat.runtimeCrashes ? ` ${t('compat.runtimeCount', { count: compat.runtimeCrashes })}` : ''}
+            {compat.lastCrash.log.length > 0 && (
+              <button onClick={() => { setShowLog((v) => !v) }} className="ml-1 text-accent-300 hover:text-accent-200">
+                {showLog ? t('compat.hideLog') : t('compat.showLog')}
               </button>
             )}
-            {status !== 'ok' && (
-              <button
-                onClick={() => void clearStatus()}
-                className="flex items-center gap-1 rounded bg-fg/5 px-2 py-1 text-gray-300 hover:bg-fg/10"
-              >
-                <Undo2 size={11} />
-                {t('compat.forget')}
-              </button>
+            {showLog && (
+              <pre className="mt-1 max-h-40 overflow-auto whitespace-pre-wrap rounded bg-black/40 p-2 text-[10px] text-gray-400">
+                {compat.lastCrash.log.join('\n')}
+              </pre>
             )}
           </div>
+        )}
+
+        <textarea
+          value={note}
+          onChange={(e) => { setNoteDraft(e.target.value) }}
+          onBlur={(e) => void commitNote(e.target.value)}
+          rows={2}
+          placeholder={t('compat.notePlaceholder')}
+          className="w-full resize-y rounded border border-fg/10 bg-black/30 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600 focus:border-accent-500/50 focus:outline-none"
+        />
+
+        <div className="flex gap-1.5">
+          {canTest && (
+            <button
+              onClick={() => void test()}
+              disabled={testing}
+              title={t('compat.testHint')}
+              className="flex items-center gap-1 rounded bg-fg/5 px-2 py-1 text-gray-300 hover:bg-fg/10 disabled:opacity-50"
+            >
+              {testing ? <Loader2 size={11} className="animate-spin" /> : <FlaskConical size={11} />}
+              {t('compat.test')}
+            </button>
+          )}
+          {status !== 'ok' && (
+            <button
+              onClick={() => void clearStatus()}
+              className="flex items-center gap-1 rounded bg-fg/5 px-2 py-1 text-gray-300 hover:bg-fg/10"
+            >
+              <Undo2 size={11} />
+              {t('compat.forget')}
+            </button>
+          )}
         </div>
-      )}
-    </div>
+      </div>
+    </SidebarSection>
   )
 }

+ 88 - 103
src/renderer/src/components/common/sidebar/EngineFlagsSection.tsx

@@ -1,10 +1,11 @@
 import { useState } from 'react'
-import { ChevronDown, ChevronRight, Gauge, Loader2, TriangleAlert } from 'lucide-react'
+import { Gauge, TriangleAlert } from 'lucide-react'
 import type { EngineFlags, FullscreenPauseMode, WallpaperMeta } from '@shared/types'
 import { hasEngineFlags } from '@shared/engineFlags'
 import { BOOLEAN_FLAGS, CHOICE_FLAGS, FULLSCREEN_PAUSE_OPTIONS, optionLabel, presetName } from '../../../constants/engineFlags'
 import { useConfig } from '../../../hooks/queries'
 import { t } from '../../../i18n'
+import SidebarSection, { CustomBadge } from './SidebarSection'
 
 interface Props {
   flags?: EngineFlags
@@ -17,7 +18,6 @@ const onOff = (value: boolean | undefined) => (value ? 'on' : 'off')
 const onOffLabel = (value: boolean | undefined) => (value ? t('common.on') : t('common.off'))
 
 export default function EngineFlagsSection({ flags = {}, onChange }: Props) {
-  const [open, setOpen] = useState(false)
   const [busy, setBusy] = useState(false)
 
   const config = useConfig()
@@ -48,122 +48,107 @@ export default function EngineFlagsSection({ flags = {}, onChange }: Props) {
   }
 
   return (
-    <div className="border-t border-fg/5 pt-3">
-      <button
-        onClick={() => { setOpen((v) => !v) }}
-        className="flex w-full items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-gray-500 hover:text-gray-300"
-      >
-        {open ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
-        <Gauge size={12} />
-        <span className="flex-1 text-left">{t('perf.title')}</span>
-        {hasEngineFlags(flags) && (
-          <span className="rounded-full bg-accent-600/30 px-1.5 normal-case text-accent-300">{t('thumb.customBadge')}</span>
-        )}
-        {busy && <Loader2 size={11} className="animate-spin" />}
-      </button>
+    <SidebarSection icon={Gauge} title={t('perf.title')} busy={busy} badge={hasEngineFlags(flags) && <CustomBadge label={t('thumb.customBadge')} />}>
+      <div className="mt-2 flex flex-col gap-2">
+        <p className="text-[11px] text-gray-600">{t('perf.overrideHint')}</p>
 
-      {open && (
-        <div className="mt-2 flex flex-col gap-2">
-          <p className="text-[11px] text-gray-600">{t('perf.overrideHint')}</p>
+        <div className="flex items-center gap-2">
+          <select
+            value=""
+            disabled={busy}
+            onChange={(e) => { applyPreset(e.target.value) }}
+            className={`${selectClass} flex-1`}
+          >
+            <option value="" disabled>
+              {t('perf.applyPreset')}
+            </option>
+            {presets.map((p) => (
+              <option key={p.id} value={p.id}>
+                {presetName(p)}
+              </option>
+            ))}
+          </select>
+          {hasEngineFlags(flags) && (
+            <button
+              onClick={() => void commit({ engineFlags: undefined })}
+              disabled={busy}
+              className="rounded bg-fg/5 px-2 py-1 text-xs text-gray-400 hover:bg-fg/10 disabled:opacity-50"
+            >
+              {t('common.reset')}
+            </button>
+          )}
+        </div>
 
-          <div className="flex items-center gap-2">
+        {BOOLEAN_FLAGS.map(({ key, label, hint }) => (
+          <label key={key} className="flex items-center justify-between gap-2 text-xs text-gray-300" title={hint && t(hint)}>
+            <span>{t(label)}</span>
             <select
-              value=""
+              value={flags[key] === undefined ? 'inherit' : onOff(flags[key])}
               disabled={busy}
-              onChange={(e) => { applyPreset(e.target.value) }}
-              className={`${selectClass} flex-1`}
+              onChange={(e) => { setFlag(key, e.target.value === 'inherit' ? undefined : e.target.value === 'on') }}
+              className={selectClass}
             >
-              <option value="" disabled>
-                {t('perf.applyPreset')}
-              </option>
-              {presets.map((p) => (
-                <option key={p.id} value={p.id}>
-                  {presetName(p)}
-                </option>
-              ))}
+              <option value="inherit">{t('common.defaultValue', { value: onOffLabel(global[key]) })}</option>
+              <option value="on">{t('common.on')}</option>
+              <option value="off">{t('common.off')}</option>
             </select>
-            {hasEngineFlags(flags) && (
-              <button
-                onClick={() => void commit({ engineFlags: undefined })}
-                disabled={busy}
-                className="rounded bg-fg/5 px-2 py-1 text-xs text-gray-400 hover:bg-fg/10 disabled:opacity-50"
-              >
-                {t('common.reset')}
-              </button>
-            )}
-          </div>
+          </label>
+        ))}
 
-          {BOOLEAN_FLAGS.map(({ key, label, hint }) => (
-            <label key={key} className="flex items-center justify-between gap-2 text-xs text-gray-300" title={hint && t(hint)}>
+        {CHOICE_FLAGS.map(({ key, label, hint, wallpaperNote, fallback, options }) => (
+          <div key={key}>
+            <label className="flex items-center justify-between gap-2 text-xs text-gray-300" title={t(hint)}>
               <span>{t(label)}</span>
               <select
-                value={flags[key] === undefined ? 'inherit' : onOff(flags[key])}
+                value={flags[key] ?? 'inherit'}
                 disabled={busy}
-                onChange={(e) => { setFlag(key, e.target.value === 'inherit' ? undefined : e.target.value === 'on') }}
+                onChange={(e) => { setFlag(key, e.target.value === 'inherit' ? undefined : (e.target.value as EngineFlags[typeof key])) }
+                }
                 className={selectClass}
               >
-                <option value="inherit">{t('common.defaultValue', { value: onOffLabel(global[key]) })}</option>
-                <option value="on">{t('common.on')}</option>
-                <option value="off">{t('common.off')}</option>
+                <option value="inherit">
+                  {t('common.defaultValue', {
+                    value: optionLabel(options.find((o) => o.value === (global[key] ?? fallback))?.label ?? '')
+                  })}
+                </option>
+                {options.map((o) => (
+                  <option key={o.value} value={o.value}>
+                    {optionLabel(o.label)}
+                  </option>
+                ))}
               </select>
             </label>
-          ))}
-
-          {CHOICE_FLAGS.map(({ key, label, hint, wallpaperNote, fallback, options }) => (
-            <div key={key}>
-              <label className="flex items-center justify-between gap-2 text-xs text-gray-300" title={t(hint)}>
-                <span>{t(label)}</span>
-                <select
-                  value={flags[key] ?? 'inherit'}
-                  disabled={busy}
-                  onChange={(e) => { setFlag(key, e.target.value === 'inherit' ? undefined : (e.target.value as EngineFlags[typeof key])) }
-                  }
-                  className={selectClass}
-                >
-                  <option value="inherit">
-                    {t('common.defaultValue', {
-                      value: optionLabel(options.find((o) => o.value === (global[key] ?? fallback))?.label ?? '')
-                    })}
-                  </option>
-                  {options.map((o) => (
-                    <option key={o.value} value={o.value}>
-                      {optionLabel(o.label)}
-                    </option>
-                  ))}
-                </select>
-              </label>
-              {wallpaperNote && flags[key] !== undefined && flags[key] !== fallback && (
-                <p className="mt-1 flex gap-1.5 text-[11px] leading-snug text-amber-300">
-                  <TriangleAlert size={12} className="mt-px shrink-0" />
-                  {t(wallpaperNote)}
-                </p>
-              )}
-            </div>
-          ))}
+            {wallpaperNote && flags[key] !== undefined && flags[key] !== fallback && (
+              <p className="mt-1 flex gap-1.5 text-[11px] leading-snug text-amber-300">
+                <TriangleAlert size={12} className="mt-px shrink-0" />
+                {t(wallpaperNote)}
+              </p>
+            )}
+          </div>
+        ))}
 
-          <label className="flex flex-col gap-1 text-xs text-gray-300">
-            <span>{t('perf.fullscreenApps')}</span>
-            <select
-              value={flags.fullscreenPause ?? 'inherit'}
-              disabled={busy}
-              onChange={(e) => { setFlag('fullscreenPause', e.target.value === 'inherit' ? undefined : (e.target.value as FullscreenPauseMode)) }
-              }
-              className={selectClass}
-            >
-              <option value="inherit">
-                {t('common.defaultValue', {
-                  value: t(FULLSCREEN_PAUSE_OPTIONS.find((o) => o.value === (global.fullscreenPause ?? 'default'))!.label)
-                })}
+        <label className="flex flex-col gap-1 text-xs text-gray-300">
+          <span>{t('perf.fullscreenApps')}</span>
+          <select
+            value={flags.fullscreenPause ?? 'inherit'}
+            disabled={busy}
+            onChange={(e) => { setFlag('fullscreenPause', e.target.value === 'inherit' ? undefined : (e.target.value as FullscreenPauseMode)) }
+            }
+            className={selectClass}
+          >
+            <option value="inherit">
+              {t('common.defaultValue', {
+                value: t(FULLSCREEN_PAUSE_OPTIONS.find((o) => o.value === (global.fullscreenPause ?? 'default'))!.label)
+              })}
+            </option>
+            {FULLSCREEN_PAUSE_OPTIONS.map((o) => (
+              <option key={o.value} value={o.value}>
+                {t(o.label)}
               </option>
-              {FULLSCREEN_PAUSE_OPTIONS.map((o) => (
-                <option key={o.value} value={o.value}>
-                  {t(o.label)}
-                </option>
-              ))}
-            </select>
-          </label>
-        </div>
-      )}
-    </div>
+            ))}
+          </select>
+        </label>
+      </div>
+    </SidebarSection>
   )
 }

+ 34 - 0
src/renderer/src/components/common/sidebar/SidebarSection.tsx

@@ -0,0 +1,34 @@
+import { useState, type ReactNode } from 'react'
+import { ChevronDown, ChevronRight, Loader2, type LucideIcon } from 'lucide-react'
+
+interface Props {
+  icon: LucideIcon
+  title: string
+  defaultOpen?: boolean
+  busy?: boolean
+  badge?: ReactNode
+  children: ReactNode
+}
+
+export function CustomBadge({ label }: { label: string }) {
+  return <span className="rounded-full bg-accent-600/30 px-1.5 normal-case text-accent-300">{label}</span>
+}
+
+export default function SidebarSection({ icon: Icon, title, defaultOpen = false, busy, badge, children }: Props) {
+  const [open, setOpen] = useState(defaultOpen)
+  return (
+    <div className="border-t border-fg/5 pt-3">
+      <button
+        onClick={() => { setOpen((v) => !v) }}
+        className="flex w-full items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-gray-500 hover:text-gray-300"
+      >
+        {open ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
+        <Icon size={12} />
+        <span className="flex-1 text-left">{title}</span>
+        {badge}
+        {busy && <Loader2 size={11} className="animate-spin" />}
+      </button>
+      {open && children}
+    </div>
+  )
+}

+ 53 - 66
src/renderer/src/components/common/sidebar/ThumbnailSection.tsx

@@ -1,9 +1,10 @@
 import { useState } from 'react'
-import { Camera, ChevronDown, ChevronRight, ImageOff, ImagePlus, Loader2 } from 'lucide-react'
+import { Camera, ImageOff, ImagePlus } from 'lucide-react'
 import clsx from 'clsx'
 import type { WallpaperMeta } from '@shared/types'
 import { useToast } from '../Toast'
 import { t } from '../../../i18n'
+import SidebarSection, { CustomBadge } from './SidebarSection'
 
 interface Props {
   wallpaper: WallpaperMeta
@@ -12,7 +13,6 @@ interface Props {
 }
 
 export default function ThumbnailSection({ wallpaper, canGenerate, onUpdated }: Props) {
-  const [open, setOpen] = useState(false)
   const [busy, setBusy] = useState<'generate' | 'pick' | 'delete' | 'toggle' | null>(null)
   const { showToast } = useToast()
   const hasCustom = !!wallpaper.customPreview
@@ -34,79 +34,66 @@ export default function ThumbnailSection({ wallpaper, canGenerate, onUpdated }:
     run('toggle', () => window.electronAPI.library.update(wallpaper.id, { useOriginalPreview: value }))
 
   return (
-    <div className="border-t border-fg/5 pt-3">
-      <button
-        onClick={() => { setOpen((v) => !v) }}
-        className="flex w-full items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-gray-500 hover:text-gray-300"
-      >
-        {open ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
-        <Camera size={12} />
-        <span className="flex-1 text-left">{t('thumb.title')}</span>
-        {usingCustom && <span className="rounded-full bg-accent-600/30 px-1.5 normal-case text-accent-300">{t('thumb.customBadge')}</span>}
-        {busy && <Loader2 size={11} className="animate-spin" />}
-      </button>
-
-      {open && (
-        <div className="mt-2 flex flex-col gap-2 text-xs">
-          {hasCustom && (
-            <div className="flex overflow-hidden rounded bg-fg/5">
-              {[
-                { label: t('thumb.custom'), original: false },
-                { label: t('thumb.original'), original: true }
-              ].map(({ label, original }) => (
-                <button
-                  key={label}
-                  onClick={() => void showOriginal(original)}
-                  disabled={busy !== null || usingCustom === !original}
-                  className={clsx(
-                    'flex-1 py-1',
-                    usingCustom === !original ? 'bg-accent-600 text-white' : 'text-gray-400 hover:bg-fg/10'
-                  )}
-                >
-                  {label}
-                </button>
-              ))}
-            </div>
-          )}
-
-          <div className="flex flex-wrap gap-1.5">
-            {canGenerate && (
+    <SidebarSection icon={Camera} title={t('thumb.title')} busy={busy !== null} badge={usingCustom && <CustomBadge label={t('thumb.customBadge')} />}>
+      <div className="mt-2 flex flex-col gap-2 text-xs">
+        {hasCustom && (
+          <div className="flex overflow-hidden rounded bg-fg/5">
+            {[
+              { label: t('thumb.custom'), original: false },
+              { label: t('thumb.original'), original: true }
+            ].map(({ label, original }) => (
               <button
-                onClick={() => void run('generate', () => window.electronAPI.wallpaper.generateThumbnail(wallpaper.id))}
-                disabled={busy !== null}
-                title={t('thumb.captureHint')}
-                className="flex items-center gap-1 rounded bg-fg/5 px-2 py-1 text-gray-300 hover:bg-fg/10 disabled:opacity-50"
+                key={label}
+                onClick={() => void showOriginal(original)}
+                disabled={busy !== null || usingCustom === !original}
+                className={clsx(
+                  'flex-1 py-1',
+                  usingCustom === !original ? 'bg-accent-600 text-white' : 'text-gray-400 hover:bg-fg/10'
+                )}
               >
-                <Camera size={11} />
-                {busy === 'generate' ? t('thumb.capturing') : t('thumb.capture')}
+                {label}
               </button>
-            )}
+            ))}
+          </div>
+        )}
+
+        <div className="flex flex-wrap gap-1.5">
+          {canGenerate && (
             <button
-              onClick={() => void run('pick', () => window.electronAPI.wallpaper.pickThumbnail(wallpaper.id))}
+              onClick={() => void run('generate', () => window.electronAPI.wallpaper.generateThumbnail(wallpaper.id))}
               disabled={busy !== null}
+              title={t('thumb.captureHint')}
               className="flex items-center gap-1 rounded bg-fg/5 px-2 py-1 text-gray-300 hover:bg-fg/10 disabled:opacity-50"
             >
-              <ImagePlus size={11} />
-              {t('thumb.choose')}
+              <Camera size={11} />
+              {busy === 'generate' ? t('thumb.capturing') : t('thumb.capture')}
+            </button>
+          )}
+          <button
+            onClick={() => void run('pick', () => window.electronAPI.wallpaper.pickThumbnail(wallpaper.id))}
+            disabled={busy !== null}
+            className="flex items-center gap-1 rounded bg-fg/5 px-2 py-1 text-gray-300 hover:bg-fg/10 disabled:opacity-50"
+          >
+            <ImagePlus size={11} />
+            {t('thumb.choose')}
+          </button>
+          {hasCustom && (
+            <button
+              onClick={() => void run('delete', () => window.electronAPI.wallpaper.deleteThumbnail(wallpaper.id))}
+              disabled={busy !== null}
+              className="flex items-center gap-1 rounded bg-fg/5 px-2 py-1 text-gray-300 hover:bg-red-500/20 hover:text-red-400 disabled:opacity-50"
+            >
+              <ImageOff size={11} />
+              {t('thumb.removeCustom')}
             </button>
-            {hasCustom && (
-              <button
-                onClick={() => void run('delete', () => window.electronAPI.wallpaper.deleteThumbnail(wallpaper.id))}
-                disabled={busy !== null}
-                className="flex items-center gap-1 rounded bg-fg/5 px-2 py-1 text-gray-300 hover:bg-red-500/20 hover:text-red-400 disabled:opacity-50"
-              >
-                <ImageOff size={11} />
-                {t('thumb.removeCustom')}
-              </button>
-            )}
-          </div>
-          {canGenerate && (
-            <p className="text-[11px] text-gray-600">
-              {t('thumb.captureNote')}
-            </p>
           )}
         </div>
-      )}
-    </div>
+        {canGenerate && (
+          <p className="text-[11px] text-gray-600">
+            {t('thumb.captureNote')}
+          </p>
+        )}
+      </div>
+    </SidebarSection>
   )
 }

+ 50 - 44
src/renderer/src/components/library/LibraryView.tsx

@@ -1,4 +1,6 @@
 import { useState, useEffect, useMemo, useRef } from 'react'
+import { runQuickOptimize, useQuickOptimizeRunning } from '../../hooks/useQuickOptimize'
+import { useLibraryTasks, runLibraryTask, type LibraryTask, setLibraryTaskStatus, clearFinishedLibraryTaskStatus } from '../../hooks/useLibraryTasks'
 import { useQuery, useQueryClient } from '@tanstack/react-query'
 import {
   Loader2,
@@ -11,10 +13,12 @@ import {
   Trash2,
   Eraser,
   Archive,
+  Zap,
   WifiOff,
   ShieldAlert,
   ShieldCheck,
-  ChevronLeft
+  ChevronLeft,
+  X
 } from 'lucide-react'
 import WallpaperCard from './WallpaperCard'
 import ResizableWidth from '../common/ResizableWidth'
@@ -54,7 +58,7 @@ import { useApplyWallpaper, useSubscribe, useUnsubscribe, useVerifyFiles } from
 import { useSelectableGrid } from '../../hooks/useSelectableGrid'
 import { toggle } from '../../utils/array'
 import { isEditingText } from '../../utils/dom'
-import { backupSummary, detailSidebarProps, hasDamagedFiles, isBackupOutdated, progressVerb } from '../../utils/wallpaper'
+import { backupSummary, detailSidebarProps, hasDamagedFiles, isBackupOutdated, isOptimizableVideo, progressVerb } from '../../utils/wallpaper'
 import { t, tagLabel } from '../../i18n'
 
 interface LibraryFilterState {
@@ -183,8 +187,6 @@ function dropWallpaperId(e: React.DragEvent): string {
   return e.dataTransfer.getData('text/wallpaper-id')
 }
 
-type BackgroundTask = 'backup-selection' | 'scan-backups' | 'check-unavailable' | 'backup-unavailable' | 'verify-files'
-
 interface LibraryViewProps {
   onBrowseCreator?: (creatorSteamId: string) => void
 }
@@ -198,8 +200,6 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
   const [showFilters, setShowFilters] = usePersistentState('we-library-show-filters', true, (v) => v !== false)
   const [showFolders, setShowFolders] = usePersistentState('we-library-show-folders', true, (v) => v !== false)
   const [detailId, setDetailId] = useState<string | null>(null)
-  const [scanning, setScanning] = useState(false)
-  const [scanResult, setScanResult] = useState<{ imported: number; skipped: number; removed: number } | null>(null)
 
   const [page, setPage] = useSessionState('we-library-page', 1)
   const [pageSize, setPageSize] = usePersistentState('we-library-page-size', 50, loadPageSize)
@@ -461,8 +461,12 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
     showToast(t('playlist.addedToCurrent'))
   }
 
-  const [runningTasks, setRunningTasks] = useState<Set<BackgroundTask>>(new Set())
-  const [backupStatus, setBackupStatus] = useState<string | null>(null)
+  const { running: runningTasks, status: backupStatus } = useLibraryTasks()
+  const quickRunning = useQuickOptimizeRunning()
+  const runTask = (task: LibraryTask, work: () => Promise<string>) =>
+    runLibraryTask(task, work).finally(() => { void queryClient.invalidateQueries({ queryKey: ['library'] }) })
+  const setBackupStatus = setLibraryTaskStatus
+  useEffect(() => clearFinishedLibraryTaskStatus, [])
   const [backupProgress, setBackupProgress] = useState<
     Map<string, { percentage: number; status: 'copying' | 'verifying'; action?: BackupProgressEvent['action'] }>
   >(new Map())
@@ -508,21 +512,6 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
     liveProgress ??
     (backupTaskRunning ? (lingeringProgress ?? `${t('backup.backingUp')}...`) : (backupStatus ?? lingeringProgress))
 
-  async function runTask(task: BackgroundTask, work: () => Promise<string>) {
-    setRunningTasks((prev) => new Set(prev).add(task))
-    setBackupStatus(null)
-    try {
-      setBackupStatus(await work())
-    } finally {
-      setRunningTasks((prev) => {
-        const next = new Set(prev)
-        next.delete(task)
-        return next
-      })
-      void queryClient.invalidateQueries({ queryKey: ['library'] })
-    }
-  }
-
   function handleBackupSelection() {
     if (selectedIds.size === 0) return
     const toBackUp = wallpapers.filter((w) => selectedIds.has(w.id) && w.source === 'workshop')
@@ -552,6 +541,7 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
   function handleCheckUnavailable() {
     void runTask('check-unavailable', async () => {
       const result = await window.electronAPI.library.checkUnavailable()
+      if (result.failed) return t('library.checkUnavailableNoAnswer')
       return t('library.checkedUnavailable', { count: result.checked, unavailable: result.unavailable })
     })
   }
@@ -567,14 +557,14 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
     void runTask('verify-files', () => verifyFiles(undefined, setBackupStatus))
   }
 
-  async function handleScan() {
-    setScanning(true)
-    setScanResult(null)
-    const result = await window.electronAPI.library.scan()
-    setScanResult(result)
-    setScanning(false)
-    void queryClient.invalidateQueries({ queryKey: ['library'] })
-    void queryClient.invalidateQueries({ queryKey: ['library-tags'] })
+  function handleScan() {
+    void runTask('scan-library', async () => {
+      const result = await window.electronAPI.library.scan()
+      void queryClient.invalidateQueries({ queryKey: ['library-tags'] })
+      return result.removed > 0
+        ? t('library.scanCompleteRemoved', { imported: result.imported, removed: result.removed })
+        : t('library.scanComplete', { imported: result.imported })
+    })
   }
 
   const [creatingFolder, setCreatingFolder] = useState(false)
@@ -704,10 +694,10 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
         <div className="ml-auto" />
         <ToolbarButton
           icon={<RefreshCw size={14} />}
-          busy={scanning}
-          disabled={scanning}
+          busy={runningTasks.has('scan-library')}
+          disabled={runningTasks.has('scan-library')}
           title={t('library.scanHint')}
-          onClick={() => void handleScan()}
+          onClick={handleScan}
         >
           {t('library.scan')}
         </ToolbarButton>
@@ -769,6 +759,21 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
               {t('library.backupUnavailable', { count: unavailableNotBackedUp.length })}
             </button>
           )}
+          {selectedIds.size > 0 && wallpapers.some((w) => selectedIds.has(w.id) && isOptimizableVideo(w)) && (
+            <button
+              onClick={() => {
+                void runQuickOptimize(
+                  wallpapers.filter((w) => selectedIds.has(w.id) && isOptimizableVideo(w)).map((w) => w.id),
+                  () => { void queryClient.invalidateQueries({ queryKey: ['library'] }) }
+                )
+              }}
+              disabled={quickRunning}
+              className="flex items-center gap-1.5 rounded-lg bg-fg/5 px-3 py-1.5 text-xs text-gray-300 hover:bg-fg/10 disabled:opacity-50"
+            >
+              {quickRunning ? <Loader2 size={12} className="animate-spin" /> : <Zap size={12} />}
+              {t('quick.action')}
+            </button>
+          )}
           {selectedIds.size > 0 && (
             <button
               onClick={handleBackupSelection}
@@ -787,17 +792,18 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
         </div>
       </div>
 
-      {scanResult && (
-        <div className="border-b border-fg/5 px-4 py-2 text-xs text-gray-400">
-          {scanResult.removed > 0
-            ? t('library.scanCompleteRemoved', { imported: scanResult.imported, removed: scanResult.removed })
-            : t('library.scanComplete', { imported: scanResult.imported })}
-        </div>
-      )}
-
       {statusLine && (
-        <div className="truncate border-b border-fg/5 px-4 py-2 text-xs text-gray-400" title={statusLine}>
-          {statusLine}
+        <div className="flex items-center gap-2 border-b border-fg/5 px-4 py-2 text-xs text-gray-400">
+          <span className="min-w-0 flex-1 truncate" title={statusLine}>{statusLine}</span>
+          {!liveProgress && runningTasks.size === 0 && (
+            <button
+              onClick={() => { setBackupStatus(null); setLingeringProgress(null) }}
+              title={t('common.close')}
+              className="shrink-0 rounded p-0.5 text-gray-500 hover:bg-fg/10 hover:text-gray-200"
+            >
+              <X size={12} />
+            </button>
+          )}
         </div>
       )}
 

+ 7 - 19
src/renderer/src/components/library/WallpaperCard.tsx

@@ -356,31 +356,19 @@ export default function WallpaperCard({
             )}
           </CardOverlay>
         )}
-        {wallpaper.downloadFailed && (
+        {(wallpaper.downloadFailed || hasDamagedFiles(wallpaper)) && (
           <CardOverlay>
-            <AlertTriangle size={20} className="text-red-400" />
-            <span className="text-xs text-gray-300">{t('subscribe.downloadFailed')}</span>
-            <button
-              onClick={(e) => void handleRedownload(e)}
-              disabled={isRedownloading}
-              className="flex items-center gap-1 rounded bg-accent-600/80 px-2 py-1 text-xs text-white transition-colors hover:bg-accent-600 disabled:cursor-not-allowed disabled:opacity-50"
-            >
-              {isRedownloading ? <Loader2 size={11} className="animate-spin" /> : <RotateCw size={11} />}
-              {t('subscribe.redownload')}
-            </button>
-          </CardOverlay>
-        )}
-        {hasDamagedFiles(wallpaper) && (
-          <CardOverlay>
-            <AlertTriangle size={20} className="text-amber-400" />
-            <span className="text-xs text-gray-300">{verifyProblemLabel(wallpaper.verifyProblem!)}</span>
+            <AlertTriangle size={20} className={wallpaper.downloadFailed ? 'text-red-400' : 'text-amber-400'} />
+            <span className="text-xs text-gray-300">
+              {wallpaper.downloadFailed ? t('subscribe.downloadFailed') : verifyProblemLabel(wallpaper.verifyProblem!)}
+            </span>
             <button
               onClick={(e) => void handleRedownload(e)}
               disabled={isRedownloading}
               className="flex items-center gap-1 rounded bg-accent-600/80 px-2 py-1 text-xs text-white transition-colors hover:bg-accent-600 disabled:cursor-not-allowed disabled:opacity-50"
             >
               {isRedownloading ? <Loader2 size={11} className="animate-spin" /> : <RotateCw size={11} />}
-              {t('verify.repair')}
+              {wallpaper.downloadFailed ? t('subscribe.redownload') : t('verify.repair')}
             </button>
           </CardOverlay>
         )}
@@ -443,7 +431,7 @@ export default function WallpaperCard({
           />
         </div>
         {error && <p className="mt-1 text-xs text-red-400">{error}</p>}
-        <div className={clsx('flex items-center justify-center', tiny ? 'mt-1.5' : 'mt-2', tiny ? 'gap-0.5' : compact ? 'gap-1' : 'gap-2')}>
+        <div className={clsx('flex items-center justify-start', tiny ? 'mt-1.5' : 'mt-2', tiny ? 'gap-0.5' : compact ? 'gap-1' : 'gap-2')}>
           {actionButtons}
         </div>
       </div>

+ 71 - 19
src/renderer/src/components/playlist/PlaylistItemRow.tsx

@@ -2,9 +2,10 @@ import { useState } from 'react'
 import { GripVertical, Trash2, Volume2, Clock, ChevronDown, ChevronUp, Play, Pause } from 'lucide-react'
 import clsx from 'clsx'
 import CompatBadge from '../common/CompatBadge'
-import type { PlaylistItem, WallpaperMeta } from '@shared/types'
+import type { PlaylistItem, PlaylistMode, WallpaperMeta } from '@shared/types'
 import { getPreviewSrc } from '../../utils/preview'
 import { t } from '../../i18n'
+import { parseTime } from '@shared/schedule'
 
 interface PlaylistItemRowProps {
   item: PlaylistItem
@@ -17,11 +18,25 @@ interface PlaylistItemRowProps {
   onDrop: () => void
   onPlay: () => void
   onRemove: () => void
-  onUpdate: (patch: { volume?: number; durationSec?: number }) => void
+  onUpdate: (patch: { volume?: number; durationSec?: number; endMinute?: number }) => void
   onContextMenu: (e: React.MouseEvent) => void
   onOpenDetail: () => void
   defaultDurationSec: number
+  mode: PlaylistMode
   defaultVolume: number
+  earlierEnd: number
+  isLast: boolean
+}
+
+function formatMinute(minute: number): string {
+  const clamped = Math.min(Math.max(Math.round(minute), 0), 1439)
+  return `${String(Math.floor(clamped / 60)).padStart(2, '0')}:${String(clamped % 60).padStart(2, '0')}`
+}
+
+function parseMinute(time: string): number | undefined {
+  const parsed = parseTime(time)
+  const minute = parsed ? parsed.hours * 60 + parsed.minutes : 0
+  return minute > 0 ? minute : undefined
 }
 
 export default function PlaylistItemRow({
@@ -39,7 +54,10 @@ export default function PlaylistItemRow({
   onContextMenu,
   onOpenDetail,
   defaultDurationSec,
-  defaultVolume
+  mode,
+  defaultVolume,
+  earlierEnd,
+  isLast
 }: PlaylistItemRowProps) {
   const [expanded, setExpanded] = useState(false)
 
@@ -97,7 +115,11 @@ export default function PlaylistItemRow({
             {wallpaper?.title ?? item.wallpaperId}
           </p>
           <p className="text-xs text-gray-600">
-            {t('playlist.itemSummary', { seconds: item.durationSec ?? defaultDurationSec, volume: item.volume ?? defaultVolume })}
+            {mode === 'timer'
+              ? t('playlist.itemSummary', { seconds: item.durationSec ?? defaultDurationSec, volume: item.volume ?? defaultVolume })
+              : mode === 'daytime' && (item.endMinute ?? 0) > 0
+                ? t('playlist.itemUntil', { time: formatMinute(item.endMinute ?? 0), volume: item.volume ?? defaultVolume })
+                : t('playlist.itemVolume', { volume: item.volume ?? defaultVolume })}
           </p>
         </button>
         <button
@@ -139,21 +161,51 @@ export default function PlaylistItemRow({
               </button>
             )}
           </label>
-          <label className="flex items-center gap-2 text-xs text-gray-400">
-            <Clock size={12} />
-            {t('playlist.durationSeconds')}
-            <input
-              type="number"
-              min={1}
-              placeholder={String(defaultDurationSec)}
-              value={item.durationSec ?? ''}
-              onChange={(e) => {
-                const v = e.target.value.trim()
-                onUpdate({ durationSec: v === '' ? undefined : Number(v) })
-              }}
-              className="w-20 rounded bg-fg/5 px-2 py-1 text-gray-200 outline-none focus:ring-1 focus:ring-accent-500"
-            />
-          </label>
+          {mode === 'timer' && (
+            <label className="flex items-center gap-2 text-xs text-gray-400">
+              <Clock size={12} />
+              {t('playlist.durationSeconds')}
+              <input
+                type="number"
+                min={1}
+                placeholder={String(defaultDurationSec)}
+                value={item.durationSec ?? ''}
+                onChange={(e) => {
+                  const v = e.target.value.trim()
+                  onUpdate({ durationSec: v === '' ? undefined : Number(v) })
+                }}
+                className="w-20 rounded bg-fg/5 px-2 py-1 text-gray-200 outline-none focus:ring-1 focus:ring-accent-500"
+              />
+            </label>
+          )}
+          {mode === 'daytime' && (
+            <label className="flex items-center gap-2 text-xs text-gray-400">
+              <Clock size={12} />
+              {t('playlist.until')}
+              <input
+                type="time"
+                defaultValue={(item.endMinute ?? 0) > 0 ? formatMinute(item.endMinute ?? 0) : ''}
+                onChange={(e) => {
+                  const minute = parseMinute(e.target.value)
+                  if (minute !== undefined) {
+                    onUpdate({ endMinute: minute })
+                  } else if (e.target.value === '00:00' && item.endMinute !== undefined) {
+                    e.target.value = ''
+                    onUpdate({ endMinute: undefined })
+                  }
+                }}
+                onBlur={(e) => {
+                  if (e.target.value === '' && item.endMinute !== undefined) onUpdate({ endMinute: undefined })
+                }}
+                className="rounded bg-fg/5 px-2 py-1 text-gray-200 outline-none focus:ring-1 focus:ring-accent-500"
+              />
+              {!isLast && earlierEnd > 0 && (item.endMinute ?? 0) > 0 && (item.endMinute ?? 0) <= earlierEnd ? (
+                <span className="text-amber-400">{t('playlist.untilNotLater', { time: formatMinute(earlierEnd) })}</span>
+              ) : (
+                <span className="text-gray-600">{t('playlist.untilHint')}</span>
+              )}
+            </label>
+          )}
         </div>
       )}
     </div>

+ 46 - 4
src/renderer/src/components/playlist/PlaylistsView.tsx

@@ -16,10 +16,11 @@ import {
   Shuffle,
   Film,
   Heart,
-  ArrowDownWideNarrow
+  ArrowDownWideNarrow,
+  CalendarClock
 } from 'lucide-react'
 import clsx from 'clsx'
-import type { PlaylistSettings, ScreenTarget } from '@shared/types'
+import type { PlaylistMode, PlaylistSettings, ScreenTarget } from '@shared/types'
 import PlaylistItemRow from './PlaylistItemRow'
 import WallpaperPickerModal from './WallpaperPickerModal'
 import DetailSidebar from '../common/DetailSidebar'
@@ -34,6 +35,19 @@ import { screenLabel } from '../../utils/screens'
 import { t } from '../../i18n'
 import type { MessageKey } from '@shared/i18n'
 
+const MODE_OPTIONS: { value: PlaylistMode; label: MessageKey }[] = [
+  { value: 'timer', label: 'playlist.modeTimer' },
+  { value: 'daytime', label: 'playlist.modeDaytime' },
+  { value: 'dayofweek', label: 'playlist.modeDayOfWeek' },
+  { value: 'logon', label: 'playlist.modeLogon' }
+]
+
+const MODE_HINTS: Record<Exclude<PlaylistMode, 'timer'>, MessageKey> = {
+  daytime: 'playlist.modeDaytimeHint',
+  dayofweek: 'playlist.modeDayOfWeekHint',
+  logon: 'playlist.modeLogonHint'
+}
+
 const SORT_OPTIONS: { value: PlaylistSettings['sortBy']; label: MessageKey }[] = [
   { value: 'manual', label: 'playlist.sortManual' },
   { value: 'title', label: 'playlist.sortTitle' },
@@ -76,6 +90,7 @@ export default function PlaylistsView({ onBrowseCreator }: PlaylistsViewProps) {
   const unsubscribe = useUnsubscribe()
 
   const activePlaylist = playlists.find((p) => p.id === activePlaylistId) ?? null
+  const mode: PlaylistMode = activePlaylist?.settings.mode ?? 'timer'
   const favoriteIds = useFavoriteIds()
   const favoriteCount = activePlaylist?.items.filter((i) => favoriteIds.has(i.wallpaperId)).length ?? 0
 
@@ -133,7 +148,7 @@ export default function PlaylistsView({ onBrowseCreator }: PlaylistsViewProps) {
 
   async function handleUpdateItem(
     wallpaperId: string,
-    patch: { volume?: number; durationSec?: number }
+    patch: { volume?: number; durationSec?: number; endMinute?: number }
   ) {
     if (!activePlaylist) return
     await window.electronAPI.playlist.updateItem(activePlaylist.id, wallpaperId, patch)
@@ -397,6 +412,27 @@ export default function PlaylistsView({ onBrowseCreator }: PlaylistsViewProps) {
               )}
 
               <div className="mt-3 flex flex-wrap items-center gap-4">
+                <label className="flex items-center gap-2 text-xs text-gray-400">
+                  <CalendarClock size={12} />
+                  {t('playlist.mode')}
+                  <select
+                    value={mode}
+                    onChange={(e) => void updateSettings({ mode: e.target.value as PlaylistMode })}
+                    className="rounded bg-fg/5 px-2 py-1 text-gray-200 outline-none focus:ring-1 focus:ring-accent-500"
+                  >
+                    {MODE_OPTIONS.map((o) => (
+                      <option key={o.value} value={o.value}>
+                        {t(o.label)}
+                      </option>
+                    ))}
+                  </select>
+                </label>
+                {mode !== 'timer' && (
+                  <p className="basis-full text-xs text-gray-600">{t(MODE_HINTS[mode])}</p>
+                )}
+
+                {mode === 'timer' && (
+                  <>
                 <label className="flex items-center gap-2 text-xs text-gray-400">
                   <Toggle on={activePlaylist.settings.randomize} onClick={() => void updateSettings({ randomize: !activePlaylist.settings.randomize })} />
                   <Shuffle size={12} />
@@ -446,6 +482,9 @@ export default function PlaylistsView({ onBrowseCreator }: PlaylistsViewProps) {
                   {t('playlist.finishVideos')}
                 </label>
 
+                  </>
+                )}
+
                 <label
                   className="flex items-center gap-2 text-xs text-gray-400"
                   title={t('playlist.favoritesOnlyHint')}
@@ -496,10 +535,12 @@ export default function PlaylistsView({ onBrowseCreator }: PlaylistsViewProps) {
                   {t('playlist.empty')}
                 </div>
               )}
-              {activePlaylist.items.map((item, index) => (
+              {activePlaylist.items.map((item, index, items) => (
                 <PlaylistItemRow
                   key={item.wallpaperId}
                   item={item}
+                  earlierEnd={items.slice(0, index).reduce((end, other) => Math.max(end, other.endMinute ?? 0), 0)}
+                  isLast={index === items.length - 1}
                   wallpaper={wallpaperById.get(item.wallpaperId)}
                   index={index}
                   isPlaying={isPlaying}
@@ -513,6 +554,7 @@ export default function PlaylistsView({ onBrowseCreator }: PlaylistsViewProps) {
                   onContextMenu={(e) => { openItemCtxMenu(e, item.wallpaperId) }}
                   onOpenDetail={() => { setDetailId(item.wallpaperId) }}
                   defaultDurationSec={activePlaylist.settings.defaultDurationSec}
+                  mode={mode}
                   defaultVolume={activePlaylist.settings.defaultVolume}
                 />
               ))}

+ 5 - 17
src/renderer/src/components/playlist/WallpaperPickerModal.tsx

@@ -1,5 +1,6 @@
-import { useMemo, useState } from 'react'
-import { useQuery } from '@tanstack/react-query'
+import { useCallback, useState } from 'react'
+import type { WallpaperMeta } from '@shared/types'
+import { useWallpaperPicker } from '../../hooks/queries'
 import { Plus } from 'lucide-react'
 import { PickerCard, PickerFrame, PickerGrid, PickerSearch } from '../common/PickerParts'
 import { t } from '../../i18n'
@@ -18,21 +19,8 @@ export default function WallpaperPickerModal({
   const [search, setSearch] = useState('')
   const [selected, setSelected] = useState<Set<string>>(new Set())
 
-  const { data: wallpapers = [], isLoading } = useQuery({
-    queryKey: ['library', { sortBy: 'title', sortDir: 'asc' }],
-    queryFn: () => window.electronAPI.library.getAll({ sortBy: 'title', sortDir: 'asc' })
-  })
-
-  const available = useMemo(
-    () => wallpapers.filter((w) => !excludeIds.has(w.id)),
-    [wallpapers, excludeIds]
-  )
-
-  const filtered = useMemo(() => {
-    if (!search.trim()) return available
-    const q = search.toLowerCase()
-    return available.filter((w) => w.title.toLowerCase().includes(q))
-  }, [available, search])
+  const keep = useCallback((w: WallpaperMeta) => !excludeIds.has(w.id), [excludeIds])
+  const { matches: filtered, isLoading } = useWallpaperPicker(search, keep)
 
   function toggle(id: string) {
     setSelected((prev) => {

+ 147 - 0
src/renderer/src/components/settings/ActionPicker.tsx

@@ -0,0 +1,147 @@
+import { useMemo, useState } from 'react'
+import type { ScheduleAction, ScreenTarget } from '@shared/types'
+import ScreenSelect from '../common/ScreenSelect'
+import { inputClass } from '../common/inputClass'
+import { useDisplayTargets } from '../../hooks/useDisplayTargets'
+import { useAllWallpapers, usePlaylists, useProfiles } from '../../hooks/queries'
+import { t } from '../../i18n'
+import type { MessageKey } from '@shared/i18n'
+
+/** The sentence a rule shows for its action */
+export function useDescribeAction(): (action: ScheduleAction) => string {
+  const wallpapers = useAllWallpapers()
+  const playlists = usePlaylists()
+  const profiles = useProfiles()
+
+  return (action) => {
+    if (action.type === 'wallpaper') {
+      const title = wallpapers.find((w) => w.id === action.wallpaperId)?.title ?? t('schedule.missingWallpaper')
+      return t('schedule.show', { title })
+    }
+    if (action.type === 'playlist') {
+      const title = playlists.find((p) => p.id === action.playlistId)?.title ?? t('schedule.missingPlaylist')
+      return t('schedule.play', { title })
+    }
+    if (action.type === 'profile') {
+      const name = profiles.find((p) => p.id === action.profileId)?.name ?? t('profiles.missing')
+      return t('profiles.load', { name })
+    }
+    return t('schedule.stop')
+  }
+}
+
+/** The message to show when the action is not finished, null when it is */
+export function actionProblem(action: ScheduleAction): MessageKey | null {
+  if (action.type === 'wallpaper' && !action.wallpaperId) return 'schedule.pickWallpaper'
+  if (action.type === 'playlist' && !action.playlistId) return 'schedule.pickPlaylist'
+  if (action.type === 'profile' && !action.profileId) return 'profiles.pick'
+  return null
+}
+
+interface Props {
+  action: ScheduleAction
+  screen: ScreenTarget
+  onAction: (action: ScheduleAction) => void
+  onScreen: (screen: ScreenTarget) => void
+}
+
+export default function ActionPicker({ action, screen, onAction, onScreen }: Props) {
+  const { targets, perScreen } = useDisplayTargets()
+  const wallpapers = useAllWallpapers()
+  const playlists = usePlaylists()
+  const profiles = useProfiles()
+  const [wallpaperFilter, setWallpaperFilter] = useState('')
+
+  const selectedWallpaperId = action.type === 'wallpaper' ? action.wallpaperId : ''
+  const wallpaperOptions = useMemo(() => {
+    const needle = wallpaperFilter.trim().toLowerCase()
+    const matches = wallpapers
+      .filter((w) => w.localPath && (!needle || w.title.toLowerCase().includes(needle)))
+      .slice(0, 100)
+    const selected = wallpapers.find((w) => w.id === selectedWallpaperId)
+    return selected && !matches.includes(selected) ? [selected, ...matches] : matches
+  }, [wallpapers, wallpaperFilter, selectedWallpaperId])
+
+  return (
+    <>
+      <div className="flex flex-wrap items-center gap-2">
+        <select
+          value={action.type}
+          onChange={(e) => {
+            const type = e.target.value as ScheduleAction['type']
+            onAction(
+              type === 'wallpaper'
+                ? { type, wallpaperId: '' }
+                : type === 'playlist'
+                  ? { type, playlistId: playlists[0]?.id ?? '' }
+                  : type === 'profile'
+                    ? { type, profileId: profiles[0]?.id ?? '' }
+                    : { type }
+            )
+          }}
+          className={inputClass}
+        >
+          <option value="wallpaper">{t('schedule.showWallpaper')}</option>
+          <option value="playlist">{t('schedule.playPlaylist')}</option>
+          <option value="profile">{t('profiles.loadProfile')}</option>
+          <option value="stop">{t('schedule.stop')}</option>
+        </select>
+        {perScreen && action.type !== 'profile' && (
+          <ScreenSelect targets={targets} value={screen} onChange={onScreen} />
+        )}
+      </div>
+
+      {action.type === 'playlist' && (
+        <select
+          value={action.playlistId}
+          onChange={(e) => { onAction({ type: 'playlist', playlistId: e.target.value }) }}
+          className={`${inputClass} w-full`}
+        >
+          {playlists.map((p) => (
+            <option key={p.id} value={p.id}>
+              {p.title}
+            </option>
+          ))}
+        </select>
+      )}
+
+      {action.type === 'profile' && (
+        <select
+          value={action.profileId}
+          onChange={(e) => { onAction({ type: 'profile', profileId: e.target.value }) }}
+          className={`${inputClass} w-full`}
+        >
+          {profiles.length === 0 && <option value="">{t('profiles.none')}</option>}
+          {profiles.map((p) => (
+            <option key={p.id} value={p.id}>
+              {p.name}
+            </option>
+          ))}
+        </select>
+      )}
+
+      {action.type === 'wallpaper' && (
+        <div className="space-y-1.5">
+          <input
+            value={wallpaperFilter}
+            onChange={(e) => { setWallpaperFilter(e.target.value) }}
+            placeholder={t('schedule.searchLibrary')}
+            className={`${inputClass} w-full`}
+          />
+          <select
+            value={action.wallpaperId}
+            onChange={(e) => { onAction({ type: 'wallpaper', wallpaperId: e.target.value }) }}
+            size={6}
+            className={`${inputClass} w-full`}
+          >
+            {wallpaperOptions.map((w) => (
+              <option key={w.id} value={w.id}>
+                {w.title}
+              </option>
+            ))}
+          </select>
+        </div>
+      )}
+    </>
+  )
+}

+ 172 - 0
src/renderer/src/components/settings/AppRuleSettings.tsx

@@ -0,0 +1,172 @@
+import { useState } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { AppWindow, Music } from 'lucide-react'
+import type { AppRule, AppRuleCondition } from '@shared/types'
+import { parseProcessNames } from '@shared/appRules'
+import { actionProblem } from './ActionPicker'
+import { AddRuleButton, RuleEditor, RuleRow } from './RuleParts'
+import { inputClass } from '../common/inputClass'
+import { useToast } from '../common/Toast'
+import Toggle from '../common/Toggle'
+import { t } from '../../i18n'
+
+type Draft = Omit<AppRule, 'id'> & { id?: string }
+
+const EMPTY_DRAFT: Draft = {
+  name: '',
+  enabled: true,
+  condition: { type: 'process', names: [] },
+  action: { type: 'stop' },
+  screen: '*',
+  revert: true
+}
+
+function describeCondition(condition: AppRuleCondition): string {
+  if (condition.type === 'audio') return t('appRules.whileAudio')
+  return t('appRules.whileRuns', { names: condition.names.join(', ') })
+}
+
+export default function AppRuleSettings() {
+  const queryClient = useQueryClient()
+  const { showToast } = useToast()
+  const [draft, setDraft] = useState<Draft | null>(null)
+  const [names, setNames] = useState('')
+
+  const { data: audioAvailable } = useQuery({
+    queryKey: ['app-rules-audio-available'],
+    queryFn: () => window.electronAPI.appRules.audioAvailable(),
+    staleTime: Infinity
+  })
+
+  const { data: rules = [] } = useQuery({
+    queryKey: ['app-rules'],
+    queryFn: () => window.electronAPI.appRules.getAll()
+  })
+  const { data: active = [] } = useQuery({
+    queryKey: ['app-rules-active'],
+    queryFn: () => window.electronAPI.appRules.active(),
+    refetchInterval: 3000
+  })
+
+  function refresh() {
+    void queryClient.invalidateQueries({ queryKey: ['app-rules'] })
+    void queryClient.invalidateQueries({ queryKey: ['app-rules-active'] })
+  }
+
+  function edit(rule: Draft) {
+    setDraft(rule)
+    setNames(rule.condition.type === 'process' ? rule.condition.names.join(', ') : '')
+  }
+
+  async function save() {
+    if (!draft) return
+    const condition: AppRuleCondition =
+      draft.condition.type === 'process' ? { type: 'process', names: parseProcessNames(names) } : draft.condition
+    if (condition.type === 'process' && condition.names.length === 0) {
+      showToast(t('appRules.pickProgram'), { warning: true })
+      return
+    }
+    const problem = actionProblem(draft.action)
+    if (problem) {
+      showToast(t(problem), { warning: true })
+      return
+    }
+    await window.electronAPI.appRules.save({
+      ...draft,
+      condition,
+      name: draft.name.trim() || describeCondition(condition)
+    })
+    setDraft(null)
+    refresh()
+  }
+
+  async function toggle(rule: AppRule) {
+    await window.electronAPI.appRules.save({ ...rule, enabled: !rule.enabled })
+    refresh()
+  }
+
+  async function remove(id: string) {
+    await window.electronAPI.appRules.delete(id)
+    refresh()
+  }
+
+  return (
+    <div>
+      <label className="block text-xs font-medium uppercase tracking-wide text-gray-500">{t('appRules.title')}</label>
+      <p className="mt-1 text-xs text-gray-600">{t('appRules.description')}</p>
+
+      <div className="mt-3 space-y-1.5">
+        {rules.map((rule) => (
+          <RuleRow
+            key={rule.id}
+            enabled={rule.enabled}
+            onToggle={() => void toggle(rule)}
+            name={
+              <>
+                {rule.name}
+                {active.includes(rule.id) && <span className="ml-2 text-xs text-accent-400">{t('appRules.active')}</span>}
+              </>
+            }
+            condition={describeCondition(rule.condition)}
+            action={rule.action}
+            screen={rule.screen}
+            onEdit={() => { edit(rule) }}
+            onDelete={() => void remove(rule.id)}
+          />
+        ))}
+      </div>
+
+      {!draft ? (
+        <AddRuleButton label={t('appRules.add')} onClick={() => { edit(EMPTY_DRAFT) }} />
+      ) : (
+        <RuleEditor
+          name={draft.name}
+          action={draft.action}
+          screen={draft.screen}
+          onChange={(patch) => { setDraft({ ...draft, ...patch }) }}
+          onSave={() => void save()}
+          onCancel={() => { setDraft(null) }}
+          footer={
+            <label className="flex items-center gap-3 cursor-pointer">
+              <Toggle on={draft.revert} onClick={() => { setDraft({ ...draft, revert: !draft.revert }) }} />
+              <span className="text-sm text-gray-300">{t('appRules.revert')}</span>
+            </label>
+          }
+        >
+          <div className="flex flex-wrap items-center gap-2 text-sm text-gray-300">
+            {draft.condition.type === 'audio' ? <Music size={14} /> : <AppWindow size={14} />}
+            <select
+              value={draft.condition.type}
+              onChange={(e) => {
+                setDraft({
+                  ...draft,
+                  condition: e.target.value === 'audio' ? { type: 'audio' } : { type: 'process', names: [] }
+                })
+              }}
+              className={inputClass}
+            >
+              <option value="process">{t('appRules.runs')}</option>
+              <option value="audio">{t('appRules.audio')}</option>
+            </select>
+          </div>
+
+          {draft.condition.type === 'audio' && audioAvailable === false && (
+            <p className="text-xs text-amber-400">{t('appRules.audioUnavailable')}</p>
+          )}
+
+          {draft.condition.type === 'process' && (
+            <div>
+              <input
+                value={names}
+                onChange={(e) => { setNames(e.target.value) }}
+                placeholder={t('appRules.programsPlaceholder')}
+                className={`${inputClass} w-full`}
+              />
+              <p className="mt-1 text-xs text-gray-600">{t('appRules.programsHint')}</p>
+            </div>
+          )}
+        </RuleEditor>
+      )}
+    </div>
+  )
+}

+ 107 - 0
src/renderer/src/components/settings/AudioInputSettings.tsx

@@ -0,0 +1,107 @@
+import { useEffect, useRef, useState } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { Mic, RefreshCw } from 'lucide-react'
+import type { EngineFlags } from '@shared/types'
+import { useConfig } from '../../hooks/queries'
+import { inputClass } from '../common/inputClass'
+import CommitRange from '../common/sidebar/CommitRange'
+import { t } from '../../i18n'
+
+export default function AudioInputSettings() {
+  const queryClient = useQueryClient()
+  const config = useConfig()
+  const flags: EngineFlags = config?.engineFlags ?? {}
+  const latestFlags = useRef(flags)
+  useEffect(() => {
+    latestFlags.current = flags
+  })
+  const { data: devices = [], refetch } = useQuery({
+    queryKey: ['audio-inputs'],
+    queryFn: () => window.electronAPI.lwe.listAudioInputs()
+  })
+
+  const [sliding, setSliding] = useState<EngineFlags>({})
+
+  // an engine without the option lists nothing, there is nothing to choose then
+  if (!config || devices.length === 0) return null
+
+  async function save(patch: EngineFlags) {
+    const next = { ...latestFlags.current, ...patch }
+    latestFlags.current = next
+    queryClient.setQueryData(['config'], { ...config!, engineFlags: next })
+    await window.electronAPI.config.setEngineFlags(next)
+    void queryClient.invalidateQueries({ queryKey: ['config'] })
+  }
+
+  function commit() {
+    const pending = sliding
+    if (Object.keys(pending).length === 0) return
+    void save(pending).then(() => { setSliding((cur) => (cur === pending ? {} : cur)) }).catch(console.error)
+  }
+
+  const device = flags.audioInput ?? 'default'
+  const known = device === 'default' || devices.some((d) => d.name === device)
+  const volume = sliding.audioInputVolume ?? flags.audioInputVolume ?? 50
+  const threshold = sliding.audioInputThreshold ?? flags.audioInputThreshold ?? 0
+
+  return (
+    <div>
+      <label className="block text-xs font-medium uppercase tracking-wide text-gray-500">{t('audioInput.title')}</label>
+      <p className="mt-1 text-xs text-gray-600">{t('audioInput.hint')}</p>
+
+      <div className="mt-3 flex items-center gap-2">
+        <Mic size={14} className="text-gray-400" />
+        <select
+          value={device}
+          onChange={(e) => void save({ audioInput: e.target.value === 'default' ? undefined : e.target.value })}
+          className={`${inputClass} min-w-0 flex-1`}
+        >
+          <option value="default">{t('audioInput.default')}</option>
+          {!known && <option value={device}>{device}</option>}
+          <optgroup label={t('audioInput.inputs')}>
+            {devices.filter((d) => !d.monitor).map((d) => (
+              <option key={d.name} value={d.name}>{d.description || d.name}</option>
+            ))}
+          </optgroup>
+          <optgroup label={t('audioInput.outputs')}>
+            {devices.filter((d) => d.monitor).map((d) => (
+              <option key={d.name} value={d.name}>{d.description || d.name}</option>
+            ))}
+          </optgroup>
+        </select>
+        <button onClick={() => void refetch()} title={t('audioInput.refresh')} className="rounded p-1.5 text-gray-500 hover:text-gray-200">
+          <RefreshCw size={13} />
+        </button>
+      </div>
+
+      <div className="mt-3">
+        <label className="block text-xs text-gray-400 mb-1">{t('audioInput.volume', { value: volume })}</label>
+        <div className="w-56">
+          <CommitRange
+            min={0}
+            max={100}
+            value={volume}
+            disabled={false}
+            onSlide={(v) => { setSliding((cur) => ({ ...cur, audioInputVolume: v })) }}
+            onCommit={commit}
+          />
+        </div>
+      </div>
+
+      <div className="mt-3">
+        <label className="block text-xs text-gray-400 mb-1">{t('audioInput.threshold', { value: threshold })}</label>
+        <div className="w-56">
+          <CommitRange
+            min={0}
+            max={500}
+            value={threshold}
+            disabled={false}
+            onSlide={(v) => { setSliding((cur) => ({ ...cur, audioInputThreshold: v })) }}
+            onCommit={commit}
+          />
+        </div>
+        <p className="mt-1 text-xs text-gray-600">{t('audioInput.thresholdHint')}</p>
+      </div>
+    </div>
+  )
+}

+ 8 - 12
src/renderer/src/components/settings/DiagnosticsTargetModal.tsx

@@ -1,14 +1,16 @@
 import { useMemo, useState } from 'react'
-import { useQuery } from '@tanstack/react-query'
 import { Play } from 'lucide-react'
 import { compatStatus } from '@shared/compat'
-import type { ScreenTarget } from '@shared/types'
+import type { ScreenTarget, WallpaperMeta } from '@shared/types'
 import { screenLabel } from '../../utils/screens'
 import { useDisplayTargets } from '../../hooks/useDisplayTargets'
+import { useWallpaperPicker } from '../../hooks/queries'
 import { PickerCard, PickerFrame, PickerGrid, PickerSearch } from '../common/PickerParts'
 import { CompatStatusIcon } from '../common/CompatBadge'
 import { t } from '../../i18n'
 
+const hasLocalFolder = (w: WallpaperMeta) => !!w.localPath
+
 export interface DiagnosticsChoice {
   wallpaperId: string
   screen: ScreenTarget
@@ -26,17 +28,11 @@ export default function DiagnosticsTargetModal({ seconds, onCollect, onClose }:
   const { targets, perScreen } = useDisplayTargets()
   const [screen, setScreen] = useState<ScreenTarget | null>(null)
 
-  const { data: wallpapers = [], isLoading } = useQuery({
-    queryKey: ['library', { sortBy: 'title', sortDir: 'asc' }],
-    queryFn: () => window.electronAPI.library.getAll({ sortBy: 'title', sortDir: 'asc' })
-  })
-
+  const { matches, isLoading } = useWallpaperPicker(search, hasLocalFolder)
   const filtered = useMemo(() => {
-    const q = search.trim().toLowerCase()
-    const list = wallpapers.filter((w) => w.localPath && (!q || w.title.toLowerCase().includes(q)))
-    const flagged = (w: (typeof list)[number]) => (compatStatus(w.compat) === 'ok' ? 1 : 0)
-    return [...list].sort((a, b) => flagged(a) - flagged(b))
-  }, [wallpapers, search])
+    const flagged = (w: (typeof matches)[number]) => (compatStatus(w.compat) === 'ok' ? 1 : 0)
+    return [...matches].sort((a, b) => flagged(a) - flagged(b))
+  }, [matches])
 
   const chosenScreen = screen && targets.includes(screen) ? screen : targets[0]
 

+ 4 - 22
src/renderer/src/components/settings/FontSettings.tsx

@@ -1,33 +1,15 @@
-import { useState } from 'react'
-import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { useQuery } from '@tanstack/react-query'
 import { Type, X } from 'lucide-react'
+import { useFontAdd } from '../../hooks/useFontAdd'
 import { t } from '../../i18n'
 
 export default function FontSettings() {
-  const queryClient = useQueryClient()
   const { data: fonts = [] } = useQuery({
     queryKey: ['user-fonts'],
     queryFn: () => window.electronAPI.fonts.list(),
     staleTime: Infinity
   })
-  const [status, setStatus] = useState<string | null>(null)
-
-  async function refresh() {
-    await queryClient.invalidateQueries({ queryKey: ['user-fonts'] })
-    await queryClient.invalidateQueries({ queryKey: ['lwe-fonts'] })
-  }
-
-  async function handleAdd() {
-    const result = await window.electronAPI.fonts.add()
-    setStatus(
-      result.rejected.length > 0
-        ? t('fonts.rejected', { files: result.rejected.join(', ') })
-        : result.added.length > 0
-          ? t('fonts.added', { count: result.added.length })
-          : null
-    )
-    await refresh()
-  }
+  const { status, setStatus, add, refresh } = useFontAdd((count) => t('fonts.added', { count }))
 
   async function handleRemove(name: string) {
     await window.electronAPI.fonts.remove(name)
@@ -60,7 +42,7 @@ export default function FontSettings() {
         </ul>
       )}
       <button
-        onClick={() => void handleAdd()}
+        onClick={() => void add()}
         className="mt-3 flex items-center gap-2 rounded-lg bg-fg/5 px-3 py-2 text-sm text-gray-300 hover:bg-fg/10"
       >
         <Type size={16} />

+ 86 - 0
src/renderer/src/components/settings/ProfileSettings.tsx

@@ -0,0 +1,86 @@
+import { useState } from 'react'
+import { useQueryClient } from '@tanstack/react-query'
+import { Camera, Play, Trash2 } from 'lucide-react'
+import { useProfiles } from '../../hooks/queries'
+import { inputClass } from '../common/inputClass'
+import { useToast } from '../common/Toast'
+import { t } from '../../i18n'
+
+export default function ProfileSettings() {
+  const queryClient = useQueryClient()
+  const { showToast } = useToast()
+  const profiles = useProfiles()
+  const [name, setName] = useState('')
+
+  function refresh() {
+    void queryClient.invalidateQueries({ queryKey: ['profiles'] })
+  }
+
+  async function capture() {
+    const trimmed = name.trim()
+    if (!trimmed) {
+      showToast(t('profiles.nameFirst'), { warning: true })
+      return
+    }
+    await window.electronAPI.profiles.capture(trimmed)
+    setName('')
+    refresh()
+  }
+
+  async function apply(id: string) {
+    try {
+      await window.electronAPI.profiles.apply(id)
+    } catch (err) {
+      showToast((err as Error).message, { warning: true, durationMs: 6000 })
+    }
+  }
+
+  async function remove(id: string) {
+    const { disabled } = await window.electronAPI.profiles.delete(id)
+    refresh()
+    if (disabled > 0) {
+      void queryClient.invalidateQueries({ queryKey: ['app-rules'] })
+      void queryClient.invalidateQueries({ queryKey: ['app-rules-active'] })
+      void queryClient.invalidateQueries({ queryKey: ['schedule'] })
+      showToast(t('profiles.rulesOff'), { warning: true })
+    }
+  }
+
+  return (
+    <div>
+      <label className="block text-xs font-medium uppercase tracking-wide text-gray-500">{t('profiles.title')}</label>
+      <p className="mt-1 text-xs text-gray-600">{t('profiles.description')}</p>
+
+      <div className="mt-3 space-y-1.5">
+        {profiles.map((profile) => (
+          <div key={profile.id} className="flex items-center gap-2 rounded-lg bg-fg/5 px-3 py-2">
+            <p className="min-w-0 flex-1 truncate text-sm text-gray-200">{profile.name}</p>
+            <button onClick={() => void apply(profile.id)} title={t('profiles.apply')} className="rounded p-1 text-gray-500 hover:text-gray-200">
+              <Play size={13} />
+            </button>
+            <button onClick={() => void remove(profile.id)} title={t('common.delete')} className="rounded p-1 text-gray-500 hover:text-red-400">
+              <Trash2 size={13} />
+            </button>
+          </div>
+        ))}
+      </div>
+
+      <div className="mt-2 flex gap-2">
+        <input
+          value={name}
+          onChange={(e) => { setName(e.target.value) }}
+          onKeyDown={(e) => { if (e.key === 'Enter') void capture() }}
+          placeholder={t('profiles.namePlaceholder')}
+          className={`${inputClass} min-w-0 flex-1`}
+        />
+        <button
+          onClick={() => void capture()}
+          className="flex items-center gap-2 rounded-lg bg-fg/5 px-3 py-2 text-sm text-gray-300 hover:bg-fg/10"
+        >
+          <Camera size={14} />
+          {t('profiles.saveCurrent')}
+        </button>
+      </div>
+    </div>
+  )
+}

+ 113 - 0
src/renderer/src/components/settings/RuleParts.tsx

@@ -0,0 +1,113 @@
+import type { ReactNode } from 'react'
+import { Pencil, Plus, Trash2 } from 'lucide-react'
+import clsx from 'clsx'
+import type { ScheduleAction } from '@shared/types'
+import ActionPicker, { useDescribeAction } from './ActionPicker'
+import { inputClass } from '../common/inputClass'
+import { useDisplayTargets } from '../../hooks/useDisplayTargets'
+import { screenLabel } from '../../utils/screens'
+import { t } from '../../i18n'
+
+const iconButton = 'rounded p-1 text-gray-500'
+
+interface RuleRowProps {
+  enabled: boolean
+  onToggle: () => void
+  name: ReactNode
+  condition: string
+  action: ScheduleAction
+  screen: string
+  suffix?: string | null
+  extraButtons?: ReactNode
+  onEdit: () => void
+  onDelete: () => void
+}
+
+export function RuleRow({ enabled, onToggle, name, condition, action, screen, suffix, extraButtons, onEdit, onDelete }: RuleRowProps) {
+  const describeAction = useDescribeAction()
+  const { perScreen } = useDisplayTargets()
+  return (
+    <div className={clsx('flex items-center gap-2 rounded-lg bg-fg/5 px-3 py-2', !enabled && 'opacity-50')}>
+      <input type="checkbox" checked={enabled} onChange={onToggle} className="accent-accent-500" />
+      <div className="min-w-0 flex-1">
+        <p className="truncate text-sm text-gray-200">{name}</p>
+        <p className="truncate text-xs text-gray-500">
+          {condition} · {describeAction(action)}
+          {perScreen && action.type !== 'profile' && ` · ${screenLabel(screen)}`}
+          {suffix && ` · ${suffix}`}
+        </p>
+      </div>
+      {extraButtons}
+      <button onClick={onEdit} title={t('common.edit')} className={`${iconButton} hover:text-gray-200`}>
+        <Pencil size={13} />
+      </button>
+      <button onClick={onDelete} title={t('common.delete')} className={`${iconButton} hover:text-red-400`}>
+        <Trash2 size={13} />
+      </button>
+    </div>
+  )
+}
+
+export function RuleIconButton({ title, onClick, children }: { title: string; onClick: () => void; children: ReactNode }) {
+  return (
+    <button onClick={onClick} title={title} className={`${iconButton} hover:text-gray-200`}>
+      {children}
+    </button>
+  )
+}
+
+export function AddRuleButton({ label, onClick }: { label: string; onClick: () => void }) {
+  return (
+    <button
+      onClick={onClick}
+      className="mt-2 flex items-center gap-2 rounded-lg bg-fg/5 px-3 py-2 text-sm text-gray-300 hover:bg-fg/10"
+    >
+      <Plus size={14} />
+      {label}
+    </button>
+  )
+}
+
+interface RuleEditorProps {
+  name: string
+  action: ScheduleAction
+  screen: string
+  onChange: (patch: { name?: string; action?: ScheduleAction; screen?: string }) => void
+  onSave: () => void
+  onCancel: () => void
+  children: ReactNode
+  footer?: ReactNode
+}
+
+export function RuleEditor({ name, action, screen, onChange, onSave, onCancel, children, footer }: RuleEditorProps) {
+  return (
+    <div className="mt-2 space-y-3 rounded-lg border border-fg/10 p-3">
+      <input
+        value={name}
+        onChange={(e) => { onChange({ name: e.target.value }) }}
+        placeholder={t('schedule.namePlaceholder')}
+        className={`${inputClass} w-full`}
+      />
+
+      {children}
+
+      <ActionPicker
+        action={action}
+        screen={screen}
+        onAction={(next) => { onChange({ action: next }) }}
+        onScreen={(next) => { onChange({ screen: next }) }}
+      />
+
+      {footer}
+
+      <div className="flex gap-2">
+        <button onClick={onSave} className="rounded-lg bg-accent-600 px-4 py-2 text-sm font-medium text-white hover:bg-accent-500">
+          {t('common.save')}
+        </button>
+        <button onClick={onCancel} className="rounded-lg bg-fg/5 px-4 py-2 text-sm text-gray-300 hover:bg-fg/10">
+          {t('common.cancel')}
+        </button>
+      </div>
+    </div>
+  )
+}

+ 36 - 151
src/renderer/src/components/settings/ScheduleSettings.tsx

@@ -1,14 +1,13 @@
-import { useEffect, useMemo, useState } from 'react'
+import { useEffect, useState } from 'react'
 import { useQuery, useQueryClient } from '@tanstack/react-query'
-import { CalendarClock, Moon, Pencil, Play, Plus, Sun, Trash2 } from 'lucide-react'
+import { CalendarClock, Moon, Play, Sun } from 'lucide-react'
 import clsx from 'clsx'
-import type { ScheduleAction, ScheduleRule, ScheduleTrigger } from '@shared/types'
+import type { ScheduleRule, ScheduleTrigger } from '@shared/types'
 import { nextFireTime, parseTime } from '@shared/schedule'
-import ScreenSelect from '../common/ScreenSelect'
-import { useDisplayTargets } from '../../hooks/useDisplayTargets'
-import { screenLabel } from '../../utils/screens'
+import { actionProblem, useDescribeAction } from './ActionPicker'
+import { AddRuleButton, RuleEditor, RuleIconButton, RuleRow } from './RuleParts'
+import { inputClass } from '../common/inputClass'
 import { useToast } from '../common/Toast'
-import { useAllWallpapers, usePlaylists } from '../../hooks/queries'
 import { t, currentLanguage } from '../../i18n'
 
 // 2024-01-07 was a Sunday, day 0 like Date.getDay()
@@ -27,8 +26,6 @@ const EMPTY_DRAFT: Draft = {
   screen: '*'
 }
 
-const inputClass = 'rounded-lg bg-fg/5 px-2 py-1.5 text-sm text-gray-200 outline-none focus:ring-1 focus:ring-accent-500'
-
 function describeTrigger(trigger: ScheduleTrigger): string {
   if (trigger.type === 'theme') return trigger.theme === 'dark' ? t('schedule.whenDark') : t('schedule.whenLight')
   const labels = dayLabels()
@@ -43,9 +40,8 @@ const currentTime = (): Date => new Date()
 export default function ScheduleSettings() {
   const queryClient = useQueryClient()
   const { showToast } = useToast()
-  const { targets, perScreen } = useDisplayTargets()
+  const describeAction = useDescribeAction()
   const [draft, setDraft] = useState<Draft | null>(null)
-  const [wallpaperFilter, setWallpaperFilter] = useState('')
   const [now, setNow] = useState(currentTime)
 
   useEffect(() => {
@@ -64,28 +60,6 @@ export default function ScheduleSettings() {
     queryKey: ['schedule'],
     queryFn: () => window.electronAPI.schedule.getAll()
   })
-  const wallpapers = useAllWallpapers()
-  const playlists = usePlaylists()
-
-  const wallpaperTitle = (id: string) => wallpapers.find((w) => w.id === id)?.title ?? t('schedule.missingWallpaper')
-  const playlistTitle = (id: string) => playlists.find((p) => p.id === id)?.title ?? t('schedule.missingPlaylist')
-
-  function describeAction(action: ScheduleAction): string {
-    if (action.type === 'wallpaper') return t('schedule.show', { title: wallpaperTitle(action.wallpaperId) })
-    if (action.type === 'playlist') return t('schedule.play', { title: playlistTitle(action.playlistId) })
-    return t('schedule.stop')
-  }
-
-  const selectedWallpaperId = draft?.action.type === 'wallpaper' ? draft.action.wallpaperId : ''
-  const wallpaperOptions = useMemo(() => {
-    const needle = wallpaperFilter.trim().toLowerCase()
-    const matches = wallpapers
-      .filter((w) => w.localPath && (!needle || w.title.toLowerCase().includes(needle)))
-      .slice(0, 100)
-    const selected = wallpapers.find((w) => w.id === selectedWallpaperId)
-    return selected && !matches.includes(selected) ? [selected, ...matches] : matches
-  }, [wallpapers, wallpaperFilter, selectedWallpaperId])
-
   function refresh() {
     setNow(currentTime())
     void queryClient.invalidateQueries({ queryKey: ['schedule'] })
@@ -97,12 +71,9 @@ export default function ScheduleSettings() {
       showToast(t('schedule.badTime'), { warning: true })
       return
     }
-    if (draft.action.type === 'wallpaper' && !draft.action.wallpaperId) {
-      showToast(t('schedule.pickWallpaper'), { warning: true })
-      return
-    }
-    if (draft.action.type === 'playlist' && !draft.action.playlistId) {
-      showToast(t('schedule.pickPlaylist'), { warning: true })
+    const problem = actionProblem(draft.action)
+    if (problem) {
+      showToast(t(problem), { warning: true })
       return
     }
     await window.electronAPI.schedule.save({ ...draft, name: draft.name.trim() || describeAction(draft.action) })
@@ -132,10 +103,6 @@ export default function ScheduleSettings() {
     setDraft((d) => (d ? { ...d, trigger } : d))
   }
 
-  function setAction(action: ScheduleAction) {
-    setDraft((d) => (d ? { ...d, action } : d))
-  }
-
   return (
     <div>
       <label className="block text-xs font-medium uppercase tracking-wide text-gray-500">{t('schedule.title')}</label>
@@ -147,50 +114,38 @@ export default function ScheduleSettings() {
         {rules.map((rule) => {
           const next = rule.enabled && rule.trigger.type === 'time' ? nextFireTime(rule, now) : null
           return (
-            <div
+            <RuleRow
               key={rule.id}
-              className={clsx('flex items-center gap-2 rounded-lg bg-fg/5 px-3 py-2', !rule.enabled && 'opacity-50')}
-            >
-              <input type="checkbox" checked={rule.enabled} onChange={() => void toggle(rule)} className="accent-accent-500" />
-              <div className="min-w-0 flex-1">
-                <p className="truncate text-sm text-gray-200">{rule.name}</p>
-                <p className="truncate text-xs text-gray-500">
-                  {describeTrigger(rule.trigger)} · {describeAction(rule.action)}
-                  {perScreen && ` · ${screenLabel(rule.screen)}`}
-                  {next && ` · ${t('schedule.next', { time: next.toLocaleString(currentLanguage(), { weekday: 'short', hour: '2-digit', minute: '2-digit' }) })}`}
-                </p>
-              </div>
-              <button onClick={() => void runNow(rule)} title={t('schedule.runNow')} className="rounded p-1 text-gray-500 hover:text-gray-200">
-                <Play size={13} />
-              </button>
-              <button onClick={() => { setDraft(rule) }} title={t('common.edit')} className="rounded p-1 text-gray-500 hover:text-gray-200">
-                <Pencil size={13} />
-              </button>
-              <button onClick={() => void remove(rule.id)} title={t('common.delete')} className="rounded p-1 text-gray-500 hover:text-red-400">
-                <Trash2 size={13} />
-              </button>
-            </div>
+              enabled={rule.enabled}
+              onToggle={() => void toggle(rule)}
+              name={rule.name}
+              condition={describeTrigger(rule.trigger)}
+              action={rule.action}
+              screen={rule.screen}
+              suffix={next && t('schedule.next', { time: next.toLocaleString(currentLanguage(), { weekday: 'short', hour: '2-digit', minute: '2-digit' }) })}
+              extraButtons={
+                <RuleIconButton title={t('schedule.runNow')} onClick={() => void runNow(rule)}>
+                  <Play size={13} />
+                </RuleIconButton>
+              }
+              onEdit={() => { setDraft(rule) }}
+              onDelete={() => void remove(rule.id)}
+            />
           )
         })}
       </div>
 
       {!draft ? (
-        <button
-          onClick={() => { setDraft(EMPTY_DRAFT) }}
-          className="mt-2 flex items-center gap-2 rounded-lg bg-fg/5 px-3 py-2 text-sm text-gray-300 hover:bg-fg/10"
-        >
-          <Plus size={14} />
-          {t('schedule.add')}
-        </button>
+        <AddRuleButton label={t('schedule.add')} onClick={() => { setDraft(EMPTY_DRAFT) }} />
       ) : (
-        <div className="mt-2 space-y-3 rounded-lg border border-fg/10 p-3">
-          <input
-            value={draft.name}
-            onChange={(e) => { setDraft({ ...draft, name: e.target.value }); }}
-            placeholder={t('schedule.namePlaceholder')}
-            className={`${inputClass} w-full`}
-          />
-
+        <RuleEditor
+          name={draft.name}
+          action={draft.action}
+          screen={draft.screen}
+          onChange={(patch) => { setDraft({ ...draft, ...patch }) }}
+          onSave={() => void save()}
+          onCancel={() => { setDraft(null) }}
+        >
           <div className="flex flex-wrap items-center gap-2 text-sm text-gray-300">
             <CalendarClock size={14} />
             <select
@@ -240,77 +195,7 @@ export default function ScheduleSettings() {
               <span className="self-center text-xs text-gray-600">{t('schedule.noneEveryDay')}</span>
             </div>
           )}
-
-          <div className="flex flex-wrap items-center gap-2">
-            <select
-              value={draft.action.type}
-              onChange={(e) => {
-                const type = e.target.value as ScheduleAction['type']
-                setAction(
-                  type === 'wallpaper'
-                    ? { type, wallpaperId: '' }
-                    : type === 'playlist'
-                      ? { type, playlistId: playlists[0]?.id ?? '' }
-                      : { type }
-                )
-              }}
-              className={inputClass}
-            >
-              <option value="wallpaper">{t('schedule.showWallpaper')}</option>
-              <option value="playlist">{t('schedule.playPlaylist')}</option>
-              <option value="stop">{t('schedule.stop')}</option>
-            </select>
-            {perScreen && (
-              <ScreenSelect targets={targets} value={draft.screen} onChange={(screen) => { setDraft({ ...draft, screen }); }} />
-            )}
-          </div>
-
-          {draft.action.type === 'playlist' && (
-            <select
-              value={draft.action.playlistId}
-              onChange={(e) => { setAction({ type: 'playlist', playlistId: e.target.value }); }}
-              className={`${inputClass} w-full`}
-            >
-              {playlists.map((p) => (
-                <option key={p.id} value={p.id}>
-                  {p.title}
-                </option>
-              ))}
-            </select>
-          )}
-
-          {draft.action.type === 'wallpaper' && (
-            <div className="space-y-1.5">
-              <input
-                value={wallpaperFilter}
-                onChange={(e) => { setWallpaperFilter(e.target.value) }}
-                placeholder={t('schedule.searchLibrary')}
-                className={`${inputClass} w-full`}
-              />
-              <select
-                value={draft.action.wallpaperId}
-                onChange={(e) => { setAction({ type: 'wallpaper', wallpaperId: e.target.value }); }}
-                size={6}
-                className={`${inputClass} w-full`}
-              >
-                {wallpaperOptions.map((w) => (
-                  <option key={w.id} value={w.id}>
-                    {w.title}
-                  </option>
-                ))}
-              </select>
-            </div>
-          )}
-
-          <div className="flex gap-2">
-            <button onClick={() => void save()} className="rounded-lg bg-accent-600 px-4 py-2 text-sm font-medium text-white hover:bg-accent-500">
-              {t('common.save')}
-            </button>
-            <button onClick={() => { setDraft(null) }} className="rounded-lg bg-fg/5 px-4 py-2 text-sm text-gray-300 hover:bg-fg/10">
-              {t('common.cancel')}
-            </button>
-          </div>
-        </div>
+        </RuleEditor>
       )}
     </div>
   )

+ 27 - 6
src/renderer/src/components/settings/SettingsTabs.tsx

@@ -1,7 +1,20 @@
-import { Cpu, Library, Monitor, Palette, Settings, Gauge, Wrench, type LucideIcon } from 'lucide-react'
+import { useSyncExternalStore } from 'react'
+import { Cpu, Library, Monitor, Palette, Settings, Gauge, Clapperboard, Wrench, type LucideIcon } from 'lucide-react'
+import ResizableWidth from '../common/ResizableWidth'
 import { t } from '../../i18n'
 
-export type SettingsTab = 'appearance' | 'library' | 'engine' | 'display' | 'performance' | 'system' | 'troubleshooting'
+const wideQuery = window.matchMedia('(min-width: 768px)')
+
+function subscribeWide(listener: () => void): () => void {
+  wideQuery.addEventListener('change', listener)
+  return () => { wideQuery.removeEventListener('change', listener) }
+}
+
+function useWideLayout(): boolean {
+  return useSyncExternalStore(subscribeWide, () => wideQuery.matches)
+}
+
+export type SettingsTab = 'appearance' | 'library' | 'engine' | 'display' | 'performance' | 'videoDefaults' | 'system' | 'troubleshooting'
 
 const TABS: { id: SettingsTab; icon: LucideIcon }[] = [
   { id: 'appearance', icon: Palette },
@@ -9,6 +22,7 @@ const TABS: { id: SettingsTab; icon: LucideIcon }[] = [
   { id: 'engine', icon: Cpu },
   { id: 'display', icon: Monitor },
   { id: 'performance', icon: Gauge },
+  { id: 'videoDefaults', icon: Clapperboard },
   { id: 'system', icon: Settings },
   { id: 'troubleshooting', icon: Wrench }
 ]
@@ -32,11 +46,12 @@ export function saveSettingsTab(tab: SettingsTab): void {
 }
 
 export default function SettingsTabs({ active, onChange }: { active: SettingsTab; onChange: (tab: SettingsTab) => void }) {
-  return (
+  const wide = useWideLayout()
+  const nav = (
     <nav
       role="tablist"
       aria-orientation="vertical"
-      className="flex shrink-0 gap-1 overflow-x-auto px-4 pb-2 pt-4 md:w-52 md:flex-col md:overflow-x-visible md:border-r md:border-fg/5 md:px-3 md:pb-4"
+      className="flex shrink-0 gap-1 overflow-x-auto px-4 pb-2 pt-4 md:w-full md:flex-col md:overflow-x-visible md:border-r md:border-fg/5 md:px-3 md:pb-4"
     >
       <h2 className="hidden px-3 pb-3 text-lg font-semibold text-gray-100 md:block">{t('nav.settings')}</h2>
       {TABS.map(({ id, icon: Icon }) => {
@@ -54,11 +69,17 @@ export default function SettingsTabs({ active, onChange }: { active: SettingsTab
                 : 'text-gray-400 hover:bg-fg/5 hover:text-gray-200')
             }
           >
-            <Icon size={18} strokeWidth={selected ? 2.2 : 1.8} />
-            <span className="whitespace-nowrap">{t(`settings.tab.${id}`)}</span>
+            <Icon size={18} strokeWidth={selected ? 2.2 : 1.8} className="shrink-0" />
+            <span className="whitespace-nowrap md:whitespace-normal">{t(`settings.tab.${id}`)}</span>
           </button>
         )
       })}
     </nav>
   )
+  if (!wide) return nav
+  return (
+    <ResizableWidth storageKey="we-settings-tabs-width" defaultWidth={208} min={160} max={400} edge="right">
+      {nav}
+    </ResizableWidth>
+  )
 }

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

@@ -15,9 +15,14 @@ import FontSettings from './FontSettings'
 import LedSettings from './LedSettings'
 import LoaderSettings from './LoaderSettings'
 import ScheduleSettings from './ScheduleSettings'
+import AppRuleSettings from './AppRuleSettings'
+import ProfileSettings from './ProfileSettings'
+import AudioInputSettings from './AudioInputSettings'
 import UpdateSettings from './UpdateSettings'
 import DiagnosticsSettings from './DiagnosticsSettings'
+import VideoToolsSettings from './VideoToolsSettings'
 import SettingsCard from './SettingsCard'
+import VideoDefaultsSettings from './VideoDefaultsSettings'
 import SettingsTabs, { loadSettingsTab, saveSettingsTab, type SettingsTab } from './SettingsTabs'
 import CopyField from '../common/CopyField'
 import { useToast } from '../common/Toast'
@@ -93,6 +98,9 @@ function SettingsPanels({ onReset }: { onReset: () => void }) {
   const [killLweOnQuit, setKillLweOnQuit] = useState(false)
   const [skipPlaylistResume, setSkipPlaylistResume] = useState(false)
   const [freshProcessOnPathChange, setFreshProcessOnPathChange] = useState(false)
+  const [stopPlaylistsOnKillAll, setStopPlaylistsOnKillAll] = useState(false)
+  const [forgetOnKillAll, setForgetOnKillAll] = useState(false)
+  const [desktopIconsAuto, setDesktopIconsAuto] = useState(true)
   const [steamIdentity, setSteamIdentityState] = useState<SteamIdentity>('wallpaper-engine')
   const [steamIdentitySaved, setSteamIdentitySaved] = useState(false)
   const [autostartSupported, setAutostartSupported] = useState(false)
@@ -128,6 +136,8 @@ function SettingsPanels({ onReset }: { onReset: () => void }) {
       setKillLweOnQuit(cfg.killLweOnQuit)
       setSkipPlaylistResume(cfg.skipPlaylistResume)
       setFreshProcessOnPathChange(cfg.freshProcessOnPathChange)
+      setStopPlaylistsOnKillAll(cfg.stopPlaylistsOnKillAll)
+      setForgetOnKillAll(cfg.forgetOnKillAll)
       setSteamIdentityState(cfg.steamIdentity)
       setAutostartSupported(cfg.autostartSupported)
       setAutostartCompositorLine(cfg.autostartCompositorLine)
@@ -144,6 +154,7 @@ function SettingsPanels({ onReset }: { onReset: () => void }) {
     window.electronAPI.lwe.detectDistro().then(setDistro).catch(console.error)
     window.electronAPI.lwe.prebuiltTarget().then(setPrebuiltTarget).catch(console.error)
     window.electronAPI.desktopIcons.getEnabled().then(setDesktopIconsEnabled).catch(console.error)
+    window.electronAPI.desktopIcons.getAuto().then(setDesktopIconsAuto).catch(console.error)
     window.electronAPI.desktopIcons.getStatus().then(setDesktopIconsStatus).catch(console.error)
     window.electronAPI.playlist.getAll().then((all) => { setPlaylists(all.map((p) => ({ id: p.id, title: p.title }))); }).catch(console.error)
     window.electronAPI.lwe.listScreens().then(setScreens).catch(console.error)
@@ -343,6 +354,24 @@ function SettingsPanels({ onReset }: { onReset: () => void }) {
     await window.electronAPI.config.setKillLweOnQuit(newVal)
   }
 
+  async function handleStopPlaylistsOnKillAllToggle() {
+    const newVal = !stopPlaylistsOnKillAll
+    setStopPlaylistsOnKillAll(newVal)
+    await window.electronAPI.config.setStopPlaylistsOnKillAll(newVal)
+  }
+
+  async function handleForgetOnKillAllToggle() {
+    const newVal = !forgetOnKillAll
+    setForgetOnKillAll(newVal)
+    await window.electronAPI.config.setForgetOnKillAll(newVal)
+  }
+
+  async function handleDesktopIconsAutoToggle() {
+    const newVal = !desktopIconsAuto
+    setDesktopIconsAuto(newVal)
+    await window.electronAPI.desktopIcons.setAuto(newVal)
+  }
+
   async function handleSkipPlaylistResumeToggle() {
     const newVal = !skipPlaylistResume
     setSkipPlaylistResume(newVal)
@@ -452,6 +481,12 @@ function SettingsPanels({ onReset }: { onReset: () => void }) {
           </div>
         )}
 
+        {tab === 'videoDefaults' && (
+          <div className="settings-sections max-w-lg">
+            <VideoDefaultsSettings />
+          </div>
+        )}
+
         {tab === 'library' && (
           <div className="settings-sections max-w-lg">
             <div>
@@ -842,6 +877,16 @@ function SettingsPanels({ onReset }: { onReset: () => void }) {
                   </span>
                 </label>
 
+                <label className="mt-3 flex items-center gap-3 cursor-pointer">
+                  <Toggle on={stopPlaylistsOnKillAll} onClick={() => void handleStopPlaylistsOnKillAllToggle()} />
+                  <span className="text-sm text-gray-300">{t('settings.stopPlaylistsOnKillAll')}</span>
+                </label>
+
+                <label className="mt-3 flex items-center gap-3 cursor-pointer">
+                  <Toggle on={forgetOnKillAll} onClick={() => void handleForgetOnKillAllToggle()} />
+                  <span className="text-sm text-gray-300">{t('settings.forgetOnKillAll')}</span>
+                </label>
+
                 <label className="mt-3 flex items-center gap-3 cursor-pointer">
                   <Toggle on={skipPlaylistResume} onClick={() => void handleSkipPlaylistResumeToggle()} />
                   <span className="text-sm text-gray-300">{t('settings.skipPlaylistResume')}</span>
@@ -982,6 +1027,11 @@ function SettingsPanels({ onReset }: { onReset: () => void }) {
                   {desktopIconsEnabled ? t('settings.desktopIconsOn') : t('settings.desktopIconsOff')}
                 </span>
               </label>
+              <label className="mt-3 flex items-center gap-3 cursor-pointer">
+                <Toggle on={desktopIconsAuto} onClick={() => void handleDesktopIconsAutoToggle()} />
+                <span className="text-sm text-gray-300">{t('settings.desktopIconsAuto')}</span>
+              </label>
+              <p className="mt-1 text-xs text-gray-600">{t('settings.desktopIconsAutoHint')}</p>
               {desktopIconsStatus?.problem && (
                 <p className="mt-2 text-xs text-amber-400">
                   {t(`settings.desktopIcons_${desktopIconsStatus.problem}`)}
@@ -1118,6 +1168,12 @@ function SettingsPanels({ onReset }: { onReset: () => void }) {
 
             <AutomuteIgnoreSettings />
 
+            <AudioInputSettings />
+
+            <ProfileSettings />
+
+            <AppRuleSettings />
+
             <ScheduleSettings />
           </div>
         )}
@@ -1212,6 +1268,8 @@ function SettingsPanels({ onReset }: { onReset: () => void }) {
               <p className="text-xs text-gray-600">{t('settings.scriptLimitsHint')}</p>
             </SettingsCard>
 
+            <VideoToolsSettings />
+
             <DiagnosticsSettings />
 
             <SettingsCard title={t('settings.resetTitle')} hint={t('settings.resetHint')}>

+ 172 - 0
src/renderer/src/components/settings/VideoDefaultsSettings.tsx

@@ -0,0 +1,172 @@
+import { useEffect, useRef, useState } from 'react'
+import {
+  CRF_MAX,
+  CRF_MIN,
+  ENCODER_LABELS,
+  ENCODER_RANKING,
+  FPS_MAX,
+  FPS_TARGETS,
+  normalizeFps,
+  SCALE_TARGETS,
+  TRIM_MODES,
+  type HevcEncoder,
+  type ScaleMode,
+  type ScaleTarget,
+  type TrimMode,
+  type VideoToolSettings
+} from '@shared/video-tools'
+import SettingsCard from './SettingsCard'
+import Toggle from '../common/Toggle'
+import { inputClass } from '../common/inputClass'
+import { t } from '../../i18n'
+
+export default function VideoDefaultsSettings() {
+  const [settings, setSettings] = useState<VideoToolSettings | null>(null)
+  const latest = useRef<VideoToolSettings | null>(null)
+  const sent = useRef(0)
+  const [fpsCustom, setFpsCustom] = useState(false)
+  const [fpsText, setFpsText] = useState('')
+
+  useEffect(() => {
+    void window.electronAPI.videoTools
+      .getSettings()
+      .then((value) => {
+        latest.current = value
+        setSettings(value)
+        if (value.maxFps && !FPS_TARGETS.includes(value.maxFps)) {
+          setFpsCustom(true)
+          setFpsText(String(value.maxFps))
+        }
+      })
+      .catch(console.error)
+  }, [])
+
+  function change(patch: Partial<VideoToolSettings>) {
+    if (!latest.current) return
+    const next = { ...latest.current, ...patch }
+    latest.current = next
+    setSettings(next)
+    const mine = ++sent.current
+    void window.electronAPI.videoTools
+      .setSettings(next)
+      .then((saved) => {
+        if (mine !== sent.current) return
+        latest.current = saved
+        setSettings(saved)
+      })
+      .catch(console.error)
+  }
+
+  if (!settings) return null
+
+  return (
+    <SettingsCard title={t('videoDefaults.title')} hint={t('videoDefaults.hint')}>
+      <div>
+        <label className="flex cursor-pointer items-center gap-3">
+          <Toggle on={settings.backupOriginal} onClick={() => { change({ backupOriginal: !settings.backupOriginal }) }} />
+          <span className="text-sm text-gray-300">{t('videoDefaults.backup')}</span>
+        </label>
+        <p className="mt-1 pl-12 text-xs text-gray-600">{t('videoDefaults.backupHint')}</p>
+      </div>
+
+      <div className="flex items-center gap-2 text-sm text-gray-300">
+        <span>{t('optimize.encoder')}</span>
+        <select value={settings.encoder} onChange={(e) => { change({ encoder: e.target.value as HevcEncoder | 'auto' }) }} className={inputClass}>
+          <option value="auto">{t('optimize.auto')}</option>
+          {ENCODER_RANKING.map((encoder) => <option key={encoder} value={encoder}>{ENCODER_LABELS[encoder]}</option>)}
+        </select>
+      </div>
+
+      <div>
+        <div className="flex items-center gap-2 text-sm text-gray-300">
+          <span>{t('optimize.quality')}</span>
+          <input
+            type="range"
+            min={CRF_MIN}
+            max={CRF_MAX}
+            step={1}
+            value={settings.crf}
+            onChange={(e) => { change({ crf: Number(e.target.value) }) }}
+            className="w-40"
+          />
+          <span className="w-6 text-right tabular-nums">{settings.crf}</span>
+        </div>
+        <p className="mt-1 text-xs text-gray-600">{t('optimize.qualityHint', { min: CRF_MIN, max: CRF_MAX })}</p>
+      </div>
+
+      <div>
+        <div className="flex flex-wrap items-center gap-2 text-sm text-gray-300">
+          <span>{t('videoDefaults.scaleTo')}</span>
+          <select value={settings.scaleTo} onChange={(e) => { change({ scaleTo: e.target.value as ScaleTarget }) }} className={inputClass}>
+            <option value="none">{t('videoDefaults.scaleNone')}</option>
+            {(Object.keys(SCALE_TARGETS) as Exclude<ScaleTarget, 'none'>[]).map((key) => (
+              <option key={key} value={key}>{`${SCALE_TARGETS[key].label} (${t('optimize.dimensions', { width: SCALE_TARGETS[key].width, height: SCALE_TARGETS[key].height })})`}</option>
+            ))}
+          </select>
+          {settings.scaleTo !== 'none' && (
+            <span className="flex gap-3 text-xs">
+              {(['fit', 'fill'] as ScaleMode[]).map((mode) => (
+                <label key={mode} className="flex items-center gap-1.5">
+                  <input type="radio" checked={settings.scaleMode === mode} onChange={() => { change({ scaleMode: mode }) }} />
+                  {t(mode === 'fit' ? 'optimize.fit' : 'optimize.fill')}
+                </label>
+              ))}
+            </span>
+          )}
+        </div>
+        <p className="mt-1 text-xs text-gray-600">{t('videoDefaults.scaleHint')}</p>
+      </div>
+
+      <div>
+        <div className="flex items-center gap-2 text-sm text-gray-300">
+          <span>{t('videoDefaults.fps')}</span>
+          <select
+            value={fpsCustom ? 'custom' : settings.maxFps}
+            onChange={(e) => {
+              const custom = e.target.value === 'custom'
+              setFpsCustom(custom)
+              if (custom) {
+                setFpsText(String(settings.maxFps || 30))
+                change({ maxFps: settings.maxFps || 30 })
+              } else {
+                change({ maxFps: Number(e.target.value) })
+              }
+            }}
+            className={inputClass}
+          >
+            <option value={0}>{t('videoDefaults.fpsNone')}</option>
+            {FPS_TARGETS.map((n) => <option key={n} value={n}>{t('optimize.fpsValue', { fps: n })}</option>)}
+            <option value="custom">{t('optimize.custom')}</option>
+          </select>
+          {fpsCustom && (
+            <span className="flex items-center gap-1">
+              <input
+                value={fpsText}
+                onChange={(e) => {
+                  const text = e.target.value.replace(/\D/g, '').slice(0, 3)
+                  setFpsText(text)
+                  const n = normalizeFps(Number(text))
+                  if (n) change({ maxFps: n })
+                }}
+                className={`${inputClass} w-16`}
+              />
+              {t('optimize.fpsUnit')}
+            </span>
+          )}
+        </div>
+        <p className="mt-1 text-xs text-gray-600">{t('videoDefaults.fpsHint')}</p>
+        {fpsCustom && !normalizeFps(Number(fpsText)) && <p className="mt-1 text-xs text-red-400">{t('videoDefaults.fpsInvalid', { max: FPS_MAX })}</p>}
+      </div>
+
+      <div>
+        <div className="flex items-center gap-2 text-sm text-gray-300">
+          <span>{t('videoDefaults.trim')}</span>
+          <select value={settings.trimMode} onChange={(e) => { change({ trimMode: e.target.value as TrimMode }) }} className={inputClass}>
+            {TRIM_MODES.map((mode) => <option key={mode} value={mode}>{t(`videoDefaults.trim.${mode}`)}</option>)}
+          </select>
+        </div>
+        <p className="mt-1 text-xs text-gray-600">{t('videoDefaults.trimHint')}</p>
+      </div>
+    </SettingsCard>
+  )
+}

+ 77 - 0
src/renderer/src/components/settings/VideoToolsSettings.tsx

@@ -0,0 +1,77 @@
+import { useEffect, useState } from 'react'
+import { Download, Loader2, Trash2 } from 'lucide-react'
+import { ENCODER_LABELS, type OptimizeProgress, type VideoToolsStatus } from '@shared/video-tools'
+import SettingsCard from './SettingsCard'
+import { ProgressBar } from '../common/GridCard'
+import { t } from '../../i18n'
+
+export default function VideoToolsSettings() {
+  const [status, setStatus] = useState<VideoToolsStatus | null>(null)
+  const [busy, setBusy] = useState(false)
+  const [progress, setProgress] = useState<OptimizeProgress | null>(null)
+  const [error, setError] = useState('')
+
+  function refresh() {
+    void window.electronAPI.videoTools.status().then(setStatus).catch(console.error)
+  }
+
+  useEffect(() => {
+    void window.electronAPI.videoTools.status().then(setStatus).catch(console.error)
+    return window.electronAPI.on.videoToolsProgress((p) => { if (p.itemId === 'ffmpeg') setProgress(p) })
+  }, [])
+
+  async function act(action: () => Promise<unknown>) {
+    setBusy(true)
+    setError('')
+    setProgress(null)
+    try {
+      await action()
+    } catch (err) {
+      setError((err as Error).message)
+    } finally {
+      setBusy(false)
+      refresh()
+    }
+  }
+
+  return (
+    <SettingsCard title={t('optimize.settingsTitle')} hint={t('optimize.settingsHint')}>
+      <p className="text-xs text-gray-400">
+        {status === null
+          ? '...'
+          : status.encoders.length === 0
+            ? t('optimize.noEncoder')
+            : t('optimize.encodersFound', { list: status.encoders.map((o) => ENCODER_LABELS[o.encoder]).join(', ') })}
+      </p>
+      {busy && (
+        <div className="space-y-1">
+          <p className="text-xs text-gray-400">{progress?.message}</p>
+          <ProgressBar percentage={progress?.percentage ?? 0} className="h-1.5 rounded bg-fg/10" />
+        </div>
+      )}
+      <div className="flex gap-2">
+        {status?.canDownload && !status.downloaded && (
+          <button
+            onClick={() => void act(() => window.electronAPI.videoTools.download())}
+            disabled={busy}
+            className="flex items-center gap-2 rounded-lg bg-accent-500/15 px-4 py-2 text-sm text-accent-300 hover:bg-accent-500/25 disabled:opacity-50"
+          >
+            {busy ? <Loader2 size={14} className="animate-spin" /> : <Download size={14} />}
+            {t('optimize.download')}
+          </button>
+        )}
+        {status?.downloaded && (
+          <button
+            onClick={() => void act(() => window.electronAPI.videoTools.remove())}
+            disabled={busy}
+            className="flex items-center gap-2 rounded-lg bg-fg/5 px-4 py-2 text-sm text-gray-300 hover:bg-fg/10 disabled:opacity-50"
+          >
+            <Trash2 size={14} />
+            {t('optimize.removeDownloaded')}
+          </button>
+        )}
+      </div>
+      {error && <p className="text-xs text-red-400">{error}</p>}
+    </SettingsCard>
+  )
+}

+ 11 - 11
src/renderer/src/components/workshop/WorkshopCard.tsx

@@ -67,6 +67,12 @@ export default function WorkshopCard({
     }
   }
 
+  const downloadBar =
+    subscribeState === 'downloading' && downloadPercentage != null ? (
+      <ProgressBar percentage={downloadPercentage} className="absolute bottom-0 left-0 right-0 h-1 bg-black/40" />
+    ) : null
+  const stats = `${t('workshop.subscribers', { count: item.subscriptions, formatted: formatNumber(item.subscriptions) })}${fileSizeLabel ? ` · ${fileSizeLabel}` : ''}`
+
   const controls = (
     <>
     {canPlay && (
@@ -123,17 +129,14 @@ export default function WorkshopCard({
       >
         <div className="relative w-20 shrink-0">
           <CardPreview src={item.previewUrl} alt={item.title} dimmed={ignored} />
-          {subscribeState === 'downloading' && downloadPercentage != null && (
-            <ProgressBar percentage={downloadPercentage} className="absolute bottom-0 left-0 right-0 h-1 bg-black/40" />
-          )}
+          {downloadBar}
         </div>
         <div className="min-w-0 flex-1 px-3 py-1">
           <h3 className="truncate text-sm font-medium text-gray-200" title={item.title}>
             {item.title}
           </h3>
           <p className="truncate text-[11px] text-gray-500">
-            {t('workshop.subscribers', { count: item.subscriptions, formatted: formatNumber(item.subscriptions) })}
-            {fileSizeLabel ? ` · ${fileSizeLabel}` : ''}
+            {stats}
             {ignored ? ` · ${t('workshop.ignored')}` : ''}
           </p>
         </div>
@@ -162,9 +165,7 @@ export default function WorkshopCard({
             {t('workshop.ignored')}
           </div>
         )}
-        {subscribeState === 'downloading' && downloadPercentage != null && (
-          <ProgressBar percentage={downloadPercentage} className="absolute bottom-0 left-0 right-0 h-1 bg-black/40" />
-        )}
+        {downloadBar}
         {subscribeState === 'download-error' && (
           <button
             onClick={handleSubscribe}
@@ -194,11 +195,10 @@ export default function WorkshopCard({
         </h3>
         {!tiny && (
           <p className="mt-1 text-xs text-gray-500">
-            {t('workshop.subscribers', { count: item.subscriptions, formatted: formatNumber(item.subscriptions) })}
-            {fileSizeLabel ? ` · ${fileSizeLabel}` : ''}
+            {stats}
           </p>
         )}
-        <div className={clsx('flex items-center justify-center gap-1.5', tiny ? 'mt-1.5' : 'mt-2')}>
+        <div className={clsx('flex items-center justify-start gap-1.5', tiny ? 'mt-1.5' : 'mt-2')}>
           <LikeAction id={item.publishedFileId} isLiked={steam.isLiked} compact={tiny} />
           <SteamAction id={item.publishedFileId} compact={tiny} />
         </div>

+ 8 - 1
src/renderer/src/constants/engineFlags.ts

@@ -19,7 +19,14 @@ type ChoiceFlag =
 // kdeBackgroundLayer, windowed and windowBackground are global only
 type BooleanFlag = Exclude<
   keyof EngineFlags,
-  'fullscreenPause' | 'kdeBackgroundLayer' | 'windowed' | 'windowBackground' | ChoiceFlag
+  | 'fullscreenPause'
+  | 'kdeBackgroundLayer'
+  | 'windowed'
+  | 'windowBackground'
+  | 'audioInput'
+  | 'audioInputVolume'
+  | 'audioInputThreshold'
+  | ChoiceFlag
 >
 
 export const BOOLEAN_FLAGS: { key: BooleanFlag; label: MessageKey; hint?: MessageKey }[] = [

+ 19 - 0
src/renderer/src/hooks/externalStore.ts

@@ -0,0 +1,19 @@
+import { useSyncExternalStore } from 'react'
+
+export function createStore<T extends object>(initial: T) {
+  let state = initial
+  const listeners = new Set<() => void>()
+  const subscribe = (listener: () => void) => {
+    listeners.add(listener)
+    return () => { listeners.delete(listener) }
+  }
+  return {
+    get: () => state,
+    update(next: Partial<T>) {
+      state = { ...state, ...next }
+      listeners.forEach((l) => { l() })
+    },
+    use: () => useSyncExternalStore(subscribe, () => state),
+    useSelect: <S>(select: (state: T) => S) => useSyncExternalStore(subscribe, () => select(state))
+  }
+}

+ 21 - 1
src/renderer/src/hooks/queries.ts

@@ -1,6 +1,6 @@
 import { useEffect, useMemo, useState } from 'react'
 import { useQuery, useQueryClient } from '@tanstack/react-query'
-import type { LweInstallProgress, WallpaperFolder } from '@shared/types'
+import type { LweInstallProgress, WallpaperFolder, WallpaperMeta } from '@shared/types'
 import { t } from '../i18n'
 
 export function useConfig() {
@@ -79,6 +79,18 @@ export function useAllWallpapers() {
   return data
 }
 
+export function useWallpaperPicker(search: string, keep: (wallpaper: WallpaperMeta) => boolean) {
+  const { data: wallpapers = [], isLoading } = useQuery({
+    queryKey: ['library', { sortBy: 'title', sortDir: 'asc' }],
+    queryFn: () => window.electronAPI.library.getAll({ sortBy: 'title', sortDir: 'asc' })
+  })
+  const matches = useMemo(() => {
+    const q = search.trim().toLowerCase()
+    return wallpapers.filter((w) => keep(w) && (!q || w.title.toLowerCase().includes(q)))
+  }, [wallpapers, search, keep])
+  return { matches, isLoading }
+}
+
 export function usePlaylists() {
   const { data = [] } = useQuery({
     queryKey: ['playlists'],
@@ -87,6 +99,14 @@ export function usePlaylists() {
   return data
 }
 
+export function useProfiles() {
+  const { data = [] } = useQuery({
+    queryKey: ['profiles'],
+    queryFn: () => window.electronAPI.profiles.getAll()
+  })
+  return data
+}
+
 export function usePlaybackStates() {
   const queryClient = useQueryClient()
   const { data = [] } = useQuery({

+ 53 - 0
src/renderer/src/hooks/useBackgroundOptimize.ts

@@ -0,0 +1,53 @@
+import { createStore } from './externalStore'
+import type { OptimizeResult } from '@shared/video-tools'
+
+interface BackgroundState {
+  id: string | null
+  phase: 'running' | 'review' | null
+  percent: number
+  result: OptimizeResult | null
+  error: string | null
+  finishing: boolean
+}
+
+const idle: BackgroundState = { id: null, phase: null, percent: 0, result: null, error: null, finishing: false }
+
+// Outside React so a job handed over from the dialog keeps going after the dialog is gone.
+const store = createStore<BackgroundState>(idle)
+let cancelRequested = false
+
+export function detachOptimize(id: string, job: Promise<OptimizeResult>) {
+  cancelRequested = false
+  store.update({ ...idle, id, phase: 'running' })
+  const off = window.electronAPI.on.videoToolsProgress((p) => {
+    if (p.itemId === id && p.stage === 'encoding') store.update({ percent: p.percentage })
+  })
+  job.then(
+    (result) => { store.update({ phase: 'review', result }) },
+    (err: Error) => { store.update(cancelRequested ? idle : { ...idle, error: err.message }) }
+  ).finally(off)
+}
+
+export function cancelBackgroundOptimize() {
+  cancelRequested = true
+  void window.electronAPI.videoTools.cancel()
+}
+
+export async function finishBackgroundOptimize(keep: boolean, onDone: () => void) {
+  const { id, finishing } = store.get()
+  if (!id || finishing) return
+  store.update({ finishing: true })
+  try {
+    await window.electronAPI.videoTools.finish(id, keep)
+    store.update(idle)
+    if (keep) onDone()
+  } catch (err) {
+    store.update({ finishing: false, error: (err as Error).message })
+  }
+}
+
+export function dismissBackgroundError() {
+  if (store.get().phase === null) store.update({ error: null })
+}
+
+export const useBackgroundOptimize = store.use

+ 27 - 0
src/renderer/src/hooks/useFontAdd.ts

@@ -0,0 +1,27 @@
+import { useState } from 'react'
+import { useQueryClient } from '@tanstack/react-query'
+import { t } from '../i18n'
+
+export function useFontAdd(addedMessage: (count: number) => string) {
+  const queryClient = useQueryClient()
+  const [status, setStatus] = useState<string | null>(null)
+
+  async function refresh() {
+    await queryClient.invalidateQueries({ queryKey: ['user-fonts'] })
+    await queryClient.invalidateQueries({ queryKey: ['lwe-fonts'] })
+  }
+
+  async function add() {
+    const result = await window.electronAPI.fonts.add()
+    setStatus(
+      result.rejected.length > 0
+        ? t('fonts.rejected', { files: result.rejected.join(', ') })
+        : result.added.length > 0
+          ? addedMessage(result.added.length)
+          : null
+    )
+    await refresh()
+  }
+
+  return { status, setStatus, add, refresh }
+}

+ 34 - 0
src/renderer/src/hooks/useLibraryTasks.ts

@@ -0,0 +1,34 @@
+import { createStore } from './externalStore'
+
+export type LibraryTask = 'scan-library' | 'backup-selection' | 'scan-backups' | 'check-unavailable' | 'backup-unavailable' | 'verify-files'
+
+interface TaskState {
+  running: ReadonlySet<LibraryTask>
+  status: string | null
+}
+
+// Lives outside the component so a task started in the library view still shows as running,
+// and its result still lands, after switching to another view and back.
+const store = createStore<TaskState>({ running: new Set(), status: null })
+const update = store.update
+
+export function setLibraryTaskStatus(status: string | null) {
+  update({ status })
+}
+
+export function clearFinishedLibraryTaskStatus() {
+  if (store.get().running.size === 0) update({ status: null })
+}
+
+export async function runLibraryTask(task: LibraryTask, work: () => Promise<string>) {
+  update({ running: new Set(store.get().running).add(task), status: null })
+  try {
+    setLibraryTaskStatus(await work())
+  } finally {
+    const running = new Set(store.get().running)
+    running.delete(task)
+    update({ running })
+  }
+}
+
+export const useLibraryTasks = store.use

+ 87 - 0
src/renderer/src/hooks/useQuickOptimize.ts

@@ -0,0 +1,87 @@
+import { createStore } from './externalStore'
+import type { QuickLine, QuickProgress, QuickTrim } from '@shared/video-tools'
+import { formatFileSize } from '../utils/format'
+import { t } from '../i18n'
+
+interface QuickState {
+  running: boolean
+  progress: QuickProgress | null
+  percent: number
+  lines: QuickLine[]
+  summary: string | null
+  error: string | null
+  question: QuickTrim[] | null
+}
+
+export type TrimAnswer = 'trim' | 'keep' | 'cancel'
+
+// Outside React so the run, its progress and its result survive switching views.
+const store = createStore<QuickState>({ running: false, progress: null, percent: 0, lines: [], summary: null, error: null, question: null })
+let answerTrim: ((answer: TrimAnswer) => void) | null = null
+const update = store.update
+
+export function dismissQuickOptimize() {
+  if (!store.get().running) update({ lines: [], summary: null, error: null })
+}
+
+export function answerQuickTrim(answer: TrimAnswer) {
+  answerTrim?.(answer)
+}
+
+function askAboutTrim(items: QuickTrim[]): Promise<TrimAnswer> {
+  return new Promise((resolve) => {
+    answerTrim = (answer) => {
+      answerTrim = null
+      update({ question: null })
+      resolve(answer)
+    }
+    update({ question: items, lines: [], summary: null, error: null })
+  })
+}
+
+let preparing = false
+
+export async function runQuickOptimize(ids: string[], onDone: () => void) {
+  if (preparing || store.get().running || store.get().question || ids.length === 0) return
+  preparing = true
+  let trim = false
+  try {
+    const { trimMode } = await window.electronAPI.videoTools.getSettings()
+    const trimmed = trimMode === 'never' ? [] : await window.electronAPI.videoTools.quickTrims(ids)
+    if (trimmed.length > 0) {
+      const answer = trimMode === 'ask' ? await askAboutTrim(trimmed) : 'trim'
+      if (answer === 'cancel') return
+      trim = answer === 'trim'
+    }
+  } catch (err) {
+    update({ lines: [], summary: null, error: (err as Error).message })
+    return
+  } finally {
+    preparing = false
+  }
+  update({ running: true, progress: null, percent: 0, lines: [], summary: null, error: null })
+  const offQuick = window.electronAPI.on.videoToolsQuick((progress) => { update({ progress, percent: 0 }) })
+  const offProgress = window.electronAPI.on.videoToolsProgress((p) => {
+    if (p.itemId === store.get().progress?.id && p.stage === 'encoding') update({ percent: p.percentage })
+  })
+  try {
+    const report = await window.electronAPI.videoTools.quick(ids, trim)
+    const summary =
+      report.optimized === 0
+        ? null
+        : report.originalsKept
+          ? t('quick.doneKept', { count: report.optimized, size: formatFileSize(report.savedBytes) ?? '' })
+          : t('quick.done', { count: report.optimized, size: formatFileSize(report.savedBytes) ?? '' })
+    update({ lines: report.lines, summary })
+  } catch (err) {
+    update({ lines: [], summary: null, error: (err as Error).message })
+  } finally {
+    offQuick()
+    offProgress()
+    update({ running: false, progress: null, percent: 0 })
+    onDone()
+  }
+}
+
+export const useQuickOptimize = store.use
+export const useQuickOptimizeRunning = (): boolean => store.useSelect((s) => s.running)

+ 15 - 14
src/renderer/src/hooks/useSelectableGrid.ts

@@ -62,17 +62,21 @@ export function useSelectableGrid({ ids, dataAttr, onOpenDetail }: UseSelectable
     [ids, lastClickedId, onOpenDetail]
   )
 
+  const gridPoint = useCallback((e: React.MouseEvent) => {
+    const container = gridRef.current
+    if (!container) return null
+    const rect = container.getBoundingClientRect()
+    return { x: e.clientX - rect.left + container.scrollLeft, y: e.clientY - rect.top + container.scrollTop }
+  }, [])
+
   const handleMarqueeStart = useCallback(
     (e: React.MouseEvent) => {
       if ((e.target as HTMLElement).closest(`[${dataAttr}]`)) return
       if (e.button !== 0) return
 
-      const container = gridRef.current
-      if (!container) return
-
-      const rect = container.getBoundingClientRect()
-      const x = e.clientX - rect.left + container.scrollLeft
-      const y = e.clientY - rect.top + container.scrollTop
+      const point = gridPoint(e)
+      if (!point) return
+      const { x, y } = point
 
       marqueeActive.current = true
       setMarquee({ startX: x, startY: y, endX: x, endY: y })
@@ -81,23 +85,20 @@ export function useSelectableGrid({ ids, dataAttr, onOpenDetail }: UseSelectable
         setSelectedIds(new Set())
       }
     },
-    [dataAttr]
+    [dataAttr, gridPoint]
   )
 
   const handleMarqueeMove = useCallback(
     (e: React.MouseEvent) => {
       if (!marqueeActive.current || !marquee) return
 
-      const container = gridRef.current
-      if (!container) return
-
-      const rect = container.getBoundingClientRect()
-      const x = e.clientX - rect.left + container.scrollLeft
-      const y = e.clientY - rect.top + container.scrollTop
+      const point = gridPoint(e)
+      if (!point) return
+      const { x, y } = point
 
       setMarquee((prev) => (prev ? { ...prev, endX: x, endY: y } : null))
     },
-    [marquee]
+    [marquee, gridPoint]
   )
 
   const handleMarqueeEnd = useCallback(() => {

+ 4 - 0
src/renderer/src/utils/wallpaper.ts

@@ -8,6 +8,10 @@ export function isPlayable(w: Pick<WallpaperMeta, 'localPath' | 'downloading' |
   return !!w.localPath && !w.downloading && !w.downloadFailed
 }
 
+export function isOptimizableVideo(w: Pick<WallpaperMeta, 'type' | 'source'>): boolean {
+  return w.type === 'video' && w.source !== 'workshop'
+}
+
 export function hasBackup(w: WallpaperMeta): boolean {
   return !!w.backedUp || w.source === 'backup'
 }

+ 135 - 0
src/shared/appRules.test.ts

@@ -0,0 +1,135 @@
+import { describe, expect, it } from 'vitest'
+import {
+  AUDIO_GRACE_MS,
+  PROCESS_GRACE_MS,
+  normalizeProcessName,
+  parseProcessNames,
+  popLayers,
+  pushLayer,
+  stepAppRules,
+  type Observation,
+  type RuleStates
+} from './appRules'
+import type { AppRule } from './types'
+
+const none: Observation = { processes: new Set(), audioPlaying: false }
+
+function processRule(id: string, names: string[], extra: Partial<AppRule> = {}): AppRule {
+  return {
+    id,
+    name: id,
+    enabled: true,
+    condition: { type: 'process', names },
+    action: { type: 'stop' },
+    screen: '*',
+    revert: true,
+    ...extra
+  }
+}
+
+const audioRule: AppRule = { ...processRule('music', []), condition: { type: 'audio' } }
+
+describe('process names', () => {
+  it('ignores case, paths and .exe', () => {
+    expect(normalizeProcessName(' C:\\Games\\Game.EXE ')).toBe('game')
+    expect(normalizeProcessName('/usr/bin/Firefox')).toBe('firefox')
+    expect(normalizeProcessName('')).toBe('')
+  })
+
+  it('splits a list on commas and lines and drops duplicates', () => {
+    expect(parseProcessNames('Steam, game.exe\n\nSTEAM')).toEqual(['steam', 'game'])
+  })
+})
+
+describe('stepAppRules', () => {
+  it('fires a rule once when its program starts and not again while it runs', () => {
+    const rule = processRule('a', ['game.exe'])
+    const running: Observation = { processes: new Set(['game']), audioPlaying: false }
+
+    const first = stepAppRules({}, [rule], running, 1000)
+    expect(first.activate).toEqual([rule])
+
+    const second = stepAppRules(first.next, [rule], running, 3000)
+    expect(second.activate).toEqual([])
+    expect(second.deactivate).toEqual([])
+  })
+
+  it('keeps the rule through a short gap and ends it after the grace time', () => {
+    const rule = processRule('a', ['game'])
+    const running: Observation = { processes: new Set(['game']), audioPlaying: false }
+    let states: RuleStates = stepAppRules({}, [rule], running, 0).next
+
+    const gone = stepAppRules(states, [rule], none, 1000)
+    expect(gone.deactivate).toEqual([])
+    states = gone.next
+
+    const back = stepAppRules(states, [rule], running, 2000)
+    expect(back.activate).toEqual([])
+    expect(back.next.a.unmetSince).toBeNull()
+
+    const away = stepAppRules(back.next, [rule], none, 3000)
+    const ended = stepAppRules(away.next, [rule], none, 3000 + PROCESS_GRACE_MS)
+    expect(ended.deactivate).toEqual(['a'])
+    expect(ended.next.a).toBeUndefined()
+  })
+
+  it('waits longer for audio than for programs', () => {
+    const playing: Observation = { processes: new Set(), audioPlaying: true }
+    const started = stepAppRules({}, [audioRule], playing, 0)
+    expect(started.activate).toEqual([audioRule])
+
+    const quiet = stepAppRules(started.next, [audioRule], none, 1000)
+    const stillOn = stepAppRules(quiet.next, [audioRule], none, 1000 + PROCESS_GRACE_MS)
+    expect(stillOn.deactivate).toEqual([])
+    const over = stepAppRules(stillOn.next, [audioRule], none, 1000 + AUDIO_GRACE_MS)
+    expect(over.deactivate).toEqual(['music'])
+  })
+
+  it('ends an active rule that was disabled or deleted at once', () => {
+    const rule = processRule('a', ['game'])
+    const running: Observation = { processes: new Set(['game']), audioPlaying: false }
+    const states = stepAppRules({}, [rule], running, 0).next
+
+    expect(stepAppRules(states, [{ ...rule, enabled: false }], running, 10).deactivate).toEqual(['a'])
+    expect(stepAppRules(states, [], running, 10).deactivate).toEqual(['a'])
+  })
+
+  it('does not fire a disabled rule', () => {
+    const rule = processRule('a', ['game'], { enabled: false })
+    const running: Observation = { processes: new Set(['game']), audioPlaying: false }
+    expect(stepAppRules({}, [rule], running, 0).activate).toEqual([])
+  })
+
+  it('matches any of several names', () => {
+    const rule = processRule('a', ['one', 'two.exe'])
+    const running: Observation = { processes: new Set(['two']), audioPlaying: false }
+    expect(stepAppRules({}, [rule], running, 0).activate).toEqual([rule])
+  })
+})
+
+describe('layers', () => {
+  it('gives a screen back what it showed before the top rule', () => {
+    let layers = pushLayer({}, 'DP-1', 'a', 'original')
+    layers = pushLayer(layers, 'DP-1', 'b', 'from a')
+
+    const first = popLayers(layers, 'b')
+    expect(first.restore).toEqual({ 'DP-1': 'from a' })
+    const second = popLayers(first.layers, 'a')
+    expect(second.restore).toEqual({ 'DP-1': 'original' })
+    expect(second.layers).toEqual({})
+  })
+
+  it('hands the original to the rule above when a lower rule ends first', () => {
+    let layers = pushLayer({}, 'DP-1', 'a', 'original')
+    layers = pushLayer(layers, 'DP-1', 'b', 'from a')
+
+    const lower = popLayers(layers, 'a')
+    expect(lower.restore).toEqual({})
+    expect(popLayers(lower.layers, 'b').restore).toEqual({ 'DP-1': 'original' })
+  })
+
+  it('leaves screens the rule never touched alone', () => {
+    const layers = pushLayer({}, 'DP-1', 'a', 'x')
+    expect(popLayers(layers, 'b')).toEqual({ layers, restore: {} })
+  })
+})

+ 126 - 0
src/shared/appRules.ts

@@ -0,0 +1,126 @@
+import type { AppRule } from './types'
+
+export interface Observation {
+  /** normalized process names, see normalizeProcessName */
+  processes: ReadonlySet<string>
+  audioPlaying: boolean
+}
+
+export interface RuleState {
+  active: boolean
+  /** since when the condition has not held while the rule is active */
+  unmetSince: number | null
+}
+
+export type RuleStates = Record<string, RuleState>
+
+// a track change or a short pause between songs must not end the rule
+export const AUDIO_GRACE_MS = 8000
+export const PROCESS_GRACE_MS = 2500
+
+/** Case folded base name without a trailing .exe, so "C:\Games\Game.EXE" and "game" are the same program */
+export function normalizeProcessName(name: string): string {
+  const base = name.trim().split(/[\\/]/).pop() ?? ''
+  return base.toLowerCase().replace(/\.exe$/, '')
+}
+
+export function parseProcessNames(text: string): string[] {
+  const names = text
+    .split(/[,\n]/)
+    .map(normalizeProcessName)
+    .filter((name) => name !== '')
+  return [...new Set(names)]
+}
+
+export function conditionMet(rule: AppRule, observation: Observation): boolean {
+  if (rule.condition.type === 'audio') return observation.audioPlaying
+  return rule.condition.names.some((name) => observation.processes.has(normalizeProcessName(name)))
+}
+
+function graceFor(rule: AppRule): number {
+  return rule.condition.type === 'audio' ? AUDIO_GRACE_MS : PROCESS_GRACE_MS
+}
+
+export interface StepResult {
+  next: RuleStates
+  /** rules whose condition just started to hold, in list order */
+  activate: AppRule[]
+  /** ids of rules that ended: the condition was gone for the grace time, or the rule was disabled or deleted */
+  deactivate: string[]
+}
+
+/**
+ * One look at the world. A rule becomes active the moment its condition holds and stays active until the condition
+ * has been gone for its grace time, so the action fires once per start and not on every blip.
+ */
+export function stepAppRules(previous: RuleStates, rules: AppRule[], observation: Observation, now: number): StepResult {
+  const next: RuleStates = {}
+  const activate: AppRule[] = []
+  const deactivate: string[] = []
+
+  for (const rule of rules) {
+    const before = previous[rule.id] ?? { active: false, unmetSince: null }
+
+    if (!rule.enabled) {
+      if (before.active) deactivate.push(rule.id)
+      continue
+    }
+
+    if (conditionMet(rule, observation)) {
+      if (!before.active) activate.push(rule)
+      next[rule.id] = { active: true, unmetSince: null }
+    } else if (before.active) {
+      const since = before.unmetSince ?? now
+      if (now - since >= graceFor(rule)) deactivate.push(rule.id)
+      else next[rule.id] = { active: true, unmetSince: since }
+    }
+  }
+
+  const known = new Set(rules.map((rule) => rule.id))
+  for (const [id, state] of Object.entries(previous)) {
+    if (!known.has(id) && state.active) deactivate.push(id)
+  }
+
+  return { next, activate, deactivate }
+}
+
+/** What one screen showed before a rule changed it */
+export interface LayerEntry<A> {
+  ruleId: string
+  previous: A
+}
+
+export type ScreenLayers<A> = Record<string, LayerEntry<A>[]>
+
+export function pushLayer<A>(layers: ScreenLayers<A>, screen: string, ruleId: string, previous: A): ScreenLayers<A> {
+  return { ...layers, [screen]: [...(layers[screen] ?? []).filter((entry) => entry.ruleId !== ruleId), { ruleId, previous }] }
+}
+
+/**
+ * Takes a rule off every screen. A screen the rule was on top of gets what was there before it back in `restore`; under a
+ * later rule the entry above inherits the previous state, so the screen still goes back to the original when that one
+ * ends too.
+ */
+export function popLayers<A>(
+  layers: ScreenLayers<A>,
+  ruleId: string
+): { layers: ScreenLayers<A>; restore: Record<string, A> } {
+  const next: ScreenLayers<A> = {}
+  const restore: Record<string, A> = {}
+
+  for (const [screen, stack] of Object.entries(layers)) {
+    const index = stack.findIndex((entry) => entry.ruleId === ruleId)
+    if (index === -1) {
+      next[screen] = stack
+      continue
+    }
+
+    const rest = [...stack]
+    const [removed] = rest.splice(index, 1)
+    if (index === stack.length - 1) restore[screen] = removed.previous
+    else rest[index] = { ...rest[index], previous: removed.previous }
+    if (rest.length > 0) next[screen] = rest
+  }
+
+  return { layers: next, restore }
+}

+ 8 - 0
src/shared/engineFlags.test.ts

@@ -42,6 +42,14 @@ describe('engineFlagArgs', () => {
     expect(engineFlagArgs({ frameLimiter: 'budget' })).toEqual([])
     expect(engineFlagArgs({ hrtf: 'on' })).toEqual(['--hrtf', 'on'])
     expect(engineFlagArgs({ hrtf: 'auto' })).toEqual([])
+    expect(engineFlagArgs({ audioInput: 'alsa_input.mic' })).toEqual(['--audio-input', 'alsa_input.mic'])
+    expect(engineFlagArgs({ audioInput: 'default', audioInputVolume: 50, audioInputThreshold: 0 })).toEqual([])
+    expect(engineFlagArgs({ audioInputVolume: 80, audioInputThreshold: 120 })).toEqual([
+      '--audio-input-volume',
+      '80',
+      '--audio-input-threshold',
+      '120'
+    ])
     expect(engineFlagArgs({ batteryFps: '15' })).toEqual(['--fps-battery', '15'])
     expect(engineFlagArgs({ batteryFps: 'pause' })).toEqual(['--pause-on-battery'])
     expect(engineFlagArgs({ batteryFps: 'off' })).toEqual([])

+ 5 - 0
src/shared/engineFlags.ts

@@ -91,6 +91,11 @@ export function engineFlagArgs(flags: EngineFlags): string[] {
   if (flags.webFrames && flags.webFrames !== 'auto') args.push('--web-frames', flags.webFrames)
   if (flags.frameLimiter && flags.frameLimiter !== 'budget') args.push('--frame-limiter', flags.frameLimiter)
   if (flags.hrtf && flags.hrtf !== 'auto') args.push('--hrtf', flags.hrtf)
+  if (flags.audioInput && flags.audioInput !== 'default') args.push('--audio-input', flags.audioInput)
+  if (flags.audioInputVolume !== undefined && flags.audioInputVolume !== 50) {
+    args.push('--audio-input-volume', String(flags.audioInputVolume))
+  }
+  if (flags.audioInputThreshold) args.push('--audio-input-threshold', String(flags.audioInputThreshold))
   if (flags.transition && flags.transition !== 'none') {
     args.push('--transition', flags.transition)
     if (flags.transitionDuration && flags.transitionDuration !== '600') {

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

@@ -15,6 +15,19 @@ export const de: Messages = {
 
   'app.error': 'Etwas ist schiefgelaufen',
 
+  'appRules.active': 'aktiv',
+  'appRules.add': 'Regel hinzufügen',
+  'appRules.audio': 'Solange eine andere App Ton wiedergibt',
+  'appRules.audioUnavailable': 'Der Sound-Server lässt sich nicht fragen, welche Apps Ton wiedergeben (pactl fehlt oder antwortet nicht), daher startet diese Regel nie.',
+  'appRules.description': 'Zeigt ein Wallpaper, eine Playlist oder ein Profil, solange ein Programm läuft oder eine andere Anwendung Ton wiedergibt, und kehrt danach zurück. Programme werden am Prozessnamen erkannt.',
+  'appRules.pickProgram': 'Gib mindestens einen Programmnamen ein',
+  'appRules.programsHint': 'Mehrere mit Kommas trennen. Groß- und Kleinschreibung und ein angehängtes .exe spielen keine Rolle.',
+  'appRules.programsPlaceholder': 'Programmnamen, z. B. steam, game.exe',
+  'appRules.revert': 'Danach zum vorherigen Wallpaper zurückkehren',
+  'appRules.runs': 'Solange ein Programm läuft',
+  'appRules.title': 'Anwendungsregeln',
+  'appRules.whileAudio': 'Solange eine andere App Ton wiedergibt',
+  'appRules.whileRuns': 'Solange {names} läuft',
   'appearance.accent': 'Akzentfarbe',
   'appearance.accentHue': 'Farbton der Akzentfarbe',
   'appearance.always': 'Immer',
@@ -33,6 +46,15 @@ export const de: Messages = {
   'appearance.system': 'System',
   'appearance.title': 'Darstellung',
 
+  'audioInput.default': 'Was der Computer wiedergibt (Standard)',
+  'audioInput.hint': 'Worauf die Audio-Visualisierungen der Wallpaper reagieren. Standardmäßig ist das der Ton, den der Computer wiedergibt; wähle ein Mikrofon oder einen Line-In, um stattdessen darauf zu reagieren.',
+  'audioInput.inputs': 'Eingänge',
+  'audioInput.outputs': 'Ausgänge (was sie wiedergeben)',
+  'audioInput.refresh': 'Liste aktualisieren',
+  'audioInput.threshold': 'Leisen Ton ignorieren unter: {value}',
+  'audioInput.thresholdHint': 'Ton, der leiser ist als dieser Wert, gilt als Stille. Bei 0 wird alles verarbeitet.',
+  'audioInput.title': 'Audioeingang',
+  'audioInput.volume': 'Verstärkung: {value}',
   'backup.action': 'Sichern',
   'backup.alreadyCurrent': 'Sicherung ist bereits aktuell',
   'backup.alreadyUpToDate_one': '{count} bereits aktuell',
@@ -495,6 +517,7 @@ export const de: Messages = {
   'library.checkUnavailableHint': 'Den Workshop nach entfernten Hintergründen durchsuchen',
   'library.checkedUnavailable_one': '{count} Workshop-Objekt geprüft: {unavailable} nicht mehr im Workshop verfügbar.',
   'library.checkedUnavailable_other': '{count} Workshop-Objekte geprüft: {unavailable} nicht mehr im Workshop verfügbar.',
+  'library.checkUnavailableNoAnswer': 'Steam hat nicht geantwortet, es wurde nichts geprüft. Stelle sicher, dass Steam läuft und online ist, und versuche es erneut.',
   'library.cleanedUp_one': '{count} nicht vorhandener Hintergrund aus Ordnern entfernt.',
   'library.cleanedUp_other': '{count} nicht vorhandene Hintergründe aus Ordnern entfernt.',
   'library.cleanup': 'Ordner aufräumen (nicht vorhandene Hintergründe entfernen)',
@@ -628,6 +651,153 @@ export const de: Messages = {
   'nav.library': 'Bibliothek',
   'nav.playlists': 'Playlists',
   'nav.settings': 'Einstellungen',
+  'optimize.action': 'Video optimieren ...',
+  'optimize.applied': 'Video ersetzt',
+  'optimize.background': 'Im Hintergrund fortsetzen',
+  'optimize.bgRunning': 'Video wird im Hintergrund optimiert ... {percent} %',
+  'optimize.bgDone': 'Optimiertes Video fertig: {before} -> {after}',
+  'optimize.auto': 'Automatisch (am schnellsten)',
+  'optimize.bigger': 'Das Ergebnis ist {size} ({percent} %) größer als das Original. Verwerfen wird empfohlen.',
+  'optimize.checking': 'Video wird geprüft ...',
+  'optimize.convert': 'In H.265 umwandeln',
+  'optimize.convertHint': 'Bei gleicher Qualität meist deutlich kleiner.',
+  'optimize.custom': 'Eigene Größe',
+  'optimize.cut': 'Schneiden',
+  'optimize.cutHint': 'Nur einen Teil des Videos behalten. Zeiten als 1:30 oder 90.5.',
+  'optimize.discard': 'Verwerfen',
+  'optimize.download': 'ffmpeg herunterladen',
+  'optimize.downloading': 'ffmpeg wird heruntergeladen ({size} MB) ...',
+  'optimize.downscale': 'Verkleinern',
+  'optimize.downscaleHint': 'Nur kleiner als das Original, nie vergrößert. Jede Bildschirmform geht.',
+  'optimize.fps': 'Bildrate reduzieren',
+  'optimize.fpsHint': 'Entfernt Bilder bis zur gewählten Rate: kleinere Datei, weniger Rechenaufwand. Die Rate wird nie erhöht.',
+  'optimize.fpsNothing': 'Dieses Video läuft mit {fps} fps, es gibt keine niedrigere Auswahl.',
+  'optimize.fpsValue': '{fps} fps',
+  'optimize.fpsUnit': 'fps',
+  'optimize.dimensions': '{width} x {height}',
+  'optimize.errFps': 'Das Video läuft bereits mit dieser Bildrate oder weniger.',
+  'optimize.errFpsValue': "Ganze Zahl von 1 bis {max} eingeben, niedriger als die {fps} fps des Videos.",
+  'videoDefaults.fpsInvalid': "Ganze Zahl von 1 bis {max} eingeben.",
+  'videoDefaults.fps': 'Bildrate begrenzen auf',
+  'videoDefaults.fpsNone': 'Bildrate beibehalten',
+  'videoDefaults.fpsHint': 'Schnelloptimierung erhöht die Rate nie: Ein Video auf oder unter diesem Wert behält seine Bildrate.',
+  'optimize.encoder': 'Encoder',
+  'optimize.quality': 'Qualität',
+  'optimize.qualityHint': 'CRF {min} (schärfstes Bild, größte Datei) bis {max} (kleinste Datei). 26 ist ein guter Start.',
+  'optimize.encodersFound': 'Gefundene H.265-Encoder: {list}',
+  'optimize.encoding': 'Kodierung ... {percent} %',
+  'optimize.errBusy': 'Es läuft bereits ein anderer Videoauftrag.',
+  'optimize.errCancelled': 'Abgebrochen.',
+  'optimize.errCut': 'Der Schnittbereich liegt nicht im Video.',
+  'optimize.errFailed': 'ffmpeg ist fehlgeschlagen: {detail}',
+  'optimize.errInUse': 'Das Wallpaper läuft gerade auf einem Bildschirm oder in einer Playlist bzw. einem Zeitplan.',
+  'optimize.errNoBuild': 'Für diese CPU gibt es keinen ffmpeg-Build.',
+  'optimize.errNoEncoder': 'Kein funktionierender H.265-Encoder gefunden. Lade ffmpeg in den Einstellungen herunter.',
+  'optimize.errNoFfmpeg': 'ffmpeg ist nicht installiert. Lade es in den Einstellungen herunter.',
+  'optimize.errPicture': 'Das Bild von {encoder} stimmt nicht mit dem Original überein (falsche Farben). Das Original wurde nicht verändert. Versuche einen anderen Encoder.',
+  'optimize.errNotVideo': 'Das ist kein Video-Wallpaper, das sich ändern lässt.',
+  'optimize.errNothing': 'Nichts zu tun: Das Video ist bereits H.265.',
+  'optimize.errNoResult': 'Es gibt kein fertiges Ergebnis zum Behalten.',
+  'optimize.errScale': 'Das Video ist nicht größer als diese Größe.',
+  'optimize.errSpace': 'Nicht genug freier Speicherplatz für die neue Datei.',
+  'optimize.errSteam': 'Steam verwaltet diesen Ordner und würde ihn wiederherstellen. Sichere das Wallpaper zuerst.',
+  'optimize.fastCut': 'Schneller Schnitt ohne Neukodierung (rastet auf Keyframes ein)',
+  'optimize.fill': 'Größe ausfüllen (schneidet Überstand ab)',
+  'playlist.itemUntil': 'bis {time} · Lautst. {volume}',
+  'playlist.itemVolume': 'Lautst. {volume}',
+  'playlist.mode': 'Modus',
+  'playlist.modeDayOfWeek': 'Wochentag',
+  'playlist.modeDayOfWeekHint': 'Die Uhr wählt das Wallpaper: Die Wochentage werden in Listenreihenfolge auf die Einträge verteilt (bis zu sieben).',
+  'playlist.modeDaytime': 'Tageszeit',
+  'playlist.modeDaytimeHint': 'Die Uhr wählt das Wallpaper in Listenreihenfolge. Lege fest, wann jedes endet; Einträge ohne Zeit teilen den Rest gleichmäßig, der letzte läuft bis Mitternacht.',
+  'playlist.modeLogon': 'Bei der Anmeldung',
+  'playlist.modeLogonHint': 'Zeigt bei jeder Anmeldung das nächste Wallpaper der Liste und behält es bis zur nächsten Sitzung.',
+  'playlist.modeTimer': 'Nacheinander',
+  'playlist.until': 'Bis',
+  'playlist.untilHint': 'leer = teilt die Zeit',
+  'playlist.untilNotLater': 'muss nach {time} liegen, sonst wird dieses Hintergrundbild übersprungen',
+  'profiles.apply': 'Profil laden',
+  'profiles.description': 'Ein Profil merkt sich, was jeder Bildschirm zeigt. Lade es hier, über einen Zeitplan oder eine Anwendungsregel.',
+  'profiles.load': '{name} laden',
+  'profiles.loadProfile': 'Ein Profil laden',
+  'profiles.gone': 'Das Profil existiert nicht mehr',
+  'rules.wallpaperGone': 'Das geplante Hintergrundbild ist nicht mehr in der Bibliothek',
+  'rules.playlistGone': 'Die geplante Playlist existiert nicht mehr',
+  'profiles.failedOn': '„{name}“ konnte auf {screens} nicht angewendet werden',
+  'profiles.missing': 'fehlendes Profil',
+  'profiles.rulesOff': 'Regeln, die dieses Profil nutzten, wurden ausgeschaltet',
+  'profiles.nameFirst': 'Gib dem Profil zuerst einen Namen',
+  'profiles.namePlaceholder': 'Name für die aktuelle Einrichtung',
+  'profiles.none': 'Keine Profile gespeichert',
+  'profiles.pick': 'Wähle ein Profil',
+  'profiles.saveCurrent': 'Aktuelle Einrichtung speichern',
+  'profiles.title': 'Profile',
+  'settings.tab.videoDefaults': 'Optimierungseinstellungen',
+  'videoDefaults.title': 'Optimierungseinstellungen',
+  'videoDefaults.hint': 'Werden von „Schnell optimieren“ genutzt und sind die Startwerte des Optimieren-Dialogs.',
+  'videoDefaults.backup': 'Vor dem Ersetzen eine Kopie des Originals behalten',
+  'videoDefaults.backupHint': 'Das Original wird als „Name (original)“ neben das Video kopiert und auf die Platte geschrieben, bevor das Video ersetzt wird. Braucht so viel freien Platz wie das Video. Nur ausschalten, wenn du ein eigenes Backup hast.',
+  'videoDefaults.scaleTo': 'Verkleinern auf',
+  'videoDefaults.scaleNone': 'Größe beibehalten',
+  'videoDefaults.scaleHint': 'Schnell optimieren vergrößert nie ein Video: Eines, das nicht größer ist, behält seine Größe.',
+  'videoDefaults.trim': 'Zuschnitt des Wallpapers',
+  'videoDefaults.trim.never': 'Nicht zuschneiden',
+  'videoDefaults.trim.ask': 'Vor dem Zuschneiden fragen',
+  'videoDefaults.trim.auto': 'Automatisch zuschneiden',
+  'videoDefaults.trimHint': 'Bei Videos mit eigenen Zuschnittzeiten kann Schnell optimieren das Video darauf kürzen. Workshop-Wallpaper werden nie verändert.',
+  'optimize.cutTrimHint': 'Dein Zuschnitt dieses Wallpapers ({start} - {end}) ist eingetragen. Aktiviere dies, um das Video darauf zu kürzen.',
+  'optimize.cutTrimPartsHint': 'Dein Zuschnitt dieses Wallpapers ({parts} Teile) ist eingetragen. Aktiviere dies, um das Video darauf zu kürzen.',
+  'optimize.cutJoinHint': 'Die Teile werden in dieser Reihenfolge zusammengefügt, alles dazwischen wird herausgeschnitten.',
+  'optimize.cutResult': 'Ergebnis: {length} aus {parts} Teilen',
+  'optimize.cutPreview': 'Vorschau',
+  'optimize.cutPreviewUnsupported': 'Dieses Video kann in der Vorschau nicht abgespielt werden (Format oder Codec).',
+  'optimize.cutSeam': 'Übergang abspielen',
+  'optimize.cutAddPart': 'Teil hinzufügen',
+  'optimize.cutRemovePart': 'Diesen Teil entfernen',
+  'optimize.cutPartLabel': 'Teil {n}',
+  'optimize.errCutOrder': 'Die Teile müssen zeitlich aufeinander folgen und dürfen sich nicht überlappen.',
+  'optimize.fastCutSingle': 'Schneller Schnitt funktioniert nur mit einem einzelnen Teil.',
+  'quick.trimTitle': 'Videos auf deinen Zuschnitt kürzen?',
+  'quick.trimText': 'Diese Videos haben eigene Zuschnittzeiten. Beim Optimieren darauf kürzen?',
+  'quick.trimYes': 'Zuschneiden und optimieren',
+  'quick.trimNo': 'Ohne Zuschneiden optimieren',
+  'quick.action': 'Schnell optimieren',
+  'quick.running': 'Schnell optimieren: {done} von {total} - {title} {percent}%',
+  'quick.skipped': '{title} ({id}) übersprungen: {reason}',
+  'quick.failed': '{title} ({id}) fehlgeschlagen: {error}',
+  'quick.done': 'Schnell optimieren: {count} optimiert, {size} gespart.',
+  'quick.doneKept': 'Schnell optimieren: {count} optimiert, {size} kleiner. Die Originale liegen weiter daneben, lösche sie, um den Platz wirklich freizugeben.',
+  'quick.reasonHevc': 'es bereits H.265 ist',
+  'quick.reasonHevcSize': 'es bereits H.265 und nicht größer als {size} ist',
+  'quick.reasonBigger': 'die neue Datei nicht kleiner war',
+  'quick.reasonBusy': 'gerade ein anderer Video-Auftrag läuft',
+  'optimize.errBackup': 'Das Original konnte nicht kopiert werden: {detail}. Das Video wurde nicht ersetzt.',
+  'optimize.detailCopySize': 'Die Kopie hat eine andere Größe',
+  'optimize.detailEmpty': 'leere Ausgabe',
+  'optimize.keptRejected': 'Die abgelehnte Datei wurde als {path} behalten, lösche sie, wenn du fertig bist.',
+  'optimize.wrongEncoder': '{encoder} ({source}) zeichnet auf diesem Computer ein falsches Bild und wird deshalb nicht angeboten.',
+  'optimize.wrongEncoderHint': 'Oft hilft ein Update des Grafiktreibers (Mesa) oder von ffmpeg. Bis dahin werden die anderen Encoder genutzt, der CPU-Encoder geht immer.',
+  'optimize.tryDownloaded': 'ffmpeg der App ausprobieren',
+  'optimize.srcSystem': 'System-ffmpeg',
+  'optimize.srcDownloaded': 'heruntergeladenes ffmpeg',
+  'optimize.skipped': '{skipped} hat bei diesem Video ein falsches Bild erzeugt und wurde übersprungen. Stattdessen wurde {used} genutzt.',
+  'optimize.force': 'Trotzdem neu kodieren',
+  'optimize.forceHint': 'Das Video ist bereits H.265. Einschalten, um es mit der Qualität unten erneut zu kodieren, für eine kleinere Datei. Die Datei wird wie bei jeder Änderung ersetzt, das Ergebnis bestätigst du vorher.',
+  'optimize.forceWarn': 'Das Neukodieren von H.265 nach H.265 kostet jedes Mal etwas Qualität, wiederholte Durchläufe auf derselben Datei werden also weicher.',
+  'optimize.fit': 'In die Größe einpassen (ganzes Bild bleibt)',
+  'optimize.keep': 'Video ersetzen',
+  'optimize.keepAnyway': 'Trotzdem ersetzen',
+  'optimize.noEncoder': 'Auf diesem System ist kein H.265-Encoder verfügbar.',
+  'optimize.nothingSmaller': 'Das Video ist nicht größer als eine dieser Größen.',
+  'optimize.removeDownloaded': 'Heruntergeladenes ffmpeg entfernen',
+  'optimize.resultSize': 'Ergebnis: {width} x {height}',
+  'optimize.settingsHint': 'Umwandeln in H.265, Verkleinern und Schneiden nutzen ffmpeg. Nur Wallpaper außerhalb des Steam-Ordners lassen sich ändern.',
+  'optimize.settingsTitle': 'Videowerkzeuge',
+  'optimize.smaller': '{size} ({percent} %) gespart.',
+  'optimize.start': 'Starten',
+  'optimize.title': 'Video optimieren',
+  'optimize.unpacking': 'ffmpeg wird entpackt ...',
+
   'settings.tab.appearance': 'Darstellung',
   'settings.tab.library': 'Bibliothek',
   'settings.tab.engine': 'Engine',
@@ -747,6 +917,10 @@ export const de: Messages = {
   'schedule.description': 'Wechselt Hintergründe oder Playlists zu festen Zeiten oder bei Dunkel/Hell-Wechsel. Eine verpasste Zeit läuft beim Start nach (die neueste je Bildschirm).',
   'schedule.everyDay': 'täglich',
   'schedule.fired': 'Zeitplan: {name}',
+  'appRule.started': 'Regel gestartet: {name}',
+  'appRule.ended': 'Regel beendet: {name}',
+  'appRule.restoreFailed': 'Wallpaper nach Regel konnte nicht wiederhergestellt werden: {name}',
+  'appRule.failed': 'Regel konnte nicht gestartet werden: {name}',
   'schedule.missingPlaylist': 'fehlende Playlist',
   'schedule.missingWallpaper': 'fehlender Hintergrund',
   'schedule.namePlaceholder': 'Name (optional)',
@@ -794,6 +968,8 @@ export const de: Messages = {
   'settings.desktopIconsHint': 'Zeigt die Desktopsymbole über dem Hintergrund mit einem transparenten Overlay, das deiner KDE-Ordneransicht folgt. Klicks gehen hindurch.',
   'settings.desktopIconsOff': 'Desktopsymbole ausgeblendet',
   'settings.desktopIconsOn': 'Desktopsymbole sichtbar',
+  'settings.desktopIconsAuto': 'Overlay nur zeichnen, solange ein Wallpaper läuft',
+  'settings.desktopIconsAutoHint': 'Das Overlay startet mit dem ersten Wallpaper und verschwindet, wenn das letzte stoppt, damit keine Symbole über einen leeren Desktop gezeichnet werden',
   'settings.desktopIcons_not-kde': 'Hier nicht nötig: Nur KDE Plasma versteckt seine Symbole unter dem Hintergrund. Dein Desktop zeigt seine Symbole selbst.',
   'settings.desktopIcons_not-wayland': 'Das Overlay läuft nur in einer Wayland-Sitzung.',
   'settings.desktopIcons_missing-lib': 'Das Overlay braucht die Bibliothek gtk4-layer-shell, die nicht installiert ist. Installiere sie und schalte die Option aus und wieder ein:',
@@ -819,6 +995,8 @@ export const de: Messages = {
   'settings.skipPlaylistResumeHint': 'Bildschirme mit einer Playlist bleiben nach einem Neustart leer. Das letzte Playlist-Element wird nicht wiederhergestellt.',
   'settings.freshProcessOnPathChange': 'Neuen Engine-Prozess starten, wenn sich das Hintergrundbild ändert',
   'settings.freshProcessOnPathChangeHint': 'Standardmäßig aus, damit ein Wechsel die laufende Engine und ihren Übergang behält. Aktiviere es, wenn ein getauschtes Hintergrundbild leer bleibt oder der vorherige Ton weiterläuft. Playlists, Zeitpläne und das Tray starten die Engine dann ebenfalls neu.',
+  'settings.stopPlaylistsOnKillAll': 'Beim Beenden aller Prozesse auch laufende Playlists pausieren (sie bleiben geladen)',
+  'settings.forgetOnKillAll': 'Beim Beenden aller Prozesse auch Playlists stoppen und die Hintergründe vergessen, damit nach einem Neustart nichts zurückkommt (hat Vorrang vor Pausieren)',
   'settings.lweHint': 'Nötig für animierte/Szenen-Hintergründe unter Linux. Rendert Wallpaper-Engine-Szenen direkt auf deinem Desktop.',
   'settings.none': 'Keine',
   'settings.notConfigured': 'Nicht eingerichtet',

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно