Skip to content

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

refactor(execution): run optimizations and built-in tools through one lifecycle

fatDuck5b147e9e29cf
diff --git a/AGENTS.md b/AGENTS.md
index df0dca2..9dfb6f8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -27,7 +27,7 @@
- `Attributes/` — `[Optimization]`, `[CustomizeSetting]`, `[OptimizationCategory]`, `[CustomizeCategory]`
- `Conditions/` — compatibility condition system: `ICondition`, `ConditionBase`, `ConditionResult`, `ConditionState`, `ConditionValidation`, `WindowsBuilds`, and `BuiltIn/` (Windows version, CPU/GPU brand, min RAM, registry-key/service existence conditions)
- `Exceptions/` — `StepExecutionException`
- - `Execution/` — `OpCall` (explicit per-operation context: changes, logger, cancellation), `ChangeSet` (thread-safe change collector) + `Change` (one recorded step, also the step result shown to the user), `OpResult` (single-operation result)
+ - `Execution/` — `OpCall` (explicit per-operation context: changes, logger, cancellation), `ChangeSet` (thread-safe change collector) + `Change` (one recorded step, also the step result shown to the user), `OpResult` (single-operation result), `OperationSubject` (the Id, key and English log name a run and its record belong to), `OperationRequest` (one run: subject, display name, logger, whether its compensation is persisted) + `RevertPersistence`, `ToolSubjects` (the fixed subjects of the built-in tools)
- `Customize/Categories/` — Desktop, Gaming, Preferences, SystemFeatures (nested setting classes)
- `Optimizations/Categories/` — Performance, SecurityAndPrivacy, Gpu, PowerManagement, BloatwareAndServices, UserExperience, AI (nested optimization classes)
- `Optimizations/Models/` — `BaseOptimization`, `ApplyResult`, `OptimizationContext`, `OptimizationResult`
@@ -47,15 +47,15 @@
- `Conditions/` — `ConditionEvaluator` (static, fail-open evaluation)
- `Configuration/` — `ConfigManager`, `LanguageManager`
- `Customize/` — `CustomizeRegistry` (reflection-based discovery), `CustomizationExecutor` (debounce + sequential serialization for setting writes)
- - `Optimization/` — `OptimizationRegistry`, `OptimizationService`, `OptimizationValidation` (fail-fast Id checks at startup)
+ - `Optimization/` — `OptimizationRegistry`, `OptimizationService`, `OperationRunner` (the one lifecycle a system-changing run takes: invoke the work, classify the outcome from the recorded steps, write the record, persist revert data when the subject asks for it), `OptimizationValidation` (fail-fast Id checks at startup)
- `System/Primitives/` — `RegistryService`, `ScheduledTaskService`, `ServiceProcessService` are **static** (stateless); `ShellService` + `ProcessRunner` are DI singletons (stateful; `ShellService` reads the timeout live from settings). Those four take an explicit `OpCall`, record into `call.Changes`, log via `call.Logger`, return `OpResult`. `ShellMapping` centralises cmd/PowerShell argument building and result mapping. `PowerPlanChanges` is the single edge recorder turning lean `PowerPlanService` results into `Change` + revert step + retry (categories never hand-roll power steps). Service startup types are read and written through the Service Control Manager inside `ServiceProcessService` (no `sc.exe`, no START_TYPE parsing). `RecycleBinService`, `HibernationService` and `UsbPowerService` are **static** primitives owning one Windows operation each (shell Recycle Bin APIs, the documented power information callback, `root\wmi` device power) and fail open instead of throwing.
- `ApplicationServiceCollectionExtensions.cs` — `AddOptimizerApplication(IConfiguration)`: the whole application graph, separated from `App.xaml.cs` so a test can build it
- `Revert/` — `RevertManager` (atomic file-based revert data persistence)
- `System/` — `RegistryWatcher` (+ `IRegistryWatcher`), `SystemInfoService` (defines `SystemInfo` + models), `StreamService`, `UpdaterService`, `CrossPageEventBus`, `CrossPageEvents`, `PowerPlanService` (lean native core: reads take ids, writes take `ILogger? = null` and record nothing; single owner of power **scheme** interop), `SystemRestoreService` (same lean shape; single owner of every System Restore WMI call, reusable by a future restore-point tool)
- `UI/` — `BloatwareService`, `DiskCleanupService`, `StartupManagerService`
- - `UI/` — XAML pages, ViewModels, windows, controls, dialogs, styles
+ - `UI/` — XAML pages, ViewModels, windows, controls, dialogs, styles. `ToolRunPresenter` runs one tool action and reports its outcome (progress dialog, retry dialog, snackbar), so every tool page runs and reports an action the same way.
- `Common/` — extensions, helpers, converters:
- - `Helpers/` — `Shared.cs` (constants, paths, SafeApps/CautionApps sets), `ReflectionHelper.cs`, `SystemRefreshService.cs` (P/Invoke for Windows refresh), `EmbeddedResourceHelper.cs`, `WmiHelper.cs`, `GitHubSourceHelper.cs`, `ThemeResource.cs`, `HttpClientFactory.cs`, `UiThread.cs`
+ - `Helpers/` — `Shared.cs` (constants, paths, SafeApps/CautionApps sets), `ReflectionHelper.cs`, `SystemRefreshService.cs` (P/Invoke for Windows refresh), `EmbeddedResourceHelper.cs`, `WmiHelper.cs`, `GitHubSourceHelper.cs`, `ThemeResource.cs`, `HttpClientFactory.cs`, `UiThread.cs`, `UserErrorSurface.cs` (reports one unhandled failure to the user, once per exception, and never throws)
- `Converters/` — WPF value converters (BooleanToVisibility, MBToGB, ...)
- `Extensions/` — `StringExtensions`, `CustomizePageRegistryExtensions`, `OptimizationPageRegistryExtensions`, `LanguageExtensions`
- `Resources/` — images, embedded assets, locale files
@@ -82,13 +82,13 @@
- **Discovery**: `ReflectionHelper.FindImplementationsInLoadedAssemblies<T>()` scans assemblies whose name starts with `optimizerDuck` — no DI registration array to update. Results are cached in `_implementationCache`.
- **Provider services**: stateless services are static (`RegistryService`, `ServiceProcessService`, `ScheduledTaskService`) — call directly. `ShellService` + `ProcessRunner` are DI singletons, reached from optimizations as `context.Shell`. All take an explicit `OpCall`, record into `call.Changes`, return `OpResult`. Exception: `PowerPlanService` is a lean DI singleton — reads take ids, writes take `ILogger? = null` and record nothing (named record results); `PowerPlanChanges` records at the edge instead.
- **Results**: Optimizations end `ApplyAsync` with `return context.Changes.ToApplyResult();`. Do not manually construct `ApplyResult` except for early-out failures.
-- **Single execution path**: `BaseOptimization` + `OptimizationContext` (`OpCall`) + static providers + `ShellService`, orchestrated by `OptimizationService`. There is no second framework — do not add one, and do not write a second implementation of an existing Windows operation.
+- **Single execution path**: `BaseOptimization` + `OptimizationContext` (`OpCall`) + static providers + `ShellService`, orchestrated by `OperationRunner`. Every system-changing run goes through it: an optimization (`OptimizationService.ApplyAsync` builds the `OperationRequest`) and a tool action (`ToolRunPresenter` builds it) differ only in their subject and in whether revert data is persisted. There is no second framework — do not add one, and do not write a second implementation of an existing Windows operation.
- **One implementation per Windows operation**: `RegistryService`/`ServiceProcessService`/`ScheduledTaskService`/`ShellService` are the single source of truth (plus the shared `RegistryValues`, `ShellMapping`), `PowerPlanService` owns power-scheme interop, `SystemRestoreService` owns System Restore, and the static primitives (`RecycleBinService`, `HibernationService`, `UsbPowerService`) own one Windows operation each. Fix behaviour there, not in a copy.
- **DI**: register through `AddOptimizerApplication(configuration)` (the whole app graph); `App.xaml.cs` only builds the host. The host sets `ValidateOnBuild`/`ValidateScopes`, so a broken registration fails at startup instead of at Apply time — keep it that way.
- **Skip policy**: a provider whose mutation needs a privilege it may not have, has a side effect beyond the value it sets, or can be refused when called a second time reads the current state first and records a skip when the machine already matches, without calling the mutation (`RegistryService`, `ServiceProcessService`, `ScheduledTaskService`, `PowerPlanChanges`, hibernation, USB). An item never decides this on its own: skipping at the item level drops the step from the record entirely.
-- **Kinds**: `Change` (modified, carries compensation), `Skip` (already correct), `NotApplicable` (nothing on this machine to act on), `Refused` (Windows refused; not a failure), `Irreversible` (no way back). Only `Change` counts for `DidApplyAnything`, so a run that recorded no change is reported as nothing to do rather than as a failure.
-- **The record of an apply**: `OptimizationService` writes what a run did to `%LocalAppData%\optimizerDuck\History\{id}.json` (one file per item, atomic, best effort, never part of the revert data). `ChangeRecordStore` reads it back for the details view, and the applied badge's summary comes from it.
-- **Per-step failure policy**: providers record a failed `Change` with an error and (where a retry can help) a retry action; they do not throw. Power failures record the same way via `PowerPlanChanges` (the service itself only returns diagnostics). Only truly unrecoverable state throws. `OptimizationService` persists partial work with `CancellationToken.None` and builds the `OptimizationResult`.
+- **Kinds**: `Change` (modified, carries compensation), `Skip` (already correct), `NotApplicable` (nothing on this machine to act on), `Refused` (Windows refused; not a failure), `Irreversible` (no way back). `DidApplyAnything` (only `Change`, and what revert persistence is gated on) is narrower than `ModifiedSystem` (`Change` + `Irreversible`, and what tells a change from nothing to do), so a run whose only step was irreversible is a success rather than nothing to do, and a run that recorded no change at all is reported as nothing to do rather than as a failure.
+- **The record of a run**: `OperationRunner` writes what a run did to `%LocalAppData%\optimizerDuck\History\{id}.json` (one file per subject, atomic, best effort, never part of the revert data). An optimization and a built-in tool both write one, under the fixed ids in `ToolSubjects`. `ChangeRecordStore` reads it back for the details view and for a retry's attempt counts, and the applied badge's summary comes from it.
+- **Per-step failure policy**: providers record a failed `Change` with an error and (where a retry can help) a retry action; they do not throw. Power failures record the same way via `PowerPlanChanges` (the service itself only returns diagnostics). Only truly unrecoverable state throws. `OperationRunner` persists partial work with `CancellationToken.None` and builds the `OptimizationResult`; an exception from a run is recorded as a failed step named for the user.
- **Preloading**: `OptimizationRegistry.PreloadOptimizationsAsync()` / `EnsurePreloadedAsync()` (and `CustomizeRegistry.PreloadCategoriesAsync()` / `EnsurePreloadedAsync()`) run reflection discovery on a background thread. `App.xaml.cs` preloads at startup; the Optimize/Customize pages call `EnsurePreloadedAsync()` before binding.
## Condition System (Compatibility Gating)
@@ -106,7 +106,7 @@
- **Step types**: `RegistryRevertStep`, `ServiceRevertStep`, `ScheduledTaskRevertStep`, `ShellRevertStep`, `UsbPowerRevertStep`, `PowerPlanRevertStep`, `PowerSettingRevertStep`. Each verifies its own effect inside `ExecuteAsync` (registry read-back, service re-query, task state re-check, power re-read). Access-denied is failure, never success. Missing `OriginalEnabled` throws (fail-closed).
- **Unknown types**: persisted data with an unregistered step type becomes a failing step with a clear message (never silently skipped); raw payload round-trips.
- **Step registry**: Revert step deserialization uses reflection-based `_stepRegistry` (`ConcurrentDictionary`). New step types auto-register by implementing `IRevertStep` with a static `FromData(JObject)` method.
-- **Retry**: `OptimizationService.RetryFailedStepsWithResultsAsync()` re-invokes `Retry` with a fresh `OpCall` and persists recovered steps via `AppendRevertStepAsync`.
+- **Retry**: `OptimizationService.RetryFailedStepsWithResultsAsync()` re-invokes `Retry` with a fresh `OpCall` and persists recovered steps via `AppendRevertStepAsync`. The optimization page's dialog and `ToolRunPresenter` both call it; reverting an optimization passes a `RevertManager` and a tool passes none, so a retried tool step writes no revert data.
- **Key methods**: `SaveRevertDataAsync()`, `RevertAsync()`, `AppendRevertStepAsync()`, `RemoveRevertStepsAtIndexesAsync()`, `IsAppliedAsync(id)`, `GetRevertDataAsync(id)`, `ClearAllRevertData()`, `RemoveOrphanedTempFiles()`.
## Customize Setting API Notes
@@ -123,8 +123,8 @@
- DI via `Microsoft.Extensions.Hosting` + `CommunityToolkit.Mvvm`. Pages + ViewModels registered as singletons in `App.xaml.cs`.
- `optimizerDuck.csproj` has `<InternalsVisibleTo Include="optimizerDuck.Test" />` — test project can access internal members.
- Category pages auto-register via `services.AddAllCustomizeCategoryPages()` and `services.AddAllOptimizationPages()`.
-- `ProcessRunner` + `ShellService` come from DI; there is no init step. `OptimizationService` creates the per-apply `ChangeSet`. Revert steps that run commands receive the app shell service from `RevertManager` so the configured timeout applies to undo.
-- The full build/format/analysis gate is: `dotnet build ... Release` must be **0 warnings** (`.editorconfig` promotes CA2016/CA1068/CA2250/CA2213/CA2219/IDE0330 to warnings), then `dotnet test`, then `csharpier check .`.
+- `ProcessRunner` + `ShellService` come from DI; there is no init step. `OperationRunner` creates the per-run `ChangeSet`. Revert steps that run commands receive the app shell service from `RevertManager` so the configured timeout applies to undo.
+- The full build/format/analysis gate is: `dotnet build ... Release` (the build **fails on any warning**: `TreatWarningsAsErrors` + `EnforceCodeStyleInBuild` are set in both project files, so the severity table in `.editorconfig` decides), then `dotnet test`, then `csharpier check .`. `AnalysisMode=All` is deliberately not enabled; the measured reason is in `.editorconfig`.
- `WmiHelper.Initialize()` registers WMI cleanup for abnormal termination.
## Localization (All Locales)
diff --git a/optimizerDuck.Test/Common/Helpers/UserErrorSurfaceTests.cs b/optimizerDuck.Test/Common/Helpers/UserErrorSurfaceTests.cs
new file mode 100644
index 0000000..5360fc0
--- /dev/null
+++ b/optimizerDuck.Test/Common/Helpers/UserErrorSurfaceTests.cs
@@ -0,0 +1,60 @@
+using optimizerDuck.Common.Helpers;
+using optimizerDuck.Resources.Languages;
+using optimizerDuck.Services.Configuration;
+
+namespace optimizerDuck.Test.Common.Helpers;
+
+/// <summary>
+/// Pins that an unhandled failure is reported once, names the failure, and never throws.
+/// </summary>
+public class UserErrorSurfaceTests
+{
+ [Fact]
+ public void TryReport_TheSameFailureTwice_ReportsItOnce()
+ {
+ var reports = new List<(string Title, string Message)>();
+ var surface = new UserErrorSurface((title, message) => reports.Add((title, message)));
+ var failure = new InvalidOperationException("the last action failed");
+
+ Assert.True(surface.TryReport(failure));
+ Assert.False(surface.TryReport(failure));
+
+ Assert.Single(reports);
+ }
+
+ [Fact]
+ public void TryReport_CarriesTheFailureMessageAndTheLogHint()
+ {
+ var reports = new List<(string Title, string Message)>();
+ var surface = new UserErrorSurface((title, message) => reports.Add((title, message)));
+
+ Assert.True(surface.TryReport(new InvalidOperationException("the last action failed")));
+
+ var (title, message) = Assert.Single(reports);
+ Assert.Equal(Loc.Instance["Error.Unhandled.Title"], title);
+ Assert.Contains("the last action failed", message);
+ Assert.Contains(Loc.Instance["Error.Unhandled.LogHint"], message);
+ }
+
+ [Fact]
+ public void TryReport_DifferentFailures_AreEachReported()
+ {
+ var reports = new List<(string Title, string Message)>();
+ var surface = new UserErrorSurface((title, message) => reports.Add((title, message)));
+
+ Assert.True(surface.TryReport(new InvalidOperationException("first")));
+ Assert.True(surface.TryReport(new InvalidOperationException("second")));
+
+ Assert.Equal(2, reports.Count);
+ }
+
+ [Fact]
+ public void TryReport_WhenThePresenterThrows_DoesNotThrow()
+ {
+ var surface = new UserErrorSurface(
+ (_, _) => throw new InvalidOperationException("no shell")
+ );
+
+ Assert.True(surface.TryReport(new InvalidOperationException("the last action failed")));
+ }
+}
diff --git a/optimizerDuck.Test/Domain/Execution/ToolSubjectsTests.cs b/optimizerDuck.Test/Domain/Execution/ToolSubjectsTests.cs
new file mode 100644
index 0000000..ad48612
--- /dev/null
+++ b/optimizerDuck.Test/Domain/Execution/ToolSubjectsTests.cs
@@ -0,0 +1,107 @@
+using System.Reflection;
+using optimizerDuck.Common.Helpers;
+using optimizerDuck.Domain.Abstractions;
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Models;
+
+namespace optimizerDuck.Test.Domain.Execution;
+
+/// <summary>
+/// Pins that a tool subject identifies exactly one owner. A shared identifier would make a run
+/// of either owner replace the other's record file.
+/// </summary>
+public class ToolSubjectsTests
+{
+ [Fact]
+ public void EveryToolSubject_IsItsOwnRecord()
+ {
+ var subjects = DeclaredSubjects();
+ Assert.NotEmpty(subjects);
+
+ AssertDistinct(subjects, declared => declared.Subject.Id, nameof(OperationSubject.Id));
+ AssertDistinct(subjects, declared => declared.Subject.Key, nameof(OperationSubject.Key));
+
+ foreach (var declared in subjects)
+ {
+ Assert.False(
+ string.IsNullOrWhiteSpace(declared.Subject.Key),
+ $"{declared.Name} declares no {nameof(OperationSubject.Key)}."
+ );
+ Assert.False(
+ string.IsNullOrWhiteSpace(declared.Subject.LogName),
+ $"{declared.Name} declares no {nameof(OperationSubject.LogName)}."
+ );
+ }
+ }
+
+ [Fact]
+ public void EveryToolSubject_UsesARecordIdNoOptimizationUses()
+ {
+ var optimizationIds = DiscoveredOptimizationIds();
+ Assert.NotEmpty(optimizationIds);
+
+ foreach (var declared in DeclaredSubjects())
+ Assert.False(
+ optimizationIds.Contains(declared.Subject.Id),
+ $"{declared.Name} reuses the record id {declared.Subject.Id} of an optimization."
+ );
+ }
+
+ /// <summary>The subjects the built-in tools declare.</summary>
+ private static IReadOnlyList<DeclaredSubject> DeclaredSubjects() =>
+ [
+ .. typeof(ToolSubjects)
+ .GetFields(BindingFlags.Public | BindingFlags.Static)
+ .Select(field => new DeclaredSubject(
+ $"{nameof(ToolSubjects)}.{field.Name}",
+ (OperationSubject)field.GetValue(null)!
+ )),
+ ];
+
+ /// <summary>The identities of every optimization the catalog declares.</summary>
+ private static List<Guid> DiscoveredOptimizationIds()
+ {
+ var ids = new List<Guid>();
+
+ foreach (
+ var category in ReflectionHelper.FindImplementationsInLoadedAssemblies<IOptimizationCategory>()
+ )
+ {
+ foreach (
+ var nested in category
+ .GetNestedTypes(BindingFlags.Public)
+ .Where(t =>
+ typeof(IOptimization).IsAssignableFrom(t) && !t.IsAbstract && t.IsClass
+ )
+ )
+ {
+ ids.Add(((BaseOptimization)Activator.CreateInstance(nested)!).Id);
+ }
+ }
+
+ return ids;
+ }
+
+ /// <summary>Asserts that no two declared subjects share a value in one field.</summary>
+ private static void AssertDistinct(
+ IReadOnlyList<DeclaredSubject> subjects,
+ Func<DeclaredSubject, object> field,
+ string fieldName
+ )
+ {
+ var owners = new Dictionary<object, string>();
+
+ foreach (var declared in subjects)
+ {
+ var value = field(declared);
+ Assert.False(
+ owners.TryGetValue(value, out var owner),
+ $"{declared.Name} and {owner} share one {fieldName}: {value}."
+ );
+ owners[value] = declared.Name;
+ }
+ }
+
+ /// <summary>One declared subject with the name of the field it was read from.</summary>
+ private sealed record DeclaredSubject(string Name, OperationSubject Subject);
+}
diff --git a/optimizerDuck.Test/Domain/Optimizations/PowerManagementTests.cs b/optimizerDuck.Test/Domain/Optimizations/PowerManagementTests.cs
index b74cc3e..67e9a47 100644
--- a/optimizerDuck.Test/Domain/Optimizations/PowerManagementTests.cs
+++ b/optimizerDuck.Test/Domain/Optimizations/PowerManagementTests.cs
@@ -1,9 +1,9 @@
using Microsoft.Extensions.Logging.Abstractions;
using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Categories;
+using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.Revert.Steps;
using optimizerDuck.Domain.UI;
-using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Services.System.Primitives;
namespace optimizerDuck.Test.Domain.Optimizations;
@@ -26,6 +26,7 @@ public class PowerManagementTests
RegistryService.DeleteSubKeyTree(call, new RegistryItem(key));
}
}
+
[Theory]
[InlineData(false, false)]
[InlineData(true, true)]
@@ -70,6 +71,7 @@ public class PowerManagementTests
Assert.Null(step.Revert);
Assert.Null(result.Revert);
}
+
[Fact]
public void Apply_HibernationAlreadyDisabled_RecordsSkipAndLeavesTheMachineAlone()
{
diff --git a/optimizerDuck.Test/Domain/Revert/Steps/HibernationRevertStepTests.cs b/optimizerDuck.Test/Domain/Revert/Steps/HibernationRevertStepTests.cs
index 751c660..ebaa049 100644
--- a/optimizerDuck.Test/Domain/Revert/Steps/HibernationRevertStepTests.cs
+++ b/optimizerDuck.Test/Domain/Revert/Steps/HibernationRevertStepTests.cs
@@ -36,10 +36,7 @@ public class HibernationRevertStepTests
Assert.Null(
HibernationRevertStep
.FromData(
- new JObject
- {
- [nameof(HibernationRevertStep.WasPresent)] = JValue.CreateNull(),
- }
+ new JObject { [nameof(HibernationRevertStep.WasPresent)] = JValue.CreateNull() }
)
.WasPresent
);
diff --git a/optimizerDuck.Test/Domain/UI/ChangeKindPresentationTests.cs b/optimizerDuck.Test/Domain/UI/ChangeKindPresentationTests.cs
index 29abf99..e4a4e56 100644
--- a/optimizerDuck.Test/Domain/UI/ChangeKindPresentationTests.cs
+++ b/optimizerDuck.Test/Domain/UI/ChangeKindPresentationTests.cs
@@ -1,5 +1,5 @@
-using optimizerDuck.Domain.Execution;
using Newtonsoft.Json.Linq;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.UI;
namespace optimizerDuck.Test.Domain.UI;
@@ -33,6 +33,7 @@ public class ChangeKindPresentationTests
Assert.Equal("Optimizer.Details.Step.Changed", display.LabelKey);
}
+
[Fact]
public void ForStep_FailedStep_ShowsAsAFailureWhateverItsKind()
{
@@ -45,7 +46,10 @@ public class ChangeKindPresentationTests
Error = "access denied",
};
- Assert.Equal("Optimizer.Details.Step.Failed", ChangeKindPresentation.ForStep(failed).LabelKey);
+ Assert.Equal(
+ "Optimizer.Details.Step.Failed",
+ ChangeKindPresentation.ForStep(failed).LabelKey
+ );
Assert.Equal(
"Optimizer.Details.Step.Changed",
ChangeKindPresentation.ForStep(failed with { Ok = true }).LabelKey
diff --git a/optimizerDuck.Test/Infrastructure/AppDataCleanupFixture.cs b/optimizerDuck.Test/Infrastructure/AppDataCleanupFixture.cs
index 43d88f2..8129610 100644
--- a/optimizerDuck.Test/Infrastructure/AppDataCleanupFixture.cs
+++ b/optimizerDuck.Test/Infrastructure/AppDataCleanupFixture.cs
@@ -42,8 +42,15 @@ public sealed class AppDataCleanupFixture : IDisposable
{
try
{
- var name = JObject.Parse(File.ReadAllText(file, Encoding.UTF8))[nameField]?.ToString();
- if (name is null || !TestNameMarkers.Any(marker => name.Contains(marker, StringComparison.OrdinalIgnoreCase)))
+ var name = JObject
+ .Parse(File.ReadAllText(file, Encoding.UTF8))[nameField]
+ ?.ToString();
+ if (
+ name is null
+ || !TestNameMarkers.Any(marker =>
+ name.Contains(marker, StringComparison.OrdinalIgnoreCase)
+ )
+ )
continue;
File.Delete(file);
diff --git a/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs b/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
index 1c8e630..29c6f66 100644
--- a/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
+++ b/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
@@ -1109,19 +1109,13 @@ public class ApplyRevertComprehensiveTests
TimeProvider.System
);
var loggerFactory = NullLoggerFactory.Instance;
- var systemInfoService = new SystemInfoService(NullLogger<SystemInfoService>.Instance);
- var streamService = new StreamService(NullLogger<StreamService>.Instance);
var contentDialogService = new ContentDialogService();
- var shellService = new ShellService(new ProcessRunner(120000));
var logger = NullLogger<OptimizationService>.Instance;
return new OptimizationService(
+ TestRunner.New(revertManager),
revertManager,
loggerFactory,
- systemInfoService,
- streamService,
contentDialogService,
- shellService,
- new PowerPlanService(NullLogger<PowerPlanService>.Instance),
new SystemRestoreService(NullLogger<SystemRestoreService>.Instance),
logger
);
diff --git a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
index 63fff47..cf79901 100644
--- a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
+++ b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
@@ -569,40 +569,16 @@ public class MockOptimization(Guid id) : StubOptimization
}
/// <summary>
-/// Pins the guard that a step recorded as a change carries the data needed to undo it.
-/// The writer filters entries without compensation, so the warning is the only signal
-/// that a provider forgot one.
+/// Pins that the writer keeps only steps carrying compensation: a change recorded without one
+/// produces no file, and the run that recorded it is the place the defect is reported.
/// </summary>
public class RevertManagerChangeGuardTests
{
- private sealed class CapturingLogger : ILogger<RevertManager>
- {
- public List<string> Warnings { get; } = [];
-
- public IDisposable? BeginScope<TState>(TState state)
- where TState : notnull => null;
-
- public bool IsEnabled(LogLevel logLevel) => true;
-
- public void Log<TState>(
- LogLevel logLevel,
- EventId eventId,
- TState state,
- Exception? exception,
- Func<TState, Exception?, string> formatter
- )
- {
- if (logLevel == LogLevel.Warning)
- Warnings.Add(formatter(state, exception));
- }
- }
-
[Fact]
- public async Task SaveRevertDataAsync_ChangeWithoutCompensation_WarnsAndWritesNoFile()
+ public async Task SaveRevertDataAsync_ChangeWithoutCompensation_WritesNoFile()
{
- var logger = new CapturingLogger();
var manager = new RevertManager(
- logger,
+ NullLogger<RevertManager>.Instance,
TestShell.New(),
new PowerPlanService(NullLogger<PowerPlanService>.Instance),
TimeProvider.System
@@ -621,7 +597,6 @@ public class RevertManagerChangeGuardTests
TestContext.Current.CancellationToken
);
- Assert.Contains(logger.Warnings, w => w.Contains("carries no revert data"));
Assert.False(File.Exists(path));
}
finally
@@ -632,6 +607,111 @@ public class RevertManagerChangeGuardTests
}
}
+/// <summary>
+/// Pins what a cancelled revert leaves behind and that two writes for one item keep every step
+/// they were given.
+/// </summary>
+public class RevertCancellationAndConcurrencyTests
+{
+ private static RevertManager NewManager() =>
+ new(
+ NullLogger<RevertManager>.Instance,
+ TestShell.New(),
+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),
+ TimeProvider.System
+ );
+
+ private static void Cleanup(Guid id)
+ {
+ foreach (var file in Directory.GetFiles(Shared.RevertDirectory, id + ".json*"))
+ File.Delete(file);
+ }
+
+ [Fact]
+ public async Task RevertAsync_CancelledAfterTheFirstStep_KeepsEveryEntry()
+ {
+ var id = Guid.NewGuid();
+ var path = Path.Combine(Shared.RevertDirectory, id + ".json");
+ var cancellationToken = TestContext.Current.CancellationToken;
+ Directory.CreateDirectory(Shared.RevertDirectory);
+
+ try
+ {
+ var changes = new ChangeSet();
+ changes.Add("Registry", "wrote the first value", true, new MockRevertStep());
+ changes.Add("Registry", "wrote the second value", true, new MockRevertStep());
+ await NewManager()
+ .SaveRevertDataAsync(changes, id, "CancellationTest", cancellationToken);
+
+ using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(
+ cancellationToken
+ );
+ // The revert reports before each step, so the first report is the moment the user's
+ // cancellation would land: the first step has run, the second has not.
+ var progress = new CancellingProgress(cancellation);
+
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
+ NewManager().RevertAsync(new MockOptimization(id), progress, cancellation.Token)
+ );
+
+ var kept = await RevertManager.GetRevertDataAsync(id);
+ Assert.NotNull(kept);
+ Assert.Equal(2, kept!.Steps.Count(s => s != null));
+
+ // Running it again from a live token finishes the job and removes the file.
+ var result = await NewManager()
+ .RevertAsync(new MockOptimization(id), null, cancellationToken);
+
+ Assert.True(result.Success);
+ Assert.False(File.Exists(path));
+ }
+ finally
+ {
+ Cleanup(id);
+ }
+ }
+
+ [Fact]
+ public async Task SaveRevertDataAsync_TwoRunsAtOnce_KeepEveryStepWithItsOwnIndex()
+ {
+ var id = Guid.NewGuid();
+ var cancellationToken = TestContext.Current.CancellationToken;
+ Directory.CreateDirectory(Shared.RevertDirectory);
+
+ try
+ {
+ var first = new ChangeSet();
+ first.Add("Registry", "wrote the first value", true, new MockRevertStep());
+ var second = new ChangeSet();
+ second.Add("Registry", "wrote the second value", true, new MockRevertStep());
+
+ var manager = NewManager();
+ await Task.WhenAll(
+ manager.SaveRevertDataAsync(first, id, "ConcurrencyTest", cancellationToken),
+ manager.SaveRevertDataAsync(second, id, "ConcurrencyTest", cancellationToken)
+ );
+
+ var data = await RevertManager.GetRevertDataAsync(id);
+
+ Assert.NotNull(data);
+ var steps = data!.Steps.Where(s => s != null).Select(s => s!).ToList();
+ Assert.Equal(2, steps.Count);
+ Assert.Equal(2, steps.Select(s => s.Index).Distinct().Count());
+ Assert.Equal([1, 2], steps.Select(s => s.Index).Order());
+ }
+ finally
+ {
+ Cleanup(id);
+ }
+ }
+
+ private sealed class CancellingProgress(CancellationTokenSource cancellation)
+ : IProgress<ProcessingProgress>
+ {
+ public void Report(ProcessingProgress value) => cancellation.Cancel();
+ }
+}
+
/// <summary>
/// Pins how revert data survives being unreadable: the bytes are kept, the item still counts
/// as applied, and a revert says which file it could not read instead of claiming none.
@@ -711,7 +791,54 @@ public class RevertIntegrityTests
var parked = Directory.GetFiles(Shared.RevertDirectory, id + ".json.unreadable-*");
Assert.Single(parked);
- Assert.Contains("SchemaVersion", await File.ReadAllTextAsync(parked[0], cancellationToken));
+ Assert.Contains(
+ "SchemaVersion",
+ await File.ReadAllTextAsync(parked[0], cancellationToken)
+ );
+ }
+ finally
+ {
+ Cleanup(id);
+ }
+ }
+
+ [Fact]
+ public async Task Load_WhenTheStepArrayIsNull_IsTreatedAsUnreadable()
+ {
+ var id = Guid.NewGuid();
+ var path = Path.Combine(Shared.RevertDirectory, id + ".json");
+ var cancellationToken = TestContext.Current.CancellationToken;
+ Directory.CreateDirectory(Shared.RevertDirectory);
+
+ try
+ {
+ await File.WriteAllTextAsync(
+ path,
+ $"{{\"SchemaVersion\":1,\"OptimizationId\":\"{id}\","
+ + "\"OptimizationName\":\"IntegrityTest\",\"Steps\":null}",
+ cancellationToken
+ );
+
+ // The item was applied once, and this file is the only copy of what it held.
+ Assert.True(await RevertManager.IsAppliedAsync(id));
+ Assert.Null(await RevertManager.GetRevertDataAsync(id));
+
+ var result = await NewManager()
+ .RevertAsync(new MockOptimization(id), null, cancellationToken);
+
+ Assert.False(result.Success);
+ Assert.Contains(path, result.Message);
+
+ var changes = new ChangeSet();
+ changes.Add("Registry", "wrote a value", true, new MockRevertStep());
+ await NewManager().SaveRevertDataAsync(changes, id, "IntegrityTest", cancellationToken);
+
+ var parked = Directory.GetFiles(Shared.RevertDirectory, id + ".json.unreadable-*");
+ Assert.Single(parked);
+ Assert.Contains(
+ "\"Steps\":null",
+ await File.ReadAllTextAsync(parked[0], cancellationToken)
+ );
}
finally
{
diff --git a/optimizerDuck.Test/Services/OperationRunnerTests.cs b/optimizerDuck.Test/Services/OperationRunnerTests.cs
new file mode 100644
index 0000000..1012dce
--- /dev/null
+++ b/optimizerDuck.Test/Services/OperationRunnerTests.cs
@@ -0,0 +1,580 @@
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Common.Helpers;
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.Optimizations.Models.Services;
+using optimizerDuck.Domain.Revert.Steps;
+using optimizerDuck.Domain.UI;
+using optimizerDuck.Services.History;
+using optimizerDuck.Services.Optimization;
+using optimizerDuck.Services.Revert;
+using optimizerDuck.Services.System;
+using optimizerDuck.Services.System.Primitives;
+using optimizerDuck.Test.TestDoubles;
+
+namespace optimizerDuck.Test.Services;
+
+/// <summary>
+/// Pins the run lifecycle: the steps, outcome and revert data a run produces, what the
+/// compensation guard reports, and that a run keeping no revert data writes nothing.
+/// </summary>
+public class OperationRunnerTests
+{
+ [Fact]
+ public async Task Run_RecordsStatusStepsAndPersistedRevertData()
+ {
+ var subject = NewSubject();
+ var runner = TestRunner.New(NewRevertManager());
+ var revertPath = RevertPath(subject.Id);
+
+ try
+ {
+ var result = await runner.RunAsync(
+ new OperationRequest(
+ subject,
+ "Runner test optimization",
+ NullLogger.Instance,
+ RevertPersistence.Enabled,
+ (_, context) =>
+ {
+ context.Changes.Add(
+ "Test step",
+ "wrote a value",
+ true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }
+ );
+ context.Changes.AddSkip("Test step", "already set");
+ context.Changes.Add(
+ "Test step",
+ "refused value",
+ false,
+ null,
+ error: "refused"
+ );
+ return Task.FromResult(context.Changes.ToApplyResult());
+ }
+ ),
+ new RecordingProgress(),
+ TestContext.Current.CancellationToken
+ );
+
+ Assert.Equal(OptimizationSuccessResult.PartialSuccess, result.Status);
+ Assert.Single(result.FailedSteps);
+
+ var data = await RevertManager.GetRevertDataAsync(subject.Id);
+ Assert.NotNull(data);
+
+ var steps = data!.Steps.Where(s => s != null).ToList();
+ Assert.Single(steps);
+ Assert.Equal(1, steps[0]!.Index);
+ Assert.Equal("Shell", steps[0]!.Type);
+
+ var record = ChangeRecordStore.TryRead(subject.Id);
+ Assert.NotNull(record);
+ Assert.Equal(3, record!.Steps.Count);
+ Assert.Equal(subject.Key, record.OptimizationKey);
+ Assert.Equal(1, record.ChangedCount);
+ Assert.Equal(1, record.FailedCount);
+ }
+ finally
+ {
+ Cleanup(subject.Id);
+ Assert.False(File.Exists(revertPath));
+ }
+ }
+
+ [Fact]
+ public async Task Run_ChangeWithoutCompensation_ReportsTheDefectForEveryRun()
+ {
+ foreach (var persistence in new[] { RevertPersistence.Enabled, RevertPersistence.Disabled })
+ {
+ var subject = NewSubject();
+ var logger = new CapturingLogger();
+ var runner = TestRunner.New(NewRevertManager());
+
+ try
+ {
+ var result = await runner.RunAsync(
+ new OperationRequest(
+ subject,
+ "Runner test tool",
+ logger,
+ persistence,
+ (_, context) =>
+ {
+ context.Changes.Add("Test step", "wrote a value", true, null);
+ return Task.FromResult(context.Changes.ToApplyResult());
+ }
+ ),
+ new RecordingProgress(),
+ TestContext.Current.CancellationToken
+ );
+
+ Assert.Equal(OptimizationSuccessResult.Success, result.Status);
+ Assert.Contains(logger.Warnings, w => w.Contains("carries no revert data"));
+ }
+ finally
+ {
+ Cleanup(subject.Id);
+ }
+ }
+ }
+
+ [Fact]
+ public async Task ToolRun_RecordsStepsAndWritesNoRevertData()
+ {
+ var subject = NewToolSubject();
+ var runner = TestRunner.New(NewRevertManager());
+
+ try
+ {
+ var result = await runner.RunAsync(
+ new OperationRequest(
+ subject,
+ "Runner test tool",
+ NullLogger.Instance,
+ RevertPersistence.Disabled,
+ (_, context) =>
+ {
+ context.Changes.AddSkip("Scheduled Task", "task already enabled");
+ context.Changes.AddIrreversible("Scheduled Task", "ran a task");
+ return Task.FromResult(context.Changes.ToApplyResult());
+ }
+ ),
+ new RecordingProgress(),
+ TestContext.Current.CancellationToken
+ );
+
+ // An irreversible step modified the system, so this is a success, not nothing to do.
+ Assert.Equal(OptimizationSuccessResult.Success, result.Status);
+
+ var record = ChangeRecordStore.TryRead(subject.Id);
+ Assert.NotNull(record);
+ Assert.Equal(subject.Key, record!.OptimizationKey);
+ Assert.Equal(2, record.Steps.Count);
+ Assert.Equal(ChangeKind.Skip, record.Steps[0].Kind);
+ Assert.Equal(ChangeKind.Irreversible, record.Steps[1].Kind);
+ Assert.False(File.Exists(RevertPath(subject.Id)));
+ }
+ finally
+ {
+ Cleanup(subject.Id);
+ }
+ }
+
+ [Fact]
+ public async Task ToolRun_ChangeWithCompensation_PersistsNothing()
+ {
+ var subject = NewToolSubject();
+ var runner = TestRunner.New(NewRevertManager());
+
+ try
+ {
+ var result = await runner.RunAsync(
+ new OperationRequest(
+ subject,
+ "Runner test tool",
+ NullLogger.Instance,
+ RevertPersistence.Disabled,
+ (_, context) =>
+ {
+ context.Changes.Add(
+ "Scheduled Task",
+ "disabled a task",
+ true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }
+ );
+ return Task.FromResult(context.Changes.ToApplyResult());
+ }
+ ),
+ new RecordingProgress(),
+ TestContext.Current.CancellationToken
+ );
+
+ Assert.Equal(OptimizationSuccessResult.Success, result.Status);
+ Assert.False(File.Exists(RevertPath(subject.Id)));
+
+ var record = ChangeRecordStore.TryRead(subject.Id);
+ Assert.NotNull(record);
+ Assert.Equal(ChangeKind.Change, record!.Steps[0].Kind);
+ Assert.Equal(1, record.ChangedCount);
+ }
+ finally
+ {
+ Cleanup(subject.Id);
+ }
+ }
+
+ [Fact]
+ public async Task ToolRun_RetryingAFailedStep_PersistsNoRevertData()
+ {
+ var subject = NewToolSubject();
+ var runner = TestRunner.New(NewRevertManager());
+
+ try
+ {
+ var result = await runner.RunAsync(
+ new OperationRequest(
+ subject,
+ "Runner test tool",
+ NullLogger.Instance,
+ RevertPersistence.Disabled,
+ (_, context) =>
+ {
+ context.Changes.Add(
+ "Scheduled Task",
+ "disabled a task",
+ false,
+ null,
+ error: "refused",
+ retry: _ =>
+ {
+ context.Changes.Add(
+ "Scheduled Task",
+ "disabled a task",
+ true,
+ new ShellRevertStep
+ {
+ ShellType = ShellType.CMD,
+ Command = "exit 0",
+ }
+ );
+ return Task.FromResult(OpResult.Success());
+ }
+ );
+ return Task.FromResult(context.Changes.ToApplyResult());
+ }
+ ),
+ new RecordingProgress(),
+ TestContext.Current.CancellationToken
+ );
+
+ Assert.Equal(OptimizationSuccessResult.Failed, result.Status);
+ Assert.Single(result.FailedSteps);
+
+ var retry = await OptimizationService.RetryFailedStepsWithResultsAsync(
+ result.FailedSteps,
+ reverseOrder: false,
+ NullLogger.Instance,
+ revertManager: null,
+ optimizationId: subject.Id,
+ optimizationKey: subject.Key
+ );
+
+ Assert.Single(retry.RecoveredSteps);
+ Assert.Empty(retry.FailedSteps);
+ Assert.False(File.Exists(RevertPath(subject.Id)));
+
+ var record = ChangeRecordStore.TryRead(subject.Id);
+ Assert.NotNull(record);
+ Assert.Equal(1, record!.ChangedCount);
+ Assert.Equal(0, record.FailedCount);
+ }
+ finally
+ {
+ Cleanup(subject.Id);
+ }
+ }
+
+ [Fact]
+ public async Task Run_WhenRevertDataCannotBePersisted_ReportsAFailedStepAndKeepsTheChange()
+ {
+ var subject = NewSubject();
+ var runner = TestRunner.New(NewRevertManager());
+ var revertPath = RevertPath(subject.Id);
+ var key = $@"HKCU\Software\TestOptimizerDuckRunner\{Guid.NewGuid():N}";
+ var written = new RegistryItem(key, "Value", 1);
+
+ try
+ {
+ // A directory where the revert file belongs makes the atomic write fail.
+ Directory.CreateDirectory(revertPath);
+
+ var result = await runner.RunAsync(
+ new OperationRequest(
+ subject,
+ "Runner test optimization",
+ NullLogger.Instance,
+ RevertPersistence.Enabled,
+ (_, context) =>
+ {
+ RegistryService.Write(context, written);
+ return Task.FromResult(context.Changes.ToApplyResult());
+ }
+ ),
+ new RecordingProgress(),
+ TestContext.Current.CancellationToken
+ );
+
+ Assert.Equal(OptimizationSuccessResult.PartialSuccess, result.Status);
+
+ var failed = Assert.Single(result.FailedSteps);
+ Assert.False(string.IsNullOrWhiteSpace(failed.Error));
+ Assert.Null(failed.Revert);
+
+ // The run still did what it reported, and it reported that undo is unavailable.
+ Assert.Equal((int?)1, RegistryService.Read<int>(written));
+ }
+ finally
+ {
+ RegistryService.DeleteSubKeyTree(
+ new OpCall { Logger = NullLogger.Instance },
+ new RegistryItem(key)
+ );
+ if (Directory.Exists(revertPath))
+ Directory.Delete(revertPath);
+ Cleanup(subject.Id);
+ }
+ }
+
+ /// <summary>
+ /// Pins the outcome each recorded shape is reported as, for both revert modes.
+ /// </summary>
+ [Theory]
+ [InlineData(RecordedShape.SkipOnly, OptimizationSuccessResult.NothingToDo)]
+ [InlineData(RecordedShape.Change, OptimizationSuccessResult.Success)]
+ [InlineData(RecordedShape.Irreversible, OptimizationSuccessResult.Success)]
+ [InlineData(RecordedShape.ChangeAndIrreversible, OptimizationSuccessResult.Success)]
+ [InlineData(RecordedShape.Failed, OptimizationSuccessResult.Failed)]
+ [InlineData(RecordedShape.ChangeAndFailed, OptimizationSuccessResult.PartialSuccess)]
+ [InlineData(RecordedShape.SkipThenProviderError, OptimizationSuccessResult.Failed)]
+ [InlineData(
+ RecordedShape.CompensatedFailureThenProviderError,
+ OptimizationSuccessResult.PartialSuccess
+ )]
+ [InlineData(RecordedShape.SkipThenThrows, OptimizationSuccessResult.Failed)]
+ [InlineData(RecordedShape.ChangeThenThrows, OptimizationSuccessResult.PartialSuccess)]
+ public async Task Run_ClassifiesEveryRecordedShape(
+ RecordedShape shape,
+ OptimizationSuccessResult expected
+ )
+ {
+ foreach (var persistence in new[] { RevertPersistence.Enabled, RevertPersistence.Disabled })
+ {
+ var subject = NewSubject();
+ var runner = TestRunner.New(NewRevertManager());
+
+ try
+ {
+ var result = await runner.RunAsync(
+ new OperationRequest(
+ subject,
+ "Runner test optimization",
+ NullLogger.Instance,
+ persistence,
+ (_, context) =>
+ {
+ Record(context.Changes, shape);
+ return Finish(context.Changes, shape);
+ }
+ ),
+ new RecordingProgress(),
+ TestContext.Current.CancellationToken
+ );
+
+ Assert.Equal(expected, result.Status);
+ }
+ finally
+ {
+ Cleanup(subject.Id);
+ }
+ }
+ }
+
+ /// <summary>A failure with no failed step reports the error the work gave.</summary>
+ [Fact]
+ public async Task Run_ProviderErrorWithoutAFailedStep_ReportsWhatWentWrong()
+ {
+ var subject = NewSubject();
+ var runner = TestRunner.New(NewRevertManager());
+
+ try
+ {
+ var result = await runner.RunAsync(
+ new OperationRequest(
+ subject,
+ "Runner test tool",
+ NullLogger.Instance,
+ RevertPersistence.Disabled,
+ (_, _) => Task.FromResult(ApplyResult.False(ProviderErrorText))
+ ),
+ new RecordingProgress(),
+ TestContext.Current.CancellationToken
+ );
+
+ Assert.Equal(OptimizationSuccessResult.Failed, result.Status);
+ Assert.Empty(result.FailedSteps);
+ Assert.Equal(ProviderErrorText, result.Message);
+ }
+ finally
+ {
+ Cleanup(subject.Id);
+ }
+ }
+
+ /// <summary>A run that threw records a failed step named for the user, not for the log.</summary>
+ [Fact]
+ public async Task Run_Throws_RecordsTheFailureUnderTheDisplayName()
+ {
+ var subject = NewSubject();
+ var runner = TestRunner.New(NewRevertManager());
+
+ try
+ {
+ var result = await runner.RunAsync(
+ new OperationRequest(
+ subject,
+ "Runner test optimization",
+ NullLogger.Instance,
+ RevertPersistence.Disabled,
+ (_, _) => throw new InvalidOperationException(ThrownText)
+ ),
+ new RecordingProgress(),
+ TestContext.Current.CancellationToken
+ );
+
+ var failed = Assert.Single(result.FailedSteps);
+ Assert.Equal("Runner test optimization", failed.Name);
+ Assert.Equal(subject.Key, failed.Description);
+ }
+ finally
+ {
+ Cleanup(subject.Id);
+ }
+ }
+
+ private static OperationSubject NewSubject() =>
+ new(Guid.NewGuid(), "RunnerTestSubject", "Runner test subject");
+
+ /// <summary>A subject owned by this suite, so no two suites share a record file.</summary>
+ private static OperationSubject NewToolSubject() =>
+ new(Guid.NewGuid(), "RunnerTestTool", "Runner test tool");
+
+ private static string RevertPath(Guid id) => Path.Combine(Shared.RevertDirectory, id + ".json");
+
+ private static RevertManager NewRevertManager() =>
+ new(
+ NullLogger<RevertManager>.Instance,
+ TestShell.New(),
+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),
+ TimeProvider.System
+ );
+
+ private static void Cleanup(Guid id)
+ {
+ foreach (
+ var path in new[]
+ {
+ ChangeRecordStore.PathFor(id),
+ RevertPath(id),
+ RevertPath(id) + ".tmp",
+ }
+ )
+ if (File.Exists(path))
+ File.Delete(path);
+ }
+
+ /// <summary>Records the steps one shape is made of.</summary>
+ private static void Record(ChangeSet changes, RecordedShape shape)
+ {
+ switch (shape)
+ {
+ case RecordedShape.SkipOnly:
+ case RecordedShape.SkipThenProviderError:
+ case RecordedShape.SkipThenThrows:
+ changes.AddSkip("Test step", "already set");
+ break;
+ case RecordedShape.Change:
+ case RecordedShape.ChangeThenThrows:
+ changes.Add("Test step", "wrote a value", true, TestCompensation());
+ break;
+ case RecordedShape.CompensatedFailureThenProviderError:
+ changes.Add(
+ "Test step",
+ "wrote a value, then a device refused",
+ false,
+ TestCompensation(),
+ "a device refused the write"
+ );
+ break;
+ case RecordedShape.Irreversible:
+ changes.AddIrreversible("Test step", "ran a task");
+ break;
+ case RecordedShape.ChangeAndIrreversible:
+ changes.Add("Test step", "wrote a value", true, TestCompensation());
+ changes.AddIrreversible("Test step", "ran a task");
+ break;
+ case RecordedShape.Failed:
+ changes.Add("Test step", "wrote a value", false, null, error: "refused");
+ break;
+ case RecordedShape.ChangeAndFailed:
+ changes.Add("Test step", "wrote a value", true, TestCompensation());
+ changes.Add("Test step", "wrote a value", false, null, error: "refused");
+ break;
+ }
+ }
+
+ private static ShellRevertStep TestCompensation() =>
+ new() { ShellType = ShellType.CMD, Command = "exit 0" };
+
+ /// <summary>How a run ends once the steps of its shape are recorded.</summary>
+ private static Task<ApplyResult> Finish(ChangeSet changes, RecordedShape shape) =>
+ shape switch
+ {
+ RecordedShape.SkipThenProviderError
+ or RecordedShape.CompensatedFailureThenProviderError => Task.FromResult(
+ ApplyResult.False(ProviderErrorText)
+ ),
+ RecordedShape.SkipThenThrows or RecordedShape.ChangeThenThrows =>
+ throw new InvalidOperationException(ThrownText),
+ _ => Task.FromResult(changes.ToApplyResult()),
+ };
+
+ /// <summary>What a work reports when it did not succeed and recorded no failed step.</summary>
+ private const string ProviderErrorText = "the entry is no longer on this machine";
+
+ private const string ThrownText = "simulated";
+
+ /// <summary>The recorded shapes a run can end with, which decide its reported outcome.</summary>
+ public enum RecordedShape
+ {
+ SkipOnly,
+ Change,
+ Irreversible,
+ ChangeAndIrreversible,
+ Failed,
+ ChangeAndFailed,
+ SkipThenProviderError,
+ CompensatedFailureThenProviderError,
+ SkipThenThrows,
+ ChangeThenThrows,
+ }
+
+ private sealed class RecordingProgress : IProgress<ProcessingProgress>
+ {
+ public void Report(ProcessingProgress value) { }
+ }
+
+ private sealed class CapturingLogger : ILogger
+ {
+ public List<string> Warnings { get; } = [];
+
+ public IDisposable? BeginScope<TState>(TState state)
+ where TState : notnull => null;
+
+ public bool IsEnabled(LogLevel logLevel) => true;
+
+ public void Log<TState>(
+ LogLevel logLevel,
+ EventId eventId,
+ TState state,
+ Exception? exception,
+ Func<TState, Exception?, string> formatter
+ )
+ {
+ if (logLevel == LogLevel.Warning)
+ Warnings.Add(formatter(state, exception));
+ }
+ }
+}
diff --git a/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs b/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
index f772c72..800f175 100644
--- a/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
@@ -1,4 +1,4 @@
-using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Execution;
@@ -74,6 +74,66 @@ public class ChangeSetTests
Assert.False(changes.DidApplyAnything);
}
+ [Fact]
+ public void ModifiedSystem_IgnoresStepsThatWroteNothing()
+ {
+ var changes = new ChangeSet();
+
+ changes.AddSkip("Service", "already set");
+ changes.AddNotApplicable("Service", "not present");
+ changes.AddRefused("Service", "protected");
+
+ // Nothing was written, so the run reports nothing to do rather than a change.
+ Assert.False(changes.ModifiedSystem);
+ }
+
+ [Fact]
+ public void ModifiedSystem_CountsAChange()
+ {
+ var changes = new ChangeSet();
+
+ changes.Add("Registry", "wrote a value", true, new MockRevertStep());
+
+ Assert.True(changes.ModifiedSystem);
+
+ // A write whose compensation the provider forgot still modified the machine: the
+ // compensation guard reports that defect, it does not reclassify the run.
+ var uncompensated = new ChangeSet();
+ uncompensated.Add("Registry", "wrote a value", true);
+
+ Assert.True(uncompensated.ModifiedSystem);
+ }
+
+ [Fact]
+ public void ModifiedSystem_CountsAnIrreversibleAction()
+ {
+ var changes = new ChangeSet();
+
+ changes.AddSkip("Service", "already set");
+ changes.AddIrreversible("Scheduled Task", "deleted a task");
+
+ // Deleting modified the machine, so the run is a success rather than a run that found
+ // nothing to change. It left nothing to undo, which is the one thing the two queries
+ // disagree about.
+ Assert.True(changes.ModifiedSystem);
+ Assert.False(changes.DidApplyAnything);
+ }
+
+ [Fact]
+ public void ModifiedSystem_FollowsCompensationForAFailedChange()
+ {
+ var changes = new ChangeSet();
+
+ changes.Add("Service", "Change startup type", false, error: "access denied");
+
+ Assert.False(changes.ModifiedSystem);
+
+ changes.Add("USB power", "a device changed then refused", false, new MockRevertStep());
+
+ // A step that carries compensation counts as having modified the machine.
+ Assert.True(changes.ModifiedSystem);
+ }
+
[Fact]
public void FailedSteps_ReturnsOnlyFailedChanges()
{
diff --git a/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs b/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs
index d0a7a62..effc36a 100644
--- a/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
@@ -162,17 +162,11 @@ public class OptimizationServiceIntegrationTests : IDisposable
new PowerPlanService(NullLogger<PowerPlanService>.Instance),
TimeProvider.System
);
- var systemInfoService = new SystemInfoService(NullLogger<SystemInfoService>.Instance);
- var streamService = new StreamService(NullLogger<StreamService>.Instance);
-
var optimizationService = new OptimizationService(
+ TestRunner.New(revertManager),
revertManager,
loggerFactory,
- systemInfoService,
- streamService,
null!,
- new ShellService(new ProcessRunner(120000)),
- new PowerPlanService(NullLogger<PowerPlanService>.Instance),
new SystemRestoreService(NullLogger<SystemRestoreService>.Instance),
NullLogger<OptimizationService>.Instance
);
@@ -275,13 +269,10 @@ public class OptimizationServiceIntegrationTests : IDisposable
TimeProvider.System
);
var optimizationService = new OptimizationService(
+ TestRunner.New(revertManager),
revertManager,
loggerFactory,
- new SystemInfoService(NullLogger<SystemInfoService>.Instance),
- new StreamService(NullLogger<StreamService>.Instance),
null!,
- new ShellService(new ProcessRunner(120000)),
- new PowerPlanService(NullLogger<PowerPlanService>.Instance),
new SystemRestoreService(NullLogger<SystemRestoreService>.Instance),
NullLogger<OptimizationService>.Instance
);
@@ -312,13 +303,10 @@ public class OptimizationServiceIntegrationTests : IDisposable
TimeProvider.System
);
var optimizationService = new OptimizationService(
+ TestRunner.New(revertManager),
revertManager,
loggerFactory,
- new SystemInfoService(NullLogger<SystemInfoService>.Instance),
- new StreamService(NullLogger<StreamService>.Instance),
null!,
- new ShellService(new ProcessRunner(120000)),
- new PowerPlanService(NullLogger<PowerPlanService>.Instance),
new SystemRestoreService(NullLogger<SystemRestoreService>.Instance),
NullLogger<OptimizationService>.Instance
);
@@ -351,13 +339,10 @@ public class OptimizationServiceIntegrationTests : IDisposable
TimeProvider.System
);
var optimizationService = new OptimizationService(
+ TestRunner.New(revertManager),
revertManager,
loggerFactory,
- new SystemInfoService(NullLogger<SystemInfoService>.Instance),
- new StreamService(NullLogger<StreamService>.Instance),
null!,
- new ShellService(new ProcessRunner(120000)),
- new PowerPlanService(NullLogger<PowerPlanService>.Instance),
new SystemRestoreService(NullLogger<SystemRestoreService>.Instance),
NullLogger<OptimizationService>.Instance
);
diff --git a/optimizerDuck.Test/Services/OptimizationServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServiceTests.cs
index a2013d3..dbc6b0b 100644
--- a/optimizerDuck.Test/Services/OptimizationServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServiceTests.cs
@@ -1,4 +1,4 @@
-using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Abstractions;
@@ -549,19 +549,13 @@ public class OptimizationServiceTests
TimeProvider.System
);
var loggerFactory = NullLoggerFactory.Instance;
- var systemInfoService = new SystemInfoService(NullLogger<SystemInfoService>.Instance);
- var streamService = new StreamService(NullLogger<StreamService>.Instance);
var contentDialogService = new ContentDialogService();
- var shellService = new ShellService(new ProcessRunner(120000));
var logger = NullLogger<OptimizationService>.Instance;
return new OptimizationService(
+ TestRunner.New(revertManager),
revertManager,
loggerFactory,
- systemInfoService,
- streamService,
contentDialogService,
- shellService,
- new PowerPlanService(NullLogger<PowerPlanService>.Instance),
new SystemRestoreService(NullLogger<SystemRestoreService>.Instance),
logger
);
diff --git a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
index ee5b3c4..5f9ac33 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
@@ -16,6 +16,39 @@ public class RegistryServiceTests : IDisposable
{
private const string BaseTestKey = @"HKCU\Software\TestOptimizerDuck";
+ [Fact]
+ public void Write_WhenHklmDeniesTheWrite_RecordsAccessDeniedWithoutCompensation()
+ {
+ if (!IsElevated())
+ Assert.Skip("The write to a protected hive is refused before its ACL is reached.");
+
+ var call = NewCall();
+ var item = new RegistryItem(@"HKLM\SECURITY", "TestOptimizerDuckValue", 1);
+
+ var result = RegistryService.Write(call, item);
+
+ if (result.Ok)
+ {
+ // A host running as SYSTEM can write this hive, so no refusal can be observed here.
+ RegistryService.DeleteValue(NewCall(), item);
+ Assert.Skip("This host can write HKLM\\SECURITY.");
+ }
+
+ Assert.False(result.Ok);
+ var change = Assert.Single(call.Changes.Changes);
+ Assert.False(change.Ok);
+ Assert.Equal(ServiceStrings.CommonErrorAccessDenied, change.Error);
+ Assert.Null(change.Revert);
+ }
+
+ private static bool IsElevated()
+ {
+ using var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
+ return new System.Security.Principal.WindowsPrincipal(identity).IsInRole(
+ System.Security.Principal.WindowsBuiltInRole.Administrator
+ );
+ }
+
private static OpCall NewCall() =>
new() { Changes = new ChangeSet(), Logger = NullLogger.Instance };
diff --git a/optimizerDuck.Test/Services/OptimizationServices/ScheduledTaskServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/ScheduledTaskServiceTests.cs
index 634f241..3dde66b 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/ScheduledTaskServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/ScheduledTaskServiceTests.cs
@@ -40,11 +40,7 @@ public class ScheduledTaskServiceTests
try
{
- var registered = ScheduledTaskService.RegisterTask(
- NewCall(),
- "\\",
- model
- );
+ var registered = ScheduledTaskService.RegisterTask(NewCall(), "\\", model);
Assert.True(registered.Ok, registered.Error);
// Disable: the recorded step must carry "was enabled" and restore it.
@@ -60,9 +56,7 @@ public class ScheduledTaskServiceTests
ScheduledTaskService.GetTaskEnabledState(fullPath, NullLogger.Instance)
);
- Assert.True(
- await disableStep.ExecuteAsync(TestShell.Context(), NullLogger.Instance)
- );
+ Assert.True(await disableStep.ExecuteAsync(TestShell.Context(), NullLogger.Instance));
Assert.Equal(
TaskEnabledState.Enabled,
ScheduledTaskService.GetTaskEnabledState(fullPath, NullLogger.Instance)
@@ -107,6 +101,7 @@ public class ScheduledTaskServiceTests
private static OpCall NewCall() =>
new() { Changes = new ChangeSet(), Logger = NullLogger.Instance };
+
[Theory]
[InlineData(true)]
[InlineData(false)]
diff --git a/optimizerDuck.Test/Services/OptimizationServices/UsbPowerServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/UsbPowerServiceTests.cs
index cde4c62..6827034 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/UsbPowerServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/UsbPowerServiceTests.cs
@@ -133,10 +133,7 @@ public class UsbPowerServiceTests
[Fact]
public void SelectChanges_DeviceAlreadyInTheRequestedState_IsLeftAlone()
{
- var current = new List<UsbPowerService.UsbPowerState>
- {
- new(@"USB\ROOT_HUB30\1", true),
- };
+ var current = new List<UsbPowerService.UsbPowerState> { new(@"USB\ROOT_HUB30\1", true) };
Assert.Empty(UsbPowerService.SelectChanges(current, _ => true));
}
diff --git a/optimizerDuck.Test/Services/OptimizationValidationTests.cs b/optimizerDuck.Test/Services/OptimizationValidationTests.cs
index 1315826..403290b 100644
--- a/optimizerDuck.Test/Services/OptimizationValidationTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationValidationTests.cs
@@ -1,11 +1,11 @@
-using System.Globalization;
+using System.Globalization;
using System.Reflection;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Abstractions;
-using optimizerDuck.Domain.Execution;
-using optimizerDuck.Domain.UI;
using optimizerDuck.Domain.Attributes;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.UI;
using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.Optimization;
@@ -146,6 +146,11 @@ public class OptimizationValidationTests
var category in ReflectionHelper.FindImplementationsInLoadedAssemblies<IOptimizationCategory>()
)
{
+#if DEBUG
+ // The Debug category carries hard-coded English, so it has no resource keys to find.
+ if (category.Name == "Debug")
+ continue;
+#endif
foreach (
var nested in category
.GetNestedTypes(BindingFlags.Public)
@@ -183,8 +188,7 @@ public class OptimizationValidationTests
missing.Add(key);
}
- var labelKeys = Enum
- .GetValues<ChangeKind>()
+ var labelKeys = Enum.GetValues<ChangeKind>()
.Select(kind => kind.ToDisplay().LabelKey)
.Append(ChangeKindPresentation.ForStep(new ChangeRecordStep { Ok = false }).LabelKey);
diff --git a/optimizerDuck.Test/Services/UI/ScheduledTasksToolRunTests.cs b/optimizerDuck.Test/Services/UI/ScheduledTasksToolRunTests.cs
new file mode 100644
index 0000000..9ec552f
--- /dev/null
+++ b/optimizerDuck.Test/Services/UI/ScheduledTasksToolRunTests.cs
@@ -0,0 +1,360 @@
+using System.Windows.Threading;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Common.Helpers;
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.Optimizations.Models.ScheduledTask;
+using optimizerDuck.Domain.UI;
+using optimizerDuck.Services.History;
+using optimizerDuck.Services.Optimization;
+using optimizerDuck.Services.Revert;
+using optimizerDuck.Services.System;
+using optimizerDuck.Services.System.Primitives;
+using optimizerDuck.Test.TestDoubles;
+using optimizerDuck.UI.ViewModels;
+using optimizerDuck.UI.ViewModels.Pages;
+using Wpf.Ui;
+using Wpf.Ui.Controls;
+
+namespace optimizerDuck.Test.Services.UI;
+
+/// <summary>
+/// Pins what a tool action on the scheduled tasks page does: its steps run under the tool's
+/// subject, a failure names the failed step, and a second toggle starts no second run.
+/// </summary>
+public class ScheduledTasksToolRunTests
+{
+ [Fact]
+ public async Task ToolRun_ThroughTheTaskProvider_RecordsChangeSkipAndIrreversible()
+ {
+ var name = $"optimizerDuck_Test_{Guid.NewGuid():N}";
+ var fullPath = "\\" + name;
+ var runner = TestRunner.New(NewRevertManager());
+ var subject = ToolSubjects.ScheduledTasks;
+
+ try
+ {
+ Assert.True(Register(name).Ok);
+
+ var first = await RunAsync(
+ runner,
+ subject,
+ context => ScheduledTaskService.DisableTask(context, fullPath)
+ );
+
+ Assert.Equal(OptimizationSuccessResult.Success, first.Status);
+ var record = ChangeRecordStore.TryRead(subject.Id);
+ Assert.NotNull(record);
+ Assert.Equal(subject.Key, record!.OptimizationKey);
+ Assert.Equal(ChangeKind.Change, Assert.Single(record.Steps).Kind);
+
+ var second = await RunAsync(
+ runner,
+ subject,
+ context => ScheduledTaskService.DisableTask(context, fullPath)
+ );
+
+ Assert.Equal(OptimizationSuccessResult.NothingToDo, second.Status);
+ Assert.Equal(
+ ChangeKind.Skip,
+ Assert.Single(ChangeRecordStore.TryRead(subject.Id)!.Steps).Kind
+ );
+
+ var third = await RunAsync(
+ runner,
+ subject,
+ context => ScheduledTaskService.DeleteTask(context, fullPath)
+ );
+
+ // Deleting is irreversible, so the run is a success, not nothing to do.
+ Assert.Equal(OptimizationSuccessResult.Success, third.Status);
+ var deleted = Assert.Single(ChangeRecordStore.TryRead(subject.Id)!.Steps);
+ Assert.Equal(ChangeKind.Irreversible, deleted.Kind);
+ // The record carries the outcome the run was classified as.
+ Assert.Equal(
+ nameof(OptimizationSuccessResult.Success),
+ ChangeRecordStore.TryRead(subject.Id)!.Outcome
+ );
+
+ // The tool action went through the run lifecycle, which keeps no revert data.
+ Assert.False(File.Exists(RevertPath(subject.Id)));
+ }
+ finally
+ {
+ ScheduledTaskService.DeleteTask(NewCall(), fullPath);
+ Cleanup(subject.Id);
+ }
+ }
+
+ [Fact]
+ public async Task ToolRun_FailedStep_IsReportedAsAFailureWithThatStep()
+ {
+ var subject = new OperationSubject(Guid.NewGuid(), "ScheduledTasksTestTool", "Test tool");
+ var runner = TestRunner.New(NewRevertManager());
+
+ try
+ {
+ var result = await runner.RunAsync(
+ new OperationRequest(
+ subject,
+ "Runner test tool",
+ NullLogger.Instance,
+ RevertPersistence.Disabled,
+ (_, context) =>
+ {
+ context.Changes.Add(
+ "Scheduled Task",
+ "disabled a task",
+ false,
+ null,
+ error: "access denied"
+ );
+ return Task.FromResult(context.Changes.ToApplyResult());
+ }
+ ),
+ new NoProgress(),
+ TestContext.Current.CancellationToken
+ );
+
+ Assert.Equal(OptimizationSuccessResult.Failed, result.Status);
+ var failed = Assert.Single(result.FailedSteps);
+ Assert.Equal("Scheduled Task", failed.Name);
+ Assert.Equal("access denied", failed.Error);
+ }
+ finally
+ {
+ Cleanup(subject.Id);
+ }
+ }
+
+ [Fact]
+ public async Task RepeatedToggle_ForOneTask_StartsOneRun()
+ {
+ await RunInStaThreadAsync(async () =>
+ {
+ var name = $"optimizerDuck_Test_{Guid.NewGuid():N}";
+ var fullPath = "\\" + name;
+ var logger = new CapturingLogger<OperationRunner>();
+ var viewModelLogger = new CapturingLogger<ScheduledTasksViewModel>();
+ var snackbar = new FakeSnackbarService();
+ var revertManager = NewRevertManager();
+ var runner = TestRunner.New(revertManager, logger);
+ var dialogs = new ContentDialogService();
+ var viewModel = new ScheduledTasksViewModel(
+ new ToolRunPresenter(
+ runner,
+ dialogs,
+ snackbar,
+ NullLogger<ToolRunPresenter>.Instance
+ ),
+ dialogs,
+ snackbar,
+ viewModelLogger
+ );
+
+ try
+ {
+ Assert.True(Register(name).Ok);
+
+ await viewModel.OnNavigatedToAsync();
+ var task = viewModel.Tasks.FirstOrDefault(t => t.FullPath == fullPath);
+ Assert.NotNull(task);
+ Assert.True(task!.IsEnabled);
+
+ // The second flip lands while the first run is still writing.
+ task.IsEnabled = false;
+ task.IsEnabled = true;
+
+ var settled = false;
+ for (var attempt = 0; attempt < 100 && !settled; attempt++)
+ {
+ await Task.Delay(50);
+ settled = snackbar.Shown.Count > 0 && !task.IsEnabled;
+ }
+
+ Assert.True(
+ settled,
+ $"started={logger.Started.Count} shown={snackbar.Shown.Count} "
+ + $"switch={task.IsEnabled} vmLog={string.Join(" | ", viewModelLogger.Messages)} "
+ + $"runLog={string.Join(" | ", logger.Messages)}"
+ );
+ Assert.Single(logger.Started);
+ // The switch shows what Windows has, not what the dropped flip asked for.
+ Assert.False(task.IsEnabled);
+ }
+ finally
+ {
+ ScheduledTaskService.DeleteTask(NewCall(), fullPath);
+ Cleanup(ToolSubjects.ScheduledTasks.Id);
+ }
+ });
+ }
+
+ private static Task<OptimizationResult> RunAsync(
+ OperationRunner runner,
+ OperationSubject subject,
+ Func<OptimizationContext, OpResult> work
+ )
+ {
+ return runner.RunAsync(
+ new OperationRequest(
+ subject,
+ "Scheduled task test",
+ NullLogger.Instance,
+ RevertPersistence.Disabled,
+ (_, context) =>
+ Task.Run(() =>
+ {
+ work(context);
+ return context.Changes.ToApplyResult();
+ })
+ ),
+ new NoProgress(),
+ TestContext.Current.CancellationToken
+ );
+ }
+
+ private static OpResult Register(string name)
+ {
+ return ScheduledTaskService.RegisterTask(
+ NewCall(),
+ "\\",
+ new ScheduledTaskModel
+ {
+ Name = name,
+ Path = "\\",
+ FullPath = "\\" + name,
+ ExecutablePath = "cmd.exe",
+ Arguments = "/c exit 0",
+ IsEnabled = true,
+ }
+ );
+ }
+
+ private static OpCall NewCall() =>
+ new() { Changes = new ChangeSet(), Logger = NullLogger.Instance };
+
+ private static string RevertPath(Guid id) => Path.Combine(Shared.RevertDirectory, id + ".json");
+
+ private static RevertManager NewRevertManager() =>
+ new(
+ NullLogger<RevertManager>.Instance,
+ TestShell.New(),
+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),
+ TimeProvider.System
+ );
+
+ private static void Cleanup(Guid id)
+ {
+ foreach (
+ var path in new[]
+ {
+ ChangeRecordStore.PathFor(id),
+ RevertPath(id),
+ RevertPath(id) + ".tmp",
+ }
+ )
+ if (File.Exists(path))
+ File.Delete(path);
+ }
+
+ /// <summary>
+ /// Runs the action on a single-threaded apartment with a dispatcher, without which a dialog
+ /// cannot be touched.
+ /// </summary>
+ private static Task RunInStaThreadAsync(Func<Task> action)
+ {
+ var tcs = new TaskCompletionSource();
+
+ var thread = new Thread(() =>
+ {
+ var dispatcher = Dispatcher.CurrentDispatcher;
+ SynchronizationContext.SetSynchronizationContext(
+ new DispatcherSynchronizationContext(dispatcher)
+ );
+ var frame = new DispatcherFrame();
+
+ dispatcher.InvokeAsync(async () =>
+ {
+ try
+ {
+ await action();
+ tcs.SetResult();
+ }
+ catch (Exception ex)
+ {
+ tcs.SetException(ex);
+ }
+ finally
+ {
+ frame.Continue = false;
+ }
+ });
+
+ Dispatcher.PushFrame(frame);
+ });
+
+ thread.SetApartmentState(ApartmentState.STA);
+ thread.Start();
+
+ return tcs.Task;
+ }
+
+ private sealed class NoProgress : IProgress<ProcessingProgress>
+ {
+ public void Report(ProcessingProgress value) { }
+ }
+
+ /// <summary>Records what a component logged, and the runs the lifecycle started.</summary>
+ /// <typeparam name="T">The category the logger is created for.</typeparam>
+ private sealed class CapturingLogger<T> : ILogger<T>
+ {
+ public List<string> Messages { get; } = [];
+
+ public List<string> Started { get; } = [];
+
+ public IDisposable? BeginScope<TState>(TState state)
+ where TState : notnull => null;
+
+ public bool IsEnabled(LogLevel logLevel) => true;
+
+ public void Log<TState>(
+ LogLevel logLevel,
+ EventId eventId,
+ TState state,
+ Exception? exception,
+ Func<TState, Exception?, string> formatter
+ )
+ {
+ var message = formatter(state, exception);
+ Messages.Add(
+ $"{logLevel}: {message}{exception switch { null => "", _ => $" [{exception.GetType().Name}: {exception.Message}]" }}"
+ );
+ if (message.StartsWith("Starting run of", StringComparison.Ordinal))
+ Started.Add(message);
+ }
+ }
+
+ private sealed class FakeSnackbarService : ISnackbarService
+ {
+ public List<(string Title, string Message)> Shown { get; } = [];
+
+ public TimeSpan DefaultTimeOut { get; set; } = TimeSpan.FromSeconds(3);
+
+ public SnackbarPresenter? GetSnackbarPresenter() => null;
+
+ public void SetSnackbarPresenter(SnackbarPresenter presenter) { }
+
+ public void Show(
+ string title,
+ string message,
+ ControlAppearance appearance,
+ IconElement? icon,
+ TimeSpan timeout
+ )
+ {
+ Shown.Add((title, message));
+ }
+ }
+}
diff --git a/optimizerDuck.Test/Services/UI/StartupManagerServiceTests.cs b/optimizerDuck.Test/Services/UI/StartupManagerServiceTests.cs
index cb691b5..c273ea0 100644
--- a/optimizerDuck.Test/Services/UI/StartupManagerServiceTests.cs
+++ b/optimizerDuck.Test/Services/UI/StartupManagerServiceTests.cs
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.StartupManager;
using optimizerDuck.Services.UI;
@@ -28,15 +29,19 @@ public class StartupManagerServiceTests
{
// A toggle for a task that does not exist must report failure, never log success.
var service = new StartupManagerService(NullLogger<StartupManagerService>.Instance);
+ var call = new OpCall { Changes = new ChangeSet(), Logger = NullLogger.Instance };
var task = new StartupTask
{
TaskName = $"optimizerDuck_Test_Missing_{Guid.NewGuid():N}",
TaskPath = "\\",
};
- var result = await service.ToggleStartupTask(task, true);
+ var result = await service.ToggleStartupTask(call, task, true);
Assert.False(result.Ok);
Assert.NotNull(result.Error);
+
+ // The provider recorded what it found, and the service decided this list cannot act on it.
+ Assert.Equal(ChangeKind.NotApplicable, Assert.Single(call.Changes.Changes).Kind);
}
}
diff --git a/optimizerDuck.Test/Services/UI/StartupManagerTaskRunTests.cs b/optimizerDuck.Test/Services/UI/StartupManagerTaskRunTests.cs
new file mode 100644
index 0000000..b71b6a8
--- /dev/null
+++ b/optimizerDuck.Test/Services/UI/StartupManagerTaskRunTests.cs
@@ -0,0 +1,205 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Common.Helpers;
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.Optimizations.Models.ScheduledTask;
+using optimizerDuck.Domain.Optimizations.Models.StartupManager;
+using optimizerDuck.Domain.UI;
+using optimizerDuck.Services.Configuration;
+using optimizerDuck.Services.History;
+using optimizerDuck.Services.Revert;
+using optimizerDuck.Services.System;
+using optimizerDuck.Services.System.Primitives;
+using optimizerDuck.Services.UI;
+using optimizerDuck.Test.TestDoubles;
+
+namespace optimizerDuck.Test.Services.UI;
+
+/// <summary>
+/// Pins what a startup manager task toggle does through the run lifecycle: the provider's step
+/// is recorded under the startup manager's subject, no revert data is persisted, and an entry
+/// Windows no longer has is reported as a failure naming it.
+/// </summary>
+/// <remarks>
+/// These drive the work the page's delegate performs, not the page's wiring of it.
+/// </remarks>
+public class StartupManagerTaskRunTests
+{
+ [Fact]
+ public async Task TogglingALiveTask_RecordsTheChangeUnderItsOwnSubject()
+ {
+ var name = $"optimizerDuck_Test_{Guid.NewGuid():N}";
+
+ try
+ {
+ Assert.True(Register(name).Ok);
+
+ var result = await RunToggleAsync(Task(name), enable: false);
+
+ Assert.Equal(OptimizationSuccessResult.Success, result.Status);
+ Assert.Empty(result.FailedSteps);
+
+ var record = ChangeRecordStore.TryRead(ToolSubjects.StartupManagerTasks.Id);
+ Assert.NotNull(record);
+ Assert.Equal(ToolSubjects.StartupManagerTasks.Key, record!.OptimizationKey);
+ Assert.Equal(ChangeKind.Change, Assert.Single(record.Steps).Kind);
+
+ // A tool run keeps no revert data, whatever the provider recorded.
+ Assert.False(File.Exists(RevertPath(ToolSubjects.StartupManagerTasks.Id)));
+ }
+ finally
+ {
+ Delete(name);
+ Cleanup();
+ }
+ }
+
+ [Fact]
+ public async Task TogglingAnAlreadyDisabledTask_RecordsASkip()
+ {
+ var name = $"optimizerDuck_Test_{Guid.NewGuid():N}";
+
+ try
+ {
+ Assert.True(Register(name).Ok);
+ Assert.Equal(
+ OptimizationSuccessResult.Success,
+ (await RunToggleAsync(Task(name), enable: false)).Status
+ );
+
+ var result = await RunToggleAsync(Task(name), enable: false);
+
+ Assert.Equal(OptimizationSuccessResult.NothingToDo, result.Status);
+ Assert.Equal(
+ ChangeKind.Skip,
+ Assert
+ .Single(ChangeRecordStore.TryRead(ToolSubjects.StartupManagerTasks.Id)!.Steps)
+ .Kind
+ );
+ }
+ finally
+ {
+ Delete(name);
+ Cleanup();
+ }
+ }
+
+ [Fact]
+ public async Task TogglingATaskWindowsNoLongerHas_ReportsAFailureNamingIt()
+ {
+ var name = $"optimizerDuck_Test_{Guid.NewGuid():N}";
+
+ try
+ {
+ Assert.True(Register(name).Ok);
+ // The page's list still holds it, and Windows does not: the stale entry case.
+ Delete(name);
+
+ var result = await RunToggleAsync(Task(name), enable: false);
+
+ Assert.Equal(OptimizationSuccessResult.Failed, result.Status);
+ // No failed step to name, so the message says what went wrong, and it names the entry.
+ Assert.Empty(result.FailedSteps);
+ Assert.Contains(name, result.Message, StringComparison.Ordinal);
+
+ // The provider's own statement is the only step recorded, and nothing was persisted.
+ Assert.Equal(
+ ChangeKind.NotApplicable,
+ Assert
+ .Single(ChangeRecordStore.TryRead(ToolSubjects.StartupManagerTasks.Id)!.Steps)
+ .Kind
+ );
+ Assert.False(File.Exists(RevertPath(ToolSubjects.StartupManagerTasks.Id)));
+ }
+ finally
+ {
+ Delete(name);
+ Cleanup();
+ }
+ }
+
+ /// <summary>
+ /// Runs one toggle the way the page's delegate does: the service records into the run's
+ /// context, and a result it reports as failed becomes the error the run carries.
+ /// </summary>
+ private static Task<OptimizationResult> RunToggleAsync(StartupTask task, bool enable) =>
+ TestRunner
+ .New(NewRevertManager())
+ .RunAsync(
+ new OperationRequest(
+ ToolSubjects.StartupManagerTasks,
+ "Startup manager task",
+ NullLogger.Instance,
+ RevertPersistence.Disabled,
+ async (_, context) =>
+ {
+ var result = await new StartupManagerService(
+ NullLogger<StartupManagerService>.Instance
+ ).ToggleStartupTask(context, task, enable);
+
+ return result.Ok
+ ? context.Changes.ToApplyResult()
+ : ApplyResult.False(
+ result.Error
+ ?? Loc.Instance["Optimization.Apply.Error.AllStepsFailed"]
+ );
+ }
+ ),
+ new NoProgress(),
+ TestContext.Current.CancellationToken
+ );
+
+ private static StartupTask Task(string name) => new() { TaskName = name, TaskPath = "\\" };
+
+ private static OpResult Register(string name) =>
+ ScheduledTaskService.RegisterTask(
+ NewCall(),
+ "\\",
+ new ScheduledTaskModel
+ {
+ Name = name,
+ Path = "\\",
+ FullPath = "\\" + name,
+ ExecutablePath = "cmd.exe",
+ Arguments = "/c exit 0",
+ IsEnabled = true,
+ }
+ );
+
+ private static void Delete(string name) =>
+ ScheduledTaskService.DeleteTask(NewCall(), "\\" + name);
+
+ private static OpCall NewCall() =>
+ new() { Changes = new ChangeSet(), Logger = NullLogger.Instance };
+
+ private static string RevertPath(Guid id) => Path.Combine(Shared.RevertDirectory, id + ".json");
+
+ private static RevertManager NewRevertManager() =>
+ new(
+ NullLogger<RevertManager>.Instance,
+ TestShell.New(),
+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),
+ TimeProvider.System
+ );
+
+ private static void Cleanup()
+ {
+ var id = ToolSubjects.StartupManagerTasks.Id;
+
+ foreach (
+ var path in new[]
+ {
+ ChangeRecordStore.PathFor(id),
+ RevertPath(id),
+ RevertPath(id) + ".tmp",
+ }
+ )
+ if (File.Exists(path))
+ File.Delete(path);
+ }
+
+ private sealed class NoProgress : IProgress<ProcessingProgress>
+ {
+ public void Report(ProcessingProgress value) { }
+ }
+}
diff --git a/optimizerDuck.Test/Services/UI/ToolRunPresenterTests.cs b/optimizerDuck.Test/Services/UI/ToolRunPresenterTests.cs
new file mode 100644
index 0000000..b6d0338
--- /dev/null
+++ b/optimizerDuck.Test/Services/UI/ToolRunPresenterTests.cs
@@ -0,0 +1,328 @@
+using System.Windows.Controls;
+using System.Windows.Threading;
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Common.Helpers;
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.UI;
+using optimizerDuck.Services.History;
+using optimizerDuck.Services.Revert;
+using optimizerDuck.Services.System;
+using optimizerDuck.Services.System.Primitives;
+using optimizerDuck.Test.TestDoubles;
+using optimizerDuck.UI.ViewModels;
+using Wpf.Ui;
+using Wpf.Ui.Controls;
+
+namespace optimizerDuck.Test.Services.UI;
+
+/// <summary>
+/// Pins what a tool run reports: a failure with nothing to retry goes to a snackbar, a retry
+/// runs under the run's own subject, and a dialog that cannot be built never stops the run.
+/// </summary>
+/// <remarks>
+/// Wpf.Ui's boxes resolve theme resources this host does not load, so a presenter that needs
+/// one is exercised as the degraded path. Retries go through
+/// <see cref="ToolRunPresenter.RetryAsync" />.
+/// </remarks>
+public class ToolRunPresenterTests
+{
+ private const string FailureTitle = "Error";
+
+ [Fact]
+ public async Task RunAsync_ReportsTheRunEvenWhenNoBoxCanBeBuilt()
+ {
+ await RunInStaThreadAsync(async () =>
+ {
+ var subject = NewSubject();
+ var dialogs = new FakeContentDialogService();
+ var snackbar = new FakeSnackbarService();
+ var presenter = NewPresenter(dialogs, snackbar);
+ var request = NewRequest(
+ subject,
+ context =>
+ {
+ context.Changes.Add("Scheduled Task", "disabled a task", true);
+ return context.Changes.ToApplyResult();
+ }
+ );
+
+ try
+ {
+ var result = await presenter.RunAsync(request);
+
+ // The box could not be built here, and the action still ran and was classified.
+ Assert.Equal(OptimizationSuccessResult.Success, result.Status);
+ Assert.Empty(snackbar.Shown);
+
+ var record = ChangeRecordStore.TryRead(subject.Id);
+ Assert.NotNull(record);
+ Assert.Equal(1, record!.ChangedCount);
+ }
+ finally
+ {
+ Cleanup(subject.Id);
+ }
+ });
+ }
+
+ [Fact]
+ public async Task RetryAsync_UsesTheRunsOwnSubjectAndTheRecordTakesTheRetry()
+ {
+ await RunInStaThreadAsync(async () =>
+ {
+ var subject = NewSubject();
+ var presenter = NewPresenter(new FakeContentDialogService(), new FakeSnackbarService());
+ var request = NewRequest(
+ subject,
+ context =>
+ {
+ context.Changes.Add(
+ "Scheduled Task",
+ "disabled a task",
+ false,
+ null,
+ error: "access denied",
+ retry: retryCall =>
+ {
+ retryCall.Changes.Add("Scheduled Task", "disabled a task", true);
+ return Task.FromResult(OpResult.Success());
+ }
+ );
+ return context.Changes.ToApplyResult();
+ }
+ );
+
+ try
+ {
+ var result = await presenter.RunAsync(request);
+ Assert.Equal(OptimizationSuccessResult.Failed, result.Status);
+ Assert.Single(result.FailedSteps);
+
+ var retry = await presenter.RetryAsync(request, result.FailedSteps);
+
+ var recovered = Assert.Single(retry.RecoveredSteps);
+ Assert.Empty(retry.FailedSteps);
+ Assert.Equal(2, recovered.Attempt);
+
+ // The retry landed in its run's record, and persisted no revert data.
+ var record = ChangeRecordStore.TryRead(subject.Id);
+ Assert.NotNull(record);
+ Assert.Equal(1, record!.ChangedCount);
+ Assert.Equal(0, record.FailedCount);
+ Assert.False(File.Exists(RevertPath(subject.Id)));
+ }
+ finally
+ {
+ Cleanup(subject.Id);
+ }
+ });
+ }
+
+ [Fact]
+ public async Task ReportAsync_FailureWithNothingToRetry_ReportsItInASnackbar()
+ {
+ await RunInStaThreadAsync(async () =>
+ {
+ var subject = NewSubject();
+ var dialogs = new FakeContentDialogService();
+ var snackbar = new FakeSnackbarService();
+ var presenter = NewPresenter(dialogs, snackbar);
+ var request = NewRequest(
+ subject,
+ _ => ApplyResult.False("the entry is no longer on this machine")
+ );
+
+ try
+ {
+ var result = await presenter.RunAsync(request);
+ Assert.Equal(OptimizationSuccessResult.Failed, result.Status);
+ Assert.Empty(result.FailedSteps);
+
+ var reported = await presenter.ReportAsync(request, result, FailureTitle);
+
+ Assert.False(reported);
+ var shown = Assert.Single(snackbar.Shown);
+ Assert.Equal(FailureTitle, shown.Title);
+ Assert.Equal(result.Message, shown.Message);
+ Assert.Empty(dialogs.ShownTitles);
+ }
+ finally
+ {
+ Cleanup(subject.Id);
+ }
+ });
+ }
+
+ [Fact]
+ public async Task ReportAsync_Success_ReportsNothing()
+ {
+ await RunInStaThreadAsync(async () =>
+ {
+ var subject = NewSubject();
+ var dialogs = new FakeContentDialogService();
+ var snackbar = new FakeSnackbarService();
+ var presenter = NewPresenter(dialogs, snackbar);
+ var request = NewRequest(subject, context => context.Changes.ToApplyResult());
+
+ try
+ {
+ var result = await presenter.RunAsync(request);
+ Assert.Equal(OptimizationSuccessResult.NothingToDo, result.Status);
+
+ var reported = await presenter.ReportAsync(request, result, FailureTitle);
+
+ Assert.True(reported);
+ Assert.Empty(snackbar.Shown);
+ Assert.Empty(dialogs.ShownTitles);
+ }
+ finally
+ {
+ Cleanup(subject.Id);
+ }
+ });
+ }
+
+ private static ToolRunPresenter NewPresenter(
+ FakeContentDialogService dialogs,
+ FakeSnackbarService snackbar
+ ) =>
+ new(
+ TestRunner.New(NewRevertManager()),
+ dialogs,
+ snackbar,
+ NullLogger<ToolRunPresenter>.Instance
+ );
+
+ private static OperationRequest NewRequest(
+ OperationSubject subject,
+ Func<OptimizationContext, ApplyResult> work
+ ) =>
+ new(
+ subject,
+ "Startup manager task",
+ NullLogger.Instance,
+ RevertPersistence.Disabled,
+ (_, context) => Task.FromResult(work(context))
+ );
+
+ private static OperationSubject NewSubject() =>
+ new(Guid.NewGuid(), "PresenterTestTool", "Presenter test tool");
+
+ private static string RevertPath(Guid id) => Path.Combine(Shared.RevertDirectory, id + ".json");
+
+ private static RevertManager NewRevertManager() =>
+ new(
+ NullLogger<RevertManager>.Instance,
+ TestShell.New(),
+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),
+ TimeProvider.System
+ );
+
+ private static void Cleanup(Guid id)
+ {
+ foreach (
+ var path in new[]
+ {
+ ChangeRecordStore.PathFor(id),
+ RevertPath(id),
+ RevertPath(id) + ".tmp",
+ }
+ )
+ if (File.Exists(path))
+ File.Delete(path);
+ }
+
+ /// <summary>
+ /// Runs the action on a single-threaded apartment with a dispatcher, without which a dialog
+ /// cannot be touched.
+ /// </summary>
+ private static Task RunInStaThreadAsync(Func<Task> action)
+ {
+ var tcs = new TaskCompletionSource();
+
+ var thread = new Thread(() =>
+ {
+ var dispatcher = Dispatcher.CurrentDispatcher;
+ SynchronizationContext.SetSynchronizationContext(
+ new DispatcherSynchronizationContext(dispatcher)
+ );
+ var frame = new DispatcherFrame();
+
+ dispatcher.InvokeAsync(async () =>
+ {
+ try
+ {
+ await action();
+ tcs.SetResult();
+ }
+ catch (Exception ex)
+ {
+ tcs.SetException(ex);
+ }
+ finally
+ {
+ frame.Continue = false;
+ }
+ });
+
+ Dispatcher.PushFrame(frame);
+ });
+
+ thread.SetApartmentState(ApartmentState.STA);
+ thread.Start();
+
+ return tcs.Task;
+ }
+
+ private sealed class FakeSnackbarService : ISnackbarService
+ {
+ public List<(string Title, string Message)> Shown { get; } = [];
+
+ public TimeSpan DefaultTimeOut { get; set; } = TimeSpan.FromSeconds(3);
+
+ public SnackbarPresenter? GetSnackbarPresenter() => null;
+
+ public void SetSnackbarPresenter(SnackbarPresenter presenter) { }
+
+ public void Show(
+ string title,
+ string message,
+ ControlAppearance appearance,
+ IconElement? icon,
+ TimeSpan timeout
+ )
+ {
+ Shown.Add((title, message));
+ }
+ }
+
+ /// <summary>
+ /// Stands in for the dialog host a real shell provides, and records what was asked of it.
+ /// </summary>
+ private sealed class FakeContentDialogService : IContentDialogService
+ {
+ public List<string> ShownTitles { get; } = [];
+
+ public Task<ContentDialogResult> ShowAsync(
+ ContentDialog dialog,
+ CancellationToken cancellationToken
+ )
+ {
+ ShownTitles.Add(dialog.Title?.ToString() ?? string.Empty);
+ return Task.FromResult(ContentDialogResult.None);
+ }
+
+ public ContentPresenter? GetDialogHost() => null;
+
+ public ContentDialogHost? GetDialogHostEx() => null;
+
+ public void SetDialogHost(ContentDialogHost dialogHost) { }
+
+ public void SetDialogHost(ContentPresenter contentPresenter) { }
+
+ public ContentPresenter? GetContentPresenter() => null;
+
+ public void SetContentPresenter(ContentPresenter contentPresenter) { }
+ }
+}
diff --git a/optimizerDuck.Test/TestDoubles/TestRunner.cs b/optimizerDuck.Test/TestDoubles/TestRunner.cs
new file mode 100644
index 0000000..15fcba0
--- /dev/null
+++ b/optimizerDuck.Test/TestDoubles/TestRunner.cs
@@ -0,0 +1,31 @@
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Services.Optimization;
+using optimizerDuck.Services.Revert;
+using optimizerDuck.Services.System;
+using optimizerDuck.Services.System.Primitives;
+
+namespace optimizerDuck.Test.TestDoubles;
+
+/// <summary>The run lifecycle as the application's graph builds it, logging nothing.</summary>
+internal static class TestRunner
+{
+ /// <summary>Builds a run lifecycle over the given revert store.</summary>
+ /// <param name="revertManager">The revert store the runs persist into.</param>
+ /// <param name="logger">The logger the runs report to, or nothing when omitted.</param>
+ /// <returns>The run lifecycle the application's graph would inject.</returns>
+ internal static OperationRunner New(
+ RevertManager revertManager,
+ ILogger<OperationRunner>? logger = null
+ )
+ {
+ return new OperationRunner(
+ revertManager,
+ new SystemInfoService(NullLogger<SystemInfoService>.Instance),
+ new StreamService(NullLogger<StreamService>.Instance),
+ new ShellService(new ProcessRunner(120_000)),
+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),
+ logger ?? NullLogger<OperationRunner>.Instance
+ );
+ }
+}
diff --git a/optimizerDuck/App.xaml.cs b/optimizerDuck/App.xaml.cs
index d86e22b..9e403b2 100644
--- a/optimizerDuck/App.xaml.cs
+++ b/optimizerDuck/App.xaml.cs
@@ -214,9 +214,7 @@ public partial class App : Application
{
await HandleStartupErrorStaticAsync(ex);
}
- catch
- {
- }
+ catch { }
}
}
@@ -271,6 +269,17 @@ public partial class App : Application
{
LogExceptionToFile("DispatcherUnhandledException", e.Exception);
Log.Logger?.Error(e.Exception, "Unhandled UI dispatcher exception");
+
+ // The exception is swallowed below, so the user is told about it here.
+ try
+ {
+ _host?.Services.GetService<UserErrorSurface>()?.TryReport(e.Exception);
+ }
+ catch (Exception ex)
+ {
+ Log.Logger?.Warning(ex, "Could not report the unhandled exception to the user");
+ }
+
e.Handled = true;
}
diff --git a/optimizerDuck/ApplicationServiceCollectionExtensions.cs b/optimizerDuck/ApplicationServiceCollectionExtensions.cs
index ac89741..1d32e97 100644
--- a/optimizerDuck/ApplicationServiceCollectionExtensions.cs
+++ b/optimizerDuck/ApplicationServiceCollectionExtensions.cs
@@ -1,6 +1,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using optimizerDuck.Common.Extensions;
+using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Configuration;
using optimizerDuck.Services.Configuration;
@@ -11,6 +12,7 @@ using optimizerDuck.Services.System;
using optimizerDuck.Services.System.Primitives;
using optimizerDuck.Services.UI;
using optimizerDuck.UI.Pages;
+using optimizerDuck.UI.ViewModels;
using optimizerDuck.UI.ViewModels.Dialogs;
using optimizerDuck.UI.ViewModels.Pages;
using optimizerDuck.UI.ViewModels.Windows;
@@ -98,6 +100,8 @@ public static class ApplicationServiceCollectionExtensions
services.AddSingleton<RevertManager>();
services.AddSingleton<OptimizationRegistry>();
services.AddSingleton<CustomizeRegistry>();
+ services.AddSingleton<OperationRunner>();
+ services.AddSingleton<ToolRunPresenter>();
services.AddSingleton<OptimizationService>();
services.AddSingleton<BloatwareService>();
services.AddSingleton<DiskCleanupService>();
@@ -106,6 +110,7 @@ public static class ApplicationServiceCollectionExtensions
services.AddSingleton<StreamService>();
services.AddSingleton<UpdaterService>();
services.AddSingleton<IRegistryWatcher, RegistryWatcher>();
+ services.AddSingleton<UserErrorSurface>();
return services;
}
diff --git a/optimizerDuck/Common/Helpers/UserErrorSurface.cs b/optimizerDuck/Common/Helpers/UserErrorSurface.cs
new file mode 100644
index 0000000..63d50ab
--- /dev/null
+++ b/optimizerDuck/Common/Helpers/UserErrorSurface.cs
@@ -0,0 +1,111 @@
+using System.Runtime.CompilerServices;
+using System.Windows;
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Resources.Languages;
+using optimizerDuck.Services.Configuration;
+using Wpf.Ui;
+using Wpf.Ui.Controls;
+
+namespace optimizerDuck.Common.Helpers;
+
+/// <summary>
+/// Reports an unhandled failure to the user once per failure, and never throws.
+/// </summary>
+public sealed class UserErrorSurface
+{
+ private readonly ILogger<UserErrorSurface>? _logger;
+ private readonly Action<string, string>? _present;
+
+ // Key and value are the same failure: the table only remembers which ones were already
+ // reported, and it holds them weakly, so a reported failure is never kept alive by it.
+ private readonly ConditionalWeakTable<Exception, Exception> _reported = new();
+ private readonly ISnackbarService? _snackbar;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserErrorSurface" /> class that reports
+ /// through the shell's snackbar.
+ /// </summary>
+ /// <param name="snackbar">The snackbar service of the shell.</param>
+ /// <param name="logger">The logger a failed report is written to.</param>
+ public UserErrorSurface(ISnackbarService snackbar, ILogger<UserErrorSurface> logger)
+ {
+ _snackbar = snackbar;
+ _logger = logger;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserErrorSurface" /> class that hands the
+ /// report to <paramref name="present" />.
+ /// </summary>
+ /// <param name="present">Receives the report's title and message.</param>
+ internal UserErrorSurface(Action<string, string> present)
+ {
+ _present = present;
+ }
+
+ /// <summary>Reports a failure to the user, once per exception.</summary>
+ /// <param name="exception">The failure to report.</param>
+ /// <returns>
+ /// <see langword="true" /> if this call reported the failure; otherwise,
+ /// <see langword="false" />.
+ /// </returns>
+ public bool TryReport(Exception exception)
+ {
+ ArgumentNullException.ThrowIfNull(exception);
+
+ if (!_reported.TryAdd(exception, exception))
+ return false;
+
+ var title = Loc.Instance["Error.Unhandled.Title"];
+ var message =
+ Loc.Instance["Error.Unhandled.Message", exception.Message]
+ + Environment.NewLine
+ + Loc.Instance["Error.Unhandled.LogHint"];
+
+ try
+ {
+ Present(title, message);
+ }
+ catch (Exception ex)
+ {
+ _logger?.LogWarning(ex, "Could not report the failure to the user");
+ }
+
+ return true;
+ }
+
+ private void Present(string title, string message)
+ {
+ if (_present is not null)
+ {
+ _present(title, message);
+ return;
+ }
+
+ try
+ {
+ if (_snackbar is not null)
+ {
+ _snackbar.Show(
+ title,
+ message,
+ ControlAppearance.Danger,
+ new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
+ TimeSpan.FromSeconds(8)
+ );
+ return;
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger?.LogWarning(ex, "The shell could not show the report; using a message box");
+ }
+
+ System.Windows.MessageBox.Show(
+ message,
+ title,
+ System.Windows.MessageBoxButton.OK,
+ System.Windows.MessageBoxImage.Error
+ );
+ }
+}
diff --git a/optimizerDuck/Domain/Execution/ChangeRecord.cs b/optimizerDuck/Domain/Execution/ChangeRecord.cs
index ae242ea..7c33a6f 100644
--- a/optimizerDuck/Domain/Execution/ChangeRecord.cs
+++ b/optimizerDuck/Domain/Execution/ChangeRecord.cs
@@ -82,18 +82,21 @@ public sealed record ChangeRecord
};
}
- /// <summary>
- /// Captures one finished apply. The record is a copy: nothing here is live state.
- /// </summary>
- public static ChangeRecord From(ChangeSet changes, IOptimization item, string outcome)
+ /// <summary>Captures one finished run.</summary>
+ /// <param name="changes">The steps the run recorded.</param>
+ /// <param name="subject">The owner the record belongs to.</param>
+ /// <param name="outcome">The name of the status the run ended with.</param>
+ /// <returns>The record as the file stores it.</returns>
+ public static ChangeRecord From(ChangeSet changes, OperationSubject subject, string outcome)
{
ArgumentNullException.ThrowIfNull(changes);
+ ArgumentNullException.ThrowIfNull(subject);
return new ChangeRecord
{
- Id = item.Id,
- OptimizationKey = item.OptimizationKey,
- LogName = item.LogName(),
+ Id = subject.Id,
+ OptimizationKey = subject.Key,
+ LogName = subject.LogName,
AppliedAt = DateTime.Now,
StartedAt = changes.StartedAt,
ElapsedMs = changes.ElapsedMs,
@@ -104,6 +107,22 @@ public sealed record ChangeRecord
};
}
+ /// <summary>Captures one finished apply for an optimization.</summary>
+ /// <param name="changes">The steps the run recorded.</param>
+ /// <param name="item">The optimization the record belongs to.</param>
+ /// <param name="outcome">The name of the status the run ended with.</param>
+ /// <returns>The record as the file stores it.</returns>
+ public static ChangeRecord From(ChangeSet changes, IOptimization item, string outcome)
+ {
+ ArgumentNullException.ThrowIfNull(item);
+
+ return From(
+ changes,
+ new OperationSubject(item.Id, item.OptimizationKey, item.LogName()),
+ outcome
+ );
+ }
+
/// <summary>
/// The same record as a retry leaves it: a step the retry took further takes the
/// outcome the retry reached and counts one more attempt, and a step the retry did
diff --git a/optimizerDuck/Domain/Execution/ChangeSet.cs b/optimizerDuck/Domain/Execution/ChangeSet.cs
index ea8d0c2..b173cd6 100644
--- a/optimizerDuck/Domain/Execution/ChangeSet.cs
+++ b/optimizerDuck/Domain/Execution/ChangeSet.cs
@@ -75,10 +75,10 @@ public sealed class ChangeSet
}
/// <summary>
- /// Whether any step modified the system. Skips and irreversible actions
- /// did not leave something to undo, so they do not count as applied changes. A step that
- /// modified the system and then failed still counts, because it carries the compensation
- /// for what it changed, and dropping it here would leave that work unrevertible.
+ /// Gets a value that indicates whether any step left work that undo covers, which is what
+ /// revert persistence is gated on. Only a <see cref="ChangeKind.Change" /> counts: a failed
+ /// one still does when it carries compensation, while a skip or an irreversible step leaves
+ /// nothing to undo.
/// </summary>
public bool DidApplyAnything
{
@@ -89,6 +89,38 @@ public sealed class ChangeSet
}
}
+ /// <summary>
+ /// Gets a value that indicates whether any step modified the system, which is what tells a
+ /// change from nothing to do. Wider than <see cref="DidApplyAnything" />: an irreversible
+ /// step counts, even though it leaves nothing to undo.
+ /// </summary>
+ public bool ModifiedSystem
+ {
+ get
+ {
+ lock (_gate)
+ return _changes.Any(c =>
+ (c.Kind is ChangeKind.Change or ChangeKind.Irreversible)
+ && (c.Ok || c.Revert != null)
+ );
+ }
+ }
+
+ /// <summary>
+ /// Gets the successful changes that carry no compensation. Only a provider can supply that
+ /// data, so one of these is a provider defect and undo does not cover what it wrote.
+ /// </summary>
+ public IReadOnlyList<Change> UncompensatedChanges
+ {
+ get
+ {
+ lock (_gate)
+ return _changes
+ .Where(c => c.Ok && c.Kind == ChangeKind.Change && c.Revert == null)
+ .ToList();
+ }
+ }
+
/// <summary>Records a step that found nothing to do, so it needs no compensation.</summary>
public Change AddSkip(string name, string description, ChangeDetail? detail = null) =>
Add(name, description, true, detail: detail, kind: ChangeKind.Skip);
@@ -174,20 +206,17 @@ public sealed class ChangeSet
}
/// <summary>
- /// Maps recorded changes to an apply result. Any success (full or
- /// partial) is success; total failure carries the first error message.
- /// Empty is failure (fail-closed): a genuine skip must return
- /// <see cref="ApplyResult.True"/> directly with a logged reason,
- /// never an empty set.
+ /// Maps the recorded changes to an apply result. Any success is a success, and a total
+ /// failure carries the first error message. A run that recorded nothing reports success,
+ /// because the caller classifies that as nothing to do.
/// </summary>
public ApplyResult ToApplyResult(string? fallbackError = null)
{
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.
+ // Recording nothing is legitimate: an item can match nothing on this machine. A
+ // provider that changes something without recording it is a defect the compensation
+ // guard reports, not a failure to report here.
if (_changes.Count == 0)
return ApplyResult.True();
if (_changes.Any(c => c.Ok))
diff --git a/optimizerDuck/Domain/Execution/OperationRequest.cs b/optimizerDuck/Domain/Execution/OperationRequest.cs
new file mode 100644
index 0000000..a70c2c8
--- /dev/null
+++ b/optimizerDuck/Domain/Execution/OperationRequest.cs
@@ -0,0 +1,22 @@
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.UI;
+
+namespace optimizerDuck.Domain.Execution;
+
+/// <summary>
+/// One run: the subject it belongs to, the work to invoke, and whether its compensation is
+/// persisted.
+/// </summary>
+/// <param name="Subject">The owner the run's record and revert data belong to.</param>
+/// <param name="DisplayName">The name user-facing messages carry.</param>
+/// <param name="RunLogger">The logger the run writes through.</param>
+/// <param name="Revert">Whether the run persists revert data.</param>
+/// <param name="Work">The work to invoke once with the run's context.</param>
+public sealed record OperationRequest(
+ OperationSubject Subject,
+ string DisplayName,
+ ILogger RunLogger,
+ RevertPersistence Revert,
+ Func<IProgress<ProcessingProgress>, OptimizationContext, Task<ApplyResult>> Work
+);
diff --git a/optimizerDuck/Domain/Execution/OperationSubject.cs b/optimizerDuck/Domain/Execution/OperationSubject.cs
new file mode 100644
index 0000000..1a52f86
--- /dev/null
+++ b/optimizerDuck/Domain/Execution/OperationSubject.cs
@@ -0,0 +1,17 @@
+namespace optimizerDuck.Domain.Execution;
+
+/// <summary>Identifies the owner of a run, which is an optimization or a built-in tool.</summary>
+/// <param name="Id">The stable identifier, which names the run's record file.</param>
+/// <param name="Key">The stable key written into the record and the log.</param>
+/// <param name="LogName">The English name written to the log.</param>
+public sealed record OperationSubject(Guid Id, string Key, string LogName);
+
+/// <summary>Whether a run persists the compensation of the steps it records.</summary>
+public enum RevertPersistence
+{
+ /// <summary>The compensation of every step carrying one is written as revert data.</summary>
+ Enabled,
+
+ /// <summary>Nothing is written to the revert store, so the run offers no undo.</summary>
+ Disabled,
+}
diff --git a/optimizerDuck/Domain/Execution/ToolSubjects.cs b/optimizerDuck/Domain/Execution/ToolSubjects.cs
new file mode 100644
index 0000000..17720e8
--- /dev/null
+++ b/optimizerDuck/Domain/Execution/ToolSubjects.cs
@@ -0,0 +1,25 @@
+namespace optimizerDuck.Domain.Execution;
+
+/// <summary>
+/// The subjects of the built-in tools. An identifier is a permanent record key, so changing one
+/// orphans the records already written under it.
+/// </summary>
+public static class ToolSubjects
+{
+ /// <summary>The scheduled task manager on the tools page.</summary>
+ public static readonly OperationSubject ScheduledTasks = new(
+ Guid.Parse("9F1C4A2E-7B3D-4E58-9A61-0D2F5C8B7E14"),
+ "ScheduledTasks",
+ "Scheduled task"
+ );
+
+ /// <summary>
+ /// The startup manager's scheduled-task list. Its toggles are reported as its own runs, not
+ /// as the task manager's.
+ /// </summary>
+ public static readonly OperationSubject StartupManagerTasks = new(
+ Guid.Parse("34E4A189-58FA-418A-AEFB-9D384C4D586B"),
+ "StartupManagerTasks",
+ "Startup manager task"
+ );
+}
diff --git a/optimizerDuck/Domain/Optimizations/Categories/Debug.cs b/optimizerDuck/Domain/Optimizations/Categories/Debug.cs
new file mode 100644
index 0000000..e3ab355
--- /dev/null
+++ b/optimizerDuck/Domain/Optimizations/Categories/Debug.cs
@@ -0,0 +1,264 @@
+#if DEBUG
+using System.Collections.ObjectModel;
+using optimizerDuck.Common.Extensions;
+using optimizerDuck.Domain.Abstractions;
+using optimizerDuck.Domain.Attributes;
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.Revert.Steps;
+using optimizerDuck.Domain.UI;
+using optimizerDuck.Services.System.Primitives;
+using optimizerDuck.UI.Pages;
+
+namespace optimizerDuck.Domain.Optimizations.Categories;
+
+/// <summary>
+/// Provides the base class for the debug optimizations, whose text is hard-coded English.
+/// </summary>
+public abstract class DebugOptimization : BaseOptimization
+{
+ protected abstract string EnglishName { get; }
+
+ protected abstract string EnglishDescription { get; }
+
+ public override string Name => EnglishName;
+
+ public override string ShortDescription => EnglishDescription;
+
+ public override string LogName => EnglishName;
+
+ public override string LogShortDescription => EnglishDescription;
+
+ /// <summary>Records a no-op change, so a partial failure reaches the retry dialog.</summary>
+ protected static void RecordDebugChange(OptimizationContext context) =>
+ context.Changes.Add("Debug step", "wrote a debug value", true, DebugCompensation());
+
+ /// <summary>Creates a compensation that does nothing.</summary>
+ protected static ShellRevertStep DebugCompensation() =>
+ new() { ShellType = ShellType.CMD, Command = "exit 0" };
+
+ protected const string DebugFailure = "a deliberate debug failure";
+}
+
+/// <summary>
+/// Provides the debug scenarios reachable by hand from the optimize page. The file is excluded
+/// from a release build, so the category is never discovered there.
+/// </summary>
+/// <remarks>
+/// A scenario records steps in the run's own change set and touches nothing on the machine.
+/// </remarks>
+[OptimizationCategory(typeof(DebugOptimizerPage))]
+public class Debug : LocalizedObject, IOptimizationCategory
+{
+ public string Name => "Debug";
+
+ // Reuses the last production order; a debug category only has to sort somewhere.
+ public OptimizationCategoryOrder Order { get; init; } = OptimizationCategoryOrder.AI;
+
+ public ObservableCollection<IOptimization> Optimizations { get; init; } = [];
+
+ [Optimization(
+ Id = "95828E58-DAB1-4382-A0B1-F40B6A44156D",
+ Risk = OptimizationRisk.Safe,
+ Tags = OptimizationTags.System
+ )]
+ public class FailedStepThenRetrySucceeds : DebugOptimization
+ {
+ protected override string EnglishName => "Failed step after a change, retry succeeds";
+
+ protected override string EnglishDescription =>
+ "Records a change, then a failed step whose retry succeeds from the dialog.";
+
+ public override Task<ApplyResult> ApplyAsync(
+ IProgress<ProcessingProgress> progress,
+ OptimizationContext context
+ )
+ {
+ RecordDebugChange(context);
+
+ context.Changes.Add(
+ "Debug step",
+ "the debug step failed, and its retry succeeds",
+ false,
+ null,
+ error: DebugFailure,
+ retry: retryCall =>
+ {
+ retryCall.Changes.Add(
+ "Debug step",
+ "the retry succeeded",
+ true,
+ DebugCompensation()
+ );
+ return Task.FromResult(OpResult.Success());
+ }
+ );
+
+ return Task.FromResult(context.Changes.ToApplyResult());
+ }
+ }
+
+ [Optimization(
+ Id = "DA23B162-A11B-451D-88F1-BE37E250A769",
+ Risk = OptimizationRisk.Safe,
+ Tags = OptimizationTags.System
+ )]
+ public class FailedStepThenRetryFailsAgain : DebugOptimization
+ {
+ protected override string EnglishName => "Failed step after a change, retry fails again";
+
+ protected override string EnglishDescription =>
+ "Records a change, then a failed step whose retry fails again in the dialog.";
+
+ public override Task<ApplyResult> ApplyAsync(
+ IProgress<ProcessingProgress> progress,
+ OptimizationContext context
+ )
+ {
+ RecordDebugChange(context);
+
+ context.Changes.Add(
+ "Debug step",
+ "the debug step failed, and its retry fails again",
+ false,
+ null,
+ error: DebugFailure,
+ retry: retryCall =>
+ {
+ retryCall.Changes.Add(
+ "Debug step",
+ "the retry failed again",
+ false,
+ null,
+ error: DebugFailure
+ );
+ return Task.FromResult(OpResult.Fail(DebugFailure));
+ }
+ );
+
+ return Task.FromResult(context.Changes.ToApplyResult());
+ }
+ }
+
+ [Optimization(
+ Id = "6A5C5662-61AB-4963-98F6-6C2C85478CB7",
+ Risk = OptimizationRisk.Safe,
+ Tags = OptimizationTags.System
+ )]
+ public class FailedStepWithoutARetry : DebugOptimization
+ {
+ protected override string EnglishName => "Failed step after a change, no retry";
+
+ protected override string EnglishDescription =>
+ "Records a change, then a failed step that carries no retry to offer.";
+
+ public override Task<ApplyResult> ApplyAsync(
+ IProgress<ProcessingProgress> progress,
+ OptimizationContext context
+ )
+ {
+ RecordDebugChange(context);
+
+ context.Changes.Add(
+ "Debug step",
+ "the debug step failed",
+ false,
+ null,
+ error: DebugFailure
+ );
+
+ return Task.FromResult(context.Changes.ToApplyResult());
+ }
+ }
+
+ [Optimization(
+ Id = "868F8DA4-8D56-44E4-ADFF-4B593164BCB5",
+ Risk = OptimizationRisk.Safe,
+ Tags = OptimizationTags.System
+ )]
+ public class ProviderErrorWithoutAFailedStep : DebugOptimization
+ {
+ protected override string EnglishName => "Provider reports an error";
+
+ protected override string EnglishDescription =>
+ "Reports an error while recording no step, so no failed step is named.";
+
+ public override Task<ApplyResult> ApplyAsync(
+ IProgress<ProcessingProgress> progress,
+ OptimizationContext context
+ ) =>
+ Task.FromResult(
+ ApplyResult.False("the debug run reported an error and recorded no failed step")
+ );
+ }
+
+ [Optimization(
+ Id = "1C3387DA-2F17-4BE7-B17A-5AAF90794C5D",
+ Risk = OptimizationRisk.Safe,
+ Tags = OptimizationTags.System
+ )]
+ public class ThrowsAfterRecordingAChange : DebugOptimization
+ {
+ protected override string EnglishName => "Throws after recording a change";
+
+ protected override string EnglishDescription =>
+ "Records a change, then throws, so the exception is captured as a failed step.";
+
+ public override Task<ApplyResult> ApplyAsync(
+ IProgress<ProcessingProgress> progress,
+ OptimizationContext context
+ )
+ {
+ RecordDebugChange(context);
+
+ throw new InvalidOperationException("the debug run threw after recording a change");
+ }
+ }
+
+ [Optimization(
+ Id = "78F8BFE3-34EA-47C1-96A3-88DEF36D8A7B",
+ Risk = OptimizationRisk.Safe,
+ Tags = OptimizationTags.System
+ )]
+ public class RecordsAChange : DebugOptimization
+ {
+ protected override string EnglishName => "Records a change";
+
+ protected override string EnglishDescription =>
+ "Records one change and nothing else, so the run is a plain success.";
+
+ public override Task<ApplyResult> ApplyAsync(
+ IProgress<ProcessingProgress> progress,
+ OptimizationContext context
+ )
+ {
+ RecordDebugChange(context);
+
+ return Task.FromResult(context.Changes.ToApplyResult());
+ }
+ }
+
+ [Optimization(
+ Id = "6B2CAF01-8855-488A-9505-D9123E7BDBC7",
+ Risk = OptimizationRisk.Safe,
+ Tags = OptimizationTags.System
+ )]
+ public class AlreadyInTheDesiredState : DebugOptimization
+ {
+ protected override string EnglishName => "Already in the desired state";
+
+ protected override string EnglishDescription =>
+ "Records one skip, so the run reports that there was nothing to do.";
+
+ public override Task<ApplyResult> ApplyAsync(
+ IProgress<ProcessingProgress> progress,
+ OptimizationContext context
+ )
+ {
+ context.Changes.AddSkip("Debug step", "the debug target already matches");
+
+ return Task.FromResult(context.Changes.ToApplyResult());
+ }
+ }
+}
+#endif
diff --git a/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs b/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs
index a50653d..ad2a1ce 100644
--- a/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs
+++ b/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs
@@ -145,16 +145,16 @@ public abstract partial class BaseOptimization : LocalizedObject, IOptimization
public string ErrorPrefix => Loc.Instance[$"{Prefix}.Error"];
/// <summary>Gets the localized display name of the optimization.</summary>
- public string Name => Loc.Instance[$"{Prefix}.Name"];
+ public virtual string Name => Loc.Instance[$"{Prefix}.Name"];
/// <summary>Gets the localized short description of what this optimization does.</summary>
- public string ShortDescription => Loc.Instance[$"{Prefix}.ShortDescription"];
+ public virtual string ShortDescription => Loc.Instance[$"{Prefix}.ShortDescription"];
/// <summary>Gets the English name written to the log.</summary>
- public string LogName => Loc.Invariant[$"Optimizer.{OwnerKey}.{OptimizationKey}.Name"];
+ public virtual string LogName => Loc.Invariant[$"Optimizer.{OwnerKey}.{OptimizationKey}.Name"];
/// <summary>Gets the English short description written to the log.</summary>
- public string LogShortDescription =>
+ public virtual string LogShortDescription =>
Loc.Invariant[$"Optimizer.{OwnerKey}.{OptimizationKey}.ShortDescription"];
#endregion
diff --git a/optimizerDuck/Resources/Languages/Translations.ar-SA.resx b/optimizerDuck/Resources/Languages/Translations.ar-SA.resx
index 72d1243..7015654 100644
--- a/optimizerDuck/Resources/Languages/Translations.ar-SA.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ar-SA.resx
@@ -2567,5 +2567,14 @@
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>المدة</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>حدث خطأ ما</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>تعذّر إكمال الإجراء الأخير: {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>التفاصيل موجودة في ملف السجل.</value>
+ </data>
</root>
diff --git a/optimizerDuck/Resources/Languages/Translations.de-DE.resx b/optimizerDuck/Resources/Languages/Translations.de-DE.resx
index 615b763..3b90408 100644
--- a/optimizerDuck/Resources/Languages/Translations.de-DE.resx
+++ b/optimizerDuck/Resources/Languages/Translations.de-DE.resx
@@ -2577,4 +2577,13 @@ Aktualisiere jetzt, um die neuesten Funktionen, Verbesserungen und Fehlerbehebun
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>Dauer</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>Etwas ist schiefgelaufen</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>Die letzte Aktion konnte nicht abgeschlossen werden: {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>Details stehen in der Protokolldatei.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.es-ES.resx b/optimizerDuck/Resources/Languages/Translations.es-ES.resx
index f7322ff..9833df5 100644
--- a/optimizerDuck/Resources/Languages/Translations.es-ES.resx
+++ b/optimizerDuck/Resources/Languages/Translations.es-ES.resx
@@ -4330,4 +4330,13 @@ Actualiza ahora para disfrutar de las nuevas funciones y mejoras.</value>
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>Duración</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>Se ha producido un error</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>No se pudo completar la última acción: {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>Los detalles están en el archivo de registro.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.fr-FR.resx b/optimizerDuck/Resources/Languages/Translations.fr-FR.resx
index 74d803a..bcd4171 100644
--- a/optimizerDuck/Resources/Languages/Translations.fr-FR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.fr-FR.resx
@@ -2525,4 +2525,13 @@ Mettez à jour maintenant pour profiter des dernières fonctionnalités, amélio
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>Durée</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>Un problème est survenu</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>La dernière action n'a pas pu être terminée : {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>Les détails se trouvent dans le fichier journal.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.he-IL.resx b/optimizerDuck/Resources/Languages/Translations.he-IL.resx
index 3a3119f..9d29168 100644
--- a/optimizerDuck/Resources/Languages/Translations.he-IL.resx
+++ b/optimizerDuck/Resources/Languages/Translations.he-IL.resx
@@ -2582,4 +2582,13 @@
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>משך</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>משהו השתבש</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>לא ניתן היה להשלים את הפעולה האחרונה: {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>הפרטים נמצאים בקובץ היומן.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.id-ID.resx b/optimizerDuck/Resources/Languages/Translations.id-ID.resx
index b12a01a..7272a81 100644
--- a/optimizerDuck/Resources/Languages/Translations.id-ID.resx
+++ b/optimizerDuck/Resources/Languages/Translations.id-ID.resx
@@ -2582,4 +2582,13 @@ Perbarui sekarang untuk menikmati fitur terbaru, peningkatan, dan perbaikan bug.
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>Durasi</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>Terjadi kesalahan</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>Tindakan terakhir tidak dapat diselesaikan: {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>Detailnya ada di file log.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.it-IT.resx b/optimizerDuck/Resources/Languages/Translations.it-IT.resx
index 4297da1..02ea556 100644
--- a/optimizerDuck/Resources/Languages/Translations.it-IT.resx
+++ b/optimizerDuck/Resources/Languages/Translations.it-IT.resx
@@ -2533,4 +2533,13 @@ Aggiorna ora per godere delle ultime funzionalità, miglioramenti e correzioni.<
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>Durata</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>Si è verificato un errore</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>Impossibile completare l'ultima azione: {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>I dettagli sono nel file di log.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.ja-JP.resx b/optimizerDuck/Resources/Languages/Translations.ja-JP.resx
index 11ae6f0..259b051 100644
--- a/optimizerDuck/Resources/Languages/Translations.ja-JP.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ja-JP.resx
@@ -2517,4 +2517,13 @@
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>所要時間</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>問題が発生しました</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>最後の操作を完了できませんでした: {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>詳細はログ ファイルに記録されています。</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.ko-KR.resx b/optimizerDuck/Resources/Languages/Translations.ko-KR.resx
index 072c324..683d70d 100644
--- a/optimizerDuck/Resources/Languages/Translations.ko-KR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ko-KR.resx
@@ -2516,4 +2516,13 @@
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>소요 시간</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>문제가 발생했습니다</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>마지막 작업을 완료하지 못했습니다: {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>자세한 내용은 로그 파일에 있습니다.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.pl-PL.resx b/optimizerDuck/Resources/Languages/Translations.pl-PL.resx
index cc5d137..b86a54a 100644
--- a/optimizerDuck/Resources/Languages/Translations.pl-PL.resx
+++ b/optimizerDuck/Resources/Languages/Translations.pl-PL.resx
@@ -2525,4 +2525,13 @@ Zaktualizuj teraz, aby korzystać z najnowszych funkcji, ulepszeń i poprawek b
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>Czas trwania</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>Coś poszło nie tak</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>Nie udało się ukończyć ostatniej operacji: {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>Szczegóły znajdują się w pliku dziennika.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.pt-BR.resx b/optimizerDuck/Resources/Languages/Translations.pt-BR.resx
index 7c0e04a..9be6da7 100644
--- a/optimizerDuck/Resources/Languages/Translations.pt-BR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.pt-BR.resx
@@ -2525,4 +2525,13 @@ Atualize agora para desfrutar das últimas funcionalidades, melhorias e correç
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>Duração</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>Algo deu errado</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>Não foi possível concluir a última ação: {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>Os detalhes estão no arquivo de log.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resx
index 610cab4..8b0a5b1 100644
--- a/optimizerDuck/Resources/Languages/Translations.resx
+++ b/optimizerDuck/Resources/Languages/Translations.resx
@@ -2583,4 +2583,13 @@ Update now to enjoy the latest features, improvements, and bug fixes.</value>
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>Took</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>Something went wrong</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>The last action could not be completed: {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>Details are in the log file.</value>
+ </data>
</root>
diff --git a/optimizerDuck/Resources/Languages/Translations.ru-RU.resx b/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
index 04bfebb..4cbed02 100644
--- a/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
@@ -2525,4 +2525,13 @@
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>Затрачено</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>Что-то пошло не так</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>Не удалось завершить последнее действие: {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>Подробности в файле журнала.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.tr-TR.resx b/optimizerDuck/Resources/Languages/Translations.tr-TR.resx
index c2461d0..f784738 100644
--- a/optimizerDuck/Resources/Languages/Translations.tr-TR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.tr-TR.resx
@@ -2516,4 +2516,13 @@ En son özelliklerden, iyileştirmelerden ve hata düzeltmelerinden yararlanmak
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>Süre</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>Bir sorun oluştu</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>Son işlem tamamlanamadı: {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>Ayrıntılar günlük dosyasında.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
index db8e91f..52d632f 100644
--- a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
+++ b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
@@ -2517,4 +2517,13 @@ Cập nhật ngay để trải nghiệm các tính năng mới, cải tiến và
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>Thời gian</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>Đã xảy ra sự cố</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>Không thể hoàn tất thao tác vừa rồi: {0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>Chi tiết có trong tệp log.</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.zh-CN.resx b/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
index 95b9e4c..2ccc62a 100644
--- a/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
+++ b/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
@@ -2533,4 +2533,13 @@
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>耗时</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>出现问题</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>无法完成上一步操作:{0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>详细信息已写入日志文件。</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.zh-TW.resx b/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
index b9d39ee..5b196af 100644
--- a/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
+++ b/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
@@ -2520,4 +2520,13 @@
<data name="Optimizer.Details.Record.Took" xml:space="preserve">
<value>耗時</value>
</data>
+ <data name="Error.Unhandled.Title" xml:space="preserve">
+ <value>發生問題</value>
+ </data>
+ <data name="Error.Unhandled.Message" xml:space="preserve">
+ <value>無法完成上一個操作:{0}</value>
+ </data>
+ <data name="Error.Unhandled.LogHint" xml:space="preserve">
+ <value>詳細資料已寫入記錄檔。</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Services/Optimization/OperationRunner.cs b/optimizerDuck/Services/Optimization/OperationRunner.cs
new file mode 100644
index 0000000..87893d2
--- /dev/null
+++ b/optimizerDuck/Services/Optimization/OperationRunner.cs
@@ -0,0 +1,288 @@
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.UI;
+using optimizerDuck.Resources.Languages;
+using optimizerDuck.Services.Configuration;
+using optimizerDuck.Services.History;
+using optimizerDuck.Services.Revert;
+using optimizerDuck.Services.System;
+using optimizerDuck.Services.System.Primitives;
+
+namespace optimizerDuck.Services.Optimization;
+
+/// <summary>
+/// Runs the lifecycle every system-changing run takes: it invokes the work, classifies the
+/// outcome from the recorded steps, writes the record, and persists revert data when asked.
+/// </summary>
+public class OperationRunner(
+ RevertManager revertManager,
+ SystemInfoService systemInfoService,
+ StreamService streamService,
+ ShellService shellService,
+ PowerPlanService powerPlanService,
+ ILogger<OperationRunner> logger
+)
+{
+ private readonly ILogger _logger = logger;
+
+ /// <summary>Executes one run and writes what it did to the record store.</summary>
+ /// <param name="request">The run to execute.</param>
+ /// <param name="progress">The progress reporter the run writes to.</param>
+ /// <param name="cancellationToken">The token that cancels the run.</param>
+ /// <returns>The classified outcome of the run.</returns>
+ public async Task<OptimizationResult> RunAsync(
+ OperationRequest request,
+ IProgress<ProcessingProgress> progress,
+ CancellationToken cancellationToken = default
+ )
+ {
+ ArgumentNullException.ThrowIfNull(request);
+ ArgumentNullException.ThrowIfNull(progress);
+
+ var changes = new ChangeSet();
+ var result = await RunCoreAsync(request, changes, progress, cancellationToken)
+ .ConfigureAwait(false);
+
+ // Best effort, after the result is decided: the record must never change what a run
+ // reports about the machine.
+ ChangeRecordStore.TryWrite(
+ ChangeRecord.From(changes, request.Subject, result.Status.ToString()),
+ _logger
+ );
+
+ return result;
+ }
+
+ private async Task<OptimizationResult> RunCoreAsync(
+ OperationRequest request,
+ ChangeSet changes,
+ IProgress<ProcessingProgress> progress,
+ CancellationToken cancellationToken
+ )
+ {
+ _logger.LogInformation(
+ "Starting run of {Name} ({Key}) with ID {Id}",
+ request.Subject.LogName,
+ request.Subject.Key,
+ request.Subject.Id
+ );
+
+ progress.Report(
+ new ProcessingProgress
+ {
+ Message = Loc.Instance["Optimization.Apply.Processing"],
+ IsIndeterminate = true,
+ }
+ );
+
+ string? providerError = null;
+ Exception? exception = null;
+ try
+ {
+ var applyResult = await request
+ .Work(progress, NewContext(changes, request.RunLogger, cancellationToken))
+ .ConfigureAwait(false);
+
+ providerError = string.IsNullOrWhiteSpace(applyResult.ErrorMessage)
+ ? null
+ : applyResult.ErrorMessage;
+ }
+ catch (Exception ex)
+ {
+ exception = ex;
+ RecordRunFailure(changes, request, ex);
+ }
+
+ if (exception == null && providerError == null)
+ {
+ progress.Report(
+ new ProcessingProgress
+ {
+ Message = Loc.Instance["Optimization.Apply.Completed"],
+ IsIndeterminate = false,
+ Value = 1,
+ Total = 1,
+ }
+ );
+ }
+
+ ReportUncompensatedChanges(changes, request);
+
+ // Persist before the result, so a persistence failure lands as a failed step.
+ await TrySaveRevertDataAsync(changes, request).ConfigureAwait(false);
+
+ var failedSteps = changes.FailedSteps.OrderBy(s => s.Index).ToList();
+
+ // Whether any step succeeded; the all-failed branch below asks this, not the outcome.
+ var changedSomething = changes.HasSuccessfulSteps || changes.DidApplyAnything;
+
+ if (exception != null)
+ {
+ return new OptimizationResult
+ {
+ Status = changes.ModifiedSystem
+ ? OptimizationSuccessResult.PartialSuccess
+ : OptimizationSuccessResult.Failed,
+ Message = Loc.Instance["Optimization.Apply.Error.Failed", request.DisplayName],
+ Exception = exception,
+ FailedSteps = failedSteps,
+ };
+ }
+
+ if (providerError != null)
+ {
+ _logger.LogWarning(
+ "Provider error in run {OptimizationKey}: {ProviderError}",
+ request.Subject.Key,
+ providerError
+ );
+
+ var message =
+ failedSteps.Count > 0
+ ? Loc.Instance[
+ "Optimization.Apply.Error.FailedWithSteps",
+ request.DisplayName,
+ failedSteps.Count
+ ]
+ : providerError;
+
+ return new OptimizationResult
+ {
+ Status = changes.ModifiedSystem
+ ? OptimizationSuccessResult.PartialSuccess
+ : OptimizationSuccessResult.Failed,
+ Message = message,
+ FailedSteps = failedSteps,
+ };
+ }
+
+ // Every step failed and none carries compensation, so nothing changed: a total failure. A
+ // failed step that recorded what it changed falls through to partial success below.
+ if (changes.Changes.Count > 0 && !changedSomething)
+ {
+ return new OptimizationResult
+ {
+ Status = OptimizationSuccessResult.Failed,
+ Message = Loc.Instance["Optimization.Apply.Error.Failed", request.DisplayName],
+ FailedSteps = failedSteps,
+ };
+ }
+
+ // Nothing to do: no step modified the system, because there was nothing to change or
+ // every step was a skip. An irreversible step counts as modifying it.
+ if (!changes.ModifiedSystem)
+ {
+ if (changes.Changes.Count == 0)
+ _logger.LogWarning(
+ "Run {OptimizationKey} recorded no step at all; the provider may have returned without recording",
+ request.Subject.Key
+ );
+
+ _logger.LogInformation(
+ "Run {OptimizationKey} changed nothing, reporting nothing to do",
+ request.Subject.Key
+ );
+ return new OptimizationResult
+ {
+ Status = OptimizationSuccessResult.NothingToDo,
+ Message = Loc.Instance["Optimization.Apply.NothingToDo", request.DisplayName],
+ FailedSteps = failedSteps,
+ };
+ }
+
+ var failedCount = failedSteps.Count;
+ return new OptimizationResult
+ {
+ Status =
+ failedCount == 0
+ ? OptimizationSuccessResult.Success
+ : OptimizationSuccessResult.PartialSuccess,
+ Message =
+ failedCount == 0
+ ? Loc.Instance["Optimization.Apply.Success", request.DisplayName]
+ : Loc.Instance[
+ "Optimization.Apply.Error.FailedWithSteps",
+ request.DisplayName,
+ failedCount
+ ],
+ FailedSteps = failedSteps,
+ };
+ }
+
+ private OptimizationContext NewContext(
+ ChangeSet changes,
+ ILogger runLogger,
+ CancellationToken cancellationToken
+ )
+ {
+ return new OptimizationContext
+ {
+ Changes = changes,
+ Logger = runLogger,
+ CancellationToken = cancellationToken,
+ Snapshot = systemInfoService.Snapshot,
+ StreamService = streamService,
+ Shell = shellService,
+ PowerPlans = powerPlanService,
+ };
+ }
+
+ /// <summary>
+ /// Reports every step that claims the system was modified while carrying no compensation,
+ /// which is a provider defect.
+ /// </summary>
+ private void ReportUncompensatedChanges(ChangeSet changes, OperationRequest request)
+ {
+ foreach (var defect in changes.UncompensatedChanges)
+ request.RunLogger.LogWarning(
+ "Recorded change {Step} for {Name} carries no revert data, so undo does not cover it",
+ defect.Name,
+ request.Subject.Key
+ );
+ }
+
+ private async Task TrySaveRevertDataAsync(ChangeSet changes, OperationRequest request)
+ {
+ if (request.Revert != RevertPersistence.Enabled || !changes.DidApplyAnything)
+ return;
+
+ try
+ {
+ await revertManager
+ .SaveRevertDataAsync(
+ changes,
+ request.Subject.Id,
+ request.Subject.Key,
+ // CancellationToken.None: persist partial work even when the run was cancelled.
+ CancellationToken.None
+ )
+ .ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Failed to save revert data for {Name}", request.Subject.Key);
+ RecordRunFailure(changes, request, ex);
+ }
+ }
+
+ /// <summary>
+ /// Records a failure of the run itself as a step, named for the user and described by the
+ /// run's English key, which is what the log reads.
+ /// </summary>
+ private static void RecordRunFailure(
+ ChangeSet changes,
+ OperationRequest request,
+ Exception exception
+ )
+ {
+ changes.Add(
+ request.DisplayName,
+ request.Subject.Key,
+ false,
+ null,
+ exception.Message,
+ exception.ToString()
+ );
+ }
+}
diff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.cs
index 3d2b5fa..dfff680 100644
--- a/optimizerDuck/Services/Optimization/OptimizationService.cs
+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs
@@ -1,4 +1,4 @@
-using System.IO;
+using System.IO;
using System.Management;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
@@ -24,44 +24,20 @@ using Wpf.Ui.Controls;
namespace optimizerDuck.Services.Optimization;
/// <summary>
-/// Runs the apply and revert paths of an optimization: it builds each item's execution
-/// context, drives the provider, persists revert data and writes the record of the run.
+/// Applies and reverts optimizations, and owns the revert, retry and applied-state paths.
/// </summary>
public class OptimizationService(
+ OperationRunner runner,
RevertManager revertManager,
ILoggerFactory loggerFactory,
- SystemInfoService systemInfoService,
- StreamService streamService,
IContentDialogService contentDialogService,
- ShellService shellService,
- PowerPlanService powerPlanService,
SystemRestoreService systemRestoreService,
ILogger<OptimizationService> logger
)
{
private readonly ILogger _logger = logger;
- private readonly ShellService _shellService = shellService;
- private readonly PowerPlanService _powerPlanService = powerPlanService;
private readonly SystemRestoreService _systemRestoreService = systemRestoreService;
- private OptimizationContext NewContext(
- ChangeSet changes,
- ILogger optLogger,
- CancellationToken cancellationToken
- )
- {
- return new OptimizationContext
- {
- Changes = changes,
- Logger = optLogger,
- CancellationToken = cancellationToken,
- Snapshot = systemInfoService.Snapshot,
- StreamService = streamService,
- Shell = _shellService,
- PowerPlans = _powerPlanService,
- };
- }
-
/// <summary>
/// Gets or sets a value that indicates whether a system restore point was created before
/// applying optimizations.
@@ -205,200 +181,29 @@ public class OptimizationService(
/// An <see cref="OptimizationResult"/> describing the outcome, including partial-success or
/// failure details.
/// </returns>
- public async Task<OptimizationResult> ApplyAsync(
+ public Task<OptimizationResult> ApplyAsync(
IOptimization optimization,
IProgress<ProcessingProgress> progress,
CancellationToken cancellationToken = default
)
{
- var optLogger = loggerFactory.CreateLogger(optimization.GetType());
- var changes = new ChangeSet();
-
- var result = await ApplyCoreAsync(
- optimization,
- changes,
- optLogger,
- progress,
- cancellationToken
- )
- .ConfigureAwait(false);
-
- // Best effort and deliberately after the result is decided: what a run did is worth
- // keeping, but it is never a reason for an apply to report anything other than the truth
- // about the machine, and it is not revert data.
- ChangeRecordStore.TryWrite(
- ChangeRecord.From(changes, optimization, result.Status.ToString()),
- _logger
- );
-
- return result;
- }
-
- private async Task<OptimizationResult> ApplyCoreAsync(
- IOptimization optimization,
- ChangeSet changes,
- ILogger optLogger,
- IProgress<ProcessingProgress> progress,
- CancellationToken cancellationToken
- )
- {
- _logger.LogInformation(
- "Starting apply of {Name} ({Key}) with ID {Id}",
- optimization.LogName(),
- optimization.OptimizationKey,
- optimization.Id
- );
+ ArgumentNullException.ThrowIfNull(optimization);
- progress.Report(
- new ProcessingProgress
- {
- Message = Loc.Instance["Optimization.Apply.Processing"],
- IsIndeterminate = true,
- }
- );
-
- string? providerError = null;
- Exception? exception = null;
- try
- {
- var applyResult = await optimization
- .ApplyAsync(progress, NewContext(changes, optLogger, cancellationToken))
- .ConfigureAwait(false);
-
- providerError = string.IsNullOrWhiteSpace(applyResult.ErrorMessage)
- ? null
- : applyResult.ErrorMessage;
- }
- catch (Exception ex)
- {
- exception = ex;
- changes.Add(
- optimization.OptimizationKey,
+ return runner.RunAsync(
+ new OperationRequest(
+ new OperationSubject(
+ optimization.Id,
+ optimization.OptimizationKey,
+ optimization.LogName()
+ ),
optimization.Name,
- false,
- null,
- ex.Message,
- ex.ToString()
- );
- }
-
- if (exception == null && providerError == null)
- {
- progress.Report(
- new ProcessingProgress
- {
- Message = Loc.Instance["Optimization.Apply.Completed"],
- IsIndeterminate = false,
- Value = 1,
- Total = 1,
- }
- );
- }
-
- // Persist BEFORE building the result so a persistence failure surfaces
- // as a failed step instead of a silent success-without-revert.
- await TrySaveRevertDataAsync(changes, optimization, cancellationToken)
- .ConfigureAwait(false);
-
- var failedSteps = changes.FailedSteps.OrderBy(s => s.Index).ToList();
-
- // A step that changed the system and then failed carries the compensation for what it
- // changed, so the machine did change: such a run is a partial success, never a failure
- // that reads as if nothing had been touched.
- var changedSomething = changes.HasSuccessfulSteps || changes.DidApplyAnything;
-
- if (exception != null)
- {
- return new OptimizationResult
- {
- Status = changedSomething
- ? OptimizationSuccessResult.PartialSuccess
- : OptimizationSuccessResult.Failed,
- Message = Loc.Instance["Optimization.Apply.Error.Failed", optimization.Name],
- Exception = exception,
- FailedSteps = failedSteps,
- };
- }
-
- if (providerError != null)
- {
- _logger.LogWarning(
- "Provider error applying {OptimizationKey}: {ProviderError}",
- optimization.OptimizationKey,
- providerError
- );
-
- return new OptimizationResult
- {
- Status = changedSomething
- ? OptimizationSuccessResult.PartialSuccess
- : OptimizationSuccessResult.Failed,
- Message =
- failedSteps.Count > 0
- ? Loc.Instance[
- "Optimization.Apply.Error.FailedWithSteps",
- optimization.Name,
- failedSteps.Count
- ]
- : Loc.Instance["Optimization.Apply.Error.Failed", optimization.Name],
- FailedSteps = failedSteps,
- };
- }
-
- // Every recorded step failed and none of them carries compensation: nothing changed and
- // nothing succeeded, so it stays a failure with the failure dialog as before. A failed step
- // that recorded what it changed falls through to the partial success path below, because
- // the machine did change and the revert file covers it.
- if (changes.Changes.Count > 0 && !changedSomething)
- {
- return new OptimizationResult
- {
- Status = OptimizationSuccessResult.Failed,
- Message = Loc.Instance["Optimization.Apply.Error.Failed", optimization.Name],
- FailedSteps = failedSteps,
- };
- }
-
- // Nothing to do: the provider reported success but no step changed the system, either
- // because there was nothing to change or because every recorded step was a skip. No
- // 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
- );
- return new OptimizationResult
- {
- Status = OptimizationSuccessResult.NothingToDo,
- Message = Loc.Instance["Optimization.Apply.NothingToDo", optimization.Name],
- FailedSteps = failedSteps,
- };
- }
-
- var failedCount = failedSteps.Count;
- return new OptimizationResult
- {
- Status =
- failedCount == 0
- ? OptimizationSuccessResult.Success
- : OptimizationSuccessResult.PartialSuccess,
- Message =
- failedCount == 0
- ? Loc.Instance["Optimization.Apply.Success", optimization.Name]
- : Loc.Instance[
- "Optimization.Apply.Error.FailedWithSteps",
- optimization.Name,
- failedCount
- ],
- FailedSteps = failedSteps,
- };
+ loggerFactory.CreateLogger(optimization.GetType()),
+ RevertPersistence.Enabled,
+ optimization.ApplyAsync
+ ),
+ progress,
+ cancellationToken
+ );
}
/// <summary>
@@ -768,43 +573,6 @@ public class OptimizationService(
}
}
- private async Task TrySaveRevertDataAsync(
- ChangeSet changes,
- IOptimization optimization,
- CancellationToken cancellationToken = default
- )
- {
- if (!changes.DidApplyAnything)
- return;
-
- try
- {
- await revertManager
- .SaveRevertDataAsync(
- changes,
- optimization.Id,
- optimization.OptimizationKey,
- // CancellationToken.None: persist partial work even when the operation was
- // cancelled.
- CancellationToken.None
- )
- .ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.LogError("Failed to save revert data for {Name}", optimization.OptimizationKey);
- // Visible, not silent: the apply succeeded but undo is unavailable.
- changes.Add(
- optimization.OptimizationKey,
- optimization.Name,
- false,
- null,
- ex.Message,
- ex.ToString()
- );
- }
- }
-
/// <summary>
/// Deletes all files in the downloads directory. Silently skips files that cannot be
/// deleted.
diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.cs
index 464bb47..253c306 100644
--- a/optimizerDuck/Services/Revert/RevertManager.cs
+++ b/optimizerDuck/Services/Revert/RevertManager.cs
@@ -1,4 +1,4 @@
-using System.Collections.Concurrent;
+using System.Collections.Concurrent;
using System.IO;
using System.Reflection;
using System.Text;
@@ -57,10 +57,9 @@ public class RevertManager(
}
/// <summary>
- /// Persists revert steps from a <see cref="ChangeSet"/>. Appends every successful change
- /// as a new entry with a fresh index. No payload-based dedupe: two executions of the same
- /// command are two real executions, so dropping either loses revert coverage. Indexes are
- /// never reused, and reverting an extra entry is harmless because revert runs LIFO.
+ /// Persists the revert steps of a <see cref="ChangeSet"/>. Every change that carries
+ /// compensation is appended as a new entry with a fresh index; entries are never deduped or
+ /// reused, and reverting an extra entry is harmless because revert runs last in, first out.
/// </summary>
public async Task SaveRevertDataAsync(
ChangeSet changes,
@@ -74,20 +73,6 @@ public class RevertManager(
// needs its previous state recorded.
var incoming = changes.Changes.Where(c => c.Revert != null).OrderBy(c => c.Index).ToList();
- // A step that modified the system must carry the data needed to undo it. The filter
- // above drops entries without compensation, so a Change arriving here without one is a
- // provider defect rather than a legitimate skip.
- foreach (
- var defect in changes.Changes.Where(c =>
- c.Ok && c.Kind == ChangeKind.Change && c.Revert == null
- )
- )
- _logger.LogWarning(
- "Recorded change {Step} for {Name} carries no revert data, so undo does not cover it",
- defect.Name,
- name
- );
-
if (incoming.Count == 0)
return;
@@ -598,6 +583,18 @@ public class RevertManager(
return null;
}
+ // A payload with no step array is unreadable rather than empty, so it is
+ // reported as corrupt and parked before any new write.
+ if (data.Steps is null)
+ {
+ LogCorruptRevertFile(
+ logger,
+ path,
+ new InvalidOperationException("Revert data carries no step array")
+ );
+ return null;
+ }
+
return data;
}
catch (IOException) when (i < 2)
diff --git a/optimizerDuck/Services/UI/StartupManagerService.cs b/optimizerDuck/Services/UI/StartupManagerService.cs
index 3011cea..786af49 100644
--- a/optimizerDuck/Services/UI/StartupManagerService.cs
+++ b/optimizerDuck/Services/UI/StartupManagerService.cs
@@ -21,13 +21,6 @@ namespace optimizerDuck.Services.UI;
public class StartupManagerService(ILogger<StartupManagerService> logger)
{
- // UI toggles are user-driven one-shot actions outside any optimization
- // apply: changes land in a throwaway set, revert is not persisted.
- private OpCall UiCall()
- {
- return new OpCall { Changes = new ChangeSet(), Logger = logger };
- }
-
/// <summary>
/// Retrieves all startup applications from registry Run/RunOnce keys (including the 32-bit
/// Wow6432Node view), startup folders, and packaged (UWP / MSIX) apps with StartupTask
@@ -689,19 +682,21 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)
/// <summary>
/// Enables or disables a startup scheduled task using the Task Scheduler API.
/// </summary>
+ /// <param name="call">The run the toggle records its steps into.</param>
/// <param name="task">The startup task to toggle.</param>
/// <param name="enable">
/// <see langword="true"/> to enable, <see langword="false"/> to disable.
/// </param>
/// <returns>The toggle outcome.</returns>
- public Task<OpResult> ToggleStartupTask(StartupTask task, bool enable)
+ public Task<OpResult> ToggleStartupTask(OpCall call, StartupTask task, bool enable)
{
+ ArgumentNullException.ThrowIfNull(call);
+
return Task.Run(() =>
{
try
{
var fullPath = task.TaskPath.TrimEnd('\\') + "\\" + task.TaskName;
- var call = UiCall();
var result = enable
? ScheduledTaskService.EnableTask(call, fullPath)
: ScheduledTaskService.DisableTask(call, fullPath);
@@ -720,14 +715,7 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)
)
);
- if (result.Ok)
- logger.LogInformation(
- "{Action} task {Name} ({Path})",
- enable ? "Enabled" : "Disabled",
- task.TaskName,
- fullPath
- );
- else
+ if (!result.Ok)
logger.LogError(
"Failed to toggle task {Name}: {Error}",
task.TaskName,
diff --git a/optimizerDuck/UI/Pages/DebugPages.cs b/optimizerDuck/UI/Pages/DebugPages.cs
new file mode 100644
index 0000000..e5e163b
--- /dev/null
+++ b/optimizerDuck/UI/Pages/DebugPages.cs
@@ -0,0 +1,18 @@
+#if DEBUG
+using optimizerDuck.UI.Pages.Optimizations;
+using optimizerDuck.UI.ViewModels.Optimizer;
+
+namespace optimizerDuck.UI.Pages;
+
+/// <summary>
+/// Provides the page that shows the debug category.
+/// </summary>
+public sealed class DebugOptimizerPage : OptimizationPage
+{
+ public DebugOptimizerPage(OptimizationCategoryViewModel viewModel)
+ : base(viewModel)
+ {
+ InitializeComponent();
+ }
+}
+#endif
diff --git a/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs
index a61e993..9781807 100644
--- a/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs
@@ -5,6 +5,8 @@ using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.Optimizations.Models.ScheduledTask;
using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.Configuration;
using optimizerDuck.Services.System;
@@ -21,7 +23,9 @@ public partial class ScheduledTasksViewModel : ViewModel
private readonly List<ScheduledTaskModel> _allTasks = [];
private readonly IContentDialogService _contentDialogService;
private readonly ILogger<ScheduledTasksViewModel> _logger;
+ private readonly ToolRunPresenter _presenter;
private readonly ISnackbarService _snackbarService;
+ private readonly HashSet<object> _suppressToggle = [];
[ObservableProperty]
private bool _hideMicrosoftTasks = true;
@@ -38,11 +42,13 @@ public partial class ScheduledTasksViewModel : ViewModel
private int _sortByIndex;
public ScheduledTasksViewModel(
+ ToolRunPresenter presenter,
IContentDialogService contentDialogService,
ISnackbarService snackbarService,
ILogger<ScheduledTasksViewModel> logger
)
{
+ _presenter = presenter;
_contentDialogService = contentDialogService;
_snackbarService = snackbarService;
_logger = logger;
@@ -94,64 +100,32 @@ public partial class ScheduledTasksViewModel : ViewModel
{
if (task == null)
return;
- try
- {
- await Task.Run(() =>
- {
- var call = UiCall();
- if (task.IsEnabled)
- {
- var result = ScheduledTaskService.EnableTask(call, task.FullPath);
- if (!result.Ok)
- throw new InvalidOperationException(result.Error ?? "Enable failed");
- _logger.LogInformation(
- "Enabled task {Name} ({Path})",
- task.Name,
- task.FullPath
- );
- }
- else
- {
- var result = ScheduledTaskService.DisableTask(call, task.FullPath);
- if (!result.Ok)
- throw new InvalidOperationException(result.Error ?? "Disable failed");
- _logger.LogInformation(
- "Disabled task {Name} ({Path})",
- task.Name,
- task.FullPath
- );
- }
- });
-
- _snackbarService.Show(
- task.IsEnabled
- ? Loc.Instance["ScheduledTasks.Snackbar.Enabled.Title"]
- : Loc.Instance["ScheduledTasks.Snackbar.Disabled.Title"],
- Loc.Instance["ScheduledTasks.Snackbar.Toggle.Message", task.Name],
- ControlAppearance.Success,
- new SymbolIcon { Symbol = SymbolRegular.CheckmarkCircle24, Filled = true },
- TimeSpan.FromSeconds(3)
- );
+ var enable = task.IsEnabled;
+ var request = NewToolRequest(context =>
+ enable
+ ? ScheduledTaskService.EnableTask(context, task.FullPath)
+ : ScheduledTaskService.DisableTask(context, task.FullPath)
+ );
+ var result = await _presenter.RunAsync(request);
+
+ if (!await _presenter.ReportAsync(request, result, FailureTitle))
+ {
await RefreshTaskState(task);
+ return;
}
- catch (Exception ex)
- {
- _logger.LogError(ex, "Failed to toggle task {Name} ({Path})", task.Name, task.FullPath);
- // Revert UI without triggering PropertyChanged to avoid infinite loop
- task.PropertyChanged -= Task_PropertyChanged;
- task.IsEnabled = !task.IsEnabled;
- task.PropertyChanged += Task_PropertyChanged;
-
- _snackbarService.Show(
- Loc.Instance["ScheduledTasks.Snackbar.Error.Title"],
- ex.Message,
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
- }
+ _snackbarService.Show(
+ enable
+ ? Loc.Instance["ScheduledTasks.Snackbar.Enabled.Title"]
+ : Loc.Instance["ScheduledTasks.Snackbar.Disabled.Title"],
+ Loc.Instance["ScheduledTasks.Snackbar.Toggle.Message", task.Name],
+ ControlAppearance.Success,
+ new SymbolIcon { Symbol = SymbolRegular.CheckmarkCircle24, Filled = true },
+ TimeSpan.FromSeconds(3)
+ );
+
+ await RefreshTaskState(task);
}
[RelayCommand]
@@ -159,62 +133,24 @@ public partial class ScheduledTasksViewModel : ViewModel
{
if (task == null)
return;
- try
- {
- var result = await Task.Run(() =>
- ScheduledTaskService.RunTask(UiCall(), task.FullPath)
- );
- if (result.Ok)
- {
- _logger.LogInformation("Ran task {Name} ({Path})", task.Name, task.FullPath);
+ var request = NewToolRequest(context =>
+ ScheduledTaskService.RunTask(context, task.FullPath)
+ );
+ var result = await _presenter.RunAsync(request);
- _snackbarService.Show(
- Loc.Instance["ScheduledTasks.Snackbar.Run.Title"],
- Loc.Instance["ScheduledTasks.Snackbar.Run.Message", task.Name],
- ControlAppearance.Success,
- new SymbolIcon { Symbol = SymbolRegular.Play24, Filled = true },
- TimeSpan.FromSeconds(3)
- );
+ if (!await _presenter.ReportAsync(request, result, FailureTitle))
+ return;
- await RefreshTaskState(task);
- }
- else
- {
- var error = result.Error ?? Loc.Instance["ScheduledTasks.Error.TaskNotFound"];
- _logger.LogError(
- "Failed to run task {Name} ({Path}): {Error}",
- task.Name,
- task.FullPath,
- error
- );
-
- _snackbarService.Show(
- Loc.Instance["ScheduledTasks.Snackbar.Error.Title"],
- error,
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
- }
- }
- catch (Exception ex)
- {
- _logger.LogError(
- ex,
- "Unexpected error running task {Name} ({Path})",
- task.Name,
- task.FullPath
- );
+ _snackbarService.Show(
+ Loc.Instance["ScheduledTasks.Snackbar.Run.Title"],
+ Loc.Instance["ScheduledTasks.Snackbar.Run.Message", task.Name],
+ ControlAppearance.Success,
+ new SymbolIcon { Symbol = SymbolRegular.Play24, Filled = true },
+ TimeSpan.FromSeconds(3)
+ );
- _snackbarService.Show(
- Loc.Instance["ScheduledTasks.Snackbar.Error.Title"],
- ex.Message,
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
- }
+ await RefreshTaskState(task);
}
[RelayCommand]
@@ -222,62 +158,24 @@ public partial class ScheduledTasksViewModel : ViewModel
{
if (task == null)
return;
- try
- {
- var result = await Task.Run(() =>
- ScheduledTaskService.StopTask(UiCall(), task.FullPath)
- );
- if (result.Ok)
- {
- _logger.LogInformation("Stopped task {Name} ({Path})", task.Name, task.FullPath);
+ var request = NewToolRequest(context =>
+ ScheduledTaskService.StopTask(context, task.FullPath)
+ );
+ var result = await _presenter.RunAsync(request);
- _snackbarService.Show(
- Loc.Instance["ScheduledTasks.Snackbar.Stop.Title"],
- Loc.Instance["ScheduledTasks.Snackbar.Stop.Message", task.Name],
- ControlAppearance.Success,
- new SymbolIcon { Symbol = SymbolRegular.Stop24, Filled = true },
- TimeSpan.FromSeconds(3)
- );
+ if (!await _presenter.ReportAsync(request, result, FailureTitle))
+ return;
- await RefreshTaskState(task);
- }
- else
- {
- var error = result.Error ?? Loc.Instance["ScheduledTasks.Error.TaskNotFound"];
- _logger.LogError(
- "Failed to stop task {Name} ({Path}): {Error}",
- task.Name,
- task.FullPath,
- error
- );
-
- _snackbarService.Show(
- Loc.Instance["ScheduledTasks.Snackbar.Error.Title"],
- error,
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
- }
- }
- catch (Exception ex)
- {
- _logger.LogError(
- ex,
- "Unexpected error stopping task {Name} ({Path})",
- task.Name,
- task.FullPath
- );
+ _snackbarService.Show(
+ Loc.Instance["ScheduledTasks.Snackbar.Stop.Title"],
+ Loc.Instance["ScheduledTasks.Snackbar.Stop.Message", task.Name],
+ ControlAppearance.Success,
+ new SymbolIcon { Symbol = SymbolRegular.Stop24, Filled = true },
+ TimeSpan.FromSeconds(3)
+ );
- _snackbarService.Show(
- Loc.Instance["ScheduledTasks.Snackbar.Error.Title"],
- ex.Message,
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
- }
+ await RefreshTaskState(task);
}
[RelayCommand]
@@ -298,63 +196,24 @@ public partial class ScheduledTasksViewModel : ViewModel
if (result != ContentDialogResult.Primary)
return;
- try
- {
- var deleteOutcome = await Task.Run(() =>
- ScheduledTaskService.DeleteTask(UiCall(), task.FullPath)
- );
+ var request = NewToolRequest(context =>
+ ScheduledTaskService.DeleteTask(context, task.FullPath)
+ );
+ var run = await _presenter.RunAsync(request);
- if (deleteOutcome.Ok)
- {
- _logger.LogInformation("Deleted task {Name} ({Path})", task.Name, task.FullPath);
- _allTasks.RemoveAll(t => t.FullPath == task.FullPath);
- ApplyFilter();
-
- _snackbarService.Show(
- Loc.Instance["ScheduledTasks.Snackbar.Delete.Title"],
- Loc.Instance["ScheduledTasks.Snackbar.Delete.Message", task.Name],
- ControlAppearance.Success,
- new SymbolIcon { Symbol = SymbolRegular.Delete24, Filled = true },
- TimeSpan.FromSeconds(3)
- );
- }
- else
- {
- var error =
- deleteOutcome.Error ?? Loc.Instance["ScheduledTasks.Error.TaskNotFound"];
- _logger.LogError(
- "Failed to delete task {Name} ({Path}): {Error}",
- task.Name,
- task.FullPath,
- error
- );
-
- _snackbarService.Show(
- Loc.Instance["ScheduledTasks.Snackbar.Error.Title"],
- error,
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
- }
- }
- catch (Exception ex)
- {
- _logger.LogError(
- ex,
- "Unexpected error deleting task {Name} ({Path})",
- task.Name,
- task.FullPath
- );
+ if (!await _presenter.ReportAsync(request, run, FailureTitle))
+ return;
- _snackbarService.Show(
- Loc.Instance["ScheduledTasks.Snackbar.Error.Title"],
- ex.Message,
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
- }
+ _allTasks.RemoveAll(t => t.FullPath == task.FullPath);
+ ApplyFilter();
+
+ _snackbarService.Show(
+ Loc.Instance["ScheduledTasks.Snackbar.Delete.Title"],
+ Loc.Instance["ScheduledTasks.Snackbar.Delete.Message", task.Name],
+ ControlAppearance.Success,
+ new SymbolIcon { Symbol = SymbolRegular.Delete24, Filled = true },
+ TimeSpan.FromSeconds(3)
+ );
}
[RelayCommand]
@@ -390,7 +249,7 @@ public partial class ScheduledTasksViewModel : ViewModel
}
/// <summary>
- /// Refreshes the state of a single task in-place by re-querying the task scheduler.
+ /// Re-reads the state and the enabled flag Windows reports for a task, without running it.
/// </summary>
private async Task RefreshTaskState(ScheduledTaskModel task)
{
@@ -402,6 +261,16 @@ public partial class ScheduledTasksViewModel : ViewModel
task.State = newState;
task.NotifyStateChanged();
}
+
+ var enabled = await Task.Run(() =>
+ ScheduledTaskService.GetTaskEnabledState(task.FullPath)
+ );
+ if (enabled is TaskEnabledState.Enabled or TaskEnabledState.Disabled)
+ {
+ task.PropertyChanged -= Task_PropertyChanged;
+ task.IsEnabled = enabled == TaskEnabledState.Enabled;
+ task.PropertyChanged += Task_PropertyChanged;
+ }
}
catch (Exception ex)
{
@@ -432,11 +301,24 @@ public partial class ScheduledTasksViewModel : ViewModel
}
}
- // UI toggles are one-shot actions outside any apply: throwaway set, no revert.
- private OpCall UiCall()
- {
- return new OpCall { Changes = new ChangeSet(), Logger = _logger };
- }
+ /// <summary>Builds the run for one tool action.</summary>
+ /// <param name="work">The provider call that records the run's steps.</param>
+ private OperationRequest NewToolRequest(Func<OptimizationContext, OpResult> work) =>
+ new(
+ ToolSubjects.ScheduledTasks,
+ Loc.Instance["ScheduledTasks.Header.Title"],
+ _logger,
+ RevertPersistence.Disabled,
+ (_, context) =>
+ Task.Run(() =>
+ {
+ work(context);
+ return context.Changes.ToApplyResult();
+ })
+ );
+
+ /// <summary>Gets the heading a failed action is reported under.</summary>
+ private static string FailureTitle => Loc.Instance["ScheduledTasks.Snackbar.Error.Title"];
private void ApplyFilter()
{
@@ -485,19 +367,27 @@ public partial class ScheduledTasksViewModel : ViewModel
private async void Task_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (
- e.PropertyName == nameof(ScheduledTaskModel.IsEnabled)
- && sender is ScheduledTaskModel task
+ e.PropertyName != nameof(ScheduledTaskModel.IsEnabled)
+ || sender is not ScheduledTaskModel task
)
+ return;
+
+ // Ignore a toggle that races the run already under way for this task.
+ if (!_suppressToggle.Add(task))
+ return;
+
+ try
{
- try
- {
- await ToggleTask(task);
- CrossPageEventBus.NotifyDataChanged<ScheduledTasksChanged>();
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Failed to toggle scheduled task {Name}", task.Name);
- }
+ await ToggleTask(task);
+ CrossPageEventBus.NotifyDataChanged<ScheduledTasksChanged>();
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Failed to toggle scheduled task {Name}", task.Name);
+ }
+ finally
+ {
+ _suppressToggle.Remove(task);
}
}
}
diff --git a/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs
index 5c6d5ac..2bb97b4 100644
--- a/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs
@@ -5,11 +5,14 @@ using System.IO;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Models;
using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.Configuration;
using optimizerDuck.Services.System;
using optimizerDuck.Services.UI;
using optimizerDuck.UI.Dialogs;
+using optimizerDuck.UI.ViewModels;
using Wpf.Ui;
using Wpf.Ui.Controls;
using StartupApp = optimizerDuck.Domain.Optimizations.Models.StartupManager.StartupApp;
@@ -23,6 +26,7 @@ public partial class StartupManagerViewModel : ViewModel
private readonly List<StartupTask> _allTasks = [];
private readonly IContentDialogService _contentDialogService;
private readonly ILogger<StartupManagerViewModel> _logger;
+ private readonly ToolRunPresenter _presenter;
private readonly StartupManagerService _startupManagerService;
// Per-section: Apps
@@ -49,11 +53,13 @@ public partial class StartupManagerViewModel : ViewModel
public StartupManagerViewModel(
StartupManagerService startupManagerService,
+ ToolRunPresenter presenter,
IContentDialogService contentDialogService,
ILogger<StartupManagerViewModel> logger
)
{
_startupManagerService = startupManagerService;
+ _presenter = presenter;
_contentDialogService = contentDialogService;
_logger = logger;
}
@@ -373,20 +379,22 @@ public partial class StartupManagerViewModel : ViewModel
try
{
- var result = await _startupManagerService.ToggleStartupTask(task, task.IsEnabled);
- if (result.Ok)
- {
- CrossPageEventBus.NotifyDataChanged<StartupAppsChanged>();
- }
- else
+ var enable = task.IsEnabled;
+ var request = NewTaskRequest(task, enable);
+ var result = await _presenter.RunAsync(request);
+
+ if (!await _presenter.ReportAsync(request, result, FailureTitle))
{
_logger.LogWarning(
- "Startup task toggle failed for {Name}: {Error}",
+ "Startup task toggle did not end as asked for {Name}: {Message}",
task.TaskName,
- result.Error
+ result.Message
);
task.IsEnabled = !task.IsEnabled;
+ return;
}
+
+ CrossPageEventBus.NotifyDataChanged<StartupAppsChanged>();
}
catch (Exception ex)
{
@@ -399,6 +407,32 @@ public partial class StartupManagerViewModel : ViewModel
}
}
+ /// <summary>Builds the run for one startup task toggle.</summary>
+ /// <param name="task">The startup task the user flipped.</param>
+ /// <param name="enable">
+ /// <see langword="true" /> to enable the task; otherwise, <see langword="false" />.
+ /// </param>
+ private OperationRequest NewTaskRequest(StartupTask task, bool enable) =>
+ new(
+ ToolSubjects.StartupManagerTasks,
+ Loc.Instance["StartupManager.Header.Title"],
+ _logger,
+ RevertPersistence.Disabled,
+ async (_, context) =>
+ {
+ var result = await _startupManagerService.ToggleStartupTask(context, task, enable);
+
+ return result.Ok
+ ? context.Changes.ToApplyResult()
+ : ApplyResult.False(
+ result.Error ?? Loc.Instance["Optimization.Apply.Error.AllStepsFailed"]
+ );
+ }
+ );
+
+ /// <summary>Gets the heading a failed action is reported under.</summary>
+ private static string FailureTitle => Loc.Instance["StartupManager.Header.Title"];
+
private async Task ReloadTasksAsync()
{
try
diff --git a/optimizerDuck/UI/ViewModels/ToolRunPresenter.cs b/optimizerDuck/UI/ViewModels/ToolRunPresenter.cs
new file mode 100644
index 0000000..2af20f3
--- /dev/null
+++ b/optimizerDuck/UI/ViewModels/ToolRunPresenter.cs
@@ -0,0 +1,205 @@
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.UI;
+using optimizerDuck.Services.Configuration;
+using optimizerDuck.Services.Optimization;
+using optimizerDuck.UI.Dialogs;
+using optimizerDuck.UI.ViewModels.Dialogs;
+using Wpf.Ui;
+using Wpf.Ui.Controls;
+
+namespace optimizerDuck.UI.ViewModels;
+
+/// <summary>
+/// Runs one tool action and reports the outcome to the user, offering a retry for failed steps.
+/// </summary>
+/// <remarks>Shared by the tool pages, so a tool action is run and reported one way.</remarks>
+public class ToolRunPresenter(
+ OperationRunner runner,
+ IContentDialogService contentDialogService,
+ ISnackbarService snackbarService,
+ ILogger<ToolRunPresenter> logger
+)
+{
+ /// <summary>
+ /// Runs the request while a progress dialog is shown. A dialog that cannot be built does
+ /// not stop the run.
+ /// </summary>
+ /// <param name="request">The run to execute.</param>
+ /// <returns>The classified outcome of the run.</returns>
+ public async Task<OptimizationResult> RunAsync(OperationRequest request)
+ {
+ ArgumentNullException.ThrowIfNull(request);
+
+ var progressViewModel = new ProcessingViewModel();
+ var dialog = TryCreateProgressDialog(request, progressViewModel);
+ if (dialog is not null)
+ _ = ShowProgressAsync(dialog);
+
+ try
+ {
+ return await runner.RunAsync(request, progressViewModel.ProgressReporter);
+ }
+ finally
+ {
+ if (dialog is not null)
+ {
+ try
+ {
+ dialog.Hide();
+ }
+ catch (Exception ex)
+ {
+ logger.LogDebug(ex, "Could not hide the progress dialog");
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Reports the outcome to the user: the failed steps get a retry dialog, and a failure with
+ /// no retryable step is shown in a snackbar.
+ /// </summary>
+ /// <param name="request">The run that produced the outcome.</param>
+ /// <param name="result">The outcome of the run.</param>
+ /// <param name="failureTitle">The heading a failure is shown under.</param>
+ /// <returns>
+ /// <see langword="true" /> if the action ended up as the user asked; otherwise,
+ /// <see langword="false" />.
+ /// </returns>
+ public async Task<bool> ReportAsync(
+ OperationRequest request,
+ OptimizationResult result,
+ string failureTitle
+ )
+ {
+ ArgumentNullException.ThrowIfNull(request);
+ ArgumentNullException.ThrowIfNull(result);
+
+ if (result.FailedSteps.Count > 0)
+ return await OfferRetryAsync(request, result.FailedSteps);
+
+ if (result.Status == OptimizationSuccessResult.Failed)
+ {
+ ShowFailure(failureTitle, result.Message);
+ return false;
+ }
+
+ return true;
+ }
+
+ /// <summary>Shows the failed steps and retries them while the user asks for it.</summary>
+ /// <param name="request">The run whose steps failed.</param>
+ /// <param name="failedSteps">The steps that failed.</param>
+ /// <returns>Whether everything the run attempted ended up done.</returns>
+ private async Task<bool> OfferRetryAsync(
+ OperationRequest request,
+ IReadOnlyList<Change> failedSteps
+ )
+ {
+ var remaining = failedSteps.OrderBy(step => step.Index).ToList();
+
+ while (remaining.Count > 0)
+ {
+ var canRetry = remaining.Any(step => step.Retry != null);
+ var dialog = new ContentDialog
+ {
+ Title = request.DisplayName,
+ Content = new OptimizationResultDialog
+ {
+ DataContext = new OptimizationResultDialogViewModel(
+ remaining,
+ ChangeRecordOperation.Apply
+ ),
+ },
+ CloseButtonText = Loc.Instance[canRetry ? "Button.Cancel" : "Button.Ok"],
+ };
+ if (canRetry)
+ dialog.PrimaryButtonText = Loc.Instance["Button.Retry"];
+
+ var answer = await contentDialogService.ShowAsync(dialog, CancellationToken.None);
+ if (!canRetry || answer != ContentDialogResult.Primary)
+ return false;
+
+ var retry = await RetryAsync(request, remaining);
+
+ remaining = retry.FailedSteps.OrderBy(step => step.Index).ToList();
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Retries the failed steps through the same lifecycle and reports what the retry recovered
+ /// and what still failed. Kept apart from the dialog, so a retry needs no shell.
+ /// </summary>
+ /// <param name="request">The run whose steps failed.</param>
+ /// <param name="failedSteps">The steps to retry.</param>
+ /// <returns>What the retry recovered and what still failed.</returns>
+ internal Task<RetryFailedStepsResult> RetryAsync(
+ OperationRequest request,
+ IReadOnlyList<Change> failedSteps
+ )
+ {
+ ArgumentNullException.ThrowIfNull(request);
+ ArgumentNullException.ThrowIfNull(failedSteps);
+
+ return OptimizationService.RetryFailedStepsWithResultsAsync(
+ failedSteps,
+ reverseOrder: false,
+ logger,
+ revertManager: null,
+ optimizationId: request.Subject.Id,
+ optimizationKey: request.Subject.Key
+ );
+ }
+
+ /// <summary>
+ /// Builds the progress dialog, or <see langword="null" /> when the shell cannot build it.
+ /// </summary>
+ private ContentDialog? TryCreateProgressDialog(
+ OperationRequest request,
+ ProcessingViewModel progressViewModel
+ )
+ {
+ try
+ {
+ return new ContentDialog
+ {
+ Title = request.DisplayName,
+ Content = new ProcessingDialog { DataContext = progressViewModel },
+ IsFooterVisible = false,
+ };
+ }
+ catch (Exception ex)
+ {
+ logger.LogDebug(ex, "Could not build the progress dialog");
+ return null;
+ }
+ }
+
+ /// <summary>Shows the progress dialog, keeping a failure of it out of the run.</summary>
+ private async Task ShowProgressAsync(ContentDialog dialog)
+ {
+ try
+ {
+ await contentDialogService.ShowAsync(dialog, CancellationToken.None);
+ }
+ catch (Exception ex)
+ {
+ logger.LogDebug(ex, "Could not show the progress dialog");
+ }
+ }
+
+ private void ShowFailure(string title, string message)
+ {
+ snackbarService.Show(
+ title,
+ message,
+ ControlAppearance.Danger,
+ new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
+ TimeSpan.FromSeconds(5)
+ );
+ }
+}