From 74d9468487eefc19d6d30c40235d81b82bfa45db Mon Sep 17 00:00:00 2001 From: Hussein Ba Ragaa Date: Sat, 3 Oct 2026 14:40:31 +0300 Subject: [PATCH 1/2] feat(correction): complete manual shortcut flow --- README.md | 19 +- app-core-rust/README.md | 31 +- .../src/background/context_capture.rs | 96 +++++ app-core-rust/src/background/mod.rs | 9 +- app-core-rust/src/background/pipeline.rs | 103 ++++-- .../src/background/pipeline/tests.rs | 30 +- .../src/background/pipeline/tests/manual.rs | 333 ++++++++++++++++++ .../src/background/replacement/mod.rs | 11 +- .../src/background/replacement/native.rs | 79 ++++- .../src/background/replacement/tests.rs | 215 ++++++++++- app-core-rust/src/background/session.rs | 43 +++ app-core-rust/src/background/tests.rs | 2 +- 12 files changed, 894 insertions(+), 77 deletions(-) create mode 100644 app-core-rust/src/background/pipeline/tests/manual.rs diff --git a/README.md b/README.md index ddba476..34432e3 100644 --- a/README.md +++ b/README.md @@ -72,8 +72,23 @@ runs. Editor automatic correction requires explicit trigger and prose opt-ins, and a whole segment of recognizable line-comment prose. Terminal automatic requests still skip because the shell context cannot be proven safe. Existing permissions survive migration; the new editor prose permission starts -off. Selected results still skip native replacement until caret-end proof is -available, and manual-only rules do not enable continuous typed-input capture. +off. Selected correction requires both UI Automation and the native caret to +prove the selection ends at the caret. Manual-only rules do not enable +continuous typed-input capture. + +The manual correction shortcut (default **Ctrl+Alt+Space**) checks security, +app rules, selection ownership and session validity before sending read-only +informative context and editable executable context to the selected engine. +Confidence policy controls whether the result applies, previews or skips. +Successful replacement changes only the proved executable span before the caret, +moves the corrected text into informative context, clears executable context, +records app-level undo and writes metadata without document text. + +Selected text must belong to the current typed segment unless **Correct arbitrary +selection** is enabled under **Shortcuts**. Even with that option, backward +selections and selections without reliable caret proof skip correction. Text after +the caret stays untouched. Unchanged or suppressed selections retain their context +and selection; suggestion acceptance remains planned. ## Run App diff --git a/app-core-rust/README.md b/app-core-rust/README.md index 647a16e..afbef71 100644 --- a/app-core-rust/README.md +++ b/app-core-rust/README.md @@ -185,8 +185,15 @@ An outside or unreadable selection blocks the shortcut by default. The `shortcuts.correct_arbitrary_selection` setting is off by default; when enabled, a selected span outside the typed segment becomes temporary executable context for that request, while text before and after it -stays informative. V1 discards selected results because it cannot prove which -selection end is the live caret. +stays informative. Selected correction requires TextPattern2 and a native caret +in the focused control. The provider caret and a TextPattern range at the native +caret must both equal the selection end; backward selections refuse correction. +Completion recaptures the selected text and its read-only anchors, and the native +replacement owner rechecks exact selection geometry before mutation. Successful +selection replacement establishes a collapsed caret, retires its preceding text +and corrected span into informative context, clears executable context and records +undo. Unselected text after the caret is never changed or promoted to executable +context. Unchanged and suppressed selections retain their original context. App rules and the hard security gate are checked before routing. Application policy must be readable: a failed app-rule read blocks capture and correction for every trigger and engine, even if dictionary reads still work. A matching app @@ -301,8 +308,8 @@ Uncertain languages and fragments skip. Editor automatic requests additionally require their trigger permission and complete `//` or `#` line-comment sentences; inline/block comments are unsupported. Terminal automatic text requests skip because the shell dialect and prompt state are unknown. Manual-only rules never -authorize tracking or final-fix triggers. Selected results retain the existing -native replacement refusal until the live caret end can be proven. +authorize tracking or final-fix triggers. Selected results require the same +independently verified caret-end proof as ordinary selected correction. Admission reads app rules through a fresh, nonblocking read-only connection without migrations or writer reservations. API sends and native replacement recheck the @@ -337,9 +344,10 @@ Before a changed result reaches replacement, completion also requires a stable focused control identity and a fresh read-only TextPattern capture. The entire known session region must match exactly at the live caret, including text typed after a frozen segment. Missing captures or mismatches discard the result; no -fuzzy search or replacement is attempted. Selected-text results are discarded -because their replacement range cannot be proven before the caret, even when -arbitrary selected-text correction is enabled. +fuzzy search or replacement is attempted. Selected-text results require a fresh +exact selection capture with native caret-end proof. Arbitrary-selection opt-in +changes only ownership admission; it never relaxes security, confidence, geometry +or post-caret protection. Failed, suppressed, or refused frozen results release their slot and restore the original text and dependent newer segments to active executable context. Their queued requests are cancelled so a later trigger can check the combined text in @@ -363,11 +371,18 @@ manual override, stale and reordered results, queued input, secure targets, failed replacement, selection boundaries, and commit/undo after confirmed replacement. +Every successful changed commit writes the same metadata-only correction event +as accepted no-change commits, including trigger, engine, confidence, replacement +method, result reason and latency. Document text and engine response details are +excluded even when full-text debug logging is enabled. Busy or unavailable storage +skips persistence without delaying input processing or losing the committed undo. + The replacement feature lives in `src/background/replacement`. Its strategy interface tries direct text APIs, UI Automation replacement, clipboard paste, then SendInput. Direct APIs/TSF and UI Automation mutation currently report unavailable and can be implemented progressively. UI Automation TextPattern -must first prove a collapsed caret, the exact executable span and any newer +must first prove a collapsed caret (or a selection ending at the native caret), +the exact executable span and any newer typed text between that span and the caret. Only that span is selected; text after the original caret remains untouched. Missing or unreliable providers refuse replacement rather than guessing a keystroke distance. diff --git a/app-core-rust/src/background/context_capture.rs b/app-core-rust/src/background/context_capture.rs index c6a5ba9..f15f502 100644 --- a/app-core-rust/src/background/context_capture.rs +++ b/app-core-rust/src/background/context_capture.rs @@ -93,6 +93,7 @@ fn selected_executable_prefix<'a>( found } +#[derive(Debug)] pub(super) enum SelectionCapture { NoSelection, Selected { @@ -106,6 +107,100 @@ pub(super) enum SelectionCapture { const MAX_SELECTED_CHARS: i32 = 4096; +/// A selection is editable only when its active caret is at the range end. +/// TextPattern's sorted endpoints alone cannot establish selection direction. +#[cfg(windows)] +pub(super) unsafe fn selected_caret( + element: &windows::Win32::UI::Accessibility::IUIAutomationElement, + selection: &windows::Win32::UI::Accessibility::IUIAutomationTextRange, +) -> windows::core::Result { + use windows::Win32::UI::Accessibility::{ + IUIAutomationTextPattern2, TextPatternRangeEndpoint_End as END, + TextPatternRangeEndpoint_Start as START, UIA_TextPattern2Id, + }; + let pattern: IUIAutomationTextPattern2 = element.GetCurrentPatternAs(UIA_TextPattern2Id)?; + let mut active = windows::core::BOOL::default(); + let caret = pattern.GetCaretRange(&mut active)?; + // Some native Edit providers report the sorted selection end for either + // direction. Independently locate the real system caret in this control. + use windows_sys::Win32::UI::WindowsAndMessaging::{ + GetGUIThreadInfo, GetWindowThreadProcessId, GUITHREADINFO, + }; + let window = element.CurrentNativeWindowHandle()?.0; + let mut process = 0; + let thread = GetWindowThreadProcessId(window as _, &mut process); + let mut info: GUITHREADINFO = std::mem::zeroed(); + info.cbSize = std::mem::size_of::() as u32; + let unavailable = + || windows::core::Error::from_hresult(windows::core::HRESULT(0x80004005u32 as i32)); + if window.is_null() + || thread == 0 + || process != element.CurrentProcessId()? as u32 + || GetGUIThreadInfo(thread, &mut info) == 0 + || info.hwndFocus != window as _ + || info.hwndCaret != window as _ + { + return Err(unavailable()); + } + let mut point = windows_sys::Win32::Foundation::POINT { + x: info.rcCaret.left, + y: info.rcCaret.top + (info.rcCaret.bottom - info.rcCaret.top) / 2, + }; + if windows_sys::Win32::Graphics::Gdi::ClientToScreen(info.hwndCaret, &mut point) == 0 { + return Err(unavailable()); + } + let native_caret = pattern.RangeFromPoint(windows::Win32::Foundation::POINT { + x: point.x, + y: point.y, + })?; + if !active.as_bool() + || caret.CompareEndpoints(START, &caret, END)? != 0 + || caret.CompareEndpoints(END, selection, END)? != 0 + || native_caret.CompareEndpoints(START, &native_caret, END)? != 0 + || native_caret.CompareEndpoints(END, selection, END)? != 0 + { + return Err(windows::core::Error::from_hresult(windows::core::HRESULT( + 0x80004005u32 as i32, + ))); + } + Ok(caret) +} + +/// Completion rechecks the exact selected span and both read-only anchors. +pub(super) fn read_correction_context( + target: &FocusedTarget, + request: &super::triggers::CorrectionRequest, + limits: &ContextConfig, + known_chars: usize, +) -> Option { + if !request.selected_text { + return read_before_caret(target, limits, known_chars); + } + let mut capture_limits = limits.clone(); + capture_limits.informative_context_max_chars = capture_limits + .informative_context_max_chars + .max(request.following_context.chars().count() as u32); + match read_selection( + target, + &request.informative_context, + &request.executable_context, + &capture_limits, + ) { + SelectionCapture::Selected { + text, + preceding, + following, + .. + } if text == request.executable_context + && preceding.ends_with(&request.informative_context) + && following.starts_with(&request.following_context) => + { + Some(format!("{preceding}{text}")) + } + _ => None, + } +} + fn capture_char_limit(limits: &ContextConfig, known_typed_chars: usize) -> i32 { (limits.informative_context_max_chars as usize) .saturating_add(known_typed_chars) @@ -262,6 +357,7 @@ pub(super) fn read_selection( if selected.is_empty() || selected.chars().count() > MAX_SELECTED_CHARS as usize { return None; } + selected_caret(&element, &selection).ok()?; let selection_at_document_start = pattern.DocumentRange().ok().is_some_and(|document| { selection diff --git a/app-core-rust/src/background/mod.rs b/app-core-rust/src/background/mod.rs index a69fcb1..69436e3 100644 --- a/app-core-rust/src/background/mod.rs +++ b/app-core-rust/src/background/mod.rs @@ -468,8 +468,13 @@ impl InputProcessor { SecurityDecision::Allowed { target } if config.correction.enabled => Some(target), _ => None, }, - |target, known_chars| { - context_capture::read_before_caret(target, &config.context, known_chars) + |target, request, known_chars| { + context_capture::read_correction_context( + target, + request, + &config.context, + known_chars, + ) }, |target, request, output| { let Some(_policy_guard) = SecurityGate::authorize_correction_replacement( diff --git a/app-core-rust/src/background/pipeline.rs b/app-core-rust/src/background/pipeline.rs index 6365b82..18fa6ed 100644 --- a/app-core-rust/src/background/pipeline.rs +++ b/app-core-rust/src/background/pipeline.rs @@ -193,6 +193,18 @@ impl CorrectionPipeline { config: &AppConfig, dictionary: Vec, ) -> bool { + if request.selected_text + && (request.trigger != TriggerKind::ManualShortcut + || request.pending_segment_id.is_some() + || if request.temporary_selection { + !config.shortcuts.correct_arbitrary_selection + } else { + !session + .owns_selection(&request.informative_context, &request.executable_context) + }) + { + return false; + } // Check executable text before either local execution or API transmission. if let Some(path) = self.database_path.as_deref() { let allowed = @@ -416,7 +428,7 @@ impl CorrectionPipeline { limits: &ContextConfig, current_stamp: impl Fn() -> InputStamp, check_target: impl FnOnce(TriggerKind) -> Option, - read_before_caret: impl FnOnce(&FocusedTarget, usize) -> Option, + read_before_caret: impl FnOnce(&FocusedTarget, &CorrectionRequest, usize) -> Option, replace: impl FnOnce(&FocusedTarget, &CorrectionRequest, &CorrectionOutput) -> R, ) -> bool { self.timeout_notice = false; @@ -472,11 +484,7 @@ impl CorrectionPipeline { }; // Security/UIA calls can race with queued typing or focus changes. if target.correction_eligibility() != CorrectionEligibility::Allowed - || target.process_id != active.target.process_id - || target.process_name != active.target.process_name - || target.window_handle != active.target.window_handle - || target.focused_element_id != active.target.focused_element_id - || target.session_key() != active.target.session_key() + || target != active.target || !manager.active_matches(&target) || current_stamp() != validation_stamp || manager @@ -543,25 +551,31 @@ impl CorrectionPipeline { self.feedback_event = Some((Event::Skipped(reason), manual)); return false; } + // An unchanged selection remains selected in the host app. Keep its + // ownership unchanged until typing or a later correction resolves it. + if active.request.selected_text && !output.changes_needed { + self.feedback_event = + Some((Event::Skipped("AutoFix: no correction needed."), manual)); + return false; + } if let Some(id) = segment_id { let Some(following) = manager.active().unwrap().pending_following_text(id) else { return false; }; active.request.replacement_following_text = following; } - // A selection does not prove which end contains the live caret. - // V1 only completes corrections of collapsed, pre-caret ranges. - if active.request.selected_text { - return false; - } let session = manager.active().unwrap(); - let known_before_caret = format!( - "{}{}", - session.informative_context(), - session.executable_context() - ); + let known_before_caret = if active.request.selected_text { + format!("{}{}", active.request.informative_context, original) + } else { + format!( + "{}{}", + session.informative_context(), + session.executable_context() + ) + }; let Some(live_before_caret) = - read_before_caret(&target, known_before_caret.chars().count()) + read_before_caret(&target, &active.request, known_before_caret.chars().count()) else { return false; }; @@ -593,11 +607,13 @@ impl CorrectionPipeline { return false; } let confirmation = if output.changes_needed { - if !session.can_complete_correction( - segment_id, - original, - &output.corrected_executable_text, - ) { + if !active.request.selected_text + && !session.can_complete_correction( + segment_id, + original, + &output.corrected_executable_text, + ) + { return false; } let confirmation = replace(&target, &active.request, &output).into(); @@ -615,7 +631,15 @@ impl CorrectionPipeline { let session = manager.active_mut().unwrap(); let changed = output.changes_needed; let confidence = output.confidence; - let completed = if let Some(id) = segment_id { + let completed = if active.request.selected_text { + session.complete_selection( + &active.request.informative_context, + original, + &output.corrected_executable_text, + limits, + ); + true + } else if let Some(id) = segment_id { session.complete_pending(id, &output.corrected_executable_text, limits) } else if output.changes_needed { session.queue_correction(original.clone(), output.corrected_executable_text) @@ -626,11 +650,21 @@ impl CorrectionPipeline { }; if completed && changed { self.feedback_event = Some((Event::Applied, manual)); + let confirmation = confirmation.unwrap(); + let method = confirmation.method; session.record_undo_metadata( active.request.language_info.primary_language.clone(), active.request.trigger, confidence, - confirmation.unwrap(), + confirmation, + ); + self.log_context_commit( + &active.request, + &active.target, + confidence, + "correction_applied", + output.engine_latency_ms, + method, ); } else if completed { self.feedback_event = Some(( @@ -641,12 +675,13 @@ impl CorrectionPipeline { }), manual, )); - self.log_no_change_commit( + self.log_context_commit( &active.request, &active.target, confidence, no_change_reason.unwrap(), output.engine_latency_ms, + None, ); } completed @@ -673,14 +708,22 @@ impl CorrectionPipeline { /// Record accepted commits once without waiting on SQLite policy reservations. /// Metadata contains no document text, even in full-debug mode. - fn log_no_change_commit( + fn log_context_commit( &self, request: &CorrectionRequest, target: &FocusedTarget, confidence: ConfidenceTier, reason: &str, latency_ms: u64, + method: Option, ) { + let replacement_method = match method { + Some(super::replacement::ReplacementMethod::DirectTextApi) => "direct_text_api", + Some(super::replacement::ReplacementMethod::UiAutomation) => "ui_automation", + Some(super::replacement::ReplacementMethod::Clipboard) => "clipboard", + Some(super::replacement::ReplacementMethod::SendInput) => "send_input", + None => "none", + }; tracing::info!( session_id = request.session_id, trigger = request.trigger.as_str(), @@ -688,8 +731,8 @@ impl CorrectionPipeline { confidence = ?confidence, reason, latency_ms, - replacement_method = "none", - "no-change context committed" + replacement_method, + "correction context committed" ); let Some(path) = self.database_path.as_deref() else { return; @@ -711,14 +754,14 @@ impl CorrectionPipeline { EngineKind::CustomApi => "custom_api", } .into(), - replacement_method: "none".into(), + replacement_method: replacement_method.into(), result_reason: reason.into(), latency_ms, }; if crate::storage::Database::record_metadata_nowait(path, &metadata).is_err() { tracing::warn!( session_id = request.session_id, - "no-change metadata unavailable" + "correction metadata unavailable" ); } } diff --git a/app-core-rust/src/background/pipeline/tests.rs b/app-core-rust/src/background/pipeline/tests.rs index ee33feb..f8ab324 100644 --- a/app-core-rust/src/background/pipeline/tests.rs +++ b/app-core-rust/src/background/pipeline/tests.rs @@ -7,6 +7,8 @@ use crate::background::{ }; use std::{cell::Cell, sync::mpsc, time::Instant}; +mod manual; + const STAMP: InputStamp = InputStamp { position: 7, sequence: 12, @@ -412,7 +414,7 @@ fn queued_api_job_is_denied_after_rule_revocation_and_releases_its_slot() { &config.context, || STAMP, |_| None, - |_, _| panic!("revoked target must not be captured"), + |_, _, _| panic!("revoked target must not be captured"), |_, _, _| -> bool { panic!("revoked target must not be edited") } )); // The rejected first segment restores the dependent queued request too. @@ -531,7 +533,7 @@ fn stale_cancelled_or_secure_timeouts_cannot_show_notices() { } Some(live) }, - |_, _| panic!("timeout must not read target text"), + |_, _, _| panic!("timeout must not read target text"), |_, _, _| -> bool { panic!("timeout must not replace text") }, )); assert!(!pipeline.take_timeout_notice()); @@ -555,7 +557,7 @@ fn automatic_timeout_releases_frozen_slot_without_live_target_calls() { &config.context, || STAMP, |_| panic!("automatic timeout must skip live security/UIA calls"), - |_, _| panic!("automatic timeout must not capture text"), + |_, _, _| panic!("automatic timeout must not capture text"), |_, _, _| -> bool { panic!("automatic timeout must not replace text") }, )); assert!(!pipeline.take_timeout_notice()); @@ -686,7 +688,7 @@ fn delayed_frozen_corrections_keep_all_results_and_preserve_newer_typing() { &config.context, || stamp, |_| Some(target()), - |_, _| Some(live), + |_, _, _| Some(live), |_, request, _| { assert_eq!(request.replacement_following_text, expected_tail); true @@ -705,7 +707,7 @@ fn delayed_frozen_corrections_keep_all_results_and_preserve_newer_typing() { &config.context, || stamp, |_| Some(target()), - |_, _| Some(live), + |_, _, _| Some(live), |_, request, _| { assert_eq!(request.executable_context, " teh"); assert_eq!(request.replacement_following_text, " 尾"); @@ -817,7 +819,7 @@ fn frozen_failures_release_capacity_without_committing_engine_output() { &config.context, || STAMP, |_| if failure == 4 { None } else { Some(target()) }, - |_, _| Some(live), + |_, _, _| Some(live), |_, _, _| { calls.set(calls.get() + 1); false @@ -1063,7 +1065,7 @@ fn frozen_result_revalidates_queued_position_and_input_during_security_check() { }); Some(target()) }, - |_, _| panic!("raced input reached live range validation"), + |_, _, _| panic!("raced input reached live range validation"), |_, _, _| -> bool { panic!("raced input reached replacement") } )); } @@ -1193,7 +1195,7 @@ fn finish( &config.context, || stamp, |_| Some(target()), - |_, _| Some(live), + |_, _, _| Some(live), |_, _, _| { replaced.set(replaced.get() + 1); success @@ -1326,7 +1328,7 @@ fn input_race_after_native_success_drops_session_instead_of_restoring_stale_text &config.context, || current.get(), |_| Some(target()), - |_, _| Some(live), + |_, _, _| Some(live), |_, _, _| { calls.set(calls.get() + 1); current.set(InputStamp { @@ -1412,7 +1414,7 @@ fn manual_failure_feedback_is_validated_and_contains_no_provider_text() { target.is_password_or_protected = unsafe_target; Some(target) }, - |_, _| panic!("failure must not read document text"), + |_, _, _| panic!("failure must not read document text"), |_, _, _| -> bool { panic!("failure must not mutate") } )); assert_eq!( @@ -1642,7 +1644,7 @@ fn unsafe_or_stale_suggestions_cannot_surface_a_preview() { t.is_password_or_protected = failure == 2; Some(t) }, - |_, _| { + |_, _, _| { if failure == 3 { return None; } @@ -1747,7 +1749,7 @@ fn security_and_input_changes_during_live_validation_block_replacement() { } Some(target) }, - |_, _| panic!("invalid result reached live range validation"), + |_, _, _| panic!("invalid result reached live range validation"), |_, _, _| -> bool { panic!("invalid result reached replacement") } )); assert_eq!(manager.active().unwrap().editable_context(), "teh"); @@ -1775,7 +1777,7 @@ fn live_range_must_match_exactly_before_caret() { &config.context, || STAMP, |_| Some(target()), - |_, _| live.map(str::to_owned), + |_, _, _| live.map(str::to_owned), |_, _, _| { calls.set(calls.get() + 1); true @@ -1878,7 +1880,7 @@ fn unchanged_success_commits_only_after_validation() { &config.context, || STAMP, |_| Some(target()), - |_, _| Some(live), + |_, _, _| Some(live), |_, _, _| -> bool { panic!("unchanged text needs no replacement") } )); assert_eq!(manager.active().unwrap().informative_context(), "hello"); diff --git a/app-core-rust/src/background/pipeline/tests/manual.rs b/app-core-rust/src/background/pipeline/tests/manual.rs new file mode 100644 index 0000000..3a9f8e5 --- /dev/null +++ b/app-core-rust/src/background/pipeline/tests/manual.rs @@ -0,0 +1,333 @@ +use super::*; +use crate::background::replacement::{ReplacedRange, ReplacementMethod}; + +fn selection_request( + manager: &SessionManager, + config: &AppConfig, + arbitrary: bool, +) -> CorrectionRequest { + let session = manager.active().unwrap(); + let selection = SelectionCapture::Selected { + text: "teh".into(), + preceding: if arbitrary { "Foreign é " } else { "old é " }.into(), + following: " AFTER".into(), + executable_prefix: (!arbitrary).then(|| "é ".into()), + }; + let mut request = triggers::manual( + session.id(), + session.informative_context(), + &session.editable_context(), + session.versions(), + &selection, + config, + ) + .unwrap(); + request.language_info.primary_language = Some("en".into()); + request +} + +/// Both routes receive separate contexts; only the executable selection can change. +#[test] +fn selected_manual_flow_commits_context_undo_and_metadata_once() { + for engine in [ + EngineKind::LocalRule, + EngineKind::OpenAiCompatibleApi, + EngineKind::CustomApi, + ] { + for arbitrary in [false, true] { + let path = std::env::temp_dir().join(format!( + "autofix-manual-{}-{}.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.shortcuts.correct_arbitrary_selection = arbitrary; + config.logging.full_text_debug_mode_enabled = true; + let mut manager = manager(&config, "é teh AFTER"); + manager.set_informative_context("old ".into()); + manager.input(TypedInput::Uncertain(MovementSignal::MouseClick)); + let mut request = selection_request(&manager, &config, arbitrary); + request.engine = engine; + let prefix = request.informative_context.clone(); + let mut pipeline = CorrectionPipeline::start(move |job| { + assert_eq!(job.request.engine, engine); + assert_eq!(job.input.executable_context, "teh"); + assert!(job.input.informative_context.starts_with(if arbitrary { + "Foreign é " + } else { + "old é " + })); + assert!(job.input.informative_context.ends_with(" AFTER")); + let mut output = + CorrectionOutput::changed("the".into(), ConfidenceTier::High, None, 42); + output.behavior = ConfidenceBehavior::Silent; + output + }) + .unwrap(); + pipeline.database_path = Some(path.clone()); + assert!(pipeline.submit( + request, + manager.active().unwrap(), + target(), + STAMP, + &config, + vec![] + )); + wait_completion(&pipeline); + let calls = Cell::new(0); + assert!(pipeline.finish( + &mut manager, + &config.context, + || STAMP, + |_| Some(target()), + |_, request, _| { + assert!(request.selected_text); + Some(format!("{}teh", request.informative_context)) + }, + |_, request, output| { + calls.set(calls.get() + 1); + assert_eq!(request.executable_context, "teh"); + assert!(request.replacement_following_text.is_empty()); + assert_eq!(output.corrected_executable_text, "the"); + ReplacementConfirmation { + success: true, + method: Some(ReplacementMethod::SendInput), + range: Some(ReplacedRange { + start_back: 3, + end_back: 0, + }), + } + } + )); + assert_eq!(calls.get(), 1); + let session = manager.active_mut().unwrap(); + assert_eq!(session.informative_context(), format!("{prefix}the")); + assert!(session.editable_context().is_empty()); + assert!(!session.position_uncertain()); + let undo = session.undo_target().unwrap(); + assert_eq!(undo.original, "teh"); + assert_eq!(undo.corrected, "the"); + assert!(undo.following.is_empty()); + assert!(session.undo_last_correction(&config.context)); + assert_eq!(session.informative_context(), format!("{prefix}teh")); + assert!(!session.undo_last_correction(&config.context)); + assert!(!pipeline.finish( + &mut manager, + &config.context, + || STAMP, + |_| panic!("duplicate target check"), + |_, _, _| panic!("duplicate capture"), + |_, _, _| -> bool { panic!("duplicate replacement") } + )); + let connection = rusqlite::Connection::open(&path).unwrap(); + let rows: Vec<(String, String, String, u64)> = connection.prepare( + "select trigger_type, replacement_method, result_reason, latency_ms from correction_metadata" + ).unwrap().query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))) + .unwrap().map(Result::unwrap).collect(); + assert_eq!( + rows, + vec![( + "manual_shortcut".into(), + "send_input".into(), + "correction_applied".into(), + 42 + )] + ); + let debug_count: u64 = connection + .query_row("select count(*) from debug_events", [], |row| row.get(0)) + .unwrap(); + assert_eq!(debug_count, 0); + drop(pipeline); + drop(connection); + drop(database); + std::fs::remove_file(path).unwrap(); + } + } +} + +/// Stale, protected, unproved and failed results cannot commit selection ownership. +#[test] +fn selection_failures_preserve_executable_context_and_have_no_undo() { + for failure in [ + "capture", "mismatch", "secure", "title", "input", "replace", "low", "medium", + ] { + let config = AppConfig::default(); + let mut manager = manager(&config, "é teh AFTER"); + manager.set_informative_context("old ".into()); + let request = selection_request(&manager, &config, false); + let mut pipeline = CorrectionPipeline::start(move |_| { + let confidence = match failure { + "low" => ConfidenceTier::Low, + "medium" => ConfidenceTier::Medium, + _ => ConfidenceTier::High, + }; + let mut output = CorrectionOutput::changed("the".into(), confidence, None, 0); + output.behavior = ConfidenceBehavior::Silent; + output + }) + .unwrap(); + assert!(pipeline.submit( + request, + manager.active().unwrap(), + target(), + STAMP, + &config, + vec![] + )); + wait_completion(&pipeline); + let calls = Cell::new(0); + assert!(!pipeline.finish( + &mut manager, + &config.context, + || InputStamp { + sequence: STAMP.sequence + u64::from(failure == "input"), + ..STAMP + }, + |_| { + let mut target = target(); + target.is_password_or_protected = failure == "secure"; + if failure == "title" { + target.window_title = "Private".into(); + } + Some(target) + }, + |_, _, _| match failure { + "capture" => None, + "mismatch" => Some("old é teh AFTER".into()), + _ => Some("old é teh".into()), + }, + |_, _, _| { + calls.set(calls.get() + 1); + false + } + )); + assert_eq!(calls.get(), usize::from(failure == "replace")); + assert_eq!(manager.active().unwrap().editable_context(), "é teh AFTER"); + assert_eq!(manager.active().unwrap().informative_context(), "old "); + assert!(manager.active().unwrap().undo_target().is_none()); + } +} + +/// A forged temporary or foreign selection cannot bypass the default ownership gate. +#[test] +fn selected_submission_requires_current_typed_scope_or_arbitrary_opt_in() { + let mut config = AppConfig::default(); + config.shortcuts.correct_arbitrary_selection = true; + let manager = manager(&config, "é teh AFTER"); + let mut request = selection_request(&manager, &config, true); + config.shortcuts.correct_arbitrary_selection = false; + let mut pipeline = + CorrectionPipeline::start(|_| panic!("unauthorized selection reached engine")).unwrap(); + assert!(!pipeline.submit( + request.clone(), + manager.active().unwrap(), + target(), + STAMP, + &config, + vec![] + )); + request.temporary_selection = false; + assert!(!pipeline.submit( + request, + manager.active().unwrap(), + target(), + STAMP, + &config, + vec![] + )); + assert!(pipeline.active.is_empty()); +} + +/// Selected medium results preview by policy and apply only with explicit silent behavior. +#[test] +fn selected_medium_confidence_obeys_preview_and_silent_preferences() { + for silent in [false, true] { + let mut config = AppConfig::default(); + config.feedback.show_medium_confidence_suggestions = true; + if silent { + config.correction.medium_confidence_behavior = ConfidenceBehavior::Silent; + } + let mut manager = manager(&config, "é teh AFTER"); + manager.set_informative_context("old ".into()); + let request = selection_request(&manager, &config, false); + let mut pipeline = CorrectionPipeline::start(|job| { + let mut output = + CorrectionOutput::changed("the".into(), ConfidenceTier::Medium, None, 0); + output.behavior = job.input.confidence_behavior.behavior_for( + ConfidenceTier::Medium, + job.input.trigger_type, + job.input.suggestion_ui_available, + ); + output + }) + .unwrap(); + assert!(pipeline.submit( + request, + manager.active().unwrap(), + target(), + STAMP, + &config, + vec![] + )); + wait_completion(&pipeline); + let calls = Cell::new(0); + let applied = pipeline.finish( + &mut manager, + &config.context, + || STAMP, + |_| Some(target()), + |_, _, _| Some("old é teh".into()), + |_, _, _| { + calls.set(calls.get() + 1); + true + }, + ); + assert_eq!(applied, silent); + assert_eq!(calls.get(), usize::from(silent)); + let preview = pipeline.take_suggestion(); + let ui_available = PreviewSuggestionUi::new(&config.feedback).is_available(); + assert_eq!(preview.is_some(), !silent && ui_available); + if let Some(preview) = preview { + assert_eq!(preview.text, "AutoFix suggestion: the"); + } + assert_eq!( + manager.active().unwrap().editable_context(), + if silent { "" } else { "é teh AFTER" } + ); + assert_eq!(manager.active().unwrap().undo_target().is_some(), silent); + } +} + +/// Successful unselected manual correction uses the same receipt and clears executable typing. +#[test] +fn collapsed_manual_flow_preserves_informative_context_and_records_undo() { + let config = AppConfig::default(); + let mut manager = manager(&config, "teh"); + manager.set_informative_context("read only ".into()); + let mut pipeline = CorrectionPipeline::new().unwrap(); + submit(&mut pipeline, &manager, &config); + wait_completion(&pipeline); + let calls = Cell::new(0); + assert!(finish( + &mut pipeline, + &mut manager, + &config, + STAMP, + &calls, + true + )); + assert_eq!(calls.get(), 1); + assert_eq!( + manager.active().unwrap().informative_context(), + "read only the" + ); + assert!(manager.active().unwrap().editable_context().is_empty()); + assert_eq!( + manager.active().unwrap().undo_target().unwrap().original, + "teh" + ); +} diff --git a/app-core-rust/src/background/replacement/mod.rs b/app-core-rust/src/background/replacement/mod.rs index 7542a69..61ce39f 100644 --- a/app-core-rust/src/background/replacement/mod.rs +++ b/app-core-rust/src/background/replacement/mod.rs @@ -115,6 +115,7 @@ struct ReplacementPlan<'a> { original: &'a str, replacement: &'a str, following: &'a str, + selected_text: bool, stamp: InputStamp, } @@ -195,9 +196,11 @@ impl ReplacementEngine { ) -> ReplacementResult { let reason = if target.correction_eligibility() != CorrectionEligibility::Allowed { Some("target is protected, unavailable or unsupported") - } else if request.selected_text { - // Even opt-in selections must prove the live caret end. V1 cannot do so. - Some("selected range has no verified pre-caret geometry") + } else if request.selected_text + && (request.trigger != super::security::TriggerKind::ManualShortcut + || !request.replacement_following_text.is_empty()) + { + Some("selection must be a manual range ending at the caret") } else if request.executable_context.is_empty() { Some("executable context is empty") } else if request.executable_context.contains('\0') @@ -229,6 +232,7 @@ impl ReplacementEngine { original: &request.executable_context, replacement: &output.corrected_executable_text, following: &request.replacement_following_text, + selected_text: request.selected_text, stamp, }; Self::execute(&plan, clipboard_enabled) @@ -247,6 +251,7 @@ impl ReplacementEngine { original: &undo.corrected, replacement: &undo.original, following: &undo.following, + selected_text: false, stamp, }, clipboard_enabled, diff --git a/app-core-rust/src/background/replacement/native.rs b/app-core-rust/src/background/replacement/native.rs index 73c64d0..2221cd3 100644 --- a/app-core-rust/src/background/replacement/native.rs +++ b/app-core-rust/src/background/replacement/native.rs @@ -58,12 +58,13 @@ struct PreparedRange { element: IUIAutomationElement, pattern: IUIAutomationTextPattern, original_caret: IUIAutomationTextRange, + original_selection: IUIAutomationTextRange, span: IUIAutomationTextRange, } #[cfg(windows)] impl PreparedRange { - /// Prove exact session text at a collapsed caret without modifying the document. + /// Prove exact session text before a collapsed caret or a verified selection end. fn new(plan: &ReplacementPlan<'_>) -> Result { if plan.original.contains('\0') || plan.replacement.contains('\0') { return Err("embedded NUL cannot be replaced safely".into()); @@ -89,7 +90,20 @@ impl PreparedRange { } let pattern: IUIAutomationTextPattern = element.GetCurrentPatternAs(UIA_TextPatternId)?; - let caret = collapsed_selection(&pattern)?; + let selections = pattern.GetSelection()?; + if selections.Length()? != 1 { + return Err(range_error("selection is not a single range")); + } + let original_selection = selections.GetElement(0)?; + let caret = if plan.selected_text { + let selection = &original_selection; + if selection.GetText(-1)? != plan.original || !plan.following.is_empty() { + return Err(range_error("selection does not match executable text")); + } + super::super::context_capture::selected_caret(&element, selection)? + } else { + collapsed_selection(&pattern)? + }; // Providers differ on supplementary Unicode character units. // Resolve both known spans independently and require exact text. let following = adjacent_range(&caret, plan.following, true)?; @@ -99,6 +113,9 @@ impl PreparedRange { if span.CompareEndpoints(START, &span, END)? > 0 || span.CompareEndpoints(END, &caret, END)? > 0 || span.GetText(-1)? != plan.original + || (plan.selected_text + && (span.CompareEndpoints(START, &original_selection, START)? != 0 + || span.CompareEndpoints(END, &original_selection, END)? != 0)) { return Err(range_error("pre-caret text does not match")); } @@ -107,12 +124,13 @@ impl PreparedRange { element, pattern, original_caret: caret, + original_selection, span, }) })() }; // Provider error messages are untrusted and can contain document text. - let range = result.map_err(|_| "no reliable collapsed pre-caret range".to_owned())?; + let range = result.map_err(|_| "no reliable pre-caret range".to_owned())?; if !current(plan) || !range.focused() { return Err("focus or input changed while proving range".into()); } @@ -202,6 +220,8 @@ impl PreparedRange { if !current(plan) || !self.focused() { return Err("target changed before selection".into()); } + // Preparation must not silently replace a newer programmatic selection. + self.verify_original_selection(plan)?; selection_attempted = true; unsafe { self.span.Select() }.map_err(|_| "range selection failed")?; // Verify Select selected exactly the proven span, not a provider approximation. @@ -275,15 +295,56 @@ impl PreparedRange { return false; } unsafe { - self.original_caret.Select().is_ok() - && collapsed_selection(&self.pattern).is_ok_and(|caret| { - caret.CompareEndpoints(END, &self.original_caret, END).ok() == Some(0) - }) + self.original_selection.Select().is_ok() + && self.verify_original_selection(plan).is_ok() && current(plan) && self.focused() } } + /// Preserve the original selection and its active endpoint until mutation begins. + fn verify_original_selection(&self, plan: &ReplacementPlan<'_>) -> Result<(), String> { + unsafe { + let selections = self + .pattern + .GetSelection() + .map_err(|_| "selection unreadable")?; + if selections.Length().ok() != Some(1) { + return Err("selection changed during preparation".into()); + } + let selection = selections + .GetElement(0) + .map_err(|_| "selection unreadable")?; + if selection + .CompareEndpoints(START, &self.original_selection, START) + .ok() + != Some(0) + || selection + .CompareEndpoints(END, &self.original_selection, END) + .ok() + != Some(0) + || (plan.selected_text + && selection + .GetText(-1) + .ok() + .as_ref() + .is_none_or(|text| *text != plan.original)) + { + return Err("selection changed during preparation".into()); + } + let caret = if plan.selected_text { + super::super::context_capture::selected_caret(&self.element, &selection) + } else { + collapsed_selection(&self.pattern) + } + .map_err(|_| "caret endpoint unavailable")?; + if caret.CompareEndpoints(END, &self.original_caret, END).ok() != Some(0) { + return Err("caret endpoint changed during preparation".into()); + } + } + Ok(()) + } + /// Reject approximate provider selections before publishing or injecting text. fn verify_selection(&self, plan: &ReplacementPlan<'_>) -> Result<(), String> { unsafe { @@ -305,6 +366,10 @@ impl PreparedRange { { return Err("selected range or input changed".into()); } + if plan.selected_text { + super::super::context_capture::selected_caret(&self.element, &selected) + .map_err(|_| "selected caret endpoint changed")?; + } } Ok(()) } diff --git a/app-core-rust/src/background/replacement/tests.rs b/app-core-rust/src/background/replacement/tests.rs index 59fccd8..7fb7d8a 100644 --- a/app-core-rust/src/background/replacement/tests.rs +++ b/app-core-rust/src/background/replacement/tests.rs @@ -78,6 +78,7 @@ fn disabling_clipboard_skips_its_preparation_and_uses_fallback() { original: "teh", replacement: "the", following: "", + selected_text: false, stamp: STAMP, }; let calls = RefCell::new(Vec::new()); @@ -135,6 +136,7 @@ fn strategy_order_and_preparation_failures_allow_fallback() { original: "teh", replacement: "the", following: " newer", + selected_text: false, stamp: STAMP, }; let calls = RefCell::new(Vec::new()); @@ -187,6 +189,7 @@ fn successful_safer_method_never_reaches_send_input() { original: "teh", replacement: "the", following: "", + selected_text: false, stamp: STAMP, }; let calls = RefCell::new(Vec::new()); @@ -227,6 +230,7 @@ fn no_retry_after_paste_partial_input_or_failed_verification() { original: "teh", replacement: "the", following: "", + selected_text: false, stamp: STAMP, }; let calls = RefCell::new(Vec::new()); @@ -262,6 +266,7 @@ fn unavailable_result_has_method_reason_and_unknown_range() { original: "teh", replacement: "the", following: "", + selected_text: false, stamp: STAMP, }; let calls = RefCell::new(Vec::new()); @@ -285,6 +290,7 @@ fn exact_range_counts_unicode_characters_and_preserves_following_text() { original: "é😃", replacement: "new", following: " العربية", + selected_text: false, stamp: STAMP, }; assert_eq!( @@ -320,7 +326,10 @@ fn protected_selected_empty_suppressed_and_failed_requests_never_reach_native_st let mut output = output.clone(); match case { 0 => target.is_password_or_protected = true, - 1 => request.selected_text = true, + 1 => { + request.selected_text = true; + request.replacement_following_text = "later".into(); + } 2 => request.executable_context.clear(), 3 => output.behavior = ConfidenceBehavior::Suggestion, 4 => output.confidence = ConfidenceTier::Low, @@ -488,6 +497,7 @@ fn native_edit_replacement_smoke() { 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(), @@ -591,7 +601,7 @@ fn native_edit_replacement_smoke() { &config.context, || stamp, |_| Some(target.clone()), - |target, known| { + |target, _, known| { super::super::context_capture::read_before_caret(target, &config.context, known) }, |_, _, _| -> bool { panic!("unchanged result reached native replacement") }, @@ -629,14 +639,140 @@ fn native_edit_replacement_smoke() { } assert_eq!((caret_start as usize, caret_end as usize), (caret, caret)); } - for (method, original, replacement, following) in [ - (ReplacementMethod::Clipboard, "teh", "the", ""), - (ReplacementMethod::Clipboard, "teh", "the", " newer"), - (ReplacementMethod::SendInput, "teh", "the", ""), - (ReplacementMethod::SendInput, "teh", "the", " newer"), - (ReplacementMethod::SendInput, "teh", "", " newer"), - (ReplacementMethod::SendInput, "teh", "é😃", ""), - (ReplacementMethod::SendInput, "teh", "العربية", ""), + // Exercise the runtime shortcut owner, real security/policy gates, local + // engine, native replacement, session commit, undo and metadata together. + for (selected, arbitrary, allowed) in [ + (false, false, true), + (true, false, true), + (true, true, true), + (true, false, false), + ] { + let initial = "old teh AFTER"; + 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, if selected { 4 } else { 7 }, 7); + } + 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-shortcut-{}-{}.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.shortcuts.correct_arbitrary_selection = arbitrary; + config.replacement.clipboard_enabled = false; + config.feedback.show_blocked_app_notice = false; + 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); + if !arbitrary { + processor + .session_manager + .set_informative_context("old ".into()); + processor.session_manager.input(TypedInput::Text( + if !allowed { + "other" + } else if selected { + "teh AFTER" + } else { + "teh" + } + .into(), + )); + } + processor.process_shortcut(1); + 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, + "manual shortcut did not complete" + ); + } + let mut text = [0u16; 128]; + let length = unsafe { + SendMessageW( + edit as _, + WM_GETTEXT, + text.len(), + text.as_mut_ptr() as isize, + ) + }; + assert_eq!( + String::from_utf16_lossy(&text[..length as usize]), + if allowed { "old the AFTER" } else { initial } + ); + let session = processor.session_manager.active().unwrap(); + if allowed { + assert_eq!(session.informative_context(), "old the"); + assert!(session.editable_context().is_empty()); + assert_eq!(session.undo_target().unwrap().original, "teh"); + let connection = rusqlite::Connection::open(&path).unwrap(); + let count: u64 = connection.query_row( + "select count(*) from correction_metadata where result_reason = 'correction_applied' and replacement_method = 'send_input'", + [], |row| row.get(0)).unwrap(); + assert_eq!(count, 1); + processor.process_shortcut(2); + let length = unsafe { + SendMessageW( + edit as _, + WM_GETTEXT, + text.len(), + text.as_mut_ptr() as isize, + ) + }; + assert_eq!(String::from_utf16_lossy(&text[..length as usize]), initial); + assert_eq!( + processor + .session_manager + .active() + .unwrap() + .informative_context(), + "old teh" + ); + assert!(processor + .session_manager + .active() + .unwrap() + .undo_target() + .is_none()); + } else { + assert_eq!(session.editable_context(), "other"); + assert!(session.undo_target().is_none()); + } + drop(processor); + std::fs::remove_file(path).unwrap(); + } + for (method, original, replacement, following, selected_text) in [ + (ReplacementMethod::Clipboard, "teh", "the", "", false), + (ReplacementMethod::Clipboard, "teh", "the", " newer", false), + (ReplacementMethod::SendInput, "teh", "the", "", false), + (ReplacementMethod::SendInput, "teh", "the", " newer", false), + (ReplacementMethod::SendInput, "teh", "", " newer", false), + (ReplacementMethod::SendInput, "teh", "é😃", "", false), + (ReplacementMethod::SendInput, "teh", "العربية", "", false), + (ReplacementMethod::Clipboard, "teh", "the", "", true), + (ReplacementMethod::SendInput, "teh", "é😃", "", true), + (ReplacementMethod::SendInput, "teh", "", "", true), ] { let initial = format!("old {original}{following} AFTER"); let initial_caret = format!("old {original}{following}").encode_utf16().count(); @@ -675,11 +811,53 @@ fn native_edit_replacement_smoke() { position: super::super::input_listener::current_position_generation(), sequence: super::super::input_listener::current_input_sequence(), }; + if selected_text { + // A backward selection has its active caret at the start. It must + // never edit the selected text after that caret. + unsafe { + SendMessageW(edit as _, EM_SETSEL, initial_caret, initial_caret as isize); + SendMessageW( + GetAncestor(edit as _, GA_ROOT), + WM_APP + 3, + original.chars().count(), + 0, + ); + }; + let backward = super::super::context_capture::read_selection( + &target, + "old ", + original, + &AppConfig::default().context, + ); + assert!( + matches!(backward, SelectionCapture::Unavailable), + "{backward:?}" + ); + let unsafe_plan = ReplacementPlan { + target: &target, + original, + replacement, + following, + selected_text: true, + stamp, + }; + let refused = run_strategies( + &unsafe_plan, + &mut [&mut native::NativeStrategy(method)], + true, + ); + assert!(!refused.success && !refused.may_have_changed); + unsafe { SendMessageW(edit as _, EM_SETSEL, 4, initial_caret as isize) }; + assert!(matches!(super::super::context_capture::read_selection( + &target, "old ", original, &AppConfig::default().context), + SelectionCapture::Selected { executable_prefix: Some(prefix), .. } if prefix.is_empty())); + } let plan = ReplacementPlan { target: &target, original, replacement, following, + selected_text, stamp, }; unsafe { SendMessageW(GetAncestor(edit as _, GA_ROOT), WM_APP + 2, 1, 0) }; @@ -831,6 +1009,23 @@ unsafe extern "system" fn native_test_editor_window_proc( SetWindowLongPtrW(window, GWLP_USERDATA, wparam as isize); return 0; } + if message == WM_APP + 3 { + use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + GetKeyboardState, SetKeyboardState, VK_LEFT, VK_SHIFT, + }; + let mut previous = [0u8; 256]; + assert_ne!(GetKeyboardState(previous.as_mut_ptr()), 0); + let mut shift = previous; + shift[VK_SHIFT as usize] = 0x80; + assert_ne!(SetKeyboardState(shift.as_ptr()), 0); + let edit = GetWindow(window, GW_CHILD); + for _ in 0..wparam { + SendMessageW(edit, WM_KEYDOWN, VK_LEFT as usize, 1); + SendMessageW(edit, WM_KEYUP, VK_LEFT as usize, 1); + } + assert_ne!(SetKeyboardState(previous.as_ptr()), 0); + return 0; + } if message == WM_COMMAND && wparam >> 16 == 0x0300 && GetWindowLongPtrW(window, GWLP_USERDATA) != 0 diff --git a/app-core-rust/src/background/session.rs b/app-core-rust/src/background/session.rs index 8ce1b1d..ba07ed4 100644 --- a/app-core-rust/src/background/session.rs +++ b/app-core-rust/src/background/session.rs @@ -525,6 +525,49 @@ impl Session { true } + /// Check an admitted selection against the still-retained typed segment. + pub(super) fn owns_selection(&self, informative: &str, original: &str) -> bool { + let Some(prefix) = informative.strip_prefix(&self.informative_context) else { + return false; + }; + !original.is_empty() + && self + .editable_context() + .starts_with(&format!("{prefix}{original}")) + } + + /// After verified selection replacement, establish a new collapsed caret anchor. + /// Unselected text after that caret is forgotten, never promoted to executable text. + pub(super) fn complete_selection( + &mut self, + informative: &str, + original: &str, + replacement: &str, + limits: &ContextConfig, + ) { + let start = informative + .strip_prefix(&self.informative_context) + .map_or(0, |prefix| prefix.chars().count()); + self.restore_pending(); + self.pending_corrections.clear(); + self.pending_movement = None; + self.executable.clear_executable(); + self.correction_floor = 0; + self.invalidate_undo_anchors(); + self.informative_context = informative.to_owned(); + self.informative_context.push_str(replacement); + self.versions.context = self.versions.context.wrapping_add(1); + self.versions.executable = self.versions.executable.wrapping_add(1); + self.versions.caret_anchor = self.versions.caret_anchor.wrapping_add(1); + self.shrink_informative(limits); + self.record_undo( + original.to_owned(), + replacement.to_owned(), + start..start + original.chars().count(), + limits, + ); + } + /// Prove bookkeeping can retain a changed result before authorizing its native edit. /// Frozen prefixes retire into informative context; manual suffixes need typed capacity. pub(super) fn can_complete_correction( diff --git a/app-core-rust/src/background/tests.rs b/app-core-rust/src/background/tests.rs index a74fc31..851aae7 100644 --- a/app-core-rust/src/background/tests.rs +++ b/app-core-rust/src/background/tests.rs @@ -227,7 +227,7 @@ fn finish_unchanged_dispatch( &processor.config.context, || stamp, |_| Some(target.clone()), - |_, _| Some(live_text.into()), + |_, _, _| Some(live_text.into()), |_, _, _| -> bool { panic!("unchanged text must not be replaced") }, ) { return; From 7f0b5a8246a0662c00e8541a35ab08a07595ef4e Mon Sep 17 00:00:00 2001 From: Hussein Ba Ragaa Date: Sat, 3 Oct 2026 15:12:01 +0300 Subject: [PATCH 2/2] fix(correction): compare caret handles directly --- app-core-rust/src/background/context_capture.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app-core-rust/src/background/context_capture.rs b/app-core-rust/src/background/context_capture.rs index f15f502..d36987d 100644 --- a/app-core-rust/src/background/context_capture.rs +++ b/app-core-rust/src/background/context_capture.rs @@ -137,8 +137,8 @@ pub(super) unsafe fn selected_caret( || thread == 0 || process != element.CurrentProcessId()? as u32 || GetGUIThreadInfo(thread, &mut info) == 0 - || info.hwndFocus != window as _ - || info.hwndCaret != window as _ + || !std::ptr::eq(info.hwndFocus, window) + || !std::ptr::eq(info.hwndCaret, window) { return Err(unavailable()); }