-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathmain.rs
More file actions
5446 lines (5045 loc) · 210 KB
/
Copy pathmain.rs
File metadata and controls
5446 lines (5045 loc) · 210 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use flate2::read::GzDecoder;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use socket2::{Domain, Protocol, Socket, Type};
use std::{
collections::HashMap,
env, fs,
io::{Read, Write},
net::{SocketAddr, TcpStream},
path::{Path, PathBuf},
process::{Child, Command, Output, Stdio},
sync::{
atomic::{AtomicU64, Ordering},
Mutex,
},
thread,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tar::Archive;
use tauri::{Emitter, Manager};
use tauri_plugin_store::StoreExt;
#[cfg(windows)]
use zip::ZipArchive;
const SETUP_VERSION: u64 = 1;
// ── In-app updater platform support (#421) ──────────────────────────────────
//
// Windows and Linux ship the same shape: a flat directory with the executable,
// `backend/` and `python/` side by side, which is exactly what the swap needs.
//
// macOS is deliberately excluded. There `backend_dir()` resolves the backend
// inside the downloaded runtime pack rather than the .app, so the app layer is
// a different thing entirely and the existing runtime-pack updater already
// covers most of it. Treating it as "the same but with .app" would be wrong.
//
// The archive format differs because each platform's packaging script already
// produces one: Compress-Archive on Windows, tar on Linux.
#[cfg(windows)]
const UPDATE_APP_ARCHIVE: &str = "stemdeck-update-app.zip";
#[cfg(target_os = "linux")]
const UPDATE_APP_ARCHIVE: &str = "stemdeck-update-app.tar.gz";
/// The shipped executable's filename. Defined for every platform so the
/// leftover sweep does not need its own cfg dance.
#[cfg(windows)]
const APP_EXE_NAME: &str = "StemDeck.exe";
#[cfg(not(windows))]
const APP_EXE_NAME: &str = "StemDeck";
// Windows FFmpeg comes from BtbN's GitHub build (served via GitHub's CDN, far
// faster worldwide than the old gyan.dev single mirror -- #248). Unlike gyan.dev,
// which published a per-file `{url}.sha256` companion, BtbN publishes ONE combined
// `checksums.sha256` listing every asset as `<hash> <filename>` lines; we fetch it
// and pick the line for our archive's basename. The `latest` tag is rolling (the
// `n8.1-latest` asset is rebuilt in place), so the checksum is fetched fresh each
// run and verified -- the same trust model as the old gyan flow. A compile-time pin
// is not possible without self-hosting the archive.
const DEFAULT_WINDOWS_FFMPEG_URL: &str =
"https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-n8.1-latest-win64-gpl-8.1.zip";
#[cfg(windows)]
const DEFAULT_WINDOWS_FFMPEG_CHECKSUMS_URL: &str =
"https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/checksums.sha256";
// macOS FFmpeg is pinned to a specific evermeet build and verified by SHA256
// before it is extracted or executed (#172). evermeet publishes no .sha256
// companion (only a GPG signature and a size), so unlike the Windows BtbN
// path we cannot fetch the hash at runtime -- instead we pin the hash of a
// specific versioned zip, captured at build time from evermeet's TLS endpoint
// (the download size matched evermeet's signed release info). Bump the version
// and BOTH hashes together when updating FFmpeg. The rolling getrelease/latest
// URL is intentionally avoided so the pinned hash stays valid.
const DEFAULT_MACOS_FFMPEG_URL: &str = "https://evermeet.cx/ffmpeg/ffmpeg-8.1.1.zip";
#[cfg(target_os = "macos")]
const DEFAULT_MACOS_FFPROBE_URL: &str = "https://evermeet.cx/ffmpeg/ffprobe-8.1.1.zip";
#[cfg(target_os = "macos")]
const DEFAULT_MACOS_FFMPEG_SHA256: &str =
"4610988e2f54c243c50da73a09e4e2c36d9bb77546f9aa6c84cb328dcb1a98c1";
#[cfg(target_os = "macos")]
const DEFAULT_MACOS_FFPROBE_SHA256: &str =
"aeade29dee3c3844e9bcc974f4ae4b29cc4f87994177d77003a8589fa531009e";
// Primary macOS FFmpeg source: shaka-project's static builds, built from
// source via GitHub Actions and served from GitHub Releases -- GitHub's
// global CDN behind it, the same class of fix that already solved this for
// Windows (#248, moved off gyan.dev's single mirror). evermeet.cx above is
// now the fallback only: a single host with no CDN, reported unreachable
// from multiple regions (#388). Binaries are raw (not zip-wrapped) and
// published per-architecture. All four hashes were independently verified
// (downloaded, sha256'd, and cross-checked against the release notes' own
// published MD5s and each binary's Mach-O magic bytes) before pinning here.
// Bump the release tag and all four hashes together when updating.
#[cfg(target_os = "macos")]
const SHAKA_FFMPEG_RELEASE: &str = "n8.1.2-1";
#[cfg(target_os = "macos")]
const SHAKA_FFMPEG_BASE_URL: &str =
"https://github.com/shaka-project/static-ffmpeg-binaries/releases/download";
#[cfg(target_os = "macos")]
const SHAKA_FFMPEG_SHA256_ARM64: &str =
"e7b9fcd97f95f333512d6e8b8ac24d9dbc08f189f36047695499bd7b57214b22";
#[cfg(target_os = "macos")]
const SHAKA_FFMPEG_SHA256_X64: &str =
"62c87854d851f202fc4a29bdda0fe7b6ebcddd37b863482ce1bdc81151b03fe4";
#[cfg(target_os = "macos")]
const SHAKA_FFPROBE_SHA256_ARM64: &str =
"ded4c698b8ff38d0bc1fd30fcc5e768dc46f58bc15a8dfd61f98615ba49cde5c";
#[cfg(target_os = "macos")]
const SHAKA_FFPROBE_SHA256_X64: &str =
"d530823f480a3c7eb6334f18a00197d1e9f1070e86172b9aa89c4bf4022bd879";
// Linux: a static amd64 build (ffmpeg + ffprobe in one .tar.xz) downloaded at
// first launch, mirroring the Windows/macOS model so we never redistribute
// FFmpeg ourselves. Overridable via STEMDECK_FFMPEG_URL. The archive unpacks to
// ffmpeg-<ver>-amd64-static/{ffmpeg,ffprobe}; extraction uses the system `tar`.
#[cfg(all(unix, not(target_os = "macos")))]
const DEFAULT_LINUX_FFMPEG_URL: &str =
"https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-amd64-static.tar.xz";
struct BackendHandles {
child: Child,
url: String,
}
#[derive(Default)]
struct BackendStateInner {
handles: Option<BackendHandles>,
/// True while start_backend is executing; prevents concurrent starts (#145).
starting: bool,
/// PID of an in-progress setup-time subprocess (pip install, or the model
/// warmup download, #275); killed by stop_backend on window close (#140).
setup_child_pid: Option<u32>,
/// Save destinations the user has picked but not yet downloaded to (#338).
///
/// The export is two commands so the UI can tell "choosing a folder" apart
/// from "writing the file", but the second half must not take a path from
/// JS: that would hand a compromised WebView the ability to write any URL
/// to any location on disk. The path stays here and JS only ever holds an
/// opaque token.
pending_saves: HashMap<String, PathBuf>,
/// Source of those tokens. A counter is enough -- the token is not a
/// secret. Every live token maps to a path the user chose in a native
/// dialog, so guessing one only ever yields another approved destination.
next_save_token: u64,
}
/// Cap on unconsumed destinations. A pick whose download never runs (the user
/// closes the window mid-export) would otherwise sit here for the life of the
/// process.
const MAX_PENDING_SAVES: usize = 16;
struct BackendState {
inner: Mutex<BackendStateInner>,
}
impl Default for BackendState {
fn default() -> Self {
BackendState {
inner: Mutex::new(BackendStateInner::default()),
}
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct RuntimeProbe {
app_root: String,
data_dir: String,
python_path: Option<String>,
python_ready: bool,
ffmpeg_path: Option<String>,
ffmpeg_ready: bool,
/// Persisted from previous setup run; None means GPU step hasn't run yet.
torch_device: Option<String>,
/// Why the persisted device was chosen (e.g. "verified", "no-gpu-detected",
/// "cuda-verify-failed", "cpu-only-package"). None on installs that predate
/// reason tracking -- the setup gate treats those as unsettled so a wrongly
/// pinned CPU heals itself on the next launch (#247).
torch_device_reason: Option<String>,
}
#[derive(Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
struct RuntimeManifest {
version: String,
arch: String,
runtime_url: String,
runtime_sha256: String,
runtime_size: Option<u64>,
archive_name: Option<String>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct RuntimePackStatus {
manifest_ready: bool,
manifest_path: Option<String>,
runtime_ready: bool,
runtime_dir: String,
backend_ready: bool,
python_ready: bool,
archive_path: Option<String>,
archive_ready: bool,
installed_version: Option<String>,
manifest: Option<RuntimeManifest>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct RuntimeArchive {
archive_path: String,
sha256: String,
size: u64,
}
/// The app-layer artifact to install, resolved by the frontend from the GitHub
/// Releases API (the same check already in static/js/catalog.js) and handed to
/// `download_app_update`. Rust downloads, verifies and applies; it does not
/// re-resolve "what is the latest version" itself.
///
/// There is no runtime artifact here on purpose. The updater replaces
/// the executable and backend/ only -- python/ is never touched, because an
/// NVIDIA install rewrites it with CUDA torch at first run and replacing the
/// directory would silently drop that machine back to CPU. The frontend gates
/// on the release's runtime id first, and falls back to the full-package
/// download whenever the Python dependency set changed.
// Only the Windows build reads these fields; the other platforms keep the
// struct so download_app_update has one signature everywhere and can answer
// with a clear "not available here" rather than a missing-command error.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(not(windows), allow(dead_code))]
struct AppUpdatePlan {
app_url: String,
app_sha256: String,
}
/// Asset URLs lifted from the GitHub release JSON by the frontend, for
/// `check_app_update` to resolve.
///
/// The small metadata files are fetched HERE rather than in JS on purpose. The
/// page is served by the Python backend over http, so the backend's own
/// Content-Security-Policy applies to it, and `connect-src` allows
/// `api.github.com` but NOT `github.com`/`objects.githubusercontent.com` where
/// release *assets* actually live (app/main.py). A `fetch()` for the checksum
/// or the runtime id would be blocked outright and the updater would silently
/// never appear. reqwest is not bound by the page CSP, so doing it in Rust
/// keeps that policy exactly as tight as it is today.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(not(windows), allow(dead_code))]
struct AppUpdateQuery {
app_sha_url: String,
runtime_id_url: String,
}
/// Whether this release can be installed in place, and the verified checksum to
/// install it with. `reason` is for the log, not the user: the UI just falls
/// back to the normal download link.
#[derive(Serialize, Default)]
#[serde(rename_all = "camelCase")]
struct AppUpdateAvailability {
supported: bool,
app_sha256: Option<String>,
reason: Option<String>,
}
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct DownloadProgress {
received: u64,
total: Option<u64>,
}
#[derive(Serialize)]
struct BackendStarted {
url: String,
}
/// Identifies which published release asset matches the running build, so the
/// frontend's "new release" dialog can offer the correct download link.
/// `gpu` only distinguishes Windows/Linux assets (NVIDIA vs CPU variant);
/// macOS ships one build per arch, so it reports "universal" and the frontend
/// keys the macOS asset name on `arch` alone.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct BuildTarget {
os: String,
arch: String,
gpu: String,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct AssetStatus {
ffmpeg_ready: bool,
ffmpeg_path: Option<String>,
model_ready: bool,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct GpuSetup {
gpu_detected: bool,
gpu_name: Option<String>,
cuda_version: Option<String>,
torch_device: String,
cuda_verified: bool,
/// Why this device was chosen; mirrors the persisted torchDeviceReason.
reason: String,
}
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_store::Builder::default().build())
.setup(|app| {
let data_dir = match local_data_dir() {
Ok(d) => d,
Err(e) => {
eprintln!("[stemdeck] could not resolve data_dir, skipping version check: {e}");
return Ok(());
}
};
let _ = fs::create_dir_all(&data_dir);
// Sweep what an in-app update left at the app root: the previous
// backend/ and exe, plus a staging dir if the update was
// interrupted before it could clean up. The new files are already
// in place, so these are only ever the old version's leftovers.
//
// Runs on EVERY launch, not just a version change. apply_app_update
// relaunches and then exits, so on the very first launch of the new
// build the outgoing process is usually still alive and Windows
// still holds StemDeck.exe.old open -- the delete fails silently
// and, gated on a version change that has already happened, would
// never be retried. Verified: after a real self-update both
// backend.old and StemDeck.exe.old were still on disk. Three path
// checks per launch is nothing; leaking ~30 MB forever is not.
sweep_update_leftovers();
let version_file = data_dir.join("last_version.txt");
let migration_flag = data_dir.join("store_migration_done");
let current = env!("CARGO_PKG_VERSION");
let last = fs::read_to_string(&version_file).unwrap_or_default();
if last.trim() != current {
if migration_flag.exists() {
#[cfg(target_os = "macos")]
clear_webkit_data();
}
// A new version is the moment to throw away what the old one
// left behind (#356): archives for runtimes that are no longer
// the expected one, and any half-finished runtime swap. The
// archive this build wants is spared, so an update that already
// downloaded it does not fetch it twice.
//
// Deliberately narrow. settings.json in this directory holds
// the stems location (#354); removing it would send a user who
// moved their library to another disk back to the default
// folder, to an empty app with their stems stranded.
prune_runtime_leftovers(&data_dir);
let manifest = app_root()
.ok()
.and_then(|root| load_runtime_manifest(&root).ok());
// Spare the expected archive only while it is still needed. If
// the installed runtime already matches, the pack it came from
// is dead weight -- and its filename carries no version, so it
// would otherwise sit there forever looking current.
let keep = manifest.as_ref().and_then(|m| {
if runtime_is_current(&data_dir, m) {
None
} else {
Some(runtime_archive_path(&data_dir, m))
}
});
let freed = prune_downloads(&data_dir, keep.as_deref());
if freed > 0 {
eprintln!(
"[stemdeck] freed {} MB of stale downloads",
freed / 1_048_576
);
}
// Only update the version file if write succeeds. If it fails, skip
// cleanup — a missing version file would otherwise cause every launch
// to wipe WebKit data.
if let Err(e) = fs::write(&version_file, current) {
eprintln!("[stemdeck] failed to write version file, skipping cleanup: {e}");
}
}
let _ = app; // suppress unused warning
Ok(())
})
.manage(BackendState::default())
.invoke_handler(tauri::generate_handler![
probe_runtime,
ensure_workspace,
runtime_pack_status,
download_runtime_pack,
verify_runtime_pack,
extract_runtime_pack,
installed_runtime_id,
check_app_update,
download_app_update,
apply_app_update,
ensure_external_assets,
ensure_torch_device,
warmup_models,
start_backend,
local_ip,
build_target,
open_url,
save_audio_file,
pick_export_destination,
download_to_path,
pick_stems_folder,
store_get,
store_set,
reset_user_data,
mark_store_migration_done,
])
.build(tauri::generate_context!())
.expect("failed to build StemDeck desktop app")
.run(|app_handle, event| {
if let tauri::RunEvent::WindowEvent {
event: tauri::WindowEvent::CloseRequested { .. },
..
} = event
{
let state = app_handle.state::<BackendState>();
stop_backend(&state);
app_handle.exit(0);
}
});
}
/// Returns ~/Documents/StemDeck/ WITHOUT creating it. The Documents
/// *default* for the jobs folder (documents_dir_for_jobs below) and the
/// source of a pre-#403 user-data.json for one-time migration
/// (documents_store_path) -- chosen so the library is visible in
/// Finder/Explorer, eligible for iCloud/OneDrive backup, and survives app
/// reinstalls, before the user ever relocates it via Settings.
///
/// Deliberately does not mkdir: this is called on every startup just to
/// compute the *default* jobs path, even when the user has relocated their
/// library elsewhere via Settings and this default will never be used. Prior
/// to the fix for #403 (part 2) this always recreated an empty
/// ~/Documents/StemDeck/jobs, since the backend's own ensure_runtime_dirs
/// (app/core/config.py) already mkdirs whichever JOBS_DIR actually wins that
/// precedence -- this path only needs to exist when it is the one in use.
fn documents_stemdeck_dir(app: &tauri::AppHandle) -> Result<PathBuf, String> {
let documents = app.path().document_dir().map_err(|e| e.to_string())?;
Ok(documents.join("StemDeck"))
}
/// The stems/jobs folder as it exists right now: the backend's own
/// settings.json `jobs_dir` override if the user relocated it (#354) and that
/// folder still exists, otherwise the Documents default. Mirrors
/// app/core/config.py's `_stored_jobs_dir()` precedence exactly, read
/// directly from disk (not over IPC/HTTP) so this works even before the
/// backend process is up.
fn current_jobs_dir(app: &tauri::AppHandle) -> PathBuf {
if let Ok(data_dir) = local_data_dir() {
let settings_path = data_dir.join("settings.json");
if let Ok(text) = fs::read_to_string(&settings_path) {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) {
if let Some(configured) = json.get("jobs_dir").and_then(|v| v.as_str()) {
let candidate = PathBuf::from(configured);
if candidate.is_dir() {
return candidate;
}
}
}
}
}
documents_dir_for_jobs(app)
}
/// Returns <current jobs folder>/user-data.json (library metadata store).
///
/// Lives *inside* the jobs folder (not its parent) so relocating stems via
/// Settings (#354) carries this along automatically -- move_library()
/// (app/core/stems_location.py) already moves every entry it finds inside
/// the jobs folder one by one, so a plain file sitting there (same as
/// registry.json) needs no special-casing on that side. Before #403 this
/// lived at the jobs folder's *parent* (~/Documents/StemDeck/user-data.json),
/// which relocation never touched -- a stems move would "forget" favorites,
/// folder layout, and per-job mixer state even though the audio moved fine.
///
/// One-time migration: if the new location has nothing yet, copy (not move)
/// any pre-#403 file found at the old parent-folder path. Copy rather than
/// delete so a problem here can never lose the only copy of that data.
fn documents_store_path(app: &tauri::AppHandle) -> Result<PathBuf, String> {
let jobs_dir = current_jobs_dir(app);
fs::create_dir_all(&jobs_dir)
.map_err(|e| format!("failed to create {}: {e}", jobs_dir.display()))?;
let new_path = jobs_dir.join("user-data.json");
if !new_path.is_file() {
if let Ok(old_path) = documents_stemdeck_dir(app).map(|d| d.join("user-data.json")) {
if old_path.is_file() && old_path != new_path {
let _ = fs::copy(&old_path, &new_path);
}
}
}
Ok(new_path)
}
/// True if `path` exists and contains at least one entry. Used to tell an
/// already-in-use default folder apart from one nothing has ever written to.
fn directory_has_entries(path: &Path) -> bool {
fs::read_dir(path)
.map(|mut entries| entries.next().is_some())
.unwrap_or(false)
}
/// The DEFAULT stems folder. Does NOT create it -- see documents_stemdeck_dir
/// for why.
///
/// Handed to the backend as STEMDECK_DEFAULT_JOBS_DIR, not STEMDECK_JOBS_DIR:
/// the latter means "this deployment pins the location" and would override the
/// folder the user picked in Settings (#354). The backend owns that choice; it
/// is the one that has to move the library when it changes, including
/// creating whichever path wins (app/core/config.py's ensure_runtime_dirs).
///
/// Two candidates, resolved in this order:
///
/// 1. ~/Documents/StemDeck/jobs, if it already has anything in it. Every
/// install before this default existed used this path, so an existing
/// user's real library lives there without any explicit `jobs_dir` in
/// settings.json to record it -- it was simply "the default." Checking
/// disk content directly (rather than writing a one-time migration flag
/// into settings.json, which only the backend otherwise writes) keeps this
/// self-contained: nothing to persist, no other-process race, and it stays
/// correct on every future launch for as long as that folder holds data.
/// 2. Otherwise, for the Windows portable package, local_data_dir()/jobs --
/// i.e. next to data/cache and data/models inside the package itself,
/// rather than leaving a footprint in Documents. Non-portable installs
/// (installer builds, macOS, Linux) keep candidate 1 either way: the
/// original Documents rationale (visible in Finder/Explorer, eligible for
/// OneDrive/iCloud backup, survives reinstalls) still applies to them.
fn documents_dir_for_jobs(app: &tauri::AppHandle) -> PathBuf {
let legacy_default = match documents_stemdeck_dir(app) {
Ok(dir) => dir.join("jobs"),
Err(_) => {
return local_data_dir()
.map(|d| d.join("jobs"))
.unwrap_or_else(|_| PathBuf::from("jobs"));
}
};
if directory_has_entries(&legacy_default) {
return legacy_default;
}
if let Ok(root) = app_root() {
if is_portable_package(&root) {
if let Ok(data_dir) = local_data_dir() {
return data_dir.join("jobs");
}
}
}
legacy_default
}
/// Native folder picker for the stems location. Returns None when the user
/// cancels, which the UI treats as "leave it where it is".
#[tauri::command]
async fn pick_stems_folder(app: tauri::AppHandle) -> Result<Option<String>, String> {
use tauri_plugin_dialog::DialogExt;
let (tx, rx) = std::sync::mpsc::channel();
app.dialog()
.file()
.set_title("Choose where StemDeck stores extracted stems")
.pick_folder(move |path| {
let _ = tx.send(path);
});
let picked = rx.recv().map_err(|e| e.to_string())?;
Ok(picked.map(|p| p.to_string()))
}
/// Get a value from the persistent user-data store.
#[tauri::command]
fn store_get(app: tauri::AppHandle, key: String) -> Result<Option<serde_json::Value>, String> {
let path = documents_store_path(&app)?;
let store = app.store(path).map_err(|e| e.to_string())?;
Ok(store.get(&key))
}
/// Set a value in the persistent user-data store and immediately flush to disk.
#[tauri::command]
fn store_set(app: tauri::AppHandle, key: String, value: serde_json::Value) -> Result<(), String> {
let path = documents_store_path(&app)?;
let store = app.store(path).map_err(|e| e.to_string())?;
store.set(key, value);
store.save().map_err(|e| e.to_string())
}
/// Clear the persistent user-data store entirely (Settings -> General ->
/// "Reset app data"). Complements the backend's own job-data wipe (POST
/// /api/reset) -- together they fully clear a user's local StemDeck state,
/// including the per-job mixer-state keys (stemdeck:mix:<job_id>) that have
/// no fixed enumeration to clear individually.
#[tauri::command]
fn reset_user_data(app: tauri::AppHandle) -> Result<(), String> {
let path = documents_store_path(&app)?;
let store = app.store(path).map_err(|e| e.to_string())?;
store.clear();
store.save().map_err(|e| e.to_string())
}
/// Called by JS after the one-time localStorage → store migration completes.
/// Writing this flag allows the setup hook to safely clear stale WebKit data
/// on subsequent version upgrades.
#[tauri::command]
fn mark_store_migration_done() {
match local_data_dir() {
Ok(d) => {
if let Err(e) = fs::write(d.join("store_migration_done"), "") {
eprintln!("[stemdeck] failed to write migration flag: {e}");
}
}
Err(e) => eprintln!("[stemdeck] could not write migration flag: {e}"),
}
}
/// Delete stale WebKit data directories on macOS so a new app version starts
/// with a clean WebView. Only called after the JS store migration is confirmed
/// (store_migration_done flag exists), ensuring no user data is lost.
#[cfg(target_os = "macos")]
fn clear_webkit_data() {
let home = match std::env::var("HOME") {
Ok(h) => h,
Err(_) => return,
};
let targets = [
format!("{home}/Library/WebKit/app.stemdeck.desktop"),
format!("{home}/Library/WebKit/stemdeck"),
];
for path in &targets {
if let Err(e) = fs::remove_dir_all(path) {
if e.kind() != std::io::ErrorKind::NotFound {
eprintln!("[stemdeck] WebKit cleanup failed for {path}: {e}");
}
}
}
}
/// Returns current runtime state: Python path, FFmpeg path, and persisted torch device.
#[tauri::command]
fn probe_runtime() -> Result<RuntimeProbe, String> {
let root = app_root()?;
let data_dir = local_data_dir()?;
let python = python_path(&root);
if let Some(path) = python.as_deref() {
patch_pyvenv_cfg(path);
}
let ffmpeg = resolve_existing_ffmpeg(&data_dir);
let torch_device = read_config_str(&data_dir, "torchDevice");
let torch_device_reason = effective_device_reason(
read_config_str(&data_dir, "torchDeviceReason"),
is_cpu_only_package(&root),
);
Ok(RuntimeProbe {
app_root: root.display().to_string(),
data_dir: data_dir.display().to_string(),
python_ready: python.as_ref().is_some_and(|p| python_stdlib_ok(p)),
python_path: python.map(|p| p.display().to_string()),
ffmpeg_ready: ffmpeg.is_some(),
ffmpeg_path: ffmpeg.map(|p| p.display().to_string()),
torch_device,
torch_device_reason,
})
}
/// Read a single string field from data/config.json, returning None on any error.
fn read_config_str(data_dir: &std::path::Path, key: &str) -> Option<String> {
let text = fs::read_to_string(data_dir.join("config.json")).ok()?;
let value: serde_json::Value = serde_json::from_str(&text).ok()?;
value.get(key)?.as_str().map(|s| s.to_string())
}
/// Returns the current state of the bundled Python runtime pack (manifest, archive, install).
#[tauri::command]
fn runtime_pack_status() -> Result<RuntimePackStatus, String> {
let root = app_root()?;
let data_dir = local_data_dir()?;
let runtime_dir = runtime_dir(&data_dir);
let backend_dir = runtime_dir.join("backend");
let python = runtime_python_path(&data_dir);
let manifest_path = runtime_manifest_path(&root);
let manifest = manifest_path
.as_deref()
.and_then(|path| read_runtime_manifest(path).ok());
let archive_path = manifest
.as_ref()
.map(|item| runtime_archive_path(&data_dir, item));
let installed_version = read_runtime_install_manifest(&runtime_dir)
.and_then(|value| value.get("version")?.as_str().map(|text| text.to_string()));
Ok(RuntimePackStatus {
manifest_ready: manifest.is_some(),
manifest_path: manifest_path.map(|path| path.display().to_string()),
runtime_ready: backend_dir.join("app").is_dir() && python.is_file(),
runtime_dir: runtime_dir.display().to_string(),
backend_ready: backend_dir.join("app").is_dir(),
python_ready: python.is_file(),
archive_ready: archive_path.as_ref().is_some_and(|path| path.is_file()),
archive_path: archive_path.map(|path| path.display().to_string()),
installed_version,
manifest,
})
}
/// Downloads the Python runtime pack archive, emitting progress events to the frontend.
#[tauri::command]
async fn download_runtime_pack(app_handle: tauri::AppHandle) -> Result<RuntimeArchive, String> {
ensure_workspace()?;
let root = app_root()?;
let data_dir = local_data_dir()?;
let manifest = load_runtime_manifest(&root)?;
validate_runtime_manifest(&manifest)?;
let archive = runtime_archive_path(&data_dir, &manifest);
if let Some(parent) = archive.parent() {
fs::create_dir_all(parent)
.map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
}
download_file_with_progress(&manifest.runtime_url, &archive, &app_handle).await?;
verify_runtime_archive(&manifest, &archive)
}
/// Verifies the SHA256 of a previously downloaded runtime pack archive.
#[tauri::command]
fn verify_runtime_pack() -> Result<RuntimeArchive, String> {
let root = app_root()?;
let data_dir = local_data_dir()?;
let manifest = load_runtime_manifest(&root)?;
validate_runtime_manifest(&manifest)?;
let archive = runtime_archive_path(&data_dir, &manifest);
verify_runtime_archive(&manifest, &archive)
}
/// Extracts the verified runtime pack archive and atomically swaps it into place.
#[tauri::command]
fn extract_runtime_pack() -> Result<RuntimePackStatus, String> {
ensure_workspace()?;
let root = app_root()?;
let data_dir = local_data_dir()?;
let manifest = load_runtime_manifest(&root)?;
validate_runtime_manifest(&manifest)?;
let archive = runtime_archive_path(&data_dir, &manifest);
verify_runtime_archive(&manifest, &archive)?;
let runtime = runtime_dir(&data_dir);
let tmp = data_dir.join("runtime.tmp");
let old = data_dir.join("runtime.old");
if tmp.exists() {
fs::remove_dir_all(&tmp).map_err(|e| format!("failed to remove {}: {e}", tmp.display()))?;
}
fs::create_dir_all(&tmp).map_err(|e| format!("failed to create {}: {e}", tmp.display()))?;
extract_tar_archive(&archive, &tmp)?;
let extracted = tmp.join("runtime");
if !extracted.join("backend").join("app").is_dir() {
return Err("runtime archive did not contain runtime/backend/app".to_string());
}
if !extracted
.join("python")
.join("bin")
.join("python")
.is_file()
{
return Err("runtime archive did not contain runtime/python/bin/python".to_string());
}
let install_manifest = serde_json::json!({
"version": manifest.version,
"arch": manifest.arch,
"runtimeUrl": manifest.runtime_url,
"runtimeSha256": manifest.runtime_sha256,
"installedAt": unix_timestamp(),
});
fs::write(
extracted.join("runtime-manifest.json"),
serde_json::to_string_pretty(&install_manifest)
.map_err(|e| format!("failed to serialize runtime install manifest: {e}"))?
+ "\n",
)
.map_err(|e| format!("failed to write runtime manifest: {e}"))?;
if old.exists() {
fs::remove_dir_all(&old).map_err(|e| format!("failed to remove {}: {e}", old.display()))?;
}
if runtime.exists() {
fs::rename(&runtime, &old)
.map_err(|e| format!("failed to move existing runtime aside: {e}"))?;
}
fs::rename(&extracted, &runtime).map_err(|e| format!("failed to install runtime: {e}"))?;
// Cleanup is non-fatal; log warnings rather than silently discarding errors.
if let Err(e) = fs::remove_dir_all(&tmp) {
if let Ok(d) = local_data_dir() {
append_to_setup_log(&d, &format!("cleanup warning: {}: {e}", tmp.display()));
}
}
if let Err(e) = fs::remove_dir_all(&old) {
if let Ok(d) = local_data_dir() {
append_to_setup_log(&d, &format!("cleanup warning: {}: {e}", old.display()));
}
}
// The archive has done its job (#356). Keeping it meant every pack a user
// ever installed stayed on disk at full size; a retry can download it again,
// which costs bandwidth once rather than hundreds of megabytes forever.
let freed = prune_downloads(&data_dir, None);
if freed > 0 {
append_to_setup_log(
&data_dir,
&format!(
"removed {} MB of installed runtime archives",
freed / 1_048_576
),
);
}
let python = runtime.join("python").join("bin").join("python");
patch_pyvenv_cfg(&python);
runtime_pack_status()
}
/// Delete the `.old` siblings and staging dir an in-app update leaves at the
/// app root (#421). Best-effort and idempotent: whatever is still locked by the
/// outgoing process this launch is simply picked up on the next one.
fn sweep_update_leftovers() {
let Ok(root) = app_root() else { return };
for name in ["backend.old", "python.old", "_update_app.tmp"] {
let stale = root.join(name);
if stale.is_dir() {
let _ = fs::remove_dir_all(&stale);
}
}
let stale_exe = root.join(format!("{APP_EXE_NAME}.old"));
if stale_exe.is_file() {
let _ = fs::remove_file(&stale_exe);
}
}
/// The Python dependency-set id of the runtime currently on disk, written into
/// `python/runtime-version.json` by make-portable.ps1. `None` when the marker
/// is absent -- a pre-#421 install, a macOS build, or a source checkout.
///
/// The frontend compares this against the release's published runtime id and
/// only offers an in-app update when they match, since the updater cannot
/// replace python/ (see `AppUpdatePlan`). `None` is treated as "cannot verify",
/// which sends the user to the full-package download rather than risking an app
/// layer whose imports the installed runtime may not satisfy.
#[tauri::command]
fn installed_runtime_id() -> Option<String> {
let root = app_root().ok()?;
let text = fs::read_to_string(root.join("python").join("runtime-version.json")).ok()?;
parse_runtime_id(&text)
}
/// Split from the command above so the marker's on-disk contract -- the exact
/// shape make-portable.ps1 writes -- is unit-testable without an app root.
fn parse_runtime_id(text: &str) -> Option<String> {
let value: serde_json::Value = serde_json::from_str(text).ok()?;
value.get("runtimeId")?.as_str().map(|s| s.to_string())
}
/// Decides whether the latest release can be applied in place, and resolves its
/// checksum. Windows and Linux; every other platform reports unsupported.
///
/// An in-app update is offered only when the release's Python dependency set
/// matches the installed one, because the updater cannot replace `python/`
/// (see `AppUpdatePlan`). Any uncertainty -- an unreachable asset, an install
/// with no recorded runtime id, a malformed checksum -- reports unsupported, so
/// the UI falls back to the full download rather than risking an app layer
/// whose imports the installed runtime cannot satisfy.
#[tauri::command]
async fn check_app_update(query: AppUpdateQuery) -> Result<AppUpdateAvailability, String> {
#[cfg(not(any(windows, target_os = "linux")))]
{
let _ = query;
Ok(AppUpdateAvailability {
supported: false,
reason: Some("in-app updates are not available on this platform".to_string()),
..Default::default()
})
}
#[cfg(any(windows, target_os = "linux"))]
{
let unsupported = |reason: &str| {
Ok(AppUpdateAvailability {
supported: false,
reason: Some(reason.to_string()),
..Default::default()
})
};
// A root-owned install (Linux `install.sh --global` puts it in
// /opt/stemdeck) cannot rewrite itself. Check before promising an
// update we would fail to apply.
match app_root() {
Ok(root) if !app_root_is_writable(&root) => {
return unsupported("this install is not writable by the current user");
}
Err(e) => return unsupported(&format!("could not resolve the app directory: {e}")),
_ => {}
}
let Some(installed) = installed_runtime_id() else {
return unsupported("this install records no runtime id");
};
let release_marker = match fetch_text(&query.runtime_id_url).await {
Ok(text) => text,
Err(e) => return unsupported(&format!("could not read the release runtime id: {e}")),
};
let Some(release_id) = parse_runtime_id(&release_marker) else {
return unsupported("the release runtime id could not be parsed");
};
if release_id != installed {
return unsupported(&format!(
"python dependencies changed ({installed} -> {release_id})"
));
}
let checksum_file = match fetch_text(&query.app_sha_url).await {
Ok(text) => text,
Err(e) => return unsupported(&format!("could not read the update checksum: {e}")),
};
let Some(sha256) = parse_sha256_line(&checksum_file) else {
return unsupported("the update checksum could not be parsed");
};
Ok(AppUpdateAvailability {
supported: true,
app_sha256: Some(sha256),
reason: None,
})
}
}
/// Fetch a small text file (a checksum, a version marker). Capped so a wrong
/// URL that points at something huge cannot be read into memory unbounded.
#[cfg(any(windows, target_os = "linux"))]
async fn fetch_text(url: &str) -> Result<String, String> {
const MAX_BYTES: usize = 64 * 1024;
let client = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(15))
.timeout(Duration::from_secs(60))
.build()
.map_err(|e| format!("failed to build HTTP client: {e}"))?;
let response = client
.get(url)
.send()
.await
.map_err(|e| format!("request failed: {e}"))?;
if !response.status().is_success() {
return Err(format!("HTTP {}", response.status()));
}
let bytes = response
.bytes()
.await
.map_err(|e| format!("read failed: {e}"))?;
if bytes.len() > MAX_BYTES {
return Err(format!("response larger than {MAX_BYTES} bytes"));
}
String::from_utf8(bytes.to_vec()).map_err(|e| format!("response was not valid UTF-8: {e}"))
}
/// Pull the hash out of a `<sha256> <filename>` checksum file, the shape
/// make-portable.ps1 writes (Get-FileHash + Set-Content). Rejects anything that
/// is not exactly one 64-char hex digest so a redirect to an HTML error page
/// can never be mistaken for a checksum.
#[cfg(any(windows, target_os = "linux", test))]
fn parse_sha256_line(text: &str) -> Option<String> {
let token = text.split_whitespace().next()?.to_ascii_lowercase();
let ok = token.len() == 64 && token.chars().all(|c| c.is_ascii_hexdigit());
ok.then_some(token)
}
/// Downloads and checksum-verifies the app-layer update. Windows and Linux
/// only: both ship a flat directory shaped for an in-place file swap.
#[tauri::command]
async fn download_app_update(
plan: AppUpdatePlan,
app_handle: tauri::AppHandle,
) -> Result<(), String> {
#[cfg(not(any(windows, target_os = "linux")))]
{
let _ = (plan, app_handle);
Err("in-app updates are not available on this platform".to_string())
}
#[cfg(any(windows, target_os = "linux"))]
{
let data_dir = local_data_dir()?;
let downloads = data_dir.join("downloads");
fs::create_dir_all(&downloads)
.map_err(|e| format!("failed to create {}: {e}", downloads.display()))?;
let app_archive = downloads.join(UPDATE_APP_ARCHIVE);
// Drop any archive left by an earlier, abandoned download so apply can
// never install something the current plan did not ask for.