Free, open-source Windows optimization tool for performance, privacy, and simplicity.
C# csharpdebloatdotnetgamingopen-sourceoptimizationoptimizeroptimizerduckperformanceprivacytweakertweakswindowswinui
refactor: improve revert error handling, diagnostics, and tests
fatDuckc61cedbfe766
diff --git a/optimizerDuck.Test/Domain/Exceptions/StepExecutionExceptionTests.cs b/optimizerDuck.Test/Domain/Exceptions/StepExecutionExceptionTests.csnew file mode 100644index 0000000..45ce210--- /dev/null+++ b/optimizerDuck.Test/Domain/Exceptions/StepExecutionExceptionTests.cs@@ -0,0 +1,42 @@+using optimizerDuck.Domain.Exceptions;++namespace optimizerDuck.Test.Domain.Exceptions;++public class StepExecutionExceptionTests+{+ [Fact]+ public void Constructor_WithErrorAndDetail_SetsProperties()+ {+ var ex = new StepExecutionException("Something went wrong", "Stack trace details");++ Assert.Equal("Something went wrong", ex.Message);+ Assert.Equal("Stack trace details", ex.ErrorDetail);+ }++ [Fact]+ public void Constructor_WithNullError_UsesDefaultMessage()+ {+ var ex = new StepExecutionException(null, null);++ Assert.Equal("Step execution failed", ex.Message);+ Assert.Null(ex.ErrorDetail);+ }++ [Fact]+ public void Constructor_WithErrorOnly_SetsMessageAndNullDetail()+ {+ var ex = new StepExecutionException("Access denied", null);++ Assert.Equal("Access denied", ex.Message);+ Assert.Null(ex.ErrorDetail);+ }++ [Fact]+ public void Constructor_WithDetailOnly_DefaultMessageUsed()+ {+ var ex = new StepExecutionException(null, "Inner exception details");++ Assert.Equal("Step execution failed", ex.Message);+ Assert.Equal("Inner exception details", ex.ErrorDetail);+ }+}diff --git a/optimizerDuck.Test/Domain/Optimizations/Models/Services/RegistryItemKindDetectionTests.cs b/optimizerDuck.Test/Domain/Optimizations/Models/Services/RegistryItemKindDetectionTests.csnew file mode 100644index 0000000..d702fd5--- /dev/null+++ b/optimizerDuck.Test/Domain/Optimizations/Models/Services/RegistryItemKindDetectionTests.cs@@ -0,0 +1,80 @@+using Microsoft.Win32;+using optimizerDuck.Domain.Optimizations.Models.Services;++namespace optimizerDuck.Test.Domain.Optimizations.Models.Services;++public class RegistryItemKindDetectionTests+{+ [Fact]+ public void Constructor_WithIntValue_DetectsDWord()+ {+ var item = new RegistryItem("HKLM\\Test", "Value", 42);+ Assert.Equal(RegistryValueKind.DWord, item.Kind);+ }++ [Fact]+ public void Constructor_WithLongValue_DetectsQWord()+ {+ var item = new RegistryItem("HKLM\\Test", "Value", 9999999999L);+ Assert.Equal(RegistryValueKind.QWord, item.Kind);+ }++ [Fact]+ public void Constructor_WithStringValue_DetectsString()+ {+ var item = new RegistryItem("HKLM\\Test", "Value", "Hello");+ Assert.Equal(RegistryValueKind.String, item.Kind);+ }++ [Fact]+ public void Constructor_WithStringArrayValue_DetectsMultiString()+ {+ var item = new RegistryItem("HKLM\\Test", "Value", new[] { "a", "b", "c" });+ Assert.Equal(RegistryValueKind.MultiString, item.Kind);+ }++ [Fact]+ public void Constructor_WithByteArrayValue_DetectsBinary()+ {+ var item = new RegistryItem("HKLM\\Test", "Value", new byte[] { 0x01, 0x02, 0x03 });+ Assert.Equal(RegistryValueKind.Binary, item.Kind);+ }++ [Fact]+ public void Constructor_WithNullValue_DetectsUnknown()+ {+ var item = new RegistryItem("HKLM\\Test", "Value", null as object);+ Assert.Equal(RegistryValueKind.Unknown, item.Kind);+ }++ [Fact]+ public void Constructor_WithExplicitKind_DoesNotAutoDetect()+ {+ var item = new RegistryItem("HKLM\\Test", "Value", 42, RegistryValueKind.QWord);+ Assert.Equal(RegistryValueKind.QWord, item.Kind);+ }++ [Fact]+ public void Constructor_WithoutValue_SetsKindUnknown()+ {+ var item = new RegistryItem("HKLM\\Test", "Value");+ Assert.Equal(RegistryValueKind.Unknown, item.Kind);+ Assert.Null(item.Value);+ }++ [Fact]+ public void Constructor_KeyOnly_SetsKindUnknownAndNullName()+ {+ var item = new RegistryItem("HKLM\\Test");+ Assert.Equal(RegistryValueKind.Unknown, item.Kind);+ Assert.Null(item.Name);+ Assert.Null(item.Value);+ }++ [Fact]+ public void Constructor_WithBoolValue_DetectsUnknown()+ {+ var item = new RegistryItem("HKLM\\Test", "Value", true);+ Assert.Equal(RegistryValueKind.Unknown, item.Kind);+ }+}diff --git a/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.cs b/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.csnew file mode 100644index 0000000..119b217--- /dev/null+++ b/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.cs@@ -0,0 +1,492 @@+using Microsoft.Win32;+using Newtonsoft.Json.Linq;+using optimizerDuck.Domain.Optimizations.Models.Services;+using optimizerDuck.Domain.Revert.Steps;++namespace optimizerDuck.Test.Domain.Revert.Steps;++public class RevertStepSerializationTests+{+ [Fact]+ public void ShellRevertStep_RoundTrip_PreservesAllProperties()+ {+ var original = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "sc config TestService start= auto",+ };++ var json = original.ToData();+ var restored = ShellRevertStep.FromData(json);++ Assert.Equal(original.ShellType, restored.ShellType);+ Assert.Equal(original.Command, restored.Command);+ Assert.Equal(original.Type, restored.Type);+ }++ [Fact]+ public void ShellRevertStep_PowerShell_RoundTrip()+ {+ var original = new ShellRevertStep+ {+ ShellType = ShellType.PowerShell,+ Command = "Set-ItemProperty -Path 'HKLM:\\Test' -Name 'Value' -Value 0",+ };++ var json = original.ToData();+ var restored = ShellRevertStep.FromData(json);++ Assert.Equal(ShellType.PowerShell, restored.ShellType);+ Assert.Equal(original.Command, restored.Command);+ }++ [Fact]+ public void ShellRevertStep_WithEmptyCommand_RoundTrip()+ {+ var original = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "",+ };++ var json = original.ToData();+ var restored = ShellRevertStep.FromData(json);++ Assert.Equal(string.Empty, restored.Command);+ }++ [Fact]+ public void ServiceRevertStep_RoundTrip_PreservesAllProperties()+ {+ var original = new ServiceRevertStep+ {+ ServiceName = "wuauserv",+ OriginalStartupType = ServiceStartupType.Automatic,+ };++ var json = original.ToData();+ var restored = ServiceRevertStep.FromData(json);++ Assert.Equal(original.ServiceName, restored.ServiceName);+ Assert.Equal(original.OriginalStartupType, restored.OriginalStartupType);+ Assert.Equal(original.Type, restored.Type);+ }++ [Fact]+ public void ServiceRevertStep_Disabled_RoundTrip()+ {+ var original = new ServiceRevertStep+ {+ ServiceName = "Spooler",+ OriginalStartupType = ServiceStartupType.Disabled,+ };++ var json = original.ToData();+ var restored = ServiceRevertStep.FromData(json);++ Assert.Equal("Spooler", restored.ServiceName);+ Assert.Equal(ServiceStartupType.Disabled, restored.OriginalStartupType);+ }++ [Fact]+ public void ServiceRevertStep_Manual_RoundTrip()+ {+ var original = new ServiceRevertStep+ {+ ServiceName = "MpsSvc",+ OriginalStartupType = ServiceStartupType.Manual,+ };++ var json = original.ToData();+ var restored = ServiceRevertStep.FromData(json);++ Assert.Equal(ServiceStartupType.Manual, restored.OriginalStartupType);+ }++ [Fact]+ public void ServiceRevertStep_DelayedStart_RoundTrip()+ {+ var original = new ServiceRevertStep+ {+ ServiceName = "WpnService",+ OriginalStartupType = ServiceStartupType.AutomaticDelayedStart,+ };++ var json = original.ToData();+ var restored = ServiceRevertStep.FromData(json);++ Assert.Equal(ServiceStartupType.AutomaticDelayedStart, restored.OriginalStartupType);+ }++ [Fact]+ public void ServiceRevertStep_EmptyServiceName_RoundTrip()+ {+ var original = new ServiceRevertStep+ {+ ServiceName = "",+ OriginalStartupType = ServiceStartupType.Manual,+ };++ var json = original.ToData();+ var restored = ServiceRevertStep.FromData(json);++ Assert.Equal(string.Empty, restored.ServiceName);+ }++ [Fact]+ public void ScheduledTaskRevertStep_RoundTrip_PreservesAllProperties()+ {+ var original = new ScheduledTaskRevertStep+ {+ FullPath = @"\Microsoft\Windows\TestTask",+ OriginalEnabled = true,+ };++ var json = original.ToData();+ var restored = ScheduledTaskRevertStep.FromData(json);++ Assert.Equal(original.FullPath, restored.FullPath);+ Assert.Equal(original.OriginalEnabled, restored.OriginalEnabled);+ Assert.Equal(original.Type, restored.Type);+ }++ [Fact]+ public void ScheduledTaskRevertStep_DisabledTask_RoundTrip()+ {+ var original = new ScheduledTaskRevertStep+ {+ FullPath = @"\MyApp\Updater",+ OriginalEnabled = false,+ };++ var json = original.ToData();+ var restored = ScheduledTaskRevertStep.FromData(json);++ Assert.False(restored.OriginalEnabled);+ }++ [Theory]+ [InlineData(true)]+ [InlineData(false)]+ public void ScheduledTaskRevertStep_WithBothEnabledStates_RoundTrip(bool originalState)+ {+ var original = new ScheduledTaskRevertStep+ {+ FullPath = @"\Test\Task",+ OriginalEnabled = originalState,+ };++ var json = original.ToData();+ var restored = ScheduledTaskRevertStep.FromData(json);++ Assert.Equal(originalState, restored.OriginalEnabled);+ }++ [Fact]+ public void UsbPowerRevertStep_RoundTrip_PreservesAllProperties()+ {+ var original = new UsbPowerRevertStep+ {+ States =+ [+ new UsbPowerRevertStep.DeviceState+ {+ InstanceName = @"USB\VID_1234\ABC123",+ Enable = true,+ },+ new UsbPowerRevertStep.DeviceState+ {+ InstanceName = @"USB\VID_5678\DEF456",+ Enable = false,+ },+ ],+ };++ var json = original.ToData();+ var restored = UsbPowerRevertStep.FromData(json);++ Assert.Equal(original.Type, restored.Type);+ Assert.Equal(original.States.Count, restored.States.Count);+ Assert.Equal(original.States[0].InstanceName, restored.States[0].InstanceName);+ Assert.Equal(original.States[0].Enable, restored.States[0].Enable);+ Assert.Equal(original.States[1].InstanceName, restored.States[1].InstanceName);+ Assert.Equal(original.States[1].Enable, restored.States[1].Enable);+ }++ [Fact]+ public void UsbPowerRevertStep_EmptyStates_RoundTrip()+ {+ var original = new UsbPowerRevertStep();++ var json = original.ToData();+ var restored = UsbPowerRevertStep.FromData(json);++ Assert.Empty(restored.States);+ }++ [Fact]+ public void RegistryRevertStep_RestorePreviousDWord_RoundTrip()+ {+ var original = new RegistryRevertStep+ {+ Action = RevertAction.RestorePrevious,+ Path = @"HKLM\SOFTWARE\Test",+ Name = "DWordValue",+ Value = 42,+ Kind = RegistryValueKind.DWord,+ };++ var json = original.ToData();+ var restored = RegistryRevertStep.FromData(json);++ Assert.Equal(original.Action, restored.Action);+ Assert.Equal(original.Path, restored.Path);+ Assert.Equal(original.Name, restored.Name);+ Assert.Equal(original.Kind, restored.Kind);+ Assert.Equal(42, restored.Value);+ }++ [Fact]+ public void RegistryRevertStep_RestorePreviousQWord_RoundTrip()+ {+ var original = new RegistryRevertStep+ {+ Action = RevertAction.RestorePrevious,+ Path = @"HKLM\SOFTWARE\Test",+ Name = "QWordValue",+ Value = 9999999999L,+ Kind = RegistryValueKind.QWord,+ };++ var json = original.ToData();+ var restored = RegistryRevertStep.FromData(json);++ Assert.Equal(RegistryValueKind.QWord, restored.Kind);+ Assert.Equal(9999999999L, restored.Value);+ }++ [Fact]+ public void RegistryRevertStep_RestorePreviousString_RoundTrip()+ {+ var original = new RegistryRevertStep+ {+ Action = RevertAction.RestorePrevious,+ Path = @"HKCU\Software\Test",+ Name = "StringValue",+ Value = "Hello World",+ Kind = RegistryValueKind.String,+ };++ var json = original.ToData();+ var restored = RegistryRevertStep.FromData(json);++ Assert.Equal("Hello World", restored.Value);+ }++ [Fact]+ public void RegistryRevertStep_RestorePreviousExpandString_RoundTrip()+ {+ var original = new RegistryRevertStep+ {+ Action = RevertAction.RestorePrevious,+ Path = @"HKLM\SOFTWARE\Test",+ Name = "ExpandValue",+ Value = "%PATH%",+ Kind = RegistryValueKind.ExpandString,+ };++ var json = original.ToData();+ var restored = RegistryRevertStep.FromData(json);++ Assert.Equal(RegistryValueKind.ExpandString, restored.Kind);+ Assert.Equal("%PATH%", restored.Value);+ }++ [Fact]+ public void RegistryRevertStep_RestorePreviousMultiString_RoundTrip()+ {+ var original = new RegistryRevertStep+ {+ Action = RevertAction.RestorePrevious,+ Path = @"HKLM\SOFTWARE\Test",+ Name = "MultiValue",+ Value = new[] { "Line1", "Line2", "Line3" },+ Kind = RegistryValueKind.MultiString,+ };++ var json = original.ToData();+ var restored = RegistryRevertStep.FromData(json);++ Assert.Equal(RegistryValueKind.MultiString, restored.Kind);+ var restoredArray = Assert.IsType<string[]>(restored.Value);+ Assert.Equal(["Line1", "Line2", "Line3"], restoredArray);+ }++ [Fact]+ public void RegistryRevertStep_RestorePreviousBinary_RoundTrip()+ {+ var original = new RegistryRevertStep+ {+ Action = RevertAction.RestorePrevious,+ Path = @"HKLM\SOFTWARE\Test",+ Name = "BinaryValue",+ Value = new byte[] { 0x01, 0x02, 0xFF, 0x00 },+ Kind = RegistryValueKind.Binary,+ };++ var json = original.ToData();+ var restored = RegistryRevertStep.FromData(json);++ Assert.Equal(RegistryValueKind.Binary, restored.Kind);+ var restoredBytes = Assert.IsType<byte[]>(restored.Value);+ Assert.Equal([0x01, 0x02, 0xFF, 0x00], restoredBytes);+ }++ [Fact]+ public void RegistryRevertStep_RestorePreviousNullValue_RoundTrip()+ {+ var original = new RegistryRevertStep+ {+ Action = RevertAction.RestorePrevious,+ Path = @"HKLM\SOFTWARE\Test",+ Name = "NullValue",+ Value = null,+ Kind = RegistryValueKind.String,+ };++ var json = original.ToData();+ var restored = RegistryRevertStep.FromData(json);++ Assert.Null(restored.Value);+ }++ [Fact]+ public void RegistryRevertStep_NoPreviousValue_RoundTrip()+ {+ var original = new RegistryRevertStep+ {+ Action = RevertAction.NoPreviousValue,+ Path = @"HKLM\SOFTWARE\Test",+ Name = "OldValue",+ };++ var json = original.ToData();+ var restored = RegistryRevertStep.FromData(json);++ Assert.Equal(RevertAction.NoPreviousValue, restored.Action);+ Assert.Equal("OldValue", restored.Name);+ Assert.Null(restored.Value);+ }++ [Fact]+ public void RegistryRevertStep_DefaultValueName_RoundTrip()+ {+ var original = new RegistryRevertStep+ {+ Action = RevertAction.RestorePrevious,+ Path = @"HKLM\SOFTWARE\Test",+ Name = null,+ Value = "DefaultData",+ Kind = RegistryValueKind.String,+ };++ var json = original.ToData();+ var restored = RegistryRevertStep.FromData(json);++ Assert.Null(restored.Name);+ Assert.Equal("DefaultData", restored.Value);+ }++ [Fact]+ public void RegistryRevertStep_RestoreKeyAction_RoundTrip()+ {+ var original = new RegistryRevertStep+ {+ Action = RevertAction.RestoreKey,+ Path = @"HKLM\SOFTWARE\Test",+ };++ var json = original.ToData();+ var restored = RegistryRevertStep.FromData(json);++ Assert.Equal(RevertAction.RestoreKey, restored.Action);+ Assert.Equal(@"HKLM\SOFTWARE\Test", restored.Path);+ }++ [Fact]+ public void RegistryRevertStep_DeleteKeyAction_RoundTrip()+ {+ var original = new RegistryRevertStep+ {+ Action = RevertAction.DeleteKey,+ Path = @"HKLM\SOFTWARE\Test\SubKey",+ };++ var json = original.ToData();+ var restored = RegistryRevertStep.FromData(json);++ Assert.Equal(RevertAction.DeleteKey, restored.Action);+ Assert.Null(restored.Name);+ }++ [Fact]+ public void RegistryRevertStep_WithCreatedSubKeys_RoundTrip()+ {+ var original = new RegistryRevertStep+ {+ Action = RevertAction.RestorePrevious,+ Path = @"HKLM\SOFTWARE\Test",+ Name = "Value",+ Value = 1,+ Kind = RegistryValueKind.DWord,+ CreatedSubKeys = new List<string>+ {+ @"HKLM\SOFTWARE\Test\NewKey\SubKey",+ @"HKLM\SOFTWARE\Test\NewKey",+ },+ };++ var json = original.ToData();+ var restored = RegistryRevertStep.FromData(json);++ Assert.NotNull(restored.CreatedSubKeys);+ Assert.Equal(2, restored.CreatedSubKeys.Count);+ Assert.Contains(restored.CreatedSubKeys, k => k.Contains("NewKey"));+ }++ [Fact]+ public void RegistryRevertStep_WithSubSteps_RoundTrip()+ {+ var original = new RegistryRevertStep+ {+ Action = RevertAction.RestoreKeyTree,+ Path = @"HKLM\SOFTWARE\TestTree",+ SubSteps =+ [+ new RegistryRevertStep+ {+ Action = RevertAction.RestoreKey,+ Path = @"HKLM\SOFTWARE\TestTree\SubKeyA",+ },+ new RegistryRevertStep+ {+ Action = RevertAction.RestorePrevious,+ Path = @"HKLM\SOFTWARE\TestTree\SubKeyA",+ Name = "Value1",+ Value = "Data1",+ Kind = RegistryValueKind.String,+ },+ ],+ };++ var json = original.ToData();+ var restored = RegistryRevertStep.FromData(json);++ Assert.Equal(RevertAction.RestoreKeyTree, restored.Action);+ Assert.NotNull(restored.SubSteps);+ Assert.Equal(2, restored.SubSteps.Count);+ Assert.Equal(RevertAction.RestoreKey, restored.SubSteps[0].Action);+ Assert.Equal(RevertAction.RestorePrevious, restored.SubSteps[1].Action);+ Assert.Equal("Value1", restored.SubSteps[1].Name);+ }+}diff --git a/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.cs b/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.csindex 00d991f..0db871d 100644--- a/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.cs+++ b/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.cs@@ -1,3 +1,4 @@+using optimizerDuck.Domain.Exceptions;using optimizerDuck.Domain.Revert.Steps;namespace optimizerDuck.Test.Domain.Revert.Steps;@@ -5,7 +6,7 @@ namespace optimizerDuck.Test.Domain.Revert.Steps;public class ScheduledTaskRevertStepTests{[Fact]- public async Task ExecuteAsync_WithMissingTask_ReturnsFalse()+ public async Task ExecuteAsync_WithMissingTask_ThrowsStepExecutionException(){var step = new ScheduledTaskRevertStep{@@ -13,8 +14,8 @@ public class ScheduledTaskRevertStepTestsOriginalEnabled = true,};- var success = await step.ExecuteAsync();+ var ex = await Assert.ThrowsAsync<StepExecutionException>(() => step.ExecuteAsync());- Assert.False(success);+ Assert.Contains("NonExistent", ex.Message);}}diff --git a/optimizerDuck.Test/Services/OptimizationServices/ShellPolicyTests.cs b/optimizerDuck.Test/Services/OptimizationServices/ShellPolicyTests.csnew file mode 100644index 0000000..e901b8f--- /dev/null+++ b/optimizerDuck.Test/Services/OptimizationServices/ShellPolicyTests.cs@@ -0,0 +1,256 @@+using optimizerDuck.Domain.Optimizations.Models.Services;+using optimizerDuck.Services.OptimizationServices;++namespace optimizerDuck.Test.Services.OptimizationServices;++public class ShellPolicyTests+{+ [Fact]+ public void DefaultPolicy_ExitCodeZero_ReturnsSuccess()+ {+ var result = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "",+ ExitCode = 0,+ Duration = TimeSpan.Zero,+ };++ Assert.True(ShellPolicy.Default.IsSuccess(result));+ }++ [Fact]+ public void DefaultPolicy_NonZeroExitCode_ReturnsFailure()+ {+ var result = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "",+ ExitCode = 1,+ Duration = TimeSpan.Zero,+ };++ Assert.False(ShellPolicy.Default.IsSuccess(result));+ }++ [Fact]+ public void DefaultPolicy_WithStderr_ReturnsStderrAsError()+ {+ var result = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "Access denied",+ ExitCode = 5,+ Duration = TimeSpan.Zero,+ };++ var error = ShellPolicy.Default.ErrorFactory(result);+ Assert.Equal("Access denied", error);+ }++ [Fact]+ public void DefaultPolicy_WithoutStderr_ReturnsExitCodeMessage()+ {+ var result = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "",+ ExitCode = 3,+ Duration = TimeSpan.Zero,+ };++ var error = ShellPolicy.Default.ErrorFactory(result);+ Assert.Contains("3", error, StringComparison.Ordinal);+ }++ [Fact]+ public void DefaultPolicy_TimedOut_ReturnsTimeoutMessage()+ {+ var result = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "",+ ExitCode = -1,+ Duration = TimeSpan.FromSeconds(30),+ };++ var error = ShellPolicy.Default.ErrorFactory(result);+ Assert.Contains("timed out", error, StringComparison.OrdinalIgnoreCase);+ }++ [Fact]+ public void SuccessExitCodes_WithAllowedExitCode_ReturnsSuccess()+ {+ var policy = ShellPolicy.SuccessExitCodes(0, 1, 2);++ var result = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "",+ ExitCode = 1,+ Duration = TimeSpan.Zero,+ };++ Assert.True(policy.IsSuccess(result));+ }++ [Fact]+ public void SuccessExitCodes_WithDisallowedExitCode_ReturnsFailure()+ {+ var policy = ShellPolicy.SuccessExitCodes(0, 1);++ var result = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "",+ ExitCode = 3,+ Duration = TimeSpan.Zero,+ };++ Assert.False(policy.IsSuccess(result));+ }++ [Fact]+ public void SuccessExitCodeRange_WithInRange_ReturnsSuccess()+ {+ var policy = ShellPolicy.SuccessExitCodeRange(5);++ var result = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "",+ ExitCode = 3,+ Duration = TimeSpan.Zero,+ };++ Assert.True(policy.IsSuccess(result));+ }++ [Fact]+ public void SuccessExitCodeRange_WithNegativeExitCode_ReturnsFailure()+ {+ var policy = ShellPolicy.SuccessExitCodeRange(5);++ var result = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "",+ ExitCode = -1,+ Duration = TimeSpan.Zero,+ };++ Assert.False(policy.IsSuccess(result));+ }++ [Fact]+ public void SuccessExitCodeRange_WithOutOfRange_ReturnsFailure()+ {+ var policy = ShellPolicy.SuccessExitCodeRange(5);++ var result = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "",+ ExitCode = 6,+ Duration = TimeSpan.Zero,+ };++ Assert.False(policy.IsSuccess(result));+ }++ [Fact]+ public void From_CustomPolicy_UsesCustomPredicate()+ {+ var policy = ShellPolicy.From(r => r.ExitCode == 42);++ var successResult = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "",+ ExitCode = 42,+ Duration = TimeSpan.Zero,+ };++ var failResult = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "",+ ExitCode = 0,+ Duration = TimeSpan.Zero,+ };++ Assert.True(policy.IsSuccess(successResult));+ Assert.False(policy.IsSuccess(failResult));+ }++ [Fact]+ public void From_WithCustomErrorFactory_UsesCustomFactory()+ {+ var policy = ShellPolicy.From(+ r => r.ExitCode == 0,+ r => $"Custom error: exit code {r.ExitCode}"+ );++ var result = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "",+ ExitCode = 1,+ Duration = TimeSpan.Zero,+ };++ Assert.Equal("Custom error: exit code 1", policy.ErrorFactory(result));+ }++ [Fact]+ public void From_WithoutErrorFactory_UsesDefault()+ {+ var policy = ShellPolicy.From(r => r.ExitCode is 0 or 1);++ var result = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "Permission denied",+ ExitCode = 2,+ Duration = TimeSpan.Zero,+ };++ Assert.Equal("Permission denied", policy.ErrorFactory(result));+ }++ [Fact]+ public void DefaultPolicy_IsSingleton()+ {+ Assert.Same(ShellPolicy.Default, ShellPolicy.Default);+ }++ [Fact]+ public void DefaultPolicy_ExitCodeNegativeOne_AlwaysReturnsTimeoutMessage()+ {+ var result = new ShellResult+ {+ Command = "test",+ Stdout = "",+ Stderr = "File not found",+ ExitCode = -1,+ Duration = TimeSpan.FromSeconds(30),+ };++ var error = ShellPolicy.Default.ErrorFactory(result);+ Assert.Contains("timed out", error, StringComparison.OrdinalIgnoreCase);+ }+}diff --git a/optimizerDuck/Domain/Exceptions/StepExecutionException.cs b/optimizerDuck/Domain/Exceptions/StepExecutionException.csnew file mode 100644index 0000000..c171b85--- /dev/null+++ b/optimizerDuck/Domain/Exceptions/StepExecutionException.cs@@ -0,0 +1,12 @@+namespace optimizerDuck.Domain.Exceptions;++public class StepExecutionException : Exception+{+ public string? ErrorDetail { get; }++ public StepExecutionException(string? error, string? errorDetail)+ : base(error ?? "Step execution failed")+ {+ ErrorDetail = errorDetail;+ }+}diff --git a/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.csindex 90f76fc..c3fa119 100644--- a/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs@@ -1,6 +1,7 @@using Microsoft.Win32;using Newtonsoft.Json.Linq;using optimizerDuck.Domain.Abstractions;+using optimizerDuck.Domain.Exceptions;using optimizerDuck.Domain.Optimizations.Models.Services;using optimizerDuck.Resources.Languages;using optimizerDuck.Services.OptimizationServices;@@ -102,7 +103,11 @@ public class RegistryRevertStep : IRevertStep};if (!result)- throw new Exception(string.Format(Translations.Revert_Error_StepFailed) + $": {Description}");+ {+ var error = RegistryService.LastError+ ?? Description;+ throw new StepExecutionException(error, RegistryService.LastErrorDetail);+ }// Cleanup empty subkeys if they were created during applyif (result && CreatedSubKeys?.Count > 0)diff --git a/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.csindex 4564dba..7d7c557 100644--- a/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs@@ -1,5 +1,6 @@-using Newtonsoft.Json.Linq;+using Newtonsoft.Json.Linq;using optimizerDuck.Domain.Abstractions;+using optimizerDuck.Domain.Exceptions;using optimizerDuck.Resources.Languages;using optimizerDuck.Services.OptimizationServices;@@ -38,7 +39,15 @@ public class ScheduledTaskRevertStep : IRevertStepvar success = OriginalEnabled? ScheduledTaskService.EnableTask(FullPath): ScheduledTaskService.DisableTask(FullPath);- return Task.FromResult(success);++ if (!success)+ {+ var error = ScheduledTaskService.LastError+ ?? Description;+ throw new StepExecutionException(error, ScheduledTaskService.LastErrorDetail);+ }++ return Task.FromResult(true);}/// <inheritdoc />diff --git a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.csindex daa4a78..78edfbb 100644--- a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs@@ -1,5 +1,6 @@-using Newtonsoft.Json.Linq;+using Newtonsoft.Json.Linq;using optimizerDuck.Domain.Abstractions;+using optimizerDuck.Domain.Exceptions;using optimizerDuck.Domain.Optimizations.Models.Services;using optimizerDuck.Resources.Languages;using optimizerDuck.Services.OptimizationServices;@@ -40,11 +41,13 @@ public class ServiceRevertStep : IRevertStep);if (!result)- throw new Exception(- string.Format(Translations.Service_Service_Error_UpdateRegistryForStartupTypeFailed)- );+ {+ var error = ServiceProcessService.LastError+ ?? Description;+ throw new StepExecutionException(error, ServiceProcessService.LastErrorDetail);+ }- return Task.FromResult(result);+ return Task.FromResult(true);}/// <inheritdoc />diff --git a/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.csindex 927ceb9..ad7cd5d 100644--- a/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs@@ -1,5 +1,6 @@using Newtonsoft.Json.Linq;using optimizerDuck.Domain.Abstractions;+using optimizerDuck.Domain.Exceptions;using optimizerDuck.Domain.Optimizations.Models.Services;using optimizerDuck.Resources.Languages;using optimizerDuck.Services.OptimizationServices;@@ -39,20 +40,21 @@ public class ShellRevertStep : IRevertStep{Command = Command,Stdout = "",- Stderr = "Unknown shell type",+ Stderr = Translations.Revert_Shell_Error_UnknownShellType,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}"- );+ {+ var error = !string.IsNullOrWhiteSpace(result.Stderr)+ ? result.Stderr+ : string.Format(Translations.Revert_Shell_Error_CommandFailed, result.ExitCode);+ throw new StepExecutionException(error, result.Stderr);+ }- return result.ExitCode == 0;+ return true;}/// <inheritdoc />diff --git a/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.csindex 9230002..136c743 100644--- a/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs@@ -2,6 +2,7 @@ using System.Text;using Newtonsoft.Json;using Newtonsoft.Json.Linq;using optimizerDuck.Domain.Abstractions;+using optimizerDuck.Domain.Exceptions;using optimizerDuck.Resources.Languages;using optimizerDuck.Services.OptimizationServices;@@ -52,7 +53,16 @@ public class UsbPowerRevertStep : IRevertStep+ "}}";var result = await ShellService.PowerShellAsync(script);- return result.ExitCode == 0;++ if (result.ExitCode != 0)+ {+ var error = !string.IsNullOrWhiteSpace(result.Stderr)+ ? result.Stderr+ : string.Format(Translations.Revert_UsbPower_Error_CommandFailed, result.ExitCode);+ throw new StepExecutionException(error, result.Stderr);+ }++ return true;}/// <inheritdoc />diff --git a/optimizerDuck/Resources/Languages/Translations.Designer.cs b/optimizerDuck/Resources/Languages/Translations.Designer.csindex 7210e77..88000de 100644--- a/optimizerDuck/Resources/Languages/Translations.Designer.cs+++ b/optimizerDuck/Resources/Languages/Translations.Designer.cs@@ -3800,6 +3800,24 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to Revert command failed with exit code {0}.+ /// </summary>+ internal static string Revert_Shell_Error_CommandFailed {+ get {+ return ResourceManager.GetString("Revert.Shell.Error.CommandFailed", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Unknown shell type.+ /// </summary>+ internal static string Revert_Shell_Error_UnknownShellType {+ get {+ return ResourceManager.GetString("Revert.Shell.Error.UnknownShellType", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to Restore USB selective suspend power states./// </summary>@@ -3809,6 +3827,15 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to USB power revert failed with exit code {0}.+ /// </summary>+ internal static string Revert_UsbPower_Error_CommandFailed {+ get {+ return ResourceManager.GetString("Revert.UsbPower.Error.CommandFailed", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to Delete./// </summary>diff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resxindex b7d161b..2924b80 100644--- a/optimizerDuck/Resources/Languages/Translations.resx+++ b/optimizerDuck/Resources/Languages/Translations.resx@@ -1596,6 +1596,15 @@ Update now to enjoy the latest features, improvements, and bug fixes.</value><data name="Revert.Shell.Description.Run" xml:space="preserve"><value>Run {0} command: {1}</value></data>+ <data name="Revert.Shell.Error.UnknownShellType" xml:space="preserve">+ <value>Unknown shell type</value>+ </data>+ <data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">+ <value>Revert command failed with exit code {0}</value>+ </data>+ <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">+ <value>USB power revert failed with exit code {0}</value>+ </data><data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve"><value>Show completion notification</value></data>diff --git a/optimizerDuck/Services/Optimization/Providers/RegistryService.cs b/optimizerDuck/Services/Optimization/Providers/RegistryService.csindex eabb345..c7b8ba0 100644--- a/optimizerDuck/Services/Optimization/Providers/RegistryService.cs+++ b/optimizerDuck/Services/Optimization/Providers/RegistryService.cs@@ -13,6 +13,12 @@ namespace optimizerDuck.Services.OptimizationServices;public static class RegistryService{+ private static readonly AsyncLocal<string?> _lastError = new();+ private static readonly AsyncLocal<string?> _lastErrorDetail = new();++ internal static string? LastError => _lastError.Value;+ internal static string? LastErrorDetail => _lastErrorDetail.Value;+private static readonly Dictionary<string, RegistryKey> RootKeysMap = new(StringComparer.OrdinalIgnoreCase)@@ -45,6 +51,7 @@ public static class RegistryServiceif (string.IsNullOrWhiteSpace(fullPath)){+ _lastError.Value = _lastErrorDetail.Value = "Registry path is null or empty";ExecutionScope.LogError(null, "Registry path is null or empty");ExecutionScope.Track(nameof(RegistryService), false);return false;@@ -56,6 +63,7 @@ public static class RegistryServiceif (!RootKeysMap.TryGetValue(rootToken, out rootKey)){+ _lastError.Value = _lastErrorDetail.Value = $"Unknown root key: {rootToken}";ExecutionScope.LogError(null, "Unknown root key: {RootToken}", rootToken);ExecutionScope.Track(nameof(RegistryService), false);return false;@@ -178,11 +186,18 @@ public static class RegistryServicereturn name ?? string.Empty;}+ /// <summary>Determines whether the specified registry key path exists.</summary>+ /// <param name="item">The registry path to check.</param>+ /// <returns><see langword="true" /> if the key exists; otherwise, <see langword="false" />.</returns>public static bool KeyExists(RegistryItem item){return WithKey(item, key => true, false);}+ /// <summary>Reads a registry value and converts it to the specified type.</summary>+ /// <typeparam name="T">The target type to convert the value to.</typeparam>+ /// <param name="item">The registry path and value name to read.</param>+ /// <returns>The converted value, or the default of <typeparamref name="T" /> if the value is missing or conversion fails.</returns>public static T? Read<T>(RegistryItem item){return WithKey(@@ -223,10 +238,17 @@ public static class RegistryService);}+ /// <summary>Writes a value to the registry, backing up the previous value for revert.</summary>+ /// <param name="item">The registry path, value name, value, and kind to write.</param>+ /// <returns><see langword="true" /> if the write succeeded; otherwise, <see langword="false" />.</returns>public static bool Write(RegistryItem item){+ _lastError.Value = _lastErrorDetail.Value = null;+if (item.Value == null){+ _lastError.Value = _lastErrorDetail.Value =+ $"Value cannot be null when writing {item.Path}:{item.Name}";ExecutionScope.LogError(null,"Value can't be null when writing {Path}:{Name}",@@ -296,6 +318,12 @@ public static class RegistryService}catch (UnauthorizedAccessException){+ _lastError.Value = Translations.Service_Common_Error_AccessDenied;+ _lastErrorDetail.Value = string.Format(+ Translations.Service_Registry_ErrorDetail_AccessDeniedWrite,+ item.Path,+ item.Name+ );ExecutionScope.LogError(null,"Access denied writing {Path}:{Name}",@@ -308,18 +336,16 @@ public static class RegistryServicedescription,false,null,- Translations.Service_Common_Error_AccessDenied,+ _lastError.Value,() => Task.FromResult(Write(item)),- string.Format(- Translations.Service_Registry_ErrorDetail_AccessDeniedWrite,- item.Path,- item.Name- )+ _lastErrorDetail.Value);return false;}catch (Exception ex){+ _lastError.Value = ex.Message;+ _lastErrorDetail.Value = ex.ToString();ExecutionScope.LogError(ex,"Failed to write registry {Path}:{Name}",@@ -332,9 +358,9 @@ public static class RegistryServicedescription,false,null,- ex.Message,+ _lastError.Value,() => Task.FromResult(Write(item)),- ex.ToString()+ _lastErrorDetail.Value);return false;}@@ -345,8 +371,13 @@ public static class RegistryService);}+ /// <summary>Deletes a registry value, backing up the current value for revert.</summary>+ /// <param name="item">The registry path and value name to delete.</param>+ /// <returns><see langword="true" /> if the value was deleted or did not exist; otherwise, <see langword="false" />.</returns>public static bool DeleteValue(RegistryItem item){+ _lastError.Value = _lastErrorDetail.Value = null;+return WithKey(item,key =>@@ -408,6 +439,12 @@ public static class RegistryService}catch (UnauthorizedAccessException){+ _lastError.Value = Translations.Service_Common_Error_AccessDenied;+ _lastErrorDetail.Value = string.Format(+ Translations.Service_Registry_ErrorDetail_AccessDeniedDelete,+ item.Path,+ item.Name+ );ExecutionScope.LogError(null,"Access denied deleting {Path}:{Name}",@@ -420,18 +457,16 @@ public static class RegistryServicedescription,false,null,- Translations.Service_Common_Error_AccessDenied,+ _lastError.Value,() => Task.FromResult(DeleteValue(item)),- string.Format(- Translations.Service_Registry_ErrorDetail_AccessDeniedDelete,- item.Path,- item.Name- )+ _lastErrorDetail.Value);return false;}catch (Exception ex){+ _lastError.Value = ex.Message;+ _lastErrorDetail.Value = ex.ToString();ExecutionScope.LogError(ex,"Failed to delete registry {Path}:{Name}",@@ -444,9 +479,9 @@ public static class RegistryServicedescription,false,null,- ex.Message,+ _lastError.Value,() => Task.FromResult(DeleteValue(item)),- ex.ToString()+ _lastErrorDetail.Value);return false;}@@ -455,8 +490,13 @@ public static class RegistryService);}+ /// <summary>Creates a registry subkey, tracking created intermediate keys for revert.</summary>+ /// <param name="item">The registry path of the key to create.</param>+ /// <returns><see langword="true" /> if the key was created or already exists; otherwise, <see langword="false" />.</returns>public static bool CreateSubKey(RegistryItem item){+ _lastError.Value = _lastErrorDetail.Value = null;+if (!TryParsePath(item.Path, out var rootKey, out var subPath))return false;@@ -503,6 +543,11 @@ public static class RegistryService}catch (UnauthorizedAccessException){+ _lastError.Value = Translations.Service_Common_Error_AccessDenied;+ _lastErrorDetail.Value = string.Format(+ Translations.Service_Registry_ErrorDetail_AccessDeniedCreateKey,+ item.Path+ );ExecutionScope.LogError(null, "Access denied creating {Path}", item.Path);ExecutionScope.Track(nameof(CreateSubKey), false);ExecutionScope.RecordStep(@@ -510,17 +555,16 @@ public static class RegistryServicedescription,false,null,- Translations.Service_Common_Error_AccessDenied,+ _lastError.Value,() => Task.FromResult(CreateSubKey(item)),- string.Format(- Translations.Service_Registry_ErrorDetail_AccessDeniedCreateKey,- item.Path- )+ _lastErrorDetail.Value);return false;}catch (Exception ex){+ _lastError.Value = ex.Message;+ _lastErrorDetail.Value = ex.ToString();ExecutionScope.LogError(ex, "Failed to create registry {Path}", item.Path);ExecutionScope.Track(nameof(CreateSubKey), false);ExecutionScope.RecordStep(@@ -528,16 +572,21 @@ public static class RegistryServicedescription,false,null,- ex.Message,+ _lastError.Value,() => Task.FromResult(CreateSubKey(item)),- ex.ToString()+ _lastErrorDetail.Value);return false;}}+ /// <summary>Deletes an entire registry key tree, backing up all values and subkeys for revert.</summary>+ /// <param name="item">The registry path of the key tree to delete.</param>+ /// <returns><see langword="true" /> if the tree was deleted or did not exist; otherwise, <see langword="false" />.</returns>public static bool DeleteSubKeyTree(RegistryItem item){+ _lastError.Value = _lastErrorDetail.Value = null;+if (!TryParsePath(item.Path, out var rootKey, out var subPath))return false;@@ -560,6 +609,11 @@ public static class RegistryServicevar (subSteps, backupComplete) = BackupRegistryTree(key, item.Path);if (!backupComplete){+ var msg = string.Format(+ Translations.Service_Registry_Error_BackupTruncated,+ item.Path+ );+ _lastError.Value = _lastErrorDetail.Value = msg;ExecutionScope.LogError(null,"Registry subtree backup truncated for {Path}",@@ -571,10 +625,7 @@ public static class RegistryServicedescription,false,null,- string.Format(- Translations.Service_Registry_Error_BackupTruncated,- item.Path- ),+ _lastError.Value,() => Task.FromResult(DeleteSubKeyTree(item)));return false;@@ -601,6 +652,11 @@ public static class RegistryService}catch (UnauthorizedAccessException){+ _lastError.Value = Translations.Service_Registry_Error_AccessDeniedProtectedHive;+ _lastErrorDetail.Value = string.Format(+ Translations.Service_Registry_ErrorDetail_AccessDeniedDeleteKeyTree,+ item.Path+ );ExecutionScope.LogError(null, "Access denied deleting {Path}", item.Path);ExecutionScope.Track(nameof(DeleteSubKeyTree), false);ExecutionScope.RecordStep(@@ -608,17 +664,16 @@ public static class RegistryServicedescription,false,null,- Translations.Service_Registry_Error_AccessDeniedProtectedHive,+ _lastError.Value,() => Task.FromResult(DeleteSubKeyTree(item)),- string.Format(- Translations.Service_Registry_ErrorDetail_AccessDeniedDeleteKeyTree,- item.Path- )+ _lastErrorDetail.Value);return false;}catch (Exception ex){+ _lastError.Value = ex.Message;+ _lastErrorDetail.Value = ex.ToString();ExecutionScope.LogError(ex, "Failed to delete subkey tree {Path}", item.Path);ExecutionScope.Track(nameof(DeleteSubKeyTree), false);ExecutionScope.RecordStep(@@ -626,9 +681,9 @@ public static class RegistryServicedescription,false,null,- ex.Message,+ _lastError.Value,() => Task.FromResult(DeleteSubKeyTree(item)),- ex.ToString()+ _lastErrorDetail.Value);return false;}@@ -711,12 +766,16 @@ public static class RegistryService}}+ /// <summary>Writes multiple distinct registry values.</summary>+ /// <param name="items">The registry items to write.</param>public static void Write(params RegistryItem[] items){foreach (var item in items.Distinct())Write(item);}+ /// <summary>Deletes multiple distinct registry values.</summary>+ /// <param name="items">The registry items to delete.</param>public static void DeleteValue(params RegistryItem[] items){foreach (var item in items.Distinct())@@ -781,6 +840,7 @@ public static class RegistryService){var path = string.IsNullOrEmpty(subPath) ? root.Name : $"{root.Name}\\{subPath}";+ _lastError.Value = _lastErrorDetail.Value = uiReason;ExecutionScope.LogError(ex, "{Reason}: {Path}", logReason, path);@@ -789,9 +849,7 @@ public static class RegistryServiceExecutionScope.RecordStep(Translations.Service_Registry_Name, path, false, null, uiReason);}- /// <summary>- /// Creates registry subkeys and tracks which ones were created (did not exist before)- /// </summary>+ /// <summary>Creates registry subkeys and tracks which ones were newly created for revert cleanup.</summary>private static RegistryKey CreateSubKeyTrack(RegistryKey root,string subPath,@@ -845,12 +903,9 @@ public static class RegistryService}}- /// <summary>- /// Safely cleanup empty registry keys that were created during apply operation- /// Only deletes keys that:- /// 1. Were created during the apply operation (in createdSubKeys list)- /// 2. Are now empty (no values and no subkeys)- /// </summary>+ /// <summary>Cleans up empty registry keys that were created during the apply operation.</summary>+ /// <remarks>Only deletes keys that were created during apply (tracked in <paramref name="createdSubKeys" />) and are now completely empty — no values and no subkeys.</remarks>+ /// <param name="createdSubKeys">The list of registry key paths that were created.</param>public static void CleanupEmptyKeys(IEnumerable<string> createdSubKeys){// Sort by path length descending to delete deepest keys firstdiff --git a/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs b/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.csindex be125d5..934eaa4 100644--- a/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs+++ b/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs@@ -1,4 +1,4 @@-using System.Collections.ObjectModel;+using System.Collections.ObjectModel;using Microsoft.Win32.TaskScheduler;using optimizerDuck.Domain.Execution;using optimizerDuck.Domain.Revert.Steps;@@ -10,9 +10,13 @@ namespace optimizerDuck.Services.OptimizationServices;public static class ScheduledTaskService{- /// <summary>- /// Checks whether a task at the given full path exists and is enabled.- /// </summary>+ private static readonly AsyncLocal<string?> _lastError = new();+ private static readonly AsyncLocal<string?> _lastErrorDetail = new();++ internal static string? LastError => _lastError.Value;+ internal static string? LastErrorDetail => _lastErrorDetail.Value;++ /// <summary>Checks whether a task at the given full path exists and is enabled.</summary>public static bool IsTaskEnabled(string fullPath){try@@ -32,11 +36,13 @@ public static class ScheduledTaskService}}- /// <summary>- /// Disables a task by full path with logging, tracking, and revert recording.- /// </summary>+ /// <summary>Disables a scheduled task.</summary>+ /// <param name="fullPath">The full path of the task to disable.</param>+ /// <returns><see langword="true" /> if the task was disabled; otherwise, <see langword="false" />.</returns>public static bool DisableTask(string fullPath){+ _lastError.Value = _lastErrorDetail.Value = null;+var description = string.Format(Translations.Service_ScheduledTask_Description_Disable,fullPath@@ -74,6 +80,11 @@ public static class ScheduledTaskService}catch (UnauthorizedAccessException){+ _lastError.Value = Translations.Service_Common_Error_AccessDenied;+ _lastErrorDetail.Value = string.Format(+ Translations.Service_ScheduledTask_ErrorDetail_AccessDeniedDisable,+ fullPath+ );ExecutionScope.LogError(null, "Access denied disabling task {Path}", fullPath);ExecutionScope.Track(nameof(DisableTask), false);ExecutionScope.RecordStep(@@ -81,17 +92,16 @@ public static class ScheduledTaskServicedescription,false,null,- Translations.Service_Common_Error_AccessDenied,+ _lastError.Value,() => System.Threading.Tasks.Task.FromResult(DisableTask(fullPath)),- string.Format(- Translations.Service_ScheduledTask_ErrorDetail_AccessDeniedDisable,- fullPath- )+ _lastErrorDetail.Value);return false;}catch (Exception ex){+ _lastError.Value = ex.Message;+ _lastErrorDetail.Value = ex.ToString();ExecutionScope.LogError(ex, "Failed to disable task {Path}", fullPath);ExecutionScope.Track(nameof(DisableTask), false);ExecutionScope.RecordStep(@@ -99,19 +109,21 @@ public static class ScheduledTaskServicedescription,false,null,- ex.Message,+ _lastError.Value,() => System.Threading.Tasks.Task.FromResult(DisableTask(fullPath)),- ex.ToString()+ _lastErrorDetail.Value);return false;}}- /// <summary>- /// Enables a task by full path with logging, tracking, and revert recording.- /// </summary>+ /// <summary>Enables a scheduled task.</summary>+ /// <param name="fullPath">The full path of the task to enable.</param>+ /// <returns><see langword="true" /> if the task was enabled; otherwise, <see langword="false" />.</returns>public static bool EnableTask(string fullPath){+ _lastError.Value = _lastErrorDetail.Value = null;+var description = string.Format(Translations.Service_ScheduledTask_Description_Enable,fullPath@@ -149,6 +161,11 @@ public static class ScheduledTaskService}catch (UnauthorizedAccessException){+ _lastError.Value = Translations.Service_Common_Error_AccessDenied;+ _lastErrorDetail.Value = string.Format(+ Translations.Service_ScheduledTask_ErrorDetail_AccessDeniedEnable,+ fullPath+ );ExecutionScope.LogError(null, "Access denied enabling task {Path}", fullPath);ExecutionScope.Track(nameof(EnableTask), false);ExecutionScope.RecordStep(@@ -156,17 +173,16 @@ public static class ScheduledTaskServicedescription,false,null,- Translations.Service_Common_Error_AccessDenied,+ _lastError.Value,() => System.Threading.Tasks.Task.FromResult(EnableTask(fullPath)),- string.Format(- Translations.Service_ScheduledTask_ErrorDetail_AccessDeniedEnable,- fullPath- )+ _lastErrorDetail.Value);return false;}catch (Exception ex){+ _lastError.Value = ex.Message;+ _lastErrorDetail.Value = ex.ToString();ExecutionScope.LogError(ex, "Failed to enable task {Path}", fullPath);ExecutionScope.Track(nameof(EnableTask), false);ExecutionScope.RecordStep(@@ -174,17 +190,16 @@ public static class ScheduledTaskServicedescription,false,null,- ex.Message,+ _lastError.Value,() => System.Threading.Tasks.Task.FromResult(EnableTask(fullPath)),- ex.ToString()+ _lastErrorDetail.Value);return false;}}- /// <summary>- /// Recursively retrieves all scheduled tasks from the system.- /// </summary>+ /// <summary>Retrieves all scheduled tasks from the system, including icon extraction.</summary>+ /// <returns>A list of all scheduled tasks.</returns>public static List<ScheduledTaskModel> GetAllTasks(){var results = new List<ScheduledTaskModel>();@@ -212,9 +227,8 @@ public static class ScheduledTaskServicereturn results;}- /// <summary>- /// Returns only tasks that have a LogonTrigger or BootTrigger (startup-related).- /// </summary>+ /// <summary>Returns startup-related tasks — those with a LogonTrigger or BootTrigger.</summary>+ /// <returns>A list of startup-related tasks ordered by name.</returns>public static List<ScheduledTaskModel> GetStartupTasks(){return GetAllTasks()@@ -223,8 +237,13 @@ public static class ScheduledTaskService.ToList();}- public static void RunTask(string fullPath)+ /// <summary>Runs a scheduled task immediately.</summary>+ /// <param name="fullPath">The full path of the task to run.</param>+ /// <returns><see langword="true" /> if the task was started; otherwise, <see langword="false" />.</returns>+ public static bool RunTask(string fullPath){+ _lastError.Value = _lastErrorDetail.Value = null;+try{using var ts = new TaskService();@@ -235,16 +254,24 @@ public static class ScheduledTaskService);task.Run();ExecutionScope.LogInfo("Started task {Path}", fullPath);+ return true;}catch (Exception ex){+ _lastError.Value = ex.Message;+ _lastErrorDetail.Value = ex.ToString();ExecutionScope.LogError(ex, "Failed to run task {Path}", fullPath);- throw;+ return false;}}- public static void StopTask(string fullPath)+ /// <summary>Stops a running scheduled task.</summary>+ /// <param name="fullPath">The full path of the task to stop.</param>+ /// <returns><see langword="true" /> if the task was stopped; otherwise, <see langword="false" />.</returns>+ public static bool StopTask(string fullPath){+ _lastError.Value = _lastErrorDetail.Value = null;+try{using var ts = new TaskService();@@ -255,17 +282,20 @@ public static class ScheduledTaskService);task.Stop();ExecutionScope.LogInfo("Stopped task {Path}", fullPath);+ return true;}catch (Exception ex){+ _lastError.Value = ex.Message;+ _lastErrorDetail.Value = ex.ToString();ExecutionScope.LogError(ex, "Failed to stop task {Path}", fullPath);- throw;+ return false;}}- /// <summary>- /// Gets the current state string of a task by its full path.- /// </summary>+ /// <summary>Gets the current state string of a task.</summary>+ /// <param name="fullPath">The full path of the task.</param>+ /// <returns>The task state string, or <see langword="null" /> if the task is not found or an error occurs.</returns>public static string? GetTaskState(string fullPath){try@@ -285,8 +315,13 @@ public static class ScheduledTaskService}}- public static void DeleteTask(string fullPath)+ /// <summary>Deletes a scheduled task.</summary>+ /// <param name="fullPath">The full path of the task to delete.</param>+ /// <returns><see langword="true" /> if the task was deleted; otherwise, <see langword="false" />.</returns>+ public static bool DeleteTask(string fullPath){+ _lastError.Value = _lastErrorDetail.Value = null;+try{using var ts = new TaskService();@@ -298,17 +333,21 @@ public static class ScheduledTaskServicevar folderPath = task.Folder.Path;ts.GetFolder(folderPath).DeleteTask(task.Name);ExecutionScope.LogInfo("Deleted task {Path}", fullPath);+ return true;}catch (Exception ex){+ _lastError.Value = ex.Message;+ _lastErrorDetail.Value = ex.ToString();ExecutionScope.LogError(ex, "Failed to delete task {Path}", fullPath);- throw;+ return false;}}- /// <summary>- /// [WIP] Registers a new scheduled task from a model definition.- /// </summary>+ /// <summary>[WIP] Registers a new scheduled task from a model definition.</summary>+ /// <param name="folderPath">The target folder path (e.g. <c>\MyApp</c>).</param>+ /// <param name="model">The task definition model.</param>+ /// <exception cref="InvalidOperationException">Failed to create a registry subkey during registration.</exception>public static void RegisterTask(string folderPath, ScheduledTaskModel model){trydiff --git a/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs b/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.csindex 09ea4a9..c681e36 100644--- a/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs+++ b/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs@@ -10,11 +10,17 @@ namespace optimizerDuck.Services.OptimizationServices;public static class ServiceProcessService{+ private static readonly AsyncLocal<string?> _lastError = new();+ private static readonly AsyncLocal<string?> _lastErrorDetail = new();++ internal static string? LastError => _lastError.Value;+ internal static string? LastErrorDetail => _lastErrorDetail.Value;+private static readonly ManagementScope Scope = new(@"\\.\root\cimv2");- /// <summary>- /// Get current startup type of a service- /// </summary>+ /// <summary>Gets the current startup type of a Windows service from the registry.</summary>+ /// <param name="serviceName">The name of the service.</param>+ /// <returns>The startup type, or <see langword="null" /> if the value is unrecognized or an error occurs.</returns>public static ServiceStartupType? GetStartupType(string serviceName){try@@ -50,8 +56,13 @@ public static class ServiceProcessService}}+ /// <summary>Changes a service's startup type by writing the corresponding registry values.</summary>+ /// <param name="item">The service name and target startup type.</param>+ /// <returns><see langword="true" /> if the change succeeded; otherwise, <see langword="false" />.</returns>public static bool ChangeServiceStartupType(ServiceItem item){+ _lastError.Value = _lastErrorDetail.Value = null;+var description = string.Format(Translations.Service_Service_Description_Change,item.Name,@@ -74,12 +85,13 @@ public static class ServiceProcessServicevar serviceKey = $@"HKLM\SYSTEM\CurrentControlSet\Services\{item.Name}";- // 1. Change the main 'Start' valuevar mainSuccess = RegistryService.Write(new RegistryItem(serviceKey, "Start", startValue));+ var regError = RegistryService.LastError;+ var regErrorDetail = RegistryService.LastErrorDetail;- // 2. Handle 'DelayedAutoStart' if necessary+ // handle 'DelayedAutoStart' if necessaryvar delayedSuccess = true;if (item.StartupType == ServiceStartupType.AutomaticDelayedStart)delayedSuccess = RegistryService.Write(@@ -119,6 +131,9 @@ public static class ServiceProcessServicereturn true;}+ _lastError.Value = regError+ ?? Translations.Service_Service_Error_UpdateRegistryForStartupTypeFailed;+ _lastErrorDetail.Value = regErrorDetail;ExecutionScope.LogInfo("[SERVICE][{Name}][FAIL][D={Duration}] startup -> {StartupType}",item.Name,@@ -131,13 +146,19 @@ public static class ServiceProcessServicedescription,false,null,- Translations.Service_Service_Error_UpdateRegistryForStartupTypeFailed,+ _lastError.Value,() => Task.FromResult(ChangeServiceStartupType(item)));return false;}catch (Exception ex){+ _lastError.Value = string.Format(+ Translations.Service_Service_Error_ExceptionOccurred,+ item.Name,+ ex.Message+ );+ _lastErrorDetail.Value = ex.ToString();ExecutionScope.LogError(ex,"[SERVICE][{Name}][FAIL][EXCEPTION] startup -> {StartupType}",@@ -150,17 +171,15 @@ public static class ServiceProcessServicedescription,false,null,- string.Format(- Translations.Service_Service_Error_ExceptionOccurred,- item.Name,- ex.Message- ),+ _lastError.Value,() => Task.FromResult(ChangeServiceStartupType(item)));return false;}}+ /// <summary>Changes the startup type for multiple services.</summary>+ /// <param name="items">The service items to update.</param>public static void ChangeServiceStartupType(params ServiceItem[] items){foreach (var item in items)diff --git a/optimizerDuck/Services/Optimization/Providers/ShellService.cs b/optimizerDuck/Services/Optimization/Providers/ShellService.csindex 5ffac24..8a8dea7 100644--- a/optimizerDuck/Services/Optimization/Providers/ShellService.cs+++ b/optimizerDuck/Services/Optimization/Providers/ShellService.cs@@ -10,12 +10,16 @@ using optimizerDuck.Resources.Languages;namespace optimizerDuck.Services.OptimizationServices;+/// <summary>Defines success criteria and error reporting for shell command execution.</summary>public sealed class ShellPolicy{+ /// <summary>The default policy — exit code 0 means success, error is derived from stderr or exit code.</summary>public static readonly ShellPolicy Default = new();+ /// <summary>Gets or sets a function that determines whether a shell result indicates success.</summary>public Func<ShellResult, bool> IsSuccess { get; init; } = r => r.ExitCode == 0;+ /// <summary>Gets or sets a function that produces an error message from a failed shell result.</summary>public Func<ShellResult, string?> ErrorFactory { get; init; } =r =>r.ExitCode == -1 // if timed out use Error.TimedOut@@ -24,6 +28,10 @@ public sealed class ShellPolicy? string.Format(Translations.Service_Shell_Error_ExitCode, r.ExitCode): r.Stderr;+ /// <summary>Creates a policy with a custom success function and optional error factory.</summary>+ /// <param name="isSuccess">A function that determines whether a result is successful.</param>+ /// <param name="errorFactory">An optional function that produces an error message from a failed result. Defaults to the default error factory.</param>+ /// <returns>A new <see cref="ShellPolicy"/> instance.</returns>public static ShellPolicy From(Func<ShellResult, bool> isSuccess,Func<ShellResult, string?>? errorFactory = null@@ -36,11 +44,17 @@ public sealed class ShellPolicy};}+ /// <summary>Creates a policy that treats specific exit codes as success.</summary>+ /// <param name="okExitCodes">The exit codes considered successful.</param>+ /// <returns>A new <see cref="ShellPolicy"/> instance.</returns>public static ShellPolicy SuccessExitCodes(params int[] okExitCodes){return From(r => okExitCodes.Contains(r.ExitCode));}+ /// <summary>Creates a policy that treats exit codes from 0 to <paramref name="maxOk"/> as success.</summary>+ /// <param name="maxOk">The maximum exit code considered successful (inclusive).</param>+ /// <returns>A new <see cref="ShellPolicy"/> instance.</returns>public static ShellPolicy SuccessExitCodeRange(int maxOk){return From(r => r.ExitCode >= 0 && r.ExitCode <= maxOk);@@ -54,6 +68,8 @@ public static class ShellServiceprivate static IOptionsMonitor<AppSettings>? _options;+ /// <summary>Initializes the shell service with application settings.</summary>+ /// <param name="options">The application settings monitor.</param>public static void Init(IOptionsMonitor<AppSettings> options){_options = options;@@ -578,6 +594,12 @@ public static class ShellService);}+ /// <summary>Runs a command in cmd.exe asynchronously with an optional revert step.</summary>+ /// <param name="command">The command to execute.</param>+ /// <param name="revertStep">The revert step to record.</param>+ /// <param name="policy">The policy for determining success.</param>+ /// <param name="ct">The cancellation token.</param>+ /// <returns>The result of the command execution.</returns>public static Task<ShellResult> CMDAsync(string command,ShellRevertStep? revertStep = null,@@ -588,6 +610,12 @@ public static class ShellServicereturn RunAsync("cmd.exe", "/c", command, nameof(CMD), revertStep, policy, ct);}+ /// <summary>Runs a command in cmd.exe asynchronously with a lazy revert command.</summary>+ /// <param name="command">The command to execute.</param>+ /// <param name="revertCommand">A factory function that provides the revert command.</param>+ /// <param name="policy">The policy for determining success.</param>+ /// <param name="ct">The cancellation token.</param>+ /// <returns>The result of the command execution.</returns>public static Task<ShellResult> CMDAsync(string command,Func<string> revertCommand,@@ -705,6 +733,12 @@ public static class ShellService);}+ /// <summary>Runs a command in PowerShell asynchronously with a specific revert command.</summary>+ /// <param name="command">The command to execute.</param>+ /// <param name="revertCommand">The command to execute for reverting.</param>+ /// <param name="policy">The policy for determining success.</param>+ /// <param name="ct">The cancellation token.</param>+ /// <returns>The result of the command execution.</returns>public static Task<ShellResult> PowerShellAsync(string command,string revertCommand,@@ -728,6 +762,12 @@ public static class ShellService);}+ /// <summary>Runs a command in PowerShell asynchronously with a lazy revert command.</summary>+ /// <param name="command">The command to execute.</param>+ /// <param name="revertFunction">A factory function that provides the revert command.</param>+ /// <param name="policy">The policy for determining success.</param>+ /// <param name="ct">The cancellation token.</param>+ /// <returns>The result of the command execution.</returns>public static Task<ShellResult> PowerShellAsync(string command,Func<string> revertFunction,diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.csindex 6892869..b65d8a9 100644--- a/optimizerDuck/Services/Revert/RevertManager.cs+++ b/optimizerDuck/Services/Revert/RevertManager.cs@@ -6,6 +6,7 @@ using Newtonsoft.Json;using Newtonsoft.Json.Linq;using optimizerDuck.Common.Helpers;using optimizerDuck.Domain.Abstractions;+using optimizerDuck.Domain.Exceptions;using optimizerDuck.Domain.Execution;using optimizerDuck.Domain.Optimizations.Models;using optimizerDuck.Domain.Revert;@@ -116,6 +117,8 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _loggestep.Type,optimization.OptimizationKey);++ var stepEx = ex as StepExecutionException;failedSteps.Add(new OperationStepResult{@@ -123,7 +126,8 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _loggeName = step.Type,Description = step.Description,Success = false,- Error = ex.Message,+ Error = stepEx?.Message ?? ex.Message,+ ErrorDetail = stepEx?.ErrorDetail,RetryAction = () => step.ExecuteAsync(),});diff --git a/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.csindex 8ebe651..4c7b785 100644--- a/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs@@ -149,22 +149,39 @@ public partial class ScheduledTasksViewModel : ViewModelreturn;try{- await Task.Run(() => ScheduledTaskService.RunTask(task.FullPath));- _logger.LogInformation("Ran task {Name} ({Path})", task.Name, task.FullPath);+ var success = await Task.Run(() => ScheduledTaskService.RunTask(task.FullPath));- _snackbarService.Show(- Translations.ScheduledTasks_Snackbar_Run_Title,- string.Format(Translations.ScheduledTasks_Snackbar_Run_Message, task.Name),- ControlAppearance.Success,- new SymbolIcon { Symbol = SymbolRegular.Play24, Filled = true },- TimeSpan.FromSeconds(3)- );+ if (success)+ {+ _logger.LogInformation("Ran task {Name} ({Path})", task.Name, task.FullPath);- await RefreshTaskState(task);+ _snackbarService.Show(+ Translations.ScheduledTasks_Snackbar_Run_Title,+ string.Format(Translations.ScheduledTasks_Snackbar_Run_Message, task.Name),+ ControlAppearance.Success,+ new SymbolIcon { Symbol = SymbolRegular.Play24, Filled = true },+ TimeSpan.FromSeconds(3)+ );++ await RefreshTaskState(task);+ }+ else+ {+ var error = ScheduledTaskService.LastError ?? Translations.ScheduledTasks_Error_TaskNotFound;+ _logger.LogError("Failed to run task {Name} ({Path}): {Error}", task.Name, task.FullPath, error);++ _snackbarService.Show(+ Translations.ScheduledTasks_Snackbar_Error_Title,+ error,+ ControlAppearance.Danger,+ new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },+ TimeSpan.FromSeconds(5)+ );+ }}catch (Exception ex){- _logger.LogError(ex, "Failed to run task {Name} ({Path})", task.Name, task.FullPath);+ _logger.LogError(ex, "Unexpected error running task {Name} ({Path})", task.Name, task.FullPath);_snackbarService.Show(Translations.ScheduledTasks_Snackbar_Error_Title,@@ -183,22 +200,39 @@ public partial class ScheduledTasksViewModel : ViewModelreturn;try{- await Task.Run(() => ScheduledTaskService.StopTask(task.FullPath));- _logger.LogInformation("Stopped task {Name} ({Path})", task.Name, task.FullPath);+ var success = await Task.Run(() => ScheduledTaskService.StopTask(task.FullPath));- _snackbarService.Show(- Translations.ScheduledTasks_Snackbar_Stop_Title,- string.Format(Translations.ScheduledTasks_Snackbar_Stop_Message, task.Name),- ControlAppearance.Success,- new SymbolIcon { Symbol = SymbolRegular.Stop24, Filled = true },- TimeSpan.FromSeconds(3)- );+ if (success)+ {+ _logger.LogInformation("Stopped task {Name} ({Path})", task.Name, task.FullPath);- await RefreshTaskState(task);+ _snackbarService.Show(+ Translations.ScheduledTasks_Snackbar_Stop_Title,+ string.Format(Translations.ScheduledTasks_Snackbar_Stop_Message, task.Name),+ ControlAppearance.Success,+ new SymbolIcon { Symbol = SymbolRegular.Stop24, Filled = true },+ TimeSpan.FromSeconds(3)+ );++ await RefreshTaskState(task);+ }+ else+ {+ var error = ScheduledTaskService.LastError ?? Translations.ScheduledTasks_Error_TaskNotFound;+ _logger.LogError("Failed to stop task {Name} ({Path}): {Error}", task.Name, task.FullPath, error);++ _snackbarService.Show(+ Translations.ScheduledTasks_Snackbar_Error_Title,+ error,+ ControlAppearance.Danger,+ new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },+ TimeSpan.FromSeconds(5)+ );+ }}catch (Exception ex){- _logger.LogError(ex, "Failed to stop task {Name} ({Path})", task.Name, task.FullPath);+ _logger.LogError(ex, "Unexpected error stopping task {Name} ({Path})", task.Name, task.FullPath);_snackbarService.Show(Translations.ScheduledTasks_Snackbar_Error_Title,@@ -230,22 +264,39 @@ public partial class ScheduledTasksViewModel : ViewModeltry{- await Task.Run(() => ScheduledTaskService.DeleteTask(task.FullPath));- _logger.LogInformation("Deleted task {Name} ({Path})", task.Name, task.FullPath);- _allTasks.RemoveAll(t => t.FullPath == task.FullPath);- ApplyFilter();+ var success = await Task.Run(() => ScheduledTaskService.DeleteTask(task.FullPath));- _snackbarService.Show(- Translations.ScheduledTasks_Snackbar_Delete_Title,- string.Format(Translations.ScheduledTasks_Snackbar_Delete_Message, task.Name),- ControlAppearance.Success,- new SymbolIcon { Symbol = SymbolRegular.Delete24, Filled = true },- TimeSpan.FromSeconds(3)- );+ if (success)+ {+ _logger.LogInformation("Deleted task {Name} ({Path})", task.Name, task.FullPath);+ _allTasks.RemoveAll(t => t.FullPath == task.FullPath);+ ApplyFilter();++ _snackbarService.Show(+ Translations.ScheduledTasks_Snackbar_Delete_Title,+ string.Format(Translations.ScheduledTasks_Snackbar_Delete_Message, task.Name),+ ControlAppearance.Success,+ new SymbolIcon { Symbol = SymbolRegular.Delete24, Filled = true },+ TimeSpan.FromSeconds(3)+ );+ }+ else+ {+ var error = ScheduledTaskService.LastError ?? Translations.ScheduledTasks_Error_TaskNotFound;+ _logger.LogError("Failed to delete task {Name} ({Path}): {Error}", task.Name, task.FullPath, error);++ _snackbarService.Show(+ Translations.ScheduledTasks_Snackbar_Error_Title,+ error,+ ControlAppearance.Danger,+ new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },+ TimeSpan.FromSeconds(5)+ );+ }}catch (Exception ex){- _logger.LogError(ex, "Failed to delete task {Name} ({Path})", task.Name, task.FullPath);+ _logger.LogError(ex, "Unexpected error deleting task {Name} ({Path})", task.Name, task.FullPath);_snackbarService.Show(Translations.ScheduledTasks_Snackbar_Error_Title,