Skip to content

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

refactor: simplify execution architecture and fix logic issues

fatDuckd00d432fbe8d
diff --git a/.editorconfig b/.editorconfig
index ce65901..bacdaa9 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -1,27 +1,74 @@
-[*.cs]
+root = true
-
-# bro ts solve so many warnings!!
-# CA1416: Validate platform compatibility
-dotnet_diagnostic.CA1416.severity = silent
-
-
-# https://csharpier.com/docs/Configuration
+# ---------------------------------------------------------------------------
+# Compiler-level opt-ins. AnalysisLevel/AnalysisMode enable the platform and
+# CAxxxx analyzers that the build previously never ran; EnforceCodeStyleInBuild
+# makes IDExxxx style rules fail the build instead of only showing in the IDE.
+# ---------------------------------------------------------------------------
[*.{cs,csx}]
-# Non-configurable behaviors
charset = utf-8
insert_final_newline = true
trim_trailing_whitespace = true
-dotnet_sort_system_directives_first = true
-dotnet_separate_import_directive_groups = false
-
-# conifguiawudiable
end_of_line = lf
indent_style = space
indent_size = 4
max_line_length = 100
+dotnet_sort_system_directives_first = true
+dotnet_separate_import_directive_groups = false
+
+# --- Style rules worth enforcing repo-wide ---------------------------------
+# Prefer the modern lock object (C# 13) over a bare object monitor.
+dotnet_diagnostic.IDE0330.severity = warning
+# File-scoped namespaces and primary constructors keep new files consistent.
+dotnet_diagnostic.IDE0161.severity = suggestion
+dotnet_diagnostic.IDE0290.severity = suggestion
+# Readonly / static members that never touch instance state.
+dotnet_diagnostic.CA1822.severity = suggestion
+dotnet_diagnostic.IDE0062.severity = suggestion
+# Unused usings and unreachable/uncalled private members.
+dotnet_diagnostic.IDE0005.severity = suggestion
+dotnet_diagnostic.IDE0051.severity = suggestion
+# Simplify using statements / conditional expressions.
+dotnet_diagnostic.IDE0063.severity = suggestion
+
+# --- Correctness rules promoted to warnings ---------------------------------
+# Blanket catch: deliberately kept visible in the IDE but off the build report.
+# The codebase has ~30 intentional best-effort boundaries (cleanup, dispose,
+# error logging, STA marshalling) where a specific exception type would be wrong.
+dotnet_diagnostic.CA1031.severity = suggestion
+# Forward the CancellationToken to methods that accept one.
+dotnet_diagnostic.CA2016.severity = warning
+# CancellationToken parameters must come last.
+dotnet_diagnostic.CA1068.severity = warning
+# Use ThrowIfCancellationRequested rather than throwing manually.
+dotnet_diagnostic.CA2250.severity = warning
+# Do not raise exceptions in finally / filter clauses.
+dotnet_diagnostic.CA2219.severity = warning
+# Dispose IDisposable fields.
+dotnet_diagnostic.CA2213.severity = warning
+# Do not call overridable members (like Task.Run continuations) during construction.
+dotnet_diagnostic.CA2214.severity = suggestion
+# Avoid async void outside event handlers.
+dotnet_diagnostic.CA2012.severity = suggestion
+# Prefer the CancellationToken-accepting overloads of Task.Delay/WaitAsync.
+dotnet_diagnostic.CA2016.severity = warning
+# Do not expose mutable collections via properties promoted to warnings.
+dotnet_diagnostic.CA2227.severity = suggestion
+# Use ArgumentNullException.ThrowIfNull at trust boundaries.
+dotnet_diagnostic.CA1510.severity = suggestion
+# Log-message argument boxing/allocation for disabled log levels.
+dotnet_diagnostic.CA1873.severity = suggestion
+# Avoid the culture-sensitive overloads of string.Format / int.Parse.
+dotnet_diagnostic.CA1305.severity = suggestion
+# Prefer a TimeProvider over DateTime.Now / UtcNow.
+dotnet_diagnostic.CA1305.severity = suggestion
+
+# CA1416 (platform compatibility) is intentionally silent: the app targets a single
+# Windows TFM, so every P/Invoke and registry call is known-good.
+dotnet_diagnostic.CA1416.severity = silent
+
[*.{config,csproj,props,slnx,targets,xml}]
indent_style = space
indent_size = 4
-max_line_length = 100
\ No newline at end of file
+max_line_length = 100
diff --git a/.github/contributing/CONTRIBUTING.ja-JP.md b/.github/contributing/CONTRIBUTING.ja-JP.md
index 0509c9c..3007fa6 100644
--- a/.github/contributing/CONTRIBUTING.ja-JP.md
+++ b/.github/contributing/CONTRIBUTING.ja-JP.md
@@ -132,7 +132,7 @@ optimizerDuck.slnx # ソリューションファイル
│ │ │ └── WindowsBuilds.cs # OS ビルド番号の定数
│ │ ├── Configuration/ # AppSettings モデル
│ │ ├── Exceptions/ # StepExecutionException
-│ │ ├── Execution/ # ExecutionScope — AsyncLocal による環境的ステップ追跡
+│ │ ├── Execution/ # OpCall(明示的な操作ごとのコンテキスト:変更記録・ロガー・キャンセル)、ChangeSet(スレッドセーフな変更コレクター)、OpResult(単一操作の結果)
│ │ ├── Customize/ # カスタマイズ設定
│ │ │ ├── Categories/ # ネストされた設定クラスを持つカテゴリクラス
│ │ │ └── Models/ # BaseCustomizeSetting, RegistryToggle, RegistryBinding,
@@ -167,8 +167,8 @@ optimizerDuck.slnx # ソリューションファイル
│ │ ├── Configuration/ # ConfigManager, LanguageManager
│ │ ├── Customize/ # CustomizeRegistry(リフレクションベースの検出)
│ │ ├── Optimization/ # OptimizationRegistry, OptimizationService
-│ │ │ └── Providers/ # 静的: RegistryService, ShellService (+ ShellPolicy),
-│ │ │ # ScheduledTaskService, ServiceProcessService
+│ │ │ └── Providers/ # インスタンス型: RegistryService, ShellService (+ ShellPolicy),
+│ │ │ # ScheduledTaskService, ServiceProcessService, ProcessRunner(共有プロセス実行)。明示的な OpCall を受け取り、call.Changes に記録し、call.Logger でログし、OpResult を返す
│ │ ├── Revert/ # RevertManager(リバート JSON のアトミック読み書き)
│ │ ├── System/ # RegistryWatcher (+ IRegistryWatcher), SystemInfoService,
│ │ │ # StreamService, UpdaterService, CrossPageEventBus
@@ -207,7 +207,7 @@ optimizerDuck.slnx # ソリューションファイル
| 判断 | 理由 |
|---|---|
| **リフレクションによる自動検出** | DI 登録配列を更新する必要がありません。`ReflectionHelper.FindImplementationsInLoadedAssemblies<T>()` が `optimizerDuck.*` アセンブリをスキャンします。新しい最適化や設定は自動的に検出されます。 |
-| **静的プロバイダーサービス** | `RegistryService`、`ShellService`、`ScheduledTaskService`、`ServiceProcessService` は静的クラスです。環境的な `ExecutionScope` にリバートステップを記録するため、コンテキストの注入や受け渡しは不要です。 |
+| **プロバイダーサービス** | ステートレスなサービス(`RegistryService`、`ScheduledTaskService`、`ServiceProcessService`)は **static** です — 明示的な `OpCall`(`context`)で直接呼びます。`ShellService`(+ `ProcessRunner`)は DI シングルトンです(ライブ設定状態を持つ)。ドメインコードは `context.Shell`(`ShellService`)を使います。 |
| **ファイルベースのリバート追跡** | 適用状態 = ディスク上にファイルが存在する(`%localappdata%\optimizerDuck\Revert\{id}.json`)。データベースは使用しません。`File.Replace()` によるアトミック書き込み。 |
| **条件システム(フェイルオープン)** | 最適化や設定は互換性条件を宣言できます。評価の失敗がアイテムを隠すことはありません — [条件システム](#the-condition-system) を参照。 |
| **統合スタイルのテスト** | 実際のファイルシステム、実際のレジストリ(`HKCU\Software\TestOptimizerDuck*` 配下)、実際のプロセス実行。モックライブラリは使用せず、手書きのテストダブルのみ。 |
@@ -296,16 +296,17 @@ public class Performance : IOptimizationCategory
IProgress<ProcessingProgress> progress,
OptimizationContext context)
{
- // 1. 静的プロバイダーでシステムを変更
+ // 1. インスタンス型プロバイダーでシステムを変更 — 明示的な OpCall(ここでは context)を渡す
RegistryService.Write(new RegistryItem(
- @"HKLM\SOFTWARE\Something", "ValueName", 1));
+ @"HKLM\SOFTWARE\Something", "ValueName", 1), context);
// 2. 非同期操作を await — UI スレッドを解放
await ServiceProcessService.ChangeServiceStartupTypeAsync(
- new ServiceItem("SomeService", ServiceStartupType.Disabled));
+ new ServiceItem("SomeService", ServiceStartupType.Disabled),
+ context);
- // 3. 環境的な ExecutionScope から結果を返す
- return CompleteFromScope();
+ // 3. 集められた変更から結果を返す
+ return context.Changes.ToApplyResult();
}
}
}
@@ -318,11 +319,10 @@ public class Performance : IOptimizationCategory
| **`Id` は新しい GUID であること** | リバートファイルの命名と適用状態の追跡に使用。PowerShell で `[guid]::NewGuid()` で生成。 |
| **`BaseOptimization` を継承する** | 属性とローカライズキーから `Name`、`ShortDescription`、`RiskVisual`、`TagDisplays` を提供。 |
| **`OwnerType` は自動で割り当てられる** | 検出処理が設定します — 自分で設定しないこと。 |
-| **`async Task<ApplyResult>` を使用する** | サービスプロバイダーは非同期 — `await` して UI の応答性を保つ。 |
-| **`CompleteFromScope()` を返す** | 環境的な `ExecutionScope` に記録されたステップから `ApplyResult` を導出。手動で `ApplyResult` を構築しないこと。 |
+| **`context.Changes.ToApplyResult()` を返す** | `call.Changes`(`ChangeSet`)に集められた変更から `ApplyResult` を導出。早期終了の失敗時を除き、手動で `ApplyResult` を構築しないこと。 |
| **進捗を報告する** | `progress.Report(new ProcessingProgress { ... })` で UI ダイアログを更新。 |
-| **すべての例外をキャッチしない** | 例外は上位に伝播。`ExecutionScope` が成功/失敗を追跡し、`OptimizationService` が処理。 |
-| **リバートステップを手動で作成しない** | 静的プロバイダーサービスが `ExecutionScope.RecordStep()` 経由で自動的に行う。 |
+| **すべての例外をキャッチしない** | 例外は上位に伝播。プロバイダーが `OpResult` に成功/失敗を記録し、`OptimizationService` が `ChangeSet` から処理。 |
+| **リバートステップを手動で作成しない** | インスタンス型プロバイダーが `call.Changes` への記録経由で自動的に行う。 |
| **`context.Logger` を使用する** | 重要な診断情報の記録に使用。 |
| **`context.Snapshot` を使用する** | `OptimizationContext.Snapshot`(`SystemSnapshot`)が RAM、GPU、CPU、OS 情報を提供。条件分岐に使用。 |
| **`context.StreamService` を使用する** | リモートリソース(電源プランなど)をダウンロードする最適化向け。 |
@@ -330,43 +330,42 @@ public class Performance : IOptimizationCategory
<h3 id="available-service-providers">利用可能なサービスプロバイダー</h3>
-これらの**静的**クラスは、ログ記録、エラー処理、リバートステップの自動記録を担当します。
+ステートレスなサービスは **static** で直接呼びます(`new` 不要・割り当てなし)。`Shell` は `BaseOptimization`/`BaseCustomizeSetting` のプロパティを使います。これらのクラスはログ記録、エラー処理、`call.Changes` への変更記録を担当し、各操作は `OpResult` を返します。`ShellService` と `ProcessRunner` は DI シングルトンです(タイムアウトは設定からライブ読み取り)。
| サービス | 主要メソッド | 使用理由 |
|---|---|---|
-| **`RegistryService`** | `Write()`、`Read<T>()`、`DeleteValue()`、`CreateSubKey()`、`DeleteSubKeyTree()`、`KeyExists()`、`CleanupEmptyKeys()` | レジストリキーの読み書き/削除。リバート用に元の値をバックアップ。params 配列でバッチ書き込み可能。 |
-| **`ShellService`** | `CMDAsync()`、`PowerShellAsync()`、`CMD()`(同期)、`PowerShell()`(同期) | CMD / PowerShell コマンドの実行。非同期版を推奨。元に戻すコマンドを `revertCommand` で指定可能。非標準終了コードは `ShellPolicy` を参照。 |
-| **`ScheduledTaskService`** | `DisableTask()`、`EnableTask()`、`IsTaskEnabled()`、`DeleteTask()`、`GetAllTasks()`、`RegisterTask()`、`RunTask()`、`StopTask()` | Windows スケジュールタスクの管理。 |
-| **`ServiceProcessService`** | `ChangeServiceStartupTypeAsync()`、`GetStartupTypeAsync()` | Windows サービスの管理。常に非同期版を使用。params 配列でバッチ変更可能。 |
+| **`RegistryService`**(static) | `Write()`、`Read<T>()`、`DeleteValue()`、`CreateSubKey()`、`DeleteSubKeyTree()`、`KeyExists()`、`CleanupEmptyKeys()` | レジストリキーの読み書き/削除。リバート用に元の値をバックアップ。params 配列でバッチ書き込み可能。単体は `Write(item, context)`、バッチは `Write(context, items)`。 |
+| **`context.Shell`**(`ShellService`) | `CMDAsync()`、`PowerShellAsync()`、`CMD()`(同期)、`PowerShell()`(同期)、`QueryCMDAsync()`/`QueryPowerShellAsync()`(記録なしの素の実行) | CMD / PowerShell コマンドの実行。非同期版を推奨。元に戻すコマンドを `revertCommand` で指定可能。非標準終了コードは `ShellPolicy` を参照。 |
+| **`ScheduledTaskService`**(static) | `DisableTask(path, context)`、`EnableTask(path, context)`、`IsTaskEnabled()`、`DeleteTask()`、`GetAllTasks()`、`RegisterTask()`、`RunTask()`、`StopTask()` | Windows スケジュールタスクの管理。 |
+| **`ServiceProcessService`**(static) | `ChangeServiceStartupTypeAsync(item, context)`(単体/配列)、`GetStartupTypeAsync()` | Windows サービスの管理。常に非同期版を使用。配列でバッチ変更可能。 |
-> **params 配列で複数アイテムを受け付けるメソッド**:ほとんどの書き込み/変更メソッドは params 配列を受け付けます(例:`RegistryService.Write(item1, item2, item3)`)。個別呼び出しより効率的です。
+> **params 配列で複数アイテムを受け付けるメソッド**:ほとんどの書き込み/変更メソッドは params 配列を受け付けます(例:`RegistryService.Write(context, item1, item2, item3)`)。個別呼び出しより効率的です。
使用例:
```csharp
// 同期レジストリ書き込み — 複数アイテムを一度に
-RegistryService.Write(
+RegistryService.Write(context,
new RegistryItem(@"HKLM\...", "Value1", 1),
new RegistryItem(@"HKLM\...", "Value2", 0)
);
-RegistryService.DeleteValue(new RegistryItem(@"HKCU\...", "OldValue"));
+RegistryService.DeleteValue(new RegistryItem(@"HKCU\...", "OldValue"), context);
// 非同期サービス変更 — 複数サービスを一度に
await ServiceProcessService.ChangeServiceStartupTypeAsync(
- new ServiceItem("DiagTrack", ServiceStartupType.Disabled),
- new ServiceItem("dmwappushservice", ServiceStartupType.Disabled)
-);
+ [
+ new ServiceItem("DiagTrack", ServiceStartupType.Disabled),
+ new ServiceItem("dmwappushservice", ServiceStartupType.Disabled),
+ ],
+ context);
// リバートコマンド付きの非同期シェルコマンド
-var result = await ShellService.CMDAsync(
+var result = await context.Shell.CMDAsync(
"powercfg /h off",
+ context,
"powercfg /h on" // 元に戻すコマンドを保存
);
-// 非同期 PowerShell
-var usbStates = await ShellService.PowerShellAsync(
- "Get-CimInstance -Namespace root\\wmi -ClassName MSPower_DeviceEnable"
-);
```
<h3 id="handling-async">非同期操作の扱い</h3>
@@ -378,9 +377,9 @@ public override Task<ApplyResult> ApplyAsync(
IProgress<ProcessingProgress> progress,
OptimizationContext context)
{
- RegistryService.Write(new RegistryItem(@"HKLM\...", "Value", 1));
+ RegistryService.Write(new RegistryItem(@"HKLM\...", "Value", 1), context);
context.Logger.LogInformation("Applied tweak");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
```
@@ -389,11 +388,12 @@ public override Task<ApplyResult> ApplyAsync(
```csharp
public override async Task<ApplyResult> ApplyAsync(...)
{
- await ServiceProcessService.ChangeServiceStartupTypeAsync(...);
- return CompleteFromScope();
+ await ServiceProcessService.ChangeServiceStartupTypeAsync(new ServiceItem("SomeService", ServiceStartupType.Disabled), context);
+ return context.Changes.ToApplyResult();
}
```
+
<h3 id="new-category">新しいカテゴリの作成</h3>
既存カテゴリに当てはまらない場合のみ。過度に細かいカテゴリは避けてください。
@@ -419,9 +419,9 @@ public abstract class GpuRegistryOptimization : BaseOptimization
foreach (var gpu in context.Snapshot.Gpus.Where(g => g.Vendor == Vendor))
{
var path = $@"HKLM\...\{index:D4}";
- RegistryService.Write(CreateItems(path).ToArray());
+ RegistryService.Write(context, CreateItems(path).ToArray());
}
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
```
@@ -621,12 +621,12 @@ public class MouseAcceleration : BaseCustomizeSetting
});
}
- public override async Task ApplyAsync(object? value)
+ public override async Task ApplyAsync(object? value, OpCall call)
{
var isOn = value is bool b && b;
- RegistryService.Write(new RegistryItem(Path, "MouseSpeed", isOn ? "1" : "0"));
- RegistryService.Write(new RegistryItem(Path, "MouseThreshold1", isOn ? "6" : "0"));
- RegistryService.Write(new RegistryItem(Path, "MouseThreshold2", isOn ? "10" : "0"));
+ RegistryService.Write(new RegistryItem(Path, "MouseSpeed", isOn ? "1" : "0"), call);
+ RegistryService.Write(new RegistryItem(Path, "MouseThreshold1", isOn ? "6" : "0"), call);
+ RegistryService.Write(new RegistryItem(Path, "MouseThreshold2", isOn ? "10" : "0"), call);
if (NeedsPostAction)
await ExecutePostActionAsync();
@@ -653,18 +653,18 @@ public class MouseAcceleration : BaseCustomizeSetting
埋め込みリソースの抽出を伴う設定(ショートカット矢印を空白アイコンに置き換えるなど)の場合:
```csharp
-public override async Task ApplyAsync(object? value)
+public override async Task ApplyAsync(object? value, OpCall call)
{
var isOn = value is bool b && b;
if (isOn)
{
- RegistryService.DeleteValue(new RegistryItem(Path, "29"));
+ RegistryService.DeleteValue(new RegistryItem(Path, "29"), call);
}
else
{
var outputPath = Path.Combine(Shared.AssetsDirectory, nameof(Desktop), "blank.ico");
EmbeddedResourceHelper.TryExtract("Icons.blank.ico", outputPath);
- RegistryService.Write(new RegistryItem(Path, "29", outputPath));
+ RegistryService.Write(new RegistryItem(Path, "29", outputPath), call);
}
await ExecutePostActionAsync();
}
@@ -932,7 +932,7 @@ services.AddSingleton<UpdaterService>();
services.AddSingleton<IRegistryWatcher, RegistryWatcher>();
```
-> これは把握のためのスナップショットです — 現在の登録は `App.xaml.cs` が正です。また、起動時の呼び出し `ShellService.Init(appOptionsMonitor)` と `WmiHelper.Initialize()`、およびトランジェントなダイアログの解決に使われる公開プロパティ `App.AppHost` にも注意してください。
+> これは把握のためのスナップショットです — 現在の登録は `App.xaml.cs` が正です。また、起動時の呼び出し `RevertManager.RemoveOrphanedTempFiles(_logger)`(stale `.tmp` の掃除)と `WmiHelper.Initialize()`、およびトランジェントなダイアログの解決に使われる公開プロパティ `App.AppHost` にも注意してください。
<h3 id="system-services">システムサービスリファレンス</h3>
@@ -951,31 +951,29 @@ services.AddSingleton<IRegistryWatcher, RegistryWatcher>();
<h1 id="revert-system">リバートシステム</h1>
-適用された各最適化は `%localappdata%\optimizerDuck\Revert\{optimizationId}.json` に JSON ファイルを作成します。
-
-<h3 id="how-it-works-jp">仕組み</h3>
-
```
ApplyAsync()
│
- ├─ ExecutionScope.Begin(optimization, logger) ← 環境的な AsyncLocal スコープを作成
+ ├─ OptimizationService が ChangeSet を用意し、OptimizationContext(OpCall の一種)で渡す
│
- ├─ RegistryService.Write(...) ← RegistryRevertStep を自動記録
- ├─ ServiceProcessService.ChangeServiceStartupTypeAsync(...) ← ServiceRevertStep を自動記録
- ├─ ShellService.CMDAsync(...) ← ShellRevertStep を自動記録
+ ├─ RegistryService.Write(context, ...) ← RegistryRevertStep を call.Changes に記録
+ ├─ await ServiceProcessService.ChangeServiceStartupTypeAsync(item, context) ← ServiceRevertStep を記録
+ ├─ await context.Shell.CMDAsync(cmd, context, revertCommand) ← ShellRevertStep を記録
│
- ├─ CompleteFromScope() → ApplyResult ← 記録されたステップから導出
+ ├─ context.Changes.ToApplyResult() → ApplyResult ← 集められた変更から導出
│
- └─ ExecutionScope 破棄 → RevertManager.SaveRevertDataAsync()
+ └─ OptimizationService が RevertManager.SaveRevertDataAsync() で永続化
```
-<h3 id="scope-variants-jp">スコープのバリエーション</h3>
+<h3 id="explicit-context-jp">明示的コンテキスト(OpCall / ChangeSet / OpResult)</h3>
-| メソッド | 目的 |
+| 要素 | 役割 |
|---|---|
-| `ExecutionScope.Begin(optimization, logger)` | 実際の適用のための永続化可能なスコープを作成。 |
-| `ExecutionScope.BeginForLogging(logger)` | ログのみ — ステップは記録するがリバートデータは永続化しない。 |
-| `ExecutionScope.BeginForCapture(logger)` | リトライ用: `OptimizationId = Guid.Empty` でステップを捕捉し、後で実スコープに再割り当て。 |
+| `OpCall` | 操作ごとの明示的コンテキスト:`Changes`(変更コレクター)、`Logger`、キャンセル。すべてのプロバイダーメソッドがパラメーターで受け取る。`OptimizationContext` は `OpCall` を継承し、`Snapshot` と `StreamService` を追加したもの。 |
+| `ChangeSet` | スレッドセーフな変更コレクター。`Add()` で自動連番(`Seq`)を付与。`SuccessfulSteps`/`FailedSteps`/`HasSuccessfulSteps` を提供。 |
+| `Change` | 1 件の記録:安定キー(`Key`)、実行順(`Seq`、1 始まり、リバートファイルのインデックスとして保持)、成否(`Ok`)、リバート手順、エラー、リトライ(`Func<OpCall, Task<OpResult>>`)。 |
+| `OpResult` | 単一プロバイダー操作の結果:成功時は任意でリバート手順、失敗時はエラーと詳細。環境的なエラー状態の代わりにここに流す。 |
+| `context.Changes.ToApplyResult()` | 記録から適用結果を導出。成功が 1 件でもあれば成功、すべて失敗なら先頭エラーを運ぶ。何も記録がなければ失敗。 |
<h3 id="step-types-jp">ステップタイプ</h3>
@@ -984,8 +982,8 @@ ApplyAsync()
| **`RegistryRevertStep`** | 変更前の元のレジストリ値 | `RegistryService.Write()`、`DeleteValue()`、`CreateSubKey()`、`DeleteSubKeyTree()` |
| **`ServiceRevertStep`** | 元のサービス起動タイプ | `ServiceProcessService.ChangeServiceStartupTypeAsync()` |
| **`ScheduledTaskRevertStep`** | 元のタスク状態(有効/無効) | `ScheduledTaskService.DisableTask()`、`EnableTask()` |
-| **`ShellRevertStep`** | 元に戻すシェルコマンド | `ShellService.CMDAsync()`、`PowerShellAsync()` — `revertCommand` パラメータを渡す |
-| **`UsbPowerRevertStep`** | USB 電源設定(デバイス別) | USB 関連の最適化(手動で `ExecutionScope.RecordStep()`) |
+| **`ShellRevertStep`** | 元に戻すシェルコマンド | `context.Shell.CMDAsync()`、`context.Shell.PowerShellAsync()` — `revertCommand` パラメータを渡す |
+| **`UsbPowerRevertStep`** | USB 電源設定(デバイス別) | USB 関連の最適化(`call.Changes.Add(...)` で手動記録) |
<h3 id="revert-command">シェル呼び出しへのリバートコマンド追加</h3>
@@ -993,7 +991,7 @@ ApplyAsync()
```csharp
// "powercfg /h on" がこの変更を元に戻すために保存される
-await ShellService.CMDAsync("powercfg /h off", "powercfg /h on");
+await context.Shell.CMDAsync("powercfg /h off", context, "powercfg /h on");
```
<h3 id="revert-data-format-jp">リバートデータ形式</h3>
@@ -1005,26 +1003,25 @@ await ShellService.CMDAsync("powercfg /h off", "powercfg /h on");
"OptimizationName": "DisableTelemetry",
"AppliedAt": "2026-06-02T12:00:00Z",
"Steps": [
- { "Index": 0, "Type": "Registry", "Data": { "..." } },
- null, // null ギャップ = このインデックスの失敗ステップ
+ { "Index": 1, "Type": "Registry", "Data": { "..." } },
{ "Index": 2, "Type": "Service", "Data": { "..." } }
]
}
```
+成功したステップのみ永続化され、各エントリに新しい連番が振られます。失敗ステップ用の null ギャップはありません。再適用は新しいエントリを追記します。
+
<h3 id="key-details-jp">重要な詳細</h3>
- **適用状態**はディスク上のファイルの存在から推論されます(`RevertManager.IsAppliedAsync(id)`)。
-- **アトミック書き込み**:`.tmp` に書き込んでから `File.Replace()` — クラッシュ安全。
-- **同時アクセス**:ファイルごとの `SemaphoreSlim` ロックで競合を防止、30 秒タイムアウト。
-- **`ExecutionScope`** は `AsyncLocal<ExecutionScope?>` で環境的ステップ追跡。パラメータでコンテキストを渡す必要なし。
-- **リバートは逆順で実行**(最後に適用 = 最初にリバート)。
-- **部分成功**:一部のステップが失敗しても続行。失敗ステップにはリトライアクションが記録。
-- **リトライ**:`OptimizationService.RetryFailedStepsAsync()` が個別の失敗ステップをリトライ。`RecordStepAtIndex()` が元のインデックス配置を保持。
-- **Upsert**:`RevertManager.UpsertRevertStepAtIndexAsync()` が特定インデックスのリバートステップを追加/置換(リトライ時に使用)。
-- **ステップレジストリ**:リバートステップのデシリアライズはリフレクションベースの `_stepRegistry` — 新しいステップ型は `IRevertStep` を実装し静的な `FromData(JObject)` メソッドを持つだけで自動登録。
-
-> **重要**: プロバイダーサービス(`RegistryService.Write`、`ShellService.CMDAsync` など)を呼ぶと、リバートステップは自動記録されます。カスタムプロバイダー(`UsbPowerRevertStep` など)を実装する場合を除き、手動でリバートステップを作成**しないでください**。
+- **アトミック書き込み**:`FileStream(WriteThrough)`+`Flush(flushToDisk: true)` で `.tmp` に書き込んでから `File.Replace()` — クラッシュ安全。起動時に孤立した `.tmp` を掃除(`RemoveOrphanedTempFiles`)。
+- **同時アクセス**:ファイルごとの `SemaphoreSlim` ロックで競合を防止、30 秒タイムアウト。使用中のロックエントリは破棄しません。
+- **明示的コンテキスト**:プロバイダーは `OpCall` をパラメーターで受け取り、`call.Changes` に記録、`call.Logger` でログします。環境的な共有状態はありません。
+- **リバートは逆順で実行**(最後に適用 = 最初にリバート、LIFO)。
+- **部分成功**:一部のステップが失敗しても続行。失敗ステップには `Func<OpCall, Task<OpResult>>` 型のリトライアクションが記録されます。
+- **リトライ**:`OptimizationService.RetryFailedStepsWithResultsAsync()` が新しい `OpCall` で個別の失敗ステップを再実行し、回復したステップは `AppendRevertStepAsync()` で追記します(上書きしません — LIFO リバートが最新のバックアップを先に戻し、元のバックアップが真の初期状態を復元します)。
+- **ステップレジストリ**:リバートステップのデシリアライズはリフレクションベースの `_stepRegistry` — 新しいステップ型は `IRevertStep` を実装し静的な `FromData(JObject)` メソッドを持つだけで自動登録。未知の型は明確なメッセージの失敗ステップになり、黙ってスキップされません(生ペイロードは保持)。
+- **主要メソッド**:`SaveRevertDataAsync()`、`RevertAsync()`、`AppendRevertStepAsync()`、`RemoveRevertStepsAtIndexesAsync()`、`IsAppliedAsync(id)`、`GetRevertDataAsync(id)`、`ClearAllRevertData()`、`RemoveOrphanedTempFiles()`。
---
@@ -1096,10 +1093,10 @@ public class MyOptimizationTests
{
var optimization = new TestOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep("Test", "Step 1", true);
- return Task.FromResult(ApplyResult.True());
+ args.context.Changes.Add("Test", "Step 1", true);
+ return Task.FromResult(args.context.Changes.ToApplyResult());
},
};
@@ -1112,7 +1109,11 @@ public class MyOptimizationTests
private static OptimizationService CreateService()
{
return new OptimizationService(
- new RevertManager(NullLogger<RevertManager>.Instance, NullLoggerFactory.Instance),
+ new RevertManager(
+ NullLogger<RevertManager>.Instance,
+ new ShellService(new ProcessRunner(120000)),
+ TimeProvider.System
+ ),
NullLoggerFactory.Instance,
new SystemInfoService(NullLogger<SystemInfoService>.Instance),
new StreamService(NullLogger<StreamService>.Instance),
@@ -1173,15 +1174,15 @@ public class MyOptimizationTests
- サービス、ViewModel、ページは `App.xaml.cs` にシングルトンとして登録します。
- コンストラクタ注入を使用:`public class Foo(Bar bar, Baz baz)` または `public class Foo(ILogger<Foo> logger)`。
-- 静的プロバイダーサービス(`RegistryService`、`ShellService`、`ScheduledTaskService`、`ServiceProcessService`)は注入**されません** — 直接アクセスします。
+- プロバイダーサービスはインスタンス型です:`BaseOptimization`/`BaseCustomizeSetting` のプロパティ(`Reg`/`Svc`/`Tasks`/`Shell`)かローカルな `new` で使います。`ShellService` と `ProcessRunner` のみ DI シングルトンとして登録されます(タイムアウトは設定からライブ読み取り)。
- テストダブルは手書き(モックライブラリなし)。
<h3 id="error-handling-jp">エラー処理</h3>
| レイヤー | プラクティス |
|---|---|
-| **最適化** | スローせず `ApplyResult.False("reason")` を返す。ステップ単位の失敗追跡は `ExecutionScope` に任せる。 |
-| **プロバイダーサービス** | システム呼び出しを try/catch で囲みエラーをログ。失敗ステップにリトライアクションを記録。 |
+| **最適化** | スローせず `ApplyResult.False("reason")` を返す(早期終了の失敗時のみ)。ステップ単位の失敗追跡は `call.Changes` への記録に任せる。 |
+| **プロバイダーサービス** | システム呼び出しを try/catch で囲みエラーをログ。失敗時は `OpResult.Fail(...)` を返し、`call.Changes` に `Func<OpCall, Task<OpResult>>` 型のリトライアクションを記録。 |
| **ViewModel** | コマンドハンドラーで例外をキャッチし、ユーザーフレンドリーなスナックバーを表示。 |
| **条件** | `ConditionResult.Error()` を返すか throw — `ConditionEvaluator` がキャッチして `Error`(ブロックしない)に変換。 |
| **してはいけない** | 処理できない例外のキャッチ。すべての例外を黙って握りつぶさない。 |
@@ -1413,7 +1414,7 @@ uuidgen
1. `Domain/Revert/Steps/` に `IRevertStep` を実装する新しいクラスを作成します。
2. デシリアライズ用に静的な `FromData(JObject data)` メソッドを追加します。
3. `RevertManager` のリフレクションベースの `_stepRegistry` が自動検出します。
-4. `ExecutionScope.RecordStep()` で `revertStep` パラメータとして記録します。
+4. `call.Changes.Add(key, name, description, ok, revertStep)` で `revertStep` パラメータとして記録します(プロバイダーは自動的に行います)。
<h3>クラッシュセーフティの仕組み</h3>
diff --git a/.github/contributing/CONTRIBUTING.tr-TR.md b/.github/contributing/CONTRIBUTING.tr-TR.md
index 6d89b1a..99bbd77 100644
--- a/.github/contributing/CONTRIBUTING.tr-TR.md
+++ b/.github/contributing/CONTRIBUTING.tr-TR.md
@@ -132,7 +132,7 @@ optimizerDuck.slnx # Solution file (.slnx format)
│ │ │ └── WindowsBuilds.cs # OS build number constants
│ │ ├── Configuration/ # AppSettings model
│ │ ├── Exceptions/ # StepExecutionException
-│ │ ├── Execution/ # ExecutionScope — ambient step tracking via AsyncLocal
+│ │ ├── Execution/ # OpCall, OpResult, ChangeSet — açık çağrı bağlamı
│ │ ├── Customize/ # Customize settings
│ │ │ ├── Categories/ # Category classes with nested setting classes
│ │ │ └── Models/ # BaseCustomizeSetting, RegistryToggle, RegistryBinding,
@@ -167,8 +167,8 @@ optimizerDuck.slnx # Solution file (.slnx format)
│ │ ├── Configuration/ # ConfigManager, LanguageManager
│ │ ├── Customize/ # CustomizeRegistry (reflection-based discovery)
│ │ ├── Optimization/ # OptimizationRegistry, OptimizationService
-│ │ │ └── Providers/ # Static: RegistryService, ShellService (+ ShellPolicy),
-│ │ │ # ScheduledTaskService, ServiceProcessService
+│ │ │ └── Providers/ # Örnek (instance): RegistryService, ShellService (+ ShellPolicy),
+│ │ │ # ScheduledTaskService, ServiceProcessService, ProcessRunner
│ │ ├── Revert/ # RevertManager (atomic write/read of revert JSON files)
│ │ ├── System/ # RegistryWatcher (+ IRegistryWatcher), SystemInfoService,
│ │ │ # StreamService, UpdaterService, CrossPageEventBus
@@ -207,7 +207,7 @@ optimizerDuck.slnx # Solution file (.slnx format)
| Karar | Gerekçe |
|---|---|
| **Yansıma tabanlı keşif** | Güncellenecek DI kayıt dizisi yok. `ReflectionHelper.FindImplementationsInLoadedAssemblies<T>()` `optimizerDuck.*` derlemelerini tarar. Yeni optimizasyonlar/ayarlar otomatik keşfedilir. |
-| **Statik sağlayıcı hizmetler** | `RegistryService`, `ShellService`, `ScheduledTaskService`, `ServiceProcessService` statik sınıflardır. Geri alma adımlarını çevresel `ExecutionScope`'a kaydeder — bağlam enjekte etmek veya geçirmek gerekmez. |
+| **Sağlayıcı hizmetler** | Durumsuz hizmetler (`RegistryService`, `ScheduledTaskService`, `ServiceProcessService`) **statik**tir — açık `OpCall` (`context`) ile doğrudan çağırın. `ShellService` (+ `ProcessRunner`) DI singleton'dır (canlı ayar durumuna sahiptir); domain kodu `Shell` özelliğini kullanır. |
| **Dosya tabanlı geri alma takibi** | Uygulanma durumu = diskte dosya var (`%localappdata%\optimizerDuck\Revert\{id}.json`). Veritabanı yok. `File.Replace()` ile atomik yazma. |
| **Koşul sistemi (açık kalma)** | Optimizasyonlar ve ayarlar uyumluluk koşulları bildirebilir. Değerlendirme hataları asla bir öğeyi gizlemez — [Koşul Sistemi](#the-condition-system) bölümüne bakın. |
| **Entegrasyon tarzı testler** | Gerçek dosya sistemi, gerçek kayıt defteri (`HKCU\Software\TestOptimizerDuck*` altında), gerçek süreç yürütme. Mock kütüphanesi yok — yalnızca elle yazılmış test ikizleri. |
@@ -296,16 +296,17 @@ public class Performance : IOptimizationCategory
IProgress<ProcessingProgress> progress,
OptimizationContext context)
{
- // 1. Sistem değişiklikleri için statik sağlayıcıları kullanın
- RegistryService.Write(new RegistryItem(
- @"HKLM\SOFTWARE\Something", "ValueName", 1));
+ // 1. Örnek sağlayıcıları (`Reg`/`Svc`/`Tasks`/`Shell`) açık bağlamla kullanın
+ RegistryService.Write(
+ new RegistryItem(@"HKLM\SOFTWARE\Something", "ValueName", 1), context);
// 2. Asenkron işlemleri await edin — bu UI iş parçacığını serbest bırakır
await ServiceProcessService.ChangeServiceStartupTypeAsync(
- new ServiceItem("SomeService", ServiceStartupType.Disabled));
+ [new ServiceItem("SomeService", ServiceStartupType.Disabled)],
+ context);
- // 3. Çevresel ExecutionScope'tan sonucu döndürün
- return CompleteFromScope();
+ // 3. Toplanan değişikliklerden sonucu döndürün
+ return context.Changes.ToApplyResult();
}
}
}
@@ -319,10 +320,10 @@ public class Performance : IOptimizationCategory
| **`BaseOptimization`'dan türetin** | Öznitelik + yerelleştirme anahtarlarından `Name`, `ShortDescription`, `RiskVisual`, `TagDisplays` sağlar. |
| **`OwnerType` otomatik atanır** | Keşif bunu ayarlar — kendiniz ayarlamayın. |
| **`async Task<ApplyResult>` kullanın** | Hizmet sağlayıcıları asenkrondur — UI'nın duyarlı kalması için `await` edin. |
-| **`CompleteFromScope()` döndürün** | Çevresel `ExecutionScope`'a kaydedilen adımlardan `ApplyResult` türetir. `ApplyResult`'ı elle oluşturmayın. |
+| **`context.Changes.ToApplyResult()` döndürün** | `call.Changes` içinde toplanan değişikliklerden `ApplyResult` türetir. Erken çıkıştaki başarısızlıklar dışında `ApplyResult`'ı elle oluşturmayın. |
| **İlerlemeyi bildirin** | UI diyaloğunu güncellemek için `progress.Report(new ProcessingProgress { ... })` kullanın. |
-| **Tüm istisnaları yakalamayın** | Yukarı yayılsın. `ExecutionScope` başarı/başarısızlığı izler; `OptimizationService` istisnaları işler. |
-| **Geri alma adımlarını elle oluşturmayın** | Statik sağlayıcı hizmetler bunu `ExecutionScope.RecordStep()` ile otomatik yapar. |
+| **Tüm istisnaları yakalamayın** | Yukarı yayılsın. Başarı/başarısızlık `ChangeSet` içinde izlenir; `OptimizationService` istisnaları işler. |
+| **Geri alma adımlarını elle oluşturmayın** | Örnek sağlayıcılar bunu otomatik yapar (`call.Changes` içine kaydeder). `ChangeSet.Add()` ile elle kayıt yapmayın (USB durumları gibi özel sağlayıcı dışı durumlar dışında). |
| **`context.Logger` kullanın** | Önemli tanılama bilgileri için günlük kaydı sağlar. |
| **`context.Snapshot` kullanın** | `OptimizationContext.Snapshot` (`SystemSnapshot`) RAM, GPU, CPU, OS bilgisi verir. Koşullu mantık için kullanın. |
| **`context.StreamService` kullanın** | Uzak kaynakları (örn. güç planları) indiren optimizasyonlar için. |
@@ -330,43 +331,47 @@ public class Performance : IOptimizationCategory
<h3 id="available-service-providers">Mevcut Hizmet Sağlayıcılar</h3>
-Bu **statik** sınıflar günlük kaydı, hata işleme ve otomatik geri alma adımı kaydını yönetir.
+Bu sınıflar günlük kaydı, hata işleme ve otomatik geri alma adımı kaydını yönetir. Her yazma/değiştirme çağrısı açık bir `OpCall` alır (`OptimizationContext` bir `OpCall`'dır), değişikliği `call.Changes` içine kaydeder ve `OpResult` döndürür. Durumsuz hizmetler statiktir (doğrudan çağırın); `Shell` için hazır özelliği kullanın.
| Hizmet | Temel Metotlar | Neden Kullanılır |
|---|---|---|
-| **`RegistryService`** | `Write()`, `Read<T>()`, `DeleteValue()`, `CreateSubKey()`, `DeleteSubKeyTree()`, `KeyExists()`, `CleanupEmptyKeys()` | Kayıt defteri anahtarlarını oku/yaz/sil. Geri alma için orijinal değerleri yedekler. params dizisiyle toplu yazmayı destekler. |
-| **`ShellService`** | `CMDAsync()`, `PowerShellAsync()`, `CMD()` (senkron), `PowerShell()` (senkron) | CMD veya PowerShell komutları çalıştırır. Asenkron sürümleri tercih edin. Geri alma için isteğe bağlı `revertCommand` parametresi. Standart dışı çıkış kodları için `ShellPolicy`'ye bakın. |
-| **`ScheduledTaskService`** | `DisableTask()`, `EnableTask()`, `IsTaskEnabled()`, `DeleteTask()`, `GetAllTasks()`, `RegisterTask()`, `RunTask()`, `StopTask()` | Windows Zamanlanmış Görevlerini yönetir. |
-| **`ServiceProcessService`** | `ChangeServiceStartupTypeAsync()`, `GetStartupTypeAsync()` | Windows Hizmetlerini yönetir. Her zaman asenkron sürümleri kullanın. params dizisiyle toplu değişikliği destekler. |
+| **`RegistryService`** | `Write(item, call)`, `Write(call, params items)`, `Read<T>(item, call?)`, `DeleteValue(item, call)`, `CreateSubKey(item, call)`, `DeleteSubKeyTree(item, call)`, `KeyExists(item, call?)`, `CleanupEmptyKeys(keys, call?)` | Kayıt defteri anahtarlarını oku/yaz/sil. Geri alma için orijinal değerleri yedekler. Toplu yazma için ikinci `Write` aşırı yüklemesini kullanın. |
+| **`context.Shell`**(`ShellService`) | `CMDAsync(command, call, revertCommand?)`, `PowerShellAsync(command, call, revertCommand?)`, ham çalıştırma için `QueryCMDAsync` / `QueryPowerShellAsync` | CMD veya PowerShell komutları çalıştırır. Asenkron sürümleri tercih edin. Geri alma için isteğe bağlı `revertCommand` parametresi. Standart dışı çıkış kodları için `ShellPolicy`'ye bakın. Ham `Run*` metotları değişiklik **kaydetmez**. |
+| **`ScheduledTaskService`** | `DisableTask(path, call)`, `EnableTask(path, call)`, `IsTaskEnabled(path, call?)`, `DeleteTask(...)`, `GetAllTasks(call?)`, `RegisterTask(...)`, `RunTask(...)`, `StopTask(...)` | Windows Zamanlanmış Görevlerini yönetir. |
+| **`ServiceProcessService`** | `ChangeServiceStartupTypeAsync(item, call)`, `ChangeServiceStartupTypeAsync(items, call)`, `GetStartupTypeAsync(name, call?)` | Windows Hizmetlerini yönetir. Her zaman asenkron sürümleri kullanın. Toplu değişikliği dizi aşırı yüklemesiyle yapın. |
-> **params ile birden çok öğe kabul eden metotlar**: Çoğu yazma/değiştirme metodu bir params dizisi kabul eder (örn. `RegistryService.Write(item1, item2, item3)`). Bu, birden çok ayrı çağrıdan daha verimlidir.
+> **Toplu çağrılar**: Tekil params yerine `RegistryService.Write(context, item1, item2)` ve `ServiceProcessService.ChangeServiceStartupTypeAsync([item1, item2], context)` kullanın. Bu, tek tek çağrılardan daha verimlidir.
Örnek kullanım:
```csharp
// Senkron kayıt defteri yazma — birden çok öğeyi tek seferde
RegistryService.Write(
+ context,
new RegistryItem(@"HKLM\...", "Value1", 1),
new RegistryItem(@"HKLM\...", "Value2", 0)
);
-RegistryService.DeleteValue(new RegistryItem(@"HKCU\...", "OldValue"));
+RegistryService.DeleteValue(new RegistryItem(@"HKCU\...", "OldValue"), context);
// Asenkron hizmet değişiklikleri — birden çok hizmeti tek seferde
await ServiceProcessService.ChangeServiceStartupTypeAsync(
- new ServiceItem("DiagTrack", ServiceStartupType.Disabled),
- new ServiceItem("dmwappushservice", ServiceStartupType.Disabled)
-);
+ [
+ new ServiceItem("DiagTrack", ServiceStartupType.Disabled),
+ new ServiceItem("dmwappushservice", ServiceStartupType.Disabled),
+ ],
+ context);
// Geri alma komutuyla asenkron kabuk komutu
-var result = await ShellService.CMDAsync(
+var result = await context.Shell.CMDAsync(
"powercfg /h off",
+ context,
"powercfg /h on" // geri alma komutu saklanır
);
-// Asenkron PowerShell
-var usbStates = await ShellService.PowerShellAsync(
- "Get-CimInstance -Namespace root\\wmi -ClassName MSPower_DeviceEnable"
-);
+// Ham PowerShell sorgusu (değişiklik kaydetmez — salt okuma içindir)
+var usbStates = await context.Shell.QueryPowerShellAsync(
+ "Get-CimInstance -Namespace root\\wmi -ClassName MSPower_DeviceEnable",
+ context.Logger);
```
<h3 id="handling-async">Asenkron İşlemleri Yönetme</h3>
@@ -378,9 +383,9 @@ public override Task<ApplyResult> ApplyAsync(
IProgress<ProcessingProgress> progress,
OptimizationContext context)
{
- RegistryService.Write(new RegistryItem(@"HKLM\...", "Value", 1));
+ RegistryService.Write(new RegistryItem(@"HKLM\...", "Value", 1), context);
context.Logger.LogInformation("Applied tweak");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
```
@@ -389,9 +394,8 @@ Ancak herhangi bir asenkron sağlayıcı (hizmet, kabuk, görev) kullanıyorsan
```csharp
public override async Task<ApplyResult> ApplyAsync(...)
{
- await ServiceProcessService.ChangeServiceStartupTypeAsync(...);
- return CompleteFromScope();
-}
+ await ServiceProcessService.ChangeServiceStartupTypeAsync(new ServiceItem("SomeService", ServiceStartupType.Disabled), context);
+ return context.Changes.ToApplyResult();
```
<h3 id="new-category">Yeni Kategori Oluşturma</h3>
@@ -419,9 +423,9 @@ public abstract class GpuRegistryOptimization : BaseOptimization
foreach (var gpu in context.Snapshot.Gpus.Where(g => g.Vendor == Vendor))
{
var path = $@"HKLM\...\{index:D4}";
- RegistryService.Write(CreateItems(path).ToArray());
+ RegistryService.Write(context, CreateItems(path).ToArray());
}
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
```
@@ -621,12 +625,12 @@ public class MouseAcceleration : BaseCustomizeSetting
});
}
- public override async Task ApplyAsync(object? value)
+ public override async Task ApplyAsync(object? value, OpCall call)
{
var isOn = value is bool b && b;
- RegistryService.Write(new RegistryItem(Path, "MouseSpeed", isOn ? "1" : "0"));
- RegistryService.Write(new RegistryItem(Path, "MouseThreshold1", isOn ? "6" : "0"));
- RegistryService.Write(new RegistryItem(Path, "MouseThreshold2", isOn ? "10" : "0"));
+ RegistryService.Write(new RegistryItem(Path, "MouseSpeed", isOn ? "1" : "0"), call);
+ RegistryService.Write(new RegistryItem(Path, "MouseThreshold1", isOn ? "6" : "0"), call);
+ RegistryService.Write(new RegistryItem(Path, "MouseThreshold2", isOn ? "10" : "0"), call);
if (NeedsPostAction)
await ExecutePostActionAsync();
@@ -653,18 +657,18 @@ Bu, yazma sonrası kayıt defteri otururken UI'nın bayat değerler göstermesin
Gömülü kaynak çıkarmayı içeren ayarlar için (kısayol oklarını boş bir simgeyle değiştirmek gibi):
```csharp
-public override async Task ApplyAsync(object? value)
+public override async Task ApplyAsync(object? value, OpCall call)
{
var isOn = value is bool b && b;
if (isOn)
{
- RegistryService.DeleteValue(new RegistryItem(Path, "29"));
+ RegistryService.DeleteValue(new RegistryItem(Path, "29"), call);
}
else
{
var outputPath = Path.Combine(Shared.AssetsDirectory, nameof(Desktop), "blank.ico");
EmbeddedResourceHelper.TryExtract("Icons.blank.ico", outputPath);
- RegistryService.Write(new RegistryItem(Path, "29", outputPath));
+ RegistryService.Write(new RegistryItem(Path, "29", outputPath), call);
}
await ExecutePostActionAsync();
}
@@ -933,7 +937,7 @@ services.AddSingleton<UpdaterService>();
services.AddSingleton<IRegistryWatcher, RegistryWatcher>();
```
-> Bu, oryantasyon için bir anlık görüntüdür — güncel kayıtlar için `App.xaml.cs` kaynaktır. Ayrıca başlangıç çağrılarına dikkat edin: `ShellService.Init(appOptionsMonitor)` ve `WmiHelper.Initialize()`, ve transient diyalogları çözmek için kullanılan `App.AppHost` özelliği.
+> Bu, oryantasyon için bir anlık görüntüdür — güncel kayıtlar için `App.xaml.cs` kaynaktır. Ayrıca başlangıç çağrılarına dikkat edin: DI içine kayıtlı `ProcessRunner`/`ShellService` tekilleri ve `WmiHelper.Initialize()`, ve transient diyalogları çözmek için kullanılan `App.AppHost` özelliği.
<h3 id="system-services">Sistem Hizmetleri Referansı</h3>
@@ -957,36 +961,45 @@ Uygulanan her optimizasyon `%localappdata%\optimizerDuck\Revert\{optimizationId}
<h3 id="how-it-works-tr">Nasıl Çalışır</h3>
```
-ApplyAsync()
- │
- ├─ ExecutionScope.Begin(optimization, logger) ← çevresel AsyncLocal kapsamı oluşturur
+ApplyAsync(progress, context) ← context: OptimizationContext (bir OpCall)
│
- ├─ RegistryService.Write(...) ← RegistryRevertStep'i otomatik kaydeder
- ├─ ServiceProcessService.ChangeServiceStartupTypeAsync(...) ← ServiceRevertStep'i otomatik kaydeder
- ├─ ShellService.CMDAsync(...) ← ShellRevertStep'i otomatik kaydeder
+ ├─ RegistryService.Write(item, context) ← RegistryRevertStep'i context.Changes'e kaydeder
+ ├─ await ServiceProcessService.ChangeServiceStartupTypeAsync(item, context) ← ServiceRevertStep'i context.Changes'e kaydeder
+ ├─ await context.Shell.CMDAsync(cmd, context, revert) ← ShellRevertStep'i context.Changes'e kaydeder
│
- ├─ CompleteFromScope() → ApplyResult ← kaydedilen adımlardan türetilir
+ ├─ context.Changes.ToApplyResult() → ApplyResult ← toplanan değişikliklerden türetilir
│
- └─ ExecutionScope dispose → RevertManager.SaveRevertDataAsync()
+ └─ OptimizationService → RevertManager.SaveRevertDataAsync(changes, id, key)
+ └─ yalnızca başarılı adımlar, sıkı (compact) eklemeli günlük olarak kalıcılaşır
```
-<h3 id="scope-variants-tr">Kapsam Varyantları</h3>
+<h3 id="call-context-tr">Çağrı Bağlamı (`OpCall` / `ChangeSet` / `OpResult`)</h3>
-| Metot | Amaç |
+| Parça | Amaç |
|---|---|
-| `ExecutionScope.Begin(optimization, logger)` | Gerçek bir uygulama için kalıcı kapsam oluşturur. |
-| `ExecutionScope.BeginForLogging(logger)` | Yalnızca günlük — adımları kaydeder ama geri alma verisini asla kalıcılaştırmaz. |
-| `ExecutionScope.BeginForCapture(logger)` | Yeniden deneme için: `OptimizationId = Guid.Empty` ile adımları yakalar, daha sonra gerçek kapsama yeniden atanır. |
+| `OpCall` | Açık işlem bağlamı: `Changes` (toplayıcı), `Logger`, `CancellationToken`. Parametre olarak geçirin — ortamda taşınan duruma güvenmeyin. `OptimizationContext`, `Snapshot` ve `StreamService` ekleyen bir `OpCall`'dır. |
+| `ChangeSet` | İş parçacığı güvenli değişiklik toplayıcı. Sağlayıcılar her işlemi `Add()` ile buraya ekler; motor sonuç ve geri alma verisini buradan türetir (`ToApplyResult()`). |
+| `OpResult` | Tek sağlayıcı işleminin sonucu (`Ok`, `Revert`, `Error`, `ErrorDetail`). Hatalar burada taşınır. |
+| `Change` | Tek kayıt: kararlı `Key`, 1 tabanlı sıra `Seq` (geri alma dosyası dizini olur), `Retry` (`Func<OpCall, Task<OpResult>>`). |
+
+<h3 id="provider-instances-tr">Sağlayıcı Örnekleri</h3>
+
+| Kullanım | Detay |
+|---|---|
+| Optimizasyonlar | `BaseOptimization` üzerindeki `Reg`/`Svc`/`Tasks`/`Shell` özelliklerini kullanın. |
+| Özelleştirme ayarları | `BaseCustomizeSetting` üzerindeki aynı `Reg`/`Svc`/`Tasks`/`Shell` özelliklerini kullanın (`ApplyAsync(value, call)` içinden). |
+| DI tekilleri | `ShellService` + `ProcessRunner` DI tekilidir (zaman aşımı ayarlardan canlı okunur). Geri kalanı gerektiği yerde `new` ile kurulur. |
+| Ham sorgular | `context.Shell.QueryCMDAsync(cmd, logger)` / `context.Shell.QueryPowerShellAsync(cmd, logger)` değişiklik **kaydetmez** — salt okuma sorguları içindir. USB tespiti gibi ham sonuç + elle kayıt gereken durumlarda `context.Changes.Add(...)` kullanın. |
<h3 id="step-types-tr">Adım Türleri</h3>
| Adım Türü | Kaydettiği | Otomatik Oluşturan |
|---|---|---|
-| **`RegistryRevertStep`** | Değişiklikten önceki orijinal kayıt defteri değeri | `RegistryService.Write()`, `DeleteValue()`, `CreateSubKey()`, `DeleteSubKeyTree()` |
-| **`ServiceRevertStep`** | Orijinal hizmet başlangıç türü | `ServiceProcessService.ChangeServiceStartupTypeAsync()` |
-| **`ScheduledTaskRevertStep`** | Orijinal görev durumu (etkin/devre dışı) | `ScheduledTaskService.DisableTask()`, `EnableTask()` |
-| **`ShellRevertStep`** | Değişikliği tersine çeviren kabuk komutu | `ShellService.CMDAsync()`, `PowerShellAsync()` — bir `revertCommand` parametresi geçirin |
-| **`UsbPowerRevertStep`** | USB güç ayarları (cihaz başına) | USB ile ilgili optimizasyonlar (elle `ExecutionScope.RecordStep()` ile) |
+| **`RegistryRevertStep`** | Değişiklikten önceki orijinal kayıt defteri değeri | `RegistryService.Write()`, `DeleteValue()`, `CreateSubKey()`, `DeleteSubKeyTree()` (açık `OpCall` ile) |
+| **`ServiceRevertStep`** | Orijinal hizmet başlangıç türü | `ServiceProcessService.ChangeServiceStartupTypeAsync()` (açık `OpCall` ile) |
+| **`ScheduledTaskRevertStep`** | Orijinal görev durumu (etkin/devre dışı) | `ScheduledTaskService.DisableTask()`, `ScheduledTaskService.EnableTask()` (açık `OpCall` ile) |
+| **`ShellRevertStep`** | Değişikliği tersine çeviren kabuk komutu | `context.Shell.CMDAsync()`, `context.Shell.PowerShellAsync()` — bir `revertCommand` parametresi geçirin |
+| **`UsbPowerRevertStep`** | USB güç ayarları (cihaz başına) | USB ile ilgili optimizasyonlar (`context.Changes.Add(...)` ile elle) |
<h3 id="revert-command">Kabuk Çağrılarına Geri Alma Komutu Ekleme</h3>
@@ -994,7 +1007,7 @@ ApplyAsync()
```csharp
// "powercfg /h on" bu değişikliği tersine çevirmek için saklanır
-await ShellService.CMDAsync("powercfg /h off", "powercfg /h on");
+await context.Shell.CMDAsync("powercfg /h off", context, "powercfg /h on");
```
<h3 id="revert-data-format-tr">Geri Alma Veri Formatı</h3>
@@ -1005,27 +1018,26 @@ await ShellService.CMDAsync("powercfg /h off", "powercfg /h on");
"OptimizationId": "guid",
"OptimizationName": "DisableTelemetry",
"AppliedAt": "2026-06-02T12:00:00Z",
- "Steps": [
- { "Index": 0, "Type": "Registry", "Data": { "..." } },
- null, // null boşluğu = bu dizindeki başarısız adım
+ { "Index": 1, "Type": "Registry", "Data": { "..." } },
{ "Index": 2, "Type": "Service", "Data": { "..." } }
]
}
```
+Sıkı ve yalnızca eklemeli günlük: yalnızca **başarılı** adımlar kalıcılaşır, her biri taze bir dizinle. Başarısız adımlar için boş yuva ayrılmaz. Yeniden uygulama yeni girdiler ekler; dizinler asla yeniden kullanılmaz, böylece diskteki girdiler kayıtlar arasında kararlı kalır.
+
<h3 id="key-details-tr">Temel Detaylar</h3>
- **Uygulanma durumu**, diskte dosya varlığından çıkarılır (`RevertManager.IsAppliedAsync(id)`).
-- **Atomik yazma**: `.tmp` dosyasına yazar, sonra `File.Replace()` — çökme güvenli.
+- **Atomik yazma**: `WriteThrough` bayraklı `FileStream` + `Flush(flushToDisk: true)` ile `.tmp` dosyasına yazar, sonra `File.Replace()` — çökme güvenli. Kalan `.tmp` dosyaları başlangıçta temizlenir (`RemoveOrphanedTempFiles`).
- **Eşzamanlı erişim**: dosya başına `SemaphoreSlim` kilitleri yarış koşullarını önler; 30 saniye zaman aşımı.
-- **`ExecutionScope`** çevresel adım takibi için `AsyncLocal<ExecutionScope?>` kullanır. Parametrelerle bağlam geçirmeye gerek yok.
+- **Açık bağlam**: Her sağlayıcı çağrısı `OpCall` alır (`Changes`, `Logger`, `CancellationToken`). Ortamda taşınan duruma güvenmeyin — bağlamı parametreyle geçirin.
- **Geri alma adımları ters sırada çalışır** (en son uygulanan = ilk geri alınan).
- **Kısmi başarı**: bazı adımlar başarısız olsa bile geri alma devam eder. Başarısız adımlara yeniden deneme eylemleri kaydedilir.
-- **Yeniden deneme**: `OptimizationService.RetryFailedStepsAsync()` tek tek başarısız adımları yeniden deneyebilir; `RecordStepAtIndex()` orijinal dizin düzenini korur.
-- **Upsert**: `RevertManager.UpsertRevertStepAtIndexAsync()` belirli dizinlerdeki geri alma adımlarını ekleyebilir/değiştirebilir (yeniden deneme sırasında kullanılır).
+- **Yeniden deneme**: `OptimizationService.RetryFailedStepsWithResultsAsync()` başarısız adımları taze bir `OpCall` ile `Func<OpCall, Task<OpResult>>` üzerinden yeniden dener; kurtarılan adımlar `AppendRevertStepAsync()` ile sona eklenir (üzerine yazma yok — LIFO geri alma yine özgün yedekte biter).
- **Adım kaydı**: Geri alma adımı serisizleştirme yansıma tabanlı `_stepRegistry` kullanır — yeni adım türleri, `IRevertStep` uygulayıp statik bir `FromData(JObject)` metoduyla otomatik kaydolur.
-> **Önemli**: Sağlayıcı hizmetleri (`RegistryService.Write`, `ShellService.CMDAsync` vb.) çağırdığınızda geri alma adımları otomatik kaydedilir. Özel bir sağlayıcı uygulamadığınız sürece (`UsbPowerRevertStep` gibi) geri alma adımlarını elle oluşturMAYIN.
+> **Önemli**: Sağlayıcı hizmetleri (`RegistryService.Write`, `context.Shell.CMDAsync` vb.) çağırdığınızda geri alma adımları otomatik kaydedilir. Özel bir sağlayıcı uygulamadığınız sürece (`UsbPowerRevertStep` gibi) geri alma adımlarını elle oluşturMAYIN.
---
@@ -1097,9 +1109,9 @@ public class MyOptimizationTests
{
var optimization = new TestOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep("Test", "Step 1", true);
+ args.context.Changes.Add("Test", "Step 1", true);
return Task.FromResult(ApplyResult.True());
},
};
@@ -1113,11 +1125,16 @@ public class MyOptimizationTests
private static OptimizationService CreateService()
{
return new OptimizationService(
- new RevertManager(NullLogger<RevertManager>.Instance, NullLoggerFactory.Instance),
+ new RevertManager(
+ NullLogger<RevertManager>.Instance,
+ new ShellService(new ProcessRunner(120000)),
+ TimeProvider.System
+ ),
NullLoggerFactory.Instance,
new SystemInfoService(NullLogger<SystemInfoService>.Instance),
new StreamService(NullLogger<StreamService>.Instance),
- null!,
+ new ContentDialogService(),
+ new ShellService(new ProcessRunner(120000)),
NullLogger<OptimizationService>.Instance
);
}
@@ -1174,15 +1191,15 @@ public class MyOptimizationTests
- Hizmetler, ViewModel'ler ve Sayfalar `App.xaml.cs` içinde singleton olarak kaydedilir.
- Yapıcı enjeksiyonu kullanın: `public class Foo(Bar bar, Baz baz)` veya `public class Foo(ILogger<Foo> logger)`.
-- Statik sağlayıcı hizmetler (`RegistryService`, `ShellService`, `ScheduledTaskService`, `ServiceProcessService`) enjekte EDİLMEZ — doğrudan erişin.
+- Örnek sağlayıcılar (`RegistryService`, `ScheduledTaskService`, `ServiceProcessService`) enjekte EDİLMEZ — `BaseOptimization`/`BaseCustomizeSetting` üzerindeki `Reg`/`Svc`/`Tasks`/`Shell` özellikleriyle ya da gerektiğinde `new` ile kullanın. `ShellService` + `ProcessRunner` DI tekilidir.
- Test ikizleri elle yazılır (mock kütüphanesi yok).
<h3 id="error-handling-tr">Hata İşleme</h3>
| Katman | Uygulama |
|---|---|
-| **Optimizasyonlar** | Fırlatmak yerine `ApplyResult.False("reason")` döndürün. Adım düzeyi başarısızlık takibini `ExecutionScope`'a bırakın. |
-| **Sağlayıcı hizmetler** | Sistem çağrılarını try/catch ile sarın, hataları günlükleyin. Başarısız adımları yeniden deneme eylemleriyle kaydedin. |
+| **Optimizasyonlar** | Fırlatmak yerine `ApplyResult.False("reason")` döndürün. Adım düzeyi başarısızlık takibini `ChangeSet`'e bırakın. |
+| **Sağlayıcı hizmetler** | Sistem çağrılarını try/catch ile sarın, hataları `call.Logger` ile günlükleyin. Başarısız adımları `Func<OpCall, Task<OpResult>>` yeniden deneme eylemleriyle kaydedin. |
| **ViewModel'ler** | Komut işleyicilerinde istisnaları yakalayın, kullanıcı dostu snackbar'lar gösterin. |
| **Koşullar** | `ConditionResult.Error()` döndürün veya fırlatın — `ConditionEvaluator` yakalar ve `Error`'a (asla engellemez) eşler. |
| **Yapmayın** | İşleyemeyeceğiniz istisnaları yakalamayın. Tüm istisnaları sessizce yutmayın. |
@@ -1409,12 +1426,10 @@ uuidgen
Optimizasyonun `Id` GUID'inin değişmediğini kontrol edin. Geri alma dosyaları `Id` ile anahtarlanır. GUID'i yeniden üretirseniz, daha önce uygulanan optimizasyonların eşleşen geri alma dosyaları kalmaz.
-<h3>Yeni bir geri alma adımı türü nasıl eklerim?</h3>
-
1. `Domain/Revert/Steps/` içinde `IRevertStep` uygulayan yeni bir sınıf oluşturun.
2. Serisizleştirme için statik bir `FromData(JObject data)` metodu ekleyin.
3. `RevertManager`'ın yansıma tabanlı `_stepRegistry`'si onu otomatik keşfeder.
-4. `ExecutionScope.RecordStep()` ile `revertStep` parametresi olarak kaydedin.
+4. `call.Changes.Add(key, name, description, ok, revertStep)` ile `revertStep` parametresi olarak kaydedin (sağlayıcılar bunu otomatik yapar).
<h3>Uygulama çökme güvenliğini nasıl ele alır?</h3>
diff --git a/.gitignore b/.gitignore
index c0e2320..d08439e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -697,3 +697,8 @@ $RECYCLE.BIN/
# End of https://www.toptal.com/developers/gitignore/api/csharp,windows,rider,visualstudio,visualstudiocode
+
+# Local agent/session artifacts
+omp-session-*.html
+crash_*.log
+TestResults/
diff --git a/AGENTS.md b/AGENTS.md
index 8bb9023..f9657e6 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -23,10 +23,10 @@
- `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/` — `ExecutionScope` (ambient `AsyncLocal`-based step tracking)
+ - `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)
- `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`, `OperationStepResult`
+ - `Optimizations/Models/` — `BaseOptimization`, `ApplyResult`, `OptimizationContext`, `OptimizationResult`
- `Optimizations/Models/Services/` — `RegistryItem`, `ServiceItem` (+ `ServiceStartupType`), `ShellResult`
- `Optimizations/Models/Bloatware/` — `AppXPackage`
- `Optimizations/Models/Cleanup/` — `CleanupItem`
@@ -37,12 +37,15 @@
- `Revert/Steps/` — `RegistryRevertStep`, `ServiceRevertStep`, `ScheduledTaskRevertStep`, `ShellRevertStep`, `UsbPowerRevertStep`
- `Configuration/` — `AppSettings`
- `UI/` — enums: `OptimizationRisk`, `OptimizationTags` (flags), `OptimizationCategoryOrder`, `CustomizeOrder`, `OptimizationSuccessResult`, `OptimizationState` (ObservableObject with relative-time display), `RiskVisual`, `ProcessingProgress`, `LanguageOption`
+ - `Optimizations/Models/Services/` — also `RegistryValues` (shared value equality), `ShellPolicy` (shell success/error policy), `ShellResult`
- `Services/` — business logic:
- `Conditions/` — `ConditionEvaluator` (static, fail-open evaluation)
- `Configuration/` — `ConfigManager`, `LanguageManager`
- - `Customize/` — `CustomizeRegistry` (reflection-based discovery)
- - `Optimization/` — `OptimizationRegistry`, `OptimizationService`
- - `Optimization/Providers/` — static: `RegistryService`, `ShellService` (+ `ShellPolicy`), `ScheduledTaskService`, `ServiceProcessService`
+ - `Customize/` — `CustomizeRegistry` (reflection-based discovery), `CustomizationExecutor` (debounce + sequential serialization for setting writes)
+ - `Optimization/` — `OptimizationRegistry`, `OptimizationService`, `OptimizationValidation` (fail-fast Id checks at startup)
+ - `Optimization/Providers/` — `RegistryService`, `ScheduledTaskService`, `ServiceProcessService` are **static** (stateless); `ShellService` + `ProcessRunner` are DI singletons (stateful; `ShellService` reads the timeout live from settings). All take an explicit `OpCall`, record into `call.Changes`, log via `call.Logger`, return `OpResult`. `ShellMapping` centralises cmd/PowerShell argument building and result mapping.
+ - `Windows/Services/ScStartupTypeParser.cs` — shared parser for `sc.exe qc` START_TYPE output, used by `ServiceProcessService`.
+ - `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 `SystemSnapshot` + models), `StreamService`, `UpdaterService`, `CrossPageEventBus`, `CrossPageEvents`
- `UI/` — `BloatwareService`, `DiskCleanupService`, `StartupManagerService`
@@ -69,12 +72,16 @@
> Package versions live in `optimizerDuck.csproj` / `optimizerDuck.Test.csproj` — verify there rather than trusting this snapshot.
## Optimization & Customize Discovery (Reflection, No Manual Registration)
-- **New optimizations**: Create a **nested class** inside the relevant category class (e.g., `Domain/Optimizations/Categories/Performance.cs`), extend `BaseOptimization`, decorate with `[Optimization(Id = "guid", Risk = ..., Tags = ..., Condition = typeof(...)?)]`.
+- **New optimizations**: Create a **nested class** inside the relevant category class (e.g., `Domain/Optimizations/Categories/Performance.cs`), extend `BaseOptimization`, decorate with `[Optimization(Id = "guid", Risk = ..., Tags = ..., Condition = typeof(...)?)]`. This is the only optimization path.
- **New customize settings**: Same nesting pattern inside `Domain/Customize/Categories/`, extend `BaseCustomizeSetting`, decorate with `[CustomizeSetting(Section = ..., Icon = ..., Recommendation = ..., Condition = typeof(...)?)]`. `Icon` is required (`SymbolRegular` enum). `Section` can be a string or enum value. `Recommendation` can be `On`, `Off`, `Depends`, `Experimental`, or `None`.
- **Category classes**: Decorate with `[OptimizationCategory(typeof(PageClass))]` or `[CustomizeCategory(PageType = typeof(PageClass))]`.
- **Discovery**: `ReflectionHelper.FindImplementationsInLoadedAssemblies<T>()` scans assemblies whose name starts with `optimizerDuck` — no DI registration array to update. Results are cached in `_implementationCache`.
-- **Static provider services**: `RegistryService`, `ServiceProcessService`, `ScheduledTaskService`, `ShellService` are **static classes** (not DI-registered). They capture revert steps into the ambient `ExecutionScope`.
-- **`CompleteFromScope()`**: Optimizations call `BaseOptimization.CompleteFromScope()` to build the `ApplyResult` from steps recorded in the ambient `ExecutionScope`. Do not manually construct `ApplyResult`.
+- **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`.
+- **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.
+- **One implementation per Windows operation**: `RegistryService`/`ServiceProcessService`/`ScheduledTaskService`/`ShellService` are the single source of truth (plus the shared `ScStartupTypeParser`, `RegistryValues`, `ShellMapping`). 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.
+- **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. Only truly unrecoverable state throws. `OptimizationService` persists partial work with `CancellationToken.None` and builds the `OptimizationResult`.
- **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)
@@ -86,17 +93,14 @@
## Revert System
- **File-based**: Each applied optimization creates `%LocalAppData%\optimizerDuck\Revert\{optimizationId}.json`. Applied state is inferred from file presence on disk.
-- **Atomic writes**: `RevertManager` writes to `.tmp` then `File.Replace` for crash safety.
-- **Concurrent access**: Per-file `SemaphoreSlim` locks with 30-second timeout prevent race conditions.
-- **Step types**: `RegistryRevertStep`, `ServiceRevertStep`, `ScheduledTaskRevertStep`, `ShellRevertStep`, `UsbPowerRevertStep`.
-- **`ExecutionScope`**: Uses `AsyncLocal<ExecutionScope?>` for ambient step tracking — no need to pass context through parameters.
-- **Scope variants**: `ExecutionScope.Begin()` (creates persistable scope), `ExecutionScope.BeginForLogging()` (logging only, no persistence), `ExecutionScope.BeginForCapture()` (for retry, `OptimizationId = Guid.Empty`).
-- **`ExecutionScope.RecordStep()`**: Auto-incremented index. Records name, description, success/fail status, revert step, error, retry action, error detail.
-- **`ExecutionScope.RecordStepAtIndex()`**: For retry — preserves original index layout in revert files.
-- **`ExecutionScope.Track()`**: Tracks service-level success/fail counts for summary logging.
+- **Atomic writes**: `RevertManager` writes to `.tmp` via `FileStream(WriteThrough)` + `Flush(flushToDisk: true)`, then `File.Replace` for crash safety. Stale `.tmp` files are swept at startup (`RemoveOrphanedTempFiles`).
+- **Concurrent access**: Per-file `SemaphoreSlim` locks with 30-second timeout prevent race conditions. Lock entries are never disposed while in use.
+- **Compact layout**: only successful steps persist, each with a fresh index; no null gaps. Re-apply appends new entries; recovered retry steps append via `AppendRevertStepAsync` (never overwrite — LIFO revert still ends at the original backup).
+- **Step types**: `RegistryRevertStep`, `ServiceRevertStep`, `ScheduledTaskRevertStep`, `ShellRevertStep`, `UsbPowerRevertStep`. Each verifies its own effect inside `ExecuteAsync` (registry read-back, service re-query, task state re-check). 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.
-- **Upsert**: `RevertManager.UpsertRevertStepAtIndexAsync()` can add/replace revert steps at specific indices (used during retry to persist recovered steps).
-- **Key methods**: `SaveRevertDataAsync()`, `RevertAsync()`, `IsAppliedAsync(id)`, `GetRevertDataAsync(id)`, `ClearAllRevertData()`.
+- **Retry**: `OptimizationService.RetryFailedStepsWithResultsAsync()` re-invokes `Retry` with a fresh `OpCall` and persists recovered steps via `AppendRevertStepAsync`.
+- **Key methods**: `SaveRevertDataAsync()`, `RevertAsync()`, `AppendRevertStepAsync()`, `RemoveRevertStepsAtIndexesAsync()`, `IsAppliedAsync(id)`, `GetRevertDataAsync(id)`, `ClearAllRevertData()`, `RemoveOrphanedTempFiles()`.
## Customize Setting API Notes
- `RegistryToggle` uses `OnValues` / `OffValues` (lists; `null` = key absent) + `DefaultValue`, `IsOptional`, `ValueKind`. There is no `OnValue`/`OffValue`/`TreatMissingAsDefault`.
@@ -112,7 +116,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()`.
-- ShellService must be initialized at startup: `ShellService.Init(appOptionsMonitor)`.
+- `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 .`.
- `WmiHelper.Initialize()` registers WMI cleanup for abnormal termination.
## Testing (xUnit v3, Integration-Style)
@@ -127,9 +132,8 @@
- **Test project packages**: `Microsoft.NET.Test.Sdk` 18.6.0, `xunit.v3` 3.2.2, `coverlet.collector` 10.0.1.
## Shell Service Details
-- `ShellService.CMD()` and `CMDAsync()` run commands in cmd.exe.
-- `ShellService.PowerShell()` and `PowerShellAsync()` run commands with `-EncodedCommand` for safe encoding.
-- Both sync and async variants accept an optional `ShellRevertStep` (from `revertCommand` string or `Func<string>`) that gets saved for undo.
+- `ShellService.CMDAsync()` and `PowerShellAsync()` run commands in cmd.exe / PowerShell (`-EncodedCommand`). `QueryCMDAsync()` / `QueryPowerShellAsync()` run without recording a change.
+- Async variants accept an optional revert step (from `revertCommand` string) that gets saved for undo.
- `ShellPolicy` class provides customizable success criteria (default: exit code 0). Use `ShellPolicy.SuccessExitCodes()` or `ShellPolicy.SuccessExitCodeRange()` for non-standard exit codes.
- Default timeout: 120 seconds (configurable via `AppSettings.Optimize.ShellTimeoutMs`).
- UTF-8 encoding is forced for both stdout and stderr.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 91c8a26..238af4f 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -132,7 +132,7 @@ optimizerDuck.slnx # Solution file (.slnx format)
│ │ │ └── WindowsBuilds.cs # OS build number constants
│ │ ├── Configuration/ # AppSettings model
│ │ ├── Exceptions/ # StepExecutionException
-│ │ ├── Execution/ # ExecutionScope — ambient step tracking via AsyncLocal
+│ │ ├── Execution/ # OpCall, OpResult, ChangeSet — explicit call context
│ │ ├── Customize/ # Customize settings
│ │ │ ├── Categories/ # Category classes with nested setting classes
│ │ │ └── Models/ # BaseCustomizeSetting, RegistryToggle, RegistryBinding,
@@ -167,8 +167,8 @@ optimizerDuck.slnx # Solution file (.slnx format)
│ │ ├── Configuration/ # ConfigManager, LanguageManager
│ │ ├── Customize/ # CustomizeRegistry (reflection-based discovery)
│ │ ├── Optimization/ # OptimizationRegistry, OptimizationService
-│ │ │ └── Providers/ # Static: RegistryService, ShellService (+ ShellPolicy),
-│ │ │ # ScheduledTaskService, ServiceProcessService
+│ │ │ └── Providers/ # Instance: RegistryService, ShellService (+ ShellPolicy),
+│ │ │ # ScheduledTaskService, ServiceProcessService, ProcessRunner
│ │ ├── Revert/ # RevertManager (atomic write/read of revert JSON files)
│ │ ├── System/ # RegistryWatcher (+ IRegistryWatcher), SystemInfoService,
│ │ │ # StreamService, UpdaterService, CrossPageEventBus
@@ -207,7 +207,7 @@ optimizerDuck.slnx # Solution file (.slnx format)
| Decision | Rationale |
|---|---|
| **Reflection-based discovery** | No DI registration arrays to update. `ReflectionHelper.FindImplementationsInLoadedAssemblies<T>()` scans `optimizerDuck.*` assemblies. New optimizations/settings are auto-discovered. |
-| **Static provider services** | `RegistryService`, `ShellService`, `ScheduledTaskService`, `ServiceProcessService` are static classes. They record revert steps into the ambient `ExecutionScope` — no need to inject or pass context. |
+| **Provider services** | Stateless services (`RegistryService`, `ScheduledTaskService`, `ServiceProcessService`) are **static** — call them directly, passing the explicit `OpCall` (`context`). `ShellService` is a DI singleton (it holds the live shell timeout) and reaches optimizations as `context.Shell`. |
| **File-based revert tracking** | Applied state = file exists on disk (`%localappdata%\optimizerDuck\Revert\{id}.json`). No database. Atomic writes via `File.Replace()`. |
| **Condition system (fail-open)** | Optimizations and settings can declare compatibility conditions. Evaluation failures never hide an item — see [The Condition System](#the-condition-system). |
| **Integration-style tests** | Real filesystem, real registry (under `HKCU\Software\TestOptimizerDuck*`), real process execution. No mocking libraries — hand-written test doubles only. |
@@ -250,7 +250,7 @@ At startup the app calls `OptimizationRegistry.PreloadOptimizationsAsync()`. Thi
1. `ReflectionHelper.FindImplementationsInLoadedAssemblies<IOptimizationCategory>()` finds every category class.
2. For each category it scans **nested public classes** implementing `IOptimization`.
-3. Each optimization is instantiated, `OwnerType` is assigned, and its `[Optimization]` metadata (including any `Condition`) is validated.
+3. Each optimization is instantiated, `OwnerType` is assigned, and its `[Optimization]` metadata (including any `Condition`) is validated — malformed or duplicated `Id` GUIDs fail fast here with the offending class named.
4. `OptimizationService.UpdateOptimizationStateAsync` scans revert files on disk to mark each optimization as Applied or not.
5. The Optimize page calls `EnsurePreloadedAsync()` before binding (a no-op if preloading already finished).
@@ -296,16 +296,17 @@ public class Performance : IOptimizationCategory
IProgress<ProcessingProgress> progress,
OptimizationContext context)
{
- // 1. Use static providers to make system changes
+ // 1. Static providers do the work; pass context as the OpCall
RegistryService.Write(new RegistryItem(
- @"HKLM\SOFTWARE\Something", "ValueName", 1));
+ @"HKLM\SOFTWARE\Something", "ValueName", 1), context);
- // 2. Await async operations — this yields the UI thread
+ // 2. Await async providers — this keeps the UI responsive
await ServiceProcessService.ChangeServiceStartupTypeAsync(
- new ServiceItem("SomeService", ServiceStartupType.Disabled));
+ new ServiceItem("SomeService", ServiceStartupType.Disabled),
+ context);
- // 3. Return result from the ambient ExecutionScope
- return CompleteFromScope();
+ // 3. Map the recorded changes to the result
+ return context.Changes.ToApplyResult();
}
}
}
@@ -315,58 +316,130 @@ public class Performance : IOptimizationCategory
| Rule | Detail |
|---|---|
-| **`Id` must be a new GUID** | Used for revert file naming and applied-state tracking. Generate with `[guid]::NewGuid()` in PowerShell. |
-| **Extend `BaseOptimization`** | Provides `Name`, `ShortDescription`, `RiskVisual`, `TagDisplays` from attribute + localization keys. |
+| **Extend `BaseOptimization`** | Provides the `Shell` provider plus `Name`, `ShortDescription`, `RiskVisual`, `TagDisplays` from attribute + localization keys. Stateless providers (`RegistryService`, `ServiceProcessService`, `ScheduledTaskService`) are static — call them directly. |
| **`OwnerType` is assigned automatically** | Discovery sets it — don't set it yourself. |
-| **Use `async Task<ApplyResult>`** | Service providers are async — `await` them to keep the UI responsive. |
-| **Return `CompleteFromScope()`** | Derives `ApplyResult` from steps recorded in the ambient `ExecutionScope`. Don't construct `ApplyResult` manually. |
+| **Pass `context` as the `OpCall`** | `OptimizationContext` extends `OpCall` (`Changes`, `Logger`, `CancellationToken`). Single-item calls take it last (`RegistryService.Write(item, context)`); batch overloads take it first (`RegistryService.Write(context, item1, item2)`). |
+| **Return `context.Changes.ToApplyResult()`** | Maps recorded changes to `ApplyResult`: any success is success; total failure carries the first error. Don't construct `ApplyResult` manually. |
| **Report progress** | Use `progress.Report(new ProcessingProgress { ... })` to update the UI dialog. |
-| **Don't catch all exceptions** | Let them bubble up. `ExecutionScope` tracks success/failure; `OptimizationService` handles exceptions. |
-| **Don't manually create revert steps** | Static provider services do this automatically via `ExecutionScope.RecordStep()`. |
+| **Don't catch all exceptions** | Let them bubble up. `ChangeSet` tracks per-step success/failure; `OptimizationService` handles exceptions. |
+| **Don't manually create revert steps** | Static providers record `Change` entries (with revert steps) into `context.Changes` automatically. |
| **Use `context.Logger`** | The optimization context provides a logger for important diagnostic info. |
| **Use `context.Snapshot`** | `OptimizationContext.Snapshot` (a `SystemSnapshot`) gives system info: RAM, GPU, CPU, OS. Use it for conditional logic. |
| **Use `context.StreamService`** | For optimizations that need to download remote resources (e.g. power plans). |
| **Declare a `Condition` if needed** | Gate the optimization on Windows version or hardware — see [The Condition System](#the-condition-system). |
-
### Available Service Providers
-These **static** classes handle logging, error handling, and automatic revert step recording.
+Stateless services are **static** — call them directly, no `new`, no allocation.
+`ShellService` is a DI singleton (it reads the shell timeout from settings on every call);
+it reaches optimizations through `OptimizationContext.Shell`.
+All of them handle logging, error handling, and revert recording through the explicit `OpCall`.
| Service | Key Methods | Why It's Used |
|---|---|---|
-| **`RegistryService`** | `Write()`, `Read<T>()`, `DeleteValue()`, `CreateSubKey()`, `DeleteSubKeyTree()`, `KeyExists()`, `CleanupEmptyKeys()` | Read/write/delete registry keys. Backs up original values for revert. Supports batch writes via params array. |
-| **`ShellService`** | `CMDAsync()`, `PowerShellAsync()`, `CMD()` (sync), `PowerShell()` (sync) | Run CMD or PowerShell commands. Prefer async variants. Optional `revertCommand` parameter for undo. See `ShellPolicy` for non-standard exit codes. |
-| **`ScheduledTaskService`** | `DisableTask()`, `EnableTask()`, `IsTaskEnabled()`, `DeleteTask()`, `GetAllTasks()`, `RegisterTask()`, `RunTask()`, `StopTask()` | Manage Windows Scheduled Tasks. |
-| **`ServiceProcessService`** | `ChangeServiceStartupTypeAsync()`, `GetStartupTypeAsync()` | Manage Windows Services. Always use async variants. Supports batch changes via params array. |
+| **`RegistryService`** (static) | `Write()`, `Read<T>()`, `DeleteValue()`, `CreateSubKey()`, `DeleteSubKeyTree()`, `KeyExists()`, `CleanupEmptyKeys()` | Read/write/delete registry keys. Backs up original values for revert. Supports batch writes via params array. |
+| **`context.Shell`** (`ShellService`) | `CMDAsync()`, `PowerShellAsync()` (record a change), `QueryCMDAsync()`, `QueryPowerShellAsync()` (read-only) | Run CMD or PowerShell commands. Prefer the async variants. Pass a `revertCommand` string, or an `IRevertStep`, for undo. See `ShellPolicy` for non-standard exit codes. |
+| **`ScheduledTaskService`** (static) | `DisableTask()`, `EnableTask()`, `IsTaskEnabled()`, `DeleteTask()`, `GetAllTasks()`, `RegisterTask()`, `RunTask()`, `StopTask()` | Manage Windows Scheduled Tasks. |
+| **`ServiceProcessService`** (static) | `ChangeServiceStartupTypeAsync()`, `GetStartupTypeAsync()` | Manage Windows Services. Always use async variants. Supports batch changes via array overload. |
-> **Methods accepting multiple items via params**: Most write/change methods accept a params array of items (e.g., `RegistryService.Write(item1, item2, item3)`). This is more efficient than multiple individual calls.
+> **Methods accepting multiple items via params**: Most write/change methods accept a params array of items (e.g., `RegistryService.Write(context, item1, item2, item3)`). This is more efficient than multiple individual calls.
-Example usage:
+Every mutating call takes the `OpCall` explicitly and returns an
+`OpResult`. Reads take an optional call for logging
+(`RegistryService.Read<T>(item, context)` or `RegistryService.Read<T>(item)` for silent reads).
```csharp
-// Sync registry writes — multiple items at once
-RegistryService.Write(
+// Sync registry writes — multiple items at once (batch: call first)
+RegistryService.Write(context,
new RegistryItem(@"HKLM\...", "Value1", 1),
new RegistryItem(@"HKLM\...", "Value2", 0)
);
-RegistryService.DeleteValue(new RegistryItem(@"HKCU\...", "OldValue"));
+// Single item: item first, call last
+RegistryService.DeleteValue(new RegistryItem(@"HKCU\...", "OldValue"), context);
-// Async service changes — multiple services at once
+// Async service changes — batch via array overload (items, call)
await ServiceProcessService.ChangeServiceStartupTypeAsync(
- new ServiceItem("DiagTrack", ServiceStartupType.Disabled),
- new ServiceItem("dmwappushservice", ServiceStartupType.Disabled)
-);
+ [new ServiceItem("DiagTrack", ServiceStartupType.Disabled),
+ new ServiceItem("dmwappushservice", ServiceStartupType.Disabled)],
+ context);
// Async shell command with revert command
-var result = await ShellService.CMDAsync(
+var result = await context.Shell.CMDAsync(
"powercfg /h off",
+ context,
"powercfg /h on" // revert command stored for undo
);
+if (!result.Ok)
+{
+ context.Logger.LogError("Hibernation tweak failed: {Error}", result.Error);
+ return context.Changes.ToApplyResult();
+}
-// Async PowerShell
-var usbStates = await ShellService.PowerShellAsync(
- "Get-CimInstance -Namespace root\\wmi -ClassName MSPower_DeviceEnable"
-);
+// Async PowerShell (read-only — nothing recorded, nothing to undo)
+var usbStates = await context.Shell.QueryPowerShellAsync(
+ "Get-CimInstance -Namespace root\\wmi -ClassName MSPower_DeviceEnable",
+ context.Logger);
+```
+
+### Before/After: a GPU-style Registry Optimization
+
+Before (stale — do not copy): static call, no explicit call context,
+result derived from hidden state.
+
+```csharp
+// BEFORE — stale execution model, do not use
+RegistryService.Write(new RegistryItem(@"HKLM\...", "Value", 1));
+return CompleteFromScope();
+```
+
+After: static provider, explicit `OpCall` (`context`),
+`return context.Changes.ToApplyResult();`. This is the GPU-tweak shape
+from `Domain/Optimizations/Categories/Gpu.cs` (`GpuRegistryOptimization`):
+
+```csharp
+public override Task<ApplyResult> ApplyAsync(
+ IProgress<ProcessingProgress> progress,
+ OptimizationContext context)
+{
+ foreach (var gpu in context.Snapshot.Gpus.Where(g =>
+ g.Vendor == Vendor && !string.IsNullOrEmpty(g.DeviceId)))
+ {
+ if (!Gpu.TryParseDeviceIdToIndex(gpu.DeviceId, out var index))
+ {
+ context.Logger.LogWarning(
+ "Invalid DeviceId for GPU {GpuName} ({DeviceId})",
+ gpu.Name,
+ gpu.DeviceId);
+ continue;
+ }
+
+ var path = $@"HKLM\SYSTEM\CurrentControlSet\Control\Class\"
+ + $@"{{4d36e968-e325-11ce-bfc1-08002be10318}}\{index:D4}";
+
+ RegistryService.Write(context, CreateItems(path).ToArray());
+ context.Logger.LogInformation(
+ "Applied {Optimization} for GPU {DeviceId}",
+ GetType().Name,
+ gpu.DeviceId);
+ }
+
+ return Task.FromResult(context.Changes.ToApplyResult());
+}
+```
+
+`OpResult` error flow: each provider call returns `OpResult`
+(`Ok`, optional `Revert`, `Error`/`ErrorDetail`). On failure the
+provider already recorded the `Change` (with `Error` plus a
+`Func<OpCall, Task<OpResult>>` retry closure) into
+`context.Changes`, so check `result.Ok` when you need to branch, and
+always finish with `context.Changes.ToApplyResult()`.
+
+Retry shape (what the failure dialog runs per failed step):
+
+```csharp
+var retryChanges = new ChangeSet();
+var retryCall = new OpCall { Changes = retryChanges, Logger = logger };
+OpResult retryOutcome = await step.Retry(retryCall).ConfigureAwait(false);
+bool success = retryOutcome.Ok;
```
### Handling Asynchronous Operations
@@ -378,9 +451,9 @@ public override Task<ApplyResult> ApplyAsync(
IProgress<ProcessingProgress> progress,
OptimizationContext context)
{
- RegistryService.Write(new RegistryItem(@"HKLM\...", "Value", 1));
+ RegistryService.Write(new RegistryItem(@"HKLM\...", "Value", 1), context);
context.Logger.LogInformation("Applied tweak");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
```
@@ -389,11 +462,34 @@ But if you use any async provider (service, shell, task), always `await` them:
```csharp
public override async Task<ApplyResult> ApplyAsync(...)
{
- await ServiceProcessService.ChangeServiceStartupTypeAsync(...);
- return CompleteFromScope();
+ await ServiceProcessService.ChangeServiceStartupTypeAsync(item, context);
+ await context.Shell.CMDAsync("powercfg /h off", context, "powercfg /h on");
+ return context.Changes.ToApplyResult();
}
```
+### The Execution Model
+
+There is one execution path. An optimization extends `BaseOptimization`, is decorated with
+`[Optimization]`, and implements `ApplyAsync`. Providers record their effect into
+`context.Changes` (a `ChangeSet`) and return an `OpResult`; `OptimizationService` persists
+revert data and builds the UI result. Do not add a second framework, and do not write a
+second implementation of a Windows operation.
+
+Providers reached through `context`:
+
+| Provider | Records | Notes |
+|---|---|---|
+| `RegistryService` (static) | `RegistryRevertStep` | `Write` / `DeleteValue` / `CreateSubKey` / `DeleteSubKeyTree` |
+| `ServiceProcessService` (static) | `ServiceRevertStep` | sc.exe; access-denied is a reported failure, never a silent success |
+| `ScheduledTaskService` (static) | `ScheduledTaskRevertStep` | enable/disable, run/stop, register |
+| `context.Shell` (`ShellService`) | `ShellRevertStep` | pass a `revertCommand` with `CMDAsync`/`PowerShellAsync` |
+
+Rules:
+
+- **Never throw for a per-step failure.** Record it (`OpResult`) so sibling steps still run and the step stays retryable.
+- **`OptimizationService` owns persistence and retries.** Do not call `RevertManager` from an optimization.
+
### Create a New Category
Only if your optimizations don't fit any existing category. Avoid hyper-specific categories.
@@ -413,15 +509,13 @@ public abstract class GpuRegistryOptimization : BaseOptimization
{
protected abstract GpuVendor Vendor { get; }
protected abstract IReadOnlyList<RegistryItem> CreateItems(string registryPath);
-
public override Task<ApplyResult> ApplyAsync(...)
{
foreach (var gpu in context.Snapshot.Gpus.Where(g => g.Vendor == Vendor))
{
var path = $@"HKLM\...\{index:D4}";
- RegistryService.Write(CreateItems(path).ToArray());
+ RegistryService.Write(context, CreateItems(path).ToArray());
}
- return Task.FromResult(CompleteFromScope());
}
}
```
@@ -612,28 +706,24 @@ public class MouseAcceleration : BaseCustomizeSetting
{
return Task.Run(() =>
{
- var speed = RegistryService.Read<string>(new RegistryItem(Path, "MouseSpeed"));
- var t1 = RegistryService.Read<string>(new RegistryItem(Path, "MouseThreshold1"));
- var t2 = RegistryService.Read<string>(new RegistryItem(Path, "MouseThreshold2"));
+ var reg = new RegistryService();
+ var speed = reg.Read<string>(new RegistryItem(Path, "MouseSpeed"));
+ var t1 = reg.Read<string>(new RegistryItem(Path, "MouseThreshold1"));
+ var t2 = reg.Read<string>(new RegistryItem(Path, "MouseThreshold2"));
return (int.TryParse(speed, out var s) && s != 0)
|| (int.TryParse(t1, out var a) && a != 0)
|| (int.TryParse(t2, out var b) && b != 0);
});
}
- public override async Task ApplyAsync(object? value)
+ public override async Task ApplyAsync(object? value, OpCall call)
{
var isOn = value is bool b && b;
- RegistryService.Write(new RegistryItem(Path, "MouseSpeed", isOn ? "1" : "0"));
- RegistryService.Write(new RegistryItem(Path, "MouseThreshold1", isOn ? "6" : "0"));
- RegistryService.Write(new RegistryItem(Path, "MouseThreshold2", isOn ? "10" : "0"));
+ RegistryService.Write(new RegistryItem(Path, "MouseSpeed", isOn ? "1" : "0"), call);
+ RegistryService.Write(new RegistryItem(Path, "MouseThreshold1", isOn ? "6" : "0"), call);
+ RegistryService.Write(new RegistryItem(Path, "MouseThreshold2", isOn ? "10" : "0"), call);
if (NeedsPostAction)
- await ExecutePostActionAsync();
- }
-
- protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.Default;
-}
```
> When you override `ApplyAsync`, you **must** call `await ExecutePostActionAsync()` yourself (guarded by `NeedsPostAction`). The base class only does this automatically for the default `RegistryToggles`-based and dropdown-binding-based paths.
@@ -931,7 +1021,7 @@ services.AddSingleton<UpdaterService>();
services.AddSingleton<IRegistryWatcher, RegistryWatcher>();
```
-> This is a snapshot for orientation — `App.xaml.cs` is the source of truth for the current registrations. Also note the startup calls: `ShellService.Init(appOptionsMonitor)` and `WmiHelper.Initialize()`, and the exposed `App.AppHost` property used to resolve transient dialogs.
+> This is a snapshot for orientation — `App.xaml.cs` is the source of truth for the current registrations. Also note the startup calls: `RevertManager.RemoveOrphanedTempFiles(_logger)` (stale `.tmp` sweep) and `WmiHelper.Initialize()`, and the exposed `App.AppHost` property used to resolve transient dialogs.
### System Services Reference
@@ -955,44 +1045,43 @@ Every applied optimization creates a JSON file at `%localappdata%\optimizerDuck\
### How It Works
```
-ApplyAsync()
- │
- ├─ ExecutionScope.Begin(optimization, logger) ← creates ambient AsyncLocal scope
- │
- ├─ RegistryService.Write(...) ← auto-records RegistryRevertStep
- ├─ ServiceProcessService.ChangeServiceStartupTypeAsync(...) ← auto-records ServiceRevertStep
- ├─ ShellService.CMDAsync(...) ← auto-records ShellRevertStep
+ApplyAsync(progress, context) ← context IS the OpCall (Changes + Logger + CancellationToken)
│
- ├─ CompleteFromScope() → ApplyResult ← derived from recorded steps
+ ├─ RegistryService.Write(item, context) ← records Change + RegistryRevertStep, returns OpResult
+ ├─ await ServiceProcessService.ChangeServiceStartupTypeAsync(item, context) ← records Change + ServiceRevertStep
+ ├─ await context.Shell.CMDAsync(cmd, context, revertCmd) ← records Change + ShellRevertStep
│
- └─ ExecutionScope disposes → RevertManager.SaveRevertDataAsync()
+ └─ return context.Changes.ToApplyResult(); ← derived from recorded changes
+
+OptimizationService.ApplyAsync saves context.Changes via RevertManager.SaveRevertDataAsync().
```
-### Scope Variants
+### Change Recording
-| Method | Purpose |
+| Concept | Purpose |
|---|---|
-| `ExecutionScope.Begin(optimization, logger)` | Creates a persistable scope for a real apply. |
-| `ExecutionScope.BeginForLogging(logger)` | Logging only — records steps but never persists revert data. |
-| `ExecutionScope.BeginForCapture(logger)` | For retry: captures steps with `OptimizationId = Guid.Empty`, later re-assigned to the real scope. |
+| `OpCall` | Explicit per-operation context: `Changes`, `Logger`, `CancellationToken`. The `OptimizationContext` passed to `ApplyAsync` is one — pass it straight through. |
+| `ChangeSet` | Thread-safe collector. Providers append via `call.Changes.Add(key, name, description, ok, revert, error)`. |
+| `OpResult` | Single-operation outcome (`Ok`, `Revert`, `Error`, `ErrorDetail`). Check `result.Ok`; log `result.Error`. |
+| `context.Changes.ToApplyResult()` | Maps recorded changes to `ApplyResult`. Any success (full or partial) is success; total failure carries the first error. |
### Step Types
| Step Type | Records | Automatically Created By |
|---|---|---|
-| **`RegistryRevertStep`** | Original registry value before change | `RegistryService.Write()`, `DeleteValue()`, `CreateSubKey()`, `DeleteSubKeyTree()` |
-| **`ServiceRevertStep`** | Original service startup type | `ServiceProcessService.ChangeServiceStartupTypeAsync()` |
-| **`ScheduledTaskRevertStep`** | Original task state (enabled/disabled) | `ScheduledTaskService.DisableTask()`, `EnableTask()` |
-| **`ShellRevertStep`** | Shell command to reverse the change | `ShellService.CMDAsync()`, `PowerShellAsync()` — pass a `revertCommand` parameter |
-| **`UsbPowerRevertStep`** | USB power settings (per-device) | USB-related optimizations (manual via `ExecutionScope.RecordStep()`) |
+| **`RegistryRevertStep`** | Original registry value before change | `RegistryService.Write()`, `DeleteValue()`, `CreateSubKey()`, `DeleteSubKeyTree()` (with explicit `OpCall`) |
+| **`ServiceRevertStep`** | Original service startup type | `ServiceProcessService.ChangeServiceStartupTypeAsync()` (with explicit `OpCall`) |
+| **`ScheduledTaskRevertStep`** | Original task state (enabled/disabled) | `ScheduledTaskService.DisableTask()`, `EnableTask()` (with explicit `OpCall`) |
+| **`ShellRevertStep`** | Shell command to reverse the change | `context.Shell.CMDAsync()`, `PowerShellAsync()` — pass a `revertCommand` parameter |
+| **`UsbPowerRevertStep`** | USB power settings (per-device) | USB-related optimizations (manual via `context.Changes.Add(...)`) |
### Adding a Revert Command to Shell Calls
-When calling `CMDAsync` or `PowerShellAsync`, you can optionally pass a `revertCommand` parameter that gets saved for undo:
+When calling `CMDAsync` or `PowerShellAsync`, you can optionally pass a `revertCommand` that gets saved for undo:
```csharp
// The revert command "powercfg /h on" will be stored to reverse this change
-await ShellService.CMDAsync("powercfg /h off", "powercfg /h on");
+await context.Shell.CMDAsync("powercfg /h off", context, "powercfg /h on");
```
### Revert Data Format
@@ -1004,26 +1093,26 @@ await ShellService.CMDAsync("powercfg /h off", "powercfg /h on");
"OptimizationName": "DisableTelemetry",
"AppliedAt": "2026-06-02T12:00:00Z",
"Steps": [
- { "Index": 0, "Type": "Registry", "Data": { "..." } },
- null, // null gap = failed step at this index
+ { "Index": 1, "Type": "Registry", "Data": { "..." } },
{ "Index": 2, "Type": "Service", "Data": { "..." } }
]
}
```
+Compact layout: only successful steps persist, each with a fresh index — no null gaps. Re-apply appends; recovered retry steps append via `AppendRevertStepAsync` (never overwrite).
+
### Key Details
- **Applied state** is inferred from file presence on disk (`RevertManager.IsAppliedAsync(id)`).
-- **Atomic writes**: writes to `.tmp` then `File.Replace()` — crash-safe.
-- **Concurrent access**: per-file `SemaphoreSlim` locks prevent race conditions; 30-second timeout.
-- **`ExecutionScope`** uses `AsyncLocal<ExecutionScope?>` for ambient step tracking. No need to pass context through parameters.
+- **Atomic writes**: `.tmp` via `FileStream(WriteThrough)` + fsync, then `File.Replace()` — crash-safe. Stale `.tmp` files are swept at startup.
+- **Concurrent access**: per-file `SemaphoreSlim` locks prevent race conditions; 30-second timeout. Lock entries are never disposed while in use.
- **Revert executes steps in reverse order** (last applied = first reverted).
-- **Partial success**: revert continues even if some steps fail. Failed steps get retry actions recorded.
-- **Retry**: `OptimizationService.RetryFailedStepsAsync()` can retry individual failed steps; `RecordStepAtIndex()` preserves the original index layout.
-- **Upsert**: `RevertManager.UpsertRevertStepAtIndexAsync()` can add/replace revert steps at specific indices (used during retry).
+- **Partial success**: revert continues even if some steps fail. Failed steps carry retry actions.
+- **Retry**: `OptimizationService.RetryFailedStepsWithResultsAsync()` re-invokes `Retry` with a fresh `OpCall`; recovered steps append via `AppendRevertStepAsync`.
+- **Verification**: every revert step verifies its own effect inside `ExecuteAsync` (registry read-back, service re-query, task re-check). Access-denied is failure; unknown step types fail loudly instead of vanishing.
- **Step registry**: Revert step deserialization uses reflection-based `_stepRegistry` — new step types auto-register by implementing `IRevertStep` with a static `FromData(JObject)` method.
-> **Important**: When you call provider services (`RegistryService.Write`, `ShellService.CMDAsync`, etc.), revert steps are recorded automatically. Do NOT manually create revert steps unless you're implementing a custom provider (like `UsbPowerRevertStep`).
+> **Important**: When you call provider services (`RegistryService.Write`, `context.Shell.CMDAsync`, etc. with the `OpCall`), revert steps are recorded automatically. Do NOT manually create revert steps unless you're implementing a custom provider (like `UsbPowerRevertStep`, recorded via `context.Changes.Add(...)`).
---
@@ -1095,10 +1184,9 @@ public class MyOptimizationTests
{
var optimization = new TestOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep("Test", "Step 1", true);
- return Task.FromResult(ApplyResult.True());
+ args.context.Changes.Add("Test", "Step 1", true);
},
};
@@ -1111,11 +1199,16 @@ public class MyOptimizationTests
private static OptimizationService CreateService()
{
return new OptimizationService(
- new RevertManager(NullLogger<RevertManager>.Instance, NullLoggerFactory.Instance),
+ new RevertManager(
+ NullLogger<RevertManager>.Instance,
+ new ShellService(new ProcessRunner(120000)),
+ TimeProvider.System
+ ),
NullLoggerFactory.Instance,
new SystemInfoService(NullLogger<SystemInfoService>.Instance),
new StreamService(NullLogger<StreamService>.Instance),
null!,
+ new ShellService(new ProcessRunner(120000)),
NullLogger<OptimizationService>.Instance
);
}
@@ -1172,14 +1265,14 @@ public class MyOptimizationTests
- Services, ViewModels, and Pages are registered as singletons in `App.xaml.cs`.
- Use constructor injection: `public class Foo(Bar bar, Baz baz)` or `public class Foo(ILogger<Foo> logger)`.
-- Static provider services (`RegistryService`, `ShellService`, `ScheduledTaskService`, `ServiceProcessService`) are NOT injected — access them directly.
+- `ShellService` + `ProcessRunner` are DI singletons. `RegistryService`, `ScheduledTaskService`, `ServiceProcessService` are **static** — call them directly. Revert steps that run commands receive the app shell service from `RevertManager` through `IRevertStep.ExecuteAsync(ShellService, ILogger)`, so the configured timeout applies to undo as well.
- Test doubles are hand-written (no mocking libraries).
### Error Handling
| Layer | Practice |
|---|---|
-| **Optimizations** | Return `ApplyResult.False("reason")` instead of throwing. Let `ExecutionScope` handle step-level failure tracking. |
+| **Optimizations** | Return `ApplyResult.False("reason")` instead of throwing for whole-operation failures. Step-level failures flow through `OpResult` into `call.Changes` automatically. |
| **Provider services** | Use try/catch around system calls, log errors. Record failed steps with retry actions. |
| **ViewModels** | Catch exceptions in command handlers, show user-friendly snackbars. |
| **Conditions** | Return `ConditionResult.Error()` or throw — `ConditionEvaluator` catches and maps to `Error` (which never blocks). |
@@ -1412,7 +1505,7 @@ Check that the optimization's `Id` GUID hasn't changed. Revert files are keyed b
1. Create a new class in `Domain/Revert/Steps/` that implements `IRevertStep`.
2. Add a static `FromData(JObject data)` method for deserialization.
3. The `RevertManager`'s reflection-based `_stepRegistry` will auto-discover it.
-4. Record it via `ExecutionScope.RecordStep()` with your step as the `revertStep` parameter.
+4. Record it via `call.Changes.Add(key, name, description, ok, revertStep)` with your step as the `revertStep` parameter.
### How does the app handle crash safety?
diff --git a/optimizerDuck.Test/Core/DependencyInjectionTests.cs b/optimizerDuck.Test/Core/DependencyInjectionTests.cs
new file mode 100644
index 0000000..e1ae755
--- /dev/null
+++ b/optimizerDuck.Test/Core/DependencyInjectionTests.cs
@@ -0,0 +1,40 @@
+namespace optimizerDuck.Test.Core;
+
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Services.Optimization.Providers;
+using optimizerDuck.Services.Revert;
+
+/// <summary>
+/// Guards the composition root: the application graph must build and validate the same
+/// way the app host validates it at startup, so a broken registration fails here instead
+/// of on a user's machine.
+/// </summary>
+public class DependencyInjectionTests
+{
+ /// <summary>
+ /// The application graph is registered separately from the host so it can be built
+ /// here. Pages are created lazily on navigation and need a live WPF dispatcher, so
+ /// only the non-UI registrations are asserted.
+ /// </summary>
+ [Fact]
+ public void ApplicationGraph_BuildsWithoutAPageFactoryCycle()
+ {
+ var configuration = new ConfigurationBuilder().Build();
+
+ var services = new ServiceCollection();
+ services.AddSingleton<ILoggerFactory, NullLoggerFactory>();
+ services.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>));
+ services.AddOptimizerApplication(configuration);
+
+ using var provider = services.BuildServiceProvider(
+ new ServiceProviderOptions { ValidateOnBuild = true, ValidateScopes = true }
+ );
+
+ Assert.NotNull(provider.GetRequiredService<ShellService>());
+ Assert.NotNull(provider.GetRequiredService<ProcessRunner>());
+ Assert.NotNull(provider.GetRequiredService<RevertManager>());
+ }
+}
diff --git a/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs b/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs
index 6d2de0d..49be9c8 100644
--- a/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs
+++ b/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs
@@ -2,9 +2,11 @@ using System.Collections.ObjectModel;
using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Win32;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Customize.Models;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Services.Configuration;
using optimizerDuck.Services.Optimization.Providers;
@@ -16,6 +18,8 @@ public class BaseCustomizeSettingTests : IDisposable
{
private const string TestKeyPath = @"HKCU\Software\TestOptimizerDuckCustomize";
+ private static OpCall NewCall() => new() { Logger = NullLogger.Instance };
+
private class TestCustomizeSetting : BaseCustomizeSetting
{
protected override IEnumerable<RegistryToggle> RegistryToggles =>
@@ -108,7 +112,7 @@ public class BaseCustomizeSettingTests : IDisposable
{
var setting = new TestCustomizeSetting { OwnerType = typeof(TestCustomizeSetting) };
- await setting.ApplyAsync(true);
+ Assert.True((await setting.ApplyAsync(true, NewCall())).Ok);
var value = RegistryService.Read<int>(new RegistryItem(TestKeyPath, "TestValue"));
Assert.Equal(1, value);
@@ -119,7 +123,7 @@ public class BaseCustomizeSettingTests : IDisposable
{
var setting = new TestCustomizeSetting { OwnerType = typeof(TestCustomizeSetting) };
- await setting.ApplyAsync(false);
+ Assert.True((await setting.ApplyAsync(false, NewCall())).Ok);
var value = RegistryService.Read<int>(new RegistryItem(TestKeyPath, "TestValue"));
Assert.Equal(0, value);
@@ -135,12 +139,12 @@ public class BaseCustomizeSettingTests : IDisposable
Assert.False(initialState);
// Enable
- await setting.ApplyAsync(true);
+ Assert.True((await setting.ApplyAsync(true, NewCall())).Ok);
var enabledState = await setting.GetStateAsync();
Assert.True(enabledState);
// Disable
- await setting.ApplyAsync(false);
+ Assert.True((await setting.ApplyAsync(false, NewCall())).Ok);
var disabledState = await setting.GetStateAsync();
Assert.False(disabledState);
}
@@ -153,13 +157,13 @@ public class BaseCustomizeSettingTests : IDisposable
// Perform multiple rapid toggles
for (int i = 0; i < 10; i++)
{
- await setting.ApplyAsync(true);
+ Assert.True((await setting.ApplyAsync(true, NewCall())).Ok);
var enabledValue = RegistryService.Read<int>(
new RegistryItem(TestKeyPath, "TestValue")
);
Assert.Equal(1, enabledValue);
- await setting.ApplyAsync(false);
+ Assert.True((await setting.ApplyAsync(false, NewCall())).Ok);
var disabledValue = RegistryService.Read<int>(
new RegistryItem(TestKeyPath, "TestValue")
);
@@ -230,12 +234,12 @@ public class BaseCustomizeSettingTests : IDisposable
{
var setting = new TestCustomizeSetting { OwnerType = typeof(TestCustomizeSetting) };
- await setting.ApplyAsync(true);
+ Assert.True((await setting.ApplyAsync(true, NewCall())).Ok);
var result = await setting.GetStateWithRetryAsync(maxRetries: 3, delayMs: 10);
Assert.True(result);
- await setting.ApplyAsync(false);
+ Assert.True((await setting.ApplyAsync(false, NewCall())).Ok);
result = await setting.GetStateWithRetryAsync(maxRetries: 3, delayMs: 10);
Assert.False(result);
@@ -403,7 +407,7 @@ public class BaseCustomizeSettingTests : IDisposable
// ExecutePostActionAsync entirely. We confirm the gate behaviour:
// NeedsPostAction is false, so no refresh runs.
Assert.False(GetNeedsPostAction(setting));
- await setting.ApplyAsync(false); // must not throw
+ Assert.True((await setting.ApplyAsync(false, NewCall())).Ok); // must not throw
}
[Fact]
@@ -422,8 +426,8 @@ public class BaseCustomizeSettingTests : IDisposable
foreach (var setting in settings)
{
- await setting.ApplyAsync(true);
- await setting.ApplyAsync(false);
+ Assert.True((await setting.ApplyAsync(true, NewCall())).Ok);
+ Assert.True((await setting.ApplyAsync(false, NewCall())).Ok);
}
}
@@ -482,7 +486,7 @@ public class BaseCustomizeSettingTests : IDisposable
[Fact]
public void RegistryToggle_GetState_ReturnsTrueWhenValueMatchesOnValues()
{
- RegistryService.Write(new RegistryItem(TestKeyPath, "OnValTest", 1));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "OnValTest", 1));
var toggle = new RegistryToggle
{
@@ -500,7 +504,7 @@ public class BaseCustomizeSettingTests : IDisposable
[Fact]
public void RegistryToggle_GetState_ReturnsFalseWhenValueMatchesOffValues()
{
- RegistryService.Write(new RegistryItem(TestKeyPath, "OffValTest", 0));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "OffValTest", 0));
var toggle = new RegistryToggle
{
@@ -555,11 +559,11 @@ public class BaseCustomizeSettingTests : IDisposable
OffValues = [0],
};
- toggle.SetState(true);
+ toggle.SetState(true, NewCall());
var value = RegistryService.Read<int>(new RegistryItem(TestKeyPath, "SetStateTest"));
Assert.Equal(1, value);
- toggle.SetState(false);
+ toggle.SetState(false, NewCall());
value = RegistryService.Read<int>(new RegistryItem(TestKeyPath, "SetStateTest"));
Assert.Equal(0, value);
@@ -570,7 +574,7 @@ public class BaseCustomizeSettingTests : IDisposable
public void RegistryToggle_SetState_DeletesKeyWhenFirstValueIsNull()
{
// First write a value
- RegistryService.Write(new RegistryItem(TestKeyPath, "NullSetTest", 1));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "NullSetTest", 1));
var toggle = new RegistryToggle
{
@@ -580,7 +584,7 @@ public class BaseCustomizeSettingTests : IDisposable
OffValues = [0],
};
- toggle.SetState(true); // Should delete the key
+ toggle.SetState(true, NewCall()); // Should delete the key
var value = RegistryService.Read<object>(new RegistryItem(TestKeyPath, "NullSetTest"));
Assert.Null(value);
@@ -592,7 +596,7 @@ public class BaseCustomizeSettingTests : IDisposable
public void RegistryToggle_GetState_MatchesMultipleOnValues()
{
// Value 1 → ON
- RegistryService.Write(new RegistryItem(TestKeyPath, "MultiOnTest", 1));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "MultiOnTest", 1));
var toggle = new RegistryToggle
{
Path = TestKeyPath,
@@ -603,7 +607,7 @@ public class BaseCustomizeSettingTests : IDisposable
Assert.True(toggle.GetState());
// Value 2 → also ON
- RegistryService.Write(new RegistryItem(TestKeyPath, "MultiOnTest", 2));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "MultiOnTest", 2));
Assert.True(toggle.GetState());
CleanupTestKeys();
@@ -662,10 +666,10 @@ public class BaseCustomizeSettingTests : IDisposable
{
var setting = new TestDropdownSetting { OwnerType = typeof(TestDropdownSetting) };
- RegistryService.Write(new RegistryItem(TestKeyPath, "DropdownTest", 1));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "DropdownTest", 1));
Assert.Equal(1, setting.CurrentValue);
- RegistryService.Write(new RegistryItem(TestKeyPath, "DropdownTest", 2));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "DropdownTest", 2));
Assert.Equal(2, setting.CurrentValue);
CleanupTestKeys();
@@ -676,7 +680,7 @@ public class BaseCustomizeSettingTests : IDisposable
{
var setting = new TestDropdownSetting { OwnerType = typeof(TestDropdownSetting) };
- RegistryService.Write(new RegistryItem(TestKeyPath, "DropdownTest", 99));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "DropdownTest", 99));
Assert.Equal(99, setting.CurrentValue);
CleanupTestKeys();
@@ -687,11 +691,11 @@ public class BaseCustomizeSettingTests : IDisposable
{
var setting = new TestDropdownSetting { OwnerType = typeof(TestDropdownSetting) };
- await setting.ApplyAsync(1);
+ Assert.True((await setting.ApplyAsync(1, NewCall())).Ok);
var value = RegistryService.Read<int>(new RegistryItem(TestKeyPath, "DropdownTest"));
Assert.Equal(1, value);
- await setting.ApplyAsync(2);
+ Assert.True((await setting.ApplyAsync(2, NewCall())).Ok);
value = RegistryService.Read<int>(new RegistryItem(TestKeyPath, "DropdownTest"));
Assert.Equal(2, value);
@@ -705,7 +709,7 @@ public class BaseCustomizeSettingTests : IDisposable
{
var setting = new TestDropdownSetting { OwnerType = typeof(TestDropdownSetting) };
- RegistryService.Write(new RegistryItem(TestKeyPath, "DropdownTest", 1));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "DropdownTest", 1));
var effective = setting.Options;
@@ -721,7 +725,7 @@ public class BaseCustomizeSettingTests : IDisposable
{
var setting = new TestDropdownSetting { OwnerType = typeof(TestDropdownSetting) };
- RegistryService.Write(new RegistryItem(TestKeyPath, "DropdownTest", 99));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "DropdownTest", 99));
var effective = setting.Options;
@@ -743,10 +747,10 @@ public class BaseCustomizeSettingTests : IDisposable
{
var setting = new TestDropdownSetting { OwnerType = typeof(TestDropdownSetting) };
- RegistryService.Write(new RegistryItem(TestKeyPath, "DropdownTest", 99));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "DropdownTest", 99));
Assert.Equal(3, setting.Options!.Count);
- RegistryService.Write(new RegistryItem(TestKeyPath, "DropdownTest", 2));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "DropdownTest", 2));
var effective = setting.Options;
@@ -763,10 +767,10 @@ public class BaseCustomizeSettingTests : IDisposable
{
var setting = new TestDropdownSetting { OwnerType = typeof(TestDropdownSetting) };
- RegistryService.Write(new RegistryItem(TestKeyPath, "DropdownTest", 99));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "DropdownTest", 99));
Assert.Equal(99, setting.Options![2].Value);
- RegistryService.Write(new RegistryItem(TestKeyPath, "DropdownTest", 123));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "DropdownTest", 123));
var effective = setting.Options;
@@ -786,7 +790,7 @@ public class BaseCustomizeSettingTests : IDisposable
// WPF can select it) is appended, labeled distinctly from "Custom".
var setting = new TestDropdownSetting { OwnerType = typeof(TestDropdownSetting) };
- RegistryService.DeleteValue(new RegistryItem(TestKeyPath, "DropdownTest"));
+ RegistryService.DeleteValue(NewCall(), new RegistryItem(TestKeyPath, "DropdownTest"));
var effective = setting.Options;
@@ -810,8 +814,10 @@ public class BaseCustomizeSettingTests : IDisposable
// declared Options (where it never exists), so nothing is written and it throws.
var setting = new TestDropdownSetting { OwnerType = typeof(TestDropdownSetting) };
- RegistryService.Write(new RegistryItem(TestKeyPath, "DropdownTest", 1));
- await setting.ApplyAsync(BaseCustomizeSetting.MissingValueSentinel);
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "DropdownTest", 1));
+ Assert.True(
+ (await setting.ApplyAsync(BaseCustomizeSetting.MissingValueSentinel, NewCall())).Ok
+ );
var value = RegistryService.Read<int>(new RegistryItem(TestKeyPath, "DropdownTest"));
Assert.Equal(1, value);
@@ -824,10 +830,10 @@ public class BaseCustomizeSettingTests : IDisposable
{
var setting = new TestDropdownSetting { OwnerType = typeof(TestDropdownSetting) };
- RegistryService.DeleteValue(new RegistryItem(TestKeyPath, "DropdownTest"));
+ RegistryService.DeleteValue(NewCall(), new RegistryItem(TestKeyPath, "DropdownTest"));
Assert.Equal(3, setting.Options!.Count);
- RegistryService.Write(new RegistryItem(TestKeyPath, "DropdownTest", 2));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "DropdownTest", 2));
var effective = setting.Options;
@@ -853,8 +859,9 @@ public class BaseCustomizeSettingTests : IDisposable
// Key A = 1 (matches "On" primary) but Key B = 0 → no full match; the raw primary
// value (1) already equals the declared "On" value, so no "Custom" duplicate.
- RegistryService.Write(new RegistryItem(TestKeyPath, "Key1", 1));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "Key1", 1));
RegistryService.Write(
+ NewCall(),
new RegistryItem(@"HKCU\Software\TestOptimizerDuckMultiKey", "Key2", 0)
);
@@ -884,7 +891,7 @@ public class BaseCustomizeSettingTests : IDisposable
// so re-reading it must always reflect the current registry value.
var setting = new TestDropdownSetting { OwnerType = typeof(TestDropdownSetting) };
- RegistryService.Write(new RegistryItem(TestKeyPath, "DropdownTest", 99));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "DropdownTest", 99));
var first = setting.Options!;
var second = setting.Options!;
@@ -921,7 +928,7 @@ public class BaseCustomizeSettingTests : IDisposable
{
var setting = new TestNotSetOptionDropdown { OwnerType = typeof(TestNotSetOptionDropdown) };
- RegistryService.DeleteValue(new RegistryItem(TestKeyPath, "NotSetOptionTest"));
+ RegistryService.DeleteValue(NewCall(), new RegistryItem(TestKeyPath, "NotSetOptionTest"));
// The declared null-binding option matches the missing state (null == null),
// so no synthetic fallback is appended; CurrentValue is the declared value.
@@ -943,11 +950,11 @@ public class BaseCustomizeSettingTests : IDisposable
{
var setting = new TestNotSetOptionDropdown { OwnerType = typeof(TestNotSetOptionDropdown) };
- RegistryService.Write(new RegistryItem(TestKeyPath, "NotSetOptionTest", 1));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "NotSetOptionTest", 1));
Assert.Equal(1, setting.CurrentValue);
// Selecting the declared "NotSet" option deletes the registry value (binding null).
- await setting.ApplyAsync("notset");
+ Assert.True((await setting.ApplyAsync("notset", NewCall())).Ok);
var value = RegistryService.Read<object>(new RegistryItem(TestKeyPath, "NotSetOptionTest"));
Assert.Null(value);
@@ -962,13 +969,13 @@ public class BaseCustomizeSettingTests : IDisposable
var setting = new TestNotSetOptionDropdown { OwnerType = typeof(TestNotSetOptionDropdown) };
// Not set → apply declared "On" → value written → apply "NotSet" → deleted again.
- RegistryService.DeleteValue(new RegistryItem(TestKeyPath, "NotSetOptionTest"));
+ RegistryService.DeleteValue(NewCall(), new RegistryItem(TestKeyPath, "NotSetOptionTest"));
Assert.Equal("notset", setting.CurrentValue);
- await setting.ApplyAsync(1);
+ Assert.True((await setting.ApplyAsync(1, NewCall())).Ok);
Assert.Equal(1, setting.CurrentValue);
- await setting.ApplyAsync("notset");
+ Assert.True((await setting.ApplyAsync("notset", NewCall())).Ok);
var value = RegistryService.Read<object>(new RegistryItem(TestKeyPath, "NotSetOptionTest"));
Assert.Null(value);
Assert.Equal("notset", setting.CurrentValue);
@@ -1011,7 +1018,7 @@ public class BaseCustomizeSettingTests : IDisposable
{
var setting = new TestMultiBindingDropdown { OwnerType = typeof(TestMultiBindingDropdown) };
- await setting.ApplyAsync(1);
+ Assert.True((await setting.ApplyAsync(1, NewCall())).Ok);
var valA = RegistryService.Read<int>(new RegistryItem(TestKeyPath, "Key1"));
var valB = RegistryService.Read<int>(
@@ -1035,15 +1042,17 @@ public class BaseCustomizeSettingTests : IDisposable
var setting = new TestMultiBindingDropdown { OwnerType = typeof(TestMultiBindingDropdown) };
// Both keys = 1 → option "On" matches
- RegistryService.Write(new RegistryItem(TestKeyPath, "Key1", 1));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "Key1", 1));
RegistryService.Write(
+ NewCall(),
new RegistryItem(@"HKCU\Software\TestOptimizerDuckMultiKey", "Key2", 1)
);
Assert.Equal(1, setting.CurrentValue);
// Key A = 1, Key B = 0 → no match → returns primary binding raw value
- RegistryService.Write(new RegistryItem(TestKeyPath, "Key1", 1));
+ RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "Key1", 1));
RegistryService.Write(
+ NewCall(),
new RegistryItem(@"HKCU\Software\TestOptimizerDuckMultiKey", "Key2", 0)
);
Assert.Equal(1, setting.CurrentValue);
@@ -1073,7 +1082,8 @@ public class BaseCustomizeSettingTests : IDisposable
{
public override object? CurrentValue => "custom";
- public override Task ApplyAsync(object? value) => Task.CompletedTask;
+ public override Task<OpResult> ApplyAsync(object? value, OpCall call) =>
+ Task.FromResult(OpResult.Success());
public override Task<bool> GetStateAsync() => Task.FromResult(true);
}
@@ -1102,7 +1112,7 @@ public class BaseCustomizeSettingTests : IDisposable
var setting = new TestMatchMissingDropdown { OwnerType = typeof(TestMatchMissingDropdown) };
// Ensure key is deleted (absent)
- RegistryService.DeleteValue(new RegistryItem(TestKeyPath, "AlignTestKey"));
+ RegistryService.DeleteValue(NewCall(), new RegistryItem(TestKeyPath, "AlignTestKey"));
// Must match "Center" (value 1) without creating synthetic "Not set" fallback
Assert.Equal(1, setting.CurrentValue);
@@ -1140,15 +1150,16 @@ public class BaseCustomizeSettingTests : IDisposable
};
// Both absent -> matches Always (0)
- RegistryService.DeleteValue(new RegistryItem(TestKeyPath, "Glom1"));
+ RegistryService.DeleteValue(NewCall(), new RegistryItem(TestKeyPath, "Glom1"));
RegistryService.DeleteValue(
+ NewCall(),
new RegistryItem(@"HKCU\Software\TestOptimizerDuckMultiKey", "Glom2")
);
Assert.Equal(0, setting.CurrentValue);
// Apply Never (2) -> writes both keys
- await setting.ApplyAsync(2);
+ Assert.True((await setting.ApplyAsync(2, NewCall())).Ok);
Assert.Equal(2, setting.CurrentValue);
Assert.Equal(2, RegistryService.Read<int>(new RegistryItem(TestKeyPath, "Glom1")));
Assert.Equal(
diff --git a/optimizerDuck.Test/Domain/Optimizations/PowerManagementTests.cs b/optimizerDuck.Test/Domain/Optimizations/PowerManagementTests.cs
index 84fb0ac..96ef48d 100644
--- a/optimizerDuck.Test/Domain/Optimizations/PowerManagementTests.cs
+++ b/optimizerDuck.Test/Domain/Optimizations/PowerManagementTests.cs
@@ -10,17 +10,17 @@ public class PowerManagementTests
[Fact]
public void RegistryPath_WithHklmPrefix_IsReadable()
{
- using var scope = ExecutionScope.BeginForLogging(NullLogger.Instance);
+ var call = new OpCall { Logger = NullLogger.Instance };
var key = $@"HKCU\SOFTWARE\OptimizerDuckTest\{Guid.NewGuid():N}";
try
{
- Assert.True(RegistryService.Write(new RegistryItem(key, "Probe", 1)));
+ Assert.True(RegistryService.Write(call, new RegistryItem(key, "Probe", 1)).Ok);
Assert.Equal(1, RegistryService.Read<int>(new RegistryItem(key, "Probe")));
}
finally
{
- RegistryService.DeleteSubKeyTree(new RegistryItem(key));
+ RegistryService.DeleteSubKeyTree(call, new RegistryItem(key));
}
}
}
diff --git a/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.cs b/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.cs
index 0db871d..397c98f 100644
--- a/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.cs
+++ b/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.cs
@@ -1,5 +1,8 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using Newtonsoft.Json.Linq;
using optimizerDuck.Domain.Exceptions;
using optimizerDuck.Domain.Revert.Steps;
+using optimizerDuck.Test.TestDoubles;
namespace optimizerDuck.Test.Domain.Revert.Steps;
@@ -14,8 +17,22 @@ public class ScheduledTaskRevertStepTests
OriginalEnabled = true,
};
- var ex = await Assert.ThrowsAsync<StepExecutionException>(() => step.ExecuteAsync());
+ var ex = await Assert.ThrowsAsync<StepExecutionException>(() =>
+ step.ExecuteAsync(TestShell.New(), NullLogger.Instance)
+ );
Assert.Contains("NonExistent", ex.Message);
}
+
+ [Fact]
+ public void FromData_MissingOriginalEnabled_ThrowsFailClosed()
+ {
+ var data = new JObject { ["FullPath"] = @"\Test\Task" };
+
+ var ex = Assert.Throws<StepExecutionException>(() =>
+ ScheduledTaskRevertStep.FromData(data)
+ );
+
+ Assert.Contains(nameof(ScheduledTaskRevertStep.OriginalEnabled), ex.Message);
+ }
}
diff --git a/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs b/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
index c699ddb..80000c0 100644
--- a/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
+++ b/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
@@ -8,6 +8,7 @@ using optimizerDuck.Domain.Revert;
using optimizerDuck.Domain.Revert.Steps;
using optimizerDuck.Domain.UI;
using optimizerDuck.Services.Optimization;
+using optimizerDuck.Services.Optimization.Providers;
using optimizerDuck.Services.Revert;
using optimizerDuck.Services.System;
using optimizerDuck.Test.TestDoubles;
@@ -30,10 +31,10 @@ public class ApplyRevertComprehensiveTests
{
var optimization = new TestOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 1: Disable service",
"Step 1: Disable service",
true,
new ShellRevertStep
@@ -42,8 +43,8 @@ public class ApplyRevertComprehensiveTests
Command = "sc config TestService start= auto",
}
);
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 2: Registry change",
"Step 2: Registry change",
true,
new ShellRevertStep
@@ -52,8 +53,8 @@ public class ApplyRevertComprehensiveTests
Command = "Set-ItemProperty -Path 'HKLM:\\Test' -Name 'Value' -Value 0",
}
);
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 3: File operation",
"Step 3: File operation",
true,
new ShellRevertStep
@@ -62,7 +63,6 @@ public class ApplyRevertComprehensiveTests
Command = "del C:\\test.txt",
}
);
- return Task.FromResult(ApplyResult.True());
},
};
@@ -128,28 +128,26 @@ public class ApplyRevertComprehensiveTests
{
var optimization = new TestOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 1: Will fail",
"Step 1: Will fail",
false,
- null,
- "Step 1 failed"
+ error: "Step 1 failed"
);
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 2: Success",
"Step 2: Success",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }
);
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 3: Success",
"Step 3: Success",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }
);
- return Task.FromResult(ApplyResult.True());
},
};
@@ -171,12 +169,10 @@ public class ApplyRevertComprehensiveTests
var data = await RevertManager.GetRevertDataAsync(optimization.Id);
Assert.NotNull(data);
- Assert.Equal(3, data!.Steps.Length);
-
- // Step 1 should be null (failed), steps 2 and 3 should exist
- Assert.Null(data.Steps[0]);
+ // Compact layout: only successful steps persist, in execution order.
+ Assert.Equal(2, data!.Steps.Length);
+ Assert.NotNull(data.Steps[0]);
Assert.NotNull(data.Steps[1]);
- Assert.NotNull(data.Steps[2]);
}
finally
{
@@ -193,29 +189,38 @@ public class ApplyRevertComprehensiveTests
{
var optimization = new TestOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 1: Success",
"Step 1: Success",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 11" }
);
- ExecutionScope.RecordStep("Shell", "Step 2: Fail", false, null, "fail 2");
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 2: Fail",
+ "Step 2: Fail",
+ false,
+ error: "fail 2"
+ );
+ args.context.Changes.Add(
+ "Step 3: Success",
"Step 3: Success",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 33" }
);
- ExecutionScope.RecordStep("Shell", "Step 4: Fail", false, null, "fail 4");
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 4: Fail",
+ "Step 4: Fail",
+ false,
+ error: "fail 4"
+ );
+ args.context.Changes.Add(
+ "Step 5: Success",
"Step 5: Success",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 55" }
);
- return Task.FromResult(ApplyResult.True());
},
};
@@ -237,27 +242,21 @@ public class ApplyRevertComprehensiveTests
var data = await RevertManager.GetRevertDataAsync(optimization.Id);
Assert.NotNull(data);
- Assert.Equal(5, data!.Steps.Length);
-
- // Verify pattern: success, fail, success, fail, success
- Assert.NotNull(data.Steps[0]);
- Assert.Null(data.Steps[1]);
- Assert.NotNull(data.Steps[2]);
- Assert.Null(data.Steps[3]);
- Assert.NotNull(data.Steps[4]);
+ // Compact layout: only the 3 successful steps persist, in order.
+ Assert.Equal(3, data!.Steps.Length);
- // Verify commands are at correct indices
+ // Verify commands are in execution order
Assert.Equal(
"exit 11",
data.Steps[0]!.Data[nameof(ShellRevertStep.Command)]?.ToString()
);
Assert.Equal(
"exit 33",
- data.Steps[2]!.Data[nameof(ShellRevertStep.Command)]?.ToString()
+ data.Steps[1]!.Data[nameof(ShellRevertStep.Command)]?.ToString()
);
Assert.Equal(
"exit 55",
- data.Steps[4]!.Data[nameof(ShellRevertStep.Command)]?.ToString()
+ data.Steps[2]!.Data[nameof(ShellRevertStep.Command)]?.ToString()
);
}
finally
@@ -275,11 +274,20 @@ public class ApplyRevertComprehensiveTests
{
var optimization = new TestOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep("Shell", "Step 1: Fail", false, null, "fail 1");
- ExecutionScope.RecordStep("Shell", "Step 2: Fail", false, null, "fail 2");
- return Task.FromResult(ApplyResult.False("All steps failed"));
+ args.context.Changes.Add(
+ "Step 1: Fail",
+ "Step 1: Fail",
+ false,
+ error: "fail 1"
+ );
+ args.context.Changes.Add(
+ "Step 2: Fail",
+ "Step 2: Fail",
+ false,
+ error: "fail 2"
+ );
},
};
@@ -443,7 +451,8 @@ public class ApplyRevertComprehensiveTests
var manager = new RevertManager(
NullLogger<RevertManager>.Instance,
- NullLoggerFactory.Instance
+ TestShell.New(),
+ TimeProvider.System
);
var result = await manager.RevertAsync(optimization);
@@ -599,7 +608,7 @@ public class ApplyRevertComprehensiveTests
Assert.NotNull(updatedData.Steps[1]); // Step 2 failed and is preserved
// Failed step should have retry action
- Assert.NotNull(result.FailedSteps[0].RetryAction);
+ Assert.NotNull(result.FailedSteps[0].Retry);
}
finally
{
@@ -719,7 +728,8 @@ public class ApplyRevertComprehensiveTests
var manager = new RevertManager(
NullLogger<RevertManager>.Instance,
- NullLoggerFactory.Instance
+ TestShell.New(),
+ TimeProvider.System
);
var result = await manager.RevertAsync(optimization);
@@ -729,14 +739,15 @@ public class ApplyRevertComprehensiveTests
// Retry the failed step - note: retry will also fail because it's still "exit 1"
var failedStep = result.FailedSteps.FirstOrDefault();
Assert.NotNull(failedStep);
- Assert.NotNull(failedStep.RetryAction);
+ Assert.NotNull(failedStep.Retry);
// Retry will fail because the command is still "exit 1"
// This is expected behavior - retry just re-executes the same command
// ExecuteAsync throws exception on failure, so we need to catch it
var exception = await Record.ExceptionAsync(async () =>
- await failedStep.RetryAction!()
- );
+ {
+ await failedStep.Retry!(new OpCall { Logger = NullLogger.Instance });
+ });
Assert.NotNull(exception); // Expected to throw
Assert.True(File.Exists(revertPath)); // Still preserved
}
@@ -759,21 +770,20 @@ public class ApplyRevertComprehensiveTests
{
var optimization = new TestOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 1",
"Step 1",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }
);
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 2",
"Step 2",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }
);
- return Task.FromResult(ApplyResult.True());
},
};
@@ -813,22 +823,21 @@ public class ApplyRevertComprehensiveTests
{
var optimization = new TestOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 1",
"Step 1",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }
);
- ExecutionScope.RecordStep("Shell", "Step 2", false, null, "Step 2 failed");
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add("Step 2", "Step 2", false, error: "Step 2 failed");
+ args.context.Changes.Add(
+ "Step 3",
"Step 3",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }
);
- return Task.FromResult(ApplyResult.True());
},
};
@@ -847,10 +856,9 @@ public class ApplyRevertComprehensiveTests
var data = await RevertManager.GetRevertDataAsync(optimization.Id);
Assert.NotNull(data);
- Assert.Equal(3, data!.Steps.Length);
+ Assert.Equal(2, data!.Steps.Length);
Assert.NotNull(data.Steps[0]);
- Assert.Null(data.Steps[1]); // Gap from failed step
- Assert.NotNull(data.Steps[2]);
+ Assert.NotNull(data.Steps[1]);
// Phase 2: Revert should only revert steps 1 and 3
var revertResult = await service.RevertAsync(optimization, progress);
@@ -872,24 +880,24 @@ public class ApplyRevertComprehensiveTests
{
var optimization = new TestOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 1",
"Step 1",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }
);
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 2",
"Step 2",
false,
null,
"fail 2",
- () =>
+ retry: rc =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ rc.Changes.Add(
+ "Step 2 retry",
"Step 2 retry",
true,
new ShellRevertStep
@@ -898,16 +906,15 @@ public class ApplyRevertComprehensiveTests
Command = "exit 0",
}
);
- return Task.FromResult(true);
+ return Task.FromResult(OpResult.Success());
}
);
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "Step 3",
"Step 3",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }
);
- return Task.FromResult(ApplyResult.True());
},
};
@@ -933,16 +940,16 @@ public class ApplyRevertComprehensiveTests
Assert.Single(retryResult.RecoveredSteps);
Assert.Equal(2, retryResult.RecoveredSteps[0].Index);
- // Phase 3: Upsert the recovered step
+ // Phase 3: Append the recovered step
var revertManager = new RevertManager(
NullLogger<RevertManager>.Instance,
- NullLoggerFactory.Instance
+ TestShell.New(),
+ TimeProvider.System
);
- await revertManager.UpsertRevertStepAtIndexAsync(
+ await revertManager.AppendRevertStepAsync(
optimization.Id,
optimization.OptimizationKey,
- retryResult.RecoveredSteps[0].Index,
- retryResult.RecoveredSteps[0].RevertStep!
+ retryResult.RecoveredSteps[0].Revert!
);
// Verify complete revert data
@@ -1068,12 +1075,14 @@ public class ApplyRevertComprehensiveTests
{
var revertManager = new RevertManager(
NullLogger<RevertManager>.Instance,
- NullLoggerFactory.Instance
+ TestShell.New(),
+ 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(
revertManager,
@@ -1081,6 +1090,7 @@ public class ApplyRevertComprehensiveTests
systemInfoService,
streamService,
contentDialogService,
+ shellService,
logger
);
}
@@ -1118,17 +1128,18 @@ public class ApplyRevertComprehensiveTests
public override string Name => "Test Optimization";
public override string ShortDescription => "Test optimization for comprehensive testing";
- public Func<
- (IProgress<ProcessingProgress> progress, OptimizationContext context),
- Task<ApplyResult>
- > ApplyImpl { get; init; } = _ => Task.FromResult(ApplyResult.True());
+ public Action<(
+ IProgress<ProcessingProgress> progress,
+ OptimizationContext context
+ )> ApplyImpl { get; init; } = _ => { };
public override Task<ApplyResult> ApplyAsync(
IProgress<ProcessingProgress> progress,
OptimizationContext context
)
{
- return ApplyImpl((progress, context));
+ ApplyImpl((progress, context));
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
diff --git a/optimizerDuck.Test/Services/Configuration/LanguageManagerTests.cs b/optimizerDuck.Test/Services/Configuration/LanguageManagerTests.cs
index c12fc48..74e3d0a 100644
--- a/optimizerDuck.Test/Services/Configuration/LanguageManagerTests.cs
+++ b/optimizerDuck.Test/Services/Configuration/LanguageManagerTests.cs
@@ -70,6 +70,28 @@ public class LanguageManagerTests : IDisposable
Assert.Contains(nameof(Loc.Direction), raisedProperties);
}
+ [Fact]
+ public void ChangeCulture_RaisesAllPropertiesChanged()
+ {
+ var raisedProperties = new List<string?>();
+ PropertyChangedEventHandler handler = (_, e) => raisedProperties.Add(e.PropertyName);
+
+ Loc.Instance.PropertyChanged += handler;
+ try
+ {
+ Loc.Instance.ChangeCulture(new CultureInfo("vi"));
+ }
+ finally
+ {
+ Loc.Instance.PropertyChanged -= handler;
+ }
+
+ // Empty property name means "all properties changed". Pathless bindings to
+ // Loc.Instance (the multi-arg {ext:Loc Key, Binding} markup) re-evaluate only on
+ // this notification, so runtime language switching depends on it.
+ Assert.Contains(string.Empty, raisedProperties);
+ }
+
[Fact]
public void ChangeCulture_RaisesIsRtlAndDirection()
{
diff --git a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
index e305784..c56c233 100644
--- a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
+++ b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
@@ -1,12 +1,15 @@
+using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Abstractions;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models;
using optimizerDuck.Domain.Revert;
using optimizerDuck.Domain.Revert.Steps;
using optimizerDuck.Domain.UI;
+using optimizerDuck.Services.Optimization.Providers;
using optimizerDuck.Services.Revert;
using optimizerDuck.Test.TestDoubles;
@@ -96,10 +99,14 @@ public class RevertManagerTests
var manager = new RevertManager(
NullLogger<RevertManager>.Instance,
- NullLoggerFactory.Instance
+ TestShell.New(),
+ TimeProvider.System
);
var op = new MockOptimization(id);
- var result = await manager.RevertAsync(op);
+ var result = await manager.RevertAsync(
+ op,
+ cancellationToken: TestContext.Current.CancellationToken
+ );
Assert.False(result.Success);
}
@@ -155,15 +162,19 @@ public class RevertManagerTests
var manager = new RevertManager(
NullLogger<RevertManager>.Instance,
- NullLoggerFactory.Instance
+ TestShell.New(),
+ TimeProvider.System
+ );
+ var result = await manager.RevertAsync(
+ new MockOptimization(id),
+ cancellationToken: TestContext.Current.CancellationToken
);
- var result = await manager.RevertAsync(new MockOptimization(id));
Assert.False(result.Success);
Assert.True(File.Exists(path));
var failedStep = Assert.Single(result.FailedSteps);
Assert.Equal(2, failedStep.Index);
- Assert.NotNull(failedStep.RetryAction);
+ Assert.NotNull(failedStep.Retry);
var updatedData = await RevertManager.GetRevertDataAsync(id);
Assert.NotNull(updatedData);
@@ -212,15 +223,19 @@ public class RevertManagerTests
var manager = new RevertManager(
NullLogger<RevertManager>.Instance,
- NullLoggerFactory.Instance
+ TestShell.New(),
+ TimeProvider.System
+ );
+ var result = await manager.RevertAsync(
+ new MockOptimization(id),
+ cancellationToken: TestContext.Current.CancellationToken
);
- var result = await manager.RevertAsync(new MockOptimization(id));
Assert.False(result.Success);
Assert.True(result.AllStepsFailed);
Assert.True(File.Exists(path));
var failedStep = Assert.Single(result.FailedSteps);
- Assert.NotNull(failedStep.RetryAction);
+ Assert.NotNull(failedStep.Retry);
}
finally
{
@@ -274,16 +289,20 @@ public class RevertManagerTests
var manager = new RevertManager(
NullLogger<RevertManager>.Instance,
- NullLoggerFactory.Instance
+ TestShell.New(),
+ TimeProvider.System
+ );
+ var result = await manager.RevertAsync(
+ new MockOptimization(id),
+ cancellationToken: TestContext.Current.CancellationToken
);
- var result = await manager.RevertAsync(new MockOptimization(id));
Assert.False(result.Success);
Assert.True(File.Exists(path));
var failedStep = Assert.Single(result.FailedSteps);
- Assert.NotNull(failedStep.RetryAction);
- Assert.True(await failedStep.RetryAction!());
+ Assert.NotNull(failedStep.Retry);
+ Assert.True((await failedStep.Retry!(new OpCall { Logger = NullLogger.Instance })).Ok);
await manager.RemoveRevertStepAtIndexAsync(id, "TestOptimization", failedStep.Index);
Assert.False(File.Exists(path));
@@ -295,6 +314,172 @@ public class RevertManagerTests
}
}
+ [Fact]
+ public async Task SaveRevertDataAsync_SecondSave_AppendsWithoutLosingFirstSave()
+ {
+ var id = Guid.NewGuid();
+ var path = Path.Combine(Shared.RevertDirectory, id + ".json");
+ var manager = new RevertManager(
+ NullLogger<RevertManager>.Instance,
+ TestShell.New(),
+ TimeProvider.System
+ );
+
+ var first = new ChangeSet();
+ first.Add("Test", "First", true, new RetryableTestRevertStep { StepId = "first" });
+
+ var second = new ChangeSet();
+ second.Add("Test", "Second", true, new RetryableTestRevertStep { StepId = "second" });
+
+ try
+ {
+ await manager.SaveRevertDataAsync(
+ first,
+ id,
+ "Test",
+ TestContext.Current.CancellationToken
+ );
+ await manager.SaveRevertDataAsync(
+ second,
+ id,
+ "Test",
+ TestContext.Current.CancellationToken
+ );
+
+ var data = await RevertManager.GetRevertDataAsync(id);
+ Assert.NotNull(data);
+ Assert.Equal(2, data!.Steps.Length);
+ string?[] ids = data
+ .Steps.Where(s => s != null)
+ .Select(s => s!.Data[nameof(RetryableTestRevertStep.StepId)]?.ToString())
+ .ToArray();
+ Assert.Equal(new string?[] { "first", "second" }, ids);
+ }
+ finally
+ {
+ if (File.Exists(path))
+ File.Delete(path);
+ }
+ }
+
+ [Fact]
+ public async Task SaveRevertDataAsync_DuplicatePayload_BothEntriesPersist()
+ {
+ // Regression: payload-based dedupe once dropped the second of two
+ // identical executions, losing revert coverage.
+ var id = Guid.NewGuid();
+ var path = Path.Combine(Shared.RevertDirectory, id + ".json");
+ var manager = new RevertManager(
+ NullLogger<RevertManager>.Instance,
+ TestShell.New(),
+ TimeProvider.System
+ );
+
+ var changes = new ChangeSet();
+ changes.Add("One", "One", true, new RetryableTestRevertStep { StepId = "same" });
+ changes.Add("Two", "Two", true, new RetryableTestRevertStep { StepId = "same" });
+
+ try
+ {
+ await manager.SaveRevertDataAsync(
+ changes,
+ id,
+ "Test",
+ TestContext.Current.CancellationToken
+ );
+
+ var data = await RevertManager.GetRevertDataAsync(id);
+ Assert.NotNull(data);
+ Assert.Equal(2, data!.Steps.Length);
+ }
+ finally
+ {
+ if (File.Exists(path))
+ File.Delete(path);
+ }
+ }
+
+ [Fact]
+ public async Task RevertAsync_UnknownStepType_FailsLoudlyAndKeepsFile()
+ {
+ var id = Guid.NewGuid();
+ var path = Path.Combine(Shared.RevertDirectory, id + ".json");
+ Directory.CreateDirectory(Shared.RevertDirectory);
+ var cancellationToken = TestContext.Current.CancellationToken;
+
+ var payload = new RevertData
+ {
+ OptimizationId = id,
+ OptimizationName = "TestOptimization",
+ AppliedAt = DateTime.UtcNow,
+ Steps =
+ [
+ new RevertStepData
+ {
+ Index = 1,
+ Type = "NoSuchStepType",
+ Data = new JObject { ["foo"] = "bar" },
+ },
+ ],
+ };
+
+ try
+ {
+ await File.WriteAllTextAsync(
+ path,
+ JsonConvert.SerializeObject(payload),
+ cancellationToken
+ );
+
+ var manager = new RevertManager(
+ NullLogger<RevertManager>.Instance,
+ TestShell.New(),
+ TimeProvider.System
+ );
+ var result = await manager.RevertAsync(
+ new MockOptimization(id),
+ cancellationToken: TestContext.Current.CancellationToken
+ );
+
+ Assert.False(result.Success);
+ Assert.Single(result.FailedSteps);
+ Assert.Contains("NoSuchStepType", result.FailedSteps[0].Error);
+ // The unloadable entry is kept for a future version, not deleted.
+ Assert.True(File.Exists(path));
+ }
+ finally
+ {
+ if (File.Exists(path))
+ File.Delete(path);
+ }
+ }
+
+ [Fact]
+ public void RemoveOrphanedTempFiles_DeletesTmpKeepsJson()
+ {
+ Directory.CreateDirectory(Shared.RevertDirectory);
+ var tmp = Path.Combine(Shared.RevertDirectory, Guid.NewGuid() + ".json.tmp");
+ var json = Path.Combine(Shared.RevertDirectory, Guid.NewGuid() + ".json");
+
+ try
+ {
+ File.WriteAllText(tmp, "{}");
+ File.WriteAllText(json, "{}");
+
+ RevertManager.RemoveOrphanedTempFiles(NullLogger.Instance);
+
+ Assert.False(File.Exists(tmp));
+ Assert.True(File.Exists(json));
+ }
+ finally
+ {
+ if (File.Exists(tmp))
+ File.Delete(tmp);
+ if (File.Exists(json))
+ File.Delete(json);
+ }
+ }
+
[Fact]
public async Task LoadAsync_PathTraversalSiblingDirectory_ReturnsNull()
{
@@ -337,6 +522,24 @@ public class RevertManagerTests
Directory.Delete(siblingDir);
}
}
+
+ [Fact]
+ public void BuildStepRegistry_DoesNotThrowOnCorruptedStepOrTypesWithoutDefaultConstructor()
+ {
+ var buildMethod = typeof(RevertManager).GetMethod(
+ "BuildStepRegistry",
+ System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic
+ );
+ Assert.NotNull(buildMethod);
+
+ var registry =
+ (Dictionary<string, Func<JObject, IRevertStep>>)buildMethod!.Invoke(null, null)!;
+ Assert.NotNull(registry);
+ Assert.True(registry.ContainsKey("Registry"));
+ Assert.True(registry.ContainsKey("Service"));
+ Assert.True(registry.ContainsKey("ScheduledTask"));
+ Assert.True(registry.ContainsKey("Shell"));
+ }
}
public class MockOptimization(Guid id) : StubOptimization
@@ -367,7 +570,7 @@ public class RetryableTestRevertStep : IRevertStep
public string Description => $"Retryable test step {StepId}";
- public Task<bool> ExecuteAsync()
+ public Task<bool> ExecuteAsync(ShellService _, ILogger logger)
{
if (RemainingFailures > 0)
{
diff --git a/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs b/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
index b9490bb..9bdd296 100644
--- a/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
@@ -1,189 +1,132 @@
-using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Execution;
-using optimizerDuck.Domain.Optimizations.Models;
-using optimizerDuck.Domain.UI;
-using optimizerDuck.Test.TestDoubles;
-using OptimizationState = optimizerDuck.Domain.UI.OptimizationState;
+using optimizerDuck.Services.Optimization.Providers;
namespace optimizerDuck.Test.Services;
-public class ExecutionScopeTests
+public class ChangeSetTests
{
[Fact]
- public void RecordStep_WithSuccessfulStep_RecordsStep()
+ public void Add_WithSuccessfulChange_RecordsChange()
{
- var logger = NullLogger.Instance;
+ var changes = new ChangeSet();
- using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
+ changes.Add("TestStep", "Test description", true);
- ExecutionScope.RecordStep("TestStep", "Test description", true);
-
- Assert.Single(scope.ExecutedSteps);
- Assert.True(scope.HasSuccessfulSteps);
- Assert.Equal("TestStep", scope.ExecutedSteps[0].Name);
+ Assert.Single(changes.Changes);
+ Assert.True(changes.HasSuccessfulSteps);
+ Assert.Equal("TestStep", changes.Changes[0].Name);
+ Assert.Equal(1, changes.Changes[0].Index);
}
[Fact]
- public void RecordStep_WithFailedStep_RecordsFailedStep()
+ public void Add_WithFailedChange_RecordsError()
{
- var logger = NullLogger.Instance;
-
- using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
+ var changes = new ChangeSet();
- ExecutionScope.RecordStep("TestStep", "Test description", false, error: "Test error");
+ changes.Add("TestStep", "Test description", false, error: "Test error");
- Assert.Single(scope.ExecutedSteps);
- Assert.False(scope.ExecutedSteps[0].Success);
- Assert.False(scope.HasSuccessfulSteps);
- Assert.Equal("Test error", scope.ExecutedSteps[0].Error);
+ Assert.Single(changes.Changes);
+ Assert.False(changes.Changes[0].Ok);
+ Assert.False(changes.HasSuccessfulSteps);
+ Assert.Equal("Test error", changes.Changes[0].Error);
}
[Fact]
- public void RecordStep_WithRevertStep_RecordsRevertData()
+ public void Add_WithRevertStep_StoresRevertData()
{
- var logger = NullLogger.Instance;
+ var changes = new ChangeSet();
var revertStep = new MockRevertStep();
- using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
+ changes.Add("TestStep", "Test description", true, revertStep);
- ExecutionScope.RecordStep("TestStep", "Test description", true, revertStep);
-
- Assert.Single(scope.SuccessfulSteps);
- Assert.NotNull(scope.SuccessfulSteps[0].RevertStep);
+ Assert.Single(changes.SuccessfulSteps);
+ Assert.NotNull(changes.SuccessfulSteps[0].Revert);
}
[Fact]
- public void FailedSteps_ReturnsOnlyFailedSteps()
+ public void FailedSteps_ReturnsOnlyFailedChanges()
{
- var logger = NullLogger.Instance;
-
- using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
+ var changes = new ChangeSet();
- ExecutionScope.RecordStep("SuccessStep1", "Description", true);
- ExecutionScope.RecordStep("FailedStep", "Description", false, error: "Error");
- ExecutionScope.RecordStep("SuccessStep2", "Description", true);
+ changes.Add("SuccessStep1", "Description", true);
+ changes.Add("FailedStep", "Description", false, error: "Error");
+ changes.Add("SuccessStep2", "Description", true);
- var failedSteps = scope.FailedSteps;
+ var failedSteps = changes.FailedSteps;
Assert.Single(failedSteps);
Assert.Equal("FailedStep", failedSteps[0].Name);
}
[Fact]
- public void StepIndex_IncrementsSequentially()
+ public void Add_IncrementsSequenceSequentially()
{
- var logger = NullLogger.Instance;
+ var changes = new ChangeSet();
- using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
+ changes.Add("Step1", "Description", true);
+ changes.Add("Step2", "Description", true);
+ changes.Add("Step3", "Description", true);
- ExecutionScope.RecordStep("Step1", "Description", true);
- ExecutionScope.RecordStep("Step2", "Description", true);
- ExecutionScope.RecordStep("Step3", "Description", true);
-
- Assert.Equal(1, scope.ExecutedSteps[0].Index);
- Assert.Equal(2, scope.ExecutedSteps[1].Index);
- Assert.Equal(3, scope.ExecutedSteps[2].Index);
+ Assert.Equal(1, changes.Changes[0].Index);
+ Assert.Equal(2, changes.Changes[1].Index);
+ Assert.Equal(3, changes.Changes[2].Index);
}
[Fact]
- public void Dispose_ClearsCurrentScope()
+ public void ToApplyResult_Empty_ReturnsFailure()
{
- var logger = NullLogger.Instance;
-
- var scope = ExecutionScope.Begin(new MockOptimization(), logger);
-
- ExecutionScope.RecordStep("Success", "Description", true);
- ExecutionScope.RecordStep("Fail", "Description", false);
+ var changes = new ChangeSet();
- Assert.NotNull(ExecutionScope.Current);
+ var result = changes.ToApplyResult();
- scope.Dispose();
-
- Assert.Null(ExecutionScope.Current);
+ Assert.NotNull(result.ErrorMessage);
}
[Fact]
- public void Begin_WithLogger_CreatesLightweightScope()
+ public void ToApplyResult_AllFailed_ReturnsFirstError()
{
- var logger = NullLogger.Instance;
+ var changes = new ChangeSet();
- using var scope = ExecutionScope.BeginForLogging(logger);
+ changes.Add("Step1", "Desc1", false, error: "err");
+ changes.Add("Step2", "Desc2", false, error: "err2");
- ExecutionScope.RecordStep("TestStep", "Description", true);
+ var result = changes.ToApplyResult();
- Assert.NotNull(ExecutionScope.Current);
- Assert.Empty(scope.ExecutedSteps);
- Assert.Equal(Guid.Empty, scope.OptimizationId);
+ Assert.Equal("err", result.ErrorMessage);
}
[Fact]
- public void Begin_ThrowsIfAlreadyActive()
+ public void ToApplyResult_PartialSuccess_ReturnsSuccess()
{
- var logger = NullLogger.Instance;
+ var changes = new ChangeSet();
- using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
+ changes.Add("Step1", "Desc1", true);
+ changes.Add("Step2", "Desc2", false, error: "err");
- Assert.Throws<InvalidOperationException>(() =>
- ExecutionScope.Begin(new MockOptimization(), logger)
- );
- }
+ var result = changes.ToApplyResult();
- [Fact]
- public void RecordStep_WithoutActiveScope_ReturnsNull()
- {
- var result = ExecutionScope.RecordStep("TestStep", "Description", true);
+ Assert.Null(result.ErrorMessage);
- Assert.Null(result);
+ // Successes and failures stay separable.
+ Assert.Single(changes.SuccessfulSteps);
+ Assert.Single(changes.FailedSteps);
+ Assert.True(changes.SuccessfulSteps[0].Ok);
+ Assert.False(changes.FailedSteps[0].Ok);
+ Assert.Equal("err", changes.FailedSteps[0].Error);
}
[Fact]
- public void Track_UpdatesStats()
+ public void Add_Concurrent_IsThreadSafe()
{
- var logger = NullLogger.Instance;
-
- using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
+ var changes = new ChangeSet();
- ExecutionScope.Track("Registry", true);
- ExecutionScope.Track("Registry", true);
- ExecutionScope.Track("Registry", false);
+ Parallel.For(0, 100, i => changes.Add($"Step{i}", "Description", true));
- var steps = scope.GetStepResults();
- Assert.Empty(steps);
- }
-
- [Fact]
- public void GetStepResults_ReturnsOperationStepResults()
- {
- var logger = NullLogger.Instance;
-
- using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
-
- ExecutionScope.RecordStep("Step1", "Desc1", true);
- ExecutionScope.RecordStep("Step2", "Desc2", false, error: "err");
-
- var results = scope.GetStepResults();
-
- Assert.Equal(2, results.Count);
- Assert.True(results[0].Success);
- Assert.False(results[1].Success);
- Assert.Equal("err", results[1].Error);
- }
-}
-
-public class MockOptimization : StubOptimization
-{
- public override string OptimizationKey => "MockOptimization";
- public override string Name => "Mock Optimization";
- public override string ShortDescription => "Mock description";
-
- public override Task<ApplyResult> ApplyAsync(
- IProgress<ProcessingProgress> progress,
- OptimizationContext context
- )
- {
- return Task.FromResult(ApplyResult.True());
+ Assert.Equal(100, changes.Changes.Count);
+ Assert.Equal(100, changes.Changes.Select(c => c.Index).Distinct().Count());
}
}
@@ -192,7 +135,7 @@ public class MockRevertStep : IRevertStep
public string Type => "Mock";
public string Description => "Mock Description";
- public Task<bool> ExecuteAsync()
+ public Task<bool> ExecuteAsync(ShellService _, ILogger logger)
{
return Task.FromResult(true);
}
diff --git a/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs b/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs
index 8a517e0..5f7a6fb 100644
--- a/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs
@@ -13,6 +13,7 @@ using optimizerDuck.Domain.Optimizations.Models;
using optimizerDuck.Domain.Revert;
using optimizerDuck.Domain.UI;
using optimizerDuck.Services.Optimization;
+using optimizerDuck.Services.Optimization.Providers;
using optimizerDuck.Services.Revert;
using optimizerDuck.Services.System;
using optimizerDuck.Test.TestDoubles;
@@ -41,29 +42,21 @@ public class OptimizationServiceIntegrationTests : IDisposable
OptimizationContext context
)
{
- var results = new List<OperationStepResult>();
- _stepCount = 0;
-
// Step 1: Always succeeds
- ExecutionScope.RecordStep("Test", "Step 1", true, new TestRevertStep { StepId = 1 });
+ context.Changes.Add("Step 1", "Step 1", true, new TestRevertStep { StepId = 1 });
_stepCount++;
// Step 2: May fail
if (_shouldFail)
{
- ExecutionScope.RecordStep("Test", "Step 2", false, null, "Simulated failure");
+ context.Changes.Add("Step 2", "Step 2", false, error: "Simulated failure");
_stepCount++;
}
// Step 3: Only executes if step 2 succeeded
if (!_shouldFail)
{
- ExecutionScope.RecordStep(
- "Test",
- "Step 3",
- true,
- new TestRevertStep { StepId = 3 }
- );
+ context.Changes.Add("Step 3", "Step 3", true, new TestRevertStep { StepId = 3 });
_stepCount++;
}
@@ -80,7 +73,7 @@ public class OptimizationServiceIntegrationTests : IDisposable
public string Type => "Test";
public string Description => $"Revert step {StepId}";
- public Task<bool> ExecuteAsync()
+ public Task<bool> ExecuteAsync(ShellService _, ILogger logger)
{
// Simulate revert operation
return Task.FromResult(true);
@@ -118,7 +111,11 @@ public class OptimizationServiceIntegrationTests : IDisposable
public async Task ApplyAsync_WithSuccess_SavesRevertDataCorrectly()
{
var loggerFactory = NullLoggerFactory.Instance;
- var revertManager = new RevertManager(NullLogger<RevertManager>.Instance, loggerFactory);
+ var revertManager = new RevertManager(
+ NullLogger<RevertManager>.Instance,
+ TestShell.New(),
+ TimeProvider.System
+ );
var systemInfoService = new SystemInfoService(NullLogger<SystemInfoService>.Instance);
var streamService = new StreamService(NullLogger<StreamService>.Instance);
@@ -128,6 +125,7 @@ public class OptimizationServiceIntegrationTests : IDisposable
systemInfoService,
streamService,
null!,
+ new ShellService(new ProcessRunner(120000)),
NullLogger<OptimizationService>.Instance
);
@@ -169,16 +167,16 @@ public class OptimizationServiceIntegrationTests : IDisposable
[Fact]
public async Task RetryFailedStepsAsync_WithRetryableSteps_Succeeds()
{
- var failedSteps = new List<OperationStepResult>
+ var failedSteps = new List<Change>
{
new()
{
Index = 1,
Name = "Test",
Description = "Failed step",
- Success = false,
+ Ok = false,
Error = "Temporary failure",
- RetryAction = () => Task.FromResult(true),
+ Retry = _ => Task.FromResult(OpResult.Success()),
},
};
@@ -197,16 +195,16 @@ public class OptimizationServiceIntegrationTests : IDisposable
[Fact]
public async Task RetryFailedStepsAsync_WithNonRetryableSteps_RemainsFailed()
{
- var failedSteps = new List<OperationStepResult>
+ var failedSteps = new List<Change>
{
new()
{
Index = 1,
Name = "Test",
Description = "Failed step",
- Success = false,
+ Ok = false,
Error = "Permanent failure",
- RetryAction = null, // No retry action
+ Retry = null, // No retry action
},
};
diff --git a/optimizerDuck.Test/Services/OptimizationServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServiceTests.cs
index 5aca4c6..6d69caf 100644
--- a/optimizerDuck.Test/Services/OptimizationServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServiceTests.cs
@@ -8,6 +8,7 @@ using optimizerDuck.Domain.Revert;
using optimizerDuck.Domain.Revert.Steps;
using optimizerDuck.Domain.UI;
using optimizerDuck.Services.Optimization;
+using optimizerDuck.Services.Optimization.Providers;
using optimizerDuck.Services.Revert;
using optimizerDuck.Services.System;
using optimizerDuck.Test.TestDoubles;
@@ -24,10 +25,10 @@ public class OptimizationServiceTests
{
var optimization = new FakeOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep(
- "Test",
+ args.context.Changes.Add(
+ "Test step",
"Test step",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }
@@ -71,15 +72,15 @@ public class OptimizationServiceTests
{
var optimization = new FakeOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep(
- "Test",
+ args.context.Changes.Add(
+ "Test step",
"Test step",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }
);
- ExecutionScope.RecordStep("Test", "Failed step", false, error: "fail");
+ args.context.Changes.Add("Failed step", "Failed step", false, error: "fail");
return Task.FromResult(ApplyResult.False("apply failed"));
},
};
@@ -167,22 +168,22 @@ public class OptimizationServiceTests
{
await RunInStaThreadAsync(async () =>
{
- var failedStep = new OperationStepResult
+ var failedStep = new Change
{
Index = 3,
Name = "Shell",
Description = "failed step",
- Success = false,
+ Ok = false,
Error = "fail",
- RetryAction = () =>
+ Retry = rc =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ rc.Changes.Add(
+ "retried step",
"retried step",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }
);
- return Task.FromResult(true);
+ return Task.FromResult(OpResult.Success());
},
};
@@ -195,7 +196,7 @@ public class OptimizationServiceTests
Assert.Empty(result.FailedSteps);
Assert.Single(result.RecoveredSteps);
Assert.Equal(3, result.RecoveredSteps[0].Index);
- Assert.NotNull(result.RecoveredSteps[0].RevertStep);
+ Assert.NotNull(result.RecoveredSteps[0].Revert);
});
}
@@ -206,24 +207,24 @@ public class OptimizationServiceTests
{
var optimization = new FakeOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "step 1",
"step 1",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 11" }
);
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "step 2",
"step 2",
false,
null,
"fail",
- () =>
+ retry: rc =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ rc.Changes.Add(
+ "step 2 retry",
"step 2 retry",
true,
new ShellRevertStep
@@ -232,11 +233,11 @@ public class OptimizationServiceTests
Command = "exit 0",
}
);
- return Task.FromResult(true);
+ return Task.FromResult(OpResult.Success());
}
);
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "step 3",
"step 3",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 33" }
@@ -260,17 +261,15 @@ public class OptimizationServiceTests
Assert.Equal(OptimizationSuccessResult.PartialSuccess, result.Status);
Assert.NotNull(data);
- Assert.Equal(3, data!.Steps.Length);
- Assert.Equal("Shell", data.Steps[0]!.Type);
- Assert.Null(data.Steps[1]); // Gap - step 2 failed
- Assert.Equal("Shell", data.Steps[2]!.Type);
+ // Compact layout: only the 2 successful steps persist, in order.
+ Assert.Equal(2, data!.Steps.Length);
Assert.Equal(
"exit 11",
data.Steps[0]!.Data[nameof(ShellRevertStep.Command)]?.ToString()
);
Assert.Equal(
"exit 33",
- data.Steps[2]!.Data[nameof(ShellRevertStep.Command)]?.ToString()
+ data.Steps[1]!.Data[nameof(ShellRevertStep.Command)]?.ToString()
);
}
finally
@@ -282,30 +281,30 @@ public class OptimizationServiceTests
}
[Fact]
- public async Task UpsertRevertStepAtIndexAsync_AfterRetrySuccess_InsertsStepAtFailedIndexWithoutShiftingLaterSteps()
+ public async Task AppendRevertStepAsync_AfterRetrySuccess_AppendsWithoutDestroyingExistingEntries()
{
await RunInStaThreadAsync(async () =>
{
var optimization = new FakeOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "step 1",
"step 1",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 11" }
);
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "step 2",
"step 2",
false,
null,
"fail",
- () =>
+ retry: rc =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ rc.Changes.Add(
+ "step 2 retry",
"step 2 retry",
true,
new ShellRevertStep
@@ -314,11 +313,11 @@ public class OptimizationServiceTests
Command = "exit 0",
}
);
- return Task.FromResult(true);
+ return Task.FromResult(OpResult.Success());
}
);
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "step 3",
"step 3",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 33" }
@@ -348,33 +347,34 @@ public class OptimizationServiceTests
var retriedStep = Assert.Single(retryResult.RecoveredSteps);
Assert.Equal(2, retriedStep.Index);
- Assert.NotNull(retriedStep.RevertStep);
+ Assert.NotNull(retriedStep.Revert);
var revertManager = new RevertManager(
NullLogger<RevertManager>.Instance,
- NullLoggerFactory.Instance
+ TestShell.New(),
+ TimeProvider.System
);
- await revertManager.UpsertRevertStepAtIndexAsync(
+ await revertManager.AppendRevertStepAsync(
optimization.Id,
optimization.OptimizationKey,
- retriedStep.Index,
- retriedStep.RevertStep!
+ retriedStep.Revert!
);
var data = await RevertManager.GetRevertDataAsync(optimization.Id);
Assert.NotNull(data);
+ // Save wrote [exit 11, exit 33]; the recovered step appends.
Assert.Equal(3, data!.Steps.Length);
Assert.Equal(
"exit 11",
data.Steps[0]!.Data[nameof(ShellRevertStep.Command)]?.ToString()
);
Assert.Equal(
- "exit 0",
+ "exit 33",
data.Steps[1]!.Data[nameof(ShellRevertStep.Command)]?.ToString()
);
Assert.Equal(
- "exit 33",
+ "exit 0",
data.Steps[2]!.Data[nameof(ShellRevertStep.Command)]?.ToString()
);
}
@@ -387,30 +387,30 @@ public class OptimizationServiceTests
}
[Fact]
- public async Task UpsertRevertStepAtIndexAsync_AfterMultipleRetrySuccesses_PreservesOriginalOrder()
+ public async Task AppendRevertStepAsync_AfterMultipleRetrySuccesses_AppendsInRetryOrder()
{
await RunInStaThreadAsync(async () =>
{
var optimization = new FakeOptimization
{
- ApplyImpl = _ =>
+ ApplyImpl = args =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "step 1",
"step 1",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 11" }
);
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "step 2",
"step 2",
false,
null,
"fail 2",
- () =>
+ retry: rc =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ rc.Changes.Add(
+ "step 2 retry",
"step 2 retry",
true,
new ShellRevertStep
@@ -419,25 +419,25 @@ public class OptimizationServiceTests
Command = "exit 22",
}
);
- return Task.FromResult(true);
+ return Task.FromResult(OpResult.Success());
}
);
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "step 3",
"step 3",
true,
new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 33" }
);
- ExecutionScope.RecordStep(
- "Shell",
+ args.context.Changes.Add(
+ "step 4",
"step 4",
false,
null,
"fail 4",
- () =>
+ retry: rc =>
{
- ExecutionScope.RecordStep(
- "Shell",
+ rc.Changes.Add(
+ "step 4 retry",
"step 4 retry",
true,
new ShellRevertStep
@@ -446,7 +446,7 @@ public class OptimizationServiceTests
Command = "exit 44",
}
);
- return Task.FromResult(true);
+ return Task.FromResult(OpResult.Success());
}
);
return Task.FromResult(ApplyResult.True());
@@ -481,14 +481,14 @@ public class OptimizationServiceTests
var revertManager = new RevertManager(
NullLogger<RevertManager>.Instance,
- NullLoggerFactory.Instance
+ TestShell.New(),
+ TimeProvider.System
);
foreach (var recoveredStep in retryResult.RecoveredSteps)
- await revertManager.UpsertRevertStepAtIndexAsync(
+ await revertManager.AppendRevertStepAsync(
optimization.Id,
optimization.OptimizationKey,
- recoveredStep.Index,
- recoveredStep.RevertStep!
+ recoveredStep.Revert!
);
var data = await RevertManager.GetRevertDataAsync(optimization.Id);
@@ -499,7 +499,8 @@ public class OptimizationServiceTests
.Steps.Where(step => step != null)
.Select(step => step!.Data[nameof(ShellRevertStep.Command)]!.ToString())
.ToArray();
- Assert.Equal(["exit 11", "exit 22", "exit 33", "exit 44"], commands);
+ // Save wrote [exit 11, exit 33]; recovered steps append in retry order.
+ Assert.Equal(["exit 11", "exit 33", "exit 22", "exit 44"], commands);
}
finally
{
@@ -514,14 +515,14 @@ public class OptimizationServiceTests
{
await RunInStaThreadAsync(async () =>
{
- var failedStep = new OperationStepResult
+ var failedStep = new Change
{
Index = 2,
Name = "Shell",
Description = "still failing step",
- Success = false,
+ Ok = false,
Error = "initial error",
- RetryAction = () => throw new InvalidOperationException("retry exploded"),
+ Retry = _ => throw new InvalidOperationException("retry exploded"),
};
var result = await OptimizationService.RetryFailedStepsWithResultsAsync(
@@ -541,12 +542,14 @@ public class OptimizationServiceTests
{
var revertManager = new RevertManager(
NullLogger<RevertManager>.Instance,
- NullLoggerFactory.Instance
+ TestShell.New(),
+ 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(
revertManager,
@@ -554,6 +557,7 @@ public class OptimizationServiceTests
systemInfoService,
streamService,
contentDialogService,
+ shellService,
logger
);
}
diff --git a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
index cd3c9db..4b5a6f8 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
@@ -3,11 +3,8 @@ using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Win32;
-using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Execution;
-using optimizerDuck.Domain.Optimizations.Models;
using optimizerDuck.Domain.Optimizations.Models.Services;
-using optimizerDuck.Domain.UI;
using optimizerDuck.Services.Optimization.Providers;
using optimizerDuck.Test.TestDoubles;
using Xunit;
@@ -17,25 +14,12 @@ namespace optimizerDuck.Test.Services.OptimizationServices;
public class RegistryServiceTests : IDisposable
{
private const string BaseTestKey = @"HKCU\Software\TestOptimizerDuck";
- private readonly ExecutionScope _scope;
- private class DummyOptimization : StubOptimization
- {
- public override string OptimizationKey => "TestOpt";
- public override string Name => "Test";
- public override string ShortDescription => "";
-
- public override Task<ApplyResult> ApplyAsync(
- IProgress<ProcessingProgress> progress,
- OptimizationContext context
- ) => Task.FromResult(ApplyResult.True());
- }
+ private static OpCall NewCall() =>
+ new() { Changes = new ChangeSet(), Logger = NullLogger.Instance };
public RegistryServiceTests()
{
- // Setup execution scope to capture revert steps and logs
- _scope = ExecutionScope.Begin(new DummyOptimization(), NullLogger.Instance);
-
// Ensure clean state
CleanupTestKey();
}
@@ -43,7 +27,6 @@ public class RegistryServiceTests : IDisposable
public void Dispose()
{
CleanupTestKey();
- _scope.Dispose();
}
private static void CleanupTestKey()
@@ -71,16 +54,16 @@ public class RegistryServiceTests : IDisposable
public void DeleteValue_WithInvalidRoot_ReturnsFalse()
{
var item = new RegistryItem("BADROOT\\SomePath", "ValueName");
- var result = RegistryService.DeleteValue(item);
- Assert.False(result);
+ var result = RegistryService.DeleteValue(NewCall(), item);
+ Assert.False(result.Ok);
}
[Fact]
public void Write_WithNullValue_ReturnsFalse()
{
var item = new RegistryItem(BaseTestKey, "TestValue");
- var result = RegistryService.Write(item);
- Assert.False(result);
+ var result = RegistryService.Write(NewCall(), item);
+ Assert.False(result.Ok);
}
[Fact]
@@ -88,12 +71,13 @@ public class RegistryServiceTests : IDisposable
{
var key = $@"{BaseTestKey}\DeleteValueTest";
- RegistryService.Write(new RegistryItem(key, "A", "Hello"));
- RegistryService.DeleteValue(new RegistryItem(key, "A"));
-
- var step = _scope.ExecutedSteps.Last();
+ var write = RegistryService.Write(NewCall(), new RegistryItem(key, "A", "Hello"));
+ Assert.True(write.Ok, write.Error);
+ var delete = RegistryService.DeleteValue(NewCall(), new RegistryItem(key, "A"));
+ Assert.True(delete.Ok, delete.Error);
- await step.RevertStep!.ExecuteAsync();
+ Assert.NotNull(delete.Revert);
+ Assert.True(await delete.Revert.ExecuteAsync(TestShell.New(), NullLogger.Instance));
var val = RegistryService.Read<string>(new RegistryItem(key, "A"));
Assert.Equal("Hello", val);
@@ -104,12 +88,13 @@ public class RegistryServiceTests : IDisposable
{
var key = $@"{BaseTestKey}\DeleteDefaultValueTest";
- RegistryService.Write(new RegistryItem(key, null, "DefaultHello"));
- RegistryService.DeleteValue(new RegistryItem(key, null));
+ var write = RegistryService.Write(NewCall(), new RegistryItem(key, null, "DefaultHello"));
+ Assert.True(write.Ok, write.Error);
+ var delete = RegistryService.DeleteValue(NewCall(), new RegistryItem(key, null));
+ Assert.True(delete.Ok, delete.Error);
- var step = _scope.ExecutedSteps.Last();
-
- await step.RevertStep!.ExecuteAsync();
+ Assert.NotNull(delete.Revert);
+ Assert.True(await delete.Revert.ExecuteAsync(TestShell.New(), NullLogger.Instance));
var value = RegistryService.Read<string>(new RegistryItem(key, null));
Assert.Equal("DefaultHello", value);
@@ -120,14 +105,22 @@ public class RegistryServiceTests : IDisposable
{
var key = $@"{BaseTestKey}\WriteDefaultValueTest";
- Assert.True(RegistryService.Write(new RegistryItem(key, null, "OriginalDefault")));
- Assert.True(RegistryService.Write(new RegistryItem(key, null, "UpdatedDefault")));
+ var first = RegistryService.Write(
+ NewCall(),
+ new RegistryItem(key, null, "OriginalDefault")
+ );
+ Assert.True(first.Ok, first.Error);
+ var second = RegistryService.Write(
+ NewCall(),
+ new RegistryItem(key, null, "UpdatedDefault")
+ );
+ Assert.True(second.Ok, second.Error);
var value = RegistryService.Read<string>(new RegistryItem(key, null));
Assert.Equal("UpdatedDefault", value);
- var step = _scope.ExecutedSteps.Last();
- Assert.True(await step.RevertStep!.ExecuteAsync());
+ Assert.NotNull(second.Revert);
+ Assert.True(await second.Revert.ExecuteAsync(TestShell.New(), NullLogger.Instance));
var restoredValue = RegistryService.Read<string>(new RegistryItem(key, null));
Assert.Equal("OriginalDefault", restoredValue);
@@ -147,31 +140,32 @@ public class RegistryServiceTests : IDisposable
var keyPathB = $@"{keyPathA}\B";
var keyPathC = $@"{keyPathB}\C";
- Assert.True(RegistryService.Write(new RegistryItem(keyPathA, "Value1", "Data1")));
- Assert.True(RegistryService.Write(new RegistryItem(keyPathA, null, "DefaultData")));
- Assert.True(
- RegistryService.Write(new RegistryItem(keyPathB, "Value3", 42, RegistryValueKind.DWord))
+ var w1 = RegistryService.Write(NewCall(), new RegistryItem(keyPathA, "Value1", "Data1"));
+ Assert.True(w1.Ok, w1.Error);
+ var w2 = RegistryService.Write(NewCall(), new RegistryItem(keyPathA, null, "DefaultData"));
+ Assert.True(w2.Ok, w2.Error);
+ var w3 = RegistryService.Write(
+ NewCall(),
+ new RegistryItem(keyPathB, "Value3", 42, RegistryValueKind.DWord)
);
- Assert.True(RegistryService.CreateSubKey(new RegistryItem(keyPathC)));
+ Assert.True(w3.Ok, w3.Error);
+ var ck = RegistryService.CreateSubKey(NewCall(), new RegistryItem(keyPathC));
+ Assert.True(ck.Ok, ck.Error);
// 2. Perform the deletion of tree A
- Assert.True(RegistryService.DeleteSubKeyTree(new RegistryItem(keyPathA)));
+ var delete = RegistryService.DeleteSubKeyTree(NewCall(), new RegistryItem(keyPathA));
+ Assert.True(delete.Ok, delete.Error);
// Verify keys are gone
Assert.False(RegistryService.KeyExists(new RegistryItem(keyPathA)));
// 3. Obtain the revert step generated out of the deleted tree
- var deleteStep = _scope.ExecutedSteps.LastOrDefault(s =>
- s.Name == "Registry" && s.RevertStep != null
- );
- Assert.NotNull(deleteStep);
-
- var revertStep = deleteStep.RevertStep;
+ var revertStep = delete.Revert;
Assert.NotNull(revertStep);
Assert.Equal("Registry", revertStep.Type);
// 4. Act: Execute the Revert Step
- Assert.True(await revertStep.ExecuteAsync());
+ Assert.True(await revertStep.ExecuteAsync(TestShell.New(), NullLogger.Instance));
// 5. Assert: Verify the tree structure is perfectly restored
Assert.True(RegistryService.KeyExists(new RegistryItem(keyPathC))); // C exists, implies A and B exist
@@ -194,17 +188,15 @@ public class RegistryServiceTests : IDisposable
var keyPathB = $@"{keyPathA}\B";
// Create the deep subkey
- Assert.True(RegistryService.CreateSubKey(new RegistryItem(keyPathB)));
+ var create = RegistryService.CreateSubKey(NewCall(), new RegistryItem(keyPathB));
+ Assert.True(create.Ok, create.Error);
Assert.True(RegistryService.KeyExists(new RegistryItem(keyPathB)));
// Obtain revert step
- var createStep = _scope.ExecutedSteps.LastOrDefault(s =>
- s.Name == "Registry" && s.RevertStep != null
- );
- Assert.NotNull(createStep);
+ Assert.NotNull(create.Revert);
// Execute revert
- Assert.True(await createStep.RevertStep!.ExecuteAsync());
+ Assert.True(await create.Revert.ExecuteAsync(TestShell.New(), NullLogger.Instance));
// Verify that B and A were cleaned up since they were empty
Assert.False(RegistryService.KeyExists(new RegistryItem(keyPathB)));
@@ -220,31 +212,42 @@ public class RegistryServiceTests : IDisposable
var key3 = $@"{BaseTestKey}\MultiStepTest3";
// Write initial values
- Assert.True(RegistryService.Write(new RegistryItem(key1, "Value", "Initial1")));
- Assert.True(RegistryService.Write(new RegistryItem(key2, "Value", "Initial2")));
- Assert.True(RegistryService.Write(new RegistryItem(key3, "Value", "Initial3")));
+ var i1 = RegistryService.Write(NewCall(), new RegistryItem(key1, "Value", "Initial1"));
+ Assert.True(i1.Ok, i1.Error);
+ var i2 = RegistryService.Write(NewCall(), new RegistryItem(key2, "Value", "Initial2"));
+ Assert.True(i2.Ok, i2.Error);
+ var i3 = RegistryService.Write(NewCall(), new RegistryItem(key3, "Value", "Initial3"));
+ Assert.True(i3.Ok, i3.Error);
- // Dispose old scope and create new one to capture new operations
- _scope.Dispose();
- using var newScope = ExecutionScope.Begin(new DummyOptimization(), NullLogger.Instance);
+ // Fresh change set to capture new operations
+ var changes = new ChangeSet();
+ OpCall NewTrackedCall() => new() { Changes = changes, Logger = NullLogger.Instance };
// Perform multi-step operation
- Assert.True(RegistryService.Write(new RegistryItem(key1, "Value", "Updated1")));
- Assert.True(RegistryService.Write(new RegistryItem(key2, "Value", "Updated2")));
+ var u1 = RegistryService.Write(
+ NewTrackedCall(),
+ new RegistryItem(key1, "Value", "Updated1")
+ );
+ Assert.True(u1.Ok, u1.Error);
+ var u2 = RegistryService.Write(
+ NewTrackedCall(),
+ new RegistryItem(key2, "Value", "Updated2")
+ );
+ Assert.True(u2.Ok, u2.Error);
// Simulate a failure by not writing to key3
// In real scenario, this would be caught by transaction logic
// Get all revert steps
- var revertSteps = newScope
- .ExecutedSteps.Where(s => s.RevertStep != null)
- .Select(s => s.RevertStep!)
+ var revertSteps = changes
+ .SuccessfulSteps.Where(c => c.Revert != null)
+ .Select(c => c.Revert!)
.ToList();
// Revert all steps in reverse order
foreach (var step in revertSteps.AsEnumerable().Reverse())
{
- Assert.True(await step.ExecuteAsync());
+ Assert.True(await step.ExecuteAsync(TestShell.New(), NullLogger.Instance));
}
// Verify original state is restored
@@ -269,7 +272,11 @@ public class RegistryServiceTests : IDisposable
Task.Run(
() =>
{
- Assert.True(RegistryService.Write(new RegistryItem(key, "Value", value)));
+ var write = RegistryService.Write(
+ NewCall(),
+ new RegistryItem(key, "Value", value)
+ );
+ Assert.True(write.Ok, write.Error);
var read = RegistryService.Read<string>(new RegistryItem(key, "Value"));
Assert.Equal(value, read);
},
@@ -296,39 +303,36 @@ public class RegistryServiceTests : IDisposable
var key = $@"{BaseTestKey}\TypeConversionTest";
// Test different value types
- Assert.True(
- RegistryService.Write(new RegistryItem(key, "DWordValue", 42, RegistryValueKind.DWord))
+ var dw = RegistryService.Write(
+ NewCall(),
+ new RegistryItem(key, "DWordValue", 42, RegistryValueKind.DWord)
);
+ Assert.True(dw.Ok, dw.Error);
Assert.Equal(42, RegistryService.Read<int>(new RegistryItem(key, "DWordValue")));
- Assert.True(
- RegistryService.Write(
- new RegistryItem(key, "QWordValue", 9999999999L, RegistryValueKind.QWord)
- )
+ var qw = RegistryService.Write(
+ NewCall(),
+ new RegistryItem(key, "QWordValue", 9999999999L, RegistryValueKind.QWord)
);
+ Assert.True(qw.Ok, qw.Error);
Assert.Equal(9999999999L, RegistryService.Read<long>(new RegistryItem(key, "QWordValue")));
- Assert.True(
- RegistryService.Write(
- new RegistryItem(key, "StringValue", "TestString", RegistryValueKind.String)
- )
+ var sw = RegistryService.Write(
+ NewCall(),
+ new RegistryItem(key, "StringValue", "TestString", RegistryValueKind.String)
);
+ Assert.True(sw.Ok, sw.Error);
Assert.Equal(
"TestString",
RegistryService.Read<string>(new RegistryItem(key, "StringValue"))
);
var multiString = new[] { "Line1", "Line2", "Line3" };
- Assert.True(
- RegistryService.Write(
- new RegistryItem(
- key,
- "MultiStringValue",
- multiString,
- RegistryValueKind.MultiString
- )
- )
+ var mw = RegistryService.Write(
+ NewCall(),
+ new RegistryItem(key, "MultiStringValue", multiString, RegistryValueKind.MultiString)
);
+ Assert.True(mw.Ok, mw.Error);
var readMulti = RegistryService.Read<string[]>(new RegistryItem(key, "MultiStringValue"));
Assert.Equal(multiString, readMulti);
}
@@ -340,21 +344,31 @@ public class RegistryServiceTests : IDisposable
var key1 = $@"{BaseTestKey}\SubStepTest\Key1";
var key2 = $@"{BaseTestKey}\SubStepTest\Key2";
- Assert.True(RegistryService.Write(new RegistryItem(key1, "Value", "Original1")));
- Assert.True(RegistryService.Write(new RegistryItem(key2, "Value", "Original2")));
+ var o1 = RegistryService.Write(NewCall(), new RegistryItem(key1, "Value", "Original1"));
+ Assert.True(o1.Ok, o1.Error);
+ var o2 = RegistryService.Write(NewCall(), new RegistryItem(key2, "Value", "Original2"));
+ Assert.True(o2.Ok, o2.Error);
- // Dispose old scope and create new one to capture new operations
- _scope.Dispose();
- using var newScope = ExecutionScope.Begin(new DummyOptimization(), NullLogger.Instance);
+ // Fresh change set to capture new operations
+ var changes = new ChangeSet();
+ OpCall NewTrackedCall() => new() { Changes = changes, Logger = NullLogger.Instance };
// Perform operations
- Assert.True(RegistryService.Write(new RegistryItem(key1, "Value", "Modified1")));
- Assert.True(RegistryService.Write(new RegistryItem(key2, "Value", "Modified2")));
+ var m1 = RegistryService.Write(
+ NewTrackedCall(),
+ new RegistryItem(key1, "Value", "Modified1")
+ );
+ Assert.True(m1.Ok, m1.Error);
+ var m2 = RegistryService.Write(
+ NewTrackedCall(),
+ new RegistryItem(key2, "Value", "Modified2")
+ );
+ Assert.True(m2.Ok, m2.Error);
// Revert in reverse order (LIFO)
- var revertSteps = newScope
- .ExecutedSteps.Where(s => s.RevertStep != null)
- .Select(s => s.RevertStep!)
+ var revertSteps = changes
+ .SuccessfulSteps.Where(c => c.Revert != null)
+ .Select(c => c.Revert!)
.ToList();
var executionOrder = new List<string>();
@@ -362,7 +376,7 @@ public class RegistryServiceTests : IDisposable
{
var desc = step.Description;
executionOrder.Add(desc);
- Assert.True(await step.ExecuteAsync());
+ Assert.True(await step.ExecuteAsync(TestShell.New(), NullLogger.Instance));
}
// Verify state is restored
@@ -377,11 +391,17 @@ public class RegistryServiceTests : IDisposable
var nonEmptyKeyPath = $@"{BaseTestKey}\CleanupTest\NonEmptyKey";
// Create empty key
- Assert.True(RegistryService.CreateSubKey(new RegistryItem(emptyKeyPath)));
+ var ce = RegistryService.CreateSubKey(NewCall(), new RegistryItem(emptyKeyPath));
+ Assert.True(ce.Ok, ce.Error);
// Create non-empty key
- Assert.True(RegistryService.CreateSubKey(new RegistryItem(nonEmptyKeyPath)));
- Assert.True(RegistryService.Write(new RegistryItem(nonEmptyKeyPath, "Value", "SomeValue")));
+ var cn = RegistryService.CreateSubKey(NewCall(), new RegistryItem(nonEmptyKeyPath));
+ Assert.True(cn.Ok, cn.Error);
+ var wn = RegistryService.Write(
+ NewCall(),
+ new RegistryItem(nonEmptyKeyPath, "Value", "SomeValue")
+ );
+ Assert.True(wn.Ok, wn.Error);
// Cleanup
RegistryService.CleanupEmptyKeys(new[] { emptyKeyPath, nonEmptyKeyPath });
diff --git a/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
index 23c72c8..9569f5b 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
@@ -1,3 +1,5 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Services.Optimization.Providers;
@@ -5,6 +7,9 @@ namespace optimizerDuck.Test.Services.OptimizationServices;
public class ServiceProcessServiceTests
{
+ private static OpCall NewCall() =>
+ new() { Changes = new ChangeSet(), Logger = NullLogger.Instance };
+
// =============================================
// Unit tests: ParseScStartType (hardcoded input)
// =============================================
@@ -239,7 +244,7 @@ public class ServiceProcessServiceTests
);
}
- private static async Task EnsureTestServiceAsync()
+ private async Task EnsureTestServiceAsync()
{
var (startType, notFound) = await ServiceProcessService.GetStartupTypeAsync(
TestServiceName
@@ -345,10 +350,12 @@ public class ServiceProcessServiceTests
Assert.NotNull(startType);
var result = await ServiceProcessService.ChangeServiceStartupTypeAsync(
+ NewCall(),
new ServiceItem(TestServiceName, startType.Value)
);
- Assert.Equal(ServiceChangeResult.AlreadyConfigured, result);
+ // AlreadyConfigured maps to informational success (Ok).
+ Assert.True(result.Ok, result.Error);
}
finally
{
@@ -365,10 +372,11 @@ public class ServiceProcessServiceTests
try
{
var result = await ServiceProcessService.ChangeServiceStartupTypeAsync(
+ NewCall(),
new ServiceItem(TestServiceName, ServiceStartupType.Disabled)
);
- Assert.Equal(ServiceChangeResult.Success, result);
+ Assert.True(result.Ok, result.Error);
var (startType, _) = await ServiceProcessService.GetStartupTypeAsync(TestServiceName);
Assert.Equal(ServiceStartupType.Disabled, startType);
}
@@ -382,13 +390,15 @@ public class ServiceProcessServiceTests
public async Task ChangeServiceStartupTypeAsync_NonexistentService_ReturnsNotFound()
{
var result = await ServiceProcessService.ChangeServiceStartupTypeAsync(
+ NewCall(),
new ServiceItem(
"OptimizerDuckTest_Nonexistent_Service_12345",
ServiceStartupType.Manual
)
);
- Assert.Equal(ServiceChangeResult.NotFound, result);
+ // NotFound maps to informational success (Ok).
+ Assert.True(result.Ok, result.Error);
}
[Fact]
@@ -402,10 +412,12 @@ public class ServiceProcessServiceTests
await StripChangeConfigFromAdminsAsync(TestServiceName);
var result = await ServiceProcessService.ChangeServiceStartupTypeAsync(
+ NewCall(),
new ServiceItem(TestServiceName, ServiceStartupType.Disabled)
);
- Assert.Equal(ServiceChangeResult.AccessDenied, result);
+ Assert.False(result.Ok);
+ Assert.NotNull(result.Error);
}
finally
{
diff --git a/optimizerDuck.Test/Services/OptimizationServices/ShellServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/ShellServiceTests.cs
index 3e7d83a..4de3d9a 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/ShellServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/ShellServiceTests.cs
@@ -1,29 +1,50 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Services.Optimization.Providers;
namespace optimizerDuck.Test.Services.OptimizationServices;
public class ShellServiceTests
{
+ private static ShellService NewShell() =>
+ new(new ProcessRunner(120000, NullLogger<ProcessRunner>.Instance));
+
[Fact]
- public void Cmd_ExitZero_ReturnsSuccessExitCode()
+ public async Task Cmd_ExitZero_ReturnsSuccessExitCode()
{
- var result = ShellService.CMD("exit 0");
+ var shell = NewShell();
+ var result = await shell.QueryCMDAsync(
+ "exit 0",
+ NullLogger.Instance,
+ ct: TestContext.Current.CancellationToken
+ );
Assert.Equal(0, result.ExitCode);
}
[Fact]
- public void Cmd_ExitOne_ReturnsNonZeroExitCode()
+ public async Task Cmd_ExitOne_ReturnsNonZeroExitCode()
{
- var result = ShellService.CMD("exit 1");
+ var shell = NewShell();
+ var result = await shell.QueryCMDAsync(
+ "exit 1",
+ NullLogger.Instance,
+ ct: TestContext.Current.CancellationToken
+ );
Assert.NotEqual(0, result.ExitCode);
}
[Fact]
- public void PowerShell_SimpleCommand_ReturnsSuccessExitCode()
+ public async Task PowerShell_SimpleCommand_ReturnsSuccessExitCode()
{
- var result = ShellService.PowerShell("Write-Output 'ok'");
+ var shell = NewShell();
+ var result = await shell.QueryPowerShellAsync(
+ "Write-Output 'ok'",
+ NullLogger.Instance,
+ ct: TestContext.Current.CancellationToken
+ );
Assert.Equal(0, result.ExitCode);
}
diff --git a/optimizerDuck.Test/Services/OptimizationValidationTests.cs b/optimizerDuck.Test/Services/OptimizationValidationTests.cs
new file mode 100644
index 0000000..5fe7098
--- /dev/null
+++ b/optimizerDuck.Test/Services/OptimizationValidationTests.cs
@@ -0,0 +1,167 @@
+using System.Globalization;
+using System.Reflection;
+using optimizerDuck.Common.Helpers;
+using optimizerDuck.Domain.Abstractions;
+using optimizerDuck.Domain.Attributes;
+using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.UI;
+using optimizerDuck.Resources.Languages;
+using optimizerDuck.Services.Optimization;
+
+namespace optimizerDuck.Test.Services;
+
+public class OptimizationValidationTests
+{
+ [Optimization(
+ Id = "11111111-1111-1111-1111-111111111111",
+ Risk = OptimizationRisk.Safe,
+ Tags = OptimizationTags.System
+ )]
+ private sealed class ValidOptimization : BaseOptimization
+ {
+ public override Task<ApplyResult> ApplyAsync(
+ IProgress<ProcessingProgress> progress,
+ OptimizationContext context
+ )
+ {
+ return Task.FromResult(ApplyResult.True());
+ }
+ }
+
+ [Optimization(Id = "not-a-guid", Risk = OptimizationRisk.Safe, Tags = OptimizationTags.System)]
+ private sealed class InvalidIdOptimization : BaseOptimization
+ {
+ public override Task<ApplyResult> ApplyAsync(
+ IProgress<ProcessingProgress> progress,
+ OptimizationContext context
+ )
+ {
+ return Task.FromResult(ApplyResult.True());
+ }
+ }
+
+ [Optimization(
+ Id = "22222222-2222-2222-2222-222222222222",
+ Risk = OptimizationRisk.Safe,
+ Tags = OptimizationTags.System
+ )]
+ private sealed class DuplicateA : BaseOptimization
+ {
+ public override Task<ApplyResult> ApplyAsync(
+ IProgress<ProcessingProgress> progress,
+ OptimizationContext context
+ )
+ {
+ return Task.FromResult(ApplyResult.True());
+ }
+ }
+
+ [Optimization(
+ Id = "22222222-2222-2222-2222-222222222222",
+ Risk = OptimizationRisk.Safe,
+ Tags = OptimizationTags.System
+ )]
+ private sealed class DuplicateB : BaseOptimization
+ {
+ public override Task<ApplyResult> ApplyAsync(
+ IProgress<ProcessingProgress> progress,
+ OptimizationContext context
+ )
+ {
+ return Task.FromResult(ApplyResult.True());
+ }
+ }
+
+ [Fact]
+ public void Validate_ValidId_DoesNotThrow()
+ {
+ var seen = new HashSet<Guid>();
+ var exception = Record.Exception(() =>
+ OptimizationValidation.Validate(new ValidOptimization(), seen)
+ );
+
+ Assert.Null(exception);
+ }
+
+ [Fact]
+ public void Validate_InvalidId_ThrowsNamingTheClass()
+ {
+ var seen = new HashSet<Guid>();
+
+ var ex = Assert.Throws<InvalidOperationException>(() =>
+ OptimizationValidation.Validate(new InvalidIdOptimization(), seen)
+ );
+
+ Assert.Contains(nameof(InvalidIdOptimization), ex.Message);
+ }
+
+ [Fact]
+ public void Validate_DuplicateId_ThrowsNamingTheClass()
+ {
+ var seen = new HashSet<Guid>();
+ OptimizationValidation.Validate(new DuplicateA(), seen);
+
+ var ex = Assert.Throws<InvalidOperationException>(() =>
+ OptimizationValidation.Validate(new DuplicateB(), seen)
+ );
+
+ Assert.Contains(nameof(DuplicateB), ex.Message);
+ }
+
+ [Fact]
+ public void Discovery_AllCatalogIds_AreValidAndUnique()
+ {
+ var seen = new HashSet<Guid>();
+ var count = 0;
+
+ 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
+ )
+ )
+ {
+ var opt = (BaseOptimization)Activator.CreateInstance(nested)!;
+ opt.OwnerType = category;
+ OptimizationValidation.Validate(opt, seen);
+ count++;
+ }
+ }
+
+ Assert.True(count > 0, "No optimizations discovered.");
+ }
+
+ [Fact]
+ public void Discovery_AllCatalogResxKeys_Exist()
+ {
+ var missing = new List<string>();
+
+ 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
+ )
+ )
+ {
+ var key = $"Optimizer.{category.Name}.{nested.Name}.Name";
+ if (
+ Translations.ResourceManager.GetString(key, CultureInfo.InvariantCulture)
+ is null
+ )
+ missing.Add(key);
+ }
+ }
+
+ Assert.True(missing.Count == 0, "Missing resx keys: " + string.Join(", ", missing));
+ }
+}
diff --git a/optimizerDuck.Test/Services/UI/BloatwareServiceTests.cs b/optimizerDuck.Test/Services/UI/BloatwareServiceTests.cs
index 249f8f0..7020409 100644
--- a/optimizerDuck.Test/Services/UI/BloatwareServiceTests.cs
+++ b/optimizerDuck.Test/Services/UI/BloatwareServiceTests.cs
@@ -36,4 +36,34 @@ public class BloatwareServiceTests
Assert.Equal(expected, result);
}
+
+ [Fact]
+ public void ParsePackages_SingleObjectJson_ReturnsOnePackage()
+ {
+ // PowerShell's ConvertTo-Json emits a bare object for one package and an array
+ // for several; the single-object shape must not deserialize to an empty list.
+ const string json = """
+ {"Name":"A.B","PackageFullName":"A.B_1.0.0.0_x64__abc","Publisher":"CN=X","Version":"1.0.0.0","InstallLocation":"","Risk":"Safe"}
+ """;
+
+ var packages = BloatwareService.ParsePackages(json);
+
+ var package = Assert.Single(packages);
+ Assert.Equal("A.B", package.Name);
+ Assert.Equal(AppRisk.Safe, package.Risk);
+ }
+
+ [Fact]
+ public void ParsePackages_ArrayJson_ReturnsAllPackages()
+ {
+ const string json = """
+ [{"Name":"A.B","PackageFullName":"A.B_1.0.0.0_x64__abc","Publisher":"CN=X","Version":"1.0.0.0","InstallLocation":"","Risk":"Safe"},
+ {"Name":"C.D","PackageFullName":"C.D_1.0.0.0_x64__abc","Publisher":"CN=X","Version":"1.0.0.0","InstallLocation":"","Risk":"Caution"}]
+ """;
+
+ var packages = BloatwareService.ParsePackages(json);
+
+ Assert.Equal(2, packages.Count);
+ Assert.Equal(AppRisk.Caution, packages[1].Risk);
+ }
}
diff --git a/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs b/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs
index 023ea17..ffa383b 100644
--- a/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs
+++ b/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs
@@ -1,5 +1,6 @@
using Microsoft.Extensions.Logging.Abstractions;
using optimizerDuck.Domain.Optimizations.Models.Cleanup;
+using optimizerDuck.Services.Optimization.Providers;
using optimizerDuck.Services.UI;
using Wpf.Ui.Controls;
@@ -7,6 +8,12 @@ namespace optimizerDuck.Test.Services.UI;
public class DiskCleanupServiceTests
{
+ private static DiskCleanupService NewService() =>
+ new(
+ NullLogger<DiskCleanupService>.Instance,
+ new ShellService(new ProcessRunner(120000, NullLogger<ProcessRunner>.Instance))
+ );
+
[Fact]
public async Task CleanAsync_DoesNotDeleteFilesInDotNetDirectory()
{
@@ -26,7 +33,7 @@ public class DiskCleanupServiceTests
try
{
- var service = new DiskCleanupService(NullLogger<DiskCleanupService>.Instance);
+ var service = NewService();
var item = new CleanupItem
{
Id = "TempFiles",
@@ -83,7 +90,7 @@ public class DiskCleanupServiceTests
try
{
- var service = new DiskCleanupService(NullLogger<DiskCleanupService>.Instance);
+ var service = NewService();
var item = new CleanupItem
{
Id = "TempFiles",
diff --git a/optimizerDuck.Test/TestCulture.cs b/optimizerDuck.Test/TestCulture.cs
index 6364bbb..5b9589e 100644
--- a/optimizerDuck.Test/TestCulture.cs
+++ b/optimizerDuck.Test/TestCulture.cs
@@ -1,6 +1,13 @@
using System.Globalization;
using System.Runtime.CompilerServices;
using optimizerDuck.Resources.Languages;
+using Xunit;
+
+// The suite exercises the real registry, the real filesystem, real child processes, and
+// process-wide statics (notably Loc.Instance's culture and ReflectionHelper's cache).
+// Running test classes in parallel makes those shared statics race: a culture change in
+// one class flips the localized text another class is asserting on. Serialize instead.
+[assembly: CollectionBehavior(DisableTestParallelization = true)]
namespace optimizerDuck.Test;
diff --git a/optimizerDuck.Test/TestDoubles/TestShell.cs b/optimizerDuck.Test/TestDoubles/TestShell.cs
new file mode 100644
index 0000000..6e0f910
--- /dev/null
+++ b/optimizerDuck.Test/TestDoubles/TestShell.cs
@@ -0,0 +1,13 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Services.Optimization.Providers;
+
+namespace optimizerDuck.Test.TestDoubles;
+
+/// <summary>Builds a <see cref="ShellService"/> with a fixed timeout for tests that need one.</summary>
+internal static class TestShell
+{
+ public const int TimeoutMs = 120_000;
+
+ public static ShellService New() =>
+ new(new ProcessRunner(TimeoutMs, NullLogger<ProcessRunner>.Instance));
+}
diff --git a/optimizerDuck.Test/UI/ViewModels/CustomizeItemViewModelTests.cs b/optimizerDuck.Test/UI/ViewModels/CustomizeItemViewModelTests.cs
index fb4b36c..ae8b46b 100644
--- a/optimizerDuck.Test/UI/ViewModels/CustomizeItemViewModelTests.cs
+++ b/optimizerDuck.Test/UI/ViewModels/CustomizeItemViewModelTests.cs
@@ -3,6 +3,7 @@ using Microsoft.Win32;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
using optimizerDuck.Domain.Customize.Models;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Services.Configuration;
using optimizerDuck.Services.Optimization.Providers;
@@ -54,10 +55,10 @@ public class CustomizeItemViewModelTests : IDisposable
Option("OptionB", TestKeyPath, RegName, 2),
];
- public override async Task ApplyAsync(object? value)
+ public override async Task<OpResult> ApplyAsync(object? value, OpCall call)
{
ApplyCount++;
- await base.ApplyAsync(value);
+ return await base.ApplyAsync(value, call);
}
}
@@ -89,11 +90,17 @@ public class CustomizeItemViewModelTests : IDisposable
return (setting, watcher, vm);
}
- private static void WriteValue(int value) =>
- RegistryService.Write(new RegistryItem(TestKeyPath, RegName, value));
+ private static void WriteValue(int value)
+ {
+ var call = new OpCall { Logger = NullLogger.Instance };
+ RegistryService.Write(call, new RegistryItem(TestKeyPath, RegName, value));
+ }
- private static void DeleteValue() =>
- RegistryService.DeleteValue(new RegistryItem(TestKeyPath, RegName));
+ private static void DeleteValue()
+ {
+ var call = new OpCall { Logger = NullLogger.Instance };
+ RegistryService.DeleteValue(call, new RegistryItem(TestKeyPath, RegName));
+ }
private static object? ReadValue() =>
RegistryService.Read<object>(new RegistryItem(TestKeyPath, RegName));
diff --git a/optimizerDuck/App.xaml.cs b/optimizerDuck/App.xaml.cs
index 4661697..efb76c2 100644
--- a/optimizerDuck/App.xaml.cs
+++ b/optimizerDuck/App.xaml.cs
@@ -365,72 +365,16 @@ public partial class App : Application
ConfigManager.ValidateConfig(loggerFactory.CreateLogger(typeof(ConfigManager)));
c.AddJsonFile(Path.Combine(Shared.RootDirectory, "appsettings.json"), false, true);
})
+ // Fail fast instead of discovering a broken graph later: ValidateOnBuild catches
+ // an unbuildable registration, ValidateScopes catches a scoped service leaking
+ // into a singleton (the ChangeSet must never be resolved from the root provider).
+ .UseDefaultServiceProvider(options =>
+ {
+ options.ValidateOnBuild = true;
+ options.ValidateScopes = true;
+ })
.ConfigureServices(
- (context, services) =>
- {
- services.Configure<AppSettings>(context.Configuration);
-
- // WPF UI shi
- services.AddNavigationViewPageProvider();
- services.AddSingleton<INavigationService, NavigationService>();
- services.AddSingleton<IContentDialogService, ContentDialogService>();
- services.AddSingleton<ISnackbarService, SnackbarService>();
-
- // Windows
- services.AddSingleton<MainWindow>();
- services.AddSingleton<MainWindowViewModel>();
-
- // Pages
- services.AddSingleton<DashboardViewModel>();
- services.AddSingleton<DashboardPage>();
-
- services.AddSingleton<OptimizeViewModel>();
- services.AddSingleton<OptimizePage>();
-
- services.AddSingleton<SettingsViewModel>();
- services.AddSingleton<SettingsPage>();
-
- services.AddSingleton<BloatwareViewModel>();
- services.AddSingleton<BloatwarePage>();
-
- services.AddSingleton<DiskCleanupViewModel>();
- services.AddSingleton<DiskCleanupPage>();
-
- services.AddSingleton<StartupManagerViewModel>();
- services.AddSingleton<StartupManagerPage>();
-
- services.AddSingleton<ScheduledTasksViewModel>();
- services.AddSingleton<ScheduledTasksPage>();
-
- // Dialogs
- services.AddTransient<optimizerDuck.UI.ViewModels.Dialogs.LegalDialogViewModel>();
- services.AddTransient<optimizerDuck.UI.Dialogs.LegalDialog>();
-
- // Customize
- services.AddSingleton<CustomizeViewModel>();
- services.AddSingleton<CustomizePage>();
-
- services.AddAllCustomizeCategoryPages();
-
- // Optimizations
- services.AddAllOptimizationPages();
-
- // Managers
- services.AddSingleton<ConfigManager>();
- services.AddSingleton<RevertManager>();
-
- // Services
- services.AddSingleton<OptimizationRegistry>();
- services.AddSingleton<CustomizeRegistry>();
- services.AddSingleton<OptimizationService>();
- services.AddSingleton<BloatwareService>();
- services.AddSingleton<DiskCleanupService>();
- services.AddSingleton<StartupManagerService>();
- services.AddSingleton<SystemInfoService>();
- services.AddSingleton<StreamService>();
- services.AddSingleton<UpdaterService>();
- services.AddSingleton<IRegistryWatcher, RegistryWatcher>();
- }
+ (context, services) => services.AddOptimizerApplication(context.Configuration)
)
.Build();
@@ -442,9 +386,6 @@ public partial class App : Application
var appOptionsMonitor = _host.Services.GetRequiredService<IOptionsMonitor<AppSettings>>();
- // init shell service with config
- ShellService.Init(appOptionsMonitor);
-
// init WMI helper for cleanup on abnormal termination
WmiHelper.Initialize();
@@ -493,6 +434,8 @@ public partial class App : Application
_logger.LogInformation("Preloading customize settings...");
var customizeRegistry = _host.Services.GetRequiredService<CustomizeRegistry>();
await customizeRegistry.PreloadCategoriesAsync().ConfigureAwait(false);
+
+ RevertManager.RemoveOrphanedTempFiles(_logger);
}
protected override async void OnExit(ExitEventArgs e)
@@ -550,14 +493,17 @@ public partial class App : Application
case ContentDialogResult.Primary:
_logger.LogInformation("User chose to restart PC.");
- ShellService.CMD("shutdown /r /t 0");
+ await _host!
+ .Services.GetRequiredService<ShellService>()
+ .QueryCMDAsync("shutdown /r /t 0");
break;
case ContentDialogResult.Secondary:
_logger.LogInformation("User chose to restart Explorer.");
- ShellService.CMD("taskkill /f /im explorer.exe && start explorer.exe");
-
+ await _host!
+ .Services.GetRequiredService<ShellService>()
+ .QueryCMDAsync("taskkill /f /im explorer.exe && start explorer.exe");
_allowClose = true;
Current.Shutdown();
break;
diff --git a/optimizerDuck/ApplicationServiceCollectionExtensions.cs b/optimizerDuck/ApplicationServiceCollectionExtensions.cs
new file mode 100644
index 0000000..af187a6
--- /dev/null
+++ b/optimizerDuck/ApplicationServiceCollectionExtensions.cs
@@ -0,0 +1,110 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using optimizerDuck.Common.Extensions;
+using optimizerDuck.Domain.Abstractions;
+using optimizerDuck.Domain.Configuration;
+using optimizerDuck.Services.Configuration;
+using optimizerDuck.Services.Customize;
+using optimizerDuck.Services.Optimization;
+using optimizerDuck.Services.Optimization.Providers;
+using optimizerDuck.Services.Revert;
+using optimizerDuck.Services.System;
+using optimizerDuck.Services.UI;
+using optimizerDuck.UI.Pages;
+using optimizerDuck.UI.ViewModels.Dialogs;
+using optimizerDuck.UI.ViewModels.Pages;
+using optimizerDuck.UI.ViewModels.Windows;
+using optimizerDuck.UI.Windows;
+using Wpf.Ui;
+using Wpf.Ui.DependencyInjection;
+
+namespace optimizerDuck;
+
+/// <summary>
+/// Application DI registrations, separated from the hosting bootstrap in
+/// <see cref="App"/> so the whole graph can be built in a test.
+/// </summary>
+public static class ApplicationServiceCollectionExtensions
+{
+ /// <summary>
+ /// Registers the WPF shell, pages, view models, and application services.
+ /// </summary>
+ /// <remarks>
+ /// Every service here is a singleton: the app has a single window and a single
+ /// settings file. Per-operation state (the <c>ChangeSet</c>) is created by
+ /// <c>OptimizationService</c> for each apply, not by DI.
+ /// </remarks>
+ public static IServiceCollection AddOptimizerApplication(
+ this IServiceCollection services,
+ IConfiguration configuration
+ )
+ {
+ ArgumentNullException.ThrowIfNull(services);
+ ArgumentNullException.ThrowIfNull(configuration);
+
+ services.Configure<AppSettings>(configuration);
+
+ // Registered explicitly so the graph is buildable without the host builder, which
+ // otherwise supplies IConfiguration implicitly.
+ services.AddSingleton<IConfiguration>(configuration);
+
+ // WPF UI shell
+ services.AddNavigationViewPageProvider();
+ services.AddSingleton<INavigationService, NavigationService>();
+ services.AddSingleton<IContentDialogService, ContentDialogService>();
+ services.AddSingleton<ISnackbarService, SnackbarService>();
+
+ // Windows
+ services.AddSingleton<MainWindow>();
+ services.AddSingleton<MainWindowViewModel>();
+
+ // Pages
+ services.AddSingleton<DashboardViewModel>();
+ services.AddSingleton<DashboardPage>();
+ services.AddSingleton<OptimizeViewModel>();
+ services.AddSingleton<OptimizePage>();
+ services.AddSingleton<SettingsViewModel>();
+ services.AddSingleton<SettingsPage>();
+ services.AddSingleton<BloatwareViewModel>();
+ services.AddSingleton<BloatwarePage>();
+ services.AddSingleton<DiskCleanupViewModel>();
+ services.AddSingleton<DiskCleanupPage>();
+ services.AddSingleton<StartupManagerViewModel>();
+ services.AddSingleton<StartupManagerPage>();
+ services.AddSingleton<ScheduledTasksViewModel>();
+ services.AddSingleton<ScheduledTasksPage>();
+
+ // Dialogs
+ services.AddTransient<LegalDialogViewModel>();
+ services.AddTransient<optimizerDuck.UI.Dialogs.LegalDialog>();
+
+ // Customize
+ services.AddSingleton<CustomizeViewModel>();
+ services.AddSingleton<CustomizePage>();
+ services.AddAllCustomizeCategoryPages();
+
+ // Optimizations
+ services.AddAllOptimizationPages();
+
+ // Managers
+ services.AddSingleton<ConfigManager>();
+ services.AddSingleton<RevertManager>();
+ services.AddSingleton(TimeProvider.System);
+
+ // Services
+ services.AddSingleton<ProcessRunner>();
+ services.AddSingleton<ShellService>();
+ services.AddSingleton<OptimizationRegistry>();
+ services.AddSingleton<CustomizeRegistry>();
+ services.AddSingleton<OptimizationService>();
+ services.AddSingleton<BloatwareService>();
+ services.AddSingleton<DiskCleanupService>();
+ services.AddSingleton<StartupManagerService>();
+ services.AddSingleton<SystemInfoService>();
+ services.AddSingleton<StreamService>();
+ services.AddSingleton<UpdaterService>();
+ services.AddSingleton<IRegistryWatcher, RegistryWatcher>();
+
+ return services;
+ }
+}
diff --git a/optimizerDuck/Common/Extensions/CustomizePageRegistryExtensions.cs b/optimizerDuck/Common/Extensions/CustomizePageRegistryExtensions.cs
deleted file mode 100644
index d6a36e3..0000000
--- a/optimizerDuck/Common/Extensions/CustomizePageRegistryExtensions.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-using System.Reflection;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Logging;
-using optimizerDuck.Common.Helpers;
-using optimizerDuck.Domain.Abstractions;
-using optimizerDuck.Domain.Attributes;
-using optimizerDuck.Services.Customize;
-using optimizerDuck.Services.System;
-using optimizerDuck.UI.ViewModels.Pages;
-
-namespace optimizerDuck.Common.Extensions;
-
-public static class CustomizePageRegistryExtensions
-{
- public static void AddAllCustomizeCategoryPages(this IServiceCollection services)
- {
- var categoryTypes =
- ReflectionHelper.FindImplementationsInLoadedAssemblies<ICustomizeCategory>();
-
- foreach (var categoryType in categoryTypes)
- {
- var attr = categoryType.GetCustomAttribute<CustomizeCategoryAttribute>();
- if (attr?.PageType != null)
- {
- var pageType = attr.PageType;
- services.AddSingleton(pageType, sp => CreatePage(sp, categoryType, pageType));
- }
- }
- }
-
- private static object CreatePage(
- IServiceProvider serviceProvider,
- Type categoryType,
- Type pageType
- )
- {
- var registry = serviceProvider.GetRequiredService<CustomizeRegistry>();
- var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
- var registryWatcher = serviceProvider.GetRequiredService<IRegistryWatcher>();
- var systemInfoService = serviceProvider.GetRequiredService<SystemInfoService>();
-
- var category = registry.Categories.First(c => c.GetType() == categoryType);
-
- var viewModel = new CustomizeCategoryViewModel(
- category,
- loggerFactory,
- registryWatcher,
- systemInfoService
- );
-
- return Activator.CreateInstance(pageType, viewModel)!;
- }
-}
diff --git a/optimizerDuck/Common/Extensions/OptimizationPageRegistryExtensions.cs b/optimizerDuck/Common/Extensions/OptimizationPageRegistryExtensions.cs
index 1865f64..9f6e37e 100644
--- a/optimizerDuck/Common/Extensions/OptimizationPageRegistryExtensions.cs
+++ b/optimizerDuck/Common/Extensions/OptimizationPageRegistryExtensions.cs
@@ -6,61 +6,107 @@ using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
using optimizerDuck.Domain.Configuration;
+using optimizerDuck.Services.Customize;
using optimizerDuck.Services.Optimization;
using optimizerDuck.Services.Revert;
using optimizerDuck.Services.System;
+using optimizerDuck.UI.ViewModels.Optimizer;
+using optimizerDuck.UI.ViewModels.Pages;
using Wpf.Ui;
using OptimizationCategoryViewModel = optimizerDuck.UI.ViewModels.Optimizer.OptimizationCategoryViewModel;
namespace optimizerDuck.Common.Extensions;
-public static class OptimizationPageRegistryExtensions
+/// <summary>
+/// Shared plumbing for the reflection-discovered category pages. Kept in one place so
+/// the optimization and customize paths cannot drift apart.
+/// </summary>
+/// <remarks>
+/// A category page needs the <em>discovered category instance</em> (built by the
+/// registry during preload, not by the container), so the page is registered against a
+/// factory that pulls it from the registry. Everything else in the view model comes
+/// from DI.
+/// </remarks>
+internal static class CategoryPageFactory
{
- public static void AddAllOptimizationPages(this IServiceCollection services)
+ /// <summary>Registers one singleton page per discovered category type.</summary>
+ public static void AddCategoryPages<TCategory>(
+ IServiceCollection services,
+ Func<Type, Type?> resolvePageType,
+ Func<IServiceProvider, Type, object> createViewModel
+ )
+ where TCategory : class
{
- var categoryTypes =
- ReflectionHelper.FindImplementationsInLoadedAssemblies<IOptimizationCategory>();
+ ArgumentNullException.ThrowIfNull(services);
+ ArgumentNullException.ThrowIfNull(resolvePageType);
+ ArgumentNullException.ThrowIfNull(createViewModel);
- foreach (var categoryType in categoryTypes)
+ foreach (
+ var categoryType in ReflectionHelper.FindImplementationsInLoadedAssemblies<TCategory>()
+ )
{
- var attr = categoryType.GetCustomAttribute<OptimizationCategoryAttribute>()!;
- var pageType = attr.PageType!;
+ var pageType = resolvePageType(categoryType);
+ if (pageType is null)
+ continue;
+ var capturedCategoryType = categoryType;
services.AddSingleton(
pageType,
- sp => CreateOptimizationPage(sp, categoryType, pageType)
+ sp => Activator.CreateInstance(pageType, createViewModel(sp, capturedCategoryType))!
);
}
}
+}
- private static object CreateOptimizationPage(
- IServiceProvider serviceProvider,
- Type categoryType,
- Type pageType
- )
+/// <summary>Registers the optimize-category pages discovered on <see cref="IOptimizationCategory"/>.</summary>
+public static class OptimizationPageRegistryExtensions
+{
+ public static void AddAllOptimizationPages(this IServiceCollection services)
{
- var optimizationRegistry = serviceProvider.GetRequiredService<OptimizationRegistry>();
- var optimizationService = serviceProvider.GetRequiredService<OptimizationService>();
- var revertManager = serviceProvider.GetRequiredService<RevertManager>();
- var snackbarService = serviceProvider.GetRequiredService<ISnackbarService>();
- var contentDialogService = serviceProvider.GetRequiredService<IContentDialogService>();
- var systemInfoService = serviceProvider.GetRequiredService<SystemInfoService>();
- var logger = serviceProvider.GetRequiredService<ILogger<OptimizationCategoryViewModel>>();
- var appOptionsMonitor = serviceProvider.GetRequiredService<IOptionsMonitor<AppSettings>>();
+ CategoryPageFactory.AddCategoryPages<IOptimizationCategory>(
+ services,
+ categoryType =>
+ categoryType.GetCustomAttribute<OptimizationCategoryAttribute>()?.PageType,
+ CreateViewModel
+ );
+ }
- var optimizationCategoryType = optimizationRegistry.GetCategory(categoryType);
+ private static object CreateViewModel(IServiceProvider sp, Type categoryType)
+ {
+ return new OptimizationCategoryViewModel(
+ sp.GetRequiredService<OptimizationRegistry>().GetCategory(categoryType),
+ sp.GetRequiredService<OptimizationService>(),
+ sp.GetRequiredService<RevertManager>(),
+ sp.GetRequiredService<ISnackbarService>(),
+ sp.GetRequiredService<IContentDialogService>(),
+ sp.GetRequiredService<SystemInfoService>(),
+ sp.GetRequiredService<ILogger<OptimizationCategoryViewModel>>(),
+ sp.GetRequiredService<IOptionsMonitor<AppSettings>>()
+ );
+ }
+}
- var viewModel = new OptimizationCategoryViewModel(
- optimizationCategoryType,
- optimizationService,
- revertManager,
- snackbarService,
- contentDialogService,
- systemInfoService,
- logger,
- appOptionsMonitor
+/// <summary>Registers the customize-category pages discovered on <see cref="ICustomizeCategory"/>.</summary>
+public static class CustomizePageRegistryExtensions
+{
+ public static void AddAllCustomizeCategoryPages(this IServiceCollection services)
+ {
+ CategoryPageFactory.AddCategoryPages<ICustomizeCategory>(
+ services,
+ categoryType => categoryType.GetCustomAttribute<CustomizeCategoryAttribute>()?.PageType,
+ CreateViewModel
);
+ }
- return Activator.CreateInstance(pageType, viewModel)!;
+ private static object CreateViewModel(IServiceProvider sp, Type categoryType)
+ {
+ var registry = sp.GetRequiredService<CustomizeRegistry>();
+
+ return new CustomizeCategoryViewModel(
+ registry.Categories.First(c => c.GetType() == categoryType),
+ sp.GetRequiredService<ILoggerFactory>(),
+ sp.GetRequiredService<IRegistryWatcher>(),
+ sp.GetRequiredService<SystemInfoService>()
+ );
}
}
diff --git a/optimizerDuck/Common/Helpers/CategoryDiscovery.cs b/optimizerDuck/Common/Helpers/CategoryDiscovery.cs
new file mode 100644
index 0000000..d966e92
--- /dev/null
+++ b/optimizerDuck/Common/Helpers/CategoryDiscovery.cs
@@ -0,0 +1,106 @@
+using System.Reflection;
+
+namespace optimizerDuck.Common.Helpers;
+
+/// <summary>
+/// Reflection-based discovery of category classes and the items nested inside them.
+/// Used by <c>OptimizationRegistry</c> and <c>CustomizeRegistry</c> so no manual
+/// registration array has to be maintained when a category or item is added.
+/// </summary>
+public static class CategoryDiscovery
+{
+ /// <summary>
+ /// Builds one instance per discovered category type, populating the collection
+ /// property named <paramref name="itemsPropertyName"/> with its nested items.
+ /// Categories that contain no items are skipped.
+ /// </summary>
+ /// <param name="itemsPropertyName">The public collection property to fill (e.g. <c>Optimizations</c>).</param>
+ /// <param name="buildItems">Builds the nested items for a category type.</param>
+ /// <param name="orderBy">Sort key applied to the resulting categories.</param>
+ public static TCategory[] Discover<TCategory, TItem>(
+ string itemsPropertyName,
+ Func<Type, List<TItem>> buildItems,
+ Func<TCategory, int> orderBy
+ )
+ where TCategory : class
+ {
+ ArgumentNullException.ThrowIfNull(itemsPropertyName);
+ ArgumentNullException.ThrowIfNull(buildItems);
+ ArgumentNullException.ThrowIfNull(orderBy);
+
+ var categories = new List<TCategory>();
+
+ foreach (
+ var categoryType in ReflectionHelper.FindImplementationsInLoadedAssemblies<TCategory>()
+ )
+ {
+ var items = buildItems(categoryType);
+ if (items.Count == 0)
+ continue;
+
+ var instance = (TCategory)Activator.CreateInstance(categoryType)!;
+ PopulateItems(instance, categoryType, itemsPropertyName, items);
+ categories.Add(instance);
+ }
+
+ return categories.OrderBy(orderBy).ToArray();
+ }
+
+ /// <summary>
+ /// Instantiates every public nested class assignable to <typeparamref name="TItem"/>.
+ /// </summary>
+ /// <param name="category">The category type whose nested types are scanned.</param>
+ /// <param name="init">Optional callback invoked with each item and its owning category.</param>
+ public static List<TItem> NestedItems<TItem>(Type category, Action<TItem, Type>? init = null)
+ where TItem : class
+ {
+ ArgumentNullException.ThrowIfNull(category);
+
+ var items = new List<TItem>();
+
+ foreach (var nested in category.GetNestedTypes(BindingFlags.Public))
+ {
+ if (!typeof(TItem).IsAssignableFrom(nested) || !nested.IsClass || nested.IsAbstract)
+ continue;
+
+ var item = (TItem)Activator.CreateInstance(nested)!;
+ init?.Invoke(item, category);
+ items.Add(item);
+ }
+
+ return items;
+ }
+
+ /// <summary>
+ /// Assigns the built items to the category's collection property, adapting a
+ /// <see cref="List{T}"/> to whatever collection type the property declares.
+ /// </summary>
+ private static void PopulateItems<TCategory, TItem>(
+ TCategory instance,
+ Type categoryType,
+ string itemsPropertyName,
+ List<TItem> items
+ )
+ where TCategory : class
+ {
+ var property = categoryType.GetProperty(
+ itemsPropertyName,
+ BindingFlags.Public | BindingFlags.Instance
+ );
+
+ if (property is not { CanWrite: true })
+ {
+ throw new InvalidOperationException(
+ $"Category '{categoryType.FullName}' must expose a writable '{itemsPropertyName}' collection."
+ );
+ }
+
+ // List<T> matches the property type directly; otherwise build the declared
+ // collection from the same items (e.g. ObservableCollection<T>).
+ var value = property.PropertyType.IsAssignableFrom(items.GetType())
+ ? items
+ : Activator.CreateInstance(property.PropertyType, items);
+
+ property.SetValue(instance, value);
+ }
+}
diff --git a/optimizerDuck/Common/Helpers/ReflectionHelper.cs b/optimizerDuck/Common/Helpers/ReflectionHelper.cs
index 6c8c2fc..24a0e37 100644
--- a/optimizerDuck/Common/Helpers/ReflectionHelper.cs
+++ b/optimizerDuck/Common/Helpers/ReflectionHelper.cs
@@ -22,7 +22,7 @@ public static class ReflectionHelper
}
private static readonly Dictionary<Type, List<Type>> _implementationCache = new();
- private static readonly object _cacheLock = new();
+ private static readonly Lock _cacheLock = new();
public static IEnumerable<Type> FindImplementationsInLoadedAssemblies(Type interfaceType)
{
diff --git a/optimizerDuck/Domain/Abstractions/ICustomizeSetting.cs b/optimizerDuck/Domain/Abstractions/ICustomizeSetting.cs
index f612863..e1641f7 100644
--- a/optimizerDuck/Domain/Abstractions/ICustomizeSetting.cs
+++ b/optimizerDuck/Domain/Abstractions/ICustomizeSetting.cs
@@ -52,8 +52,12 @@ public interface ICustomizeSetting
/// </summary>
Task<bool> GetStateWithRetryAsync(int maxRetries = 3, int delayMs = 80);
- /// <summary>Applies a bool (toggles) or a declared dropdown option value.</summary>
- Task ApplyAsync(object? value);
+ /// <summary>
+ /// Applies the value, recording every write into <paramref name="call"/>
+ /// for change tracking and revert. The first failure wins the return,
+ /// but all writes are still attempted.
+ /// </summary>
+ Task<Execution.OpResult> ApplyAsync(object? value, Execution.OpCall call);
/// <summary>
/// Registry key paths that should be watched for external changes,
diff --git a/optimizerDuck/Domain/Abstractions/IRevertStep.cs b/optimizerDuck/Domain/Abstractions/IRevertStep.cs
index d43da69..366b352 100644
--- a/optimizerDuck/Domain/Abstractions/IRevertStep.cs
+++ b/optimizerDuck/Domain/Abstractions/IRevertStep.cs
@@ -1,4 +1,7 @@
-using Newtonsoft.Json.Linq;
+using Microsoft.Extensions.Logging;
+using Newtonsoft.Json.Linq;
+using optimizerDuck.Domain.Optimizations.Models.Services;
+using optimizerDuck.Services.Optimization.Providers;
namespace optimizerDuck.Domain.Abstractions;
@@ -20,8 +23,10 @@ public interface IRevertStep
/// <summary>
/// Executes this revert step asynchronously.
/// </summary>
+ /// <param name="shell">The application shell service, so command-executing steps use the configured timeout.</param>
+ /// <param name="logger">The logger to record provider and shell operations.</param>
/// <returns><c>true</c> if the revert succeeded; otherwise, <c>false</c>.</returns>
- Task<bool> ExecuteAsync();
+ Task<bool> ExecuteAsync(ShellService shell, ILogger logger);
/// <summary>
/// Serializes this revert step to a JSON object for persistence.
diff --git a/optimizerDuck/Domain/Attributes/CustomizeSettingAttribute.cs b/optimizerDuck/Domain/Attributes/CustomizeSettingAttribute.cs
index 4c3884c..cbbc7ef 100644
--- a/optimizerDuck/Domain/Attributes/CustomizeSettingAttribute.cs
+++ b/optimizerDuck/Domain/Attributes/CustomizeSettingAttribute.cs
@@ -6,7 +6,7 @@ namespace optimizerDuck.Domain.Attributes;
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public sealed class CustomizeSettingAttribute : Attribute
{
- public object? Section { get; init; }
+ public string? Section { get; init; }
public required SymbolRegular Icon { get; init; }
public RecommendationState Recommendation { get; init; } = RecommendationState.None;
@@ -19,11 +19,6 @@ public sealed class CustomizeSettingAttribute : Attribute
public string GetSectionName()
{
- if (Section == null)
- return string.Empty;
-
- return Section is Enum e
- ? Enum.GetName(e.GetType(), e) ?? string.Empty
- : Section.ToString() ?? string.Empty;
+ return Section ?? string.Empty;
}
}
diff --git a/optimizerDuck/Domain/Customize/Categories/Desktop.cs b/optimizerDuck/Domain/Customize/Categories/Desktop.cs
index aa0eb49..88bd2ce 100644
--- a/optimizerDuck/Domain/Customize/Categories/Desktop.cs
+++ b/optimizerDuck/Domain/Customize/Categories/Desktop.cs
@@ -4,6 +4,7 @@ using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
using optimizerDuck.Domain.Customize.Models;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.UI;
using optimizerDuck.Services.Configuration;
@@ -194,14 +195,15 @@ public class Desktop : LocalizedObject, ICustomizeCategory
return Task.FromResult(!isHidden);
}
- public override async Task ApplyAsync(object? value)
+ public override async Task<OpResult> ApplyAsync(object? value, OpCall call)
{
var isOn = value is bool b && b;
+ OpResult result;
if (isOn)
{
// restore default Windows behavior by deleting the value
- RegistryService.DeleteValue(new RegistryItem(Path, "29"));
+ result = RegistryService.DeleteValue(call, new RegistryItem(Path, "29"));
}
else
{
@@ -214,10 +216,11 @@ public class Desktop : LocalizedObject, ICustomizeCategory
EmbeddedResourceHelper.TryExtract("Icons.blank.ico", outputPath);
// set the registry value to point to the blank icon, which effectively hides the shortcut arrow overlay
- RegistryService.Write(new RegistryItem(Path, "29", outputPath));
+ result = RegistryService.Write(call, new RegistryItem(Path, "29", outputPath));
}
await ExecutePostActionAsync();
+ return result;
}
}
}
diff --git a/optimizerDuck/Domain/Customize/Categories/Gaming.cs b/optimizerDuck/Domain/Customize/Categories/Gaming.cs
index 9ea7a57..499986d 100644
--- a/optimizerDuck/Domain/Customize/Categories/Gaming.cs
+++ b/optimizerDuck/Domain/Customize/Categories/Gaming.cs
@@ -4,6 +4,7 @@ using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
using optimizerDuck.Domain.Conditions;
using optimizerDuck.Domain.Customize.Models;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.UI;
using optimizerDuck.Services.Configuration;
@@ -201,16 +202,22 @@ public class Gaming : LocalizedObject, ICustomizeCategory
});
}
- public override async Task ApplyAsync(object? value)
+ public override async Task<OpResult> ApplyAsync(object? value, OpCall call)
{
var isOn = value is bool b && b;
- RegistryService.Write(new RegistryItem(Path, "MouseSpeed", isOn ? "1" : "0"));
- RegistryService.Write(new RegistryItem(Path, "MouseThreshold1", isOn ? "6" : "0"));
- RegistryService.Write(new RegistryItem(Path, "MouseThreshold2", isOn ? "10" : "0"));
+ // Batch call: every value is attempted, the first failure is returned.
+ var result = RegistryService.Write(
+ call,
+ new RegistryItem(Path, "MouseSpeed", isOn ? "1" : "0"),
+ new RegistryItem(Path, "MouseThreshold1", isOn ? "6" : "0"),
+ new RegistryItem(Path, "MouseThreshold2", isOn ? "10" : "0")
+ );
if (NeedsPostAction)
await ExecutePostActionAsync();
+
+ return result;
}
}
diff --git a/optimizerDuck/Domain/Customize/Categories/Preferences.cs b/optimizerDuck/Domain/Customize/Categories/Preferences.cs
index 8e84335..599966e 100644
--- a/optimizerDuck/Domain/Customize/Categories/Preferences.cs
+++ b/optimizerDuck/Domain/Customize/Categories/Preferences.cs
@@ -5,6 +5,7 @@ using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
using optimizerDuck.Domain.Conditions;
using optimizerDuck.Domain.Customize.Models;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.UI;
using optimizerDuck.Services.Configuration;
@@ -513,17 +514,20 @@ public class Preferences : LocalizedObject, ICustomizeCategory
return Task.FromResult(exists);
}
- public override async Task ApplyAsync(object? value)
+ public override async Task<OpResult> ApplyAsync(object? value, OpCall call)
{
var isOn = value is bool b && b;
+ OpResult result;
if (isOn)
- RegistryService.Write(new RegistryItem(InprocPath, null, ""));
+ result = RegistryService.Write(call, new RegistryItem(InprocPath, null, ""));
else
- RegistryService.DeleteSubKeyTree(new RegistryItem(BasePath));
+ result = RegistryService.DeleteSubKeyTree(call, new RegistryItem(BasePath));
if (NeedsPostAction)
await ExecutePostActionAsync();
+
+ return result;
}
}
diff --git a/optimizerDuck/Domain/Customize/Categories/SystemFeatures.cs b/optimizerDuck/Domain/Customize/Categories/SystemFeatures.cs
index 5572a93..b1891eb 100644
--- a/optimizerDuck/Domain/Customize/Categories/SystemFeatures.cs
+++ b/optimizerDuck/Domain/Customize/Categories/SystemFeatures.cs
@@ -6,6 +6,7 @@ using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
using optimizerDuck.Domain.Conditions;
using optimizerDuck.Domain.Customize.Models;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.UI;
using optimizerDuck.Services.Configuration;
@@ -72,7 +73,7 @@ public class SystemFeatures : LocalizedObject, ICustomizeCategory
});
}
- public override async Task ApplyAsync(object? value)
+ public override async Task<OpResult> ApplyAsync(object? value, OpCall call)
{
var isOn = value is bool b && b;
@@ -83,15 +84,14 @@ public class SystemFeatures : LocalizedObject, ICustomizeCategory
new RegistryItem(PathDefault, ValueName)
);
- RegistryService.Write(
+ var result = RegistryService.Write(
+ call,
new RegistryItem(
PathCurrent,
ValueName,
SetNumLockBit(currentRaw, isOn),
RegistryValueKind.String
- )
- );
- RegistryService.Write(
+ ),
new RegistryItem(
PathDefault,
ValueName,
@@ -102,6 +102,8 @@ public class SystemFeatures : LocalizedObject, ICustomizeCategory
if (NeedsPostAction)
await ExecutePostActionAsync();
+
+ return result;
}
private static string SetNumLockBit(object? raw, bool enabled)
diff --git a/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs b/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs
index 4a6bbd6..7aaaf3e 100644
--- a/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs
+++ b/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs
@@ -4,6 +4,7 @@ using optimizerDuck.Common.Extensions;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Services.Configuration;
using optimizerDuck.Services.Optimization.Providers;
@@ -29,7 +30,7 @@ public abstract partial class BaseCustomizeSetting : LocalizedObject, ICustomize
$"{GetType().Name} is missing [CustomizeSetting] attribute"
);
- public Type? OwnerType { get; set; }
+ public Type? OwnerType { get; internal set; }
public string OwnerKey =>
OwnerType?.Name
@@ -198,40 +199,70 @@ public abstract partial class BaseCustomizeSetting : LocalizedObject, ICustomize
/// <summary>
/// Applies the value to the registry: for toggles a <see cref="bool"/>, for
/// dropdowns the matching declared option's bindings. Then runs any post-apply
- /// Windows refresh declared by <see cref="RefreshScope"/>.
+ /// Windows refresh declared by <see cref="RefreshScope"/>. Every write is
+ /// recorded into <paramref name="call"/> (provider-stable keys). The first
+ /// failure wins the return, but all writes are still attempted (partial
+ /// application recorded).
/// </summary>
/// <param name="value">The value to apply. The synthetic "Custom"/"Not set" fallback
/// value is a safe no-op.</param>
- public virtual async Task ApplyAsync(object? value)
+ /// <param name="call">The explicit per-operation call context (change collector, logger, cancellation).</param>
+ /// <returns>The first failure, or success when every write succeeded.</returns>
+ public virtual async Task<OpResult> ApplyAsync(object? value, OpCall call)
{
+ OpResult? firstFailure = null;
+
if (value is bool isOn)
{
- await Task.Run(() =>
+ // Attempt every toggle even after a failure; the first failure
+ // wins the return while partial application stays recorded.
+ foreach (var toggle in RegistryToggles)
{
- foreach (var toggle in RegistryToggles)
- toggle.SetState(isOn);
- });
+ try
+ {
+ var toggleResult = toggle.SetState(isOn, call);
+ if (!toggleResult.Ok)
+ firstFailure ??= toggleResult;
+ }
+ catch (Exception ex)
+ {
+ firstFailure ??= OpResult.Fail($"Failed to apply {LogName}", ex.Message);
+ }
+ }
}
else if (ControlType == CustomizeControlType.Dropdown && GetOptions() is { } options)
{
// Find the matching declared option and apply all its bindings. The
// "Custom"/"Not set" fallback is never a declared option, so applying it
// is a safe no-op.
- var option = options.FirstOrDefault(o => Equals(o.Value, value));
+ var option = options.FirstOrDefault(o => ValuesEqual(o.Value, value));
if (option?.Bindings is { Count: > 0 })
{
- foreach (var binding in option.Bindings)
- {
- if (binding.Value == null)
- RegistryService.DeleteValue(new RegistryItem(binding.Path, binding.Name));
- else
- RegistryService.Write(binding.ToRegistryItem());
- }
+ // Split by action, then batch: a binding with no value deletes the value.
+ var toWrite = option
+ .Bindings.Where(b => b.Value != null)
+ .Select(b => b.ToRegistryItem())
+ .ToArray();
+ var toDelete = option
+ .Bindings.Where(b => b.Value == null)
+ .Select(b => new RegistryItem(b.Path, b.Name))
+ .ToArray();
+
+ // All bindings are attempted; the first failure wins the return.
+ var results = new List<OpResult>();
+ if (toDelete.Length > 0)
+ results.Add(RegistryService.DeleteValue(call, toDelete));
+ if (toWrite.Length > 0)
+ results.Add(RegistryService.Write(call, toWrite));
+
+ firstFailure = OpResult.FirstFailure(results);
}
}
if (NeedsPostAction)
await ExecutePostActionAsync();
+
+ return firstFailure ?? OpResult.Success();
}
protected virtual IEnumerable<RegistryToggle> RegistryToggles => [];
diff --git a/optimizerDuck/Domain/Customize/Models/RegistryToggle.cs b/optimizerDuck/Domain/Customize/Models/RegistryToggle.cs
index d089654..8792255 100644
--- a/optimizerDuck/Domain/Customize/Models/RegistryToggle.cs
+++ b/optimizerDuck/Domain/Customize/Models/RegistryToggle.cs
@@ -1,4 +1,5 @@
using Microsoft.Win32;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Services.Optimization.Providers;
@@ -56,15 +57,21 @@ public class RegistryToggle
return IsValueInList(value, OnValues);
}
- public void SetState(bool isOn)
+ /// <summary>
+ /// Writes the on/off state to the registry, recording the change into
+ /// <paramref name="call"/>. The first value in the target list is the
+ /// primary value written; a leading <c>null</c> deletes the value.
+ /// </summary>
+ /// <returns>The provider result; a failed write is returned, not thrown.</returns>
+ public OpResult SetState(bool isOn, OpCall call)
{
var targetValues = isOn ? OnValues : OffValues;
// First value in the list is the primary value to write
if (targetValues is { Count: > 0 } && targetValues[0] is { } firstValue)
- RegistryService.Write(new RegistryItem(Path, Name, firstValue, ValueKind));
- else
- RegistryService.DeleteValue(new RegistryItem(Path, Name));
+ return RegistryService.Write(call, new RegistryItem(Path, Name, firstValue, ValueKind));
+
+ return RegistryService.DeleteValue(call, new RegistryItem(Path, Name));
}
private object? GetRawValue()
diff --git a/optimizerDuck/Domain/Execution/ChangeSet.cs b/optimizerDuck/Domain/Execution/ChangeSet.cs
new file mode 100644
index 0000000..764f0b2
--- /dev/null
+++ b/optimizerDuck/Domain/Execution/ChangeSet.cs
@@ -0,0 +1,143 @@
+using optimizerDuck.Domain.Abstractions;
+using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Services.Configuration;
+
+namespace optimizerDuck.Domain.Execution;
+
+/// <summary>
+/// Thread-safe collector of changes made during one apply operation.
+/// Providers append here via <see cref="OpCall"/>; the engine derives
+/// results and revert data from the collected changes.
+/// </summary>
+public sealed class ChangeSet
+{
+ private readonly List<Change> _changes = [];
+ private readonly Lock _gate = new();
+ private int _sequence;
+
+ /// <summary>All recorded changes in execution order.</summary>
+ public IReadOnlyList<Change> Changes
+ {
+ get
+ {
+ lock (_gate)
+ return _changes.ToList();
+ }
+ }
+
+ /// <summary>Only the successful changes.</summary>
+ public IReadOnlyList<Change> SuccessfulSteps
+ {
+ get
+ {
+ lock (_gate)
+ return _changes.Where(c => c.Ok).ToList();
+ }
+ }
+
+ /// <summary>Only the failed changes.</summary>
+ public IReadOnlyList<Change> FailedSteps
+ {
+ get
+ {
+ lock (_gate)
+ return _changes.Where(c => !c.Ok).ToList();
+ }
+ }
+
+ /// <summary>Whether at least one change succeeded.</summary>
+ public bool HasSuccessfulSteps
+ {
+ get
+ {
+ lock (_gate)
+ return _changes.Any(c => c.Ok);
+ }
+ }
+
+ /// <summary>Whether at least one change failed.</summary>
+ public bool HasFailedSteps
+ {
+ get
+ {
+ lock (_gate)
+ return _changes.Any(c => !c.Ok);
+ }
+ }
+
+ /// <summary>Adds a change with an auto-incremented execution index.</summary>
+ public Change Add(
+ string name,
+ string description,
+ bool ok,
+ IRevertStep? revert = null,
+ string? error = null,
+ string? errorDetail = null,
+ Func<OpCall, Task<OpResult>>? retry = null
+ )
+ {
+ var change = new Change
+ {
+ Name = name,
+ Description = description,
+ Ok = ok,
+ Revert = revert,
+ Error = error,
+ ErrorDetail = errorDetail,
+ Retry = retry,
+ };
+ lock (_gate)
+ {
+ _changes.Add(change with { Index = ++_sequence });
+ return _changes[^1];
+ }
+ }
+
+ /// <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.
+ /// </summary>
+ public ApplyResult ToApplyResult(string? fallbackError = null)
+ {
+ lock (_gate)
+ {
+ if (_changes.Count == 0)
+ return ApplyResult.False(fallbackError ?? Loc.Instance["Revert.Error.NoSteps"]);
+ if (_changes.Any(c => c.Ok))
+ return ApplyResult.True();
+ return ApplyResult.False(
+ _changes.FirstOrDefault(c => c.Error != null)?.Error
+ ?? fallbackError
+ ?? Loc.Instance["Optimization.Apply.Error.AllStepsFailed"]
+ );
+ }
+ }
+}
+
+/// <summary>
+/// A single recorded step: what ran, whether it succeeded, the compensation
+/// step for undo, and an optional retry action. <see cref="Index"/> is the
+/// 1-based execution order, preserved as the revert-file index. The same
+/// record is the step result shown to the user.
+/// </summary>
+public sealed record Change
+{
+ public string Name { get; init; } = string.Empty;
+
+ public string Description { get; init; } = string.Empty;
+
+ public int Index { get; init; }
+
+ public bool Ok { get; init; }
+
+ public IRevertStep? Revert { get; init; }
+
+ public string? Error { get; init; }
+
+ public string? ErrorDetail { get; init; }
+
+ public Func<OpCall, Task<OpResult>>? Retry { get; init; }
+}
diff --git a/optimizerDuck/Domain/Execution/ExecutionScope.cs b/optimizerDuck/Domain/Execution/ExecutionScope.cs
deleted file mode 100644
index 321b79a..0000000
--- a/optimizerDuck/Domain/Execution/ExecutionScope.cs
+++ /dev/null
@@ -1,560 +0,0 @@
-using System.Collections.Concurrent;
-using System.Diagnostics;
-using Microsoft.Extensions.Logging;
-using optimizerDuck.Domain.Abstractions;
-using optimizerDuck.Domain.Optimizations.Models;
-using optimizerDuck.Domain.UI;
-using optimizerDuck.Resources.Languages;
-using optimizerDuck.Services.Configuration;
-
-namespace optimizerDuck.Domain.Execution;
-
-/// <summary>
-/// Tracks the execution of optimization steps within an ambient async context.
-/// Provider services use <see cref="Current"/> to record revert steps without
-/// requiring explicit dependency injection.
-/// </summary>
-public sealed class ExecutionScope : IDisposable
-{
- private static readonly AsyncLocal<ExecutionScope?> _current = new();
- private readonly List<ExecutedStep> _executedSteps = [];
- private readonly ConcurrentDictionary<string, Stats> _stats = new();
-
- private readonly Stopwatch _stopwatch = Stopwatch.StartNew();
- private bool _disposed;
- private int _stepIndex;
-
- /// <summary>Gets the current <see cref="ExecutionScope"/> for the ambient async context.</summary>
- /// <remarks>
- /// Backed by <see cref="AsyncLocal{T}"/>, this flows across async calls without requiring
- /// dependency injection. Provider services read <see cref="Current"/> to record revert steps.
- /// </remarks>
- public static ExecutionScope? Current => _current.Value;
-
- /// <summary>Gets the identifier of the optimization being executed.</summary>
- public Guid? OptimizationId { get; private init; }
-
- /// <summary>Gets the unique key of the optimization being executed.</summary>
- public string? OptimizationKey { get; private init; }
-
- /// <summary>Gets the display name of the optimization being executed.</summary>
- public string? OptimizationName { get; init; }
-
- /// <summary>Gets the logger instance for the current execution scope.</summary>
- public required ILogger Logger { get; init; }
-
- /// <summary>Gets all recorded execution steps in the order they were executed.</summary>
- /// <value>An <see cref="IReadOnlyList{T}"/> of <see cref="ExecutedStep"/> instances.</value>
- public IReadOnlyList<ExecutedStep> ExecutedSteps => _executedSteps.AsReadOnly();
-
- /// <summary>Gets the subset of steps that completed successfully.</summary>
- /// <value>An array of <see cref="ExecutedStep"/> instances where <see cref="ExecutedStep.Success"/> is <see langword="true"/>.</value>
- public IReadOnlyList<ExecutedStep> SuccessfulSteps =>
- _executedSteps.Where(s => s.Success).ToArray();
-
- /// <summary>Gets the subset of steps that failed.</summary>
- /// <value>An array of <see cref="ExecutedStep"/> instances where <see cref="ExecutedStep.Success"/> is <see langword="false"/>.</value>
- public IReadOnlyList<ExecutedStep> FailedSteps =>
- _executedSteps.Where(s => !s.Success).ToArray();
-
- /// <summary>Gets a value that indicates whether at least one step succeeded.</summary>
- /// <value><see langword="true"/> if any recorded step completed successfully; otherwise, <see langword="false"/>.</value>
- public bool HasSuccessfulSteps => _executedSteps.Any(s => s.Success);
-
- private bool LoggingOnly { get; init; }
-
- /// <summary>
- /// Releases the execution scope, logs execution statistics, and persists revert data
- /// if the scope is associated with an optimization that has successful steps.
- /// </summary>
- public void Dispose()
- {
- if (_disposed)
- return;
- _disposed = true;
-
- _stopwatch.Stop();
-
- if (_stats.IsEmpty)
- {
- Logger.LogDebug(
- "Completed in {Time} (no operations tracked)",
- _stopwatch.Elapsed.ToString(@"mm\:ss\.fff")
- );
- }
- else
- {
- var summary = string.Join(
- ", ",
- _stats.Select(kv => $"{kv.Key}: +({kv.Value.Success}) -({kv.Value.Fail})")
- );
-
- Logger.LogDebug(
- "Completed in {Time} | {Summary}",
- _stopwatch.Elapsed.ToString(@"mm\:ss\.fff"),
- summary
- );
- }
-
- if (!LoggingOnly)
- Logger.LogDebug(
- "Steps: {Total} ({Success} success, {Failed} failed)",
- _executedSteps.Count,
- _executedSteps.Count(s => s.Success),
- _executedSteps.Count(s => !s.Success)
- );
-
- _current.Value = null;
- }
-
- /// <summary>Creates a new execution scope for an optimization and sets it as the ambient scope.</summary>
- /// <param name="optimization">The optimization to execute.</param>
- /// <param name="logger">The logger instance for the scope.</param>
- /// <returns>A new <see cref="ExecutionScope"/> instance.</returns>
- /// <exception cref="InvalidOperationException">An execution scope is already active in the current async context.</exception>
- public static ExecutionScope Begin(IOptimization optimization, ILogger logger)
- {
- if (_current.Value != null)
- throw new InvalidOperationException(
- "An execution scope is already active in the current context."
- );
-
- var scope = new ExecutionScope
- {
- OptimizationId = optimization.Id,
- OptimizationKey = optimization.OptimizationKey,
- OptimizationName = optimization.Name,
- Logger = logger,
- };
- _current.Value = scope;
- logger.LogDebug(
- "Execution scope started for {Key} (ID: {Id})",
- optimization.OptimizationKey,
- optimization.Id
- );
- return scope;
- }
-
- /// <summary>Creates a logging-only scope that records steps but does not persist revert data.</summary>
- /// <param name="logger">The logger instance for the scope.</param>
- /// <returns>A new <see cref="ExecutionScope"/> instance with <see cref="LoggingOnly"/> set to <see langword="true"/>.</returns>
- /// <exception cref="InvalidOperationException">An execution scope is already active in the current async context.</exception>
- public static ExecutionScope BeginForLogging(ILogger logger)
- {
- if (_current.Value != null)
- throw new InvalidOperationException(
- "An execution scope is already active in the current context."
- );
-
- var scope = new ExecutionScope
- {
- OptimizationId = Guid.Empty,
- OptimizationKey = string.Empty,
- OptimizationName = string.Empty,
- Logger = logger,
- LoggingOnly = true,
- };
- _current.Value = scope;
- logger.LogDebug("Execution scope started (logging only)");
- return scope;
- }
-
- /// <summary>Creates a logging-only scope scoped to a specific optimization for diagnostic purposes.</summary>
- /// <param name="optimizationId">The identifier of the optimization.</param>
- /// <param name="optimizationKey">The unique key of the optimization.</param>
- /// <param name="logger">The logger instance for the scope.</param>
- /// <returns>A new <see cref="ExecutionScope"/> instance with <see cref="LoggingOnly"/> set to <see langword="true"/>.</returns>
- /// <exception cref="InvalidOperationException">An execution scope is already active in the current async context.</exception>
- public static ExecutionScope BeginForLogging(
- Guid optimizationId,
- string optimizationKey,
- ILogger logger
- )
- {
- if (_current.Value != null)
- throw new InvalidOperationException(
- "An execution scope is already active in the current context."
- );
-
- var scope = new ExecutionScope
- {
- OptimizationId = optimizationId,
- OptimizationKey = optimizationKey,
- OptimizationName = string.Empty,
- Logger = logger,
- LoggingOnly = true,
- };
- _current.Value = scope;
- logger.LogDebug("Execution scope started for {Key} (logging only)", optimizationKey);
- return scope;
- }
-
- /// <summary>Creates a temporary scope used to re-capture revert steps during retry execution.</summary>
- /// <remarks>
- /// During retry, the original optimization context is not available, so
- /// <see cref="OptimizationId"/> is set to <see cref="Guid.Empty"/>. Captured steps are later
- /// re-assigned to the real scope via <see cref="RecordStepAtIndex"/>.
- /// </remarks>
- /// <param name="logger">The logger instance for the scope.</param>
- /// <returns>A new <see cref="ExecutionScope"/> instance with an empty optimization context.</returns>
- /// <exception cref="InvalidOperationException">An execution scope is already active in the current async context.</exception>
- public static ExecutionScope BeginForCapture(ILogger logger)
- {
- if (_current.Value != null)
- throw new InvalidOperationException(
- "An execution scope is already active in the current context."
- );
-
- var scope = new ExecutionScope
- {
- OptimizationId = Guid.Empty,
- OptimizationKey = string.Empty,
- OptimizationName = string.Empty,
- Logger = logger,
- };
- _current.Value = scope;
- logger.LogDebug("Execution scope started for retry capture");
- return scope;
- }
-
- /// <summary>Records an execution step onto the ambient scope with auto-incremented index.</summary>
- /// <param name="name">The category name of the step (for example, "Registry", "Shell").</param>
- /// <param name="description">A human-readable description of what the step does.</param>
- /// <param name="success"><see langword="true"/> if the step completed successfully; otherwise, <see langword="false"/>.</param>
- /// <param name="revertStep">An optional <see cref="IRevertStep"/> that can undo this operation.</param>
- /// <param name="error">An optional error message that describes the failure.</param>
- /// <param name="retryAction">An optional asynchronous action that retries the failed step.</param>
- /// <param name="errorDetail">An optional detailed error string (for example, exception details).</param>
- /// <returns>The recorded <see cref="ExecutedStep"/>, or <see langword="null"/> if no ambient scope exists or the scope is logging-only.</returns>
- public static ExecutedStep? RecordStep(
- string name,
- string description,
- bool success,
- IRevertStep? revertStep = null,
- string? error = null,
- Func<Task<bool>>? retryAction = null,
- string? errorDetail = null
- )
- {
- var scope = Current;
-
- return scope?.RecordStepInternal(
- name,
- description,
- success,
- revertStep,
- error,
- retryAction,
- errorDetail
- );
- }
-
- /// <summary>Records an execution step at a specific index, used during retry to preserve the original index layout.</summary>
- /// <param name="index">The explicit 1-based index for the step.</param>
- /// <param name="name">The category name of the step (for example, "Registry", "Shell").</param>
- /// <param name="description">A human-readable description of what the step does.</param>
- /// <param name="success"><see langword="true"/> if the step completed successfully; otherwise, <see langword="false"/>.</param>
- /// <param name="revertStep">An optional <see cref="IRevertStep"/> that can undo this operation.</param>
- /// <param name="error">An optional error message that describes the failure.</param>
- /// <param name="retryAction">An optional asynchronous action that retries the failed step.</param>
- /// <param name="errorDetail">An optional detailed error string (for example, exception details).</param>
- /// <returns>The recorded <see cref="ExecutedStep"/>, or <see langword="null"/> if no ambient scope exists or the scope is logging-only.</returns>
- public static ExecutedStep? RecordStepAtIndex(
- int index,
- string name,
- string description,
- bool success,
- IRevertStep? revertStep = null,
- string? error = null,
- Func<Task<bool>>? retryAction = null,
- string? errorDetail = null
- )
- {
- var scope = Current;
-
- return scope?.RecordStepInternal(
- name,
- description,
- success,
- revertStep,
- error,
- retryAction,
- errorDetail,
- explicitIndex: index
- );
- }
-
- /// <summary>Records a service invocation in the execution statistics.</summary>
- /// <param name="serviceName">The name of the service that was invoked.</param>
- /// <param name="success"><see langword="true"/> if the service call succeeded; otherwise, <see langword="false"/>.</param>
- public static void Track(string serviceName, bool success)
- {
- var scope = Current;
-
- scope?._stats.AddOrUpdate(
- serviceName,
- _ => success ? new Stats { Success = 1 } : new Stats { Fail = 1 },
- (_, stats) =>
- {
- if (success)
- stats.Success++;
- else
- stats.Fail++;
- return stats;
- }
- );
- }
-
- /// <summary>Returns the list of step results for display in the UI.</summary>
- /// <returns>A <see cref="List{T}"/> of <see cref="OperationStepResult"/> instances.</returns>
- public List<OperationStepResult> GetStepResults()
- {
- return _executedSteps.Select(ToOperationStepResult).ToList();
- }
-
- /// <summary>Maps the execution scope to an <see cref="ApplyResult"/> from the recorded steps.</summary>
- /// <returns><see cref="ApplyResult.True"/> if every step succeeded or some succeeded (partial success); <see cref="ApplyResult.False"/> with a message if all steps failed.</returns>
- public ApplyResult ToApplyResult()
- {
- var result = ToResult();
- return
- result.Status
- is OptimizationSuccessResult.Success
- or OptimizationSuccessResult.PartialSuccess
- ? ApplyResult.True()
- : ApplyResult.False(result.Message);
- }
-
- /// <summary>Builds an <see cref="OptimizationResult"/> from the recorded steps.</summary>
- /// <returns>
- /// An <see cref="OptimizationResult"/> whose <see cref="OptimizationResult.Status"/> reflects whether
- /// all steps succeeded, some failed (partial), or all failed.
- /// </returns>
- public OptimizationResult ToResult()
- {
- var status = ResolveStatus();
- var failedSteps = FailedSteps.Select(ToOperationStepResult).ToList();
-
- var allFailed = failedSteps.Count == ExecutedSteps.Count;
-
- return new OptimizationResult
- {
- Status = status,
- Message = status switch
- {
- OptimizationSuccessResult.Success => Loc.Instance[
- "Optimization.Apply.Success",
- OptimizationName
- ],
- OptimizationSuccessResult.Failed when allFailed => Loc.Instance[
- "Optimization.Apply.Error.Failed",
- OptimizationName
- ],
- OptimizationSuccessResult.PartialSuccess or OptimizationSuccessResult.Failed =>
- Loc.Instance[
- "Optimization.Apply.Error.FailedWithSteps",
- OptimizationName,
- failedSteps.Count
- ],
- _ => Loc.Instance["Optimization.Apply.Error.Unknown", OptimizationName],
- },
- FailedSteps = failedSteps,
- };
- }
-
- private ExecutedStep? RecordStepInternal(
- string name,
- string description,
- bool success,
- IRevertStep? revertStep,
- string? error,
- Func<Task<bool>>? retryAction = null,
- string? errorDetail = null,
- int? explicitIndex = null
- )
- {
- if (LoggingOnly)
- return null;
-
- // explicitIndex is used during retry to re-record a step at its original position
- // so the gap-and-index layout in the revert file stays consistent
- var stepIndex = explicitIndex ?? ++_stepIndex;
-
- var step = new ExecutedStep(
- stepIndex,
- name,
- description,
- success,
- revertStep,
- error,
- retryAction,
- errorDetail
- );
-
- _executedSteps.Add(step);
-
- return step;
- }
-
- private OptimizationSuccessResult ResolveStatus()
- {
- if (_executedSteps.Count == 0)
- return OptimizationSuccessResult.Failed;
-
- var failed = _executedSteps.Count(s => !s.Success);
- var total = ExecutedSteps.Count;
-
- return failed == 0 ? OptimizationSuccessResult.Success
- : failed < total ? OptimizationSuccessResult.PartialSuccess
- : OptimizationSuccessResult.Failed;
- }
-
- private static OperationStepResult ToOperationStepResult(ExecutedStep step)
- {
- return new OperationStepResult
- {
- Index = step.Index,
- Name = step.Name,
- Description = step.Description,
- Success = step.Success,
- Error = step.Error,
- ErrorDetail = step.ErrorDetail,
- RetryAction = step.RetryAction,
- RevertStep = step.RevertStep,
- };
- }
-
- private class Stats
- {
- public int Fail;
- public int Success;
- }
-
- #region Logging
-
- /// <summary>Logs a message at the specified level through the ambient scope's logger.</summary>
- /// <param name="level">The log level.</param>
- /// <param name="message">The message template.</param>
- /// <param name="args">Optional format arguments.</param>
- public static void Log(LogLevel level, string message, params object[] args)
- {
- Current?.Logger.Log(level, message, args);
- }
-
- /// <summary>Logs a debug-level message.</summary>
- /// <param name="message">The message template.</param>
- /// <param name="args">Optional format arguments.</param>
- public static void LogDebug(string message, params object[] args)
- {
- Log(LogLevel.Debug, message, args);
- }
-
- /// <summary>Logs a trace-level message.</summary>
- /// <param name="message">The message template.</param>
- /// <param name="args">Optional format arguments.</param>
- public static void LogTrace(string message, params object[] args)
- {
- Log(LogLevel.Trace, message, args);
- }
-
- /// <summary>Logs an informational message.</summary>
- /// <param name="message">The message template.</param>
- /// <param name="args">Optional format arguments.</param>
- public static void LogInfo(string message, params object[] args)
- {
- Log(LogLevel.Information, message, args);
- }
-
- /// <summary>Logs a warning message.</summary>
- /// <param name="message">The message template.</param>
- /// <param name="args">Optional format arguments.</param>
- public static void LogWarning(string message, params object[] args)
- {
- Log(LogLevel.Warning, message, args);
- }
-
- /// <summary>Logs an error message with an optional exception.</summary>
- /// <param name="ex">An optional exception that caused the error.</param>
- /// <param name="message">The message template.</param>
- /// <param name="args">Optional format arguments.</param>
- public static void LogError(Exception? ex, string message, params object[] args)
- {
- Current?.Logger.LogError(ex, message, args);
- }
-
- #endregion Logging
-}
-
-/// <summary>Represents a single step recorded during optimization execution.</summary>
-public sealed record ExecutedStep
-{
- /// <summary>Initializes a new instance of the <see cref="ExecutedStep"/> class.</summary>
- /// <param name="index">The 1-based index of the step in the execution sequence.</param>
- /// <param name="name">The category name of the step (for example, "Registry", "Shell").</param>
- /// <param name="description">A human-readable description of what the step did.</param>
- /// <param name="success"><see langword="true"/> if the step completed successfully; otherwise, <see langword="false"/>.</param>
- /// <param name="revertStep">An <see cref="IRevertStep"/> that can undo this operation, if applicable.</param>
- /// <param name="error">An error message if the step failed, or <see langword="null"/>.</param>
- /// <param name="retryAction">An optional asynchronous action to retry the step on failure.</param>
- /// <param name="errorDetail">An optional detailed error string (for example, exception details).</param>
- public ExecutedStep(
- int index,
- string name,
- string description,
- bool success,
- IRevertStep? revertStep,
- string? error,
- Func<Task<bool>>? retryAction = null,
- string? errorDetail = null
- )
- {
- Index = index;
- Name = name;
- Description = description;
- Success = success;
- RevertStep = revertStep;
- Error = error;
- RetryAction = retryAction;
- ErrorDetail = errorDetail;
- }
-
- /// <summary>
- /// The index of the step in the execution sequence.
- /// </summary>
- public int Index { get; init; }
-
- /// <summary>
- /// The category/name of the step (e.g., "Registry", "Shell").
- /// </summary>
- public string Name { get; init; }
-
- /// <summary>
- /// A description of what the step did.
- /// </summary>
- public string Description { get; init; }
-
- /// <summary>
- /// Whether the step succeeded.
- /// </summary>
- public bool Success { get; init; }
-
- /// <summary>
- /// The revert step that can undo this operation, if applicable.
- /// </summary>
- public IRevertStep? RevertStep { get; init; }
-
- /// <summary>
- /// The error message if the step failed, or null if it succeeded.
- /// </summary>
- public string? Error { get; init; }
-
- /// <summary>
- /// Detailed error information (exception details) for the step failure.
- /// </summary>
- public string? ErrorDetail { get; init; }
-
- /// <summary>
- /// An optional action to retry this step if it failed.
- /// </summary>
- public Func<Task<bool>>? RetryAction { get; init; }
-}
diff --git a/optimizerDuck/Domain/Execution/OpCall.cs b/optimizerDuck/Domain/Execution/OpCall.cs
new file mode 100644
index 0000000..42674e3
--- /dev/null
+++ b/optimizerDuck/Domain/Execution/OpCall.cs
@@ -0,0 +1,16 @@
+using Microsoft.Extensions.Logging;
+
+namespace optimizerDuck.Domain.Execution;
+
+/// <summary>
+/// Explicit per-operation call context: every dependency a provider needs
+/// (change collector, logger, cancellation) travels as a parameter.
+/// </summary>
+public class OpCall
+{
+ public ChangeSet Changes { get; init; } = new();
+
+ public required ILogger Logger { get; init; }
+
+ public CancellationToken CancellationToken { get; init; }
+}
diff --git a/optimizerDuck/Domain/Execution/OpResult.cs b/optimizerDuck/Domain/Execution/OpResult.cs
new file mode 100644
index 0000000..e2267d4
--- /dev/null
+++ b/optimizerDuck/Domain/Execution/OpResult.cs
@@ -0,0 +1,39 @@
+using optimizerDuck.Domain.Abstractions;
+
+namespace optimizerDuck.Domain.Execution;
+
+/// <summary>
+/// The result of a single provider operation. Errors flow here
+/// instead of ambient error state.
+/// </summary>
+public sealed record OpResult(
+ bool Ok,
+ IRevertStep? Revert = null,
+ string? Error = null,
+ string? ErrorDetail = null
+)
+{
+ public static OpResult Success(IRevertStep? revert = null)
+ {
+ return new OpResult(true, revert);
+ }
+
+ public static OpResult Fail(string error, string? errorDetail = null)
+ {
+ return new OpResult(false, null, error, errorDetail);
+ }
+
+ /// <summary>
+ /// Aggregates a batch of results: the first failure wins, otherwise success.
+ /// Callers must materialise <paramref name="results"/> first — a lazy sequence
+ /// would stop at the first failure and skip the remaining operations.
+ /// </summary>
+ public static OpResult FirstFailure(IEnumerable<OpResult> results)
+ {
+ foreach (var result in results)
+ if (!result.Ok)
+ return result;
+
+ return Success();
+ }
+}
diff --git a/optimizerDuck/Domain/Optimizations/Categories/AI.cs b/optimizerDuck/Domain/Optimizations/Categories/AI.cs
index a00f5c0..bb4192b 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/AI.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/AI.cs
@@ -4,6 +4,7 @@ using optimizerDuck.Common.Extensions;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
using optimizerDuck.Domain.Conditions;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.UI;
@@ -38,6 +39,7 @@ public class AI : LocalizedObject, IOptimizationCategory
// policy for broad build coverage; AllowRecallEnablement is device-scope only
// and removes the Recall bits on Windows 11 24H2+ (Build 26100.3915+).
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsAI",
"DisableAIDataAnalysis",
@@ -65,7 +67,7 @@ public class AI : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled Windows Recall AI snapshots");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
@@ -83,6 +85,7 @@ public class AI : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsAI",
"DisableClickToDo",
@@ -95,7 +98,7 @@ public class AI : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled Click To Do AI overlay");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
}
diff --git a/optimizerDuck/Domain/Optimizations/Categories/BloatwareAndServices.cs b/optimizerDuck/Domain/Optimizations/Categories/BloatwareAndServices.cs
index 5cb0e5c..5c613b4 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/BloatwareAndServices.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/BloatwareAndServices.cs
@@ -3,6 +3,7 @@ using Microsoft.Extensions.Logging;
using optimizerDuck.Common.Extensions;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.UI;
@@ -33,6 +34,7 @@ public class BloatwareAndServices : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager",
"PreInstalledAppsEnabled",
@@ -55,7 +57,7 @@ public class BloatwareAndServices : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Blocked preinstalled apps");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -314,7 +316,6 @@ public class BloatwareAndServices : LocalizedObject, IOptimizationCategory
new("wuauserv", ServiceStartupType.Manual),
};
- var tally = new Dictionary<ServiceChangeResult, int>();
for (var i = 0; i < servicesToChange.Count; i++)
{
var service = servicesToChange[i];
@@ -330,20 +331,14 @@ public class BloatwareAndServices : LocalizedObject, IOptimizationCategory
Total = servicesToChange.Count,
}
);
- var result = await ServiceProcessService.ChangeServiceStartupTypeAsync(service);
- tally[result] = tally.GetValueOrDefault(result) + 1;
+ await ServiceProcessService.ChangeServiceStartupTypeAsync(context, service);
}
context.Logger.LogInformation(
- "Service startup configuration: {Total} services, {Changed} changed, {AlreadyConfigured} already configured, {NotFound} not found, {AccessDenied} access denied, {Failed} failed",
- servicesToChange.Count,
- tally.GetValueOrDefault(ServiceChangeResult.Success),
- tally.GetValueOrDefault(ServiceChangeResult.AlreadyConfigured),
- tally.GetValueOrDefault(ServiceChangeResult.NotFound),
- tally.GetValueOrDefault(ServiceChangeResult.AccessDenied),
- tally.GetValueOrDefault(ServiceChangeResult.Failed)
+ "Service startup configuration: {Total} services applied",
+ servicesToChange.Count
);
- return CompleteFromScope();
+ return context.Changes.ToApplyResult();
}
}
}
diff --git a/optimizerDuck/Domain/Optimizations/Categories/Gpu.cs b/optimizerDuck/Domain/Optimizations/Categories/Gpu.cs
index f975c1b..b3cf029 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/Gpu.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/Gpu.cs
@@ -4,6 +4,7 @@ using optimizerDuck.Common.Extensions;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
using optimizerDuck.Domain.Conditions;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.UI;
@@ -44,7 +45,7 @@ public abstract class GpuRegistryOptimization : BaseOptimization
var path =
$@"HKLM\SYSTEM\CurrentControlSet\Control\Class\{{4d36e968-e325-11ce-bfc1-08002be10318}}\{index:D4}";
- RegistryService.Write(CreateItems(path).ToArray());
+ RegistryService.Write(context, CreateItems(path).ToArray());
context.Logger.LogInformation(
"Applied {Optimization} for GPU {DeviceId}",
GetType().Name,
@@ -52,7 +53,7 @@ public abstract class GpuRegistryOptimization : BaseOptimization
);
}
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
diff --git a/optimizerDuck/Domain/Optimizations/Categories/Performance.cs b/optimizerDuck/Domain/Optimizations/Categories/Performance.cs
index 288d10d..ca0a756 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/Performance.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/Performance.cs
@@ -4,6 +4,7 @@ using Microsoft.Win32;
using optimizerDuck.Common.Extensions;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.UI;
@@ -33,6 +34,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKCU\Software\Microsoft\Windows\CurrentVersion\BackgroundAccessApplications",
"GlobalUserDisabled",
@@ -45,7 +47,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled background apps");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
@@ -75,6 +77,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
}
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SYSTEM\CurrentControlSet\Control",
"SvcHostSplitThresholdInKB",
@@ -86,7 +89,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
"Consolidated service hosts with threshold: {ThresholdKB} KB",
context.Snapshot.Ram.TotalKB
);
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
@@ -124,6 +127,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
const int win32Priority = 38; // Short, Variable, High foreground boost
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SYSTEM\CurrentControlSet\Control\PriorityControl",
"Win32PrioritySeparation",
@@ -134,7 +138,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
"Enabled foreground boost with priority: {Priority}",
win32Priority
);
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
@@ -159,6 +163,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
// Parent SystemProfile settings (NoLazyMode, AlwaysOn, NetworkThrottlingIndex, SystemResponsiveness)
RegistryService.Write(
+ context,
new RegistryItem(systemProfileKey, "NoLazyMode", 1),
new RegistryItem(systemProfileKey, "AlwaysOn", 1),
new RegistryItem(
@@ -177,6 +182,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
// Games task scheduling (Priority, Scheduling Category, SFIO Priority, GPU Priority)
RegistryService.Write(
+ context,
new RegistryItem($@"{systemProfileKey}\Tasks\Games", "Priority", 2),
new RegistryItem($@"{systemProfileKey}\Tasks\Games", "Scheduling Category", "High"),
new RegistryItem($@"{systemProfileKey}\Tasks\Games", "SFIO Priority", "High"),
@@ -186,7 +192,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
context.Logger.LogInformation(
"Optimized Multimedia Class Scheduler Service (MMCSS) for gaming and low latency"
);
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
@@ -203,12 +209,13 @@ public class Performance : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(@"HKEY_CURRENT_USER\Control Panel\Keyboard", "KeyboardDelay", "0"),
new RegistryItem(@"HKEY_CURRENT_USER\Control Panel\Keyboard", "KeyboardSpeed", "31")
);
context.Logger.LogInformation("Optimized keyboard repeat settings");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
@@ -225,6 +232,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKEY_CURRENT_USER\Control Panel\Accessibility\StickyKeys",
"Flags",
@@ -243,7 +251,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
);
context.Logger.LogInformation("Disabled accessibility keyboard hotkeys");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
@@ -260,6 +268,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SYSTEM\CurrentControlSet\Services\WebClient\Parameters",
"FileSizeLimitInBytes",
@@ -269,7 +278,7 @@ public class Performance : LocalizedObject, IOptimizationCategory
);
context.Logger.LogInformation("Lifted the WebDAV file size limit to 4 GB");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
}
diff --git a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
index c2fe388..e1ac539 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
@@ -8,7 +8,6 @@ using optimizerDuck.Common.Extensions;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
-using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.Revert.Steps;
@@ -48,13 +47,13 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
) != 0;
string revertCommand = wasEnabled ? "powercfg /h on" : "powercfg /h off";
- await ShellService.CMDAsync("powercfg /h off", revertCommand);
+ await context.Shell.CMDAsync("powercfg /h off", context, revertCommand);
context.Logger.LogInformation(
"Disabled hibernation and Fast Startup. Previous state: {State}",
wasEnabled ? "Enabled" : "Disabled"
);
- return CompleteFromScope();
+ return context.Changes.ToApplyResult();
}
}
@@ -65,62 +64,55 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
)]
public class DisableUSBPowerSaving : BaseOptimization
{
- public override Task<ApplyResult> ApplyAsync(
+ public override async Task<ApplyResult> ApplyAsync(
IProgress<ProcessingProgress> progress,
OptimizationContext context
)
{
- return Task.Run(async () =>
- {
- context.Logger.LogInformation("Saving current USB power state");
- var usbStates = await ShellService.PowerShellAsync(
- """
- $states = Get-CimInstance -Namespace root\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue |
- Where-Object { $_.InstanceName -match 'USB\\ROOT' } |
- Select-Object InstanceName, Enable
+ context.Logger.LogInformation("Saving current USB power state");
+ var usbStates = await context.Shell.QueryPowerShellAsync(
+ """
+ $states = Get-CimInstance -Namespace root\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue |
+ Where-Object { $_.InstanceName -match 'USB\\ROOT' } |
+ Select-Object InstanceName, Enable
- $states | ConvertTo-Json -Compress
- """
- );
+ $states | ConvertTo-Json -Compress
+ """,
+ context.Logger
+ );
- if (string.IsNullOrWhiteSpace(usbStates.Stdout))
- {
- context.Logger.LogInformation("No USB devices found, skipping");
- return CompleteFromScope();
- }
+ if (string.IsNullOrWhiteSpace(usbStates.Stdout))
+ {
+ context.Logger.LogInformation("No USB devices found, skipping");
+ return ApplyResult.True();
+ }
- var capturedStates = ParseUsbPowerStates(usbStates.Stdout);
- if (capturedStates.Count == 0)
- {
- context.Logger.LogInformation("No USB device states parsed, skipping");
- return CompleteFromScope();
- }
+ var capturedStates = ParseUsbPowerStates(usbStates.Stdout);
+ if (capturedStates.Count == 0)
+ {
+ context.Logger.LogInformation("No USB device states parsed, skipping");
+ return ApplyResult.True();
+ }
- context.Logger.LogInformation("Disabling USB power saving");
- var disableResult = await ShellService.PowerShellAsync(
- """
- $devices = Get-CimInstance -Namespace root\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue |
- Where-Object { $_.InstanceName -match 'USB\\ROOT' }
+ context.Logger.LogInformation("Disabling USB power saving");
+ var revertStep = new UsbPowerRevertStep { States = capturedStates };
+ var disableOp = await context.Shell.PowerShellAsync(
+ """
+ $devices = Get-CimInstance -Namespace root\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue |
+ Where-Object { $_.InstanceName -match 'USB\\ROOT' }
- foreach ($d in $devices) {
- if ($d.Enable -ne $false) {
- Set-CimInstance -CimInstance $d -Property @{ Enable = $false } | Out-Null
- }
+ foreach ($d in $devices) {
+ if ($d.Enable -ne $false) {
+ Set-CimInstance -CimInstance $d -Property @{ Enable = $false } | Out-Null
}
- """
- );
-
- var revertStep = new UsbPowerRevertStep { States = capturedStates };
- ExecutionScope.RecordStep(
- ServiceStrings.ShellName,
- Loc.Invariant[$"Optimizer.{nameof(PowerManagement)}"],
- disableResult.ExitCode == 0,
- disableResult.ExitCode == 0 ? revertStep : null,
- disableResult.ExitCode == 0 ? null : disableResult.Stderr
- );
+ }
+ """,
+ context,
+ revertStep
+ );
+ var ok = disableOp.Ok;
- return CompleteFromScope();
- });
+ return context.Changes.ToApplyResult();
}
private static List<UsbPowerRevertStep.DeviceState> ParseUsbPowerStates(string stdout)
@@ -159,7 +151,10 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
OptimizationContext context
)
{
- var activeQuery = await ShellService.CMDAsync("powercfg /getactivescheme");
+ var activeQuery = await context.Shell.QueryCMDAsync(
+ "powercfg /getactivescheme",
+ context.Logger
+ );
var match = _activePlanGuidRegex.Match(activeQuery.Stdout);
if (!match.Success)
@@ -200,34 +195,36 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
}
);
- var importResult = await ShellService.CMDAsync(
+ var importOp = await context.Shell.CMDAsync(
$"powercfg /import \"{powerPlanPath}\" {Shared.PowerPlanGUID}",
+ context,
$"powercfg /delete {Shared.PowerPlanGUID}"
);
- if (importResult.ExitCode != 0)
+ if (!importOp.Ok)
{
context.Logger.LogError(
"Failed to import optimizerDuck power plan: {Error}",
- importResult.Stderr
+ importOp.Error
);
return ApplyResult.False(Loc.Instance[$"{ErrorPrefix}.ImportFailed"]);
}
- var setActiveResult = await ShellService.CMDAsync(
+ var setActiveOp = await context.Shell.CMDAsync(
$"powercfg /setactive {Shared.PowerPlanGUID}",
+ context,
$"powercfg /setactive {previousPlanGuid}"
);
- if (setActiveResult.ExitCode != 0)
+ if (!setActiveOp.Ok)
{
context.Logger.LogError(
"Failed to activate optimizerDuck power plan: {Error}",
- setActiveResult.Stderr
+ setActiveOp.Error
);
return ApplyResult.False(Loc.Instance[$"{ErrorPrefix}.ActivateFailed"]);
}
context.Logger.LogInformation("Installed optimizerDuck power plan successfully!");
- return CompleteFromScope();
+ return context.Changes.ToApplyResult();
}
}
@@ -244,6 +241,7 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SYSTEM\CurrentControlSet\Control\USB\AutomaticSurpriseRemoval",
"AttemptRecoveryFromUsbPowerDrain",
@@ -257,7 +255,7 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
);
context.Logger.LogInformation("Disabled power saving features");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
}
diff --git a/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs b/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs
index 63bda3e..fca6944 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs
@@ -4,6 +4,7 @@ using optimizerDuck.Common.Extensions;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
using optimizerDuck.Domain.Conditions;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.UI;
@@ -44,6 +45,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
);
// @formatter:off
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection",
"AllowTelemetry",
@@ -111,9 +113,10 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
0
)
);
- RegistryService.DeleteValue([
- new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Siuf\Rules", "PeriodInNanoSeconds"),
- ]);
+ RegistryService.DeleteValue(
+ context,
+ [new RegistryItem(@"HKCU\SOFTWARE\Microsoft\Siuf\Rules", "PeriodInNanoSeconds")]
+ );
context.Logger.LogInformation("Reduced core telemetry and feedback");
progress?.Report(
new ProcessingProgress
@@ -125,13 +128,16 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
}
);
await ServiceProcessService.ChangeServiceStartupTypeAsync(
- new ServiceItem("DiagTrack", ServiceStartupType.Disabled),
- new ServiceItem("dmwappushservice", ServiceStartupType.Disabled),
- new ServiceItem("DcpSvc", ServiceStartupType.Disabled),
- new ServiceItem(
- "diagnosticshub.standardcollector.service",
- ServiceStartupType.Disabled
- )
+ context,
+ [
+ new ServiceItem("DiagTrack", ServiceStartupType.Disabled),
+ new ServiceItem("dmwappushservice", ServiceStartupType.Disabled),
+ new ServiceItem("DcpSvc", ServiceStartupType.Disabled),
+ new ServiceItem(
+ "diagnosticshub.standardcollector.service",
+ ServiceStartupType.Disabled
+ ),
+ ]
);
progress?.Report(
@@ -159,12 +165,12 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
foreach (var task in tasksToDelete)
{
- if (!ScheduledTaskService.IsTaskEnabled(task))
+ if (!ScheduledTaskService.IsTaskEnabled(task, context.Logger))
continue;
- ScheduledTaskService.DisableTask(task);
+ ScheduledTaskService.DisableTask(context, task);
}
- return CompleteFromScope();
+ return context.Changes.ToApplyResult();
}
}
@@ -181,6 +187,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SOFTWARE\Microsoft\Windows\Windows Error Reporting",
"Disabled",
@@ -194,8 +201,11 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
);
await ServiceProcessService.ChangeServiceStartupTypeAsync(
- new ServiceItem("WerSvc", ServiceStartupType.Disabled),
- new ServiceItem("PcaSvc", ServiceStartupType.Disabled)
+ context,
+ [
+ new ServiceItem("WerSvc", ServiceStartupType.Disabled),
+ new ServiceItem("PcaSvc", ServiceStartupType.Disabled),
+ ]
);
var tasksToDelete = new[]
@@ -208,15 +218,15 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
foreach (var task in tasksToDelete)
{
- if (!ScheduledTaskService.IsTaskEnabled(task))
+ if (!ScheduledTaskService.IsTaskEnabled(task, context.Logger))
continue;
- ScheduledTaskService.DisableTask(task);
+ ScheduledTaskService.DisableTask(context, task);
}
context.Logger.LogInformation(
"Disabled Windows Error Reporting and Compatibility Assistant"
);
- return CompleteFromScope();
+ return context.Changes.ToApplyResult();
}
}
@@ -234,6 +244,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
{
// @formatter:off
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo",
"Enabled",
@@ -300,7 +311,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
"Disabled advertising ID, consumer features and system suggestions"
);
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -317,6 +328,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SOFTWARE\Policies\Microsoft\Dsh",
"AllowNewsAndInterests",
@@ -330,7 +342,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
);
context.Logger.LogInformation("Disabled News and Interests feed");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -348,6 +360,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer",
"HideSCAMeetNow",
@@ -356,7 +369,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
);
context.Logger.LogInformation("Hidden Meet Now button from the taskbar");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -373,6 +386,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SOFTWARE\Policies\Microsoft\Windows\System",
"PublishUserActivities",
@@ -396,7 +410,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
);
context.Logger.LogInformation("Disabled activity history collection and syncing");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -413,6 +427,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SOFTWARE\Policies\Microsoft\Windows\LocationAndSensors",
"DisableLocation",
@@ -461,13 +476,21 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
);
- if (ScheduledTaskService.IsTaskEnabled(@"\Microsoft\Windows\Maps\MapsUpdateTask"))
- ScheduledTaskService.DisableTask(@"\Microsoft\Windows\Maps\MapsUpdateTask");
+ if (
+ ScheduledTaskService.IsTaskEnabled(
+ @"\Microsoft\Windows\Maps\MapsUpdateTask",
+ context.Logger
+ )
+ )
+ ScheduledTaskService.DisableTask(
+ context,
+ @"\Microsoft\Windows\Maps\MapsUpdateTask"
+ );
context.Logger.LogInformation(
"Disabled location tracking, sensors and offline maps updates"
);
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -484,6 +507,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\AppModel",
"Start",
@@ -536,7 +560,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled WMI AutoLogger sessions");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -554,6 +578,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SOFTWARE\Policies\Microsoft\Windows\Windows Search",
"AllowCortana",
@@ -591,7 +616,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled Cortana and web search");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -612,6 +637,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsCopilot",
"TurnOffWindowsCopilot",
@@ -635,7 +661,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
);
context.Logger.LogInformation("Disabled Windows Copilot");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -652,6 +678,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager",
"ContentDeliveryAllowed",
@@ -684,7 +711,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled content delivery manager");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -701,6 +728,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SOFTWARE\Policies\Microsoft\FindMyDevice",
"AllowFindMyDevice",
@@ -708,7 +736,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled Find My Device location tracking");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
@@ -725,6 +753,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SOFTWARE\Policies\Microsoft\Windows\DeliveryOptimization",
"DODownloadMode",
@@ -732,7 +761,7 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled peer-to-peer Delivery Optimization sharing");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(context.Changes.ToApplyResult());
}
}
}
diff --git a/optimizerDuck/Domain/Optimizations/Categories/UserExperience.cs b/optimizerDuck/Domain/Optimizations/Categories/UserExperience.cs
index 7f2d676..e94a3ba 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/UserExperience.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/UserExperience.cs
@@ -5,6 +5,7 @@ using optimizerDuck.Common.Extensions;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
using optimizerDuck.Domain.Conditions;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.UI;
@@ -35,6 +36,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Serialize",
"StartupDelayInMSec",
@@ -43,7 +45,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
new RegistryItem(@"HKCU\Control Panel\Desktop", "MenuShowDelay", "0")
);
context.Logger.LogInformation("Speeded up Explorer and menus");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
@@ -60,6 +62,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced",
"TaskbarAnimations",
@@ -78,7 +81,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
new RegistryItem(@"HKCU\Software\Microsoft\Windows\DWM", "EnableAeroPeek", 0)
);
context.Logger.LogInformation("Disabled visual effects for better performance");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
@@ -95,6 +98,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Explorer",
"DisableSearchBoxSuggestions",
@@ -102,7 +106,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled web search for Start Menu");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
@@ -120,6 +124,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKEY_CURRENT_USER\SOFTWARE\Policies\Microsoft\Windows\Explorer",
"HideRecommendedSection",
@@ -127,7 +132,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled Recommended section in Start Menu");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
@@ -144,6 +149,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
)
{
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SOFTWARE\Policies\Microsoft\Windows\CloudContent",
"DisableConsumerAccountStateContent",
@@ -151,7 +157,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
)
);
context.Logger.LogInformation("Disabled Microsoft 365 ads in Settings");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
@@ -169,6 +175,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
{
// DWORD maximum; only honored by Windows versions that still support this setting
RegistryService.Write(
+ context,
new RegistryItem(
@"HKLM\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings",
"FlightSettingsMaxPauseDays",
@@ -178,7 +185,7 @@ public class UserExperience : LocalizedObject, IOptimizationCategory
);
context.Logger.LogInformation("Maximized the Windows Update pause limit");
- return Task.FromResult(CompleteFromScope());
+ return Task.FromResult(CompleteFromScope(context));
}
}
}
diff --git a/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs b/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs
index 8114978..2b36780 100644
--- a/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs
+++ b/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs
@@ -9,6 +9,7 @@ using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.UI;
using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.Configuration;
+using optimizerDuck.Services.Optimization.Providers;
using Wpf.Ui.Controls;
using OptimizationState = optimizerDuck.Domain.UI.OptimizationState;
@@ -38,12 +39,11 @@ public abstract partial class BaseOptimization : LocalizedObject, IOptimization
);
/// <summary>
- /// Gets or sets the type of the category class that owns this optimization.
+ /// Gets the type of the category class that owns this optimization.
/// Assigned automatically during reflection-based discovery in <c>OptimizationRegistry</c>.
/// </summary>
- public Type? OwnerType { get; set; }
+ public Type? OwnerType { get; internal set; }
- /// <summary>Gets the name of the owner category class.</summary>
/// <exception cref="InvalidOperationException">Thrown when <see cref="OwnerType"/> has not been assigned.</exception>
public string OwnerKey =>
OwnerType?.Name
@@ -191,12 +191,9 @@ public abstract partial class BaseOptimization : LocalizedObject, IOptimization
OptimizationContext context
);
- /// <summary>
- /// Returns an <see cref="ApplyResult" /> derived from steps recorded in the active <see cref="ExecutionScope" />.
- /// </summary>
- protected static ApplyResult CompleteFromScope()
+ /// <summary>Returns result from changes recorded into <paramref name="call"/>.</summary>
+ protected static ApplyResult CompleteFromScope(OpCall call)
{
- return ExecutionScope.Current?.ToApplyResult()
- ?? ApplyResult.False(Loc.Instance["Revert.Error.NoSteps"]);
+ return call.Changes.ToApplyResult();
}
}
diff --git a/optimizerDuck/Domain/Optimizations/Models/OperationStepResult.cs b/optimizerDuck/Domain/Optimizations/Models/OperationStepResult.cs
deleted file mode 100644
index 75fe1f0..0000000
--- a/optimizerDuck/Domain/Optimizations/Models/OperationStepResult.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-using optimizerDuck.Domain.Abstractions;
-
-namespace optimizerDuck.Domain.Optimizations.Models;
-
-/// <summary>
-/// Represents the result of a single operation step within an optimization.
-/// </summary>
-public record OperationStepResult
-{
- /// <summary>
- /// Gets the one-based index of this step in the execution order.
- /// </summary>
- public int Index { get; init; }
-
- /// <summary>
- /// Gets the name of the step.
- /// </summary>
- public string Name { get; init; } = string.Empty;
-
- /// <summary>
- /// Gets a description of what this step does.
- /// </summary>
- public string Description { get; init; } = string.Empty;
-
- /// <summary>
- /// Gets a value that indicates whether the step completed successfully.
- /// </summary>
- public bool Success { get; init; }
-
- /// <summary>
- /// Gets the error message if the step failed, or <see langword="null"/> if it succeeded.
- /// </summary>
- public string? Error { get; init; }
-
- /// <summary>
- /// Gets detailed error information (exception details) for the step failure.
- /// </summary>
- public string? ErrorDetail { get; init; }
-
- /// <summary>
- /// Gets an optional action to retry this step.
- /// </summary>
- public Func<Task<bool>>? RetryAction { get; init; }
-
- /// <summary>
- /// Gets the revert data generated when applying this step, used to support retry synchronization.
- /// </summary>
- public IRevertStep? RevertStep { get; init; }
-}
diff --git a/optimizerDuck/Domain/Optimizations/Models/OptimizationContext.cs b/optimizerDuck/Domain/Optimizations/Models/OptimizationContext.cs
index bee6857..9d67c50 100644
--- a/optimizerDuck/Domain/Optimizations/Models/OptimizationContext.cs
+++ b/optimizerDuck/Domain/Optimizations/Models/OptimizationContext.cs
@@ -1,19 +1,18 @@
using Microsoft.Extensions.Logging;
+using optimizerDuck.Domain.Abstractions;
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Services.Optimization.Providers;
using optimizerDuck.Services.System;
namespace optimizerDuck.Domain.Optimizations.Models;
/// <summary>
-/// Provides context information for optimization execution, including
-/// logging, system state, and download capabilities.
+/// Per-apply call context: the explicit <see cref="OpCall"/> surface
+/// (change collector, logger, cancellation) plus optimization-specific
+/// dependencies (system snapshot, download service).
/// </summary>
-public record OptimizationContext
+public class OptimizationContext : OpCall
{
- /// <summary>
- /// Gets the logger instance used to record diagnostic messages during optimization.
- /// </summary>
- public required ILogger Logger { get; init; }
-
/// <summary>
/// Gets a snapshot of the current system hardware and software information.
/// </summary>
@@ -23,4 +22,9 @@ public record OptimizationContext
/// Gets the service used to download remote resources required by optimizations.
/// </summary>
public required StreamService StreamService { get; init; }
+
+ /// <summary>
+ /// Gets the shell service used to execute CMD/PowerShell commands.
+ /// </summary>
+ public required ShellService Shell { get; init; }
}
diff --git a/optimizerDuck/Domain/Optimizations/Models/OptimizationResult.cs b/optimizerDuck/Domain/Optimizations/Models/OptimizationResult.cs
index e6917b9..2114ac7 100644
--- a/optimizerDuck/Domain/Optimizations/Models/OptimizationResult.cs
+++ b/optimizerDuck/Domain/Optimizations/Models/OptimizationResult.cs
@@ -1,4 +1,5 @@
-using optimizerDuck.Domain.UI;
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.UI;
namespace optimizerDuck.Domain.Optimizations.Models;
@@ -27,5 +28,5 @@ public record OptimizationResult
/// <summary>
/// Gets the list of steps that failed during the operation.
/// </summary>
- public List<OperationStepResult> FailedSteps { get; init; } = [];
+ public List<Change> FailedSteps { get; init; } = [];
}
diff --git a/optimizerDuck/Domain/Optimizations/Models/Services/RegistryValues.cs b/optimizerDuck/Domain/Optimizations/Models/Services/RegistryValues.cs
new file mode 100644
index 0000000..cdff586
--- /dev/null
+++ b/optimizerDuck/Domain/Optimizations/Models/Services/RegistryValues.cs
@@ -0,0 +1,32 @@
+using Microsoft.Win32;
+
+namespace optimizerDuck.Domain.Optimizations.Models.Services;
+
+/// <summary>
+/// Shared registry value equality. Single source of truth replacing the
+/// three private <c>ValuesEqual</c> copies (legacy provider, revert step,
+/// Windows capability).
+/// </summary>
+public static class RegistryValues
+{
+ public static bool Equal(object? actual, object? expected, RegistryValueKind kind)
+ {
+ if (actual == null || expected == null)
+ return actual == null && expected == null;
+ return kind switch
+ {
+ RegistryValueKind.DWord => Convert.ToInt32(actual) == Convert.ToInt32(expected),
+ RegistryValueKind.QWord => Convert.ToInt64(actual) == Convert.ToInt64(expected),
+ RegistryValueKind.String or RegistryValueKind.ExpandString => string.Equals(
+ actual.ToString(),
+ expected.ToString(),
+ StringComparison.Ordinal
+ ),
+ RegistryValueKind.MultiString when actual is string[] a && expected is string[] e =>
+ a.SequenceEqual(e),
+ RegistryValueKind.Binary when actual is byte[] ab && expected is byte[] eb =>
+ ab.SequenceEqual(eb),
+ _ => Equals(actual, expected),
+ };
+ }
+}
diff --git a/optimizerDuck/Domain/Optimizations/Models/Services/ShellPolicy.cs b/optimizerDuck/Domain/Optimizations/Models/Services/ShellPolicy.cs
new file mode 100644
index 0000000..6665793
--- /dev/null
+++ b/optimizerDuck/Domain/Optimizations/Models/Services/ShellPolicy.cs
@@ -0,0 +1,56 @@
+using optimizerDuck.Domain.Optimizations.Models.Services;
+using optimizerDuck.Resources.Languages;
+using optimizerDuck.Services.Configuration;
+
+namespace optimizerDuck.Domain.Optimizations.Models.Services;
+
+/// <summary>Defines success criteria and error reporting for shell command execution.</summary>
+public sealed class ShellPolicy
+{
+ /// <summary>Default policy: exit code 0 means success; error text is taken from stderr or the exit code.</summary>
+ public static readonly ShellPolicy Default = new();
+
+ /// <summary>Gets or sets a function that determines whether a shell result indicates success.</summary>
+ public Func<ShellResult, bool> IsSuccess { get; init; } = r => r.ExitCode == 0;
+
+ /// <summary>Gets or sets a function that produces an error message from a failed shell result.</summary>
+ public Func<ShellResult, string?> ErrorFactory { get; init; } =
+ r =>
+ r.ExitCode == -1 // if timed out use Error.TimedOut
+ ? Loc.Instance["Service.Shell.Error.TimedOut"]
+ : string.IsNullOrWhiteSpace(r.Stderr) // else check stderr, if empty use exitcode, else use raw stderr
+ ? Loc.Instance["Service.Shell.Error.ExitCode", r.ExitCode]
+ : r.Stderr;
+
+ /// <summary>Creates a policy with a custom success function and optional error factory.</summary>
+ /// <param name="isSuccess">A function that determines whether a result is successful.</param>
+ /// <param name="errorFactory">An optional function that produces an error message from a failed result. Defaults to the default error factory.</param>
+ /// <returns>A new <see cref="ShellPolicy"/> instance.</returns>
+ public static ShellPolicy From(
+ Func<ShellResult, bool> isSuccess,
+ Func<ShellResult, string?>? errorFactory = null
+ )
+ {
+ return new ShellPolicy
+ {
+ IsSuccess = isSuccess,
+ ErrorFactory = errorFactory ?? Default.ErrorFactory,
+ };
+ }
+
+ /// <summary>Creates a policy that treats specific exit codes as success.</summary>
+ /// <param name="okExitCodes">The exit codes considered successful.</param>
+ /// <returns>A new <see cref="ShellPolicy"/> instance.</returns>
+ public static ShellPolicy SuccessExitCodes(params int[] okExitCodes)
+ {
+ return From(r => okExitCodes.Contains(r.ExitCode));
+ }
+
+ /// <summary>Creates a policy that treats exit codes from 0 to <paramref name="maxOk"/> as success.</summary>
+ /// <param name="maxOk">The maximum exit code considered successful (inclusive).</param>
+ /// <returns>A new <see cref="ShellPolicy"/> instance.</returns>
+ public static ShellPolicy SuccessExitCodeRange(int maxOk)
+ {
+ return From(r => r.ExitCode >= 0 && r.ExitCode <= maxOk);
+ }
+}
diff --git a/optimizerDuck/Domain/Revert/RevertResult.cs b/optimizerDuck/Domain/Revert/RevertResult.cs
index a7b7720..5eeb4e5 100644
--- a/optimizerDuck/Domain/Revert/RevertResult.cs
+++ b/optimizerDuck/Domain/Revert/RevertResult.cs
@@ -1,4 +1,4 @@
-using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.Execution;
namespace optimizerDuck.Domain.Revert;
@@ -18,15 +18,10 @@ public class RevertResult
/// </summary>
public string Message { get; set; } = string.Empty;
- /// <summary>
- /// Gets or sets the exception that occurred, if any, during the revert.
- /// </summary>
- public Exception? Exception { get; set; }
-
/// <summary>
/// Gets or sets the list of steps that failed during the revert operation.
/// </summary>
- public List<OperationStepResult> FailedSteps { get; set; } = [];
+ public List<Change> FailedSteps { get; set; } = [];
/// <summary>
/// Gets or sets a value that indicates whether the revert failed completely
diff --git a/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs
index aab86cb..d45fac6 100644
--- a/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs
+++ b/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs
@@ -1,7 +1,9 @@
+using Microsoft.Extensions.Logging;
using Microsoft.Win32;
using Newtonsoft.Json.Linq;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Exceptions;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.Configuration;
@@ -77,38 +79,46 @@ public class RegistryRevertStep : IRevertStep
};
/// <inheritdoc />
- public async Task<bool> ExecuteAsync()
+ public async Task<bool> ExecuteAsync(ShellService shell, ILogger logger)
{
- var result = Action switch
+ var opCall = new OpCall { Logger = logger };
+ OpResult result = Action switch
{
RevertAction.NoPreviousValue => RegistryService.DeleteValue(
+ opCall,
new RegistryItem(Path, Name!)
),
RevertAction.RestorePrevious => Value == null
- ? RegistryService.DeleteValue(new RegistryItem(Path, Name!))
- : RegistryService.Write(new RegistryItem(Path, Name!, Value, Kind)),
+ ? RegistryService.DeleteValue(opCall, new RegistryItem(Path, Name!))
+ : RegistryService.Write(opCall, new RegistryItem(Path, Name!, Value, Kind)),
- RevertAction.RestoreKey => RegistryService.CreateSubKey(new RegistryItem(Path)),
+ RevertAction.RestoreKey => RegistryService.CreateSubKey(opCall, new RegistryItem(Path)),
- RevertAction.DeleteKey => RegistryService.DeleteSubKeyTree(new RegistryItem(Path)),
+ RevertAction.DeleteKey => RegistryService.DeleteSubKeyTree(
+ opCall,
+ new RegistryItem(Path)
+ ),
- RevertAction.RestoreKeyTree => await ExecuteSubStepsAsync(),
+ RevertAction.RestoreKeyTree => await ExecuteSubStepsAsync(shell, logger)
+ .ConfigureAwait(false)
+ ? OpResult.Success()
+ : OpResult.Fail(Description),
- _ => false,
+ _ => OpResult.Fail(Description),
};
- if (!result)
- {
- var error = RegistryService.LastError ?? Description;
- throw new StepExecutionException(error, RegistryService.LastErrorDetail);
- }
+ if (!result.Ok)
+ throw new StepExecutionException(result.Error ?? Description, result.ErrorDetail);
+
+ // Read-back verify for the local value actions.
+ VerifyRestore(opCall);
// Cleanup empty subkeys if they were created during apply
- if (result && CreatedSubKeys?.Count > 0)
- RegistryService.CleanupEmptyKeys(CreatedSubKeys);
+ if (CreatedSubKeys?.Count > 0)
+ RegistryService.CleanupEmptyKeys(CreatedSubKeys, opCall.Logger);
- return result;
+ return true;
}
/// <inheritdoc />
@@ -238,13 +248,65 @@ public class RegistryRevertStep : IRevertStep
};
}
- private async Task<bool> ExecuteSubStepsAsync()
+ private void VerifyRestore(OpCall call)
+ {
+ switch (Action)
+ {
+ case RevertAction.RestorePrevious when Value != null:
+ {
+ var item = new RegistryItem(Path, Name!);
+ var actual = RegistryService.Read<object>(item, call.Logger);
+ if (!ValuesEqual(actual, Value, Kind))
+ throw new StepExecutionException(
+ $"Registry verify failed at {Path}:{Name}: expected '{Value}', actual '{actual}'",
+ null
+ );
+ break;
+ }
+ case RevertAction.NoPreviousValue:
+ case RevertAction.RestorePrevious:
+ {
+ // Value must be absent after delete.
+ var actual = RegistryService.Read<object>(
+ new RegistryItem(Path, Name!),
+ call.Logger
+ );
+ if (actual != null)
+ throw new StepExecutionException(
+ $"Registry verify failed at {Path}:{Name}: expected '<absent>', actual '{actual}'",
+ null
+ );
+ break;
+ }
+ case RevertAction.RestoreKey:
+ if (!RegistryService.KeyExists(new RegistryItem(Path), call.Logger))
+ throw new StepExecutionException(
+ $"Registry verify failed at {Path}: expected key to exist, but it was missing",
+ null
+ );
+ break;
+ case RevertAction.DeleteKey:
+ if (RegistryService.KeyExists(new RegistryItem(Path), call.Logger))
+ throw new StepExecutionException(
+ $"Registry verify failed at {Path}: expected key to be absent, but it still exists",
+ null
+ );
+ break;
+ default:
+ break;
+ }
+ }
+
+ private static bool ValuesEqual(object? actual, object? expected, RegistryValueKind kind) =>
+ RegistryValues.Equal(actual, expected, kind);
+
+ private async Task<bool> ExecuteSubStepsAsync(ShellService shell, ILogger logger)
{
if (SubSteps == null)
return true;
foreach (var step in SubSteps)
{
- if (!await step.ExecuteAsync())
+ if (!await step.ExecuteAsync(shell, logger))
return false;
}
return true;
diff --git a/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs
index 59d75a4..301c892 100644
--- a/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs
+++ b/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs
@@ -1,6 +1,8 @@
+using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Exceptions;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.Configuration;
using optimizerDuck.Services.Optimization.Providers;
@@ -32,17 +34,23 @@ public class ScheduledTaskRevertStep : IRevertStep
: Loc.Instance["Revert.ScheduledTask.Description.Disable", FullPath];
/// <inheritdoc />
- public Task<bool> ExecuteAsync()
+ public Task<bool> ExecuteAsync(ShellService _, ILogger logger)
{
- var success = OriginalEnabled
- ? ScheduledTaskService.EnableTask(FullPath)
- : ScheduledTaskService.DisableTask(FullPath);
+ var opCall = new OpCall { Logger = logger };
+ var result = OriginalEnabled
+ ? ScheduledTaskService.EnableTask(opCall, FullPath)
+ : ScheduledTaskService.DisableTask(opCall, FullPath);
- if (!success)
- {
- var error = ScheduledTaskService.LastError ?? Description;
- throw new StepExecutionException(error, ScheduledTaskService.LastErrorDetail);
- }
+ if (!result.Ok)
+ throw new StepExecutionException(result.Error ?? Description, result.ErrorDetail);
+
+ // Read-back verify: task must report the restored enabled state afterward.
+ var actualState = ScheduledTaskService.IsTaskEnabled(FullPath, opCall.Logger);
+ if (actualState != OriginalEnabled)
+ throw new StepExecutionException(
+ $"Scheduled task verify failed at {FullPath}: expected enabled={OriginalEnabled}, actual={actualState}",
+ null
+ );
return Task.FromResult(true);
}
@@ -64,10 +72,16 @@ public class ScheduledTaskRevertStep : IRevertStep
/// <returns>A new <see cref="ScheduledTaskRevertStep" /> instance.</returns>
public static ScheduledTaskRevertStep FromData(JObject data)
{
+ var enabledToken = data[nameof(OriginalEnabled)];
+ if (enabledToken == null || enabledToken.Type == JTokenType.Null)
+ throw new StepExecutionException(
+ $"Missing required '{nameof(OriginalEnabled)}' in scheduled-task revert data.",
+ data.ToString()
+ );
return new ScheduledTaskRevertStep
{
FullPath = data[nameof(FullPath)]?.ToString() ?? string.Empty,
- OriginalEnabled = data[nameof(OriginalEnabled)]?.Value<bool>() ?? true,
+ OriginalEnabled = enabledToken.Value<bool>(),
};
}
}
diff --git a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs
index 8ba3296..14dd550 100644
--- a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs
+++ b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs
@@ -1,6 +1,8 @@
+using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Exceptions;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.Configuration;
@@ -31,23 +33,39 @@ public class ServiceRevertStep : IRevertStep
Loc.Instance["Revert.Service.Description.Restore", ServiceName, OriginalStartupType];
/// <inheritdoc />
- public async Task<bool> ExecuteAsync()
+ public async Task<bool> ExecuteAsync(ShellService _, ILogger logger)
{
- var result = await ServiceProcessService.ChangeServiceStartupTypeAsync(
- new ServiceItem { Name = ServiceName, StartupType = OriginalStartupType }
- );
+ var opCall = new OpCall { Logger = logger };
+ var result = await ServiceProcessService
+ .ChangeServiceStartupTypeAsync(
+ opCall,
+ new ServiceItem { Name = ServiceName, StartupType = OriginalStartupType }
+ )
+ .ConfigureAwait(false);
- if (
- result
- is ServiceChangeResult.Success
- or ServiceChangeResult.NotFound
- or ServiceChangeResult.AlreadyConfigured
- or ServiceChangeResult.AccessDenied
- )
- return true;
+ if (!result.Ok)
+ {
+ // Fail closed: access-denied returns false so RevertManager records a failed
+ // step; every other failure throws with provider error detail.
+ var accessDenied = ServiceStrings.Format(
+ ServiceStrings.ServiceInfoSkippedAccessDenied,
+ ServiceName
+ );
+ if (string.Equals(result.Error, accessDenied, StringComparison.Ordinal))
+ return false;
+ throw new StepExecutionException(result.Error ?? Description, result.ErrorDetail);
+ }
- var error = ServiceProcessService.LastError ?? Description;
- throw new StepExecutionException(error, ServiceProcessService.LastErrorDetail);
+ // Read-back verify: service must report the restored startup type afterward.
+ var (actual, _) = await ServiceProcessService
+ .GetStartupTypeAsync(ServiceName, opCall.Logger)
+ .ConfigureAwait(false);
+ if (actual != null && actual.Value != OriginalStartupType)
+ throw new StepExecutionException(
+ $"Service verify failed for {ServiceName}: expected {OriginalStartupType}, actual={actual}",
+ null
+ );
+ return true;
}
/// <inheritdoc />
diff --git a/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs
index c53737c..d80f410 100644
--- a/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs
+++ b/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs
@@ -1,3 +1,4 @@
+using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Exceptions;
@@ -30,12 +31,14 @@ public class ShellRevertStep : IRevertStep
public string Description => Loc.Instance["Revert.Shell.Description.Run", ShellType, Command];
/// <inheritdoc />
- public async Task<bool> ExecuteAsync()
+ public async Task<bool> ExecuteAsync(ShellService shell, ILogger logger)
{
var result = ShellType switch
{
- ShellType.PowerShell => await ShellService.PowerShellAsync(Command),
- ShellType.CMD => await ShellService.CMDAsync(Command),
+ ShellType.PowerShell => await shell
+ .QueryPowerShellAsync(Command, logger)
+ .ConfigureAwait(false),
+ ShellType.CMD => await shell.QueryCMDAsync(Command, logger).ConfigureAwait(false),
_ => new ShellResult
{
Command = Command,
diff --git a/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs
index b00da7f..792f386 100644
--- a/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs
+++ b/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs
@@ -1,4 +1,5 @@
using System.Text;
+using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using optimizerDuck.Domain.Abstractions;
@@ -42,7 +43,7 @@ public class UsbPowerRevertStep : IRevertStep
public string Description => Loc.Instance["Revert.UsbPower.Description"];
/// <inheritdoc />
- public async Task<bool> ExecuteAsync()
+ public async Task<bool> ExecuteAsync(ShellService shell, ILogger logger)
{
if (States.Count == 0)
return true;
@@ -63,7 +64,7 @@ public class UsbPowerRevertStep : IRevertStep
+ "Set-CimInstance -CimInstance $obj -Property @{ Enable = [bool]$s.Enable } | Out-Null "
+ "}}";
- var result = await ShellService.PowerShellAsync(script);
+ var result = await shell.QueryPowerShellAsync(script, logger).ConfigureAwait(false);
if (result.ExitCode != 0)
{
diff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resx
index 13b2ea8..9500ae1 100644
--- a/optimizerDuck/Resources/Languages/Translations.resx
+++ b/optimizerDuck/Resources/Languages/Translations.resx
@@ -449,6 +449,12 @@
<data name="Common.AppliedJustNow" xml:space="preserve">
<value>Just applied</value>
</data>
+ <data name="Common.OperationCancelled" xml:space="preserve">
+ <value>Operation canceled.</value>
+ </data>
+ <data name="Optimization.Apply.Error.AllStepsFailed" xml:space="preserve">
+ <value>All steps failed.</value>
+ </data>
<data name="Optimization.Apply.Snackbar.Error.Title" xml:space="preserve">
<value>Couldn't fully apply optimization</value>
</data>
diff --git a/optimizerDuck/Services/Configuration/LanguageManager.cs b/optimizerDuck/Services/Configuration/LanguageManager.cs
index f9b0bb3..40e4d99 100644
--- a/optimizerDuck/Services/Configuration/LanguageManager.cs
+++ b/optimizerDuck/Services/Configuration/LanguageManager.cs
@@ -68,6 +68,11 @@ public class Loc : INotifyPropertyChanged
OnPropertyChanged(nameof(IsRtl));
OnPropertyChanged(nameof(Direction));
OnPropertyChanged("Item[]");
+ // WPF convention: an empty property name means "all properties changed". Pathless
+ // bindings to Loc.Instance (used by the multi-arg {ext:Loc Key, Binding} markup)
+ // only re-evaluate on this notification, so without it those texts stay in the old
+ // language until restart.
+ OnPropertyChanged(string.Empty);
LanguageChanged?.Invoke(this, new LanguageChangedEventArgs(culture));
}
diff --git a/optimizerDuck/Services/Customize/CustomizationExecutor.cs b/optimizerDuck/Services/Customize/CustomizationExecutor.cs
new file mode 100644
index 0000000..ad9ee15
--- /dev/null
+++ b/optimizerDuck/Services/Customize/CustomizationExecutor.cs
@@ -0,0 +1,113 @@
+using Microsoft.Extensions.Logging;
+
+namespace optimizerDuck.Services.Customize;
+
+/// <summary>
+/// Lightweight executor for customization actions.
+/// Provides debouncing and sequential serialization without leaking threading locks into ViewModels.
+/// </summary>
+public sealed class CustomizationExecutor(ILogger<CustomizationExecutor>? logger = null)
+ : IDisposable
+{
+ private readonly Lock _gate = new();
+ private object? _pendingValue;
+ private bool _hasPendingValue;
+ private bool _isApplying;
+ private CancellationTokenSource? _debounceCts;
+
+ /// <summary>
+ /// Gets whether a customization action is currently being applied.
+ /// </summary>
+ public bool IsApplying
+ {
+ get
+ {
+ lock (_gate)
+ return _isApplying;
+ }
+ }
+
+ /// <summary>
+ /// Applies the value after a debounce period, serializing calls sequentially.
+ /// </summary>
+ public async Task ApplyWithDebounceAsync(
+ object? value,
+ Func<object?, Task> applyAction,
+ int debounceMs = 400
+ )
+ {
+ CancellationToken token;
+ lock (_gate)
+ {
+ _debounceCts?.Cancel();
+ _debounceCts?.Dispose();
+ _debounceCts = new CancellationTokenSource();
+ token = _debounceCts.Token;
+ }
+
+ try
+ {
+ await Task.Delay(debounceMs, token);
+ if (token.IsCancellationRequested)
+ return;
+
+ QueueApply(value, applyAction);
+ }
+ catch (TaskCanceledException) { }
+ }
+
+ private void QueueApply(object? value, Func<object?, Task> applyAction)
+ {
+ lock (_gate)
+ {
+ _pendingValue = value;
+ _hasPendingValue = true;
+
+ if (_isApplying)
+ return;
+
+ _isApplying = true;
+ }
+
+ _ = ProcessQueueAsync(applyAction);
+ }
+
+ private async Task ProcessQueueAsync(Func<object?, Task> applyAction)
+ {
+ while (true)
+ {
+ object? valueToApply;
+ lock (_gate)
+ {
+ if (!_hasPendingValue)
+ {
+ _isApplying = false;
+ break;
+ }
+
+ valueToApply = _pendingValue;
+ _hasPendingValue = false;
+ }
+
+ try
+ {
+ await applyAction(valueToApply);
+ }
+ catch (Exception ex)
+ {
+ // Fire-and-forget, so log here instead of throwing.
+ logger?.LogError(ex, "Customization apply failed.");
+ }
+ }
+ }
+
+ public void Dispose()
+ {
+ lock (_gate)
+ {
+ _debounceCts?.Cancel();
+ _debounceCts?.Dispose();
+ _debounceCts = null;
+ }
+ }
+}
diff --git a/optimizerDuck/Services/Customize/CustomizeRegistry.cs b/optimizerDuck/Services/Customize/CustomizeRegistry.cs
index 622f1a6..dc6564c 100644
--- a/optimizerDuck/Services/Customize/CustomizeRegistry.cs
+++ b/optimizerDuck/Services/Customize/CustomizeRegistry.cs
@@ -44,48 +44,22 @@ public class CustomizeRegistry
{
_logger.LogInformation("Discovering customize setting categories...");
- var result = ReflectionHelper
- .FindImplementationsInLoadedAssemblies<ICustomizeCategory>()
- .Select(t =>
- {
- var featureTypes = t.GetNestedTypes(BindingFlags.Public)
- .Where(nt =>
- typeof(ICustomizeSetting).IsAssignableFrom(nt) && !nt.IsAbstract
- )
- .Select(nt =>
+ var result = CategoryDiscovery.Discover<ICustomizeCategory, ICustomizeSetting>(
+ nameof(ICustomizeCategory.Features),
+ t =>
+ CategoryDiscovery.NestedItems<ICustomizeSetting>(
+ t,
+ (opt, owner) =>
{
- var opt = (ICustomizeSetting)Activator.CreateInstance(nt)!;
-
if (opt is BaseCustomizeSetting bo)
{
- bo.OwnerType = t;
+ bo.OwnerType = owner;
ConditionValidation.Validate(bo.ConditionType, bo.FeatureKey);
}
-
- return opt;
- })
- .ToList();
-
- if (featureTypes.Count == 0)
- return null;
-
- var features = new ObservableCollection<ICustomizeSetting>(featureTypes);
-
- var instance = (ICustomizeCategory)Activator.CreateInstance(t)!;
-
- var featuresProp = t.GetProperty(
- nameof(ICustomizeCategory.Features),
- BindingFlags.Public | BindingFlags.Instance
- );
- if (featuresProp != null && featuresProp.CanWrite)
- featuresProp.SetValue(instance, features);
-
- return instance;
- })
- .Where(c => c != null)
- .Cast<ICustomizeCategory>()
- .OrderBy(c => c.Order)
- .ToArray();
+ }
+ ),
+ c => (int)c.Order
+ );
_logger.LogInformation(
"Registered {CategoryCount} customize categories with {SettingCount} total settings",
diff --git a/optimizerDuck/Services/Optimization/OptimizationRegistry.cs b/optimizerDuck/Services/Optimization/OptimizationRegistry.cs
index 399ea5b..838e5d3 100644
--- a/optimizerDuck/Services/Optimization/OptimizationRegistry.cs
+++ b/optimizerDuck/Services/Optimization/OptimizationRegistry.cs
@@ -32,51 +32,29 @@ public class OptimizationRegistry(ILoggerFactory loggerFactory)
/// <summary>Discovers all optimization categories and their optimizations via reflection, then loads the applied state from revert data on disk.</summary>
public async Task PreloadOptimizationsAsync()
{
+ var seenIds = new HashSet<Guid>();
// Run reflection work on background thread to avoid blocking startup
var optimizationCategories = await Task.Run(() =>
- ReflectionHelper
- .FindImplementationsInLoadedAssemblies<IOptimizationCategory>()
- .Select(t =>
- {
- var optimizations = new ObservableCollection<IOptimization>(
- t.GetNestedTypes(BindingFlags.Public)
- .Where(nt => typeof(IOptimization).IsAssignableFrom(nt))
- .Select(nt =>
+ CategoryDiscovery.Discover<IOptimizationCategory, IOptimization>(
+ nameof(IOptimizationCategory.Optimizations),
+ t =>
+ CategoryDiscovery.NestedItems<IOptimization>(
+ t,
+ (opt, owner) =>
+ {
+ if (opt is BaseOptimization bo)
{
- var opt = (IOptimization)Activator.CreateInstance(nt)!;
-
- if (opt is BaseOptimization bo)
- {
- bo.OwnerType = t;
- ConditionValidation.Validate(
- bo.ConditionType,
- bo.OptimizationKey
- );
- }
-
- return opt;
- })
- .ToList()
- );
-
- if (optimizations.Count == 0)
- return null;
-
- var instance = (IOptimizationCategory)Activator.CreateInstance(t)!;
-
- var optProp = t.GetProperty(
- nameof(IOptimizationCategory.Optimizations),
- BindingFlags.Public | BindingFlags.Instance
- );
- if (optProp != null && optProp.CanWrite)
- optProp.SetValue(instance, optimizations);
-
- return instance;
- })
- .Where(c => c != null) // skip nulls
- .Cast<IOptimizationCategory>()
- .OrderBy(c => c.Order)
- .ToArray()
+ bo.OwnerType = owner;
+ OptimizationValidation.Validate(bo, seenIds);
+ ConditionValidation.Validate(
+ bo.ConditionType,
+ bo.OptimizationKey
+ );
+ }
+ }
+ ),
+ c => (int)c.Order
+ )
)
.ConfigureAwait(false);
diff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.cs
index 6fa347d..97537c8 100644
--- a/optimizerDuck/Services/Optimization/OptimizationService.cs
+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs
@@ -26,10 +26,12 @@ public class OptimizationService(
SystemInfoService systemInfoService,
StreamService streamService,
IContentDialogService contentDialogService,
+ ShellService shellService,
ILogger<OptimizationService> logger
)
{
private readonly ILogger _logger = logger;
+ private readonly ShellService _shellService = shellService;
/// <summary>Gets or sets a value that indicates whether a system restore point was created before applying optimizations.</summary>
public bool WasRequestedRestorePoint { get; set; } = false;
@@ -62,12 +64,10 @@ public class OptimizationService(
IsIndeterminate = true,
}
);
-
- using var scope = ExecutionScope.BeginForLogging(_logger);
-
- var result = await ShellService
- .PowerShellAsync(
- $"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS"
+ var result = await _shellService
+ .QueryPowerShellAsync(
+ $"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS",
+ _logger
)
.ConfigureAwait(false);
@@ -98,10 +98,9 @@ public class OptimizationService(
}
);
- var enableResult = await ShellService
- .PowerShellAsync("Enable-ComputerRestore -Drive \"$env:SystemDrive\"")
+ var enableResult = await _shellService
+ .QueryPowerShellAsync("Enable-ComputerRestore -Drive \"$env:SystemDrive\"", _logger)
.ConfigureAwait(false);
-
if (enableResult.ExitCode != 0)
{
_logger.LogError(
@@ -119,9 +118,10 @@ public class OptimizationService(
}
);
- result = await ShellService
- .PowerShellAsync(
- $"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS"
+ result = await _shellService
+ .QueryPowerShellAsync(
+ $"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS",
+ _logger
)
.ConfigureAwait(false);
@@ -156,7 +156,7 @@ public class OptimizationService(
)
{
var optLogger = loggerFactory.CreateLogger(optimization.GetType());
- using var scope = ExecutionScope.Begin(optimization, optLogger);
+ var changes = new ChangeSet();
_logger.LogInformation(
"Starting apply of {Name} ({Key}) with ID {Id}",
@@ -173,6 +173,8 @@ public class OptimizationService(
}
);
+ string? providerError = null;
+ Exception? exception = null;
try
{
var applyResult = await optimization
@@ -180,28 +182,35 @@ public class OptimizationService(
progress,
new OptimizationContext
{
+ Changes = changes,
Logger = optLogger,
+ CancellationToken = cancellationToken,
Snapshot = systemInfoService.Snapshot,
StreamService = streamService,
+ Shell = _shellService,
}
)
.ConfigureAwait(false);
- if (!string.IsNullOrWhiteSpace(applyResult.ErrorMessage))
- {
- if (scope.HasSuccessfulSteps)
- await TrySaveRevertDataAsync(scope, optimization).ConfigureAwait(false);
-
- return new OptimizationResult
- {
- Status = scope.HasSuccessfulSteps
- ? OptimizationSuccessResult.PartialSuccess
- : OptimizationSuccessResult.Failed,
- Message = applyResult.ErrorMessage,
- FailedSteps = [.. scope.GetStepResults().Where(step => !step.Success)],
- };
- }
+ providerError = string.IsNullOrWhiteSpace(applyResult.ErrorMessage)
+ ? null
+ : applyResult.ErrorMessage;
+ }
+ catch (Exception ex)
+ {
+ exception = ex;
+ changes.Add(
+ optimization.OptimizationKey,
+ optimization.Name,
+ false,
+ null,
+ ex.Message,
+ ex.ToString()
+ );
+ }
+ if (exception == null && providerError == null)
+ {
progress.Report(
new ProcessingProgress
{
@@ -211,31 +220,80 @@ public class OptimizationService(
Total = 1,
}
);
+ }
- var result = scope.ToResult();
- await TrySaveRevertDataAsync(scope, optimization).ConfigureAwait(false);
+ // 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);
- return result;
- }
- catch (Exception ex)
- {
- var failedSteps = scope.GetStepResults().Where(step => !step.Success).ToList();
+ var failedSteps = changes.FailedSteps.OrderBy(s => s.Index).ToList();
- var status = scope.HasSuccessfulSteps
- ? OptimizationSuccessResult.PartialSuccess
- : OptimizationSuccessResult.Failed;
- var result = new OptimizationResult
+ if (exception != null)
+ {
+ return new OptimizationResult
{
- Status = status,
+ Status = changes.HasSuccessfulSteps
+ ? OptimizationSuccessResult.PartialSuccess
+ : OptimizationSuccessResult.Failed,
Message = Loc.Instance["Optimization.Apply.Error.Failed", optimization.Name],
- Exception = ex,
+ Exception = exception,
FailedSteps = failedSteps,
};
+ }
- await TrySaveRevertDataAsync(scope, optimization).ConfigureAwait(false);
+ if (providerError != null)
+ {
+ _logger.LogWarning(
+ "Provider error applying {OptimizationKey}: {ProviderError}",
+ optimization.OptimizationKey,
+ providerError
+ );
- return result;
+ return new OptimizationResult
+ {
+ Status = changes.HasSuccessfulSteps
+ ? 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,
+ };
}
+
+ if (!changes.HasSuccessfulSteps)
+ {
+ return new OptimizationResult
+ {
+ Status = OptimizationSuccessResult.Failed,
+ Message = Loc.Instance["Optimization.Apply.Error.Failed", 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,
+ };
}
/// <summary>Reverts the specified optimization using stored revert data from a previous apply operation.</summary>
@@ -263,7 +321,9 @@ public class OptimizationService(
IsIndeterminate = true,
}
);
- var result = await revertManager.RevertAsync(optimization, progress).ConfigureAwait(false);
+ var result = await revertManager
+ .RevertAsync(optimization, progress, cancellationToken)
+ .ConfigureAwait(false);
progress?.Report(
new ProcessingProgress
{
@@ -331,8 +391,8 @@ public class OptimizationService(
/// <param name="optimizationKey">The optimization key for revert step persistence.</param>
/// <param name="progress">An optional progress reporter.</param>
/// <returns>The list of steps that remain failed after retry.</returns>
- public static async Task<List<OperationStepResult>> RetryFailedStepsAsync(
- IReadOnlyList<OperationStepResult> failedSteps,
+ public static async Task<List<Change>> RetryFailedStepsAsync(
+ IReadOnlyList<Change> failedSteps,
bool reverseOrder,
ILogger logger,
RevertManager? revertManager = null,
@@ -365,7 +425,7 @@ public class OptimizationService(
/// <param name="progress">An optional progress reporter.</param>
/// <returns>A <see cref="RetryFailedStepsResult"/> containing both recovered and remaining failed steps.</returns>
public static async Task<RetryFailedStepsResult> RetryFailedStepsWithResultsAsync(
- IReadOnlyList<OperationStepResult> failedSteps,
+ IReadOnlyList<Change> failedSteps,
bool reverseOrder,
ILogger logger,
RevertManager? revertManager = null,
@@ -377,8 +437,8 @@ public class OptimizationService(
if (failedSteps.Count == 0)
return new RetryFailedStepsResult([], []);
- var remainingFailedSteps = new List<OperationStepResult>();
- var recoveredSteps = new List<OperationStepResult>();
+ var remainingFailedSteps = new List<Change>();
+ var recoveredSteps = new List<Change>();
var orderedSteps = reverseOrder
? failedSteps.OrderByDescending(s => s.Index)
: failedSteps.OrderBy(s => s.Index);
@@ -410,7 +470,7 @@ public class OptimizationService(
}
);
- if (step.RetryAction == null)
+ if (step.Retry == null)
{
remainingFailedSteps.Add(step);
continue;
@@ -420,32 +480,29 @@ public class OptimizationService(
Exception? error = null;
try
{
- using var retryScope = ExecutionScope.BeginForCapture(logger);
- success = await step.RetryAction().ConfigureAwait(false);
+ // Fresh call: retry is user-initiated, the original token may be dead.
+ // Captured changes merge back into the apply set (first backup wins).
+ var retryChanges = new ChangeSet();
+ var retryCall = new OpCall { Changes = retryChanges, Logger = logger };
+ var retryOutcome = await step.Retry(retryCall).ConfigureAwait(false);
+ success = retryOutcome.Ok;
if (success)
{
- var retriedStep = retryScope.SuccessfulSteps.LastOrDefault();
- var recoveredStep =
- retriedStep == null
- ? step with
- {
- Error = null,
- }
- : new OperationStepResult
- {
- Index = step.Index,
- Name = retriedStep.Name,
- Description = retriedStep.Description,
- Success = true,
- Error = null,
- RetryAction = null,
- RevertStep = retriedStep.RevertStep,
- };
+ var capturedStep = retryChanges.SuccessfulSteps.LastOrDefault();
+ var capturedRevert = capturedStep?.Revert ?? retryOutcome.Revert;
+ var recoveredStep = new Change
+ {
+ Index = step.Index,
+ Name = capturedStep?.Name ?? step.Name,
+ Description = capturedStep?.Description ?? step.Description,
+ Ok = true,
+ Revert = capturedRevert,
+ };
// Auto-persist recovered revert step if revertManager is available
if (
- recoveredStep.RevertStep != null
+ recoveredStep.Revert != null
&& revertManager != null
&& optimizationId.HasValue
)
@@ -453,11 +510,10 @@ public class OptimizationService(
try
{
await revertManager
- .UpsertRevertStepAtIndexAsync(
+ .AppendRevertStepAsync(
optimizationId.Value,
optimizationKey ?? string.Empty,
- step.Index, // Use original failed step's index
- recoveredStep.RevertStep
+ recoveredStep.Revert
)
.ConfigureAwait(false);
}
@@ -465,7 +521,7 @@ public class OptimizationService(
{
logger.LogError(
ex,
- "Failed to auto-persist revert step at index {Index}",
+ "Failed to auto-persist recovered revert step for {Index}",
step.Index
);
}
@@ -489,21 +545,38 @@ public class OptimizationService(
return new RetryFailedStepsResult(remainingFailedSteps, recoveredSteps);
}
- private async Task TrySaveRevertDataAsync(ExecutionScope scope, IOptimization optimization)
+ private async Task TrySaveRevertDataAsync(
+ ChangeSet changes,
+ IOptimization optimization,
+ CancellationToken cancellationToken = default
+ )
{
- if (!scope.HasSuccessfulSteps)
+ if (!changes.HasSuccessfulSteps)
return;
try
{
- await revertManager.SaveRevertDataAsync(scope).ConfigureAwait(false);
+ 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(
- ex,
- "Failed to save revert data for {Name}",
- optimization.OptimizationKey
+ _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()
);
}
}
@@ -542,7 +615,4 @@ public enum RestorePointResult
/// <summary>Represents the result of retrying failed operation steps, separating recovered steps from those that remain failed.</summary>
/// <param name="FailedSteps">The steps that remain failed after retry.</param>
/// <param name="RecoveredSteps">The steps that succeeded on retry.</param>
-public sealed record RetryFailedStepsResult(
- List<OperationStepResult> FailedSteps,
- List<OperationStepResult> RecoveredSteps
-);
+public sealed record RetryFailedStepsResult(List<Change> FailedSteps, List<Change> RecoveredSteps);
diff --git a/optimizerDuck/Services/Optimization/OptimizationValidation.cs b/optimizerDuck/Services/Optimization/OptimizationValidation.cs
new file mode 100644
index 0000000..86da532
--- /dev/null
+++ b/optimizerDuck/Services/Optimization/OptimizationValidation.cs
@@ -0,0 +1,38 @@
+using optimizerDuck.Domain.Optimizations.Models;
+
+namespace optimizerDuck.Services.Optimization;
+
+/// <summary>
+/// Fail-fast discovery validation: malformed or duplicated optimization
+/// IDs surface at startup with the offending class named, instead of a
+/// <c>FormatException</c> on first UI render.
+/// </summary>
+public static class OptimizationValidation
+{
+ public static void Validate(BaseOptimization optimization, HashSet<Guid> seen)
+ {
+ var typeName = optimization.GetType().FullName ?? optimization.GetType().Name;
+ Guid id;
+ try
+ {
+ id = optimization.Id;
+ }
+ catch (Exception ex)
+ {
+ throw new InvalidOperationException(
+ $"Optimization '{typeName}' has an invalid [Optimization] Id (must be a GUID).",
+ ex
+ );
+ }
+
+ if (id == Guid.Empty)
+ throw new InvalidOperationException(
+ $"Optimization '{typeName}' has an empty [Optimization] Id."
+ );
+
+ if (!seen.Add(id))
+ throw new InvalidOperationException(
+ $"Duplicate [Optimization] Id {id} (optimization '{typeName}'). IDs must be unique."
+ );
+ }
+}
diff --git a/optimizerDuck/Services/Optimization/Providers/ProcessRunner.cs b/optimizerDuck/Services/Optimization/Providers/ProcessRunner.cs
new file mode 100644
index 0000000..e1114f1
--- /dev/null
+++ b/optimizerDuck/Services/Optimization/Providers/ProcessRunner.cs
@@ -0,0 +1,254 @@
+using System.Diagnostics;
+using System.Text;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+using optimizerDuck.Domain.Configuration;
+
+namespace optimizerDuck.Services.Optimization.Providers;
+
+/// <summary>
+/// The captured output of a single child-process execution.
+/// </summary>
+/// <param name="ExitCode">The process exit code; <c>-1</c> on timeout, <c>-2</c> on exception.</param>
+/// <param name="Stdout">Raw captured standard output (not CLIXML-parsed).</param>
+/// <param name="Stderr">Raw captured standard error (not CLIXML-parsed).</param>
+/// <param name="TimedOut">Whether the process was killed because the shell timeout elapsed.</param>
+/// <param name="Duration">Wall-clock time from process start to exit (or kill).</param>
+/// <param name="Cancelled">Whether an external <see cref="CancellationToken"/> fired first.</param>
+public sealed record ProcessResult(
+ int ExitCode,
+ string Stdout,
+ string Stderr,
+ bool TimedOut,
+ TimeSpan Duration,
+ bool Cancelled = false
+);
+
+/// <summary>
+/// Single home for child-process execution: unified start, capture,
+/// timeout, kill-grace (2s) and force-kill logic. Async only.
+/// The timeout is read live from <see cref="AppSettings.Optimize"/>
+/// on every call, so settings changes apply without re-construction.
+/// </summary>
+public sealed class ProcessRunner
+{
+ private const int GraceDrainMs = 2000;
+ private const int ForceKillWaitMs = 5000;
+
+ private readonly Func<int> _readTimeoutMs;
+ private readonly ILogger<ProcessRunner>? _logger;
+
+ public ProcessRunner(
+ IOptionsMonitor<AppSettings> options,
+ ILogger<ProcessRunner>? logger = null
+ )
+ {
+ _readTimeoutMs = () => options.CurrentValue.Optimize.ShellTimeoutMs;
+ _logger = logger;
+ }
+
+ /// <summary>
+ /// Fixed-timeout construction for call sites outside DI (domain base
+ /// classes, revert steps). App paths use the options overload so
+ /// settings changes apply live.
+ /// </summary>
+ public ProcessRunner(int timeoutMs, ILogger<ProcessRunner>? logger = null)
+ {
+ _readTimeoutMs = () => timeoutMs;
+ _logger = logger;
+ }
+
+ /// <summary>Starts a process, captures stdout/stderr, and enforces the live shell timeout.</summary>
+ public async Task<ProcessResult> RunAsync(
+ string fileName,
+ string arguments,
+ CancellationToken ct = default
+ )
+ {
+ var timeoutMs = Math.Max(1, _readTimeoutMs());
+
+ var psi = new ProcessStartInfo
+ {
+ FileName = fileName,
+ Arguments = arguments,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ StandardOutputEncoding = Encoding.UTF8,
+ StandardErrorEncoding = Encoding.UTF8,
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ };
+
+ var sw = Stopwatch.StartNew();
+ try
+ {
+ using var process = new Process { StartInfo = psi };
+
+ var stdoutBuilder = new StringBuilder();
+ var stderrBuilder = new StringBuilder();
+
+ process.OutputDataReceived += (_, e) =>
+ {
+ if (e.Data != null)
+ stdoutBuilder.AppendLine(e.Data);
+ };
+ process.ErrorDataReceived += (_, e) =>
+ {
+ if (e.Data != null)
+ stderrBuilder.AppendLine(e.Data);
+ };
+
+ process.Start();
+ var pid = TryGetPid(process);
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
+
+ using var timeoutCts = new CancellationTokenSource(timeoutMs);
+ using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
+ timeoutCts.Token,
+ ct
+ );
+
+ var timedOut = false;
+ var cancelled = false;
+ try
+ {
+ await process.WaitForExitAsync(linkedCts.Token).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ // External cancellation wins over our own timeout when both fired.
+ cancelled = ct.IsCancellationRequested && !timeoutCts.IsCancellationRequested;
+ timedOut = !cancelled;
+
+ _logger?.LogWarning(
+ "Process {Reason}, attempting to kill: PID {ProcessId}",
+ cancelled ? "cancelled" : "timed out",
+ pid
+ );
+
+ TryKill(process, pid, cancelled ? "cancel" : "timeout");
+ }
+
+ sw.Stop();
+
+ if (!HasExited(process))
+ {
+ // Still running after the kill attempt: grace period, then force kill.
+ _logger?.LogWarning(
+ "Process still running after kill, waiting grace period: PID {ProcessId}",
+ pid
+ );
+ try
+ {
+ process.WaitForExit(GraceDrainMs);
+ }
+ catch (Exception ex)
+ {
+ _logger?.LogError(
+ ex,
+ "Failed to wait for process exit after kill, PID: {ProcessId}",
+ pid
+ );
+ }
+
+ if (!HasExited(process))
+ {
+ _logger?.LogWarning(
+ "Process still running after grace period, force killing: PID {ProcessId}",
+ pid
+ );
+ TryKill(process, pid, "force kill");
+ try
+ {
+ if (!process.WaitForExit(ForceKillWaitMs))
+ _logger?.LogWarning(
+ "Process did not exit after force kill: PID {ProcessId}. User may need manual cleanup.",
+ pid
+ );
+ }
+ catch (Exception ex)
+ {
+ _logger?.LogError(
+ ex,
+ "Failed to wait for process exit after force kill, PID: {ProcessId}",
+ pid
+ );
+ }
+ }
+
+ timedOut |= !cancelled && !HasExited(process);
+ }
+
+ var exited = HasExited(process);
+ return new ProcessResult(
+ !exited ? -1
+ : timedOut ? -1
+ : process.ExitCode,
+ stdoutBuilder.ToString().Trim(),
+ stderrBuilder.ToString().Trim(),
+ timedOut || !exited,
+ sw.Elapsed,
+ cancelled
+ );
+ }
+ catch (Exception ex)
+ {
+ sw.Stop();
+ _logger?.LogError(ex, "Failed to execute {FileName}", fileName);
+ return new ProcessResult(
+ -2,
+ string.Empty,
+ ex.Message,
+ false,
+ sw.Elapsed,
+ ct.IsCancellationRequested
+ );
+ }
+ }
+
+ private void TryKill(Process process, int pid, string reason)
+ {
+ try
+ {
+ if (!HasExited(process))
+ {
+ process.Kill(entireProcessTree: true);
+ _logger?.LogInformation("Killed process ({Reason}): PID {ProcessId}", reason, pid);
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger?.LogError(
+ ex,
+ "Failed to kill process ({Reason}), PID: {ProcessId}",
+ reason,
+ pid
+ );
+ }
+ }
+
+ private static bool HasExited(Process process)
+ {
+ try
+ {
+ return process.HasExited;
+ }
+ catch
+ {
+ return true;
+ }
+ }
+
+ private static int TryGetPid(Process process)
+ {
+ try
+ {
+ return process.Id;
+ }
+ catch
+ {
+ return -1;
+ }
+ }
+}
diff --git a/optimizerDuck/Services/Optimization/Providers/RegistryService.cs b/optimizerDuck/Services/Optimization/Providers/RegistryService.cs
index 90a978a..8ffacfd 100644
--- a/optimizerDuck/Services/Optimization/Providers/RegistryService.cs
+++ b/optimizerDuck/Services/Optimization/Providers/RegistryService.cs
@@ -2,6 +2,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Security;
+using Microsoft.Extensions.Logging;
using Microsoft.Win32;
using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
@@ -11,12 +12,6 @@ namespace optimizerDuck.Services.Optimization.Providers;
public static class RegistryService
{
- private static readonly AsyncLocal<string?> _lastError = new();
- private static readonly AsyncLocal<string?> _lastErrorDetail = new();
-
- internal static string? LastError => _lastError.Value;
- internal static string? LastErrorDetail => _lastErrorDetail.Value;
-
private static readonly Dictionary<string, RegistryKey> RootKeysMap = new(
StringComparer.OrdinalIgnoreCase
)
@@ -40,6 +35,7 @@ public static class RegistryService
private static bool TryParsePath(
string fullPath,
+ ILogger? logger,
[NotNullWhen(true)] out RegistryKey? rootKey,
[NotNullWhen(true)] out string? subPath
)
@@ -49,9 +45,7 @@ public static class RegistryService
if (string.IsNullOrWhiteSpace(fullPath))
{
- _lastError.Value = _lastErrorDetail.Value = "Registry path is null or empty";
- ExecutionScope.LogError(null, "Registry path is null or empty");
- ExecutionScope.Track(nameof(RegistryService), false);
+ logger?.LogError("Registry path is null or empty");
return false;
}
@@ -61,9 +55,7 @@ public static class RegistryService
if (!RootKeysMap.TryGetValue(rootToken, out rootKey))
{
- _lastError.Value = _lastErrorDetail.Value = $"Unknown root key: {rootToken}";
- ExecutionScope.LogError(null, "Unknown root key: {RootToken}", rootToken);
- ExecutionScope.Track(nameof(RegistryService), false);
+ logger?.LogError("Unknown root key: {RootToken}", rootToken);
return false;
}
@@ -78,11 +70,16 @@ public static class RegistryService
out bool shouldDispose,
bool writable,
bool createIfMissing,
- List<string>? createdSubKeys
+ List<string>? createdSubKeys,
+ ILogger? logger,
+ out string? error,
+ out string? errorDetail
)
{
key = null;
shouldDispose = false;
+ error = null;
+ errorDetail = null;
if (string.IsNullOrEmpty(subPath))
{
@@ -97,7 +94,7 @@ public static class RegistryService
if (opened == null && writable && createIfMissing)
opened =
createdSubKeys != null
- ? CreateSubKeyTrack(rootKey, subPath, createdSubKeys)
+ ? CreateSubKeyTrack(rootKey, subPath, createdSubKeys, logger)
: rootKey.CreateSubKey(subPath);
if (opened != null)
@@ -111,35 +108,26 @@ public static class RegistryService
}
catch (SecurityException ex)
{
- TrackRegistryError(
- ServiceStrings.RegistryErrorAccessDeniedProtectedHive,
- "Access denied (protected hive)",
- rootKey,
- subPath,
- ex
- );
+ var path = $"{rootKey.Name}\\{subPath}";
+ error = ServiceStrings.RegistryErrorAccessDeniedProtectedHive;
+ errorDetail = ex.ToString();
+ logger?.LogError(ex, "Access denied (protected hive): {Path}", path);
return false;
}
catch (UnauthorizedAccessException ex)
{
- TrackRegistryError(
- ServiceStrings.RegistryErrorUnauthorizedAccess,
- "Unauthorized access",
- rootKey,
- subPath,
- ex
- );
+ var path = $"{rootKey.Name}\\{subPath}";
+ error = ServiceStrings.RegistryErrorUnauthorizedAccess;
+ errorDetail = ex.ToString();
+ logger?.LogError(ex, "Unauthorized access: {Path}", path);
return false;
}
catch (Exception ex)
{
- TrackRegistryError(
- ServiceStrings.RegistryErrorCreateOrOpenSubkeyFailed,
- "Failed to create/open subkey",
- rootKey,
- subPath,
- ex
- );
+ var path = $"{rootKey.Name}\\{subPath}";
+ error = ServiceStrings.RegistryErrorCreateOrOpenSubkeyFailed;
+ errorDetail = ex.ToString();
+ logger?.LogError(ex, "Failed to create/open subkey: {Path}", path);
return false;
}
}
@@ -147,12 +135,20 @@ public static class RegistryService
private static T? WithKey<T>(
RegistryItem item,
Func<RegistryKey, T?> action,
+ ILogger? logger,
+ out bool opened,
+ out string? openError,
+ out string? openErrorDetail,
bool writable = false,
bool createIfMissing = false,
List<string>? createdSubKeys = null
)
{
- if (!TryParsePath(item.Path, out var rootKey, out var subPath))
+ opened = false;
+ openError = null;
+ openErrorDetail = null;
+
+ if (!TryParsePath(item.Path, logger, out var rootKey, out var subPath))
return default;
if (
@@ -163,11 +159,16 @@ public static class RegistryService
out var shouldDispose,
writable,
createIfMissing,
- createdSubKeys
+ createdSubKeys,
+ logger,
+ out openError,
+ out openErrorDetail
)
)
return default;
+ opened = true;
+
try
{
return subKey == null ? default : action(subKey);
@@ -186,17 +187,19 @@ public static class RegistryService
/// <summary>Determines whether the specified registry key path exists.</summary>
/// <param name="item">The registry path to check.</param>
+ /// <param name="logger">Optional logger; <c>null</c> means silent.</param>
/// <returns><see langword="true" /> if the key exists; otherwise, <see langword="false" />.</returns>
- public static bool KeyExists(RegistryItem item)
+ public static bool KeyExists(RegistryItem item, ILogger? logger = null)
{
- return WithKey(item, key => true, false);
+ return WithKey<bool>(item, key => true, logger, out _, out _, out _);
}
/// <summary>Reads a registry value and converts it to the specified type.</summary>
/// <typeparam name="T">The target type to convert the value to.</typeparam>
/// <param name="item">The registry path and value name to read.</param>
+ /// <param name="logger">Optional logger; <c>null</c> means silent.</param>
/// <returns>The converted value, or the default of <typeparamref name="T" /> if the value is missing or conversion fails.</returns>
- public static T? Read<T>(RegistryItem item)
+ public static T? Read<T>(RegistryItem item, ILogger? logger = null)
{
return WithKey(
item,
@@ -214,7 +217,7 @@ public static class RegistryService
return default;
var result = ConvertRegistryValue<T>(value);
- ExecutionScope.LogInfo(
+ logger?.LogInformation(
"Read registry {Path}:{Name} = {Value}",
item.Path,
item.Name!,
@@ -224,7 +227,7 @@ public static class RegistryService
}
catch (Exception ex)
{
- ExecutionScope.LogError(
+ logger?.LogError(
ex,
"Failed to read registry {Path}:{Name}",
item.Path,
@@ -232,59 +235,79 @@ public static class RegistryService
);
return default;
}
- }
+ },
+ logger,
+ out _,
+ out _,
+ out _
);
}
/// <summary>Writes a value to the registry, backing up the previous value for revert.</summary>
+ /// <param name="call">The call context carrying the change collector and logger.</param>
/// <param name="item">The registry path, value name, value, and kind to write.</param>
- /// <returns><see langword="true" /> if the write succeeded; otherwise, <see langword="false" />.</returns>
- public static bool Write(RegistryItem item)
+ /// <returns>The operation result, carrying the revert step on success.</returns>
+ public static OpResult Write(OpCall call, RegistryItem item)
{
- _lastError.Value = _lastErrorDetail.Value = null;
+ ArgumentNullException.ThrowIfNull(call);
+ var name = ServiceStrings.RegistryName;
+ var description = ServiceStrings.Format(
+ ServiceStrings.RegistryDescriptionWrite,
+ item.Path,
+ item.Name
+ );
+ var logger = call.Logger;
if (item.Value == null)
{
- _lastError.Value = _lastErrorDetail.Value =
- $"Value cannot be null when writing {item.Path}:{item.Name}";
- ExecutionScope.LogError(
- null,
+ var nullError = $"Value cannot be null when writing {item.Path}:{item.Name}";
+ logger.LogError(
"Value can't be null when writing {Path}:{Name}",
item.Path,
item.Name!
);
- ExecutionScope.Track(nameof(Write), false);
- return false;
+ return OpResult.Fail(nullError, nullError);
}
var createdSubKeys = new List<string>();
- return WithKey(
+ var result = WithKey<OpResult>(
item,
- key =>
+ regKey =>
{
- var description = ServiceStrings.Format(
- ServiceStrings.RegistryDescriptionWrite,
- item.Path,
- item.Name
- );
try
{
var valueName = NormalizeValueName(item.Name);
- var backupValue = key.GetValue(
+ var backupValue = regKey.GetValue(
valueName,
null,
RegistryValueOptions.DoNotExpandEnvironmentNames
);
var valueExists =
backupValue != null
- || key.GetValueNames()
+ || regKey
+ .GetValueNames()
.Contains(valueName, StringComparer.OrdinalIgnoreCase);
var backupKind = valueExists
- ? key.GetValueKind(valueName)
+ ? regKey.GetValueKind(valueName)
: RegistryValueKind.Unknown;
- key.SetValue(valueName, item.Value, item.Kind);
+ if (
+ valueExists
+ && backupKind == item.Kind
+ && ValuesEqual(backupValue, item.Value, item.Kind)
+ )
+ {
+ logger.LogInformation(
+ "Skip write registry {Path}:{Name} (already set)",
+ item.Path,
+ item.Name!
+ );
+ call.Changes.Add(name, description, true);
+ return OpResult.Success();
+ }
+
+ regKey.SetValue(valueName, item.Value, item.Kind);
var revertStep = new RegistryRevertStep
{
@@ -298,119 +321,131 @@ public static class RegistryService
CreatedSubKeys = createdSubKeys,
};
- ExecutionScope.LogInfo(
+ logger.LogInformation(
"Wrote {Path}:{Name}[{Kind}] = {Value}",
item.Path,
item.Name!,
item.Kind,
item.Value
);
- ExecutionScope.Track(nameof(Write), true);
- ExecutionScope.RecordStep(
- ServiceStrings.RegistryName,
- description,
- true,
- revertStep
- );
- return true;
+ call.Changes.Add(name, description, true, revertStep);
+ return OpResult.Success(revertStep);
}
catch (UnauthorizedAccessException)
{
- _lastError.Value = ServiceStrings.CommonErrorAccessDenied;
- _lastErrorDetail.Value = ServiceStrings.Format(
+ var error = ServiceStrings.CommonErrorAccessDenied;
+ var errorDetail = ServiceStrings.Format(
ServiceStrings.RegistryErrorDetailAccessDeniedWrite,
item.Path,
item.Name
);
- ExecutionScope.LogError(
- null,
- "Access denied writing {Path}:{Name}",
- item.Path,
- item.Name!
- );
- ExecutionScope.Track(nameof(Write), false);
- ExecutionScope.RecordStep(
- ServiceStrings.RegistryName,
+ logger.LogError("Access denied writing {Path}:{Name}", item.Path, item.Name!);
+ call.Changes.Add(
+ name,
description,
false,
null,
- _lastError.Value,
- () => Task.FromResult(Write(item)),
- _lastErrorDetail.Value
+ error,
+ errorDetail,
+ (OpCall rc) => Task.FromResult(Write(rc, item))
);
- return false;
+ return OpResult.Fail(error, errorDetail);
}
catch (Exception ex)
{
- _lastError.Value = ex.Message;
- _lastErrorDetail.Value = ex.ToString();
- ExecutionScope.LogError(
+ var error = ex.Message;
+ var errorDetail = ex.ToString();
+ logger.LogError(
ex,
"Failed to write registry {Path}:{Name}",
item.Path,
item.Name!
);
- ExecutionScope.Track(nameof(Write), false);
- ExecutionScope.RecordStep(
- ServiceStrings.RegistryName,
+ call.Changes.Add(
+ name,
description,
false,
null,
- _lastError.Value,
- () => Task.FromResult(Write(item)),
- _lastErrorDetail.Value
+ error,
+ errorDetail,
+ (OpCall rc) => Task.FromResult(Write(rc, item))
);
- return false;
+ return OpResult.Fail(error, errorDetail);
}
},
+ logger,
+ out _,
+ out var openError,
+ out var openErrorDetail,
true,
true,
createdSubKeys
);
+
+ if (result is null)
+ {
+ if (openError is null)
+ return OpResult.Fail($"Failed to access registry {item.Path}:{item.Name}.");
+ call.Changes.Add(
+ name,
+ description,
+ false,
+ null,
+ openError,
+ openErrorDetail,
+ (OpCall rc) => Task.FromResult(Write(rc, item))
+ );
+ return OpResult.Fail(openError, openErrorDetail);
+ }
+
+ return result;
}
/// <summary>Deletes a registry value, backing up the current value for revert.</summary>
+ /// <param name="call">The call context carrying the change collector and logger.</param>
/// <param name="item">The registry path and value name to delete.</param>
- /// <returns><see langword="true" /> if the value was deleted or did not exist; otherwise, <see langword="false" />.</returns>
- public static bool DeleteValue(RegistryItem item)
+ /// <returns>The operation result, carrying the revert step on success.</returns>
+ public static OpResult DeleteValue(OpCall call, RegistryItem item)
{
- _lastError.Value = _lastErrorDetail.Value = null;
+ ArgumentNullException.ThrowIfNull(call);
+ var name = ServiceStrings.RegistryName;
+ var description = ServiceStrings.Format(
+ ServiceStrings.RegistryDescriptionDelete,
+ item.Path,
+ item.Name ?? "(Default)"
+ );
+ var logger = call.Logger;
- return WithKey(
+ var result = WithKey<OpResult>(
item,
- key =>
+ regKey =>
{
- var description = ServiceStrings.Format(
- ServiceStrings.RegistryDescriptionDelete,
- item.Path,
- item.Name ?? "(Default)"
- );
try
{
var valueName = NormalizeValueName(item.Name);
- var backupValue = key.GetValue(
+ var backupValue = regKey.GetValue(
valueName,
null,
RegistryValueOptions.DoNotExpandEnvironmentNames
);
if (
backupValue == null
- && !key.GetValueNames()
+ && !regKey
+ .GetValueNames()
.Contains(valueName, StringComparer.OrdinalIgnoreCase)
)
{
- ExecutionScope.LogInfo(
+ logger.LogInformation(
"Skip delete registry {Path}:{Name} (not found)",
item.Path,
item.Name!
);
- ExecutionScope.Track(nameof(DeleteValue), true);
- ExecutionScope.RecordStep(ServiceStrings.RegistryName, description, true);
- return true;
+ call.Changes.Add(name, description, true);
+ return OpResult.Success();
}
- var backupKind = key.GetValueKind(valueName);
- key.DeleteValue(valueName, false);
+ var backupKind = regKey.GetValueKind(valueName);
+ regKey.DeleteValue(valueName, false);
var revertStep = new RegistryRevertStep
{
@@ -421,97 +456,108 @@ public static class RegistryService
Kind = backupKind,
};
- ExecutionScope.LogInfo("Deleted registry {Path}:{Name}", item.Path, item.Name!);
- ExecutionScope.Track(nameof(DeleteValue), true);
- ExecutionScope.RecordStep(
- ServiceStrings.RegistryName,
- description,
- true,
- revertStep
- );
- return true;
+ logger.LogInformation("Deleted registry {Path}:{Name}", item.Path, item.Name!);
+ call.Changes.Add(name, description, true, revertStep);
+ return OpResult.Success(revertStep);
}
catch (UnauthorizedAccessException)
{
- _lastError.Value = ServiceStrings.CommonErrorAccessDenied;
- _lastErrorDetail.Value = ServiceStrings.Format(
+ var error = ServiceStrings.CommonErrorAccessDenied;
+ var errorDetail = ServiceStrings.Format(
ServiceStrings.RegistryErrorDetailAccessDeniedDelete,
item.Path,
item.Name
);
- ExecutionScope.LogError(
- null,
- "Access denied deleting {Path}:{Name}",
- item.Path,
- item.Name!
- );
- ExecutionScope.Track(nameof(DeleteValue), false);
- ExecutionScope.RecordStep(
- ServiceStrings.RegistryName,
+ logger.LogError("Access denied deleting {Path}:{Name}", item.Path, item.Name!);
+ call.Changes.Add(
+ name,
description,
false,
null,
- _lastError.Value,
- () => Task.FromResult(DeleteValue(item)),
- _lastErrorDetail.Value
+ error,
+ errorDetail,
+ (OpCall rc) => Task.FromResult(DeleteValue(rc, item))
);
- return false;
+ return OpResult.Fail(error, errorDetail);
}
catch (Exception ex)
{
- _lastError.Value = ex.Message;
- _lastErrorDetail.Value = ex.ToString();
- ExecutionScope.LogError(
+ var error = ex.Message;
+ var errorDetail = ex.ToString();
+ logger.LogError(
ex,
"Failed to delete registry {Path}:{Name}",
item.Path,
item.Name!
);
- ExecutionScope.Track(nameof(DeleteValue), false);
- ExecutionScope.RecordStep(
- ServiceStrings.RegistryName,
+ call.Changes.Add(
+ name,
description,
false,
null,
- _lastError.Value,
- () => Task.FromResult(DeleteValue(item)),
- _lastErrorDetail.Value
+ error,
+ errorDetail,
+ (OpCall rc) => Task.FromResult(DeleteValue(rc, item))
);
- return false;
+ return OpResult.Fail(error, errorDetail);
}
},
+ logger,
+ out _,
+ out var openError,
+ out var openErrorDetail,
true
);
+
+ if (result is null)
+ {
+ if (openError is null)
+ return OpResult.Fail($"Failed to access registry {item.Path}:{item.Name}.");
+ call.Changes.Add(
+ name,
+ description,
+ false,
+ null,
+ openError,
+ openErrorDetail,
+ (OpCall rc) => Task.FromResult(DeleteValue(rc, item))
+ );
+ return OpResult.Fail(openError, openErrorDetail);
+ }
+
+ return result;
}
/// <summary>Creates a registry subkey, tracking created intermediate keys for revert.</summary>
+ /// <param name="call">The call context carrying the change collector and logger.</param>
/// <param name="item">The registry path of the key to create.</param>
- /// <returns><see langword="true" /> if the key was created or already exists; otherwise, <see langword="false" />.</returns>
- public static bool CreateSubKey(RegistryItem item)
+ /// <returns>The operation result, carrying the revert step on success.</returns>
+ public static OpResult CreateSubKey(OpCall call, RegistryItem item)
{
- _lastError.Value = _lastErrorDetail.Value = null;
-
- if (!TryParsePath(item.Path, out var rootKey, out var subPath))
- return false;
-
+ ArgumentNullException.ThrowIfNull(call);
+ var name = ServiceStrings.RegistryName;
var description = ServiceStrings.Format(
ServiceStrings.RegistryDescriptionCreateKey,
item.Path
);
+ var logger = call.Logger;
+
+ if (!TryParsePath(item.Path, logger, out var rootKey, out var subPath))
+ return OpResult.Fail($"Failed to parse registry path: {item.Path}.");
+
var createdSubKeys = new List<string>();
try
{
- using var key = rootKey.OpenSubKey(subPath, false);
- if (key != null)
+ using var regKey = rootKey.OpenSubKey(subPath, false);
+ if (regKey != null)
{
- ExecutionScope.LogInfo("Skip create registry {Path} (already exists)", item.Path);
- ExecutionScope.Track(nameof(CreateSubKey), true);
- ExecutionScope.RecordStep(ServiceStrings.RegistryName, description, true);
- return true;
+ logger.LogInformation("Skip create registry {Path} (already exists)", item.Path);
+ call.Changes.Add(name, description, true);
+ return OpResult.Success();
}
- using var newKey = CreateSubKeyTrack(rootKey, subPath, createdSubKeys);
+ using var newKey = CreateSubKeyTrack(rootKey, subPath, createdSubKeys, logger);
var revertStep = new RegistryRevertStep
{
@@ -521,99 +567,92 @@ public static class RegistryService
CreatedSubKeys = createdSubKeys,
};
- ExecutionScope.LogInfo("Created registry key {Path}", item.Path);
- ExecutionScope.Track(nameof(CreateSubKey), true);
- ExecutionScope.RecordStep(ServiceStrings.RegistryName, description, true, revertStep);
- return true;
+ logger.LogInformation("Created registry key {Path}", item.Path);
+ call.Changes.Add(name, description, true, revertStep);
+ return OpResult.Success(revertStep);
}
catch (UnauthorizedAccessException)
{
- _lastError.Value = ServiceStrings.CommonErrorAccessDenied;
- _lastErrorDetail.Value = ServiceStrings.Format(
+ var error = ServiceStrings.CommonErrorAccessDenied;
+ var errorDetail = ServiceStrings.Format(
ServiceStrings.RegistryErrorDetailAccessDeniedCreateKey,
item.Path
);
- ExecutionScope.LogError(null, "Access denied creating {Path}", item.Path);
- ExecutionScope.Track(nameof(CreateSubKey), false);
- ExecutionScope.RecordStep(
- ServiceStrings.RegistryName,
+ logger.LogError("Access denied creating {Path}", item.Path);
+ call.Changes.Add(
+ name,
description,
false,
null,
- _lastError.Value,
- () => Task.FromResult(CreateSubKey(item)),
- _lastErrorDetail.Value
+ error,
+ errorDetail,
+ (OpCall rc) => Task.FromResult(CreateSubKey(rc, item))
);
- return false;
+ return OpResult.Fail(error, errorDetail);
}
catch (Exception ex)
{
- _lastError.Value = ex.Message;
- _lastErrorDetail.Value = ex.ToString();
- ExecutionScope.LogError(ex, "Failed to create registry {Path}", item.Path);
- ExecutionScope.Track(nameof(CreateSubKey), false);
- ExecutionScope.RecordStep(
- ServiceStrings.RegistryName,
+ var error = ex.Message;
+ var errorDetail = ex.ToString();
+ logger.LogError(ex, "Failed to create registry {Path}", item.Path);
+ call.Changes.Add(
+ name,
description,
false,
null,
- _lastError.Value,
- () => Task.FromResult(CreateSubKey(item)),
- _lastErrorDetail.Value
+ error,
+ errorDetail,
+ (OpCall rc) => Task.FromResult(CreateSubKey(rc, item))
);
- return false;
+ return OpResult.Fail(error, errorDetail);
}
}
/// <summary>Deletes an entire registry key tree, backing up all values and subkeys for revert.</summary>
+ /// <param name="call">The call context carrying the change collector and logger.</param>
/// <param name="item">The registry path of the key tree to delete.</param>
- /// <returns><see langword="true" /> if the tree was deleted or did not exist; otherwise, <see langword="false" />.</returns>
- public static bool DeleteSubKeyTree(RegistryItem item)
+ /// <returns>The operation result, carrying the revert step on success.</returns>
+ public static OpResult DeleteSubKeyTree(OpCall call, RegistryItem item)
{
- _lastError.Value = _lastErrorDetail.Value = null;
-
- if (!TryParsePath(item.Path, out var rootKey, out var subPath))
- return false;
-
+ ArgumentNullException.ThrowIfNull(call);
+ var name = ServiceStrings.RegistryName;
var description = ServiceStrings.Format(
ServiceStrings.RegistryDescriptionDeleteKey,
item.Path
);
+ var logger = call.Logger;
+
+ if (!TryParsePath(item.Path, logger, out var rootKey, out var subPath))
+ return OpResult.Fail($"Failed to parse registry path: {item.Path}.");
try
{
- using var key = rootKey.OpenSubKey(subPath, false);
- if (key == null)
+ using var regKey = rootKey.OpenSubKey(subPath, false);
+ if (regKey == null)
{
- ExecutionScope.LogInfo("Skip delete registry key {Path} (not found)", item.Path);
- ExecutionScope.Track(nameof(DeleteSubKeyTree), true);
- ExecutionScope.RecordStep(ServiceStrings.RegistryName, description, true);
- return true;
+ logger.LogInformation("Skip delete registry key {Path} (not found)", item.Path);
+ call.Changes.Add(name, description, true);
+ return OpResult.Success();
}
- var (subSteps, backupComplete) = BackupRegistryTree(key, item.Path);
+ var (subSteps, backupComplete) = BackupRegistryTree(regKey, item.Path, logger);
if (!backupComplete)
{
- var msg = ServiceStrings.Format(
+ var error = ServiceStrings.Format(
ServiceStrings.RegistryErrorBackupTruncated,
item.Path
);
- _lastError.Value = _lastErrorDetail.Value = msg;
- ExecutionScope.LogError(
- null,
- "Registry subtree backup truncated for {Path}",
- item.Path
- );
- ExecutionScope.Track(nameof(DeleteSubKeyTree), false);
- ExecutionScope.RecordStep(
- ServiceStrings.RegistryName,
+ logger.LogError("Registry subtree backup truncated for {Path}", item.Path);
+ call.Changes.Add(
+ name,
description,
false,
null,
- _lastError.Value,
- () => Task.FromResult(DeleteSubKeyTree(item))
+ error,
+ error,
+ (OpCall rc) => Task.FromResult(DeleteSubKeyTree(rc, item))
);
- return false;
+ return OpResult.Fail(error, error);
}
rootKey.DeleteSubKeyTree(subPath, false);
@@ -625,58 +664,56 @@ public static class RegistryService
SubSteps = subSteps,
};
- ExecutionScope.LogInfo("Deleted registry key tree {Path}", item.Path);
- ExecutionScope.Track(nameof(DeleteSubKeyTree), true);
- ExecutionScope.RecordStep(ServiceStrings.RegistryName, description, true, revertStep);
- return true;
+ logger.LogInformation("Deleted registry key tree {Path}", item.Path);
+ call.Changes.Add(name, description, true, revertStep);
+ return OpResult.Success(revertStep);
}
catch (UnauthorizedAccessException)
{
- _lastError.Value = ServiceStrings.RegistryErrorAccessDeniedProtectedHive;
- _lastErrorDetail.Value = ServiceStrings.Format(
+ var error = ServiceStrings.RegistryErrorAccessDeniedProtectedHive;
+ var errorDetail = ServiceStrings.Format(
ServiceStrings.RegistryErrorDetailAccessDeniedDeleteKeyTree,
item.Path
);
- ExecutionScope.LogError(null, "Access denied deleting {Path}", item.Path);
- ExecutionScope.Track(nameof(DeleteSubKeyTree), false);
- ExecutionScope.RecordStep(
- ServiceStrings.RegistryName,
+ logger.LogError("Access denied deleting {Path}", item.Path);
+ call.Changes.Add(
+ name,
description,
false,
null,
- _lastError.Value,
- () => Task.FromResult(DeleteSubKeyTree(item)),
- _lastErrorDetail.Value
+ error,
+ errorDetail,
+ (OpCall rc) => Task.FromResult(DeleteSubKeyTree(rc, item))
);
- return false;
+ return OpResult.Fail(error, errorDetail);
}
catch (Exception ex)
{
- _lastError.Value = ex.Message;
- _lastErrorDetail.Value = ex.ToString();
- ExecutionScope.LogError(ex, "Failed to delete subkey tree {Path}", item.Path);
- ExecutionScope.Track(nameof(DeleteSubKeyTree), false);
- ExecutionScope.RecordStep(
- ServiceStrings.RegistryName,
+ var error = ex.Message;
+ var errorDetail = ex.ToString();
+ logger.LogError(ex, "Failed to delete subkey tree {Path}", item.Path);
+ call.Changes.Add(
+ name,
description,
false,
null,
- _lastError.Value,
- () => Task.FromResult(DeleteSubKeyTree(item)),
- _lastErrorDetail.Value
+ error,
+ errorDetail,
+ (OpCall rc) => Task.FromResult(DeleteSubKeyTree(rc, item))
);
- return false;
+ return OpResult.Fail(error, errorDetail);
}
}
private static (List<RegistryRevertStep> Steps, bool IsComplete) BackupRegistryTree(
RegistryKey key,
- string keyPath
+ string keyPath,
+ ILogger? logger
)
{
var steps = new List<RegistryRevertStep>();
var truncated = false;
- BackupRegistryTreeRecursive(key, keyPath, steps, 0, ref truncated);
+ BackupRegistryTreeRecursive(key, keyPath, steps, 0, ref truncated, logger);
return (steps, !truncated);
}
@@ -687,13 +724,14 @@ public static class RegistryService
string keyPath,
List<RegistryRevertStep> steps,
int depth,
- ref bool truncated
+ ref bool truncated,
+ ILogger? logger
)
{
if (depth > 15 || steps.Count > 5000)
{
truncated = true;
- ExecutionScope.LogWarning(
+ logger?.LogWarning(
"Registry subtree backup limit reached at {Path} (depth: {Depth}, items: {Count})",
keyPath,
depth,
@@ -743,25 +781,35 @@ public static class RegistryService
$@"{keyPath}\{subKeyName}",
steps,
depth + 1,
- ref truncated
+ ref truncated,
+ logger
);
}
}
- /// <summary>Writes multiple distinct registry values.</summary>
- /// <param name="items">The registry items to write.</param>
- public static void Write(params RegistryItem[] items)
+ /// <summary>Writes multiple distinct registry values, recording one change per item.</summary>
+ /// <param name="call">The shared call context for all items.</param>
+ /// <param name="items">The registry items to write. All are attempted; the first failure is returned.</param>
+ public static OpResult Write(OpCall call, params RegistryItem[] items)
{
- foreach (var item in items.Distinct())
- Write(item);
+ ArgumentNullException.ThrowIfNull(call);
+ ArgumentNullException.ThrowIfNull(items);
+
+ // Materialise before aggregating: a lazy sequence would stop at the first failure.
+ return OpResult.FirstFailure(items.Distinct().Select(item => Write(call, item)).ToList());
}
- /// <summary>Deletes multiple distinct registry values.</summary>
- /// <param name="items">The registry items to delete.</param>
- public static void DeleteValue(params RegistryItem[] items)
+ /// <summary>Deletes multiple distinct registry values, recording one change per item.</summary>
+ /// <param name="call">The shared call context for all items.</param>
+ /// <param name="items">The registry items to delete. All are attempted; the first failure is returned.</param>
+ public static OpResult DeleteValue(OpCall call, params RegistryItem[] items)
{
- foreach (var item in items.Distinct())
- DeleteValue(item);
+ ArgumentNullException.ThrowIfNull(call);
+ ArgumentNullException.ThrowIfNull(items);
+
+ return OpResult.FirstFailure(
+ items.Distinct().Select(item => DeleteValue(call, item)).ToList()
+ );
}
#region Helpers
@@ -813,30 +861,13 @@ public static class RegistryService
return (T)converted!;
}
- private static void TrackRegistryError(
- string uiReason,
- string logReason,
- RegistryKey root,
- string? subPath,
- Exception ex
- )
- {
- var path = string.IsNullOrEmpty(subPath) ? root.Name : $"{root.Name}\\{subPath}";
- _lastError.Value = _lastErrorDetail.Value = uiReason;
-
- ExecutionScope.LogError(ex, "{Reason}: {Path}", logReason, path);
-
- ExecutionScope.Track(nameof(RegistryService), false);
-
- ExecutionScope.RecordStep(ServiceStrings.RegistryName, path, false, null, uiReason);
- }
-
// walks each segment of the subkey path, creating missing segments one by one
// only tracks the keys it actually creates so revert cleanup knows what to delete
private static RegistryKey CreateSubKeyTrack(
RegistryKey root,
string subPath,
- List<string> createdSubKeys
+ List<string> createdSubKeys,
+ ILogger? logger
)
{
var parts = subPath.Split('\\', StringSplitOptions.RemoveEmptyEntries);
@@ -861,7 +892,7 @@ public static class RegistryService
);
createdSubKeys.Add($"{root.Name}\\{currentPath}");
- ExecutionScope.LogDebug(
+ logger?.LogDebug(
"Created registry subkey: {Path}",
$"{root.Name}\\{currentPath}"
);
@@ -893,7 +924,8 @@ public static class RegistryService
/// subkeys). Sorts by path depth descending so child keys are deleted before parents.
/// </remarks>
/// <param name="createdSubKeys">The list of registry key paths that were created.</param>
- public static void CleanupEmptyKeys(IEnumerable<string> createdSubKeys)
+ /// <param name="logger">Optional logger; <c>null</c> means silent.</param>
+ public static void CleanupEmptyKeys(IEnumerable<string> createdSubKeys, ILogger? logger = null)
{
// Sort by path length descending to delete deepest keys first
var sortedKeys = createdSubKeys
@@ -905,7 +937,7 @@ public static class RegistryService
foreach (var fullPath in sortedKeys)
try
{
- if (!TryParsePath(fullPath, out var root, out var subPath))
+ if (!TryParsePath(fullPath, logger, out var root, out var subPath))
continue;
// Check if the key still exists and is empty
@@ -933,12 +965,12 @@ public static class RegistryService
parent?.DeleteSubKey(keyName, false);
}
- ExecutionScope.LogInfo("Cleaned up empty registry key {Path}", fullPath);
+ logger?.LogInformation("Cleaned up empty registry key {Path}", fullPath);
}
else
{
// Key is not empty, don't delete it
- ExecutionScope.LogDebug(
+ logger?.LogDebug(
"Skipped cleanup of registry key {Path} (has {SubKeyCount} subkeys and {ValueCount} values)",
fullPath,
key.SubKeyCount,
@@ -948,20 +980,20 @@ public static class RegistryService
}
catch (UnauthorizedAccessException)
{
- ExecutionScope.LogWarning(
- "Access denied cleaning up registry key: {Path}",
- fullPath
- );
+ logger?.LogWarning("Access denied cleaning up registry key: {Path}", fullPath);
}
catch (IOException ex)
{
- ExecutionScope.LogError(ex, "I/O error cleaning up registry key: {Path}", fullPath);
+ logger?.LogError(ex, "I/O error cleaning up registry key: {Path}", fullPath);
}
catch (Exception ex)
{
- ExecutionScope.LogError(ex, "Failed to cleanup registry key: {Path}", fullPath);
+ logger?.LogError(ex, "Failed to cleanup registry key: {Path}", fullPath);
}
}
+ private static bool ValuesEqual(object? actual, object? expected, RegistryValueKind kind) =>
+ RegistryValues.Equal(actual, expected, kind);
+
#endregion Helpers
}
diff --git a/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs b/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs
index baa195b..b20c847 100644
--- a/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs
+++ b/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs
@@ -1,4 +1,5 @@
using System.Collections.ObjectModel;
+using Microsoft.Extensions.Logging;
using Microsoft.Win32.TaskScheduler;
using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Revert.Steps;
@@ -12,14 +13,8 @@ namespace optimizerDuck.Services.Optimization.Providers;
public static class ScheduledTaskService
{
- private static readonly AsyncLocal<string?> _lastError = new();
- private static readonly AsyncLocal<string?> _lastErrorDetail = new();
-
- internal static string? LastError => _lastError.Value;
- internal static string? LastErrorDetail => _lastErrorDetail.Value;
-
/// <summary>Checks whether a task at the given full path exists and is enabled.</summary>
- public static bool IsTaskEnabled(string fullPath)
+ public static bool IsTaskEnabled(string fullPath, ILogger? logger = null)
{
try
{
@@ -29,7 +24,7 @@ public static class ScheduledTaskService
}
catch (Exception ex)
{
- ExecutionScope.LogDebug(
+ logger?.LogDebug(
"Failed to check task enabled state {Path}: {Error}",
fullPath,
ex.Message
@@ -38,12 +33,13 @@ public static class ScheduledTaskService
}
}
- /// <summary>Disables a scheduled task.</summary>
+ /// <summary>Disables a scheduled task, recording the change into <paramref name="call"/>.</summary>
+ /// <param name="call">The explicit call context: change collector, logger and cancellation token.</param>
/// <param name="fullPath">The full path of the task to disable.</param>
- /// <returns><see langword="true" /> if the task was disabled; otherwise, <see langword="false" />.</returns>
- public static bool DisableTask(string fullPath)
+ /// <returns>The outcome of the disable request.</returns>
+ public static OpResult DisableTask(OpCall call, string fullPath)
{
- _lastError.Value = _lastErrorDetail.Value = null;
+ ArgumentNullException.ThrowIfNull(call);
var description = ServiceStrings.Format(
ServiceStrings.ScheduledTaskDescriptionDisable,
@@ -70,61 +66,56 @@ public static class ScheduledTaskService
OriginalEnabled = true,
};
- ExecutionScope.LogInfo("Disabled task {Path}", fullPath);
- ExecutionScope.Track(nameof(DisableTask), true);
- ExecutionScope.RecordStep(
- ServiceStrings.ScheduledTaskName,
- description,
- true,
- revertStep
- );
- return true;
+ call.Logger.LogInformation("Disabled task {Path}", fullPath);
+ call.Changes.Add(ServiceStrings.ScheduledTaskName, description, true, revertStep);
+ return OpResult.Success(revertStep);
}
- catch (UnauthorizedAccessException)
+ catch (UnauthorizedAccessException ex)
{
- _lastError.Value = ServiceStrings.CommonErrorAccessDenied;
- _lastErrorDetail.Value = ServiceStrings.Format(
+ var error = ServiceStrings.CommonErrorAccessDenied;
+ var errorDetail = ServiceStrings.Format(
ServiceStrings.ScheduledTaskErrorDetailAccessDeniedDisable,
fullPath
);
- ExecutionScope.LogError(null, "Access denied disabling task {Path}", fullPath);
- ExecutionScope.Track(nameof(DisableTask), false);
- ExecutionScope.RecordStep(
+ call.Logger.LogError(ex, "Access denied disabling task {Path}", fullPath);
+ call.Changes.Add(
ServiceStrings.ScheduledTaskName,
description,
false,
null,
- _lastError.Value,
- () => global::System.Threading.Tasks.Task.FromResult(DisableTask(fullPath)),
- _lastErrorDetail.Value
+ error,
+ errorDetail,
+ retryCall =>
+ global::System.Threading.Tasks.Task.FromResult(DisableTask(retryCall, fullPath))
);
- return false;
+ return OpResult.Fail(error, errorDetail);
}
catch (Exception ex)
{
- _lastError.Value = ex.Message;
- _lastErrorDetail.Value = ex.ToString();
- ExecutionScope.LogError(ex, "Failed to disable task {Path}", fullPath);
- ExecutionScope.Track(nameof(DisableTask), false);
- ExecutionScope.RecordStep(
+ var error = ex.Message;
+ var errorDetail = ex.ToString();
+ call.Logger.LogError(ex, "Failed to disable task {Path}", fullPath);
+ call.Changes.Add(
ServiceStrings.ScheduledTaskName,
description,
false,
null,
- _lastError.Value,
- () => global::System.Threading.Tasks.Task.FromResult(DisableTask(fullPath)),
- _lastErrorDetail.Value
+ error,
+ errorDetail,
+ retryCall =>
+ global::System.Threading.Tasks.Task.FromResult(DisableTask(retryCall, fullPath))
);
- return false;
+ return OpResult.Fail(error, errorDetail);
}
}
- /// <summary>Enables a scheduled task.</summary>
+ /// <summary>Enables a scheduled task, recording the change into <paramref name="call"/>.</summary>
+ /// <param name="call">The explicit call context: change collector, logger and cancellation token.</param>
/// <param name="fullPath">The full path of the task to enable.</param>
- /// <returns><see langword="true" /> if the task was enabled; otherwise, <see langword="false" />.</returns>
- public static bool EnableTask(string fullPath)
+ /// <returns>The outcome of the enable request.</returns>
+ public static OpResult EnableTask(OpCall call, string fullPath)
{
- _lastError.Value = _lastErrorDetail.Value = null;
+ ArgumentNullException.ThrowIfNull(call);
var description = ServiceStrings.Format(
ServiceStrings.ScheduledTaskDescriptionEnable,
@@ -151,64 +142,58 @@ public static class ScheduledTaskService
OriginalEnabled = false,
};
- ExecutionScope.LogInfo("Enabled task {Path}", fullPath);
- ExecutionScope.Track(nameof(EnableTask), true);
- ExecutionScope.RecordStep(
- ServiceStrings.ScheduledTaskName,
- description,
- true,
- revertStep
- );
- return true;
+ call.Logger.LogInformation("Enabled task {Path}", fullPath);
+ call.Changes.Add(ServiceStrings.ScheduledTaskName, description, true, revertStep);
+ return OpResult.Success(revertStep);
}
- catch (UnauthorizedAccessException)
+ catch (UnauthorizedAccessException ex)
{
- _lastError.Value = ServiceStrings.CommonErrorAccessDenied;
- _lastErrorDetail.Value = ServiceStrings.Format(
+ var error = ServiceStrings.CommonErrorAccessDenied;
+ var errorDetail = ServiceStrings.Format(
ServiceStrings.ScheduledTaskErrorDetailAccessDeniedEnable,
fullPath
);
- ExecutionScope.LogError(null, "Access denied enabling task {Path}", fullPath);
- ExecutionScope.Track(nameof(EnableTask), false);
- ExecutionScope.RecordStep(
+ call.Logger.LogError(ex, "Access denied enabling task {Path}", fullPath);
+ call.Changes.Add(
ServiceStrings.ScheduledTaskName,
description,
false,
null,
- _lastError.Value,
- () => global::System.Threading.Tasks.Task.FromResult(EnableTask(fullPath)),
- _lastErrorDetail.Value
+ error,
+ errorDetail,
+ retryCall =>
+ global::System.Threading.Tasks.Task.FromResult(EnableTask(retryCall, fullPath))
);
- return false;
+ return OpResult.Fail(error, errorDetail);
}
catch (Exception ex)
{
- _lastError.Value = ex.Message;
- _lastErrorDetail.Value = ex.ToString();
- ExecutionScope.LogError(ex, "Failed to enable task {Path}", fullPath);
- ExecutionScope.Track(nameof(EnableTask), false);
- ExecutionScope.RecordStep(
+ var error = ex.Message;
+ var errorDetail = ex.ToString();
+ call.Logger.LogError(ex, "Failed to enable task {Path}", fullPath);
+ call.Changes.Add(
ServiceStrings.ScheduledTaskName,
description,
false,
null,
- _lastError.Value,
- () => global::System.Threading.Tasks.Task.FromResult(EnableTask(fullPath)),
- _lastErrorDetail.Value
+ error,
+ errorDetail,
+ retryCall =>
+ global::System.Threading.Tasks.Task.FromResult(EnableTask(retryCall, fullPath))
);
- return false;
+ return OpResult.Fail(error, errorDetail);
}
}
/// <summary>Retrieves all scheduled tasks from the system, including icon extraction.</summary>
/// <returns>A list of all scheduled tasks.</returns>
- public static List<ScheduledTaskModel> GetAllTasks()
+ public static List<ScheduledTaskModel> GetAllTasks(ILogger? logger = null)
{
var results = new List<ScheduledTaskModel>();
try
{
using var ts = new TaskService();
- CollectTasks(ts.RootFolder, results);
+ CollectTasks(ts.RootFolder, results, logger);
// Extract icons from task commands
Parallel.ForEach(
@@ -223,7 +208,7 @@ public static class ScheduledTaskService
}
catch (Exception ex)
{
- ExecutionScope.LogError(ex, "Failed to enumerate scheduled tasks");
+ logger?.LogError(ex, "Failed to enumerate scheduled tasks");
}
return results;
@@ -231,20 +216,21 @@ public static class ScheduledTaskService
/// <summary>Returns startup-related tasks: those with a LogonTrigger or BootTrigger.</summary>
/// <returns>A list of startup-related tasks ordered by name.</returns>
- public static List<ScheduledTaskModel> GetStartupTasks()
+ public static List<ScheduledTaskModel> GetStartupTasks(ILogger? logger = null)
{
- return GetAllTasks()
+ return GetAllTasks(logger)
.Where(t => t.HasLogonTrigger || t.HasBootTrigger)
.OrderBy(t => t.Name)
.ToList();
}
/// <summary>Runs a scheduled task immediately.</summary>
+ /// <param name="call">Optional call context used for change recording and logging.</param>
/// <param name="fullPath">The full path of the task to run.</param>
- /// <returns><see langword="true" /> if the task was started; otherwise, <see langword="false" />.</returns>
- public static bool RunTask(string fullPath)
+ /// <returns>The outcome of the run request. No revert step: starting a task is not reversible.</returns>
+ public static OpResult RunTask(OpCall? call, string fullPath)
{
- _lastError.Value = _lastErrorDetail.Value = null;
+ var description = ServiceStrings.Format("Run scheduled task: {0}", fullPath);
try
{
@@ -255,24 +241,36 @@ public static class ScheduledTaskService
Loc.Instance["ScheduledTasks.Error.TaskNotFound", fullPath]
);
task.Run();
- ExecutionScope.LogInfo("Started task {Path}", fullPath);
- return true;
+ call?.Logger.LogInformation("Started task {Path}", fullPath);
+ call?.Changes.Add(ServiceStrings.ScheduledTaskName, description, true);
+ return OpResult.Success();
}
catch (Exception ex)
{
- _lastError.Value = ex.Message;
- _lastErrorDetail.Value = ex.ToString();
- ExecutionScope.LogError(ex, "Failed to run task {Path}", fullPath);
- return false;
+ var error = ex.Message;
+ var errorDetail = ex.ToString();
+ call?.Logger.LogError(ex, "Failed to run task {Path}", fullPath);
+ call?.Changes.Add(
+ ServiceStrings.ScheduledTaskName,
+ description,
+ false,
+ null,
+ error,
+ errorDetail,
+ retryCall =>
+ global::System.Threading.Tasks.Task.FromResult(RunTask(retryCall, fullPath))
+ );
+ return OpResult.Fail(error, errorDetail);
}
}
/// <summary>Stops a running scheduled task.</summary>
+ /// <param name="call">Optional call context used for change recording and logging.</param>
/// <param name="fullPath">The full path of the task to stop.</param>
- /// <returns><see langword="true" /> if the task was stopped; otherwise, <see langword="false" />.</returns>
- public static bool StopTask(string fullPath)
+ /// <returns>The outcome of the stop request. No revert step: stopping a task is not reversible.</returns>
+ public static OpResult StopTask(OpCall? call, string fullPath)
{
- _lastError.Value = _lastErrorDetail.Value = null;
+ var description = ServiceStrings.Format("Stop scheduled task: {0}", fullPath);
try
{
@@ -283,22 +281,34 @@ public static class ScheduledTaskService
Loc.Instance["ScheduledTasks.Error.TaskNotFound", fullPath]
);
task.Stop();
- ExecutionScope.LogInfo("Stopped task {Path}", fullPath);
- return true;
+ call?.Logger.LogInformation("Stopped task {Path}", fullPath);
+ call?.Changes.Add(ServiceStrings.ScheduledTaskName, description, true);
+ return OpResult.Success();
}
catch (Exception ex)
{
- _lastError.Value = ex.Message;
- _lastErrorDetail.Value = ex.ToString();
- ExecutionScope.LogError(ex, "Failed to stop task {Path}", fullPath);
- return false;
+ var error = ex.Message;
+ var errorDetail = ex.ToString();
+ call?.Logger.LogError(ex, "Failed to stop task {Path}", fullPath);
+ call?.Changes.Add(
+ ServiceStrings.ScheduledTaskName,
+ description,
+ false,
+ null,
+ error,
+ errorDetail,
+ retryCall =>
+ global::System.Threading.Tasks.Task.FromResult(StopTask(retryCall, fullPath))
+ );
+ return OpResult.Fail(error, errorDetail);
}
}
/// <summary>Gets the current state string of a task.</summary>
/// <param name="fullPath">The full path of the task.</param>
+ /// <param name="logger">Optional logger used only for logging.</param>
/// <returns>The task state string, or <see langword="null" /> if the task is not found or an error occurs.</returns>
- public static string? GetTaskState(string fullPath)
+ public static string? GetTaskState(string fullPath, ILogger? logger = null)
{
try
{
@@ -308,21 +318,21 @@ public static class ScheduledTaskService
}
catch (Exception ex)
{
- ExecutionScope.LogDebug(
- "Failed to get state for task {Path}: {Error}",
- fullPath,
- ex.Message
- );
+ logger?.LogDebug("Failed to get state for task {Path}: {Error}", fullPath, ex.Message);
return null;
}
}
- /// <summary>Deletes a scheduled task.</summary>
+ /// <summary>Deletes a scheduled task. This is destructive and cannot be undone.</summary>
+ /// <param name="call">Optional call context used for change recording and logging.</param>
/// <param name="fullPath">The full path of the task to delete.</param>
- /// <returns><see langword="true" /> if the task was deleted; otherwise, <see langword="false" />.</returns>
- public static bool DeleteTask(string fullPath)
+ /// <returns>The outcome of the delete request. No revert step.</returns>
+ public static OpResult DeleteTask(OpCall? call, string fullPath)
{
- _lastError.Value = _lastErrorDetail.Value = null;
+ var description = ServiceStrings.Format(
+ "Delete scheduled task: {0} (cannot be undone)",
+ fullPath
+ );
try
{
@@ -334,24 +344,45 @@ public static class ScheduledTaskService
);
var folderPath = task.Folder.Path;
ts.GetFolder(folderPath).DeleteTask(task.Name);
- ExecutionScope.LogInfo("Deleted task {Path}", fullPath);
- return true;
+ call?.Logger.LogInformation("Deleted task {Path}", fullPath);
+ call?.Changes.Add(ServiceStrings.ScheduledTaskName, description, true);
+ return OpResult.Success();
}
catch (Exception ex)
{
- _lastError.Value = ex.Message;
- _lastErrorDetail.Value = ex.ToString();
- ExecutionScope.LogError(ex, "Failed to delete task {Path}", fullPath);
- return false;
+ var error = ex.Message;
+ var errorDetail = ex.ToString();
+ call?.Logger.LogError(ex, "Failed to delete task {Path}", fullPath);
+ call?.Changes.Add(
+ ServiceStrings.ScheduledTaskName,
+ description,
+ false,
+ null,
+ error,
+ errorDetail,
+ retryCall =>
+ global::System.Threading.Tasks.Task.FromResult(DeleteTask(retryCall, fullPath))
+ );
+ return OpResult.Fail(error, errorDetail);
}
}
- /// <summary>[WIP] Registers a new scheduled task from a model definition.</summary>
+ /// <summary>Registers a new scheduled task from a model definition. Overwrites any existing task with the same name.</summary>
+ /// <param name="call">Optional call context used for change recording and logging.</param>
/// <param name="folderPath">The target folder path (e.g. <c>\MyApp</c>).</param>
/// <param name="model">The task definition model.</param>
- /// <exception cref="InvalidOperationException">Failed to create a registry subkey during registration.</exception>
- public static void RegisterTask(string folderPath, ScheduledTaskModel model)
+ /// <returns>The outcome of the registration. No revert step.</returns>
+ public static OpResult RegisterTask(OpCall? call, string folderPath, ScheduledTaskModel model)
{
+ var displayPath =
+ string.IsNullOrWhiteSpace(folderPath) || folderPath == "\\"
+ ? $"\\{model.Name}"
+ : $"{folderPath.TrimEnd('\\')}\\{model.Name}";
+ var description = ServiceStrings.Format(
+ "Register scheduled task: {0} (overwrites existing task, cannot be undone)",
+ displayPath
+ );
+
try
{
using var ts = new TaskService();
@@ -409,27 +440,47 @@ public static class ScheduledTaskService
}
folder.RegisterTaskDefinition(model.Name, td);
- ExecutionScope.LogInfo(
+ call?.Logger.LogInformation(
"Registered task {Name} in folder {Folder}",
model.Name,
folderPath
);
+ call?.Changes.Add(ServiceStrings.ScheduledTaskName, description, true);
+ return OpResult.Success();
}
catch (Exception ex)
{
- ExecutionScope.LogError(
+ var error = ex.Message;
+ var errorDetail = ex.ToString();
+ call?.Logger.LogError(
ex,
"Failed to register task {Name} in {Folder}",
model.Name,
folderPath
);
- throw;
+ call?.Changes.Add(
+ ServiceStrings.ScheduledTaskName,
+ description,
+ false,
+ null,
+ error,
+ errorDetail,
+ retryCall =>
+ global::System.Threading.Tasks.Task.FromResult(
+ RegisterTask(retryCall, folderPath, model)
+ )
+ );
+ return OpResult.Fail(error, errorDetail);
}
}
#region Helpers
- private static void CollectTasks(TaskFolder folder, List<ScheduledTaskModel> results)
+ private static void CollectTasks(
+ TaskFolder folder,
+ List<ScheduledTaskModel> results,
+ ILogger? logger
+ )
{
try
{
@@ -440,23 +491,15 @@ public static class ScheduledTaskService
}
catch (Exception ex)
{
- ExecutionScope.LogDebug(
- "Failed to map task {Name}: {Error}",
- task.Name,
- ex.Message
- );
+ logger?.LogDebug("Failed to map task {Name}: {Error}", task.Name, ex.Message);
}
foreach (var subFolder in folder.SubFolders)
- CollectTasks(subFolder, results);
+ CollectTasks(subFolder, results, logger);
}
catch (Exception ex)
{
- ExecutionScope.LogDebug(
- "Failed to enumerate folder {Path}: {Error}",
- folder.Path,
- ex.Message
- );
+ logger?.LogDebug("Failed to enumerate folder {Path}: {Error}", folder.Path, ex.Message);
}
}
diff --git a/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs b/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs
index b747fd1..ec048d9 100644
--- a/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs
+++ b/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs
@@ -1,6 +1,7 @@
using System.Diagnostics;
-using System.Text.RegularExpressions;
+using Microsoft.Extensions.Logging;
using optimizerDuck.Common.Extensions;
+using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.Revert.Steps;
@@ -13,31 +14,8 @@ public static class ServiceProcessService
private const int ErrorAccessDenied = 5;
- private static readonly AsyncLocal<string?> _lastError = new();
- private static readonly AsyncLocal<string?> _lastErrorDetail = new();
-
- /// <summary>
- /// Matches the START_TYPE line in <c>sc qc</c> output.
- /// Format: <c>FIELD_NAME : &lt;0-4&gt; DESCRIPTION</c>
- /// Uses <c>[0-4]</c> to cover every START_TYPE value
- /// (0=Boot, 1=System, 2=Auto, 3=Demand, 4=Disabled).
- /// START_TYPE is the first matching line: it appears before ERROR_CONTROL and
- /// TAG in the fixed output order. The field name is locale-dependent, so we
- /// match structurally only. Group 1 = numeric start value (0-4); Group 2 =
- /// description text (used for delayed-auto detection on value 2).
- /// </summary>
- private static readonly Regex _startTypeLineRegex = new(
- @"^\s*\S+\s*:\s*([0-4])\s(.+)$",
- RegexOptions.Compiled
- );
-
- private static readonly Regex _delayedRegex = new(
- @"\([^)]+\)",
- RegexOptions.Compiled | RegexOptions.IgnoreCase
- );
-
- internal static string? LastError => _lastError.Value;
- internal static string? LastErrorDetail => _lastErrorDetail.Value;
+ private const int DefaultScTimeoutMs = 30000;
+ private const int DefaultScQueryTimeoutMs = 15000;
/// <summary>
/// Parses the START_TYPE from raw <c>sc qc</c> stdout.
@@ -47,52 +25,34 @@ public static class ServiceProcessService
string stdout
)
{
- var lines = stdout.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries);
-
- foreach (var line in lines)
- {
- var match = _startTypeLineRegex.Match(line);
- if (!match.Success)
- continue;
-
- var startValue = int.Parse(match.Groups[1].Value);
- var valueText = match.Groups[2].Value;
- var isDelayed = _delayedRegex.IsMatch(valueText);
-
- var result = startValue switch
- {
- 2 => isDelayed
- ? ServiceStartupType.AutomaticDelayedStart
- : ServiceStartupType.Automatic,
- 3 => ServiceStartupType.Manual,
- 4 => ServiceStartupType.Disabled,
- _ => (ServiceStartupType?)null,
- };
- return (result, false);
- }
-
- return (null, true);
+ var (type, matched) = Windows.Services.ScStartupTypeParser.ParseWithMatch(stdout);
+ return (type, !matched);
}
/// <summary>Retrieves the current startup type of a Windows service by running <c>sc.exe qc</c>.</summary>
/// <param name="serviceName">The internal service name.</param>
+ /// <param name="logger">Optional logger used only for logging.</param>
/// <returns>
/// A tuple. <c>StartupType</c> is the type if parsed successfully.
/// <c>NotFound</c> is <see langword="true"/> when the service does not exist (exit code 1060),
/// <see langword="false"/> for other errors.
/// </returns>
public static async Task<(ServiceStartupType? StartupType, bool NotFound)> GetStartupTypeAsync(
- string serviceName
+ string serviceName,
+ ILogger? logger = null
)
{
try
{
- var (exitCode, stdout, stderr) = await RunScExeAsync($"qc \"{serviceName}\"", 15000);
+ var (exitCode, stdout, stderr) = await RunScExeAsync(
+ $"qc \"{serviceName}\"",
+ DefaultScQueryTimeoutMs
+ );
if (exitCode != 0)
{
var notFound = exitCode == ErrorServiceDoesNotExist;
- ExecutionScope.LogWarning(
+ logger?.LogWarning(
"[SERVICE][{Name}] sc.exe qc failed with exit code {ExitCode}: {Stderr}",
serviceName,
exitCode,
@@ -105,7 +65,7 @@ public static class ServiceProcessService
if (parseError)
{
- ExecutionScope.LogWarning(
+ logger?.LogWarning(
"[SERVICE][{Name}] Could not parse START_TYPE from sc.exe qc output:\n{Output}",
serviceName,
stdout
@@ -117,21 +77,18 @@ public static class ServiceProcessService
}
catch (Exception ex)
{
- ExecutionScope.LogError(
- ex,
- "Failed to get startup type for {ServiceName}",
- serviceName
- );
+ logger?.LogError(ex, "Failed to get startup type for {ServiceName}", serviceName);
return (null, false);
}
}
- /// <summary>Changes the startup type of a single Windows service via <c>sc.exe config</c>. Records a revert step if the original type differs.</summary>
+ /// <summary>Changes the startup type of a single Windows service via <c>sc.exe config</c>. Records the change into <paramref name="call"/>.</summary>
+ /// <param name="call">The explicit call context: change collector, logger and cancellation token.</param>
/// <param name="item">The service item with the target startup type.</param>
/// <returns>The outcome of the change request.</returns>
- public static async Task<ServiceChangeResult> ChangeServiceStartupTypeAsync(ServiceItem item)
+ public static async Task<OpResult> ChangeServiceStartupTypeAsync(OpCall call, ServiceItem item)
{
- _lastError.Value = _lastErrorDetail.Value = null;
+ ArgumentNullException.ThrowIfNull(call);
var description = ServiceStrings.Format(
ServiceStrings.ServiceDescriptionChange,
@@ -142,7 +99,7 @@ public static class ServiceProcessService
try
{
- var (originalStartupType, notFound) = await GetStartupTypeAsync(item.Name);
+ var (originalStartupType, notFound) = await GetStartupTypeAsync(item.Name, call.Logger);
if (notFound)
{
@@ -151,31 +108,30 @@ public static class ServiceProcessService
ServiceStrings.ServiceInfoSkippedNotFound,
item.Name
);
- ExecutionScope.LogInfo("[SERVICE][{Name}] not found, skipping", item.Name);
- ExecutionScope.Track(nameof(ChangeServiceStartupTypeAsync), true);
- ExecutionScope.RecordStep(ServiceStrings.ServiceName, skipDescription, true, null);
- return ServiceChangeResult.NotFound;
+ call.Logger.LogInformation("[SERVICE][{Name}] not found, skipping", item.Name);
+ call.Changes.Add(ServiceStrings.ServiceName, skipDescription, true);
+ return MapToOpResult(ServiceChangeResult.NotFound, null, null, null);
}
if (originalStartupType == null)
{
sw.Stop();
- ExecutionScope.LogInfo(
+ var queryError = $"Could not query startup type for service '{item.Name}'";
+ call.Logger.LogInformation(
"[SERVICE][{Name}][FAIL][D={Duration}] could not query startup type",
item.Name,
sw.Elapsed.FormatTime()
);
- ExecutionScope.Track(nameof(ChangeServiceStartupTypeAsync), false);
- ExecutionScope.RecordStep(
+ call.Changes.Add(
ServiceStrings.ServiceName,
description,
false,
null,
- _lastError.Value,
- () => RetryChangeServiceStartupTypeAsync(item),
- _lastErrorDetail.Value
+ queryError,
+ null,
+ retryCall => ChangeServiceStartupTypeAsync(retryCall, item)
);
- return ServiceChangeResult.Failed;
+ return MapToOpResult(ServiceChangeResult.Failed, null, queryError, null);
}
if (originalStartupType.Value == item.StartupType)
@@ -186,19 +142,13 @@ public static class ServiceProcessService
item.Name,
item.StartupType
);
- ExecutionScope.LogInfo(
+ call.Logger.LogInformation(
"[SERVICE][{Name}] already {StartupType}, skipping",
item.Name,
item.StartupType
);
- ExecutionScope.Track(nameof(ChangeServiceStartupTypeAsync), true);
- ExecutionScope.RecordStep(
- ServiceStrings.ServiceName,
- alreadyDescription,
- true,
- null
- );
- return ServiceChangeResult.AlreadyConfigured;
+ call.Changes.Add(ServiceStrings.ServiceName, alreadyDescription, true);
+ return MapToOpResult(ServiceChangeResult.AlreadyConfigured, null, null, null);
}
var scType = item.StartupType switch
@@ -212,15 +162,15 @@ public static class ServiceProcessService
var (exitCode, stdout, stderr) = await RunScExeAsync(
$"config \"{item.Name}\" start= {scType}",
- 30000
+ DefaultScTimeoutMs
);
var success = exitCode == 0;
sw.Stop();
+ string? errorDetail = null;
if (!success)
- _lastErrorDetail.Value =
- $"sc.exe exit code: {exitCode}\nstdout: {stdout}\nstderr: {stderr}";
+ errorDetail = $"sc.exe exit code: {exitCode}\nstdout: {stdout}\nstderr: {stderr}";
if (success)
{
@@ -232,91 +182,126 @@ public static class ServiceProcessService
OriginalStartupType = originalStartupType.Value,
};
- ExecutionScope.LogInfo(
+ call.Logger.LogInformation(
"[SERVICE][{Name}][OK][D={Duration}] startup -> {StartupType}",
item.Name,
sw.Elapsed.FormatTime(),
item.StartupType
);
- ExecutionScope.Track(nameof(ChangeServiceStartupTypeAsync), true);
- ExecutionScope.RecordStep(
- ServiceStrings.ServiceName,
- description,
- true,
- revertStep
- );
- return ServiceChangeResult.Success;
+ call.Changes.Add(ServiceStrings.ServiceName, description, true, revertStep);
+ return MapToOpResult(ServiceChangeResult.Success, revertStep, null, null);
}
if (exitCode == ErrorAccessDenied)
{
- _lastError.Value = ServiceStrings.Format(
+ var accessDeniedError = ServiceStrings.Format(
ServiceStrings.ServiceInfoSkippedAccessDenied,
item.Name
);
- ExecutionScope.LogInfo(
+ call.Logger.LogInformation(
"[SERVICE][{Name}][SKIP][D={Duration}] access denied, Windows protects this service",
item.Name,
sw.Elapsed.FormatTime()
);
- ExecutionScope.Track(nameof(ChangeServiceStartupTypeAsync), true);
- ExecutionScope.RecordStep(ServiceStrings.ServiceName, _lastError.Value, true, null);
- return ServiceChangeResult.AccessDenied;
+ call.Changes.Add(
+ ServiceStrings.ServiceName,
+ description,
+ false,
+ null,
+ accessDeniedError,
+ errorDetail
+ );
+ return MapToOpResult(
+ ServiceChangeResult.AccessDenied,
+ null,
+ accessDeniedError,
+ errorDetail
+ );
}
- _lastError.Value = ServiceStrings.ServiceErrorChangeStartupTypeFailed;
- ExecutionScope.LogInfo(
+ var error = $"{ServiceStrings.ServiceErrorChangeStartupTypeFailed} '{item.Name}'";
+ call.Logger.LogInformation(
"[SERVICE][{Name}][FAIL][D={Duration}] startup -> {StartupType}",
item.Name,
sw.Elapsed.FormatTime(),
item.StartupType
);
- ExecutionScope.Track(nameof(ChangeServiceStartupTypeAsync), false);
- ExecutionScope.RecordStep(
+ call.Changes.Add(
ServiceStrings.ServiceName,
description,
false,
null,
- _lastError.Value,
- () => RetryChangeServiceStartupTypeAsync(item),
- _lastErrorDetail.Value
+ error,
+ errorDetail,
+ retryCall => ChangeServiceStartupTypeAsync(retryCall, item)
);
- return ServiceChangeResult.Failed;
+ return MapToOpResult(ServiceChangeResult.Failed, null, error, errorDetail);
}
catch (Exception ex)
{
- _lastError.Value = ServiceStrings.Format(
+ var exceptionError = ServiceStrings.Format(
ServiceStrings.ServiceErrorExceptionOccurred,
item.Name,
ex.Message
);
- _lastErrorDetail.Value = ex.ToString();
+ var exceptionDetail = ex.ToString();
- ExecutionScope.LogError(
+ call.Logger.LogError(
ex,
"[SERVICE][{Name}][FAIL][EXCEPTION] startup -> {StartupType}",
item.Name,
item.StartupType
);
- ExecutionScope.Track(nameof(ChangeServiceStartupTypeAsync), false);
- ExecutionScope.RecordStep(
+ call.Changes.Add(
ServiceStrings.ServiceName,
description,
false,
null,
- _lastError.Value,
- () => RetryChangeServiceStartupTypeAsync(item),
- _lastErrorDetail.Value
+ exceptionError,
+ exceptionDetail,
+ retryCall => ChangeServiceStartupTypeAsync(retryCall, item)
);
- return ServiceChangeResult.Failed;
+ return MapToOpResult(ServiceChangeResult.Failed, null, exceptionError, exceptionDetail);
+ }
+ }
+
+ /// <summary>Changes the startup type for multiple services, serially.</summary>
+ /// <param name="call">The explicit call context; cancellation is honored between items.</param>
+ /// <param name="items">The service items to update.</param>
+ public static async Task ChangeServiceStartupTypeAsync(OpCall call, ServiceItem[] items)
+ {
+ ArgumentNullException.ThrowIfNull(call);
+
+ foreach (var item in items)
+ {
+ call.CancellationToken.ThrowIfCancellationRequested();
+ await ChangeServiceStartupTypeAsync(call, item);
}
}
- private static async Task<bool> RetryChangeServiceStartupTypeAsync(ServiceItem item)
+ /// <summary>
+ /// Maps the compat <see cref="ServiceChangeResult"/> outcome to an <see cref="OpResult"/>.
+ /// NotFound and AlreadyConfigured are informational successes; AccessDenied and
+ /// Failed carry an error naming the service.
+ /// </summary>
+ private static OpResult MapToOpResult(
+ ServiceChangeResult outcome,
+ IRevertStep? revert,
+ string? error,
+ string? errorDetail
+ )
{
- var result = await ChangeServiceStartupTypeAsync(item);
- return result != ServiceChangeResult.Failed;
+ return outcome switch
+ {
+ ServiceChangeResult.Success
+ or ServiceChangeResult.NotFound
+ or ServiceChangeResult.AlreadyConfigured => OpResult.Success(revert),
+ _ => OpResult.Fail(
+ error ?? ServiceStrings.ServiceErrorChangeStartupTypeFailed,
+ errorDetail
+ ),
+ };
}
private static async Task<(int ExitCode, string Stdout, string Stderr)> RunScExeAsync(
@@ -359,12 +344,4 @@ public static class ServiceProcessService
var stderr = await stderrTask;
return (process.ExitCode, stdout, stderr);
}
-
- /// <summary>Changes the startup type for multiple services.</summary>
- /// <param name="items">The service items to update.</param>
- public static async Task ChangeServiceStartupTypeAsync(params ServiceItem[] items)
- {
- foreach (var item in items)
- await ChangeServiceStartupTypeAsync(item);
- }
}
diff --git a/optimizerDuck/Services/Optimization/Providers/ServiceStrings.cs b/optimizerDuck/Services/Optimization/Providers/ServiceStrings.cs
index 3a3f596..2ed781a 100644
--- a/optimizerDuck/Services/Optimization/Providers/ServiceStrings.cs
+++ b/optimizerDuck/Services/Optimization/Providers/ServiceStrings.cs
@@ -32,6 +32,10 @@ public static class ServiceStrings
public const string ScheduledTaskName = "Scheduled Task";
public const string ScheduledTaskDescriptionEnable = "Enable scheduled task: {0}";
public const string ScheduledTaskDescriptionDisable = "Disable scheduled task: {0}";
+ public const string ScheduledTaskInfoSkippedNotFound =
+ "Scheduled task '{0}' not found (skipped)";
+ public const string ScheduledTaskInfoAlreadyConfigured =
+ "Scheduled task '{0}' is already {1} (skipped)";
public const string ScheduledTaskErrorDetailAccessDeniedEnable =
"Access denied enabling task {0}";
public const string ScheduledTaskErrorDetailAccessDeniedDisable =
@@ -41,6 +45,14 @@ public static class ServiceStrings
public const string ServiceDescriptionChange = "Change service '{0}' to {1} startup";
public const string ServiceErrorChangeStartupTypeFailed =
"Failed to change startup type for service";
+ public const string ServiceErrorChangeStartupTypeFailedTemplate =
+ "Failed to change service '{0}' to {1} startup. sc.exe exited with {2}: {3}";
+ public const string ServiceErrorQueryFailed = "Failed to query service '{0}'";
+
+ public const string RevertDataUnloadableDescription =
+ "Unloadable revert data (unknown type '{0}')";
+ public const string RevertDataUnknownType =
+ "Cannot revert step of unknown type '{0}'. The revert data was written by a different app version.";
public const string ServiceErrorExceptionOccurred = "Failed to change service '{0}': {1}";
public const string ServiceInfoSkippedNotFound = "Service '{0}' not found (skipped)";
public const string ServiceInfoAlreadyConfigured =
diff --git a/optimizerDuck/Services/Optimization/Providers/ShellMapping.cs b/optimizerDuck/Services/Optimization/Providers/ShellMapping.cs
new file mode 100644
index 0000000..35c3026
--- /dev/null
+++ b/optimizerDuck/Services/Optimization/Providers/ShellMapping.cs
@@ -0,0 +1,46 @@
+using optimizerDuck.Common.Extensions;
+using optimizerDuck.Domain.Optimizations.Models.Services;
+
+namespace optimizerDuck.Services.Optimization.Providers;
+
+/// <summary>
+/// Shared mapping between <see cref="ProcessResult"/> and <see cref="ShellResult"/>
+/// plus command-building helpers. Single source of truth for both legacy
+/// <c>ShellService</c> and the new <c>ShellRunner</c> capability.
+/// </summary>
+internal static class ShellMapping
+{
+ internal const string PowerShellArguments =
+ "-NonInteractive -NoLogo -NoProfile -ExecutionPolicy Bypass -EncodedCommand";
+
+ internal static string PrefixPowerShell(string command)
+ {
+ // prefix forces UTF-8 output and silences progress stream clutter in stderr
+ return "$ProgressPreference='SilentlyContinue'; "
+ + "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
+ + "$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8; "
+ + command;
+ }
+
+ internal static string BuildCmdArguments(string arguments, string command)
+ {
+ return arguments.Contains("chcp 65001")
+ ? // try best effort to ensure UTF-8 codepage for cmd, but better use PowerShell if possible
+ $"{arguments} {command}"
+ : $"{arguments} chcp 65001 > nul & {command}";
+ }
+
+ internal static string EncodePowerShellCommand(string command) =>
+ PrefixPowerShell(command).EncodeBase64();
+
+ internal static ShellResult Map(ProcessResult raw, string commandForUser) =>
+ new()
+ {
+ Command = commandForUser,
+ Stdout = raw.Stdout,
+ Stderr = raw.Stderr.ParseCliXml().Trim(),
+ // use -1 error code for timed out
+ ExitCode = raw.TimedOut ? -1 : raw.ExitCode,
+ Duration = raw.Duration,
+ };
+}
diff --git a/optimizerDuck/Services/Optimization/Providers/ShellService.cs b/optimizerDuck/Services/Optimization/Providers/ShellService.cs
index 4d78e8f..a725922 100644
--- a/optimizerDuck/Services/Optimization/Providers/ShellService.cs
+++ b/optimizerDuck/Services/Optimization/Providers/ShellService.cs
@@ -1,81 +1,24 @@
-using System.Diagnostics;
-using System.Text;
-using Microsoft.Extensions.Options;
+using Microsoft.Extensions.Logging;
using optimizerDuck.Common.Extensions;
-using optimizerDuck.Domain.Configuration;
+using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.Revert.Steps;
-using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.Configuration;
namespace optimizerDuck.Services.Optimization.Providers;
-/// <summary>Defines success criteria and error reporting for shell command execution.</summary>
-public sealed class ShellPolicy
+/// <summary>
+/// Thin instance facade over <see cref="ProcessRunner"/>: builds the
+/// cmd.exe / powershell.exe command lines, maps the raw
+/// <see cref="ProcessResult"/> to a <see cref="ShellResult"/> for policy
+/// evaluation, records a <see cref="Change"/> into the passed
+/// <see cref="OpCall"/>, and returns an <see cref="OpResult"/>.
+/// Holds no static state; the timeout lives in <see cref="ProcessRunner"/>
+/// and is read live from settings on every call.
+/// </summary>
+public sealed class ShellService(ProcessRunner _runner)
{
- /// <summary>Default policy: exit code 0 means success; error text is taken from stderr or the exit code.</summary>
- public static readonly ShellPolicy Default = new();
-
- /// <summary>Gets or sets a function that determines whether a shell result indicates success.</summary>
- public Func<ShellResult, bool> IsSuccess { get; init; } = r => r.ExitCode == 0;
-
- /// <summary>Gets or sets a function that produces an error message from a failed shell result.</summary>
- public Func<ShellResult, string?> ErrorFactory { get; init; } =
- r =>
- r.ExitCode == -1 // if timed out use Error.TimedOut
- ? Loc.Instance["Service.Shell.Error.TimedOut"]
- : string.IsNullOrWhiteSpace(r.Stderr) // else check stderr, if empty use exitcode, else use raw stderr
- ? Loc.Instance["Service.Shell.Error.ExitCode", r.ExitCode]
- : r.Stderr;
-
- /// <summary>Creates a policy with a custom success function and optional error factory.</summary>
- /// <param name="isSuccess">A function that determines whether a result is successful.</param>
- /// <param name="errorFactory">An optional function that produces an error message from a failed result. Defaults to the default error factory.</param>
- /// <returns>A new <see cref="ShellPolicy"/> instance.</returns>
- public static ShellPolicy From(
- Func<ShellResult, bool> isSuccess,
- Func<ShellResult, string?>? errorFactory = null
- )
- {
- return new ShellPolicy
- {
- IsSuccess = isSuccess,
- ErrorFactory = errorFactory ?? Default.ErrorFactory,
- };
- }
-
- /// <summary>Creates a policy that treats specific exit codes as success.</summary>
- /// <param name="okExitCodes">The exit codes considered successful.</param>
- /// <returns>A new <see cref="ShellPolicy"/> instance.</returns>
- public static ShellPolicy SuccessExitCodes(params int[] okExitCodes)
- {
- return From(r => okExitCodes.Contains(r.ExitCode));
- }
-
- /// <summary>Creates a policy that treats exit codes from 0 to <paramref name="maxOk"/> as success.</summary>
- /// <param name="maxOk">The maximum exit code considered successful (inclusive).</param>
- /// <returns>A new <see cref="ShellPolicy"/> instance.</returns>
- public static ShellPolicy SuccessExitCodeRange(int maxOk)
- {
- return From(r => r.ExitCode >= 0 && r.ExitCode <= maxOk);
- }
-}
-
-public static class ShellService
-{
- private const int DefaultShellTimeoutMs = 120000;
- private const int ProcessGraceDrainMs = 2000;
-
- private static IOptionsMonitor<AppSettings>? _options;
-
- /// <summary>Initializes the shell service with application settings.</summary>
- /// <param name="options">The application settings monitor.</param>
- public static void Init(IOptionsMonitor<AppSettings> options)
- {
- _options = options;
- }
-
private static (string commandForUser, string fullCommandForUser) SanitizeCommandForUser(
string fileName,
string arguments,
@@ -101,601 +44,242 @@ public static class ShellService
return (commandForUser, fullCommandForUser);
}
- private static ShellResult Run(
+ /// <summary>
+ /// Executes the process and maps the raw result to a <see cref="ShellResult"/>
+ /// without recording a <see cref="Change"/>. Shared by the optimization
+ /// path (<see cref="RunCoreAsync"/>) and the raw-run methods below.
+ /// </summary>
+ private async Task<(ShellResult Result, bool Cancelled)> BuildShellResultAsync(
string fileName,
string arguments,
string command,
string serviceName,
- ShellRevertStep? revertStep,
- ShellPolicy? policy = null
+ ShellPolicy policy,
+ ILogger? logger,
+ CancellationToken ct
)
{
- policy ??= ShellPolicy.Default;
-
var (_, fullCommandForUser) = SanitizeCommandForUser(fileName, arguments, command);
- var processArgs =
- fileName.Equals("cmd.exe", StringComparison.OrdinalIgnoreCase)
- && !arguments.Contains("chcp 65001") // try best effort to ensure UTF-8 codepage for cmd, but better use PowerShell if possible
- ? $"{arguments} chcp 65001 > nul & {command}"
- : $"{arguments} {command}";
+ // Best-effort UTF-8 codepage for cmd.exe (matches the pre-migration sync path);
+ // PowerShell already forces UTF-8 via its prefixed preamble.
+ var processArgs = fileName.Equals("cmd.exe", StringComparison.OrdinalIgnoreCase)
+ ? ShellMapping.BuildCmdArguments(arguments, command)
+ : $"{arguments} {command}";
+
+ var raw = await _runner.RunAsync(fileName, processArgs, ct).ConfigureAwait(false);
+
+ var result = ShellMapping.Map(raw, fullCommandForUser);
+
+ var success = !raw.Cancelled && policy.IsSuccess(result);
+ var status =
+ raw.Cancelled ? "CANCELLED"
+ : raw.TimedOut ? "TIMEOUT"
+ : success ? "OK"
+ : "FAIL";
+
+ logger?.LogInformation(
+ "[{Service}][{Status}][EC={ExitCode}][D={Duration}] {Command}",
+ serviceName,
+ status,
+ result.ExitCode,
+ result.Duration.FormatTime(),
+ fullCommandForUser
+ );
- var psi = new ProcessStartInfo
- {
- FileName = fileName,
- Arguments = processArgs,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- StandardOutputEncoding = Encoding.UTF8,
- StandardErrorEncoding = Encoding.UTF8,
- UseShellExecute = false,
- CreateNoWindow = true,
- };
+ logger?.LogTrace(
+ "[{Service}][STDOUT] {Stdout}",
+ serviceName,
+ string.IsNullOrWhiteSpace(result.Stdout) ? "N/A" : result.Stdout
+ );
+ logger?.LogTrace(
+ "[{Service}][STDERR] {Stderr}",
+ serviceName,
+ string.IsNullOrWhiteSpace(result.Stderr) ? "N/A" : result.Stderr
+ );
- try
- {
- using var process = new Process();
- process.StartInfo = psi;
-
- var stdoutBuilder = new StringBuilder();
- var stderrBuilder = new StringBuilder();
-
- process.OutputDataReceived += (_, e) =>
- {
- if (e.Data == null)
- return;
- stdoutBuilder.AppendLine(e.Data);
- };
-
- process.ErrorDataReceived += (_, e) =>
- {
- if (e.Data == null)
- return;
- stderrBuilder.AppendLine(e.Data);
- };
- var sw = Stopwatch.StartNew();
-
- process.Start();
- process.BeginOutputReadLine();
- process.BeginErrorReadLine();
-
- var exited = process.WaitForExit(
- _options?.CurrentValue.Optimize.ShellTimeoutMs ?? DefaultShellTimeoutMs
- );
- var timedOut = !exited;
-
- if (timedOut)
- {
- ExecutionScope.LogWarning(
- "Process timed out, attempting to kill: PID {ProcessId}",
- process.Id
- );
-
- try
- {
- process.Kill(entireProcessTree: true);
- ExecutionScope.LogInfo("Killed process: PID {ProcessId}", process.Id);
- }
- catch (Exception ex)
- {
- ExecutionScope.LogError(
- ex,
- "Failed to kill process for timeout (sync), PID: {ProcessId}",
- process.Id
- );
- }
-
- try
- {
- process.WaitForExit(ProcessGraceDrainMs);
- }
- catch (Exception ex)
- {
- ExecutionScope.LogError(
- ex,
- "Failed to wait for process exit after kill (sync), PID: {ProcessId}",
- process.Id
- );
- }
-
- // Force kill if still running after grace period
- if (!process.HasExited)
- {
- try
- {
- ExecutionScope.LogWarning(
- "Process still running after grace period, force killing: PID {ProcessId}",
- process.Id
- );
- process.Kill(entireProcessTree: true);
- if (!process.HasExited)
- {
- process.WaitForExit(5000); // Wait up to 5 seconds for force kill
- }
- }
- catch (Exception ex)
- {
- ExecutionScope.LogError(
- ex,
- "Failed to force kill process after timeout (sync), PID: {ProcessId}",
- process.Id
- );
- }
- }
- }
-
- sw.Stop();
- var duration = sw.Elapsed;
- var stdout = stdoutBuilder.ToString().Trim();
- var stderr = stderrBuilder.ToString().ParseCliXml().Trim();
-
- var result = new ShellResult
- {
- Command = fullCommandForUser,
- Stdout = stdout,
- Stderr = stderr,
- ExitCode = timedOut ? -1 : process.ExitCode, // use -1 error code for timed out
- Duration = duration,
- };
-
- var success = policy.IsSuccess(result);
-
- ExecutionScope.Track(serviceName, success);
-
- ExecutionScope.LogInfo(
- "[{Service}][{Status}][EC={ExitCode}][D={Duration}] {Command}",
- serviceName,
- timedOut ? "TIMEOUT"
- : success ? "OK"
- : "FAIL",
- result.ExitCode,
- duration.FormatTime(),
- fullCommandForUser
- );
-
- ExecutionScope.LogTrace(
- "[{Service}][STDOUT] {Stdout}",
- serviceName,
- string.IsNullOrWhiteSpace(stdout) ? "N/A" : stdout
- );
- ExecutionScope.LogTrace(
- "[{Service}][STDERR] {Stderr}",
- serviceName,
- string.IsNullOrWhiteSpace(stderr) ? "N/A" : stderr
- );
-
- var error = success ? null : policy.ErrorFactory(result);
-
- ExecutionScope.RecordStep(
- ServiceStrings.ShellName,
- fullCommandForUser,
- success,
- revertStep,
- error,
- success
- ? null
- : () =>
- // wrapping sync Run in Task.Run because retry expects a Task<bool>
- Task.Run(() =>
- policy.IsSuccess(
- Run(fileName, arguments, command, serviceName, revertStep, policy)
- )
- ),
- success ? null : GetShellErrorDetail(result)
- );
-
- return result;
- }
- catch (Exception ex)
- {
- ExecutionScope.LogError(
- ex,
- "[{Service}][FAIL][EXCEPTION] {Command}",
- serviceName,
- fullCommandForUser
- );
- ExecutionScope.Track(serviceName, false);
-
- var result = new ShellResult
- {
- Command = fullCommandForUser,
- Stdout = string.Empty,
- Stderr = ex.Message,
- ExitCode = -2,
- Duration = TimeSpan.Zero,
- };
-
- ExecutionScope.RecordStep(
- ServiceStrings.ShellName,
- fullCommandForUser,
- false,
- revertStep,
- ex.Message,
- () =>
- // wrapping sync Run in Task.Run because retry expects a Task<bool>
- Task.Run(() =>
- policy.IsSuccess(
- Run(fileName, arguments, command, serviceName, revertStep, policy)
- )
- ),
- ex.ToString()
- );
-
- return result;
- }
+ return (result, raw.Cancelled);
}
- private static async Task<ShellResult> RunAsync(
+ private async Task<OpResult> RunCoreAsync(
string fileName,
string arguments,
string command,
string serviceName,
- ShellRevertStep? revertStep,
- ShellPolicy? policy = null,
- CancellationToken ct = default
+ ShellType shellType,
+ IRevertStep? revertStep,
+ ShellPolicy? policy,
+ OpCall call,
+ CancellationToken ct
)
{
policy ??= ShellPolicy.Default;
- var (_, fullCommandForUser) = SanitizeCommandForUser(fileName, arguments, command);
-
- var psi = new ProcessStartInfo
- {
- FileName = fileName,
- Arguments = $"{arguments} {command}",
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- StandardOutputEncoding = Encoding.UTF8,
- StandardErrorEncoding = Encoding.UTF8,
- UseShellExecute = false,
- CreateNoWindow = true,
- };
-
- try
- {
- using var process = new Process();
- process.StartInfo = psi;
-
- var stdoutBuilder = new StringBuilder();
- var stderrBuilder = new StringBuilder();
-
- process.OutputDataReceived += (_, e) =>
- {
- if (e.Data != null)
- stdoutBuilder.AppendLine(e.Data);
- };
-
- process.ErrorDataReceived += (_, e) =>
- {
- if (e.Data != null)
- stderrBuilder.AppendLine(e.Data);
- };
+ using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
+ call.CancellationToken,
+ ct
+ );
- var sw = Stopwatch.StartNew();
+ var (result, cancelled) = await BuildShellResultAsync(
+ fileName,
+ arguments,
+ command,
+ serviceName,
+ policy,
+ call.Logger,
+ linkedCts.Token
+ )
+ .ConfigureAwait(false);
- process.Start();
- process.BeginOutputReadLine();
- process.BeginErrorReadLine();
+ var success = !cancelled && policy.IsSuccess(result);
- var timeout = _options?.CurrentValue.Optimize.ShellTimeoutMs ?? DefaultShellTimeoutMs;
+ var error =
+ success ? null
+ : cancelled ? Loc.Instance["Common.OperationCancelled"]
+ : policy.ErrorFactory(result);
+ var errorDetail = success ? null : GetShellErrorDetail(result);
- using var timeoutCts = new CancellationTokenSource(timeout);
- using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
- timeoutCts.Token,
- ct
- );
-
- try
- {
- await process.WaitForExitAsync(linkedCts.Token);
- }
- catch (OperationCanceledException)
- {
- // Process timed out, attempt cleanup
- ExecutionScope.LogWarning(
- "Process timed out, attempting to kill: PID {ProcessId}",
- process.Id
- );
-
- try
- {
- if (!process.HasExited)
- {
- process.Kill(entireProcessTree: true);
- ExecutionScope.LogInfo("Killed process: PID {ProcessId}", process.Id);
- }
- }
- catch (Exception ex)
- {
- ExecutionScope.LogError(
- ex,
- "Failed to kill process for timeout (async), PID: {ProcessId}",
- process.Id
- );
- }
- }
-
- sw.Stop();
-
- var timedOut = !process.HasExited;
- if (!process.HasExited)
- {
- // Process still running after kill attempt, wait for grace period
- try
- {
- ExecutionScope.LogWarning(
- "Process still running after kill, waiting for grace period: PID {ProcessId}",
- process.Id
- );
- process.WaitForExit(ProcessGraceDrainMs);
- }
- catch (Exception ex)
- {
- ExecutionScope.LogError(
- ex,
- "Failed to wait for process exit after kill (async), PID: {ProcessId}",
- process.Id
- );
- }
-
- // Force kill if still running after grace period
- if (!process.HasExited)
- {
- try
- {
- ExecutionScope.LogWarning(
- "Process still running after grace period, force killing: PID {ProcessId}",
- process.Id
- );
- process.Kill(entireProcessTree: true);
-
- // Wait up to 5 seconds for force kill
- if (!process.WaitForExit(5000))
- {
- ExecutionScope.LogWarning(
- "Process did not exit after force kill: PID {ProcessId}. User may need manual cleanup.",
- process.Id
- );
- }
- }
- catch (Exception ex)
- {
- ExecutionScope.LogError(
- ex,
- "Failed to force kill process after timeout (async), PID: {ProcessId}. User may need manual cleanup.",
- process.Id
- );
- }
- }
- }
-
- var stdout = stdoutBuilder.ToString().Trim();
- var stderr = stderrBuilder.ToString().ParseCliXml().Trim();
-
- var result = new ShellResult
- {
- Command = fullCommandForUser,
- Stdout = stdout,
- Stderr = stderr,
- ExitCode = timedOut ? -1 : process.ExitCode,
- Duration = sw.Elapsed,
- };
-
- var success = policy.IsSuccess(result);
-
- ExecutionScope.Track(serviceName, success);
-
- ExecutionScope.LogInfo(
- "[{Service}][{Status}][EC={ExitCode}][D={Duration}] {Command}",
- serviceName,
- timedOut ? "TIMEOUT"
- : success ? "OK"
- : "FAIL",
- result.ExitCode,
- sw.Elapsed.FormatTime(),
- fullCommandForUser
- );
-
- ExecutionScope.LogTrace(
- "[{Service}][STDOUT] {Stdout}",
- serviceName,
- string.IsNullOrWhiteSpace(stdout) ? "N/A" : stdout
- );
+ call.Changes.Add(
+ ServiceStrings.ShellName,
+ result.Command,
+ success,
+ revertStep,
+ error,
+ errorDetail,
+ success
+ ? null
+ : retryCall =>
+ RunCoreAsync(
+ fileName,
+ arguments,
+ command,
+ serviceName,
+ shellType,
+ revertStep,
+ policy,
+ retryCall,
+ CancellationToken.None
+ )
+ );
- ExecutionScope.LogTrace(
- "[{Service}][STDERR] {Stderr}",
- serviceName,
- string.IsNullOrWhiteSpace(stderr) ? "N/A" : stderr
- );
-
- var error = success ? null : policy.ErrorFactory(result);
-
- ExecutionScope.RecordStep(
- ServiceStrings.ShellName,
- fullCommandForUser,
- success,
- revertStep,
- error,
- success
- ? null
- : async () =>
- policy.IsSuccess(
- await RunAsync(
- fileName,
- arguments,
- command,
- serviceName,
- revertStep,
- policy,
- ct
- )
- ),
- success ? null : GetShellErrorDetail(result)
- );
-
- return result;
- }
- catch (Exception ex)
- {
- ExecutionScope.LogError(
- ex,
- "[{Service}][FAIL][EXCEPTION] {Command}",
- serviceName,
- fullCommandForUser
- );
- ExecutionScope.Track(serviceName, false);
-
- var result = new ShellResult
- {
- Command = fullCommandForUser,
- Stdout = string.Empty,
- Stderr = ex.Message,
- ExitCode = -2,
- Duration = TimeSpan.Zero,
- };
-
- ExecutionScope.RecordStep(
- ServiceStrings.ShellName,
- fullCommandForUser,
- false,
- revertStep,
- ex.Message,
- async () =>
- policy.IsSuccess(
- await RunAsync(
- fileName,
- arguments,
- command,
- serviceName,
- revertStep,
- policy,
- ct
- )
- ),
- ex.ToString()
- );
-
- return result;
- }
+ return success ? OpResult.Success(revertStep) : OpResult.Fail(error!, errorDetail);
}
- #region Command Prompt methods
+ #region Raw runs (no Change recording)
/// <summary>
- /// Runs a command in the Command Prompt (cmd.exe).
+ /// Runs a cmd.exe command without recording a <see cref="Change"/>.
+ /// For non-optimization callers (UI services, revert steps, shutdown paths)
+ /// that need the raw <see cref="ShellResult"/> (stdout/stderr/exit code).
/// </summary>
- /// <param name="command">The command to execute.</param>
- /// <param name="revertStep">The revert step to record.</param>
- /// <param name="policy">The policy to use for determining success.</param>
- /// <returns>The result of the command execution.</returns>
- public static ShellResult CMD(
+ public async Task<ShellResult> QueryCMDAsync(
string command,
- ShellRevertStep? revertStep = null,
- ShellPolicy? policy = null
+ ILogger? logger = null,
+ ShellPolicy? policy = null,
+ CancellationToken ct = default
)
{
- return Run("cmd.exe", "/c", command, nameof(CMD), revertStep, policy);
+ var (result, _) = await BuildShellResultAsync(
+ "cmd.exe",
+ "/c",
+ command,
+ nameof(QueryCMDAsync),
+ policy ?? ShellPolicy.Default,
+ logger,
+ ct
+ )
+ .ConfigureAwait(false);
+ return result;
}
/// <summary>
- /// Runs a command in the Command Prompt (cmd.exe) asynchronously.
+ /// Runs a PowerShell command without recording a <see cref="Change"/>.
+ /// For non-optimization callers (UI services, revert steps, queries)
+ /// that need the raw <see cref="ShellResult"/> (stdout/stderr/exit code).
/// </summary>
- /// <param name="command">The command to execute.</param>
- /// <param name="revertStep">The revert step to record.</param>
- /// <param name="policy">The policy to use for determining success.</param>
- /// <param name="ct">The cancellation token.</param>
- /// <returns>The result of the command execution.</returns>
- public static Task<ShellResult> CMDAsync(
+ public async Task<ShellResult> QueryPowerShellAsync(
string command,
- string revertCommand,
+ ILogger? logger = null,
ShellPolicy? policy = null,
CancellationToken ct = default
)
{
- return RunAsync(
- "cmd.exe",
- "/c",
- command,
- nameof(CMD),
- new ShellRevertStep { ShellType = ShellType.CMD, Command = revertCommand },
- policy,
- ct
- );
+ // -EncodedCommand avoids quoting/escaping issues
+ var (result, _) = await BuildShellResultAsync(
+ "powershell.exe",
+ ShellMapping.PowerShellArguments,
+ ShellMapping.EncodePowerShellCommand(command),
+ nameof(QueryPowerShellAsync),
+ policy ?? ShellPolicy.Default,
+ logger,
+ ct
+ )
+ .ConfigureAwait(false);
+ return result;
}
- /// <summary>Runs a command in cmd.exe asynchronously with an optional revert step.</summary>
- /// <param name="command">The command to execute.</param>
- /// <param name="revertStep">The revert step to record.</param>
- /// <param name="policy">The policy for determining success.</param>
- /// <param name="ct">The cancellation token.</param>
- /// <returns>The result of the command execution.</returns>
- public static Task<ShellResult> CMDAsync(
- string command,
- ShellRevertStep? revertStep = null,
- ShellPolicy? policy = null,
- CancellationToken ct = default
- )
- {
- return RunAsync("cmd.exe", "/c", command, nameof(CMD), revertStep, policy, ct);
- }
+ #endregion Raw runs (no Change recording)
+
+ #region Command Prompt methods
+
- /// <summary>Runs a command in cmd.exe asynchronously with a lazy revert command.</summary>
+ /// <summary>
+ /// Runs a command in the Command Prompt (cmd.exe) asynchronously.
+ /// </summary>
/// <param name="command">The command to execute.</param>
- /// <param name="revertCommand">A factory function that provides the revert command.</param>
- /// <param name="policy">The policy for determining success.</param>
- /// <param name="ct">The cancellation token.</param>
+ /// <param name="call">The explicit per-operation call context (change collector, logger, cancellation).</param>
+ /// <param name="revertStep">The revert step to record.</param>
+ /// <param name="policy">The policy to use for determining success.</param>
+ /// <param name="ct">An additional cancellation token, linked with <see cref="OpCall.CancellationToken"/>.</param>
/// <returns>The result of the command execution.</returns>
- public static Task<ShellResult> CMDAsync(
+ public Task<OpResult> CMDAsync(
string command,
- Func<string> revertCommand,
+ OpCall call,
+ IRevertStep? revertStep = null,
ShellPolicy? policy = null,
CancellationToken ct = default
)
{
- return RunAsync(
+ return RunCoreAsync(
"cmd.exe",
"/c",
command,
- nameof(CMD),
- new ShellRevertStep { ShellType = ShellType.CMD, Command = revertCommand() },
+ "CMD",
+ ShellType.CMD,
+ revertStep,
policy,
+ call,
ct
);
}
/// <summary>
- /// Runs a command in the Command Prompt (cmd.exe) with a specific revert command.
- /// </summary>
- /// <param name="command">The command to execute.</param>
- /// <param name="revertCommand">The command to execute for reverting.</param>
- /// <param name="policy">The policy to use for determining success.</param>
- /// <returns>The result of the command execution.</returns>
- public static ShellResult CMD(string command, string revertCommand, ShellPolicy? policy = null)
- {
- return CMD(
- command,
- new ShellRevertStep { ShellType = ShellType.CMD, Command = revertCommand },
- policy
- );
- }
-
- /// <summary>
- /// Runs a command in the Command Prompt (cmd.exe) with a specific revert command.
+ /// Runs a command in the Command Prompt (cmd.exe) asynchronously with a specific revert command.
/// </summary>
/// <param name="command">The command to execute.</param>
+ /// <param name="call">The explicit per-operation call context (change collector, logger, cancellation).</param>
/// <param name="revertCommand">The command to execute for reverting.</param>
/// <param name="policy">The policy to use for determining success.</param>
+ /// <param name="ct">An additional cancellation token, linked with <see cref="OpCall.CancellationToken"/>.</param>
/// <returns>The result of the command execution.</returns>
- public static ShellResult CMD(
+ public Task<OpResult> CMDAsync(
string command,
- Func<string> revertCommand,
- ShellPolicy? policy = null
+ OpCall call,
+ string revertCommand,
+ ShellPolicy? policy = null,
+ CancellationToken ct = default
)
{
- return CMD(
+ return RunCoreAsync(
+ "cmd.exe",
+ "/c",
command,
- new ShellRevertStep { ShellType = ShellType.CMD, Command = revertCommand() },
- policy
+ "CMD",
+ ShellType.CMD,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = revertCommand },
+ policy,
+ call,
+ ct
);
}
@@ -703,165 +287,65 @@ public static class ShellService
#region PowerShell methods
- /// <summary>
- /// Runs a command in PowerShell.
- /// </summary>
- /// <param name="command">The command to execute.</param>
- /// <param name="revertStep">The revert step to record.</param>
- /// <param name="policy">The policy to use for determining success.</param>
- /// <returns>The result of the command execution.</returns>
- public static ShellResult PowerShell(
- string command,
- ShellRevertStep? revertStep = null,
- ShellPolicy? policy = null
- )
- {
- // -EncodedCommand avoids quoting/escaping issues
- // prefix forces UTF-8 output and silences progress stream clutter in stderr
- command =
- "$ProgressPreference='SilentlyContinue'; "
- + "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
- + "$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8; "
- + command;
- return Run(
- "powershell.exe",
- "-NonInteractive -NoLogo -NoProfile -ExecutionPolicy Bypass -EncodedCommand",
- command.EncodeBase64(),
- nameof(PowerShell),
- revertStep,
- policy
- );
- }
/// <summary>
/// Runs a command in PowerShell asynchronously.
/// </summary>
/// <param name="command">The command to execute.</param>
+ /// <param name="call">The explicit per-operation call context (change collector, logger, cancellation).</param>
/// <param name="revertStep">The revert step to record.</param>
/// <param name="policy">The policy to use for determining success.</param>
- /// <param name="ct">The cancellation token.</param>
+ /// <param name="ct">An additional cancellation token, linked with <see cref="OpCall.CancellationToken"/>.</param>
/// <returns>The result of the command execution.</returns>
- public static Task<ShellResult> PowerShellAsync(
+ public Task<OpResult> PowerShellAsync(
string command,
- ShellRevertStep? revertStep = null,
+ OpCall call,
+ IRevertStep? revertStep = null,
ShellPolicy? policy = null,
CancellationToken ct = default
)
{
- command =
- "$ProgressPreference='SilentlyContinue'; "
- + "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
- + "$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8; "
- + command;
- return RunAsync(
+ return RunCoreAsync(
"powershell.exe",
- "-NonInteractive -NoLogo -NoProfile -ExecutionPolicy Bypass -EncodedCommand",
- command.EncodeBase64(),
- nameof(PowerShell),
+ ShellMapping.PowerShellArguments,
+ ShellMapping.EncodePowerShellCommand(command),
+ "PowerShell",
+ ShellType.PowerShell,
revertStep,
policy,
+ call,
ct
);
}
/// <summary>Runs a command in PowerShell asynchronously with a specific revert command.</summary>
/// <param name="command">The command to execute.</param>
+ /// <param name="call">The explicit per-operation call context (change collector, logger, cancellation).</param>
/// <param name="revertCommand">The command to execute for reverting.</param>
/// <param name="policy">The policy for determining success.</param>
- /// <param name="ct">The cancellation token.</param>
+ /// <param name="ct">An additional cancellation token, linked with <see cref="OpCall.CancellationToken"/>.</param>
/// <returns>The result of the command execution.</returns>
- public static Task<ShellResult> PowerShellAsync(
+ public Task<OpResult> PowerShellAsync(
string command,
+ OpCall call,
string revertCommand,
ShellPolicy? policy = null,
CancellationToken ct = default
)
{
- command =
- "$ProgressPreference='SilentlyContinue'; "
- + "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
- + "$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8; "
- + command;
- return RunAsync(
+ return RunCoreAsync(
"powershell.exe",
- "-NonInteractive -NoLogo -NoProfile -ExecutionPolicy Bypass -EncodedCommand",
- command.EncodeBase64(),
- nameof(PowerShell),
+ ShellMapping.PowerShellArguments,
+ ShellMapping.EncodePowerShellCommand(command),
+ "PowerShell",
+ ShellType.PowerShell,
new ShellRevertStep { ShellType = ShellType.PowerShell, Command = revertCommand },
policy,
+ call,
ct
);
}
- /// <summary>Runs a command in PowerShell asynchronously with a lazy revert command.</summary>
- /// <param name="command">The command to execute.</param>
- /// <param name="revertFunction">A factory function that provides the revert command.</param>
- /// <param name="policy">The policy for determining success.</param>
- /// <param name="ct">The cancellation token.</param>
- /// <returns>The result of the command execution.</returns>
- public static Task<ShellResult> PowerShellAsync(
- string command,
- Func<string> revertFunction,
- ShellPolicy? policy = null,
- CancellationToken ct = default
- )
- {
- command =
- "$ProgressPreference='SilentlyContinue'; "
- + "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
- + "$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8; "
- + command;
- return RunAsync(
- "powershell.exe",
- "-NonInteractive -NoLogo -NoProfile -ExecutionPolicy Bypass -EncodedCommand",
- command.EncodeBase64(),
- nameof(PowerShell),
- new ShellRevertStep { ShellType = ShellType.PowerShell, Command = revertFunction() },
- policy,
- ct
- );
- }
-
- /// <summary>
- /// Runs a command in PowerShell with a specific revert command.
- /// </summary>
- /// <param name="command">The command to execute.</param>
- /// <param name="revertCommand">The command to execute for reverting.</param>
- /// <param name="policy">The policy to use for determining success.</param>
- /// <returns>The result of the command execution.</returns>
- public static ShellResult PowerShell(
- string command,
- string revertCommand,
- ShellPolicy? policy = null
- )
- {
- return PowerShell(
- command,
- new ShellRevertStep { ShellType = ShellType.PowerShell, Command = revertCommand },
- policy
- );
- }
-
- /// <summary>
- /// Runs a command in PowerShell with a specific revert command.
- /// </summary>
- /// <param name="command">The command to execute.</param>
- /// <param name="revertCommand">The command to execute for reverting.</param>
- /// <param name="policy">The policy to use for determining success.</param>
- /// <returns>The result of the command execution.</returns>
- public static ShellResult PowerShell(
- string command,
- Func<string> revertCommand,
- ShellPolicy? policy = null
- )
- {
- return PowerShell(
- command,
- new ShellRevertStep { ShellType = ShellType.PowerShell, Command = revertCommand() },
- policy
- );
- }
-
private static string GetShellErrorDetail(ShellResult result)
{
var sections = new List<string>
diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.cs
index 52eedc7..9adbbca 100644
--- a/optimizerDuck/Services/Revert/RevertManager.cs
+++ b/optimizerDuck/Services/Revert/RevertManager.cs
@@ -1,6 +1,7 @@
using System.Collections.Concurrent;
using System.IO;
using System.Reflection;
+using System.Text;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
@@ -13,10 +14,11 @@ using optimizerDuck.Domain.Revert;
using optimizerDuck.Domain.UI;
using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.Configuration;
+using optimizerDuck.Services.Optimization.Providers;
namespace optimizerDuck.Services.Revert;
-public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _loggerFactory)
+public class RevertManager(ILogger<RevertManager> _logger, ShellService _shell, TimeProvider _time)
{
private const int SchemaVersion = 1;
private const int FileLockTimeoutSeconds = 30;
@@ -26,57 +28,92 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
private static readonly ConcurrentDictionary<Guid, SemaphoreSlim> _fileLocks = new();
- public async Task SaveRevertDataAsync(ExecutionScope scope)
+ /// <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; dropping either loses revert coverage.
+ /// Reverting extra entries is harmless (LIFO ends at the original backup).
+ /// </summary>
+ public async Task SaveRevertDataAsync(
+ ChangeSet changes,
+ Guid id,
+ string name,
+ CancellationToken cancellationToken = default
+ )
{
- var successfulSteps = scope
- .ExecutedSteps.Where(s => s.Success && s.RevertStep != null)
+ var incoming = changes
+ .Changes.Where(c => c.Ok && c.Revert != null)
+ .OrderBy(c => c.Index)
.ToList();
- if (successfulSteps.Count == 0)
+ if (incoming.Count == 0)
return;
- var maxIndex = successfulSteps.Max(s => s.Index);
- var steps = new RevertStepData?[maxIndex];
-
- foreach (var executedStep in successfulSteps)
+ var filePath = GetFilePath(id);
+ var lockObj = await AcquireFileLockAsync(id).ConfigureAwait(false);
+ try
{
- var arrayIndex = executedStep.Index - 1;
- steps[arrayIndex] = new RevertStepData
- {
- Index = executedStep.Index,
- Type = executedStep.RevertStep!.Type,
- Data = executedStep.RevertStep.ToData(),
- };
- }
-
- var optimizationId = scope.OptimizationId!.Value;
- await WriteJsonAsync(
- optimizationId,
- GetFilePath(optimizationId),
- new RevertData
+ cancellationToken.ThrowIfCancellationRequested();
+ var data =
+ await LoadAsync(filePath, _logger).ConfigureAwait(false)
+ ?? new RevertData
{
SchemaVersion = SchemaVersion,
- OptimizationId = optimizationId,
- OptimizationName = scope.OptimizationName ?? scope.OptimizationKey!,
- AppliedAt = DateTime.Now,
- Steps = steps,
- }
- )
- .ConfigureAwait(false);
+ OptimizationId = id,
+ OptimizationName = name,
+ AppliedAt = _time.GetLocalNow().DateTime,
+ Steps = Array.Empty<RevertStepData?>(),
+ };
+
+ data.OptimizationName = name;
+
+ // Every incoming change appends its own entry with a fresh index.
+ // No payload-based dedupe: two executions of the same command are
+ // two real executions, and dropping either loses revert coverage.
+ // Reverting extra entries is harmless (LIFO ends at the original
+ // backup); dropping one silently is not. Indexes are never reused
+ // so on-disk entries stay stable across saves.
+ var nextIndex =
+ data.Steps.Where(s => s != null).Select(s => s!.Index).DefaultIfEmpty(0).Max() + 1;
+ var merged = data.Steps.Where(s => s != null).Cast<RevertStepData>().ToList();
+
+ foreach (var change in incoming)
+ {
+ var step = new RevertStepData
+ {
+ Index = nextIndex++,
+ Type = change.Revert!.Type,
+ Data = change.Revert.ToData(),
+ };
+ merged.Add(step);
+ }
+
+ var maxIndex = merged.Count > 0 ? merged.Max(s => s.Index) : 0;
+ var steps = new RevertStepData?[maxIndex];
+ foreach (var step in merged)
+ steps[step.Index - 1] = step;
+ data.Steps = steps;
+
+ data.SchemaVersion = SchemaVersion;
+ // CancellationToken.None: a cancelled write would leave a half-written file;
+ // cancellation is honoured by the guard above instead.
+ await WriteJsonAtomicAsync(filePath, data, CancellationToken.None)
+ .ConfigureAwait(false);
+
+ _logger.LogInformation("Saved {Total} revert steps to {Path}", merged.Count, filePath);
+ }
+ finally
+ {
+ lockObj.Release();
+ }
}
+ /// <summary>Reverts the optimization using its persisted revert steps.</summary>
public async Task<RevertResult> RevertAsync(
IOptimization optimization,
- IProgress<ProcessingProgress>? progress = null
+ IProgress<ProcessingProgress>? progress = null,
+ CancellationToken cancellationToken = default
)
{
- var operationLogger = _loggerFactory.CreateLogger<RevertManager>();
- using var scope = ExecutionScope.BeginForLogging(
- optimization.Id,
- optimization.OptimizationKey,
- operationLogger
- );
-
var steps = await LoadStepsAsync(optimization.Id).ConfigureAwait(false);
if (steps.Count == 0)
return new RevertResult
@@ -85,13 +122,14 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
Message = Loc.Instance["Revert.Error.NoDataFound", optimization.Name],
};
- var failedSteps = new List<OperationStepResult>();
+ var failedSteps = new List<Change>();
var sortedSteps = steps.OrderByDescending(s => s.Index).ToList();
var total = sortedSteps.Count;
for (var i = 0; i < total; i++)
{
var (idx, step) = sortedSteps[i];
+ cancellationToken.ThrowIfCancellationRequested();
var remaining = total - i;
progress?.Report(
new ProcessingProgress
@@ -109,12 +147,12 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
try
{
- if (!await step.ExecuteAsync().ConfigureAwait(false))
+ if (!await step.ExecuteAsync(_shell, _logger).ConfigureAwait(false))
throw new Exception(Loc.Instance["Revert.Error.StepFailed"]);
}
catch (Exception ex)
{
- operationLogger.LogError(
+ _logger.LogError(
ex,
"Revert step {StepType} failed for {Optimization}",
step.Type,
@@ -123,15 +161,17 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
var stepEx = ex as StepExecutionException;
failedSteps.Add(
- new OperationStepResult
+ new Change
{
Index = idx,
Name = step.Type,
Description = step.Description,
- Success = false,
+ Ok = false,
Error = stepEx?.Message ?? ex.Message,
ErrorDetail = stepEx?.ErrorDetail,
- RetryAction = () => step.ExecuteAsync(),
+ Retry = async _ => new OpResult(
+ await step.ExecuteAsync(_shell, _logger).ConfigureAwait(false)
+ ),
}
);
}
@@ -143,19 +183,23 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
}
else if (failedSteps.Count < total)
{
+ // Partial revert: prune every succeeded step with a single
+ // load-modify-write so concurrent readers never observe a
+ // half-pruned file.
var failedIndexes = failedSteps.Select(s => s.Index).ToHashSet();
- foreach (var (idx, _) in sortedSteps)
- {
- if (!failedIndexes.Contains(idx))
- {
- await RemoveRevertStepAtIndexAsync(
- optimization.Id,
- optimization.OptimizationKey,
- idx
- )
- .ConfigureAwait(false);
- }
- }
+ var succeededIndexes = sortedSteps
+ .Select(s => s.Index)
+ .Where(idx => !failedIndexes.Contains(idx))
+ .ToList();
+ // CancellationToken.None: the prune must run to completion, otherwise the
+ // file would list steps that already reverted successfully.
+ await RemoveRevertStepsAtIndexesAsync(
+ optimization.Id,
+ optimization.OptimizationKey,
+ succeededIndexes,
+ CancellationToken.None
+ )
+ .ConfigureAwait(false);
}
return new RevertResult
@@ -176,20 +220,26 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
};
}
- public async Task UpsertRevertStepAtIndexAsync(
+ /// <summary>
+ /// Appends a recovered revert step (e.g. after a successful retry) as
+ /// a new entry. Never overwrites: with compact indexes the original
+ /// sequence number no longer addresses an empty slot, so writing into
+ /// it would destroy an unrelated entry. Revert runs LIFO, so the
+ /// newest backup is undone first and the original backup still
+ /// restores the true original state.
+ /// </summary>
+ public async Task AppendRevertStepAsync(
Guid id,
string name,
- int stepIndex,
- IRevertStep step
+ IRevertStep step,
+ CancellationToken cancellationToken = default
)
{
- if (stepIndex <= 0)
- throw new ArgumentException("Step index must be greater than 0", nameof(stepIndex));
-
var filePath = GetFilePath(id);
var lockObj = await AcquireFileLockAsync(id).ConfigureAwait(false);
try
{
+ cancellationToken.ThrowIfCancellationRequested();
var data =
await LoadAsync(filePath, _logger).ConfigureAwait(false)
?? new RevertData
@@ -197,32 +247,37 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
SchemaVersion = SchemaVersion,
OptimizationId = id,
OptimizationName = name,
+ AppliedAt = _time.GetLocalNow().DateTime,
Steps = Array.Empty<RevertStepData?>(),
};
- if (data.Steps.Length < stepIndex)
- {
- var newSteps = new RevertStepData?[stepIndex];
- Array.Copy(data.Steps, newSteps, data.Steps.Length);
- data.Steps = newSteps;
- }
+ data.OptimizationName = name;
+ var nextIndex =
+ data.Steps.Where(s => s != null).Select(s => s!.Index).DefaultIfEmpty(0).Max() + 1;
+ var merged = data.Steps.Where(s => s != null).Cast<RevertStepData>().ToList();
+ merged.Add(
+ new RevertStepData
+ {
+ Index = nextIndex,
+ Type = step.Type,
+ Data = step.ToData(),
+ }
+ );
- data.Steps[stepIndex - 1] = new RevertStepData
- {
- Index = stepIndex,
- Type = step.Type,
- Data = step.ToData(),
- };
+ var maxIndex = merged.Max(s => s.Index);
+ var steps = new RevertStepData?[maxIndex];
+ foreach (var entry in merged)
+ steps[entry.Index - 1] = entry;
+ data.Steps = steps;
data.SchemaVersion = SchemaVersion;
- await WriteJsonAtomicAsync(filePath, data).ConfigureAwait(false);
+ await WriteJsonAtomicAsync(filePath, data, cancellationToken).ConfigureAwait(false);
- var totalSteps = data.Steps.Count(s => s != null);
_logger.LogInformation(
- "Upserted revert step at index {Index} for {Id} (total: {Total} steps)",
- stepIndex,
+ "Appended revert step at index {Index} for {Id} (total: {Total} steps)",
+ nextIndex,
id,
- totalSteps
+ merged.Count
);
}
finally
@@ -235,18 +290,37 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
{
if (stepIndex <= 0)
return;
+ await RemoveRevertStepsAtIndexesAsync(id, name, [stepIndex]).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Prunes several steps with a single load-modify-write so a crash
+ /// can never leave a half-pruned file behind.
+ /// </summary>
+ public async Task RemoveRevertStepsAtIndexesAsync(
+ Guid id,
+ string? name,
+ IReadOnlyCollection<int> stepIndexes,
+ CancellationToken cancellationToken = default
+ )
+ {
+ var targets = stepIndexes.Where(i => i > 0).ToHashSet();
+ if (targets.Count == 0)
+ return;
var filePath = GetFilePath(id);
var lockObj = await AcquireFileLockAsync(id).ConfigureAwait(false);
try
{
+ cancellationToken.ThrowIfCancellationRequested();
var data = await LoadAsync(filePath, _logger).ConfigureAwait(false);
if (data == null || data.Steps.Length == 0)
return;
- if (stepIndex <= data.Steps.Length)
+ foreach (var index in targets)
{
- data.Steps[stepIndex - 1] = null;
+ if (index <= data.Steps.Length)
+ data.Steps[index - 1] = null;
}
if (data.Steps.All(s => s == null))
@@ -256,12 +330,12 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
}
data.SchemaVersion = SchemaVersion;
- await WriteJsonAtomicAsync(filePath, data).ConfigureAwait(false);
+ await WriteJsonAtomicAsync(filePath, data, cancellationToken).ConfigureAwait(false);
var remainingSteps = data.Steps.Count(s => s != null);
_logger.LogInformation(
- "Removed revert step at index {Index} for {Id} (remaining: {Remaining} steps)",
- stepIndex,
+ "Removed {Count} revert steps for {Id} (remaining: {Remaining} steps)",
+ targets.Count,
id,
remainingSteps
);
@@ -300,12 +374,9 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
}
}
- var semaphores = _fileLocks.Values.ToList();
- _fileLocks.Clear();
- foreach (var sem in semaphores)
- {
- sem.Dispose();
- }
+ // NOTE: file locks are intentionally left alone. Disposing a
+ // SemaphoreSlim while another thread holds or waits on it throws
+ // ObjectDisposedException; the entries are cheap and safely reused.
}
private static string GetFilePath(Guid id)
@@ -430,38 +501,40 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
public void RemoveRevertData(Guid id, string? name = null)
{
Remove(id, name);
- if (_fileLocks.TryRemove(id, out var sem))
- {
- sem.Dispose();
- }
+ // Lock entry intentionally kept: disposing a SemaphoreSlim that a
+ // concurrent operation holds or waits on throws. Entries are reused.
}
- private async Task WriteJsonAsync(Guid optimizationId, string path, RevertData data)
- {
- data.SchemaVersion = SchemaVersion;
- var lockObj = await AcquireFileLockAsync(optimizationId).ConfigureAwait(false);
- try
- {
- await WriteJsonAtomicAsync(path, data).ConfigureAwait(false);
- var totalOperations = data.Steps.Count(s => s != null);
- _logger.LogInformation("Saved {Total} operations to {Path}", totalOperations, path);
- }
- finally
- {
- lockObj.Release();
- }
- }
-
- private static async Task WriteJsonAtomicAsync(string path, RevertData data)
+ private static async Task WriteJsonAtomicAsync(
+ string path,
+ RevertData data,
+ CancellationToken cancellationToken = default
+ )
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var json = JsonConvert.SerializeObject(data, Formatting.Indented);
var tempPath = path + ".tmp";
- await File.WriteAllTextAsync(tempPath, json).ConfigureAwait(false);
+ await using (
+ var stream = new FileStream(
+ tempPath,
+ FileMode.Create,
+ FileAccess.Write,
+ FileShare.None,
+ 4096,
+ FileOptions.WriteThrough | FileOptions.Asynchronous
+ )
+ )
+ await using (var writer = new StreamWriter(stream, Encoding.UTF8))
+ {
+ await writer.WriteAsync(json).ConfigureAwait(false);
+ await writer.FlushAsync(cancellationToken).ConfigureAwait(false);
+ stream.Flush(flushToDisk: true);
+ }
try
{
+ cancellationToken.ThrowIfCancellationRequested();
if (File.Exists(path))
File.Replace(tempPath, path, destinationBackupFileName: null);
else
@@ -484,6 +557,28 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
}
}
+ /// <summary>
+ /// Deletes stale <c>.tmp</c> files left by crashes between temp-write
+ /// and replace. Called once at startup; never touches live <c>.json</c> files.
+ /// </summary>
+ public static void RemoveOrphanedTempFiles(ILogger? logger = null)
+ {
+ if (!Directory.Exists(Shared.RevertDirectory))
+ return;
+ foreach (var tmp in Directory.GetFiles(Shared.RevertDirectory, "*.tmp"))
+ {
+ try
+ {
+ File.Delete(tmp);
+ logger?.LogInformation("Removed orphaned revert temp file {Path}", tmp);
+ }
+ catch (Exception ex)
+ {
+ logger?.LogWarning(ex, "Failed to remove orphaned temp file {Path}", tmp);
+ }
+ }
+ }
+
private static async Task<SemaphoreSlim> AcquireFileLockAsync(Guid id)
{
var lockObj = _fileLocks.GetOrAdd(id, _ => new SemaphoreSlim(1, 1));
@@ -537,11 +632,15 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
}
else
{
+ // Never silently drop: an unknown type becomes a step that
+ // fails loudly at revert time, preserving the index layout
+ // and telling the user exactly which data is unloadable.
_logger.LogWarning(
- "Skipped unknown revert step type '{Type}' for optimization {Id}",
+ "Unknown revert step type '{Type}' for optimization {Id}",
stepData.Type,
id
);
+ result.Add((stepData.Index, new CorruptedStep(stepData.Type, stepData.Data)));
}
}
@@ -578,12 +677,20 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
var dict = new Dictionary<string, Func<JObject, IRevertStep>>();
foreach (var type in ReflectionHelper.FindImplementationsInLoadedAssemblies<IRevertStep>())
{
+ if (type.IsAbstract || type.IsInterface || type == typeof(CorruptedStep))
+ continue;
+
+ if (type.GetConstructor(Type.EmptyTypes) == null)
+ continue;
+
+ var method = type.GetMethod("FromData", BindingFlags.Static | BindingFlags.Public);
+ if (method == null)
+ continue;
+
try
{
var instance = (IRevertStep)Activator.CreateInstance(type)!;
- var method = type.GetMethod("FromData", BindingFlags.Static | BindingFlags.Public);
- if (method != null)
- dict[instance.Type] = data => (IRevertStep)method.Invoke(null, [data])!;
+ dict[instance.Type] = data => (IRevertStep)method.Invoke(null, [data])!;
}
catch (Exception ex)
{
@@ -611,4 +718,37 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
_logger.LogWarning("Unknown revert step type: {Type}", type);
return null;
}
+
+ /// <summary>
+ /// Placeholder for persisted data whose step type is not registered
+ /// (downgrade, removed plugin). Fails loudly at revert time instead
+ /// of vanishing silently, and round-trips the raw payload so a
+ /// future version can still read it.
+ /// </summary>
+ private sealed class CorruptedStep(string rawType, JObject rawData) : IRevertStep
+ {
+ public string Type => rawType;
+
+ public string Description =>
+ Services.Optimization.Providers.ServiceStrings.Format(
+ Services.Optimization.Providers.ServiceStrings.RevertDataUnloadableDescription,
+ rawType
+ );
+
+ public Task<bool> ExecuteAsync(ShellService _, ILogger logger)
+ {
+ throw new StepExecutionException(
+ Services.Optimization.Providers.ServiceStrings.Format(
+ Services.Optimization.Providers.ServiceStrings.RevertDataUnknownType,
+ rawType
+ ),
+ null
+ );
+ }
+
+ public JObject ToData()
+ {
+ return rawData;
+ }
+ }
}
diff --git a/optimizerDuck/Services/UI/BloatwareService.cs b/optimizerDuck/Services/UI/BloatwareService.cs
index 8e49c0b..b73d956 100644
--- a/optimizerDuck/Services/UI/BloatwareService.cs
+++ b/optimizerDuck/Services/UI/BloatwareService.cs
@@ -8,7 +8,6 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Configuration;
-using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Bloatware;
using optimizerDuck.Services.Optimization.Providers;
using AppXPackage = optimizerDuck.Domain.Optimizations.Models.Bloatware.AppXPackage;
@@ -18,7 +17,8 @@ namespace optimizerDuck.Services.UI;
public class BloatwareService(
ILogger<BloatwareService> logger,
- IOptionsMonitor<AppSettings> appOptionsMonitor
+ IOptionsMonitor<AppSettings> appOptionsMonitor,
+ ShellService shellService
)
{
private static readonly ConcurrentDictionary<string, string?> LogoCache = new(
@@ -45,8 +45,8 @@ public class BloatwareService(
var safePattern = string.Join("|", Shared.SafeApps.Select(Regex.Escape));
var cautionPattern = string.Join("|", Shared.CautionApps.Select(Regex.Escape));
- var result = await ShellService
- .PowerShellAsync(
+ var result = await shellService
+ .QueryPowerShellAsync(
$$"""
$safeRegex = '{{safePattern}}'
$cautionRegex = '{{cautionPattern}}'
@@ -83,15 +83,9 @@ public class BloatwareService(
return [];
}
- var options = new JsonSerializerOptions
- {
- PropertyNameCaseInsensitive = true,
- Converters = { new JsonStringEnumConverter() },
- };
-
- var apps = JsonSerializer.Deserialize<List<AppXPackage>>(result.Stdout, options);
+ var apps = ParsePackages(result.Stdout);
- if (apps == null || apps.Count == 0)
+ if (apps.Count == 0)
{
logger.LogInformation("No removable AppX packages found");
return [];
@@ -142,6 +136,28 @@ public class BloatwareService(
}
}
+ /// <summary>
+ /// Parses the <c>ConvertTo-Json</c> output of the AppX query. PowerShell emits a
+ /// bare object for a single package and an array for several, so both shapes are
+ /// accepted; deserialising only as a list silently yielded an empty result for the
+ /// single-package case.
+ /// </summary>
+ internal static List<AppXPackage> ParsePackages(string stdout)
+ {
+ var json = stdout.TrimStart();
+ var options = new JsonSerializerOptions
+ {
+ PropertyNameCaseInsensitive = true,
+ Converters = { new JsonStringEnumConverter() },
+ };
+
+ if (json.StartsWith('['))
+ return JsonSerializer.Deserialize<List<AppXPackage>>(json, options) ?? [];
+
+ var single = JsonSerializer.Deserialize<AppXPackage>(json, options);
+ return single is null ? [] : [single];
+ }
+
// Validates an AppX package name/identifier to prevent PowerShell injection.
// AppX names follow: Publisher.PackageName (alphanumeric, dots, dashes)
// PackageFullName follows: Name_Version_Architecture__ResourceId
@@ -181,10 +197,8 @@ public class BloatwareService(
/// <summary>
/// Removes an AppX package from the system.
/// </summary>
- /// <param name="appXPackage">The package to remove.</param>
public async Task RemoveAppXPackage(AppXPackage appXPackage)
{
- using var scope = ExecutionScope.BeginForLogging(logger);
try
{
if (string.IsNullOrWhiteSpace(appXPackage.PackageFullName))
@@ -267,7 +281,9 @@ public class BloatwareService(
Write-Output "Skipping provisioned package removal (disabled by user)"
""";
- var result = await ShellService.PowerShellAsync(script).ConfigureAwait(false);
+ var result = await shellService
+ .QueryPowerShellAsync(script, logger)
+ .ConfigureAwait(false);
if (!string.IsNullOrWhiteSpace(result.Stderr))
logger.LogWarning("Remove AppX stderr: {Error}", result.Stderr);
diff --git a/optimizerDuck/Services/UI/DiskCleanupService.cs b/optimizerDuck/Services/UI/DiskCleanupService.cs
index 6f03868..93d5861 100644
--- a/optimizerDuck/Services/UI/DiskCleanupService.cs
+++ b/optimizerDuck/Services/UI/DiskCleanupService.cs
@@ -8,7 +8,7 @@ using CleanupItem = optimizerDuck.Domain.Optimizations.Models.Cleanup.CleanupIte
namespace optimizerDuck.Services.UI;
-public class DiskCleanupService(ILogger<DiskCleanupService> logger)
+public class DiskCleanupService(ILogger<DiskCleanupService> logger, ShellService shellService)
{
private static readonly string DotNetTempPath =
Path.GetFullPath(Path.Combine(Path.GetTempPath(), ".net"))
@@ -119,7 +119,7 @@ public class DiskCleanupService(ILogger<DiskCleanupService> logger)
+ " Write-Output \"$sum|$count\" "
+ "} else { Write-Output '0|0' }";
- var result = await ShellService.PowerShellAsync(script);
+ var result = await shellService.QueryPowerShellAsync(script, logger);
var parts = result.Stdout.Trim().Split('|');
if (
parts.Length == 2
@@ -183,13 +183,27 @@ public class DiskCleanupService(ILogger<DiskCleanupService> logger)
if (item.IsCommand)
{
var sizeBefore = item.SizeBytes;
- await ShellService.PowerShellAsync(item.Path);
- freedBytes = sizeBefore;
- logger.LogInformation(
- "Cleaned {ItemId} via command, freed ~{Size}",
- item.Id,
- CleanupItem.FormatBytes(freedBytes)
- );
+ var result = await shellService.QueryPowerShellAsync(item.Path, logger);
+ if (result.ExitCode == 0)
+ {
+ freedBytes = sizeBefore;
+ logger.LogInformation(
+ "Cleaned {ItemId} via command, freed ~{Size}",
+ item.Id,
+ CleanupItem.FormatBytes(freedBytes)
+ );
+ }
+ else
+ {
+ // Never report freed space for a command that failed; only the exit
+ // code distinguishes "cleaned" from "ran but did nothing".
+ logger.LogError(
+ "Clean command for {ItemId} failed with exit code {ExitCode}: {Error}",
+ item.Id,
+ result.ExitCode,
+ result.Stderr
+ );
+ }
}
else
{
diff --git a/optimizerDuck/Services/UI/StartupManagerService.cs b/optimizerDuck/Services/UI/StartupManagerService.cs
index e9f1722..3c4c09b 100644
--- a/optimizerDuck/Services/UI/StartupManagerService.cs
+++ b/optimizerDuck/Services/UI/StartupManagerService.cs
@@ -9,6 +9,7 @@ using System.Windows.Media.Imaging;
using System.Xml.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.Win32;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.StartupManager;
using optimizerDuck.Services.Optimization.Providers;
using Windows.ApplicationModel;
@@ -20,6 +21,13 @@ 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
@@ -653,12 +661,12 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)
var fullPath = task.TaskPath.TrimEnd('\\') + "\\" + task.TaskName;
if (enable)
{
- ScheduledTaskService.EnableTask(fullPath);
+ ScheduledTaskService.EnableTask(UiCall(), fullPath);
logger.LogInformation("Enabled task {Name} ({Path})", task.TaskName, fullPath);
}
else
{
- ScheduledTaskService.DisableTask(fullPath);
+ ScheduledTaskService.DisableTask(UiCall(), fullPath);
logger.LogInformation("Disabled task {Name} ({Path})", task.TaskName, fullPath);
}
}
diff --git a/optimizerDuck/UI/Controls/TaskStateBadge.xaml b/optimizerDuck/UI/Controls/TaskStateBadge.xaml
index 818a3df..b9faba5 100644
--- a/optimizerDuck/UI/Controls/TaskStateBadge.xaml
+++ b/optimizerDuck/UI/Controls/TaskStateBadge.xaml
@@ -25,13 +25,8 @@
<DataTrigger Binding="{Binding IsEnabledState, ElementName=TaskStateRoot}" Value="False">
<Setter Property="Background" Value="{DynamicResource SystemFillColorCriticalBrush}" />
</DataTrigger>
- <DataTrigger Binding="{Binding State, ElementName=TaskStateRoot}" Value="Ready">
- <Setter Property="Background" Value="{DynamicResource SystemFillColorSuccessBrush}" />
- </DataTrigger>
- <DataTrigger Binding="{Binding State, ElementName=TaskStateRoot}" Value="Running">
- <Setter Property="Background" Value="{DynamicResource AccentButtonBackground}" />
- </DataTrigger>
- <DataTrigger Binding="{Binding State, ElementName=TaskStateRoot}" Value="Disabled">
+ <!-- Disabled scheduled task: language-independent (State is localized text). -->
+ <DataTrigger Binding="{Binding IsDisabledState, ElementName=TaskStateRoot}" Value="True">
<Setter Property="Background" Value="{DynamicResource SystemFillColorCriticalBrush}" />
</DataTrigger>
</Style.Triggers>
@@ -63,15 +58,7 @@
<Setter Property="Symbol" Value="Dismiss24" />
<Setter Property="Foreground" Value="{DynamicResource TextFillColorInverseBrush}" />
</DataTrigger>
- <DataTrigger Binding="{Binding State, ElementName=TaskStateRoot}" Value="Ready">
- <Setter Property="Symbol" Value="CheckmarkCircle24" />
- <Setter Property="Foreground" Value="{DynamicResource TextFillColorInverseBrush}" />
- </DataTrigger>
- <DataTrigger Binding="{Binding State, ElementName=TaskStateRoot}" Value="Running">
- <Setter Property="Symbol" Value="Play24" />
- <Setter Property="Foreground" Value="{DynamicResource TextFillColorInverseBrush}" />
- </DataTrigger>
- <DataTrigger Binding="{Binding State, ElementName=TaskStateRoot}" Value="Disabled">
+ <DataTrigger Binding="{Binding IsDisabledState, ElementName=TaskStateRoot}" Value="True">
<Setter Property="Symbol" Value="Dismiss24" />
<Setter Property="Foreground" Value="{DynamicResource TextFillColorInverseBrush}" />
</DataTrigger>
diff --git a/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs b/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs
index 17a1239..1e09cfc 100644
--- a/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs
@@ -10,6 +10,7 @@ using optimizerDuck.Domain.Conditions;
using optimizerDuck.Domain.Customize.Models;
using optimizerDuck.Domain.Execution;
using optimizerDuck.Services.Configuration;
+using optimizerDuck.Services.Customize;
using optimizerDuck.Services.System;
using Wpf.Ui.Controls;
@@ -25,16 +26,13 @@ public partial class CustomizeItemViewModel(
loggerFactory.CreateLogger<CustomizeItemViewModel>();
private bool _hasLoaded;
- private CancellationTokenSource? _debounceCts;
+ private readonly CustomizationExecutor _executor = new(
+ loggerFactory.CreateLogger<CustomizationExecutor>()
+ );
private bool _disposed;
private readonly HashSet<string> _watchedPaths = new(StringComparer.OrdinalIgnoreCase);
- private readonly object _applyLock = new();
- private bool _isApplying;
- private object? _pendingValue;
- private bool _hasPendingValue;
-
public ICustomizeSetting Setting => setting;
public CustomizeControlType ControlType => setting.ControlType;
@@ -222,11 +220,8 @@ public partial class CustomizeItemViewModel(
{
try
{
- lock (_applyLock)
- {
- if (_isApplying)
- return;
- }
+ if (_executor.IsApplying)
+ return;
// Only the refresh bookkeeping runs on the UI thread; the reads stay off it.
IsEnabled = await Task.Run(() =>
@@ -249,21 +244,7 @@ public partial class CustomizeItemViewModel(
[RelayCommand]
private void Toggle()
{
- lock (_applyLock)
- {
- var currentTarget = _hasPendingValue ? (bool)_pendingValue! : IsEnabled;
- var nextState = !currentTarget;
-
- _pendingValue = nextState;
- _hasPendingValue = true;
-
- if (_isApplying)
- return;
-
- _isApplying = true;
- }
-
- _ = ProcessPendingValuesAsync();
+ _ = _executor.ApplyWithDebounceAsync(!IsEnabled, ApplyCoreAsync, debounceMs: 0);
}
partial void OnCurrentValueChanged(object? value)
@@ -274,98 +255,55 @@ public partial class CustomizeItemViewModel(
if (Equals(value, setting.CurrentValue))
return;
- if (ControlType == CustomizeControlType.String)
- _ = ApplyWithDebounceAsync(value);
- else
- QueueApplyValue(value);
+ var debounce = ControlType == CustomizeControlType.String ? 400 : 0;
+ _ = _executor.ApplyWithDebounceAsync(value, ApplyCoreAsync, debounce);
}
- private void QueueApplyValue(object? value)
+ private async Task ApplyCoreAsync(object? valueToApply)
{
- lock (_applyLock)
+ IsLoading = true;
+ try
{
- _pendingValue = value;
- _hasPendingValue = true;
-
- if (_isApplying)
- return;
+ _logger.LogInformation(
+ "Apply {Value} for {Setting} ({Key})",
+ valueToApply,
+ setting.LogName(),
+ setting.FeatureKey
+ );
- _isApplying = true;
- }
+ var applyResult = await setting.ApplyAsync(
+ valueToApply,
+ new OpCall { Logger = _logger }
+ );
- _ = ProcessPendingValuesAsync();
- }
+ if (!applyResult.Ok)
+ {
+ _logger.LogError(
+ "Failed to apply {Setting} ({Key}): {Error} {Detail}",
+ setting.LogName(),
+ setting.FeatureKey,
+ applyResult.Error,
+ applyResult.ErrorDetail
+ );
+ }
- private async Task ApplyWithDebounceAsync(object? value)
- {
- _debounceCts?.Cancel();
- _debounceCts = new CancellationTokenSource();
- var token = _debounceCts.Token;
+ IsEnabled = await Task.Run(() => setting.GetStateWithRetryAsync());
- try
- {
- await Task.Delay(400, token);
- if (token.IsCancellationRequested)
- return;
+ if (ControlType != CustomizeControlType.Toggle)
+ {
+ var (options, current) = await Task.Run(() =>
+ (setting.Options, setting.CurrentValue)
+ );
+ UpdateOptions(options);
+ CurrentValue = current;
+ }
- QueueApplyValue(value);
+ if (Application.Current is App app)
+ app.HasPendingChanges = true;
}
- catch (TaskCanceledException) { }
- }
-
- private async Task ProcessPendingValuesAsync()
- {
- try
+ catch (Exception ex)
{
- while (true)
- {
- object? valueToApply;
- lock (_applyLock)
- {
- if (!_hasPendingValue)
- {
- _isApplying = false;
- break;
- }
-
- valueToApply = _pendingValue;
- _hasPendingValue = false;
- }
-
- IsLoading = true;
- try
- {
- _logger.LogInformation(
- "Apply {Value} for {Setting} ({Key})",
- valueToApply,
- setting.LogName(),
- setting.FeatureKey
- );
-
- using (ExecutionScope.BeginForLogging(_logger))
- {
- await setting.ApplyAsync(valueToApply);
- }
-
- IsEnabled = await Task.Run(() => setting.GetStateWithRetryAsync());
-
- if (ControlType != CustomizeControlType.Toggle)
- {
- var (options, current) = await Task.Run(() =>
- (setting.Options, setting.CurrentValue)
- );
- UpdateOptions(options);
- CurrentValue = current;
- }
-
- if (Application.Current is App app)
- app.HasPendingChanges = true;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Failed to apply {SettingName}", setting.LogName());
- }
- }
+ _logger.LogError(ex, "Failed to apply {SettingName}", setting.LogName());
}
finally
{
@@ -386,7 +324,6 @@ public partial class CustomizeItemViewModel(
registryWatcher.Unwatch(path);
_watchedPaths.Clear();
- _debounceCts?.Cancel();
- _debounceCts?.Dispose();
+ _executor.Dispose();
}
}
diff --git a/optimizerDuck/UI/ViewModels/Dialogs/OptimizationResultDialogViewModel.cs b/optimizerDuck/UI/ViewModels/Dialogs/OptimizationResultDialogViewModel.cs
index 656ba20..aa41dfa 100644
--- a/optimizerDuck/UI/ViewModels/Dialogs/OptimizationResultDialogViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Dialogs/OptimizationResultDialogViewModel.cs
@@ -1,18 +1,18 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using optimizerDuck.Common.Extensions;
-using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.Execution;
namespace optimizerDuck.UI.ViewModels.Dialogs;
public class OptimizationResultDialogViewModel : LocalizedObject
{
- public OptimizationResultDialogViewModel(IEnumerable<OperationStepResult> failedSteps)
+ public OptimizationResultDialogViewModel(IEnumerable<Change> failedSteps)
{
- FailedSteps = new ObservableCollection<OperationStepResult>(failedSteps);
+ FailedSteps = new ObservableCollection<Change>(failedSteps);
}
- public ObservableCollection<OperationStepResult> FailedSteps { get; }
+ public ObservableCollection<Change> FailedSteps { get; }
public int FailedCount => FailedSteps.Count;
}
diff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.Dialogs.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.Dialogs.cs
new file mode 100644
index 0000000..007630a
--- /dev/null
+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.Dialogs.cs
@@ -0,0 +1,409 @@
+namespace optimizerDuck.UI.ViewModels.Optimizer;
+
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Threading;
+using CommunityToolkit.Mvvm.ComponentModel;
+using CommunityToolkit.Mvvm.Input;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+using optimizerDuck.Common.Helpers;
+using optimizerDuck.Domain.Abstractions;
+using optimizerDuck.Domain.Configuration;
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.Revert;
+using optimizerDuck.Domain.UI;
+using optimizerDuck.Resources.Languages;
+using optimizerDuck.Services.Conditions;
+using optimizerDuck.Services.Configuration;
+using optimizerDuck.Services.Optimization;
+using optimizerDuck.Services.Revert;
+using optimizerDuck.Services.System;
+using optimizerDuck.UI.Dialogs;
+using optimizerDuck.UI.ViewModels.Dialogs;
+using Wpf.Ui;
+using Wpf.Ui.Controls;
+using Wpf.Ui.Extensions;
+using TextBlock = Wpf.Ui.Controls.TextBlock;
+
+public partial class OptimizationCategoryViewModel
+{
+ /// <summary>
+ /// Run a long-running action with a processing dialog.
+ /// </summary>
+ private async Task<T> RunWithProcessingDialogAsync<T>(
+ IOptimization optimization,
+ Func<IProgress<ProcessingProgress>, Task<T>> action
+ )
+ {
+ var viewModel = new ProcessingViewModel();
+ var dialog = new ContentDialog
+ {
+ Title = BuildDialogTitle(optimization),
+ Content = new ProcessingDialog { DataContext = viewModel },
+ IsFooterVisible = false,
+ };
+
+ _ = _contentDialogService.ShowAsync(dialog, CancellationToken.None);
+
+ try
+ {
+ return await action(viewModel.ProgressReporter);
+ }
+ finally
+ {
+ dialog.Hide();
+ }
+ }
+
+ /// <summary>
+ /// Handle failed steps for an optimization.
+ /// </summary>
+ private async Task<FailureResolutionOutcome> HandleRetryableFailuresAsync(
+ IOptimization optimization,
+ IReadOnlyList<Change> failedSteps,
+ OptimizationOperation operation
+ )
+ {
+ if (failedSteps.Count == 0)
+ return FailureResolutionOutcome.NoFailures;
+
+ var remainingFailedSteps = failedSteps.OrderBy(s => s.Index).ToList();
+ while (remainingFailedSteps.Count > 0)
+ {
+ // Only offer Retry when at least one failed step can actually be re-run. A
+ // non-retryable failure (e.g. access denied on a Windows-protected service)
+ // must not loop the dialog with a button that cannot change anything.
+ var canRetry = remainingFailedSteps.Any(s => s.Retry != null);
+ var dialogViewModel = new OptimizationResultDialogViewModel(remainingFailedSteps);
+ var dialogContent = new OptimizationResultDialog { DataContext = dialogViewModel };
+
+ var dialog = new ContentDialog
+ {
+ Title = BuildDialogTitle(optimization),
+ Content = dialogContent,
+ };
+ if (canRetry)
+ {
+ dialog.PrimaryButtonText = Loc.Instance["Button.Retry"];
+ dialog.CloseButtonText = Loc.Instance["Button.Cancel"];
+ }
+ else
+ {
+ dialog.CloseButtonText = Loc.Instance["Button.Ok"];
+ }
+
+ var result = await _contentDialogService.ShowAsync(dialog, CancellationToken.None);
+ if (!canRetry || result != ContentDialogResult.Primary)
+ return FailureResolutionOutcome.Deferred;
+
+ if (operation == OptimizationOperation.Revert)
+ {
+ var retryResult = await RunWithProcessingDialogAsync(
+ optimization,
+ progress =>
+ OptimizationService.RetryFailedStepsWithResultsAsync(
+ remainingFailedSteps,
+ true,
+ _logger,
+ revertManager: null,
+ optimizationId: null,
+ optimizationKey: null,
+ progress: progress
+ )
+ );
+
+ foreach (var recoveredStep in retryResult.RecoveredSteps)
+ {
+ await _revertManager.RemoveRevertStepAtIndexAsync(
+ optimization.Id,
+ optimization.OptimizationKey,
+ recoveredStep.Index
+ );
+ }
+
+ remainingFailedSteps = retryResult.FailedSteps.OrderBy(s => s.Index).ToList();
+ if (remainingFailedSteps.Count == 0)
+ {
+ _revertManager.RemoveRevertData(optimization.Id, optimization.OptimizationKey);
+ await OptimizationService.UpdateOptimizationStateAsync(optimization);
+ return FailureResolutionOutcome.Recovered;
+ }
+ }
+ else
+ {
+ var retryResult = await RunWithProcessingDialogAsync(
+ optimization,
+ progress =>
+ OptimizationService.RetryFailedStepsWithResultsAsync(
+ remainingFailedSteps,
+ false,
+ _logger,
+ _revertManager,
+ optimization.Id,
+ optimization.OptimizationKey,
+ progress
+ )
+ );
+
+ var newFailed = retryResult.FailedSteps.OrderBy(s => s.Index).ToList();
+
+ remainingFailedSteps = newFailed;
+ if (remainingFailedSteps.Count == 0)
+ return FailureResolutionOutcome.Recovered;
+ }
+ }
+
+ return FailureResolutionOutcome.Recovered;
+ }
+
+ private static OperationNotificationState ResolveApplyNotificationState(
+ OptimizationResult applyResult,
+ FailureResolutionOutcome retryOutcome
+ )
+ {
+ if (
+ applyResult.Status == OptimizationSuccessResult.Success
+ || retryOutcome == FailureResolutionOutcome.Recovered
+ )
+ return OperationNotificationState.Success;
+
+ return retryOutcome == FailureResolutionOutcome.Deferred
+ ? OperationNotificationState.Partial
+ : OperationNotificationState.Failed;
+ }
+
+ private static OperationNotificationState ResolveRevertNotificationState(
+ RevertResult revertResult,
+ FailureResolutionOutcome retryOutcome
+ )
+ {
+ if (revertResult.Success || retryOutcome == FailureResolutionOutcome.Recovered)
+ return OperationNotificationState.Success;
+
+ return revertResult.AllStepsFailed
+ ? OperationNotificationState.Failed
+ : OperationNotificationState.Partial;
+ }
+
+ /// <summary>
+ /// Shows a snackbar notification based on the operation outcome.
+ /// </summary>
+ private void ShowOperationOutcomeSnackbar(
+ OperationNotificationState notificationState,
+ OptimizationOperation operation,
+ string message,
+ bool restorePointCreated = false
+ )
+ {
+ var showSuccess = _appOptionsMonitor.CurrentValue.Optimize.ShowCompletionNotification;
+ var finalMessage = message;
+
+ if (restorePointCreated && showSuccess)
+ finalMessage +=
+ "\n"
+ + Loc.Instance["RestorePoint.Snackbar.Success.Message", Shared.RestorePointName];
+
+ if (notificationState == OperationNotificationState.Success)
+ {
+ if (showSuccess)
+ _snackbarService.Show(
+ operation == OptimizationOperation.Apply
+ ? Loc.Instance["Optimization.Apply.Snackbar.Success.Title"]
+ : Loc.Instance["Optimization.Revert.Snackbar.Success.Title"],
+ finalMessage,
+ ControlAppearance.Success,
+ new SymbolIcon { Symbol = SymbolRegular.CheckmarkCircle24, Filled = true },
+ TimeSpan.FromSeconds(5)
+ );
+ }
+ else if (notificationState == OperationNotificationState.Partial)
+ {
+ _snackbarService.Show(
+ operation == OptimizationOperation.Apply
+ ? Loc.Instance["Optimization.Apply.Snackbar.Error.Title"]
+ : Loc.Instance["Optimization.Revert.Snackbar.Error.Title"],
+ finalMessage,
+ ControlAppearance.Caution,
+ new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },
+ TimeSpan.FromSeconds(5)
+ );
+ }
+ else if (notificationState == OperationNotificationState.Failed)
+ {
+ _snackbarService.Show(
+ operation == OptimizationOperation.Apply
+ ? Loc.Instance["Optimization.Apply.Snackbar.Error.Title"]
+ : Loc.Instance["Optimization.Revert.Snackbar.Error.Title"],
+ finalMessage,
+ ControlAppearance.Danger,
+ new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
+ TimeSpan.FromSeconds(5)
+ );
+ }
+ }
+
+ /// <summary>
+ /// Handles the restore point dialog.
+ /// </summary>
+ private async Task<(bool Proceed, bool RestorePointCreated)> HandleRestorePointAsync()
+ {
+ var dialogContent = new RestorePointDialog();
+ var dialog = new ContentDialog
+ {
+ Title = Loc.Instance["RestorePoint.Title"],
+ Content = dialogContent,
+ PrimaryButtonText = Loc.Instance["Button.Ok"],
+ SecondaryButtonText = Loc.Instance["Button.Skip"],
+ CloseButtonText = Loc.Instance["Button.Cancel"],
+ };
+
+ var result = await _contentDialogService.ShowAsync(dialog, CancellationToken.None);
+ if (result == ContentDialogResult.None)
+ {
+ _logger.LogInformation("User cancelled the restore point dialog");
+ return (false, false);
+ }
+
+ if (result == ContentDialogResult.Secondary)
+ {
+ _logger.LogInformation("User chose to skip creating a restore point");
+ return (true, false);
+ }
+
+ try
+ {
+ _logger.LogInformation("User accepted to create a restore point, starting creation");
+ var resultState = await _optimizationService.CreateRestorePointAsync();
+
+ switch (resultState)
+ {
+ case RestorePointResult.Success:
+ if (!_appOptionsMonitor.CurrentValue.Optimize.ShowCompletionNotification)
+ {
+ _snackbarService.Show(
+ Loc.Instance["RestorePoint.Snackbar.Success.Title"],
+ Loc.Instance[
+ "RestorePoint.Snackbar.Success.Message",
+ Shared.RestorePointName
+ ],
+ ControlAppearance.Success,
+ new SymbolIcon
+ {
+ Symbol = SymbolRegular.CheckmarkCircle24,
+ Filled = true,
+ },
+ TimeSpan.FromSeconds(5)
+ );
+ }
+
+ _logger.LogInformation("Successfully created restore point");
+ return (true, true);
+
+ case RestorePointResult.FrequencyLimitReached:
+ _snackbarService.Show(
+ Loc.Instance["RestorePoint.Snackbar.Error.Title"],
+ Loc.Instance["RestorePoint.Snackbar.Warning.LimitReached"],
+ ControlAppearance.Caution,
+ new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },
+ TimeSpan.FromSeconds(5)
+ );
+ _logger.LogWarning("Restore point creation frequency limit reached");
+ break;
+
+ case RestorePointResult.Failed:
+ default:
+ _snackbarService.Show(
+ Loc.Instance["RestorePoint.Snackbar.Error.Title"],
+ Loc.Instance["RestorePoint.Snackbar.Error.Message"],
+ ControlAppearance.Danger,
+ new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
+ TimeSpan.FromSeconds(5)
+ );
+ _logger.LogError("Failed to create restore point");
+ break;
+ }
+
+ var failedMessage =
+ resultState == RestorePointResult.FrequencyLimitReached
+ ? Loc.Instance["RestorePoint.Snackbar.Warning.LimitReached"]
+ : "";
+ var failedResult = await _contentDialogService.ShowSimpleDialogAsync(
+ new SimpleContentDialogCreateOptions
+ {
+ Title = Loc.Instance["RestorePoint.Snackbar.Error.Title"],
+ Content =
+ failedMessage + $"\n{Loc.Instance["RestorePoint.Snackbar.Error.Message"]}",
+ PrimaryButtonText = Loc.Instance["Button.Skip"],
+ CloseButtonText = Loc.Instance["Button.Cancel"],
+ },
+ CancellationToken.None
+ );
+
+ if (failedResult == ContentDialogResult.Primary)
+ return (true, false);
+
+ return (false, false);
+ }
+ catch (Exception e)
+ {
+ _logger.LogError(e, "Failed to create restore point");
+ _snackbarService.Show(
+ Loc.Instance["RestorePoint.Snackbar.Error.Title"],
+ Loc.Instance["RestorePoint.Snackbar.Error.Message"],
+ ControlAppearance.Caution,
+ new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },
+ TimeSpan.FromSeconds(5)
+ );
+ }
+
+ return (true, false);
+ }
+
+ /// <summary>
+ /// Builds the dialog title for an optimization.
+ /// </summary>
+ private static StackPanel BuildDialogTitle(IOptimization optimization)
+ {
+ return new StackPanel
+ {
+ Children =
+ {
+ new TextBlock
+ {
+ FontTypography = FontTypography.Caption,
+ Appearance = TextColor.Disabled,
+ Text = optimization.Id.ToString(),
+ },
+ new TextBlock
+ {
+ FontTypography = FontTypography.Subtitle,
+ Text = optimization.Name,
+ },
+ },
+ };
+ }
+
+ private enum FailureResolutionOutcome
+ {
+ NoFailures,
+ Recovered,
+ Deferred,
+ }
+
+ private enum OperationNotificationState
+ {
+ Success,
+ Partial,
+ Failed,
+ }
+
+ private enum OptimizationOperation
+ {
+ Apply,
+ Revert,
+ }
+}
diff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
index c40cb21..6ac2b69 100644
--- a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
@@ -156,6 +156,7 @@ public partial class OptimizationCategoryViewModel : ViewModel
[RelayCommand(CanExecute = nameof(CanToggleOptimization))]
private async Task ToggleOptimizationAsync(IOptimization optimization)
{
+ IsProcessing = true;
try
{
var wasApplied = await RevertManager.IsAppliedAsync(optimization.Id);
@@ -341,11 +342,16 @@ public partial class OptimizationCategoryViewModel : ViewModel
: notificationState == OperationNotificationState.Partial ? LogLevel.Warning
: LogLevel.Warning;
+ var pastTense = operationName switch
+ {
+ "apply" => "applied",
+ "revert" => "reverted",
+ _ => $"{operationName}ed",
+ };
+
var message =
- notificationState == OperationNotificationState.Success
- ? $"Successfully {operationName}d"
- : notificationState == OperationNotificationState.Partial
- ? $"Partially {operationName}d"
+ notificationState == OperationNotificationState.Success ? $"Successfully {pastTense}"
+ : notificationState == OperationNotificationState.Partial ? $"Partially {pastTense}"
: $"Failed to {operationName}";
_logger.Log(level, "{Message}: {Name}", message, optimization.OptimizationKey);
@@ -536,389 +542,5 @@ public partial class OptimizationCategoryViewModel : ViewModel
OnPropertyChanged(nameof(HasAppliedOptimizations));
}
- /// <summary>
- /// Run a long-running action with a processing dialog.
- /// </summary>
- /// <param name="optimization">The optimization to run the action for.</param>
- /// <param name="action">The action to run.</param>
- /// <typeparam name="T">The return type of the action.</typeparam>
- /// <returns>The result of the action.</returns>
- private async Task<T> RunWithProcessingDialogAsync<T>(
- IOptimization optimization,
- Func<IProgress<ProcessingProgress>, Task<T>> action
- )
- {
- var viewModel = new ProcessingViewModel();
- var dialog = new ContentDialog
- {
- Title = BuildDialogTitle(optimization),
- Content = new ProcessingDialog { DataContext = viewModel },
- IsFooterVisible = false,
- };
-
- _ = _contentDialogService.ShowAsync(dialog, CancellationToken.None);
-
- try
- {
- return await action(viewModel.ProgressReporter);
- }
- finally
- {
- dialog.Hide();
- }
- }
-
- /// <summary>
- /// Handle failed steps for an optimization.
- /// </summary>
- /// <param name="optimization">The optimization that failed.</param>
- /// <param name="failedSteps">The failed steps.</param>
- /// <param name="operation">The operation currently being processed.</param>
- /// <returns>The retry outcome.</returns>
- private async Task<FailureResolutionOutcome> HandleRetryableFailuresAsync(
- IOptimization optimization,
- IReadOnlyList<OperationStepResult> failedSteps,
- OptimizationOperation operation
- )
- {
- if (failedSteps.Count == 0)
- return FailureResolutionOutcome.NoFailures;
-
- // Always keep steps ordered by their original index for a stable UI.
- var remainingFailedSteps = failedSteps.OrderBy(s => s.Index).ToList();
- while (remainingFailedSteps.Count > 0)
- {
- var dialogViewModel = new OptimizationResultDialogViewModel(remainingFailedSteps);
- var dialogContent = new OptimizationResultDialog { DataContext = dialogViewModel };
-
- var dialog = new ContentDialog
- {
- Title = BuildDialogTitle(optimization),
- Content = dialogContent,
- PrimaryButtonText = Loc.Instance["Button.Retry"],
- CloseButtonText = Loc.Instance["Button.Cancel"],
- };
-
- var result = await _contentDialogService.ShowAsync(dialog, CancellationToken.None);
- if (result != ContentDialogResult.Primary)
- return FailureResolutionOutcome.Deferred;
-
- if (operation == OptimizationOperation.Revert)
- {
- var retryResult = await RunWithProcessingDialogAsync(
- optimization,
- progress =>
- OptimizationService.RetryFailedStepsWithResultsAsync(
- remainingFailedSteps,
- true,
- _logger,
- revertManager: null,
- optimizationId: null,
- optimizationKey: null,
- progress: progress
- )
- );
-
- foreach (var recoveredStep in retryResult.RecoveredSteps)
- {
- await _revertManager.RemoveRevertStepAtIndexAsync(
- optimization.Id,
- optimization.OptimizationKey,
- recoveredStep.Index
- );
- }
-
- remainingFailedSteps = retryResult.FailedSteps.OrderBy(s => s.Index).ToList();
- if (remainingFailedSteps.Count == 0)
- {
- _revertManager.RemoveRevertData(optimization.Id, optimization.OptimizationKey);
- await OptimizationService.UpdateOptimizationStateAsync(optimization);
- return FailureResolutionOutcome.Recovered;
- }
- }
- else
- {
- var retryResult = await RunWithProcessingDialogAsync(
- optimization,
- progress =>
- OptimizationService.RetryFailedStepsWithResultsAsync(
- remainingFailedSteps,
- false,
- _logger,
- _revertManager,
- optimization.Id,
- optimization.OptimizationKey,
- progress
- )
- );
-
- var newFailed = retryResult.FailedSteps.OrderBy(s => s.Index).ToList();
-
- remainingFailedSteps = newFailed;
- if (remainingFailedSteps.Count == 0)
- return FailureResolutionOutcome.Recovered;
- }
- }
-
- return FailureResolutionOutcome.Recovered;
- }
-
- private static OperationNotificationState ResolveApplyNotificationState(
- OptimizationResult applyResult,
- FailureResolutionOutcome retryOutcome
- )
- {
- if (
- applyResult.Status == OptimizationSuccessResult.Success
- || retryOutcome == FailureResolutionOutcome.Recovered
- )
- return OperationNotificationState.Success;
-
- return retryOutcome == FailureResolutionOutcome.Deferred
- ? OperationNotificationState.Partial
- : OperationNotificationState.Failed;
- }
-
- private static OperationNotificationState ResolveRevertNotificationState(
- RevertResult revertResult,
- FailureResolutionOutcome retryOutcome
- )
- {
- if (revertResult.Success || retryOutcome == FailureResolutionOutcome.Recovered)
- return OperationNotificationState.Success;
-
- return revertResult.AllStepsFailed
- ? OperationNotificationState.Failed
- : OperationNotificationState.Partial;
- }
-
- /// <summary>
- /// Shows a snackbar notification based on the operation outcome.
- /// </summary>
- /// <param name="notificationState">The notification state to show.</param>
- /// <param name="operation">The type of operation.</param>
- /// <param name="message">The message to show.</param>
- /// <param name="restorePointCreated">Whether a restore point was created.</param>
- private void ShowOperationOutcomeSnackbar(
- OperationNotificationState notificationState,
- OptimizationOperation operation,
- string message,
- bool restorePointCreated = false
- )
- {
- var showSuccess = _appOptionsMonitor.CurrentValue.Optimize.ShowCompletionNotification;
- var finalMessage = message;
-
- if (restorePointCreated && showSuccess)
- finalMessage +=
- "\n"
- + Loc.Instance["RestorePoint.Snackbar.Success.Message", Shared.RestorePointName];
-
- if (notificationState == OperationNotificationState.Success)
- {
- if (showSuccess)
- _snackbarService.Show(
- operation == OptimizationOperation.Apply
- ? Loc.Instance["Optimization.Apply.Snackbar.Success.Title"]
- : Loc.Instance["Optimization.Revert.Snackbar.Success.Title"],
- finalMessage,
- ControlAppearance.Success,
- new SymbolIcon { Symbol = SymbolRegular.CheckmarkCircle24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
- }
- else if (notificationState == OperationNotificationState.Partial)
- {
- _snackbarService.Show(
- operation == OptimizationOperation.Apply
- ? Loc.Instance["Optimization.Apply.Snackbar.Error.Title"]
- : Loc.Instance["Optimization.Revert.Snackbar.Error.Title"],
- finalMessage,
- ControlAppearance.Caution,
- new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
- }
- else if (notificationState == OperationNotificationState.Failed)
- {
- _snackbarService.Show(
- operation == OptimizationOperation.Apply
- ? Loc.Instance["Optimization.Apply.Snackbar.Error.Title"]
- : Loc.Instance["Optimization.Revert.Snackbar.Error.Title"],
- finalMessage,
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
- }
- }
-
- /// <summary>
- /// Handles the restore point dialog.
- /// </summary>
- /// <returns>Whether the user accepted the restore point dialog.</returns>
- private async Task<(bool Proceed, bool RestorePointCreated)> HandleRestorePointAsync()
- {
- var dialogContent = new RestorePointDialog();
- var dialog = new ContentDialog
- {
- Title = Loc.Instance["RestorePoint.Title"],
- Content = dialogContent,
-
- PrimaryButtonText = Loc.Instance["Button.Ok"],
- SecondaryButtonText = Loc.Instance["Button.Skip"],
- CloseButtonText = Loc.Instance["Button.Cancel"],
- };
-
- var result = await _contentDialogService.ShowAsync(dialog, CancellationToken.None);
- if (result == ContentDialogResult.None)
- { // User cancelled
- _logger.LogInformation("User cancelled the restore point dialog");
- return (false, false);
- }
-
- if (result == ContentDialogResult.Secondary)
- { // User skipped
- _logger.LogInformation("User chose to skip creating a restore point");
- return (true, false);
- }
-
- try
- {
- _logger.LogInformation("User accepted to create a restore point, starting creation");
- var resultState = await _optimizationService.CreateRestorePointAsync();
-
- switch (resultState)
- {
- case RestorePointResult.Success:
- if (!_appOptionsMonitor.CurrentValue.Optimize.ShowCompletionNotification)
- {
- _snackbarService.Show(
- Loc.Instance["RestorePoint.Snackbar.Success.Title"],
- Loc.Instance[
- "RestorePoint.Snackbar.Success.Message",
- Shared.RestorePointName
- ],
- ControlAppearance.Success,
- new SymbolIcon
- {
- Symbol = SymbolRegular.CheckmarkCircle24,
- Filled = true,
- },
- TimeSpan.FromSeconds(5)
- );
- }
-
- _logger.LogInformation("Successfully created restore point");
-
- return (true, true);
-
- case RestorePointResult.FrequencyLimitReached:
- _snackbarService.Show(
- Loc.Instance["RestorePoint.Snackbar.Error.Title"],
- Loc.Instance["RestorePoint.Snackbar.Warning.LimitReached"],
- ControlAppearance.Caution,
- new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
- _logger.LogWarning("Restore point creation frequency limit reached");
- break;
-
- case RestorePointResult.Failed:
- default:
- _snackbarService.Show(
- Loc.Instance["RestorePoint.Snackbar.Error.Title"],
- Loc.Instance["RestorePoint.Snackbar.Error.Message"],
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
- _logger.LogError("Failed to create restore point");
- break;
- }
-
- var failedMessage =
- resultState == RestorePointResult.FrequencyLimitReached
- ? Loc.Instance["RestorePoint.Snackbar.Warning.LimitReached"]
- : "";
- var failedResult = await _contentDialogService.ShowSimpleDialogAsync(
- new SimpleContentDialogCreateOptions
- {
- Title = Loc.Instance["RestorePoint.Snackbar.Error.Title"],
- Content =
- failedMessage + $"\n{Loc.Instance["RestorePoint.Snackbar.Error.Message"]}",
-
- PrimaryButtonText = Loc.Instance["Button.Skip"],
- CloseButtonText = Loc.Instance["Button.Cancel"],
- },
- CancellationToken.None
- );
-
- if (failedResult == ContentDialogResult.Primary) // User chose to skip after failure
- return (true, false);
-
- return (false, false);
- }
- catch (Exception e)
- {
- _logger.LogError(e, "Failed to create restore point");
- _snackbarService.Show(
- Loc.Instance["RestorePoint.Snackbar.Error.Title"],
- Loc.Instance["RestorePoint.Snackbar.Error.Message"],
- ControlAppearance.Caution,
- new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
- }
-
- return (true, false);
- }
-
- /// <summary>
- /// Builds the dialog title for an optimization.
- /// </summary>
- /// <param name="optimization">The optimization to build the title for.</param>
- /// <returns>The dialog title.</returns>
- private static StackPanel BuildDialogTitle(IOptimization optimization)
- {
- return new StackPanel
- {
- Children =
- {
- new TextBlock
- {
- FontTypography = FontTypography.Caption,
- Appearance = TextColor.Disabled,
- Text = optimization.Id.ToString(),
- },
- new TextBlock
- {
- FontTypography = FontTypography.Subtitle,
- Text = optimization.Name,
- },
- },
- };
- }
-
- private enum FailureResolutionOutcome
- {
- NoFailures,
- Recovered,
- Deferred,
- }
-
- private enum OperationNotificationState
- {
- Success,
- Partial,
- Failed,
- }
-
- private enum OptimizationOperation
- {
- Apply,
- Revert,
- }
-
#endregion Helpers
}
diff --git a/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs
index c9913f3..2aa5d79 100644
--- a/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs
@@ -4,6 +4,7 @@ using System.Diagnostics;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.Configuration;
using optimizerDuck.Services.Optimization.Providers;
@@ -96,9 +97,12 @@ public partial class ScheduledTasksViewModel : ViewModel
{
await Task.Run(() =>
{
+ var call = UiCall();
if (task.IsEnabled)
{
- ScheduledTaskService.EnableTask(task.FullPath);
+ 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,
@@ -107,7 +111,9 @@ public partial class ScheduledTasksViewModel : ViewModel
}
else
{
- ScheduledTaskService.DisableTask(task.FullPath);
+ 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,
@@ -154,9 +160,11 @@ public partial class ScheduledTasksViewModel : ViewModel
return;
try
{
- var success = await Task.Run(() => ScheduledTaskService.RunTask(task.FullPath));
+ var result = await Task.Run(() =>
+ ScheduledTaskService.RunTask(UiCall(), task.FullPath)
+ );
- if (success)
+ if (result.Ok)
{
_logger.LogInformation("Ran task {Name} ({Path})", task.Name, task.FullPath);
@@ -172,9 +180,7 @@ public partial class ScheduledTasksViewModel : ViewModel
}
else
{
- var error =
- ScheduledTaskService.LastError
- ?? Loc.Instance["ScheduledTasks.Error.TaskNotFound"];
+ var error = result.Error ?? Loc.Instance["ScheduledTasks.Error.TaskNotFound"];
_logger.LogError(
"Failed to run task {Name} ({Path}): {Error}",
task.Name,
@@ -217,9 +223,11 @@ public partial class ScheduledTasksViewModel : ViewModel
return;
try
{
- var success = await Task.Run(() => ScheduledTaskService.StopTask(task.FullPath));
+ var result = await Task.Run(() =>
+ ScheduledTaskService.StopTask(UiCall(), task.FullPath)
+ );
- if (success)
+ if (result.Ok)
{
_logger.LogInformation("Stopped task {Name} ({Path})", task.Name, task.FullPath);
@@ -235,9 +243,7 @@ public partial class ScheduledTasksViewModel : ViewModel
}
else
{
- var error =
- ScheduledTaskService.LastError
- ?? Loc.Instance["ScheduledTasks.Error.TaskNotFound"];
+ var error = result.Error ?? Loc.Instance["ScheduledTasks.Error.TaskNotFound"];
_logger.LogError(
"Failed to stop task {Name} ({Path}): {Error}",
task.Name,
@@ -293,9 +299,11 @@ public partial class ScheduledTasksViewModel : ViewModel
try
{
- var success = await Task.Run(() => ScheduledTaskService.DeleteTask(task.FullPath));
+ var deleteOutcome = await Task.Run(() =>
+ ScheduledTaskService.DeleteTask(UiCall(), task.FullPath)
+ );
- if (success)
+ if (deleteOutcome.Ok)
{
_logger.LogInformation("Deleted task {Name} ({Path})", task.Name, task.FullPath);
_allTasks.RemoveAll(t => t.FullPath == task.FullPath);
@@ -312,8 +320,7 @@ public partial class ScheduledTasksViewModel : ViewModel
else
{
var error =
- ScheduledTaskService.LastError
- ?? Loc.Instance["ScheduledTasks.Error.TaskNotFound"];
+ deleteOutcome.Error ?? Loc.Instance["ScheduledTasks.Error.TaskNotFound"];
_logger.LogError(
"Failed to delete task {Name} ({Path}): {Error}",
task.Name,
@@ -425,6 +432,12 @@ 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 };
+ }
+
private void ApplyFilter()
{
// Unsubscribe
diff --git a/optimizerDuck/Windows/Services/ScStartupTypeParser.cs b/optimizerDuck/Windows/Services/ScStartupTypeParser.cs
new file mode 100644
index 0000000..40e6a9a
--- /dev/null
+++ b/optimizerDuck/Windows/Services/ScStartupTypeParser.cs
@@ -0,0 +1,48 @@
+using System.Text.RegularExpressions;
+using optimizerDuck.Domain.Optimizations.Models.Services;
+
+namespace optimizerDuck.Windows.Services;
+
+/// <summary>
+/// Shared parser for <c>sc.exe qc</c> START_TYPE output, used by
+/// <c>ServiceProcessService</c>.
+/// </summary>
+public static partial class ScStartupTypeParser
+{
+ [GeneratedRegex(@"^\s*\S+\s*:\s*([0-4])\s(.+)$")]
+ private static partial Regex StartTypeLineRegex();
+
+ [GeneratedRegex(@"\([^)]+\)", RegexOptions.IgnoreCase)]
+ private static partial Regex DelayedRegex();
+
+ public static ServiceStartupType? Parse(string stdout) => ParseWithMatch(stdout).Type;
+
+ public static (ServiceStartupType? Type, bool Matched) ParseWithMatch(string stdout)
+ {
+ var lines = stdout.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries);
+ foreach (var line in lines)
+ {
+ var match = StartTypeLineRegex().Match(line);
+ if (!match.Success)
+ continue;
+
+ var startValue = int.Parse(match.Groups[1].Value);
+ var isDelayed = DelayedRegex().IsMatch(match.Groups[2].Value);
+
+ return (
+ startValue switch
+ {
+ 2 => isDelayed
+ ? ServiceStartupType.AutomaticDelayedStart
+ : ServiceStartupType.Automatic,
+ 3 => ServiceStartupType.Manual,
+ 4 => ServiceStartupType.Disabled,
+ _ => null,
+ },
+ true
+ );
+ }
+
+ return (null, false);
+ }
+}