From b4e2bcf9a52c1e2edf973f09b43b147d4f79a4a7 Mon Sep 17 00:00:00 2001 From: Hussein Ba Ragaa Date: Thu, 1 Oct 2026 18:15:14 +0300 Subject: [PATCH 1/8] feat: make correction a reversible transaction --- README.md | 13 + app-core-rust/README.md | 23 ++ app-core-rust/src/background/mod.rs | 48 ++- app-core-rust/src/background/pipeline.rs | 29 +- .../src/background/pipeline/tests.rs | 72 +++++ app-core-rust/src/background/session.rs | 11 + .../src/background/session/pending.rs | 1 + app-core-rust/src/background/tests.rs | 5 + app-core-rust/src/dictionary/learning.rs | 277 ++++++++++++++++++ app-core-rust/src/dictionary/mod.rs | 273 +++++++++++++++++ app-core-rust/src/dictionary/tests.rs | 239 +++++++++++++++ app-core-rust/src/lib.rs | 1 + app-core-rust/src/settings/mod.rs | 3 +- app-core-rust/src/settings/model.rs | 29 ++ app-core-rust/src/settings/tests.rs | 34 +++ app-core-rust/src/storage.rs | 3 + app-core-rust/src/storage/migrations.rs | 6 +- shared-schema/README.md | 14 + .../AutoFix.SettingsUi.Tests.csproj | 2 + .../DictionaryStorageTests.cs | 84 ++++++ .../MainWindowViewModelTests.cs | 88 ++++++ ui/settings-ui-tests/SettingsSkeletonTests.cs | 1 + ui/settings-ui/MainWindow.xaml | 33 ++- ui/settings-ui/MainWindow.xaml.cs | 7 +- ui/settings-ui/Models/DictionaryItem.cs | 5 + ui/settings-ui/README.md | 11 + ui/settings-ui/Settings/AppConfig.cs | 13 + ui/settings-ui/Settings/ConfigFormMapper.cs | 3 + ui/settings-ui/Settings/ConfigValidator.cs | 4 +- ui/settings-ui/Settings/DictionaryStorage.cs | 117 ++++++++ .../ViewModels/MainWindowViewModel.Config.cs | 1 + .../MainWindowViewModel.Dictionary.cs | 100 +++++++ .../ViewModels/MainWindowViewModel.cs | 5 + .../ViewModels/SettingsSectionViewModel.cs | 3 +- ui/settings-ui/ViewModels/SettingsSkeleton.cs | 12 + 35 files changed, 1550 insertions(+), 20 deletions(-) create mode 100644 app-core-rust/src/dictionary/learning.rs create mode 100644 app-core-rust/src/dictionary/mod.rs create mode 100644 app-core-rust/src/dictionary/tests.rs create mode 100644 ui/settings-ui-tests/DictionaryStorageTests.cs create mode 100644 ui/settings-ui/Settings/DictionaryStorage.cs create mode 100644 ui/settings-ui/ViewModels/MainWindowViewModel.Dictionary.cs diff --git a/README.md b/README.md index 33ea8fa..eb8bbaf 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,19 @@ Local ML correction, suggestion acceptance, IME composition, and direct text API or UI Automation mutation remain planned. App-level undo restores only recorded corrections whose exact span and caret can still be verified. +**Dictionary** settings edit words and phrases that AutoFix must never correct, +plus specific pairs such as `teh` → `the` that must never be applied. Entries live +in `%LOCALAPPDATA%\AutoFix\autofix.sqlite`, with a language tag and optional app +process scope. `und` protects all languages; an empty app scope applies everywhere. + +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 +exclusion. Choose whether to protect the original word/phrase or only the rejected +pair, and whether learning applies just to that app. Existing exclusions stay +active when learning is off. Native Ctrl+Z and suggestion rejection are not tracked; +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 correction** or set `replacement.clipboard_enabled = false` in settings TOML. diff --git a/app-core-rust/README.md b/app-core-rust/README.md index 9efa6e8..6e3664d 100644 --- a/app-core-rust/README.md +++ b/app-core-rust/README.md @@ -19,6 +19,29 @@ the correction mode, enabled grammar categories, language and mixed-language policy, dictionary and protected terms, trigger, and confidence behavior. Its result includes corrected executable text, change need and optional details, confidence, no-change reason, latency, and completion/error/timeout status. + +`src/dictionary` owns persistent exclusions and optional learning. SQLite stores +word/phrase entries and active pair-specific rules. App process matching ignores +ASCII case. `und` and null language scopes protect every language; base tags such +as `en` apply to variants such as `en-US`. Regional tags match the resolved tag. +Unknown or mixed language conservatively protects all entries for the app. +Both engine routes enforce whole-term boundaries, including phrases, and filter +blocked pairs while preserving unrelated edits. Exclusions are snapshotted for +execution. Broad edits that cross a pair's boundary are refused when unchanged +context cannot prove a different replacement. Exclusions are reread +under the replacement writer reservation; a newly +blocked edit refuses the in-flight replacement. + +Learning defaults to off. Only a verified, successful AutoFix undo supplies a +rejection, using the original/replacement span and the correction's recorded +language. It never captures document text or native Ctrl+Z. The smallest changed +word/phrase is learned; multiple separated changes form one phrase. Ask mode uses +a separate, coalesced native Yes/No prompt, defaults to No, and stores no text +until consent. Input processing remains available while the prompt is open. +Changing learning settings cancels pending consent. Automatic mode writes the +selected dictionary or pair exclusion after successful undo. Disabling learning +does not disable existing rules. Suggestion rejection remains unavailable with +the planned suggestion UI; failed or refused undo never learns. `LocalRuleEngine`, `LocalMlEngine`, `OpenAiCompatibleApiEngine`, and `CustomApiEngine` implement the same interface. `LocalRuleEngine` provides fast, deterministic English correction for a conservative list of clear misspellings. diff --git a/app-core-rust/src/background/mod.rs b/app-core-rust/src/background/mod.rs index a9efa9c..620861b 100644 --- a/app-core-rust/src/background/mod.rs +++ b/app-core-rust/src/background/mod.rs @@ -103,6 +103,7 @@ fn capture_if_current( } struct InputProcessor { + learner: crate::dictionary::Learner, pipeline: CorrectionPipeline, processed_input_sequence: u64, config: AppConfig, @@ -312,6 +313,7 @@ impl InputWorker { .name("autofix-input-processing".into()) .spawn(move || { let mut processor = InputProcessor { + learner: crate::dictionary::Learner::default(), pipeline, processed_input_sequence: input_listener::current_input_sequence(), session_manager: SessionManager::new(config.context.clone()), @@ -439,6 +441,8 @@ impl InputProcessor { /// Defer completion until hook input is drained, then validate the live target and caret. fn finish_correction(&mut self) { + self.learner + .poll(&self.config.learning, &self.database.dictionary()); // Frozen ranges may survive processed typing, but never guess what keys // still queued in the hooks did to the target. if Self::input_stamp().sequence != self.processed_input_sequence { @@ -471,6 +475,17 @@ impl InputProcessor { ); return false; }; + // Recheck live exclusions under the same writer reservation as mutation. + let Ok(policy) = database + .dictionary() + .policy(&target.process_name, &request.language_info) + else { + tracing::warn!("replacement skipped: exclusions unavailable"); + return false; + }; + if policy.filter(&request.executable_context, output.clone()) != *output { + return false; + } let result = ReplacementEngine::replace( target, request, @@ -819,10 +834,25 @@ impl InputProcessor { self.config.replacement.clipboard_enabled, ); result.log_outcome(true); + drop(_policy_guard); if result.success { if let Some(session) = self.session_manager.active_mut() { session.undo_last_correction(&self.config.context); } + if self.config.learning.mode != crate::settings::LearningMode::Off { + if let Some(rejection) = crate::dictionary::Rejection::from_undo( + &undo.original, + &undo.corrected, + undo.language.clone(), + target.process_name.clone(), + ) { + self.learner.rejected( + rejection, + &self.config.learning, + &self.database.dictionary(), + ); + } + } } else if result.may_have_changed { self.session_manager .deactivate(MovementSignal::UnknownPosition); @@ -960,10 +990,10 @@ impl InputProcessor { request.confidence_behavior = self.config.confidence_behavior(); let dictionary = match self .database - .custom_dictionary() - .entries_for_app(&target.process_name) + .dictionary() + .policy(&target.process_name, &request.language_info) { - Ok(entries) => entries, + Ok(policy) => policy.terms, Err(error) => { tracing::warn!(%error, "correction skipped: dictionary unavailable"); return false; @@ -985,8 +1015,16 @@ impl InputProcessor { tracing::debug!(session_id = request.session_id, ?request.versions, ?request.engine, ?request.mode, trigger = request.trigger.as_str(), "correction queued"); - self.pipeline - .submit(request, session, target, stamp, &self.config, dictionary); + if !self.pipeline.submit( + request, + session, + target, + stamp, + &self.config, + dictionary, + ) { + return false; + } if manual { self.pipeline.wait_manual(); self.finish_correction(); diff --git a/app-core-rust/src/background/pipeline.rs b/app-core-rust/src/background/pipeline.rs index e6bf3ec..4248863 100644 --- a/app-core-rust/src/background/pipeline.rs +++ b/app-core-rust/src/background/pipeline.rs @@ -49,6 +49,7 @@ struct Job { api: ApiEngineConfig, cancelled: Arc, authorization: SendAuthorization, + exclusions: crate::dictionary::Policy, } struct Completion { @@ -149,7 +150,9 @@ impl CorrectionPipeline { if job.cancelled.load(Ordering::Acquire) { continue; } - let output = correct(&job); + let output = job + .exclusions + .filter(&job.input.executable_context, correct(&job)); let (lock, ready) = &*worker_mailbox; let mut state = lock.lock().unwrap(); // Transport may finish after cancellation; never publish that result. @@ -178,7 +181,7 @@ impl CorrectionPipeline { stamp: InputStamp, config: &AppConfig, dictionary: Vec, - ) { + ) -> bool { if request.pending_segment_id.is_none() { self.cancel(); } @@ -228,6 +231,19 @@ impl CorrectionPipeline { confidence_behavior: request.confidence_behavior.clone(), suggestion_ui_available: false, }; + let exclusions = match self.database_path.as_deref() { + Some(path) => match crate::storage::Database::open(path).and_then(|db| { + db.dictionary() + .policy(&target.process_name, &request.language_info) + }) { + Ok(policy) => policy, + Err(_) => { + tracing::warn!("correction skipped: exclusions unavailable"); + return false; + } + }, + None => crate::dictionary::Policy::default(), + }; self.active.push_back(ActiveRequest { id, request: request.clone(), @@ -246,8 +262,10 @@ impl CorrectionPipeline { api: (&config.api).into(), cancelled, authorization, + exclusions, }); ready.notify_all(); + true } /// Cancel all admitted work and clear queued jobs, completions, and timeout feedback. @@ -449,7 +467,8 @@ impl CorrectionPipeline { return false; } let session = manager.active_mut().unwrap(); - if let Some(id) = segment_id { + let changed = output.changes_needed; + let completed = if let Some(id) = segment_id { session.complete_pending(id, Some(&output.corrected_executable_text), limits) } else if output.changes_needed { session.queue_correction(original.clone(), output.corrected_executable_text) @@ -457,7 +476,11 @@ impl CorrectionPipeline { } else { session.complete_without_changes(limits); true + }; + if completed && changed { + session.record_undo_language(active.request.language_info.primary_language.clone()); } + completed })(); if !applied { if let (Some(id), Some(session)) = (segment_id, manager.active_mut()) { diff --git a/app-core-rust/src/background/pipeline/tests.rs b/app-core-rust/src/background/pipeline/tests.rs index dbb732a..67f3c73 100644 --- a/app-core-rust/src/background/pipeline/tests.rs +++ b/app-core-rust/src/background/pipeline/tests.rs @@ -12,6 +12,77 @@ const STAMP: InputStamp = InputStamp { sequence: 12, }; +#[test] +fn persisted_pair_filters_worker_edits_and_learns_original_language() { + let path = std::env::temp_dir().join(format!( + "autofix-pair-pipeline-{}.sqlite", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let db = crate::storage::Database::open(&path).unwrap(); + let rejection = crate::dictionary::Rejection::from_undo( + "teh", + "the", + Some("en".into()), + "notepad.exe".into(), + ) + .unwrap(); + let learning = crate::settings::LearningConfig { + mode: crate::settings::LearningMode::Automatic, + ..Default::default() + }; + db.dictionary().remember(&rejection, &learning).unwrap(); + let mut config = AppConfig::default(); + config.correction.preferred_language = Some("en".into()); + let mut manager = manager(&config, "teh wierd"); + let mut pipeline = CorrectionPipeline::with_database(&db).unwrap(); + let mut request = request(&manager, &config); + request.language_info = crate::correction::LanguageInfo { + primary_language: Some("en".into()), + detected_languages: vec!["en".into()], + }; + assert!(pipeline.submit( + request, + manager.active().unwrap(), + target(), + STAMP, + &config, + vec![] + )); + wait_completion(&pipeline); + let replaced = Cell::new(0); + assert!(finish( + &mut pipeline, + &mut manager, + &config, + STAMP, + &replaced, + true + )); + assert_eq!(replaced.get(), 1); + assert_eq!(manager.active().unwrap().informative_context(), "teh weird"); + assert_eq!( + manager + .active() + .unwrap() + .undo_target() + .unwrap() + .language + .as_deref(), + Some("en") + ); + assert!(manager + .active_mut() + .unwrap() + .undo_last_correction(&config.context)); + assert_eq!(manager.active().unwrap().informative_context(), "teh wierd"); + drop(pipeline); + drop(db); + std::fs::remove_file(path).unwrap(); +} + /// A real queued API job must not transmit after revocation commits behind an earlier send. #[test] fn queued_api_job_is_denied_after_rule_revocation_and_releases_its_slot() { @@ -632,6 +703,7 @@ fn input_processor_defers_frozen_completion_until_hook_input_is_drained() { submit_frozen(&mut pipeline, &mut manager, &config); wait_completion(&pipeline); let mut processor = crate::background::InputProcessor { + learner: crate::dictionary::Learner::default(), pipeline, processed_input_sequence: crate::background::input_listener::current_input_sequence() .wrapping_sub(1), diff --git a/app-core-rust/src/background/session.rs b/app-core-rust/src/background/session.rs index 2d54014..1c28c13 100644 --- a/app-core-rust/src/background/session.rs +++ b/app-core-rust/src/background/session.rs @@ -40,6 +40,7 @@ pub(crate) struct PendingCorrection { #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct CorrectionUndo { + language: Option, original: String, replacement: String, informative_start: usize, @@ -49,6 +50,7 @@ pub(crate) struct CorrectionUndo { /// Only a recorded, fully retained app correction may make informative text editable. pub(super) struct CorrectionUndoTarget { + pub(super) language: Option, pub(super) corrected: String, pub(super) original: String, pub(super) following: String, @@ -570,6 +572,7 @@ impl Session { .filter(|start| self.informative_context.get(*start..) == Some(replacement.as_str())) { self.correction_undo_history.push(CorrectionUndo { + language: None, complete_range_retained: replacement == correction.replacement, original: correction.original, replacement, @@ -591,6 +594,7 @@ impl Session { return None; } Some(CorrectionUndoTarget { + language: last.language.clone(), corrected: last.replacement.clone(), original: last.original.clone(), following: format!( @@ -601,6 +605,13 @@ impl Session { }) } + /// Keep the correction's language with its memory-only undo record. + pub(super) fn record_undo_language(&mut self, language: Option) { + if let Some(last) = self.correction_undo_history.last_mut() { + last.language = language; + } + } + /// Restore a recorded original in session context while preserving newer typed text. pub(crate) fn undo_last_correction(&mut self, limits: &ContextConfig) -> bool { let Some(last) = self.correction_undo_history.last().cloned() else { diff --git a/app-core-rust/src/background/session/pending.rs b/app-core-rust/src/background/session/pending.rs index c3d8a1c..47d21cf 100644 --- a/app-core-rust/src/background/session/pending.rs +++ b/app-core-rust/src/background/session/pending.rs @@ -131,6 +131,7 @@ impl Session { .collect(); let start = self.informative_context.len() - retained.len(); self.correction_undo_history.push(CorrectionUndo { + language: None, complete_range_retained: retained == corrected, original: segment.original, replacement: retained, diff --git a/app-core-rust/src/background/tests.rs b/app-core-rust/src/background/tests.rs index 4ed2a09..e863419 100644 --- a/app-core-rust/src/background/tests.rs +++ b/app-core-rust/src/background/tests.rs @@ -16,6 +16,7 @@ fn frozen_dispatch_survives_typing_but_manual_and_moved_requests_are_rejected() for during_gate in [false, true] { let config = AppConfig::default(); let mut processor = super::InputProcessor { + learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: 12, session_manager: super::SessionManager::new(config.context.clone()), @@ -81,6 +82,7 @@ fn failed_frozen_dispatch_preserves_older_work_and_releases_newer_reservations() let mut config = AppConfig::default(); config.context.pending_queue_size = 3; let mut processor = super::InputProcessor { + learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: 12, session_manager: super::SessionManager::new(config.context.clone()), @@ -229,6 +231,7 @@ fn queued_typing_before_or_during_capture_never_enters_informative_context() { fn delayed_key_from_previous_focus_cannot_enter_session() { let config = AppConfig::default(); let mut processor = super::InputProcessor { + learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: super::input_listener::current_input_sequence(), session_manager: super::SessionManager::new(config.context.clone()), @@ -264,6 +267,7 @@ fn delayed_key_from_previous_focus_cannot_enter_session() { fn later_character_trigger_keeps_full_editable_snapshot() { let config = AppConfig::default(); let mut processor = super::InputProcessor { + learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: super::input_listener::current_input_sequence(), session_manager: super::SessionManager::new(config.context.clone()), @@ -320,6 +324,7 @@ fn automatic_triggers_in_one_batch_obey_capacity_and_overflow_policy() { let mut config = AppConfig::default(); config.context.pending_queue_full_behavior = policy; let mut processor = super::InputProcessor { + learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: super::input_listener::current_input_sequence(), session_manager: super::SessionManager::new(config.context.clone()), diff --git a/app-core-rust/src/dictionary/learning.rs b/app-core-rust/src/dictionary/learning.rs new file mode 100644 index 0000000..2b8587d --- /dev/null +++ b/app-core-rust/src/dictionary/learning.rs @@ -0,0 +1,277 @@ +use super::{word_char, Repository}; +use crate::settings::{LearningConfig, LearningMode}; +use std::sync::mpsc::{self, Receiver}; + +#[derive(Debug, Clone)] +pub(crate) struct Rejection { + pub(crate) original: String, + pub(crate) corrected: String, + pub(crate) language: Option, + pub(crate) app: String, +} + +impl Rejection { + /// Learn the changed word/phrase, excluding unchanged leading/trailing text. + pub(crate) fn from_undo( + original: &str, + corrected: &str, + language: Option, + app: String, + ) -> Option { + if original == corrected { + return None; + } + let a: Vec = original.chars().collect(); + let b: Vec = corrected.chars().collect(); + let mut start = a.iter().zip(&b).take_while(|(a, b)| a == b).count(); + // Bound common suffix before expanding the changed span, so removed + // repeated words cannot be mistaken for unchanged suffix context. + let mut suffix = a[start..] + .iter() + .rev() + .zip(b[start..].iter().rev()) + .take_while(|(a, b)| a == b) + .count(); + let needs_word_anchor = a[start..a.len() - suffix].iter().all(|c| c.is_whitespace()); + while start > 0 && word_char(a[start - 1]) { + start -= 1; + } + while suffix > 0 && (word_char(a[a.len() - suffix]) || word_char(b[b.len() - suffix])) { + suffix -= 1; + } + if needs_word_anchor { + // Pure spacing/insertion edits need adjacent words to form a rule. + while start > 0 && a[start - 1].is_whitespace() { + start -= 1; + } + while start > 0 && !a[start - 1].is_whitespace() { + start -= 1; + } + } + let original: String = a[start..a.len() - suffix].iter().collect(); + if original.trim().is_empty() { + return None; + } + Some(Self { + original, + corrected: b[start..b.len() - suffix].iter().collect(), + language, + app, + }) + } +} + +#[derive(Default)] +pub(crate) struct Learner { + pending: Option, +} + +struct PendingConsent { + config: LearningConfig, + receive: Receiver>, + cancelled: bool, +} + +impl Learner { + pub(crate) fn rejected( + &mut self, + rejection: Rejection, + config: &LearningConfig, + repository: &Repository<'_>, + ) { + self.rejected_with(rejection, config, repository, confirm); + } + + fn rejected_with( + &mut self, + rejection: Rejection, + config: &LearningConfig, + repository: &Repository<'_>, + ask: impl FnOnce(&Rejection) -> bool + Send + 'static, + ) { + match config.mode { + LearningMode::Off => {} + LearningMode::Automatic => remember(repository, &rejection, config), + LearningMode::Ask if self.pending.is_none() => { + let (send, receive) = mpsc::channel(); + match std::thread::Builder::new() + .name("autofix-learning".into()) + .spawn(move || { + let accepted = ask(&rejection); + let _ = send.send(accepted.then_some(rejection)); + }) { + Ok(_) => { + self.pending = Some(PendingConsent { + config: config.clone(), + receive, + cancelled: false, + }) + } + Err(_) => tracing::warn!("learning prompt unavailable"), + } + } + LearningMode::Ask => {} + } + } + + /// Changing settings cancels pending consent; refusals never persist text. + pub(crate) fn poll(&mut self, config: &LearningConfig, repository: &Repository<'_>) { + let Some(pending) = &mut self.pending else { + return; + }; + pending.cancelled |= pending.config != *config; + let cancelled = pending.cancelled; + match pending.receive.try_recv() { + Ok(rejection) => { + self.pending = None; + if let Some(rejection) = rejection.filter(|_| !cancelled) { + remember(repository, &rejection, config); + } + } + Err(mpsc::TryRecvError::Disconnected) => self.pending = None, + Err(mpsc::TryRecvError::Empty) => {} + } + } +} + +fn remember(repository: &Repository<'_>, rejection: &Rejection, config: &LearningConfig) { + if repository.remember(rejection, config).is_err() { + tracing::warn!("learning could not save exclusion"); + } +} + +fn confirm(rejection: &Rejection) -> bool { + use windows_sys::Win32::UI::WindowsAndMessaging::{ + MessageBoxW, IDYES, MB_DEFBUTTON2, MB_YESNO, + }; + let text: Vec = format!( + "Don't correct this again?\n\n{} → {}", + rejection.original, rejection.corrected + ) + .encode_utf16() + .chain(Some(0)) + .collect(); + let title: Vec = "AutoFix".encode_utf16().chain(Some(0)).collect(); + unsafe { + MessageBoxW( + std::ptr::null_mut(), + text.as_ptr(), + title.as_ptr(), + MB_YESNO | MB_DEFBUTTON2, + ) == IDYES + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{correction::LanguageInfo, storage::Database}; + fn rejection() -> Rejection { + Rejection::from_undo( + "I typed teh today", + "I typed the today", + Some("en".into()), + "Notepad.EXE".into(), + ) + .unwrap() + } + fn terms(db: &Database) -> usize { + let p = db + .dictionary() + .policy( + "notepad.exe", + &LanguageInfo { + primary_language: Some("en".into()), + detected_languages: vec!["en".into()], + }, + ) + .unwrap(); + p.terms.len() + } + + #[test] + fn extracts_complete_changed_words_and_unicode_phrases() { + assert_eq!(rejection().original, "teh"); + assert_eq!(rejection().corrected, "the"); + let r = + Rejection::from_undo("é teh wierd!", "é the weird!", None, "app.exe".into()).unwrap(); + assert_eq!( + (r.original.as_str(), r.corrected.as_str()), + ("teh wierd", "the weird") + ); + assert!(Rejection::from_undo("abc", "abc", None, "".into()).is_none()); + assert!(Rejection::from_undo("", "abc", None, "".into()).is_none()); + for (original, corrected, expected_original, expected_corrected) in [ + ("hello", "hello.", "hello", "hello."), + ("very very", "very", "very very", "very"), + ("two words", "two words", "two words", "two words"), + ("cant", "can't", "cant", "can't"), + ] { + let r = Rejection::from_undo(original, corrected, None, "app.exe".into()).unwrap(); + assert_eq!( + (r.original.as_str(), r.corrected.as_str()), + (expected_original, expected_corrected) + ); + } + } + + #[test] + fn default_undo_never_writes_or_prompts_and_automatic_deduplicates() { + let db = Database::open_memory().unwrap(); + let mut learner = Learner::default(); + learner.rejected_with( + rejection(), + &LearningConfig::default(), + &db.dictionary(), + |_| panic!("default must not ask"), + ); + assert_eq!(terms(&db), 0); + let config = LearningConfig { + mode: LearningMode::Automatic, + rule: crate::settings::LearningRule::Dictionary, + per_app: true, + }; + learner.rejected_with(rejection(), &config, &db.dictionary(), |_| { + panic!("automatic must not ask") + }); + learner.rejected_with(rejection(), &config, &db.dictionary(), |_| panic!()); + assert_eq!(terms(&db), 1); + } + + #[test] + fn ask_requires_consent_and_cancels_when_disabled() { + let db = Database::open_memory().unwrap(); + let mut learner = Learner::default(); + let config = LearningConfig { + mode: LearningMode::Ask, + rule: crate::settings::LearningRule::Dictionary, + per_app: false, + }; + for accepted in [false, true] { + learner.rejected_with(rejection(), &config, &db.dictionary(), move |_| accepted); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while learner.pending.is_some() && std::time::Instant::now() < deadline { + learner.poll(&config, &db.dictionary()); + std::thread::yield_now(); + } + assert!(learner.pending.is_none()); + assert_eq!(terms(&db), usize::from(accepted)); + } + let (release, wait) = mpsc::channel(); + let mut other = rejection(); + other.original = "wierd".into(); + learner.rejected_with(other, &config, &db.dictionary(), move |_| { + wait.recv().unwrap(); + true + }); + learner.poll(&LearningConfig::default(), &db.dictionary()); + release.send(()).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while learner.pending.is_some() && std::time::Instant::now() < deadline { + learner.poll(&config, &db.dictionary()); + std::thread::yield_now(); + } + assert!(learner.pending.is_none()); + assert_eq!(terms(&db), 1); + } +} diff --git a/app-core-rust/src/dictionary/mod.rs b/app-core-rust/src/dictionary/mod.rs new file mode 100644 index 0000000..25f062b --- /dev/null +++ b/app-core-rust/src/dictionary/mod.rs @@ -0,0 +1,273 @@ +//! Persistent user exclusions. Session text enters storage only through opt-in learning. +mod learning; +#[cfg(test)] +mod tests; + +use crate::correction::{CorrectionChange, CorrectionOutput, LanguageInfo, NoChangeReason}; +use crate::settings::{LearningConfig, LearningRule}; +pub(crate) use learning::{Learner, Rejection}; +use rusqlite::{params, Connection, Result}; + +#[derive(Default)] +pub(crate) struct Policy { + pub(crate) terms: Vec, + pairs: Vec<(String, String)>, +} + +pub(crate) struct Repository<'a> { + connection: &'a Connection, +} + +impl<'a> Repository<'a> { + pub(crate) fn new(connection: &'a Connection) -> Self { + Self { connection } + } + + /// Unknown/mixed language protects all applicable entries conservatively. + pub(crate) fn policy(&self, app: &str, language: &LanguageInfo) -> Result { + let mut policy = Policy::default(); + let mut statement = self.connection.prepare( + "select language_code, entry from custom_dictionary_entries + where app_process_name is null or lower(app_process_name) = lower(?1)", + )?; + for row in statement.query_map([app], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) + })? { + let (tag, term) = row?; + if language_matches(Some(&tag), language) { + policy.terms.push(term); + } + } + let mut statement = self.connection.prepare( + "select language_code, original_text, rejected_correction from learned_correction_rules + where learning_enabled = 1 and rule_type = 'pair' and rejected_correction is not null + and (app_process_name is null or lower(app_process_name) = lower(?1))", + )?; + for row in statement.query_map([app], |row| { + Ok(( + row.get::<_, Option>(0)?, + row.get::<_, String>(1)?, + row.get::<_, String>(2)?, + )) + })? { + let (tag, original, replacement) = row?; + if language_matches(tag.as_deref(), language) { + policy.pairs.push((original, replacement)); + } + } + Ok(policy) + } + + pub(crate) fn remember(&self, rejection: &Rejection, config: &LearningConfig) -> Result<()> { + let app = config.per_app.then(|| rejection.app.to_ascii_lowercase()); + match config.rule { + LearningRule::Dictionary => { + self.connection.execute( + "insert into custom_dictionary_entries (language_code, app_process_name, entry) + select ?1, ?2, ?3 where not exists (select 1 from custom_dictionary_entries + where lower(language_code) = lower(?1) and coalesce(lower(app_process_name), '') = coalesce(?2, '') and entry = ?3)", + params![rejection.language.as_deref().unwrap_or("und"), app, rejection.original])?; + } + LearningRule::Pair => { + self.connection.execute( + "insert into learned_correction_rules + (learning_enabled, original_text, rejected_correction, rule_type, language_code, app_process_name) + select 1, ?1, ?2, 'pair', ?3, ?4 where not exists (select 1 from learned_correction_rules + where learning_enabled = 1 and rule_type = 'pair' and original_text = ?1 + and rejected_correction = ?2 and coalesce(lower(language_code), 'und') = coalesce(lower(?3), 'und') + and coalesce(lower(app_process_name), '') = coalesce(?4, ''))", + params![rejection.original, rejection.corrected, rejection.language, app])?; + } + } + Ok(()) + } +} + +fn language_matches(tag: Option<&str>, language: &LanguageInfo) -> bool { + let Some(tag) = tag else { + return true; + }; + if tag.eq_ignore_ascii_case("und") || language.is_uncertain() || language.is_mixed() { + return true; + } + language.primary_language.as_deref().is_none_or(|primary| { + tag.eq_ignore_ascii_case(primary) + || (!tag.contains('-') + && primary + .split('-') + .next() + .is_some_and(|base| tag.eq_ignore_ascii_case(base))) + }) +} + +impl Policy { + /// Remove excluded edits, preserving unrelated changes for either engine. + pub(crate) fn filter(&self, original: &str, mut output: CorrectionOutput) -> CorrectionOutput { + if !output.changes_needed { + return output; + } + let Some(changes) = output.changes.as_ref() else { + // Unstructured results cannot prove that exclusions remain untouched. + return if self.terms.is_empty() && self.pairs.is_empty() { + output + } else { + CorrectionOutput::unchanged( + original.to_owned(), + output.confidence, + NoChangeReason::AllCandidatesProtected, + output.engine_latency_ms, + ) + }; + }; + let text: Vec = original.chars().collect(); + let mut blocked = vec![false; changes.len()]; + for term in &self.terms { + for (start, end) in occurrences(&text, term) { + for (i, change) in changes.iter().enumerate() { + blocked[i] |= overlaps(change, start, end); + } + } + } + for (original, replacement) in &self.pairs { + for (start, end) in occurrences(&text, original) { + let inside: Vec<_> = changes + .iter() + .filter(|c| pair_overlaps(c, start, end)) + .cloned() + .collect(); + if inside.is_empty() { + continue; + } + if inside + .iter() + .any(|c| c.start_char < start || c.end_char > end) + { + // Broad edits can bundle the pair with other changes. Allow + // a different replacement only when unchanged context can + // be trimmed to prove a sole changed word/phrase. + for (i, change) in changes + .iter() + .enumerate() + .filter(|(_, c)| pair_overlaps(c, start, end)) + { + let isolated = Rejection::from_undo( + &change.original_text, + &change.replacement_text, + None, + String::new(), + ); + let proven_different = isolated.as_ref().is_some_and(|edit| { + edit.original.eq_ignore_ascii_case(original) + && !edit.corrected.eq_ignore_ascii_case(replacement) + }); + blocked[i] |= !proven_different; + } + continue; + } + if render(&text, start, end, &inside) + .is_some_and(|result| result.eq_ignore_ascii_case(replacement)) + { + for (i, change) in changes.iter().enumerate() { + blocked[i] |= pair_overlaps(change, start, end); + } + } + } + } + if !blocked.iter().any(|b| *b) { + return output; + } + let kept: Vec<_> = changes + .iter() + .enumerate() + .filter(|(i, _)| !blocked[*i]) + .map(|(_, c)| c.clone()) + .collect(); + if kept.is_empty() { + return CorrectionOutput::unchanged( + original.to_owned(), + output.confidence, + NoChangeReason::AllCandidatesProtected, + output.engine_latency_ms, + ); + } + let Some(corrected) = render(&text, 0, text.len(), &kept) else { + return CorrectionOutput::unchanged( + original.to_owned(), + output.confidence, + NoChangeReason::AllCandidatesProtected, + output.engine_latency_ms, + ); + }; + output.corrected_executable_text = corrected; + output.changes = Some(kept); + output + } +} + +fn overlaps(change: &CorrectionChange, start: usize, end: usize) -> bool { + if change.start_char == change.end_char { + change.start_char > start && change.start_char < end + } else { + change.start_char < end && change.end_char > start + } +} + +fn pair_overlaps(change: &CorrectionChange, start: usize, end: usize) -> bool { + if change.start_char == change.end_char { + change.start_char >= start && change.start_char <= end + } else { + overlaps(change, start, end) + } +} + +fn occurrences(text: &[char], term: &str) -> Vec<(usize, usize)> { + let term: Vec = term.chars().collect(); + if term.is_empty() || term.len() > text.len() { + return Vec::new(); + } + (0..=text.len() - term.len()) + .filter_map(|start| { + let end = start + term.len(); + (text[start..end] + .iter() + .zip(&term) + .all(|(a, b)| a.eq_ignore_ascii_case(b)) + && (start == 0 || !word_char(text[start - 1]) || !word_char(term[0])) + && (end == text.len() + || !word_char(text[end]) + || !word_char(*term.last().unwrap()))) + .then_some((start, end)) + }) + .collect() +} + +fn word_char(c: char) -> bool { + c.is_alphanumeric() || c == '_' || c == '\'' +} + +fn render(text: &[char], start: usize, end: usize, changes: &[CorrectionChange]) -> Option { + let mut sorted: Vec<_> = changes.iter().collect(); + sorted.sort_by_key(|c| c.start_char); + let mut cursor = start; + let mut result = String::new(); + for change in sorted { + if change.start_char < cursor + || change.end_char < change.start_char + || change.end_char > end + { + return None; + } + if text[change.start_char..change.end_char] + .iter() + .collect::() + != change.original_text + { + return None; + } + result.extend(&text[cursor..change.start_char]); + result.push_str(&change.replacement_text); + cursor = change.end_char; + } + result.extend(&text[cursor..end]); + Some(result) +} diff --git a/app-core-rust/src/dictionary/tests.rs b/app-core-rust/src/dictionary/tests.rs new file mode 100644 index 0000000..336698c --- /dev/null +++ b/app-core-rust/src/dictionary/tests.rs @@ -0,0 +1,239 @@ +use super::*; +use crate::{ + correction::{ConfidenceTier, CorrectionChangeKind}, + settings::{LearningMode, LearningRule}, + storage::Database, +}; + +fn language(tag: Option<&str>) -> LanguageInfo { + LanguageInfo { + primary_language: tag.map(str::to_owned), + detected_languages: tag.map(|t| vec![t.to_owned()]).unwrap_or_default(), + } +} +fn change(start: usize, end: usize, from: &str, to: &str) -> CorrectionChange { + CorrectionChange { + start_char: start, + end_char: end, + original_text: from.into(), + replacement_text: to.into(), + kind: CorrectionChangeKind::Typo, + explanation: None, + } +} +fn output(text: &str, edits: Vec) -> CorrectionOutput { + let mut out = CorrectionOutput::changed(text.into(), ConfidenceTier::High, Some(edits), 1); + out.behavior = crate::correction::ConfidenceBehavior::Silent; + out +} + +#[test] +fn sqlite_scopes_language_and_apps_and_preserves_unknown_language() { + let db = Database::open_memory().unwrap(); + let config = LearningConfig { + mode: LearningMode::Automatic, + rule: LearningRule::Dictionary, + per_app: true, + }; + db.dictionary() + .remember( + &Rejection { + original: "teh phrase".into(), + corrected: "the phrase".into(), + language: Some("en".into()), + app: "Notepad.EXE".into(), + }, + &config, + ) + .unwrap(); + assert_eq!( + db.dictionary() + .policy("notepad.exe", &language(Some("en-US"))) + .unwrap() + .terms, + ["teh phrase"] + ); + assert!(db + .dictionary() + .policy("other.exe", &language(Some("en"))) + .unwrap() + .terms + .is_empty()); + assert!(db + .dictionary() + .policy("notepad.exe", &language(Some("fr"))) + .unwrap() + .terms + .is_empty()); + assert_eq!( + db.dictionary() + .policy("notepad.exe", &language(None)) + .unwrap() + .terms + .len(), + 1 + ); +} + +#[test] +fn protects_whole_phrases_without_matching_inside_words_and_keeps_other_edits() { + let policy = Policy { + terms: vec!["teh phrase".into()], + pairs: vec![], + }; + let source = "é teh phrase wierd"; + let out = output( + "é the phrase weird", + vec![change(2, 5, "teh", "the"), change(13, 18, "wierd", "weird")], + ); + assert_eq!( + policy.filter(source, out).corrected_executable_text, + "é teh phrase weird" + ); + let policy = Policy { + terms: vec!["teh".into()], + pairs: vec![], + }; + let out = output("thex", vec![change(0, 4, "tehx", "thex")]); + assert_eq!(policy.filter("tehx", out).corrected_executable_text, "thex"); +} + +#[test] +fn pair_blocks_only_rejected_replacement_and_supports_multiple_edits_in_phrase() { + let policy = Policy { + terms: vec![], + pairs: vec![("teh".into(), "the".into())], + }; + let out = output( + "the weird", + vec![change(0, 3, "teh", "the"), change(4, 9, "wierd", "weird")], + ); + assert_eq!( + policy.filter("teh wierd", out).corrected_executable_text, + "teh weird" + ); + let out = output("ten", vec![change(0, 3, "teh", "ten")]); + assert_eq!(policy.filter("teh", out).corrected_executable_text, "ten"); + assert!( + !policy + .filter( + "I teh today", + output( + "I the today", + vec![change(0, 11, "I teh today", "I the today")] + ) + ) + .changes_needed + ); + assert_eq!( + policy + .filter( + "I teh today", + output( + "I ten today", + vec![change(0, 11, "I teh today", "I ten today")] + ) + ) + .corrected_executable_text, + "I ten today" + ); + assert!( + !policy + .filter( + "teh wierd", + output("the weird", vec![change(0, 9, "teh wierd", "the weird")]) + ) + .changes_needed + ); + let policy = Policy { + terms: vec![], + pairs: vec![("teh wierd".into(), "the weird".into())], + }; + let out = output( + "the weird", + vec![change(0, 3, "teh", "the"), change(4, 9, "wierd", "weird")], + ); + assert!(!policy.filter("teh wierd", out).changes_needed); +} + +#[test] +fn insertion_and_deletion_rules_are_enforced() { + let policy = Policy { + terms: vec![], + pairs: vec![ + ("cant".into(), "can't".into()), + ("very very".into(), "very".into()), + ], + }; + assert!( + !policy + .filter("cant", output("can't", vec![change(3, 3, "", "'")])) + .changes_needed + ); + assert!( + !policy + .filter("very very", output("very", vec![change(4, 9, " very", "")])) + .changes_needed + ); + let policy = Policy { + terms: vec![], + pairs: vec![("hello".into(), "hello.".into())], + }; + assert!( + !policy + .filter("hello", output("hello.", vec![change(5, 5, "", ".")])) + .changes_needed + ); +} + +#[test] +fn active_pairs_work_when_learning_is_disabled_and_deduplicate() { + let db = Database::open_memory().unwrap(); + let rejection = Rejection { + original: "teh".into(), + corrected: "the".into(), + language: Some("en".into()), + app: "app.exe".into(), + }; + let config = LearningConfig { + mode: LearningMode::Automatic, + ..LearningConfig::default() + }; + db.dictionary().remember(&rejection, &config).unwrap(); + db.dictionary().remember(&rejection, &config).unwrap(); + let policy = db + .dictionary() + .policy("app.exe", &language(Some("en"))) + .unwrap(); + assert_eq!(policy.pairs.len(), 1); + assert!( + !policy + .filter("teh", output("the", vec![change(0, 3, "teh", "the")])) + .changes_needed + ); +} + +#[test] +fn engine_migrates_database_created_by_settings_first() { + // File-backed migration is exercised through the production Database entry point. + let path = std::env::temp_dir().join(format!( + "autofix-dictionary-{}.sqlite", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let file = Connection::open(&path).unwrap(); + file.execute_batch("create table custom_dictionary_entries (id integer primary key, language_code text not null, app_process_name text, entry text not null, created_at text not null default current_timestamp, unique(language_code,app_process_name,entry)); insert into custom_dictionary_entries(language_code,entry) values ('en','teh');").unwrap(); + drop(file); + let db = Database::open(&path).unwrap(); + assert_eq!( + db.dictionary() + .policy("app.exe", &language(Some("en"))) + .unwrap() + .terms, + ["teh"] + ); + drop(db); + std::fs::remove_file(path).unwrap(); +} diff --git a/app-core-rust/src/lib.rs b/app-core-rust/src/lib.rs index dc22f7d..96d3e37 100644 --- a/app-core-rust/src/lib.rs +++ b/app-core-rust/src/lib.rs @@ -1,5 +1,6 @@ mod background; pub mod correction; +mod dictionary; mod ipc; mod settings; mod storage; diff --git a/app-core-rust/src/settings/mod.rs b/app-core-rust/src/settings/mod.rs index 2dbe52a..9af501c 100644 --- a/app-core-rust/src/settings/mod.rs +++ b/app-core-rust/src/settings/mod.rs @@ -7,7 +7,8 @@ mod validation; pub(crate) use crate::correction::CorrectionMode; pub(crate) use model::{ - AppConfig, ContextConfig, CorrectionEngine, PendingQueueFullBehavior, RunMode, + AppConfig, ContextConfig, CorrectionEngine, LearningConfig, LearningMode, LearningRule, + PendingQueueFullBehavior, RunMode, }; pub(crate) use shortcuts::{Shortcut, ShortcutKey}; pub(crate) use toml_io::{load_config, save_config, ConfigIoError}; diff --git a/app-core-rust/src/settings/model.rs b/app-core-rust/src/settings/model.rs index bbeedf5..5972867 100644 --- a/app-core-rust/src/settings/model.rs +++ b/app-core-rust/src/settings/model.rs @@ -16,11 +16,40 @@ pub(crate) struct AppConfig { pub(crate) correction: CorrectionConfig, #[serde(default)] pub(crate) replacement: ReplacementConfig, + #[serde(default)] + pub(crate) learning: LearningConfig, pub(crate) api: ApiConfig, pub(crate) feedback: FeedbackConfig, pub(crate) logging: LoggingConfig, } +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +pub(crate) struct LearningConfig { + #[serde(default)] + pub(crate) mode: LearningMode, + #[serde(default)] + pub(crate) rule: LearningRule, + #[serde(default)] + pub(crate) per_app: bool, +} + +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum LearningMode { + #[default] + Off, + Ask, + Automatic, +} + +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum LearningRule { + Dictionary, + #[default] + Pair, +} + impl AppConfig { /// Snapshot confidence settings, honoring the user's suggestion preference. pub(crate) fn confidence_behavior(&self) -> ConfidenceBehaviorSettings { diff --git a/app-core-rust/src/settings/tests.rs b/app-core-rust/src/settings/tests.rs index 389e8c9..af94d6d 100644 --- a/app-core-rust/src/settings/tests.rs +++ b/app-core-rust/src/settings/tests.rs @@ -10,6 +10,40 @@ use super::{ AppConfig, ValidateConfig, }; +#[test] +fn learning_is_opt_in_and_round_trips_with_legacy_defaults() { + use super::{LearningMode, LearningRule}; + let mut config = AppConfig::default(); + assert_eq!(config.learning.mode, LearningMode::Off); + for mode in [ + LearningMode::Off, + LearningMode::Ask, + LearningMode::Automatic, + ] { + for rule in [LearningRule::Dictionary, LearningRule::Pair] { + config.learning.mode = mode; + config.learning.rule = rule; + config.learning.per_app = true; + let encoded = config_to_toml(&config).unwrap(); + assert_eq!( + super::toml_io::parse_config(&encoded).unwrap().learning, + config.learning + ); + } + } + let mut document = toml::Value::try_from(&config).unwrap(); + document.as_table_mut().unwrap().remove("learning"); + let legacy = toml::to_string(&document).unwrap(); + assert_eq!( + super::toml_io::parse_config(&legacy).unwrap().learning.mode, + LearningMode::Off + ); + assert!(super::toml_io::parse_config( + &legacy.replace("[general]", "[learning]\nmode = 'invalid'\n[general]") + ) + .is_err()); +} + #[test] fn clipboard_preference_round_trips_and_legacy_configs_keep_default() { let mut config = AppConfig::default(); diff --git a/app-core-rust/src/storage.rs b/app-core-rust/src/storage.rs index 286ee93..b6028e3 100644 --- a/app-core-rust/src/storage.rs +++ b/app-core-rust/src/storage.rs @@ -27,6 +27,9 @@ pub(crate) struct Database { } impl Database { + pub(crate) fn dictionary(&self) -> crate::dictionary::Repository<'_> { + crate::dictionary::Repository::new(&self.connection) + } /// File identity for fresh policy reads on a separate transport connection. pub(crate) fn path(&self) -> Option<&Path> { self.connection diff --git a/app-core-rust/src/storage/migrations.rs b/app-core-rust/src/storage/migrations.rs index 14c65fc..8fdf264 100644 --- a/app-core-rust/src/storage/migrations.rs +++ b/app-core-rust/src/storage/migrations.rs @@ -169,7 +169,7 @@ fn current_version(connection: &Connection) -> Result { fn migrate_to_v1(connection: &Connection) -> Result<()> { connection.execute_batch( " - create table app_rules ( + create table if not exists app_rules ( id integer primary key, process_name text not null, window_title_pattern text not null default '', @@ -184,7 +184,7 @@ fn migrate_to_v1(connection: &Connection) -> Result<()> { unique (process_name, window_title_pattern) ); - create table custom_dictionary_entries ( + create table if not exists custom_dictionary_entries ( id integer primary key, language_code text not null, app_process_name text, @@ -193,7 +193,7 @@ fn migrate_to_v1(connection: &Connection) -> Result<()> { unique (language_code, app_process_name, entry) ); - create table learned_correction_rules ( + create table if not exists learned_correction_rules ( id integer primary key, learning_enabled integer not null default 0 check (learning_enabled in (0, 1)), original_text text not null, diff --git a/shared-schema/README.md b/shared-schema/README.md index 36f62d7..34f33e8 100644 --- a/shared-schema/README.md +++ b/shared-schema/README.md @@ -10,6 +10,20 @@ 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. +`[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. +Learning changes only future exclusions after successful app-level undo. +Exclusions remain active independently of these settings. + +The WPF editor and Rust engine share `custom_dictionary_entries` and +`learned_correction_rules` in `autofix.sqlite`. Null app scope means all apps; +`und` dictionary language and null/`und` pair language mean all languages. +Active pairs use `learning_enabled = 1` and `rule_type = 'pair'`. SQLite row IDs +identify editor updates and deletes; dictionary/rule edits use transactions. +The engine owns migration versions and accepts tables initialized by settings. +No dictionary IPC is required: the settings editor writes the same local database. + Confidence settings retain the existing TOML values: `silent`, `suggestion`, and `do_nothing`. High defaults to `silent`, medium to `suggestion`, and low is fixed to `do_nothing`. In v1, medium `suggestion` means manual-only with available diff --git a/ui/settings-ui-tests/AutoFix.SettingsUi.Tests.csproj b/ui/settings-ui-tests/AutoFix.SettingsUi.Tests.csproj index 0c2deea..9d96ced 100644 --- a/ui/settings-ui-tests/AutoFix.SettingsUi.Tests.csproj +++ b/ui/settings-ui-tests/AutoFix.SettingsUi.Tests.csproj @@ -2,6 +2,7 @@ net8.0-windows + true enable enable @@ -22,6 +23,7 @@ + diff --git a/ui/settings-ui-tests/DictionaryStorageTests.cs b/ui/settings-ui-tests/DictionaryStorageTests.cs new file mode 100644 index 0000000..284b1cc --- /dev/null +++ b/ui/settings-ui-tests/DictionaryStorageTests.cs @@ -0,0 +1,84 @@ +using AutoFix.SettingsUi.Models; +using AutoFix.SettingsUi.Settings; +using AutoFix.SettingsUi.ViewModels; + +namespace AutoFix.SettingsUi.Tests; + +[TestClass] +public sealed class DictionaryStorageTests +{ + [TestMethod] + public void WordsPhrasesScopesAndPairsRoundTripAndRemainUnique() + { + using var fixture = TempConfigFixture.Create(); + var storage = new DictionaryStorage(Path.Combine(fixture.Root, "autofix.sqlite")); + storage.Save(new DictionaryItem { Word = "teh phrase", Language = "en", Source = "dictionary" }); + storage.Save(new DictionaryItem { Word = "teh phrase", Language = "EN", Source = "dictionary" }); + storage.Save(new DictionaryItem { Word = "teh", Language = "en-US", App = "Notepad.EXE", Source = "pair", Replacement = "the" }); + var rows = storage.List(); + Assert.AreEqual(2, rows.Count); + var pair = rows.Single(e => e.Source == "pair"); + Assert.AreEqual("notepad.exe", pair.App); + Assert.AreEqual("the", pair.Replacement); + Assert.AreEqual("en-US", pair.Language); + storage.Save(new DictionaryItem { Word = "wierd", Language = "und", Source = "dictionary" }, pair); + rows = storage.List(); + Assert.AreEqual(2, rows.Count); + Assert.IsTrue(rows.All(e => e.Source == "dictionary")); + storage.Delete(rows.Single(e => e.Word == "wierd")); + Assert.AreEqual(1, storage.List().Count); + } + + [TestMethod] + public void InvalidEditPreservesExistingEntry() + { + using var fixture = TempConfigFixture.Create(); + var storage = new DictionaryStorage(Path.Combine(fixture.Root, "autofix.sqlite")); + storage.Save(new DictionaryItem { Word = "teh", Language = "en", Source = "dictionary" }); + var row = storage.List().Single(); + foreach (var bad in new[] { + new DictionaryItem { Word = "", Language = "en", Source = "dictionary" }, + new DictionaryItem { Word = "teh", Language = "English-US-!", Source = "dictionary" }, + new DictionaryItem { Word = "teh", Language = "en", Source = "dictionary", App = @"C:\app.exe" }, + new DictionaryItem { Word = "teh", Language = "en", Source = "pair", Replacement = "teh" } }) + { + Assert.ThrowsException(() => storage.Save(bad, row)); + Assert.AreEqual("teh", storage.List().Single().Word); + } + } + + [TestMethod] + public void EmptyDictionaryEditorStaysVisibleAndLearningDefaultsOff() + { + var section = SettingsSkeleton.CreateSections().Single(s => s.ShowsDictionary); + Assert.IsTrue(section.HasDictionary); + Assert.AreEqual(0, section.Dictionary.Count); + Assert.AreEqual("off", section.Settings.Single(s => s.Path == "learning.mode").SelectedValue); + Assert.AreEqual("pair", section.Settings.Single(s => s.Path == "learning.rule").SelectedValue); + } + + [TestMethod] + public void LearningChoicesPersistAndLegacyConfigDefaultsOff() + { + using var fixture = TempConfigFixture.Create(); + var config = AppConfig.Default(); + foreach (var mode in new[] { "off", "ask", "automatic" }) + foreach (var rule in new[] { "dictionary", "pair" }) + { + config.Learning.Mode = mode; config.Learning.Rule = rule; config.Learning.PerApp = true; + var mapped = ConfigFormMapper.BuildConfig(SettingsSkeleton.CreateSections(config)); + fixture.Storage.Save(mapped); + var loaded = fixture.Storage.Load(fixture.Path); + Assert.AreEqual(mode, loaded.Learning.Mode); + Assert.AreEqual(rule, loaded.Learning.Rule); + Assert.IsTrue(loaded.Learning.PerApp); + } + var toml = File.ReadAllText(fixture.Path); + var start = toml.IndexOf("[learning]", StringComparison.Ordinal); + var end = toml.IndexOf('[', start + 1); + File.WriteAllText(fixture.Path, end < 0 ? toml[..start] : toml.Remove(start, end-start)); + Assert.AreEqual("off", fixture.Storage.Load(fixture.Path).Learning.Mode); + config.Learning.Mode = "unknown"; + Assert.ThrowsException(() => ConfigValidator.Validate(config)); + } +} diff --git a/ui/settings-ui-tests/MainWindowViewModelTests.cs b/ui/settings-ui-tests/MainWindowViewModelTests.cs index 3162963..eae41bd 100644 --- a/ui/settings-ui-tests/MainWindowViewModelTests.cs +++ b/ui/settings-ui-tests/MainWindowViewModelTests.cs @@ -7,6 +7,94 @@ namespace AutoFix.SettingsUi.Tests; [TestClass] public sealed class MainWindowViewModelTests { + [TestMethod] + public void DictionaryWindowEditsScopedPairsAndPreservesInvalidEdits() + { + 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 storage = new DictionaryStorage(Path.Combine(fixture.Root, "autofix.sqlite")); + var viewModel = new MainWindowViewModel(new FakeBackgroundIpcClient(), fixture.Storage, + new AppRuleStorage(Path.Combine(fixture.Root, "autofix.sqlite")), new NullConfigFileDialog(), new FakeApiKeyStatus(false), new FakeStartupRegistration()); + window = new MainWindow(viewModel) { ShowActivated = false, Left = -10000, Top = -10000, Width = 1080, Height = 1150 }; + window.Show(); + viewModel.SelectedSection = viewModel.Sections.Single(s => s.ShowsDictionary); + viewModel.DictionaryKind = "pair"; + Pump(); + var boxes = Descendants(window).OfType().ToArray(); + void Type(string name, string text) => boxes.Single(b => System.Windows.Automation.AutomationProperties.GetName(b) == name) + .SetCurrentValue(System.Windows.Controls.TextBox.TextProperty, text); + void Click(string content) + { + var button = Descendants(window).OfType().Single(b => Equals(b.Content, content)); + Assert.IsNotNull(button.Command); + button.Command.Execute(button.CommandParameter); + Pump(); + } + Type("Dictionary word or phrase", "teh phrase"); + Type("Blocked replacement", "the phrase"); + Type("Dictionary language", "en-US"); + Type("Dictionary app scope", "Notepad.EXE"); + Click("Save entry"); + var row = storage.List().Single(); + Assert.AreEqual("teh phrase", row.Word); + Assert.AreEqual("the phrase", row.Replacement); + Assert.AreEqual("notepad.exe", row.App); + var grid = Descendants(window).OfType().Single(g => System.Windows.Automation.AutomationProperties.GetName(g) == "Dictionary"); + grid.SelectedItem = grid.Items[0]; + Pump(); + Assert.AreEqual("teh phrase", viewModel.DictionaryWord); + Assert.IsTrue(viewModel.IsPairRule); + var preview = Environment.GetEnvironmentVariable("AUTOFIX_SETTINGS_PREVIEW"); + if (!string.IsNullOrEmpty(preview)) + { + window.UpdateLayout(); + var bitmap = new System.Windows.Media.Imaging.RenderTargetBitmap((int)window.ActualWidth, (int)window.ActualHeight, 96, 96, System.Windows.Media.PixelFormats.Pbgra32); + bitmap.Render(window); + var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder(); + encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmap)); + using var file = File.Create(preview); encoder.Save(file); + } + Type("Dictionary language", "invalid-!"); + Click("Save entry"); + Assert.AreEqual("Exclusion not saved.", viewModel.StatusTitle); + StringAssert.Contains(viewModel.DictionaryMessage, "BCP 47"); + Assert.AreEqual("en-US", storage.List().Single().Language); + Type("Dictionary language", "fr"); + Click("Save entry"); + Assert.AreEqual("fr", storage.List().Single().Language); + grid.SelectedItem = grid.Items[0]; + Pump(); + Click("Delete selected"); + Assert.AreEqual(0, storage.List().Count); + } + catch (Exception error) { failure = error; } + finally { window?.Close(); } + }) { IsBackground = true }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + Assert.IsTrue(thread.Join(TimeSpan.FromSeconds(15)), "WPF dictionary flow timed out."); + if (failure is not null) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(failure).Throw(); + } + + private static void Pump() => System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(() => { }, System.Windows.Threading.DispatcherPriority.Background); + + private static IEnumerable Descendants(System.Windows.DependencyObject root) + { + for (var i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(root); i++) + { + var child = System.Windows.Media.VisualTreeHelper.GetChild(root, i); + yield return child; + foreach (var descendant in Descendants(child)) yield return descendant; + } + } + [TestMethod] public async Task SettingChangeSavesConfigAutomatically() { diff --git a/ui/settings-ui-tests/SettingsSkeletonTests.cs b/ui/settings-ui-tests/SettingsSkeletonTests.cs index 43b09a0..e72549d 100644 --- a/ui/settings-ui-tests/SettingsSkeletonTests.cs +++ b/ui/settings-ui-tests/SettingsSkeletonTests.cs @@ -40,6 +40,7 @@ public void CreateSectionsIncludesExpectedSettingsAreas() "Shortcuts", "Triggers", "Correction", + "Dictionary", "Engines", "Context", "Feedback", diff --git a/ui/settings-ui/MainWindow.xaml b/ui/settings-ui/MainWindow.xaml index fef5872..8a826b0 100644 --- a/ui/settings-ui/MainWindow.xaml +++ b/ui/settings-ui/MainWindow.xaml @@ -373,17 +373,42 @@ - + + + +