diff --git a/README.md b/README.md index f19352b..4708e53 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,15 @@ plus specific pairs such as `teh` → `the` that must never be applied. Entries in `%LOCALAPPDATA%\AutoFix\autofix.sqlite`, with a language tag and optional app process scope. `und` protects all languages; an empty app scope applies everywhere. +**Languages** defaults to automatic detection. Set a global preferred BCP 47 +language tag, optional app overrides, and policies for uncertain or mixed text. +App overrides take priority. **Engines** configures local/API routing, provider, +custom endpoint, model, timeouts and local fallback. Manage provider keys through +the masked Windows Credential Manager editor; keys are excluded from config +exports. **Logs / Debug** displays the latest 500 metadata events and can clear +metadata and debug logs. Full-text debug requires an explicit privacy warning, +including through config import; redacted debug remains available separately. + Learning defaults to **Off — undo only**. App-level undo only restores the correction unless you choose **Ask after undo** or **Automatically learn**. Ask shows “Don't correct this again?” after a successful undo; only Yes saves an @@ -81,7 +90,7 @@ active when learning is off. Native Ctrl+Z and suggestion rejection are not trac use AutoFix's undo shortcut to reject an applied correction. Native clipboard replacement preserves all readable formats and restores them -before reporting success. Disable it under **Correction > Use clipboard for +before reporting success. Disable it under **Privacy & Security > Use clipboard for correction** or set `replacement.clipboard_enabled = false` in settings TOML. See [the engine documentation](app-core-rust/README.md) for runtime boundaries. @@ -130,13 +139,35 @@ moves the corrected text into informative context, clears executable context, records app-level undo and writes metadata without document text. Selected text must belong to the current typed segment unless **Correct arbitrary -selection** is enabled under **Shortcuts**. Even with that option, backward +selection** is enabled under **Privacy & Security**. Even with that option, backward selections and selections without reliable caret proof skip correction. Text after the caret stays untouched. Unchanged or suppressed selections retain their context and selection; suggestion acceptance remains planned. ## Run App +The settings search bar finds names, descriptions, choices and config paths +across every page, including Privacy & Security and nested Context limits. +Use Ctrl+F, then try `word count threshold`, `timeout` or `cancel oldest`. +Matching settings are filtered and highlighted. Clear search or press Escape in +the search box to browse again. Keys, typed text and saved dictionary contents +are excluded from the search index. + +**Advanced → Settings import/export** exports a ZIP containing `settings.toml`, +app rules, the custom dictionary and language overrides. Learned pair rules are +optional and excluded by default. Import validates a ZIP bundle or legacy TOML +file, previews the replacements, and applies only after confirmation. Successful +imports reload the background process. Bundles exclude API keys, logs, typed +session data and correction-history text; keys remain in Windows Credential +Manager on the current device. + +Interrupted imports recover automatically before settings are loaded: SQLite +durably records whether to restore the old settings or finish the committed +import. Correction remains blocked while recovery is pending. Settings and rule +data therefore resume from the same committed import, even if the settings file +did not survive shutdown. See [the settings documentation](ui/settings-ui/README.md) +for the recovery protocol and failure reporting. + From the repository root, build and run AutoFix: ```powershell diff --git a/app-core-rust/README.md b/app-core-rust/README.md index 39c04e3..0a83d74 100644 --- a/app-core-rust/README.md +++ b/app-core-rust/README.md @@ -506,3 +506,21 @@ interactive Windows desktop. It safely refuses unsupported clipboard formats. Feature code should be organized by product behavior, not technical layer. Keep modules small, private by default, and colocate tests with the behavior they verify. Do not implement optional helper mode here until it becomes a committed product requirement. + +## Interrupted settings imports + +The WPF importer and native settings reader share `settings.toml.lock` and the +SQLite `settings_import_recovery` protocol. Before replacing settings, the UI +durably stores original and imported TOML bytes with `committed = 0`. The product +replacement transaction sets `committed = 1` atomically with its rule changes. +Settings loads reconcile a surviving record: zero restores the original bytes, +one finishes the imported bytes. They flush and atomically replace the file +before clearing the record using SQLite synchronous FULL. This operation is +idempotent across another interruption. Existing databases without the recovery +table retain their normal behavior; engine migration versions are unchanged. + +Correction policy guards refuse any surviving recovery record, including during +an active import. Settings reads/writes share the Windows lock, whose ownership +ends with the process. IPC edits start from the latest settings under that lock. +Failed reloads are retried rather than marking the new timestamp as loaded. +The recovery table and temporary backups are excluded from config bundles. diff --git a/app-core-rust/src/background/mod.rs b/app-core-rust/src/background/mod.rs index 48b1dd2..5de9fec 100644 --- a/app-core-rust/src/background/mod.rs +++ b/app-core-rust/src/background/mod.rs @@ -32,10 +32,7 @@ use std::{ time::{Duration, SystemTime}, }; -use crate::{ - settings::{save_config, AppConfig}, - storage::Database, -}; +use crate::{settings::AppConfig, storage::Database}; use self::{ admin::reject_elevated_process, @@ -193,10 +190,17 @@ impl BackgroundRuntime { ensure_parent_directory(paths.config_path())?; ensure_parent_directory(paths.database_path())?; + let config_modified_at = modified_at(paths.config_path()); let config = load_or_create_config(paths.config_path())?; let database = Database::open(paths.database_path()).map_err(BackgroundError::Database)?; let shutdown_requested = Arc::new(AtomicBool::new(false)); - let components = RuntimeComponents::start(&config, &paths, shutdown_requested, database)?; + let components = RuntimeComponents::start( + &config, + config_modified_at, + &paths, + shutdown_requested, + database, + )?; tracing::info!("AutoFix background process started"); Ok(Self { components }) @@ -219,6 +223,7 @@ impl BackgroundRuntime { impl RuntimeComponents { fn start( config: &AppConfig, + config_modified_at: Option, paths: &RuntimePaths, shutdown_requested: Arc, database: Database, @@ -229,7 +234,7 @@ impl RuntimeComponents { let input_worker = InputWorker::start(config.clone(), database)?; Ok(Self { config_path: paths.config_path().to_path_buf(), - config_modified_at: modified_at(paths.config_path()), + config_modified_at, config: config.clone(), ipc_server: NamedPipeIpcServer::initialize( config, @@ -284,14 +289,10 @@ impl RuntimeComponents { } fn reload_shortcuts_if_config_changed(&mut self) { - let modified_at = modified_at(&self.config_path); - if modified_at == self.config_modified_at { - return; - } - - self.config_modified_at = modified_at; - match crate::settings::load_config(&self.config_path) { - Ok(config) => { + match load_changed_config(&self.config_path, &mut self.config_modified_at, |path| { + crate::settings::load_config(path) + }) { + Ok(Some(config)) => { if shortcuts::detect_conflict(&config) { tracing::warn!("shortcut conflict detected while reloading config"); } @@ -299,6 +300,7 @@ impl RuntimeComponents { self.global_shortcut.reload(&config); self.input_worker.send(InputWork::Config(Box::new(config))); } + Ok(None) => {} Err(error) => tracing::warn!("failed to reload shortcuts from config: {}", error), } } @@ -1266,12 +1268,22 @@ fn ensure_parent_directory(path: &Path) -> Result<(), BackgroundError> { fn load_or_create_config(path: &Path) -> Result { ensure_parent_directory(path)?; + crate::settings::load_or_create_config(path).map_err(BackgroundError::Config) +} - if !path.exists() { - save_config(path, &AppConfig::default()).map_err(BackgroundError::Config)?; +/// Cache the pre-load timestamp so writes during loading remain visible on the next tick. +fn load_changed_config( + path: &Path, + last_modified_at: &mut Option, + load: impl FnOnce(&Path) -> Result, +) -> Result, crate::settings::ConfigIoError> { + let current_modified_at = modified_at(path); + if current_modified_at == *last_modified_at { + return Ok(None); } - - crate::settings::load_config(path).map_err(BackgroundError::Config) + let config = load(path)?; + *last_modified_at = current_modified_at; + Ok(Some(config)) } fn modified_at(path: &Path) -> Option { diff --git a/app-core-rust/src/background/security/outbound.rs b/app-core-rust/src/background/security/outbound.rs index 647c65a..7792f3c 100644 --- a/app-core-rust/src/background/security/outbound.rs +++ b/app-core-rust/src/background/security/outbound.rs @@ -211,6 +211,53 @@ mod tests { assert!(authorize().is_none()); } + /// Pending import recovery denies existing outbound authorizations and replacement reservations for every trigger. + #[test] + fn pending_import_blocks_sends_and_replacements() { + for trigger in [ + TriggerKind::ManualShortcut, + TriggerKind::WordCount, + TriggerKind::Character, + TriggerKind::FinalFixBeforeReanchor, + ] { + let fixture = Fixture::new(); + fixture.database.app_rules().upsert(&allow_rule()).unwrap(); + let authorize = fixture.authorize(trigger, Arc::new(AtomicBool::new(false))); + assert!(authorize().is_some()); + let connection = rusqlite::Connection::open(&fixture.path).unwrap(); + connection + .execute_batch( + "create table settings_import_recovery (id integer primary key); + insert into settings_import_recovery values (1)", + ) + .unwrap(); + assert!(authorize().is_none()); + let mut request = triggers::manual( + 1, + "", + "This is teh sentence.", + ContextVersions::default(), + &SelectionCapture::NoSelection, + &AppConfig::default(), + ) + .unwrap(); + request.trigger = trigger; + assert!( + super::super::SecurityGate::authorize_correction_replacement( + &request, + &AppConfig::default(), + &fixture.database, + &target() + ) + .is_none() + ); + connection + .execute("delete from settings_import_recovery", []) + .unwrap(); + assert!(authorize().is_some()); + } + } + /// Permission is read at every send, including changes to trigger and title rules. #[test] fn revocation_blocks_existing_authorizations_for_every_correction_trigger() { diff --git a/app-core-rust/src/background/tests.rs b/app-core-rust/src/background/tests.rs index 851aae7..d005312 100644 --- a/app-core-rust/src/background/tests.rs +++ b/app-core-rust/src/background/tests.rs @@ -495,6 +495,82 @@ fn slow_input_worker_discards_stale_batches_at_queue_limit() { worker.shutdown(); } +#[test] +fn config_write_during_reload_is_loaded_on_the_next_tick() { + let root = unique_temp_dir(); + let path = root.join("settings.toml"); + load_or_create_config(&path).unwrap(); + let before = UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000); + let after = before + std::time::Duration::from_secs(10); + let set_modified = |time| { + fs::File::options() + .write(true) + .open(&path) + .unwrap() + .set_times(fs::FileTimes::new().set_modified(time)) + .unwrap(); + }; + set_modified(before); + let mut last_modified_at = None; + let mut newer = AppConfig::default(); + newer.triggers.word_count = 20; + + let loaded = super::load_changed_config(&path, &mut last_modified_at, |path| { + let config = crate::settings::load_config(path)?; + crate::settings::save_config(path, &newer)?; + set_modified(after); + Ok(config) + }) + .unwrap() + .unwrap(); + assert_eq!(loaded.triggers.word_count, 10); + assert_eq!(last_modified_at, Some(before)); + + let loaded = super::load_changed_config(&path, &mut last_modified_at, |path| { + crate::settings::load_config(path) + }) + .unwrap() + .unwrap(); + assert_eq!(loaded, newer); + assert_eq!(last_modified_at, Some(after)); + assert!( + super::load_changed_config(&path, &mut last_modified_at, |_| { + panic!("unchanged config must not be loaded") + }) + .unwrap() + .is_none() + ); + fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn failed_config_reload_is_retried_without_another_write() { + let root = unique_temp_dir(); + let path = root.join("settings.toml"); + load_or_create_config(&path).unwrap(); + let mut last_modified_at = None; + + assert!( + super::load_changed_config(&path, &mut last_modified_at, |path| { + Err(crate::settings::ConfigIoError::Read { + path: path.into(), + source: std::io::Error::other("transient load failure"), + }) + }) + .is_err() + ); + assert_eq!(last_modified_at, None); + assert!( + super::load_changed_config(&path, &mut last_modified_at, |path| { + crate::settings::load_config(path) + }) + .unwrap() + .is_some() + ); + assert_eq!(last_modified_at, super::modified_at(&path)); + fs::remove_dir_all(root).unwrap(); +} + #[test] fn creates_default_config_when_missing() { let root = unique_temp_dir(); @@ -526,7 +602,14 @@ fn background_runtime_respects_elevation_and_initializes_files() { assert!(!root.exists()); } Ok(()) => { - let runtime = result.unwrap(); + let mut runtime = result.unwrap(); + // Startup must retain the timestamp from before default-file creation. + assert_eq!(runtime.components.config_modified_at, None); + runtime.components.reload_shortcuts_if_config_changed(); + assert_eq!( + runtime.components.config_modified_at, + super::modified_at(&config_path) + ); #[cfg(windows)] assert_ne!(runtime.components.input_listener.hook_thread_id(), unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() diff --git a/app-core-rust/src/ipc/state.rs b/app-core-rust/src/ipc/state.rs index fd7f481..313b655 100644 --- a/app-core-rust/src/ipc/state.rs +++ b/app-core-rust/src/ipc/state.rs @@ -1,7 +1,7 @@ use std::{path::PathBuf, sync::Arc}; use crate::{ - settings::{save_config, AppConfig, CorrectionEngine, CorrectionMode, ValidateConfig}, + settings::{edit_config, AppConfig, CorrectionEngine, CorrectionMode}, storage::{AppRule, Database}, }; @@ -158,13 +158,10 @@ impl IpcServerState { } fn update_setting(&mut self, path: String, value: serde_json::Value) -> IpcResponse { - let mut next = self.config.clone(); - let result = apply_setting(&mut next, &path, value) - .and_then(|_| next.validate().map_err(|error| error.to_string())) - .and_then(|_| save_config(&self.config_path, &next).map_err(|error| error.to_string())); + let result = edit_config(&self.config_path, |next| apply_setting(next, &path, value)); match result { - Ok(()) => { + Ok(next) => { self.config = next; IpcResponse::SettingUpdated(SettingUpdatedResponse { path }) } diff --git a/app-core-rust/src/ipc/tests.rs b/app-core-rust/src/ipc/tests.rs index b601044..aa74665 100644 --- a/app-core-rust/src/ipc/tests.rs +++ b/app-core-rust/src/ipc/tests.rs @@ -327,6 +327,27 @@ fn updates_any_valid_config_setting_by_path() { assert_eq!(config.shortcuts.correct, "Ctrl+Shift+Space"); } +/// An IPC edit cannot replace a freshly imported setting with the server's earlier cached config. +#[test] +fn ipc_edits_preserve_external_imported_settings() { + let fixture = IpcFixture::start(); + let mut config = AppConfig::default(); + config.triggers.word_count = 22; + save_config(&fixture.config_path, &config).unwrap(); + let response = send_request( + &fixture.pipe_path, + &IpcRequest::UpdateSetting(UpdateSettingRequest { + path: "shortcuts.correct".into(), + value: json!("Ctrl+Shift+Space"), + }), + ) + .unwrap(); + assert!(matches!(response, IpcResponse::SettingUpdated(_))); + let saved = crate::settings::load_config(&fixture.config_path).unwrap(); + assert_eq!(saved.triggers.word_count, 22); + assert_eq!(saved.shortcuts.correct, "Ctrl+Shift+Space"); +} + #[test] fn reads_update_setting_requests_larger_than_initial_buffer() { let fixture = IpcFixture::start(); diff --git a/app-core-rust/src/settings/import_recovery.rs b/app-core-rust/src/settings/import_recovery.rs new file mode 100644 index 0000000..3ae0a8f --- /dev/null +++ b/app-core-rust/src/settings/import_recovery.rs @@ -0,0 +1,126 @@ +//! Shared Windows settings lock and SQLite-backed interrupted-import reconciliation. + +use std::{ + fs::{File, OpenOptions}, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +use rusqlite::{Connection, OpenFlags, OptionalExtension, TransactionBehavior}; +#[cfg(not(windows))] +use std::fs; + +/// Opens the same non-shared lock file as WPF. A process exit releases ownership automatically. +pub(super) fn acquire(path: &Path) -> io::Result { + let mut options = OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.share_mode(0); + } + options.open(suffixed(path, ".lock")) +} + +fn suffixed(path: &Path, suffix: &str) -> PathBuf { + let mut name = path.as_os_str().to_os_string(); + name.push(suffix); + name.into() +} + +/// Flushes content and atomically replaces the Windows file before the journal can be cleared. +pub(super) fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { + let temporary = suffixed(path, ".native-save.tmp"); + let mut file = File::create(&temporary)?; + file.write_all(bytes)?; + file.sync_all()?; + drop(file); + #[cfg(windows)] + { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::Storage::FileSystem::{ + MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, + }; + let source: Vec = temporary.as_os_str().encode_wide().chain(Some(0)).collect(); + let destination: Vec = path.as_os_str().encode_wide().chain(Some(0)).collect(); + // Both names are nul-terminated; neither pointer outlives its backing vector. + if unsafe { + MoveFileExW( + source.as_ptr(), + destination.as_ptr(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + } + #[cfg(not(windows))] + { + fs::rename(&temporary, path)?; + File::open(path.parent().unwrap_or(Path::new(".")))?.sync_all()?; + } + Ok(()) +} + +/// Must run with the settings lock held. Failed recovery retains the durable decision and denies policy use. +pub(super) fn recover(path: &Path) -> io::Result { + let database = path + .parent() + .unwrap_or(Path::new(".")) + .join("autofix.sqlite"); + if !database.exists() { + return Ok(false); + } + let mut connection = Connection::open_with_flags(database, OpenFlags::SQLITE_OPEN_READ_WRITE) + .map_err(io::Error::other)?; + connection + .busy_timeout(std::time::Duration::ZERO) + .map_err(io::Error::other)?; + if !pending(&connection).map_err(io::Error::other)? { + return Ok(false); + } + connection + .pragma_update(None, "synchronous", "FULL") + .map_err(io::Error::other)?; + let transaction = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .map_err(io::Error::other)?; + let bytes: Option> = transaction + .query_row( + "select case committed when 0 then original_settings when 1 then imported_settings end + from settings_import_recovery where id = 1", + [], + |row| row.get(0), + ) + .optional() + .map_err(io::Error::other)?; + let Some(bytes) = bytes else { + return Ok(false); + }; + write_atomic(path, &bytes)?; + transaction + .execute("delete from settings_import_recovery where id = 1", []) + .map_err(io::Error::other)?; + transaction.commit().map_err(io::Error::other)?; + Ok(true) +} + +/// Read-only admission check; missing legacy tables are allowed, unreadable recovery state is denied. +pub(crate) fn pending(connection: &Connection) -> rusqlite::Result { + let table: bool = connection.query_row( + "select exists(select 1 from sqlite_master where type = 'table' and name = 'settings_import_recovery')", + [], |row| row.get(0), + )?; + if !table { + return Ok(false); + } + connection.query_row( + "select exists(select 1 from settings_import_recovery)", + [], + |row| row.get(0), + ) +} + +#[cfg(test)] +mod tests; diff --git a/app-core-rust/src/settings/import_recovery/tests.rs b/app-core-rust/src/settings/import_recovery/tests.rs new file mode 100644 index 0000000..820d06e --- /dev/null +++ b/app-core-rust/src/settings/import_recovery/tests.rs @@ -0,0 +1,136 @@ +use super::*; +use crate::{ + settings::{load_config, save_config, AppConfig}, + storage::AppPolicyGuard, +}; +use rusqlite::Connection; +use std::{fs, time::SystemTime}; + +fn fixture(committed: bool) -> (PathBuf, Connection, Vec, Vec) { + let root = std::env::temp_dir().join(format!( + "autofix-import-recovery-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&root).unwrap(); + let path = root.join("settings.toml"); + let mut config = AppConfig::default(); + let original = crate::settings::toml_io::config_to_toml(&config) + .unwrap() + .into_bytes(); + config.triggers.word_count = 22; + let imported = crate::settings::toml_io::config_to_toml(&config) + .unwrap() + .into_bytes(); + let database = Connection::open(root.join("autofix.sqlite")).unwrap(); + database + .execute_batch( + "create table settings_import_recovery ( + id integer primary key check(id = 1), original_settings blob not null, + imported_settings blob not null, committed integer not null check(committed in (0,1)))", + ) + .unwrap(); + database + .execute( + "insert into settings_import_recovery values (1, ?1, ?2, ?3)", + rusqlite::params![original, imported, committed], + ) + .unwrap(); + (path, database, original, imported) +} + +/// Native startup reads the same durable decision as WPF, restoring even a missing or corrupted file. +#[test] +fn native_reads_reconcile_both_import_decisions_before_loading() { + for committed in [false, true] { + let (path, database, original, imported) = fixture(committed); + fs::write(&path, "partially persisted file").unwrap(); + assert_eq!( + load_config(&path).unwrap().triggers.word_count, + if committed { 22 } else { 10 } + ); + assert_eq!( + fs::read(&path).unwrap(), + if committed { imported } else { original } + ); + assert!(!pending(&database).unwrap()); + assert!(!recover(&path).unwrap()); + drop(database); + fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } +} + +/// First-start initialization repairs a committed import when its settings file did not survive shutdown. +#[test] +fn startup_recovery_precedes_default_creation() { + let (path, database, _, imported) = fixture(true); + assert!(!path.exists()); + assert_eq!( + crate::settings::load_or_create_config(&path) + .unwrap() + .triggers + .word_count, + 22 + ); + assert_eq!(fs::read(&path).unwrap(), imported); + assert!(!pending(&database).unwrap()); + drop(database); + fs::remove_dir_all(path.parent().unwrap()).unwrap(); +} + +/// Both outbound admission and replacement reservation fail closed while any import record survives. +#[test] +fn correction_policy_is_denied_until_import_recovery() { + for committed in [false, true] { + let (path, database, _, _) = fixture(committed); + let database_path = path.parent().unwrap().join("autofix.sqlite"); + assert!(AppPolicyGuard::read_rules_nowait(&database_path).is_err()); + assert!(AppPolicyGuard::acquire(&database_path).is_err()); + recover(&path).unwrap(); + assert!(AppPolicyGuard::acquire(&database_path).is_ok()); + drop(database); + fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } +} + +/// IPC edits first recover the committed import and preserve its unrelated settings. +#[test] +fn fresh_edits_preserve_recovered_imported_values() { + let (path, database, _, _) = fixture(true); + let edited = crate::settings::edit_config(&path, |config| { + config.general.start_with_windows = true; + Ok(()) + }) + .unwrap(); + assert_eq!(edited.triggers.word_count, 22); + assert!(edited.general.start_with_windows); + drop(database); + fs::remove_dir_all(path.parent().unwrap()).unwrap(); +} + +/// A conflicting Windows handle prevents reconciliation without deleting the only durable recovery record. +#[cfg(windows)] +#[test] +fn failed_recovery_and_contended_lock_preserve_the_decision() { + use std::os::windows::fs::OpenOptionsExt; + let (path, database, _, _) = fixture(false); + fs::write(&path, "imported").unwrap(); + let locked = OpenOptions::new() + .read(true) + .share_mode(1) + .open(&path) + .unwrap(); + assert!(load_config(&path).is_err()); + assert!(pending(&database).unwrap()); + drop(locked); + let access = acquire(&path).unwrap(); + assert!(load_config(&path).is_err()); + assert!(save_config(&path, &AppConfig::default()).is_err()); + drop(access); + assert_eq!(load_config(&path).unwrap().triggers.word_count, 10); + drop(database); + fs::remove_dir_all(path.parent().unwrap()).unwrap(); +} diff --git a/app-core-rust/src/settings/mod.rs b/app-core-rust/src/settings/mod.rs index ec41343..8676d68 100644 --- a/app-core-rust/src/settings/mod.rs +++ b/app-core-rust/src/settings/mod.rs @@ -1,3 +1,4 @@ +pub(crate) mod import_recovery; mod model; mod shortcuts; #[cfg(test)] @@ -11,5 +12,7 @@ pub(crate) use model::{ LearningRule, PendingQueueFullBehavior, RunMode, }; pub(crate) use shortcuts::{Shortcut, ShortcutKey}; -pub(crate) use toml_io::{load_config, save_config, ConfigIoError}; +#[cfg(test)] +pub(crate) use tests::save_config; +pub(crate) use toml_io::{edit_config, load_config, load_or_create_config, ConfigIoError}; pub(crate) use validation::ValidateConfig; diff --git a/app-core-rust/src/settings/tests.rs b/app-core-rust/src/settings/tests.rs index 0fe7114..ece470f 100644 --- a/app-core-rust/src/settings/tests.rs +++ b/app-core-rust/src/settings/tests.rs @@ -5,11 +5,31 @@ use crate::correction::{ConfidenceBehavior, CorrectionMode, GrammarCategory}; use super::{ load_config, model::{CorrectionEngine, RunMode}, - save_config, toml_io::config_to_toml, AppConfig, ValidateConfig, }; +/// Persists fixture configurations through the same initialization and edit path used by the native runtime. +pub(crate) fn save_config( + path: impl AsRef, + config: &AppConfig, +) -> Result<(), super::ConfigIoError> { + let path = path.as_ref(); + config + .validate() + .map_err(super::ConfigIoError::Validation)?; + super::load_or_create_config(path)?; + super::edit_config(path, |current| { + *current = config.clone(); + Ok(()) + }) + .map(|_| ()) + .map_err(|error| super::ConfigIoError::Write { + path: path.into(), + source: std::io::Error::other(error), + }) +} + /// Undo capacity round-trips through TOML and defaults to ten for legacy files. #[test] fn undo_capacity_round_trips_and_legacy_settings_keep_ten_entries() { diff --git a/app-core-rust/src/settings/toml_io.rs b/app-core-rust/src/settings/toml_io.rs index f3f149b..4cc665d 100644 --- a/app-core-rust/src/settings/toml_io.rs +++ b/app-core-rust/src/settings/toml_io.rs @@ -4,6 +4,7 @@ use std::{ path::{Path, PathBuf}, }; +use super::import_recovery; use super::{validation::ConfigValidationError, AppConfig, ValidateConfig}; #[derive(Debug)] @@ -44,7 +45,8 @@ impl Error for ConfigIoError { /// Normalize previously supported retry counts on read; writes remain strict. pub(crate) fn parse_config(input: &str) -> Result { - let mut config = toml::from_str::(input).map_err(ConfigIoError::Parse)?; + let mut config = toml::from_str::(input.trim_start_matches('\u{feff}')) + .map_err(ConfigIoError::Parse)?; if config.api.retry_count > 1 { tracing::warn!( retry_count = config.api.retry_count, @@ -64,6 +66,14 @@ pub(crate) fn config_to_toml(config: &AppConfig) -> Result) -> Result { let path = path.as_ref(); + let _access = import_recovery::acquire(path).map_err(|source| ConfigIoError::Read { + path: path.into(), + source, + })?; + import_recovery::recover(path).map_err(|source| ConfigIoError::Read { + path: path.into(), + source, + })?; let input = fs::read_to_string(path).map_err(|source| ConfigIoError::Read { path: path.to_path_buf(), source, @@ -72,13 +82,49 @@ pub(crate) fn load_config(path: impl AsRef) -> Result, config: &AppConfig) -> Result<(), ConfigIoError> { - let path = path.as_ref(); - let output = config_to_toml(config)?; - fs::write(path, output).map_err(|source| ConfigIoError::Write { - path: path.to_path_buf(), +/// Initializes missing settings only after recovery, holding the lock between read and creation. +pub(crate) fn load_or_create_config(path: &Path) -> Result { + let _access = import_recovery::acquire(path).map_err(|source| ConfigIoError::Read { + path: path.into(), + source, + })?; + import_recovery::recover(path).map_err(|source| ConfigIoError::Read { + path: path.into(), source, - }) + })?; + match fs::read_to_string(path) { + Ok(input) => parse_config(&input), + Err(source) if source.kind() == io::ErrorKind::NotFound => { + let config = AppConfig::default(); + let output = config_to_toml(&config)?; + import_recovery::write_atomic(path, output.as_bytes()).map_err(|source| { + ConfigIoError::Write { + path: path.into(), + source, + } + })?; + Ok(config) + } + Err(source) => Err(ConfigIoError::Read { + path: path.into(), + source, + }), + } +} + +/// IPC edits start from the latest recovered config and hold the import lock through the durable write. +pub(crate) fn edit_config( + path: &Path, + edit: impl FnOnce(&mut AppConfig) -> Result<(), String>, +) -> Result { + let _access = import_recovery::acquire(path).map_err(|error| error.to_string())?; + import_recovery::recover(path).map_err(|error| error.to_string())?; + let input = fs::read_to_string(path).map_err(|error| error.to_string())?; + let mut config = parse_config(&input).map_err(|error| error.to_string())?; + edit(&mut config)?; + let output = config_to_toml(&config).map_err(|error| error.to_string())?; + import_recovery::write_atomic(path, output.as_bytes()).map_err(|error| error.to_string())?; + Ok(config) } /// Describe configuration boundaries and queue defaults without serializing credentials. diff --git a/app-core-rust/src/storage/app_policy.rs b/app-core-rust/src/storage/app_policy.rs index 84d89e3..13a674a 100644 --- a/app-core-rust/src/storage/app_policy.rs +++ b/app-core-rust/src/storage/app_policy.rs @@ -16,6 +16,7 @@ impl AppPolicyGuard { pub(crate) fn read_rules_nowait(path: &Path) -> Result> { let connection = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)?; connection.busy_timeout(Duration::ZERO)?; + reject_pending_import(&connection)?; AppRuleRepository::new(&connection).list() } @@ -25,6 +26,7 @@ impl AppPolicyGuard { // Contention denies the operation immediately; never wait on policy writers. connection.busy_timeout(Duration::ZERO)?; connection.execute_batch("BEGIN IMMEDIATE")?; + reject_pending_import(&connection)?; Ok(Self { connection }) } @@ -34,6 +36,14 @@ impl AppPolicyGuard { } } +/// A surviving import decision prevents outbound requests and replacement until settings reconciliation. +fn reject_pending_import(connection: &Connection) -> Result<()> { + if crate::settings::import_recovery::pending(connection)? { + return Err(rusqlite::Error::InvalidQuery); + } + Ok(()) +} + impl Drop for AppPolicyGuard { /// Closing the connection rolls back the read-only transaction and releases writers. fn drop(&mut self) { diff --git a/shared-schema/README.md b/shared-schema/README.md index a80f888..78765a6 100644 --- a/shared-schema/README.md +++ b/shared-schema/README.md @@ -10,6 +10,9 @@ This component owns stable contracts between: Keep schemas explicit, versioned, and documented. Avoid storing executable runtime state here; this area is for contracts, structured settings, and compatibility notes. +The [settings import recovery protocol](import-recovery.md) defines the durable +SQLite decision and Windows settings lock shared by WPF and the native engine. + `[learning]` is optional in TOML. `mode` accepts `off` (default), `ask`, or `automatic`; `rule` accepts `pair` (default) or `dictionary`; `per_app` defaults to false. Rust and WPF use the same defaults and reject unknown choices. diff --git a/shared-schema/import-recovery.md b/shared-schema/import-recovery.md new file mode 100644 index 0000000..7a94504 --- /dev/null +++ b/shared-schema/import-recovery.md @@ -0,0 +1,43 @@ +# Settings import recovery protocol + +WPF and the Rust settings feature coordinate using a non-shared Windows handle +to `settings.toml.lock` in the product directory. Every live settings read and +write owns this handle. A terminated process releases it automatically. The +engine denies correction admission, outbound API sends and replacement whenever +`settings_import_recovery` in `autofix.sqlite` contains any record. Missing legacy +tables are allowed; unreadable recovery state denies correction. + +The UI initializes this recovery table without changing engine migration versions: + +```sql +create table settings_import_recovery ( + id integer primary key check (id = 1), + original_settings blob not null, + imported_settings blob not null, + committed integer not null check (committed in (0, 1)) +); +``` + +An import first validates the preview against settings and participating product +rows under the settings lock and a SQLite write transaction. That transaction +durably inserts the two exact TOML byte snapshots and `committed = 0` using +SQLite synchronous FULL. Only after that commit may the settings file change. +The second transaction rechecks participating product data, replaces those rows, +and sets `committed = 1`. The flushed temporary TOML replaces the live file using +Windows `MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH)` before this second commit. + +After interruption, settings access takes the same lock and a SQLite writer +reservation. A zero record restores original bytes; a one record restores imported +bytes. The chosen bytes are flushed and atomically replace the live file before +the journal record is deleted and that deletion commits with synchronous FULL. +A missing settings file is restored rather than replaced with defaults. Another +interruption repeats the same decision, so recovery is idempotent. Any failure +leaves the journal intact, keeps correction blocked and reports the underlying +error. The engine retries config reload failures instead of consuming the file's +new modification timestamp. Stale saves which trigger recovery require a reload; +IPC setting edits read and update the latest recovered configuration under the lock. + +The journal is strictly local recovery storage. It is excluded from bundles, +along with lock files, temporary settings files and retained error backups. +Durability depends on the filesystem and device honoring Windows and SQLite +flush requests; physical storage corruption is not recoverable by this protocol. diff --git a/ui/settings-ui-tests/AppRuleStorageTests.cs b/ui/settings-ui-tests/AppRuleStorageTests.cs index 681f5ac..4ba1bfc 100644 --- a/ui/settings-ui-tests/AppRuleStorageTests.cs +++ b/ui/settings-ui-tests/AppRuleStorageTests.cs @@ -8,6 +8,20 @@ namespace AutoFix.SettingsUi.Tests; [TestClass] public sealed class AppRuleStorageTests { + [TestMethod] + public void FirstOfflineLoadSeedsDefaultsOnlyOnceAndPreservesDeletedRules() + { + using var fixture = TempConfigFixture.Create(); + var storage = new AppRuleStorage(Path.Combine(fixture.Root, "autofix.sqlite")); + var rules = storage.List(); + Assert.IsTrue(rules.Any(r => r.SafetyMode == "terminal" && !r.ManualShortcutAllowed)); + Assert.IsTrue(rules.Any(r => r.SafetyMode == "code_editor" && !r.WordCountTriggerAllowed && !r.ProseContextAllowed)); + Assert.IsTrue(rules.Any(r => r.ProcessName == "Bitwarden.exe" && !r.LocalEngineAllowed && !r.ApiEngineAllowed)); + Assert.IsTrue(storage.Delete("code.exe", null)); + Assert.IsFalse(storage.List().Any(r => r.ProcessName == "code.exe")); + Assert.IsTrue(storage.ResetDefaults().Any(r => r.ProcessName == "code.exe")); + } + [DataTestMethod] [DataRow("", "auto", false)] [DataRow(",\"safety_mode\":null", "auto", false)] @@ -27,7 +41,7 @@ public void IpcSafetyFieldsRoundTripThroughStorage(string safetyFields, string e using var fixture = TempConfigFixture.Create(); var storage = new AppRuleStorage(Path.Combine(fixture.Root, "autofix.sqlite")); storage.Upsert(rule); - var saved = storage.List().Single(); + var saved = storage.List().Single(item => item.ProcessName == rule.ProcessName); Assert.AreEqual(expectedMode, saved.SafetyMode); Assert.AreEqual(expectedProse, saved.ProseContextAllowed); Assert.IsTrue(saved.ManualShortcutAllowed); @@ -72,8 +86,8 @@ public void UpsertListAndDeleteRoundTrip() var listed = storage.List(); Assert.IsTrue(listed.Any(item => item.ProcessName == "word.exe" && item.WindowTitlePattern == "*admin*")); - Assert.AreEqual("code_editor", listed[0].SafetyMode); - Assert.IsTrue(listed[0].ProseContextAllowed); + Assert.AreEqual("code_editor", listed.Single(item => item.ProcessName == "word.exe").SafetyMode); + Assert.IsTrue(listed.Single(item => item.ProcessName == "word.exe").ProseContextAllowed); Assert.IsTrue(storage.Delete("word.exe", "*admin*")); } diff --git a/ui/settings-ui-tests/AutoFix.SettingsUi.Tests.csproj b/ui/settings-ui-tests/AutoFix.SettingsUi.Tests.csproj index 9d96ced..7936e3f 100644 --- a/ui/settings-ui-tests/AutoFix.SettingsUi.Tests.csproj +++ b/ui/settings-ui-tests/AutoFix.SettingsUi.Tests.csproj @@ -8,6 +8,8 @@ false true + Exe + AutoFix.SettingsUi.Tests.ImportCrashHost diff --git a/ui/settings-ui-tests/ConfigFormMapperTests.cs b/ui/settings-ui-tests/ConfigFormMapperTests.cs index ae099fb..5729ef2 100644 --- a/ui/settings-ui-tests/ConfigFormMapperTests.cs +++ b/ui/settings-ui-tests/ConfigFormMapperTests.cs @@ -215,7 +215,7 @@ public void BuildConfigRejectsDuplicatePaths() public void BuildConfigRejectsMissingRequiredPath() { var sections = SettingsSkeleton.CreateSections(); - sections[0].Settings.Remove(Card(sections, "general.run_mode")); + sections.Single(section => section.Name == "App Rules").Settings.Remove(Card(sections, "general.run_mode")); var error = Assert.ThrowsException(() => ConfigFormMapper.BuildConfig(sections)); diff --git a/ui/settings-ui-tests/ConfigStorageTests.cs b/ui/settings-ui-tests/ConfigStorageTests.cs index 5e2cfd6..364cd62 100644 --- a/ui/settings-ui-tests/ConfigStorageTests.cs +++ b/ui/settings-ui-tests/ConfigStorageTests.cs @@ -5,6 +5,25 @@ namespace AutoFix.SettingsUi.Tests; [TestClass] public sealed class ConfigStorageTests { + /// Snapshot config and retained bytes agree, including BOM and legacy normalization, after the live file changes. + [TestMethod] + public void SnapshotRetainsTheBytesUsedToParseAndCreatesMissingDefaults() + { + using var fixture = TempConfigFixture.Create(); + var defaults = fixture.Storage.LoadSnapshot(); + Assert.IsTrue(fixture.Storage.LastLoadCreatedConfig); + CollectionAssert.AreEqual(File.ReadAllBytes(fixture.Path), defaults.Bytes); + File.WriteAllText(fixture.Path, "[api]\nretry_count = 255\n[triggers]\nword_count = 18\n", new System.Text.UTF8Encoding(true)); + var snapshot = fixture.Storage.LoadSnapshot(); + Assert.IsFalse(fixture.Storage.LastLoadCreatedConfig); + CollectionAssert.AreEqual(File.ReadAllBytes(fixture.Path), snapshot.Bytes); + fixture.Storage.Save(AppConfig.Default()); + using var reader = new StreamReader(new MemoryStream(snapshot.Bytes)); + StringAssert.Contains(reader.ReadToEnd(), "word_count = 18"); + Assert.AreEqual(18, snapshot.Config.Triggers.WordCount); + Assert.AreEqual(1, snapshot.Config.Api.RetryCount); + } + /// Old retry counts load and import safely without relaxing save validation. [TestMethod] public void LegacyApiRetryCountsAreMigratedOnLoadAndImport() diff --git a/ui/settings-ui-tests/ConfigTransferStorageTests.cs b/ui/settings-ui-tests/ConfigTransferStorageTests.cs new file mode 100644 index 0000000..752118c --- /dev/null +++ b/ui/settings-ui-tests/ConfigTransferStorageTests.cs @@ -0,0 +1,432 @@ +using System.IO.Compression; +using System.Text.Json; +using AutoFix.SettingsUi.Settings; +using AutoFix.SettingsUi.Settings.Transfer; +using Microsoft.Data.Sqlite; + +namespace AutoFix.SettingsUi.Tests; + +[TestClass] +public sealed class ConfigTransferStorageTests +{ + /// A missing live config gets default settings and a matching preview fingerprint. + [TestMethod] + public void PreviewCreatesMissingSettingsAndHashesTheDisplayedSnapshot() + { + using var fixture = TempConfigFixture.Create(); + var transfer = CreateTransfer(fixture); + var path = Path.Combine(fixture.Root, "bundle.zip"); + Execute(fixture, "delete from app_rules"); + transfer.Export(path, AppConfig.Default(), true); + File.Delete(fixture.Path); + var preview = transfer.Preview(path); + Assert.IsTrue(fixture.Storage.LastLoadCreatedConfig); + Assert.IsFalse(preview.HasChanges); + Assert.AreEqual(ConfigTransferStorage.Fingerprint(File.ReadAllBytes(fixture.Path), preview.Bundle.Data!), preview.Fingerprint); + transfer.Apply(preview); + } + + /// Commit failures restore exact settings bytes and roll back all product rows. + [TestMethod] + public void CommitFailureRestoresOriginalSettingsAndPreservesThePrimaryError() + { + using var fixture = TempConfigFixture.Create(); + var transfer = CreateTransfer(fixture); + var config = AppConfig.Default(); config.Triggers.WordCount = 22; + var path = Path.Combine(fixture.Root, "bundle.zip"); transfer.Export(path, config, true); + new DictionaryStorage(Database(fixture)).Save(new() { Word = "keep-word", Language = "und", Source = "dictionary" }); + var preview = transfer.Preview(path); + var before = File.ReadAllBytes(fixture.Path); + var primary = new SqliteException("commit failed", 19); + var error = Assert.ThrowsException(() => transfer.Apply(preview, _ => throw primary)); + Assert.AreSame(primary, error); + CollectionAssert.AreEqual(before, File.ReadAllBytes(fixture.Path)); + Assert.AreEqual("keep-word", Scalar(fixture, "select entry from custom_dictionary_entries")); + Assert.AreEqual(0, Directory.GetFiles(fixture.Root, ".autofix-import-*").Length); + } + + /// Failed restoration retains an exact backup and reports it without replacing the commit exception. + [TestMethod] + public void RestoreFailureKeepsBackupAndReportsBothErrors() + { + using var fixture = TempConfigFixture.Create(); + var transfer = CreateTransfer(fixture); + var config = AppConfig.Default(); config.Triggers.WordCount = 22; + var path = Path.Combine(fixture.Root, "bundle.zip"); transfer.Export(path, config, true); + new DictionaryStorage(Database(fixture)).Save(new() { Word = "keep-word", Language = "und", Source = "dictionary" }); + var preview = transfer.Preview(path); + var before = File.ReadAllBytes(fixture.Path); + var primary = new SqliteException("commit failed", 19); + FileStream? locked = null; + try + { + var error = Assert.ThrowsException(() => transfer.Apply(preview, _ => + { + locked = new FileStream(fixture.Path, FileMode.Open, FileAccess.Read, FileShare.Read); + throw primary; + })); + Assert.AreSame(primary, error); + Assert.IsInstanceOfType(error.Data["SettingsRestoreError"], typeof(IOException)); + var backup = (string)error.Data["SettingsBackupPath"]!; + CollectionAssert.AreEqual(before, File.ReadAllBytes(backup)); + Assert.AreEqual(22, ConfigStorage.Parse(File.ReadAllText(fixture.Path)).Triggers.WordCount); + Assert.AreEqual(1L, Scalar(fixture, "select count(*) from settings_import_recovery")); + Assert.AreEqual("keep-word", Scalar(fixture, "select entry from custom_dictionary_entries")); + StringAssert.Contains(ConfigTransferStorage.DescribeFailure(error), "commit failed"); + StringAssert.Contains(ConfigTransferStorage.DescribeFailure(error), backup); + Assert.AreEqual(1, Directory.GetFiles(fixture.Root, ".autofix-import-*").Length); + } + finally { locked?.Dispose(); } + Assert.AreEqual(10, fixture.Storage.Load(fixture.Path).Triggers.WordCount); + Assert.AreEqual(0L, Scalar(fixture, "select count(*) from settings_import_recovery")); + } + + /// A locked temporary file cannot mask a commit failure or stop settings restoration. + [TestMethod] + public void CleanupFailurePreservesCommitErrorAndRestoredSettings() + { + using var fixture = TempConfigFixture.Create(); + var transfer = CreateTransfer(fixture); + var path = Path.Combine(fixture.Root, "bundle.zip"); transfer.Export(path, AppConfig.Default(), false); + var preview = transfer.Preview(path); + var before = File.ReadAllBytes(fixture.Path); + var primary = new SqliteException("commit failed", 19); + FileStream? locked = null; + try + { + var error = Assert.ThrowsException(() => transfer.Apply(preview, _ => + { + var backup = Directory.GetFiles(fixture.Root, ".autofix-import-*.backup").Single(); + var temporary = backup[..^".backup".Length]; + locked = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None); + throw primary; + })); + Assert.AreSame(primary, error); + CollectionAssert.AreEqual(before, File.ReadAllBytes(fixture.Path)); + Assert.IsInstanceOfType(error.Data["ImportCleanupError"], typeof(IOException)); + StringAssert.Contains(ConfigTransferStorage.DescribeFailure(error), (string)error.Data["ImportCleanupPath"]!); + Assert.AreEqual(0, Directory.GetFiles(fixture.Root, "*.backup").Length); + } + finally { locked?.Dispose(); } + } + + [TestMethod] + public void BundleRoundTripsPermissionsPhrasesScopesAndEffectiveLanguages() + { + using var source = TempConfigFixture.Create(); + var transfer = CreateTransfer(source); + var config = source.Storage.Load(source.Path); + config.General.RunMode = "allowlist"; + config.Triggers.WordCount = 18; + config.Correction.PreferredLanguage = "fr"; + config.Correction.AppLanguageOverrides = ["notes.exe=en-US"]; + var apps = new AppRuleStorage(Database(source)); + apps.Upsert(new() { ProcessName = "notes.exe", WindowTitlePattern = "Report", ListBehavior = "allowlist", + ManualShortcutAllowed = true, WordCountTriggerAllowed = false, CharacterTriggerAllowed = true, + LocalEngineAllowed = true, ApiEngineAllowed = false, SafetyMode = "code_editor", ProseContextAllowed = true }); + var words = new DictionaryStorage(Database(source)); + words.Save(new() { Word = "AutoFix", Language = "und", Source = "dictionary" }); + words.Save(new() { Word = "projet secret", Language = "fr", App = "notes.exe", Source = "dictionary" }); + words.Save(new() { Word = "私の製品", Language = "ja", Source = "dictionary" }); + words.Save(new() { Word = "learned-source", Replacement = "learned-replacement", Language = "en", App = "notes.exe", Source = "pair" }); + Execute(source, """ + create table language_overrides (id integer primary key, app_process_name text not null unique, language_code text not null, created_at text default current_timestamp); + insert into language_overrides (app_process_name, language_code) values ('notes.exe', 'de'), ('word.exe', 'ar'); + insert into learned_correction_rules (original_text, rejected_correction, rule_type, learning_enabled) values ('disabled-rule', 'bad-replacement', 'pair', 0); + """); + var path = Path.Combine(source.Root, "bundle.zip"); + transfer.Export(path, config, true); + + using var target = TempConfigFixture.Create(); + var targetTransfer = CreateTransfer(target); + new DictionaryStorage(Database(target)).Save(new() { Word = "old-word", Language = "und", Source = "dictionary" }); + Execute(target, """ + create table language_overrides (id integer primary key, app_process_name text not null unique, language_code text not null); + insert into language_overrides (app_process_name, language_code) values ('old.exe', 'es'); + """); + var before = File.ReadAllText(target.Path); + var preview = targetTransfer.Preview(path); + Assert.AreEqual(before, File.ReadAllText(target.Path)); + Assert.IsTrue(preview.Changes.Any(c => c.Name == "triggers.word_count" && c.After == "18")); + Assert.IsTrue(preview.Changes.Any(c => c.Area == "Dictionary" && c.Name.Contains("old-word") && c.After == "(absent)")); + Assert.IsFalse(JsonSerializer.Serialize(preview.Changes).Contains("learned-source")); + targetTransfer.Apply(preview); + + var imported = target.Storage.Load(target.Path); + Assert.AreEqual("allowlist", imported.General.RunMode); + Assert.AreEqual(18, imported.Triggers.WordCount); + Assert.AreEqual("fr", imported.Correction.PreferredLanguage); + CollectionAssert.AreEqual(new[] { "notes.exe=en-US", "word.exe=ar" }, imported.Correction.AppLanguageOverrides.ToArray()); + var rule = new AppRuleStorage(Database(target)).List().Single(r => r.ProcessName == "notes.exe"); + Assert.AreEqual("Report", rule.WindowTitlePattern); + Assert.IsTrue(rule.ManualShortcutAllowed && rule.CharacterTriggerAllowed && rule.LocalEngineAllowed && rule.ProseContextAllowed); + Assert.IsFalse(rule.WordCountTriggerAllowed || rule.ApiEngineAllowed); + Assert.AreEqual("code_editor", rule.SafetyMode); + var entries = new DictionaryStorage(Database(target)).List(); + Assert.AreEqual(4, entries.Count); + Assert.IsTrue(entries.Any(d => d.Word == "projet secret" && d.Language == "fr" && d.App == "notes.exe")); + Assert.IsTrue(entries.Any(d => d.Word == "私の製品")); + Assert.IsFalse(entries.Any(d => d.Word == "old-word")); + Assert.AreEqual(2L, Scalar(target, "select count(*) from learned_correction_rules")); + Assert.AreEqual("en-US", Scalar(target, "select language_code from language_overrides where app_process_name = 'notes.exe'")); + } + + [TestMethod] + public void DefaultExportExcludesSecretsSessionHistoryLogsAndLearnedPairs() + { + using var source = TempConfigFixture.Create(); + var transfer = CreateTransfer(source); + File.AppendAllText(source.Path, "\n[secrets]\napi_key = 'private-api-key'\n"); + new DictionaryStorage(Database(source)).Save(new() { Word = "learned-private-original", Replacement = "learned-private-replacement", Language = "und", Source = "pair" }); + Execute(source, """ + create table debug_events (typed_text text); + insert into debug_events values ('private-session-text'); + create table correction_history (original_text text, corrected_text text); + insert into correction_history values ('private-original-history', 'private-corrected-history'); + create table correction_metadata (result_reason text); + insert into correction_metadata values ('private-log-sentinel'); + """); + var path = Path.Combine(source.Root, "default.zip"); + // Export accepts typed settings, never raw TOML or database bytes. + transfer.Export(path, AppConfig.Default(), false); + var contents = Contents(path); + CollectionAssert.AreEquivalent(new[] { "manifest.json", "settings.toml", "app-rules.json", "dictionary.json", "language-overrides.json" }, contents.Keys.ToArray()); + var text = string.Join("\n", contents.Values); + Assert.IsFalse(text.Contains("private-") || text.Contains("learned-private-")); + + using var target = TempConfigFixture.Create(); + var targetTransfer = CreateTransfer(target); + new DictionaryStorage(Database(target)).Save(new() { Word = "kept-pair", Replacement = "kept-replacement", Language = "und", Source = "pair" }); + Execute(target, """ + create table correction_history (original_text text); + insert into correction_history values ('kept-history'); + create table debug_events (typed_text text); + insert into debug_events values ('kept-session'); + create table secure_keys (secret text); + insert into secure_keys values ('kept-key'); + """); + targetTransfer.Apply(targetTransfer.Preview(path)); + Assert.AreEqual("kept-pair", Scalar(target, "select original_text from learned_correction_rules")); + Assert.AreEqual("kept-history", Scalar(target, "select original_text from correction_history")); + Assert.AreEqual("kept-session", Scalar(target, "select typed_text from debug_events")); + Assert.AreEqual("kept-key", Scalar(target, "select secret from secure_keys")); + } + + [TestMethod] + public void FreshDatabaseImportsLanguageOverridesWithoutOwningEngineMigrations() + { + using var source = TempConfigFixture.Create(); + var transfer = CreateTransfer(source); + var config = AppConfig.Default(); config.Correction.AppLanguageOverrides = ["notes.exe=fr"]; + var path = Path.Combine(source.Root, "bundle.zip"); transfer.Export(path, config, false); + using var target = TempConfigFixture.Create(); + var targetTransfer = CreateTransfer(target); + targetTransfer.Apply(targetTransfer.Preview(path)); + CollectionAssert.AreEqual(new[] { "notes.exe=fr" }, target.Storage.Load(target.Path).Correction.AppLanguageOverrides.ToArray()); + Assert.AreEqual(0L, Scalar(target, "select count(*) from sqlite_master where name = 'language_overrides'")); + } + + [DataTestMethod] + [DataRow("settings")] + [DataRow("apps")] + [DataRow("dictionary")] + [DataRow("learned")] + [DataRow("languages")] + public void StalePreviewIsRejectedBeforeAnyReplacement(string changedArea) + { + using var fixture = TempConfigFixture.Create(); + var transfer = CreateTransfer(fixture); + var path = Path.Combine(fixture.Root, "bundle.zip"); transfer.Export(path, AppConfig.Default(), true); + var preview = transfer.Preview(path); + switch (changedArea) + { + case "settings": var config = AppConfig.Default(); config.Triggers.WordCount = 19; fixture.Storage.Save(config); break; + case "apps": new AppRuleStorage(Database(fixture)).Upsert(new() { ProcessName = "new.exe" }); break; + case "dictionary": new DictionaryStorage(Database(fixture)).Save(new() { Word = "new", Language = "und", Source = "dictionary" }); break; + case "learned": new DictionaryStorage(Database(fixture)).Save(new() { Word = "new", Replacement = "newer", Language = "und", Source = "pair" }); break; + case "languages": Execute(fixture, "create table language_overrides (app_process_name text, language_code text); insert into language_overrides values ('new.exe', 'fr')"); break; + } + var before = File.ReadAllText(fixture.Path); + var dictionaryBefore = JsonSerializer.Serialize(new DictionaryStorage(Database(fixture)).List()); + Assert.ThrowsException(() => transfer.Apply(preview)); + Assert.AreEqual(before, File.ReadAllText(fixture.Path)); + Assert.AreEqual(dictionaryBefore, JsonSerializer.Serialize(new DictionaryStorage(Database(fixture)).List())); + } + + [TestMethod] + public void ReviewedSnapshotSurvivesSourceMutationAndDoesNotReadLogsOnApply() + { + using var fixture = TempConfigFixture.Create(); + var transfer = CreateTransfer(fixture); + var config = AppConfig.Default(); config.Triggers.WordCount = 22; + var path = Path.Combine(fixture.Root, "bundle.zip"); transfer.Export(path, config, false); + var preview = transfer.Preview(path); + File.WriteAllText(path, "replaced file after preview"); + Execute(fixture, "create table debug_events (typed_text text); insert into debug_events values ('changed-session')"); + transfer.Apply(preview); + Assert.AreEqual(22, fixture.Storage.Load(fixture.Path).Triggers.WordCount); + Assert.AreEqual("changed-session", Scalar(fixture, "select typed_text from debug_events")); + } + + [TestMethod] + public void NoChangePreviewPreservesLearnedRulesAddedAfterPreviewWhenExcluded() + { + using var fixture = TempConfigFixture.Create(); + var transfer = CreateTransfer(fixture); + var path = Path.Combine(fixture.Root, "bundle.zip"); transfer.Export(path, AppConfig.Default(), false); + var preview = transfer.Preview(path); + Assert.IsFalse(preview.HasChanges); + StringAssert.Contains(preview.ChangeSummary, "No changes."); + new DictionaryStorage(Database(fixture)).Save(new() { Word = "just-learned", Replacement = "replacement", Language = "und", Source = "pair" }); + transfer.Apply(preview); + Assert.AreEqual("just-learned", Scalar(fixture, "select original_text from learned_correction_rules")); + } + + [TestMethod] + public void DatabaseFailureRollsBackConfigAndAllReplacedTables() + { + using var fixture = TempConfigFixture.Create(); + var transfer = CreateTransfer(fixture); + var config = AppConfig.Default(); config.Triggers.WordCount = 22; + var path = Path.Combine(fixture.Root, "bundle.zip"); transfer.Export(path, config, true); + new DictionaryStorage(Database(fixture)).Save(new() { Word = "keep-word", Language = "und", Source = "dictionary" }); + var preview = transfer.Preview(path); + Execute(fixture, "create trigger deny_dictionary_delete before delete on custom_dictionary_entries begin select raise(abort, 'test failure'); end"); + var before = File.ReadAllText(fixture.Path); + var appsBefore = JsonSerializer.Serialize(new AppRuleStorage(Database(fixture)).List()); + Assert.ThrowsException(() => transfer.Apply(preview)); + Assert.AreEqual(before, File.ReadAllText(fixture.Path)); + Assert.AreEqual(appsBefore, JsonSerializer.Serialize(new AppRuleStorage(Database(fixture)).List())); + Assert.AreEqual("keep-word", Scalar(fixture, "select entry from custom_dictionary_entries")); + Assert.AreEqual(0, Directory.GetFiles(fixture.Root, "*.tmp").Length); + } + + [TestMethod] + public void SettingsFileFailureRollsBackDatabaseReplacements() + { + using var fixture = TempConfigFixture.Create(); + var transfer = CreateTransfer(fixture); + var path = Path.Combine(fixture.Root, "bundle.zip"); transfer.Export(path, AppConfig.Default(), false); + new DictionaryStorage(Database(fixture)).Save(new() { Word = "keep-word", Language = "und", Source = "dictionary" }); + var preview = transfer.Preview(path); + var before = File.ReadAllText(fixture.Path); + using (var locked = new FileStream(fixture.Path, FileMode.Open, FileAccess.Read, FileShare.Read)) + Assert.ThrowsException(() => transfer.Apply(preview)); + Assert.AreEqual(before, File.ReadAllText(fixture.Path)); + Assert.AreEqual("keep-word", Scalar(fixture, "select entry from custom_dictionary_entries")); + } + + [DataTestMethod] + [DataRow("missing")] + [DataRow("version")] + [DataRow("manifest")] + [DataRow("extra")] + [DataRow("traversal")] + [DataRow("duplicate")] + [DataRow("settings")] + [DataRow("secret")] + [DataRow("null")] + [DataRow("duplicate-rules")] + [DataRow("bad-app")] + [DataRow("bad-language")] + [DataRow("language-disagreement")] + [DataRow("bad-learned")] + [DataRow("oversized")] + [DataRow("too-many-rules")] + public void InvalidBundlesNeverChangeLocalConfigOrRules(string fault) + { + using var fixture = TempConfigFixture.Create(); + var transfer = CreateTransfer(fixture); + var path = Path.Combine(fixture.Root, "bundle.zip"); transfer.Export(path, AppConfig.Default(), true); + var files = Contents(path); + switch (fault) + { + case "missing": files.Remove("dictionary.json"); break; + case "version": files["manifest.json"] = "{\"format_version\":2,\"learned_rules_included\":true}"; break; + case "manifest": files["manifest.json"] = "{\"format_version\":1,\"learned_rules_included\":false}"; break; + case "extra": files["secrets.json"] = "{\"api_key\":\"private\"}"; break; + case "traversal": files["../settings.toml"] = "traversal"; break; + case "settings": var invalid = AppConfig.Default(); invalid.Api.TimeoutManualMs = 0; files["settings.toml"] = ConfigStorage.ToToml(invalid); break; + case "secret": files["dictionary.json"] = "[{\"word\":\"safe\",\"language\":\"und\",\"api_key\":\"private\"}]"; break; + case "null": files["dictionary.json"] = "[null]"; break; + case "duplicate-rules": files["dictionary.json"] = "[{\"word\":\"same\",\"language\":\"en\"},{\"word\":\"same\",\"language\":\"EN\"}]"; break; + case "bad-app": files["app-rules.json"] = "[{\"process_name\":\"../bad.exe\",\"list_behavior\":\"allowlist\"}]"; break; + case "bad-language": files["dictionary.json"] = "[{\"word\":\"safe\",\"language\":\"invalid!\"}]"; break; + case "language-disagreement": files["language-overrides.json"] = "[{\"process\":\"notes.exe\",\"language\":\"fr\"}]"; break; + case "bad-learned": files["learned-rules.json"] = "[{\"original\":\"word\",\"rule_type\":\"unknown\"}]"; break; + case "oversized": files["dictionary.json"] = new string(' ', 8 * 1024 * 1024 + 1); break; + case "too-many-rules": files["dictionary.json"] = JsonSerializer.Serialize(Enumerable.Range(0, 10001).Select(i => new { word = $"term-{i}", language = "und" })); break; + } + WriteBundle(path, files, fault == "duplicate"); + var before = File.ReadAllText(fixture.Path); + var appsBefore = JsonSerializer.Serialize(new AppRuleStorage(Database(fixture)).List()); + try { transfer.Preview(path); Assert.Fail("Invalid bundle was accepted."); } + catch (Exception error) when (error is InvalidDataException or ArgumentException or JsonException) { } + Assert.AreEqual(before, File.ReadAllText(fixture.Path)); + Assert.AreEqual(appsBefore, JsonSerializer.Serialize(new AppRuleStorage(Database(fixture)).List())); + } + + [TestMethod] + public void ExportCannotOverwriteLiveSettingsOrDatabase() + { + using var fixture = TempConfigFixture.Create(); + var transfer = CreateTransfer(fixture); + var before = File.ReadAllText(fixture.Path); + Assert.ThrowsException(() => transfer.Export(fixture.Path, AppConfig.Default(), false)); + Assert.ThrowsException(() => transfer.Export(Database(fixture), AppConfig.Default(), false)); + Assert.AreEqual(before, File.ReadAllText(fixture.Path)); + } + + [TestMethod] + public void LegacyTomlImportDropsUnknownSecretsAndPreservesProductRows() + { + using var fixture = TempConfigFixture.Create(); + var transfer = CreateTransfer(fixture); + new DictionaryStorage(Database(fixture)).Save(new() { Word = "keep-word", Language = "und", Source = "dictionary" }); + var appsBefore = JsonSerializer.Serialize(new AppRuleStorage(Database(fixture)).List()); + var config = AppConfig.Default(); config.Triggers.WordCount = 24; + var path = Path.Combine(fixture.Root, "legacy.toml"); + File.WriteAllText(path, ConfigStorage.ToToml(config) + "\n[secrets]\napi_key = 'private-secret'\n[session]\ntyped_text = 'private-typing'\n"); + var preview = transfer.Preview(path); + StringAssert.Contains(preview.Summary, "Settings-only"); + Assert.IsFalse(JsonSerializer.Serialize(preview.Changes).Contains("private-")); + transfer.Apply(preview); + Assert.AreEqual(24, fixture.Storage.Load(fixture.Path).Triggers.WordCount); + Assert.IsFalse(File.ReadAllText(fixture.Path).Contains("private-") || File.ReadAllText(fixture.Path).Contains("[secrets]")); + Assert.AreEqual("keep-word", Scalar(fixture, "select entry from custom_dictionary_entries")); + Assert.AreEqual(appsBefore, JsonSerializer.Serialize(new AppRuleStorage(Database(fixture)).List())); + } + + internal static ConfigTransferStorage CreateTransfer(TempConfigFixture fixture) + { + fixture.Storage.LoadOrCreate(); + var apps = new AppRuleStorage(Database(fixture)); apps.List(); + new DictionaryStorage(Database(fixture)).List(); + return new(fixture.Storage, apps); + } + internal static string Database(TempConfigFixture fixture) => Path.Combine(fixture.Root, "autofix.sqlite"); + internal static void Execute(TempConfigFixture fixture, string sql) + { + using var connection = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = Database(fixture) }.ToString()); + connection.Open(); using var command = connection.CreateCommand(); command.CommandText = sql; command.ExecuteNonQuery(); + } + internal static object? Scalar(TempConfigFixture fixture, string sql) + { + using var connection = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = Database(fixture) }.ToString()); + connection.Open(); using var command = connection.CreateCommand(); command.CommandText = sql; return command.ExecuteScalar(); + } + internal static Dictionary Contents(string path) + { + using var archive = ZipFile.OpenRead(path); + return archive.Entries.ToDictionary(entry => entry.FullName, entry => { using var reader = new StreamReader(entry.Open()); return reader.ReadToEnd(); }); + } + private static void WriteBundle(string path, Dictionary files, bool duplicate) + { + using var archive = new ZipArchive(File.Create(path), ZipArchiveMode.Create); + foreach (var file in files) + { + using var writer = new StreamWriter(archive.CreateEntry(file.Key).Open()); writer.Write(file.Value); + } + if (duplicate) { using var writer = new StreamWriter(archive.CreateEntry("settings.toml").Open()); writer.Write(files["settings.toml"]); } + } +} diff --git a/ui/settings-ui-tests/ImportCrashHost.cs b/ui/settings-ui-tests/ImportCrashHost.cs new file mode 100644 index 0000000..1a147fc --- /dev/null +++ b/ui/settings-ui-tests/ImportCrashHost.cs @@ -0,0 +1,23 @@ +using AutoFix.SettingsUi.Settings; +using AutoFix.SettingsUi.Settings.Transfer; + +namespace AutoFix.SettingsUi.Tests; + +/// Child-process entry point: stops a real import without running catch/finally compensation. +internal static class ImportCrashHost +{ + public static int Main(string[] args) + { + if (args.Length != 2 || !Enum.TryParse(args[1], out var stopAt)) return 2; + var config = new ConfigStorage(Path.Combine(args[0], "settings.toml")); + var transfer = new ConfigTransferStorage(config, new AppRuleStorage(Path.Combine(args[0], "autofix.sqlite"))); + var preview = transfer.Preview(Path.Combine(args[0], "bundle.zip")); + transfer.Apply(preview, transaction => transaction.Commit(), stage => + { + if (stage == stopAt) Environment.Exit(73); + if (stage == ImportStage.Committed && stopAt == ImportStage.RecoveryFileReplaced) + ImportRecovery.Recover(config.ConfigPath, afterFileReplaced: () => Environment.Exit(73)); + }); + return 3; + } +} diff --git a/ui/settings-ui-tests/ImportRecoveryTests.cs b/ui/settings-ui-tests/ImportRecoveryTests.cs new file mode 100644 index 0000000..b5b9d16 --- /dev/null +++ b/ui/settings-ui-tests/ImportRecoveryTests.cs @@ -0,0 +1,83 @@ +using System.Diagnostics; +using AutoFix.SettingsUi.Settings; +using AutoFix.SettingsUi.Settings.Transfer; + +namespace AutoFix.SettingsUi.Tests; + +[TestClass] +public sealed class ImportRecoveryTests +{ + /// Actual process termination at each durable boundary recovers settings and permissions to one generation. + [DataTestMethod] + [DataRow("Prepared", false, false)] + [DataRow("SettingsReplaced", false, false)] + [DataRow("Committed", true, false)] + [DataRow("RecoveryFileReplaced", true, false)] + [DataRow("Prepared", false, true)] + [DataRow("SettingsReplaced", false, true)] + [DataRow("Committed", true, true)] + [DataRow("RecoveryFileReplaced", true, true)] + public void InterruptedImportRecoversTheDatabaseDecision(string stage, bool committed, bool useWal) + { + using var fixture = TempConfigFixture.Create(); + var transfer = ConfigTransferStorageTests.CreateTransfer(fixture); + if (useWal) ConfigTransferStorageTests.Execute(fixture, "pragma journal_mode = WAL"); + var apps = new AppRuleStorage(ConfigTransferStorageTests.Database(fixture)); + apps.Upsert(new() { ProcessName = "notes.exe", ManualShortcutAllowed = true, ApiEngineAllowed = false }); + var config = AppConfig.Default(); config.Triggers.WordCount = 22; + var bundle = Path.Combine(fixture.Root, "bundle.zip"); + transfer.Export(bundle, config, true); + apps.Upsert(new() { ProcessName = "notes.exe", ManualShortcutAllowed = true, ApiEngineAllowed = true }); + new DictionaryStorage(ConfigTransferStorageTests.Database(fixture)).Save(new() { Word = "old-word", Language = "und", Source = "dictionary" }); + var original = File.ReadAllBytes(fixture.Path); + var start = new ProcessStartInfo("dotnet") { UseShellExecute = false, CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden, RedirectStandardOutput = true, RedirectStandardError = true }; + start.ArgumentList.Add(typeof(ImportCrashHost).Assembly.Location); + start.ArgumentList.Add(fixture.Root); start.ArgumentList.Add(stage); + using var process = Process.Start(start)!; + var output = process.StandardOutput.ReadToEndAsync(); var errors = process.StandardError.ReadToEndAsync(); + if (!process.WaitForExit(15000)) { process.Kill(entireProcessTree: true); Assert.Fail("Import child did not terminate."); } + Assert.AreEqual(73, process.ExitCode, output.Result + errors.Result); + Assert.AreEqual(committed ? 1L : 0L, ConfigTransferStorageTests.Scalar(fixture, "select committed from settings_import_recovery")); + // Simulate a settings file not surviving shutdown; the durable decision must repair it. + File.Delete(fixture.Path); + var recovered = new ConfigStorage(fixture.Path).LoadOrCreate(); + Assert.AreEqual(committed ? 22 : 10, recovered.Triggers.WordCount); + Assert.AreEqual(committed ? 0L : 1L, ConfigTransferStorageTests.Scalar(fixture, "select count(*) from custom_dictionary_entries where entry = 'old-word'")); + Assert.AreEqual(committed ? 0L : 1L, ConfigTransferStorageTests.Scalar(fixture, "select api_engine_allowed from app_rules where process_name = 'notes.exe'")); + Assert.AreEqual(0L, ConfigTransferStorageTests.Scalar(fixture, "select count(*) from settings_import_recovery")); + if (!committed) CollectionAssert.AreEqual(original, File.ReadAllBytes(fixture.Path)); + Assert.AreEqual(recovered.Triggers.WordCount, fixture.Storage.LoadOrCreate().Triggers.WordCount); + } + + /// Readers and stale writers refuse the in-progress import lock without changing persistent data. + [TestMethod] + public void SettingsReadersAndWritersHonorTheImportLock() + { + using var fixture = TempConfigFixture.Create(); fixture.Storage.LoadOrCreate(); + var original = File.ReadAllBytes(fixture.Path); + using (ConfigFileAccess.Acquire(fixture.Path)) + { + Assert.ThrowsException(() => fixture.Storage.LoadOrCreate()); + Assert.ThrowsException(() => fixture.Storage.Save(AppConfig.Default())); + } + CollectionAssert.AreEqual(original, File.ReadAllBytes(fixture.Path)); + } + + /// Recovered imports are not overwritten by a settings form built from an older generation. + [TestMethod] + public void StaleSaveAfterRecoveryRequiresReload() + { + using var fixture = TempConfigFixture.Create(); fixture.Storage.LoadOrCreate(); + var imported = AppConfig.Default(); imported.Triggers.WordCount = 22; + using (var connection = new Microsoft.Data.Sqlite.SqliteConnection($"Data Source={ConfigTransferStorageTests.Database(fixture)}")) + { + connection.Open(); ImportRecovery.EnsureTable(connection); + using var transaction = connection.BeginTransaction(); + ImportRecovery.Prepare(connection, transaction, File.ReadAllBytes(fixture.Path), System.Text.Encoding.UTF8.GetBytes(ConfigStorage.ToToml(imported))); + ImportRecovery.MarkCommitted(connection, transaction); transaction.Commit(); + } + Assert.ThrowsException(() => fixture.Storage.Save(AppConfig.Default())); + Assert.AreEqual(22, fixture.Storage.LoadOrCreate().Triggers.WordCount); + } +} diff --git a/ui/settings-ui-tests/LogStorageTests.cs b/ui/settings-ui-tests/LogStorageTests.cs new file mode 100644 index 0000000..db80e22 --- /dev/null +++ b/ui/settings-ui-tests/LogStorageTests.cs @@ -0,0 +1,122 @@ +using AutoFix.SettingsUi.Settings; +using Microsoft.Data.Sqlite; + +namespace AutoFix.SettingsUi.Tests; + +[TestClass] +public sealed class LogStorageTests +{ + /// Legacy null metadata remains readable without changing populated values or the database. + [TestMethod] + public void ViewerDefaultsNullMetadataAndPreservesPopulatedValues() + { + using var fixture = TempConfigFixture.Create(); + var path = Path.Combine(fixture.Root, "nullable.sqlite"); + using var connection = new SqliteConnection($"Data Source={path}"); + connection.Open(); + using var command = connection.CreateCommand(); + command.CommandText = """ + create table correction_metadata (id integer primary key, occurred_at text, + app_process_name text, trigger_type text, confidence_tier text, engine_used text, + replacement_method text, result_reason text, latency_ms integer); + insert into correction_metadata values (1, 'timestamp', 'notes.exe', 'manual', 'high', 'local', 'clipboard', 'applied', 20); + insert into correction_metadata (id) values (2); + """; + command.ExecuteNonQuery(); + var rows = new LogStorage(path).List(); + Assert.AreEqual(new AutoFix.SettingsUi.Models.MetadataLogItem("", "", "", "", "", "", "", 0), rows[0]); + Assert.AreEqual(new AutoFix.SettingsUi.Models.MetadataLogItem("timestamp", "notes.exe", "manual", "high", "local", "clipboard", "applied", 20), rows[1]); + command.CommandText = "select count(*) from correction_metadata where occurred_at is null and latency_ms is null"; + Assert.AreEqual(1L, command.ExecuteScalar()); + } + + [TestMethod] + public void MissingLogsAreEmptyWithoutCreatingDatabase() + { + using var fixture = TempConfigFixture.Create(); + var path = Path.Combine(fixture.Root, "absent.sqlite"); + var storage = new LogStorage(path); + Assert.AreEqual(0, storage.List().Count); + storage.Clear(); + Assert.IsFalse(File.Exists(path)); + } + + [TestMethod] + public void ViewerIsBoundedAndMetadataOnlyAndClearKeepsProductData() + { + using var fixture = TempConfigFixture.Create(); + var path = Path.Combine(fixture.Root, "autofix.sqlite"); + var dictionary = new DictionaryStorage(path); + dictionary.Save(new() { Word = "AutoFix", Language = "und", Source = "dictionary" }); + var rules = new AppRuleStorage(path); rules.List(); + using var connection = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path }.ToString()); + connection.Open(); + using var command = connection.CreateCommand(); + command.CommandText = """ + create table correction_metadata (id integer primary key, occurred_at text default current_timestamp, + app_process_name text, trigger_type text, confidence_tier text, engine_used text, + replacement_method text, result_reason text, latency_ms integer); + create table debug_events (id integer primary key, message text, typed_text text); + insert into debug_events (message, typed_text) values ('private-debug-message', 'private-typed-text'); + with recursive n(x) as (select 1 union all select x + 1 from n where x < 505) + insert into correction_metadata (app_process_name, trigger_type, confidence_tier, engine_used, + replacement_method, result_reason, latency_ms) + select 'notepad.exe', 'manual', 'high', 'local', 'clipboard', 'applied', x from n; + """; + command.ExecuteNonQuery(); + var storage = new LogStorage(path); + var rows = storage.List(); + Assert.AreEqual(500, rows.Count); + Assert.AreEqual(505L, rows[0].LatencyMs); + Assert.AreEqual(6L, rows[^1].LatencyMs); + var json = System.Text.Json.JsonSerializer.Serialize(rows); + Assert.IsFalse(json.Contains("private-typed-text") || json.Contains("private-debug-message")); + storage.Clear(); + Assert.AreEqual(0, storage.List().Count); + command.CommandText = "select count(*) from debug_events"; + Assert.AreEqual(0L, command.ExecuteScalar()); + Assert.AreEqual(1, dictionary.List().Count); + Assert.IsTrue(rules.List().Any(r => r.ProcessName == "Bitwarden.exe")); + } + + [TestMethod] + public void ViewerReadsLegacyMetadataWithoutMigratingDatabase() + { + using var fixture = TempConfigFixture.Create(); + var path = Path.Combine(fixture.Root, "legacy.sqlite"); + using var connection = new SqliteConnection($"Data Source={path}"); + connection.Open(); + using var command = connection.CreateCommand(); + command.CommandText = """ + create table correction_metadata (id integer primary key, occurred_at text, + trigger_type text, confidence_tier text, engine_used text, + replacement_method text, result_reason text, latency_ms integer); + insert into correction_metadata values (1, '2026-10-04 00:00:00', 'manual', 'high', 'local', 'clipboard', 'applied', 20); + """; + command.ExecuteNonQuery(); + Assert.AreEqual("unknown", new LogStorage(path).List().Single().App); + command.CommandText = "select count(*) from pragma_table_info('correction_metadata') where name = 'app_process_name'"; + Assert.AreEqual(0L, command.ExecuteScalar()); + } + + [TestMethod] + public void ClearingLogsRollsBackBothTablesOnFailure() + { + using var fixture = TempConfigFixture.Create(); + var path = Path.Combine(fixture.Root, "autofix.sqlite"); + using var connection = new SqliteConnection($"Data Source={path}"); + connection.Open(); + using var command = connection.CreateCommand(); + command.CommandText = """ + create table correction_metadata (id integer primary key); + create table debug_events (id integer primary key); + insert into correction_metadata values (1); + insert into debug_events values (1); + create trigger fail_clear before delete on debug_events begin select raise(abort, 'busy'); end; + """; + command.ExecuteNonQuery(); + Assert.ThrowsException(() => new LogStorage(path).Clear()); + command.CommandText = "select count(*) from correction_metadata"; + Assert.AreEqual(1L, command.ExecuteScalar()); + } +} diff --git a/ui/settings-ui-tests/MainWindowViewModel.ProductTests.cs b/ui/settings-ui-tests/MainWindowViewModel.ProductTests.cs new file mode 100644 index 0000000..21ab242 --- /dev/null +++ b/ui/settings-ui-tests/MainWindowViewModel.ProductTests.cs @@ -0,0 +1,310 @@ +using System.Security; +using System.Windows; +using System.Windows.Controls; +using AutoFix.SettingsUi.Settings; +using AutoFix.SettingsUi.ViewModels; + +namespace AutoFix.SettingsUi.Tests; + +public sealed partial class MainWindowViewModelTests +{ + /// Invalid dropdown profiles show a recoverable credential message on change, refresh and navigation. + [DataTestMethod] + [DataRow("")] + [DataRow(" ")] + [DataRow("bad\nprofile")] + public async Task InvalidProviderProfileDoesNotInterruptSettings(string profile) + { + using var fixture = TempConfigFixture.Create(); + var storage = new AppRuleStorage(Path.Combine(fixture.Root, "autofix.sqlite")); + var vm = new MainWindowViewModel(new FakeBackgroundIpcClient(), fixture.Storage, storage, + new NullConfigFileDialog(), new WindowsCredentialApiKeyStatus(), new FakeStartupRegistration(), new FakeSettingsConsent()); + await vm.LoadSettingsAsync(); + Card(vm, "api.provider_preset").SelectedValue = profile; + StringAssert.Contains(vm.ApiKeyMessage, "Choose a valid provider profile."); + vm.RefreshApiKeyCommand.Execute(null); + vm.SelectedSection = vm.Sections.Single(section => section.Settings.Any(card => card.Path == "api.provider_preset")); + StringAssert.Contains(vm.ApiKeyMessage, "Choose a valid provider profile."); + Assert.AreEqual("openai_compatible", fixture.Storage.Load(fixture.Path).Api.ProviderPreset); + Card(vm, "api.provider_preset").SelectedValue = "openai_compatible"; + Assert.IsFalse(vm.ApiKeyMessage.Contains("Choose a valid provider profile.")); + } + + [TestMethod] + public async Task DebugConsentAndDependenciesSaveValidConfigs() + { + using var fixture = TempConfigFixture.Create(); + var consent = new FakeSettingsConsent(); + var vm = ProductViewModel(fixture, consent); + await vm.LoadSettingsAsync(); + Card(vm, "logging.full_text_debug_mode_enabled").IsEnabled = true; + Assert.AreEqual(1, consent.FullTextRequests); + Assert.IsFalse(Card(vm, "logging.full_text_debug_mode_enabled").IsEnabled); + Assert.IsFalse(fixture.Storage.Load(fixture.Path).Logging.FullTextDebugModeEnabled); + + Card(vm, "logging.redacted_debug_mode_enabled").IsEnabled = true; + await vm.SaveSettingsAsync(); + var saved = fixture.Storage.Load(fixture.Path).Logging; + Assert.IsTrue(saved.DebugModeEnabled && saved.RedactedDebugModeEnabled); + Assert.IsFalse(saved.FullTextDebugModeEnabled); + + consent.AllowFullText = true; + Card(vm, "logging.full_text_debug_mode_enabled").IsEnabled = true; + await vm.SaveSettingsAsync(); + saved = fixture.Storage.Load(fixture.Path).Logging; + Assert.IsTrue(saved.DebugModeEnabled && saved.FullTextDebugModeEnabled); + Assert.IsFalse(saved.RedactedDebugModeEnabled); + + Card(vm, "logging.debug_mode_enabled").IsEnabled = false; + await vm.SaveSettingsAsync(); + saved = fixture.Storage.Load(fixture.Path).Logging; + Assert.IsFalse(saved.DebugModeEnabled || saved.RedactedDebugModeEnabled || saved.FullTextDebugModeEnabled); + } + + [TestMethod] + public async Task ImportRequiresConsentBeforeEnablingFullTextAndKeepsAppRules() + { + using var fixture = TempConfigFixture.Create(); + var importedPath = Path.Combine(fixture.Root, "import.toml"); + var imported = AppConfig.Default(); + imported.Logging.DebugModeEnabled = true; + imported.Logging.FullTextDebugModeEnabled = true; + fixture.Storage.Export(importedPath, imported); + var consent = new FakeSettingsConsent(); + var ipc = new FakeBackgroundIpcClient(); + ipc.AppRules.Add(new("notepad.exe", null, "allowlist", true, false, false, true, false)); + var vm = new MainWindowViewModel(ipc, fixture.Storage, new AppRuleStorage(Path.Combine(fixture.Root, "autofix.sqlite")), + new ImportOnlyDialog(importedPath), new FakeApiKeyStore(), new FakeStartupRegistration(), consent); + await vm.LoadSettingsAsync(); + var before = File.ReadAllText(fixture.Path); + vm.ImportConfigCommand.Execute(null); + Assert.IsTrue(vm.IsImportPreviewVisible); + Assert.AreEqual(0, consent.FullTextRequests); + vm.ConfirmImportCommand.Execute(null); + await WaitForAsync(() => consent.FullTextRequests == 1); + Assert.AreEqual(before, File.ReadAllText(fixture.Path)); + Assert.IsFalse(Card(vm, "logging.full_text_debug_mode_enabled").IsEnabled); + consent.AllowFullText = true; + vm.ImportConfigCommand.Execute(null); + vm.ConfirmImportCommand.Execute(null); + await WaitForAsync(() => vm.StatusTitle == "Settings imported."); + Assert.IsTrue(fixture.Storage.Load(fixture.Path).Logging.FullTextDebugModeEnabled); + Assert.AreEqual("notepad.exe", vm.Sections.Single(s => s.ShowsAppRules).AppRules.Single().ProcessName); + } + + [TestMethod] + public async Task ProviderChangeClearsCustomEndpointAndKeysStayOutsideConfig() + { + using var fixture = TempConfigFixture.Create(); + var keys = new FakeApiKeyStore(); + var config = AppConfig.Default(); + config.Api.ProviderPreset = "custom"; + config.Api.BaseUrl = "https://example.com/v1"; + fixture.Storage.Save(config); + var vm = ProductViewModel(fixture, new FakeSettingsConsent(), keys); + await vm.LoadSettingsAsync(); + using var secret = new SecureString(); + foreach (var c in "dummy-key-must-not-export") secret.AppendChar(c); + vm.SaveApiKey(secret); + Assert.AreEqual("custom", keys.SavedProfile); + Assert.IsTrue(keys.Stored.Contains("custom")); + Assert.IsFalse(File.ReadAllText(fixture.Path).Contains("dummy-key-must-not-export")); + Card(vm, "api.provider_preset").SelectedValue = "groq"; + await vm.SaveSettingsAsync(); + Assert.IsNull(fixture.Storage.Load(fixture.Path).Api.BaseUrl); + StringAssert.Contains(vm.ApiKeyMessage, "No key saved for groq"); + vm.SaveApiKey(secret); + vm.DeleteApiKeyCommand.Execute(null); + Assert.IsFalse(keys.Stored.Contains("groq")); + Assert.IsTrue(keys.Stored.Contains("custom")); + } + + [TestMethod] + public async Task AppRuleDraftValidationAndTriggerPermissionsPersistThroughIpc() + { + using var fixture = TempConfigFixture.Create(); + var ipc = new FakeBackgroundIpcClient(); + var vm = new MainWindowViewModel(ipc, fixture.Storage, new AppRuleStorage(Path.Combine(fixture.Root, "autofix.sqlite")), + new NullConfigFileDialog(), new FakeApiKeyStore(), new FakeStartupRegistration(), new FakeSettingsConsent()); + await vm.LoadSettingsAsync(); + vm.NewAppProcess = @"C:\notes.exe"; + vm.AddAppRuleCommand.Execute(null); + Assert.AreEqual(0, ipc.UpsertedRules.Count); + vm.NewAppProcess = "notes.exe"; + vm.AddAppRuleCommand.Execute(null); + await WaitForAsync(() => ipc.UpsertedRules.Count == 1); + var rule = vm.SelectedAppRule!; + rule.ManualShortcutAllowed = true; + rule.WordCountTriggerAllowed = true; + rule.CharacterTriggerAllowed = true; + rule.ApiEngineAllowed = false; + await WaitForAsync(() => ipc.UpsertedRules.Count == 5); + var saved = ipc.UpsertedRules.Last(); + Assert.IsTrue(saved.ManualShortcutAllowed && saved.WordCountTriggerAllowed && saved.CharacterTriggerAllowed); + Assert.IsTrue(saved.LocalEngineAllowed); + Assert.IsFalse(saved.ApiEngineAllowed); + vm.NewAppProcess = "NOTES.EXE"; + vm.AddAppRuleCommand.Execute(null); + Assert.AreEqual(1, vm.Sections.Single(s => s.ShowsAppRules).AppRules.Count); + Assert.AreEqual(5, ipc.UpsertedRules.Count); + Card(vm, "general.run_mode").SelectedValue = "allowlist"; + await vm.SaveSettingsAsync(); + Assert.AreEqual("allowlist", fixture.Storage.Load(fixture.Path).General.RunMode); + } + + [TestMethod] + public async Task LanguageDefaultsAndOverridesRoundTripWithoutDuplicatePaths() + { + using var fixture = TempConfigFixture.Create(); + var vm = ProductViewModel(fixture, new FakeSettingsConsent()); + await vm.LoadSettingsAsync(); + StringAssert.Contains(vm.LanguageDetectionSummary, "Automatic"); + Card(vm, "correction.preferred_language").TextValue = "ar"; + Card(vm, "correction.app_language_overrides").TextValue = "notepad.exe=en-US, winword.exe=fr"; + Card(vm, "correction.mixed_language_policy").SelectedValue = "disable_correction"; + await vm.SaveSettingsAsync(); + var saved = fixture.Storage.Load(fixture.Path); + Assert.AreEqual("ar", saved.Correction.PreferredLanguage); + CollectionAssert.AreEqual(new[] { "notepad.exe=en-US", "winword.exe=fr" }, saved.Correction.AppLanguageOverrides); + vm.AutoDetectLanguageCommand.Execute(null); + await vm.SaveSettingsAsync(); + saved = fixture.Storage.Load(fixture.Path); + Assert.IsNull(saved.Correction.PreferredLanguage); + Assert.AreEqual(2, saved.Correction.AppLanguageOverrides.Count); + Assert.AreEqual("disable_correction", saved.Correction.MixedLanguagePolicy); + Assert.AreEqual("App Rules", vm.Sections.Single(s => s.Settings.Any(c => c.Path == "general.run_mode")).Name); + Card(vm, "correction.app_language_overrides").TextValue = "notepad.exe=bad_tag"; + await vm.SaveSettingsAsync(); + Assert.IsTrue(Card(vm, "correction.app_language_overrides").HasValidationError); + Assert.AreEqual(2, fixture.Storage.Load(fixture.Path).Correction.AppLanguageOverrides.Count); + } + + [TestMethod] + public void ProductPagesRenderAndKeyEditorClearsAcrossProfilesAndNavigation() + { + Exception? failure = null; + var thread = new Thread(() => + { + MainWindow? window = null; + try + { + using var fixture = TempConfigFixture.Create(); + var config = AppConfig.Default(); config.Onboarding.Completed = true; + fixture.Storage.Save(config); + var dictionaries = new DictionaryStorage(Path.Combine(fixture.Root, "autofix.sqlite")); + dictionaries.Save(new() { Word = "AutoFix", Language = "und", Source = "dictionary" }); + dictionaries.Save(new() { Word = "projet secret", Language = "fr", App = "notepad.exe", Source = "dictionary" }); + var keys = new FakeApiKeyStore(); + var consent = new FakeSettingsConsent(); + var vm = ProductViewModel(fixture, consent, keys); + window = new MainWindow(vm) { ShowActivated = false, Left = -10000, Top = -10000, Width = 1080, Height = 720 }; + window.Show(); Pump(); + var scroll = (ScrollViewer)window.FindName("SettingsScrollViewer"); + foreach (var name in new[] { "App Rules", "Dictionary", "Engines", "Logs / Debug", "Languages" }) + { + vm.SelectedSection = vm.Sections.Single(s => s.Name == name); + Pump(); scroll.ScrollToTop(); Pump(); + Assert.IsTrue(Descendants(window).OfType().Any(b => b.IsVisible)); + SavePreview(window, name, "top"); + scroll.ScrollToBottom(); Pump(); + SavePreview(window, name, "bottom"); + } + vm.SelectedSection = vm.Sections.Single(s => s.ShowsEngines); Pump(); scroll.ScrollToBottom(); Pump(); + var password = (PasswordBox)window.FindName("ApiKeyBox"); + Assert.IsTrue(password.IsVisible); + password.Password = "test-key"; + Descendants(window).OfType