Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 32 additions & 6 deletions app-core-rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,14 +98,27 @@ 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
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.
Expand All @@ -116,15 +129,28 @@ 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.
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
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
Expand Down
250 changes: 250 additions & 0 deletions app-core-rust/src/background/feedback.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
//! Quiet feedback policy. Tray state is metadata only; opt-in previews stay ephemeral.

use super::security::BlockReason;
mod notice;
pub(crate) mod suggestion;
use crate::settings::FeedbackConfig;
use std::{
sync::{
atomic::{AtomicBool, AtomicU8, Ordering},
Arc,
},
time::{Duration, Instant},
};
use suggestion::{Preview, PreviewSuggestionUi, SuggestionUi};

#[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<Instant>,
last_notice: Option<Instant>,
notice_cancelled: Arc<AtomicBool>,
}

impl Feedback {
/// Opt-in, read-only preview. Text stays in the short-lived notice worker only.
pub(super) fn suggestion(&mut self, preview: Preview, config: &FeedbackConfig) {
let now = Instant::now();
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);
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;
}

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,
notice::Origin::current(Arc::clone(&self.notice_cancelled)),
);
}
}
}

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))
);
}
}
Loading
Loading