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
35 changes: 33 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,15 @@ plus specific pairs such as `teh` → `the` that must never be applied. Entries
in `%LOCALAPPDATA%\AutoFix\autofix.sqlite`, with a language tag and optional app
process scope. `und` protects all languages; an empty app scope applies everywhere.

**Languages** defaults to automatic detection. Set a global preferred BCP 47
language tag, optional app overrides, and policies for uncertain or mixed text.
App overrides take priority. **Engines** configures local/API routing, provider,
custom endpoint, model, timeouts and local fallback. Manage provider keys through
the masked Windows Credential Manager editor; keys are excluded from config
exports. **Logs / Debug** displays the latest 500 metadata events and can clear
metadata and debug logs. Full-text debug requires an explicit privacy warning,
including through config import; redacted debug remains available separately.

Learning defaults to **Off — undo only**. App-level undo only restores the
correction unless you choose **Ask after undo** or **Automatically learn**.
Ask shows “Don't correct this again?” after a successful undo; only Yes saves an
Expand All @@ -81,7 +90,7 @@ active when learning is off. Native Ctrl+Z and suggestion rejection are not trac
use AutoFix's undo shortcut to reject an applied correction.

Native clipboard replacement preserves all readable formats and restores them
before reporting success. Disable it under **Correction > Use clipboard for
before reporting success. Disable it under **Privacy & Security > 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.

Expand Down Expand Up @@ -130,13 +139,35 @@ moves the corrected text into informative context, clears executable context,
records app-level undo and writes metadata without document text.

Selected text must belong to the current typed segment unless **Correct arbitrary
selection** is enabled under **Shortcuts**. Even with that option, backward
selection** is enabled under **Privacy & Security**. Even with that option, backward
selections and selections without reliable caret proof skip correction. Text after
the caret stays untouched. Unchanged or suppressed selections retain their context
and selection; suggestion acceptance remains planned.

## Run App

The settings search bar finds names, descriptions, choices and config paths
across every page, including Privacy & Security and nested Context limits.
Use Ctrl+F, then try `word count threshold`, `timeout` or `cancel oldest`.
Matching settings are filtered and highlighted. Clear search or press Escape in
the search box to browse again. Keys, typed text and saved dictionary contents
are excluded from the search index.

**Advanced → Settings import/export** exports a ZIP containing `settings.toml`,
app rules, the custom dictionary and language overrides. Learned pair rules are
optional and excluded by default. Import validates a ZIP bundle or legacy TOML
file, previews the replacements, and applies only after confirmation. Successful
imports reload the background process. Bundles exclude API keys, logs, typed
session data and correction-history text; keys remain in Windows Credential
Manager on the current device.

Interrupted imports recover automatically before settings are loaded: SQLite
durably records whether to restore the old settings or finish the committed
import. Correction remains blocked while recovery is pending. Settings and rule
data therefore resume from the same committed import, even if the settings file
did not survive shutdown. See [the settings documentation](ui/settings-ui/README.md)
for the recovery protocol and failure reporting.

From the repository root, build and run AutoFix:

