diff --git a/AGENTS.md b/AGENTS.md index 8869da0..876e98e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,6 +37,11 @@ Never discard user changes. Never commit to main. For repository changes made on main, create a branch unless the user explicitly says no branch is needed. Use branch names without `/`. Commit completed logical checkpoints. +Always push completed, verified review fixes and their supporting tests or +documentation to the existing feature branch on `origin`. The user grants +standing authorization for these pushes to this repository without asking +again, unless the user explicitly requests local-only work. + For commits, use `.agents/skills/conventional-commit/SKILL.md` and `.agents/skills/caveman-commit/SKILL.md`; keep the final message Conventional Commits compliant. Close only shells and app processes started for the task. diff --git a/README.md b/README.md index 33ea8fa..0e54a0a 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,27 @@ 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. +Undo defaults to **Ctrl+Alt+Z**. Under **Shortcuts**, configure the hotkey and +**Undo history entries** (default 10, range 1–1000). Each session keeps its own +history in memory and deletes it with the session. Repeated undo restores the +latest recorded correction first, preserving newly typed text and text after +the caret. Restored originals become informative context; only new typing stays +executable. AutoFix replaces the verified corrected span directly instead of +sending the target application's Ctrl+Z. + +**Dictionary** settings edit words and phrases that AutoFix must never correct, +plus specific pairs such as `teh` → `the` that must never be applied. Entries live +in `%LOCALAPPDATA%\AutoFix\autofix.sqlite`, with a language tag and optional app +process scope. `und` protects all languages; an empty app scope applies everywhere. + +Learning defaults to **Off — undo only**. App-level undo only restores the +correction unless you choose **Ask after undo** or **Automatically learn**. +Ask shows “Don't correct this again?” after a successful undo; only Yes saves an +exclusion. Choose whether to protect the original word/phrase or only the rejected +pair, and whether learning applies just to that app. Existing exclusions stay +active when learning is off. Native Ctrl+Z and suggestion rejection are not tracked; +use AutoFix's undo shortcut to reject an applied correction. + Native clipboard replacement preserves all readable formats and restores them before reporting success. Disable it under **Correction > Use clipboard for correction** or set `replacement.clipboard_enabled = false` in settings TOML. diff --git a/app-core-rust/README.md b/app-core-rust/README.md index 9efa6e8..15f7474 100644 --- a/app-core-rust/README.md +++ b/app-core-rust/README.md @@ -19,6 +19,36 @@ the correction mode, enabled grammar categories, language and mixed-language policy, dictionary and protected terms, trigger, and confidence behavior. Its result includes corrected executable text, change need and optional details, confidence, no-change reason, latency, and completion/error/timeout status. + +`src/dictionary` owns persistent exclusions and optional learning. SQLite stores +word/phrase entries and active pair-specific rules. App process matching ignores +ASCII case. `und` and null language scopes protect every language; base tags such +as `en` apply to variants such as `en-US`. Regional tags match the resolved tag. +Unknown or mixed language conservatively protects all entries for the app. +Both engine routes enforce whole-term boundaries, including phrases, and filter +blocked pairs while preserving unrelated edits. Exclusions are snapshotted for +execution through a fresh read-only connection with a zero busy timeout and one +read transaction for both exclusion tables. Submission never creates or migrates +storage; unreadable or incompatible exclusions refuse the request. Broad edits +that cross a pair's boundary are refused when unchanged +context cannot prove a different replacement. Exclusions are reread +under the replacement writer reservation; a newly +blocked edit refuses the in-flight replacement. + +Learning defaults to off. Only a verified, successful AutoFix undo supplies a +rejection, using the original/replacement span and the correction's recorded +language. It never captures document text or native Ctrl+Z. The smallest changed +word/phrase is learned; multiple separated changes form one phrase. Ask mode uses +a separate, coalesced native Yes/No prompt, defaults to No, and stores no text +until consent. Input processing remains available while the prompt is open. +Changing learning settings cancels pending consent. Accepted consent and automatic +learning submit the selected dictionary or pair exclusion to a dedicated worker +with its own SQLite connection and a 16-entry queue. Input processing never waits +for a save. The worker waits at most 100 ms for SQLite writer contention; a full +queue or unavailable storage skips the save and emits a warning without text. +The worker never creates or migrates storage, and shutdown drains authorized saves. +Disabling learning does not disable existing rules. Suggestion rejection remains unavailable with +the planned suggestion UI; failed or refused undo never learns. `LocalRuleEngine`, `LocalMlEngine`, `OpenAiCompatibleApiEngine`, and `CustomApiEngine` implement the same interface. `LocalRuleEngine` provides fast, deterministic English correction for a conservative list of clear misspellings. @@ -156,10 +186,16 @@ versions. Captured field text may enter informative context; executable context contains only text typed during the current engine run. On a successful correction, corrected text becomes read-only informative context. Automatic correction retires only its frozen segment and preserves newer -executable text. A manual trigger or final fix with no changes -does the same with the original text. Exceeding the configured executable word -limit also commits the current segment. New typing starts a fresh executable -segment. Undo restores the corrected span in informative context to its +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. +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 +starts a fresh executable segment. Undo restores the corrected span in informative context to its original text and leaves newer executable text intact. Informative context is shrunk in app memory after every append and commit. Shrinking stays within the configured character budget, prefers configured sentence boundaries, and @@ -178,6 +214,21 @@ their owning process exits. All session state disappears on engine exit or termination and is never written to disk. Session completion methods do not themselves change target text; the replacement engine must confirm mutation first. +Undo history is owned by `src/background/session/undo.rs`. The configurable +`context.undo_history_size` defaults to 10 and accepts 1–1000 entries per session; +overflow and capacity reductions evict the oldest entries. Each record retains +the session ID, original executable-context Unicode range, verified native range +relative to the correction-time caret when available, exact original/corrected +text, commit timestamp, trigger, confidence tier, replacement method and language. +Only verified app-made corrections enter history. No history text is persisted. +Context shrinking adjusts byte anchors for fully retained spans and invalidates +partial spans without truncating the recorded text. Movement and re-anchoring +invalidate range proofs; session deletion drops history. Undo requires the latest +entry's complete span at the verified current caret, restores its exact original +text through the replacement engine, and pops the entry only after success. +Newer typed text remains executable; restored text stays informative. Native +Ctrl+Z is never used as the undo mechanism. + The correction pipeline uses one worker, a FIFO of requests, and one completion slot with backpressure so results cannot overwrite each other. Each session has one active executable context and a bounded pending correction queue. @@ -187,8 +238,9 @@ before processing subsequent typing, including keys in the same input batch. New typing starts a fresh executable context while correction runs asynchronously. `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, retires its original text into informative context, and -admits the new segment. `merge_newest` cancels the newest pending request, merges +oldest pending request and its dependent newer requests, restores their unchecked +text to executable context, and admits the combined segment for a new check. +`merge_newest` cancels the newest pending request, merges its typed text back into the active executable context, and waits for the next trigger. Manual correction cancels pending work and restores its original text to the active context before taking its selection or caret snapshot. @@ -223,7 +275,7 @@ writes from IPC and the settings UI, including when SQLite uses WAL mode. Revocation takes effect when the rule write commits: a send already holding the reservation may finish first, and transmitted data cannot be recalled. Missing, unreadable, or busy policy storage denies the send without waiting or retrying. -Denied frozen jobs retire their original text and release queue capacity through +Denied frozen jobs restore their original text and release queue capacity through normal failed completion. Completion rechecks the live security gate and focused target, then input generations again after those checks. Completions wait for hook input to be processed and retire frozen ranges in document order. @@ -234,9 +286,23 @@ 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. -Failed, suppressed, or refused frozen results release their slot and retire the -original text without applying engine output. Results are -consumed once. Only completed silent corrections above low confidence reach the +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 +document order. Invalidated requests also restore any still-active segment; +movement and lost caret ownership continue through the final-fix/re-anchor rules. +Only validated unchanged results with `no_correction_needed` or +`all_candidates_protected` accept the original text into informative context; +language and confidence skips retain executable text. Accepted no-change commits +are recorded as metadata without running migrations or waiting for SQLite locks. +An active policy writer or unavailable database skips only this optional event; +the accepted context commit and input processing continue. +Changed results preflight exact session ownership and typed-buffer capacity +before native mutation. If input races with a successful mutation or session +bookkeeping cannot commit it, pending requests are cancelled and session +ownership is invalidated. Undo likewise commits its session update before +learning; a lost input snapshot invalidates ownership and skips learning. +Results are consumed once. Only completed silent corrections above low confidence reach the replacement boundary. Failed and suppressed manual edits do not commit executable context. Tests cover delayed engines, frozen queues and overflow policies, manual override, stale and reordered results, queued input, @@ -324,7 +390,7 @@ Range offsets count Unicode characters backwards from the original caret, with `start_back >= end_back >= 0`; they are not document byte or UTF-16 offsets. App-level undo uses only a recorded app correction that remains fully retained in informative context. It verifies the live anchor and restores that recorded -span, preserving newer executable text. Memory truncation, movement, unknown +span, preserving newer executable text. Truncation of that span, movement, unknown selection geometry and secure fields block native undo. Focused tests cover strategy ordering, the clipboard disable preference, @@ -337,7 +403,8 @@ and a bitmap. It verifies actual native paste, restoration, recovery from a locked clipboard, and retention of a newer copy without touching the desktop clipboard. It refuses a visible station or unrelated existing clipboard data. The opt-in `native_edit_replacement_smoke` test owns a separate native editor; -it checks clipboard/SendInput and preservation of the document suffix on an +it checks clipboard/SendInput correction and recorded app undo, preserving the +newer executable text, caret and document suffix on an interactive Windows desktop. It safely refuses unsupported clipboard formats. Feature code should be organized by product behavior, not technical layer. Keep modules small, private by default, and colocate tests with the behavior they verify. diff --git a/app-core-rust/src/background/mod.rs b/app-core-rust/src/background/mod.rs index a9efa9c..22c70b4 100644 --- a/app-core-rust/src/background/mod.rs +++ b/app-core-rust/src/background/mod.rs @@ -90,6 +90,7 @@ enum InputWork { const INPUT_WORK_QUEUE_LIMIT: usize = 8; +/// Accept read-only capture only while the hook input sequence remains unchanged. fn capture_if_current( expected: u64, current: impl Fn() -> u64, @@ -103,6 +104,7 @@ fn capture_if_current( } struct InputProcessor { + learner: crate::dictionary::Learner, pipeline: CorrectionPipeline, processed_input_sequence: u64, config: AppConfig, @@ -312,6 +314,7 @@ impl InputWorker { .name("autofix-input-processing".into()) .spawn(move || { let mut processor = InputProcessor { + learner: crate::dictionary::Learner::default(), pipeline, processed_input_sequence: input_listener::current_input_sequence(), session_manager: SessionManager::new(config.context.clone()), @@ -370,6 +373,7 @@ impl InputWorker { } processor.finish_correction(); } + processor.learner.finish(); let _ = done_sender.send(replacement::finish_shutdown()); }) .map_err(BackgroundError::InputWorker)?; @@ -439,6 +443,8 @@ impl InputProcessor { /// Defer completion until hook input is drained, then validate the live target and caret. fn finish_correction(&mut self) { + self.learner + .poll(&self.config.learning, self.database.path()); // Frozen ranges may survive processed typing, but never guess what keys // still queued in the hooks did to the target. if Self::input_stamp().sequence != self.processed_input_sequence { @@ -469,8 +475,19 @@ impl InputProcessor { reason = "replacement policy unavailable or denied", "replacement skipped" ); - return false; + return replacement::ReplacementConfirmation::default(); + }; + // Recheck live exclusions under the same writer reservation as mutation. + let Ok(policy) = database + .dictionary() + .policy(&target.process_name, &request.language_info) + else { + tracing::warn!("replacement skipped: exclusions unavailable"); + return replacement::ReplacementConfirmation::default(); }; + if policy.filter(&request.executable_context, output.clone()) != *output { + return replacement::ReplacementConfirmation::default(); + } let result = ReplacementEngine::replace( target, request, @@ -480,7 +497,7 @@ impl InputProcessor { ); replacement_uncertain = !result.success && result.may_have_changed; result.log_outcome(false); - result.success + result.into() }, ); if replacement_uncertain { @@ -760,6 +777,8 @@ impl InputProcessor { } } + /// Restore a verified session correction, committing bookkeeping before optional learning. + /// Any uncertain native result or input race revokes the session's editable ownership. fn undo_correction(&mut self) { let stamp = Self::input_stamp(); if stamp.sequence != self.processed_input_sequence { @@ -819,16 +838,47 @@ impl InputProcessor { self.config.replacement.clipboard_enabled, ); result.log_outcome(true); + drop(_policy_guard); if result.success { - if let Some(session) = self.session_manager.active_mut() { - session.undo_last_correction(&self.config.context); - } + self.complete_undo(undo, &target, stamp, Self::input_stamp()); } else if result.may_have_changed { self.session_manager .deactivate(MovementSignal::UnknownPosition); } } + /// Commit a successful native undo before learning; lost ownership drops the session. + fn complete_undo( + &mut self, + undo: session::CorrectionUndoTarget, + target: &target::FocusedTarget, + stamp: InputStamp, + current_stamp: InputStamp, + ) { + if current_stamp != stamp + || !self + .session_manager + .active_mut() + .is_some_and(|session| session.undo_last_correction(&self.config.context)) + { + self.session_manager + .deactivate(MovementSignal::UnknownPosition); + tracing::warn!("undo bookkeeping lost session ownership"); + return; + } + if self.config.learning.mode != crate::settings::LearningMode::Off { + if let Some(rejection) = crate::dictionary::Rejection::from_undo( + &undo.original, + &undo.corrected, + undo.language, + target.process_name.clone(), + ) { + self.learner + .rejected(rejection, &self.config.learning, self.database.path()); + } + } + } + /// Update the typed session and retain trigger requests with their full scope. fn track_input( &mut self, @@ -860,15 +910,18 @@ impl InputProcessor { ) { // Freeze the entire current context, including earlier // skipped boundaries. New keys belong to a fresh context. - request.executable_context = editable_snapshot.clone(); let (segment, cancelled) = session.freeze_pending(&self.config.context); - if let Some(id) = cancelled { + for id in cancelled { self.pipeline.cancel_segment(id); } if let Some(id) = segment { + // Overflow can restore older unchecked text. Snapshot + // the admitted range after reservation, not before it. + (request.informative_context, request.executable_context) = + session.pending_context(id).unwrap(); request.pending_segment_id = Some(id); pending.push(PendingTrigger { - editable_snapshot, + editable_snapshot: request.executable_context.clone(), request, }); } @@ -915,7 +968,7 @@ impl InputProcessor { check_target: impl FnOnce(TriggerKind, &AppConfig, &Database) -> SecurityDecision, ) -> bool { self.pipeline - .invalidate(&self.session_manager, current_stamp()); + .invalidate(&mut self.session_manager, current_stamp()); let frozen = request.pending_segment_id.is_some(); if !self.config.correction.enabled || !stamp.permits(current_stamp(), frozen) { return false; @@ -960,10 +1013,10 @@ impl InputProcessor { request.confidence_behavior = self.config.confidence_behavior(); let dictionary = match self .database - .custom_dictionary() - .entries_for_app(&target.process_name) + .dictionary() + .policy(&target.process_name, &request.language_info) { - Ok(entries) => entries, + Ok(policy) => policy.terms, Err(error) => { tracing::warn!(%error, "correction skipped: dictionary unavailable"); return false; @@ -985,8 +1038,16 @@ impl InputProcessor { tracing::debug!(session_id = request.session_id, ?request.versions, ?request.engine, ?request.mode, trigger = request.trigger.as_str(), "correction queued"); - self.pipeline - .submit(request, session, target, stamp, &self.config, dictionary); + if !self.pipeline.submit( + request, + session, + target, + stamp, + &self.config, + dictionary, + ) { + return false; + } if manual { self.pipeline.wait_manual(); self.finish_correction(); diff --git a/app-core-rust/src/background/pipeline.rs b/app-core-rust/src/background/pipeline.rs index e6bf3ec..efbe35a 100644 --- a/app-core-rust/src/background/pipeline.rs +++ b/app-core-rust/src/background/pipeline.rs @@ -13,6 +13,7 @@ use std::{ }; use super::{ + replacement::ReplacementConfirmation, security::TriggerKind, session::{Session, SessionManager}, target::{CorrectionEligibility, FocusedTarget}, @@ -49,6 +50,7 @@ struct Job { api: ApiEngineConfig, cancelled: Arc, authorization: SendAuthorization, + exclusions: crate::dictionary::Policy, } struct Completion { @@ -149,7 +151,9 @@ impl CorrectionPipeline { if job.cancelled.load(Ordering::Acquire) { continue; } - let output = correct(&job); + let output = job + .exclusions + .filter(&job.input.executable_context, correct(&job)); let (lock, ready) = &*worker_mailbox; let mut state = lock.lock().unwrap(); // Transport may finish after cancellation; never publish that result. @@ -178,7 +182,7 @@ impl CorrectionPipeline { stamp: InputStamp, config: &AppConfig, dictionary: Vec, - ) { + ) -> bool { if request.pending_segment_id.is_none() { self.cancel(); } @@ -228,6 +232,20 @@ impl CorrectionPipeline { confidence_behavior: request.confidence_behavior.clone(), suggestion_ui_available: false, }; + let exclusions = match self.database_path.as_deref() { + Some(path) => match crate::dictionary::Repository::policy_nowait( + path, + &target.process_name, + &request.language_info, + ) { + Ok(policy) => policy, + Err(_) => { + tracing::warn!("correction skipped: exclusions unavailable"); + return false; + } + }, + None => crate::dictionary::Policy::default(), + }; self.active.push_back(ActiveRequest { id, request: request.clone(), @@ -246,8 +264,10 @@ impl CorrectionPipeline { api: (&config.api).into(), cancelled, authorization, + exclusions, }); ready.notify_all(); + true } /// Cancel all admitted work and clear queued jobs, completions, and timeout feedback. @@ -294,7 +314,18 @@ impl CorrectionPipeline { } /// Frozen work survives newer typing; manual snapshots remain strict. - pub(super) fn invalidate(&mut self, manager: &SessionManager, stamp: InputStamp) { + pub(super) fn invalidate(&mut self, manager: &mut SessionManager, stamp: InputStamp) { + // Losing worker ownership does not mean the typed segment was checked. + // Return it and its dependent suffix to the active context when present. + for active in &self.active { + if let Some(session) = manager.active_mut() { + if session.id() == active.request.session_id && !active.valid(session, stamp) { + if let Some(id) = active.request.pending_segment_id { + session.restore_pending_from(id); + } + } + } + } self.active.retain(|active| { if manager .active() @@ -326,14 +357,14 @@ impl CorrectionPipeline { } /// Take once: duplicates and reordered completions cannot reach the mutation owner. - pub(super) fn finish( + pub(super) fn finish>( &mut self, manager: &mut SessionManager, limits: &ContextConfig, current_stamp: impl Fn() -> InputStamp, check_target: impl FnOnce(TriggerKind) -> Option, read_before_caret: impl FnOnce(&FocusedTarget, usize) -> Option, - replace: impl FnOnce(&FocusedTarget, &CorrectionRequest, &CorrectionOutput) -> bool, + replace: impl FnOnce(&FocusedTarget, &CorrectionRequest, &CorrectionOutput) -> R, ) -> bool { self.timeout_notice = false; self.invalidate(manager, current_stamp()); @@ -355,8 +386,9 @@ impl CorrectionPipeline { let mut active = self.active.pop_front().unwrap(); let validation_stamp = current_stamp(); let segment_id = active.request.pending_segment_id; - // Every completion releases its slot, including errors, suppressed - // outputs and refused mutation. Frozen original text retires unchanged. + let mut native_changed = false; + // Every completion releases its slot. Only accepted results commit; + // failed or skipped work returns to executable context below. let applied = (|| { let output = completion.output; let notify_timeout = output.status == EngineStatus::TimedOut @@ -393,6 +425,11 @@ impl CorrectionPipeline { return false; } let original = &active.request.executable_context; + let no_change_reason = match output.no_change_reason { + Some(NoChangeReason::NoCorrectionNeeded) => Some("no_correction_needed"), + Some(NoChangeReason::AllCandidatesProtected) => Some("all_candidates_protected"), + _ => None, + }; if output.changes_needed { if target.focused_element_id.is_none() || output.behavior != ConfidenceBehavior::Silent @@ -401,14 +438,7 @@ impl CorrectionPipeline { { return false; } - } else if output.corrected_executable_text != *original - || !matches!( - output.no_change_reason, - Some( - NoChangeReason::NoCorrectionNeeded | NoChangeReason::AllCandidatesProtected - ) - ) - { + } else if output.corrected_executable_text != *original || no_change_reason.is_none() { return false; } if let Some(id) = segment_id { @@ -445,29 +475,127 @@ impl CorrectionPipeline { { return false; } - if output.changes_needed && !replace(&target, &active.request, &output) { - return false; - } + let confirmation = if output.changes_needed { + if !session.can_complete_correction( + segment_id, + original, + &output.corrected_executable_text, + ) { + return false; + } + let confirmation = replace(&target, &active.request, &output).into(); + if !confirmation.success { + return false; + } + native_changed = true; + if current_stamp() != validation_stamp { + return false; + } + Some(confirmation) + } else { + None + }; let session = manager.active_mut().unwrap(); - if let Some(id) = segment_id { - session.complete_pending(id, Some(&output.corrected_executable_text), limits) + let changed = output.changes_needed; + let confidence = output.confidence; + let completed = 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) && session.apply_next_correction(limits) } else { session.complete_without_changes(limits); true + }; + if completed && changed { + session.record_undo_metadata( + active.request.language_info.primary_language.clone(), + active.request.trigger, + confidence, + confirmation.unwrap(), + ); + } else if completed { + self.log_no_change_commit( + &active.request, + &active.target, + confidence, + no_change_reason.unwrap(), + output.engine_latency_ms, + ); } + completed })(); if !applied { + if native_changed { + // The document changed but session ownership was not committed. + // Never restore unchecked originals into a now-stale executable range. + self.cancel(); + manager.deactivate(super::typing::MovementSignal::UnknownPosition); + tracing::warn!("replacement bookkeeping lost session ownership"); + return false; + } if let (Some(id), Some(session)) = (segment_id, manager.active_mut()) { if session.id() == active.request.session_id { - session.complete_pending(id, None, limits); + for cancelled in session.restore_pending_from(id) { + self.cancel_segment(cancelled); + } } } } applied } + + /// 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( + &self, + request: &CorrectionRequest, + target: &FocusedTarget, + confidence: ConfidenceTier, + reason: &str, + latency_ms: u64, + ) { + tracing::info!( + session_id = request.session_id, + trigger = request.trigger.as_str(), + engine = ?request.engine, + confidence = ?confidence, + reason, + latency_ms, + replacement_method = "none", + "no-change context committed" + ); + let Some(path) = self.database_path.as_deref() else { + return; + }; + let metadata = crate::storage::CorrectionMetadata { + session_id: request.session_id.to_string(), + app_process_name: target.process_name.clone(), + trigger_type: request.trigger.as_str().into(), + confidence_tier: match confidence { + ConfidenceTier::High => "high", + ConfidenceTier::Medium => "medium", + ConfidenceTier::Low => "low", + } + .into(), + engine_used: match request.engine { + EngineKind::LocalRule => "local_rule", + EngineKind::LocalMl => "local_ml", + EngineKind::OpenAiCompatibleApi => "open_ai_compatible_api", + EngineKind::CustomApi => "custom_api", + } + .into(), + replacement_method: "none".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" + ); + } + } } /// Require the tracked original and following text at the live caret without searching. diff --git a/app-core-rust/src/background/pipeline/tests.rs b/app-core-rust/src/background/pipeline/tests.rs index dbb732a..1cfe5a3 100644 --- a/app-core-rust/src/background/pipeline/tests.rs +++ b/app-core-rust/src/background/pipeline/tests.rs @@ -12,6 +12,209 @@ const STAMP: InputStamp = InputStamp { sequence: 12, }; +/// Unavailable exclusion storage refuses submission without dispatching work or changing session text. +#[test] +fn unavailable_exclusions_refuse_submission_without_storage_side_effects() { + for failure in ["missing", "schema", "locked"] { + let path = std::env::temp_dir().join(format!( + "autofix-submit-policy-{}-{}.sqlite", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let config = AppConfig::default(); + let manager = manager(&config, "teh"); + let mut connection = None; + let mut database = None; + if failure != "missing" { + let writer = rusqlite::Connection::open(&path).unwrap(); + if failure == "schema" { + writer + .execute_batch("create table sentinel (value text)") + .unwrap(); + } else { + database = Some(crate::storage::Database::open(&path).unwrap()); + writer + .execute_batch("PRAGMA journal_mode=delete; BEGIN EXCLUSIVE") + .unwrap(); + } + connection = Some(writer); + } + let mut pipeline = + CorrectionPipeline::start(|_| panic!("unavailable exclusions must not reach engine")) + .unwrap(); + pipeline.database_path = Some(path.clone()); + let started = Instant::now(); + assert!(!pipeline.submit( + request(&manager, &config), + manager.active().unwrap(), + target(), + STAMP, + &config, + vec![] + )); + assert!(started.elapsed() < Duration::from_millis(250)); + assert!(pipeline.active.is_empty()); + assert!(pipeline.mailbox.0.lock().unwrap().jobs.is_empty()); + assert_eq!(manager.active().unwrap().editable_context(), "teh"); + if failure == "schema" { + let tables: usize = connection + .as_ref() + .unwrap() + .query_row( + "select count(*) from sqlite_master where type = 'table'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(tables, 1); + } + drop(pipeline); + drop(connection); + drop(database); + if failure == "missing" { + assert!(!path.exists()); + } else { + std::fs::remove_file(path).unwrap(); + } + } +} + +/// Submission reads compatible exclusion tables without invoking migrations, even during an API send. +#[test] +fn submit_uses_exclusion_snapshot_without_migration_writes() { + for journal in ["delete", "wal"] { + let path = std::env::temp_dir().join(format!( + "autofix-submit-no-migrate-{}-{}.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 writer = rusqlite::Connection::open(&path).unwrap(); + writer + .execute_batch(&format!( + "PRAGMA journal_mode={journal}; drop table schema_migrations; + insert into custom_dictionary_entries(language_code,entry) values ('en','teh');" + )) + .unwrap(); + let config = AppConfig::default(); + let manager = manager(&config, "teh"); + let mut pipeline = CorrectionPipeline::start(|job| { + assert_eq!(job.exclusions.terms, ["teh"]); + CorrectionOutput::unchanged( + job.input.executable_context.clone(), + ConfidenceTier::High, + NoChangeReason::NoCorrectionNeeded, + 0, + ) + }) + .unwrap(); + pipeline.database_path = Some(path.clone()); + let guard = crate::storage::AppPolicyGuard::acquire(&path).unwrap(); + let started = Instant::now(); + assert!(pipeline.submit( + request(&manager, &config), + manager.active().unwrap(), + target(), + STAMP, + &config, + vec![] + )); + assert!(started.elapsed() < Duration::from_millis(250)); + wait_completion(&pipeline); + let migration_tables: usize = writer + .query_row( + "select count(*) from sqlite_master where name = 'schema_migrations'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(migration_tables, 0); + drop(guard); + drop(pipeline); + drop(writer); + drop(database); + std::fs::remove_file(path).unwrap(); + } +} + +/// Persisted pairs filter worker edits without losing the original correction language. +#[test] +fn persisted_pair_filters_worker_edits_and_learns_original_language() { + let path = std::env::temp_dir().join(format!( + "autofix-pair-pipeline-{}.sqlite", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let db = crate::storage::Database::open(&path).unwrap(); + let rejection = crate::dictionary::Rejection::from_undo( + "teh", + "the", + Some("en".into()), + "notepad.exe".into(), + ) + .unwrap(); + let learning = crate::settings::LearningConfig { + mode: crate::settings::LearningMode::Automatic, + ..Default::default() + }; + db.dictionary().remember(&rejection, &learning).unwrap(); + let mut config = AppConfig::default(); + config.correction.preferred_language = Some("en".into()); + let mut manager = manager(&config, "teh wierd"); + let mut pipeline = CorrectionPipeline::with_database(&db).unwrap(); + let mut request = request(&manager, &config); + request.language_info = crate::correction::LanguageInfo { + primary_language: Some("en".into()), + detected_languages: vec!["en".into()], + }; + assert!(pipeline.submit( + request, + manager.active().unwrap(), + target(), + STAMP, + &config, + vec![] + )); + wait_completion(&pipeline); + let replaced = Cell::new(0); + assert!(finish( + &mut pipeline, + &mut manager, + &config, + STAMP, + &replaced, + true + )); + assert_eq!(replaced.get(), 1); + assert_eq!(manager.active().unwrap().informative_context(), "teh weird"); + assert_eq!( + manager + .active() + .unwrap() + .undo_target() + .unwrap() + .language + .as_deref(), + Some("en") + ); + assert!(manager + .active_mut() + .unwrap() + .undo_last_correction(&config.context)); + assert_eq!(manager.active().unwrap().informative_context(), "teh wierd"); + drop(pipeline); + drop(db); + std::fs::remove_file(path).unwrap(); +} + /// A real queued API job must not transmit after revocation commits behind an earlier send. #[test] fn queued_api_job_is_denied_after_rule_revocation_and_releases_its_slot() { @@ -147,28 +350,20 @@ fn queued_api_job_is_denied_after_rule_revocation_and_releases_its_slot() { || STAMP, |_| None, |_, _| panic!("revoked target must not be captured"), - |_, _, _| panic!("revoked target must not be edited") - )); - wait_completion(&pipeline); - assert!(!pipeline.finish( - &mut manager, - &config.context, - || STAMP, - |_| panic!("denied send must complete silently"), - |_, _| panic!("denied send must not capture"), - |_, _, _| panic!("denied send must not replace") + |_, _, _| -> bool { panic!("revoked target must not be edited") } )); + // The rejected first segment restores the dependent queued request too. let listener = server.join().unwrap(); assert_eq!( listener.accept().unwrap_err().kind(), std::io::ErrorKind::WouldBlock ); assert!(pipeline.active.is_empty()); + assert_eq!(manager.active().unwrap().informative_context(), ""); assert_eq!( - manager.active().unwrap().informative_context(), - "First. Second." + manager.active().unwrap().editable_context(), + "First. Second. next" ); - assert_eq!(manager.active().unwrap().editable_context(), " next"); assert!(!pipeline.take_timeout_notice()); } @@ -274,7 +469,7 @@ fn stale_cancelled_or_secure_timeouts_cannot_show_notices() { Some(live) }, |_, _| panic!("timeout must not read target text"), - |_, _, _| panic!("timeout must not replace text"), + |_, _, _| -> bool { panic!("timeout must not replace text") }, )); assert!(!pipeline.take_timeout_notice()); } @@ -298,12 +493,12 @@ fn automatic_timeout_releases_frozen_slot_without_live_target_calls() { || STAMP, |_| panic!("automatic timeout must skip live security/UIA calls"), |_, _| panic!("automatic timeout must not capture text"), - |_, _, _| panic!("automatic timeout must not replace text"), + |_, _, _| -> bool { panic!("automatic timeout must not replace text") }, )); assert!(!pipeline.take_timeout_notice()); assert!(pipeline.active.is_empty()); - assert_eq!(manager.active().unwrap().informative_context(), "teh"); - assert_eq!(manager.active().unwrap().editable_context(), " next"); + assert_eq!(manager.active().unwrap().informative_context(), ""); + assert_eq!(manager.active().unwrap().editable_context(), "teh next"); } /// Build a safe ordinary control with stable focus identity. @@ -376,10 +571,12 @@ fn submit_frozen( .active_mut() .unwrap() .freeze_pending(&config.context); - if let Some(id) = cancelled { + for id in cancelled { pipeline.cancel_segment(id); } let id = segment.unwrap(); + (request.informative_context, request.executable_context) = + manager.active().unwrap().pending_context(id).unwrap(); request.pending_segment_id = Some(id); pipeline.submit( request, @@ -415,7 +612,7 @@ fn delayed_frozen_corrections_keep_all_results_and_preserve_newer_typing() { sequence: STAMP.sequence + 5, ..STAMP }; - pipeline.invalidate(&manager, stamp); + pipeline.invalidate(&mut manager, stamp); assert_eq!(pipeline.active.len(), 2); release_tx.send(()).unwrap(); wait_completion(&pipeline); @@ -479,7 +676,11 @@ fn cancel_oldest_suppresses_late_transport_and_runs_new_segment() { submit_frozen(&mut pipeline, &mut manager, &config); assert!(cancelled.load(Ordering::Acquire)); assert_eq!(pipeline.active.len(), 1); - assert_eq!(manager.active().unwrap().informative_context(), "teh"); + assert_eq!(manager.active().unwrap().informative_context(), ""); + assert_eq!( + pipeline.active.front().unwrap().request.executable_context, + "teh teh" + ); release_tx.send(()).unwrap(); let newest = started_rx.recv_timeout(Duration::from_secs(2)).unwrap(); assert_ne!(first, newest); @@ -494,14 +695,14 @@ fn cancel_oldest_suppresses_late_transport_and_runs_new_segment() { &Cell::new(0), true )); - assert_eq!(manager.active().unwrap().informative_context(), "teh the"); + assert_eq!(manager.active().unwrap().informative_context(), "the the"); } -/// Failed and suppressed corrections retire originals without importing engine output. +/// Failed and suppressed corrections restore unchecked text and release capacity. #[test] fn frozen_failures_release_capacity_without_committing_engine_output() { let config = AppConfig::default(); - for failure in 0..5 { + for failure in 0..9 { let mut manager = manager(&config, "teh"); let mut pipeline = CorrectionPipeline::new().unwrap(); submit_frozen(&mut pipeline, &mut manager, &config); @@ -515,6 +716,34 @@ fn frozen_failures_release_capacity_without_committing_engine_output() { 1 => output.behavior = ConfidenceBehavior::Suggestion, 2 => output.confidence = ConfidenceTier::Low, 3 | 4 => {} + 5 => { + *output = CorrectionOutput::failed( + "teh".into(), + crate::correction::EngineFailure { + kind: crate::correction::EngineFailureKind::Internal, + message: "test failure".into(), + retryable: false, + }, + 0, + ) + } + 6 => output.behavior = ConfidenceBehavior::DoNothing, + 7 => { + *output = CorrectionOutput::unchanged( + "teh".into(), + ConfidenceTier::Medium, + NoChangeReason::ConfidenceBelowConfiguredBehavior, + 0, + ) + } + 8 => { + *output = CorrectionOutput::unchanged( + "teh".into(), + ConfidenceTier::Low, + NoChangeReason::UnsupportedLanguage, + 0, + ) + } _ => unreachable!(), } } @@ -532,8 +761,9 @@ fn frozen_failures_release_capacity_without_committing_engine_output() { } )); assert_eq!(calls.get(), usize::from(failure == 3)); - assert_eq!(manager.active().unwrap().informative_context(), "teh"); - assert_eq!(manager.active().unwrap().editable_context(), " next"); + assert_eq!(manager.active().unwrap().informative_context(), ""); + assert_eq!(manager.active().unwrap().editable_context(), "teh next"); + assert!(manager.active().unwrap().undo_target().is_none()); assert!(manager .active_mut() .unwrap() @@ -543,6 +773,212 @@ fn frozen_failures_release_capacity_without_committing_engine_output() { } } +/// Failure cancels dependent work and preserves the whole span for a successful retry. +#[test] +fn failed_frozen_prefix_restores_dependents_and_can_be_corrected_on_retry() { + let mut config = AppConfig::default(); + config.context.pending_queue_size = 2; + let mut manager = manager(&config, "teh"); + let mut pipeline = CorrectionPipeline::new().unwrap(); + submit_frozen(&mut pipeline, &mut manager, &config); + wait_completion(&pipeline); + manager.input(TypedInput::Text(" wierd".into())); + submit_frozen(&mut pipeline, &mut manager, &config); + let cancelled = pipeline.active.back().unwrap().cancelled.clone(); + manager.input(TypedInput::Text(" 尾".into())); + pipeline + .mailbox + .0 + .lock() + .unwrap() + .completion + .as_mut() + .unwrap() + .output = CorrectionOutput::timed_out("teh".into(), 700); + assert!(!finish( + &mut pipeline, + &mut manager, + &config, + STAMP, + &Cell::new(0), + false + )); + assert!(cancelled.load(Ordering::Acquire)); + assert!(pipeline.active.is_empty()); + assert_eq!(manager.active().unwrap().informative_context(), ""); + assert_eq!(manager.active().unwrap().editable_context(), "teh wierd 尾"); + submit_frozen(&mut pipeline, &mut manager, &config); + wait_completion(&pipeline); + assert!(finish( + &mut pipeline, + &mut manager, + &config, + STAMP, + &Cell::new(0), + true + )); + assert_eq!( + manager.active().unwrap().informative_context(), + "the weird 尾" + ); + assert_eq!(manager.active().unwrap().editable_context(), ""); + assert!(manager + .active_mut() + .unwrap() + .undo_last_correction(&config.context)); + assert_eq!( + manager.active().unwrap().informative_context(), + "teh wierd 尾" + ); +} + +/// Every trigger accepts only checked unchanged text and shrinks its read-only context. +#[test] +fn unchanged_commit_policy_preserves_skips_for_all_triggers() { + let path = std::env::temp_dir().join(format!( + "autofix-no-change-{}.sqlite", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let database = crate::storage::Database::open(&path).unwrap(); + let connection = rusqlite::Connection::open(&path).unwrap(); + for trigger in [ + TriggerKind::ManualShortcut, + TriggerKind::WordCount, + TriggerKind::Character, + TriggerKind::FinalFixBeforeReanchor, + ] { + for reason in [ + NoChangeReason::NoCorrectionNeeded, + NoChangeReason::AllCandidatesProtected, + NoChangeReason::ConfidenceBelowConfiguredBehavior, + NoChangeReason::UnsupportedLanguage, + NoChangeReason::UncertainLanguage, + NoChangeReason::EngineUnavailable, + NoChangeReason::TimedOut, + NoChangeReason::EngineError, + ] { + let mut config = AppConfig::default(); + config.context.informative_context_max_chars = 12; + config.logging.debug_mode_enabled = true; + config.logging.full_text_debug_mode_enabled = true; + let mut manager = manager(&config, "hello"); + manager.set_informative_context("Old context ".into()); + database.clear_logs().unwrap(); + let mut pipeline = CorrectionPipeline::with_database(&database).unwrap(); + if matches!(trigger, TriggerKind::WordCount | TriggerKind::Character) { + submit_frozen(&mut pipeline, &mut manager, &config); + pipeline.active.front_mut().unwrap().request.trigger = trigger; + manager.input(TypedInput::Text(" 尾".into())); + } else { + let mut request = request(&manager, &config); + request.trigger = trigger; + assert!(pipeline.submit( + request, + manager.active().unwrap(), + target(), + STAMP, + &config, + vec![] + )); + } + wait_completion(&pipeline); + pipeline + .mailbox + .0 + .lock() + .unwrap() + .completion + .as_mut() + .unwrap() + .output = CorrectionOutput::unchanged( + "hello".into(), + ConfidenceTier::Low, + reason.clone(), + 17, + ); + let accepted = matches!( + reason, + NoChangeReason::NoCorrectionNeeded | NoChangeReason::AllCandidatesProtected + ); + let calls = Cell::new(0); + assert_eq!( + finish(&mut pipeline, &mut manager, &config, STAMP, &calls, false), + accepted + ); + assert_eq!(calls.get(), 0); + // A completion is consumed once, including its metadata event. + assert!(!finish( + &mut pipeline, + &mut manager, + &config, + STAMP, + &calls, + false + )); + let events: i64 = connection + .query_row("select count(*) from correction_metadata", [], |row| { + row.get(0) + }) + .unwrap(); + assert_eq!(events, i64::from(accepted)); + if accepted { + let metadata: (String, String, String, String, String, String, u64) = connection.query_row( + "select session_id, app_process_name, trigger_type, confidence_tier, replacement_method, result_reason, latency_ms from correction_metadata", + [], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?, row.get(5)?, row.get(6)?)) + ).unwrap(); + assert_eq!( + metadata, + ( + manager.active().unwrap().id().to_string(), + "notepad.exe".into(), + trigger.as_str().into(), + "low".into(), + "none".into(), + if reason == NoChangeReason::NoCorrectionNeeded { + "no_correction_needed" + } else { + "all_candidates_protected" + } + .into(), + 17 + ) + ); + } + let debug_events: i64 = connection + .query_row("select count(*) from debug_events", [], |row| row.get(0)) + .unwrap(); + assert_eq!(debug_events, 0); + let session = manager.active().unwrap(); + let newer = if matches!(trigger, TriggerKind::WordCount | TriggerKind::Character) { + " 尾" + } else { + "" + }; + assert_eq!( + session.editable_context(), + if accepted { + newer.to_owned() + } else { + format!("hello{newer}") + } + ); + if accepted { + assert!(session.informative_context().ends_with("hello")); + assert!(session.informative_context().chars().count() <= 12); + } else { + assert_eq!(session.informative_context(), "Old context "); + } + assert!(session.undo_target().is_none()); + } + } + drop(connection); + drop(database); + std::fs::remove_file(path).unwrap(); +} + /// Completion rejects position changes and input arriving during live security validation. #[test] fn frozen_result_revalidates_queued_position_and_input_during_security_check() { @@ -565,7 +1001,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 replacement") + |_, _, _| -> bool { panic!("raced input reached replacement") } )); } } @@ -632,6 +1068,7 @@ fn input_processor_defers_frozen_completion_until_hook_input_is_drained() { submit_frozen(&mut pipeline, &mut manager, &config); wait_completion(&pipeline); let mut processor = crate::background::InputProcessor { + learner: crate::dictionary::Learner::default(), pipeline, processed_input_sequence: crate::background::input_listener::current_input_sequence() .wrapping_sub(1), @@ -700,6 +1137,152 @@ fn finish( ) } +/// A policy writer must not delay accepted no-change commits or later input. +#[test] +fn no_change_metadata_contention_never_stalls_completion() { + for mode in ["delete", "wal"] { + let path = std::env::temp_dir().join(format!( + "autofix-nowait-{mode}-{}.sqlite", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let database = crate::storage::Database::open(&path).unwrap(); + let writer = rusqlite::Connection::open(&path).unwrap(); + writer.pragma_update(None, "journal_mode", mode).unwrap(); + let config = AppConfig::default(); + let mut manager = manager(&config, "hello"); + let mut pipeline = CorrectionPipeline::with_database(&database).unwrap(); + submit_frozen(&mut pipeline, &mut manager, &config); + wait_completion(&pipeline); + manager.input(TypedInput::Text(" 尾".into())); + writer.execute_batch("BEGIN IMMEDIATE").unwrap(); + let calls = Cell::new(0); + let started = Instant::now(); + assert!(finish( + &mut pipeline, + &mut manager, + &config, + STAMP, + &calls, + false + )); + assert!(started.elapsed() < Duration::from_millis(250)); + assert_eq!(calls.get(), 0); + assert_eq!(manager.active().unwrap().informative_context(), "hello"); + assert_eq!(manager.active().unwrap().editable_context(), " 尾"); + manager.input(TypedInput::Text(" next".into())); + assert_eq!(manager.active().unwrap().editable_context(), " 尾 next"); + assert!(pipeline.active.is_empty()); + writer.execute_batch("ROLLBACK").unwrap(); + let count: i64 = writer + .query_row("select count(*) from correction_metadata", [], |row| { + row.get(0) + }) + .unwrap(); + assert_eq!(count, 0); + // Losing optional telemetry does not poison later accepted commits. + submit(&mut pipeline, &manager, &config); + wait_completion(&pipeline); + assert!(finish( + &mut pipeline, + &mut manager, + &config, + STAMP, + &calls, + false + )); + let count: i64 = writer + .query_row("select count(*) from correction_metadata", [], |row| { + row.get(0) + }) + .unwrap(); + assert_eq!(count, 1); + drop(pipeline); + drop(writer); + drop(database); + std::fs::remove_file(path).unwrap(); + } +} + +/// Manual expansion must fit the Unicode typed buffer before any native mutation. +#[test] +fn oversized_manual_result_is_refused_before_native_replacement() { + let config = AppConfig::default(); + let original = format!("{}teh", "é".repeat(4093)); + let mut manager = manager(&config, &original); + let mut pipeline = CorrectionPipeline::new().unwrap(); + submit(&mut pipeline, &manager, &config); + wait_completion(&pipeline); + let mut state = pipeline.mailbox.0.lock().unwrap(); + state.completion.as_mut().unwrap().output = CorrectionOutput::changed( + format!("{}the!", "é".repeat(4093)), + ConfidenceTier::High, + None, + 1, + ); + drop(state); + let calls = Cell::new(0); + assert!(!finish( + &mut pipeline, + &mut manager, + &config, + STAMP, + &calls, + true + )); + assert_eq!(calls.get(), 0); + assert_eq!(manager.active().unwrap().editable_context(), original); + assert!(manager.active().unwrap().informative_context().is_empty()); + assert!(manager.active().unwrap().undo_target().is_none()); +} + +/// Input arriving after a successful edit invalidates ownership and dependent work. +#[test] +fn input_race_after_native_success_drops_session_instead_of_restoring_stale_text() { + for frozen in [false, true] { + let mut config = AppConfig::default(); + config.context.pending_queue_size = 2; + let mut manager = manager(&config, "teh"); + let mut pipeline = CorrectionPipeline::new().unwrap(); + if frozen { + submit_frozen(&mut pipeline, &mut manager, &config); + manager.input(TypedInput::Text(" next".into())); + submit_frozen(&mut pipeline, &mut manager, &config); + } else { + submit(&mut pipeline, &manager, &config); + } + wait_completion(&pipeline); + let live = manager.active().unwrap().executable_context(); + let current = Cell::new(STAMP); + let calls = Cell::new(0); + assert!(!pipeline.finish( + &mut manager, + &config.context, + || current.get(), + |_| Some(target()), + |_, _| Some(live), + |_, _, _| { + calls.set(calls.get() + 1); + current.set(InputStamp { + sequence: STAMP.sequence + 1, + ..STAMP + }); + true + } + )); + assert_eq!(calls.get(), 1); + assert!(manager.active().is_none()); + assert!(pipeline.active.is_empty()); + assert!(pipeline.mailbox.0.lock().unwrap().jobs.is_empty()); + manager.focus(&target()); + manager.input(TypedInput::Text("fresh".into())); + assert_eq!(manager.active().unwrap().editable_context(), "fresh"); + assert!(manager.active().unwrap().undo_target().is_none()); + } +} + /// Confirmed replacement commits once and records the original span for undo. #[test] fn valid_result_replaces_once_then_records_commit_and_undo() { @@ -823,7 +1406,7 @@ fn security_and_input_changes_during_live_validation_block_replacement() { Some(target) }, |_, _| panic!("invalid result reached live range validation"), - |_, _, _| panic!("invalid result reached replacement") + |_, _, _| -> bool { panic!("invalid result reached replacement") } )); assert_eq!(manager.active().unwrap().editable_context(), "teh"); } @@ -857,7 +1440,8 @@ fn live_range_must_match_exactly_before_caret() { } )); assert_eq!(calls.get(), 0); - assert_eq!(manager.active().unwrap().informative_context(), "teh"); + assert_eq!(manager.active().unwrap().informative_context(), ""); + assert_eq!(manager.active().unwrap().editable_context(), "teh"); } } @@ -953,7 +1537,7 @@ fn unchanged_success_commits_only_after_validation() { || STAMP, |_| Some(target()), |_, _| Some(live), - |_, _, _| panic!("unchanged text needs no replacement") + |_, _, _| -> bool { panic!("unchanged text needs no replacement") } )); assert_eq!(manager.active().unwrap().informative_context(), "hello"); assert_eq!(manager.active().unwrap().editable_context(), ""); @@ -1049,7 +1633,7 @@ fn slow_engine_never_blocks_automatic_input_and_keeps_only_latest_queued_work() let cancelled = Arc::clone(&pipeline.active.front().unwrap().cancelled); let start = Instant::now(); manager.input(TypedInput::Text("!".into())); - pipeline.invalidate(&manager, STAMP); + pipeline.invalidate(&mut manager, STAMP); assert!(cancelled.load(Ordering::Acquire)); manager.input(TypedInput::Backspace); for _ in 0..32 { diff --git a/app-core-rust/src/background/replacement/mod.rs b/app-core-rust/src/background/replacement/mod.rs index 76a2fb7..7542a69 100644 --- a/app-core-rust/src/background/replacement/mod.rs +++ b/app-core-rust/src/background/replacement/mod.rs @@ -66,6 +66,36 @@ pub(super) struct ReplacementResult { pub(super) may_have_changed: bool, } +/// Verified mutation metadata passed to the session's undo owner. +#[derive(Default)] +pub(super) struct ReplacementConfirmation { + pub(super) success: bool, + pub(super) method: Option, + pub(super) range: Option, +} + +impl From for ReplacementConfirmation { + /// Pass the verified native receipt to session bookkeeping without document text. + fn from(result: ReplacementResult) -> Self { + Self { + success: result.success, + method: result.method, + range: result.range, + } + } +} + +#[cfg(test)] +impl From for ReplacementConfirmation { + /// Supply a minimal success receipt for tests that replace through a fake native boundary. + fn from(success: bool) -> Self { + Self { + success, + ..Self::default() + } + } +} + impl ReplacementResult { /// Native failures remain visible with default logging. No target text is logged. pub(super) fn log_outcome(&self, undo: bool) { diff --git a/app-core-rust/src/background/replacement/tests.rs b/app-core-rust/src/background/replacement/tests.rs index ca3b050..59fccd8 100644 --- a/app-core-rust/src/background/replacement/tests.rs +++ b/app-core-rust/src/background/replacement/tests.rs @@ -374,6 +374,7 @@ fn app_undo_refuses_partially_retained_correction() { #[ignore = "requires an interactive Windows desktop; briefly focuses an isolated test editor"] fn native_edit_replacement_smoke() { const EM_SETSEL: u32 = 0x00b1; + use crate::background::security::TriggerKind; use std::{ io::{BufRead, BufReader, Read}, os::windows::process::CommandExt, @@ -518,6 +519,116 @@ fn native_edit_replacement_smoke() { 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) = + 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)); + } for (method, original, replacement, following) in [ (ReplacementMethod::Clipboard, "teh", "the", ""), (ReplacementMethod::Clipboard, "teh", "the", " newer"), @@ -648,6 +759,58 @@ fn native_edit_replacement_smoke() { .encode_utf16() .count() as u32; assert_eq!((caret_start, caret_end), (expected_caret, expected_caret)); + + // Exercise app undo using committed history, never target Ctrl+Z. + let limits = AppConfig::default().context; + let mut manager = SessionManager::new(limits.clone()); + manager.focus(&after); + manager.set_informative_context("old ".into()); + manager.input(TypedInput::Text(original.into())); + let segment = manager + .active_mut() + .unwrap() + .freeze_pending(&limits) + .0 + .unwrap(); + manager.input(TypedInput::Text(following.into())); + assert!(manager + .active_mut() + .unwrap() + .complete_pending(segment, replacement, &limits)); + let undo = manager.active().unwrap().undo_target().unwrap(); + let undone = + ReplacementEngine::undo(&after, &undo, stamp, method == ReplacementMethod::Clipboard); + assert!(undone.success, "{undone:?}"); + assert!(manager.active_mut().unwrap().undo_last_correction(&limits)); + assert_eq!( + manager.active().unwrap().informative_context(), + format!("old {original}") + ); + assert_eq!(manager.active().unwrap().editable_context(), following); + let restored_length = unsafe { + SendMessageW( + edit as _, + WM_GETTEXT, + observed.len(), + observed.as_mut_ptr() as isize, + ) + }; + assert_eq!( + String::from_utf16_lossy(&observed[..restored_length as usize]), + initial + ); + unsafe { + 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), + (initial_caret, initial_caret) + ); } } diff --git a/app-core-rust/src/background/session.rs b/app-core-rust/src/background/session.rs index 2d54014..8ce1b1d 100644 --- a/app-core-rust/src/background/session.rs +++ b/app-core-rust/src/background/session.rs @@ -13,6 +13,9 @@ use crate::settings::ContextConfig; mod pending; use pending::FrozenSegment; +mod undo; +use undo::CorrectionUndo; +pub(super) use undo::CorrectionUndoTarget; #[derive(Debug, Clone, PartialEq, Eq, Hash)] struct SessionIdentity { @@ -38,22 +41,6 @@ pub(crate) struct PendingCorrection { pub(crate) versions: ContextVersions, } -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct CorrectionUndo { - original: String, - replacement: String, - informative_start: usize, - caret_anchor: u64, - complete_range_retained: bool, -} - -/// Only a recorded, fully retained app correction may make informative text editable. -pub(super) struct CorrectionUndoTarget { - pub(super) corrected: String, - pub(super) original: String, - pub(super) following: String, -} - pub(crate) struct Session { id: u64, // Informative text is known session text before the executable segment. @@ -227,7 +214,7 @@ impl Session { tracked_arrows_only, }); self.pending_corrections.clear(); - self.correction_undo_history.clear(); + self.invalidate_undo_anchors(); self.versions.caret_anchor = self.versions.caret_anchor.wrapping_add(1); } @@ -266,6 +253,7 @@ impl Session { self.pending_movement = None; self.correction_floor = 0; self.informative_context.clear(); + self.invalidate_undo_anchors(); return; } } @@ -277,13 +265,14 @@ impl Session { self.executable.invalidate(MovementSignal::UnknownPosition); self.correction_floor = 0; self.informative_context.clear(); + self.invalidate_undo_anchors(); self.pending_corrections.clear(); return; } if matches!(&input, TypedInput::Backspace) && self.executable_context().is_empty() { // The user may have deleted text we only keep as read-only context. self.informative_context.clear(); - self.correction_undo_history.clear(); + self.invalidate_undo_anchors(); } let is_text_edit = matches!(&input, TypedInput::Text(value) if !value.is_empty()) || matches!(&input, TypedInput::Backspace | TypedInput::Delete); @@ -312,10 +301,21 @@ impl Session { self.versions.executable = self.versions.executable.wrapping_add(1); self.pending_corrections.clear(); } - if self.editable_context().split_whitespace().count() - > usize::from(limits.executable_context_max_words) - { + self.enforce_executable_limit(limits); + } + + /// Retire oversized active text only after its pre-caret position is known. + fn enforce_executable_limit(&mut self, limits: &ContextConfig) { + let words = self.editable_context().split_whitespace().count(); + if !self.position_uncertain() && words > usize::from(limits.executable_context_max_words) { self.commit_executable(limits); + tracing::info!( + session_id = self.id, + executable_words = words, + max_words = limits.executable_context_max_words, + reason = "executable_context_max_words", + "original context committed" + ); } } @@ -441,9 +441,11 @@ impl Session { /// Bound read-only context in memory after an append or commit. fn shrink_informative(&mut self, limits: &ContextConfig) { + let previous_len = self.informative_context.len(); if super::informative_context::shrink(&mut self.informative_context, limits) { - self.correction_undo_history.clear(); + self.trim_undo_anchors(previous_len - self.informative_context.len()); } + self.limit_undo_history(limits); } /// Move only known text before the caret into read-only context. @@ -505,15 +507,41 @@ impl Session { self.informative_context = context; self.shrink_informative(limits); self.pending_corrections.clear(); - self.correction_undo_history.clear(); + self.invalidate_undo_anchors(); self.versions.context = self.versions.context.wrapping_add(1); self.versions.caret_anchor = self.versions.caret_anchor.wrapping_add(1); } /// Queue a replacement only for an exact, stable typed suffix. pub(crate) fn queue_correction(&mut self, original: String, replacement: String) -> bool { + if !self.can_complete_correction(None, &original, &replacement) { + return false; + } + self.pending_corrections.push_back(PendingCorrection { + original, + replacement, + versions: self.versions, + }); + true + } + + /// 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( + &self, + segment_id: Option, + original: &str, + replacement: &str, + ) -> bool { + if let Some(id) = segment_id { + return self + .frozen_segments + .front() + .is_some_and(|segment| segment.id() == id) + && self.pending_matches(id, original); + } if original.is_empty() - || !self.executable_context().ends_with(&original) + || !self.executable_context().ends_with(original) || original.chars().count() > self .executable_context() @@ -524,12 +552,8 @@ impl Session { { return false; } - self.pending_corrections.push_back(PendingCorrection { - original, - replacement, - versions: self.versions, - }); - true + self.executable + .can_replace_executable_suffix(original, replacement) } /// Commit a queued replacement into read-only context and record its undo span. @@ -538,10 +562,14 @@ impl Session { let Some(correction) = self.pending_corrections.pop_front() else { return false; }; - if correction.versions != self.versions - || !self - .executable - .replace_executable_suffix(&correction.original, &correction.replacement) + if correction.versions != self.versions { + return false; + } + let executable_end = self.executable_context().chars().count(); + let executable_range = executable_end - correction.original.chars().count()..executable_end; + if !self + .executable + .replace_executable_suffix(&correction.original, &correction.replacement) { return false; } @@ -552,75 +580,12 @@ impl Session { self.versions.context = self.versions.context.wrapping_add(1); self.versions.executable = self.versions.executable.wrapping_add(1); } - let retained_chars = correction - .replacement - .chars() - .count() - .min(self.informative_context.chars().count()); - let replacement_start = correction - .replacement - .char_indices() - .nth(correction.replacement.chars().count() - retained_chars) - .map_or(correction.replacement.len(), |(index, _)| index); - let replacement = correction.replacement[replacement_start..].to_owned(); - if let Some(informative_start) = self - .informative_context - .len() - .checked_sub(replacement.len()) - .filter(|start| self.informative_context.get(*start..) == Some(replacement.as_str())) - { - self.correction_undo_history.push(CorrectionUndo { - complete_range_retained: replacement == correction.replacement, - original: correction.original, - replacement, - informative_start, - caret_anchor: self.versions.caret_anchor, - }); - } - true - } - - pub(super) fn undo_target(&self) -> Option { - let last = self.correction_undo_history.last()?; - let end = last.informative_start.checked_add(last.replacement.len())?; - if self.position_uncertain() - || !last.complete_range_retained - || last.caret_anchor != self.versions.caret_anchor - || self.informative_context.get(last.informative_start..end)? != last.replacement - { - return None; - } - Some(CorrectionUndoTarget { - corrected: last.replacement.clone(), - original: last.original.clone(), - following: format!( - "{}{}", - self.informative_context.get(end..)?, - self.executable_context() - ), - }) - } - - /// Restore a recorded original in session context while preserving newer typed text. - pub(crate) fn undo_last_correction(&mut self, limits: &ContextConfig) -> bool { - let Some(last) = self.correction_undo_history.last().cloned() else { - return false; - }; - if last.caret_anchor != self.versions.caret_anchor { - return false; - } - let start = last.informative_start; - let end = start + last.replacement.len(); - if self.informative_context.get(start..end) != Some(last.replacement.as_str()) { - return false; - } - self.restore_pending(); - self.informative_context - .replace_range(start..end, &last.original); - self.correction_undo_history.pop(); - self.shrink_informative(limits); - self.pending_corrections.clear(); - self.versions.context = self.versions.context.wrapping_add(1); + self.record_undo( + correction.original, + correction.replacement, + executable_range, + limits, + ); true } } @@ -640,17 +605,13 @@ impl SessionManager { } } + /// Apply live limits to retained context, undo history and oversized executable segments. pub(crate) fn update_limits(&mut self, limits: ContextConfig) { self.limits = limits; let active_limits = self.limits.clone(); - if let Some(session) = self.active_mut() { + for session in self.sessions.values_mut() { session.shrink_informative(&active_limits); - if !session.position_uncertain() - && session.executable_context().split_whitespace().count() - > usize::from(active_limits.executable_context_max_words) - { - session.commit_executable(&active_limits); - } + session.enforce_executable_limit(&active_limits); } } @@ -709,11 +670,14 @@ impl SessionManager { .map_or(0, Session::movement_capture_extra_chars) } + /// Resolve the new caret using read-only evidence, then enforce the active text limit. pub(crate) fn resolve_movement(&mut self, preceding: Option<&str>) -> MovementResolution { let limits = self.limits.clone(); self.active_mut() .map_or(MovementResolution::Continued, |session| { - session.resolve_movement(preceding, &limits) + let resolution = session.resolve_movement(preceding, &limits); + session.enforce_executable_limit(&limits); + resolution }) } @@ -1359,6 +1323,7 @@ mod tests { assert_eq!(session.executable_context(), ""); } + /// Executable word limits accept the configured boundary and retire only excess known text. #[test] fn configurable_word_limit_commits_on_exceeding() { let limits = ContextConfig { @@ -1379,6 +1344,41 @@ mod tests { assert_eq!(manager.active().unwrap().executable_context(), " four"); } + /// Every movement-resolution route must bound resumed executable typing. + #[test] + fn movement_resolution_commits_oversized_original_context() { + for route in 0..4 { + let limits = ContextConfig { + executable_context_max_words: 1, + informative_context_max_chars: 12, + ..ContextConfig::default() + }; + let mut manager = SessionManager::new(limits); + manager.focus(&target(1, 10, None)); + manager.input(TypedInput::Text("typed".into())); + manager.input(if route < 2 { + TypedInput::Left + } else { + TypedInput::Uncertain(MovementSignal::HomeEnd) + }); + manager.input(TypedInput::Text(" one two".into())); + assert!(manager.active().unwrap().position_uncertain()); + manager.resolve_movement(match route { + 1 => Some("type one two"), + 3 => Some("typed gap one two"), + _ => None, + }); + let session = manager.active().unwrap(); + assert!(!session.position_uncertain()); + assert_eq!(session.executable_context(), "", "route {route}"); + assert!(session.informative_context().ends_with("one two")); + assert!(session.informative_context().chars().count() <= 12); + assert!(session.undo_target().is_none()); + manager.input(TypedInput::Text("new".into())); + assert_eq!(manager.active().unwrap().editable_context(), "new"); + } + } + #[test] fn updated_limit_commits_active_segment() { let mut manager = SessionManager::new(ContextConfig::default()); @@ -1407,8 +1407,9 @@ mod tests { assert_eq!(session.informative_context(), "extra"); } + /// Informative context truncation cannot leave a partial span eligible for undo. #[test] - fn undo_restores_original_suffix_after_informative_limit() { + fn undo_refuses_incomplete_corrected_span_after_informative_limit() { let limits = ContextConfig { informative_context_max_chars: 4, ..ContextConfig::default() @@ -1420,8 +1421,8 @@ mod tests { assert!(session.queue_correction("abcdef".into(), "uvwxyz".into())); assert!(session.apply_next_correction(&limits)); assert_eq!(session.informative_context(), "wxyz"); - assert!(session.undo_last_correction(&limits)); - assert_eq!(session.informative_context(), "cdef"); + assert!(!session.undo_last_correction(&limits)); + assert_eq!(session.informative_context(), "wxyz"); } #[test] @@ -1542,6 +1543,7 @@ mod tests { assert!(manager.active().unwrap().executable_context().is_empty()); } + /// Repeated undo restores earlier corrections in order without losing newer typing. #[test] fn undo_history_can_walk_back_multiple_corrections() { let limits = ContextConfig::default(); @@ -1561,4 +1563,34 @@ mod tests { assert_eq!(session.informative_context(), "teh next"); assert_eq!(session.executable_context(), ""); } + + /// Live capacity reductions evict oldest records and session deletion removes all history. + #[test] + fn history_limit_reload_evicts_oldest_and_session_deletion_drops_history() { + let mut limits = ContextConfig::default(); + let mut manager = SessionManager::new(limits.clone()); + let editor = target(1, 10, None); + manager.focus(&editor); + for _ in 0..3 { + manager.input(TypedInput::Text("teh ".into())); + let session = manager.active_mut().unwrap(); + assert!(session.queue_correction("teh ".into(), "the ".into())); + assert!(session.apply_next_correction(&limits)); + } + let old_id = manager.active().unwrap().id(); + limits.undo_history_size = 1; + manager.update_limits(limits.clone()); + let session = manager.active_mut().unwrap(); + assert_eq!(session.correction_undo_history.len(), 1); + assert!(session.undo_last_correction(&limits)); + assert_eq!(session.informative_context(), "the the teh "); + assert!(!session.undo_last_correction(&limits)); + manager.deactivate(MovementSignal::FocusChange); + assert!(manager.sessions.is_empty()); + manager.focus(&editor); + let session = manager.active().unwrap(); + assert_ne!(session.id(), old_id); + assert!(session.correction_undo_history.is_empty()); + assert!(session.undo_target().is_none()); + } } diff --git a/app-core-rust/src/background/session/pending.rs b/app-core-rust/src/background/session/pending.rs index c3d8a1c..46dcd1f 100644 --- a/app-core-rust/src/background/session/pending.rs +++ b/app-core-rust/src/background/session/pending.rs @@ -1,5 +1,5 @@ //! Frozen automatic segments stay separate from the one active editable context. -use super::{ContextConfig, CorrectionUndo, Session}; +use super::{ContextConfig, Session}; use crate::settings::PendingQueueFullBehavior; pub(super) struct FrozenSegment { @@ -29,27 +29,38 @@ impl Session { context } + /// Snapshot a reserved range and its read-only prefix after overflow handling. + pub(crate) fn pending_context(&self, id: u64) -> Option<(String, String)> { + let mut informative = self.informative_context.clone(); + for segment in &self.frozen_segments { + if segment.id == id { + return Some((informative, segment.original.clone())); + } + informative.push_str(&segment.original); + } + None + } + /// Reserve capacity at the trigger, before later keys in the same batch. - /// Return the segment to submit and any worker request to cancel. - pub(crate) fn freeze_pending(&mut self, limits: &ContextConfig) -> (Option, Option) { + /// Return the segment to submit and all dependent worker requests to cancel. + pub(crate) fn freeze_pending(&mut self, limits: &ContextConfig) -> (Option, Vec) { if self.position_uncertain() || self.editable_context().trim().is_empty() { - return (None, None); + return (None, Vec::new()); } - let mut cancelled = None; + let mut cancelled = Vec::new(); if self.frozen_segments.len() >= usize::from(limits.pending_queue_size.clamp(1, 16)) { match limits.pending_queue_full_behavior { - PendingQueueFullBehavior::SkipNew => return (None, None), + PendingQueueFullBehavior::SkipNew => return (None, Vec::new()), PendingQueueFullBehavior::CancelOldest => { let oldest = self.frozen_segments.front().unwrap().id; - if !self.complete_pending(oldest, None, limits) { - return (None, None); - } - cancelled = Some(oldest); + // Unchecked text must stay executable. Restore the whole + // suffix before freezing it again, preserving document order. + cancelled = self.restore_pending_from(oldest); } PendingQueueFullBehavior::MergeNewest => { let newest = self.frozen_segments.pop_back().unwrap(); self.correction_floor -= newest.original.chars().count(); - return (None, Some(newest.id)); + return (None, vec![newest.id]); } } } @@ -97,12 +108,12 @@ impl Session { None } - /// Consume in document order. None discards the result and retires original - /// text; a replacement is recorded only after native mutation succeeds. + /// Commit only checked text, in document order. The caller confirms native + /// mutation first for changed text; unchanged text needs accepted engine output. pub(crate) fn complete_pending( &mut self, id: u64, - replacement: Option<&str>, + corrected: &str, limits: &ContextConfig, ) -> bool { let Some(segment) = self.frozen_segments.front() else { @@ -117,26 +128,16 @@ impl Session { return false; } self.correction_floor -= segment.original.chars().count(); - let corrected = replacement.unwrap_or(&segment.original); self.append_informative(corrected, limits); self.versions.context = self.versions.context.wrapping_add(1); if corrected != segment.original { - let retained_chars = corrected - .chars() - .count() - .min(self.informative_context.chars().count()); - let retained: String = corrected - .chars() - .skip(corrected.chars().count() - retained_chars) - .collect(); - let start = self.informative_context.len() - retained.len(); - self.correction_undo_history.push(CorrectionUndo { - complete_range_retained: retained == corrected, - original: segment.original, - replacement: retained, - informative_start: start, - caret_anchor: self.versions.caret_anchor, - }); + let executable_range = 0..segment.original.chars().count(); + self.record_undo( + segment.original, + corrected.to_owned(), + executable_range, + limits, + ); } true } @@ -150,7 +151,7 @@ impl Session { } } - /// Restore a failed dispatch and its newer reservations without disturbing older work. + /// Restore failed or skipped work and its newer reservations without disturbing older work. /// A suffix can return to editable text while preserving document order. pub(crate) fn restore_pending_from(&mut self, id: u64) -> Vec { let Some(index) = self @@ -178,7 +179,7 @@ impl Session { ) { self.informative_context = context; self.shrink_informative(limits); - self.correction_undo_history.clear(); + self.invalidate_undo_anchors(); self.versions.context = self.versions.context.wrapping_add(1); self.versions.caret_anchor = self.versions.caret_anchor.wrapping_add(1); for segment in &mut self.frozen_segments { @@ -219,18 +220,18 @@ mod tests { session.pending_following_text(first).as_deref(), Some("é next 尾") ); - assert!(!session.complete_pending(second, Some("bad"), &limits)); - assert!(session.complete_pending(first, Some("the "), &limits)); + assert!(!session.complete_pending(second, "bad", &limits)); + assert!(session.complete_pending(first, "the ", &limits)); assert_eq!(session.informative_context(), "the "); assert!(session.pending_matches(second, "é next ")); - assert!(session.complete_pending(second, Some("É next "), &limits)); + assert!(session.complete_pending(second, "É next ", &limits)); assert_eq!(session.informative_context(), "the É next "); assert_eq!(session.editable_context(), "尾"); assert!(session.undo_last_correction(&limits)); assert!(session.undo_last_correction(&limits)); assert_eq!(session.informative_context(), "teh é next "); assert_eq!(session.editable_context(), "尾"); - assert!(!session.complete_pending(first, Some("duplicate"), &limits)); + assert!(!session.complete_pending(first, "duplicate", &limits)); } /// Default overflow keeps the admitted range and leaves newer text editable. @@ -240,15 +241,15 @@ mod tests { let mut session = session("first."); let first = session.freeze_pending(&limits).0.unwrap(); session.input(TypedInput::Text(" next.".into()), &limits); - assert_eq!(session.freeze_pending(&limits), (None, None)); + assert_eq!(session.freeze_pending(&limits), (None, vec![])); assert_eq!(session.editable_context(), " next."); assert!(session.pending_matches(first, "first.")); assert_eq!(session.correction_informative_context(), "first."); } - /// Cancel-oldest releases capacity by retiring the original before admitting newer text. + /// Cancel-oldest preserves unchecked original text in the newly admitted range. #[test] - fn cancel_oldest_retires_original_and_admits_new_segment() { + fn cancel_oldest_rechecks_original_with_new_segment() { let limits = ContextConfig { pending_queue_full_behavior: PendingQueueFullBehavior::CancelOldest, ..ContextConfig::default() @@ -257,14 +258,73 @@ mod tests { let first = session.freeze_pending(&limits).0.unwrap(); session.input(TypedInput::Text(" new".into()), &limits); let (second, cancelled) = session.freeze_pending(&limits); - assert_eq!(cancelled, Some(first)); + assert_eq!(cancelled, vec![first]); assert_ne!(second, Some(first)); - assert_eq!(session.informative_context(), "teh"); + assert_eq!(session.informative_context(), ""); assert!(!session.pending_matches(first, "teh")); - assert!(session.complete_pending(second.unwrap(), None, &limits)); + let second = second.unwrap(); + assert!(session.pending_matches(second, "teh new")); + assert!(session.complete_pending(second, "teh new", &limits)); assert_eq!(session.informative_context(), "teh new"); } + /// Overflow must cancel every dependent range rather than commit unchecked text. + #[test] + fn cancel_oldest_restores_entire_full_queue_before_freezing_again() { + let limits = ContextConfig { + pending_queue_size: 2, + pending_queue_full_behavior: PendingQueueFullBehavior::CancelOldest, + ..ContextConfig::default() + }; + let mut session = session("teh"); + let first = session.freeze_pending(&limits).0.unwrap(); + session.input(TypedInput::Text(" é".into()), &limits); + let second = session.freeze_pending(&limits).0.unwrap(); + session.input(TypedInput::Text(" 尾".into()), &limits); + let (new, cancelled) = session.freeze_pending(&limits); + assert_eq!(cancelled, vec![first, second]); + let new = new.unwrap(); + assert_eq!( + session.pending_context(new), + Some((String::new(), "teh é 尾".into())) + ); + assert!(session.pending_matches(new, "teh é 尾")); + assert_eq!(session.informative_context(), ""); + assert!(session.undo_target().is_none()); + } + + /// Frozen commit shrinks memory, preserves newer text, and retains safe undo. + #[test] + fn frozen_commit_shrinks_context_and_retains_undo_only_for_the_complete_span() { + for cap in [5, 8] { + let limits = ContextConfig { + informative_context_max_chars: cap, + ..ContextConfig::default() + }; + let mut session = session("teh é"); + session.set_informative_context("older ".into(), &limits); + let id = session.freeze_pending(&limits).0.unwrap(); + session.input(TypedInput::Text(" 尾".into()), &limits); + assert!(session.complete_pending(id, "the é", &limits)); + assert!(session.informative_context().ends_with("the é")); + assert!(session.informative_context().chars().count() <= cap as usize); + assert_eq!(session.editable_context(), " 尾"); + let undo = session.undo_target().unwrap(); + assert_eq!(undo.original, "teh é"); + assert_eq!(undo.corrected, "the é"); + assert_eq!(undo.following, " 尾"); + } + let limits = ContextConfig { + informative_context_max_chars: 2, + ..ContextConfig::default() + }; + let mut session = session("teh é"); + let id = session.freeze_pending(&limits).0.unwrap(); + assert!(session.complete_pending(id, "the é", &limits)); + assert_eq!(session.informative_context(), " é"); + assert!(session.undo_target().is_none()); + } + /// Merge-newest restores only the latest frozen range and preserves older pending work. #[test] fn merge_newest_keeps_older_work_and_waits_for_another_trigger() { @@ -278,7 +338,7 @@ mod tests { session.input(TypedInput::Text(" second.".into()), &limits); let second = session.freeze_pending(&limits).0.unwrap(); session.input(TypedInput::Text(" third.".into()), &limits); - assert_eq!(session.freeze_pending(&limits), (None, Some(second))); + assert_eq!(session.freeze_pending(&limits), (None, vec![second])); assert_eq!(session.editable_context(), " second. third."); assert!(session.pending_matches(first, "first.")); assert!(!session.pending_matches(second, " second.")); @@ -347,7 +407,7 @@ mod tests { session.input(TypedInput::Text(" next".into()), &limits); session.set_captured_informative_context("earlier ".into(), &limits); assert!(session.pending_matches(id, "teh.")); - assert!(session.complete_pending(id, None, &limits)); + assert!(session.complete_pending(id, "teh.", &limits)); assert_eq!(session.informative_context(), "earlier teh."); assert_eq!(session.editable_context(), " next"); } diff --git a/app-core-rust/src/background/session/undo.rs b/app-core-rust/src/background/session/undo.rs new file mode 100644 index 0000000..fc8e084 --- /dev/null +++ b/app-core-rust/src/background/session/undo.rs @@ -0,0 +1,316 @@ +//! Session-owned correction history. Text and metadata never leave app memory. + +use std::{ops::Range, time::SystemTime}; + +use super::{ContextConfig, Session}; +use crate::{ + background::{ + replacement::{ReplacedRange, ReplacementConfirmation, ReplacementMethod}, + security::TriggerKind, + }, + correction::ConfidenceTier, +}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct CorrectionUndo { + session_id: u64, + executable_range: Range, // Unicode scalars in the original executable context. + text_range: Option, // Backwards from the caret at correction time. + original: String, + replacement: String, + timestamp: SystemTime, + trigger: Option, + confidence: Option, + method: Option, + language: Option, + informative_start: Option, // Current byte offset; None means proof was lost. + caret_anchor: u64, +} + +/// Only a recorded, fully retained correction may make informative text editable. +pub(in crate::background) struct CorrectionUndoTarget { + pub(in crate::background) language: Option, + pub(in crate::background) corrected: String, + pub(in crate::background) original: String, + pub(in crate::background) following: String, +} + +impl Session { + /// Record the exact executable text only after its native mutation succeeded. + pub(super) fn record_undo( + &mut self, + original: String, + replacement: String, + executable_range: Range, + limits: &ContextConfig, + ) { + if original == replacement { + return; + } + let informative_start = self + .informative_context + .len() + .checked_sub(replacement.len()) + .filter(|start| self.informative_context.get(*start..) == Some(replacement.as_str())); + self.correction_undo_history.push(CorrectionUndo { + session_id: self.id, + executable_range, + text_range: None, + original, + replacement, + timestamp: SystemTime::now(), + trigger: None, + confidence: None, + method: None, + language: None, + informative_start, + caret_anchor: self.versions.caret_anchor, + }); + self.limit_undo_history(limits); + } + + /// Attach the actual engine decision and verified replacement receipt. + pub(in crate::background) fn record_undo_metadata( + &mut self, + language: Option, + trigger: TriggerKind, + confidence: ConfidenceTier, + confirmation: ReplacementConfirmation, + ) { + if let Some(last) = self.correction_undo_history.last_mut() { + last.language = language; + last.trigger = Some(trigger); + last.confidence = Some(confidence); + last.method = confirmation.method; + last.text_range = confirmation.range; + } + } + + /// Evict oldest records after commits or capacity reductions, keeping the newest rejections. + pub(super) fn limit_undo_history(&mut self, limits: &ContextConfig) { + let excess = self + .correction_undo_history + .len() + .saturating_sub(usize::from(limits.undo_history_size.clamp(1, 1000))); + self.correction_undo_history.drain(..excess); + } + + /// Shrinking context preserves full history text but removes unsafe range proofs. + pub(super) fn trim_undo_anchors(&mut self, removed_bytes: usize) { + for entry in &mut self.correction_undo_history { + entry.informative_start = entry + .informative_start + .and_then(|start| start.checked_sub(removed_bytes)); + } + } + + /// Keep history text but revoke every native range proof after movement or re-anchoring. + pub(super) fn invalidate_undo_anchors(&mut self) { + for entry in &mut self.correction_undo_history { + entry.informative_start = None; + } + } + + /// Expose only the newest fully retained span with the same session and caret anchor. + /// Following session text is carried separately so native undo can preserve it. + pub(in crate::background) fn undo_target(&self) -> Option { + let last = self.correction_undo_history.last()?; + let start = last.informative_start?; + let end = start.checked_add(last.replacement.len())?; + if self.position_uncertain() + || last.session_id != self.id + || last.caret_anchor != self.versions.caret_anchor + || self.informative_context.get(start..end)? != last.replacement + { + return None; + } + Some(CorrectionUndoTarget { + language: last.language.clone(), + corrected: last.replacement.clone(), + original: last.original.clone(), + following: format!( + "{}{}", + self.informative_context.get(end..)?, + self.executable_context() + ), + }) + } + + /// Called after verified native undo; originals remain read-only and new typing stays editable. + pub(crate) fn undo_last_correction(&mut self, limits: &ContextConfig) -> bool { + if self.undo_target().is_none() { + return false; + } + let last = self.correction_undo_history.pop().unwrap(); + let start = last.informative_start.unwrap(); + self.restore_pending(); + self.informative_context + .replace_range(start..start + last.replacement.len(), &last.original); + self.shrink_informative(limits); + self.pending_corrections.clear(); + self.versions.context = self.versions.context.wrapping_add(1); + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::background::{ + target::SessionKey, + typing::{MovementSignal, TypedInput}, + }; + + /// Create a session with no imported document context. + fn session() -> Session { + Session::new(1, SessionKey::WindowHandle(1)) + } + + /// Simulate a verified app correction through the same session commit path. + fn correct(session: &mut Session, original: &str, replacement: &str, limits: &ContextConfig) { + session.input(TypedInput::Text(original.into()), limits); + assert!(session.queue_correction(original.into(), replacement.into())); + assert!(session.apply_next_correction(limits)); + } + + /// Repeated undo stops at the configured capacity and preserves evicted corrections. + #[test] + fn oldest_entries_are_evicted_at_default_and_custom_capacity() { + for capacity in [1, 3, 10] { + let limits = ContextConfig { + undo_history_size: capacity, + ..Default::default() + }; + let mut session = session(); + for _ in 0..12 { + correct(&mut session, "teh ", "the ", &limits); + assert!(session.correction_undo_history.len() <= usize::from(capacity)); + } + for _ in 0..capacity { + assert!(session.undo_last_correction(&limits)); + } + assert!(!session.undo_last_correction(&limits)); + assert_eq!( + session.informative_context(), + format!( + "{}{}", + "the ".repeat(12 - usize::from(capacity)), + "teh ".repeat(usize::from(capacity)) + ) + ); + assert_eq!(session.executable_context(), ""); + } + } + + /// Unicode undo restores exact originals while newer typing remains executable. + #[test] + fn length_changing_unicode_undo_preserves_new_typing_and_originals_are_informative() { + let limits = ContextConfig::default(); + let mut session = session(); + correct(&mut session, "é😃 teh", "é the", &limits); + correct(&mut session, " alot", " a lot", &limits); + session.input(TypedInput::Text("尾".into()), &limits); + assert_eq!(session.undo_target().unwrap().original, " alot"); + assert!(session.undo_last_correction(&limits)); + let older = session.undo_target().unwrap(); + assert_eq!(older.corrected, "é the"); + assert_eq!(older.original, "é😃 teh"); + assert_eq!(older.following, " alot尾"); + assert!(session.undo_last_correction(&limits)); + assert_eq!(session.informative_context(), "é😃 teh alot"); + assert_eq!(session.editable_context(), "尾"); + } + + /// Trimming a Unicode prefix preserves complete undo spans and their byte anchors. + #[test] + fn shrinking_prefix_preserves_complete_older_spans_and_adjusts_unicode_offsets() { + let limits = ContextConfig { + informative_context_max_chars: 9, + ..Default::default() + }; + let mut session = session(); + session.set_informative_context("é😃. ".into(), &limits); + correct(&mut session, "teh ", "the ", &limits); + correct(&mut session, "wierd", "weird", &limits); + assert_eq!(session.informative_context(), "the weird"); + assert_eq!(session.correction_undo_history.len(), 2); + assert!(session.undo_last_correction(&limits)); + assert!(session.undo_last_correction(&limits)); + assert_eq!(session.informative_context(), "teh wierd"); + } + + /// Partial retained spans keep full history text but cannot authorize native undo. + #[test] + fn trimming_retains_full_history_text_but_refuses_partial_native_undo() { + let limits = ContextConfig { + informative_context_max_chars: 2, + ..Default::default() + }; + let mut session = session(); + correct(&mut session, "teh 😃", "the é", &limits); + let entry = &session.correction_undo_history[0]; + assert_eq!(entry.original, "teh 😃"); + assert_eq!(entry.replacement, "the é"); + assert_eq!(entry.executable_range, 0..5); + assert!(entry.informative_start.is_none()); + assert!(session.undo_target().is_none()); + assert!(!session.undo_last_correction(&limits)); + assert_eq!(session.informative_context(), " é"); + assert_eq!(session.correction_undo_history.len(), 1); + } + + /// Undo records retain the engine decision and verified native range receipt. + #[test] + fn receipt_records_session_timestamp_trigger_confidence_and_native_method() { + let limits = ContextConfig::default(); + let mut session = session(); + let before = SystemTime::now(); + correct(&mut session, "teh", "the", &limits); + let range = ReplacedRange { + start_back: 8, + end_back: 5, + }; + session.record_undo_metadata( + Some("en".into()), + TriggerKind::Character, + ConfidenceTier::Medium, + ReplacementConfirmation { + success: true, + method: Some(ReplacementMethod::SendInput), + range: Some(range), + }, + ); + let entry = &session.correction_undo_history[0]; + assert_eq!(entry.session_id, session.id()); + assert!(entry.timestamp >= before && entry.timestamp <= SystemTime::now()); + assert_eq!(entry.trigger, Some(TriggerKind::Character)); + assert_eq!(entry.confidence, Some(ConfidenceTier::Medium)); + assert_eq!(entry.method, Some(ReplacementMethod::SendInput)); + assert_eq!(entry.text_range, Some(range)); + assert_eq!(entry.language.as_deref(), Some("en")); + } + + /// Caret movement revokes range proof while retaining bounded history in memory. + #[test] + fn movement_invalidates_proof_without_discarding_session_history() { + let limits = ContextConfig::default(); + let mut session = session(); + correct(&mut session, "teh", "the", &limits); + session.input(TypedInput::Uncertain(MovementSignal::MouseClick), &limits); + assert!(session.undo_target().is_none()); + assert!(!session.undo_last_correction(&limits)); + assert_eq!(session.correction_undo_history.len(), 1); + session.set_informative_context("the".into(), &limits); + assert!(session.undo_target().is_none()); + } + + /// Accepted unchanged text cannot create an app correction to undo. + #[test] + fn unchanged_commits_do_not_create_undo_entries() { + let limits = ContextConfig::default(); + let mut session = session(); + correct(&mut session, "unchanged", "unchanged", &limits); + assert!(session.correction_undo_history.is_empty()); + assert!(session.undo_target().is_none()); + } +} diff --git a/app-core-rust/src/background/tests.rs b/app-core-rust/src/background/tests.rs index 4ed2a09..c3eb8c9 100644 --- a/app-core-rust/src/background/tests.rs +++ b/app-core-rust/src/background/tests.rs @@ -8,6 +8,78 @@ use crate::{background::paths::RuntimePaths, settings::AppConfig}; use super::{admin, load_or_create_config, BackgroundError, BackgroundRuntime}; +/// Successful native undo learns only after a stable, successful session commit. +#[test] +fn undo_learning_requires_committed_bookkeeping_and_stable_input() { + for failure in 0..4 { + let root = unique_temp_dir(); + fs::create_dir_all(&root).unwrap(); + let path = root.join("learning.sqlite"); + let mut config = AppConfig::default(); + config.learning.mode = crate::settings::LearningMode::Automatic; + config.learning.rule = crate::settings::LearningRule::Dictionary; + let mut processor = super::InputProcessor { + learner: crate::dictionary::Learner::default(), + pipeline: super::CorrectionPipeline::new().unwrap(), + processed_input_sequence: 12, + session_manager: super::SessionManager::new(config.context.clone()), + config, + database: crate::storage::Database::open(&path).unwrap(), + }; + let target = dispatch_target(); + processor.session_manager.focus(&target); + processor + .session_manager + .input(super::typing::TypedInput::Text("teh".into())); + let session = processor.session_manager.active_mut().unwrap(); + assert!(session.queue_correction("teh".into(), "the".into())); + assert!(session.apply_next_correction(&processor.config.context)); + let undo = session.undo_target().unwrap(); + processor + .session_manager + .input(super::typing::TypedInput::Text(" 尾".into())); + let stamp = super::InputStamp { + position: 7, + sequence: 12, + }; + let mut current = stamp; + match failure { + 1 => current.sequence += 1, + 2 => current.position += 1, + 3 => processor + .session_manager + .set_informative_context("different anchor".into()), + _ => {} + } + processor.complete_undo(undo, &target, stamp, current); + processor.learner.finish(); + let policy = processor + .database + .dictionary() + .policy( + &target.process_name, + &crate::correction::LanguageInfo { + primary_language: None, + detected_languages: Vec::new(), + }, + ) + .unwrap(); + if failure == 0 { + let session = processor.session_manager.active().unwrap(); + assert_eq!(session.informative_context(), "teh"); + assert_eq!(session.editable_context(), " 尾"); + assert!(session.undo_target().is_none()); + assert_eq!(policy.terms, ["teh"]); + } else { + assert!(processor.session_manager.active().is_none()); + assert!(policy.terms.is_empty()); + } + drop(processor); + fs::remove_file(path).unwrap(); + fs::remove_dir(root).unwrap(); + } +} + /// Exercise both dispatch checks when hook input arrives before or during the slow gate. #[test] fn frozen_dispatch_survives_typing_but_manual_and_moved_requests_are_rejected() { @@ -16,6 +88,7 @@ fn frozen_dispatch_survives_typing_but_manual_and_moved_requests_are_rejected() for during_gate in [false, true] { let config = AppConfig::default(); let mut processor = super::InputProcessor { + learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: 12, session_manager: super::SessionManager::new(config.context.clone()), @@ -81,6 +154,7 @@ fn failed_frozen_dispatch_preserves_older_work_and_releases_newer_reservations() let mut config = AppConfig::default(); config.context.pending_queue_size = 3; let mut processor = super::InputProcessor { + learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: 12, session_manager: super::SessionManager::new(config.context.clone()), @@ -151,7 +225,7 @@ fn finish_unchanged_dispatch( || stamp, |_| Some(target.clone()), |_, _| Some(live_text.into()), - |_, _, _| panic!("unchanged text must not be replaced"), + |_, _, _| -> bool { panic!("unchanged text must not be replaced") }, ) { return; } @@ -229,6 +303,7 @@ fn queued_typing_before_or_during_capture_never_enters_informative_context() { fn delayed_key_from_previous_focus_cannot_enter_session() { let config = AppConfig::default(); let mut processor = super::InputProcessor { + learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: super::input_listener::current_input_sequence(), session_manager: super::SessionManager::new(config.context.clone()), @@ -264,6 +339,7 @@ fn delayed_key_from_previous_focus_cannot_enter_session() { fn later_character_trigger_keeps_full_editable_snapshot() { let config = AppConfig::default(); let mut processor = super::InputProcessor { + learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: super::input_listener::current_input_sequence(), session_manager: super::SessionManager::new(config.context.clone()), @@ -320,6 +396,7 @@ fn automatic_triggers_in_one_batch_obey_capacity_and_overflow_policy() { let mut config = AppConfig::default(); config.context.pending_queue_full_behavior = policy; let mut processor = super::InputProcessor { + learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: super::input_listener::current_input_sequence(), session_manager: super::SessionManager::new(config.context.clone()), @@ -363,8 +440,8 @@ fn automatic_triggers_in_one_batch_obey_capacity_and_overflow_policy() { } crate::settings::PendingQueueFullBehavior::CancelOldest => { assert_eq!(valid.len(), 1); - assert_eq!(valid[0].request.executable_context, " next."); - assert_eq!(valid[0].request.informative_context, "first."); + assert_eq!(valid[0].request.executable_context, "first. next."); + assert_eq!(valid[0].request.informative_context, ""); assert_eq!(session.editable_context(), ""); } crate::settings::PendingQueueFullBehavior::MergeNewest => { diff --git a/app-core-rust/src/background/typing.rs b/app-core-rust/src/background/typing.rs index 83879d1..f2cac4c 100644 --- a/app-core-rust/src/background/typing.rs +++ b/app-core-rust/src/background/typing.rs @@ -133,14 +133,11 @@ impl TypedSession { /// Replace only the known text immediately before the caret. The tracked /// suffix remains untouched and is never submitted to a correction engine. pub(crate) fn replace_executable_suffix(&mut self, original: &str, replacement: &str) -> bool { - let original: Vec = original.chars().collect(); - let replacement: Vec = replacement.chars().collect(); - if original.len() > self.caret - || self.typed[self.caret - original.len()..self.caret] != original - || self.typed.len() - original.len() + replacement.len() > MAX_TYPED_CHARS - { + if !self.can_replace_executable_suffix(original, replacement) { return false; } + let original: Vec = original.chars().collect(); + let replacement: Vec = replacement.chars().collect(); self.typed.splice( self.caret - original.len()..self.caret, replacement.iter().copied(), @@ -148,6 +145,14 @@ impl TypedSession { self.caret = self.caret - original.len() + replacement.len(); true } + + /// Preflight exact suffix ownership and Unicode capacity before native mutation. + pub(crate) fn can_replace_executable_suffix(&self, original: &str, replacement: &str) -> bool { + let original: Vec = original.chars().collect(); + original.len() <= self.caret + && self.typed[self.caret - original.len()..self.caret] == original + && self.typed.len() - original.len() + replacement.chars().count() <= MAX_TYPED_CHARS + } } #[cfg(test)] @@ -240,4 +245,23 @@ mod tests { assert_eq!(session.executable_context(), "ABc"); assert!(!session.replace_executable_suffix("ab", "bad")); } + + /// Preflight counts Unicode scalars and includes tracked text after the caret. + #[test] + fn correction_preflight_preserves_capacity_and_suffix() { + let mut session = session(); + session.input(TypedInput::Text(format!( + "{}😃", + "é".repeat(MAX_TYPED_CHARS - 1) + ))); + session.input(TypedInput::Left); + let before = session.executable_context(); + assert!(!session.can_replace_executable_suffix("é", "éé")); + assert!(!session.replace_executable_suffix("é", "éé")); + assert_eq!(session.executable_context(), before); + assert!(session.can_replace_executable_suffix("é", "尾")); + assert!(session.replace_executable_suffix("é", "尾")); + session.input(TypedInput::Right); + assert!(session.executable_context().ends_with("尾😃")); + } } diff --git a/app-core-rust/src/dictionary/learning.rs b/app-core-rust/src/dictionary/learning.rs new file mode 100644 index 0000000..2f28ec6 --- /dev/null +++ b/app-core-rust/src/dictionary/learning.rs @@ -0,0 +1,676 @@ +use super::{word_char, Repository}; +use crate::settings::{LearningConfig, LearningMode}; +use std::{ + path::{Path, PathBuf}, + sync::mpsc::{self, Receiver, SyncSender}, + thread::JoinHandle, + time::Duration, +}; + +const SAVE_QUEUE_LIMIT: usize = 16; +const SAVE_BUSY_TIMEOUT: Duration = Duration::from_millis(100); + +#[derive(Debug, Clone)] +pub(crate) struct Rejection { + pub(crate) original: String, + pub(crate) corrected: String, + pub(crate) language: Option, + pub(crate) app: String, +} + +impl Rejection { + /// Learn the changed word/phrase, excluding unchanged leading/trailing text. + pub(crate) fn from_undo( + original: &str, + corrected: &str, + language: Option, + app: String, + ) -> Option { + if original == corrected { + return None; + } + let a: Vec = original.chars().collect(); + let b: Vec = corrected.chars().collect(); + let mut start = a.iter().zip(&b).take_while(|(a, b)| a == b).count(); + // Bound common suffix before expanding the changed span, so removed + // repeated words cannot be mistaken for unchanged suffix context. + let mut suffix = a[start..] + .iter() + .rev() + .zip(b[start..].iter().rev()) + .take_while(|(a, b)| a == b) + .count(); + let needs_word_anchor = a[start..a.len() - suffix].iter().all(|c| c.is_whitespace()); + while start > 0 && word_char(a[start - 1]) { + start -= 1; + } + while suffix > 0 && (word_char(a[a.len() - suffix]) || word_char(b[b.len() - suffix])) { + suffix -= 1; + } + if needs_word_anchor { + // Pure spacing/insertion edits need adjacent words to form a rule. + while start > 0 && a[start - 1].is_whitespace() { + start -= 1; + } + while start > 0 && !a[start - 1].is_whitespace() { + start -= 1; + } + } + let original: String = a[start..a.len() - suffix].iter().collect(); + if original.trim().is_empty() { + return None; + } + Some(Self { + original, + corrected: b[start..b.len() - suffix].iter().collect(), + language, + app, + }) + } +} + +#[derive(Default)] +pub(crate) struct Learner { + pending: Option, + writer: Option, +} + +struct Save { + rejection: Rejection, + config: LearningConfig, +} + +struct LearningWriter { + send: SyncSender, + thread: JoinHandle<()>, +} + +impl LearningWriter { + /// Own a separate connection on a bounded worker; never create or migrate storage. + fn start(path: PathBuf) -> std::io::Result { + let (send, receive) = mpsc::sync_channel::(SAVE_QUEUE_LIMIT); + let thread = std::thread::Builder::new() + .name("autofix-learning-writer".into()) + .spawn(move || { + let mut connection = None; + for save in receive { + if connection.is_none() { + connection = rusqlite::Connection::open_with_flags( + &path, + rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE, + ) + .and_then(|connection| { + connection.busy_timeout(SAVE_BUSY_TIMEOUT)?; + Ok(connection) + }) + .ok(); + } + let Some(connection) = &connection else { + tracing::warn!("learning storage unavailable"); + continue; + }; + let repository = Repository::new(connection); + if repository.remember(&save.rejection, &save.config).is_err() { + tracing::warn!("learning could not save exclusion"); + } + } + })?; + Ok(Self { send, thread }) + } + + /// Drop a full or disconnected submission without waiting or logging captured text. + fn submit(&self, save: Save) -> bool { + if self.send.try_send(save).is_err() { + tracing::warn!("learning save queue unavailable"); + return false; + } + true + } + + /// Drain accepted saves during shutdown, after input processing has stopped. + fn finish(self) { + drop(self.send); + if self.thread.join().is_err() { + tracing::warn!("learning writer failed during shutdown"); + } + } +} + +struct PendingConsent { + config: LearningConfig, + receive: Receiver>, + cancelled: bool, +} + +impl Learner { + /// Handle only a successful AutoFix undo according to the current opt-in policy. + pub(crate) fn rejected( + &mut self, + rejection: Rejection, + config: &LearningConfig, + path: Option<&Path>, + ) { + self.rejected_with(rejection, config, path, confirm); + } + + /// Run at most one consent prompt while leaving input processing available. + /// Off never prompts or writes; automatic queues the authorized rejection. + fn rejected_with( + &mut self, + rejection: Rejection, + config: &LearningConfig, + path: Option<&Path>, + ask: impl FnOnce(&Rejection) -> bool + Send + 'static, + ) { + match config.mode { + LearningMode::Off => {} + LearningMode::Automatic => self.remember(path, rejection, config), + LearningMode::Ask if self.pending.is_none() => { + let (send, receive) = mpsc::channel(); + match std::thread::Builder::new() + .name("autofix-learning".into()) + .spawn(move || { + let accepted = ask(&rejection); + let _ = send.send(accepted.then_some(rejection)); + }) { + Ok(_) => { + self.pending = Some(PendingConsent { + config: config.clone(), + receive, + cancelled: false, + }) + } + Err(_) => tracing::warn!("learning prompt unavailable"), + } + } + LearningMode::Ask => {} + } + } + + /// Changing settings cancels pending consent; refusals never persist text. + pub(crate) fn poll(&mut self, config: &LearningConfig, path: Option<&Path>) { + let Some(pending) = &mut self.pending else { + return; + }; + pending.cancelled |= pending.config != *config; + let cancelled = pending.cancelled; + match pending.receive.try_recv() { + Ok(rejection) => { + self.pending = None; + if let Some(rejection) = rejection.filter(|_| !cancelled) { + self.remember(path, rejection, config); + } + } + Err(mpsc::TryRecvError::Disconnected) => self.pending = None, + Err(mpsc::TryRecvError::Empty) => {} + } + } + + /// Queue authorized text without performing SQLite work on the input thread. + fn remember(&mut self, path: Option<&Path>, rejection: Rejection, config: &LearningConfig) { + if self.writer.is_none() { + let Some(path) = path else { + tracing::warn!("learning storage unavailable"); + return; + }; + match LearningWriter::start(PathBuf::from(path)) { + Ok(writer) => self.writer = Some(writer), + Err(_) => { + tracing::warn!("learning writer unavailable"); + return; + } + } + } + self.writer.as_ref().unwrap().submit(Save { + rejection, + config: config.clone(), + }); + } + + /// Stop accepting consent and finish already authorized saves on engine shutdown. + pub(crate) fn finish(&mut self) { + self.pending = None; + if let Some(writer) = self.writer.take() { + writer.finish(); + } + } +} + +/// Ask for native Yes/No consent with No selected by default; only Yes permits storage. +fn confirm(rejection: &Rejection) -> bool { + use windows_sys::Win32::UI::WindowsAndMessaging::{ + MessageBoxW, IDYES, MB_DEFBUTTON2, MB_YESNO, + }; + let text: Vec = format!( + "Don't correct this again?\n\n{} → {}", + rejection.original, rejection.corrected + ) + .encode_utf16() + .chain(Some(0)) + .collect(); + let title: Vec = "AutoFix".encode_utf16().chain(Some(0)).collect(); + unsafe { + MessageBoxW( + std::ptr::null_mut(), + text.as_ptr(), + title.as_ptr(), + MB_YESNO | MB_DEFBUTTON2, + ) == IDYES + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{correction::LanguageInfo, storage::Database}; + + struct Fixture { + db: Database, + path: PathBuf, + learner: Learner, + } + + impl Fixture { + /// Use a real file so the writer must own a separate SQLite connection. + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "autofix-learning-{}-{}.sqlite", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + Self { + db: Database::open(&path).unwrap(), + path, + learner: Learner::default(), + } + } + + /// Consume the asynchronous prompt answer without waiting for persistence. + fn poll_consent(&mut self, config: &LearningConfig) { + let deadline = std::time::Instant::now() + Duration::from_secs(2); + while self.learner.pending.is_some() && std::time::Instant::now() < deadline { + self.learner.poll(config, self.db.path()); + std::thread::yield_now(); + } + assert!(self.learner.pending.is_none()); + } + } + + impl Drop for Fixture { + /// Drain the worker and close both connections before removing Windows test files. + fn drop(&mut self) { + self.learner.finish(); + drop(std::mem::replace( + &mut self.db, + Database::open_memory().unwrap(), + )); + std::fs::remove_file(&self.path).unwrap(); + } + } + /// Build a successful undo rejection with English and app scope. + fn rejection() -> Rejection { + Rejection::from_undo( + "I typed teh today", + "I typed the today", + Some("en".into()), + "Notepad.EXE".into(), + ) + .unwrap() + } + /// Count applicable saved word exclusions for the test application. + fn terms(db: &Database) -> usize { + let p = db + .dictionary() + .policy( + "notepad.exe", + &LanguageInfo { + primary_language: Some("en".into()), + detected_languages: vec!["en".into()], + }, + ) + .unwrap(); + p.terms.len() + } + + /// Learning isolates changed words and phrases, including Unicode, spacing and deletions. + #[test] + fn extracts_complete_changed_words_and_unicode_phrases() { + assert_eq!(rejection().original, "teh"); + assert_eq!(rejection().corrected, "the"); + let r = + Rejection::from_undo("é teh wierd!", "é the weird!", None, "app.exe".into()).unwrap(); + assert_eq!( + (r.original.as_str(), r.corrected.as_str()), + ("teh wierd", "the weird") + ); + assert!(Rejection::from_undo("abc", "abc", None, "".into()).is_none()); + assert!(Rejection::from_undo("", "abc", None, "".into()).is_none()); + for (original, corrected, expected_original, expected_corrected) in [ + ("hello", "hello.", "hello", "hello."), + ("very very", "very", "very very", "very"), + ("two words", "two words", "two words", "two words"), + ("cant", "can't", "cant", "can't"), + ] { + let r = Rejection::from_undo(original, corrected, None, "app.exe".into()).unwrap(); + assert_eq!( + (r.original.as_str(), r.corrected.as_str()), + (expected_original, expected_corrected) + ); + } + } + + /// Default-off undo never asks or persists; automatic learning stores one scoped exclusion. + #[test] + fn default_undo_never_writes_or_prompts_and_automatic_deduplicates() { + let mut fixture = Fixture::new(); + let db = &fixture.db; + let learner = &mut fixture.learner; + learner.rejected_with(rejection(), &LearningConfig::default(), db.path(), |_| { + panic!("default must not ask") + }); + assert_eq!(terms(db), 0); + assert!(learner.writer.is_none()); + let config = LearningConfig { + mode: LearningMode::Automatic, + rule: crate::settings::LearningRule::Dictionary, + per_app: true, + }; + learner.rejected_with(rejection(), &config, db.path(), |_| { + panic!("automatic must not ask") + }); + learner.rejected_with(rejection(), &config, db.path(), |_| panic!()); + learner.finish(); + assert_eq!(terms(db), 1); + } + + /// Only accepted, uncancelled consent persists a rejection; changing settings revokes consent. + #[test] + fn ask_requires_consent_and_cancels_when_disabled() { + let mut fixture = Fixture::new(); + let config = LearningConfig { + mode: LearningMode::Ask, + rule: crate::settings::LearningRule::Dictionary, + per_app: false, + }; + for accepted in [false, true] { + fixture + .learner + .rejected_with(rejection(), &config, fixture.db.path(), move |_| accepted); + fixture.poll_consent(&config); + if !accepted { + assert!(fixture.learner.writer.is_none()); + } + fixture.learner.finish(); + assert_eq!(terms(&fixture.db), usize::from(accepted)); + } + let (release, wait) = mpsc::channel(); + let mut other = rejection(); + other.original = "wierd".into(); + fixture + .learner + .rejected_with(other, &config, fixture.db.path(), move |_| { + wait.recv().unwrap(); + true + }); + fixture + .learner + .poll(&LearningConfig::default(), fixture.db.path()); + release.send(()).unwrap(); + fixture.poll_consent(&config); + assert!(fixture.learner.writer.is_none()); + assert_eq!(terms(&fixture.db), 1); + } + + /// API-send reservations cannot stall accepted consent or automatic learning in either journal mode. + #[test] + fn learning_during_api_send_keeps_input_available() { + for journal in ["delete", "wal"] { + for mode in [LearningMode::Ask, LearningMode::Automatic] { + let mut fixture = Fixture::new(); + fixture + .db + .dictionary() + .connection + .execute_batch(&format!("PRAGMA journal_mode={journal}")) + .unwrap(); + let config = LearningConfig { + mode, + ..LearningConfig::default() + }; + let (accepted, answer) = mpsc::channel(); + if mode == LearningMode::Ask { + // Install an already accepted prompt answer to isolate poll's input-path latency. + fixture.learner.pending = Some(PendingConsent { + config: config.clone(), + receive: answer, + cancelled: false, + }); + accepted.send(Some(rejection())).unwrap(); + } + // This is the same writer reservation held through each outbound API send. + let guard = crate::storage::AppPolicyGuard::acquire(&fixture.path).unwrap(); + let started = std::time::Instant::now(); + if mode == LearningMode::Ask { + fixture.learner.poll(&config, fixture.db.path()); + assert!(fixture.learner.pending.is_none()); + } else { + fixture.learner.rejected_with( + rejection(), + &config, + fixture.db.path(), + |_| panic!(), + ); + } + assert!( + started.elapsed() < Duration::from_millis(250), + "input waited for SQLite" + ); + // Holding the guard through worker drain proves timeout loses only the save. + fixture.learner.finish(); + assert_eq!(terms(&fixture.db), 0); + drop(guard); + // Failure must not prevent a later authorized rejection from being saved. + fixture + .learner + .remember(fixture.db.path(), rejection(), &config); + fixture.learner.finish(); + assert!( + fixture + .db + .dictionary() + .policy( + "notepad.exe", + &LanguageInfo { + primary_language: Some("en".into()), + detected_languages: vec!["en".into()] + } + ) + .unwrap() + .pairs + .len() + == 1 + ); + } + } + } + + /// A stalled writer has a fixed queue; overflow and disconnected workers return immediately. + #[test] + fn save_queue_is_bounded_and_never_waits() { + let (send, receive) = mpsc::sync_channel(SAVE_QUEUE_LIMIT); + let (release, wait) = mpsc::channel(); + let (count, counted) = mpsc::channel(); + let thread = std::thread::spawn(move || { + wait.recv().unwrap(); + count.send(receive.into_iter().count()).unwrap(); + }); + let writer = LearningWriter { send, thread }; + for _ in 0..SAVE_QUEUE_LIMIT { + assert!(writer.submit(Save { + rejection: rejection(), + config: LearningConfig::default() + })); + } + let started = std::time::Instant::now(); + assert!(!writer.submit(Save { + rejection: rejection(), + config: LearningConfig::default() + })); + assert!(started.elapsed() < Duration::from_millis(250)); + release.send(()).unwrap(); + writer.finish(); + assert_eq!( + counted.recv_timeout(Duration::from_secs(2)).unwrap(), + SAVE_QUEUE_LIMIT + ); + + let (send, receive) = mpsc::sync_channel(SAVE_QUEUE_LIMIT); + drop(receive); + let writer = LearningWriter { + send, + thread: std::thread::spawn(|| {}), + }; + assert!(!writer.submit(Save { + rejection: rejection(), + config: LearningConfig::default() + })); + writer.finish(); + } + + /// A failed save does not kill the writer or alter later jobs' snapshotted scope. + #[test] + fn writer_recovers_from_save_failure_and_preserves_scope() { + let mut fixture = Fixture::new(); + fixture + .db + .dictionary() + .connection + .execute_batch( + "create trigger reject_test_entry before insert on custom_dictionary_entries + when new.entry = 'failed' begin select raise(abort, 'test failure'); end;", + ) + .unwrap(); + let config = LearningConfig { + mode: LearningMode::Automatic, + rule: crate::settings::LearningRule::Dictionary, + per_app: true, + }; + let mut failed = rejection(); + failed.original = "failed".into(); + fixture.learner.rejected(failed, &config, fixture.db.path()); + fixture + .learner + .rejected(rejection(), &config, fixture.db.path()); + let other_config = LearningConfig { + per_app: false, + ..config + }; + let mut other = rejection(); + other.original = "wierd".into(); + fixture + .learner + .rejected(other, &other_config, fixture.db.path()); + fixture.learner.finish(); + let mut statement = fixture.db.dictionary().connection.prepare( + "select entry, app_process_name, language_code from custom_dictionary_entries order by entry", + ).unwrap(); + let saved = statement + .query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, Option>(1)?, + row.get::<_, String>(2)?, + )) + }) + .unwrap() + .collect::>>() + .unwrap(); + assert_eq!( + saved, + vec![ + ("teh".into(), Some("notepad.exe".into()), "en".into()), + ("wierd".into(), None, "en".into()), + ] + ); + } + + /// Learning cannot recreate deleted storage or run migrations against an uninitialized file. + #[test] + fn writer_never_creates_or_migrates_storage() { + let fixture = Fixture::new(); + let path = fixture.path.with_extension("uninitialized.sqlite"); + let config = LearningConfig { + mode: LearningMode::Automatic, + rule: crate::settings::LearningRule::Dictionary, + per_app: false, + }; + let writer = LearningWriter::start(path.clone()).unwrap(); + assert!(writer.submit(Save { + rejection: rejection(), + config: config.clone() + })); + writer.finish(); + assert!(!path.exists()); + let connection = rusqlite::Connection::open(&path).unwrap(); + connection + .execute_batch("create table sentinel (value text)") + .unwrap(); + let writer = LearningWriter::start(path.clone()).unwrap(); + assert!(writer.submit(Save { + rejection: rejection(), + config + })); + writer.finish(); + let tables: usize = connection + .query_row( + "select count(*) from sqlite_master where type = 'table'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(tables, 1); + drop(connection); + std::fs::remove_file(path).unwrap(); + } + + /// Scope changes cancel consent permanently, even if reverted before the answer arrives. + #[test] + fn consent_is_coalesced_and_revoked_by_scope_changes() { + let config = LearningConfig { + mode: LearningMode::Ask, + ..LearningConfig::default() + }; + for changed in [ + LearningConfig { + per_app: !config.per_app, + ..config.clone() + }, + LearningConfig { + rule: crate::settings::LearningRule::Dictionary, + ..config.clone() + }, + ] { + let mut fixture = Fixture::new(); + let (release, wait) = mpsc::channel(); + fixture + .learner + .rejected_with(rejection(), &config, fixture.db.path(), move |_| { + wait.recv().unwrap(); + true + }); + fixture + .learner + .rejected_with(rejection(), &config, fixture.db.path(), |_| { + panic!("duplicate prompt") + }); + fixture.learner.poll(&changed, fixture.db.path()); + release.send(()).unwrap(); + fixture.poll_consent(&config); + assert!(fixture.learner.writer.is_none()); + assert_eq!(terms(&fixture.db), 0); + } + } +} diff --git a/app-core-rust/src/dictionary/mod.rs b/app-core-rust/src/dictionary/mod.rs new file mode 100644 index 0000000..a1b6318 --- /dev/null +++ b/app-core-rust/src/dictionary/mod.rs @@ -0,0 +1,294 @@ +//! Persistent user exclusions. Session text enters storage only through opt-in learning. +mod learning; +#[cfg(test)] +mod tests; + +use crate::correction::{CorrectionChange, CorrectionOutput, LanguageInfo, NoChangeReason}; +use crate::settings::{LearningConfig, LearningRule}; +pub(crate) use learning::{Learner, Rejection}; +use rusqlite::{params, Connection, OpenFlags, Result}; +use std::{path::Path, time::Duration}; + +#[derive(Default)] +pub(crate) struct Policy { + pub(crate) terms: Vec, + pairs: Vec<(String, String)>, +} + +pub(crate) struct Repository<'a> { + connection: &'a Connection, +} + +impl<'a> Repository<'a> { + /// Snapshot fresh exclusions without creating storage, migrating, writing, or waiting on locks. + pub(crate) fn policy_nowait(path: &Path, app: &str, language: &LanguageInfo) -> Result { + let mut connection = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)?; + connection.busy_timeout(Duration::ZERO)?; + // Both tables belong to one read snapshot, even if a settings writer commits between reads. + let transaction = connection.transaction()?; + let policy = Repository::new(&transaction).policy(app, language)?; + transaction.commit()?; + Ok(policy) + } + + /// Borrow the engine's exclusion database without creating a separate storage owner. + pub(crate) fn new(connection: &'a Connection) -> Self { + Self { connection } + } + + /// Unknown/mixed language protects all applicable entries conservatively. + pub(crate) fn policy(&self, app: &str, language: &LanguageInfo) -> Result { + let mut policy = Policy::default(); + let mut statement = self.connection.prepare( + "select language_code, entry from custom_dictionary_entries + where app_process_name is null or lower(app_process_name) = lower(?1)", + )?; + for row in statement.query_map([app], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) + })? { + let (tag, term) = row?; + if language_matches(Some(&tag), language) { + policy.terms.push(term); + } + } + let mut statement = self.connection.prepare( + "select language_code, original_text, rejected_correction from learned_correction_rules + where learning_enabled = 1 and rule_type = 'pair' and rejected_correction is not null + and (app_process_name is null or lower(app_process_name) = lower(?1))", + )?; + for row in statement.query_map([app], |row| { + Ok(( + row.get::<_, Option>(0)?, + row.get::<_, String>(1)?, + row.get::<_, String>(2)?, + )) + })? { + let (tag, original, replacement) = row?; + if language_matches(tag.as_deref(), language) { + policy.pairs.push((original, replacement)); + } + } + Ok(policy) + } + + /// Persist an authorized rejection using the selected rule and app scope, deduplicating it. + /// The learning owner must establish opt-in or consent before calling this method. + pub(crate) fn remember(&self, rejection: &Rejection, config: &LearningConfig) -> Result<()> { + let app = config.per_app.then(|| rejection.app.to_ascii_lowercase()); + match config.rule { + LearningRule::Dictionary => { + self.connection.execute( + "insert into custom_dictionary_entries (language_code, app_process_name, entry) + select ?1, ?2, ?3 where not exists (select 1 from custom_dictionary_entries + where lower(language_code) = lower(?1) and coalesce(lower(app_process_name), '') = coalesce(?2, '') and entry = ?3)", + params![rejection.language.as_deref().unwrap_or("und"), app, rejection.original])?; + } + LearningRule::Pair => { + self.connection.execute( + "insert into learned_correction_rules + (learning_enabled, original_text, rejected_correction, rule_type, language_code, app_process_name) + select 1, ?1, ?2, 'pair', ?3, ?4 where not exists (select 1 from learned_correction_rules + where learning_enabled = 1 and rule_type = 'pair' and original_text = ?1 + and rejected_correction = ?2 and coalesce(lower(language_code), 'und') = coalesce(lower(?3), 'und') + and coalesce(lower(app_process_name), '') = coalesce(?4, ''))", + params![rejection.original, rejection.corrected, rejection.language, app])?; + } + } + Ok(()) + } +} + +/// Match global/base/regional tags, protecting all app rules when detection is uncertain. +fn language_matches(tag: Option<&str>, language: &LanguageInfo) -> bool { + let Some(tag) = tag else { + return true; + }; + if tag.eq_ignore_ascii_case("und") || language.is_uncertain() || language.is_mixed() { + return true; + } + language.primary_language.as_deref().is_none_or(|primary| { + tag.eq_ignore_ascii_case(primary) + || (!tag.contains('-') + && primary + .split('-') + .next() + .is_some_and(|base| tag.eq_ignore_ascii_case(base))) + }) +} + +impl Policy { + /// Remove excluded edits, preserving unrelated changes for either engine. + pub(crate) fn filter(&self, original: &str, mut output: CorrectionOutput) -> CorrectionOutput { + if !output.changes_needed { + return output; + } + let Some(changes) = output.changes.as_ref() else { + // Unstructured results cannot prove that exclusions remain untouched. + return if self.terms.is_empty() && self.pairs.is_empty() { + output + } else { + CorrectionOutput::unchanged( + original.to_owned(), + output.confidence, + NoChangeReason::AllCandidatesProtected, + output.engine_latency_ms, + ) + }; + }; + let text: Vec = original.chars().collect(); + let mut blocked = vec![false; changes.len()]; + for term in &self.terms { + for (start, end) in occurrences(&text, term) { + for (i, change) in changes.iter().enumerate() { + blocked[i] |= overlaps(change, start, end); + } + } + } + for (original, replacement) in &self.pairs { + for (start, end) in occurrences(&text, original) { + let inside: Vec<_> = changes + .iter() + .filter(|c| pair_overlaps(c, start, end)) + .cloned() + .collect(); + if inside.is_empty() { + continue; + } + if inside + .iter() + .any(|c| c.start_char < start || c.end_char > end) + { + // Broad edits can bundle the pair with other changes. Allow + // a different replacement only when unchanged context can + // be trimmed to prove a sole changed word/phrase. + for (i, change) in changes + .iter() + .enumerate() + .filter(|(_, c)| pair_overlaps(c, start, end)) + { + let isolated = Rejection::from_undo( + &change.original_text, + &change.replacement_text, + None, + String::new(), + ); + let proven_different = isolated.as_ref().is_some_and(|edit| { + edit.original.eq_ignore_ascii_case(original) + && !edit.corrected.eq_ignore_ascii_case(replacement) + }); + blocked[i] |= !proven_different; + } + continue; + } + if render(&text, start, end, &inside) + .is_some_and(|result| result.eq_ignore_ascii_case(replacement)) + { + for (i, change) in changes.iter().enumerate() { + blocked[i] |= pair_overlaps(change, start, end); + } + } + } + } + if !blocked.iter().any(|b| *b) { + return output; + } + let kept: Vec<_> = changes + .iter() + .enumerate() + .filter(|(i, _)| !blocked[*i]) + .map(|(_, c)| c.clone()) + .collect(); + if kept.is_empty() { + return CorrectionOutput::unchanged( + original.to_owned(), + output.confidence, + NoChangeReason::AllCandidatesProtected, + output.engine_latency_ms, + ); + } + let Some(corrected) = render(&text, 0, text.len(), &kept) else { + return CorrectionOutput::unchanged( + original.to_owned(), + output.confidence, + NoChangeReason::AllCandidatesProtected, + output.engine_latency_ms, + ); + }; + output.corrected_executable_text = corrected; + output.changes = Some(kept); + output + } +} + +/// Detect edits inside a protected term; insertions at its outside boundaries remain allowed. +fn overlaps(change: &CorrectionChange, start: usize, end: usize) -> bool { + if change.start_char == change.end_char { + change.start_char > start && change.start_char < end + } else { + change.start_char < end && change.end_char > start + } +} + +/// Include boundary insertions when checking the exact outcome of a rejected pair. +fn pair_overlaps(change: &CorrectionChange, start: usize, end: usize) -> bool { + if change.start_char == change.end_char { + change.start_char >= start && change.start_char <= end + } else { + overlaps(change, start, end) + } +} + +/// Find whole-term matches at Unicode scalar offsets with ASCII-insensitive comparison. +fn occurrences(text: &[char], term: &str) -> Vec<(usize, usize)> { + let term: Vec = term.chars().collect(); + if term.is_empty() || term.len() > text.len() { + return Vec::new(); + } + (0..=text.len() - term.len()) + .filter_map(|start| { + let end = start + term.len(); + (text[start..end] + .iter() + .zip(&term) + .all(|(a, b)| a.eq_ignore_ascii_case(b)) + && (start == 0 || !word_char(text[start - 1]) || !word_char(term[0])) + && (end == text.len() + || !word_char(text[end]) + || !word_char(*term.last().unwrap()))) + .then_some((start, end)) + }) + .collect() +} + +/// Keep letters, digits, underscores and apostrophes within one protected word. +fn word_char(c: char) -> bool { + c.is_alphanumeric() || c == '_' || c == '\'' +} + +/// Render validated, nonoverlapping edits inside a scalar range, refusing mismatched originals. +fn render(text: &[char], start: usize, end: usize, changes: &[CorrectionChange]) -> Option { + let mut sorted: Vec<_> = changes.iter().collect(); + sorted.sort_by_key(|c| c.start_char); + let mut cursor = start; + let mut result = String::new(); + for change in sorted { + if change.start_char < cursor + || change.end_char < change.start_char + || change.end_char > end + { + return None; + } + if text[change.start_char..change.end_char] + .iter() + .collect::() + != change.original_text + { + return None; + } + result.extend(&text[cursor..change.start_char]); + result.push_str(&change.replacement_text); + cursor = change.end_char; + } + result.extend(&text[cursor..end]); + Some(result) +} diff --git a/app-core-rust/src/dictionary/tests.rs b/app-core-rust/src/dictionary/tests.rs new file mode 100644 index 0000000..6eca5ab --- /dev/null +++ b/app-core-rust/src/dictionary/tests.rs @@ -0,0 +1,368 @@ +use super::*; +use crate::{ + correction::{ConfidenceTier, CorrectionChangeKind}, + settings::{LearningMode, LearningRule}, + storage::Database, +}; + +/// Generate an isolated file path for exclusion snapshot tests. +fn policy_test_path() -> std::path::PathBuf { + std::env::temp_dir().join(format!( + "autofix-policy-read-{}-{}.sqlite", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )) +} + +/// Failed policy reads cannot create a database or initialize an incompatible schema. +#[test] +fn policy_snapshot_never_creates_or_migrates_storage() { + let path = policy_test_path(); + assert!(Repository::policy_nowait(&path, "app.exe", &language(Some("en"))).is_err()); + assert!(!path.exists()); + let connection = Connection::open(&path).unwrap(); + connection + .execute_batch( + "create table sentinel (value text); insert into sentinel values ('unchanged')", + ) + .unwrap(); + assert!(Repository::policy_nowait(&path, "app.exe", &language(Some("en"))).is_err()); + let tables: usize = connection + .query_row( + "select count(*) from sqlite_master where type = 'table'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(tables, 1); + let value: String = connection + .query_row("select value from sentinel", [], |row| row.get(0)) + .unwrap(); + assert_eq!(value, "unchanged"); + drop(connection); + std::fs::remove_file(path).unwrap(); +} + +/// API-send writer reservations permit committed exclusion reads in rollback and WAL mode. +#[test] +fn policy_snapshot_reads_during_send_and_sees_later_dictionary_edits() { + for journal in ["delete", "wal"] { + let path = policy_test_path(); + let db = Database::open(&path).unwrap(); + db.dictionary() + .connection + .execute_batch(&format!("PRAGMA journal_mode={journal}")) + .unwrap(); + let config = LearningConfig { + mode: LearningMode::Automatic, + rule: LearningRule::Dictionary, + per_app: true, + }; + let mut rejection = Rejection { + original: "teh".into(), + corrected: "the".into(), + language: Some("en".into()), + app: "app.exe".into(), + }; + db.dictionary().remember(&rejection, &config).unwrap(); + let pair_config = LearningConfig { + rule: LearningRule::Pair, + ..config.clone() + }; + db.dictionary().remember(&rejection, &pair_config).unwrap(); + let guard = crate::storage::AppPolicyGuard::acquire(&path).unwrap(); + let started = std::time::Instant::now(); + let policy = Repository::policy_nowait(&path, "APP.EXE", &language(Some("en-US"))).unwrap(); + assert!(started.elapsed() < std::time::Duration::from_millis(250)); + assert_eq!(policy.terms, ["teh"]); + assert_eq!(policy.pairs, [("teh".into(), "the".into())]); + drop(guard); + rejection.original = "wierd".into(); + rejection.corrected = "weird".into(); + db.dictionary().remember(&rejection, &config).unwrap(); + db.dictionary().remember(&rejection, &pair_config).unwrap(); + let mut updated = + Repository::policy_nowait(&path, "app.exe", &language(Some("en"))).unwrap(); + updated.terms.sort(); + assert_eq!(updated.terms, ["teh", "wierd"]); + assert_eq!(updated.pairs.len(), 2); + assert!( + Repository::policy_nowait(&path, "other.exe", &language(Some("en"))) + .unwrap() + .terms + .is_empty() + ); + drop(db); + std::fs::remove_file(path).unwrap(); + } +} + +/// An exclusive rollback-mode lock fails immediately instead of waiting for SQLite's default timeout. +#[test] +fn policy_snapshot_refuses_unreadable_storage_without_waiting() { + let path = policy_test_path(); + let db = Database::open(&path).unwrap(); + let writer = Connection::open(&path).unwrap(); + writer + .execute_batch("PRAGMA journal_mode=delete; BEGIN EXCLUSIVE") + .unwrap(); + let started = std::time::Instant::now(); + let error = Repository::policy_nowait(&path, "app.exe", &language(Some("en"))) + .err() + .unwrap(); + assert_eq!( + error.sqlite_error_code(), + Some(rusqlite::ErrorCode::DatabaseBusy) + ); + assert!(started.elapsed() < std::time::Duration::from_millis(250)); + writer.execute_batch("ROLLBACK").unwrap(); + assert!(Repository::policy_nowait(&path, "app.exe", &language(Some("en"))).is_ok()); + drop(writer); + drop(db); + std::fs::remove_file(path).unwrap(); +} + +/// Build a known or unknown language snapshot for exclusion scope tests. +fn language(tag: Option<&str>) -> LanguageInfo { + LanguageInfo { + primary_language: tag.map(str::to_owned), + detected_languages: tag.map(|t| vec![t.to_owned()]).unwrap_or_default(), + } +} +/// Build a typo edit at Unicode scalar offsets. +fn change(start: usize, end: usize, from: &str, to: &str) -> CorrectionChange { + CorrectionChange { + start_char: start, + end_char: end, + original_text: from.into(), + replacement_text: to.into(), + kind: CorrectionChangeKind::Typo, + explanation: None, + } +} +/// Build a silent engine result whose categorized edits can be filtered. +fn output(text: &str, edits: Vec) -> CorrectionOutput { + let mut out = CorrectionOutput::changed(text.into(), ConfidenceTier::High, Some(edits), 1); + out.behavior = crate::correction::ConfidenceBehavior::Silent; + out +} + +/// App scopes ignore ASCII case, base languages include variants, and unknown text stays protected. +#[test] +fn sqlite_scopes_language_and_apps_and_preserves_unknown_language() { + let db = Database::open_memory().unwrap(); + let config = LearningConfig { + mode: LearningMode::Automatic, + rule: LearningRule::Dictionary, + per_app: true, + }; + db.dictionary() + .remember( + &Rejection { + original: "teh phrase".into(), + corrected: "the phrase".into(), + language: Some("en".into()), + app: "Notepad.EXE".into(), + }, + &config, + ) + .unwrap(); + assert_eq!( + db.dictionary() + .policy("notepad.exe", &language(Some("en-US"))) + .unwrap() + .terms, + ["teh phrase"] + ); + assert!(db + .dictionary() + .policy("other.exe", &language(Some("en"))) + .unwrap() + .terms + .is_empty()); + assert!(db + .dictionary() + .policy("notepad.exe", &language(Some("fr"))) + .unwrap() + .terms + .is_empty()); + assert_eq!( + db.dictionary() + .policy("notepad.exe", &language(None)) + .unwrap() + .terms + .len(), + 1 + ); +} + +/// Whole-phrase exclusions protect only matching words while unrelated corrections survive. +#[test] +fn protects_whole_phrases_without_matching_inside_words_and_keeps_other_edits() { + let policy = Policy { + terms: vec!["teh phrase".into()], + pairs: vec![], + }; + let source = "é teh phrase wierd"; + let out = output( + "é the phrase weird", + vec![change(2, 5, "teh", "the"), change(13, 18, "wierd", "weird")], + ); + assert_eq!( + policy.filter(source, out).corrected_executable_text, + "é teh phrase weird" + ); + let policy = Policy { + terms: vec!["teh".into()], + pairs: vec![], + }; + let out = output("thex", vec![change(0, 4, "tehx", "thex")]); + assert_eq!(policy.filter("tehx", out).corrected_executable_text, "thex"); +} + +/// Pair rules reject their exact outcome across narrow or broad edits, allowing proven alternatives. +#[test] +fn pair_blocks_only_rejected_replacement_and_supports_multiple_edits_in_phrase() { + let policy = Policy { + terms: vec![], + pairs: vec![("teh".into(), "the".into())], + }; + let out = output( + "the weird", + vec![change(0, 3, "teh", "the"), change(4, 9, "wierd", "weird")], + ); + assert_eq!( + policy.filter("teh wierd", out).corrected_executable_text, + "teh weird" + ); + let out = output("ten", vec![change(0, 3, "teh", "ten")]); + assert_eq!(policy.filter("teh", out).corrected_executable_text, "ten"); + assert!( + !policy + .filter( + "I teh today", + output( + "I the today", + vec![change(0, 11, "I teh today", "I the today")] + ) + ) + .changes_needed + ); + assert_eq!( + policy + .filter( + "I teh today", + output( + "I ten today", + vec![change(0, 11, "I teh today", "I ten today")] + ) + ) + .corrected_executable_text, + "I ten today" + ); + assert!( + !policy + .filter( + "teh wierd", + output("the weird", vec![change(0, 9, "teh wierd", "the weird")]) + ) + .changes_needed + ); + let policy = Policy { + terms: vec![], + pairs: vec![("teh wierd".into(), "the weird".into())], + }; + let out = output( + "the weird", + vec![change(0, 3, "teh", "the"), change(4, 9, "wierd", "weird")], + ); + assert!(!policy.filter("teh wierd", out).changes_needed); +} + +/// Rejected pairs cover boundary insertions and deletions as well as substitutions. +#[test] +fn insertion_and_deletion_rules_are_enforced() { + let policy = Policy { + terms: vec![], + pairs: vec![ + ("cant".into(), "can't".into()), + ("very very".into(), "very".into()), + ], + }; + assert!( + !policy + .filter("cant", output("can't", vec![change(3, 3, "", "'")])) + .changes_needed + ); + assert!( + !policy + .filter("very very", output("very", vec![change(4, 9, " very", "")])) + .changes_needed + ); + let policy = Policy { + terms: vec![], + pairs: vec![("hello".into(), "hello.".into())], + }; + assert!( + !policy + .filter("hello", output("hello.", vec![change(5, 5, "", ".")])) + .changes_needed + ); +} + +/// Saved pair rules remain active independently of learning and duplicate writes stay unique. +#[test] +fn active_pairs_work_when_learning_is_disabled_and_deduplicate() { + let db = Database::open_memory().unwrap(); + let rejection = Rejection { + original: "teh".into(), + corrected: "the".into(), + language: Some("en".into()), + app: "app.exe".into(), + }; + let config = LearningConfig { + mode: LearningMode::Automatic, + ..LearningConfig::default() + }; + db.dictionary().remember(&rejection, &config).unwrap(); + db.dictionary().remember(&rejection, &config).unwrap(); + let policy = db + .dictionary() + .policy("app.exe", &language(Some("en"))) + .unwrap(); + assert_eq!(policy.pairs.len(), 1); + assert!( + !policy + .filter("teh", output("the", vec![change(0, 3, "teh", "the")])) + .changes_needed + ); +} + +/// Engine migrations preserve exclusions in a database first initialized by the settings UI. +#[test] +fn engine_migrates_database_created_by_settings_first() { + // File-backed migration is exercised through the production Database entry point. + let path = std::env::temp_dir().join(format!( + "autofix-dictionary-{}.sqlite", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let file = Connection::open(&path).unwrap(); + file.execute_batch("create table custom_dictionary_entries (id integer primary key, language_code text not null, app_process_name text, entry text not null, created_at text not null default current_timestamp, unique(language_code,app_process_name,entry)); insert into custom_dictionary_entries(language_code,entry) values ('en','teh');").unwrap(); + drop(file); + let db = Database::open(&path).unwrap(); + assert_eq!( + db.dictionary() + .policy("app.exe", &language(Some("en"))) + .unwrap() + .terms, + ["teh"] + ); + drop(db); + std::fs::remove_file(path).unwrap(); +} diff --git a/app-core-rust/src/lib.rs b/app-core-rust/src/lib.rs index dc22f7d..96d3e37 100644 --- a/app-core-rust/src/lib.rs +++ b/app-core-rust/src/lib.rs @@ -1,5 +1,6 @@ mod background; pub mod correction; +mod dictionary; mod ipc; mod settings; mod storage; diff --git a/app-core-rust/src/settings/mod.rs b/app-core-rust/src/settings/mod.rs index 2dbe52a..9af501c 100644 --- a/app-core-rust/src/settings/mod.rs +++ b/app-core-rust/src/settings/mod.rs @@ -7,7 +7,8 @@ mod validation; pub(crate) use crate::correction::CorrectionMode; pub(crate) use model::{ - AppConfig, ContextConfig, CorrectionEngine, PendingQueueFullBehavior, RunMode, + AppConfig, ContextConfig, CorrectionEngine, LearningConfig, LearningMode, LearningRule, + PendingQueueFullBehavior, RunMode, }; pub(crate) use shortcuts::{Shortcut, ShortcutKey}; pub(crate) use toml_io::{load_config, save_config, ConfigIoError}; diff --git a/app-core-rust/src/settings/model.rs b/app-core-rust/src/settings/model.rs index bbeedf5..85ce079 100644 --- a/app-core-rust/src/settings/model.rs +++ b/app-core-rust/src/settings/model.rs @@ -16,11 +16,40 @@ pub(crate) struct AppConfig { pub(crate) correction: CorrectionConfig, #[serde(default)] pub(crate) replacement: ReplacementConfig, + #[serde(default)] + pub(crate) learning: LearningConfig, pub(crate) api: ApiConfig, pub(crate) feedback: FeedbackConfig, pub(crate) logging: LoggingConfig, } +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +pub(crate) struct LearningConfig { + #[serde(default)] + pub(crate) mode: LearningMode, + #[serde(default)] + pub(crate) rule: LearningRule, + #[serde(default)] + pub(crate) per_app: bool, +} + +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum LearningMode { + #[default] + Off, + Ask, + Automatic, +} + +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum LearningRule { + Dictionary, + #[default] + Pair, +} + impl AppConfig { /// Snapshot confidence settings, honoring the user's suggestion preference. pub(crate) fn confidence_behavior(&self) -> ConfidenceBehaviorSettings { @@ -105,6 +134,8 @@ impl Default for TriggersConfig { #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub(crate) struct ContextConfig { + #[serde(default = "default_undo_history_size")] + pub(crate) undo_history_size: u16, #[serde(default = "default_pending_queue_size")] pub(crate) pending_queue_size: u16, #[serde(default)] @@ -118,8 +149,10 @@ pub(crate) struct ContextConfig { } impl Default for ContextConfig { + /// Bound retained context and correction queues, keeping ten session undo entries by default. fn default() -> Self { Self { + undo_history_size: default_undo_history_size(), pending_queue_size: 1, pending_queue_full_behavior: PendingQueueFullBehavior::SkipNew, initial_context_words: 25, @@ -132,6 +165,11 @@ impl Default for ContextConfig { } } +/// Preserve the same ten-entry undo capacity when loading older TOML files. +fn default_undo_history_size() -> u16 { + 10 +} + fn default_pending_queue_size() -> u16 { 1 } diff --git a/app-core-rust/src/settings/tests.rs b/app-core-rust/src/settings/tests.rs index 389e8c9..448f469 100644 --- a/app-core-rust/src/settings/tests.rs +++ b/app-core-rust/src/settings/tests.rs @@ -10,6 +10,79 @@ use super::{ AppConfig, ValidateConfig, }; +/// Undo capacity round-trips through TOML and defaults to ten for legacy files. +#[test] +fn undo_capacity_round_trips_and_legacy_settings_keep_ten_entries() { + let mut config = AppConfig::default(); + assert_eq!(config.context.undo_history_size, 10); + for size in [1, 10, 1000] { + config.context.undo_history_size = size; + let encoded = config_to_toml(&config).unwrap(); + assert_eq!( + super::toml_io::parse_config(&encoded) + .unwrap() + .context + .undo_history_size, + size + ); + } + let encoded = config_to_toml(&config).unwrap(); + let legacy = encoded + .lines() + .filter(|line| !line.starts_with("undo_history_size")) + .collect::>() + .join("\n"); + assert_eq!( + super::toml_io::parse_config(&legacy) + .unwrap() + .context + .undo_history_size, + 10 + ); + for size in [0, 1001] { + config.context.undo_history_size = size; + assert_eq!( + config.validate().unwrap_err().field(), + "context.undo_history_size" + ); + } +} + +/// Learning stays off for legacy settings and explicit policy choices round-trip. +#[test] +fn learning_is_opt_in_and_round_trips_with_legacy_defaults() { + use super::{LearningMode, LearningRule}; + let mut config = AppConfig::default(); + assert_eq!(config.learning.mode, LearningMode::Off); + for mode in [ + LearningMode::Off, + LearningMode::Ask, + LearningMode::Automatic, + ] { + for rule in [LearningRule::Dictionary, LearningRule::Pair] { + config.learning.mode = mode; + config.learning.rule = rule; + config.learning.per_app = true; + let encoded = config_to_toml(&config).unwrap(); + assert_eq!( + super::toml_io::parse_config(&encoded).unwrap().learning, + config.learning + ); + } + } + let mut document = toml::Value::try_from(&config).unwrap(); + document.as_table_mut().unwrap().remove("learning"); + let legacy = toml::to_string(&document).unwrap(); + assert_eq!( + super::toml_io::parse_config(&legacy).unwrap().learning.mode, + LearningMode::Off + ); + assert!(super::toml_io::parse_config( + &legacy.replace("[general]", "[learning]\nmode = 'invalid'\n[general]") + ) + .is_err()); +} + #[test] fn clipboard_preference_round_trips_and_legacy_configs_keep_default() { let mut config = AppConfig::default(); diff --git a/app-core-rust/src/settings/validation.rs b/app-core-rust/src/settings/validation.rs index 8eeb97a..92717d2 100644 --- a/app-core-rust/src/settings/validation.rs +++ b/app-core-rust/src/settings/validation.rs @@ -37,6 +37,12 @@ impl Error for ConfigValidationError {} impl ValidateConfig for AppConfig { fn validate(&self) -> Result<(), ConfigValidationError> { + if !(1..=1000).contains(&self.context.undo_history_size) { + return Err(ConfigValidationError::new( + "context.undo_history_size", + "must be between 1 and 1000", + )); + } if !(1..=16).contains(&self.context.pending_queue_size) { return Err(ConfigValidationError::new( "context.pending_queue_size", diff --git a/app-core-rust/src/storage.rs b/app-core-rust/src/storage.rs index 286ee93..a349c7c 100644 --- a/app-core-rust/src/storage.rs +++ b/app-core-rust/src/storage.rs @@ -10,7 +10,7 @@ mod types; use std::path::Path; -use rusqlite::{Connection, Result}; +use rusqlite::{Connection, OpenFlags, Result}; pub(crate) use app_policy::AppPolicyGuard; use logs::{CorrectionMetadataRepository, DebugEventRepository}; @@ -19,14 +19,27 @@ use repositories::{ LearnedRuleRepository, }; pub(crate) use types::AppRule; +pub(crate) use types::CorrectionMetadata; #[cfg(test)] -use types::{CorrectionMetadata, CustomDictionaryEntry, LanguageOverride, LearnedCorrectionRule}; +use types::{CustomDictionaryEntry, LanguageOverride, LearnedCorrectionRule}; pub(crate) struct Database { connection: Connection, } impl Database { + /// Record optional telemetry without migrations, file creation, or waiting for a writer. + /// Policy reservations take priority; busy or unavailable storage loses only metadata. + pub(crate) fn record_metadata_nowait(path: &Path, metadata: &CorrectionMetadata) -> Result<()> { + let connection = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_WRITE)?; + connection.busy_timeout(std::time::Duration::ZERO)?; + CorrectionMetadataRepository::new(&connection).record(metadata) + } + + /// Access persistent exclusions independently of whether new learning is enabled. + pub(crate) fn dictionary(&self) -> crate::dictionary::Repository<'_> { + crate::dictionary::Repository::new(&self.connection) + } /// File identity for fresh policy reads on a separate transport connection. pub(crate) fn path(&self) -> Option<&Path> { self.connection diff --git a/app-core-rust/src/storage/migrations.rs b/app-core-rust/src/storage/migrations.rs index 14c65fc..8fdf264 100644 --- a/app-core-rust/src/storage/migrations.rs +++ b/app-core-rust/src/storage/migrations.rs @@ -169,7 +169,7 @@ fn current_version(connection: &Connection) -> Result { fn migrate_to_v1(connection: &Connection) -> Result<()> { connection.execute_batch( " - create table app_rules ( + create table if not exists app_rules ( id integer primary key, process_name text not null, window_title_pattern text not null default '', @@ -184,7 +184,7 @@ fn migrate_to_v1(connection: &Connection) -> Result<()> { unique (process_name, window_title_pattern) ); - create table custom_dictionary_entries ( + create table if not exists custom_dictionary_entries ( id integer primary key, language_code text not null, app_process_name text, @@ -193,7 +193,7 @@ fn migrate_to_v1(connection: &Connection) -> Result<()> { unique (language_code, app_process_name, entry) ); - create table learned_correction_rules ( + create table if not exists learned_correction_rules ( id integer primary key, learning_enabled integer not null default 0 check (learning_enabled in (0, 1)), original_text text not null, diff --git a/app-core-rust/src/storage/tests.rs b/app-core-rust/src/storage/tests.rs index 4358d0f..f1b9ece 100644 --- a/app-core-rust/src/storage/tests.rs +++ b/app-core-rust/src/storage/tests.rs @@ -9,6 +9,45 @@ use super::{ LearnedCorrectionRule, }; +/// Optional metadata must neither create a missing database nor migrate an existing one. +#[test] +fn metadata_nowait_never_creates_or_migrates_storage() { + let path = std::env::temp_dir().join(format!( + "autofix-metadata-{}.sqlite", + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let metadata = CorrectionMetadata { + session_id: "1".into(), + app_process_name: "notepad.exe".into(), + trigger_type: "manual_shortcut".into(), + confidence_tier: "high".into(), + engine_used: "local_rule".into(), + replacement_method: "none".into(), + result_reason: "no_correction_needed".into(), + latency_ms: 0, + }; + assert!(Database::record_metadata_nowait(&path, &metadata).is_err()); + assert!(!path.exists()); + let connection = Connection::open(&path).unwrap(); + connection + .execute_batch("create table sentinel (value text)") + .unwrap(); + assert!(Database::record_metadata_nowait(&path, &metadata).is_err()); + let tables: i64 = connection + .query_row( + "select count(*) from sqlite_master where type = 'table'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(tables, 1); + drop(connection); + fs::remove_file(path).unwrap(); +} + #[test] fn opens_sqlite_database_and_runs_migrations() { let database = Database::open_memory().unwrap(); diff --git a/shared-schema/README.md b/shared-schema/README.md index 36f62d7..85f4935 100644 --- a/shared-schema/README.md +++ b/shared-schema/README.md @@ -10,6 +10,23 @@ This component owns stable contracts between: Keep schemas explicit, versioned, and documented. Avoid storing executable runtime state here; this area is for contracts, structured settings, and compatibility notes. +`[learning]` is optional in TOML. `mode` accepts `off` (default), `ask`, or +`automatic`; `rule` accepts `pair` (default) or `dictionary`; `per_app` defaults +to false. Rust and WPF use the same defaults and reject unknown choices. +Learning changes only future exclusions after successful app-level undo. Accepted +consent and automatic learning queue saves on a bounded background writer with +its own connection. Settings changes revoke pending consent; save failures warn +without captured text and never block input processing. +Exclusions remain active independently of these settings. + +The WPF editor and Rust engine share `custom_dictionary_entries` and +`learned_correction_rules` in `autofix.sqlite`. Null app scope means all apps; +`und` dictionary language and null/`und` pair language mean all languages. +Active pairs use `learning_enabled = 1` and `rule_type = 'pair'`. SQLite row IDs +identify editor updates and deletes; dictionary/rule edits use transactions. +The engine owns migration versions and accepts tables initialized by settings. +No dictionary IPC is required: the settings editor writes the same local database. + Confidence settings retain the existing TOML values: `silent`, `suggestion`, and `do_nothing`. High defaults to `silent`, medium to `suggestion`, and low is fixed to `do_nothing`. In v1, medium `suggestion` means manual-only with available @@ -30,8 +47,10 @@ Pending correction settings live in the existing `[context]` TOML section: waiting requests per session. `pending_queue_full_behavior` accepts `skip_new` (default), `cancel_oldest`, and `merge_newest`. Merge cancels the newest pending request, restores its typed text into the active context alongside new typing, -and waits for the next automatic trigger. Older settings files default to one -pending correction and skipping new triggers. Queue contents remain memory-only. +and waits for the next automatic trigger. Cancel-oldest cancels the oldest and +dependent newer requests, then resubmits all unchecked text with the new segment. +It does not commit cancelled text into informative context. Older settings files +default to one pending correction and skipping new triggers. Queue contents remain memory-only. API settings retain `timeout_manual_ms = 3000`, `timeout_auto_ms = 700`, `retry_count = 1`, and `fallback_to_local = false` defaults. Retry count accepts @@ -51,12 +70,13 @@ from the fresh policy read until the send returns, so IPC and settings UI rule writes serialize with transmission. A revocation is effective when its write commits; previously transmitted data cannot be recalled. Missing, unreadable, or busy policy storage denies sending immediately. Denied frozen work releases -its slot and retires its original text through failed completion. +its slot and restores its original text and dependent newer segments to active +executable context through failed completion. -The live replacement consumer is still a placeholder. Before enabling it, the -mutation owner must enforce `silent` or explicit acceptance of a suggestion and -recheck process, focused target, security gate, caret, and context/executable -versions immediately before manual replacement. Frozen automatic replacements +The native replacement consumer enforces `silent` results; suggestion acceptance +remains planned. The mutation owner must recheck process, focused target, +security gate, caret, and context/executable versions immediately before manual +replacement. Frozen automatic replacements validate their session, segment identity, original typed range, caret anchor, and known following text instead of requiring unchanged active context versions. They wait for queued hook input and recheck generations after live security calls. @@ -72,5 +92,7 @@ out-of-order results, a target becoming secure, and interrupted replacement with rollback and clipboard/undo recovery. The async pipeline now tests stale and reordered result rejection, typing/focus changes, security revalidation, and session completion only after a replacement callback confirms success. Native -replacement remains unavailable; these tests cannot establish target mutation, -rollback, clipboard recovery, or target undo until the native consumer exists. +clipboard paste and SendInput replacement are implemented for supported controls; +direct text APIs and UI Automation mutation remain planned. Focused native tests +verify correction, recorded app-level undo, clipboard preservation and recovery, +and preservation of newer typing, caret position, and text after the caret. diff --git a/ui/settings-ui-tests/AutoFix.SettingsUi.Tests.csproj b/ui/settings-ui-tests/AutoFix.SettingsUi.Tests.csproj index 0c2deea..9d96ced 100644 --- a/ui/settings-ui-tests/AutoFix.SettingsUi.Tests.csproj +++ b/ui/settings-ui-tests/AutoFix.SettingsUi.Tests.csproj @@ -2,6 +2,7 @@ net8.0-windows + true enable enable @@ -22,6 +23,7 @@ + diff --git a/ui/settings-ui-tests/ConfigFormMapperTests.cs b/ui/settings-ui-tests/ConfigFormMapperTests.cs index d4dca33..b8d0961 100644 --- a/ui/settings-ui-tests/ConfigFormMapperTests.cs +++ b/ui/settings-ui-tests/ConfigFormMapperTests.cs @@ -6,6 +6,34 @@ namespace AutoFix.SettingsUi.Tests; [TestClass] public sealed class ConfigFormMapperTests { + [TestMethod] + public void UndoShortcutAndHistorySurviveFormStorageAndLegacyLoad() + { + using var fixture = TempConfigFixture.Create(); + var sections = SettingsSkeleton.CreateSections(); + Assert.AreEqual("Ctrl+Alt+Z", Card(sections, "shortcuts.undo").Hotkey); + Assert.AreEqual("10", Card(sections, "context.undo_history_size").TextValue); + Card(sections, "shortcuts.undo").Hotkey = "Ctrl+Shift+Z"; + foreach (var size in new[] { 1, 25, 1000 }) + { + Card(sections, "context.undo_history_size").TextValue = size.ToString(); + fixture.Storage.Save(ConfigFormMapper.BuildConfig(sections)); + var loaded = fixture.Storage.Load(fixture.Path); + Assert.AreEqual(size, loaded.Context.UndoHistorySize); + Assert.AreEqual("Ctrl+Shift+Z", loaded.Shortcuts.Undo); + Assert.AreEqual(size.ToString(), Card(SettingsSkeleton.CreateSections(loaded), "context.undo_history_size").TextValue); + } + var legacy = File.ReadAllLines(fixture.Path).Where(line => !line.StartsWith("undo_history_size", StringComparison.Ordinal)); + File.WriteAllLines(fixture.Path, legacy); + Assert.AreEqual(10, fixture.Storage.Load(fixture.Path).Context.UndoHistorySize); + foreach (var size in new[] { "0", "1001" }) + { + Card(sections, "context.undo_history_size").TextValue = size; + var error = Assert.ThrowsException(() => ConfigFormMapper.BuildConfig(sections)); + Assert.AreEqual("context.undo_history_size: must be between 1 and 1000", error.Message); + } + } + [TestMethod] public void ClipboardPreferenceSurvivesFormAndStorageRoundTrip() { diff --git a/ui/settings-ui-tests/DictionaryStorageTests.cs b/ui/settings-ui-tests/DictionaryStorageTests.cs new file mode 100644 index 0000000..284b1cc --- /dev/null +++ b/ui/settings-ui-tests/DictionaryStorageTests.cs @@ -0,0 +1,84 @@ +using AutoFix.SettingsUi.Models; +using AutoFix.SettingsUi.Settings; +using AutoFix.SettingsUi.ViewModels; + +namespace AutoFix.SettingsUi.Tests; + +[TestClass] +public sealed class DictionaryStorageTests +{ + [TestMethod] + public void WordsPhrasesScopesAndPairsRoundTripAndRemainUnique() + { + using var fixture = TempConfigFixture.Create(); + var storage = new DictionaryStorage(Path.Combine(fixture.Root, "autofix.sqlite")); + storage.Save(new DictionaryItem { Word = "teh phrase", Language = "en", Source = "dictionary" }); + storage.Save(new DictionaryItem { Word = "teh phrase", Language = "EN", Source = "dictionary" }); + storage.Save(new DictionaryItem { Word = "teh", Language = "en-US", App = "Notepad.EXE", Source = "pair", Replacement = "the" }); + var rows = storage.List(); + Assert.AreEqual(2, rows.Count); + var pair = rows.Single(e => e.Source == "pair"); + Assert.AreEqual("notepad.exe", pair.App); + Assert.AreEqual("the", pair.Replacement); + Assert.AreEqual("en-US", pair.Language); + storage.Save(new DictionaryItem { Word = "wierd", Language = "und", Source = "dictionary" }, pair); + rows = storage.List(); + Assert.AreEqual(2, rows.Count); + Assert.IsTrue(rows.All(e => e.Source == "dictionary")); + storage.Delete(rows.Single(e => e.Word == "wierd")); + Assert.AreEqual(1, storage.List().Count); + } + + [TestMethod] + public void InvalidEditPreservesExistingEntry() + { + using var fixture = TempConfigFixture.Create(); + var storage = new DictionaryStorage(Path.Combine(fixture.Root, "autofix.sqlite")); + storage.Save(new DictionaryItem { Word = "teh", Language = "en", Source = "dictionary" }); + var row = storage.List().Single(); + foreach (var bad in new[] { + new DictionaryItem { Word = "", Language = "en", Source = "dictionary" }, + new DictionaryItem { Word = "teh", Language = "English-US-!", Source = "dictionary" }, + new DictionaryItem { Word = "teh", Language = "en", Source = "dictionary", App = @"C:\app.exe" }, + new DictionaryItem { Word = "teh", Language = "en", Source = "pair", Replacement = "teh" } }) + { + Assert.ThrowsException(() => storage.Save(bad, row)); + Assert.AreEqual("teh", storage.List().Single().Word); + } + } + + [TestMethod] + public void EmptyDictionaryEditorStaysVisibleAndLearningDefaultsOff() + { + var section = SettingsSkeleton.CreateSections().Single(s => s.ShowsDictionary); + Assert.IsTrue(section.HasDictionary); + Assert.AreEqual(0, section.Dictionary.Count); + Assert.AreEqual("off", section.Settings.Single(s => s.Path == "learning.mode").SelectedValue); + Assert.AreEqual("pair", section.Settings.Single(s => s.Path == "learning.rule").SelectedValue); + } + + [TestMethod] + public void LearningChoicesPersistAndLegacyConfigDefaultsOff() + { + using var fixture = TempConfigFixture.Create(); + var config = AppConfig.Default(); + foreach (var mode in new[] { "off", "ask", "automatic" }) + foreach (var rule in new[] { "dictionary", "pair" }) + { + config.Learning.Mode = mode; config.Learning.Rule = rule; config.Learning.PerApp = true; + var mapped = ConfigFormMapper.BuildConfig(SettingsSkeleton.CreateSections(config)); + fixture.Storage.Save(mapped); + var loaded = fixture.Storage.Load(fixture.Path); + Assert.AreEqual(mode, loaded.Learning.Mode); + Assert.AreEqual(rule, loaded.Learning.Rule); + Assert.IsTrue(loaded.Learning.PerApp); + } + var toml = File.ReadAllText(fixture.Path); + var start = toml.IndexOf("[learning]", StringComparison.Ordinal); + var end = toml.IndexOf('[', start + 1); + File.WriteAllText(fixture.Path, end < 0 ? toml[..start] : toml.Remove(start, end-start)); + Assert.AreEqual("off", fixture.Storage.Load(fixture.Path).Learning.Mode); + config.Learning.Mode = "unknown"; + Assert.ThrowsException(() => ConfigValidator.Validate(config)); + } +} diff --git a/ui/settings-ui-tests/MainWindowViewModelTests.cs b/ui/settings-ui-tests/MainWindowViewModelTests.cs index 3162963..eae41bd 100644 --- a/ui/settings-ui-tests/MainWindowViewModelTests.cs +++ b/ui/settings-ui-tests/MainWindowViewModelTests.cs @@ -7,6 +7,94 @@ namespace AutoFix.SettingsUi.Tests; [TestClass] public sealed class MainWindowViewModelTests { + [TestMethod] + public void DictionaryWindowEditsScopedPairsAndPreservesInvalidEdits() + { + Exception? failure = null; + var thread = new Thread(() => + { + MainWindow? window = null; + try + { + using var fixture = TempConfigFixture.Create(); + var config = AppConfig.Default(); config.Onboarding.Completed = true; + fixture.Storage.Save(config); + var storage = new DictionaryStorage(Path.Combine(fixture.Root, "autofix.sqlite")); + var viewModel = new MainWindowViewModel(new FakeBackgroundIpcClient(), fixture.Storage, + new AppRuleStorage(Path.Combine(fixture.Root, "autofix.sqlite")), new NullConfigFileDialog(), new FakeApiKeyStatus(false), new FakeStartupRegistration()); + window = new MainWindow(viewModel) { ShowActivated = false, Left = -10000, Top = -10000, Width = 1080, Height = 1150 }; + window.Show(); + viewModel.SelectedSection = viewModel.Sections.Single(s => s.ShowsDictionary); + viewModel.DictionaryKind = "pair"; + Pump(); + var boxes = Descendants(window).OfType().ToArray(); + void Type(string name, string text) => boxes.Single(b => System.Windows.Automation.AutomationProperties.GetName(b) == name) + .SetCurrentValue(System.Windows.Controls.TextBox.TextProperty, text); + void Click(string content) + { + var button = Descendants(window).OfType().Single(b => Equals(b.Content, content)); + Assert.IsNotNull(button.Command); + button.Command.Execute(button.CommandParameter); + Pump(); + } + Type("Dictionary word or phrase", "teh phrase"); + Type("Blocked replacement", "the phrase"); + Type("Dictionary language", "en-US"); + Type("Dictionary app scope", "Notepad.EXE"); + Click("Save entry"); + var row = storage.List().Single(); + Assert.AreEqual("teh phrase", row.Word); + Assert.AreEqual("the phrase", row.Replacement); + Assert.AreEqual("notepad.exe", row.App); + var grid = Descendants(window).OfType().Single(g => System.Windows.Automation.AutomationProperties.GetName(g) == "Dictionary"); + grid.SelectedItem = grid.Items[0]; + Pump(); + Assert.AreEqual("teh phrase", viewModel.DictionaryWord); + Assert.IsTrue(viewModel.IsPairRule); + var preview = Environment.GetEnvironmentVariable("AUTOFIX_SETTINGS_PREVIEW"); + if (!string.IsNullOrEmpty(preview)) + { + window.UpdateLayout(); + var bitmap = new System.Windows.Media.Imaging.RenderTargetBitmap((int)window.ActualWidth, (int)window.ActualHeight, 96, 96, System.Windows.Media.PixelFormats.Pbgra32); + bitmap.Render(window); + var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder(); + encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmap)); + using var file = File.Create(preview); encoder.Save(file); + } + Type("Dictionary language", "invalid-!"); + Click("Save entry"); + Assert.AreEqual("Exclusion not saved.", viewModel.StatusTitle); + StringAssert.Contains(viewModel.DictionaryMessage, "BCP 47"); + Assert.AreEqual("en-US", storage.List().Single().Language); + Type("Dictionary language", "fr"); + Click("Save entry"); + Assert.AreEqual("fr", storage.List().Single().Language); + grid.SelectedItem = grid.Items[0]; + Pump(); + Click("Delete selected"); + Assert.AreEqual(0, storage.List().Count); + } + catch (Exception error) { failure = error; } + finally { window?.Close(); } + }) { IsBackground = true }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + Assert.IsTrue(thread.Join(TimeSpan.FromSeconds(15)), "WPF dictionary flow timed out."); + if (failure is not null) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(failure).Throw(); + } + + private static void Pump() => System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(() => { }, System.Windows.Threading.DispatcherPriority.Background); + + private static IEnumerable Descendants(System.Windows.DependencyObject root) + { + for (var i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(root); i++) + { + var child = System.Windows.Media.VisualTreeHelper.GetChild(root, i); + yield return child; + foreach (var descendant in Descendants(child)) yield return descendant; + } + } + [TestMethod] public async Task SettingChangeSavesConfigAutomatically() { diff --git a/ui/settings-ui-tests/SettingsSkeletonTests.cs b/ui/settings-ui-tests/SettingsSkeletonTests.cs index 43b09a0..e72549d 100644 --- a/ui/settings-ui-tests/SettingsSkeletonTests.cs +++ b/ui/settings-ui-tests/SettingsSkeletonTests.cs @@ -40,6 +40,7 @@ public void CreateSectionsIncludesExpectedSettingsAreas() "Shortcuts", "Triggers", "Correction", + "Dictionary", "Engines", "Context", "Feedback", diff --git a/ui/settings-ui/MainWindow.xaml b/ui/settings-ui/MainWindow.xaml index fef5872..8a826b0 100644 --- a/ui/settings-ui/MainWindow.xaml +++ b/ui/settings-ui/MainWindow.xaml @@ -373,17 +373,42 @@ - + + + +