AI media harness for planning, generating, and editing locally
TypeScript
Support custom weight folders in settings.json
Bittif6a13f0de778
diff --git a/docs/generator-weights.md b/docs/generator-weights.mdindex 11457a5..940e2c6 100644--- a/docs/generator-weights.md+++ b/docs/generator-weights.md@@ -74,6 +74,27 @@ Memory tiers account for the small amount of VRAM reserved by the driver.Click the template's download icon or **Download weights** in its editor todownload missing weights. Files go into `weights` beside `Slopus.exe`. If thatlocation cannot be written, Slopus uses a `weights` subfolder beside its log file.+To use custom locations, edit `%LOCALAPPDATA%\Slopus\settings.json`, which is+created automatically on startup:++```json+{+ "weightFolders": ["D:\\Projects\\weights"]+}+```++Each entry is an absolute path to the weight folder itself. Slopus checks custom+folders in list order, then `weights` beside the executable, then the log folder's+`weights` directory for an existing completed download. New downloads go to the+first writable folder in that same order. These locations apply to both model+weights and LoRAs. Changes take effect on the next download or removal without+restarting. An empty list keeps the default locations.++To move previously downloaded weights into a custom folder, move their matching+`.complete.json` records with them so Slopus can recognize and reuse the files+when you click Download. Only files with valid download records can be removed+through the app. Other app preferences continue to use WebView2 localStorage.+Downloads continue in the background when Settings is closed. Reopening Settingsshows the current progress as a color fill across the generator's template row.The fill tracks completed files plus progress through the current file.diff --git a/src-tauri/src/app_settings.rs b/src-tauri/src/app_settings.rsnew file mode 100644index 0000000..7e727ca--- /dev/null+++ b/src-tauri/src/app_settings.rs@@ -0,0 +1,64 @@+use serde::{Deserialize, Serialize};+use std::{fs::{self, OpenOptions}, io::{self, Write}, path::{Path, PathBuf}};++#[derive(Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AppSettings {+ #[serde(default)]+ pub weight_folders: Vec<PathBuf>,+}++pub fn ensure_file(data_directory: &Path) -> io::Result<()> {+ fs::create_dir_all(data_directory)?;+ match OpenOptions::new().write(true).create_new(true).open(data_directory.join("settings.json")) {+ Ok(mut file) => file.write_all(b"{\n \"weightFolders\": []\n}\n"),+ Err(error) if error.kind() == io::ErrorKind::AlreadyExists => Ok(()),+ Err(error) => Err(error),+ }+}++/// Read on each weight operation so edits take effect without restarting.+pub fn load(data_directory: &Path) -> Result<AppSettings, String> {+ let path = data_directory.join("settings.json");+ ensure_file(data_directory).map_err(|error| format!("Could not create {}: {error}", path.display()))?;+ let bytes = fs::read(&path).map_err(|error| format!("Could not read {}: {error}", path.display()))?;+ let settings: AppSettings = serde_json::from_slice(&bytes)+ .map_err(|error| format!("Invalid {}: {error}", path.display()))?;+ for folder in &settings.weight_folders {+ if !folder.is_absolute() || folder.to_string_lossy().contains('\0') {+ return Err(format!("Invalid {}: weightFolders must contain absolute folder paths.", path.display()));+ }+ }+ Ok(settings)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn creates_defaults_and_preserves_and_reloads_user_settings() {+ let directory = tempfile::tempdir().unwrap();+ assert!(load(directory.path()).unwrap().weight_folders.is_empty());+ let path = directory.path().join("settings.json");+ let custom = directory.path().join("custom models");+ let content = serde_json::to_vec(&serde_json::json!({ "weightFolders": [custom], "futureSetting": true })).unwrap();+ fs::write(&path, &content).unwrap();+ ensure_file(directory.path()).unwrap();+ assert_eq!(fs::read(&path).unwrap(), content);+ assert_eq!(load(directory.path()).unwrap().weight_folders, vec![custom]);+ fs::write(&path, b"{}").unwrap();+ assert!(load(directory.path()).unwrap().weight_folders.is_empty());+ }++ #[test]+ fn reports_invalid_settings_without_overwriting_them() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("settings.json");+ for content in [r#"{"weightFolders": ["relative/path"]}"#, r#"{"weightFolders": [""]}"#, r#"{"weightFolders": "wrong"}"#, "{"] {+ fs::write(&path, content).unwrap();+ assert!(load(directory.path()).err().unwrap().contains("settings.json"));+ assert_eq!(fs::read_to_string(&path).unwrap(), content);+ }+ }+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex b1c1cf7..f033e65 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -11,6 +11,7 @@ use tauri_plugin_dialog::DialogExt;mod agent;mod agent_commands;mod app_paths;+mod app_settings;mod cuda_support;mod diagnostics;mod export;@@ -2952,6 +2953,7 @@ pub fn run() {.setup(|app| {use tauri::Manager as _;let data_directory = app_paths::prepare(app.handle())?;+ app_settings::ensure_file(&data_directory)?;let window_config = app.config().app.windows.first().ok_or_else(|| io::Error::other("Missing main window configuration"))?;tauri::WebviewWindowBuilder::from_config(app, window_config)?.data_directory(data_directory)diff --git a/src-tauri/src/weights.rs b/src-tauri/src/weights.rsindex 85b9976..6600e11 100644--- a/src-tauri/src/weights.rs+++ b/src-tauri/src/weights.rs@@ -43,21 +43,44 @@ fn destination_name(url: &Url) -> String {format!("{hash:016x}-{}", if filename.is_empty() { "weights.bin" } else { &filename })}-fn writable_weights(parent: &Path) -> Result<PathBuf, String> {- let directory = parent.join("weights");- fs::create_dir_all(&directory).map_err(|error| error.to_string())?;+fn writable_weights(directory: &Path) -> Result<PathBuf, String> {+ fs::create_dir_all(directory).map_err(|error| error.to_string())?;let mut random = [0u8; 16];getrandom::fill(&mut random).map_err(|error| error.to_string())?;let probe = directory.join(format!(".write-check-{:x}", u128::from_le_bytes(random)));let file = OpenOptions::new().write(true).create_new(true).open(&probe).map_err(|error| error.to_string())?;drop(file);fs::remove_file(probe).map_err(|error| error.to_string())?;- Ok(directory)+ Ok(directory.to_path_buf())}-fn weights_directory(primary: &Path, fallback: &Path) -> Result<PathBuf, String> {- writable_weights(primary).or_else(|_| writable_weights(fallback))- .map_err(|error| format!("Could not create a writable weights folder: {error}"))+fn weight_roots(custom: &[PathBuf], primary: PathBuf, fallback: PathBuf) -> Vec<PathBuf> {+ let mut roots = Vec::new();+ for root in custom.iter().cloned().chain([primary, fallback]) {+ if !roots.contains(&root) { roots.push(root); }+ }+ roots+}++fn configured_weight_roots(app: &AppHandle) -> Result<Vec<PathBuf>, String> {+ let data_directory = crate::app_paths::data_directory(app);+ let settings = crate::app_settings::load(&data_directory)?;+ let executable = std::env::current_exe().map_err(|error| error.to_string())?;+ let primary = executable.parent().ok_or("Could not locate Slopus.exe.")?.join("weights");+ let fallback = diagnostics::log_info().ok().and_then(|info| Path::new(&info.path).parent().map(|parent| parent.join("weights")))+ .unwrap_or_else(|| data_directory.join("logs/weights"));+ Ok(weight_roots(&settings.weight_folders, primary, fallback))+}++fn weights_directory(roots: &[PathBuf]) -> Result<PathBuf, String> {+ let mut errors = Vec::new();+ for root in roots {+ match writable_weights(root) {+ Ok(directory) => return Ok(directory),+ Err(error) => errors.push(format!("{}: {error}", root.display())),+ }+ }+ Err(format!("Could not create a writable weights folder: {}", errors.join("; ")))}fn cached_file(path: &Path, url: &Url) -> bool {@@ -67,6 +90,16 @@ fn cached_file(path: &Path, url: &Url) -> bool {&& fs::metadata(path).is_ok_and(|file| file.is_file() && file.len() == info.bytes))}+fn transfer_from_roots(url: &Url, roots: &[PathBuf], cancelled: &AtomicBool, progress: impl FnMut(u64, Option<u64>)) -> Result<String, String> {+ if cancelled.load(Ordering::Relaxed) { return Err("Download cancelled.".into()); }+ // Search every location before choosing a destination, including read-only caches.+ for root in roots {+ let path = root.join(destination_name(url));+ if cached_file(&path, url) { return Ok(path.to_string_lossy().into_owned()); }+ }+ transfer(url, &weights_directory(roots)?, cancelled, progress)+}+fn transfer(url: &Url, directory: &Path, cancelled: &AtomicBool, mut progress: impl FnMut(u64, Option<u64>)) -> Result<String, String> {let destination = directory.join(destination_name(url));if cached_file(&destination, url) { return Ok(destination.to_string_lossy().into_owned()); }@@ -133,15 +166,8 @@ pub async fn download_weight(app: AppHandle, downloads: State<'_, WeightDownload}let event_id = request_id.clone();let result = tauri::async_runtime::spawn_blocking(move || {- let executable = std::env::current_exe().map_err(|error| error.to_string())?;- let primary = executable.parent().ok_or("Could not locate Slopus.exe.")?;- // Try beside the executable first, even when diagnostics are unavailable.- let directory = writable_weights(primary).or_else(|_| {- let log = diagnostics::log_info()?;- let path = PathBuf::from(log.path);- weights_directory(primary, path.parent().ok_or("Could not locate the log directory.")?)- })?;- transfer(&url, &directory, &cancelled, |downloaded, total| {+ let roots = configured_weight_roots(&app)?;+ transfer_from_roots(&url, &roots, &cancelled, |downloaded, total| {let _ = app.emit("weight-download-progress", Progress { request_id: event_id.clone(), downloaded, total });})}).await.map_err(|error| error.to_string()).and_then(|result| result);@@ -214,13 +240,9 @@ fn validate_removal(path: &Path, roots: &[PathBuf]) -> Result<(), String> {}#[tauri::command]-pub async fn remove_downloaded_weights(paths: Vec<String>) -> Result<(), String> {+pub async fn remove_downloaded_weights(app: AppHandle, paths: Vec<String>) -> Result<(), String> {tauri::async_runtime::spawn_blocking(move || {- let executable = std::env::current_exe().map_err(|error| error.to_string())?;- let mut roots = vec![executable.parent().ok_or("Could not locate Slopus.exe.")?.join("weights")];- if let Ok(info) = diagnostics::log_info() {- if let Some(parent) = Path::new(&info.path).parent() { roots.push(parent.join("weights")); }- }+ let roots = configured_weight_roots(&app)?;let paths: Vec<PathBuf> = paths.into_iter().map(PathBuf::from).collect();for path in &paths { validate_removal(path, &roots)?; }for path in paths {@@ -270,7 +292,49 @@ mod tests {let folder = tempfile::tempdir().unwrap();let blocked = folder.path().join("blocked");fs::write(&blocked, b"file, not a directory").unwrap();- assert_eq!(weights_directory(&blocked, folder.path()).unwrap(), folder.path().join("weights"));+ assert_eq!(weights_directory(&[blocked.join("weights"), folder.path().join("weights")]).unwrap(), folder.path().join("weights"));+ }++ #[test]+ fn custom_folders_are_used_directly_in_order_with_default_fallbacks() {+ let folder = tempfile::tempdir().unwrap();+ let blocked = folder.path().join("blocked");+ fs::write(&blocked, b"not a directory").unwrap();+ let custom = folder.path().join("custom models");+ let primary = folder.path().join("exe/weights");+ let fallback = folder.path().join("logs/weights");+ let roots = weight_roots(&[blocked.clone(), custom.clone(), custom.clone()], primary.clone(), fallback.clone());+ assert_eq!(roots, vec![blocked, custom.clone(), primary.clone(), fallback.clone()]);+ let url = server(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\ndata");+ let downloaded = transfer_from_roots(&url, &roots, &AtomicBool::new(false), |_, _| {}).unwrap();+ assert_eq!(Path::new(&downloaded).parent(), Some(custom.as_path()));+ assert!(!custom.join("weights").exists());+ assert!(!primary.exists());+ assert!(validate_removal(Path::new(&downloaded), &roots).is_ok());+ assert!(validate_removal(Path::new(&downloaded), &[primary.clone(), fallback.clone()]).is_err());+ assert_eq!(weight_roots(&[], primary.clone(), fallback.clone()), vec![primary, fallback]);+ }++ #[test]+ fn searches_all_folders_for_completed_files_before_creating_a_download_destination() {+ let folder = tempfile::tempdir().unwrap();+ let custom = folder.path().join("custom");+ let primary = folder.path().join("exe/weights");+ let fallback = folder.path().join("logs/weights");+ fs::create_dir_all(&fallback).unwrap();+ let roots = weight_roots(&[custom.clone()], primary.clone(), fallback.clone());+ let url = server(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\ndata");+ let downloaded = transfer(&url, &fallback, &AtomicBool::new(false), |_, _| {}).unwrap();+ // The server accepts only one request; reuse must work without network access.+ assert_eq!(transfer_from_roots(&url, &roots, &AtomicBool::new(false), |_, _| {}).unwrap(), downloaded);+ assert!(!custom.exists());+ assert!(!primary.exists());+ fs::create_dir_all(&custom).unwrap();+ let moved = custom.join(destination_name(&url));+ fs::rename(&downloaded, &moved).unwrap();+ fs::rename(Path::new(&downloaded).with_extension("complete.json"), moved.with_extension("complete.json")).unwrap();+ assert_eq!(transfer_from_roots(&url, &roots, &AtomicBool::new(false), |_, _| {}).unwrap(), moved.to_string_lossy());+ assert!(transfer_from_roots(&url, &roots, &AtomicBool::new(true), |_, _| {}).is_err());}#[test]