From b5b49a614fe204023955f37d3e23ca27b9d2ea8f Mon Sep 17 00:00:00 2001 From: Hussein Ba Ragaa Date: Fri, 2 Oct 2026 18:50:36 +0300 Subject: [PATCH 1/6] feat(feedback): surface quiet correction feedback --- README.md | 15 ++ app-core-rust/README.md | 25 +- app-core-rust/src/background/feedback.rs | 237 ++++++++++++++++++ .../src/background/feedback/notice.rs | 197 +++++++++++++++ app-core-rust/src/background/mod.rs | 86 ++++++- app-core-rust/src/background/pipeline.rs | 88 ++++++- .../src/background/pipeline/tests.rs | 161 ++++++++++++ app-core-rust/src/background/tests.rs | 6 + .../src/background/timeout_notice.rs | 146 ----------- app-core-rust/src/ipc/protocol.rs | 2 + app-core-rust/src/ipc/state.rs | 2 + app-core-rust/src/ipc/tests.rs | 33 +++ app-core-rust/src/settings/mod.rs | 4 +- app-core-rust/src/settings/model.rs | 7 +- app-core-rust/src/settings/tests.rs | 38 +++ shared-schema/README.md | 14 ++ shared-schema/ipc.schema.json | 21 +- ui/settings-ui-tests/ConfigFormMapperTests.cs | 21 ++ .../MainWindowViewModelTests.cs | 50 ++++ ui/settings-ui-tests/TrayFeedbackTests.cs | 56 +++++ ui/settings-ui/Ipc/IpcProtocol.cs | 4 +- ui/settings-ui/Lifetime/ShellLifetime.cs | 10 +- ui/settings-ui/Lifetime/ShellTray.cs | 79 +++++- ui/settings-ui/README.md | 15 +- ui/settings-ui/Settings/AppConfig.cs | 7 +- ui/settings-ui/Settings/ConfigFormMapper.cs | 1 + ui/settings-ui/ViewModels/SettingsSkeleton.cs | 7 +- 27 files changed, 1152 insertions(+), 180 deletions(-) create mode 100644 app-core-rust/src/background/feedback.rs create mode 100644 app-core-rust/src/background/feedback/notice.rs delete mode 100644 app-core-rust/src/background/timeout_notice.rs create mode 100644 ui/settings-ui-tests/TrayFeedbackTests.cs diff --git a/README.md b/README.md index 0e54a0a..8720eb9 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,21 @@ before reporting success. Disable it under **Correction > Use clipboard for correction** or set `replacement.clipboard_enabled = false` in settings TOML. See [the engine documentation](app-core-rust/README.md) for runtime boundaries. +**Feedback** keeps AutoFix quiet by default. The tray always stays available, +with idle, active, correcting, blocked and error states. Successful automatic +corrections show no popup. Manual failures, blocked actions and manual API +timeouts use a small notice that never takes focus. Repeated notices coalesce +and disappear after 2.5 seconds, new typing or a focus change. Secure fields do +not receive correction notices. + +You can enable correction-applied notices, skipped reasons, and read-only manual +medium-confidence suggestion previews. Suggestions never apply edits; acceptance +remains planned. Blocked-action and timeout notices can be disabled independently. +Optional near-caret placement uses the Windows native caret when available, +otherwise the notice appears in the current monitor's work-area corner. Turning +off tray state keeps the tray icon and its settings/Exit menu available. Existing +saved preferences are preserved; new feedback options default to off. + When safer methods are unavailable or clipboard correction is disabled, SendInput can replace a verified pre-caret span in supported Unicode Edit controls. Unknown controls, unsafe selections and security refusals skip correction and log only diff --git a/app-core-rust/README.md b/app-core-rust/README.md index 15f7474..c588989 100644 --- a/app-core-rust/README.md +++ b/app-core-rust/README.md @@ -98,7 +98,7 @@ unlisted changes, invalid offsets, and changed protected terms. API typo edits must match the local engine's known spelling replacements. Automatic timeouts silently skip correction and release frozen queue capacity. Valid manual API timeouts show a small, disabled, no-activate notice near the -bottom-right work area for 2.5 seconds. `feedback.show_timeout_notice` defaults +bottom-right work area of the current monitor for 2.5 seconds. `feedback.show_timeout_notice` defaults to true and can disable it. Repeated notices coalesce; cancelled, stale, and secure-target results cannot show a notice. Opt-in local fallback follows the same confidence and completion checks as normal local correction and suppresses @@ -106,6 +106,19 @@ the timeout notice when it completes. `ApiCorrectionEngine::notice_for` distinguishes manual timeout and failure feedback from silent automatic handling. The local ML engine remains a placeholder. Live triggers invoke these engines on the correction worker. +`src/background/feedback` owns runtime feedback policy and coalesced notices. +The default shows only generic manual failure/blocked-action notices and enabled +manual API timeout notices. Automatic success and skips stay silent; applied +notifications and skipped reasons are opt-in. Messages never include engine +failure strings. Input and focus generations cancel stale notices before display +and dismiss visible notices on new typing or movement. Near-caret placement is +opt-in and uses `GetGUIThreadInfo`/`ClientToScreen`; missing native caret support +falls back to the current monitor's work-area corner. +The IPC status carries only `tray_state`: idle, active (retained executable typing), +correcting (admitted work), blocked (a denied target/action), or error (brief engine +failure state). Disabling tray state publishes idle; it never removes the shell's +tray icon. Manual app-policy refusals show a generic blocked notice when enabled; +hard secure-field/desktop refusals never show notices. The native replacement path verifies the session-owned pre-caret range. Engine selection is explicit per request; neither local nor API routing depends on task difficulty, and both correction modes are accepted by every engine. @@ -116,9 +129,13 @@ manual shortcut with an available suggestion UI; word-count, character, and final-fix triggers do nothing. Setting `correction.medium_confidence_behavior` to `silent` enables medium corrections for every trigger. Low confidence is always blocked, including requests that bypass config validation. -`CorrectionInput.suggestion_ui_available` defaults to false; v1 has no suggestion -UI. `feedback.show_medium_confidence_suggestions` can suppress manual suggestions -when building the runtime policy, but never enables silent apply. Outputs include +`CorrectionInput.suggestion_ui_available` defaults to false. Runtime feedback can +enable read-only previews with `feedback.show_medium_confidence_suggestions` +(off by default), but never enables silent apply. Only validated manual medium +results can show a bounded preview of executable text; previews never include +informative context, mutate text, commit sessions or record undo. New typing, +movement, cancellation and secure targets suppress them. Suggestion acceptance +remains planned. Outputs include an explicit `behavior`: only `silent` authorizes replacement; `suggestion` requires user acceptance. Suppressed outputs preserve the original executable text and discard edit details. Local results prioritize silent edits over diff --git a/app-core-rust/src/background/feedback.rs b/app-core-rust/src/background/feedback.rs new file mode 100644 index 0000000..9a9acc9 --- /dev/null +++ b/app-core-rust/src/background/feedback.rs @@ -0,0 +1,237 @@ +//! Quiet feedback policy. Tray state is metadata only; opt-in previews stay ephemeral. + +use super::security::BlockReason; +mod notice; +use crate::settings::FeedbackConfig; +use std::{ + sync::atomic::{AtomicU8, Ordering}, + time::{Duration, Instant}, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Event { + Applied, + Timeout, + Error, + Blocked, + Skipped(&'static str), +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[repr(u8)] +pub(super) enum TrayState { + #[default] + Idle, + Active, + Correcting, + Blocked, + Error, +} + +static TRAY_STATE: AtomicU8 = AtomicU8::new(TrayState::Idle as u8); + +/// The shell polls this bounded, text-free snapshot independently of input processing. +pub(crate) fn tray_state() -> &'static str { + match TRAY_STATE.load(Ordering::Relaxed) { + 1 => "active", + 2 => "correcting", + 3 => "blocked", + 4 => "error", + _ => "idle", + } +} + +pub(super) fn notice(event: Event, manual: bool, config: &FeedbackConfig) -> Option<&'static str> { + match event { + Event::Applied if config.show_correction_applied_notification => { + Some("AutoFix: correction applied.") + } + Event::Timeout if manual && config.show_timeout_notice => { + Some("AutoFix: API correction timed out.") + } + Event::Error if manual => Some("AutoFix: correction could not be completed."), + Event::Blocked if manual && config.show_blocked_app_notice => { + Some("AutoFix: action could not be safely applied.") + } + Event::Skipped(reason) if config.show_skipped_reason => Some(reason), + _ => None, + } +} + +/// Secure fields never receive overlays, including opted-in notices. +pub(super) fn is_app_block(reason: BlockReason) -> bool { + matches!( + reason, + BlockReason::SensitiveAppDefault + | BlockReason::AppRuleBlocked + | BlockReason::EngineBlocked + | BlockReason::AllowlistRequired + | BlockReason::AppPolicyUnavailable + | BlockReason::UnsupportedTarget + | BlockReason::ElevatedTarget + ) +} + +#[derive(Default)] +pub(super) struct Feedback { + blocked: bool, + error_until: Option, + last_notice: Option, +} + +impl Feedback { + /// Opt-in, read-only preview. Text stays in the short-lived notice worker only. + pub(super) fn suggestion(&mut self, preview: String, config: &FeedbackConfig) { + let now = Instant::now(); + if config.show_medium_confidence_suggestions + && self + .last_notice + .is_none_or(|last| now.duration_since(last) >= Duration::from_millis(2500)) + { + self.last_notice = Some(now); + notice::show(preview, config.show_near_caret_overlay); + } + } + pub(super) fn reset(&mut self) { + self.blocked = false; + self.error_until = None; + } + + pub(super) fn blocked(&mut self, blocked: bool) { + self.blocked = blocked; + } + + pub(super) fn event(&mut self, event: Event, manual: bool, config: &FeedbackConfig) { + let now = Instant::now(); + if matches!(event, Event::Error | Event::Timeout) { + self.error_until = Some(now + Duration::from_millis(2500)); + } + if let Some(text) = notice(event, manual, config) { + if self + .last_notice + .is_none_or(|last| now.duration_since(last) >= Duration::from_millis(2500)) + { + self.last_notice = Some(now); + notice::show(text, config.show_near_caret_overlay); + } + } + } + + fn state(&self, enabled: bool, active: bool, correcting: bool, now: Instant) -> TrayState { + if !enabled { + TrayState::Idle + } else if self.blocked { + TrayState::Blocked + } else if self.error_until.is_some_and(|until| now < until) { + TrayState::Error + } else if correcting { + TrayState::Correcting + } else if active { + TrayState::Active + } else { + TrayState::Idle + } + } + + pub(super) fn publish(&self, config: &FeedbackConfig, active: bool, correcting: bool) { + TRAY_STATE.store( + self.state( + config.tray_state_enabled, + active, + correcting, + Instant::now(), + ) as u8, + Ordering::Relaxed, + ); + } +} + +pub(super) fn suggestion_preview(text: &str) -> String { + let mut preview: String = text + .chars() + .take(90) + .map(|c| if c.is_control() { ' ' } else { c }) + .collect(); + if text.chars().count() > 90 { + preview.push('…'); + } + format!("AutoFix suggestion: {preview}") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn quiet_defaults_and_independent_options() { + let mut config = FeedbackConfig::default(); + for event in [ + Event::Applied, + Event::Timeout, + Event::Error, + Event::Blocked, + Event::Skipped("reason"), + ] { + assert_eq!(notice(event, false, &config), None); + } + assert!(notice(Event::Error, true, &config).is_some()); + assert!(notice(Event::Blocked, true, &config).is_some()); + assert!(notice(Event::Timeout, true, &config).is_some()); + config.show_timeout_notice = false; + config.show_blocked_app_notice = false; + config.show_near_caret_overlay = true; + assert_eq!(notice(Event::Timeout, true, &config), None); + assert_eq!(notice(Event::Blocked, true, &config), None); + assert_eq!(notice(Event::Applied, true, &config), None); + config.show_correction_applied_notification = true; + config.show_skipped_reason = true; + assert!(notice(Event::Applied, false, &config).is_some()); + assert_eq!( + notice(Event::Skipped("reason"), false, &config), + Some("reason") + ); + } + + #[test] + fn states_expire_and_disabled_state_keeps_idle() { + let now = Instant::now(); + let mut feedback = Feedback::default(); + assert_eq!(feedback.state(true, false, false, now), TrayState::Idle); + assert_eq!(feedback.state(true, true, false, now), TrayState::Active); + assert_eq!(feedback.state(true, true, true, now), TrayState::Correcting); + feedback.error_until = Some(now + Duration::from_secs(2)); + assert_eq!(feedback.state(true, true, false, now), TrayState::Error); + assert_eq!( + feedback.state(true, true, false, now + Duration::from_secs(3)), + TrayState::Active + ); + feedback.blocked(true); + assert_eq!(feedback.state(true, true, true, now), TrayState::Blocked); + assert_eq!(feedback.state(false, true, true, now), TrayState::Idle); + feedback.reset(); + assert_eq!(feedback.state(true, false, false, now), TrayState::Idle); + } + + #[test] + fn hard_security_blocks_never_show_notices() { + for reason in [ + BlockReason::PasswordField, + BlockReason::ProtectedOrHiddenField, + BlockReason::SecureDesktop, + BlockReason::CredentialDialog, + BlockReason::LockScreen, + ] { + assert!(!is_app_block(reason)); + } + assert!(is_app_block(BlockReason::AppRuleBlocked)); + } + + #[test] + fn previews_are_bounded_unicode_safe_and_have_no_control_characters() { + assert_eq!(suggestion_preview("a\nb\0c"), "AutoFix suggestion: a b c"); + assert_eq!( + suggestion_preview(&"語".repeat(100)), + format!("AutoFix suggestion: {}…", "語".repeat(90)) + ); + } +} diff --git a/app-core-rust/src/background/feedback/notice.rs b/app-core-rust/src/background/feedback/notice.rs new file mode 100644 index 0000000..cd7d252 --- /dev/null +++ b/app-core-rust/src/background/feedback/notice.rs @@ -0,0 +1,197 @@ +//! Brief, coalesced, non-activating feedback independent of the input processor. + +use std::sync::atomic::{AtomicBool, Ordering}; + +static VISIBLE: AtomicBool = AtomicBool::new(false); + +/// Provide platform feedback without taking focus; unsupported platforms stay silent. +pub(super) fn show(text: impl Into, near_caret: bool) { + if VISIBLE.swap(true, Ordering::AcqRel) { + return; + } + let position = super::super::input_listener::current_position_generation(); + let sequence = super::super::input_listener::current_input_sequence(); + let text = text.into(); + if let Err(error) = std::thread::Builder::new() + .name("autofix-feedback-notice".into()) + .spawn(move || { + native::show(&text, near_caret, position, sequence); + VISIBLE.store(false, Ordering::Release); + }) + { + VISIBLE.store(false, Ordering::Release); + tracing::warn!(%error, "cannot show feedback notice"); + } +} + +#[cfg(windows)] +mod native { + use std::ptr::{null, null_mut}; + use windows_sys::Win32::{ + Foundation::{POINT, RECT}, + Graphics::Gdi::{ + ClientToScreen, GetMonitorInfoW, MonitorFromWindow, MONITORINFO, + MONITOR_DEFAULTTONEAREST, + }, + UI::WindowsAndMessaging::{ + CreateWindowExW, DestroyWindow, DispatchMessageW, GetForegroundWindow, + GetGUIThreadInfo, GetMessageW, GetWindowThreadProcessId, KillTimer, SetTimer, + ShowWindow, SystemParametersInfoW, TranslateMessage, GUITHREADINFO, MSG, + SPI_GETWORKAREA, SW_SHOWNOACTIVATE, WM_TIMER, WS_BORDER, WS_DISABLED, WS_EX_NOACTIVATE, + WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP, + }, + }; + + const SS_CENTER: u32 = 0x1; + + /// Provide platform feedback without taking focus; unsupported platforms stay silent. + pub(super) fn show(text: &str, near_caret: bool, position: u64, sequence: u64) { + let still_current = || { + position == super::super::super::input_listener::current_position_generation() + && sequence == super::super::super::input_listener::current_input_sequence() + }; + if !still_current() { + return; + } + let class: Vec = "STATIC\0".encode_utf16().collect(); + let text: Vec = format!("{text}\0").encode_utf16().collect(); + unsafe { + let mut area: RECT = std::mem::zeroed(); + if SystemParametersInfoW(SPI_GETWORKAREA, 0, (&mut area as *mut RECT).cast(), 0) == 0 { + tracing::warn!("cannot locate work area for feedback notice"); + return; + } + let foreground = GetForegroundWindow(); + let mut monitor: MONITORINFO = std::mem::zeroed(); + monitor.cbSize = std::mem::size_of::() as u32; + if GetMonitorInfoW( + MonitorFromWindow(foreground, MONITOR_DEFAULTTONEAREST), + &mut monitor, + ) != 0 + { + area = monitor.rcWork; + } + let mut x = area.right - 436; + let mut y = area.bottom - 88; + if near_caret { + let mut info: GUITHREADINFO = std::mem::zeroed(); + info.cbSize = std::mem::size_of::() as u32; + let thread = GetWindowThreadProcessId(foreground, null_mut()); + if thread != 0 + && GetGUIThreadInfo(thread, &mut info) != 0 + && !info.hwndCaret.is_null() + { + let mut point = POINT { + x: info.rcCaret.left, + y: info.rcCaret.bottom + 8, + }; + if ClientToScreen(info.hwndCaret, &mut point) != 0 { + x = point.x.clamp(area.left, (area.right - 420).max(area.left)); + y = point.y.clamp(area.top, (area.bottom - 72).max(area.top)); + } + } + } + // Disabled, no-activate tool window: no focus, taskbar entry or input capture. + // SS_CENTER wraps long previews inside the small notice. + let window = CreateWindowExW( + WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST, + class.as_ptr(), + text.as_ptr(), + WS_POPUP | WS_BORDER | WS_DISABLED | SS_CENTER, + x, + y, + 420, + 72, + null_mut(), + null_mut(), + null_mut(), + null(), + ); + if window.is_null() { + tracing::warn!("cannot create feedback notice"); + return; + } + let timer = SetTimer(window, 1, 100, None); + if timer == 0 { + DestroyWindow(window); + tracing::warn!("cannot schedule feedback notice dismissal"); + return; + } + if !still_current() { + KillTimer(window, timer); + DestroyWindow(window); + return; + } + ShowWindow(window, SW_SHOWNOACTIVATE); + let started = std::time::Instant::now(); + let mut message: MSG = std::mem::zeroed(); + while GetMessageW(&mut message, null_mut(), 0, 0) > 0 { + if message.message == WM_TIMER && message.hwnd == window && message.wParam == timer + { + if started.elapsed() >= std::time::Duration::from_millis(2500) + || GetForegroundWindow() != foreground + || !still_current() + { + break; + } + } + TranslateMessage(&message); + DispatchMessageW(&message); + } + KillTimer(window, timer); + DestroyWindow(window); + } + } +} + +#[cfg(all(test, windows))] +mod tests { + use super::*; + use std::{ + ptr::null, + thread, + time::{Duration, Instant}, + }; + use windows_sys::Win32::UI::WindowsAndMessaging::{ + FindWindowW, GetForegroundWindow, GetWindowLongW, IsWindowVisible, GWL_EXSTYLE, GWL_STYLE, + WS_DISABLED, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, + }; + + /// The native notice preserves foreground focus, coalesces duplicates, and dismisses itself. + #[test] + #[ignore = "requires an interactive Windows desktop; briefly displays a feedback notice"] + fn native_feedback_notice_preserves_focus_and_dismisses_itself() { + let title: Vec = "AutoFix: feedback verification.\0".encode_utf16().collect(); + let original = unsafe { GetForegroundWindow() }; + show("AutoFix: feedback verification.", true); + let started = Instant::now(); + let window = loop { + let window = unsafe { FindWindowW(null(), title.as_ptr()) }; + if !window.is_null() && unsafe { IsWindowVisible(window) } != 0 { + break window; + } + assert!(started.elapsed() < Duration::from_secs(2)); + thread::sleep(Duration::from_millis(10)); + }; + unsafe { + assert_eq!(GetForegroundWindow(), original); + assert_ne!(GetWindowLongW(window, GWL_STYLE) as u32 & WS_DISABLED, 0); + let style = GetWindowLongW(window, GWL_EXSTYLE) as u32; + assert_ne!(style & WS_EX_NOACTIVATE, 0); + assert_ne!(style & WS_EX_TOOLWINDOW, 0); + } + // Repeated feedback coalesces into this same notice. + show("AutoFix: feedback verification.", true); + while unsafe { !FindWindowW(null(), title.as_ptr()).is_null() } { + assert!(started.elapsed() < Duration::from_secs(4)); + thread::sleep(Duration::from_millis(20)); + } + assert!(started.elapsed() >= Duration::from_secs(2)); + } +} + +#[cfg(not(windows))] +mod native { + /// Provide platform timeout feedback without taking focus; unsupported platforms stay silent. + pub(super) fn show(_: &str, _: bool, _: u64, _: u64) {} +} diff --git a/app-core-rust/src/background/mod.rs b/app-core-rust/src/background/mod.rs index 22c70b4..498805f 100644 --- a/app-core-rust/src/background/mod.rs +++ b/app-core-rust/src/background/mod.rs @@ -2,6 +2,7 @@ mod admin; pub(crate) mod app_identity; mod components; mod context_capture; +pub(crate) mod feedback; mod informative_context; mod input_listener; mod message_loop; @@ -15,7 +16,6 @@ mod shortcuts; mod target; #[cfg(test)] mod tests; -mod timeout_notice; mod triggers; mod typing; @@ -104,6 +104,7 @@ fn capture_if_current( } struct InputProcessor { + feedback: feedback::Feedback, learner: crate::dictionary::Learner, pipeline: CorrectionPipeline, processed_input_sequence: u64, @@ -314,6 +315,7 @@ impl InputWorker { .name("autofix-input-processing".into()) .spawn(move || { let mut processor = InputProcessor { + feedback: feedback::Feedback::default(), learner: crate::dictionary::Learner::default(), pipeline, processed_input_sequence: input_listener::current_input_sequence(), @@ -345,6 +347,7 @@ impl InputWorker { InputWork::Shortcut(id) => processor.process_shortcut(id), InputWork::Tick => processor.session_manager.prune_exited(), InputWork::Config(config) => { + processor.feedback.reset(); processor.pipeline.cancel(); if let Some(session) = processor.session_manager.active_mut() { session.restore_pending(); @@ -355,6 +358,7 @@ impl InputWorker { processor.config = *config; } InputWork::Reset => { + processor.feedback.reset(); processor.pipeline.cancel(); processor .session_manager @@ -448,6 +452,8 @@ impl InputProcessor { // 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 { + self.feedback + .publish(&self.config.feedback, false, self.pipeline.is_correcting()); return; } let config = &self.config; @@ -505,9 +511,20 @@ impl InputProcessor { self.session_manager .deactivate(MovementSignal::UnknownPosition); } - if self.pipeline.take_timeout_notice() { - timeout_notice::show(); + if let Some((event, manual)) = self.pipeline.take_feedback() { + self.feedback.event(event, manual, &self.config.feedback); } + if let Some(preview) = self.pipeline.take_suggestion() { + self.feedback.suggestion(preview, &self.config.feedback); + } + self.feedback.publish( + &self.config.feedback, + self.config.correction.enabled + && self.session_manager.active().is_some_and(|session| { + !session.position_uncertain() && !session.executable_context().is_empty() + }), + self.pipeline.is_correcting(), + ); } /// Processes a guarded input batch, captures context, and snapshots correction policies. @@ -521,11 +538,13 @@ impl InputProcessor { for event in events { match event { InputEvent::FocusChange => { + self.feedback.reset(); gate_result = None; self.session_manager .input(typing::TypedInput::Uncertain(MovementSignal::FocusChange)); } InputEvent::MouseClick => { + self.feedback.reset(); gate_result = None; self.session_manager .input(typing::TypedInput::Uncertain(MovementSignal::MouseClick)); @@ -573,12 +592,14 @@ impl InputProcessor { } match decision { SecurityDecision::Allowed { target } if target.window_handle == window => { + self.feedback.blocked(false); needs_capture |= self.session_manager.focus(&target); gate_result = Some((window, true)); needs_capture |= self.track_input(key.translate(), &mut pending_requests); } _ => { + self.feedback.blocked(true); gate_result = Some((window, false)); self.session_manager.deactivate(MovementSignal::FocusChange); } @@ -719,9 +740,18 @@ impl InputProcessor { if stamp.sequence != self.processed_input_sequence { return; } - if let SecurityDecision::Allowed { target } = - SecurityGate::check(TriggerKind::ManualShortcut, &self.config, &self.database) - { + let decision = + SecurityGate::check(TriggerKind::ManualShortcut, &self.config, &self.database); + if let SecurityDecision::Blocked { reason, .. } = decision { + self.feedback.blocked(true); + if feedback::is_app_block(reason) && Self::input_stamp() == stamp { + self.feedback + .event(feedback::Event::Blocked, true, &self.config.feedback); + } + return; + } + self.feedback.blocked(false); + if let SecurityDecision::Allowed { target } = decision { if self.config.shortcuts.correct_arbitrary_selection && !self.session_manager.active_matches(&target) { @@ -753,6 +783,11 @@ impl InputProcessor { context_capture::SelectionCapture::NoSelection ) && session.position_uncertain() { + self.feedback.event( + feedback::Event::Blocked, + true, + &self.config.feedback, + ); return; } if let Some(request) = triggers::manual( @@ -764,9 +799,18 @@ impl InputProcessor { &self.config, ) { self.dispatch_trigger(request, stamp); + } else if Self::input_stamp() == stamp { + self.feedback.event( + feedback::Event::Blocked, + true, + &self.config.feedback, + ); } } } + } else if Self::input_stamp() == stamp { + self.feedback + .event(feedback::Event::Blocked, true, &self.config.feedback); } } } @@ -784,18 +828,34 @@ impl InputProcessor { if stamp.sequence != self.processed_input_sequence { return; } - let SecurityDecision::Allowed { target } = - SecurityGate::check(TriggerKind::Undo, &self.config, &self.database) - else { + let decision = SecurityGate::check(TriggerKind::Undo, &self.config, &self.database); + if let SecurityDecision::Blocked { reason, .. } = decision { + self.feedback.blocked(true); + if feedback::is_app_block(reason) && Self::input_stamp() == stamp { + self.feedback + .event(feedback::Event::Blocked, true, &self.config.feedback); + } return; + } + let SecurityDecision::Allowed { target } = decision else { + unreachable!() }; + self.feedback.blocked(false); if !self.session_manager.active_matches(&target) { + if Self::input_stamp() == stamp { + self.feedback + .event(feedback::Event::Blocked, true, &self.config.feedback); + } return; } let Some(session) = self.session_manager.active() else { return; }; let Some(undo) = session.undo_target() else { + if Self::input_stamp() == stamp { + self.feedback + .event(feedback::Event::Blocked, true, &self.config.feedback); + } return; }; let known = format!( @@ -808,6 +868,10 @@ impl InputProcessor { &self.config.context, known.chars().count(), ) else { + if Self::input_stamp() == stamp { + self.feedback + .event(feedback::Event::Blocked, true, &self.config.feedback); + } return; }; if Self::input_stamp() != stamp || !live.ends_with(&known) { @@ -845,6 +909,10 @@ impl InputProcessor { self.session_manager .deactivate(MovementSignal::UnknownPosition); } + if !result.success && Self::input_stamp() == stamp { + self.feedback + .event(feedback::Event::Error, true, &self.config.feedback); + } } /// Commit a successful native undo before learning; lost ownership drops the session. diff --git a/app-core-rust/src/background/pipeline.rs b/app-core-rust/src/background/pipeline.rs index efbe35a..d557782 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::{ + feedback::Event, replacement::ReplacementConfirmation, security::TriggerKind, session::{Session, SessionManager}, @@ -105,6 +106,8 @@ pub(super) struct CorrectionPipeline { active: VecDeque, next_id: u64, timeout_notice: bool, + feedback_event: Option<(Event, bool)>, + suggestion_preview: Option, } impl CorrectionPipeline { @@ -170,6 +173,8 @@ impl CorrectionPipeline { active: VecDeque::new(), next_id: 1, timeout_notice: false, + feedback_event: None, + suggestion_preview: None, }) } @@ -230,7 +235,7 @@ impl CorrectionPipeline { } }, confidence_behavior: request.confidence_behavior.clone(), - suggestion_ui_available: false, + suggestion_ui_available: config.feedback.show_medium_confidence_suggestions, }; let exclusions = match self.database_path.as_deref() { Some(path) => match crate::dictionary::Repository::policy_nowait( @@ -273,6 +278,8 @@ impl CorrectionPipeline { /// Cancel all admitted work and clear queued jobs, completions, and timeout feedback. pub(super) fn cancel(&mut self) { self.timeout_notice = false; + self.feedback_event = None; + self.suggestion_preview = None; for active in self.active.drain(..) { active.cancelled.store(true, Ordering::Release); } @@ -352,10 +359,23 @@ impl CorrectionPipeline { } /// Consume eligible manual timeout feedback exactly once. + #[cfg(test)] pub(super) fn take_timeout_notice(&mut self) -> bool { std::mem::take(&mut self.timeout_notice) } + pub(super) fn take_feedback(&mut self) -> Option<(Event, bool)> { + self.feedback_event.take() + } + + pub(super) fn take_suggestion(&mut self) -> Option { + self.suggestion_preview.take() + } + + pub(super) fn is_correcting(&self) -> bool { + !self.active.is_empty() + } + /// Take once: duplicates and reordered completions cannot reach the mutation owner. pub(super) fn finish>( &mut self, @@ -367,6 +387,8 @@ impl CorrectionPipeline { replace: impl FnOnce(&FocusedTarget, &CorrectionRequest, &CorrectionOutput) -> R, ) -> bool { self.timeout_notice = false; + self.feedback_event = None; + self.suggestion_preview = None; self.invalidate(manager, current_stamp()); let completion = { let (lock, ready) = &*self.mailbox; @@ -391,6 +413,7 @@ impl CorrectionPipeline { // failed or skipped work returns to executable context below. let applied = (|| { let output = completion.output; + let manual = active.request.trigger == TriggerKind::ManualShortcut; let notify_timeout = output.status == EngineStatus::TimedOut && active.show_timeout_notice && active.request.trigger == TriggerKind::ManualShortcut @@ -399,7 +422,16 @@ impl CorrectionPipeline { EngineKind::OpenAiCompatibleApi | EngineKind::CustomApi ); // Silent failures release their slot without another potentially slow UIA call. - if output.status != EngineStatus::Completed && !notify_timeout { + let notify_error = manual && matches!(output.status, EngineStatus::Error(_)); + if output.status != EngineStatus::Completed && !notify_timeout && !notify_error { + self.feedback_event = Some(( + if output.status == EngineStatus::TimedOut { + Event::Timeout + } else { + Event::Error + }, + false, + )); return false; } let Some(target) = check_target(active.request.trigger) else { @@ -422,8 +454,25 @@ impl CorrectionPipeline { } if output.status != EngineStatus::Completed { self.timeout_notice = notify_timeout; + self.feedback_event = Some(( + if notify_timeout { + Event::Timeout + } else { + Event::Error + }, + manual, + )); return false; } + // Generic fallback contains no provider text or document contents. + self.feedback_event = Some(( + if manual { + Event::Error + } else { + Event::Skipped("AutoFix: could not verify the editable range.") + }, + manual, + )); let original = &active.request.executable_context; let no_change_reason = match output.no_change_reason { Some(NoChangeReason::NoCorrectionNeeded) => Some("no_correction_needed"), @@ -432,13 +481,27 @@ impl CorrectionPipeline { }; if output.changes_needed { if target.focused_element_id.is_none() - || output.behavior != ConfidenceBehavior::Silent + || output.behavior == ConfidenceBehavior::DoNothing || output.confidence == ConfidenceTier::Low || output.corrected_executable_text == *original { + self.feedback_event = Some((Event::Skipped("AutoFix: confidence policy requires a suggestion or skips this correction."), manual)); return false; } } else if output.corrected_executable_text != *original || no_change_reason.is_none() { + let reason = match output.no_change_reason { + Some(NoChangeReason::UnsupportedLanguage) => { + "AutoFix: language is not supported by this engine." + } + Some(NoChangeReason::UncertainLanguage) => { + "AutoFix: language policy skipped this correction." + } + Some(NoChangeReason::ConfidenceBelowConfiguredBehavior) => { + "AutoFix: confidence policy skipped this correction." + } + _ => "AutoFix: correction was skipped.", + }; + self.feedback_event = Some((Event::Skipped(reason), manual)); return false; } if let Some(id) = segment_id { @@ -475,6 +538,16 @@ impl CorrectionPipeline { { return false; } + if output.behavior == ConfidenceBehavior::Suggestion { + // A preview never authorizes replacement or commits executable context. + self.feedback_event = None; + if manual && output.confidence == ConfidenceTier::Medium { + self.suggestion_preview = Some(super::feedback::suggestion_preview( + &output.corrected_executable_text, + )); + } + return false; + } let confirmation = if output.changes_needed { if !session.can_complete_correction( segment_id, @@ -508,6 +581,7 @@ impl CorrectionPipeline { true }; if completed && changed { + self.feedback_event = Some((Event::Applied, manual)); session.record_undo_metadata( active.request.language_info.primary_language.clone(), active.request.trigger, @@ -515,6 +589,14 @@ impl CorrectionPipeline { confirmation.unwrap(), ); } else if completed { + self.feedback_event = Some(( + Event::Skipped(if no_change_reason == Some("all_candidates_protected") { + "AutoFix: matching terms are protected." + } else { + "AutoFix: no correction needed." + }), + manual, + )); self.log_no_change_commit( &active.request, &active.target, diff --git a/app-core-rust/src/background/pipeline/tests.rs b/app-core-rust/src/background/pipeline/tests.rs index 1cfe5a3..6d9de00 100644 --- a/app-core-rust/src/background/pipeline/tests.rs +++ b/app-core-rust/src/background/pipeline/tests.rs @@ -1068,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 { + feedback: crate::background::feedback::Feedback::default(), learner: crate::dictionary::Learner::default(), pipeline, processed_input_sequence: crate::background::input_listener::current_input_sequence() @@ -1301,6 +1302,8 @@ fn valid_result_replaces_once_then_records_commit_and_undo() { true )); assert_eq!(calls.get(), 1); + assert_eq!(pipeline.take_feedback(), Some((Event::Applied, true))); + assert_eq!(pipeline.take_feedback(), None); assert_eq!(manager.active().unwrap().informative_context(), "the"); assert_eq!(manager.active().unwrap().editable_context(), ""); assert!(!finish( @@ -1318,6 +1321,164 @@ fn valid_result_replaces_once_then_records_commit_and_undo() { assert_eq!(manager.active().unwrap().informative_context(), "teh"); } +#[test] +fn manual_failure_feedback_is_validated_and_contains_no_provider_text() { + for unsafe_target in [false, true] { + let config = AppConfig::default(); + let mut manager = manager(&config, "teh"); + let mut pipeline = CorrectionPipeline::start(|job| { + CorrectionOutput::failed( + job.input.executable_context.clone(), + crate::correction::EngineFailure { + kind: crate::correction::EngineFailureKind::Internal, + message: "secret provider document text".into(), + retryable: false, + }, + 0, + ) + }) + .unwrap(); + submit(&mut pipeline, &manager, &config); + wait_completion(&pipeline); + assert!(!pipeline.finish( + &mut manager, + &config.context, + || STAMP, + |_| { + let mut target = target(); + target.is_password_or_protected = unsafe_target; + Some(target) + }, + |_, _| panic!("failure must not read document text"), + |_, _, _| -> bool { panic!("failure must not mutate") } + )); + assert_eq!( + pipeline.take_feedback(), + if unsafe_target { + None + } else { + Some((Event::Error, true)) + } + ); + assert_eq!(manager.active().unwrap().editable_context(), "teh"); + } +} + +#[test] +fn medium_previews_are_manual_opt_in_and_never_mutate_or_commit() { + for enabled in [false, true] { + for automatic in [false, true] { + let mut config = AppConfig::default(); + config.feedback.show_medium_confidence_suggestions = enabled; + let mut manager = manager(&config, "teh"); + let mut pipeline = CorrectionPipeline::start(|job| { + let behavior = job.input.confidence_behavior.behavior_for( + ConfidenceTier::Medium, + job.input.trigger_type, + job.input.suggestion_ui_available, + ); + if behavior == ConfidenceBehavior::Suggestion { + CorrectionOutput { + corrected_executable_text: "the".into(), + changes_needed: true, + confidence: ConfidenceTier::Medium, + behavior, + changes: None, + no_change_reason: None, + engine_latency_ms: 0, + status: EngineStatus::Completed, + } + } else { + CorrectionOutput::unchanged( + job.input.executable_context.clone(), + ConfidenceTier::Medium, + NoChangeReason::ConfidenceBelowConfiguredBehavior, + 0, + ) + } + }) + .unwrap(); + if automatic { + submit_frozen(&mut pipeline, &mut manager, &config); + } else { + submit(&mut pipeline, &manager, &config); + } + wait_completion(&pipeline); + let calls = Cell::new(0); + assert!(!finish( + &mut pipeline, + &mut manager, + &config, + STAMP, + &calls, + true + )); + assert_eq!(calls.get(), 0); + assert_eq!( + pipeline.take_suggestion(), + if enabled && !automatic { + Some("AutoFix suggestion: the".into()) + } else { + None + } + ); + assert_eq!(pipeline.take_suggestion(), None); + assert_eq!(manager.active().unwrap().editable_context(), "teh"); + assert!(manager.active().unwrap().informative_context().is_empty()); + assert!(manager.active().unwrap().undo_target().is_none()); + } + } +} + +#[test] +fn unsafe_or_stale_suggestions_cannot_surface_a_preview() { + for failure in 0..5 { + let mut config = AppConfig::default(); + config.feedback.show_medium_confidence_suggestions = true; + let mut manager = manager(&config, "teh"); + let mut pipeline = CorrectionPipeline::new().unwrap(); + submit(&mut pipeline, &manager, &config); + wait_completion(&pipeline); + { + let mut state = pipeline.mailbox.0.lock().unwrap(); + let output = &mut state.completion.as_mut().unwrap().output; + output.confidence = ConfidenceTier::Medium; + output.behavior = ConfidenceBehavior::Suggestion; + } + if failure == 0 { + pipeline.cancel(); + } + if failure == 1 { + manager.input(TypedInput::Text(" new".into())); + } + let stamp = Cell::new(STAMP); + assert!(!pipeline.finish( + &mut manager, + &config.context, + || stamp.get(), + |_| { + let mut t = target(); + t.is_password_or_protected = failure == 2; + Some(t) + }, + |_, _| { + if failure == 3 { + return None; + } + if failure == 4 { + stamp.set(InputStamp { + sequence: STAMP.sequence + 1, + ..STAMP + }); + } + Some("teh".into()) + }, + |_, _, _| -> bool { panic!("suggestion must never mutate") } + )); + assert_eq!(pipeline.take_suggestion(), None); + } +} + /// Invalidated snapshots cannot cross context, caret, or session boundaries. #[test] fn changed_context_movement_commit_and_recreated_session_discard_results() { diff --git a/app-core-rust/src/background/tests.rs b/app-core-rust/src/background/tests.rs index c3eb8c9..a74fc31 100644 --- a/app-core-rust/src/background/tests.rs +++ b/app-core-rust/src/background/tests.rs @@ -19,6 +19,7 @@ fn undo_learning_requires_committed_bookkeeping_and_stable_input() { config.learning.mode = crate::settings::LearningMode::Automatic; config.learning.rule = crate::settings::LearningRule::Dictionary; let mut processor = super::InputProcessor { + feedback: super::feedback::Feedback::default(), learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: 12, @@ -88,6 +89,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 { + feedback: super::feedback::Feedback::default(), learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: 12, @@ -154,6 +156,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 { + feedback: super::feedback::Feedback::default(), learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: 12, @@ -303,6 +306,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 { + feedback: super::feedback::Feedback::default(), learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: super::input_listener::current_input_sequence(), @@ -339,6 +343,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 { + feedback: super::feedback::Feedback::default(), learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: super::input_listener::current_input_sequence(), @@ -396,6 +401,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 { + feedback: super::feedback::Feedback::default(), learner: crate::dictionary::Learner::default(), pipeline: super::CorrectionPipeline::new().unwrap(), processed_input_sequence: super::input_listener::current_input_sequence(), diff --git a/app-core-rust/src/background/timeout_notice.rs b/app-core-rust/src/background/timeout_notice.rs deleted file mode 100644 index e74c851..0000000 --- a/app-core-rust/src/background/timeout_notice.rs +++ /dev/null @@ -1,146 +0,0 @@ -//! Brief manual timeout feedback, independent of the input processor and typing. - -use std::sync::atomic::{AtomicBool, Ordering}; - -static VISIBLE: AtomicBool = AtomicBool::new(false); - -/// Provide platform timeout feedback without taking focus; unsupported platforms stay silent. -pub(super) fn show() { - if VISIBLE.swap(true, Ordering::AcqRel) { - return; - } - if let Err(error) = std::thread::Builder::new() - .name("autofix-timeout-notice".into()) - .spawn(|| { - native::show(); - VISIBLE.store(false, Ordering::Release); - }) - { - VISIBLE.store(false, Ordering::Release); - tracing::warn!(%error, "cannot show timeout notice"); - } -} - -#[cfg(windows)] -mod native { - use std::ptr::{null, null_mut}; - use windows_sys::Win32::{ - Foundation::RECT, - UI::WindowsAndMessaging::{ - CreateWindowExW, DestroyWindow, DispatchMessageW, GetMessageW, KillTimer, SetTimer, - ShowWindow, SystemParametersInfoW, TranslateMessage, MSG, SPI_GETWORKAREA, - SW_SHOWNOACTIVATE, WM_TIMER, WS_BORDER, WS_DISABLED, WS_EX_NOACTIVATE, - WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP, - }, - }; - - const SS_CENTER: u32 = 0x1; - const SS_CENTERIMAGE: u32 = 0x200; - - /// Provide platform timeout feedback without taking focus; unsupported platforms stay silent. - pub(super) fn show() { - let class: Vec = "STATIC\0".encode_utf16().collect(); - let text: Vec = "AutoFix: API correction timed out.\0" - .encode_utf16() - .collect(); - unsafe { - let mut area: RECT = std::mem::zeroed(); - if SystemParametersInfoW(SPI_GETWORKAREA, 0, (&mut area as *mut RECT).cast(), 0) == 0 { - tracing::warn!("cannot locate work area for timeout notice"); - return; - } - // Disabled, no-activate tool window: no focus, taskbar entry or input capture. - // SS_CENTER | SS_CENTERIMAGE centers the single-line static label. - let window = CreateWindowExW( - WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST, - class.as_ptr(), - text.as_ptr(), - WS_POPUP | WS_BORDER | WS_DISABLED | SS_CENTER | SS_CENTERIMAGE, - area.right - 356, - area.bottom - 64, - 340, - 48, - null_mut(), - null_mut(), - null_mut(), - null(), - ); - if window.is_null() { - tracing::warn!("cannot create timeout notice"); - return; - } - let timer = SetTimer(window, 1, 2_500, None); - if timer == 0 { - DestroyWindow(window); - tracing::warn!("cannot schedule timeout notice dismissal"); - return; - } - ShowWindow(window, SW_SHOWNOACTIVATE); - let mut message: MSG = std::mem::zeroed(); - while GetMessageW(&mut message, null_mut(), 0, 0) > 0 { - if message.message == WM_TIMER && message.hwnd == window && message.wParam == timer - { - break; - } - TranslateMessage(&message); - DispatchMessageW(&message); - } - KillTimer(window, timer); - DestroyWindow(window); - } - } -} - -#[cfg(all(test, windows))] -mod tests { - use super::*; - use std::{ - ptr::null, - thread, - time::{Duration, Instant}, - }; - use windows_sys::Win32::UI::WindowsAndMessaging::{ - FindWindowW, GetForegroundWindow, GetWindowLongW, IsWindowVisible, GWL_EXSTYLE, GWL_STYLE, - WS_DISABLED, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, - }; - - /// The native notice preserves foreground focus, coalesces duplicates, and dismisses itself. - #[test] - #[ignore = "requires an interactive Windows desktop; briefly displays the timeout notice"] - fn native_timeout_notice_preserves_focus_and_dismisses_itself() { - let title: Vec = "AutoFix: API correction timed out.\0" - .encode_utf16() - .collect(); - let original = unsafe { GetForegroundWindow() }; - show(); - let started = Instant::now(); - let window = loop { - let window = unsafe { FindWindowW(null(), title.as_ptr()) }; - if !window.is_null() && unsafe { IsWindowVisible(window) } != 0 { - break window; - } - assert!(started.elapsed() < Duration::from_secs(2)); - thread::sleep(Duration::from_millis(10)); - }; - unsafe { - assert_eq!(GetForegroundWindow(), original); - assert_ne!(GetWindowLongW(window, GWL_STYLE) as u32 & WS_DISABLED, 0); - let style = GetWindowLongW(window, GWL_EXSTYLE) as u32; - assert_ne!(style & WS_EX_NOACTIVATE, 0); - assert_ne!(style & WS_EX_TOOLWINDOW, 0); - } - // Repeated feedback coalesces into this same notice. - show(); - while unsafe { !FindWindowW(null(), title.as_ptr()).is_null() } { - assert!(started.elapsed() < Duration::from_secs(4)); - thread::sleep(Duration::from_millis(20)); - } - assert!(started.elapsed() >= Duration::from_secs(2)); - } -} - -#[cfg(not(windows))] -mod native { - /// Provide platform timeout feedback without taking focus; unsupported platforms stay silent. - pub(super) fn show() {} -} diff --git a/app-core-rust/src/ipc/protocol.rs b/app-core-rust/src/ipc/protocol.rs index 9d60264..2b40dfd 100644 --- a/app-core-rust/src/ipc/protocol.rs +++ b/app-core-rust/src/ipc/protocol.rs @@ -80,6 +80,8 @@ pub(crate) struct AppStatusResponse { pub(crate) running: bool, pub(crate) correction_mode: IpcCorrectionMode, pub(crate) engine: IpcCorrectionEngine, + pub(crate) tray_state: String, + pub(crate) tray_state_enabled: bool, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] diff --git a/app-core-rust/src/ipc/state.rs b/app-core-rust/src/ipc/state.rs index f6b0921..8abaed0 100644 --- a/app-core-rust/src/ipc/state.rs +++ b/app-core-rust/src/ipc/state.rs @@ -142,6 +142,8 @@ impl IpcServerState { running: true, correction_mode: self.config.correction.mode.into(), engine: self.config.correction.engine.clone().into(), + tray_state: crate::background::feedback::tray_state().into(), + tray_state_enabled: self.config.feedback.tray_state_enabled, } } diff --git a/app-core-rust/src/ipc/tests.rs b/app-core-rust/src/ipc/tests.rs index a74bbc1..da1b08a 100644 --- a/app-core-rust/src/ipc/tests.rs +++ b/app-core-rust/src/ipc/tests.rs @@ -33,11 +33,44 @@ fn reports_basic_app_status() { assert!(status.running); assert_eq!(status.correction_mode, CorrectionMode::TyposOnly.into()); assert_eq!(status.engine, CorrectionEngine::Local.into()); + assert!(["idle", "active", "correcting", "blocked", "error"] + .contains(&status.tray_state.as_str())); } other => panic!("unexpected response: {other:?}"), } } +#[test] +fn feedback_options_can_be_updated_through_ipc() { + let fixture = IpcFixture::start(); + for (path, value) in [ + ("feedback.show_near_caret_overlay", true), + ("feedback.show_correction_applied_notification", true), + ("feedback.show_skipped_reason", true), + ("feedback.show_medium_confidence_suggestions", true), + ("feedback.show_blocked_app_notice", false), + ("feedback.show_timeout_notice", false), + ("feedback.tray_state_enabled", false), + ] { + let response = send_request( + &fixture.pipe_path, + &IpcRequest::UpdateSetting(UpdateSettingRequest { + path: path.into(), + value: json!(value), + }), + ) + .unwrap(); + assert!(matches!(response, IpcResponse::SettingUpdated(_))); + let config = + serde_json::to_value(crate::settings::load_config(&fixture.config_path).unwrap()) + .unwrap(); + assert_eq!( + config["feedback"][path.strip_prefix("feedback.").unwrap()], + json!(value) + ); + } +} + #[test] fn updates_correction_engine_setting_and_persists_config() { let fixture = IpcFixture::start(); diff --git a/app-core-rust/src/settings/mod.rs b/app-core-rust/src/settings/mod.rs index 9af501c..ec41343 100644 --- a/app-core-rust/src/settings/mod.rs +++ b/app-core-rust/src/settings/mod.rs @@ -7,8 +7,8 @@ mod validation; pub(crate) use crate::correction::CorrectionMode; pub(crate) use model::{ - AppConfig, ContextConfig, CorrectionEngine, LearningConfig, LearningMode, LearningRule, - PendingQueueFullBehavior, RunMode, + AppConfig, ContextConfig, CorrectionEngine, FeedbackConfig, 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 85ce079..222241e 100644 --- a/app-core-rust/src/settings/model.rs +++ b/app-core-rust/src/settings/model.rs @@ -292,6 +292,7 @@ impl From<&ApiConfig> for crate::correction::ApiEngineConfig { } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(default)] pub(crate) struct FeedbackConfig { pub(crate) tray_state_enabled: bool, pub(crate) show_correction_applied_notification: bool, @@ -299,6 +300,7 @@ pub(crate) struct FeedbackConfig { pub(crate) show_medium_confidence_suggestions: bool, pub(crate) show_blocked_app_notice: bool, pub(crate) show_timeout_notice: bool, + pub(crate) show_near_caret_overlay: bool, } impl Default for FeedbackConfig { @@ -306,10 +308,11 @@ impl Default for FeedbackConfig { Self { tray_state_enabled: true, show_correction_applied_notification: false, - show_skipped_reason: true, - show_medium_confidence_suggestions: true, + show_skipped_reason: false, + show_medium_confidence_suggestions: false, show_blocked_app_notice: true, show_timeout_notice: true, + show_near_caret_overlay: false, } } } diff --git a/app-core-rust/src/settings/tests.rs b/app-core-rust/src/settings/tests.rs index 448f469..0fe7114 100644 --- a/app-core-rust/src/settings/tests.rs +++ b/app-core-rust/src/settings/tests.rs @@ -251,6 +251,11 @@ fn pending_queue_settings_round_trip_and_legacy_configs_get_safe_defaults() { fn confidence_preferences_round_trip_and_feedback_only_disables_suggestions() { let mut config = AppConfig::default(); let defaults = crate::correction::ConfidenceBehaviorSettings::default(); + assert_eq!( + config.confidence_behavior().medium, + ConfidenceBehavior::DoNothing + ); + config.feedback.show_medium_confidence_suggestions = true; assert_eq!(config.confidence_behavior(), defaults); config.feedback.show_medium_confidence_suggestions = false; assert_eq!( @@ -275,6 +280,39 @@ fn confidence_preferences_round_trip_and_feedback_only_disables_suggestions() { ); } +#[test] +fn feedback_defaults_legacy_load_and_options_round_trip() { + let mut config = AppConfig::default(); + assert!(config.feedback.tray_state_enabled); + assert!(!config.feedback.show_correction_applied_notification); + assert!(!config.feedback.show_skipped_reason); + assert!(!config.feedback.show_medium_confidence_suggestions); + assert!(config.feedback.show_blocked_app_notice); + assert!(config.feedback.show_timeout_notice); + assert!(!config.feedback.show_near_caret_overlay); + let legacy = config_to_toml(&config) + .unwrap() + .lines() + .filter(|line| !line.starts_with("show_near_caret_overlay")) + .collect::>() + .join("\n"); + assert_eq!(super::toml_io::parse_config(&legacy).unwrap(), config); + config.feedback.tray_state_enabled = false; + config.feedback.show_correction_applied_notification = true; + config.feedback.show_skipped_reason = true; + config.feedback.show_medium_confidence_suggestions = true; + config.feedback.show_blocked_app_notice = false; + config.feedback.show_timeout_notice = false; + config.feedback.show_near_caret_overlay = true; + let encoded = config_to_toml(&config).unwrap(); + assert_eq!(super::toml_io::parse_config(&encoded).unwrap(), config); + let minimal = encoded.replace(&toml::to_string_pretty(&config.feedback).unwrap(), ""); + assert_eq!( + super::toml_io::parse_config(&minimal).unwrap().feedback, + super::model::FeedbackConfig::default() + ); +} + #[test] fn generated_toml_has_comments_and_no_api_key_field() { let output = config_to_toml(&AppConfig::default()).unwrap(); diff --git a/shared-schema/README.md b/shared-schema/README.md index 85f4935..4efeb2c 100644 --- a/shared-schema/README.md +++ b/shared-schema/README.md @@ -60,6 +60,20 @@ Both attempts share the trigger's total timeout budget. `feedback.show_timeout_notice` defaults to true and applies only to a valid manual API timeout; automatic timeouts always stay silent. +Feedback defaults to tray states and small manual error/blocked/timeout notices. +`show_correction_applied_notification`, `show_skipped_reason`, +`show_medium_confidence_suggestions` and `show_near_caret_overlay` default false; +`tray_state_enabled`, `show_blocked_app_notice` and `show_timeout_notice` default +true. Missing feedback fields use these defaults; explicit saved values survive. +Medium suggestions are read-only previews of validated executable text, never +authorization to mutate. Near-caret placement does not enable any notice. +`app_status` and `config_reloaded` include a text-free `tray_state` with one of +`idle`, `active`, `correcting`, `blocked`, or `error`. Disabling state publishes +idle while keeping the tray accessible. +The status also carries `tray_state_enabled` so the shell can preserve that +preference when the engine becomes unavailable. Hard secure-field/desktop refusals, +cancelled and stale results cannot display a notice or suggestion preview. + Unavailable application rules deny authorization for typed capture and every correction trigger, including API execution. An empty successfully read rule list is distinct from a failed read. diff --git a/shared-schema/ipc.schema.json b/shared-schema/ipc.schema.json index 004a1f2..af7925d 100644 --- a/shared-schema/ipc.schema.json +++ b/shared-schema/ipc.schema.json @@ -16,6 +16,21 @@ "type": "string", "enum": ["local", "api"] }, + "trayState": { + "type": "string", + "enum": ["idle", "active", "correcting", "blocked", "error"] + }, + "appStatus": { + "type": "object", + "required": ["running", "correction_mode", "engine", "tray_state", "tray_state_enabled"], + "properties": { + "running": { "type": "boolean" }, + "correction_mode": { "$ref": "#/$defs/correctionMode" }, + "engine": { "$ref": "#/$defs/correctionEngine" }, + "tray_state": { "$ref": "#/$defs/trayState" }, + "tray_state_enabled": { "type": "boolean" } + } + }, "request": { "type": "object", "required": ["type"], @@ -79,7 +94,11 @@ ] }, "payload": { "type": "object" } - } + }, + "allOf": [{ + "if": { "properties": { "type": { "enum": ["app_status", "config_reloaded"] } } }, + "then": { "properties": { "payload": { "$ref": "#/$defs/appStatus" } } } + }] } } } diff --git a/ui/settings-ui-tests/ConfigFormMapperTests.cs b/ui/settings-ui-tests/ConfigFormMapperTests.cs index b8d0961..ae099fb 100644 --- a/ui/settings-ui-tests/ConfigFormMapperTests.cs +++ b/ui/settings-ui-tests/ConfigFormMapperTests.cs @@ -6,6 +6,27 @@ namespace AutoFix.SettingsUi.Tests; [TestClass] public sealed class ConfigFormMapperTests { + [TestMethod] + public void FeedbackHasQuietDefaultsAndEveryOptionSurvivesFormAndStorage() + { + using var fixture = TempConfigFixture.Create(); + var sections = SettingsSkeleton.CreateSections(); + foreach (var option in new[] { "tray_state_enabled", "show_correction_applied_notification", "show_skipped_reason", "show_medium_confidence_suggestions", "show_blocked_app_notice", "show_timeout_notice", "show_near_caret_overlay" }) + { + var card = Card(sections, $"feedback.{option}"); + Assert.AreEqual(option is "tray_state_enabled" or "show_blocked_app_notice" or "show_timeout_notice", card.IsEnabled); + card.IsEnabled = !card.IsEnabled; + } + var config = ConfigFormMapper.BuildConfig(sections); + fixture.Storage.Save(config); + var loaded = fixture.Storage.Load(fixture.Path); + var reloaded = SettingsSkeleton.CreateSections(loaded); + foreach (var card in sections.Single(section => section.Name == "Feedback").Settings) + Assert.AreEqual(card.IsEnabled, Card(reloaded, card.Path).IsEnabled, card.Path); + File.WriteAllLines(fixture.Path, File.ReadAllLines(fixture.Path).Where(line => !line.StartsWith("show_near_caret_overlay", StringComparison.Ordinal))); + Assert.IsFalse(fixture.Storage.Load(fixture.Path).Feedback.ShowNearCaretOverlay); + } + [TestMethod] public void UndoShortcutAndHistorySurviveFormStorageAndLegacyLoad() { diff --git a/ui/settings-ui-tests/MainWindowViewModelTests.cs b/ui/settings-ui-tests/MainWindowViewModelTests.cs index eae41bd..840fa19 100644 --- a/ui/settings-ui-tests/MainWindowViewModelTests.cs +++ b/ui/settings-ui-tests/MainWindowViewModelTests.cs @@ -7,6 +7,56 @@ namespace AutoFix.SettingsUi.Tests; [TestClass] public sealed class MainWindowViewModelTests { + [TestMethod] + public void FeedbackWindowRendersQuietDefaultsAndSavesChangedToggle() + { + 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 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.Name == "Feedback"); + Pump(); + var boxes = Descendants(window).OfType() + .Where(box => box.DataContext is SettingCardViewModel).ToArray(); + Assert.AreEqual(7, boxes.Length); + foreach (var box in boxes) + { + var card = (SettingCardViewModel)box.DataContext; + Assert.AreEqual(card.Path is "feedback.tray_state_enabled" or "feedback.show_blocked_app_notice" or "feedback.show_timeout_notice", box.IsChecked); + } + var preview = Environment.GetEnvironmentVariable("AUTOFIX_FEEDBACK_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); + } + boxes.Single(box => ((SettingCardViewModel)box.DataContext).Path == "feedback.show_near_caret_overlay") + .SetCurrentValue(System.Windows.Controls.Primitives.ToggleButton.IsCheckedProperty, true); + Pump(); + Assert.IsTrue(fixture.Storage.Load(fixture.Path).Feedback.ShowNearCaretOverlay); + } + catch (Exception error) { failure = error; } + finally { window?.Close(); } + }) { IsBackground = true }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + Assert.IsTrue(thread.Join(TimeSpan.FromSeconds(15)), "WPF feedback flow timed out."); + if (failure is not null) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(failure).Throw(); + } + [TestMethod] public void DictionaryWindowEditsScopedPairsAndPreservesInvalidEdits() { diff --git a/ui/settings-ui-tests/TrayFeedbackTests.cs b/ui/settings-ui-tests/TrayFeedbackTests.cs new file mode 100644 index 0000000..bd2d961 --- /dev/null +++ b/ui/settings-ui-tests/TrayFeedbackTests.cs @@ -0,0 +1,56 @@ +using AutoFix.SettingsUi.Ipc; +using AutoFix.SettingsUi.Lifetime; +using System.Text.Json; + +namespace AutoFix.SettingsUi.Tests; + +[TestClass] +public sealed class TrayFeedbackTests +{ + [TestMethod] + public void TrayRemainsAvailableInEveryStateAndDisposesCleanly() + { + Exception? failure = null; + var thread = new Thread(() => + { + try + { + using var tray = new ShellTray(() => { }, () => { }); + foreach (var state in new[] { "idle", "active", "correcting", "blocked", "error", "idle" }) + { + tray.SetState(state); + Assert.IsTrue(tray.IsVisible); + Assert.AreEqual($"AutoFix — {state}", tray.StatusText); + } + tray.UpdateStatus(new AppStatusResponse(true, "typos_only", "local", "correcting", false)); + tray.UpdateStatus(null); + Assert.IsTrue(tray.IsVisible); + Assert.AreEqual("AutoFix — idle", tray.StatusText); + tray.Dispose(); + tray.SetState("error"); + Assert.IsFalse(tray.IsVisible); + } + catch (Exception error) { failure = error; } + }); + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + Assert.IsTrue(thread.Join(TimeSpan.FromSeconds(5)), "Tray verification timed out."); + if (failure is not null) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(failure).Throw(); + } + + [TestMethod] + public void StatusSupportsEveryStateAndLegacyPayloads() + { + foreach (var state in new[] { "idle", "active", "correcting", "blocked", "error" }) + { + var payload = JsonSerializer.SerializeToElement(new { running = true, correction_mode = "typos_only", engine = "local", tray_state = state }); + var result = new IpcEnvelope("app_status", payload).ReadPayload("app_status"); + Assert.AreEqual(state, result.Value!.TrayState); + Assert.AreEqual(state, ShellTray.NormalizeState(result.Value.TrayState)); + } + var legacy = JsonSerializer.SerializeToElement(new { running = true, correction_mode = "typos_only", engine = "local" }); + Assert.AreEqual("idle", new IpcEnvelope("app_status", legacy).ReadPayload("app_status").Value!.TrayState); + Assert.IsTrue(new IpcEnvelope("app_status", legacy).ReadPayload("app_status").Value!.TrayStateEnabled); + Assert.AreEqual("idle", ShellTray.NormalizeState("unknown")); + } +} diff --git a/ui/settings-ui/Ipc/IpcProtocol.cs b/ui/settings-ui/Ipc/IpcProtocol.cs index 2aae30b..d4ef9cf 100644 --- a/ui/settings-ui/Ipc/IpcProtocol.cs +++ b/ui/settings-ui/Ipc/IpcProtocol.cs @@ -10,7 +10,9 @@ public sealed record IpcEnvelope( public sealed record AppStatusResponse( [property: JsonPropertyName("running")] bool Running, [property: JsonPropertyName("correction_mode")] string CorrectionMode, - [property: JsonPropertyName("engine")] string Engine); + [property: JsonPropertyName("engine")] string Engine, + [property: JsonPropertyName("tray_state")] string TrayState = "idle", + [property: JsonPropertyName("tray_state_enabled")] bool TrayStateEnabled = true); public sealed record CorrectionModeResponse( [property: JsonPropertyName("mode")] string Mode); diff --git a/ui/settings-ui/Lifetime/ShellLifetime.cs b/ui/settings-ui/Lifetime/ShellLifetime.cs index faea8ad..47e9cc9 100644 --- a/ui/settings-ui/Lifetime/ShellLifetime.cs +++ b/ui/settings-ui/Lifetime/ShellLifetime.cs @@ -58,7 +58,12 @@ public void Start(Window shellWindow) { tray = new ShellTray(ShowShell, () => Shutdown(ShutdownReason.UserExit)); singleInstance.StartListening(); - engineSupervisor.Start(); + try { engineSupervisor.Start(); } + catch (Exception error) when (error is System.IO.IOException or InvalidOperationException or Win32Exception) + { + Debug.WriteLine(error); + tray.SetState("error"); + } shellWindow.Show(); } catch (Exception error) @@ -114,7 +119,8 @@ private void EngineExitClassified(object? sender, EngineExitClassification class return; } - application.Dispatcher.Invoke(() => Shutdown(ShutdownReason.ShellClosing)); + // Keep settings and Exit available even when the engine cannot restart. + application.Dispatcher.Invoke(() => tray?.SetState("error")); } public void Dispose() diff --git a/ui/settings-ui/Lifetime/ShellTray.cs b/ui/settings-ui/Lifetime/ShellTray.cs index 636b4e8..029356b 100644 --- a/ui/settings-ui/Lifetime/ShellTray.cs +++ b/ui/settings-ui/Lifetime/ShellTray.cs @@ -1,4 +1,6 @@ -using System.Windows; +using System.Drawing; +using System.Runtime.InteropServices; +using AutoFix.SettingsUi.Ipc; using Forms = System.Windows.Forms; namespace AutoFix.SettingsUi.Lifetime; @@ -9,6 +11,11 @@ public sealed class ShellTray : IDisposable private readonly Action showShell; private readonly Action exitShell; private bool disposed; + private readonly Forms.Timer statusTimer; + private readonly BackgroundIpcClient ipc = new(); + private readonly Dictionary icons = new(); + private bool polling; + private bool trayStateEnabled = true; public ShellTray(Action showShell, Action exitShell) { @@ -18,13 +25,78 @@ public ShellTray(Action showShell, Action exitShell) { Text = "AutoFix", Icon = System.Drawing.Icon.ExtractAssociatedIcon(Environment.ProcessPath ?? System.Reflection.Assembly.GetExecutingAssembly().Location) - ?? System.Drawing.SystemIcons.Application, + ?? (Icon)System.Drawing.SystemIcons.Application.Clone(), Visible = true, ContextMenuStrip = BuildMenu(), }; notifyIcon.DoubleClick += (_, _) => this.showShell(); + var originalIcon = notifyIcon.Icon!; + BuildStateIcons(originalIcon); + SetState("idle"); + originalIcon.Dispose(); + statusTimer = new Forms.Timer { Interval = 250 }; + statusTimer.Tick += async (_, _) => await RefreshStateAsync(); + statusTimer.Start(); } + internal static string NormalizeState(string? state) => state is "idle" or "active" or "correcting" or "blocked" or "error" ? state : "idle"; + + internal bool IsVisible => notifyIcon.Visible; + internal string StatusText => notifyIcon.Text; + + internal void SetState(string state) + { + if (disposed) return; + state = trayStateEnabled ? NormalizeState(state) : "idle"; + notifyIcon.Text = $"AutoFix — {state}"; + notifyIcon.Icon = icons[state]; + } + + internal void UpdateStatus(AppStatusResponse? status) + { + if (status is not null) trayStateEnabled = status.TrayStateEnabled; + SetState(status?.TrayState ?? "error"); + } + + private async Task RefreshStateAsync() + { + if (disposed || polling) return; + polling = true; + try + { + var result = await ipc.GetStatusAsync(); + UpdateStatus(result.Value); + } + catch (Exception error) when (error is System.IO.IOException or TimeoutException or OperationCanceledException or System.Text.Json.JsonException) + { + SetState("error"); + } + finally { polling = false; } + } + + private void BuildStateIcons(Icon original) + { + icons["idle"] = (Icon)original.Clone(); + foreach (var (state, color) in new[] { ("active", Color.SeaGreen), ("correcting", Color.DodgerBlue), ("blocked", Color.DarkOrange), ("error", Color.Firebrick) }) + { + using var bitmap = new Bitmap(32, 32); + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.DrawIcon(original, new Rectangle(0, 0, 32, 32)); + using var brush = new SolidBrush(color); + graphics.FillEllipse(Brushes.White, 19, 19, 13, 13); + graphics.FillEllipse(brush, 21, 21, 9, 9); + } + var handle = bitmap.GetHicon(); + try { icons[state] = (Icon)Icon.FromHandle(handle).Clone(); } + finally { DestroyIcon(handle); } + } + } + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool DestroyIcon(IntPtr icon); + private Forms.ContextMenuStrip BuildMenu() { var menu = new Forms.ContextMenuStrip(); @@ -41,7 +113,10 @@ public void Dispose() } disposed = true; + statusTimer.Stop(); + statusTimer.Dispose(); notifyIcon.Visible = false; notifyIcon.Dispose(); + foreach (var icon in icons.Values) icon.Dispose(); } } diff --git a/ui/settings-ui/README.md b/ui/settings-ui/README.md index b38b708..c869f03 100644 --- a/ui/settings-ui/README.md +++ b/ui/settings-ui/README.md @@ -14,6 +14,15 @@ This component owns settings mode: - Communication with the background process. - User-facing configuration for triggers, correction behavior, dictionaries, app rules, privacy, and engine selection. +**Feedback** exposes seven independent switches. Tray states, manual blocked-action +notices and manual API timeout notices default on. Applied notices, skipped reasons, +medium-confidence suggestion previews and near-caret placement default off. Every +switch round-trips through TOML and IPC, including older files without the new +`feedback.show_near_caret_overlay` key. Near-caret placement changes only where an +enabled notice appears. The tray polls metadata-only engine state and changes a +small icon badge and tooltip; it stays available when state is disabled or the +engine cannot restart. Correction feedback never uses modal dialogs or balloons. + The UI should remain a thin product surface over explicit config and IPC contracts from `shared-schema`. Background correction behavior belongs in `app-core-rust`. The **Dictionary** section lists and edits SQLite word/phrase exclusions and @@ -38,9 +47,9 @@ correction requires the API engine. Confidence controls expose high and medium behavior (`silent`, `suggestion`, or `do_nothing`). High defaults to silent apply. Medium defaults to manual -suggestions when suggestion UI is available; automatic triggers do nothing -unless silent apply is selected. V1 has no suggestion UI, so medium suggestions -currently do nothing. Low confidence is fixed to do nothing in a disabled +suggestions when the Feedback preview switch is enabled; automatic triggers do +nothing unless silent apply is selected. Previews are read-only and never accept +or apply edits. Low confidence is fixed to do nothing in a disabled control, and importing other low-confidence behaviors is rejected. Context settings expose the pending correction queue. Capacity defaults to one diff --git a/ui/settings-ui/Settings/AppConfig.cs b/ui/settings-ui/Settings/AppConfig.cs index fc61d5c..303b6ef 100644 --- a/ui/settings-ui/Settings/AppConfig.cs +++ b/ui/settings-ui/Settings/AppConfig.cs @@ -203,16 +203,19 @@ public sealed class FeedbackConfig public bool ShowCorrectionAppliedNotification { get; set; } [JsonPropertyName("show_skipped_reason")] - public bool ShowSkippedReason { get; set; } = true; + public bool ShowSkippedReason { get; set; } [JsonPropertyName("show_medium_confidence_suggestions")] - public bool ShowMediumConfidenceSuggestions { get; set; } = true; + public bool ShowMediumConfidenceSuggestions { get; set; } [JsonPropertyName("show_blocked_app_notice")] public bool ShowBlockedAppNotice { get; set; } = true; [JsonPropertyName("show_timeout_notice")] public bool ShowTimeoutNotice { get; set; } = true; + + [JsonPropertyName("show_near_caret_overlay")] + public bool ShowNearCaretOverlay { get; set; } } public sealed class LoggingConfig diff --git a/ui/settings-ui/Settings/ConfigFormMapper.cs b/ui/settings-ui/Settings/ConfigFormMapper.cs index f2b9768..7d90d1f 100644 --- a/ui/settings-ui/Settings/ConfigFormMapper.cs +++ b/ui/settings-ui/Settings/ConfigFormMapper.cs @@ -119,6 +119,7 @@ private static void ApplyFeedback(AppConfig config, IReadOnlyDictionary values) diff --git a/ui/settings-ui/ViewModels/SettingsSkeleton.cs b/ui/settings-ui/ViewModels/SettingsSkeleton.cs index c89c880..80c6582 100644 --- a/ui/settings-ui/ViewModels/SettingsSkeleton.cs +++ b/ui/settings-ui/ViewModels/SettingsSkeleton.cs @@ -140,12 +140,13 @@ public static ObservableCollection CreateSections(AppC ]), Section("Feedback", "Tray notices and correction feedback", [ - Toggle("Tray state enabled", "Show correction state through tray status.", "feedback.tray_state_enabled", config.Feedback.TrayStateEnabled), + Toggle("Tray state enabled", "Show idle, active, correcting, blocked and error states. The tray icon always remains available.", "feedback.tray_state_enabled", config.Feedback.TrayStateEnabled), Toggle("Applied notification", "Notify after a correction is applied.", "feedback.show_correction_applied_notification", config.Feedback.ShowCorrectionAppliedNotification), Toggle("Show skipped reason", "Explain why a correction did not run.", "feedback.show_skipped_reason", config.Feedback.ShowSkippedReason), - Toggle("Show medium-confidence suggestions", "Allow manual suggestions when suggestion UI is available. This never enables silent apply. Suggestion UI is not available in v1.", "feedback.show_medium_confidence_suggestions", config.Feedback.ShowMediumConfidenceSuggestions), - Toggle("Show blocked-app notice", "Notify when current app is blocked.", "feedback.show_blocked_app_notice", config.Feedback.ShowBlockedAppNotice), + Toggle("Show medium-confidence suggestions", "Show a brief read-only preview for manual medium-confidence suggestions. Never applies the suggestion; acceptance is not available in v1.", "feedback.show_medium_confidence_suggestions", config.Feedback.ShowMediumConfidenceSuggestions), + Toggle("Show blocked-app notice", "Show a small notice when a manual action is blocked by app policy. Automatic triggers stay silent.", "feedback.show_blocked_app_notice", config.Feedback.ShowBlockedAppNotice), Toggle("Show timeout notice", "Show a small notice when a manual API correction times out. Automatic timeouts stay silent.", "feedback.show_timeout_notice", config.Feedback.ShowTimeoutNotice), + Toggle("Show near-caret overlay", "Place enabled notices near the caret when Windows exposes its position; otherwise use the screen corner. Does not enable extra notices.", "feedback.show_near_caret_overlay", config.Feedback.ShowNearCaretOverlay), ]), AppRulesSection(), Section("Logs / Debug", "Diagnostics and troubleshooting", From ea9e0948aa3376cc81fc4ce20164e552d068145c Mon Sep 17 00:00:00 2001 From: Hussein Ba Ragaa Date: Fri, 2 Oct 2026 19:06:34 +0300 Subject: [PATCH 2/6] fix(correction): enforce confidence routing --- app-core-rust/README.md | 10 +- app-core-rust/src/background/feedback.rs | 7 +- .../src/background/feedback/suggestion.rs | 58 +++++++++ app-core-rust/src/background/pipeline.rs | 13 +- .../src/background/pipeline/tests.rs | 112 +++++++++++++++++- app-core-rust/src/background/triggers.rs | 2 +- app-core-rust/src/correction/contract.rs | 3 +- ui/settings-ui/ViewModels/SettingsSkeleton.cs | 2 +- 8 files changed, 197 insertions(+), 10 deletions(-) create mode 100644 app-core-rust/src/background/feedback/suggestion.rs diff --git a/app-core-rust/README.md b/app-core-rust/README.md index c588989..2835018 100644 --- a/app-core-rust/README.md +++ b/app-core-rust/README.md @@ -135,13 +135,17 @@ enable read-only previews with `feedback.show_medium_confidence_suggestions` results can show a bounded preview of executable text; previews never include informative context, mutate text, commit sessions or record undo. New typing, movement, cancellation and secure targets suppress them. Suggestion acceptance -remains planned. Outputs include +remains planned. `src/background/feedback/suggestion` defines the `SuggestionUi` +presentation interface for a future near-caret UI. The existing preview adapter +advertises availability only when enabled on a supported platform. Display never +authorizes replacement or acceptance. Outputs include an explicit `behavior`: only `silent` authorizes replacement; `suggestion` requires user acceptance. Suppressed outputs preserve the original executable text and discard edit details. Local results prioritize silent edits over suggested edits when both occur in one request. The pipeline snapshots confidence -policy and rejects suggestions, suppressed edits, and low-confidence results at -completion before allowing target replacement. +policy and preview capability. At completion it rejects any changed result whose +reported behavior differs from the admitted policy, as well as suppressed edits +and low-confidence results. Only an authorized silent result can reach replacement. The keyboard session tracker is implemented. It keeps up to 4,096 characters typed during the current engine run in memory and exposes only the known text diff --git a/app-core-rust/src/background/feedback.rs b/app-core-rust/src/background/feedback.rs index 9a9acc9..9178bca 100644 --- a/app-core-rust/src/background/feedback.rs +++ b/app-core-rust/src/background/feedback.rs @@ -2,11 +2,13 @@ use super::security::BlockReason; mod notice; +pub(crate) mod suggestion; use crate::settings::FeedbackConfig; use std::{ sync::atomic::{AtomicU8, Ordering}, time::{Duration, Instant}, }; +use suggestion::{PreviewSuggestionUi, SuggestionUi}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum Event { @@ -83,13 +85,14 @@ impl Feedback { /// Opt-in, read-only preview. Text stays in the short-lived notice worker only. pub(super) fn suggestion(&mut self, preview: String, config: &FeedbackConfig) { let now = Instant::now(); - if config.show_medium_confidence_suggestions + let ui = PreviewSuggestionUi::new(config); + if ui.is_available() && self .last_notice .is_none_or(|last| now.duration_since(last) >= Duration::from_millis(2500)) { self.last_notice = Some(now); - notice::show(preview, config.show_near_caret_overlay); + ui.show_preview(preview); } } pub(super) fn reset(&mut self) { diff --git a/app-core-rust/src/background/feedback/suggestion.rs b/app-core-rust/src/background/feedback/suggestion.rs new file mode 100644 index 0000000..e769302 --- /dev/null +++ b/app-core-rust/src/background/feedback/suggestion.rs @@ -0,0 +1,58 @@ +//! Presentation boundary for a future near-caret suggestion UI. +//! V1 supports only opt-in, read-only notices. Acceptance must go through a +//! separate, freshly validated replacement request; display never permits edits. + +use crate::settings::FeedbackConfig; + +pub(crate) trait SuggestionUi { + /// Advertise actual display support, separately from confidence preferences. + fn is_available(&self) -> bool; + /// Display a bounded preview containing only validated executable text. + fn show_preview(&self, preview: String); +} + +/// Adapter for the existing notice; no interactive overlay or acceptance UI. +pub(crate) struct PreviewSuggestionUi<'a> { + config: &'a FeedbackConfig, +} + +impl<'a> PreviewSuggestionUi<'a> { + pub(crate) fn new(config: &'a FeedbackConfig) -> Self { + Self { config } + } +} + +impl SuggestionUi for PreviewSuggestionUi<'_> { + fn is_available(&self) -> bool { + cfg!(windows) && self.config.show_medium_confidence_suggestions + } + + fn show_preview(&self, preview: String) { + if self.is_available() { + super::notice::show(preview, self.config.show_near_caret_overlay); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn availability_requires_opt_in_and_platform_support() { + let mut config = FeedbackConfig::default(); + assert!(!PreviewSuggestionUi::new(&config).is_available()); + config.show_near_caret_overlay = true; + assert!(!PreviewSuggestionUi::new(&config).is_available()); + config.show_medium_confidence_suggestions = true; + assert_eq!( + PreviewSuggestionUi::new(&config).is_available(), + cfg!(windows) + ); + config.show_near_caret_overlay = false; + assert_eq!( + PreviewSuggestionUi::new(&config).is_available(), + cfg!(windows) + ); + } +} diff --git a/app-core-rust/src/background/pipeline.rs b/app-core-rust/src/background/pipeline.rs index d557782..9f4eea9 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::{ + feedback::suggestion::{PreviewSuggestionUi, SuggestionUi}, feedback::Event, replacement::ReplacementConfirmation, security::TriggerKind, @@ -74,6 +75,8 @@ struct ActiveRequest { stamp: InputStamp, cancelled: Arc, show_timeout_notice: bool, + trigger_type: TriggerType, + suggestion_ui_available: bool, } impl ActiveRequest { @@ -235,7 +238,7 @@ impl CorrectionPipeline { } }, confidence_behavior: request.confidence_behavior.clone(), - suggestion_ui_available: config.feedback.show_medium_confidence_suggestions, + suggestion_ui_available: PreviewSuggestionUi::new(&config.feedback).is_available(), }; let exclusions = match self.database_path.as_deref() { Some(path) => match crate::dictionary::Repository::policy_nowait( @@ -259,6 +262,8 @@ impl CorrectionPipeline { stamp, cancelled: Arc::clone(&cancelled), show_timeout_notice: config.feedback.show_timeout_notice, + trigger_type: input.trigger_type, + suggestion_ui_available: input.suggestion_ui_available, }); let (lock, ready) = &*self.mailbox; let mut state = lock.lock().unwrap(); @@ -483,6 +488,12 @@ impl CorrectionPipeline { if target.focused_element_id.is_none() || output.behavior == ConfidenceBehavior::DoNothing || output.confidence == ConfidenceTier::Low + || output.behavior + != active.request.confidence_behavior.behavior_for( + output.confidence, + active.trigger_type, + active.suggestion_ui_available, + ) || output.corrected_executable_text == *original { self.feedback_event = Some((Event::Skipped("AutoFix: confidence policy requires a suggestion or skips this correction."), manual)); diff --git a/app-core-rust/src/background/pipeline/tests.rs b/app-core-rust/src/background/pipeline/tests.rs index 6d9de00..e18bc4b 100644 --- a/app-core-rust/src/background/pipeline/tests.rs +++ b/app-core-rust/src/background/pipeline/tests.rs @@ -1416,7 +1416,7 @@ fn medium_previews_are_manual_opt_in_and_never_mutate_or_commit() { assert_eq!(calls.get(), 0); assert_eq!( pipeline.take_suggestion(), - if enabled && !automatic { + if enabled && !automatic && cfg!(windows) { Some("AutoFix suggestion: the".into()) } else { None @@ -1430,6 +1430,116 @@ fn medium_previews_are_manual_opt_in_and_never_mutate_or_commit() { } } +/// An engine cannot grant itself silent apply or preview permission. +#[test] +fn completion_behavior_must_match_admitted_confidence_policy() { + for configured in [ + ConfidenceBehavior::DoNothing, + ConfidenceBehavior::Suggestion, + ConfidenceBehavior::Silent, + ] { + for enabled in [false, true] { + for trigger in [ + TriggerKind::ManualShortcut, + TriggerKind::WordCount, + TriggerKind::Character, + TriggerKind::FinalFixBeforeReanchor, + ] { + for confidence in [ConfidenceTier::Medium, ConfidenceTier::Low] { + for reported in [ConfidenceBehavior::Silent, ConfidenceBehavior::Suggestion] { + let mut config = AppConfig::default(); + config.correction.medium_confidence_behavior = configured; + config.feedback.show_medium_confidence_suggestions = enabled; + let mut manager = manager(&config, "teh"); + let mut pipeline = CorrectionPipeline::start(move |_| { + let mut output = + CorrectionOutput::changed("the".into(), confidence, None, 0); + output.behavior = reported; + output + }) + .unwrap(); + let mut request = request(&manager, &config); + request.trigger = trigger; + assert!(pipeline.submit( + request, + manager.active().unwrap(), + target(), + STAMP, + &config, + vec![], + )); + wait_completion(&pipeline); + let calls = Cell::new(0); + let silent = confidence == ConfidenceTier::Medium + && configured == ConfidenceBehavior::Silent + && reported == ConfidenceBehavior::Silent; + let preview = confidence == ConfidenceTier::Medium + && configured == ConfidenceBehavior::Suggestion + && reported == ConfidenceBehavior::Suggestion + && enabled + && cfg!(windows) + && trigger == TriggerKind::ManualShortcut; + assert_eq!( + finish(&mut pipeline, &mut manager, &config, STAMP, &calls, true,), + silent, + "{configured:?}, {trigger:?}, {confidence:?}, {reported:?}" + ); + assert_eq!(calls.get(), usize::from(silent)); + assert_eq!(pipeline.take_suggestion().is_some(), preview); + let session = manager.active().unwrap(); + assert_eq!(session.undo_target().is_some(), silent); + if !silent { + assert_eq!(session.editable_context(), "teh"); + assert!(session.informative_context().is_empty()); + } + } + } + } + } + } +} + +/// Real local medium corrections use the saved policy for manual and frozen work. +#[test] +fn medium_local_results_skip_preview_or_apply_without_losing_typed_text() { + for configured in [ + ConfidenceBehavior::DoNothing, + ConfidenceBehavior::Suggestion, + ConfidenceBehavior::Silent, + ] { + for automatic in [false, true] { + let mut config = AppConfig::default(); + config.correction.medium_confidence_behavior = configured; + let mut manager = manager(&config, "accomodate"); + let mut pipeline = CorrectionPipeline::new().unwrap(); + if automatic { + submit_frozen(&mut pipeline, &mut manager, &config); + } else { + submit(&mut pipeline, &manager, &config); + } + wait_completion(&pipeline); + let calls = Cell::new(0); + let silent = configured == ConfidenceBehavior::Silent; + assert_eq!( + finish(&mut pipeline, &mut manager, &config, STAMP, &calls, true,), + silent + ); + assert_eq!(calls.get(), usize::from(silent)); + assert_eq!(pipeline.take_suggestion(), None); + let session = manager.active().unwrap(); + assert_eq!(session.undo_target().is_some(), silent); + assert_eq!( + session.informative_context(), + if silent { "accommodate" } else { "" } + ); + assert_eq!( + session.editable_context(), + if silent { "" } else { "accomodate" } + ); + } + } +} + #[test] fn unsafe_or_stale_suggestions_cannot_surface_a_preview() { for failure in 0..5 { diff --git a/app-core-rust/src/background/triggers.rs b/app-core-rust/src/background/triggers.rs index ef59d07..ad3d553 100644 --- a/app-core-rust/src/background/triggers.rs +++ b/app-core-rust/src/background/triggers.rs @@ -191,7 +191,7 @@ fn request( }, uncertain_language_policy: UncertainLanguagePolicy::default(), mixed_language_policy: MixedLanguagePolicy::default(), - confidence_behavior: ConfidenceBehaviorSettings::default(), + confidence_behavior: config.confidence_behavior(), }) } diff --git a/app-core-rust/src/correction/contract.rs b/app-core-rust/src/correction/contract.rs index 8b7163d..ba120c4 100644 --- a/app-core-rust/src/correction/contract.rs +++ b/app-core-rust/src/correction/contract.rs @@ -150,7 +150,8 @@ pub struct CorrectionInput { pub trigger_type: TriggerType, pub confidence_behavior: ConfidenceBehaviorSettings, /// True only when the caller can display a suggestion for this request. - /// V1 has no suggestion UI, so omitted capabilities fail closed. + /// V1 has opt-in read-only previews but no acceptance UI. Omitted + /// capabilities fail closed. #[serde(default)] pub suggestion_ui_available: bool, } diff --git a/ui/settings-ui/ViewModels/SettingsSkeleton.cs b/ui/settings-ui/ViewModels/SettingsSkeleton.cs index 80c6582..7d60d4b 100644 --- a/ui/settings-ui/ViewModels/SettingsSkeleton.cs +++ b/ui/settings-ui/ViewModels/SettingsSkeleton.cs @@ -101,7 +101,7 @@ public static ObservableCollection CreateSections(AppC Dropdown("Mixed-language text", "Disable correction, use the dominant language, or correct each token with the API engine.", "correction.mixed_language_policy", config.Correction.MixedLanguagePolicy, MixedLanguagePolicies()), ..GrammarCategorySettings(config), Dropdown("High confidence behavior", "Default: apply silently for manual and automatic triggers.", "correction.high_confidence_behavior", config.Correction.HighConfidenceBehavior, ConfidenceBehaviors()), - Dropdown("Medium confidence behavior", "Default: suggest on manual correction when suggestion UI is available; otherwise do nothing. Automatic triggers do nothing unless Apply silently is selected. Suggestion UI is not available in v1.", "correction.medium_confidence_behavior", config.Correction.MediumConfidenceBehavior, ConfidenceBehaviors()), + Dropdown("Medium confidence behavior", "Default: do nothing. Enable read-only manual suggestion previews under Feedback, or choose Apply silently for manual and automatic corrections. Suggestion acceptance is not available in v1.", "correction.medium_confidence_behavior", config.Correction.MediumConfidenceBehavior, ConfidenceBehaviors()), new SettingCardViewModel { Title = "Low confidence behavior", From 8bda15c41ae191fc4e39fa9ec17b25ae646de557 Mon Sep 17 00:00:00 2001 From: Hussein Ba Ragaa Date: Fri, 2 Oct 2026 22:30:57 +0300 Subject: [PATCH 3/6] fix(feedback): contain polling and stale previews --- app-core-rust/README.md | 7 +- app-core-rust/src/background/feedback.rs | 20 +- .../src/background/feedback/notice.rs | 286 ++++++++++++++++-- .../src/background/feedback/suggestion.rs | 24 +- app-core-rust/src/background/pipeline.rs | 21 +- .../src/background/pipeline/tests.rs | 16 +- ui/settings-ui-tests/TrayFeedbackTests.cs | 80 +++++ ui/settings-ui/Lifetime/ShellTray.cs | 15 +- 8 files changed, 424 insertions(+), 45 deletions(-) diff --git a/app-core-rust/README.md b/app-core-rust/README.md index 2835018..a0d9bdd 100644 --- a/app-core-rust/README.md +++ b/app-core-rust/README.md @@ -135,7 +135,12 @@ enable read-only previews with `feedback.show_medium_confidence_suggestions` results can show a bounded preview of executable text; previews never include informative context, mutate text, commit sessions or record undo. New typing, movement, cancellation and secure targets suppress them. Suggestion acceptance -remains planned. `src/background/feedback/suggestion` defines the `SuggestionUi` +remains planned. +The preview carries its validated input generations and full target identity to +the notice worker. Display rechecks that origin before showing and while visible; +it never captures a new origin for old text. Reset, settings changes and pipeline +cancellation revoke dispatched previews, even when input generations stay unchanged. +`src/background/feedback/suggestion` defines the `SuggestionUi` presentation interface for a future near-caret UI. The existing preview adapter advertises availability only when enabled on a supported platform. Display never authorizes replacement or acceptance. Outputs include diff --git a/app-core-rust/src/background/feedback.rs b/app-core-rust/src/background/feedback.rs index 9178bca..295d95b 100644 --- a/app-core-rust/src/background/feedback.rs +++ b/app-core-rust/src/background/feedback.rs @@ -5,10 +5,13 @@ mod notice; pub(crate) mod suggestion; use crate::settings::FeedbackConfig; use std::{ - sync::atomic::{AtomicU8, Ordering}, + sync::{ + atomic::{AtomicBool, AtomicU8, Ordering}, + Arc, + }, time::{Duration, Instant}, }; -use suggestion::{PreviewSuggestionUi, SuggestionUi}; +use suggestion::{Preview, PreviewSuggestionUi, SuggestionUi}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum Event { @@ -79,11 +82,12 @@ pub(super) struct Feedback { blocked: bool, error_until: Option, last_notice: Option, + notice_cancelled: Arc, } impl Feedback { /// Opt-in, read-only preview. Text stays in the short-lived notice worker only. - pub(super) fn suggestion(&mut self, preview: String, config: &FeedbackConfig) { + pub(super) fn suggestion(&mut self, preview: Preview, config: &FeedbackConfig) { let now = Instant::now(); let ui = PreviewSuggestionUi::new(config); if ui.is_available() @@ -92,10 +96,12 @@ impl Feedback { .is_none_or(|last| now.duration_since(last) >= Duration::from_millis(2500)) { self.last_notice = Some(now); - ui.show_preview(preview); + ui.show_preview(preview, Arc::clone(&self.notice_cancelled)); } } pub(super) fn reset(&mut self) { + self.notice_cancelled.store(true, Ordering::Release); + self.notice_cancelled = Arc::new(AtomicBool::new(false)); self.blocked = false; self.error_until = None; } @@ -115,7 +121,11 @@ impl Feedback { .is_none_or(|last| now.duration_since(last) >= Duration::from_millis(2500)) { self.last_notice = Some(now); - notice::show(text, config.show_near_caret_overlay); + notice::show( + text, + config.show_near_caret_overlay, + notice::Origin::current(Arc::clone(&self.notice_cancelled)), + ); } } } diff --git a/app-core-rust/src/background/feedback/notice.rs b/app-core-rust/src/background/feedback/notice.rs index cd7d252..effa7d7 100644 --- a/app-core-rust/src/background/feedback/notice.rs +++ b/app-core-rust/src/background/feedback/notice.rs @@ -1,21 +1,112 @@ //! Brief, coalesced, non-activating feedback independent of the input processor. -use std::sync::atomic::{AtomicBool, Ordering}; +use crate::background::{ + input_listener, + pipeline::InputStamp, + target::{self, CorrectionEligibility, FocusedTarget, TargetDetection}, +}; +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, +}; static VISIBLE: AtomicBool = AtomicBool::new(false); +/// Immutable display authority; never recapture a preview's origin on its worker. +pub(super) struct Origin { + stamp: InputStamp, + foreground: isize, + target: Option, + cancelled: Arc, + policy_cancelled: Arc, +} + +impl Origin { + /// Generic notices contain no document text but still expire with input and policy. + pub(super) fn current(cancelled: Arc) -> Self { + Self { + stamp: Self::input_stamp(), + foreground: target::active_window_handle_value(), + target: None, + policy_cancelled: Arc::clone(&cancelled), + cancelled, + } + } + + /// Carry the target and generations validated by the correction pipeline. + pub(super) fn validated( + stamp: InputStamp, + target: FocusedTarget, + cancelled: Arc, + policy_cancelled: Arc, + ) -> Self { + Self { + stamp, + foreground: target.window_handle, + target: Some(target), + cancelled, + policy_cancelled, + } + } + + fn input_stamp() -> InputStamp { + InputStamp { + position: input_listener::current_position_generation(), + sequence: input_listener::current_input_sequence(), + } + } + + fn input_is_current(&self, stamp: InputStamp, foreground: isize) -> bool { + !self.cancelled.load(Ordering::Acquire) + && !self.policy_cancelled.load(Ordering::Acquire) + && self.stamp == stamp + && self.foreground != 0 + && self.foreground == foreground + } + + fn matches(&self, stamp: InputStamp, foreground: isize, live: Option<&FocusedTarget>) -> bool { + self.input_is_current(stamp, foreground) + && self.target.as_ref().is_none_or(|origin| { + live.is_some_and(|live| { + live.correction_eligibility() == CorrectionEligibility::Allowed + && live.focused_element_id.is_some() + && live == origin + }) + }) + } + + /// Check before display and throughout its lifetime, including UIA focus within a window. + fn is_current(&self) -> bool { + if !self.input_is_current(Self::input_stamp(), target::active_window_handle_value()) { + return false; + } + let live = if self.target.is_some() { + match target::detect_focused_target() { + TargetDetection::Available(target) => Some(target), + TargetDetection::Unsupported => None, + } + } else { + None + }; + // Target detection itself can race with typing, focus changes or config reset. + self.matches( + Self::input_stamp(), + target::active_window_handle_value(), + live.as_ref(), + ) + } +} + /// Provide platform feedback without taking focus; unsupported platforms stay silent. -pub(super) fn show(text: impl Into, near_caret: bool) { +pub(super) fn show(text: impl Into, near_caret: bool, origin: Origin) { if VISIBLE.swap(true, Ordering::AcqRel) { return; } - let position = super::super::input_listener::current_position_generation(); - let sequence = super::super::input_listener::current_input_sequence(); let text = text.into(); if let Err(error) = std::thread::Builder::new() .name("autofix-feedback-notice".into()) .spawn(move || { - native::show(&text, near_caret, position, sequence); + native::show(&text, near_caret, origin); VISIBLE.store(false, Ordering::Release); }) { @@ -45,11 +136,8 @@ mod native { const SS_CENTER: u32 = 0x1; /// Provide platform feedback without taking focus; unsupported platforms stay silent. - pub(super) fn show(text: &str, near_caret: bool, position: u64, sequence: u64) { - let still_current = || { - position == super::super::super::input_listener::current_position_generation() - && sequence == super::super::super::input_listener::current_input_sequence() - }; + pub(super) fn show(text: &str, near_caret: bool, origin: super::Origin) { + let still_current = || origin.is_current(); if !still_current() { return; } @@ -61,7 +149,7 @@ mod native { tracing::warn!("cannot locate work area for feedback notice"); return; } - let foreground = GetForegroundWindow(); + let foreground = origin.foreground as windows_sys::Win32::Foundation::HWND; let mut monitor: MONITORINFO = std::mem::zeroed(); monitor.cbSize = std::mem::size_of::() as u32; if GetMonitorInfoW( @@ -126,14 +214,14 @@ mod native { let started = std::time::Instant::now(); let mut message: MSG = std::mem::zeroed(); while GetMessageW(&mut message, null_mut(), 0, 0) > 0 { - if message.message == WM_TIMER && message.hwnd == window && message.wParam == timer - { - if started.elapsed() >= std::time::Duration::from_millis(2500) + if message.message == WM_TIMER + && message.hwnd == window + && message.wParam == timer + && (started.elapsed() >= std::time::Duration::from_millis(2500) || GetForegroundWindow() != foreground - || !still_current() - { - break; - } + || !still_current()) + { + break; } TranslateMessage(&message); DispatchMessageW(&message); @@ -144,6 +232,114 @@ mod native { } } +#[cfg(test)] +mod origin_tests { + use super::*; + use crate::background::target::FocusedElementId; + + fn target() -> FocusedTarget { + FocusedTarget { + process_id: 1, + process_name: "editor.exe".into(), + window_handle: 2, + window_title: "Notes".into(), + focused_element_id: Some(FocusedElementId::RuntimeId("text".into())), + is_elevated: false, + is_password_or_protected: false, + is_hidden_or_unavailable: false, + field_safety_known: true, + is_secure_desktop: false, + is_lock_screen: false, + is_credential_dialog: false, + } + } + + /// Delayed display and visible previews require the original input and target. + #[test] + fn previews_never_rebind_to_new_input_or_target() { + let stamp = InputStamp { + position: 3, + sequence: 4, + }; + let target = target(); + let origin = Origin::validated( + stamp, + target.clone(), + Arc::new(AtomicBool::new(false)), + Arc::new(AtomicBool::new(false)), + ); + assert!(origin.matches(stamp, 2, Some(&target))); + assert!(!origin.matches( + InputStamp { + position: 4, + ..stamp + }, + 2, + Some(&target) + )); + assert!(!origin.matches( + InputStamp { + sequence: 5, + ..stamp + }, + 2, + Some(&target) + )); + assert!(!origin.matches(stamp, 3, Some(&target))); + assert!(!origin.matches(stamp, 0, Some(&target))); + assert!(!origin.matches(stamp, 2, None)); + for change in 0..12 { + let mut live = target.clone(); + match change { + 0 => live.focused_element_id = Some(FocusedElementId::RuntimeId("password".into())), + 1 => live.focused_element_id = None, + 2 => live.window_title = "Other document".into(), + 3 => live.process_id += 1, + 4 => live.process_name = "other.exe".into(), + 5 => live.window_handle += 1, + 6 => live.is_password_or_protected = true, + 7 => live.is_secure_desktop = true, + 8 => live.field_safety_known = false, + 9 => live.is_elevated = true, + 10 => live.is_hidden_or_unavailable = true, + _ => live.is_credential_dialog = true, + } + assert!( + !origin.matches(stamp, 2, Some(&live)), + "target change {change}" + ); + } + } + + /// Cancellation remains attached after dispatch, independently of input generations. + #[test] + fn cancellation_and_policy_reset_revoke_dispatched_previews() { + let stamp = InputStamp { + position: 3, + sequence: 4, + }; + for policy_reset in [false, true] { + let mut feedback = super::super::Feedback::default(); + let cancelled = Arc::new(AtomicBool::new(false)); + let target = target(); + let origin = Origin::validated( + stamp, + target.clone(), + Arc::clone(&cancelled), + Arc::clone(&feedback.notice_cancelled), + ); + assert!(origin.matches(stamp, 2, Some(&target))); + if policy_reset { + feedback.reset(); + assert!(!feedback.notice_cancelled.load(Ordering::Acquire)); + } else { + cancelled.store(true, Ordering::Release); + } + assert!(!origin.matches(stamp, 2, Some(&target))); + } + } +} + #[cfg(all(test, windows))] mod tests { use super::*; @@ -163,7 +359,12 @@ mod tests { fn native_feedback_notice_preserves_focus_and_dismisses_itself() { let title: Vec = "AutoFix: feedback verification.\0".encode_utf16().collect(); let original = unsafe { GetForegroundWindow() }; - show("AutoFix: feedback verification.", true); + let cancelled = Arc::new(AtomicBool::new(false)); + show( + "AutoFix: feedback verification.", + true, + Origin::current(Arc::clone(&cancelled)), + ); let started = Instant::now(); let window = loop { let window = unsafe { FindWindowW(null(), title.as_ptr()) }; @@ -181,17 +382,60 @@ mod tests { assert_ne!(style & WS_EX_TOOLWINDOW, 0); } // Repeated feedback coalesces into this same notice. - show("AutoFix: feedback verification.", true); + show( + "AutoFix: feedback verification.", + true, + Origin::current(cancelled), + ); while unsafe { !FindWindowW(null(), title.as_ptr()).is_null() } { assert!(started.elapsed() < Duration::from_secs(4)); thread::sleep(Duration::from_millis(20)); } assert!(started.elapsed() >= Duration::from_secs(2)); + + // A reset after dispatch dismisses the visible window before its normal expiry. + let cancelled = Arc::new(AtomicBool::new(false)); + let started = Instant::now(); + while VISIBLE.load(Ordering::Acquire) { + assert!(started.elapsed() < Duration::from_secs(1)); + thread::sleep(Duration::from_millis(10)); + } + show( + "AutoFix: feedback verification.", + false, + Origin::current(Arc::clone(&cancelled)), + ); + loop { + let window = unsafe { FindWindowW(null(), title.as_ptr()) }; + if !window.is_null() && unsafe { IsWindowVisible(window) } != 0 { + break; + } + assert!(started.elapsed() < Duration::from_secs(1)); + thread::sleep(Duration::from_millis(10)); + } + cancelled.store(true, Ordering::Release); + while VISIBLE.load(Ordering::Acquire) { + assert!(started.elapsed() < Duration::from_secs(1)); + thread::sleep(Duration::from_millis(10)); + } + assert!(unsafe { FindWindowW(null(), title.as_ptr()).is_null() }); + + // Revoked work cannot create a window, even if the worker starts later. + show( + "AutoFix: feedback verification.", + false, + Origin::current(cancelled), + ); + while VISIBLE.load(Ordering::Acquire) { + assert!(started.elapsed() < Duration::from_secs(1)); + thread::sleep(Duration::from_millis(10)); + } + assert!(unsafe { FindWindowW(null(), title.as_ptr()).is_null() }); } } #[cfg(not(windows))] mod native { /// Provide platform timeout feedback without taking focus; unsupported platforms stay silent. - pub(super) fn show(_: &str, _: bool, _: u64, _: u64) {} + pub(super) fn show(_: &str, _: bool, _: super::Origin) {} } diff --git a/app-core-rust/src/background/feedback/suggestion.rs b/app-core-rust/src/background/feedback/suggestion.rs index e769302..9edd69e 100644 --- a/app-core-rust/src/background/feedback/suggestion.rs +++ b/app-core-rust/src/background/feedback/suggestion.rs @@ -2,13 +2,23 @@ //! V1 supports only opt-in, read-only notices. Acceptance must go through a //! separate, freshly validated replacement request; display never permits edits. +use crate::background::{pipeline::InputStamp, target::FocusedTarget}; use crate::settings::FeedbackConfig; +use std::sync::{atomic::AtomicBool, Arc}; -pub(crate) trait SuggestionUi { +/// A preview retains the exact origin that passed completion validation. +pub(in crate::background) struct Preview { + pub(in crate::background) text: String, + pub(in crate::background) stamp: InputStamp, + pub(in crate::background) target: FocusedTarget, + pub(in crate::background) cancelled: Arc, +} + +pub(in crate::background) trait SuggestionUi { /// Advertise actual display support, separately from confidence preferences. fn is_available(&self) -> bool; /// Display a bounded preview containing only validated executable text. - fn show_preview(&self, preview: String); + fn show_preview(&self, preview: Preview, policy_cancelled: Arc); } /// Adapter for the existing notice; no interactive overlay or acceptance UI. @@ -27,9 +37,15 @@ impl SuggestionUi for PreviewSuggestionUi<'_> { cfg!(windows) && self.config.show_medium_confidence_suggestions } - fn show_preview(&self, preview: String) { + fn show_preview(&self, preview: Preview, policy_cancelled: Arc) { if self.is_available() { - super::notice::show(preview, self.config.show_near_caret_overlay); + let origin = super::notice::Origin::validated( + preview.stamp, + preview.target, + preview.cancelled, + policy_cancelled, + ); + super::notice::show(preview.text, self.config.show_near_caret_overlay, origin); } } } diff --git a/app-core-rust/src/background/pipeline.rs b/app-core-rust/src/background/pipeline.rs index 9f4eea9..88e6cfe 100644 --- a/app-core-rust/src/background/pipeline.rs +++ b/app-core-rust/src/background/pipeline.rs @@ -13,7 +13,7 @@ use std::{ }; use super::{ - feedback::suggestion::{PreviewSuggestionUi, SuggestionUi}, + feedback::suggestion::{Preview, PreviewSuggestionUi, SuggestionUi}, feedback::Event, replacement::ReplacementConfirmation, security::TriggerKind, @@ -110,7 +110,8 @@ pub(super) struct CorrectionPipeline { next_id: u64, timeout_notice: bool, feedback_event: Option<(Event, bool)>, - suggestion_preview: Option, + suggestion_preview: Option, + preview_cancelled: Arc, } impl CorrectionPipeline { @@ -178,6 +179,7 @@ impl CorrectionPipeline { timeout_notice: false, feedback_event: None, suggestion_preview: None, + preview_cancelled: Arc::new(AtomicBool::new(false)), }) } @@ -282,6 +284,8 @@ impl CorrectionPipeline { /// Cancel all admitted work and clear queued jobs, completions, and timeout feedback. pub(super) fn cancel(&mut self) { + self.preview_cancelled.store(true, Ordering::Release); + self.preview_cancelled = Arc::new(AtomicBool::new(false)); self.timeout_notice = false; self.feedback_event = None; self.suggestion_preview = None; @@ -373,7 +377,7 @@ impl CorrectionPipeline { self.feedback_event.take() } - pub(super) fn take_suggestion(&mut self) -> Option { + pub(super) fn take_suggestion(&mut self) -> Option { self.suggestion_preview.take() } @@ -553,9 +557,14 @@ impl CorrectionPipeline { // A preview never authorizes replacement or commits executable context. self.feedback_event = None; if manual && output.confidence == ConfidenceTier::Medium { - self.suggestion_preview = Some(super::feedback::suggestion_preview( - &output.corrected_executable_text, - )); + self.suggestion_preview = Some(Preview { + text: super::feedback::suggestion_preview( + &output.corrected_executable_text, + ), + stamp: validation_stamp, + target, + cancelled: Arc::clone(&self.preview_cancelled), + }); } return false; } diff --git a/app-core-rust/src/background/pipeline/tests.rs b/app-core-rust/src/background/pipeline/tests.rs index e18bc4b..698b2f3 100644 --- a/app-core-rust/src/background/pipeline/tests.rs +++ b/app-core-rust/src/background/pipeline/tests.rs @@ -1414,15 +1414,23 @@ fn medium_previews_are_manual_opt_in_and_never_mutate_or_commit() { true )); assert_eq!(calls.get(), 0); + let preview = pipeline.take_suggestion(); + if let Some(preview) = &preview { + assert_eq!(preview.stamp, STAMP); + assert_eq!(preview.target, target()); + assert!(!preview.cancelled.load(Ordering::Acquire)); + pipeline.cancel(); + assert!(preview.cancelled.load(Ordering::Acquire)); + } assert_eq!( - pipeline.take_suggestion(), + preview.map(|preview| preview.text), if enabled && !automatic && cfg!(windows) { Some("AutoFix suggestion: the".into()) } else { None } ); - assert_eq!(pipeline.take_suggestion(), None); + assert!(pipeline.take_suggestion().is_none()); assert_eq!(manager.active().unwrap().editable_context(), "teh"); assert!(manager.active().unwrap().informative_context().is_empty()); assert!(manager.active().unwrap().undo_target().is_none()); @@ -1525,7 +1533,7 @@ fn medium_local_results_skip_preview_or_apply_without_losing_typed_text() { silent ); assert_eq!(calls.get(), usize::from(silent)); - assert_eq!(pipeline.take_suggestion(), None); + assert!(pipeline.take_suggestion().is_none()); let session = manager.active().unwrap(); assert_eq!(session.undo_target().is_some(), silent); assert_eq!( @@ -1585,7 +1593,7 @@ fn unsafe_or_stale_suggestions_cannot_surface_a_preview() { }, |_, _, _| -> bool { panic!("suggestion must never mutate") } )); - assert_eq!(pipeline.take_suggestion(), None); + assert!(pipeline.take_suggestion().is_none()); } } diff --git a/ui/settings-ui-tests/TrayFeedbackTests.cs b/ui/settings-ui-tests/TrayFeedbackTests.cs index bd2d961..b8a2f7b 100644 --- a/ui/settings-ui-tests/TrayFeedbackTests.cs +++ b/ui/settings-ui-tests/TrayFeedbackTests.cs @@ -7,6 +7,86 @@ namespace AutoFix.SettingsUi.Tests; [TestClass] public sealed class TrayFeedbackTests { + [TestMethod] + public void PollingContainsNonFatalFailuresAndRecoversOnNextPoll() + { + RunOnSta(() => + { + foreach (var error in new Exception[] + { + new InvalidDataException("IPC response was empty."), + new IOException(), new TimeoutException(), new OperationCanceledException(), + new JsonException(), new InvalidOperationException(), new UnauthorizedAccessException(), + }) + { + var calls = 0; + using var tray = new ShellTray(() => { }, () => { }, () => + ++calls == 1 + ? Task.FromException>(error) + : Task.FromResult(IpcResult.Ok(new(true, "typos_only", "local", "active")))); + tray.RefreshStateAsync().GetAwaiter().GetResult(); + Assert.AreEqual("AutoFix — error", tray.StatusText, error.GetType().Name); + Assert.IsTrue(tray.IsVisible); + tray.RefreshStateAsync().GetAwaiter().GetResult(); + Assert.AreEqual("AutoFix — active", tray.StatusText); + Assert.AreEqual(2, calls, "Failed polling must release the polling guard."); + } + }); + } + + [TestMethod] + public void PollingPreservesDisabledStateAndStopsAfterDisposal() + { + RunOnSta(() => + { + var calls = 0; + using var tray = new ShellTray(() => { }, () => { }, () => + { + calls++; + throw new InvalidDataException("IPC response was empty."); + }); + tray.UpdateStatus(new(true, "typos_only", "local", "active", false)); + tray.RefreshStateAsync().GetAwaiter().GetResult(); + Assert.AreEqual("AutoFix — idle", tray.StatusText); + Assert.IsTrue(tray.IsVisible); + tray.Dispose(); + tray.RefreshStateAsync().GetAwaiter().GetResult(); + Assert.AreEqual(1, calls); + }); + } + + [TestMethod] + public void PollingDoesNotSwallowFatalFailures() + { + RunOnSta(() => + { + foreach (var error in new Exception[] { new OutOfMemoryException(), new StackOverflowException(), new AccessViolationException() }) + { + using var tray = new ShellTray(() => { }, () => { }, () => Task.FromException>(error)); + try + { + tray.RefreshStateAsync().GetAwaiter().GetResult(); + Assert.Fail("Fatal polling failures must propagate."); + } + catch (Exception caught) when (ReferenceEquals(caught, error)) { } + } + }); + } + + private static void RunOnSta(Action action) + { + Exception? failure = null; + var thread = new Thread(() => + { + try { action(); } + catch (Exception error) { failure = error; } + }); + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + Assert.IsTrue(thread.Join(TimeSpan.FromSeconds(10)), "Tray verification timed out."); + if (failure is not null) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(failure).Throw(); + } + [TestMethod] public void TrayRemainsAvailableInEveryStateAndDisposesCleanly() { diff --git a/ui/settings-ui/Lifetime/ShellTray.cs b/ui/settings-ui/Lifetime/ShellTray.cs index 029356b..82941c5 100644 --- a/ui/settings-ui/Lifetime/ShellTray.cs +++ b/ui/settings-ui/Lifetime/ShellTray.cs @@ -12,15 +12,21 @@ public sealed class ShellTray : IDisposable private readonly Action exitShell; private bool disposed; private readonly Forms.Timer statusTimer; - private readonly BackgroundIpcClient ipc = new(); + private readonly Func>> getStatus; private readonly Dictionary icons = new(); private bool polling; private bool trayStateEnabled = true; public ShellTray(Action showShell, Action exitShell) + : this(showShell, exitShell, new BackgroundIpcClient().GetStatusAsync) + { + } + + internal ShellTray(Action showShell, Action exitShell, Func>> getStatus) { this.showShell = showShell; this.exitShell = exitShell; + this.getStatus = getStatus; notifyIcon = new Forms.NotifyIcon { Text = "AutoFix", @@ -58,16 +64,17 @@ internal void UpdateStatus(AppStatusResponse? status) SetState(status?.TrayState ?? "error"); } - private async Task RefreshStateAsync() + /// Contain non-fatal polling failures before they reach the async timer callback. + internal async Task RefreshStateAsync() { if (disposed || polling) return; polling = true; try { - var result = await ipc.GetStatusAsync(); + var result = await getStatus(); UpdateStatus(result.Value); } - catch (Exception error) when (error is System.IO.IOException or TimeoutException or OperationCanceledException or System.Text.Json.JsonException) + catch (Exception error) when (error is not (OutOfMemoryException or StackOverflowException or AccessViolationException)) { SetState("error"); } From b90f74fce38503cef7ccc816c0889b6a80a19a65 Mon Sep 17 00:00:00 2001 From: Hussein Ba Ragaa Date: Fri, 2 Oct 2026 23:17:34 +0300 Subject: [PATCH 4/6] fix(ipc): preserve replies and restrict local access --- app-core-rust/src/ipc/access.rs | 51 +++++ app-core-rust/src/ipc/mod.rs | 2 + app-core-rust/src/ipc/request_deadline.rs | 72 +++++++ app-core-rust/src/ipc/server.rs | 27 ++- app-core-rust/src/ipc/tests.rs | 201 ++++++++++++++++++ shared-schema/README.md | 15 ++ .../BackgroundIpcClientTests.cs | 59 +++++ ui/settings-ui/Ipc/BackgroundIpcClient.cs | 14 +- 8 files changed, 434 insertions(+), 7 deletions(-) create mode 100644 app-core-rust/src/ipc/access.rs create mode 100644 app-core-rust/src/ipc/request_deadline.rs create mode 100644 ui/settings-ui-tests/BackgroundIpcClientTests.cs diff --git a/app-core-rust/src/ipc/access.rs b/app-core-rust/src/ipc/access.rs new file mode 100644 index 0000000..623485c --- /dev/null +++ b/app-core-rust/src/ipc/access.rs @@ -0,0 +1,51 @@ +//! Local IPC is private to the pipe owner; remote clients remain rejected by the server. + +use std::ptr::null_mut; +use windows_sys::Win32::{ + Foundation::LocalFree, + Security::{ + Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW, PSECURITY_DESCRIPTOR, + SECURITY_ATTRIBUTES, + }, +}; + +/// Own the descriptor until Windows has copied it during pipe creation. +pub(super) struct PipeSecurity(PSECURITY_DESCRIPTOR); + +impl PipeSecurity { + /// Grant only the object's owner access; never inherit Everyone or anonymous read permissions. + pub(super) fn new() -> std::io::Result { + let sddl: Vec = "D:P(A;;GA;;;OW)\0".encode_utf16().collect(); + let mut descriptor = null_mut(); + let ok = unsafe { + ConvertStringSecurityDescriptorToSecurityDescriptorW( + sddl.as_ptr(), + 1, + &mut descriptor, + null_mut(), + ) + }; + if ok == 0 { + Err(std::io::Error::last_os_error()) + } else { + Ok(Self(descriptor)) + } + } + + /// Pipe handles are not inheritable; the protected DACL applies to every new instance. + pub(super) fn attributes(&self) -> SECURITY_ATTRIBUTES { + SECURITY_ATTRIBUTES { + nLength: std::mem::size_of::() as u32, + lpSecurityDescriptor: self.0, + bInheritHandle: 0, + } + } +} + +impl Drop for PipeSecurity { + fn drop(&mut self) { + unsafe { + LocalFree(self.0); + } + } +} diff --git a/app-core-rust/src/ipc/mod.rs b/app-core-rust/src/ipc/mod.rs index e7c7c6c..0e94f99 100644 --- a/app-core-rust/src/ipc/mod.rs +++ b/app-core-rust/src/ipc/mod.rs @@ -1,5 +1,7 @@ +mod access; mod client; mod protocol; +mod request_deadline; mod server; mod server_shutdown; mod state; diff --git a/app-core-rust/src/ipc/request_deadline.rs b/app-core-rust/src/ipc/request_deadline.rs new file mode 100644 index 0000000..2ca58fe --- /dev/null +++ b/app-core-rust/src/ipc/request_deadline.rs @@ -0,0 +1,72 @@ +//! Bound a connected client's pipe I/O, including waiting for response consumption. + +use std::{ + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc, Arc, + }, + thread::{self, JoinHandle}, + time::Duration, +}; +use windows_sys::Win32::{Foundation::HANDLE, System::IO::CancelIoEx}; + +const REQUEST_TIMEOUT: Duration = Duration::from_secs(1); + +pub(super) struct RequestDeadline { + expired: Arc, + done: mpsc::Sender<()>, + worker: Option>, +} + +impl RequestDeadline { + /// The caller must keep the pipe alive until this guard is dropped and its watchdog joined. + pub(super) fn start(pipe: HANDLE) -> std::io::Result { + let expired = Arc::new(AtomicBool::new(false)); + let flag = Arc::clone(&expired); + let (done, complete) = mpsc::channel(); + let pipe_address = pipe as usize; + let worker = thread::Builder::new() + .name("autofix-ipc-deadline".into()) + .spawn(move || { + if complete.recv_timeout(REQUEST_TIMEOUT) != Err(mpsc::RecvTimeoutError::Timeout) { + return; + } + flag.store(true, Ordering::Release); + loop { + // Retry covers a deadline that raced between two pipe I/O calls. + // Cancellation targets this pipe only, never SQLite or settings-file I/O. + unsafe { + CancelIoEx(pipe_address as HANDLE, std::ptr::null()); + } + if complete.recv_timeout(Duration::from_millis(10)) + != Err(mpsc::RecvTimeoutError::Timeout) + { + break; + } + } + })?; + Ok(Self { + expired, + done, + worker: Some(worker), + }) + } + + /// Refuse new work after expiry, even if no pipe operation was pending when cancellation began. + pub(super) fn expired(&self) -> bool { + self.expired.load(Ordering::Acquire) + } +} + +impl Drop for RequestDeadline { + fn drop(&mut self) { + let _ = self.done.send(()); + if self + .worker + .take() + .is_some_and(|worker| worker.join().is_err()) + { + tracing::error!("IPC deadline worker panicked"); + } + } +} diff --git a/app-core-rust/src/ipc/server.rs b/app-core-rust/src/ipc/server.rs index 1401e2c..2592fae 100644 --- a/app-core-rust/src/ipc/server.rs +++ b/app-core-rust/src/ipc/server.rs @@ -14,7 +14,7 @@ use windows_sys::Win32::{ Foundation::{ CloseHandle, ERROR_MORE_DATA, ERROR_PIPE_CONNECTED, HANDLE, INVALID_HANDLE_VALUE, }, - Storage::FileSystem::{ReadFile, WriteFile, PIPE_ACCESS_DUPLEX}, + Storage::FileSystem::{FlushFileBuffers, ReadFile, WriteFile, PIPE_ACCESS_DUPLEX}, System::Pipes::{ ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, PIPE_READMODE_MESSAGE, PIPE_REJECT_REMOTE_CLIENTS, PIPE_TYPE_MESSAGE, PIPE_WAIT, @@ -92,7 +92,10 @@ fn serve_pipe(pipe_path: String, state: Arc>, shutdown: Ar } } +/// Create a local, owner-only endpoint; security setup failure never falls back to a default ACL. fn create_pipe(pipe_path: &str) -> Result { + let security = super::access::PipeSecurity::new().map_err(|error| error.to_string())?; + let attributes = security.attributes(); let path = wide(pipe_path); let pipe = unsafe { CreateNamedPipeW( @@ -103,7 +106,7 @@ fn create_pipe(pipe_path: &str) -> Result { 64 * 1024, 64 * 1024, 0, - null_mut(), + &attributes, ) }; @@ -114,6 +117,7 @@ fn create_pipe(pipe_path: &str) -> Result { } } +/// Serve one connected client under a pipe-I/O deadline and drain its response before disconnect. fn handle_pipe(pipe: HANDLE, state: &Arc>) { let connected = unsafe { ConnectNamedPipe(pipe, null_mut()) }; if connected == 0 @@ -122,8 +126,15 @@ fn handle_pipe(pipe: HANDLE, state: &Arc>) { return; } + let Ok(deadline) = super::request_deadline::RequestDeadline::start(pipe) else { + tracing::warn!("cannot enforce IPC request deadline"); + return; + }; let response = read_request(pipe) .and_then(|request| { + if deadline.expired() { + return Err("IPC request deadline exceeded".into()); + } state .lock() .map_err(|_| "IPC state lock poisoned".to_owned()) @@ -131,7 +142,12 @@ fn handle_pipe(pipe: HANDLE, state: &Arc>) { }) .unwrap_or_else(IpcResponse::error); - let _ = write_response(pipe, &response); + if deadline.expired() { + return; + } + if let Err(error) = write_response(pipe, &response) { + tracing::warn!(%error, "IPC response delivery failed"); + } } fn read_request(pipe: HANDLE) -> Result { @@ -171,6 +187,7 @@ fn read_request(pipe: HANDLE) -> Result { serde_json::from_slice(&buffer[..total_read]).map_err(|error| error.to_string()) } +/// Preserve the complete response for delayed readers and clients that wait for EOF. fn write_response(pipe: HANDLE, response: &IpcResponse) -> Result<(), String> { let output = serde_json::to_vec(response).map_err(|error| error.to_string())?; let mut written = 0; @@ -184,9 +201,11 @@ fn write_response(pipe: HANDLE, response: &IpcResponse) -> Result<(), String> { ) }; - if write_ok == 0 || written != output.len() as u32 { + if write_ok == 0 || written != output.len() as u32 || unsafe { FlushFileBuffers(pipe) } == 0 { Err(std::io::Error::last_os_error().to_string()) } else { + // DisconnectNamedPipe discards unread bytes. Drain before the caller disconnects, + // including clients that consume a byte stream until EOF instead of message boundaries. Ok(()) } } diff --git a/app-core-rust/src/ipc/tests.rs b/app-core-rust/src/ipc/tests.rs index da1b08a..8a47e25 100644 --- a/app-core-rust/src/ipc/tests.rs +++ b/app-core-rust/src/ipc/tests.rs @@ -22,6 +22,207 @@ use super::pipe_path_for_process; static UNIQUE_COUNTER: AtomicU64 = AtomicU64::new(0); +/// .NET tray clients must receive a complete response even when reading starts after the write. +#[test] +fn dotnet_status_clients_preserve_delayed_responses_in_byte_and_message_modes() { + use std::{ + os::windows::process::CommandExt, + process::Command, + thread, + time::{Duration, Instant}, + }; + + let fixture = IpcFixture::start(); + let pipe_name = fixture.pipe_path.strip_prefix(r"\\.\pipe\").unwrap(); + for read_mode in ["Byte", "Message"] { + let script = format!( + r#" +$ErrorActionPreference = 'Stop' +$pipe = [System.IO.Pipes.NamedPipeClientStream]::new('.', '{pipe_name}', [System.IO.Pipes.PipeDirection]::InOut, [System.IO.Pipes.PipeOptions]::Asynchronous) +try {{ + $pipe.Connect(2000) + $pipe.ReadMode = [System.IO.Pipes.PipeTransmissionMode]::{read_mode} + $bytes = [System.Text.Encoding]::UTF8.GetBytes('{{"type":"get_app_status"}}') + $pipe.Write($bytes, 0, $bytes.Length) + $pipe.Flush() + Start-Sleep -Milliseconds 100 + $reader = [System.IO.StreamReader]::new($pipe) + try {{ + $read = $reader.ReadToEndAsync() + if (!$read.Wait(2000)) {{ throw 'IPC response timed out.' }} + [Console]::Write($read.GetAwaiter().GetResult()) + }} finally {{ $reader.Dispose() }} +}} finally {{ $pipe.Dispose() }} +"# + ); + let mut child = Command::new("powershell.exe") + .args(["-NoProfile", "-NonInteractive", "-Command", &script]) + .creation_flags(0x08000000) // CREATE_NO_WINDOW + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let started = Instant::now(); + while child.try_wait().unwrap().is_none() { + if started.elapsed() > Duration::from_secs(6) { + child.kill().unwrap(); + let _ = child.wait(); + panic!(".NET IPC client did not finish in {read_mode} mode"); + } + thread::sleep(Duration::from_millis(10)); + } + let output = child.wait_with_output().unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let response: IpcResponse = serde_json::from_slice(&output.stdout) + .expect(".NET tray client must receive a complete JSON response"); + assert!(matches!(response, IpcResponse::AppStatus(status) if status.running)); + } +} + +/// Local anonymous readers must not connect; the owning account remains able to poll status. +#[test] +fn anonymous_local_clients_are_denied_even_read_only_access() { + use std::{os::windows::ffi::OsStrExt, ptr::null_mut, thread, time::Duration}; + use windows_sys::Win32::{ + Foundation::{ + CloseHandle, GetLastError, ERROR_ACCESS_DENIED, ERROR_FILE_NOT_FOUND, GENERIC_READ, + INVALID_HANDLE_VALUE, + }, + Security::{ImpersonateAnonymousToken, RevertToSelf}, + Storage::FileSystem::{CreateFileW, FILE_ATTRIBUTE_NORMAL, OPEN_EXISTING}, + System::Threading::GetCurrentThread, + }; + let fixture = IpcFixture::start(); + assert!(matches!( + send_request(&fixture.pipe_path, &IpcRequest::GetAppStatus).unwrap(), + IpcResponse::AppStatus(_) + )); + let pipe_path = fixture.pipe_path.clone(); + let error = thread::spawn(move || { + struct Revert; + impl Drop for Revert { + fn drop(&mut self) { + assert_ne!(unsafe { RevertToSelf() }, 0); + } + } + assert_ne!(unsafe { ImpersonateAnonymousToken(GetCurrentThread()) }, 0); + let _revert = Revert; + let path: Vec = std::ffi::OsStr::new(&pipe_path) + .encode_wide() + .chain(Some(0)) + .collect(); + for _ in 0..100 { + let pipe = unsafe { + CreateFileW( + path.as_ptr(), + GENERIC_READ, + 0, + null_mut(), + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + null_mut(), + ) + }; + if pipe != INVALID_HANDLE_VALUE { + unsafe { + CloseHandle(pipe); + } + return 0; + } + let error = unsafe { GetLastError() }; + if error != ERROR_FILE_NOT_FOUND { + return error; + } + thread::sleep(Duration::from_millis(10)); + } + ERROR_FILE_NOT_FOUND + }) + .join() + .unwrap(); + assert_eq!(error, ERROR_ACCESS_DENIED); + assert!(matches!( + send_request(&fixture.pipe_path, &IpcRequest::GetAppStatus).unwrap(), + IpcResponse::AppStatus(_) + )); +} + +/// An idle or nonreading local client must not monopolize the status endpoint. +#[test] +fn stalled_clients_release_the_status_endpoint_at_the_request_deadline() { + use std::{ + os::windows::ffi::OsStrExt, + ptr::null_mut, + thread, + time::{Duration, Instant}, + }; + use windows_sys::Win32::{ + Foundation::{CloseHandle, GENERIC_READ, GENERIC_WRITE, HANDLE, INVALID_HANDLE_VALUE}, + Storage::FileSystem::{CreateFileW, WriteFile, FILE_ATTRIBUTE_NORMAL, OPEN_EXISTING}, + }; + struct Client(HANDLE); + impl Drop for Client { + fn drop(&mut self) { + unsafe { + CloseHandle(self.0); + } + } + } + for send_request_first in [false, true] { + let fixture = IpcFixture::start(); + let path: Vec = std::ffi::OsStr::new(&fixture.pipe_path) + .encode_wide() + .chain(Some(0)) + .collect(); + let started = Instant::now(); + let client = loop { + let pipe = unsafe { + CreateFileW( + path.as_ptr(), + GENERIC_READ | GENERIC_WRITE, + 0, + null_mut(), + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + null_mut(), + ) + }; + if pipe != INVALID_HANDLE_VALUE { + break Client(pipe); + } + assert!(started.elapsed() < Duration::from_secs(2)); + thread::sleep(Duration::from_millis(10)); + }; + if send_request_first { + let request = serde_json::to_vec(&IpcRequest::GetAppStatus).unwrap(); + let mut written = 0; + assert_ne!( + unsafe { + WriteFile( + client.0, + request.as_ptr().cast(), + request.len() as u32, + &mut written, + null_mut(), + ) + }, + 0 + ); + assert_eq!(written as usize, request.len()); + } + thread::sleep(Duration::from_millis(1200)); + let resumed = Instant::now(); + let response = send_request(&fixture.pipe_path, &IpcRequest::GetAppStatus).unwrap(); + assert!(matches!(response, IpcResponse::AppStatus(status) if status.running)); + assert!(resumed.elapsed() < Duration::from_millis(500)); + // Keep the unresponsive client open until after the next client has succeeded. + drop(client); + } +} + #[test] fn reports_basic_app_status() { let fixture = IpcFixture::start(); diff --git a/shared-schema/README.md b/shared-schema/README.md index 4efeb2c..773bdbe 100644 --- a/shared-schema/README.md +++ b/shared-schema/README.md @@ -74,6 +74,21 @@ The status also carries `tray_state_enabled` so the shell can preserve that preference when the engine becomes unavailable. Hard secure-field/desktop refusals, cancelled and stale results cannot display a notice or suggestion preview. +The Windows IPC pipe rejects remote clients and uses a protected ACL granting +access only to its owner. The .NET client verifies that the server has the same +Windows owner and elevation context before sending a request. Processes running +as that account share the configuration trust boundary; IPC does not authenticate +individual executables. Anonymous local clients cannot connect, including for +read-only access. + +Each connected client has a one-second pipe-I/O deadline covering request reads, +response writes and response consumption. Expiry cancels only that pipe's I/O so +an idle or nonreading client cannot monopolize status polling. Responses drain +before disconnect because Windows discards unread pipe bytes on disconnect. +Both byte-stream clients reading to EOF and message-mode clients are supported. +The .NET client retains its separate 400 ms connect and request deadlines; legacy +status payloads without tray fields default to idle with state display enabled. + Unavailable application rules deny authorization for typed capture and every correction trigger, including API execution. An empty successfully read rule list is distinct from a failed read. diff --git a/ui/settings-ui-tests/BackgroundIpcClientTests.cs b/ui/settings-ui-tests/BackgroundIpcClientTests.cs new file mode 100644 index 0000000..1808e14 --- /dev/null +++ b/ui/settings-ui-tests/BackgroundIpcClientTests.cs @@ -0,0 +1,59 @@ +using System.IO.Pipes; +using System.Text; +using System.Text.Json; +using AutoFix.SettingsUi.Ipc; + +namespace AutoFix.SettingsUi.Tests; + +[TestClass] +public sealed class BackgroundIpcClientTests +{ + /// Verify current-user transport accepts new and legacy status payloads in both read modes. + [TestMethod] + public async Task StatusPollingWorksWithCurrentUserServerAndLegacyPayloads() + { + foreach (var mode in new[] { PipeTransmissionMode.Byte, PipeTransmissionMode.Message }) + foreach (var legacy in new[] { false, true }) + { + var payload = legacy + ? "{\"running\":true,\"correction_mode\":\"typos_only\",\"engine\":\"local\"}" + : "{\"running\":true,\"correction_mode\":\"typos_only\",\"engine\":\"local\",\"tray_state\":\"active\",\"tray_state_enabled\":false}"; + var result = await WithResponse(mode, $"{{\"type\":\"app_status\",\"payload\":{payload}}}"); + Assert.IsTrue(result.Available); + Assert.IsNull(result.Error); + Assert.IsTrue(result.Value!.Running); + Assert.AreEqual(legacy ? "idle" : "active", result.Value.TrayState); + Assert.AreEqual(legacy, result.Value.TrayStateEnabled); + } + } + + /// Empty and null responses remain transport failures rather than fabricated healthy status. + [TestMethod] + public async Task EmptyAndNullStatusResponsesFailClosed() + { + await Assert.ThrowsExceptionAsync(() => WithResponse(PipeTransmissionMode.Message, "")); + await Assert.ThrowsExceptionAsync(() => WithResponse(PipeTransmissionMode.Message, "null")); + } + + /// Serve one bounded status exchange without connecting to the user's running engine. + private static async Task> WithResponse(PipeTransmissionMode mode, string response) + { + var pipeName = $"Local\\AutoFix.Status.Tests.{Guid.NewGuid():N}"; + await using var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, mode, + PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + var serving = Task.Run(async () => + { + await server.WaitForConnectionAsync(deadline.Token); + var bytes = new byte[4096]; + var count = await server.ReadAsync(bytes, deadline.Token); + using var request = JsonDocument.Parse(bytes.AsMemory(0, count)); + Assert.AreEqual("get_app_status", request.RootElement.GetProperty("type").GetString()); + await server.WriteAsync(Encoding.UTF8.GetBytes(response), deadline.Token); + server.WaitForPipeDrain(); + server.Disconnect(); + }, deadline.Token); + try { return await new BackgroundIpcClient(pipeName).GetStatusAsync(); } + finally { await serving.WaitAsync(deadline.Token); } + } +} diff --git a/ui/settings-ui/Ipc/BackgroundIpcClient.cs b/ui/settings-ui/Ipc/BackgroundIpcClient.cs index cb9435d..143e7c5 100644 --- a/ui/settings-ui/Ipc/BackgroundIpcClient.cs +++ b/ui/settings-ui/Ipc/BackgroundIpcClient.cs @@ -9,6 +9,7 @@ namespace AutoFix.SettingsUi.Ipc; public sealed class BackgroundIpcClient : IBackgroundIpcClient { private const string PipeName = @"Local\AutoFix.Background.Ipc"; + private readonly string pipeName; private static readonly TimeSpan ConnectTimeout = TimeSpan.FromMilliseconds(400); private static readonly TimeSpan RequestTimeout = TimeSpan.FromMilliseconds(400); private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) @@ -16,6 +17,12 @@ public sealed class BackgroundIpcClient : IBackgroundIpcClient DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; + /// Connect to the local engine endpoint with owner verification and bounded waits. + public BackgroundIpcClient() : this(PipeName) { } + + /// Use an isolated endpoint for transport tests without contacting the running engine. + internal BackgroundIpcClient(string pipeName) => this.pipeName = pipeName; + public async Task> GetStatusAsync() { var response = await SendAsync(new IpcEnvelope("get_app_status")).ConfigureAwait(false); @@ -122,13 +129,14 @@ public async Task> IsBackgroundRunningAsync } } - private static async Task SendAsync(IpcEnvelope request) + /// Exchange one request with a local server owned by the current Windows user. + private async Task SendAsync(IpcEnvelope request) { await using var pipe = new NamedPipeClientStream( ".", - PipeName, + pipeName, PipeDirection.InOut, - PipeOptions.Asynchronous); + PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); using var connectTimeout = new CancellationTokenSource(ConnectTimeout); await pipe.ConnectAsync(connectTimeout.Token).ConfigureAwait(false); From 39850ec036d231ace9c5c7f5cec9f83a3936a2b6 Mon Sep 17 00:00:00 2001 From: Hussein Ba Ragaa Date: Fri, 2 Oct 2026 23:21:27 +0300 Subject: [PATCH 5/6] docs(ipc): clarify owner checks and cancellation limits --- app-core-rust/src/ipc/request_deadline.rs | 2 +- shared-schema/README.md | 13 ++++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/app-core-rust/src/ipc/request_deadline.rs b/app-core-rust/src/ipc/request_deadline.rs index 2ca58fe..4c29ab1 100644 --- a/app-core-rust/src/ipc/request_deadline.rs +++ b/app-core-rust/src/ipc/request_deadline.rs @@ -1,4 +1,4 @@ -//! Bound a connected client's pipe I/O, including waiting for response consumption. +//! Request cancellation of stalled client pipe I/O, including response consumption. use std::{ sync::{ diff --git a/shared-schema/README.md b/shared-schema/README.md index 773bdbe..342a846 100644 --- a/shared-schema/README.md +++ b/shared-schema/README.md @@ -75,15 +75,18 @@ preference when the engine becomes unavailable. Hard secure-field/desktop refusa cancelled and stale results cannot display a notice or suggestion preview. The Windows IPC pipe rejects remote clients and uses a protected ACL granting -access only to its owner. The .NET client verifies that the server has the same -Windows owner and elevation context before sending a request. Processes running +access only to its owner. The .NET client compares the server's owner SID with +the current Windows identity's owner SID before sending a request. This check +does not separately query the server's elevation level. Processes running as that account share the configuration trust boundary; IPC does not authenticate individual executables. Anonymous local clients cannot connect, including for read-only access. -Each connected client has a one-second pipe-I/O deadline covering request reads, -response writes and response consumption. Expiry cancels only that pipe's I/O so -an idle or nonreading client cannot monopolize status polling. Responses drain +After one second, a watchdog requests cancellation of that client's pipe I/O, +covering request reads, response writes and response consumption. Cancellation +targets only that pipe and is best-effort; one second is the cancellation +threshold, not a guaranteed completion bound. Native tests verify endpoint +recovery with idle and nonreading clients held open. Responses drain before disconnect because Windows discards unread pipe bytes on disconnect. Both byte-stream clients reading to EOF and message-mode clients are supported. The .NET client retains its separate 400 ms connect and request deadlines; legacy From 0e64fd16d9f7f45c8d1f88dac9e2379a569be4b7 Mon Sep 17 00:00:00 2001 From: Hussein Ba Ragaa Date: Fri, 2 Oct 2026 23:36:55 +0300 Subject: [PATCH 6/6] test: stabilize Windows CI harnesses --- app-core-rust/src/background/pipeline/tests.rs | 3 +++ app-core-rust/src/ipc/tests.rs | 11 ++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/app-core-rust/src/background/pipeline/tests.rs b/app-core-rust/src/background/pipeline/tests.rs index 698b2f3..a805273 100644 --- a/app-core-rust/src/background/pipeline/tests.rs +++ b/app-core-rust/src/background/pipeline/tests.rs @@ -276,6 +276,9 @@ fn queued_api_job_is_denied_after_rule_revocation_and_releases_its_slot() { Err(error) => panic!("{error}"), } }; + // Windows sockets accepted from a nonblocking listener can inherit that mode. + // Wait for the complete HTTP request before signalling the queued-job test. + stream.set_nonblocking(false).unwrap(); stream .set_read_timeout(Some(Duration::from_secs(2))) .unwrap(); diff --git a/app-core-rust/src/ipc/tests.rs b/app-core-rust/src/ipc/tests.rs index 8a47e25..99e0ada 100644 --- a/app-core-rust/src/ipc/tests.rs +++ b/app-core-rust/src/ipc/tests.rs @@ -64,10 +64,15 @@ try {{ .unwrap(); let started = Instant::now(); while child.try_wait().unwrap().is_none() { - if started.elapsed() > Duration::from_secs(6) { + // Allow cold PowerShell/.NET startup on busy CI hosts; the connect and + // response deadlines inside the client remain two seconds each. + if started.elapsed() > Duration::from_secs(30) { child.kill().unwrap(); - let _ = child.wait(); - panic!(".NET IPC client did not finish in {read_mode} mode"); + let output = child.wait_with_output().unwrap(); + panic!( + ".NET IPC client did not finish in {read_mode} mode: {}", + String::from_utf8_lossy(&output.stderr) + ); } thread::sleep(Duration::from_millis(10)); }