From c2ed34344ce3ed061690e3f0326903e7f67bbe6b Mon Sep 17 00:00:00 2001 From: Hussein Ba Ragaa Date: Sun, 4 Oct 2026 06:58:19 +0300 Subject: [PATCH 1/6] feat(settings): complete WPF product pages --- README.md | 9 + ui/settings-ui-tests/AppRuleStorageTests.cs | 20 +- ui/settings-ui-tests/ConfigFormMapperTests.cs | 2 +- ui/settings-ui-tests/LogStorageTests.cs | 98 ++++++ .../MainWindowViewModel.ProductTests.cs | 284 ++++++++++++++++++ .../MainWindowViewModelTests.cs | 4 +- ui/settings-ui-tests/SettingsSkeletonTests.cs | 1 + .../WindowsCredentialApiKeyTests.cs | 78 +++++ ui/settings-ui/MainWindow.xaml | 72 ++++- ui/settings-ui/MainWindow.xaml.cs | 14 + ui/settings-ui/Models/MetadataLogItem.cs | 4 + ui/settings-ui/README.md | 38 +++ ui/settings-ui/Settings/AppRuleStorage.cs | 27 +- ui/settings-ui/Settings/IApiKeyStore.cs | 9 + ui/settings-ui/Settings/ISettingsConsent.cs | 19 ++ ui/settings-ui/Settings/LogStorage.cs | 75 +++++ .../Settings/WindowsCredentialApiKeyStatus.cs | 78 ++++- .../ViewModels/MainWindowViewModel.Config.cs | 32 +- .../ViewModels/MainWindowViewModel.Product.cs | 137 +++++++++ .../ViewModels/MainWindowViewModel.cs | 17 +- .../ViewModels/SettingsSectionViewModel.cs | 3 + ui/settings-ui/ViewModels/SettingsSkeleton.cs | 33 +- 22 files changed, 1019 insertions(+), 35 deletions(-) create mode 100644 ui/settings-ui-tests/LogStorageTests.cs create mode 100644 ui/settings-ui-tests/MainWindowViewModel.ProductTests.cs create mode 100644 ui/settings-ui-tests/WindowsCredentialApiKeyTests.cs create mode 100644 ui/settings-ui/Models/MetadataLogItem.cs create mode 100644 ui/settings-ui/Settings/IApiKeyStore.cs create mode 100644 ui/settings-ui/Settings/ISettingsConsent.cs create mode 100644 ui/settings-ui/Settings/LogStorage.cs create mode 100644 ui/settings-ui/ViewModels/MainWindowViewModel.Product.cs diff --git a/README.md b/README.md index f19352b..684ab16 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/ui/settings-ui-tests/AppRuleStorageTests.cs b/ui/settings-ui-tests/AppRuleStorageTests.cs index 681f5ac..4ba1bfc 100644 --- a/ui/settings-ui-tests/AppRuleStorageTests.cs +++ b/ui/settings-ui-tests/AppRuleStorageTests.cs @@ -8,6 +8,20 @@ namespace AutoFix.SettingsUi.Tests; [TestClass] public sealed class AppRuleStorageTests { + [TestMethod] + public void FirstOfflineLoadSeedsDefaultsOnlyOnceAndPreservesDeletedRules() + { + using var fixture = TempConfigFixture.Create(); + var storage = new AppRuleStorage(Path.Combine(fixture.Root, "autofix.sqlite")); + var rules = storage.List(); + Assert.IsTrue(rules.Any(r => r.SafetyMode == "terminal" && !r.ManualShortcutAllowed)); + Assert.IsTrue(rules.Any(r => r.SafetyMode == "code_editor" && !r.WordCountTriggerAllowed && !r.ProseContextAllowed)); + Assert.IsTrue(rules.Any(r => r.ProcessName == "Bitwarden.exe" && !r.LocalEngineAllowed && !r.ApiEngineAllowed)); + Assert.IsTrue(storage.Delete("code.exe", null)); + Assert.IsFalse(storage.List().Any(r => r.ProcessName == "code.exe")); + Assert.IsTrue(storage.ResetDefaults().Any(r => r.ProcessName == "code.exe")); + } + [DataTestMethod] [DataRow("", "auto", false)] [DataRow(",\"safety_mode\":null", "auto", false)] @@ -27,7 +41,7 @@ public void IpcSafetyFieldsRoundTripThroughStorage(string safetyFields, string e using var fixture = TempConfigFixture.Create(); var storage = new AppRuleStorage(Path.Combine(fixture.Root, "autofix.sqlite")); storage.Upsert(rule); - var saved = storage.List().Single(); + var saved = storage.List().Single(item => item.ProcessName == rule.ProcessName); Assert.AreEqual(expectedMode, saved.SafetyMode); Assert.AreEqual(expectedProse, saved.ProseContextAllowed); Assert.IsTrue(saved.ManualShortcutAllowed); @@ -72,8 +86,8 @@ public void UpsertListAndDeleteRoundTrip() var listed = storage.List(); Assert.IsTrue(listed.Any(item => item.ProcessName == "word.exe" && item.WindowTitlePattern == "*admin*")); - Assert.AreEqual("code_editor", listed[0].SafetyMode); - Assert.IsTrue(listed[0].ProseContextAllowed); + Assert.AreEqual("code_editor", listed.Single(item => item.ProcessName == "word.exe").SafetyMode); + Assert.IsTrue(listed.Single(item => item.ProcessName == "word.exe").ProseContextAllowed); Assert.IsTrue(storage.Delete("word.exe", "*admin*")); } diff --git a/ui/settings-ui-tests/ConfigFormMapperTests.cs b/ui/settings-ui-tests/ConfigFormMapperTests.cs index ae099fb..5729ef2 100644 --- a/ui/settings-ui-tests/ConfigFormMapperTests.cs +++ b/ui/settings-ui-tests/ConfigFormMapperTests.cs @@ -215,7 +215,7 @@ public void BuildConfigRejectsDuplicatePaths() public void BuildConfigRejectsMissingRequiredPath() { var sections = SettingsSkeleton.CreateSections(); - sections[0].Settings.Remove(Card(sections, "general.run_mode")); + sections.Single(section => section.Name == "App Rules").Settings.Remove(Card(sections, "general.run_mode")); var error = Assert.ThrowsException(() => ConfigFormMapper.BuildConfig(sections)); diff --git a/ui/settings-ui-tests/LogStorageTests.cs b/ui/settings-ui-tests/LogStorageTests.cs new file mode 100644 index 0000000..57bd4d7 --- /dev/null +++ b/ui/settings-ui-tests/LogStorageTests.cs @@ -0,0 +1,98 @@ +using AutoFix.SettingsUi.Settings; +using Microsoft.Data.Sqlite; + +namespace AutoFix.SettingsUi.Tests; + +[TestClass] +public sealed class LogStorageTests +{ + [TestMethod] + public void MissingLogsAreEmptyWithoutCreatingDatabase() + { + using var fixture = TempConfigFixture.Create(); + var path = Path.Combine(fixture.Root, "absent.sqlite"); + var storage = new LogStorage(path); + Assert.AreEqual(0, storage.List().Count); + storage.Clear(); + Assert.IsFalse(File.Exists(path)); + } + + [TestMethod] + public void ViewerIsBoundedAndMetadataOnlyAndClearKeepsProductData() + { + using var fixture = TempConfigFixture.Create(); + var path = Path.Combine(fixture.Root, "autofix.sqlite"); + var dictionary = new DictionaryStorage(path); + dictionary.Save(new() { Word = "AutoFix", Language = "und", Source = "dictionary" }); + var rules = new AppRuleStorage(path); rules.List(); + using var connection = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path }.ToString()); + connection.Open(); + using var command = connection.CreateCommand(); + command.CommandText = """ + create table correction_metadata (id integer primary key, occurred_at text default current_timestamp, + app_process_name text, trigger_type text, confidence_tier text, engine_used text, + replacement_method text, result_reason text, latency_ms integer); + create table debug_events (id integer primary key, message text, typed_text text); + insert into debug_events (message, typed_text) values ('private-debug-message', 'private-typed-text'); + with recursive n(x) as (select 1 union all select x + 1 from n where x < 505) + insert into correction_metadata (app_process_name, trigger_type, confidence_tier, engine_used, + replacement_method, result_reason, latency_ms) + select 'notepad.exe', 'manual', 'high', 'local', 'clipboard', 'applied', x from n; + """; + command.ExecuteNonQuery(); + var storage = new LogStorage(path); + var rows = storage.List(); + Assert.AreEqual(500, rows.Count); + Assert.AreEqual(505L, rows[0].LatencyMs); + Assert.AreEqual(6L, rows[^1].LatencyMs); + var json = System.Text.Json.JsonSerializer.Serialize(rows); + Assert.IsFalse(json.Contains("private-typed-text") || json.Contains("private-debug-message")); + storage.Clear(); + Assert.AreEqual(0, storage.List().Count); + command.CommandText = "select count(*) from debug_events"; + Assert.AreEqual(0L, command.ExecuteScalar()); + Assert.AreEqual(1, dictionary.List().Count); + Assert.IsTrue(rules.List().Any(r => r.ProcessName == "Bitwarden.exe")); + } + + [TestMethod] + public void ViewerReadsLegacyMetadataWithoutMigratingDatabase() + { + using var fixture = TempConfigFixture.Create(); + var path = Path.Combine(fixture.Root, "legacy.sqlite"); + using var connection = new SqliteConnection($"Data Source={path}"); + connection.Open(); + using var command = connection.CreateCommand(); + command.CommandText = """ + create table correction_metadata (id integer primary key, occurred_at text, + trigger_type text, confidence_tier text, engine_used text, + replacement_method text, result_reason text, latency_ms integer); + insert into correction_metadata values (1, '2026-10-04 00:00:00', 'manual', 'high', 'local', 'clipboard', 'applied', 20); + """; + command.ExecuteNonQuery(); + Assert.AreEqual("unknown", new LogStorage(path).List().Single().App); + command.CommandText = "select count(*) from pragma_table_info('correction_metadata') where name = 'app_process_name'"; + Assert.AreEqual(0L, command.ExecuteScalar()); + } + + [TestMethod] + public void ClearingLogsRollsBackBothTablesOnFailure() + { + using var fixture = TempConfigFixture.Create(); + var path = Path.Combine(fixture.Root, "autofix.sqlite"); + using var connection = new SqliteConnection($"Data Source={path}"); + connection.Open(); + using var command = connection.CreateCommand(); + command.CommandText = """ + create table correction_metadata (id integer primary key); + create table debug_events (id integer primary key); + insert into correction_metadata values (1); + insert into debug_events values (1); + create trigger fail_clear before delete on debug_events begin select raise(abort, 'busy'); end; + """; + command.ExecuteNonQuery(); + Assert.ThrowsException(() => new LogStorage(path).Clear()); + command.CommandText = "select count(*) from correction_metadata"; + Assert.AreEqual(1L, command.ExecuteScalar()); + } +} diff --git a/ui/settings-ui-tests/MainWindowViewModel.ProductTests.cs b/ui/settings-ui-tests/MainWindowViewModel.ProductTests.cs new file mode 100644 index 0000000..4ad89a2 --- /dev/null +++ b/ui/settings-ui-tests/MainWindowViewModel.ProductTests.cs @@ -0,0 +1,284 @@ +using System.Security; +using System.Windows; +using System.Windows.Controls; +using AutoFix.SettingsUi.Settings; +using AutoFix.SettingsUi.ViewModels; + +namespace AutoFix.SettingsUi.Tests; + +public sealed partial class MainWindowViewModelTests +{ + [TestMethod] + public async Task DebugConsentAndDependenciesSaveValidConfigs() + { + using var fixture = TempConfigFixture.Create(); + var consent = new FakeSettingsConsent(); + var vm = ProductViewModel(fixture, consent); + await vm.LoadSettingsAsync(); + Card(vm, "logging.full_text_debug_mode_enabled").IsEnabled = true; + Assert.AreEqual(1, consent.FullTextRequests); + Assert.IsFalse(Card(vm, "logging.full_text_debug_mode_enabled").IsEnabled); + Assert.IsFalse(fixture.Storage.Load(fixture.Path).Logging.FullTextDebugModeEnabled); + + Card(vm, "logging.redacted_debug_mode_enabled").IsEnabled = true; + await vm.SaveSettingsAsync(); + var saved = fixture.Storage.Load(fixture.Path).Logging; + Assert.IsTrue(saved.DebugModeEnabled && saved.RedactedDebugModeEnabled); + Assert.IsFalse(saved.FullTextDebugModeEnabled); + + consent.AllowFullText = true; + Card(vm, "logging.full_text_debug_mode_enabled").IsEnabled = true; + await vm.SaveSettingsAsync(); + saved = fixture.Storage.Load(fixture.Path).Logging; + Assert.IsTrue(saved.DebugModeEnabled && saved.FullTextDebugModeEnabled); + Assert.IsFalse(saved.RedactedDebugModeEnabled); + + Card(vm, "logging.debug_mode_enabled").IsEnabled = false; + await vm.SaveSettingsAsync(); + saved = fixture.Storage.Load(fixture.Path).Logging; + Assert.IsFalse(saved.DebugModeEnabled || saved.RedactedDebugModeEnabled || saved.FullTextDebugModeEnabled); + } + + [TestMethod] + public async Task ImportRequiresConsentBeforeEnablingFullTextAndKeepsAppRules() + { + using var fixture = TempConfigFixture.Create(); + var importedPath = Path.Combine(fixture.Root, "import.toml"); + var imported = AppConfig.Default(); + imported.Logging.DebugModeEnabled = true; + imported.Logging.FullTextDebugModeEnabled = true; + fixture.Storage.Export(importedPath, imported); + var consent = new FakeSettingsConsent(); + var ipc = new FakeBackgroundIpcClient(); + ipc.AppRules.Add(new("notepad.exe", null, "allowlist", true, false, false, true, false)); + var vm = new MainWindowViewModel(ipc, fixture.Storage, new AppRuleStorage(Path.Combine(fixture.Root, "autofix.sqlite")), + new ImportOnlyDialog(importedPath), new FakeApiKeyStore(), new FakeStartupRegistration(), consent); + await vm.LoadSettingsAsync(); + var before = File.ReadAllText(fixture.Path); + vm.ImportConfigCommand.Execute(null); + await WaitForAsync(() => consent.FullTextRequests == 1); + Assert.AreEqual(before, File.ReadAllText(fixture.Path)); + Assert.IsFalse(Card(vm, "logging.full_text_debug_mode_enabled").IsEnabled); + consent.AllowFullText = true; + vm.ImportConfigCommand.Execute(null); + await WaitForAsync(() => vm.StatusTitle == "Settings imported."); + Assert.IsTrue(fixture.Storage.Load(fixture.Path).Logging.FullTextDebugModeEnabled); + Assert.AreEqual("notepad.exe", vm.Sections.Single(s => s.ShowsAppRules).AppRules.Single().ProcessName); + } + + [TestMethod] + public async Task ProviderChangeClearsCustomEndpointAndKeysStayOutsideConfig() + { + using var fixture = TempConfigFixture.Create(); + var keys = new FakeApiKeyStore(); + var config = AppConfig.Default(); + config.Api.ProviderPreset = "custom"; + config.Api.BaseUrl = "https://example.com/v1"; + fixture.Storage.Save(config); + var vm = ProductViewModel(fixture, new FakeSettingsConsent(), keys); + await vm.LoadSettingsAsync(); + using var secret = new SecureString(); + foreach (var c in "dummy-key-must-not-export") secret.AppendChar(c); + vm.SaveApiKey(secret); + Assert.AreEqual("custom", keys.SavedProfile); + Assert.IsTrue(keys.Stored.Contains("custom")); + Assert.IsFalse(File.ReadAllText(fixture.Path).Contains("dummy-key-must-not-export")); + Card(vm, "api.provider_preset").SelectedValue = "groq"; + await vm.SaveSettingsAsync(); + Assert.IsNull(fixture.Storage.Load(fixture.Path).Api.BaseUrl); + StringAssert.Contains(vm.ApiKeyMessage, "No key saved for groq"); + vm.SaveApiKey(secret); + vm.DeleteApiKeyCommand.Execute(null); + Assert.IsFalse(keys.Stored.Contains("groq")); + Assert.IsTrue(keys.Stored.Contains("custom")); + } + + [TestMethod] + public async Task AppRuleDraftValidationAndTriggerPermissionsPersistThroughIpc() + { + using var fixture = TempConfigFixture.Create(); + var ipc = new FakeBackgroundIpcClient(); + var vm = new MainWindowViewModel(ipc, fixture.Storage, new AppRuleStorage(Path.Combine(fixture.Root, "autofix.sqlite")), + new NullConfigFileDialog(), new FakeApiKeyStore(), new FakeStartupRegistration(), new FakeSettingsConsent()); + await vm.LoadSettingsAsync(); + vm.NewAppProcess = @"C:\notes.exe"; + vm.AddAppRuleCommand.Execute(null); + Assert.AreEqual(0, ipc.UpsertedRules.Count); + vm.NewAppProcess = "notes.exe"; + vm.AddAppRuleCommand.Execute(null); + await WaitForAsync(() => ipc.UpsertedRules.Count == 1); + var rule = vm.SelectedAppRule!; + rule.ManualShortcutAllowed = true; + rule.WordCountTriggerAllowed = true; + rule.CharacterTriggerAllowed = true; + rule.ApiEngineAllowed = false; + await WaitForAsync(() => ipc.UpsertedRules.Count == 5); + var saved = ipc.UpsertedRules.Last(); + Assert.IsTrue(saved.ManualShortcutAllowed && saved.WordCountTriggerAllowed && saved.CharacterTriggerAllowed); + Assert.IsTrue(saved.LocalEngineAllowed); + Assert.IsFalse(saved.ApiEngineAllowed); + vm.NewAppProcess = "NOTES.EXE"; + vm.AddAppRuleCommand.Execute(null); + Assert.AreEqual(1, vm.Sections.Single(s => s.ShowsAppRules).AppRules.Count); + Assert.AreEqual(5, ipc.UpsertedRules.Count); + Card(vm, "general.run_mode").SelectedValue = "allowlist"; + await vm.SaveSettingsAsync(); + Assert.AreEqual("allowlist", fixture.Storage.Load(fixture.Path).General.RunMode); + } + + [TestMethod] + public async Task LanguageDefaultsAndOverridesRoundTripWithoutDuplicatePaths() + { + using var fixture = TempConfigFixture.Create(); + var vm = ProductViewModel(fixture, new FakeSettingsConsent()); + await vm.LoadSettingsAsync(); + StringAssert.Contains(vm.LanguageDetectionSummary, "Automatic"); + Card(vm, "correction.preferred_language").TextValue = "ar"; + Card(vm, "correction.app_language_overrides").TextValue = "notepad.exe=en-US, winword.exe=fr"; + Card(vm, "correction.mixed_language_policy").SelectedValue = "disable_correction"; + await vm.SaveSettingsAsync(); + var saved = fixture.Storage.Load(fixture.Path); + Assert.AreEqual("ar", saved.Correction.PreferredLanguage); + CollectionAssert.AreEqual(new[] { "notepad.exe=en-US", "winword.exe=fr" }, saved.Correction.AppLanguageOverrides); + vm.AutoDetectLanguageCommand.Execute(null); + await vm.SaveSettingsAsync(); + saved = fixture.Storage.Load(fixture.Path); + Assert.IsNull(saved.Correction.PreferredLanguage); + Assert.AreEqual(2, saved.Correction.AppLanguageOverrides.Count); + Assert.AreEqual("disable_correction", saved.Correction.MixedLanguagePolicy); + Assert.AreEqual("App Rules", vm.Sections.Single(s => s.Settings.Any(c => c.Path == "general.run_mode")).Name); + Card(vm, "correction.app_language_overrides").TextValue = "notepad.exe=bad_tag"; + await vm.SaveSettingsAsync(); + Assert.IsTrue(Card(vm, "correction.app_language_overrides").HasValidationError); + Assert.AreEqual(2, fixture.Storage.Load(fixture.Path).Correction.AppLanguageOverrides.Count); + } + + [TestMethod] + public void ProductPagesRenderAndKeyEditorClearsAcrossProfilesAndNavigation() + { + 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 dictionaries = new DictionaryStorage(Path.Combine(fixture.Root, "autofix.sqlite")); + dictionaries.Save(new() { Word = "AutoFix", Language = "und", Source = "dictionary" }); + dictionaries.Save(new() { Word = "projet secret", Language = "fr", App = "notepad.exe", Source = "dictionary" }); + var keys = new FakeApiKeyStore(); + var consent = new FakeSettingsConsent(); + var vm = ProductViewModel(fixture, consent, keys); + window = new MainWindow(vm) { ShowActivated = false, Left = -10000, Top = -10000, Width = 1080, Height = 720 }; + window.Show(); Pump(); + var scroll = (ScrollViewer)window.FindName("SettingsScrollViewer"); + foreach (var name in new[] { "App Rules", "Dictionary", "Engines", "Logs / Debug", "Languages" }) + { + vm.SelectedSection = vm.Sections.Single(s => s.Name == name); + Pump(); scroll.ScrollToTop(); Pump(); + Assert.IsTrue(Descendants(window).OfType().Any(b => b.IsVisible)); + SavePreview(window, name, "top"); + scroll.ScrollToBottom(); Pump(); + SavePreview(window, name, "bottom"); + } + vm.SelectedSection = vm.Sections.Single(s => s.ShowsEngines); Pump(); scroll.ScrollToBottom(); Pump(); + var password = (PasswordBox)window.FindName("ApiKeyBox"); + Assert.IsTrue(password.IsVisible); + password.Password = "test-key"; + Descendants(window).OfType