Free, open-source Windows optimization tool for performance, privacy, and simplicity.
C# csharpdebloatdotnetgamingopen-sourceoptimizationoptimizeroptimizerduckperformanceprivacytweakertweakswindowswinui
feat: add async registry ops, tests, and UI/perf improvements
fatDuck37b5f1f042a9
diff --git a/optimizerDuck.Test/Domain/Features/BaseFeatureTests.cs b/optimizerDuck.Test/Domain/Features/BaseFeatureTests.csnew file mode 100644index 0000000..9a093ff--- /dev/null+++ b/optimizerDuck.Test/Domain/Features/BaseFeatureTests.cs@@ -0,0 +1,139 @@+using System.Collections.ObjectModel;+using System.Threading.Channels;+using System.Threading.Tasks;+using Microsoft.Extensions.Logging;+using Microsoft.Win32;+using optimizerDuck.Domain.Features.Models;+using optimizerDuck.Domain.Optimizations.Models.Services;+using optimizerDuck.Services.OptimizationServices;+using Xunit;++namespace optimizerDuck.Test.Domain.Features;++public class BaseFeatureTests : IDisposable+{+ private const string TestKeyPath = @"HKCU\Software\TestOptimizerDuckFeatures";++ private class TestFeature : BaseFeature+ {+ // FeatureKey is not virtual, so we don't override it+ // The test will use the actual class name++ protected override IEnumerable<RegistryToggle> RegistryToggles =>+ [+ new()+ {+ Path = TestKeyPath,+ Name = "TestValue",+ OnValue = 1,+ OffValue = 0,+ ValueKind = RegistryValueKind.DWord,+ },+ ];+ }++ public BaseFeatureTests()+ {+ CleanupTestKeys();+ }++ public void Dispose()+ {+ CleanupTestKeys();+ }++ private static void CleanupTestKeys()+ {+ try+ {+ using var hkcu = Registry.CurrentUser;+ hkcu.DeleteSubKeyTree(@"Software\TestOptimizerDuckFeatures", false);+ }+ catch+ {+ // Ignore if it doesn't exist+ }+ }++ [Fact]+ public async Task EnableAsync_WritesCorrectValueToRegistry()+ {+ var feature = new TestFeature { OwnerType = typeof(TestFeature) };++ await feature.EnableAsync();++ var value = RegistryService.Read<int>(new RegistryItem(TestKeyPath, "TestValue"));+ Assert.Equal(1, value);+ }++ [Fact]+ public async Task DisableAsync_WritesCorrectValueToRegistry()+ {+ var feature = new TestFeature { OwnerType = typeof(TestFeature) };++ await feature.DisableAsync();++ var value = RegistryService.Read<int>(new RegistryItem(TestKeyPath, "TestValue"));+ Assert.Equal(0, value);+ }++ [Fact]+ public async Task GetStateAsync_ReturnsCorrectState()+ {+ var feature = new TestFeature { OwnerType = typeof(TestFeature) };++ // Initially should be false (value doesn't exist)+ var initialState = await feature.GetStateAsync();+ Assert.False(initialState);++ // Enable+ await feature.EnableAsync();+ var enabledState = await feature.GetStateAsync();+ Assert.True(enabledState);++ // Disable+ await feature.DisableAsync();+ var disabledState = await feature.GetStateAsync();+ Assert.False(disabledState);+ }++ [Fact]+ public async Task ToggleOperations_DoesNotBlockCallingThread()+ {+ var feature = new TestFeature { OwnerType = typeof(TestFeature) };++ // Measure time - should be fast since it's offloaded to thread pool+ var stopwatch = System.Diagnostics.Stopwatch.StartNew();++ await feature.EnableAsync();+ await feature.DisableAsync();++ stopwatch.Stop();++ // Should complete quickly (not blocking on UI thread equivalent)+ Assert.True(stopwatch.ElapsedMilliseconds < 1000,+ $"Operations took {stopwatch.ElapsedMilliseconds}ms, expected < 1000ms");+ }++ [Fact]+ public async Task MultipleToggles_ExecutesSequentiallyWithoutCorruption()+ {+ var feature = new TestFeature { OwnerType = typeof(TestFeature) };++ // Perform multiple rapid toggles+ for (int i = 0; i < 10; i++)+ {+ await feature.EnableAsync();+ var enabledValue = RegistryService.Read<int>(new RegistryItem(TestKeyPath, "TestValue"));+ Assert.Equal(1, enabledValue);++ await feature.DisableAsync();+ var disabledValue = RegistryService.Read<int>(new RegistryItem(TestKeyPath, "TestValue"));+ Assert.Equal(0, disabledValue);+ }++ // Final state should be disabled+ var finalState = await feature.GetStateAsync();+ Assert.False(finalState);+ }+}diff --git a/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs b/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.csnew file mode 100644index 0000000..db3c4f2--- /dev/null+++ b/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs@@ -0,0 +1,249 @@+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using System.Threading.Tasks;+using Microsoft.Extensions.Logging;+using Microsoft.Extensions.Logging.Abstractions;+using Newtonsoft.Json.Linq;+using optimizerDuck.Common.Helpers;+using optimizerDuck.Domain.Abstractions;+using optimizerDuck.Domain.Execution;+using optimizerDuck.Domain.Optimizations.Models;+using optimizerDuck.Domain.Revert;+using optimizerDuck.Domain.UI;+using optimizerDuck.Services;+using optimizerDuck.Services.Managers;+using Xunit;++namespace optimizerDuck.Test.Services;++public class OptimizationServiceIntegrationTests : IDisposable+{+ private class PartialFailureOptimization : IOptimization+ {+ private int _stepCount;+ private readonly bool _shouldFail;++ public Guid Id { get; } = Guid.NewGuid();+ public OptimizationRisk Risk => OptimizationRisk.Safe;+ public string OptimizationKey => "PartialFailureTest";+ public string Name => "Partial Failure Test";+ public string ShortDescription => "Tests partial failure scenarios";+ public OptimizationState State { get; set; } = new();++ public PartialFailureOptimization(bool shouldFail = false)+ {+ _shouldFail = shouldFail;+ }++ public Task<ApplyResult> ApplyAsync(+ IProgress<ProcessingProgress> progress,+ OptimizationContext context+ )+ {+ var results = new List<OperationStepResult>();+ _stepCount = 0;++ // Step 1: Always succeeds+ ExecutionScope.RecordStep(+ "Test",+ "Step 1",+ true,+ new TestRevertStep { StepId = 1 }+ );+ _stepCount++;++ // Step 2: May fail+ if (_shouldFail)+ {+ ExecutionScope.RecordStep(+ "Test",+ "Step 2",+ false,+ null,+ "Simulated failure"+ );+ _stepCount++;+ }++ // Step 3: Only executes if step 2 succeeded+ if (!_shouldFail)+ {+ ExecutionScope.RecordStep(+ "Test",+ "Step 3",+ true,+ new TestRevertStep { StepId = 3 }+ );+ _stepCount++;+ }++ var success = !_shouldFail;+ return Task.FromResult(+ success+ ? ApplyResult.True()+ : ApplyResult.False("Step 2 failed intentionally")+ );+ }+ }++ private class TestRevertStep : IRevertStep+ {+ public int StepId { get; init; }+ public string Type => "Test";+ public string Description => $"Revert step {StepId}";++ public Task<bool> ExecuteAsync()+ {+ // Simulate revert operation+ return Task.FromResult(true);+ }++ public JObject ToData()+ {+ return new JObject { ["StepId"] = StepId };+ }+ }++ public OptimizationServiceIntegrationTests()+ {+ // Ensure clean revert directory+ if (Directory.Exists(Shared.RevertDirectory))+ {+ foreach (var file in Directory.GetFiles(Shared.RevertDirectory))+ {+ try+ {+ File.Delete(file);+ }+ catch+ {+ // Ignore+ }+ }+ }+ }++ public void Dispose()+ {+ // Clean up test files+ if (Directory.Exists(Shared.RevertDirectory))+ {+ foreach (var file in Directory.GetFiles(Shared.RevertDirectory))+ {+ try+ {+ File.Delete(file);+ }+ catch+ {+ // Ignore+ }+ }+ }+ }++ [Fact]+ public async Task ApplyAsync_WithSuccess_SavesRevertDataCorrectly()+ {+ var loggerFactory = NullLoggerFactory.Instance;+ var revertManager = new RevertManager(NullLogger<RevertManager>.Instance, loggerFactory);+ var systemInfoService = new SystemInfoService(NullLogger<SystemInfoService>.Instance);+ var streamService = new StreamService(NullLogger<StreamService>.Instance);++ var optimizationService = new OptimizationService(+ revertManager,+ loggerFactory,+ systemInfoService,+ streamService,+ null!,+ NullLogger<OptimizationService>.Instance+ );++ var optimization = new PartialFailureOptimization(shouldFail: false);+ var progress = new Progress<ProcessingProgress>();++ var result = await optimizationService.ApplyAsync(optimization, progress);++ Assert.Equal(OptimizationSuccessResult.Success, result.Status);++ // Verify revert data was saved+ var revertData = await RevertManager.GetRevertDataAsync(optimization.Id);+ Assert.NotNull(revertData);+ Assert.Equal(2, revertData.Steps.Count); // 2 successful steps+ }++ [Fact]+ public async Task UpdateOptimizationStateAsync_WithMissingData_HandlesGracefully()+ {+ var optimizations = new IOptimization[]+ {+ new PartialFailureOptimization(shouldFail: false),+ new PartialFailureOptimization(shouldFail: true),+ };++ // These optimizations have never been applied, so no revert data exists+ await OptimizationService.UpdateOptimizationStateAsync(optimizations);++ // All should be marked as not applied+ Assert.False(optimizations[0].State.IsApplied);+ Assert.False(optimizations[1].State.IsApplied);+ }++ [Fact]+ public async Task RetryFailedStepsAsync_WithRetryableSteps_Succeeds()+ {+ var failedSteps = new List<OperationStepResult>+ {+ new()+ {+ Index = 1,+ Name = "Test",+ Description = "Failed step",+ Success = false,+ Error = "Temporary failure",+ RetryAction = () => Task.FromResult(true),+ },+ };++ var logger = NullLogger.Instance;+ var recoveredSteps = await OptimizationService.RetryFailedStepsAsync(+ failedSteps,+ false,+ logger,+ null+ );++ // Should succeed on retry+ Assert.Empty(recoveredSteps);+ }++ [Fact]+ public async Task RetryFailedStepsAsync_WithNonRetryableSteps_RemainsFailed()+ {+ var failedSteps = new List<OperationStepResult>+ {+ new()+ {+ Index = 1,+ Name = "Test",+ Description = "Failed step",+ Success = false,+ Error = "Permanent failure",+ RetryAction = null, // No retry action+ },+ };++ var logger = NullLogger.Instance;+ var remainingFailed = await OptimizationService.RetryFailedStepsAsync(+ failedSteps,+ false,+ logger,+ null+ );++ // Should remain failed+ Assert.Single(remainingFailed);+ }+}diff --git a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.csindex 07e122b..4419006 100644--- a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs+++ b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs@@ -212,4 +212,160 @@ public class RegistryServiceTests : IDisposableAssert.False(RegistryService.KeyExists(new RegistryItem(keyPathB)));Assert.False(RegistryService.KeyExists(new RegistryItem(keyPathA)));}++ [Fact]+ public async Task MultiStepRegistryOperation_PartialFailure_RollbackRestoresOriginalState()+ {+ // Test scenario: Multiple registry writes where one fails+ var key1 = $@"{BaseTestKey}\MultiStepTest1";+ var key2 = $@"{BaseTestKey}\MultiStepTest2";+ var key3 = $@"{BaseTestKey}\MultiStepTest3";++ // Write initial values+ Assert.True(RegistryService.Write(new RegistryItem(key1, "Value", "Initial1")));+ Assert.True(RegistryService.Write(new RegistryItem(key2, "Value", "Initial2")));+ Assert.True(RegistryService.Write(new RegistryItem(key3, "Value", "Initial3")));++ // Dispose old scope and create new one to capture new operations+ _scope.Dispose();+ using var newScope = ExecutionScope.Begin(new DummyOptimization(), NullLogger.Instance);++ // Perform multi-step operation+ Assert.True(RegistryService.Write(new RegistryItem(key1, "Value", "Updated1")));+ Assert.True(RegistryService.Write(new RegistryItem(key2, "Value", "Updated2")));++ // Simulate a failure by not writing to key3+ // In real scenario, this would be caught by transaction logic++ // Get all revert steps+ var revertSteps = newScope.ExecutedSteps+ .Where(s => s.RevertStep != null)+ .Select(s => s.RevertStep!)+ .ToList();++ // Revert all steps in reverse order+ foreach (var step in revertSteps.AsEnumerable().Reverse())+ {+ Assert.True(await step.ExecuteAsync());+ }++ // Verify original state is restored+ Assert.Equal("Initial1", RegistryService.Read<string>(new RegistryItem(key1, "Value")));+ Assert.Equal("Initial2", RegistryService.Read<string>(new RegistryItem(key2, "Value")));+ Assert.Equal("Initial3", RegistryService.Read<string>(new RegistryItem(key3, "Value")));+ }++ [Fact]+ public async Task ConcurrentRegistryOperations_DoesNotCauseCorruption()+ {+ // Test scenario: Concurrent writes to different keys+ var tasks = new List<Task>();+ const int concurrentOps = 10;++ for (int i = 0; i < concurrentOps; i++)+ {+ var key = $@"{BaseTestKey}\ConcurrentTest{i}";+ var value = $"Value{i}";++ tasks.Add(Task.Run(() =>+ {+ Assert.True(RegistryService.Write(new RegistryItem(key, "Value", value)));+ var read = RegistryService.Read<string>(new RegistryItem(key, "Value"));+ Assert.Equal(value, read);+ }));+ }++ await Task.WhenAll(tasks);++ // Verify all writes succeeded+ for (int i = 0; i < concurrentOps; i++)+ {+ var key = $@"{BaseTestKey}\ConcurrentTest{i}";+ var expectedValue = $"Value{i}";+ var actualValue = RegistryService.Read<string>(new RegistryItem(key, "Value"));+ Assert.Equal(expectedValue, actualValue);+ }+ }++ [Fact]+ public async Task RegistryValueKindConversion_HandlesAllTypesCorrectly()+ {+ var key = $@"{BaseTestKey}\TypeConversionTest";++ // Test different value types+ Assert.True(RegistryService.Write(new RegistryItem(key, "DWordValue", 42, RegistryValueKind.DWord)));+ Assert.Equal(42, RegistryService.Read<int>(new RegistryItem(key, "DWordValue")));++ Assert.True(RegistryService.Write(new RegistryItem(key, "QWordValue", 9999999999L, RegistryValueKind.QWord)));+ Assert.Equal(9999999999L, RegistryService.Read<long>(new RegistryItem(key, "QWordValue")));++ Assert.True(RegistryService.Write(new RegistryItem(key, "StringValue", "TestString", RegistryValueKind.String)));+ Assert.Equal("TestString", RegistryService.Read<string>(new RegistryItem(key, "StringValue")));++ var multiString = new[] { "Line1", "Line2", "Line3" };+ Assert.True(RegistryService.Write(new RegistryItem(key, "MultiStringValue", multiString, RegistryValueKind.MultiString)));+ var readMulti = RegistryService.Read<string[]>(new RegistryItem(key, "MultiStringValue"));+ Assert.Equal(multiString, readMulti);+ }++ [Fact]+ public async Task RevertStepWithSubSteps_ExecutesInCorrectOrder()+ {+ // Test that nested revert steps execute in the correct order+ var key1 = $@"{BaseTestKey}\SubStepTest\Key1";+ var key2 = $@"{BaseTestKey}\SubStepTest\Key2";++ Assert.True(RegistryService.Write(new RegistryItem(key1, "Value", "Original1")));+ Assert.True(RegistryService.Write(new RegistryItem(key2, "Value", "Original2")));++ // Dispose old scope and create new one to capture new operations+ _scope.Dispose();+ using var newScope = ExecutionScope.Begin(new DummyOptimization(), NullLogger.Instance);++ // Perform operations+ Assert.True(RegistryService.Write(new RegistryItem(key1, "Value", "Modified1")));+ Assert.True(RegistryService.Write(new RegistryItem(key2, "Value", "Modified2")));++ // Revert in reverse order (LIFO)+ var revertSteps = newScope.ExecutedSteps+ .Where(s => s.RevertStep != null)+ .Select(s => s.RevertStep!)+ .ToList();++ var executionOrder = new List<string>();+ foreach (var step in revertSteps.AsEnumerable().Reverse())+ {+ var desc = step.Description;+ executionOrder.Add(desc);+ Assert.True(await step.ExecuteAsync());+ }++ // Verify state is restored+ Assert.Equal("Original1", RegistryService.Read<string>(new RegistryItem(key1, "Value")));+ Assert.Equal("Original2", RegistryService.Read<string>(new RegistryItem(key2, "Value")));+ }++ [Fact]+ public void CleanupEmptyKeys_RemovesOnlyEmptyKeys()+ {+ var emptyKeyPath = $@"{BaseTestKey}\CleanupTest\EmptyKey";+ var nonEmptyKeyPath = $@"{BaseTestKey}\CleanupTest\NonEmptyKey";++ // Create empty key+ Assert.True(RegistryService.CreateSubKey(new RegistryItem(emptyKeyPath)));++ // Create non-empty key+ Assert.True(RegistryService.CreateSubKey(new RegistryItem(nonEmptyKeyPath)));+ Assert.True(RegistryService.Write(new RegistryItem(nonEmptyKeyPath, "Value", "SomeValue")));++ // Cleanup+ RegistryService.CleanupEmptyKeys(new[] { emptyKeyPath, nonEmptyKeyPath });++ // Empty key should be removed+ Assert.False(RegistryService.KeyExists(new RegistryItem(emptyKeyPath)));++ // Non-empty key should remain+ Assert.True(RegistryService.KeyExists(new RegistryItem(nonEmptyKeyPath)));+ Assert.Equal("SomeValue", RegistryService.Read<string>(new RegistryItem(nonEmptyKeyPath, "Value")));+ }}diff --git a/optimizerDuck/App.xaml.cs b/optimizerDuck/App.xaml.csindex 1654015..85a9e05 100644--- a/optimizerDuck/App.xaml.cs+++ b/optimizerDuck/App.xaml.cs@@ -54,7 +54,7 @@ public class ScopeBlockTextFormatter : ITextFormatter};//var prefix = $"{timestamp} | {ctx,-67} | {levelText,-7} | "; // byebye 67 char SourceContext truncation, we have a new design now...- var prefix = $"{timestamp} | {ctx, -35} | {levelText, -7} | ";+ var prefix = $"{timestamp} | {ctx,-35} | {levelText,-7} | ";// print messageoutput.WriteLine(prefix + RenderWithoutQuotes(logEvent));@@ -119,26 +119,39 @@ public partial class App : Applicationpublic bool HasPendingChanges { get; set; }- protected override async void OnStartup(StartupEventArgs e)+ protected override void OnStartup(StartupEventArgs e){base.OnStartup(e);- try- {- await OnStartupAsync(e);- }- catch (Exception ex)+ // Run initialization in a background task to keep UI responsive if needed,+ // but since we need the MainWindow to show, we'll await the async part.+ _ = Task.Run(async () =>{try{- Log.Logger?.Fatal(ex, "Fatal error during startup");- await Log.CloseAndFlushAsync();+ await OnStartupAsync(e);}- catch+ catch (Exception ex){- // ignore logging failures during fatal startup handling+ await HandleStartupErrorAsync(ex);}+ });+ }+ private async Task HandleStartupErrorAsync(Exception ex)+ {+ try+ {+ Log.Logger?.Fatal(ex, "Fatal error during startup");+ await Log.CloseAndFlushAsync();+ }+ catch+ {+ // ignore logging failures during fatal startup handling+ }++ Dispatcher.Invoke(() =>+ {System.Windows.MessageBox.Show($"Failed to start optimizerDuck.{Environment.NewLine}{Environment.NewLine}{ex.Message}","optimizerDuck",@@ -146,7 +159,7 @@ public partial class App : ApplicationMessageBoxImage.Error);Shutdown(-1);- }+ });}private async Task OnStartupAsync(StartupEventArgs e)@@ -239,11 +252,11 @@ public partial class App : Application).Build();- await _host.StartAsync().ConfigureAwait(false);+ await _host.StartAsync();var config = _host.Services.GetRequiredService<ConfigManager>();- await config.InitializeAsync().ConfigureAwait(false);- await config.EnsureDefaultsAsync().ConfigureAwait(false);+ await config.InitializeAsync();+ await config.EnsureDefaultsAsync();var appOptionsMonitor = _host.Services.GetRequiredService<IOptionsMonitor<AppSettings>>();@@ -255,7 +268,10 @@ public partial class App : Applicationvar appSettings = appOptionsMonitor.CurrentValue;- Loc.Instance.ChangeCulture(new CultureInfo(appSettings.App.Language));+ await Dispatcher.InvokeAsync(() =>+ {+ Loc.Instance.ChangeCulture(new CultureInfo(appSettings.App.Language));+ });_logger = _host.Services.GetRequiredService<ILogger<App>>();_logger.LogInformation(@@ -267,9 +283,8 @@ public partial class App : Applicationvar optimizationRegistry = _host.Services.GetRequiredService<OptimizationRegistry>();_logger.LogInformation("Preloading optimizations...");- await optimizationRegistry.PreloadOptimizations().ConfigureAwait(false);+ await optimizationRegistry.PreloadOptimizationsAsync();- // Apply custom accent colors and theme on UI threadawait Dispatcher.InvokeAsync(() =>{ApplicationAccentColorManager.Apply(@@ -320,20 +335,20 @@ public partial class App : Applicationprotected async void MainWindow_Closing(object? sender, CancelEventArgs e){- if (_allowClose)+ try{- return;- }+ if (_allowClose)+ {+ return;+ }- if (!HasPendingChanges)- {- return;- }+ if (!HasPendingChanges)+ {+ return;+ }- e.Cancel = true;+ e.Cancel = true;- try- {_contentDialogService ??= _host!.Services.GetRequiredService<IContentDialogService>();var result = await _contentDialogService.ShowSimpleDialogAsync(@@ -374,10 +389,11 @@ public partial class App : Application}catch (Exception ex){- _logger.LogError(ex, "Failed to show pending changes dialog.");+ _logger.LogError(ex, "Failed to handle window closing event. Allowing close to prevent hanging.");+ // Ensure we don't block close on error_allowClose = true;- Current.Shutdown();+ e.Cancel = false;}}}diff --git a/optimizerDuck/Common/Converters/ProgressBarVisibilityConverter.cs b/optimizerDuck/Common/Converters/ProgressBarVisibilityConverter.csnew file mode 100644index 0000000..3fbe215--- /dev/null+++ b/optimizerDuck/Common/Converters/ProgressBarVisibilityConverter.cs@@ -0,0 +1,40 @@+using System.Globalization;+using System.Windows;+using System.Windows.Data;++namespace optimizerDuck.Common.Converters;++public class ProgressBarVisibilityConverter : IMultiValueConverter+{+ public object Convert(+ object[] values,+ Type targetType,+ object parameter,+ CultureInfo culture)+ {+ if (values.Length < 2)+ return Visibility.Collapsed;++ var total = 0d;+ var isIndeterminate = false;++ if (values[0] is IConvertible convertible)+ total = convertible.ToDouble(culture);++ if (values[1] is bool b)+ isIndeterminate = b;++ return total > 0 || isIndeterminate+ ? Visibility.Visible+ : Visibility.Collapsed;+ }++ public object[] ConvertBack(+ object value,+ Type[] targetTypes,+ object parameter,+ CultureInfo culture)+ {+ throw new NotSupportedException();+ }+}diff --git a/optimizerDuck/Common/Helpers/ReflectionHelper.cs b/optimizerDuck/Common/Helpers/ReflectionHelper.csindex 2d0a9de..6c8c2fc 100644--- a/optimizerDuck/Common/Helpers/ReflectionHelper.cs+++ b/optimizerDuck/Common/Helpers/ReflectionHelper.cs@@ -1,4 +1,4 @@-using System.Reflection;+using System.Reflection;namespace optimizerDuck.Common.Helpers;@@ -21,17 +21,36 @@ public static class ReflectionHelper}}+ private static readonly Dictionary<Type, List<Type>> _implementationCache = new();+ private static readonly object _cacheLock = new();+public static IEnumerable<Type> FindImplementationsInLoadedAssemblies(Type interfaceType){- return AppDomain- .CurrentDomain.GetAssemblies()- .SelectMany(SafeGetTypes)- .Where(t =>- t != interfaceType- && t is { IsClass: true, IsAbstract: false }- && interfaceType.IsAssignableFrom(t)- )- .ToList();+ lock (_cacheLock)+ {+ if (_implementationCache.TryGetValue(interfaceType, out var cached))+ return cached;++ var types = AppDomain+ .CurrentDomain.GetAssemblies()+ .Where(a =>+ a.FullName != null+ && a.FullName.StartsWith(+ nameof(optimizerDuck),+ StringComparison.OrdinalIgnoreCase+ )+ )+ .SelectMany(SafeGetTypes)+ .Where(t =>+ t != interfaceType+ && t is { IsClass: true, IsAbstract: false }+ && interfaceType.IsAssignableFrom(t)+ )+ .ToList();++ _implementationCache[interfaceType] = types;+ return types;+ }}public static IEnumerable<Type> FindImplementationsInLoadedAssemblies<TInterface>()diff --git a/optimizerDuck/Domain/Features/Models/BaseFeature.cs b/optimizerDuck/Domain/Features/Models/BaseFeature.csindex a2c5b4f..cf2c58f 100644--- a/optimizerDuck/Domain/Features/Models/BaseFeature.cs+++ b/optimizerDuck/Domain/Features/Models/BaseFeature.cs@@ -1,4 +1,4 @@-using System.Reflection;+using System.Reflection;using optimizerDuck.Domain.Abstractions;using optimizerDuck.Domain.Attributes;using optimizerDuck.Services.Managers;@@ -73,7 +73,7 @@ public abstract class BaseFeature : IFeaturepublic virtual async Task EnableAsync(){- await SetTogglesState(true);+ await SetTogglesStateAsync(true);if (NeedsPostAction)await ExecutePostActionAsync();@@ -81,24 +81,24 @@ public abstract class BaseFeature : IFeaturepublic virtual async Task DisableAsync(){- await SetTogglesState(false);+ await SetTogglesStateAsync(false);if (NeedsPostAction)await ExecutePostActionAsync();}- protected virtual Task ExecutePostActionAsync()+ protected virtual async Task ExecutePostActionAsync(){// Default post-action: Restart Explorer- ShellService.CMD("taskkill /f /im explorer.exe & start explorer.exe");- return Task.CompletedTask;+ await ShellService.CMDAsync("taskkill /f /im explorer.exe & start explorer.exe");}- private Task SetTogglesState(bool isOn)+ private Task SetTogglesStateAsync(bool isOn){- foreach (var toggle in RegistryToggles)- toggle.SetState(isOn);-- return Task.CompletedTask;+ return Task.Run(() =>+ {+ foreach (var toggle in RegistryToggles)+ toggle.SetState(isOn);+ });}}diff --git a/optimizerDuck/Domain/Optimizations/Models/ApplyResult.cs b/optimizerDuck/Domain/Optimizations/Models/ApplyResult.csindex bfe9d00..1653ea2 100644--- a/optimizerDuck/Domain/Optimizations/Models/ApplyResult.cs+++ b/optimizerDuck/Domain/Optimizations/Models/ApplyResult.cs@@ -1,4 +1,4 @@-namespace optimizerDuck.Domain.Optimizations.Models;+namespace optimizerDuck.Domain.Optimizations.Models;/// <summary>/// Represents the result of applying a single optimization step.@@ -8,7 +8,7 @@ public readonly record struct ApplyResult/// <summary>/// The error message if the step failed; <c>null</c> if successful./// </summary>- public string? Message { get; init; }+ public string? ErrorMessage { get; init; }/// <summary>/// Creates a successful result.@@ -16,7 +16,7 @@ public readonly record struct ApplyResult/// <returns>An <see cref="ApplyResult" /> with no error message.</returns>public static ApplyResult True(){- return new ApplyResult { Message = null };+ return new ApplyResult { ErrorMessage = null };}/// <summary>@@ -26,6 +26,6 @@ public readonly record struct ApplyResult/// <returns>An <see cref="ApplyResult" /> containing the error message.</returns>public static ApplyResult False(string message){- return new ApplyResult { Message = message };+ return new ApplyResult { ErrorMessage = message };}}diff --git a/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.csindex a18dca5..8c99767 100644--- a/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs@@ -1,4 +1,4 @@-using Microsoft.Win32;+using Microsoft.Win32;using Newtonsoft.Json.Linq;using optimizerDuck.Domain.Abstractions;using optimizerDuck.Domain.Optimizations.Models.Services;@@ -80,7 +80,7 @@ public class RegistryRevertStep : IRevertStep};/// <inheritdoc />- public Task<bool> ExecuteAsync()+ public async Task<bool> ExecuteAsync(){var result = Action switch{@@ -96,7 +96,7 @@ public class RegistryRevertStep : IRevertStepRevertAction.DeleteKey => RegistryService.DeleteSubKeyTree(new RegistryItem(Path)),- RevertAction.RestoreKeyTree => ExecuteSubSteps(),+ RevertAction.RestoreKeyTree => await ExecuteSubStepsAsync(),_ => false,};@@ -108,7 +108,7 @@ public class RegistryRevertStep : IRevertStepif (result && CreatedSubKeys?.Count > 0)RegistryService.CleanupEmptyKeys(CreatedSubKeys);- return Task.FromResult(result);+ return result;}/// <inheritdoc />@@ -238,14 +238,13 @@ public class RegistryRevertStep : IRevertStep};}- private bool ExecuteSubSteps()+ private async Task<bool> ExecuteSubStepsAsync(){if (SubSteps == null)return true;foreach (var step in SubSteps){- // Run synchronously to ensure correct nested tree creation order- if (!step.ExecuteAsync().GetAwaiter().GetResult())+ if (!await step.ExecuteAsync())return false;}return true;diff --git a/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.csindex c6d4a55..e81af9d 100644--- a/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs@@ -33,16 +33,13 @@ public class ScheduledTaskRevertStep : IRevertStep);/// <inheritdoc />- public async Task<bool> ExecuteAsync()+ public Task<bool> ExecuteAsync(){- return await Task.Run(() =>- {- if (OriginalEnabled)- ScheduledTaskService.EnableTask(FullPath);- else- ScheduledTaskService.DisableTask(FullPath);- return true;- });+ if (OriginalEnabled)+ ScheduledTaskService.EnableTask(FullPath);+ else+ ScheduledTaskService.DisableTask(FullPath);+ return Task.FromResult(true);}/// <inheritdoc />diff --git a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.csindex a751896..ff7b8a8 100644--- a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs@@ -33,23 +33,20 @@ public class ServiceRevertStep : IRevertStep);/// <inheritdoc />- public async Task<bool> ExecuteAsync()+ public Task<bool> ExecuteAsync(){- return await Task.Run(() =>- {- var result = ServiceProcessService.ChangeServiceStartupType(- new ServiceItem { Name = ServiceName, StartupType = OriginalStartupType }- );+ var result = ServiceProcessService.ChangeServiceStartupType(+ new ServiceItem { Name = ServiceName, StartupType = OriginalStartupType }+ );- if (!result)- throw new Exception(- string.Format(- Translations.Service_Service_Error_UpdateRegistryForStartupTypeFailed- )- );+ if (!result)+ throw new Exception(+ string.Format(+ Translations.Service_Service_Error_UpdateRegistryForStartupTypeFailed+ )+ );- return result;- });+ return Task.FromResult(result);}/// <inheritdoc />diff --git a/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.csindex 0c7c700..927ceb9 100644--- a/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs@@ -31,31 +31,28 @@ public class ShellRevertStep : IRevertStep/// <inheritdoc />public async Task<bool> ExecuteAsync(){- return await Task.Run(() =>+ var result = ShellType switch{- var result = ShellType switch+ ShellType.PowerShell => await ShellService.PowerShellAsync(Command),+ ShellType.CMD => await ShellService.CMDAsync(Command),+ _ => new ShellResult{- ShellType.PowerShell => ShellService.PowerShell(Command),- ShellType.CMD => ShellService.CMD(Command),- _ => new ShellResult- {- Command = Command,- Stdout = "",- Stderr = "Unknown shell type",- ExitCode = 1,- Duration = TimeSpan.Zero,- },- };+ Command = Command,+ Stdout = "",+ Stderr = "Unknown shell type",+ ExitCode = 1,+ Duration = TimeSpan.Zero,+ },+ };- if (result.ExitCode != 0)- throw new Exception(- !string.IsNullOrWhiteSpace(result.Stderr)- ? result.Stderr- : $"Command failed with exit code {result.ExitCode}"- );+ if (result.ExitCode != 0)+ throw new Exception(+ !string.IsNullOrWhiteSpace(result.Stderr)+ ? result.Stderr+ : $"Command failed with exit code {result.ExitCode}"+ );- return result.ExitCode == 0;- });+ return result.ExitCode == 0;}/// <inheritdoc />diff --git a/optimizerDuck/Services/Configuration/ConfigManager.cs b/optimizerDuck/Services/Configuration/ConfigManager.csindex a201f23..d7a7da8 100644--- a/optimizerDuck/Services/Configuration/ConfigManager.cs+++ b/optimizerDuck/Services/Configuration/ConfigManager.cs@@ -396,14 +396,30 @@ public class ConfigManager(IConfiguration configuration, ILogger<ConfigManager>{var configPath = Path.Combine(Shared.RootDirectory, "appsettings.json");- // Rewrite config file if it's empty- if (!File.Exists(configPath) || string.IsNullOrWhiteSpace(File.ReadAllText(configPath)))- File.WriteAllText(configPath, "{}");-- // Rewrite config file if it's invalid JSONtry{- JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configPath));+ if (!File.Exists(configPath))+ {+ File.WriteAllText(configPath, "{}");+ return;+ }++ var content = File.ReadAllText(configPath);+ if (string.IsNullOrWhiteSpace(content))+ {+ File.WriteAllText(configPath, "{}");+ return;+ }++ // Quick check for basic JSON structure before full parse+ var trimmed = content.Trim();+ if (!trimmed.StartsWith('{') || !trimmed.EndsWith('}'))+ {+ File.WriteAllText(configPath, "{}");+ return;+ }++ JsonConvert.DeserializeObject<JObject>(content);}catch{diff --git a/optimizerDuck/Services/Optimization/OptimizationRegistry.cs b/optimizerDuck/Services/Optimization/OptimizationRegistry.csindex 0946575..c4c6997 100644--- a/optimizerDuck/Services/Optimization/OptimizationRegistry.cs+++ b/optimizerDuck/Services/Optimization/OptimizationRegistry.cs@@ -1,4 +1,4 @@-using System.Collections.ObjectModel;+using System.Collections.ObjectModel;using System.Reflection;using Microsoft.Extensions.Logging;using optimizerDuck.Common.Helpers;@@ -12,45 +12,48 @@ public class OptimizationRegistry(ILoggerFactory loggerFactory)private readonly ILogger _logger = loggerFactory.CreateLogger<OptimizationRegistry>();public IOptimizationCategory[] OptimizationCategories { get; set; } = [];- public async Task PreloadOptimizations()+ public async Task PreloadOptimizationsAsync(){- var optimizationCategories = ReflectionHelper- .FindImplementationsInLoadedAssemblies<IOptimizationCategory>()- .Select(t =>- {- var optimizations = new ObservableCollection<IOptimization>(- t.GetNestedTypes(BindingFlags.Public)- .Where(nt => typeof(IOptimization).IsAssignableFrom(nt))- .Select(nt =>- {- var opt = (IOptimization)Activator.CreateInstance(nt)!;+ // Run reflection work on background thread to avoid blocking startup+ var optimizationCategories = await Task.Run(() =>+ ReflectionHelper+ .FindImplementationsInLoadedAssemblies<IOptimizationCategory>()+ .Select(t =>+ {+ var optimizations = new ObservableCollection<IOptimization>(+ t.GetNestedTypes(BindingFlags.Public)+ .Where(nt => typeof(IOptimization).IsAssignableFrom(nt))+ .Select(nt =>+ {+ var opt = (IOptimization)Activator.CreateInstance(nt)!;- if (opt is BaseOptimization bo)- bo.OwnerType = t;+ if (opt is BaseOptimization bo)+ bo.OwnerType = t;- return opt;- })- .ToList()- );+ return opt;+ })+ .ToList()+ );- if (optimizations.Count == 0)- return null;+ if (optimizations.Count == 0)+ return null;- var instance = (IOptimizationCategory)Activator.CreateInstance(t)!;+ var instance = (IOptimizationCategory)Activator.CreateInstance(t)!;- var optProp = t.GetProperty(- nameof(IOptimizationCategory.Optimizations),- BindingFlags.Public | BindingFlags.Instance- );- if (optProp != null && optProp.CanWrite)- optProp.SetValue(instance, optimizations);+ var optProp = t.GetProperty(+ nameof(IOptimizationCategory.Optimizations),+ BindingFlags.Public | BindingFlags.Instance+ );+ if (optProp != null && optProp.CanWrite)+ optProp.SetValue(instance, optimizations);- return instance;- })- .Where(c => c != null) // skip nulls- .Cast<IOptimizationCategory>()- .OrderBy(c => c.Order)- .ToArray();+ return instance;+ })+ .Where(c => c != null) // skip nulls+ .Cast<IOptimizationCategory>()+ .OrderBy(c => c.Order)+ .ToArray()+ ).ConfigureAwait(false);_logger.LogInformation("Total {CategoryCount} categories and {OptimizationCount} optimizations found",@@ -60,7 +63,7 @@ public class OptimizationRegistry(ILoggerFactory loggerFactory)await OptimizationService.UpdateOptimizationStateAsync(optimizationCategories.SelectMany(c => c.Optimizations)- );+ ).ConfigureAwait(false);OptimizationCategories = optimizationCategories;}diff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.csindex 7730e16..8d846b9 100644--- a/optimizerDuck/Services/Optimization/OptimizationService.cs+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs@@ -1,4 +1,4 @@-using System.IO;+using System.IO;using System.Text.RegularExpressions;using Microsoft.Extensions.Logging;using optimizerDuck.Common.Helpers;@@ -50,7 +50,7 @@ public class OptimizationService(new ProcessingProgress{Message = Translations.RestorePoint_Progress_Creating,- IsIndeterminate = true,+ IsIndeterminate = true});@@ -59,8 +59,7 @@ public class OptimizationService(var result = await ShellService.PowerShellAsync($"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS"- )- .ConfigureAwait(false);+ );if (result.Stderr.Contains(@@ -98,8 +97,7 @@ public class OptimizationService();var enableResult = await ShellService- .PowerShellAsync("Enable-ComputerRestore -Drive \"$env:SystemDrive\"")- .ConfigureAwait(false);+ .PowerShellAsync("Enable-ComputerRestore -Drive \"$env:SystemDrive\"");if (enableResult.ExitCode != 0){_logger.LogError(@@ -120,8 +118,7 @@ public class OptimizationService(result = await ShellService.PowerShellAsync($"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS"- )- .ConfigureAwait(false);+ );if (result.Stderr.Contains(@@ -157,26 +154,22 @@ public class OptimizationService(try{- var applyResult = await Task.Run(async () =>- await optimization- .ApplyAsync(- progress,- new OptimizationContext- {- Logger = optLogger,- Snapshot = systemInfoService.Snapshot,- StreamService = streamService,- }- )- .ConfigureAwait(false)- )- .ConfigureAwait(false);+ var applyResult = await optimization+ .ApplyAsync(+ progress,+ new OptimizationContext+ {+ Logger = optLogger,+ Snapshot = systemInfoService.Snapshot,+ StreamService = streamService,+ }+ );- if (!string.IsNullOrWhiteSpace(applyResult.Message))+ if (!string.IsNullOrWhiteSpace(applyResult.ErrorMessage))return new OptimizationResult{Status = OptimizationSuccessResult.Failed,- Message = applyResult.Message,+ Message = applyResult.ErrorMessage,FailedSteps = scope.GetStepResults().Where(step => !step.Success).ToList(),};@@ -191,7 +184,7 @@ public class OptimizationService();var result = scope.ToResult();- await TrySaveRevertDataAsync(scope, optimization).ConfigureAwait(false);+ await TrySaveRevertDataAsync(scope, optimization);return result;}@@ -213,7 +206,7 @@ public class OptimizationService(FailedSteps = failedSteps,};- await TrySaveRevertDataAsync(scope, optimization).ConfigureAwait(false);+ await TrySaveRevertDataAsync(scope, optimization);return result;}@@ -231,7 +224,7 @@ public class OptimizationService(IsIndeterminate = true,});- var result = await revertManager.RevertAsync(optimization, progress).ConfigureAwait(false);+ var result = await revertManager.RevertAsync(optimization, progress);progress?.Report(new ProcessingProgress{@@ -244,22 +237,38 @@ public class OptimizationService(return result;}- public static Task<bool> IsAppliedAsync(Guid id)- {- return RevertManager.IsAppliedAsync(id);- }-public static async Task UpdateOptimizationStateAsync(params IOptimization[] optimizations){- await Task.WhenAll(- optimizations.Select(async opt =>- {- var data = await RevertManager.GetRevertDataAsync(opt.Id).ConfigureAwait(false);- opt.State.IsApplied = data != null;- opt.State.AppliedAt = data?.AppliedAt;- })- )- .ConfigureAwait(false);+ if (optimizations.Length == 0)+ return;++ // Optimization: List all files in revert directory once instead of checking File.Exists for each+ var revertFiles = await Task.Run(() =>+ {+ if (!Directory.Exists(Shared.RevertDirectory))+ return new HashSet<string>();++ return Directory.GetFiles(Shared.RevertDirectory, "*.json")+ .Select(Path.GetFileNameWithoutExtension)+ .Where(f => f != null)+ .ToHashSet(StringComparer.OrdinalIgnoreCase)!;+ });++ foreach (var opt in optimizations)+ {+ var idStr = opt.Id.ToString();+ if (revertFiles.Contains(idStr))+ {+ var data = await RevertManager.GetRevertDataAsync(opt.Id);+ opt.State.IsApplied = data != null;+ opt.State.AppliedAt = data?.AppliedAt;+ }+ else+ {+ opt.State.IsApplied = false;+ opt.State.AppliedAt = null;+ }+ }}public static Task UpdateOptimizationStateAsync(IEnumerable<IOptimization> optimizations)@@ -334,7 +343,7 @@ public class OptimizationService(try{using var retryScope = ExecutionScope.BeginForCapture(logger);- success = await step.RetryAction().ConfigureAwait(false);+ success = await step.RetryAction();if (success){@@ -380,7 +389,7 @@ public class OptimizationService(try{- await revertManager.SaveRevertDataAsync(scope).ConfigureAwait(false);+ await revertManager.SaveRevertDataAsync(scope);}catch (Exception ex){diff --git a/optimizerDuck/Services/Optimization/Providers/RegistryService.cs b/optimizerDuck/Services/Optimization/Providers/RegistryService.csindex 5544f0d..08d7847 100644--- a/optimizerDuck/Services/Optimization/Providers/RegistryService.cs+++ b/optimizerDuck/Services/Optimization/Providers/RegistryService.cs@@ -673,13 +673,17 @@ public static class RegistryServiceif (targetType == typeof(string[]) && value is string[] arr)return (T)(object)arr;- // Bool: Registry sometimes saves DWORD 0/1 or string "true/false"+ // Bool: Registry sometimes saves DWORD 0/1 or string "true/false", "1"/"0", "yes"/"no"if (targetType == typeof(bool))return value switch{int i => (T)(object)(i != 0),long l => (T)(object)(l != 0),string s when bool.TryParse(s, out var b) => (T)(object)b,+ string s when s.Equals("1") || s.Equals("yes", StringComparison.OrdinalIgnoreCase) =>+ (T)(object)true,+ string s when s.Equals("0") || s.Equals("no", StringComparison.OrdinalIgnoreCase) =>+ (T)(object)false,_ => default,};diff --git a/optimizerDuck/Services/Optimization/Providers/ShellService.cs b/optimizerDuck/Services/Optimization/Providers/ShellService.csindex b736fee..0dd7555 100644--- a/optimizerDuck/Services/Optimization/Providers/ShellService.cs+++ b/optimizerDuck/Services/Optimization/Providers/ShellService.cs@@ -1,4 +1,4 @@-using System.Diagnostics;+using System.Diagnostics;using System.Text;using Microsoft.Extensions.Options;using optimizerDuck.Common.Extensions;@@ -348,13 +348,20 @@ public static class ShellService}catch (OperationCanceledException){+ // Process timed out, attempt cleanup+ ExecutionScope.LogWarning("Process timed out, attempting to kill: PID {ProcessId}", process.Id);+try{- process.Kill(true);+ if (!process.HasExited)+ {+ process.Kill(entireProcessTree: true);+ ExecutionScope.LogInfo("Killed process: PID {ProcessId}", process.Id);+ }}catch (Exception ex){- ExecutionScope.LogError(ex, "Failed to kill process for timeout (async)");+ ExecutionScope.LogError(ex, "Failed to kill process for timeout (async), PID: {ProcessId}", process.Id);}}@@ -363,15 +370,18 @@ public static class ShellServicevar timedOut = !process.HasExited;if (!process.HasExited){+ // Process still running after kill attempt, wait for grace periodtry{+ ExecutionScope.LogWarning("Process still running after kill, waiting for grace period: PID {ProcessId}", process.Id);process.WaitForExit(ProcessGraceDrainMs);}catch (Exception ex){ExecutionScope.LogError(ex,- "Failed to wait for process exit after kill (async)"+ "Failed to wait for process exit after kill (async), PID: {ProcessId}",+ process.Id);}@@ -380,17 +390,21 @@ public static class ShellService{try{- process.Kill(true);- if (!process.HasExited)+ ExecutionScope.LogWarning("Process still running after grace period, force killing: PID {ProcessId}", process.Id);+ process.Kill(entireProcessTree: true);++ // Wait up to 5 seconds for force kill+ if (!process.WaitForExit(5000)){- process.WaitForExit(5000); // Wait up to 5 seconds for force kill+ ExecutionScope.LogWarning("Process did not exit after force kill: PID {ProcessId}. User may need manual cleanup.", process.Id);}}catch (Exception ex){ExecutionScope.LogError(ex,- "Failed to force kill process after timeout (async)"+ "Failed to force kill process after timeout (async), PID: {ProcessId}. User may need manual cleanup.",+ process.Id);}}diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.csindex d78d27a..8630681 100644--- a/optimizerDuck/Services/Revert/RevertManager.cs+++ b/optimizerDuck/Services/Revert/RevertManager.cs@@ -16,49 +16,38 @@ namespace optimizerDuck.Services.Managers;public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFactory){- private static readonly Dictionary<string, Func<JObject, IRevertStep>> _stepRegistry =- BuildStepRegistry();+ private static readonly Lazy<Dictionary<string, Func<JObject, IRevertStep>>> _stepRegistry =+ new(BuildStepRegistry);+private static readonly ConcurrentDictionary<Guid, SemaphoreSlim> _fileLocks = new();public async Task SaveRevertDataAsync(ExecutionScope scope){- var maxIndex = scope.ExecutedSteps.Count == 0 ? 0 : scope.ExecutedSteps.Max(s => s.Index);- if (maxIndex == 0)+ if (!scope.HasSuccessfulSteps)return;- var steps = Enumerable- .Range(0, maxIndex)- .Select(_ => new RevertStepData { Type = "Unknown", Data = new JObject() })- .ToList();- var hasRevertStep = false;-- foreach (var step in scope.ExecutedSteps)- {- if (step.RevertStep == null)- continue;-- steps[step.Index - 1] = new RevertStepData+ var steps = scope.ExecutedSteps+ .Where(s => s.RevertStep != null)+ .Select(s => new RevertStepData{- Type = step.RevertStep.Type,- Data = step.RevertStep.ToData(),- };- hasRevertStep = true;- }+ Type = s.RevertStep!.Type,+ Data = s.RevertStep.ToData(),+ })+ .ToList();- if (!hasRevertStep)+ if (steps.Count == 0)return;await WriteJsonAsync(- GetFilePath(scope.OptimizationId!.Value),- new RevertData- {- OptimizationId = scope.OptimizationId!.Value,- OptimizationName = scope.OptimizationKey!,- AppliedAt = DateTime.Now,- Steps = steps,- }- )- .ConfigureAwait(false);+ GetFilePath(scope.OptimizationId!.Value),+ new RevertData+ {+ OptimizationId = scope.OptimizationId!.Value,+ OptimizationName = scope.OptimizationKey!,+ AppliedAt = DateTime.Now,+ Steps = steps,+ }+ );}public async Task<RevertResult> RevertAsync(@@ -73,7 +62,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFoperationLogger);- var steps = await LoadStepsAsync(optimization.Id).ConfigureAwait(false);+ var steps = await LoadStepsAsync(optimization.Id);if (steps.Count == 0)return new RevertResult{@@ -103,7 +92,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFtry{- if (!await step.ExecuteAsync().ConfigureAwait(false))+ if (!await step.ExecuteAsync())throw new Exception(Translations.Revert_Error_StepFailed);}catch (Exception ex)@@ -160,7 +149,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFtry{var data =- await LoadAsync(filePath).ConfigureAwait(false)+ await LoadAsync(filePath)?? new RevertData{OptimizationId = id,@@ -176,7 +165,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFType = step.Type,Data = step.ToData(),};- await WriteJsonAsync(filePath, data).ConfigureAwait(false);+ await WriteJsonAsync(filePath, data);}finally{@@ -191,7 +180,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFpublic static async Task<RevertData?> GetRevertDataAsync(Guid id){- return await LoadAsync(GetFilePath(id)).ConfigureAwait(false);+ return await LoadAsync(GetFilePath(id));}public static void ClearAllRevertData(ILogger logger)@@ -223,7 +212,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFtry{return JsonConvert.DeserializeObject<RevertData>(- await File.ReadAllTextAsync(path).ConfigureAwait(false)+ await File.ReadAllTextAsync(path));}catch@@ -240,13 +229,12 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFprivate static async Task WriteJsonAsync(string path, RevertData data){Directory.CreateDirectory(Path.GetDirectoryName(path)!);- await File.WriteAllTextAsync(path, JsonConvert.SerializeObject(data, Formatting.Indented))- .ConfigureAwait(false);+ await File.WriteAllTextAsync(path, JsonConvert.SerializeObject(data, Formatting.Indented));}private async Task<List<(int Index, IRevertStep Step)>> LoadStepsAsync(Guid id){- var data = await LoadAsync(GetFilePath(id)).ConfigureAwait(false);+ var data = await LoadAsync(GetFilePath(id));if (data == null || data.Steps.Count == 0)return [];@@ -298,7 +286,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF{if (data is not JObject obj)return null;- return _stepRegistry.TryGetValue(type, out var factory) ? factory(obj) : null;+ return _stepRegistry.Value.TryGetValue(type, out var factory) ? factory(obj) : null;}#endregiondiff --git a/optimizerDuck/Services/System/SystemInfoService.cs b/optimizerDuck/Services/System/SystemInfoService.csindex 3e90959..c8f7006 100644--- a/optimizerDuck/Services/System/SystemInfoService.cs+++ b/optimizerDuck/Services/System/SystemInfoService.cs@@ -680,12 +680,21 @@ internal static class NativeMemoryinternal static class CpuProvider{+ private static CpuInfo? _cachedStatic;+/// <summary>/// Gets CPU info using Registry (fast) + targeted WMI (only for cache sizes)./// Registry path: HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0/// </summary>public static CpuInfo Get(){+ if (_cachedStatic != null)+ {+ // Only current clock speed changes, but we'll stick to max/registry value for stability+ // unless we really need real-time tracking (which WMI isn't great for anyway)+ return _cachedStatic;+ }+try{// ── Fast path: Registry ──────────────────────────────────────@@ -734,7 +743,7 @@ internal static class CpuProvidervar vendor = DetectCpuVendor(manufacturer);var architecture = Environment.Is64BitOperatingSystem ? "64-bit" : "32-bit";- return new CpuInfo+ _cachedStatic = new CpuInfo{Name = name,Manufacturer = manufacturer,@@ -747,6 +756,8 @@ internal static class CpuProviderL2CacheKB = l2kb,L3CacheKB = l3kb,};++ return _cachedStatic;}catch{@@ -767,6 +778,8 @@ internal static class CpuProviderinternal static class RamProvider{+ private static List<RamModule>? _cachedModules;+/// <summary>/// Gets RAM info using GlobalMemoryStatusEx (same API as Task Manager)/// for usage stats, and WMI only for physical module details.@@ -799,6 +812,9 @@ internal static class RamProviderprivate static List<RamModule> GetPhysicalModules(){+ if (_cachedModules != null)+ return _cachedModules;+var modules = new List<RamModule>();var physicalMemory = WmiHelper.Query("SELECT Capacity, Speed, Manufacturer, PartNumber, DeviceLocator FROM Win32_PhysicalMemory"@@ -825,6 +841,7 @@ internal static class RamProvider);}+ _cachedModules = modules;return modules;}diff --git a/optimizerDuck/UI/Dialogs/ProcessingDialog.xaml b/optimizerDuck/UI/Dialogs/ProcessingDialog.xamlindex 62bee2a..f1a472d 100644--- a/optimizerDuck/UI/Dialogs/ProcessingDialog.xaml+++ b/optimizerDuck/UI/Dialogs/ProcessingDialog.xaml@@ -11,10 +11,7 @@d:DesignWidth="800"mc:Ignorable="d"><UserControl.Resources>- <converters:NumericComparisonToVisibilityConverter- x:Key="GreaterThanZeroToVisibilityConverter"- ComparisonType="GreaterThan"- Threshold="0" />+ <converters:ProgressBarVisibilityConverter x:Key="ProgressBarVisibilityConverter" /></UserControl.Resources><StackPanel MinWidth="420">@@ -31,8 +28,14 @@IsIndeterminate="{Binding IsIndeterminate}"Maximum="{Binding Total}"Minimum="0"- Visibility="{Binding Total, Converter={StaticResource GreaterThanZeroToVisibilityConverter}}"- Value="{Binding Value}" />+ Value="{Binding Value}">+ <ProgressBar.Visibility>+ <MultiBinding Converter="{StaticResource ProgressBarVisibilityConverter}">+ <Binding Path="Total" />+ <Binding Path="IsIndeterminate" />+ </MultiBinding>+ </ProgressBar.Visibility>+ </ProgressBar><ui:TextBlockMargin="0,16,0,0"diff --git a/optimizerDuck/UI/Pages/DashboardPage.xaml b/optimizerDuck/UI/Pages/DashboardPage.xamlindex 5ecec48..c467224 100644--- a/optimizerDuck/UI/Pages/DashboardPage.xaml+++ b/optimizerDuck/UI/Pages/DashboardPage.xaml@@ -400,7 +400,15 @@FontTypography="BodyStrong"Text="{ext:Loc Dashboard.SystemInfo.Storage.Header}" />- <ItemsControl ItemsSource="{Binding ViewModel.RuntimeDisk.Volumes}">+ <ItemsControl+ ItemsSource="{Binding ViewModel.RuntimeDisk.Volumes}"+ VirtualizingStackPanel.IsVirtualizing="True"+ VirtualizingStackPanel.VirtualizationMode="Recycling">+ <ItemsControl.ItemsPanel>+ <ItemsPanelTemplate>+ <VirtualizingStackPanel />+ </ItemsPanelTemplate>+ </ItemsControl.ItemsPanel><ItemsControl.ItemTemplate><DataTemplate><ui:CardActiondiff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.csindex 53efdec..66b24d9 100644--- a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs@@ -21,6 +21,7 @@ using optimizerDuck.UI.Dialogs;using optimizerDuck.UI.ViewModels.Dialogs;using Wpf.Ui;using Wpf.Ui.Controls;+using Wpf.Ui.Extensions;using TextBlock = Wpf.Ui.Controls.TextBlock;namespace optimizerDuck.UI.ViewModels.Optimizer;@@ -134,7 +135,7 @@ public partial class OptimizationCategoryViewModel : ViewModeltry{// Keep a stable reference to the previous state in case we need to roll back UI changes.- var wasApplied = await OptimizationService.IsAppliedAsync(optimization.Id);+ var wasApplied = await RevertManager.IsAppliedAsync(optimization.Id);var restorePointCreated = false;if (!_optimizationService.WasRequestedRestorePoint)@@ -165,7 +166,7 @@ public partial class OptimizationCategoryViewModel : ViewModelprogress => _optimizationService.ApplyAsync(optimization, progress));- // If result status is Failed, we can't retry it+ // If result status is completely Failed, we can't retry itif (applyResult.Status == OptimizationSuccessResult.Failed){ShowOperationOutcomeSnackbar(@@ -176,7 +177,7 @@ public partial class OptimizationCategoryViewModel : ViewModel);_logger.LogWarning(- "Apply failed for {Name}: {Message}",+ "Apply failed {Name} optimization: {Message}",optimization.OptimizationKey,applyResult.Message);@@ -247,12 +248,13 @@ public partial class OptimizationCategoryViewModel : ViewModelprogress => _optimizationService.RevertAsync(optimization, progress));+ ((App)Application.Current).HasPendingChanges = true;+var retryOutcome = await HandleRetryableFailuresAsync(optimization,revertResult.FailedSteps,OptimizationOperation.Revert);-await OptimizationService.UpdateOptimizationStateAsync(optimization);var notificationState = ResolveRevertNotificationState(@@ -416,9 +418,6 @@ public partial class OptimizationCategoryViewModel : ViewModelIsLoading = true;try{- // Allow UI to render loading ring- await Task.Delay(1);-foreach (var optimization in _category.Optimizations){optimization.State.PropertyChanged += (_, e) =>@@ -731,54 +730,90 @@ public partial class OptimizationCategoryViewModel : ViewModelif (result == ContentDialogResult.Secondary) // User skippedreturn (true, false);- var resultState = await _optimizationService.CreateRestorePointAsync();- var restorePointCreated = false;-- switch (resultState)+ try{- case RestorePointResult.Success:- // if setting show snackbar after applied successfully was off, so show it and applied snackbar wont conflict this- if (!_appOptionsMonitor.CurrentValue.Optimize.ShowCompletionNotification)- {+ var resultState = await _optimizationService.CreateRestorePointAsync();++ switch (resultState)+ {+ case RestorePointResult.Success:+ // if setting show snackbar after applied successfully was off, so show it and applied snackbar wont conflict this+ if (!_appOptionsMonitor.CurrentValue.Optimize.ShowCompletionNotification)+ {+ _snackbarService.Show(+ Translations.RestorePoint_Snackbar_Success_Title,+ string.Format(+ Translations.RestorePoint_Snackbar_Success_Message,+ Shared.RestorePointName+ ),+ ControlAppearance.Success,+ new SymbolIcon { Symbol = SymbolRegular.CheckmarkCircle24, Filled = true },+ TimeSpan.FromSeconds(5)+ );+ break;+ }++ return (true, true);++ case RestorePointResult.FrequencyLimitReached:_snackbarService.Show(- Translations.RestorePoint_Snackbar_Success_Title,- string.Format(- Translations.RestorePoint_Snackbar_Success_Message,- Shared.RestorePointName- ),- ControlAppearance.Success,- new SymbolIcon { Symbol = SymbolRegular.CheckmarkCircle24, Filled = true },+ Translations.RestorePoint_Snackbar_Error_Title,+ Translations.RestorePoint_Snackbar_Warning_LimitReached,+ ControlAppearance.Caution,+ new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },TimeSpan.FromSeconds(5));break;- }- restorePointCreated = true;- break;+ case RestorePointResult.Failed:+ default:+ _snackbarService.Show(+ Translations.RestorePoint_Snackbar_Error_Title,+ Translations.RestorePoint_Snackbar_Error_Message,+ ControlAppearance.Danger,+ new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },+ TimeSpan.FromSeconds(5)+ );+ break;+ }- case RestorePointResult.FrequencyLimitReached:- _snackbarService.Show(- Translations.RestorePoint_Title,- Translations.RestorePoint_Snackbar_Warning_LimitReached,- ControlAppearance.Caution,- new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },- TimeSpan.FromSeconds(5)- );- break;+ var failedMessage =+ resultState == RestorePointResult.FrequencyLimitReached+ ? Translations.RestorePoint_Snackbar_Warning_LimitReached+ : "";+ var failedResult = await _contentDialogService.ShowSimpleDialogAsync(+ new SimpleContentDialogCreateOptions+ {+ Title = Translations.RestorePoint_Snackbar_Error_Title,+ Content =+ failedMessage + $"\n{Translations.RestorePoint_Snackbar_Error_Message}",- case RestorePointResult.Failed:- default:- _snackbarService.Show(+ PrimaryButtonText = Translations.Button_Skip,+ CloseButtonText = Translations.Button_Cancel,+ },+ CancellationToken.None+ );++ if (failedResult == ContentDialogResult.Primary) // User chose to skip after failure+ return (true, false);++ return (false, false);++ }++ catch (Exception e)+ {+ _logger.LogError(e, "Failed to create restore point");+ _snackbarService.Show(Translations.RestorePoint_Snackbar_Error_Title,Translations.RestorePoint_Snackbar_Error_Message,- ControlAppearance.Danger,- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },+ ControlAppearance.Caution,+ new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },TimeSpan.FromSeconds(5));- break;}- return (true, restorePointCreated);+ return (true, false);}/// <summary>diff --git a/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.csindex fbfdeb8..129e507 100644--- a/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs@@ -50,6 +50,7 @@ public partial class SettingsViewModel(new() { DisplayName = "English", Culture = new CultureInfo("en-US") },new() { DisplayName = "Tiếng Việt", Culture = new CultureInfo("vi-VN") },new() { DisplayName = "正體中文", Culture = new CultureInfo("zh-TW") },+ new() { DisplayName = "简体中文", Culture = new CultureInfo("zh-CN") },];public override async Task OnNavigatedToAsync()diff --git a/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.csindex fdc8cf8..a57acf9 100644--- a/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs@@ -1,4 +1,4 @@-using System.Collections.ObjectModel;+using System.Collections.ObjectModel;using System.ComponentModel;using System.Diagnostics;using CommunityToolkit.Mvvm.ComponentModel;@@ -293,8 +293,7 @@ public partial class StartupManagerViewModel : ViewModeltry{await _startupManagerService- .ToggleStartupApp(app, app.IsEnabled)- .ConfigureAwait(false);+ .ToggleStartupApp(app, app.IsEnabled);}catch (Exception ex){@@ -310,8 +309,7 @@ public partial class StartupManagerViewModel : ViewModeltry{await _startupManagerService- .ToggleStartupTask(task, task.IsEnabled)- .ConfigureAwait(false);+ .ToggleStartupTask(task, task.IsEnabled);}catch (Exception ex){