```powershell
Expand Down
18 changes: 18 additions & 0 deletions app-core-rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -506,3 +506,21 @@ interactive Windows desktop. It safely refuses unsupported clipboard formats.
Feature code should be organized by product behavior, not technical layer. Keep modules small, private by default, and colocate tests with the behavior they verify.

Do not implement optional helper mode here until it becomes a committed product requirement.

## Interrupted settings imports

The WPF importer and native settings reader share `settings.toml.lock` and the
SQLite `settings_import_recovery` protocol. Before replacing settings, the UI
durably stores original and imported TOML bytes with `committed = 0`. The product
replacement transaction sets `committed = 1` atomically with its rule changes.
Settings loads reconcile a surviving record: zero restores the original bytes,
one finishes the imported bytes. They flush and atomically replace the file
before clearing the record using SQLite synchronous FULL. This operation is
idempotent across another interruption. Existing databases without the recovery
table retain their normal behavior; engine migration versions are unchanged.

Correction policy guards refuse any surviving recovery record, including during
an active import. Settings reads/writes share the Windows lock, whose ownership
ends with the process. IPC edits start from the latest settings under that lock.
Failed reloads are retried rather than marking the new timestamp as loaded.
The recovery table and temporary backups are excluded from config bundles.
48 changes: 30 additions & 18 deletions app-core-rust/src/background/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,7 @@ use std::{
time::{Duration, SystemTime},
};

use crate::{
settings::{save_config, AppConfig},
storage::Database,
};
use crate::{settings::AppConfig, storage::Database};

use self::{
admin::reject_elevated_process,
Expand Down Expand Up @@ -193,10 +190,17 @@ impl BackgroundRuntime {
ensure_parent_directory(paths.config_path())?;
ensure_parent_directory(paths.database_path())?;

let config_modified_at = modified_at(paths.config_path());
let config = load_or_create_config(paths.config_path())?;
let database = Database::open(paths.database_path()).map_err(BackgroundError::Database)?;
let shutdown_requested = Arc::new(AtomicBool::new(false));
let components = RuntimeComponents::start(&config, &paths, shutdown_requested, database)?;
let components = RuntimeComponents::start(
&config,
config_modified_at,
&paths,
shutdown_requested,
database,
)?;

tracing::info!("AutoFix background process started");
Ok(Self { components })
Expand All @@ -219,6 +223,7 @@ impl BackgroundRuntime {
impl RuntimeComponents {
fn start(
config: &AppConfig,
config_modified_at: Option<SystemTime>,
paths: &RuntimePaths,
shutdown_requested: Arc<AtomicBool>,
database: Database,
Expand All @@ -229,7 +234,7 @@ impl RuntimeComponents {
let input_worker = InputWorker::start(config.clone(), database)?;
Ok(Self {
config_path: paths.config_path().to_path_buf(),
config_modified_at: modified_at(paths.config_path()),
config_modified_at,
config: config.clone(),
ipc_server: NamedPipeIpcServer::initialize(
config,
Expand Down Expand Up @@ -284,21 +289,18 @@ impl RuntimeComponents {
}

fn reload_shortcuts_if_config_changed(&mut self) {
let modified_at = modified_at(&self.config_path);
if modified_at == self.config_modified_at {
return;
}

self.config_modified_at = modified_at;
match crate::settings::load_config(&self.config_path) {
Ok(config) => {
match load_changed_config(&self.config_path, &mut self.config_modified_at, |path| {
crate::settings::load_config(path)
}) {
Ok(Some(config)) => {
if shortcuts::detect_conflict(&config) {
tracing::warn!("shortcut conflict detected while reloading config");
}
self.config = config.clone();
self.global_shortcut.reload(&config);
self.input_worker.send(InputWork::Config(Box::new(config)));
}
Ok(None) => {}
Err(error) => tracing::warn!("failed to reload shortcuts from config: {}", error),
}
}
Expand Down Expand Up @@ -1266,12 +1268,22 @@ fn ensure_parent_directory(path: &Path) -> Result<(), BackgroundError> {

fn load_or_create_config(path: &Path) -> Result<AppConfig, BackgroundError> {
ensure_parent_directory(path)?;
crate::settings::load_or_create_config(path).map_err(BackgroundError::Config)
}

if !path.exists() {
save_config(path, &AppConfig::default()).map_err(BackgroundError::Config)?;
/// Cache the pre-load timestamp so writes during loading remain visible on the next tick.
fn load_changed_config(
path: &Path,
last_modified_at: &mut Option<SystemTime>,
load: impl FnOnce(&Path) -> Result<AppConfig, crate::settings::ConfigIoError>,
) -> Result<Option<AppConfig>, crate::settings::ConfigIoError> {
let current_modified_at = modified_at(path);
if current_modified_at == *last_modified_at {
return Ok(None);
}

crate::settings::load_config(path).map_err(BackgroundError::Config)
let config = load(path)?;
*last_modified_at = current_modified_at;
Ok(Some(config))
}

fn modified_at(path: &Path) -> Option<SystemTime> {
Expand Down
47 changes: 47 additions & 0 deletions app-core-rust/src/background/security/outbound.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,53 @@ mod tests {
assert!(authorize().is_none());
}

/// Pending import recovery denies existing outbound authorizations and replacement reservations for every trigger.
#[test]
fn pending_import_blocks_sends_and_replacements() {
for trigger in [
TriggerKind::ManualShortcut,
TriggerKind::WordCount,
TriggerKind::Character,
TriggerKind::FinalFixBeforeReanchor,
] {
let fixture = Fixture::new();
fixture.database.app_rules().upsert(&allow_rule()).unwrap();
let authorize = fixture.authorize(trigger, Arc::new(AtomicBool::new(false)));
assert!(authorize().is_some());
let connection = rusqlite::Connection::open(&fixture.path).unwrap();
connection
.execute_batch(
"create table settings_import_recovery (id integer primary key);
insert into settings_import_recovery values (1)",
)
.unwrap();
assert!(authorize().is_none());
let mut request = triggers::manual(
1,
"",
"This is teh sentence.",
ContextVersions::default(),
&SelectionCapture::NoSelection,
&AppConfig::default(),
)
.unwrap();
request.trigger = trigger;
assert!(
super::super::SecurityGate::authorize_correction_replacement(
&request,
&AppConfig::default(),
&fixture.database,
&target()
)
.is_none()
);
connection
.execute("delete from settings_import_recovery", [])
.unwrap();
assert!(authorize().is_some());
}
}

/// Permission is read at every send, including changes to trigger and title rules.
#[test]
fn revocation_blocks_existing_authorizations_for_every_correction_trigger() {
Expand Down
85 changes: 84 additions & 1 deletion app-core-rust/src/background/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,82 @@ fn slow_input_worker_discards_stale_batches_at_queue_limit() {
worker.shutdown();
}

#[test]
fn config_write_during_reload_is_loaded_on_the_next_tick() {
let root = unique_temp_dir();
let path = root.join("settings.toml");
load_or_create_config(&path).unwrap();
let before = UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
let after = before + std::time::Duration::from_secs(10);
let set_modified = |time| {
fs::File::options()
.write(true)
.open(&path)
.unwrap()
.set_times(fs::FileTimes::new().set_modified(time))
.unwrap();
};
set_modified(before);
let mut last_modified_at = None;
let mut newer = AppConfig::default();
newer.triggers.word_count = 20;

let loaded = super::load_changed_config(&path, &mut last_modified_at, |path| {
let config = crate::settings::load_config(path)?;
crate::settings::save_config(path, &newer)?;
set_modified(after);
Ok(config)
})
.unwrap()
.unwrap();
assert_eq!(loaded.triggers.word_count, 10);
assert_eq!(last_modified_at, Some(before));

let loaded = super::load_changed_config(&path, &mut last_modified_at, |path| {
crate::settings::load_config(path)
})
.unwrap()
.unwrap();
assert_eq!(loaded, newer);
assert_eq!(last_modified_at, Some(after));
assert!(
super::load_changed_config(&path, &mut last_modified_at, |_| {
panic!("unchanged config must not be loaded")
})
.unwrap()
.is_none()
);
fs::remove_dir_all(root).unwrap();
}

#[test]
fn failed_config_reload_is_retried_without_another_write() {
let root = unique_temp_dir();
let path = root.join("settings.toml");
load_or_create_config(&path).unwrap();
let mut last_modified_at = None;

assert!(
super::load_changed_config(&path, &mut last_modified_at, |path| {
Err(crate::settings::ConfigIoError::Read {
path: path.into(),
source: std::io::Error::other("transient load failure"),
})
})
.is_err()
);
assert_eq!(last_modified_at, None);
assert!(
super::load_changed_config(&path, &mut last_modified_at, |path| {
crate::settings::load_config(path)
})
.unwrap()
.is_some()
);
assert_eq!(last_modified_at, super::modified_at(&path));
fs::remove_dir_all(root).unwrap();
}

#[test]
fn creates_default_config_when_missing() {
let root = unique_temp_dir();
Expand Down Expand Up @@ -526,7 +602,14 @@ fn background_runtime_respects_elevation_and_initializes_files() {
assert!(!root.exists());
}
Ok(()) => {
let runtime = result.unwrap();
let mut runtime = result.unwrap();
// Startup must retain the timestamp from before default-file creation.
assert_eq!(runtime.components.config_modified_at, None);
runtime.components.reload_shortcuts_if_config_changed();
assert_eq!(
runtime.components.config_modified_at,
super::modified_at(&config_path)
);
#[cfg(windows)]
assert_ne!(runtime.components.input_listener.hook_thread_id(), unsafe {
windows_sys::Win32::System::Threading::GetCurrentThreadId()
Expand Down
9 changes: 3 additions & 6 deletions app-core-rust/src/ipc/state.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{path::PathBuf, sync::Arc};

use crate::{
settings::{save_config, AppConfig, CorrectionEngine, CorrectionMode, ValidateConfig},
settings::{edit_config, AppConfig, CorrectionEngine, CorrectionMode},
storage::{AppRule, Database},
};

Expand Down Expand Up @@ -158,13 +158,10 @@ impl IpcServerState {
}

fn update_setting(&mut self, path: String, value: serde_json::Value) -> IpcResponse {
let mut next = self.config.clone();
let result = apply_setting(&mut next, &path, value)
.and_then(|_| next.validate().map_err(|error| error.to_string()))
.and_then(|_| save_config(&self.config_path, &next).map_err(|error| error.to_string()));
let result = edit_config(&self.config_path, |next| apply_setting(next, &path, value));

match result {
Ok(()) => {
Ok(next) => {
self.config = next;
IpcResponse::SettingUpdated(SettingUpdatedResponse { path })
}
Expand Down
21 changes: 21 additions & 0 deletions app-core-rust/src/ipc/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,27 @@ fn updates_any_valid_config_setting_by_path() {
assert_eq!(config.shortcuts.correct, "Ctrl+Shift+Space");
}

/// An IPC edit cannot replace a freshly imported setting with the server's earlier cached config.
#[test]
fn ipc_edits_preserve_external_imported_settings() {
let fixture = IpcFixture::start();
let mut config = AppConfig::default();
config.triggers.word_count = 22;
save_config(&fixture.config_path, &config).unwrap();
let response = send_request(
&fixture.pipe_path,
&IpcRequest::UpdateSetting(UpdateSettingRequest {
path: "shortcuts.correct".into(),
value: json!("Ctrl+Shift+Space"),
}),
)
.unwrap();
assert!(matches!(response, IpcResponse::SettingUpdated(_)));
let saved = crate::settings::load_config(&fixture.config_path).unwrap();
assert_eq!(saved.triggers.word_count, 22);
assert_eq!(saved.shortcuts.correct, "Ctrl+Shift+Space");
}

#[test]
fn reads_update_setting_requests_larger_than_initial_buffer() {
let fixture = IpcFixture::start();
Expand Down
Loading
Loading