From d15aaca76d6bb59d787de84c73a645c78b1f1b80 Mon Sep 17 00:00:00 2001 From: Hussein Ba Ragaa Date: Sat, 3 Oct 2026 17:19:24 +0300 Subject: [PATCH 1/2] feat(triggers): complete word-count correction flow --- README.md | 18 ++ app-core-rust/README.md | 9 +- app-core-rust/src/background/pipeline.rs | 28 +- .../src/background/pipeline/tests.rs | 59 ++-- .../background/pipeline/tests/word_count.rs | 296 ++++++++++++++++++ .../src/background/replacement/tests.rs | 162 ++++++++++ app-core-rust/src/background/triggers.rs | 2 +- 7 files changed, 540 insertions(+), 34 deletions(-) create mode 100644 app-core-rust/src/background/pipeline/tests/word_count.rs diff --git a/README.md b/README.md index 34432e3..0629a9b 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,24 @@ Implemented capabilities include: - Custom dictionaries, app rules, blocklists, and allowlists. - App-level undo and secure-field blocking. +**Word-count correction** is optional and defaults to every 10 completed words. +Under **Triggers**, enable or disable it and configure the threshold. A word is +completed by whitespace; an unfinished word does not trigger correction. Only +the current executable context counts. At the threshold, AutoFix freezes that +segment and runs correction on its worker while new typing starts a fresh +executable context. App rules and secure-field blocks apply before execution +and again before replacement. Completion requires the same session and control, +an exact live pre-caret range, and no input conflict during validation or mutation. +New typing and text after the caret are preserved. + +High-confidence results apply silently by default. Medium confidence follows +the saved policy; automatic suggestion behavior currently skips because suggestion +acceptance is planned. Low confidence never applies. A verified no-change or +confidence-suppressed word-count result commits the original as informative +context and clears its pending segment without an undo entry. Changed segments +record app-level undo. Failed, timed-out, stale or unsafe work returns to executable +context for a later trigger. Logs contain metadata only. + 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. diff --git a/app-core-rust/README.md b/app-core-rust/README.md index afbef71..f7d521d 100644 --- a/app-core-rust/README.md +++ b/app-core-rust/README.md @@ -223,8 +223,13 @@ executable text. Validated no-change results from manual, word-count, character, and final-fix requests commit the original segment without replacement or an undo entry. Each accepted result logs one metadata-only event and writes a `correction_metadata` row with trigger, engine, confidence, reason, latency, and -replacement method `none`; no context text enters these logs. Failed, stale, -timed-out, unsupported-language, and confidence-suppressed results stay executable. +replacement method `none`; no context text enters these logs. Completed frozen +word-count results suppressed by the admitted confidence policy also commit the +verified original, with reason `confidence_below_configured_behavior`, no native +replacement and no undo entry. They require the same target, security and exact +live range checks as changed results. Medium automatic suggestions resolve to +skip; low confidence always skips. Other confidence-suppressed results and +failed, stale, timed-out or unsupported-language results stay executable. Exceeding `context.executable_context_max_words` (default 80) also commits the current segment, including after caret movement resolves and after a limit update. This size-limit commit logs only session and word-count metadata. New typing diff --git a/app-core-rust/src/background/pipeline.rs b/app-core-rust/src/background/pipeline.rs index 18fa6ed..adc8880 100644 --- a/app-core-rust/src/background/pipeline.rs +++ b/app-core-rust/src/background/pipeline.rs @@ -518,6 +518,22 @@ impl CorrectionPipeline { let no_change_reason = match output.no_change_reason { Some(NoChangeReason::NoCorrectionNeeded) => Some("no_correction_needed"), Some(NoChangeReason::AllCandidatesProtected) => Some("all_candidates_protected"), + // A completed word-count check may deliberately keep the original. + // Retire it only after the same live range proof as an applied edit, + // and only when the admitted policy really suppresses this tier. + Some(NoChangeReason::ConfidenceBelowConfiguredBehavior) + if active.request.trigger == TriggerKind::WordCount + && segment_id.is_some() + && output.behavior == ConfidenceBehavior::DoNothing + && output.changes.as_ref().is_some_and(Vec::is_empty) + && active.request.confidence_behavior.behavior_for( + output.confidence, + active.trigger_type, + active.suggestion_ui_available, + ) == ConfidenceBehavior::DoNothing => + { + Some("confidence_below_configured_behavior") + } _ => None, }; if output.changes_needed { @@ -668,10 +684,14 @@ impl CorrectionPipeline { ); } else if completed { self.feedback_event = Some(( - Event::Skipped(if no_change_reason == Some("all_candidates_protected") { - "AutoFix: matching terms are protected." - } else { - "AutoFix: no correction needed." + Event::Skipped(match no_change_reason { + Some("all_candidates_protected") => { + "AutoFix: matching terms are protected." + } + Some("confidence_below_configured_behavior") => { + "AutoFix: confidence policy skipped this correction." + } + _ => "AutoFix: no correction needed.", }), manual, )); diff --git a/app-core-rust/src/background/pipeline/tests.rs b/app-core-rust/src/background/pipeline/tests.rs index f8ab324..aa7c096 100644 --- a/app-core-rust/src/background/pipeline/tests.rs +++ b/app-core-rust/src/background/pipeline/tests.rs @@ -8,6 +8,7 @@ use crate::background::{ use std::{cell::Cell, sync::mpsc, time::Instant}; mod manual; +mod word_count; const STAMP: InputStamp = InputStamp { position: 7, @@ -767,7 +768,7 @@ fn cancel_oldest_suppresses_late_transport_and_runs_new_segment() { #[test] fn frozen_failures_release_capacity_without_committing_engine_output() { let config = AppConfig::default(); - for failure in 0..9 { + for failure in 0..8 { let mut manager = manager(&config, "teh"); let mut pipeline = CorrectionPipeline::new().unwrap(); submit_frozen(&mut pipeline, &mut manager, &config); @@ -794,14 +795,6 @@ fn frozen_failures_release_capacity_without_committing_engine_output() { } 6 => output.behavior = ConfidenceBehavior::DoNothing, 7 => { - *output = CorrectionOutput::unchanged( - "teh".into(), - ConfidenceTier::Medium, - NoChangeReason::ConfidenceBelowConfiguredBehavior, - 0, - ) - } - 8 => { *output = CorrectionOutput::unchanged( "teh".into(), ConfidenceTier::Low, @@ -967,7 +960,8 @@ fn unchanged_commit_policy_preserves_skips_for_all_triggers() { let accepted = matches!( reason, NoChangeReason::NoCorrectionNeeded | NoChangeReason::AllCandidatesProtected - ); + ) || (trigger == TriggerKind::WordCount + && reason == NoChangeReason::ConfidenceBelowConfiguredBehavior); let calls = Cell::new(0); assert_eq!( finish(&mut pipeline, &mut manager, &config, STAMP, &calls, false), @@ -1002,10 +996,12 @@ fn unchanged_commit_policy_preserves_skips_for_all_triggers() { trigger.as_str().into(), "low".into(), "none".into(), - if reason == NoChangeReason::NoCorrectionNeeded { - "no_correction_needed" - } else { - "all_candidates_protected" + match reason { + NoChangeReason::NoCorrectionNeeded => "no_correction_needed", + NoChangeReason::ConfidenceBelowConfiguredBehavior => { + "confidence_below_configured_behavior" + } + _ => "all_candidates_protected", } .into(), 17 @@ -1470,14 +1466,10 @@ fn medium_previews_are_manual_opt_in_and_never_mutate_or_commit() { } wait_completion(&pipeline); let calls = Cell::new(0); - assert!(!finish( - &mut pipeline, - &mut manager, - &config, - STAMP, - &calls, - true - )); + assert_eq!( + finish(&mut pipeline, &mut manager, &config, STAMP, &calls, true), + automatic + ); assert_eq!(calls.get(), 0); let preview = pipeline.take_suggestion(); if let Some(preview) = &preview { @@ -1496,8 +1488,14 @@ fn medium_previews_are_manual_opt_in_and_never_mutate_or_commit() { } ); assert!(pipeline.take_suggestion().is_none()); - assert_eq!(manager.active().unwrap().editable_context(), "teh"); - assert!(manager.active().unwrap().informative_context().is_empty()); + assert_eq!( + manager.active().unwrap().editable_context(), + if automatic { "" } else { "teh" } + ); + assert_eq!( + manager.active().unwrap().informative_context(), + if automatic { "teh" } else { "" } + ); assert!(manager.active().unwrap().undo_target().is_none()); } } @@ -1593,9 +1591,10 @@ fn medium_local_results_skip_preview_or_apply_without_losing_typed_text() { wait_completion(&pipeline); let calls = Cell::new(0); let silent = configured == ConfidenceBehavior::Silent; + let committed = silent || automatic; assert_eq!( finish(&mut pipeline, &mut manager, &config, STAMP, &calls, true,), - silent + committed ); assert_eq!(calls.get(), usize::from(silent)); assert!(pipeline.take_suggestion().is_none()); @@ -1603,11 +1602,17 @@ fn medium_local_results_skip_preview_or_apply_without_losing_typed_text() { assert_eq!(session.undo_target().is_some(), silent); assert_eq!( session.informative_context(), - if silent { "accommodate" } else { "" } + if silent { + "accommodate" + } else if automatic { + "accomodate" + } else { + "" + } ); assert_eq!( session.editable_context(), - if silent { "" } else { "accomodate" } + if committed { "" } else { "accomodate" } ); } } diff --git a/app-core-rust/src/background/pipeline/tests/word_count.rs b/app-core-rust/src/background/pipeline/tests/word_count.rs new file mode 100644 index 0000000..b087140 --- /dev/null +++ b/app-core-rust/src/background/pipeline/tests/word_count.rs @@ -0,0 +1,296 @@ +//! Word-count admission, continued typing, and conservative completion as one flow. +use super::*; +use crate::background::{security, InputProcessor, PendingTrigger}; + +fn processor(config: AppConfig, pipeline: CorrectionPipeline) -> InputProcessor { + let mut processor = InputProcessor { + feedback: crate::background::feedback::Feedback::default(), + learner: crate::dictionary::Learner::default(), + pipeline, + processed_input_sequence: STAMP.sequence, + session_manager: SessionManager::new(config.context.clone()), + config, + database: crate::storage::Database::open_memory().unwrap(), + }; + processor.session_manager.focus(&target()); + processor +} + +fn type_text(processor: &mut InputProcessor, text: &str) -> Vec { + let mut pending = Vec::new(); + for character in text.chars() { + processor.track_input(TypedInput::Text(character.to_string()), &mut pending); + } + pending +} + +fn dispatch(processor: &mut InputProcessor, request: CorrectionRequest) -> bool { + processor.dispatch_trigger_with( + request, + STAMP, + || STAMP, + |trigger, config, database| { + security::check_detection( + trigger, + config, + &database.app_rules().list().unwrap(), + crate::background::target::TargetDetection::Available(target()), + ) + }, + ) +} + +/// Count only completed executable words; settings control freezing and admission. +#[test] +fn default_ten_words_optional_and_configurable() { + for (enabled, correction_enabled, threshold) in [ + (true, true, 10), + (false, true, 10), + (true, false, 10), + (true, true, 2), + ] { + let mut config = AppConfig::default(); + assert_eq!(config.triggers.word_count, 10); + config.triggers.character_trigger_enabled = false; + config.triggers.word_count_enabled = enabled; + config.triggers.word_count = threshold; + config.correction.enabled = correction_enabled; + let mut processor = processor(config, CorrectionPipeline::new().unwrap()); + processor + .session_manager + .set_informative_context("many old words never count ".into()); + let text = std::iter::repeat_n("word", usize::from(threshold)) + .collect::>() + .join(" "); + assert!(type_text(&mut processor, &text).is_empty()); + let pending = type_text(&mut processor, " "); + assert_eq!(pending.len(), usize::from(enabled && correction_enabled)); + let session = processor.session_manager.active().unwrap(); + if enabled && correction_enabled { + let request = &pending[0].request; + assert_eq!(request.trigger, TriggerKind::WordCount); + assert_eq!(request.executable_context, format!("{text} ")); + assert_eq!(request.informative_context, "many old words never count "); + assert!(session.pending_matches( + request.pending_segment_id.unwrap(), + &request.executable_context + )); + assert!(session.editable_context().is_empty()); + } else { + assert_eq!(session.editable_context(), format!("{text} ")); + } + } +} + +/// A blocked engine cannot stop typing, and each threshold owns a separate range. +#[test] +fn thresholds_freeze_separate_segments_while_worker_is_running() { + let mut config = AppConfig::default(); + config.triggers.character_trigger_enabled = false; + config.triggers.word_count = 2; + config.context.pending_queue_size = 2; + let (started_tx, started_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let pipeline = CorrectionPipeline::start(move |job| { + started_tx.send(job.input.clone()).unwrap(); + release_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + CorrectionEngines::default().correct_with(job.request.engine, &job.input) + }) + .unwrap(); + let mut processor = processor(config, pipeline); + let first = type_text(&mut processor, "teh word ").remove(0).request; + let first_id = first.pending_segment_id.unwrap(); + assert!(dispatch(&mut processor, first)); + let input = started_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + assert_eq!(input.executable_context, "teh word "); + assert!(input.informative_context.is_empty()); + // The engine remains held until after both the next threshold and new typing. + let second = type_text(&mut processor, "teh next ").remove(0).request; + let second_id = second.pending_segment_id.unwrap(); + assert_ne!(first_id, second_id); + assert_eq!(second.informative_context, "teh word "); + assert_eq!(second.executable_context, "teh next "); + assert!(dispatch(&mut processor, second)); + assert!(type_text(&mut processor, "尾 new").is_empty()); + assert_eq!( + processor + .session_manager + .active() + .unwrap() + .editable_context(), + "尾 new" + ); + let newer_stamp = InputStamp { + sequence: STAMP.sequence + 20, + ..STAMP + }; + for expected in ["the word ", "the word the next "] { + release_tx.send(()).unwrap(); + wait_completion(&processor.pipeline); + assert!(finish( + &mut processor.pipeline, + &mut processor.session_manager, + &processor.config, + newer_stamp, + &Cell::new(0), + true + )); + assert_eq!( + processor + .session_manager + .active() + .unwrap() + .informative_context(), + expected + ); + assert_eq!( + processor + .session_manager + .active() + .unwrap() + .editable_context(), + "尾 new" + ); + if expected == "the word " { + let input = started_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + assert_eq!(input.executable_context, "teh next "); + } + } + assert!(!processor.pipeline.is_correcting()); + let session = processor.session_manager.active().unwrap(); + assert!(!session.pending_matches(first_id, "teh word ")); + assert!(!session.pending_matches(second_id, "teh next ")); + assert_eq!(session.undo_target().unwrap().original, "teh next "); +} + +/// Policy/security refusal must release pending ownership without running an engine. +#[test] +fn denied_word_count_dispatch_preserves_typed_original() { + for secure in [false, true] { + let mut config = AppConfig::default(); + config.triggers.character_trigger_enabled = false; + config.triggers.word_count = 1; + let pipeline = + CorrectionPipeline::start(|_| panic!("denied request reached engine")).unwrap(); + let mut processor = processor(config, pipeline); + let rule = crate::storage::AppRule { + process_name: "notepad.exe".into(), + window_title_pattern: None, + list_behavior: "allowlist".into(), + manual_shortcut_allowed: true, + word_count_trigger_allowed: secure, + character_trigger_allowed: true, + local_engine_allowed: true, + api_engine_allowed: true, + safety_mode: "auto".into(), + prose_context_allowed: false, + }; + processor.database.app_rules().upsert(&rule).unwrap(); + let request = type_text(&mut processor, "teh ").remove(0).request; + let id = request.pending_segment_id.unwrap(); + assert!(!processor.dispatch_trigger_with( + request, + STAMP, + || STAMP, + |trigger, config, database| { + let mut target = target(); + target.is_password_or_protected = secure; + security::check_detection( + trigger, + config, + &database.app_rules().list().unwrap(), + crate::background::target::TargetDetection::Available(target), + ) + } + )); + assert!(!processor.pipeline.is_correcting()); + let session = processor.session_manager.active().unwrap(); + assert_eq!(session.editable_context(), "teh "); + assert!(!session.pending_matches(id, "teh ")); + assert!(session.informative_context().is_empty()); + } +} + +/// Policy-suppressed originals need full live validation, just like silent edits. +#[test] +fn suppressed_word_count_requires_safe_exact_range_and_matching_policy() { + for failure in 0..9 { + let mut config = AppConfig::default(); + config.correction.medium_confidence_behavior = if failure == 6 { + ConfidenceBehavior::Silent + } else { + ConfidenceBehavior::DoNothing + }; + let mut manager = manager(&config, "accomodate "); + let mut pipeline = CorrectionPipeline::start(|job| { + CorrectionOutput::unchanged( + job.input.executable_context.clone(), + ConfidenceTier::Medium, + NoChangeReason::ConfidenceBelowConfiguredBehavior, + 0, + ) + }) + .unwrap(); + let id = submit_frozen(&mut pipeline, &mut manager, &config); + manager.input(TypedInput::Text("尾".into())); + wait_completion(&pipeline); + if failure == 7 || failure == 8 { + let mut mailbox = pipeline.mailbox.0.lock().unwrap(); + let output = &mut mailbox.completion.as_mut().unwrap().output; + if failure == 7 { + output.changes = None; + } else { + output.corrected_executable_text = "accommodate ".into(); + } + } + let current = Cell::new(STAMP); + let accepted = pipeline.finish( + &mut manager, + &config.context, + || current.get(), + |_| { + let mut target = target(); + match failure { + 1 => return None, + 2 => { + target.focused_element_id = + Some(FocusedElementId::RuntimeId("other".into())) + } + 3 => target.is_password_or_protected = true, + _ => {} + } + Some(target) + }, + |_, _, _| { + if failure == 5 { + current.set(InputStamp { + sequence: STAMP.sequence + 1, + ..STAMP + }); + } + Some( + if failure == 4 { + "accommodate 尾" + } else { + "accomodate 尾" + } + .into(), + ) + }, + |_, _, _| -> bool { panic!("suppressed result must not mutate") }, + ); + assert_eq!(accepted, failure == 0, "failure {failure}"); + assert!(!pipeline.is_correcting()); + let session = manager.active().unwrap(); + assert!(!session.pending_matches(id, "accomodate ")); + assert!(session.undo_target().is_none()); + assert_eq!( + session.informative_context(), + if accepted { "accomodate " } else { "" } + ); + assert_eq!( + session.editable_context(), + if accepted { "尾" } else { "accomodate 尾" } + ); + } +} diff --git a/app-core-rust/src/background/replacement/tests.rs b/app-core-rust/src/background/replacement/tests.rs index 7fb7d8a..047ff59 100644 --- a/app-core-rust/src/background/replacement/tests.rs +++ b/app-core-rust/src/background/replacement/tests.rs @@ -639,6 +639,168 @@ fn native_edit_replacement_smoke() { } assert_eq!((caret_start as usize, caret_end as usize), (caret, caret)); } + // Exercise configured word thresholds through the runtime owner, live gates, + // real pre-caret proof, native replacement, metadata and app-level undo. + for (original, corrected, medium_silent) in [ + ("teh word ", "the word ", false), + ("hello word ", "hello word ", false), + ("accomodate word ", "accomodate word ", false), + ("accomodate word ", "accommodate word ", true), + ] { + let following = "newer"; + let initial = format!("old {original}{following} AFTER"); + let caret = format!("old {original}{following}").encode_utf16().count(); + unsafe { + SendMessageW(GetAncestor(edit as _, GA_ROOT), WM_APP + 2, 0, 0); + let text = wide(&initial); + SendMessageW(edit as _, WM_SETTEXT, 0, text.as_ptr() as isize); + SendMessageW(edit as _, EM_SETSEL, caret, caret as isize); + } + let super::super::target::TargetDetection::Available(target) = + super::super::target::detect_focused_target() + else { + panic!("test editor lost focus") + }; + let path = std::env::temp_dir().join(format!( + "autofix-native-word-count-{}-{}.sqlite", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let database = crate::storage::Database::open(&path).unwrap(); + let mut config = AppConfig::default(); + config.correction.preferred_language = Some("en".into()); + config.triggers.character_trigger_enabled = false; + config.triggers.word_count = 2; + config.correction.uncertain_language_policy = + crate::correction::UncertainLanguagePolicy::CorrectNormally; + config.replacement.clipboard_enabled = false; + if medium_silent { + config.correction.medium_confidence_behavior = ConfidenceBehavior::Silent; + } + let mut processor = super::super::InputProcessor { + feedback: super::super::feedback::Feedback::default(), + learner: crate::dictionary::Learner::default(), + pipeline: super::super::pipeline::CorrectionPipeline::with_database(&database).unwrap(), + processed_input_sequence: super::super::input_listener::current_input_sequence(), + session_manager: SessionManager::new(config.context.clone()), + config, + database, + }; + processor.session_manager.focus(&target); + processor + .session_manager + .set_informative_context("old ".into()); + let mut pending = Vec::new(); + for character in original.chars() { + processor.track_input(TypedInput::Text(character.to_string()), &mut pending); + } + assert_eq!(pending.len(), 1); + let request = pending.remove(0).request; + let id = request.pending_segment_id.unwrap(); + assert_eq!(request.trigger, TriggerKind::WordCount); + processor.dispatch_trigger(request, super::super::InputProcessor::input_stamp()); + assert!(processor.pipeline.is_correcting()); + processor.track_input(TypedInput::Text(following.into()), &mut pending); + assert!(pending.is_empty()); + assert_eq!( + processor + .session_manager + .active() + .unwrap() + .editable_context(), + following + ); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while processor.pipeline.is_correcting() { + processor.pipeline.wait_manual(); + processor.finish_correction(); + assert!( + std::time::Instant::now() < deadline, + "word-count flow did not complete" + ); + } + let mut observed = [0u16; 128]; + let length = unsafe { + SendMessageW( + edit as _, + WM_GETTEXT, + observed.len(), + observed.as_mut_ptr() as isize, + ) + }; + assert_eq!( + String::from_utf16_lossy(&observed[..length as usize]), + format!("old {corrected}{following} AFTER") + ); + let session = processor.session_manager.active().unwrap(); + assert_eq!(session.informative_context(), format!("old {corrected}")); + assert_eq!(session.editable_context(), following); + assert!(!session.pending_matches(id, original)); + assert_eq!(session.undo_target().is_some(), original != corrected); + let connection = rusqlite::Connection::open(&path).unwrap(); + let metadata: (String, String, String) = connection + .query_row( + "select trigger_type, result_reason, replacement_method from correction_metadata", + [], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .unwrap(); + assert_eq!( + metadata, + ( + "word_count".into(), + if original != corrected { + "correction_applied" + } else if original.starts_with("accomodate") { + "confidence_below_configured_behavior" + } else { + "no_correction_needed" + } + .into(), + if original != corrected { + "send_input" + } else { + "none" + } + .into(), + ) + ); + if original != corrected { + processor.process_shortcut(2); + let length = unsafe { + SendMessageW( + edit as _, + WM_GETTEXT, + observed.len(), + observed.as_mut_ptr() as isize, + ) + }; + assert_eq!( + String::from_utf16_lossy(&observed[..length as usize]), + initial + ); + assert_eq!( + processor + .session_manager + .active() + .unwrap() + .editable_context(), + following + ); + assert!(processor + .session_manager + .active() + .unwrap() + .undo_target() + .is_none()); + } + drop(connection); + drop(processor); + std::fs::remove_file(path).unwrap(); + } // Exercise the runtime shortcut owner, real security/policy gates, local // engine, native replacement, session commit, undo and metadata together. for (selected, arbitrary, allowed) in [ diff --git a/app-core-rust/src/background/triggers.rs b/app-core-rust/src/background/triggers.rs index ad3d553..721b8dd 100644 --- a/app-core-rust/src/background/triggers.rs +++ b/app-core-rust/src/background/triggers.rs @@ -101,7 +101,7 @@ pub(super) fn automatic( versions: ContextVersions, config: &AppConfig, ) -> Option { - if inserted.is_empty() || !after.ends_with(inserted) { + if !config.correction.enabled || inserted.is_empty() || !after.ends_with(inserted) { return None; } if config.triggers.character_trigger_enabled { From cf040b77a963f67c0b75cd853a69274616614c30 Mon Sep 17 00:00:00 2001 From: Hussein Ba Ragaa Date: Sat, 3 Oct 2026 17:37:40 +0300 Subject: [PATCH 2/2] feat(triggers): complete character correction flow --- README.md | 16 + app-core-rust/README.md | 11 +- app-core-rust/src/background/pipeline.rs | 8 +- .../src/background/pipeline/tests.rs | 55 ++- .../background/pipeline/tests/character.rs | 299 ++++++++++++++ .../background/pipeline/tests/word_count.rs | 39 -- .../src/background/replacement/tests.rs | 380 +++++++++++------- app-core-rust/src/background/triggers.rs | 41 +- 8 files changed, 620 insertions(+), 229 deletions(-) create mode 100644 app-core-rust/src/background/pipeline/tests/character.rs diff --git a/README.md b/README.md index 0629a9b..1c17cb7 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,22 @@ context and clears its pending segment without an undo entry. Changed segments record app-level undo. Failed, timed-out, stale or unsafe work returns to executable context for a later trigger. Logs contain metadata only. +**Character correction** is optional and defaults to `.`. Under **Triggers**, +configure the character list (for example `.`, `?`, `!`, or `。`). Configured +sequences can span keystrokes. Typing a configured boundary at the end of the +active executable context freezes that completed segment for asynchronous +correction; subsequent typing starts a new executable context. Earlier skipped +boundaries remain in the active segment so unchecked text is preserved. + +Character results use the same conservative live validation, app rules, security +blocks and confidence settings as word-count results. High confidence applies +silently by default; medium confidence follows settings and low confidence never +applies. A verified no-change or confidence skip commits the original. Corrected +or unchanged text becomes informative context, which shrinks to its configured +budget without editing the document. Failed or unsafe results stay executable. +New typing and text after the caret remain untouched; changed text supports +app-level undo, and logs contain metadata only. + 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. diff --git a/app-core-rust/README.md b/app-core-rust/README.md index f7d521d..aebf76a 100644 --- a/app-core-rust/README.md +++ b/app-core-rust/README.md @@ -224,9 +224,9 @@ and final-fix requests commit the original segment without replacement or an undo entry. Each accepted result logs one metadata-only event and writes a `correction_metadata` row with trigger, engine, confidence, reason, latency, and replacement method `none`; no context text enters these logs. Completed frozen -word-count results suppressed by the admitted confidence policy also commit the -verified original, with reason `confidence_below_configured_behavior`, no native -replacement and no undo entry. They require the same target, security and exact +word-count and character results suppressed by the admitted confidence policy +also commit the verified original, with reason `confidence_below_configured_behavior`, +no native replacement and no undo entry. They require the same target, security and exact live range checks as changed results. Medium automatic suggestions resolve to skip; low confidence always skips. Other confidence-suppressed results and failed, stale, timed-out or unsupported-language results stay executable. @@ -274,6 +274,11 @@ one active executable context and a bounded pending correction queue. includes running work. Automatic triggers freeze the current executable context before processing subsequent typing, including keys in the same input batch. New typing starts a fresh executable context while correction runs asynchronously. +The character trigger is optional, defaults to `.`, and reads its configurable +list from `triggers.characters`. Matching uses the active pre-caret text, allowing +Unicode boundaries and configured sequences entered over multiple key events. +The whole completed active segment is frozen, including earlier skipped +boundaries; informative text and already frozen text never become editable. `context.pending_queue_full_behavior` defaults to `skip_new`, which skips the new automatic trigger and retains current typing. `cancel_oldest` cancels the oldest pending request and its dependent newer requests, restores their unchecked diff --git a/app-core-rust/src/background/pipeline.rs b/app-core-rust/src/background/pipeline.rs index adc8880..73a3277 100644 --- a/app-core-rust/src/background/pipeline.rs +++ b/app-core-rust/src/background/pipeline.rs @@ -518,12 +518,14 @@ impl CorrectionPipeline { let no_change_reason = match output.no_change_reason { Some(NoChangeReason::NoCorrectionNeeded) => Some("no_correction_needed"), Some(NoChangeReason::AllCandidatesProtected) => Some("all_candidates_protected"), - // A completed word-count check may deliberately keep the original. + // A completed automatic check may deliberately keep the original. // Retire it only after the same live range proof as an applied edit, // and only when the admitted policy really suppresses this tier. Some(NoChangeReason::ConfidenceBelowConfiguredBehavior) - if active.request.trigger == TriggerKind::WordCount - && segment_id.is_some() + if matches!( + active.request.trigger, + TriggerKind::WordCount | TriggerKind::Character + ) && segment_id.is_some() && output.behavior == ConfidenceBehavior::DoNothing && output.changes.as_ref().is_some_and(Vec::is_empty) && active.request.confidence_behavior.behavior_for( diff --git a/app-core-rust/src/background/pipeline/tests.rs b/app-core-rust/src/background/pipeline/tests.rs index aa7c096..dd60c8e 100644 --- a/app-core-rust/src/background/pipeline/tests.rs +++ b/app-core-rust/src/background/pipeline/tests.rs @@ -1,15 +1,59 @@ use super::*; use crate::background::{ context_capture::SelectionCapture, + security, target::FocusedElementId, triggers, typing::{MovementSignal, TypedInput}, + InputProcessor, PendingTrigger, }; use std::{cell::Cell, sync::mpsc, time::Instant}; +mod character; mod manual; mod word_count; +/// Build the runtime input owner for automatic-trigger flow tests. +fn processor(config: AppConfig, pipeline: CorrectionPipeline) -> InputProcessor { + let mut processor = InputProcessor { + feedback: crate::background::feedback::Feedback::default(), + learner: crate::dictionary::Learner::default(), + pipeline, + processed_input_sequence: STAMP.sequence, + session_manager: SessionManager::new(config.context.clone()), + config, + database: crate::storage::Database::open_memory().unwrap(), + }; + processor.session_manager.focus(&target()); + processor +} + +/// Send translated keys individually, preserving the real trigger boundary. +fn type_text(processor: &mut InputProcessor, text: &str) -> Vec { + let mut pending = Vec::new(); + for character in text.chars() { + processor.track_input(TypedInput::Text(character.to_string()), &mut pending); + } + pending +} + +/// Dispatch with real app rules and a deterministic focused target. +fn dispatch(processor: &mut InputProcessor, request: CorrectionRequest) -> bool { + processor.dispatch_trigger_with( + request, + STAMP, + || STAMP, + |trigger, config, database| { + security::check_detection( + trigger, + config, + &database.app_rules().list().unwrap(), + crate::background::target::TargetDetection::Available(target()), + ) + }, + ) +} + const STAMP: InputStamp = InputStamp { position: 7, sequence: 12, @@ -957,11 +1001,12 @@ fn unchanged_commit_policy_preserves_skips_for_all_triggers() { reason.clone(), 17, ); - let accepted = matches!( - reason, - NoChangeReason::NoCorrectionNeeded | NoChangeReason::AllCandidatesProtected - ) || (trigger == TriggerKind::WordCount - && reason == NoChangeReason::ConfidenceBelowConfiguredBehavior); + let accepted = + matches!( + reason, + NoChangeReason::NoCorrectionNeeded | NoChangeReason::AllCandidatesProtected + ) || (matches!(trigger, TriggerKind::WordCount | TriggerKind::Character) + && reason == NoChangeReason::ConfidenceBelowConfiguredBehavior); let calls = Cell::new(0); assert_eq!( finish(&mut pipeline, &mut manager, &config, STAMP, &calls, false), diff --git a/app-core-rust/src/background/pipeline/tests/character.rs b/app-core-rust/src/background/pipeline/tests/character.rs new file mode 100644 index 0000000..890c037 --- /dev/null +++ b/app-core-rust/src/background/pipeline/tests/character.rs @@ -0,0 +1,299 @@ +//! Configured character boundaries, frozen execution, and completion policy. +use super::*; + +fn config() -> AppConfig { + let mut config = AppConfig::default(); + config.triggers.word_count_enabled = false; + config.correction.uncertain_language_policy = + crate::correction::UncertainLanguagePolicy::CorrectNormally; + config +} + +/// The default period is optional; custom Unicode and multi-key boundaries work. +#[test] +fn configured_boundaries_complete_the_active_segment() { + for (enabled, correction_enabled, boundary) in [ + (true, true, "."), + (false, true, "."), + (true, false, "."), + (true, true, "?"), + (true, true, "。"), + (true, true, "?!"), + ] { + let mut config = config(); + assert!(config.triggers.character_trigger_enabled); + assert_eq!(config.triggers.characters, ["."]); + config.triggers.character_trigger_enabled = enabled; + config.correction.enabled = correction_enabled; + config.triggers.characters = vec![boundary.into()]; + let mut processor = processor(config, CorrectionPipeline::new().unwrap()); + processor + .session_manager + .set_informative_context("old. ".into()); + assert!(type_text(&mut processor, "teh word").is_empty()); + let pending = type_text(&mut processor, boundary); + assert_eq!(pending.len(), usize::from(enabled && correction_enabled)); + let session = processor.session_manager.active().unwrap(); + let original = format!("teh word{boundary}"); + if enabled && correction_enabled { + let request = &pending[0].request; + assert_eq!(request.trigger, TriggerKind::Character); + assert_eq!(request.executable_context, original); + assert_eq!(request.informative_context, "old. "); + assert!(session.editable_context().is_empty()); + assert!(session.pending_matches(request.pending_segment_id.unwrap(), &original)); + } else { + assert_eq!(session.editable_context(), original); + } + } + let mut config = config(); + config.triggers.characters = vec!["?".into(), "!".into()]; + let mut processor = processor(config, CorrectionPipeline::new().unwrap()); + assert!(type_text(&mut processor, "teh.").is_empty()); + assert_eq!( + type_text(&mut processor, "?")[0].request.executable_context, + "teh.?" + ); +} + +/// Later sentences and unfinished typing stay independent while the engine waits. +#[test] +fn delayed_character_correction_preserves_new_segments_and_shrinks_context() { + let mut config = config(); + config.triggers.characters = vec!["?".into(), "!".into()]; + config.context.pending_queue_size = 2; + config.context.informative_context_max_chars = 12; + config.context.informative_context_min_words = 2; + let (started_tx, started_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let pipeline = CorrectionPipeline::start(move |job| { + started_tx.send(job.input.clone()).unwrap(); + release_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + CorrectionEngines::default().correct_with(job.request.engine, &job.input) + }) + .unwrap(); + let mut processor = processor(config, pipeline); + processor + .session_manager + .set_informative_context("old words. ".into()); + let first = type_text(&mut processor, "teh word?").remove(0).request; + let id = first.pending_segment_id.unwrap(); + assert!(dispatch(&mut processor, first)); + let input = started_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + assert_eq!(input.executable_context, "teh word?"); + assert_eq!(input.informative_context, "old words. "); + let second = type_text(&mut processor, " hello!").remove(0).request; + let second_id = second.pending_segment_id.unwrap(); + assert_eq!(second.informative_context, "old words. teh word?"); + assert_eq!(second.executable_context, " hello!"); + assert!(dispatch(&mut processor, second)); + assert!(type_text(&mut processor, " 尾 new").is_empty()); + let newer = InputStamp { + sequence: STAMP.sequence + 20, + ..STAMP + }; + for changed in [true, false] { + release_tx.send(()).unwrap(); + wait_completion(&processor.pipeline); + let calls = Cell::new(0); + assert!(finish( + &mut processor.pipeline, + &mut processor.session_manager, + &processor.config, + newer, + &calls, + true + )); + assert_eq!(calls.get(), usize::from(changed)); + let session = processor.session_manager.active().unwrap(); + assert_eq!(session.editable_context(), " 尾 new"); + assert!(session.informative_context().chars().count() <= 12); + assert!(session.informative_context().ends_with(if changed { + "the word?" + } else { + " hello!" + })); + assert!(!session.pending_matches(id, "teh word?")); + if changed { + assert_eq!( + started_rx + .recv_timeout(Duration::from_secs(2)) + .unwrap() + .executable_context, + " hello!" + ); + } + } + let session = processor.session_manager.active().unwrap(); + assert!(!session.pending_matches(second_id, " hello!")); + assert!(!processor.pipeline.is_correcting()); + assert_eq!(session.informative_context(), "word? hello!"); +} + +/// High confidence applies, medium follows settings, and low keeps the original. +#[test] +fn character_confidence_policy_commits_checked_text_without_applying_skips() { + for tier in [ + ConfidenceTier::High, + ConfidenceTier::Medium, + ConfidenceTier::Low, + ] { + for behavior in [ + ConfidenceBehavior::Silent, + ConfidenceBehavior::Suggestion, + ConfidenceBehavior::DoNothing, + ] { + let mut config = config(); + config.correction.medium_confidence_behavior = behavior; + let pipeline = CorrectionPipeline::start(move |job| { + let mut output = CorrectionOutput::changed("the.".into(), tier, None, 0); + let disposition = job.input.confidence_behavior.behavior_for( + tier, + job.input.trigger_type, + job.input.suggestion_ui_available, + ); + if disposition == ConfidenceBehavior::DoNothing { + output = CorrectionOutput::unchanged( + job.input.executable_context.clone(), + tier, + NoChangeReason::ConfidenceBelowConfiguredBehavior, + 0, + ); + } else { + output.behavior = disposition; + } + output + }) + .unwrap(); + let mut processor = processor(config, pipeline); + let request = type_text(&mut processor, "teh.").remove(0).request; + let id = request.pending_segment_id.unwrap(); + assert!(dispatch(&mut processor, request)); + assert!(type_text(&mut processor, " new").is_empty()); + wait_completion(&processor.pipeline); + let calls = Cell::new(0); + assert!(finish( + &mut processor.pipeline, + &mut processor.session_manager, + &processor.config, + STAMP, + &calls, + true + )); + let changed = tier == ConfidenceTier::High + || (tier == ConfidenceTier::Medium && behavior == ConfidenceBehavior::Silent); + assert_eq!(calls.get(), usize::from(changed)); + let session = processor.session_manager.active().unwrap(); + assert_eq!( + session.informative_context(), + if changed { "the." } else { "teh." } + ); + assert_eq!(session.editable_context(), " new"); + assert_eq!(session.undo_target().is_some(), changed); + assert!(!session.pending_matches(id, "teh.")); + assert!(processor.pipeline.take_suggestion().is_none()); + assert!(!processor.pipeline.is_correcting()); + } + } +} + +/// Both trigger permissions and hard field-security refusals prevent engine work. +#[test] +fn character_dispatch_respects_rules_and_security_blocks() { + for secure in [false, true] { + let pipeline = + CorrectionPipeline::start(|_| panic!("denied character request reached engine")) + .unwrap(); + let mut processor = processor(config(), pipeline); + processor + .database + .app_rules() + .upsert(&crate::storage::AppRule { + process_name: "notepad.exe".into(), + window_title_pattern: None, + list_behavior: "allowlist".into(), + manual_shortcut_allowed: true, + word_count_trigger_allowed: true, + character_trigger_allowed: secure, + local_engine_allowed: true, + api_engine_allowed: true, + safety_mode: "auto".into(), + prose_context_allowed: false, + }) + .unwrap(); + let request = type_text(&mut processor, "teh.").remove(0).request; + assert!(!processor.dispatch_trigger_with( + request, + STAMP, + || STAMP, + |trigger, config, database| { + let mut target = target(); + target.is_password_or_protected = secure; + security::check_detection( + trigger, + config, + &database.app_rules().list().unwrap(), + crate::background::target::TargetDetection::Available(target), + ) + } + )); + let session = processor.session_manager.active().unwrap(); + assert_eq!(session.editable_context(), "teh."); + assert!(session.informative_context().is_empty()); + assert!(!processor.pipeline.is_correcting()); + } +} + +/// A frozen result cannot apply to changed text, another control, or unsafe input. +#[test] +fn character_completion_rejects_conflicts_changed_control_security_and_input() { + for failure in 0..6 { + let mut processor = processor(config(), CorrectionPipeline::new().unwrap()); + let request = type_text(&mut processor, "teh.").remove(0).request; + assert!(dispatch(&mut processor, request)); + assert!(type_text(&mut processor, " new").is_empty()); + wait_completion(&processor.pipeline); + let stamp = Cell::new(STAMP); + assert!(!processor.pipeline.finish( + &mut processor.session_manager, + &processor.config.context, + || stamp.get(), + |_| { + let mut target = target(); + match failure { + 0 => return None, + 1 => { + target.focused_element_id = + Some(FocusedElementId::RuntimeId("other".into())) + } + 2 => target.is_password_or_protected = true, + 3 => target.process_id += 1, + _ => {} + } + Some(target) + }, + |_, _, _| { + if failure == 5 { + stamp.set(InputStamp { + sequence: STAMP.sequence + 1, + ..STAMP + }); + } + Some( + if failure == 4 { + "changed. new" + } else { + "teh. new" + } + .into(), + ) + }, + |_, _, _| -> bool { panic!("unsafe character result reached replacement") } + )); + let session = processor.session_manager.active().unwrap(); + assert_eq!(session.editable_context(), "teh. new"); + assert!(session.informative_context().is_empty()); + assert!(session.undo_target().is_none()); + assert!(!processor.pipeline.is_correcting()); + } +} diff --git a/app-core-rust/src/background/pipeline/tests/word_count.rs b/app-core-rust/src/background/pipeline/tests/word_count.rs index b087140..6ceb083 100644 --- a/app-core-rust/src/background/pipeline/tests/word_count.rs +++ b/app-core-rust/src/background/pipeline/tests/word_count.rs @@ -1,44 +1,5 @@ //! Word-count admission, continued typing, and conservative completion as one flow. use super::*; -use crate::background::{security, InputProcessor, PendingTrigger}; - -fn processor(config: AppConfig, pipeline: CorrectionPipeline) -> InputProcessor { - let mut processor = InputProcessor { - feedback: crate::background::feedback::Feedback::default(), - learner: crate::dictionary::Learner::default(), - pipeline, - processed_input_sequence: STAMP.sequence, - session_manager: SessionManager::new(config.context.clone()), - config, - database: crate::storage::Database::open_memory().unwrap(), - }; - processor.session_manager.focus(&target()); - processor -} - -fn type_text(processor: &mut InputProcessor, text: &str) -> Vec { - let mut pending = Vec::new(); - for character in text.chars() { - processor.track_input(TypedInput::Text(character.to_string()), &mut pending); - } - pending -} - -fn dispatch(processor: &mut InputProcessor, request: CorrectionRequest) -> bool { - processor.dispatch_trigger_with( - request, - STAMP, - || STAMP, - |trigger, config, database| { - security::check_detection( - trigger, - config, - &database.app_rules().list().unwrap(), - crate::background::target::TargetDetection::Available(target()), - ) - }, - ) -} /// Count only completed executable words; settings control freezing and admission. #[test] diff --git a/app-core-rust/src/background/replacement/tests.rs b/app-core-rust/src/background/replacement/tests.rs index 047ff59..0c151c7 100644 --- a/app-core-rust/src/background/replacement/tests.rs +++ b/app-core-rust/src/background/replacement/tests.rs @@ -382,6 +382,19 @@ fn app_undo_refuses_partially_retained_correction() { #[test] #[ignore = "requires an interactive Windows desktop; briefly focuses an isolated test editor"] fn native_edit_replacement_smoke() { + native_editor_smoke(false); +} + +#[cfg(windows)] +#[test] +#[ignore = "requires an interactive Windows desktop; briefly focuses an isolated test editor"] +fn native_automatic_trigger_smoke() { + native_editor_smoke(true); +} + +/// Share the isolated editor while allowing affected automatic flows to run alone. +#[cfg(windows)] +fn native_editor_smoke(automatic_only: bool) { const EM_SETSEL: u32 = 0x00b1; use crate::background::security::TriggerKind; use std::{ @@ -485,167 +498,209 @@ fn native_edit_replacement_smoke() { ); thread::sleep(std::time::Duration::from_millis(25)); } - // Both correction and undo use this boundary. A title-only change must - // refuse every native method while the selection and typed span stay intact. - let super::super::target::TargetDetection::Available(authorized) = - super::super::target::detect_focused_target() - else { - panic!("test editor is not available") - }; - let stale = ReplacementPlan { - target: &authorized, - original: "teh", - replacement: "the", - following: "", - selected_text: false, - stamp: InputStamp { - position: super::super::input_listener::current_position_generation(), - sequence: super::super::input_listener::current_input_sequence(), - }, - }; - unsafe { - let title = wide("Private document"); - assert_ne!( - SendMessageW( - GetAncestor(edit as _, GA_ROOT), - WM_SETTEXT, - 0, - title.as_ptr() as isize - ), - 0 - ); - } - for method in [ReplacementMethod::Clipboard, ReplacementMethod::SendInput] { - let refused = run_strategies(&stale, &mut [&mut native::NativeStrategy(method)], true); - assert!(!refused.success && !refused.may_have_changed); - assert!(refused.range.is_none()); - } - unsafe { - let title = wide("AutoFix replacement test"); - SendMessageW( - GetAncestor(edit as _, GA_ROOT), - WM_SETTEXT, - 0, - title.as_ptr() as isize, - ); - } - // Unchanged results use the real caret proof but never enter native replacement. - for trigger in [ - TriggerKind::ManualShortcut, - TriggerKind::WordCount, - TriggerKind::Character, - TriggerKind::FinalFixBeforeReanchor, - ] { - let mut config = AppConfig::default(); - config.context.informative_context_max_chars = 5; - let frozen = matches!(trigger, TriggerKind::WordCount | TriggerKind::Character); - let following = if frozen { " newer" } else { "" }; - let initial = format!("old hello{following} AFTER"); - let caret = format!("old hello{following}").encode_utf16().count(); - unsafe { - SendMessageW(GetAncestor(edit as _, GA_ROOT), WM_APP + 2, 0, 0); - let text = wide(&initial); - SendMessageW(edit as _, WM_SETTEXT, 0, text.as_ptr() as isize); - SendMessageW(edit as _, EM_SETSEL, caret, caret as isize); - } - let super::super::target::TargetDetection::Available(target) = + if !automatic_only { + // Both correction and undo use this boundary. A title-only change must + // refuse every native method while the selection and typed span stay intact. + let super::super::target::TargetDetection::Available(authorized) = super::super::target::detect_focused_target() else { - panic!("test editor lost focus") - }; - let mut manager = SessionManager::new(config.context.clone()); - manager.focus(&target); - manager.set_informative_context("old ".into()); - manager.input(TypedInput::Text("hello".into())); - let session = manager.active().unwrap(); - let mut request = super::super::triggers::manual( - session.id(), - session.informative_context(), - &session.editable_context(), - session.versions(), - &super::super::context_capture::SelectionCapture::NoSelection, - &config, - ) - .unwrap(); - request.trigger = trigger; - request.language_info = crate::correction::LanguageInfo { - primary_language: Some("en".into()), - detected_languages: vec!["en".into()], + panic!("test editor is not available") }; - if frozen { - request.pending_segment_id = manager - .active_mut() - .unwrap() - .freeze_pending(&config.context) - .0; - manager.input(TypedInput::Text(following.into())); - } - let stamp = InputStamp { - position: super::super::input_listener::current_position_generation(), - sequence: super::super::input_listener::current_input_sequence(), + let stale = ReplacementPlan { + target: &authorized, + original: "teh", + replacement: "the", + following: "", + selected_text: false, + stamp: InputStamp { + position: super::super::input_listener::current_position_generation(), + sequence: super::super::input_listener::current_input_sequence(), + }, }; - let mut pipeline = super::super::pipeline::CorrectionPipeline::new().unwrap(); - assert!(pipeline.submit( - request, - manager.active().unwrap(), - target.clone(), - stamp, - &config, - vec![] - )); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); - loop { - pipeline.wait_manual(); - if pipeline.finish( - &mut manager, - &config.context, - || stamp, - |_| Some(target.clone()), - |target, _, known| { - super::super::context_capture::read_before_caret(target, &config.context, known) - }, - |_, _, _| -> bool { panic!("unchanged result reached native replacement") }, - ) { - break; - } - assert!( - std::time::Instant::now() < deadline, - "unchanged live result did not commit: {trigger:?}" + unsafe { + let title = wide("Private document"); + assert_ne!( + SendMessageW( + GetAncestor(edit as _, GA_ROOT), + WM_SETTEXT, + 0, + title.as_ptr() as isize + ), + 0 ); } - assert_eq!(manager.active().unwrap().informative_context(), "hello"); - assert_eq!(manager.active().unwrap().editable_context(), following); - assert!(manager.active().unwrap().undo_target().is_none()); - let mut observed = [0u16; 128]; - let mut caret_start = 0u32; - let mut caret_end = 0u32; + for method in [ReplacementMethod::Clipboard, ReplacementMethod::SendInput] { + let refused = run_strategies(&stale, &mut [&mut native::NativeStrategy(method)], true); + assert!(!refused.success && !refused.may_have_changed); + assert!(refused.range.is_none()); + } unsafe { - let length = SendMessageW( - edit as _, - WM_GETTEXT, - observed.len(), - observed.as_mut_ptr() as isize, - ); - assert_eq!( - String::from_utf16_lossy(&observed[..length as usize]), - initial - ); + let title = wide("AutoFix replacement test"); SendMessageW( - edit as _, - 0x00b0, - &mut caret_start as *mut u32 as usize, - &mut caret_end as *mut u32 as isize, + GetAncestor(edit as _, GA_ROOT), + WM_SETTEXT, + 0, + title.as_ptr() as isize, ); } - assert_eq!((caret_start as usize, caret_end as usize), (caret, caret)); + // Unchanged results use the real caret proof but never enter native replacement. + for trigger in [ + TriggerKind::ManualShortcut, + TriggerKind::WordCount, + TriggerKind::Character, + TriggerKind::FinalFixBeforeReanchor, + ] { + let mut config = AppConfig::default(); + config.context.informative_context_max_chars = 5; + let frozen = matches!(trigger, TriggerKind::WordCount | TriggerKind::Character); + let following = if frozen { " newer" } else { "" }; + let initial = format!("old hello{following} AFTER"); + let caret = format!("old hello{following}").encode_utf16().count(); + unsafe { + SendMessageW(GetAncestor(edit as _, GA_ROOT), WM_APP + 2, 0, 0); + let text = wide(&initial); + SendMessageW(edit as _, WM_SETTEXT, 0, text.as_ptr() as isize); + SendMessageW(edit as _, EM_SETSEL, caret, caret as isize); + } + let super::super::target::TargetDetection::Available(target) = + super::super::target::detect_focused_target() + else { + panic!("test editor lost focus") + }; + let mut manager = SessionManager::new(config.context.clone()); + manager.focus(&target); + manager.set_informative_context("old ".into()); + manager.input(TypedInput::Text("hello".into())); + let session = manager.active().unwrap(); + let mut request = super::super::triggers::manual( + session.id(), + session.informative_context(), + &session.editable_context(), + session.versions(), + &super::super::context_capture::SelectionCapture::NoSelection, + &config, + ) + .unwrap(); + request.trigger = trigger; + request.language_info = crate::correction::LanguageInfo { + primary_language: Some("en".into()), + detected_languages: vec!["en".into()], + }; + if frozen { + request.pending_segment_id = manager + .active_mut() + .unwrap() + .freeze_pending(&config.context) + .0; + manager.input(TypedInput::Text(following.into())); + } + let stamp = InputStamp { + position: super::super::input_listener::current_position_generation(), + sequence: super::super::input_listener::current_input_sequence(), + }; + let mut pipeline = super::super::pipeline::CorrectionPipeline::new().unwrap(); + assert!(pipeline.submit( + request, + manager.active().unwrap(), + target.clone(), + stamp, + &config, + vec![] + )); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + pipeline.wait_manual(); + if pipeline.finish( + &mut manager, + &config.context, + || stamp, + |_| Some(target.clone()), + |target, _, known| { + super::super::context_capture::read_before_caret( + target, + &config.context, + known, + ) + }, + |_, _, _| -> bool { panic!("unchanged result reached native replacement") }, + ) { + break; + } + assert!( + std::time::Instant::now() < deadline, + "unchanged live result did not commit: {trigger:?}" + ); + } + assert_eq!(manager.active().unwrap().informative_context(), "hello"); + assert_eq!(manager.active().unwrap().editable_context(), following); + assert!(manager.active().unwrap().undo_target().is_none()); + let mut observed = [0u16; 128]; + let mut caret_start = 0u32; + let mut caret_end = 0u32; + unsafe { + let length = SendMessageW( + edit as _, + WM_GETTEXT, + observed.len(), + observed.as_mut_ptr() as isize, + ); + assert_eq!( + String::from_utf16_lossy(&observed[..length as usize]), + initial + ); + SendMessageW( + edit as _, + 0x00b0, + &mut caret_start as *mut u32 as usize, + &mut caret_end as *mut u32 as isize, + ); + } + assert_eq!((caret_start as usize, caret_end as usize), (caret, caret)); + } } - // Exercise configured word thresholds through the runtime owner, live gates, + // Exercise configured automatic triggers through the runtime owner, live gates, // real pre-caret proof, native replacement, metadata and app-level undo. - for (original, corrected, medium_silent) in [ - ("teh word ", "the word ", false), - ("hello word ", "hello word ", false), - ("accomodate word ", "accomodate word ", false), - ("accomodate word ", "accommodate word ", true), + for (original, corrected, medium_silent, trigger, boundary) in [ + ("teh word ", "the word ", false, TriggerKind::WordCount, "."), + ( + "hello word ", + "hello word ", + false, + TriggerKind::WordCount, + ".", + ), + ( + "accomodate word ", + "accomodate word ", + false, + TriggerKind::WordCount, + ".", + ), + ( + "accomodate word ", + "accommodate word ", + true, + TriggerKind::WordCount, + ".", + ), + ("teh.", "the.", false, TriggerKind::Character, "."), + ("hello.", "hello.", false, TriggerKind::Character, "."), + ( + "accomodate.", + "accomodate.", + false, + TriggerKind::Character, + ".", + ), + ( + "accomodate.", + "accommodate.", + true, + TriggerKind::Character, + ".", + ), + ("teh?!", "the?!", false, TriggerKind::Character, "?!"), + ("teh。", "the。", false, TriggerKind::Character, "。"), ] { let following = "newer"; let initial = format!("old {original}{following} AFTER"); @@ -662,7 +717,7 @@ fn native_edit_replacement_smoke() { panic!("test editor lost focus") }; let path = std::env::temp_dir().join(format!( - "autofix-native-word-count-{}-{}.sqlite", + "autofix-native-automatic-{}-{}.sqlite", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -672,11 +727,16 @@ fn native_edit_replacement_smoke() { let database = crate::storage::Database::open(&path).unwrap(); let mut config = AppConfig::default(); config.correction.preferred_language = Some("en".into()); - config.triggers.character_trigger_enabled = false; + config.triggers.word_count_enabled = trigger == TriggerKind::WordCount; + config.triggers.character_trigger_enabled = trigger == TriggerKind::Character; + config.triggers.characters = vec![boundary.into()]; config.triggers.word_count = 2; config.correction.uncertain_language_policy = crate::correction::UncertainLanguagePolicy::CorrectNormally; config.replacement.clipboard_enabled = false; + if trigger == TriggerKind::Character { + config.context.informative_context_max_chars = corrected.chars().count() as u32; + } if medium_silent { config.correction.medium_confidence_behavior = ConfidenceBehavior::Silent; } @@ -700,7 +760,7 @@ fn native_edit_replacement_smoke() { assert_eq!(pending.len(), 1); let request = pending.remove(0).request; let id = request.pending_segment_id.unwrap(); - assert_eq!(request.trigger, TriggerKind::WordCount); + assert_eq!(request.trigger, trigger); processor.dispatch_trigger(request, super::super::InputProcessor::input_stamp()); assert!(processor.pipeline.is_correcting()); processor.track_input(TypedInput::Text(following.into()), &mut pending); @@ -719,7 +779,7 @@ fn native_edit_replacement_smoke() { processor.finish_correction(); assert!( std::time::Instant::now() < deadline, - "word-count flow did not complete" + "automatic trigger flow did not complete: {trigger:?}" ); } let mut observed = [0u16; 128]; @@ -736,7 +796,14 @@ fn native_edit_replacement_smoke() { format!("old {corrected}{following} AFTER") ); let session = processor.session_manager.active().unwrap(); - assert_eq!(session.informative_context(), format!("old {corrected}")); + assert_eq!( + session.informative_context(), + if trigger == TriggerKind::Character { + corrected.into() + } else { + format!("old {corrected}") + } + ); assert_eq!(session.editable_context(), following); assert!(!session.pending_matches(id, original)); assert_eq!(session.undo_target().is_some(), original != corrected); @@ -751,7 +818,7 @@ fn native_edit_replacement_smoke() { assert_eq!( metadata, ( - "word_count".into(), + trigger.as_str().into(), if original != corrected { "correction_applied" } else if original.starts_with("accomodate") { @@ -801,6 +868,9 @@ fn native_edit_replacement_smoke() { drop(processor); std::fs::remove_file(path).unwrap(); } + if automatic_only { + return; + } // Exercise the runtime shortcut owner, real security/policy gates, local // engine, native replacement, session commit, undo and metadata together. for (selected, arbitrary, allowed) in [ diff --git a/app-core-rust/src/background/triggers.rs b/app-core-rust/src/background/triggers.rs index 721b8dd..f5358a3 100644 --- a/app-core-rust/src/background/triggers.rs +++ b/app-core-rust/src/background/triggers.rs @@ -104,32 +104,25 @@ pub(super) fn automatic( if !config.correction.enabled || inserted.is_empty() || !after.ends_with(inserted) { return None; } - if config.triggers.character_trigger_enabled { - if let Some(boundary) = config + if config.triggers.character_trigger_enabled + && config .triggers .characters .iter() .filter(|boundary| !boundary.is_empty()) - .find(|boundary| inserted.ends_with(boundary.as_str())) - { - let preceding = &after[..after.len() - boundary.len()]; - let start = config - .triggers - .characters - .iter() - .filter(|character| !character.is_empty()) - .filter_map(|character| preceding.rfind(character).map(|at| at + character.len())) - .max() - .unwrap_or(0); - return request( - session_id, - TriggerKind::Character, - informative, - &after[start..], - versions, - config, - ); - } + .any(|boundary| after.ends_with(boundary.as_str())) + { + // A configured boundary can span multiple translated key events. + // Freeze the complete active segment, including any earlier skipped + // boundary, rather than dropping unchecked text from the request. + return request( + session_id, + TriggerKind::Character, + informative, + after, + versions, + config, + ); } if config.triggers.word_count_enabled && config.triggers.word_count > 0 { let threshold = usize::from(config.triggers.word_count); @@ -293,7 +286,7 @@ mod tests { automatic(1, "First. Next", "First. Next.", ".", "", v, &config) .unwrap() .executable_context, - " Next." + "First. Next." ); config.triggers.character_trigger_enabled = false; config.triggers.word_count_enabled = false; @@ -327,7 +320,7 @@ mod tests { &config, ) .unwrap(); - assert_eq!(request.executable_context, " Next?"); + assert_eq!(request.executable_context, "First! Next?"); assert!(!request.executable_context.contains("trailing")); } }