Skip to content

Free, open-source Windows optimization tool for performance, privacy, and simplicity.

feat(execution): record why a step wrote nothing

fatDuckd563f8ccc8e1
diff --git a/optimizerDuck.Test/Domain/Optimizations/PowerManagementTests.cs b/optimizerDuck.Test/Domain/Optimizations/PowerManagementTests.cs
index d2909e7..a3da46d 100644
--- a/optimizerDuck.Test/Domain/Optimizations/PowerManagementTests.cs
+++ b/optimizerDuck.Test/Domain/Optimizations/PowerManagementTests.cs
@@ -1,5 +1,8 @@
using Microsoft.Extensions.Logging.Abstractions;
using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Categories;
+using optimizerDuck.Domain.Revert.Steps;
+using optimizerDuck.Domain.UI;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Services.System.Primitives;
@@ -23,4 +26,48 @@ public class PowerManagementTests
RegistryService.DeleteSubKeyTree(call, new RegistryItem(key));
}
}
+ [Theory]
+ [InlineData(false, false)]
+ [InlineData(true, true)]
+ [InlineData(null, true)]
+ public void NeedsHibernationChange_OnlySkipsAFileThatIsKnownAbsent(
+ bool? wasPresent,
+ bool expected
+ )
+ {
+ // An unreadable state is attempted: a failed read is not "already disabled".
+ Assert.Equal(
+ expected,
+ PowerManagement.DisableHibernateAndFastStartup.NeedsHibernationChange(wasPresent)
+ );
+ }
+
+ [Fact]
+ public void Apply_NoUsbDeviceChanged_RecordsSkipWithoutCompensation()
+ {
+ var call = new OpCall { Logger = NullLogger.Instance };
+ var revertStep = new UsbPowerRevertStep
+ {
+ States =
+ [
+ new UsbPowerRevertStep.DeviceState
+ {
+ InstanceName = @"USB\ROOT_HUB30\1",
+ Enable = false,
+ },
+ ],
+ };
+
+ var result = PowerManagement.DisableUSBPowerSaving.Apply(
+ call,
+ revertStep,
+ new UsbPowerService.UsbPowerWriteResult(0, [])
+ );
+
+ Assert.True(result.Ok);
+ var step = Assert.Single(call.Changes.Changes);
+ Assert.Equal(ChangeKind.Skip, step.Kind);
+ Assert.Null(step.Revert);
+ Assert.Null(result.Revert);
+ }
}
diff --git a/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.cs b/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.cs
index bd55ff5..8a80b7b 100644
--- a/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.cs
+++ b/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.cs
@@ -9,19 +9,18 @@ namespace optimizerDuck.Test.Domain.Revert.Steps;
public class ScheduledTaskRevertStepTests
{
[Fact]
- public async Task ExecuteAsync_WithMissingTask_ThrowsStepExecutionException()
+ public async Task ExecuteAsync_WithMissingTask_SucceedsBecauseThereIsNothingToRestore()
{
+ // Deliberate reversal: a missing task used to fail inside the provider before the step's
+ // own check ran. The provider now reports it as nothing to change, so the step reaches the
+ // branch it was written for: a task that no longer exists has nothing to restore.
var step = new ScheduledTaskRevertStep
{
FullPath = @"\NonExistent\OptimizerDuckTestTask",
OriginalEnabled = true,
};
- var ex = await Assert.ThrowsAsync<StepExecutionException>(() =>
- step.ExecuteAsync(TestShell.Context(), NullLogger.Instance)
- );
-
- Assert.Contains("NonExistent", ex.Message);
+ Assert.True(await step.ExecuteAsync(TestShell.Context(), NullLogger.Instance));
}
[Fact]
diff --git a/optimizerDuck.Test/Domain/UI/ChangeKindPresentationTests.cs b/optimizerDuck.Test/Domain/UI/ChangeKindPresentationTests.cs
new file mode 100644
index 0000000..a68609b
--- /dev/null
+++ b/optimizerDuck.Test/Domain/UI/ChangeKindPresentationTests.cs
@@ -0,0 +1,35 @@
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.UI;
+
+namespace optimizerDuck.Test.Domain.UI;
+
+public class ChangeKindPresentationTests
+{
+ [Theory]
+ [InlineData(ChangeKind.Change, "Optimizer.Details.Step.Changed")]
+ [InlineData(ChangeKind.Skip, "Optimizer.Details.Step.AlreadyCorrect")]
+ [InlineData(ChangeKind.NotApplicable, "Optimizer.Details.Step.NotApplicable")]
+ [InlineData(ChangeKind.Refused, "Optimizer.Details.Step.Refused")]
+ [InlineData(ChangeKind.Irreversible, "Optimizer.Details.Step.Irreversible")]
+ public void ToDisplay_MapsEveryKindToItsOwnLabel(ChangeKind kind, string labelKey)
+ {
+ Assert.Equal(labelKey, kind.ToDisplay().LabelKey);
+ }
+
+ [Fact]
+ public void ToDisplay_GivesEveryKindItsOwnIcon()
+ {
+ var icons = Enum.GetValues<ChangeKind>().Select(kind => kind.ToDisplay().Icon).ToList();
+
+ Assert.Equal(icons.Count, icons.Distinct().Count());
+ }
+
+ [Fact]
+ public void ToDisplay_UnknownKind_FallsBackToTheChangeAppearance()
+ {
+ // A kind written by a newer version stays visible instead of disappearing.
+ var display = ((ChangeKind)999).ToDisplay();
+
+ Assert.Equal("Optimizer.Details.Step.Changed", display.LabelKey);
+ }
+}
diff --git a/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs b/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
index b880ec3..9f0af06 100644
--- a/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
@@ -76,13 +76,16 @@ public class ChangeSetTests
}
[Fact]
- public void ToApplyResult_Empty_ReturnsFailure()
+ public void ToApplyResult_Empty_ReturnsSuccess()
{
+ // Deliberate reversal: an item can legitimately match nothing on this machine, so a run
+ // that recorded no step at all is nothing to do rather than a failure. A provider that
+ // changed something without recording it is caught by the compensation guard instead.
var changes = new ChangeSet();
var result = changes.ToApplyResult();
- Assert.NotNull(result.ErrorMessage);
+ Assert.Null(result.ErrorMessage);
}
[Fact]
@@ -198,4 +201,39 @@ public class MockRevertStep : IRevertStep
{
return new MockRevertStep();
}
+ [Fact]
+ public void AddNotApplicable_RecordsStepWithoutCompensation()
+ {
+ var changes = new ChangeSet();
+
+ changes.AddNotApplicable("Service", "Service 'x' not found (not present)");
+
+ var change = Assert.Single(changes.Changes);
+ Assert.True(change.Ok);
+ Assert.Equal(ChangeKind.NotApplicable, change.Kind);
+ Assert.Null(change.Revert);
+ }
+
+ [Fact]
+ public void AddRefused_RecordsStepWithoutCompensation()
+ {
+ var changes = new ChangeSet();
+
+ changes.AddRefused("Service", "Access to service 'x' is denied by Windows");
+
+ var change = Assert.Single(changes.Changes);
+ Assert.True(change.Ok);
+ Assert.Equal(ChangeKind.Refused, change.Kind);
+ Assert.Null(change.Revert);
+ }
+
+ [Fact]
+ public void DidApplyAnything_IgnoresNotApplicableAndRefusedSteps()
+ {
+ var changes = new ChangeSet();
+ changes.AddNotApplicable("Service", "not present");
+ changes.AddRefused("Service", "protected");
+
+ Assert.False(changes.DidApplyAnything);
+ }
}
diff --git a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
index b8e81b2..7b0fd2c 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
@@ -473,4 +473,63 @@ public class RegistryServiceTests : IDisposable
RegistryService.Read<string>(new RegistryItem(nonEmptyKeyPath, "Value"))
);
}
+ [Fact]
+ public void Write_ValueAlreadySet_RecordsSkip()
+ {
+ var path = $@"{BaseTestKey}\AlreadySet";
+ Assert.True(RegistryService.Write(NewCall(), new RegistryItem(path, "V", 1)).Ok);
+
+ var call = NewCall();
+ Assert.True(RegistryService.Write(call, new RegistryItem(path, "V", 1)).Ok);
+
+ var step = Assert.Single(call.Changes.Changes);
+ Assert.Equal(ChangeKind.Skip, step.Kind);
+ Assert.Null(step.Revert);
+ }
+
+ [Fact]
+ public void DeleteValue_AbsentValue_RecordsNotApplicable()
+ {
+ var path = $@"{BaseTestKey}\AbsentValue";
+
+ // The key has to exist, otherwise the delete fails before it can look at the value.
+ Assert.True(RegistryService.Write(NewCall(), new RegistryItem(path, "Keep", 1)).Ok);
+
+ var call = NewCall();
+ Assert.True(RegistryService.DeleteValue(call, new RegistryItem(path, "Missing")).Ok);
+
+ var step = Assert.Single(call.Changes.Changes);
+ Assert.Equal(ChangeKind.NotApplicable, step.Kind);
+ Assert.Null(step.Revert);
+ }
+
+ [Fact]
+ public void CreateSubKey_ExistingKey_RecordsNotApplicable()
+ {
+ var path = $@"{BaseTestKey}\ExistingKey";
+ Assert.True(RegistryService.Write(NewCall(), new RegistryItem(path, "V", 1)).Ok);
+
+ var call = NewCall();
+ Assert.True(RegistryService.CreateSubKey(call, new RegistryItem(path)).Ok);
+
+ var step = Assert.Single(call.Changes.Changes);
+ Assert.Equal(ChangeKind.NotApplicable, step.Kind);
+ Assert.Null(step.Revert);
+ }
+
+ [Fact]
+ public void DeleteSubKeyTree_AbsentTree_RecordsNotApplicable()
+ {
+ var call = NewCall();
+
+ Assert.True(
+ RegistryService
+ .DeleteSubKeyTree(call, new RegistryItem($@"{BaseTestKey}\AbsentTree"))
+ .Ok
+ );
+
+ var step = Assert.Single(call.Changes.Changes);
+ Assert.Equal(ChangeKind.NotApplicable, step.Kind);
+ Assert.Null(step.Revert);
+ }
}
diff --git a/optimizerDuck.Test/Services/OptimizationServices/ScheduledTaskServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/ScheduledTaskServiceTests.cs
index e45d67d..634f241 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/ScheduledTaskServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/ScheduledTaskServiceTests.cs
@@ -71,6 +71,14 @@ public class ScheduledTaskServiceTests
// Disable again first, so enabling really changes the state.
Assert.True(ScheduledTaskService.DisableTask(NewCall(), fullPath).Ok);
+ // Already disabled: the provider records the step and writes nothing, so a caller
+ // that delegates here never has to decide on its own.
+ var alreadyDisabledCall = NewCall();
+ Assert.True(ScheduledTaskService.DisableTask(alreadyDisabledCall, fullPath).Ok);
+ var alreadyDisabledStep = Assert.Single(alreadyDisabledCall.Changes.Changes);
+ Assert.Equal(ChangeKind.Skip, alreadyDisabledStep.Kind);
+ Assert.Null(alreadyDisabledStep.Revert);
+
// Enable: the recorded step must carry "was disabled" and restore that.
var enableCall = NewCall();
var enabled = ScheduledTaskService.EnableTask(enableCall, fullPath);
@@ -99,4 +107,22 @@ public class ScheduledTaskServiceTests
private static OpCall NewCall() =>
new() { Changes = new ChangeSet(), Logger = NullLogger.Instance };
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void TaskMissing_RecordsNotApplicableRatherThanFailure(bool disable)
+ {
+ var fullPath = $@"\{Guid.NewGuid():N}OptimizerDuckMissingTask";
+ var call = NewCall();
+
+ var result = disable
+ ? ScheduledTaskService.DisableTask(call, fullPath)
+ : ScheduledTaskService.EnableTask(call, fullPath);
+
+ // Nothing on this machine to configure, and nothing to undo either.
+ Assert.True(result.Ok, result.Error);
+ var step = Assert.Single(call.Changes.Changes);
+ Assert.Equal(ChangeKind.NotApplicable, step.Kind);
+ Assert.Null(step.Revert);
+ }
}
diff --git a/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
index 79c8383..6178e3e 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
@@ -398,11 +398,12 @@ public class ServiceProcessServiceTests
new ServiceItem(TestServiceName, ServiceStartupType.Disabled)
);
- // Windows protects this service. That is a skip, not a failure: the call reports
- // success for the batch and records no revert step for the protected item.
+ // Windows protects this service. That is a refusal, not a failure: the call reports
+ // success for the batch, records no revert step, and the step says Windows refused
+ // rather than that the machine already matched.
Assert.True(result.Ok, result.Error);
var change = Assert.Single(call.Changes.Changes);
- Assert.Equal(ChangeKind.Skip, change.Kind);
+ Assert.Equal(ChangeKind.Refused, change.Kind);
Assert.Null(change.Revert);
}
finally
diff --git a/optimizerDuck/Domain/Execution/ChangeSet.cs b/optimizerDuck/Domain/Execution/ChangeSet.cs
index dc0eb4d..6c8f597 100644
--- a/optimizerDuck/Domain/Execution/ChangeSet.cs
+++ b/optimizerDuck/Domain/Execution/ChangeSet.cs
@@ -82,6 +82,20 @@ public sealed class ChangeSet
public Change AddSkip(string name, string description) =>
Add(name, description, true, kind: ChangeKind.Skip);
+ /// <summary>
+ /// Records a step whose target does not exist on this machine, so nothing was written
+ /// and no compensation is expected.
+ /// </summary>
+ public Change AddNotApplicable(string name, string description) =>
+ Add(name, description, true, kind: ChangeKind.NotApplicable);
+
+ /// <summary>
+ /// Records a step Windows refused, so nothing was written and no compensation is
+ /// expected for it.
+ /// </summary>
+ public Change AddRefused(string name, string description) =>
+ Add(name, description, true, kind: ChangeKind.Refused);
+
/// <summary>
/// Records a step that modified the system on purpose with no way back, so no
/// compensation is expected for it.
@@ -130,8 +144,12 @@ public sealed class ChangeSet
{
lock (_gate)
{
+ // Recording no step at all is a legitimate outcome: an item can match nothing on
+ // this machine, and a run whose steps were all skipped still recorded them. A
+ // provider that changes something without recording it is caught by the
+ // compensation guard in RevertManager, not by failing the user's apply here.
if (_changes.Count == 0)
- return ApplyResult.False(fallbackError ?? Loc.Instance["Revert.Error.NoSteps"]);
+ return ApplyResult.True();
if (_changes.Any(c => c.Ok))
return ApplyResult.True();
return ApplyResult.False(
@@ -180,9 +198,15 @@ public enum ChangeKind
/// <summary>The step modified the system and carries the data needed to undo it.</summary>
Change,
- /// <summary>The step found nothing to do, so there is nothing to undo.</summary>
+ /// <summary>The system already had the desired state, so nothing was written.</summary>
Skip,
+ /// <summary>There was nothing on this machine to act on, so nothing was written.</summary>
+ NotApplicable,
+
+ /// <summary>Windows refused the change, so nothing was written.</summary>
+ Refused,
+
/// <summary>The step modified the system on purpose with no way back.</summary>
Irreversible,
}
diff --git a/optimizerDuck/Domain/Optimizations/Categories/AI.cs b/optimizerDuck/Domain/Optimizations/Categories/AI.cs
index 122069b..217ef91 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/AI.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/AI.cs
@@ -67,7 +67,7 @@ public class AI : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled Windows Recall AI snapshots");
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -98,7 +98,7 @@ public class AI : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled Click To Do AI overlay");
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
}
diff --git a/optimizerDuck/Domain/Optimizations/Categories/Performance.cs b/optimizerDuck/Domain/Optimizations/Categories/Performance.cs
index 83fb943..549da88 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/Performance.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/Performance.cs
@@ -47,7 +47,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled background apps");
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -89,7 +89,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
"Consolidated service hosts with threshold: {ThresholdKB} KB",
context.Snapshot.Memory.TotalKB
);
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -138,7 +138,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
"Enabled foreground boost with priority: {Priority}",
win32Priority
);
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -192,7 +192,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
context.Logger.LogInformation(
"Optimized Multimedia Class Scheduler Service (MMCSS) for gaming and low latency"
);
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -215,7 +215,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
);
context.Logger.LogInformation("Optimized keyboard repeat settings");
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -251,7 +251,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
);
context.Logger.LogInformation("Disabled accessibility keyboard hotkeys");
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -278,7 +278,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
);
context.Logger.LogInformation("Lifted the WebDAV file size limit to 4 GB");
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
}
diff --git a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
index f9ce8e1..df8dd25 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
@@ -52,8 +52,26 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
return Task.FromResult(context.Changes.ToApplyResult());
}
+ /// <summary>
+ /// Whether the native call is needed. An unknown state is attempted, because a failed
+ /// read is not the same as "already disabled".
+ /// </summary>
+ internal static bool NeedsHibernationChange(bool? wasPresent) => wasPresent is not false;
+
internal static OpResult Apply(OpCall call, bool? wasPresent)
{
+ if (!NeedsHibernationChange(wasPresent))
+ {
+ // Disabling a file that is already gone would call a privileged API for nothing
+ // and could fail, turning a correct machine into a failed apply.
+ call.Changes.AddSkip(
+ ServiceStrings.HibernationName,
+ ServiceStrings.HibernationDescriptionDisable
+ );
+ call.Logger.LogInformation("Hibernation already disabled, skipping");
+ return OpResult.Success();
+ }
+
var result = HibernationService.SetHibernationFile(present: false);
var revert = new HibernationRevertStep { WasPresent = wasPresent };
@@ -111,8 +129,12 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
var captured = UsbPowerService.Capture();
if (captured.Count == 0)
{
- context.Logger.LogInformation("No USB devices found, skipping");
- return Task.FromResult(ApplyResult.True());
+ context.Logger.LogInformation("No USB devices found, nothing to change");
+ context.Changes.AddNotApplicable(
+ ServiceStrings.UsbPowerName,
+ ServiceStrings.UsbPowerInfoNoDevices
+ );
+ return Task.FromResult(context.Changes.ToApplyResult());
}
context.Logger.LogInformation("Disabling USB power saving");
@@ -167,6 +189,18 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
return OpResult.Fail(ServiceStrings.UsbPowerErrorChangeFailed, detail);
}
+ if (result is { ChangedCount: 0 })
+ {
+ // Every device already matched the target, so nothing was written and there is
+ // nothing to restore.
+ call.Logger.LogInformation("[USB][SKIP] every device already at the target");
+ call.Changes.AddSkip(
+ ServiceStrings.UsbPowerName,
+ ServiceStrings.UsbPowerInfoAlreadyConfigured
+ );
+ return OpResult.Success();
+ }
+
if (result is not null)
{
call.Changes.Add(ServiceStrings.UsbPowerName, description, true, revertStep);
diff --git a/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs b/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs
index 3ac274e..01bec6f 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs
@@ -166,10 +166,8 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
foreach (var task in tasksToDelete)
{
- var state = ScheduledTaskService.GetTaskEnabledState(task, context.Logger);
- // skip when known-disabled or absent; on unknown state, attempt so the outcome is real.
- if (state is TaskEnabledState.Disabled or TaskEnabledState.NotFound)
- continue;
+ // The provider records what it found, so a task that is already disabled or
+ // absent still leaves a step: deciding here would drop it from the record.
ScheduledTaskService.DisableTask(context, task);
}
@@ -221,9 +219,8 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
foreach (var task in tasksToDelete)
{
- var state = ScheduledTaskService.GetTaskEnabledState(task, context.Logger);
- if (state is TaskEnabledState.Disabled or TaskEnabledState.NotFound)
- continue;
+ // The provider records what it found, so a task that is already disabled or
+ // absent still leaves a step: deciding here would drop it from the record.
ScheduledTaskService.DisableTask(context, task);
}
diff --git a/optimizerDuck/Domain/Optimizations/Categories/UserExperience.cs b/optimizerDuck/Domain/Optimizations/Categories/UserExperience.cs
index 2f66f25..2924e9a 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/UserExperience.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/UserExperience.cs
@@ -45,7 +45,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
new RegistryItem(@"HKCU\Control Panel\Desktop", "MenuShowDelay", "0")
);
context.Logger.LogInformation("Speeded up Explorer and menus");
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -81,7 +81,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
new RegistryItem(@"HKCU\Software\Microsoft\Windows\DWM", "EnableAeroPeek", 0)
);
context.Logger.LogInformation("Disabled visual effects for better performance");
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -106,7 +106,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled web search for Start Menu");
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -132,7 +132,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled Recommended section in Start Menu");
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -157,7 +157,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled Microsoft 365 ads in Settings");
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -185,7 +185,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
);
context.Logger.LogInformation("Maximized the Windows Update pause limit");
- return Task.FromResult(CompleteFromScope(context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
}
diff --git a/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs b/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs
index b1ba56f..0bec08b 100644
--- a/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs
+++ b/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs
@@ -190,10 +190,4 @@ public abstract partial class BaseOptimization : LocalizedObject, IOptimization
IProgress<ProcessingProgress> progress,
OptimizationContext context
);
-
- /// <summary>Returns result from changes recorded into <paramref name="call"/>.</summary>
- protected static ApplyResult CompleteFromScope(OpCall call)
- {
- return call.Changes.ToApplyResult();
- }
}
diff --git a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs
index 86ef23e..d224a86 100644
--- a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs
+++ b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs
@@ -48,7 +48,7 @@ public class ServiceRevertStep : IRevertStep
// Fail closed: access-denied returns false so RevertManager records a failed
// step; every other failure throws with provider error detail.
var accessDenied = ServiceStrings.Format(
- ServiceStrings.ServiceInfoSkippedAccessDenied,
+ ServiceStrings.ServiceInfoAccessDenied,
ServiceName
);
if (string.Equals(result.Error, accessDenied, StringComparison.Ordinal))
diff --git a/optimizerDuck/Domain/UI/ChangeKindPresentation.cs b/optimizerDuck/Domain/UI/ChangeKindPresentation.cs
new file mode 100644
index 0000000..e34fead
--- /dev/null
+++ b/optimizerDuck/Domain/UI/ChangeKindPresentation.cs
@@ -0,0 +1,59 @@
+using optimizerDuck.Domain.Execution;
+using Wpf.Ui.Controls;
+
+namespace optimizerDuck.Domain.UI;
+
+/// <summary>
+/// How the record presents one kind of recorded step: an icon and the resource key of its
+/// label. The key is carried rather than the resolved text so the mapping stays testable
+/// and the label follows the UI language.
+/// </summary>
+public sealed record ChangeKindDisplay
+{
+ public SymbolRegular Icon { get; init; }
+
+ public string LabelKey { get; init; } = string.Empty;
+}
+
+/// <summary>
+/// Maps a recorded kind of step to its presentation. An unrecognized kind falls back to the
+/// appearance of a change, so a mistake is visible instead of hidden.
+/// </summary>
+public static class ChangeKindPresentation
+{
+ extension(ChangeKind kind)
+ {
+ /// <summary>Gets the icon and label key this kind of step is shown with.</summary>
+ public ChangeKindDisplay ToDisplay()
+ {
+ return kind switch
+ {
+ ChangeKind.Skip => new ChangeKindDisplay
+ {
+ Icon = SymbolRegular.CheckmarkCircle24,
+ LabelKey = "Optimizer.Details.Step.AlreadyCorrect",
+ },
+ ChangeKind.NotApplicable => new ChangeKindDisplay
+ {
+ Icon = SymbolRegular.Info24,
+ LabelKey = "Optimizer.Details.Step.NotApplicable",
+ },
+ ChangeKind.Refused => new ChangeKindDisplay
+ {
+ Icon = SymbolRegular.ShieldError24,
+ LabelKey = "Optimizer.Details.Step.Refused",
+ },
+ ChangeKind.Irreversible => new ChangeKindDisplay
+ {
+ Icon = SymbolRegular.ArrowClockwise24,
+ LabelKey = "Optimizer.Details.Step.Irreversible",
+ },
+ _ => new ChangeKindDisplay
+ {
+ Icon = SymbolRegular.Edit24,
+ LabelKey = "Optimizer.Details.Step.Changed",
+ },
+ };
+ }
+ }
+}
diff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.cs
index 932756b..1997922 100644
--- a/optimizerDuck/Services/Optimization/OptimizationService.cs
+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs
@@ -311,6 +311,12 @@ public class OptimizationService(
// revert data exists for it, and the card is marked for this session only.
if (!changes.DidApplyAnything)
{
+ if (changes.Changes.Count == 0)
+ _logger.LogWarning(
+ "Apply of {OptimizationKey} recorded no step at all; the provider may have returned without recording",
+ optimization.OptimizationKey
+ );
+
_logger.LogInformation(
"Apply of {OptimizationKey} changed nothing, reporting nothing to do",
optimization.OptimizationKey
diff --git a/optimizerDuck/Services/System/Primitives/RegistryService.cs b/optimizerDuck/Services/System/Primitives/RegistryService.cs
index ef98775..71620ee 100644
--- a/optimizerDuck/Services/System/Primitives/RegistryService.cs
+++ b/optimizerDuck/Services/System/Primitives/RegistryService.cs
@@ -531,7 +531,7 @@ public static class RegistryService
item.Path,
item.Name!
);
- call.Changes.AddSkip(name, description);
+ call.Changes.AddNotApplicable(name, description);
return OpResult.Success();
}
@@ -644,7 +644,7 @@ public static class RegistryService
if (regKey != null)
{
logger.LogInformation("Skip create registry {Path} (already exists)", item.Path);
- call.Changes.AddSkip(name, description);
+ call.Changes.AddNotApplicable(name, description);
return OpResult.Success();
}
@@ -722,7 +722,7 @@ public static class RegistryService
if (regKey == null)
{
logger.LogInformation("Skip delete registry key {Path} (not found)", item.Path);
- call.Changes.AddSkip(name, description);
+ call.Changes.AddNotApplicable(name, description);
return OpResult.Success();
}
diff --git a/optimizerDuck/Services/System/Primitives/ScheduledTaskService.cs b/optimizerDuck/Services/System/Primitives/ScheduledTaskService.cs
index c08d05d..edfd0bc 100644
--- a/optimizerDuck/Services/System/Primitives/ScheduledTaskService.cs
+++ b/optimizerDuck/Services/System/Primitives/ScheduledTaskService.cs
@@ -57,11 +57,18 @@ public static class ScheduledTaskService
try
{
using var ts = new TaskService();
- var task =
- ts.GetTask(fullPath)
- ?? throw new InvalidOperationException(
- Loc.Instance["ScheduledTasks.Error.TaskNotFound", fullPath]
+ var task = ts.GetTask(fullPath);
+ if (task is null)
+ {
+ // Nothing on this machine to configure, and nothing to undo either, so the step
+ // is recorded as not applicable rather than as a failure of the run.
+ call.Logger.LogInformation("Task {Path} not found, nothing to change", fullPath);
+ call.Changes.AddNotApplicable(
+ ServiceStrings.ScheduledTaskName,
+ ServiceStrings.Format(ServiceStrings.ScheduledTaskInfoSkippedNotFound, fullPath)
);
+ return OpResult.Success();
+ }
if (!task.Enabled)
{
@@ -143,11 +150,18 @@ public static class ScheduledTaskService
try
{
using var ts = new TaskService();
- var task =
- ts.GetTask(fullPath)
- ?? throw new InvalidOperationException(
- Loc.Instance["ScheduledTasks.Error.TaskNotFound", fullPath]
+ var task = ts.GetTask(fullPath);
+ if (task is null)
+ {
+ // Nothing on this machine to configure, and nothing to undo either, so the step
+ // is recorded as not applicable rather than as a failure of the run.
+ call.Logger.LogInformation("Task {Path} not found, nothing to change", fullPath);
+ call.Changes.AddNotApplicable(
+ ServiceStrings.ScheduledTaskName,
+ ServiceStrings.Format(ServiceStrings.ScheduledTaskInfoSkippedNotFound, fullPath)
);
+ return OpResult.Success();
+ }
if (task.Enabled)
{
diff --git a/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs b/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs
index cb0b843..c104eca 100644
--- a/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs
+++ b/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs
@@ -69,11 +69,11 @@ public static class ServiceProcessService
{
sw.Stop();
var skipDescription = ServiceStrings.Format(
- ServiceStrings.ServiceInfoSkippedNotFound,
+ ServiceStrings.ServiceInfoNotFound,
item.Name
);
call.Logger.LogInformation("[SERVICE][{Name}] not found, skipping", item.Name);
- call.Changes.AddSkip(ServiceStrings.ServiceName, skipDescription);
+ call.Changes.AddNotApplicable(ServiceStrings.ServiceName, skipDescription);
return MapToOpResult(ServiceChangeResult.NotFound, null, null, null);
}
@@ -149,7 +149,7 @@ public static class ServiceProcessService
if (nativeError == ErrorAccessDenied)
{
var accessDeniedError = ServiceStrings.Format(
- ServiceStrings.ServiceInfoSkippedAccessDenied,
+ ServiceStrings.ServiceInfoAccessDenied,
item.Name
);
call.Logger.LogInformation(
@@ -157,7 +157,7 @@ public static class ServiceProcessService
item.Name,
sw.Elapsed.FormatTime()
);
- call.Changes.AddSkip(ServiceStrings.ServiceName, accessDeniedError);
+ call.Changes.AddRefused(ServiceStrings.ServiceName, accessDeniedError);
return MapToOpResult(
ServiceChangeResult.AccessDenied,
null,
@@ -240,8 +240,8 @@ public static class ServiceProcessService
/// <summary>
/// Maps the compat <see cref="ServiceChangeResult"/> outcome to an <see cref="OpResult"/>.
/// Success, NotFound, AlreadyConfigured and AccessDenied are informational outcomes,
- /// because a refusal by Windows is a skip rather than a failure; only Failed carries an
- /// error naming the service.
+ /// because a refusal by Windows is not a failure; only Failed carries an error naming
+ /// the service.
/// </summary>
private static OpResult MapToOpResult(
ServiceChangeResult outcome,
diff --git a/optimizerDuck/Services/System/Primitives/ServiceStrings.cs b/optimizerDuck/Services/System/Primitives/ServiceStrings.cs
index 32a56b5..0ec25f5 100644
--- a/optimizerDuck/Services/System/Primitives/ServiceStrings.cs
+++ b/optimizerDuck/Services/System/Primitives/ServiceStrings.cs
@@ -54,11 +54,11 @@ public static class ServiceStrings
public const string RevertDataUnknownType =
"Cannot revert step of unknown type '{0}'. The revert data was written by a different app version.";
public const string ServiceErrorExceptionOccurred = "Failed to change service '{0}': {1}";
- public const string ServiceInfoSkippedNotFound = "Service '{0}' not found (skipped)";
+ public const string ServiceInfoNotFound = "Service '{0}' not found (not present)";
public const string ServiceInfoAlreadyConfigured =
"Service '{0}' is already set to {1} (skipped)";
- public const string ServiceInfoSkippedAccessDenied =
- "Access to service '{0}' is denied by Windows (skipped)";
+ public const string ServiceInfoAccessDenied =
+ "Access to service '{0}' is denied by Windows (left unchanged)";
public const string ShellName = "Shell";
@@ -75,6 +75,10 @@ public static class ServiceStrings
public const string UsbPowerName = "USB power";
public const string UsbPowerDescriptionDisable = "Disable USB power saving for {0} device(s)";
public const string UsbPowerErrorChangeFailed = "Failed to change USB power saving";
+ public const string UsbPowerInfoAlreadyConfigured =
+ "USB power saving already disabled for every device (skipped)";
+ public const string UsbPowerInfoNoDevices =
+ "No USB root hub devices on this machine (nothing to change)";
/// <summary>Formats a template with invariant culture (same as Loc.Invariant did).</summary>
public static string Format(string template, params object?[] args) =>
diff --git a/optimizerDuck/Services/UI/StartupManagerService.cs b/optimizerDuck/Services/UI/StartupManagerService.cs
index 6676356..596cfa2 100644
--- a/optimizerDuck/Services/UI/StartupManagerService.cs
+++ b/optimizerDuck/Services/UI/StartupManagerService.cs
@@ -690,9 +690,24 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)
try
{
var fullPath = task.TaskPath.TrimEnd('\\') + "\\" + task.TaskName;
+ var call = UiCall();
var result = enable
- ? ScheduledTaskService.EnableTask(UiCall(), fullPath)
- : ScheduledTaskService.DisableTask(UiCall(), fullPath);
+ ? ScheduledTaskService.EnableTask(call, fullPath)
+ : ScheduledTaskService.DisableTask(call, fullPath);
+
+ // The provider reports a missing task as nothing to change, which is right for an
+ // optimization. From this list it is a stale entry the user cannot toggle, so the
+ // page says so instead of reporting a success that is not there.
+ if (
+ result.Ok
+ && call.Changes.Changes.Any(step => step.Kind == ChangeKind.NotApplicable)
+ )
+ return OpResult.Fail(
+ ServiceStrings.Format(
+ ServiceStrings.ScheduledTaskInfoSkippedNotFound,
+ fullPath
+ )
+ );
if (result.Ok)
logger.LogInformation(