From 2f56011b31621dae188eb49e38bf6adeb7ef76c8 Mon Sep 17 00:00:00 2001 From: Nardo021 Date: Tue, 3 Nov 2026 12:11:21 +1100 Subject: [PATCH 1/2] fix: recover a damaged profile collection from an explicit backup Plain reset could not load a corrupt config-profiles file, while the UI told users to reset or repair it. Co-authored-by: Cursor --- docs/architecture.md | 4 +- docs/command-line.md | 5 +- docs/command-line.zh-CN.md | 2 +- docs/configuration.md | 64 +++- src/config.rs | 671 +++++++++++++++++++++++++++++++++++-- src/main.rs | 101 +++++- src/ui.rs | 32 +- src/ui/geometry_view.rs | 4 +- tests/cli_contract.rs | 251 ++++++++++++++ 9 files changed, 1074 insertions(+), 60 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index b250041..61a8822 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -94,7 +94,9 @@ User configuration is stored as at most three named profiles in and per-profile revisions are committed atomically under a cross-process lock. On first use, the existing `config-v2.json` is preserved and imported as the `default` profile. The tray supports revision-checked live reloads without -changing a mapping that is already running. See +changing a mapping that is already running. A damaged profile collection is +left unchanged by ordinary profile commands. `sbms config reset --all --backup` +backs up the original bytes and rebuilds the entire collection. See [configuration.md](configuration.md) for the storage, CLI, JSON and Rust API contracts. diff --git a/docs/command-line.md b/docs/command-line.md index 569e407..5c9361f 100644 --- a/docs/command-line.md +++ b/docs/command-line.md @@ -20,4 +20,7 @@ sbms shutdown foreground session cleanly. A mapping plan can contain up to sixteen mirror and stream-only groups. Up to three persistent configuration profiles can coexist; see [Configuration profiles](configuration.md) for import, export, -activation and hot-reload interfaces. +activation and hot-reload interfaces. `sbms config reset` resets only the +active profile in a valid collection. `sbms config reset --all --backup` +backs up the raw profile file and rebuilds the entire collection; both flags +are required. diff --git a/docs/command-line.zh-CN.md b/docs/command-line.zh-CN.md index e41c0c2..71f2480 100644 --- a/docs/command-line.zh-CN.md +++ b/docs/command-line.zh-CN.md @@ -18,4 +18,4 @@ sbms shutdown `sbms list` 会列出 `--target` 所需的稳定显示器 ID。前台运行 `map` 时按 Enter,可以正常停止并完成恢复。映射计划最多可混合十六组本地镜像和纯串流 虚拟桌面。最多可以同时保存三套配置;导入、导出、激活和热加载接口见 -[配置档案接口](configuration.md)。 +[配置档案接口](configuration.md)。`sbms config reset` 只重置一份有效配置集合里的当前档案。`sbms config reset --all --backup` 会按原始字节备份整个配置集合,然后重建为默认集合;两个参数必须同时给出。该命令会丢弃全部档案和全局偏好,不会删除显示器覆盖、日志、串流凭据或旧版迁移文件。 diff --git a/docs/configuration.md b/docs/configuration.md index 6f2e176..cb49f61 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -34,6 +34,7 @@ sbms config reload sbms config set-target sbms config clear-target sbms config reset +sbms config reset --all --backup ``` - `path` prints the profile-store path. @@ -53,12 +54,61 @@ sbms config reset - `activate` atomically changes the active profile and requests a live reload. - `delete` rejects the active profile and unknown profiles. - `reload` requests that the running tray reload the already-active profile. -- `set-target`, `clear-target` and `reset` update only the active profile and - request a live reload. +- `set-target` and `clear-target` update only the active profile and request + a live reload. +- `reset` with no other arguments resets only the active profile inside a + valid collection. Other profiles and the global preferences + `launch_intro_disabled` and `auto_map_on_login` stay unchanged. A missing + profile store is created from the normal default. If the store is damaged, + unreadable, or uses a newer schema version, `reset` fails and does not write. +- `reset --all --backup` rebuilds the entire profile collection. Both flags are + required, in either order. Any other argument combination prints usage and + exits without writing. A successful configuration commit is not rolled back when the tray is not running. CLI output reports `reload=not-running`; the configuration is loaded -on the next tray or mapping start. +on the next tray or mapping start. After `reset --all --backup` commits, +`reload=failed` means the new collection is already on disk and only the tray +notification failed. + +## Damaged profile collection + +Ordinary profile commands, including `sbms config reset`, load the collection +before changing it. A truncated file, invalid JSON, or a version 1 collection +that fails semantic validation therefore cannot be repaired by `reset`. + +`sbms config reset --all --backup` is the explicit recovery command. Under the +existing cross-process profile lock it: + +1. Reads the current `config-profiles-v1.json` bytes. +2. Writes those exact bytes to a new file in the same directory: + `config-profiles-v1.json.recovery--.bak`. + The file is created with `create_new` and flushed before the store is + replaced, so a later recovery cannot overwrite an earlier backup. +3. Atomically replaces the store with one `default` profile at revision 1 and + default global preferences. + +The command discards every saved profile and both global preferences. It does +not delete display overrides, logs, stream credentials, `config-v2.json`, or +`config-v1.json`. + +A numeric `version` greater than 1 is a newer schema. Recovery refuses it and +leaves the file unchanged, without writing a backup. A non-numeric `version`, +truncated JSON, or any other file whose schema version cannot be recognized is +damaged. Only this command can rebuild it. The command also accepts a valid +collection: it still backs up the raw bytes and replaces the whole collection. +Permission errors and other read/write failures are not treated as damage: the +source file stays in place. If the backup itself fails, nothing is replaced. +If the backup succeeds and the atomic replacement fails, the command reports +that recovery was not committed and leaves the backup in place. + +```text +sbms config reset --all --backup +``` + +```text +recovered=default revision=1 backup=%LOCALAPPDATA%\SBMS\config-profiles-v1.json.recovery--.bak reload=not-running +``` ## JSON exchange format @@ -141,8 +191,12 @@ The public API is exported from `sbms::config`: - `ConfigProfileStore::default_store()` locates the collection. - `list`, `load_active` and `load_profile` return validated persistent state. -- `save_profile`, `save_active_as`, `activate`, `delete` and `update_active` - perform locked atomic transactions. +- `save_profile`, `save_active_as`, `activate`, `delete`, `update_active` and + `reset_active` perform locked atomic transactions. +- `recover_with_backup` is the locked recovery used by + `sbms config reset --all --backup`. It returns the new snapshot and the + backup path. `ConfigError::allows_profile_collection_recovery` is true only + for a damaged collection this build can rebuild. - `save_active_if_revision` is the compare-and-swap save operation for a pinned UI session. - `ConfigStore::load_strict` validates standalone import files; `save` writes diff --git a/src/config.rs b/src/config.rs index a2059e5..31dd9d6 100644 --- a/src/config.rs +++ b/src/config.rs @@ -28,6 +28,7 @@ use crate::limits::{ const CONFIG_VERSION: u32 = 2; const LEGACY_CONFIG_VERSION: u32 = 1; const CONFIG_PROFILES_VERSION: u32 = 1; +pub const RECOVER_PROFILE_COLLECTION_COMMAND: &str = "sbms config reset --all --backup"; pub const MAX_CONFIG_PROFILES: usize = 3; const DISPLAY_OVERRIDES_VERSION: u32 = 1; const CONFIG_DIRECTORY: &str = "SBMS"; @@ -217,6 +218,12 @@ pub struct ProfileDeleteOutcome { pub active_changed: bool, } +#[derive(Clone, Debug, PartialEq)] +pub struct ProfileRecovery { + pub snapshot: ProfileSnapshot, + pub backup_path: PathBuf, +} + #[derive(Clone, Debug)] pub struct ConfigProfileStore { path: PathBuf, @@ -292,6 +299,10 @@ impl ConfigError { pub fn new(message: impl Into) -> Self { Self(message.into()) } + + pub fn allows_profile_collection_recovery(&self) -> bool { + self.0.contains("is a damaged SBMS config profile store:") + } } impl Display for ConfigError { @@ -1283,17 +1294,7 @@ impl ConfigProfileStore { let mut profiles = if self.path.exists() { self.load_or_initialize_locked()? } else { - ConfigProfiles { - version: CONFIG_PROFILES_VERSION, - active_profile: "default".into(), - launch_intro_disabled: false, - auto_map_on_login: false, - profiles: vec![ConfigProfile { - id: "default".into(), - revision: 1, - config: AppConfig::default(), - }], - } + default_config_profiles() }; let active_id = profiles.active_profile.clone(); let profile = profiles @@ -1306,19 +1307,46 @@ impl ConfigProfileStore { Ok(result) } + pub fn recover_with_backup(&self) -> Result { + let _guard = CrossProcessConfigGuard::acquire()?; + let bytes = match fs::read(&self.path) { + Ok(bytes) => bytes, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + return Err(ConfigError(format!( + "config profile store {} does not exist and was not created", + self.path.display() + ))); + } + Err(error) => { + return Err(ConfigError(format!( + "could not read {}: {error}", + self.path.display() + ))); + } + }; + if let Some(version) = recognized_future_profiles_version(&bytes) { + return Err(future_profile_store(&self.path, &version)); + } + // Flush the original bytes before replacing the store. A backup error + // returns while the source file is still untouched. + let backup = write_unique_profile_backup(&self.path, &bytes)?; + let profiles = default_config_profiles(); + if let Err(error) = self.save_locked(&profiles) { + return Err(ConfigError(format!( + "config profile recovery was not committed; {}; backup remains at {}: {error}", + profile_store_after_failed_replace(&self.path, &bytes), + backup.display() + ))); + } + Ok(ProfileRecovery { + snapshot: snapshot(profiles.active()), + backup_path: backup, + }) + } + fn load_or_initialize_locked(&self) -> Result { match fs::read(&self.path) { - Ok(bytes) => { - let profiles = - serde_json::from_slice::(&bytes).map_err(|error| { - ConfigError(format!( - "{} is not a valid SBMS config profile store: {error}", - self.path.display() - )) - })?; - profiles.validate()?; - Ok(profiles) - } + Ok(bytes) => parse_profile_store(&self.path, &bytes), Err(error) if error.kind() == std::io::ErrorKind::NotFound => { let legacy_store = ConfigStore { path: self.legacy_config_path.clone(), @@ -1340,17 +1368,7 @@ impl ConfigProfileStore { } Err(error) => return Err(error), }; - let profiles = ConfigProfiles { - version: CONFIG_PROFILES_VERSION, - active_profile: "default".into(), - launch_intro_disabled: false, - auto_map_on_login: false, - profiles: vec![ConfigProfile { - id: "default".into(), - revision: 1, - config, - }], - }; + let profiles = single_profile_collection(config); self.save_locked(&profiles)?; Ok(profiles) } @@ -1403,6 +1421,206 @@ impl Drop for CrossProcessConfigGuard { } } +#[cfg(test)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ProfileStoreTestFault { + Backup, + Replace, +} + +#[cfg(test)] +thread_local! { + static PROFILE_STORE_TEST_FAULT: std::cell::Cell> = + const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +#[must_use] +struct ProfileStoreTestFaultGuard; + +#[cfg(test)] +impl Drop for ProfileStoreTestFaultGuard { + fn drop(&mut self) { + PROFILE_STORE_TEST_FAULT.with(|fault| fault.set(None)); + } +} + +#[cfg(test)] +fn inject_profile_store_fault(fault: ProfileStoreTestFault) -> ProfileStoreTestFaultGuard { + PROFILE_STORE_TEST_FAULT.with(|slot| slot.set(Some(fault))); + ProfileStoreTestFaultGuard +} + +#[cfg(test)] +fn consume_profile_store_test_fault(expected: ProfileStoreTestFault) -> bool { + PROFILE_STORE_TEST_FAULT.with(|slot| { + if slot.get() == Some(expected) { + slot.set(None); + true + } else { + false + } + }) +} + +fn single_profile_collection(config: AppConfig) -> ConfigProfiles { + ConfigProfiles { + version: CONFIG_PROFILES_VERSION, + active_profile: "default".into(), + launch_intro_disabled: false, + auto_map_on_login: false, + profiles: vec![ConfigProfile { + id: "default".into(), + revision: 1, + config, + }], + } +} + +fn default_config_profiles() -> ConfigProfiles { + single_profile_collection(AppConfig::default()) +} + +fn damaged_profile_store(path: &Path, detail: impl Display) -> ConfigError { + let path = path.display(); + ConfigError(format!( + "{path} is a damaged SBMS config profile store: {detail}. Run `{RECOVER_PROFILE_COLLECTION_COMMAND}` to back up and rebuild the entire profile collection" + )) +} + +fn future_profile_store(path: &Path, version: &str) -> ConfigError { + let path = path.display(); + ConfigError(format!( + "{path} uses config profiles version {version}, which is newer than this SBMS and was left unchanged" + )) +} + +fn recognized_future_profiles_version(bytes: &[u8]) -> Option { + let mut deserializer = serde_json::Deserializer::from_slice(bytes); + let value = serde_json::Value::deserialize(&mut deserializer).ok()?; + let version = value.as_object()?.get("version")?.as_number()?; + if let Some(integer) = version.as_u64() { + return (integer > u64::from(CONFIG_PROFILES_VERSION)).then(|| integer.to_string()); + } + if version.as_i64().is_some() { + return None; + } + let float = version.as_f64()?; + (float.is_finite() && float > f64::from(CONFIG_PROFILES_VERSION)).then(|| version.to_string()) +} + +fn parse_profile_store(path: &Path, bytes: &[u8]) -> Result { + if let Some(version) = recognized_future_profiles_version(bytes) { + return Err(future_profile_store(path, &version)); + } + let profiles = serde_json::from_slice::(bytes) + .map_err(|error| damaged_profile_store(path, error))?; + profiles + .validate() + .map_err(|error| damaged_profile_store(path, error))?; + Ok(profiles) +} + +fn profile_store_after_failed_replace(path: &Path, original: &[u8]) -> String { + match fs::read(path) { + Ok(current) if current == original => { + format!("original file {} is unchanged", path.display()) + } + Ok(_) => format!( + "original file {} no longer matches the backed-up bytes", + path.display() + ), + Err(error) => format!( + "original file {} could not be read after the failed replacement: {error}", + path.display() + ), + } +} + +fn backup_parent(source: &Path) -> Result<&Path, ConfigError> { + match source.parent() { + Some(parent) if !parent.as_os_str().is_empty() => Ok(parent), + Some(_) => Ok(Path::new(".")), + None => Err(ConfigError(format!( + "config profile backup path has no parent directory: {}", + source.display() + ))), + } +} + +fn write_backup_file(file: &mut File, bytes: &[u8]) -> std::io::Result<()> { + file.write_all(bytes)?; + file.sync_all() +} + +fn write_unique_profile_backup(source: &Path, bytes: &[u8]) -> Result { + #[cfg(test)] + if consume_profile_store_test_fault(ProfileStoreTestFault::Backup) { + return Err(ConfigError( + "could not create config profile backup: injected failure".into(), + )); + } + + let parent = backup_parent(source)?; + let file_name = source + .file_name() + .and_then(OsStr::to_str) + .unwrap_or(CONFIG_PROFILES_FILE); + let mut collision = None; + for _ in 0..128 { + let sequence = TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed); + let path = parent.join(format!( + "{file_name}.recovery-{}-{sequence}.bak", + std::process::id() + )); + match OpenOptions::new().write(true).create_new(true).open(&path) { + Ok(mut file) => { + if let Err(error) = write_backup_file(&mut file, bytes) { + drop(file); + let _ = fs::remove_file(&path); + return Err(ConfigError(format!( + "could not write config profile backup {}: {error}", + path.display() + ))); + } + drop(file); + match fs::read(&path) { + Ok(stored) if stored == bytes => return Ok(path), + Ok(_) => { + let _ = fs::remove_file(&path); + return Err(ConfigError(format!( + "config profile backup {} did not retain the original bytes", + path.display() + ))); + } + Err(error) => { + let _ = fs::remove_file(&path); + return Err(ConfigError(format!( + "could not read config profile backup {}: {error}", + path.display() + ))); + } + } + } + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + collision = Some(error); + } + Err(error) => { + return Err(ConfigError(format!( + "could not create config profile backup {}: {error}", + path.display() + ))); + } + } + } + Err(ConfigError(format!( + "could not allocate a unique config profile backup: {}", + collision + .map(|error| error.to_string()) + .unwrap_or_else(|| "too many attempts".into()) + ))) +} + fn snapshot(profile: &ConfigProfile) -> ProfileSnapshot { ProfileSnapshot { profile: ProfileRevision { @@ -1615,6 +1833,13 @@ fn create_temporary(parent: &Path, destination: &Path) -> Result<(PathBuf, File) } fn atomic_replace(temporary: &Path, destination: &Path) -> Result<(), ConfigError> { + #[cfg(test)] + if consume_profile_store_test_fault(ProfileStoreTestFault::Replace) { + return Err(ConfigError(format!( + "could not atomically replace {}: injected failure", + destination.display() + ))); + } let temporary_wide = wide(temporary.as_os_str()); let destination_wide = wide(destination.as_os_str()); let temporary_pcwstr = PCWSTR(temporary_wide.as_ptr()); @@ -2340,4 +2565,384 @@ mod tests { assert_eq!(profiles.load_active().unwrap(), updated); fs::remove_dir_all(root).unwrap(); } + + fn write_unrelated_files(root: &Path) -> Vec<(PathBuf, &'static [u8])> { + let files = [ + ( + DISPLAY_OVERRIDES_FILE, + br#"{"version":1,"displays":[]}"#.as_slice(), + ), + (CONFIG_FILE, br#"{"version":2,"groups":[]}"#), + (LEGACY_CONFIG_FILE, b"{legacy source"), + ("sbms.log", b"log-bytes"), + ("credentials.json", b"stream-secret"), + ]; + files + .into_iter() + .map(|(name, bytes)| { + let path = root.join(name); + fs::write(&path, bytes).unwrap(); + (path, bytes) + }) + .collect() + } + + fn assert_unrelated_unchanged(files: &[(PathBuf, &'static [u8])]) { + for (path, bytes) in files { + assert_eq!(fs::read(path).unwrap(), *bytes, "{}", path.display()); + } + } + + fn recovery_backups(root: &Path) -> Vec { + let mut paths: Vec<_> = fs::read_dir(root) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.contains(".recovery-") && name.ends_with(".bak")) + }) + .collect(); + paths.sort(); + paths + } + + fn temporary_profile_files(root: &Path) -> Vec { + fs::read_dir(root) + .unwrap() + .filter_map(|entry| { + let path = entry.ok()?.path(); + let name = path.file_name()?.to_str()?; + name.contains(".tmp").then_some(path) + }) + .collect() + } + + fn prepare_profile_bytes(name: &str, bytes: &[u8]) -> (PathBuf, ConfigProfileStore) { + let (root, store) = test_profile_store(name); + fs::create_dir_all(&root).unwrap(); + fs::write(store.path(), bytes).unwrap(); + (root, store) + } + + #[test] + fn explicit_recovery_restores_unreadable_profile_bytes_and_keeps_neighbors() { + let cases: &[(&str, &[u8])] = &[ + ("truncated", b"{not json"), + ("cut-off", br#"{"version":1,"profiles":["#), + ("non-utf8", b"\xff\xfe{not json"), + ("string-version", br#"{"version":"99","profiles":[]}"#), + ("incomplete-future", br#"{"version":99"#), + ]; + for (name, original) in cases { + let (root, store) = prepare_profile_bytes(name, original); + let unrelated = write_unrelated_files(&root); + let plain_reset = store.reset_active().unwrap_err(); + assert!( + plain_reset.allows_profile_collection_recovery(), + "{name}: {plain_reset}" + ); + assert!( + !plain_reset.to_string().contains("was not committed"), + "{name}" + ); + assert_eq!(fs::read(store.path()).unwrap(), *original, "{name}"); + assert!(recovery_backups(&root).is_empty(), "{name}"); + + let recovered = store.recover_with_backup().unwrap(); + assert_eq!( + fs::read(&recovered.backup_path).unwrap(), + *original, + "{name}" + ); + assert_eq!(recovered.snapshot.profile.id, "default"); + assert_eq!(recovered.snapshot.profile.revision, 1); + assert_eq!(recovered.snapshot.config, AppConfig::default()); + assert_ne!(fs::read(store.path()).unwrap(), *original, "{name}"); + let loaded = store.load_active().unwrap(); + assert_eq!(loaded, recovered.snapshot); + assert_unrelated_unchanged(&unrelated); + + let updated = store + .update_active(|config| { + *config = config_with_target("recovered-target"); + Ok(()) + }) + .unwrap(); + assert_eq!(updated.profile.revision, 2); + assert_eq!(store.load_active().unwrap(), updated); + let (saved, active) = store + .save_profile("edited", &config_with_target("edited-target"), false, false) + .unwrap(); + assert!(!active); + assert_eq!(saved.profile.id, "edited"); + assert_eq!(store.list().unwrap().profiles.len(), 2); + assert_eq!( + store.load_active().unwrap().config, + config_with_target("recovered-target") + ); + assert_eq!( + fs::read(&recovered.backup_path).unwrap(), + *original, + "{name}" + ); + assert_unrelated_unchanged(&unrelated); + fs::remove_dir_all(root).unwrap(); + } + } + + #[test] + fn explicit_recovery_rebuilds_a_known_but_semantically_invalid_collection() { + let original = br#"{"version":1,"active_profile":"missing","launch_intro_disabled":true,"auto_map_on_login":true,"profiles":[{"id":"default","revision":3,"config":{"version":2,"groups":[{"id":0,"route":{"kind":"mirror","target_id":"office"}}],"selected_group_id":0}},{"id":"gaming","revision":4,"config":{"version":2,"groups":[{"id":0,"route":{"kind":"mirror","target_id":"gaming"}}],"selected_group_id":0}}]}"#; + let (root, store) = prepare_profile_bytes("semantic", original); + let unrelated = write_unrelated_files(&root); + let error = store.load_active().unwrap_err(); + assert!(error.allows_profile_collection_recovery(), "{error}"); + assert!(error.to_string().contains("does not exist"), "{error}"); + + let recovered = store.recover_with_backup().unwrap(); + assert_eq!(fs::read(&recovered.backup_path).unwrap(), original); + let profiles = store.list().unwrap(); + assert_eq!(profiles.profiles.len(), 1); + assert_eq!(profiles.active_profile, "default"); + assert!(!profiles.launch_intro_disabled); + assert!(!profiles.auto_map_on_login); + assert_eq!(profiles.active().config, AppConfig::default()); + assert_eq!(profiles.active().revision, 1); + assert_unrelated_unchanged(&unrelated); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn explicit_recovery_backs_up_raw_bytes_and_repeated_runs_keep_every_backup() { + let (root, store) = test_profile_store("repeat"); + store.load_active().unwrap(); + store.set_launch_intro_disabled(true).unwrap(); + store.set_auto_map_on_login(true).unwrap(); + store + .save_profile("gaming", &config_with_target("gaming-display"), false, true) + .unwrap(); + let original = fs::read(store.path()).unwrap(); + let first = store.recover_with_backup().unwrap(); + assert_eq!(fs::read(&first.backup_path).unwrap(), original); + let rebuilt = fs::read(store.path()).unwrap(); + assert_ne!(rebuilt, original); + let profiles = store.list().unwrap(); + assert_eq!(profiles.profiles.len(), 1); + assert!(!profiles.launch_intro_disabled); + assert!(!profiles.auto_map_on_login); + + let second = store.recover_with_backup().unwrap(); + assert_ne!(first.backup_path, second.backup_path); + assert_eq!(fs::read(&first.backup_path).unwrap(), original); + assert_eq!(fs::read(&second.backup_path).unwrap(), rebuilt); + assert_eq!(recovery_backups(&root).len(), 2); + assert_eq!(store.load_active().unwrap().profile.revision, 1); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn profile_backup_creation_fails_when_the_parent_is_not_a_directory() { + let parent = env::temp_dir().join(format!( + "sbms-config-backup-parent-{}-{}", + std::process::id(), + TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + fs::write(&parent, b"not-a-directory").unwrap(); + let source = parent.join(CONFIG_PROFILES_FILE); + let error = write_unique_profile_backup(&source, b"raw-bytes").unwrap_err(); + assert!( + error + .to_string() + .contains("could not create config profile backup"), + "{error}" + ); + assert_eq!(fs::read(&parent).unwrap(), b"not-a-directory"); + assert!(!source.exists()); + fs::remove_file(parent).unwrap(); + } + + #[test] + fn profile_recovery_keeps_the_source_when_backup_fails() { + let original = b"{not-json"; + let (root, store) = prepare_profile_bytes("backup-fails", original); + let unrelated = write_unrelated_files(&root); + // The transaction holds the profile lock across backup and replacement, + // so an external process cannot fail only the backup step. This fault + // stands in for that IO error before any backup file is created. + let _fault = inject_profile_store_fault(ProfileStoreTestFault::Backup); + let error = store.recover_with_backup().unwrap_err(); + drop(_fault); + let message = error.to_string(); + assert!( + message.contains("could not create config profile backup"), + "{message}" + ); + assert!(!message.contains("was not committed"), "{message}"); + assert!( + !message.contains("configuration recovery was committed"), + "{message}" + ); + assert!(!error.allows_profile_collection_recovery(), "{message}"); + assert_eq!(fs::read(store.path()).unwrap(), original); + assert!(recovery_backups(&root).is_empty()); + assert!(temporary_profile_files(&root).is_empty()); + assert_unrelated_unchanged(&unrelated); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn profile_recovery_keeps_the_backup_when_atomic_replace_fails() { + let original = b"\xff\xfe{truncated"; + let (root, store) = prepare_profile_bytes("replace-fails", original); + let unrelated = write_unrelated_files(&root); + let _fault = inject_profile_store_fault(ProfileStoreTestFault::Replace); + let error = store.recover_with_backup().unwrap_err(); + drop(_fault); + let message = error.to_string(); + assert!(message.contains("was not committed"), "{message}"); + assert!(message.contains("is unchanged"), "{message}"); + assert!(message.contains("backup remains at"), "{message}"); + assert!( + message.contains("could not atomically replace"), + "{message}" + ); + assert!( + !message.contains("configuration recovery was committed"), + "{message}" + ); + assert_eq!(fs::read(store.path()).unwrap(), original); + let backups = recovery_backups(&root); + assert_eq!(backups.len(), 1); + assert_eq!(fs::read(&backups[0]).unwrap(), original); + let backup_name = backups[0] + .file_name() + .and_then(|name| name.to_str()) + .unwrap(); + assert!(message.contains(backup_name), "{message}"); + assert!(temporary_profile_files(&root).is_empty()); + assert_unrelated_unchanged(&unrelated); + + let recovered = store.recover_with_backup().unwrap(); + assert_ne!(recovered.backup_path, backups[0]); + assert_eq!(fs::read(&backups[0]).unwrap(), original); + assert_eq!(fs::read(&recovered.backup_path).unwrap(), original); + assert_eq!(store.load_active().unwrap().config, AppConfig::default()); + assert_unrelated_unchanged(&unrelated); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn future_profile_schema_is_refused_without_backup_or_replacement() { + let cases: &[(&str, &[u8])] = &[ + ( + "version-99", + br#"{"version":99,"active_profile":"default","profiles":[]}"#, + ), + ("version-2-extra", br#"{"version":2,"extra":true}"#), + ("version-prefix", br#"{"version":99} trailing"#), + ("version-float", br#"{"version":1.5,"profiles":[]}"#), + ]; + for (name, original) in cases { + let (root, store) = prepare_profile_bytes(name, original); + let unrelated = write_unrelated_files(&root); + for error in [ + store.reset_active().unwrap_err(), + store.recover_with_backup().unwrap_err(), + store.load_active().unwrap_err(), + ] { + let message = error.to_string(); + assert!( + message.contains("newer than this SBMS"), + "{name}: {message}" + ); + assert!(message.contains("left unchanged"), "{name}: {message}"); + assert!( + !error.allows_profile_collection_recovery(), + "{name}: {message}" + ); + assert!( + !message.contains(RECOVER_PROFILE_COLLECTION_COMMAND), + "{name}" + ); + assert!(!message.contains("was not committed"), "{name}: {message}"); + } + assert_eq!(fs::read(store.path()).unwrap(), *original, "{name}"); + assert!(recovery_backups(&root).is_empty(), "{name}"); + assert_unrelated_unchanged(&unrelated); + fs::remove_dir_all(root).unwrap(); + } + } + + #[test] + fn profile_recovery_does_not_treat_read_errors_or_absence_as_damage() { + let (root, store) = test_profile_store("missing-store"); + let missing = store.recover_with_backup().unwrap_err(); + assert!( + missing + .to_string() + .contains("does not exist and was not created"), + "{missing}" + ); + assert!(!missing.allows_profile_collection_recovery(), "{missing}"); + assert!(!root.exists()); + + let (root, store) = test_profile_store("directory-store"); + fs::create_dir_all(store.path()).unwrap(); + let unrelated = root.join("credentials.json"); + fs::write(&unrelated, b"stream-secret").unwrap(); + let error = store.recover_with_backup().unwrap_err(); + let message = error.to_string(); + assert!(message.contains("could not read"), "{message}"); + assert!(!error.allows_profile_collection_recovery(), "{message}"); + assert!( + !message.contains(RECOVER_PROFILE_COLLECTION_COMMAND), + "{message}" + ); + assert!(store.path().is_dir()); + assert_eq!(fs::read(&unrelated).unwrap(), b"stream-secret"); + assert!(recovery_backups(&root).is_empty()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn reset_active_resets_only_the_active_profile_inside_a_valid_collection() { + let (root, store) = test_profile_store("reset-active-only"); + let unrelated = { + fs::create_dir_all(&root).unwrap(); + write_unrelated_files(&root) + }; + store.load_active().unwrap(); + store + .update_active(|config| { + *config = config_with_target("default-display"); + Ok(()) + }) + .unwrap(); + store.set_launch_intro_disabled(true).unwrap(); + store.set_auto_map_on_login(true).unwrap(); + store + .save_profile("gaming", &config_with_target("gaming-display"), false, true) + .unwrap(); + + let snapshot = store.reset_active().unwrap(); + assert_eq!(snapshot.profile.id, "gaming"); + assert_eq!(snapshot.config, AppConfig::default()); + let profiles = store.list().unwrap(); + assert_eq!(profiles.profiles.len(), 2); + assert_eq!(profiles.active_profile, "gaming"); + assert!(profiles.launch_intro_disabled); + assert!(profiles.auto_map_on_login); + assert_eq!( + profiles.profile("default").unwrap().config, + config_with_target("default-display") + ); + assert_eq!( + profiles.profile("gaming").unwrap().config, + AppConfig::default() + ); + assert!(recovery_backups(&root).is_empty()); + assert_unrelated_unchanged(&unrelated); + fs::remove_dir_all(root).unwrap(); + } } diff --git a/src/main.rs b/src/main.rs index 8bd4a3e..40a39c7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,7 +6,9 @@ use std::path::Path; use std::sync::Arc; use std::time::Duration; -use sbms::config::{ConfigError, ConfigProfileStore, ConfigStore, GroupRouteConfig}; +use sbms::config::{ + ConfigError, ConfigProfileStore, ConfigStore, GroupRouteConfig, ProfileRecovery, +}; use sbms::diagnostics::{self, Level, MappingSessionId}; use sbms::display::{active_displays, unique_physical_display}; use sbms::geometry::Rotation; @@ -642,15 +644,25 @@ fn config(mut arguments: impl Iterator) -> Result<(), Box { - let snapshot = store.reset_active()?; - println!( - "reset={} revision={} reload={}", - snapshot.profile.id, - snapshot.profile.revision, - reload_status(signal_config_reload()?) - ); - } + Some("reset") => match reset_args(arguments) { + ResetArgs::Active => { + let snapshot = store.reset_active()?; + println!( + "reset={} revision={} reload={}", + snapshot.profile.id, + snapshot.profile.revision, + reload_status(signal_config_reload()?) + ); + } + ResetArgs::RecoverCollection => { + let recovery = store.recover_with_backup()?; + report_profile_recovery( + &recovery, + signal_config_reload().map_err(|error| error.to_string()), + )?; + } + ResetArgs::Invalid => usage(), + }, _ => usage(), } Ok(()) @@ -660,6 +672,57 @@ fn signal_config_reload() -> Result> { sbms::control::signal_config_reload().map_err(Into::into) } +enum ResetArgs { + Active, + RecoverCollection, + Invalid, +} + +fn reset_args(arguments: impl Iterator) -> ResetArgs { + let arguments: Vec = arguments.collect(); + match arguments.as_slice() { + [] => ResetArgs::Active, + [left, right] + if (left == "--all" && right == "--backup") + || (left == "--backup" && right == "--all") => + { + ResetArgs::RecoverCollection + } + _ => ResetArgs::Invalid, + } +} + +fn report_profile_recovery( + recovery: &ProfileRecovery, + reload: Result, +) -> Result<(), Box> { + match reload { + Ok(signaled) => { + println!( + "recovered={} revision={} backup={} reload={}", + recovery.snapshot.profile.id, + recovery.snapshot.profile.revision, + recovery.backup_path.display(), + reload_status(signaled) + ); + Ok(()) + } + Err(error) => { + println!( + "recovered={} revision={} backup={} reload=failed", + recovery.snapshot.profile.id, + recovery.snapshot.profile.revision, + recovery.backup_path.display() + ); + Err(committed_recovery_reload_error(&error).into()) + } + } +} + +fn committed_recovery_reload_error(error: &str) -> String { + format!("configuration recovery was committed; tray reload failed: {error}") +} + fn reload_status(signaled: bool) -> &'static str { if signaled { "signaled" } else { "not-running" } } @@ -711,8 +774,26 @@ fn usage() -> ! { sbms config activate|delete sbms config reload sbms config set-target |clear-target|reset + sbms config reset --all --backup sbms shutdown sbms ui" ); std::process::exit(2); } + +#[cfg(test)] +mod tests { + use super::committed_recovery_reload_error; + + #[test] + fn reload_failure_reports_that_recovery_stays_committed() { + let message = committed_recovery_reload_error( + "OpenEventW(config reload) failed: Access is denied. (os error 5)", + ); + assert!(message.contains("configuration recovery was committed")); + assert!(message.contains("tray reload failed")); + assert!(message.contains("OpenEventW(config reload) failed")); + assert!(!message.contains("rolled back")); + assert!(!message.contains("was not committed")); + } +} diff --git a/src/ui.rs b/src/ui.rs index 4a8ec99..50a16d9 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -6,8 +6,9 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use crate::config::{ - AppConfig, ConfigProfileStore, ConfigProfiles, DisplayOverrideStore, DisplayOverrides, - MAX_CONFIG_PROFILES, ProfileRevision, ReferenceSource, + AppConfig, ConfigError, ConfigProfileStore, ConfigProfiles, DisplayOverrideStore, + DisplayOverrides, MAX_CONFIG_PROFILES, ProfileRevision, RECOVER_PROFILE_COLLECTION_COMMAND, + ReferenceSource, }; use crate::control::{TrayInstance, listen_for_config_reload, listen_for_shutdown}; use crate::controller::{Controller, ControllerEvent, DisplayOption}; @@ -1460,7 +1461,8 @@ fn load_group_config(ui: &QuickAccess) -> LoadedGroups { Err(error) => { set_geometry_unconfigured(ui); ui.set_geometry_save_blocked(true); - ui.set_geometry_error(error.to_string().into()); + diagnostics::log(Level::Error, "config", "load", None, error.to_string()); + ui.set_geometry_error(profile_load_message(&error).into()); return default_loaded_groups(); } }; @@ -1512,10 +1514,11 @@ fn apply_config_reload( Ok(snapshot) => snapshot, Err(error) => { diagnostics::log(Level::Error, "config", "reload", None, error.to_string()); + let detail = profile_load_message(&error); surface_transient_error( ui, error_revision, - &format!("Couldn’t reload configuration: {error}"), + &format!("Couldn’t reload configuration: {detail}"), ); return false; } @@ -1582,10 +1585,13 @@ fn persist_groups( profile_revision: &Arc>, ) -> bool { if ui.get_geometry_save_blocked() { - surface_persistence_error( - ui, - "The saved configuration is invalid; reset or repair it before saving", - ); + let existing = ui.get_geometry_error().to_string(); + let message = if existing.is_empty() { + "The saved configuration could not be loaded and was left unchanged".to_string() + } else { + existing + }; + surface_persistence_error(ui, &message); return false; } let validated = match validate_group_drafts(groups) { @@ -1661,6 +1667,16 @@ fn finish_profile_save(ui: slint::Weak, generation: u64, succeeded: } } +fn profile_load_message(error: &ConfigError) -> String { + if error.allows_profile_collection_recovery() { + format!( + "The saved configuration is damaged. Run `{RECOVER_PROFILE_COLLECTION_COMMAND}` to back up and rebuild the entire profile collection before saving" + ) + } else { + error.to_string() + } +} + fn surface_persistence_error(ui: &QuickAccess, error: &str) { ui.set_error_text(format!("Couldn’t save mapping groups: {error}").into()); ui.set_state_detail("Mapping group changes were not saved".into()); diff --git a/src/ui/geometry_view.rs b/src/ui/geometry_view.rs index 787e5cd..059edc2 100644 --- a/src/ui/geometry_view.rs +++ b/src/ui/geometry_view.rs @@ -463,7 +463,9 @@ pub(super) fn set_geometry_result(ui: &QuickAccess, result: SizingResult, config format!("Scale {:.2}× × {:.2}×", result.scale_x, result.scale_y).into(), ); ui.set_geometry_valid(!ui.get_geometry_save_blocked()); - ui.set_geometry_error("".into()); + if !ui.get_geometry_save_blocked() { + ui.set_geometry_error("".into()); + } if configured { let refresh = result .preferred_refresh_millihz diff --git a/tests/cli_contract.rs b/tests/cli_contract.rs index 878b83b..f0e4196 100644 --- a/tests/cli_contract.rs +++ b/tests/cli_contract.rs @@ -65,6 +65,7 @@ fn usage() -> &'static str { sbms config activate|delete sbms config reload sbms config set-target |clear-target|reset + sbms config reset --all --backup sbms shutdown sbms ui " @@ -292,6 +293,256 @@ fn config_export_never_overwrites_store_or_existing_destination_without_force() assert_eq!(fs::read(destination).unwrap(), b"keep-me"); } +fn recovery_backups(root: &TestRoot) -> Vec { + let profiles = root.profiles_path(); + let directory = profiles.parent().unwrap(); + let mut paths: Vec<_> = fs::read_dir(directory) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.contains(".recovery-") && name.ends_with(".bak")) + }) + .collect(); + paths.sort(); + paths +} + +fn write_profile_neighbors(root: &TestRoot) -> (PathBuf, Vec, PathBuf, Vec) { + let profiles = root.profiles_path(); + let directory = profiles.parent().unwrap(); + fs::create_dir_all(directory).unwrap(); + let legacy = root.config_path(); + let legacy_bytes = b"legacy-source".to_vec(); + fs::write(&legacy, &legacy_bytes).unwrap(); + let overrides = directory.join("display-overrides-v1.json"); + let override_bytes = br#"{"version":1,"displays":[]}"#.to_vec(); + fs::write(&overrides, &override_bytes).unwrap(); + let credentials = directory.join("credentials.json"); + fs::write(&credentials, b"stream-secret").unwrap(); + let log = directory.join("sbms.log"); + fs::write(&log, b"log-bytes").unwrap(); + (legacy, legacy_bytes, overrides, override_bytes) +} + +#[test] +fn config_reset_rejects_incomplete_recovery_arguments_without_writing() { + let root = TestRoot::new("reset-args"); + let profiles = root.profiles_path(); + fs::create_dir_all(profiles.parent().unwrap()).unwrap(); + let original = b"{not json".to_vec(); + fs::write(&profiles, &original).unwrap(); + let (legacy, legacy_bytes, overrides, override_bytes) = write_profile_neighbors(&root); + + for arguments in [ + &["config", "reset", "--all"][..], + &["config", "reset", "--backup"][..], + &["config", "reset", "--all", "--backup", "extra"][..], + &["config", "reset", "--backup", "--all", "--force"][..], + &["config", "reset", "--all", "--all"][..], + &["config", "reset", "--backup", "--backup"][..], + ] { + let output = run(&root, arguments); + assert_eq!( + output.status.code(), + Some(2), + "{arguments:?}\n{}", + text(&output.stderr) + ); + assert_eq!(text(&output.stdout), ""); + assert_eq!(text(&output.stderr), usage()); + assert_eq!(fs::read(&profiles).unwrap(), original, "{arguments:?}"); + assert_eq!(fs::read(&legacy).unwrap(), legacy_bytes, "{arguments:?}"); + assert_eq!( + fs::read(&overrides).unwrap(), + override_bytes, + "{arguments:?}" + ); + assert_eq!( + fs::read(profiles.parent().unwrap().join("credentials.json")).unwrap(), + b"stream-secret" + ); + assert_eq!( + fs::read(profiles.parent().unwrap().join("sbms.log")).unwrap(), + b"log-bytes" + ); + assert!(recovery_backups(&root).is_empty(), "{arguments:?}"); + } +} + +#[test] +fn config_reset_all_backup_restores_damaged_bytes_and_can_save_again() { + let root = TestRoot::new("recover-store"); + let profiles = root.profiles_path(); + fs::create_dir_all(profiles.parent().unwrap()).unwrap(); + let original = b"\xff\xfe{not json".to_vec(); + fs::write(&profiles, &original).unwrap(); + let (legacy, legacy_bytes, overrides, override_bytes) = write_profile_neighbors(&root); + + let recovered = run(&root, &["config", "reset", "--backup", "--all"]); + assert!(recovered.status.success(), "{}", text(&recovered.stderr)); + let stdout = text(&recovered.stdout); + assert!(stdout.contains("recovered=default"), "{stdout}"); + assert!(stdout.contains("revision=1"), "{stdout}"); + assert!(stdout.contains("backup="), "{stdout}"); + assert!(stdout.contains("reload="), "{stdout}"); + assert!(!stdout.contains("reload=failed"), "{stdout}"); + let backups = recovery_backups(&root); + assert_eq!(backups.len(), 1); + assert_eq!(fs::read(&backups[0]).unwrap(), original); + let backup_name = backups[0] + .file_name() + .and_then(|name| name.to_str()) + .unwrap(); + assert!(stdout.contains(backup_name), "{stdout}"); + assert_eq!(fs::read(&legacy).unwrap(), legacy_bytes); + assert_eq!(fs::read(&overrides).unwrap(), override_bytes); + assert_eq!( + fs::read(profiles.parent().unwrap().join("credentials.json")).unwrap(), + b"stream-secret" + ); + assert_eq!( + fs::read(profiles.parent().unwrap().join("sbms.log")).unwrap(), + b"log-bytes" + ); + + let rebuilt = fs::read(&profiles).unwrap(); + let again = run(&root, &["config", "reset", "--all", "--backup"]); + assert!(again.status.success(), "{}", text(&again.stderr)); + let backups = recovery_backups(&root); + assert_eq!(backups.len(), 2); + let backup_bytes: Vec> = backups.iter().map(|path| fs::read(path).unwrap()).collect(); + assert!(backup_bytes.iter().any(|bytes| bytes == &original)); + assert!(backup_bytes.iter().any(|bytes| bytes == &rebuilt)); + + let shown = run(&root, &["config", "show"]); + assert!(shown.status.success(), "{}", text(&shown.stderr)); + let config: Value = serde_json::from_slice(&shown.stdout).unwrap(); + assert_eq!(config["version"], 2); + assert_eq!(config["groups"][0]["id"], 0); + + let saved = run(&root, &["config", "save", "edited"]); + assert!(saved.status.success(), "{}", text(&saved.stderr)); + let listed = run(&root, &["config", "list"]); + assert!(listed.status.success(), "{}", text(&listed.stderr)); + let profiles_json: Value = serde_json::from_slice(&listed.stdout).unwrap(); + assert_eq!(profiles_json.as_array().unwrap().len(), 2); + assert_eq!(fs::read(&legacy).unwrap(), legacy_bytes); + assert_eq!(fs::read(&overrides).unwrap(), override_bytes); +} + +#[test] +fn config_reset_all_backup_refuses_a_future_schema_without_writing() { + let root = TestRoot::new("future-store"); + let profiles = root.profiles_path(); + fs::create_dir_all(profiles.parent().unwrap()).unwrap(); + let original = br#"{"version":99,"active_profile":"default","profiles":[]}"#.to_vec(); + fs::write(&profiles, &original).unwrap(); + let (legacy, legacy_bytes, overrides, override_bytes) = write_profile_neighbors(&root); + + let output = run(&root, &["config", "reset", "--all", "--backup"]); + assert_eq!(output.status.code(), Some(1), "{}", text(&output.stdout)); + let stderr = text(&output.stderr); + assert!(stderr.contains("newer than this SBMS"), "{stderr}"); + assert!(stderr.contains("left unchanged"), "{stderr}"); + assert!( + !stderr.contains("configuration recovery was committed"), + "{stderr}" + ); + assert!( + !stderr.contains("sbms config reset --all --backup"), + "{stderr}" + ); + assert_eq!(text(&output.stdout), ""); + assert_eq!(fs::read(&profiles).unwrap(), original); + assert!(recovery_backups(&root).is_empty()); + assert_eq!(fs::read(&legacy).unwrap(), legacy_bytes); + assert_eq!(fs::read(&overrides).unwrap(), override_bytes); +} + +#[test] +fn config_reset_changes_only_the_active_profile() { + let root = TestRoot::new("reset-active"); + let office_path = root.path().join("office.json"); + let gaming_path = root.path().join("gaming.json"); + let office = json!({ + "version": 2, + "groups": [{ + "id": 0, + "route": {"kind": "mirror", "target_id": "office-display"} + }], + "selected_group_id": 0 + }); + let gaming = json!({ + "version": 2, + "groups": [{ + "id": 0, + "route": {"kind": "mirror", "target_id": "gaming-display"} + }], + "selected_group_id": 0 + }); + fs::write(&office_path, serde_json::to_vec_pretty(&office).unwrap()).unwrap(); + fs::write(&gaming_path, serde_json::to_vec_pretty(&gaming).unwrap()).unwrap(); + assert!(run(&root, &["config", "show"]).status.success()); + let replace_default = run( + &root, + &[ + "config", + "import", + "default", + office_path.to_str().unwrap(), + "--replace", + ], + ); + assert!( + replace_default.status.success(), + "{}", + text(&replace_default.stderr) + ); + let activate_gaming = run( + &root, + &[ + "config", + "import", + "gaming", + gaming_path.to_str().unwrap(), + "--activate", + ], + ); + assert!( + activate_gaming.status.success(), + "{}", + text(&activate_gaming.stderr) + ); + + let reset = run(&root, &["config", "reset"]); + assert!(reset.status.success(), "{}", text(&reset.stderr)); + assert!(text(&reset.stdout).starts_with("reset=gaming revision=2 reload=")); + assert!(recovery_backups(&root).is_empty()); + + let active = run(&root, &["config", "show"]); + let active_config: Value = serde_json::from_slice(&active.stdout).unwrap(); + assert_eq!( + active_config["groups"][0]["route"], + json!({"kind": "mirror"}) + ); + let preserved = run(&root, &["config", "show", "default"]); + assert_eq!( + serde_json::from_slice::(&preserved.stdout).unwrap(), + office + ); + let listed = serde_json::from_slice::(&run(&root, &["config", "list"]).stdout).unwrap(); + assert_eq!(listed.as_array().unwrap().len(), 2); + assert!( + listed + .as_array() + .unwrap() + .iter() + .any(|profile| { profile["id"] == "gaming" && profile["active"] == true }) + ); +} + #[test] fn plan_validation_reports_valid_and_empty_plans() { let root = TestRoot::new("plan"); From 0e67ec8d68fb5c158f73b0424b50d8e2077994a8 Mon Sep 17 00:00:00 2001 From: EvanZhu0721 Date: Fri, 6 Nov 2026 02:47:09 +0800 Subject: [PATCH 2/2] fix: keep configuration read failures blocked until reload succeeds Reuse the existing UI save-blocked state for initial load and reload failures. Keep the original error visible across edits and hydration, and reject saves, mapping starts, and manual restarts until a successful reload. Stop remains available. Record initial read failures in the existing diagnostics log. Keep the change scoped to this UI failure boundary and its regression coverage. The profile storage format and command-line interface remain unchanged. Validation: the regression fails against the previous UI and passes with this patch; fmt, Clippy, and 139 Rust tests pass (26 ignored and one mouse-hook test skipped). The signed 2.0.2 installer was built and verified locally. --- docs/architecture.md | 4 +- docs/command-line.md | 5 +- docs/command-line.zh-CN.md | 2 +- docs/configuration.md | 64 +--- src/config.rs | 671 ++----------------------------------- src/main.rs | 101 +----- src/ui.rs | 94 ++++-- src/ui/geometry_view.rs | 10 +- src/ui/handlers.rs | 12 +- src/ui/projection.rs | 4 +- tests/cli_contract.rs | 251 -------------- ui/quick-access.slint | 4 +- 12 files changed, 140 insertions(+), 1082 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 61a8822..b250041 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -94,9 +94,7 @@ User configuration is stored as at most three named profiles in and per-profile revisions are committed atomically under a cross-process lock. On first use, the existing `config-v2.json` is preserved and imported as the `default` profile. The tray supports revision-checked live reloads without -changing a mapping that is already running. A damaged profile collection is -left unchanged by ordinary profile commands. `sbms config reset --all --backup` -backs up the original bytes and rebuilds the entire collection. See +changing a mapping that is already running. See [configuration.md](configuration.md) for the storage, CLI, JSON and Rust API contracts. diff --git a/docs/command-line.md b/docs/command-line.md index 5c9361f..569e407 100644 --- a/docs/command-line.md +++ b/docs/command-line.md @@ -20,7 +20,4 @@ sbms shutdown foreground session cleanly. A mapping plan can contain up to sixteen mirror and stream-only groups. Up to three persistent configuration profiles can coexist; see [Configuration profiles](configuration.md) for import, export, -activation and hot-reload interfaces. `sbms config reset` resets only the -active profile in a valid collection. `sbms config reset --all --backup` -backs up the raw profile file and rebuilds the entire collection; both flags -are required. +activation and hot-reload interfaces. diff --git a/docs/command-line.zh-CN.md b/docs/command-line.zh-CN.md index 71f2480..e41c0c2 100644 --- a/docs/command-line.zh-CN.md +++ b/docs/command-line.zh-CN.md @@ -18,4 +18,4 @@ sbms shutdown `sbms list` 会列出 `--target` 所需的稳定显示器 ID。前台运行 `map` 时按 Enter,可以正常停止并完成恢复。映射计划最多可混合十六组本地镜像和纯串流 虚拟桌面。最多可以同时保存三套配置;导入、导出、激活和热加载接口见 -[配置档案接口](configuration.md)。`sbms config reset` 只重置一份有效配置集合里的当前档案。`sbms config reset --all --backup` 会按原始字节备份整个配置集合,然后重建为默认集合;两个参数必须同时给出。该命令会丢弃全部档案和全局偏好,不会删除显示器覆盖、日志、串流凭据或旧版迁移文件。 +[配置档案接口](configuration.md)。 diff --git a/docs/configuration.md b/docs/configuration.md index cb49f61..6f2e176 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -34,7 +34,6 @@ sbms config reload sbms config set-target sbms config clear-target sbms config reset -sbms config reset --all --backup ``` - `path` prints the profile-store path. @@ -54,61 +53,12 @@ sbms config reset --all --backup - `activate` atomically changes the active profile and requests a live reload. - `delete` rejects the active profile and unknown profiles. - `reload` requests that the running tray reload the already-active profile. -- `set-target` and `clear-target` update only the active profile and request - a live reload. -- `reset` with no other arguments resets only the active profile inside a - valid collection. Other profiles and the global preferences - `launch_intro_disabled` and `auto_map_on_login` stay unchanged. A missing - profile store is created from the normal default. If the store is damaged, - unreadable, or uses a newer schema version, `reset` fails and does not write. -- `reset --all --backup` rebuilds the entire profile collection. Both flags are - required, in either order. Any other argument combination prints usage and - exits without writing. +- `set-target`, `clear-target` and `reset` update only the active profile and + request a live reload. A successful configuration commit is not rolled back when the tray is not running. CLI output reports `reload=not-running`; the configuration is loaded -on the next tray or mapping start. After `reset --all --backup` commits, -`reload=failed` means the new collection is already on disk and only the tray -notification failed. - -## Damaged profile collection - -Ordinary profile commands, including `sbms config reset`, load the collection -before changing it. A truncated file, invalid JSON, or a version 1 collection -that fails semantic validation therefore cannot be repaired by `reset`. - -`sbms config reset --all --backup` is the explicit recovery command. Under the -existing cross-process profile lock it: - -1. Reads the current `config-profiles-v1.json` bytes. -2. Writes those exact bytes to a new file in the same directory: - `config-profiles-v1.json.recovery--.bak`. - The file is created with `create_new` and flushed before the store is - replaced, so a later recovery cannot overwrite an earlier backup. -3. Atomically replaces the store with one `default` profile at revision 1 and - default global preferences. - -The command discards every saved profile and both global preferences. It does -not delete display overrides, logs, stream credentials, `config-v2.json`, or -`config-v1.json`. - -A numeric `version` greater than 1 is a newer schema. Recovery refuses it and -leaves the file unchanged, without writing a backup. A non-numeric `version`, -truncated JSON, or any other file whose schema version cannot be recognized is -damaged. Only this command can rebuild it. The command also accepts a valid -collection: it still backs up the raw bytes and replaces the whole collection. -Permission errors and other read/write failures are not treated as damage: the -source file stays in place. If the backup itself fails, nothing is replaced. -If the backup succeeds and the atomic replacement fails, the command reports -that recovery was not committed and leaves the backup in place. - -```text -sbms config reset --all --backup -``` - -```text -recovered=default revision=1 backup=%LOCALAPPDATA%\SBMS\config-profiles-v1.json.recovery--.bak reload=not-running -``` +on the next tray or mapping start. ## JSON exchange format @@ -191,12 +141,8 @@ The public API is exported from `sbms::config`: - `ConfigProfileStore::default_store()` locates the collection. - `list`, `load_active` and `load_profile` return validated persistent state. -- `save_profile`, `save_active_as`, `activate`, `delete`, `update_active` and - `reset_active` perform locked atomic transactions. -- `recover_with_backup` is the locked recovery used by - `sbms config reset --all --backup`. It returns the new snapshot and the - backup path. `ConfigError::allows_profile_collection_recovery` is true only - for a damaged collection this build can rebuild. +- `save_profile`, `save_active_as`, `activate`, `delete` and `update_active` + perform locked atomic transactions. - `save_active_if_revision` is the compare-and-swap save operation for a pinned UI session. - `ConfigStore::load_strict` validates standalone import files; `save` writes diff --git a/src/config.rs b/src/config.rs index 31dd9d6..a2059e5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -28,7 +28,6 @@ use crate::limits::{ const CONFIG_VERSION: u32 = 2; const LEGACY_CONFIG_VERSION: u32 = 1; const CONFIG_PROFILES_VERSION: u32 = 1; -pub const RECOVER_PROFILE_COLLECTION_COMMAND: &str = "sbms config reset --all --backup"; pub const MAX_CONFIG_PROFILES: usize = 3; const DISPLAY_OVERRIDES_VERSION: u32 = 1; const CONFIG_DIRECTORY: &str = "SBMS"; @@ -218,12 +217,6 @@ pub struct ProfileDeleteOutcome { pub active_changed: bool, } -#[derive(Clone, Debug, PartialEq)] -pub struct ProfileRecovery { - pub snapshot: ProfileSnapshot, - pub backup_path: PathBuf, -} - #[derive(Clone, Debug)] pub struct ConfigProfileStore { path: PathBuf, @@ -299,10 +292,6 @@ impl ConfigError { pub fn new(message: impl Into) -> Self { Self(message.into()) } - - pub fn allows_profile_collection_recovery(&self) -> bool { - self.0.contains("is a damaged SBMS config profile store:") - } } impl Display for ConfigError { @@ -1294,7 +1283,17 @@ impl ConfigProfileStore { let mut profiles = if self.path.exists() { self.load_or_initialize_locked()? } else { - default_config_profiles() + ConfigProfiles { + version: CONFIG_PROFILES_VERSION, + active_profile: "default".into(), + launch_intro_disabled: false, + auto_map_on_login: false, + profiles: vec![ConfigProfile { + id: "default".into(), + revision: 1, + config: AppConfig::default(), + }], + } }; let active_id = profiles.active_profile.clone(); let profile = profiles @@ -1307,46 +1306,19 @@ impl ConfigProfileStore { Ok(result) } - pub fn recover_with_backup(&self) -> Result { - let _guard = CrossProcessConfigGuard::acquire()?; - let bytes = match fs::read(&self.path) { - Ok(bytes) => bytes, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - return Err(ConfigError(format!( - "config profile store {} does not exist and was not created", - self.path.display() - ))); - } - Err(error) => { - return Err(ConfigError(format!( - "could not read {}: {error}", - self.path.display() - ))); - } - }; - if let Some(version) = recognized_future_profiles_version(&bytes) { - return Err(future_profile_store(&self.path, &version)); - } - // Flush the original bytes before replacing the store. A backup error - // returns while the source file is still untouched. - let backup = write_unique_profile_backup(&self.path, &bytes)?; - let profiles = default_config_profiles(); - if let Err(error) = self.save_locked(&profiles) { - return Err(ConfigError(format!( - "config profile recovery was not committed; {}; backup remains at {}: {error}", - profile_store_after_failed_replace(&self.path, &bytes), - backup.display() - ))); - } - Ok(ProfileRecovery { - snapshot: snapshot(profiles.active()), - backup_path: backup, - }) - } - fn load_or_initialize_locked(&self) -> Result { match fs::read(&self.path) { - Ok(bytes) => parse_profile_store(&self.path, &bytes), + Ok(bytes) => { + let profiles = + serde_json::from_slice::(&bytes).map_err(|error| { + ConfigError(format!( + "{} is not a valid SBMS config profile store: {error}", + self.path.display() + )) + })?; + profiles.validate()?; + Ok(profiles) + } Err(error) if error.kind() == std::io::ErrorKind::NotFound => { let legacy_store = ConfigStore { path: self.legacy_config_path.clone(), @@ -1368,7 +1340,17 @@ impl ConfigProfileStore { } Err(error) => return Err(error), }; - let profiles = single_profile_collection(config); + let profiles = ConfigProfiles { + version: CONFIG_PROFILES_VERSION, + active_profile: "default".into(), + launch_intro_disabled: false, + auto_map_on_login: false, + profiles: vec![ConfigProfile { + id: "default".into(), + revision: 1, + config, + }], + }; self.save_locked(&profiles)?; Ok(profiles) } @@ -1421,206 +1403,6 @@ impl Drop for CrossProcessConfigGuard { } } -#[cfg(test)] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum ProfileStoreTestFault { - Backup, - Replace, -} - -#[cfg(test)] -thread_local! { - static PROFILE_STORE_TEST_FAULT: std::cell::Cell> = - const { std::cell::Cell::new(None) }; -} - -#[cfg(test)] -#[must_use] -struct ProfileStoreTestFaultGuard; - -#[cfg(test)] -impl Drop for ProfileStoreTestFaultGuard { - fn drop(&mut self) { - PROFILE_STORE_TEST_FAULT.with(|fault| fault.set(None)); - } -} - -#[cfg(test)] -fn inject_profile_store_fault(fault: ProfileStoreTestFault) -> ProfileStoreTestFaultGuard { - PROFILE_STORE_TEST_FAULT.with(|slot| slot.set(Some(fault))); - ProfileStoreTestFaultGuard -} - -#[cfg(test)] -fn consume_profile_store_test_fault(expected: ProfileStoreTestFault) -> bool { - PROFILE_STORE_TEST_FAULT.with(|slot| { - if slot.get() == Some(expected) { - slot.set(None); - true - } else { - false - } - }) -} - -fn single_profile_collection(config: AppConfig) -> ConfigProfiles { - ConfigProfiles { - version: CONFIG_PROFILES_VERSION, - active_profile: "default".into(), - launch_intro_disabled: false, - auto_map_on_login: false, - profiles: vec![ConfigProfile { - id: "default".into(), - revision: 1, - config, - }], - } -} - -fn default_config_profiles() -> ConfigProfiles { - single_profile_collection(AppConfig::default()) -} - -fn damaged_profile_store(path: &Path, detail: impl Display) -> ConfigError { - let path = path.display(); - ConfigError(format!( - "{path} is a damaged SBMS config profile store: {detail}. Run `{RECOVER_PROFILE_COLLECTION_COMMAND}` to back up and rebuild the entire profile collection" - )) -} - -fn future_profile_store(path: &Path, version: &str) -> ConfigError { - let path = path.display(); - ConfigError(format!( - "{path} uses config profiles version {version}, which is newer than this SBMS and was left unchanged" - )) -} - -fn recognized_future_profiles_version(bytes: &[u8]) -> Option { - let mut deserializer = serde_json::Deserializer::from_slice(bytes); - let value = serde_json::Value::deserialize(&mut deserializer).ok()?; - let version = value.as_object()?.get("version")?.as_number()?; - if let Some(integer) = version.as_u64() { - return (integer > u64::from(CONFIG_PROFILES_VERSION)).then(|| integer.to_string()); - } - if version.as_i64().is_some() { - return None; - } - let float = version.as_f64()?; - (float.is_finite() && float > f64::from(CONFIG_PROFILES_VERSION)).then(|| version.to_string()) -} - -fn parse_profile_store(path: &Path, bytes: &[u8]) -> Result { - if let Some(version) = recognized_future_profiles_version(bytes) { - return Err(future_profile_store(path, &version)); - } - let profiles = serde_json::from_slice::(bytes) - .map_err(|error| damaged_profile_store(path, error))?; - profiles - .validate() - .map_err(|error| damaged_profile_store(path, error))?; - Ok(profiles) -} - -fn profile_store_after_failed_replace(path: &Path, original: &[u8]) -> String { - match fs::read(path) { - Ok(current) if current == original => { - format!("original file {} is unchanged", path.display()) - } - Ok(_) => format!( - "original file {} no longer matches the backed-up bytes", - path.display() - ), - Err(error) => format!( - "original file {} could not be read after the failed replacement: {error}", - path.display() - ), - } -} - -fn backup_parent(source: &Path) -> Result<&Path, ConfigError> { - match source.parent() { - Some(parent) if !parent.as_os_str().is_empty() => Ok(parent), - Some(_) => Ok(Path::new(".")), - None => Err(ConfigError(format!( - "config profile backup path has no parent directory: {}", - source.display() - ))), - } -} - -fn write_backup_file(file: &mut File, bytes: &[u8]) -> std::io::Result<()> { - file.write_all(bytes)?; - file.sync_all() -} - -fn write_unique_profile_backup(source: &Path, bytes: &[u8]) -> Result { - #[cfg(test)] - if consume_profile_store_test_fault(ProfileStoreTestFault::Backup) { - return Err(ConfigError( - "could not create config profile backup: injected failure".into(), - )); - } - - let parent = backup_parent(source)?; - let file_name = source - .file_name() - .and_then(OsStr::to_str) - .unwrap_or(CONFIG_PROFILES_FILE); - let mut collision = None; - for _ in 0..128 { - let sequence = TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed); - let path = parent.join(format!( - "{file_name}.recovery-{}-{sequence}.bak", - std::process::id() - )); - match OpenOptions::new().write(true).create_new(true).open(&path) { - Ok(mut file) => { - if let Err(error) = write_backup_file(&mut file, bytes) { - drop(file); - let _ = fs::remove_file(&path); - return Err(ConfigError(format!( - "could not write config profile backup {}: {error}", - path.display() - ))); - } - drop(file); - match fs::read(&path) { - Ok(stored) if stored == bytes => return Ok(path), - Ok(_) => { - let _ = fs::remove_file(&path); - return Err(ConfigError(format!( - "config profile backup {} did not retain the original bytes", - path.display() - ))); - } - Err(error) => { - let _ = fs::remove_file(&path); - return Err(ConfigError(format!( - "could not read config profile backup {}: {error}", - path.display() - ))); - } - } - } - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { - collision = Some(error); - } - Err(error) => { - return Err(ConfigError(format!( - "could not create config profile backup {}: {error}", - path.display() - ))); - } - } - } - Err(ConfigError(format!( - "could not allocate a unique config profile backup: {}", - collision - .map(|error| error.to_string()) - .unwrap_or_else(|| "too many attempts".into()) - ))) -} - fn snapshot(profile: &ConfigProfile) -> ProfileSnapshot { ProfileSnapshot { profile: ProfileRevision { @@ -1833,13 +1615,6 @@ fn create_temporary(parent: &Path, destination: &Path) -> Result<(PathBuf, File) } fn atomic_replace(temporary: &Path, destination: &Path) -> Result<(), ConfigError> { - #[cfg(test)] - if consume_profile_store_test_fault(ProfileStoreTestFault::Replace) { - return Err(ConfigError(format!( - "could not atomically replace {}: injected failure", - destination.display() - ))); - } let temporary_wide = wide(temporary.as_os_str()); let destination_wide = wide(destination.as_os_str()); let temporary_pcwstr = PCWSTR(temporary_wide.as_ptr()); @@ -2565,384 +2340,4 @@ mod tests { assert_eq!(profiles.load_active().unwrap(), updated); fs::remove_dir_all(root).unwrap(); } - - fn write_unrelated_files(root: &Path) -> Vec<(PathBuf, &'static [u8])> { - let files = [ - ( - DISPLAY_OVERRIDES_FILE, - br#"{"version":1,"displays":[]}"#.as_slice(), - ), - (CONFIG_FILE, br#"{"version":2,"groups":[]}"#), - (LEGACY_CONFIG_FILE, b"{legacy source"), - ("sbms.log", b"log-bytes"), - ("credentials.json", b"stream-secret"), - ]; - files - .into_iter() - .map(|(name, bytes)| { - let path = root.join(name); - fs::write(&path, bytes).unwrap(); - (path, bytes) - }) - .collect() - } - - fn assert_unrelated_unchanged(files: &[(PathBuf, &'static [u8])]) { - for (path, bytes) in files { - assert_eq!(fs::read(path).unwrap(), *bytes, "{}", path.display()); - } - } - - fn recovery_backups(root: &Path) -> Vec { - let mut paths: Vec<_> = fs::read_dir(root) - .unwrap() - .map(|entry| entry.unwrap().path()) - .filter(|path| { - path.file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.contains(".recovery-") && name.ends_with(".bak")) - }) - .collect(); - paths.sort(); - paths - } - - fn temporary_profile_files(root: &Path) -> Vec { - fs::read_dir(root) - .unwrap() - .filter_map(|entry| { - let path = entry.ok()?.path(); - let name = path.file_name()?.to_str()?; - name.contains(".tmp").then_some(path) - }) - .collect() - } - - fn prepare_profile_bytes(name: &str, bytes: &[u8]) -> (PathBuf, ConfigProfileStore) { - let (root, store) = test_profile_store(name); - fs::create_dir_all(&root).unwrap(); - fs::write(store.path(), bytes).unwrap(); - (root, store) - } - - #[test] - fn explicit_recovery_restores_unreadable_profile_bytes_and_keeps_neighbors() { - let cases: &[(&str, &[u8])] = &[ - ("truncated", b"{not json"), - ("cut-off", br#"{"version":1,"profiles":["#), - ("non-utf8", b"\xff\xfe{not json"), - ("string-version", br#"{"version":"99","profiles":[]}"#), - ("incomplete-future", br#"{"version":99"#), - ]; - for (name, original) in cases { - let (root, store) = prepare_profile_bytes(name, original); - let unrelated = write_unrelated_files(&root); - let plain_reset = store.reset_active().unwrap_err(); - assert!( - plain_reset.allows_profile_collection_recovery(), - "{name}: {plain_reset}" - ); - assert!( - !plain_reset.to_string().contains("was not committed"), - "{name}" - ); - assert_eq!(fs::read(store.path()).unwrap(), *original, "{name}"); - assert!(recovery_backups(&root).is_empty(), "{name}"); - - let recovered = store.recover_with_backup().unwrap(); - assert_eq!( - fs::read(&recovered.backup_path).unwrap(), - *original, - "{name}" - ); - assert_eq!(recovered.snapshot.profile.id, "default"); - assert_eq!(recovered.snapshot.profile.revision, 1); - assert_eq!(recovered.snapshot.config, AppConfig::default()); - assert_ne!(fs::read(store.path()).unwrap(), *original, "{name}"); - let loaded = store.load_active().unwrap(); - assert_eq!(loaded, recovered.snapshot); - assert_unrelated_unchanged(&unrelated); - - let updated = store - .update_active(|config| { - *config = config_with_target("recovered-target"); - Ok(()) - }) - .unwrap(); - assert_eq!(updated.profile.revision, 2); - assert_eq!(store.load_active().unwrap(), updated); - let (saved, active) = store - .save_profile("edited", &config_with_target("edited-target"), false, false) - .unwrap(); - assert!(!active); - assert_eq!(saved.profile.id, "edited"); - assert_eq!(store.list().unwrap().profiles.len(), 2); - assert_eq!( - store.load_active().unwrap().config, - config_with_target("recovered-target") - ); - assert_eq!( - fs::read(&recovered.backup_path).unwrap(), - *original, - "{name}" - ); - assert_unrelated_unchanged(&unrelated); - fs::remove_dir_all(root).unwrap(); - } - } - - #[test] - fn explicit_recovery_rebuilds_a_known_but_semantically_invalid_collection() { - let original = br#"{"version":1,"active_profile":"missing","launch_intro_disabled":true,"auto_map_on_login":true,"profiles":[{"id":"default","revision":3,"config":{"version":2,"groups":[{"id":0,"route":{"kind":"mirror","target_id":"office"}}],"selected_group_id":0}},{"id":"gaming","revision":4,"config":{"version":2,"groups":[{"id":0,"route":{"kind":"mirror","target_id":"gaming"}}],"selected_group_id":0}}]}"#; - let (root, store) = prepare_profile_bytes("semantic", original); - let unrelated = write_unrelated_files(&root); - let error = store.load_active().unwrap_err(); - assert!(error.allows_profile_collection_recovery(), "{error}"); - assert!(error.to_string().contains("does not exist"), "{error}"); - - let recovered = store.recover_with_backup().unwrap(); - assert_eq!(fs::read(&recovered.backup_path).unwrap(), original); - let profiles = store.list().unwrap(); - assert_eq!(profiles.profiles.len(), 1); - assert_eq!(profiles.active_profile, "default"); - assert!(!profiles.launch_intro_disabled); - assert!(!profiles.auto_map_on_login); - assert_eq!(profiles.active().config, AppConfig::default()); - assert_eq!(profiles.active().revision, 1); - assert_unrelated_unchanged(&unrelated); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn explicit_recovery_backs_up_raw_bytes_and_repeated_runs_keep_every_backup() { - let (root, store) = test_profile_store("repeat"); - store.load_active().unwrap(); - store.set_launch_intro_disabled(true).unwrap(); - store.set_auto_map_on_login(true).unwrap(); - store - .save_profile("gaming", &config_with_target("gaming-display"), false, true) - .unwrap(); - let original = fs::read(store.path()).unwrap(); - let first = store.recover_with_backup().unwrap(); - assert_eq!(fs::read(&first.backup_path).unwrap(), original); - let rebuilt = fs::read(store.path()).unwrap(); - assert_ne!(rebuilt, original); - let profiles = store.list().unwrap(); - assert_eq!(profiles.profiles.len(), 1); - assert!(!profiles.launch_intro_disabled); - assert!(!profiles.auto_map_on_login); - - let second = store.recover_with_backup().unwrap(); - assert_ne!(first.backup_path, second.backup_path); - assert_eq!(fs::read(&first.backup_path).unwrap(), original); - assert_eq!(fs::read(&second.backup_path).unwrap(), rebuilt); - assert_eq!(recovery_backups(&root).len(), 2); - assert_eq!(store.load_active().unwrap().profile.revision, 1); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn profile_backup_creation_fails_when_the_parent_is_not_a_directory() { - let parent = env::temp_dir().join(format!( - "sbms-config-backup-parent-{}-{}", - std::process::id(), - TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed) - )); - fs::write(&parent, b"not-a-directory").unwrap(); - let source = parent.join(CONFIG_PROFILES_FILE); - let error = write_unique_profile_backup(&source, b"raw-bytes").unwrap_err(); - assert!( - error - .to_string() - .contains("could not create config profile backup"), - "{error}" - ); - assert_eq!(fs::read(&parent).unwrap(), b"not-a-directory"); - assert!(!source.exists()); - fs::remove_file(parent).unwrap(); - } - - #[test] - fn profile_recovery_keeps_the_source_when_backup_fails() { - let original = b"{not-json"; - let (root, store) = prepare_profile_bytes("backup-fails", original); - let unrelated = write_unrelated_files(&root); - // The transaction holds the profile lock across backup and replacement, - // so an external process cannot fail only the backup step. This fault - // stands in for that IO error before any backup file is created. - let _fault = inject_profile_store_fault(ProfileStoreTestFault::Backup); - let error = store.recover_with_backup().unwrap_err(); - drop(_fault); - let message = error.to_string(); - assert!( - message.contains("could not create config profile backup"), - "{message}" - ); - assert!(!message.contains("was not committed"), "{message}"); - assert!( - !message.contains("configuration recovery was committed"), - "{message}" - ); - assert!(!error.allows_profile_collection_recovery(), "{message}"); - assert_eq!(fs::read(store.path()).unwrap(), original); - assert!(recovery_backups(&root).is_empty()); - assert!(temporary_profile_files(&root).is_empty()); - assert_unrelated_unchanged(&unrelated); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn profile_recovery_keeps_the_backup_when_atomic_replace_fails() { - let original = b"\xff\xfe{truncated"; - let (root, store) = prepare_profile_bytes("replace-fails", original); - let unrelated = write_unrelated_files(&root); - let _fault = inject_profile_store_fault(ProfileStoreTestFault::Replace); - let error = store.recover_with_backup().unwrap_err(); - drop(_fault); - let message = error.to_string(); - assert!(message.contains("was not committed"), "{message}"); - assert!(message.contains("is unchanged"), "{message}"); - assert!(message.contains("backup remains at"), "{message}"); - assert!( - message.contains("could not atomically replace"), - "{message}" - ); - assert!( - !message.contains("configuration recovery was committed"), - "{message}" - ); - assert_eq!(fs::read(store.path()).unwrap(), original); - let backups = recovery_backups(&root); - assert_eq!(backups.len(), 1); - assert_eq!(fs::read(&backups[0]).unwrap(), original); - let backup_name = backups[0] - .file_name() - .and_then(|name| name.to_str()) - .unwrap(); - assert!(message.contains(backup_name), "{message}"); - assert!(temporary_profile_files(&root).is_empty()); - assert_unrelated_unchanged(&unrelated); - - let recovered = store.recover_with_backup().unwrap(); - assert_ne!(recovered.backup_path, backups[0]); - assert_eq!(fs::read(&backups[0]).unwrap(), original); - assert_eq!(fs::read(&recovered.backup_path).unwrap(), original); - assert_eq!(store.load_active().unwrap().config, AppConfig::default()); - assert_unrelated_unchanged(&unrelated); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn future_profile_schema_is_refused_without_backup_or_replacement() { - let cases: &[(&str, &[u8])] = &[ - ( - "version-99", - br#"{"version":99,"active_profile":"default","profiles":[]}"#, - ), - ("version-2-extra", br#"{"version":2,"extra":true}"#), - ("version-prefix", br#"{"version":99} trailing"#), - ("version-float", br#"{"version":1.5,"profiles":[]}"#), - ]; - for (name, original) in cases { - let (root, store) = prepare_profile_bytes(name, original); - let unrelated = write_unrelated_files(&root); - for error in [ - store.reset_active().unwrap_err(), - store.recover_with_backup().unwrap_err(), - store.load_active().unwrap_err(), - ] { - let message = error.to_string(); - assert!( - message.contains("newer than this SBMS"), - "{name}: {message}" - ); - assert!(message.contains("left unchanged"), "{name}: {message}"); - assert!( - !error.allows_profile_collection_recovery(), - "{name}: {message}" - ); - assert!( - !message.contains(RECOVER_PROFILE_COLLECTION_COMMAND), - "{name}" - ); - assert!(!message.contains("was not committed"), "{name}: {message}"); - } - assert_eq!(fs::read(store.path()).unwrap(), *original, "{name}"); - assert!(recovery_backups(&root).is_empty(), "{name}"); - assert_unrelated_unchanged(&unrelated); - fs::remove_dir_all(root).unwrap(); - } - } - - #[test] - fn profile_recovery_does_not_treat_read_errors_or_absence_as_damage() { - let (root, store) = test_profile_store("missing-store"); - let missing = store.recover_with_backup().unwrap_err(); - assert!( - missing - .to_string() - .contains("does not exist and was not created"), - "{missing}" - ); - assert!(!missing.allows_profile_collection_recovery(), "{missing}"); - assert!(!root.exists()); - - let (root, store) = test_profile_store("directory-store"); - fs::create_dir_all(store.path()).unwrap(); - let unrelated = root.join("credentials.json"); - fs::write(&unrelated, b"stream-secret").unwrap(); - let error = store.recover_with_backup().unwrap_err(); - let message = error.to_string(); - assert!(message.contains("could not read"), "{message}"); - assert!(!error.allows_profile_collection_recovery(), "{message}"); - assert!( - !message.contains(RECOVER_PROFILE_COLLECTION_COMMAND), - "{message}" - ); - assert!(store.path().is_dir()); - assert_eq!(fs::read(&unrelated).unwrap(), b"stream-secret"); - assert!(recovery_backups(&root).is_empty()); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn reset_active_resets_only_the_active_profile_inside_a_valid_collection() { - let (root, store) = test_profile_store("reset-active-only"); - let unrelated = { - fs::create_dir_all(&root).unwrap(); - write_unrelated_files(&root) - }; - store.load_active().unwrap(); - store - .update_active(|config| { - *config = config_with_target("default-display"); - Ok(()) - }) - .unwrap(); - store.set_launch_intro_disabled(true).unwrap(); - store.set_auto_map_on_login(true).unwrap(); - store - .save_profile("gaming", &config_with_target("gaming-display"), false, true) - .unwrap(); - - let snapshot = store.reset_active().unwrap(); - assert_eq!(snapshot.profile.id, "gaming"); - assert_eq!(snapshot.config, AppConfig::default()); - let profiles = store.list().unwrap(); - assert_eq!(profiles.profiles.len(), 2); - assert_eq!(profiles.active_profile, "gaming"); - assert!(profiles.launch_intro_disabled); - assert!(profiles.auto_map_on_login); - assert_eq!( - profiles.profile("default").unwrap().config, - config_with_target("default-display") - ); - assert_eq!( - profiles.profile("gaming").unwrap().config, - AppConfig::default() - ); - assert!(recovery_backups(&root).is_empty()); - assert_unrelated_unchanged(&unrelated); - fs::remove_dir_all(root).unwrap(); - } } diff --git a/src/main.rs b/src/main.rs index 40a39c7..8bd4a3e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,9 +6,7 @@ use std::path::Path; use std::sync::Arc; use std::time::Duration; -use sbms::config::{ - ConfigError, ConfigProfileStore, ConfigStore, GroupRouteConfig, ProfileRecovery, -}; +use sbms::config::{ConfigError, ConfigProfileStore, ConfigStore, GroupRouteConfig}; use sbms::diagnostics::{self, Level, MappingSessionId}; use sbms::display::{active_displays, unique_physical_display}; use sbms::geometry::Rotation; @@ -644,25 +642,15 @@ fn config(mut arguments: impl Iterator) -> Result<(), Box match reset_args(arguments) { - ResetArgs::Active => { - let snapshot = store.reset_active()?; - println!( - "reset={} revision={} reload={}", - snapshot.profile.id, - snapshot.profile.revision, - reload_status(signal_config_reload()?) - ); - } - ResetArgs::RecoverCollection => { - let recovery = store.recover_with_backup()?; - report_profile_recovery( - &recovery, - signal_config_reload().map_err(|error| error.to_string()), - )?; - } - ResetArgs::Invalid => usage(), - }, + Some("reset") if arguments.next().is_none() => { + let snapshot = store.reset_active()?; + println!( + "reset={} revision={} reload={}", + snapshot.profile.id, + snapshot.profile.revision, + reload_status(signal_config_reload()?) + ); + } _ => usage(), } Ok(()) @@ -672,57 +660,6 @@ fn signal_config_reload() -> Result> { sbms::control::signal_config_reload().map_err(Into::into) } -enum ResetArgs { - Active, - RecoverCollection, - Invalid, -} - -fn reset_args(arguments: impl Iterator) -> ResetArgs { - let arguments: Vec = arguments.collect(); - match arguments.as_slice() { - [] => ResetArgs::Active, - [left, right] - if (left == "--all" && right == "--backup") - || (left == "--backup" && right == "--all") => - { - ResetArgs::RecoverCollection - } - _ => ResetArgs::Invalid, - } -} - -fn report_profile_recovery( - recovery: &ProfileRecovery, - reload: Result, -) -> Result<(), Box> { - match reload { - Ok(signaled) => { - println!( - "recovered={} revision={} backup={} reload={}", - recovery.snapshot.profile.id, - recovery.snapshot.profile.revision, - recovery.backup_path.display(), - reload_status(signaled) - ); - Ok(()) - } - Err(error) => { - println!( - "recovered={} revision={} backup={} reload=failed", - recovery.snapshot.profile.id, - recovery.snapshot.profile.revision, - recovery.backup_path.display() - ); - Err(committed_recovery_reload_error(&error).into()) - } - } -} - -fn committed_recovery_reload_error(error: &str) -> String { - format!("configuration recovery was committed; tray reload failed: {error}") -} - fn reload_status(signaled: bool) -> &'static str { if signaled { "signaled" } else { "not-running" } } @@ -774,26 +711,8 @@ fn usage() -> ! { sbms config activate|delete sbms config reload sbms config set-target |clear-target|reset - sbms config reset --all --backup sbms shutdown sbms ui" ); std::process::exit(2); } - -#[cfg(test)] -mod tests { - use super::committed_recovery_reload_error; - - #[test] - fn reload_failure_reports_that_recovery_stays_committed() { - let message = committed_recovery_reload_error( - "OpenEventW(config reload) failed: Access is denied. (os error 5)", - ); - assert!(message.contains("configuration recovery was committed")); - assert!(message.contains("tray reload failed")); - assert!(message.contains("OpenEventW(config reload) failed")); - assert!(!message.contains("rolled back")); - assert!(!message.contains("was not committed")); - } -} diff --git a/src/ui.rs b/src/ui.rs index 50a16d9..29dbd88 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -6,9 +6,8 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use crate::config::{ - AppConfig, ConfigError, ConfigProfileStore, ConfigProfiles, DisplayOverrideStore, - DisplayOverrides, MAX_CONFIG_PROFILES, ProfileRevision, RECOVER_PROFILE_COLLECTION_COMMAND, - ReferenceSource, + AppConfig, ConfigProfileStore, ConfigProfiles, DisplayOverrideStore, DisplayOverrides, + MAX_CONFIG_PROFILES, ProfileRevision, ReferenceSource, }; use crate::control::{TrayInstance, listen_for_config_reload, listen_for_shutdown}; use crate::controller::{Controller, ControllerEvent, DisplayOption}; @@ -1459,10 +1458,10 @@ fn load_group_config(ui: &QuickAccess) -> LoadedGroups { let snapshot = match ConfigProfileStore::default_store().and_then(|store| store.load_active()) { Ok(snapshot) => snapshot, Err(error) => { + diagnostics::log(Level::Error, "config", "load", None, error.to_string()); set_geometry_unconfigured(ui); ui.set_geometry_save_blocked(true); - diagnostics::log(Level::Error, "config", "load", None, error.to_string()); - ui.set_geometry_error(profile_load_message(&error).into()); + ui.set_geometry_error(error.to_string().into()); return default_loaded_groups(); } }; @@ -1514,12 +1513,9 @@ fn apply_config_reload( Ok(snapshot) => snapshot, Err(error) => { diagnostics::log(Level::Error, "config", "reload", None, error.to_string()); - let detail = profile_load_message(&error); - surface_transient_error( - ui, - error_revision, - &format!("Couldn’t reload configuration: {detail}"), - ); + ui.set_geometry_save_blocked(true); + ui.set_geometry_valid(false); + ui.set_geometry_error(error.to_string().into()); return false; } }; @@ -1585,13 +1581,6 @@ fn persist_groups( profile_revision: &Arc>, ) -> bool { if ui.get_geometry_save_blocked() { - let existing = ui.get_geometry_error().to_string(); - let message = if existing.is_empty() { - "The saved configuration could not be loaded and was left unchanged".to_string() - } else { - existing - }; - surface_persistence_error(ui, &message); return false; } let validated = match validate_group_drafts(groups) { @@ -1610,6 +1599,9 @@ fn persist_validated_groups( active: usize, profile_revision: &Arc>, ) -> bool { + if ui.get_geometry_save_blocked() { + return false; + } let persisted = groups.iter().map(ValidatedGroupDraft::to_config).collect(); let Some(selected_group_id) = groups.get(active).map(ValidatedGroupDraft::id) else { surface_persistence_error(ui, "The selected mapping group no longer exists"); @@ -1667,16 +1659,6 @@ fn finish_profile_save(ui: slint::Weak, generation: u64, succeeded: } } -fn profile_load_message(error: &ConfigError) -> String { - if error.allows_profile_collection_recovery() { - format!( - "The saved configuration is damaged. Run `{RECOVER_PROFILE_COLLECTION_COMMAND}` to back up and rebuild the entire profile collection before saving" - ) - } else { - error.to_string() - } -} - fn surface_persistence_error(ui: &QuickAccess, error: &str) { ui.set_error_text(format!("Couldn’t save mapping groups: {error}").into()); ui.set_state_detail("Mapping group changes were not saved".into()); @@ -2478,6 +2460,62 @@ mod tests { restored.groups[0].sizing.unwrap().strategy, SizingStrategy::RoundedScale ); + + // A failed read must survive UI edits and hydration until a good reload. + // This child process uses a temporary LOCALAPPDATA, never the real profile. + let saved = std::fs::read(store.path()).unwrap(); + std::fs::write(store.path(), b"{").unwrap(); + let read_error = store.load_active().unwrap_err().to_string(); + let fallback = super::load_group_config(&ui); + assert_eq!(fallback.groups.len(), 1); + assert!(ui.get_geometry_save_blocked()); + assert!(!ui.get_geometry_valid()); + ui.invoke_geometry_edited(); + ui.invoke_save_geometry(); + ui.invoke_rendering_edited(); + super::hydrate_group( + &ui, + &tray, + &displays.lock().unwrap(), + &groups.lock().unwrap(), + *active.lock().unwrap(), + ); + assert_eq!(ui.get_geometry_error(), read_error.as_str()); + assert!(!ui.get_geometry_valid()); + // Invalid drafts must not replace the original read error with validation. + assert!(!super::persist_groups(&ui, &[], 0, &profile)); + assert!(!super::persist_validated_groups(&ui, &[], 0, &profile)); + assert_eq!(ui.get_geometry_error(), read_error.as_str()); + assert_eq!(std::fs::read(store.path()).unwrap(), b"{"); + let reload = || { + super::apply_config_reload( + &ui, + &tray, + &displays, + &groups, + &active, + &profile, + &error_revision, + ) + }; + ui.set_geometry_save_blocked(false); + ui.set_geometry_valid(true); + assert!(!reload()); + assert!(ui.get_geometry_save_blocked()); + assert!(!ui.get_geometry_valid()); + assert_eq!(ui.get_geometry_error(), read_error.as_str()); + std::fs::write(store.path(), saved).unwrap(); + assert!(reload()); + assert!(!ui.get_geometry_save_blocked()); + assert!(ui.get_geometry_error().is_empty()); + assert!(ui.get_geometry_valid()); + assert!(super::persist_groups( + &ui, + &groups.lock().unwrap(), + *active.lock().unwrap(), + &profile, + )); + // Only unfinished stream groups remain: the transitional seed must carry // the full manual settings even when there is no sizing mirror left. while groups diff --git a/src/ui/geometry_view.rs b/src/ui/geometry_view.rs index 059edc2..6908d1f 100644 --- a/src/ui/geometry_view.rs +++ b/src/ui/geometry_view.rs @@ -1,6 +1,9 @@ use super::*; pub(super) fn update_geometry_preview(ui: &QuickAccess, displays: &[DisplayOption]) { + if ui.get_geometry_save_blocked() { + return; + } update_resolution_suggestions(ui); ui.set_geometry_error("".into()); ui.set_geometry_valid(false); @@ -148,6 +151,9 @@ pub(super) fn update_resolution_suggestions(ui: &QuickAccess) { } pub(super) fn calculate_geometry(ui: &QuickAccess, displays: &[DisplayOption]) { + if ui.get_geometry_save_blocked() { + return; + } update_geometry_preview(ui, displays); if !ui.get_geometry_valid() { if ui.get_page() != QuickAccessPage::Geometry && !ui.get_geometry_error().is_empty() { @@ -463,9 +469,7 @@ pub(super) fn set_geometry_result(ui: &QuickAccess, result: SizingResult, config format!("Scale {:.2}× × {:.2}×", result.scale_x, result.scale_y).into(), ); ui.set_geometry_valid(!ui.get_geometry_save_blocked()); - if !ui.get_geometry_save_blocked() { - ui.set_geometry_error("".into()); - } + ui.set_geometry_error("".into()); if configured { let refresh = result .preferred_refresh_millihz diff --git a/src/ui/handlers.rs b/src/ui/handlers.rs index be1497f..1d55e1b 100644 --- a/src/ui/handlers.rs +++ b/src/ui/handlers.rs @@ -57,6 +57,9 @@ pub(super) fn register_lifecycle_handlers( let start_state = state.clone(); flyout.on_start(move || { if let Some(ui) = flyout_weak.upgrade() { + if ui.get_geometry_save_blocked() { + return; + } let displays = start_state .displays .lock() @@ -102,7 +105,14 @@ pub(super) fn register_lifecycle_handlers( let stop_sender = sender.clone(); flyout.on_stop(move || stop_sender.stop()); let restart_sender = sender.clone(); - flyout.on_restart_mapping(move || restart_sender.restart_mapping()); + let flyout_weak = flyout.as_weak(); + flyout.on_restart_mapping(move || { + if let Some(ui) = flyout_weak.upgrade() + && !ui.get_geometry_save_blocked() + { + restart_sender.restart_mapping(); + } + }); let flyout_weak = flyout.as_weak(); let display_settings_error_revision = error_revision.clone(); diff --git a/src/ui/projection.rs b/src/ui/projection.rs index 727bd2d..c12f46e 100644 --- a/src/ui/projection.rs +++ b/src/ui/projection.rs @@ -183,7 +183,9 @@ pub(super) fn hydrate_group( } ui.set_sizing_strategy(sizing_strategy_index(group.sizing_strategy)); rebuild_reference_options(ui, displays, groups, group.reference_source.clone()); - if let Ok(request) = group_sizing_request(group, displays) { + if ui.get_geometry_save_blocked() { + ui.set_geometry_valid(false); + } else if let Ok(request) = group_sizing_request(group, displays) { match request.calculate() { Ok(result) => set_geometry_result(ui, result, true), Err(error) => { diff --git a/tests/cli_contract.rs b/tests/cli_contract.rs index f0e4196..878b83b 100644 --- a/tests/cli_contract.rs +++ b/tests/cli_contract.rs @@ -65,7 +65,6 @@ fn usage() -> &'static str { sbms config activate|delete sbms config reload sbms config set-target |clear-target|reset - sbms config reset --all --backup sbms shutdown sbms ui " @@ -293,256 +292,6 @@ fn config_export_never_overwrites_store_or_existing_destination_without_force() assert_eq!(fs::read(destination).unwrap(), b"keep-me"); } -fn recovery_backups(root: &TestRoot) -> Vec { - let profiles = root.profiles_path(); - let directory = profiles.parent().unwrap(); - let mut paths: Vec<_> = fs::read_dir(directory) - .unwrap() - .map(|entry| entry.unwrap().path()) - .filter(|path| { - path.file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.contains(".recovery-") && name.ends_with(".bak")) - }) - .collect(); - paths.sort(); - paths -} - -fn write_profile_neighbors(root: &TestRoot) -> (PathBuf, Vec, PathBuf, Vec) { - let profiles = root.profiles_path(); - let directory = profiles.parent().unwrap(); - fs::create_dir_all(directory).unwrap(); - let legacy = root.config_path(); - let legacy_bytes = b"legacy-source".to_vec(); - fs::write(&legacy, &legacy_bytes).unwrap(); - let overrides = directory.join("display-overrides-v1.json"); - let override_bytes = br#"{"version":1,"displays":[]}"#.to_vec(); - fs::write(&overrides, &override_bytes).unwrap(); - let credentials = directory.join("credentials.json"); - fs::write(&credentials, b"stream-secret").unwrap(); - let log = directory.join("sbms.log"); - fs::write(&log, b"log-bytes").unwrap(); - (legacy, legacy_bytes, overrides, override_bytes) -} - -#[test] -fn config_reset_rejects_incomplete_recovery_arguments_without_writing() { - let root = TestRoot::new("reset-args"); - let profiles = root.profiles_path(); - fs::create_dir_all(profiles.parent().unwrap()).unwrap(); - let original = b"{not json".to_vec(); - fs::write(&profiles, &original).unwrap(); - let (legacy, legacy_bytes, overrides, override_bytes) = write_profile_neighbors(&root); - - for arguments in [ - &["config", "reset", "--all"][..], - &["config", "reset", "--backup"][..], - &["config", "reset", "--all", "--backup", "extra"][..], - &["config", "reset", "--backup", "--all", "--force"][..], - &["config", "reset", "--all", "--all"][..], - &["config", "reset", "--backup", "--backup"][..], - ] { - let output = run(&root, arguments); - assert_eq!( - output.status.code(), - Some(2), - "{arguments:?}\n{}", - text(&output.stderr) - ); - assert_eq!(text(&output.stdout), ""); - assert_eq!(text(&output.stderr), usage()); - assert_eq!(fs::read(&profiles).unwrap(), original, "{arguments:?}"); - assert_eq!(fs::read(&legacy).unwrap(), legacy_bytes, "{arguments:?}"); - assert_eq!( - fs::read(&overrides).unwrap(), - override_bytes, - "{arguments:?}" - ); - assert_eq!( - fs::read(profiles.parent().unwrap().join("credentials.json")).unwrap(), - b"stream-secret" - ); - assert_eq!( - fs::read(profiles.parent().unwrap().join("sbms.log")).unwrap(), - b"log-bytes" - ); - assert!(recovery_backups(&root).is_empty(), "{arguments:?}"); - } -} - -#[test] -fn config_reset_all_backup_restores_damaged_bytes_and_can_save_again() { - let root = TestRoot::new("recover-store"); - let profiles = root.profiles_path(); - fs::create_dir_all(profiles.parent().unwrap()).unwrap(); - let original = b"\xff\xfe{not json".to_vec(); - fs::write(&profiles, &original).unwrap(); - let (legacy, legacy_bytes, overrides, override_bytes) = write_profile_neighbors(&root); - - let recovered = run(&root, &["config", "reset", "--backup", "--all"]); - assert!(recovered.status.success(), "{}", text(&recovered.stderr)); - let stdout = text(&recovered.stdout); - assert!(stdout.contains("recovered=default"), "{stdout}"); - assert!(stdout.contains("revision=1"), "{stdout}"); - assert!(stdout.contains("backup="), "{stdout}"); - assert!(stdout.contains("reload="), "{stdout}"); - assert!(!stdout.contains("reload=failed"), "{stdout}"); - let backups = recovery_backups(&root); - assert_eq!(backups.len(), 1); - assert_eq!(fs::read(&backups[0]).unwrap(), original); - let backup_name = backups[0] - .file_name() - .and_then(|name| name.to_str()) - .unwrap(); - assert!(stdout.contains(backup_name), "{stdout}"); - assert_eq!(fs::read(&legacy).unwrap(), legacy_bytes); - assert_eq!(fs::read(&overrides).unwrap(), override_bytes); - assert_eq!( - fs::read(profiles.parent().unwrap().join("credentials.json")).unwrap(), - b"stream-secret" - ); - assert_eq!( - fs::read(profiles.parent().unwrap().join("sbms.log")).unwrap(), - b"log-bytes" - ); - - let rebuilt = fs::read(&profiles).unwrap(); - let again = run(&root, &["config", "reset", "--all", "--backup"]); - assert!(again.status.success(), "{}", text(&again.stderr)); - let backups = recovery_backups(&root); - assert_eq!(backups.len(), 2); - let backup_bytes: Vec> = backups.iter().map(|path| fs::read(path).unwrap()).collect(); - assert!(backup_bytes.iter().any(|bytes| bytes == &original)); - assert!(backup_bytes.iter().any(|bytes| bytes == &rebuilt)); - - let shown = run(&root, &["config", "show"]); - assert!(shown.status.success(), "{}", text(&shown.stderr)); - let config: Value = serde_json::from_slice(&shown.stdout).unwrap(); - assert_eq!(config["version"], 2); - assert_eq!(config["groups"][0]["id"], 0); - - let saved = run(&root, &["config", "save", "edited"]); - assert!(saved.status.success(), "{}", text(&saved.stderr)); - let listed = run(&root, &["config", "list"]); - assert!(listed.status.success(), "{}", text(&listed.stderr)); - let profiles_json: Value = serde_json::from_slice(&listed.stdout).unwrap(); - assert_eq!(profiles_json.as_array().unwrap().len(), 2); - assert_eq!(fs::read(&legacy).unwrap(), legacy_bytes); - assert_eq!(fs::read(&overrides).unwrap(), override_bytes); -} - -#[test] -fn config_reset_all_backup_refuses_a_future_schema_without_writing() { - let root = TestRoot::new("future-store"); - let profiles = root.profiles_path(); - fs::create_dir_all(profiles.parent().unwrap()).unwrap(); - let original = br#"{"version":99,"active_profile":"default","profiles":[]}"#.to_vec(); - fs::write(&profiles, &original).unwrap(); - let (legacy, legacy_bytes, overrides, override_bytes) = write_profile_neighbors(&root); - - let output = run(&root, &["config", "reset", "--all", "--backup"]); - assert_eq!(output.status.code(), Some(1), "{}", text(&output.stdout)); - let stderr = text(&output.stderr); - assert!(stderr.contains("newer than this SBMS"), "{stderr}"); - assert!(stderr.contains("left unchanged"), "{stderr}"); - assert!( - !stderr.contains("configuration recovery was committed"), - "{stderr}" - ); - assert!( - !stderr.contains("sbms config reset --all --backup"), - "{stderr}" - ); - assert_eq!(text(&output.stdout), ""); - assert_eq!(fs::read(&profiles).unwrap(), original); - assert!(recovery_backups(&root).is_empty()); - assert_eq!(fs::read(&legacy).unwrap(), legacy_bytes); - assert_eq!(fs::read(&overrides).unwrap(), override_bytes); -} - -#[test] -fn config_reset_changes_only_the_active_profile() { - let root = TestRoot::new("reset-active"); - let office_path = root.path().join("office.json"); - let gaming_path = root.path().join("gaming.json"); - let office = json!({ - "version": 2, - "groups": [{ - "id": 0, - "route": {"kind": "mirror", "target_id": "office-display"} - }], - "selected_group_id": 0 - }); - let gaming = json!({ - "version": 2, - "groups": [{ - "id": 0, - "route": {"kind": "mirror", "target_id": "gaming-display"} - }], - "selected_group_id": 0 - }); - fs::write(&office_path, serde_json::to_vec_pretty(&office).unwrap()).unwrap(); - fs::write(&gaming_path, serde_json::to_vec_pretty(&gaming).unwrap()).unwrap(); - assert!(run(&root, &["config", "show"]).status.success()); - let replace_default = run( - &root, - &[ - "config", - "import", - "default", - office_path.to_str().unwrap(), - "--replace", - ], - ); - assert!( - replace_default.status.success(), - "{}", - text(&replace_default.stderr) - ); - let activate_gaming = run( - &root, - &[ - "config", - "import", - "gaming", - gaming_path.to_str().unwrap(), - "--activate", - ], - ); - assert!( - activate_gaming.status.success(), - "{}", - text(&activate_gaming.stderr) - ); - - let reset = run(&root, &["config", "reset"]); - assert!(reset.status.success(), "{}", text(&reset.stderr)); - assert!(text(&reset.stdout).starts_with("reset=gaming revision=2 reload=")); - assert!(recovery_backups(&root).is_empty()); - - let active = run(&root, &["config", "show"]); - let active_config: Value = serde_json::from_slice(&active.stdout).unwrap(); - assert_eq!( - active_config["groups"][0]["route"], - json!({"kind": "mirror"}) - ); - let preserved = run(&root, &["config", "show", "default"]); - assert_eq!( - serde_json::from_slice::(&preserved.stdout).unwrap(), - office - ); - let listed = serde_json::from_slice::(&run(&root, &["config", "list"]).stdout).unwrap(); - assert_eq!(listed.as_array().unwrap().len(), 2); - assert!( - listed - .as_array() - .unwrap() - .iter() - .any(|profile| { profile["id"] == "gaming" && profile["active"] == true }) - ); -} - #[test] fn plan_validation_reports_valid_and_empty_plans() { let root = TestRoot::new("plan"); diff --git a/ui/quick-access.slint b/ui/quick-access.slint index aa5f161..c07b386 100644 --- a/ui/quick-access.slint +++ b/ui/quick-access.slint @@ -176,11 +176,11 @@ export component QuickAccess inherits Window { reference-action-enabled: root.reference-action-enabled; sizing-strategy <=> root.sizing-strategy; state: root.state; - state-detail: root.state-detail; + state-detail: root.geometry-save-blocked ? "Configuration unavailable" : root.state-detail; running: root.running; busy: root.busy; restart-available: root.restart-available; - error-text: root.error-text; + error-text: root.geometry-save-blocked ? root.geometry-error : root.error-text; mapping-fps: root.mapping-fps; mapping-fps-valid: root.mapping-fps-valid; mapping-fps-error: root.mapping-fps-error;