Skip to content

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

refactor: simplify execution architecture and fix logic issues

fatDuck567a775eb2a6
diff --git a/.github/contributing/CONTRIBUTING.ja-JP.md b/.github/contributing/CONTRIBUTING.ja-JP.md
index 3007fa6..339863c 100644
--- a/.github/contributing/CONTRIBUTING.ja-JP.md
+++ b/.github/contributing/CONTRIBUTING.ja-JP.md
@@ -336,7 +336,7 @@ public class Performance : IOptimizationCategory
|---|---|---|
| **`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 スケジュールタスクの管理。 |
+| **`ScheduledTaskService`**(static) | `DisableTask(path, context)`、`EnableTask(path, context)`、`GetTaskEnabledState()`、`DeleteTask()`、`GetAllTasks()`、`RegisterTask()`、`RunTask()`、`StopTask()` | Windows スケジュールタスクの管理。 |
| **`ServiceProcessService`**(static) | `ChangeServiceStartupTypeAsync(item, context)`(単体/配列)、`GetStartupTypeAsync()` | Windows サービスの管理。常に非同期版を使用。配列でバッチ変更可能。 |
> **params 配列で複数アイテムを受け付けるメソッド**:ほとんどの書き込み/変更メソッドは params 配列を受け付けます(例:`RegistryService.Write(context, item1, item2, item3)`)。個別呼び出しより効率的です。
diff --git a/.github/contributing/CONTRIBUTING.tr-TR.md b/.github/contributing/CONTRIBUTING.tr-TR.md
index 99bbd77..7129d14 100644
--- a/.github/contributing/CONTRIBUTING.tr-TR.md
+++ b/.github/contributing/CONTRIBUTING.tr-TR.md
@@ -337,7 +337,7 @@ Bu sınıflar günlük kaydı, hata işleme ve otomatik geri alma adımı kaydı
|---|---|---|
| **`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. |
+| **`ScheduledTaskService`** | `DisableTask(path, call)`, `EnableTask(path, call)`, `GetTaskEnabledState(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. |
> **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.
diff --git a/AGENTS.md b/AGENTS.md
index f9657e6..9e9da52 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -159,7 +159,7 @@
## Scheduled Task Service Details
- Uses `Microsoft.Win32.TaskScheduler` library (TaskScheduler NuGet package).
- `DisableTask(fullPath)` / `EnableTask(fullPath)` — toggle task state with revert step recording.
-- `IsTaskEnabled(fullPath)` — checks if a task exists and is enabled.
+- `GetTaskEnabledState(fullPath)` — reads whether a task exists and is enabled; returns `TaskEnabledState` (`Enabled`/`Disabled`/`NotFound`/`Unknown`) and never reports a failed query as "disabled".
- `DeleteTask(fullPath)` — deletes a task.
- `GetAllTasks()` — enumerates all tasks recursively with icon extraction via `StartupManagerService.ExtractIcon`.
- `GetStartupTasks()` — filtered to tasks with LogonTrigger or BootTrigger.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 238af4f..777b6f9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -338,7 +338,7 @@ All of them handle logging, error handling, and revert recording through the exp
|---|---|---|
| **`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. |
+| **`ScheduledTaskService`** (static) | `DisableTask()`, `EnableTask()`, `GetTaskEnabledState()`, `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(context, item1, item2, item3)`). This is more efficient than multiple individual calls.
diff --git a/optimizerDuck.Test/Common/Extensions/LocalizedObservableTests.cs b/optimizerDuck.Test/Common/Extensions/LocalizedObservableTests.cs
index 592d6d9..81008b5 100644
--- a/optimizerDuck.Test/Common/Extensions/LocalizedObservableTests.cs
+++ b/optimizerDuck.Test/Common/Extensions/LocalizedObservableTests.cs
@@ -35,7 +35,7 @@ public class LocalizedObservableTests : IDisposable
Loc.Instance.ChangeCulture(new CultureInfo("vi"));
- // WPF convention: empty string means "all bindings" — the binding engine
+ // WPF convention: empty string means "all bindings", the binding engine
// re-evaluates every getter that wraps the localization indexer.
Assert.Contains(string.Empty, raised);
}
diff --git a/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs b/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs
index 49be9c8..014c34a 100644
--- a/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs
+++ b/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs
@@ -853,12 +853,13 @@ public class BaseCustomizeSettingTests : IDisposable
}
[Fact]
- public void Options_PartialMultiBindingMatch_DoesNotDuplicateDeclaredValue()
+ public void Options_PartialMultiBindingMatch_ShowsCustomFallback()
{
var setting = new TestMultiBindingDropdown { OwnerType = typeof(TestMultiBindingDropdown) };
- // 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.
+ // Key A = 1 (matches "On" primary) but Key B = 0 → mixed state. It must not be
+ // reported as the declared "On" option; a "Custom" fallback with a distinct identity
+ // is selected instead (a duplicate value would make SelectedValuePath ambiguous).
RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "Key1", 1));
RegistryService.Write(
NewCall(),
@@ -868,12 +869,13 @@ public class BaseCustomizeSettingTests : IDisposable
var effective = setting.Options;
Assert.NotNull(effective);
- Assert.Equal(2, effective!.Count);
- Assert.DoesNotContain(
- effective,
- o => o.DisplayName == Loc.Instance[BaseCustomizeSetting.CustomOptionTranslationKey]
+ Assert.Equal(3, effective!.Count);
+ Assert.Equal(
+ Loc.Instance[BaseCustomizeSetting.CustomOptionTranslationKey],
+ effective[2].DisplayName
);
- Assert.Equal(1, setting.CurrentValue);
+ Assert.Same(effective[2].Value, setting.CurrentValue);
+ Assert.NotEqual(1, effective[2].Value);
CleanupTestKeys();
try
@@ -1049,13 +1051,32 @@ public class BaseCustomizeSettingTests : IDisposable
);
Assert.Equal(1, setting.CurrentValue);
- // Key A = 1, Key B = 0 → no match → returns primary binding raw value
+ // Key A = 1, Key B = 0 → mixed state: the "Custom" fallback is selected instead of
+ // the declared "On" option, and applying it must not write anything.
RegistryService.Write(NewCall(), new RegistryItem(TestKeyPath, "Key1", 1));
RegistryService.Write(
NewCall(),
new RegistryItem(@"HKCU\Software\TestOptimizerDuckMultiKey", "Key2", 0)
);
- Assert.Equal(1, setting.CurrentValue);
+
+ var options = setting.Options;
+ Assert.NotNull(options);
+ var fallback = options![2];
+ Assert.Equal(
+ Loc.Instance[BaseCustomizeSetting.CustomOptionTranslationKey],
+ fallback.DisplayName
+ );
+ Assert.Same(fallback.Value, setting.CurrentValue);
+ Assert.NotEqual(1, fallback.Value);
+
+ Assert.True((await setting.ApplyAsync(fallback.Value, NewCall())).Ok);
+ Assert.Equal(1, RegistryService.Read<int>(new RegistryItem(TestKeyPath, "Key1")));
+ Assert.Equal(
+ 0,
+ RegistryService.Read<int>(
+ new RegistryItem(@"HKCU\Software\TestOptimizerDuckMultiKey", "Key2")
+ )
+ );
CleanupTestKeys();
try
diff --git a/optimizerDuck.Test/Domain/Optimizations/Models/ScheduledTask/ScheduledTaskTriggerTests.cs b/optimizerDuck.Test/Domain/Optimizations/Models/ScheduledTask/ScheduledTaskTriggerTests.cs
new file mode 100644
index 0000000..552ef0f
--- /dev/null
+++ b/optimizerDuck.Test/Domain/Optimizations/Models/ScheduledTask/ScheduledTaskTriggerTests.cs
@@ -0,0 +1,176 @@
+using System.Globalization;
+using optimizerDuck.Domain.Optimizations.Models.ScheduledTask;
+using optimizerDuck.Services.Configuration;
+
+namespace optimizerDuck.Test.Domain.Optimizations.Models.ScheduledTask;
+
+public class ScheduledTaskTriggerTests
+{
+ [Fact]
+ public void TriggerTypes_ResolveLocalizedLabelsFromInfos()
+ {
+ var model = new ScheduledTaskModel
+ {
+ Name = "T",
+ Path = "\\",
+ FullPath = "\\T",
+ TriggerInfos =
+ [
+ new("ScheduledTasks.Trigger.Logon", null, [], null),
+ new(
+ "ScheduledTasks.Trigger.Daily",
+ "ScheduledTasks.TriggerDetail.Daily",
+ ["1", "9:00 AM"],
+ null
+ ),
+ ],
+ };
+ Assert.Equal(
+ [
+ Loc.Instance["ScheduledTasks.Trigger.Logon"],
+ Loc.Instance["ScheduledTasks.Trigger.Daily"],
+ ],
+ model.TriggerTypes
+ );
+ Assert.Equal(
+ string.Format(
+ CultureInfo.CurrentCulture,
+ "{0}; {1}",
+ Loc.Instance["ScheduledTasks.Trigger.Logon"],
+ string.Format(
+ CultureInfo.CurrentCulture,
+ Loc.Instance["ScheduledTasks.TriggerDetail.Daily"],
+ "1",
+ "9:00 AM"
+ )
+ ),
+ model.TriggerSummary
+ );
+ }
+
+ [Fact]
+ public void TriggerTypes_AfterCultureChange_ResolveInNewLanguage()
+ {
+ var original = Loc.CurrentCulture;
+ try
+ {
+ var model = new ScheduledTaskModel
+ {
+ Name = "T",
+ Path = "\\",
+ FullPath = "\\T",
+ TriggerInfos = [new("ScheduledTasks.Trigger.Boot", null, [], null)],
+ };
+
+ Loc.Instance.ChangeCulture(new CultureInfo("vi"));
+ var vi = model.TriggerTypes[0];
+
+ Loc.Instance.ChangeCulture(new CultureInfo("en-US"));
+ var en = model.TriggerTypes[0];
+
+ // Keys exist in resx; the resolved text must not be the raw key or a raw ToString.
+ Assert.DoesNotContain("ScheduledTasks.Trigger.Boot", vi);
+ Assert.DoesNotContain("ScheduledTasks.Trigger.Boot", en);
+ Assert.NotEqual("Boot", vi);
+ }
+ finally
+ {
+ Loc.Instance.ChangeCulture(original);
+ }
+ }
+
+ [Fact]
+ public void TriggerSummary_DetailNarratesTriggerData()
+ {
+ var model = new ScheduledTaskModel
+ {
+ Name = "T",
+ Path = "\\",
+ FullPath = "\\T",
+ TriggerInfos =
+ [
+ new(
+ "ScheduledTasks.Trigger.Daily",
+ "ScheduledTasks.TriggerDetail.Daily",
+ ["1", "9:00 AM"],
+ null
+ ),
+ ],
+ };
+
+ var expected = string.Format(
+ CultureInfo.CurrentCulture,
+ Loc.Instance["ScheduledTasks.TriggerDetail.Daily"],
+ "1",
+ "9:00 AM"
+ );
+ Assert.Equal(expected, model.TriggerSummary);
+ }
+
+ [Fact]
+ public void TriggerSummary_RawFallbackUsedOnlyWhenNoLocalizationFits()
+ {
+ var model = new ScheduledTaskModel
+ {
+ Name = "T",
+ Path = "\\",
+ FullPath = "\\T",
+ TriggerInfos =
+ [
+ new("ScheduledTasks.Trigger.Event", null, [], "On workstation unlock"),
+ new(
+ "ScheduledTasks.Trigger.Time",
+ "ScheduledTasks.TriggerDetail.Time",
+ ["x"],
+ null
+ ),
+ ],
+ };
+
+ var expectedTime = string.Format(
+ CultureInfo.CurrentCulture,
+ Loc.Instance["ScheduledTasks.TriggerDetail.Time"],
+ "x"
+ );
+ Assert.Equal($"On workstation unlock; {expectedTime}", model.TriggerSummary);
+ Assert.Equal(Loc.Instance["ScheduledTasks.Trigger.Event"], model.TriggerTypes[0]);
+ }
+
+ [Fact]
+ public void TriggerSummary_RepetitionAppendedFromOwnTemplate()
+ {
+ var model = new ScheduledTaskModel
+ {
+ Name = "T",
+ Path = "\\",
+ FullPath = "\\T",
+ TriggerInfos =
+ [
+ new(
+ "ScheduledTasks.Trigger.Daily",
+ "ScheduledTasks.TriggerDetail.Daily",
+ ["1", "9:00 AM"],
+ null,
+ "ScheduledTasks.TriggerDetail.Repeat",
+ ["00:10:00"]
+ ),
+ ],
+ };
+
+ var expected =
+ string.Format(
+ CultureInfo.CurrentCulture,
+ Loc.Instance["ScheduledTasks.TriggerDetail.Daily"],
+ "1",
+ "9:00 AM"
+ )
+ + string.Format(
+ CultureInfo.CurrentCulture,
+ Loc.Instance["ScheduledTasks.TriggerDetail.Repeat"],
+ "00:10:00"
+ );
+ Assert.Equal(expected, model.TriggerSummary);
+ // Badges stay short labels; the repetition lives in the summary only.
+ Assert.Equal([Loc.Instance["ScheduledTasks.Trigger.Daily"]], model.TriggerTypes);
+ }
+}
diff --git a/optimizerDuck.Test/Domain/Revert/Steps/ServiceRevertStepTests.cs b/optimizerDuck.Test/Domain/Revert/Steps/ServiceRevertStepTests.cs
new file mode 100644
index 0000000..6def822
--- /dev/null
+++ b/optimizerDuck.Test/Domain/Revert/Steps/ServiceRevertStepTests.cs
@@ -0,0 +1,25 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Domain.Optimizations.Models.Services;
+using optimizerDuck.Domain.Revert.Steps;
+using optimizerDuck.Test.TestDoubles;
+
+namespace optimizerDuck.Test.Domain.Revert.Steps;
+
+public class ServiceRevertStepTests
+{
+ [Fact]
+ public async Task ExecuteAsync_MissingService_ReturnsTrueWithoutThrowing()
+ {
+ // A service that no longer exists has nothing to restore: revert must
+ // succeed instead of throwing on the unverifiable query.
+ var step = new ServiceRevertStep
+ {
+ ServiceName = $"optimizerDuck_Test_Missing_{Guid.NewGuid():N}",
+ OriginalStartupType = ServiceStartupType.Manual,
+ };
+
+ var result = await step.ExecuteAsync(TestShell.New(), NullLogger.Instance);
+
+ Assert.True(result);
+ }
+}
diff --git a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
index 4b5a6f8..11c0a7c 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
@@ -50,6 +50,63 @@ public class RegistryServiceTests : IDisposable
Assert.Null(result);
}
+ [Fact]
+ public void TryKeyExists_ExistingKey_ReturnsTrueWithExists()
+ {
+ var path = $@"{BaseTestKey}\TryExists";
+ Assert.True(RegistryService.Write(NewCall(), new RegistryItem(path, "V", 1)).Ok);
+
+ Assert.True(RegistryService.TryKeyExists(new RegistryItem(path), out var exists));
+ Assert.True(exists);
+ }
+
+ [Fact]
+ public void TryKeyExists_AbsentKey_ReturnsTrueWithNotExists()
+ {
+ var path = $@"{BaseTestKey}\TryExistsAbsent";
+
+ // A successfully-answered query for a missing key reports "does not exist", not failure.
+ Assert.True(RegistryService.TryKeyExists(new RegistryItem(path), out var exists));
+ Assert.False(exists);
+ }
+
+ [Fact]
+ public void TryKeyExists_UnknownRoot_ReturnsQueryFailure()
+ {
+ // An unparseable root is a failed query, not an absent key.
+ Assert.False(RegistryService.TryKeyExists(new RegistryItem("BADROOT\\X"), out _));
+ }
+
+ [Fact]
+ public void TryReadValue_PresentValue_ReturnsTrueWithValue()
+ {
+ var path = $@"{BaseTestKey}\TryRead";
+ Assert.True(RegistryService.Write(NewCall(), new RegistryItem(path, "V", 42)).Ok);
+
+ Assert.True(RegistryService.TryReadValue(new RegistryItem(path, "V"), out var value));
+ Assert.Equal(42, value);
+ }
+
+ [Fact]
+ public void TryReadValue_AbsentValue_ReturnsTrueWithNull()
+ {
+ var path = $@"{BaseTestKey}\TryReadAbsent";
+ Assert.True(RegistryService.Write(NewCall(), new RegistryItem(path, "Other", 1)).Ok);
+
+ // The key exists but the value is absent: a successful read reporting "no value".
+ Assert.True(RegistryService.TryReadValue(new RegistryItem(path, "V"), out var value));
+ Assert.Null(value);
+ }
+
+ [Fact]
+ public void TryReadValue_UnknownRoot_ReturnsQueryFailure()
+ {
+ Assert.False(
+ RegistryService.TryReadValue(new RegistryItem("BADROOT\\X", "V"), out var value)
+ );
+ Assert.Null(value);
+ }
+
[Fact]
public void DeleteValue_WithInvalidRoot_ReturnsFalse()
{
diff --git a/optimizerDuck.Test/Services/OptimizationServices/ScheduledTaskServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/ScheduledTaskServiceTests.cs
new file mode 100644
index 0000000..9011f42
--- /dev/null
+++ b/optimizerDuck.Test/Services/OptimizationServices/ScheduledTaskServiceTests.cs
@@ -0,0 +1,20 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Domain.Optimizations.Models.ScheduledTask;
+using optimizerDuck.Services.Optimization.Providers;
+
+namespace optimizerDuck.Test.Services.OptimizationServices;
+
+public class ScheduledTaskServiceTests
+{
+ [Fact]
+ public void GetTaskEnabledState_NonExistentRootTask_ReportsNotFound()
+ {
+ // Under the always-present root folder a missing task must be reported as
+ // "not found" rather than "disabled" or "query failed".
+ var path = $"\\optimizerDuck_Test_Missing_{Guid.NewGuid():N}";
+
+ var state = ScheduledTaskService.GetTaskEnabledState(path, NullLogger.Instance);
+
+ Assert.Equal(TaskEnabledState.NotFound, state);
+ }
+}
diff --git a/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs b/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs
index ffa383b..4183f08 100644
--- a/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs
+++ b/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs
@@ -121,4 +121,24 @@ public class DiskCleanupServiceTests
}
}
}
+
+ [Fact]
+ public async Task CleanAsync_FailingCommand_ReportsNoFreedBytes()
+ {
+ var service = NewService();
+ var item = new CleanupItem
+ {
+ Id = "Command",
+ NameKey = "Temp Files",
+ DescriptionKey = "Temp Description",
+ Path = "exit 1",
+ Icon = SymbolRegular.Document24,
+ IsCommand = true,
+ SizeBytes = 4096,
+ };
+
+ var freed = await service.CleanAsync(item);
+
+ Assert.Equal(0, freed);
+ }
}
diff --git a/optimizerDuck.Test/Services/UI/StartupManagerServiceTests.cs b/optimizerDuck.Test/Services/UI/StartupManagerServiceTests.cs
new file mode 100644
index 0000000..cb691b5
--- /dev/null
+++ b/optimizerDuck.Test/Services/UI/StartupManagerServiceTests.cs
@@ -0,0 +1,42 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Domain.Optimizations.Models.StartupManager;
+using optimizerDuck.Services.UI;
+
+namespace optimizerDuck.Test.Services.UI;
+
+public class StartupManagerServiceTests
+{
+ [Fact]
+ public async Task ToggleStartupApp_UnsupportedLocation_ReturnsFailure()
+ {
+ var service = new StartupManagerService(NullLogger<StartupManagerService>.Instance);
+ var app = new StartupApp
+ {
+ Name = "Test App",
+ Location = StartupAppLocation.RegistryHKCURun,
+ PathOrKey = "NoBackslashHere",
+ };
+
+ var result = await service.ToggleStartupApp(app, true);
+
+ Assert.False(result.Ok);
+ Assert.NotNull(result.Error);
+ }
+
+ [Fact]
+ public async Task ToggleStartupTask_MissingTask_ReturnsFailure()
+ {
+ // A toggle for a task that does not exist must report failure, never log success.
+ var service = new StartupManagerService(NullLogger<StartupManagerService>.Instance);
+ var task = new StartupTask
+ {
+ TaskName = $"optimizerDuck_Test_Missing_{Guid.NewGuid():N}",
+ TaskPath = "\\",
+ };
+
+ var result = await service.ToggleStartupTask(task, true);
+
+ Assert.False(result.Ok);
+ Assert.NotNull(result.Error);
+ }
+}
diff --git a/optimizerDuck/Domain/Conditions/BuiltIn/RegistryKeyExistsCondition.cs b/optimizerDuck/Domain/Conditions/BuiltIn/RegistryKeyExistsCondition.cs
index 1c5ed8d..797a3fb 100644
--- a/optimizerDuck/Domain/Conditions/BuiltIn/RegistryKeyExistsCondition.cs
+++ b/optimizerDuck/Domain/Conditions/BuiltIn/RegistryKeyExistsCondition.cs
@@ -21,8 +21,11 @@ public abstract class RegistryKeyExistsCondition : ConditionBase
/// <summary>Strongly-typed localized failure description.</summary>
protected abstract Func<string> Description { get; }
- public override ConditionResult Evaluate(SystemSnapshot snapshot) =>
- RegistryService.KeyExists(RegistryItem)
- ? ConditionResult.Available
- : ConditionResult.Unsupported(Title, Description);
+ public override ConditionResult Evaluate(SystemSnapshot snapshot)
+ {
+ if (!RegistryService.TryKeyExists(RegistryItem, out var exists))
+ return ConditionResult.Error();
+
+ return exists ? ConditionResult.Available : ConditionResult.Unsupported(Title, Description);
+ }
}
diff --git a/optimizerDuck/Domain/Conditions/BuiltIn/ServiceExistsCondition.cs b/optimizerDuck/Domain/Conditions/BuiltIn/ServiceExistsCondition.cs
index de872f7..1fca06f 100644
--- a/optimizerDuck/Domain/Conditions/BuiltIn/ServiceExistsCondition.cs
+++ b/optimizerDuck/Domain/Conditions/BuiltIn/ServiceExistsCondition.cs
@@ -23,8 +23,9 @@ public abstract class ServiceExistsCondition : ConditionBase
public override ConditionResult Evaluate(SystemSnapshot snapshot)
{
var serviceKey = new RegistryItem($@"HKLM\SYSTEM\CurrentControlSet\Services\{ServiceName}");
- return RegistryService.KeyExists(serviceKey)
- ? ConditionResult.Available
- : ConditionResult.Unsupported(Title, Description);
+ if (!RegistryService.TryKeyExists(serviceKey, out var exists))
+ return ConditionResult.Error();
+
+ return exists ? ConditionResult.Available : ConditionResult.Unsupported(Title, Description);
}
}
diff --git a/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs b/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs
index 7aaaf3e..6470dcc 100644
--- a/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs
+++ b/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs
@@ -83,7 +83,9 @@ public abstract partial class BaseCustomizeSetting : LocalizedObject, ICustomize
return null;
var resolution = ResolveDropdownValue(options);
- return resolution.Matched ? resolution.Value : resolution.Value ?? MissingValueSentinel;
+ return resolution.Matched
+ ? resolution.Value
+ : FallbackValueFor(options, resolution.Value);
}
}
@@ -106,17 +108,40 @@ public abstract partial class BaseCustomizeSetting : LocalizedObject, ICustomize
if (resolution.Matched)
return options;
- // A partial multi-binding match can surface a raw value that already equals a
- // declared option's Value. Appending "Custom" then would duplicate that Value,
- // which makes SelectedValuePath="Value" selection ambiguous, so skip it.
- var displayValue = resolution.Value ?? MissingValueSentinel;
- if (options.Any(o => ValuesEqual(o.Value, displayValue)))
- return options;
-
- return [.. options, CreateCustomOption(displayValue)];
+ return [.. options, CreateCustomOption(FallbackValueFor(options, resolution.Value))];
}
}
+ /// <summary>
+ /// Fallback selection value: the raw registry value, wrapped in a distinct instance
+ /// when it collides with a declared option so a mixed state still shows as "Custom".
+ /// </summary>
+ private object FallbackValueFor(IReadOnlyList<SettingOption> options, object? raw)
+ {
+ if (raw is null)
+ return MissingValueSentinel;
+
+ if (!options.Any(o => ValuesEqual(o.Value, raw)))
+ return raw;
+
+ if (_outOfScope is null || !ValuesEqual(_outOfScope.RawValue, raw))
+ _outOfScope = new OutOfScopeValue(raw);
+
+ return _outOfScope;
+ }
+
+ private OutOfScopeValue? _outOfScope;
+
+ /// <summary>
+ /// Distinct fallback identity that never value-matches a declared option.
+ /// </summary>
+ private sealed class OutOfScopeValue(object rawValue)
+ {
+ public object RawValue { get; } = rawValue;
+
+ public override string ToString() => $"<custom:{RawValue}>";
+ }
+
/// <summary>
/// Stable, non-null sentinel used as the fallback option's value when the registry
/// value is missing entirely, so WPF can render a selection (null values cannot be
@@ -124,19 +149,13 @@ public abstract partial class BaseCustomizeSetting : LocalizedObject, ICustomize
/// </summary>
internal static readonly object MissingValueSentinel = new();
- /// <summary>
- /// Creates the fallback option shown when the current registry value is outside
- /// the declared options. When the value is missing entirely
- /// (<paramref name="rawValue"/> is <see cref="MissingValueSentinel"/>), a distinct
- /// "Not set" label is used; otherwise the generic "Custom" label shows the actual
- /// out-of-scope value.
- /// </summary>
- private static SettingOption CreateCustomOption(object rawValue) =>
+ /// <summary>Creates the fallback option: "Not set" when the value is missing, else "Custom".</summary>
+ private static SettingOption CreateCustomOption(object value) =>
new(
- ReferenceEquals(rawValue, MissingValueSentinel)
+ ReferenceEquals(value, MissingValueSentinel)
? Loc.Instance[CustomOptionNotSetTranslationKey]
: Loc.Instance[CustomOptionTranslationKey],
- rawValue
+ value
);
/// <summary>The translation key used for the synthetic "Custom" option label.</summary>
@@ -232,10 +251,10 @@ public abstract partial class BaseCustomizeSetting : LocalizedObject, ICustomize
}
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 => ValuesEqual(o.Value, value));
+ // identity first, so a fallback selection never resolves to a declared option.
+ var option =
+ options.FirstOrDefault(o => ReferenceEquals(o.Value, value))
+ ?? options.FirstOrDefault(o => ValuesEqual(o.Value, value));
if (option?.Bindings is { Count: > 0 })
{
// Split by action, then batch: a binding with no value deletes the value.
@@ -259,7 +278,8 @@ public abstract partial class BaseCustomizeSetting : LocalizedObject, ICustomize
}
}
- if (NeedsPostAction)
+ // a refresh after a failed write would mask the failure.
+ if (NeedsPostAction && firstFailure is null)
await ExecutePostActionAsync();
return firstFailure ?? OpResult.Success();
diff --git a/optimizerDuck/Domain/Execution/OpResult.cs b/optimizerDuck/Domain/Execution/OpResult.cs
index e2267d4..455b41c 100644
--- a/optimizerDuck/Domain/Execution/OpResult.cs
+++ b/optimizerDuck/Domain/Execution/OpResult.cs
@@ -25,7 +25,7 @@ public sealed record OpResult(
/// <summary>
/// Aggregates a batch of results: the first failure wins, otherwise success.
- /// Callers must materialise <paramref name="results"/> first — a lazy sequence
+ /// 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)
diff --git a/optimizerDuck/Domain/Optimizations/Categories/Gpu.cs b/optimizerDuck/Domain/Optimizations/Categories/Gpu.cs
index b3cf029..f24039d 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/Gpu.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/Gpu.cs
@@ -114,7 +114,7 @@ public class Gpu : LocalizedObject, IOptimizationCategory
/// </code>
/// </example>
/// <exception cref="ArgumentNullException">
- /// Thrown if <paramref name="deviceId" /> is <c>null</c> — but this method uses <c>string.IsNullOrWhiteSpace</c>
+ /// Thrown if <paramref name="deviceId" /> is <c>null</c>, but this method uses <c>string.IsNullOrWhiteSpace</c>
/// and returns <c>false</c> instead for consistency with TryParse pattern.
/// </exception>
/// <seealso cref="GpuInfo.DeviceId" />
diff --git a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
index e1ac539..695ba48 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
@@ -38,13 +38,23 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
OptimizationContext context
)
{
- var wasEnabled =
- RegistryService.Read<int>(
- new RegistryItem(
- @"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power",
- "HibernateEnabled"
- )
- ) != 0;
+ var hibernateItem = new RegistryItem(
+ @"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power",
+ "HibernateEnabled"
+ );
+
+ // default to restoring hibernation on when the previous state is unknown.
+ var wasEnabled = true;
+ if (RegistryService.TryReadValue(hibernateItem, out var hibernateValue, context.Logger))
+ wasEnabled = hibernateValue switch
+ {
+ null => true,
+ int value => value != 0,
+ long value => value != 0,
+ string value => value != "0",
+ _ => true,
+ };
+
string revertCommand = wasEnabled ? "powercfg /h on" : "powercfg /h off";
await context.Shell.CMDAsync("powercfg /h off", context, revertCommand);
diff --git a/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs b/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs
index fca6944..e983c82 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs
@@ -6,6 +6,7 @@ using optimizerDuck.Domain.Attributes;
using optimizerDuck.Domain.Conditions;
using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.Optimizations.Models.ScheduledTask;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.UI;
using optimizerDuck.Services.Configuration;
@@ -165,7 +166,9 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
foreach (var task in tasksToDelete)
{
- if (!ScheduledTaskService.IsTaskEnabled(task, context.Logger))
+ var state = ScheduledTaskService.GetTaskEnabledState(task, context.Logger);
+ // skip when known-disabled or absent; on unknown state, attempt so the outcome is real.
+ if (state is TaskEnabledState.Disabled or TaskEnabledState.NotFound)
continue;
ScheduledTaskService.DisableTask(context, task);
}
@@ -218,7 +221,8 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
foreach (var task in tasksToDelete)
{
- if (!ScheduledTaskService.IsTaskEnabled(task, context.Logger))
+ var state = ScheduledTaskService.GetTaskEnabledState(task, context.Logger);
+ if (state is TaskEnabledState.Disabled or TaskEnabledState.NotFound)
continue;
ScheduledTaskService.DisableTask(context, task);
}
@@ -476,16 +480,10 @@ public class SecurityAndPrivacy : LocalizedObject, IOptimizationCategory
)
);
- if (
- ScheduledTaskService.IsTaskEnabled(
- @"\Microsoft\Windows\Maps\MapsUpdateTask",
- context.Logger
- )
- )
- ScheduledTaskService.DisableTask(
- context,
- @"\Microsoft\Windows\Maps\MapsUpdateTask"
- );
+ const string mapsTask = @"\Microsoft\Windows\Maps\MapsUpdateTask";
+ var mapsState = ScheduledTaskService.GetTaskEnabledState(mapsTask, context.Logger);
+ if (mapsState is not (TaskEnabledState.Disabled or TaskEnabledState.NotFound))
+ ScheduledTaskService.DisableTask(context, mapsTask);
context.Logger.LogInformation(
"Disabled location tracking, sensors and offline maps updates"
diff --git a/optimizerDuck/Domain/Optimizations/Models/ScheduledTask/ScheduledTaskModel.cs b/optimizerDuck/Domain/Optimizations/Models/ScheduledTask/ScheduledTaskModel.cs
index 47f91ef..799a5ca 100644
--- a/optimizerDuck/Domain/Optimizations/Models/ScheduledTask/ScheduledTaskModel.cs
+++ b/optimizerDuck/Domain/Optimizations/Models/ScheduledTask/ScheduledTaskModel.cs
@@ -1,4 +1,3 @@
-using System.Collections.ObjectModel;
using System.Windows.Media;
using CommunityToolkit.Mvvm.ComponentModel;
using optimizerDuck.Common.Extensions;
@@ -70,19 +69,26 @@ public partial class ScheduledTaskModel : LocalizedObject
public string? Author { get; init; }
/// <summary>
- /// Summary of when the task triggers.
+ /// Display data of the task's triggers. Badges show
+ /// <see cref="ScheduledTaskTriggerInfo.Label"/>; the summary joins
+ /// <see cref="ScheduledTaskTriggerInfo.Detail"/>.
/// </summary>
- public string TriggerSummary { get; init; } = string.Empty;
+ public IReadOnlyList<ScheduledTaskTriggerInfo> TriggerInfos { get; init; } = [];
/// <summary>
- /// Summary of the task's action.
+ /// Localized trigger labels for badge display (e.g. "At log on", "Daily").
/// </summary>
- public string ActionSummary { get; init; } = string.Empty;
+ public IReadOnlyList<string> TriggerTypes => TriggerInfos.Select(t => t.Label).ToList();
/// <summary>
- /// Individual trigger type strings for badge display (e.g. "At log on", "At startup", "Daily at 09:00").
+ /// Localized summary of when the task triggers, keeping each trigger's data.
/// </summary>
- public ObservableCollection<string> TriggerTypes { get; init; } = [];
+ public string TriggerSummary => string.Join("; ", TriggerInfos.Select(t => t.Detail));
+
+ /// <summary>
+ /// Summary of the task's action.
+ /// </summary>
+ public string ActionSummary { get; init; } = string.Empty;
/// <summary>
/// The last time the task ran.
diff --git a/optimizerDuck/Domain/Optimizations/Models/ScheduledTask/ScheduledTaskTriggerInfo.cs b/optimizerDuck/Domain/Optimizations/Models/ScheduledTask/ScheduledTaskTriggerInfo.cs
new file mode 100644
index 0000000..351854a
--- /dev/null
+++ b/optimizerDuck/Domain/Optimizations/Models/ScheduledTask/ScheduledTaskTriggerInfo.cs
@@ -0,0 +1,39 @@
+using System.Globalization;
+using optimizerDuck.Services.Configuration;
+
+namespace optimizerDuck.Domain.Optimizations.Models.ScheduledTask;
+
+/// <summary>
+/// Display data for one scheduled-task trigger: a localized label plus a narrated
+/// detail with the trigger's own data. Falls back to raw library text only when no
+/// localization fits; appends the repetition schedule when present.
+/// </summary>
+public sealed record ScheduledTaskTriggerInfo(
+ string LabelKey,
+ string? DetailKey,
+ string[] Args,
+ string? Raw,
+ string? RepeatKey = null,
+ string[]? RepeatArgs = null
+)
+{
+ public string Label => Loc.Instance[LabelKey];
+
+ public string Detail
+ {
+ get
+ {
+ var text = DetailKey is null
+ ? Raw ?? Label
+ : string.Format(CultureInfo.CurrentCulture, Loc.Instance[DetailKey], [.. Args]);
+ return RepeatKey is null
+ ? text
+ : text
+ + string.Format(
+ CultureInfo.CurrentCulture,
+ Loc.Instance[RepeatKey],
+ [.. (RepeatArgs ?? [])]
+ );
+ }
+ }
+}
diff --git a/optimizerDuck/Domain/Optimizations/Models/ScheduledTask/TaskEnabledState.cs b/optimizerDuck/Domain/Optimizations/Models/ScheduledTask/TaskEnabledState.cs
new file mode 100644
index 0000000..f58978b
--- /dev/null
+++ b/optimizerDuck/Domain/Optimizations/Models/ScheduledTask/TaskEnabledState.cs
@@ -0,0 +1,13 @@
+namespace optimizerDuck.Domain.Optimizations.Models.ScheduledTask;
+
+/// <summary>Outcome of reading a scheduled task's enabled state.</summary>
+public enum TaskEnabledState
+{
+ Enabled,
+
+ Disabled,
+
+ NotFound,
+
+ Unknown,
+}
diff --git a/optimizerDuck/Domain/Optimizations/Models/Services/ShellPolicy.cs b/optimizerDuck/Domain/Optimizations/Models/Services/ShellPolicy.cs
index 6665793..8736c76 100644
--- a/optimizerDuck/Domain/Optimizations/Models/Services/ShellPolicy.cs
+++ b/optimizerDuck/Domain/Optimizations/Models/Services/ShellPolicy.cs
@@ -16,9 +16,8 @@ public sealed class ShellPolicy
/// <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
+ r.ExitCode == -1 ? Loc.Instance["Service.Shell.Error.TimedOut"]
+ : string.IsNullOrWhiteSpace(r.Stderr)
? Loc.Instance["Service.Shell.Error.ExitCode", r.ExitCode]
: r.Stderr;
diff --git a/optimizerDuck/Domain/Optimizations/Models/StartupManager/StartupTask.cs b/optimizerDuck/Domain/Optimizations/Models/StartupManager/StartupTask.cs
index 91fd9e0..fbc0d16 100644
--- a/optimizerDuck/Domain/Optimizations/Models/StartupManager/StartupTask.cs
+++ b/optimizerDuck/Domain/Optimizations/Models/StartupManager/StartupTask.cs
@@ -1,12 +1,15 @@
using System.Windows.Media;
using CommunityToolkit.Mvvm.ComponentModel;
+using optimizerDuck.Common.Extensions;
+using optimizerDuck.Domain.Optimizations.Models.ScheduledTask;
+using optimizerDuck.Services.Configuration;
namespace optimizerDuck.Domain.Optimizations.Models.StartupManager;
/// <summary>
/// Represents a scheduled task that runs at startup.
/// </summary>
-public partial class StartupTask : ObservableObject
+public partial class StartupTask : LocalizedObject
{
/// <summary>
/// Indicates whether the task is enabled.
@@ -36,14 +39,19 @@ public partial class StartupTask : ObservableObject
public string? Description { get; init; }
/// <summary>
- /// Summary of when the task triggers.
+ /// Display data of the task's triggers (labels re-resolve on language change).
/// </summary>
- public string? TriggerSummary { get; init; }
+ public IReadOnlyList<ScheduledTaskTriggerInfo> TriggerInfos { get; init; } = [];
/// <summary>
- /// The types of triggers (e.g., "At logon", "At startup").
+ /// Localized trigger labels for badge display (e.g. "At log on", "At startup").
/// </summary>
- public List<string> TriggerTypes { get; init; } = [];
+ public IReadOnlyList<string> TriggerTypes => TriggerInfos.Select(t => t.Label).ToList();
+
+ /// <summary>
+ /// Localized summary of when the task triggers.
+ /// </summary>
+ public string TriggerSummary => string.Join("; ", TriggerInfos.Select(t => t.Detail));
/// <summary>
/// Summary of what the task does.
diff --git a/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs
index d45fac6..b6d305d 100644
--- a/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs
+++ b/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs
@@ -255,7 +255,11 @@ public class RegistryRevertStep : IRevertStep
case RevertAction.RestorePrevious when Value != null:
{
var item = new RegistryItem(Path, Name!);
- var actual = RegistryService.Read<object>(item, call.Logger);
+ if (!RegistryService.TryReadValue(item, out var actual, call.Logger))
+ throw new StepExecutionException(
+ $"Registry verify failed at {Path}:{Name}: could not read the value.",
+ null
+ );
if (!ValuesEqual(actual, Value, Kind))
throw new StepExecutionException(
$"Registry verify failed at {Path}:{Name}: expected '{Value}', actual '{actual}'",
@@ -266,11 +270,18 @@ public class RegistryRevertStep : IRevertStep
case RevertAction.NoPreviousValue:
case RevertAction.RestorePrevious:
{
- // Value must be absent after delete.
- var actual = RegistryService.Read<object>(
- new RegistryItem(Path, Name!),
- call.Logger
- );
+ // a failed read is not "absent".
+ if (
+ !RegistryService.TryReadValue(
+ new RegistryItem(Path, Name!),
+ out var actual,
+ call.Logger
+ )
+ )
+ throw new StepExecutionException(
+ $"Registry verify failed at {Path}:{Name}: could not read the value.",
+ null
+ );
if (actual != null)
throw new StepExecutionException(
$"Registry verify failed at {Path}:{Name}: expected '<absent>', actual '{actual}'",
@@ -279,14 +290,36 @@ public class RegistryRevertStep : IRevertStep
break;
}
case RevertAction.RestoreKey:
- if (!RegistryService.KeyExists(new RegistryItem(Path), call.Logger))
+ if (
+ !RegistryService.TryKeyExists(
+ new RegistryItem(Path),
+ out var restoreExists,
+ call.Logger
+ )
+ )
+ throw new StepExecutionException(
+ $"Registry verify failed at {Path}: could not query the key.",
+ null
+ );
+ if (!restoreExists)
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))
+ if (
+ !RegistryService.TryKeyExists(
+ new RegistryItem(Path),
+ out var deleteExists,
+ call.Logger
+ )
+ )
+ throw new StepExecutionException(
+ $"Registry verify failed at {Path}: could not query the key.",
+ null
+ );
+ if (deleteExists)
throw new StepExecutionException(
$"Registry verify failed at {Path}: expected key to be absent, but it still exists",
null
diff --git a/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs
index 301c892..94a3683 100644
--- a/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs
+++ b/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs
@@ -3,7 +3,7 @@ using Newtonsoft.Json.Linq;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Exceptions;
using optimizerDuck.Domain.Execution;
-using optimizerDuck.Resources.Languages;
+using optimizerDuck.Domain.Optimizations.Models.ScheduledTask;
using optimizerDuck.Services.Configuration;
using optimizerDuck.Services.Optimization.Providers;
@@ -44,11 +44,18 @@ public class ScheduledTaskRevertStep : IRevertStep
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)
+ // a missing task has nothing to restore; anything else must verify positively.
+ var state = ScheduledTaskService.GetTaskEnabledState(FullPath, opCall.Logger);
+ if (state is TaskEnabledState.NotFound)
+ return Task.FromResult(true);
+ if (state is not (TaskEnabledState.Enabled or TaskEnabledState.Disabled))
throw new StepExecutionException(
- $"Scheduled task verify failed at {FullPath}: expected enabled={OriginalEnabled}, actual={actualState}",
+ $"Scheduled task verify failed at {FullPath}: could not query the task state.",
+ null
+ );
+ if ((state == TaskEnabledState.Enabled) != OriginalEnabled)
+ throw new StepExecutionException(
+ $"Scheduled task verify failed at {FullPath}: expected enabled={OriginalEnabled}, actual={state == TaskEnabledState.Enabled}",
null
);
diff --git a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs
index 14dd550..1488738 100644
--- a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs
+++ b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs
@@ -56,13 +56,24 @@ public class ServiceRevertStep : IRevertStep
throw new StepExecutionException(result.Error ?? Description, result.ErrorDetail);
}
- // Read-back verify: service must report the restored startup type afterward.
- var (actual, _) = await ServiceProcessService
+ var (actual, notFound) = await ServiceProcessService
.GetStartupTypeAsync(ServiceName, opCall.Logger)
.ConfigureAwait(false);
- if (actual != null && actual.Value != OriginalStartupType)
+
+ // a missing service has nothing to restore.
+ if (notFound)
+ return true;
+
+ // null without NotFound means the query failed; never report an unverified restore.
+ if (actual is null)
+ throw new StepExecutionException(
+ $"Service verify failed for {ServiceName}: could not query the current startup type.",
+ null
+ );
+
+ if (actual.Value != OriginalStartupType)
throw new StepExecutionException(
- $"Service verify failed for {ServiceName}: expected {OriginalStartupType}, actual={actual}",
+ $"Service verify failed for {ServiceName}: expected {OriginalStartupType}, actual={actual.Value}",
null
);
return true;
diff --git a/optimizerDuck/Domain/UI/OptimizationState.cs b/optimizerDuck/Domain/UI/OptimizationState.cs
index 326ed8a..3e84dd7 100644
--- a/optimizerDuck/Domain/UI/OptimizationState.cs
+++ b/optimizerDuck/Domain/UI/OptimizationState.cs
@@ -81,12 +81,12 @@ public partial class OptimizationState : ObservableObject
// Defer timer creation to avoid accessing dispatcher during static init.
// NOTE: This type lives in Domain/UI but owns a DispatcherTimer (WPF). Ideally
- // move to optimizerDuck.UI or Common — kept here to avoid churn. We route
+ // move to optimizerDuck.UI or Common. We route
// through the dispatcher indirection rather than hard-referencing UI assemblies
// from pure domain logic.
var dispatcher = System.Windows.Application.Current?.Dispatcher;
if (dispatcher is null)
- return; // headless/tests — no timer needed
+ return; // headless/tests, no timer needed
_ = dispatcher.InvokeAsync(() =>
{
lock (_lock)
diff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resx
index 9500ae1..542ff27 100644
--- a/optimizerDuck/Resources/Languages/Translations.resx
+++ b/optimizerDuck/Resources/Languages/Translations.resx
@@ -2006,4 +2006,115 @@ Update now to enjoy the latest features, improvements, and bug fixes.</value>
<data name="ScheduledTasks.State.Queued" xml:space="preserve">
<value>Queued</value>
</data>
-</root>
\ No newline at end of file
+ <data name="Common.SortBy.RiskAndStatus" xml:space="preserve">
+ <value>Risk &amp; Status</value>
+ </data>
+ <data name="Dashboard.SystemInfo.Ram.Total" xml:space="preserve">
+ <value>{0} GB RAM</value>
+ </data>
+ <data name="Dashboard.SystemInfo.Gpu.Memory" xml:space="preserve">
+ <value>{0} GB</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Event" xml:space="preserve">
+ <value>On event</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Time" xml:space="preserve">
+ <value>At a specific time</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Daily" xml:space="preserve">
+ <value>Daily</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Weekly" xml:space="preserve">
+ <value>Weekly</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Monthly" xml:space="preserve">
+ <value>Monthly</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.MonthlyDOW" xml:space="preserve">
+ <value>Monthly</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Idle" xml:space="preserve">
+ <value>When idle</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Registration" xml:space="preserve">
+ <value>At registration</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Boot" xml:space="preserve">
+ <value>At startup</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Logon" xml:space="preserve">
+ <value>At log on</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.SessionStateChange" xml:space="preserve">
+ <value>On session change</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Other" xml:space="preserve">
+ <value>Trigger</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Session.Lock" xml:space="preserve">
+ <value>Session lock</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Session.Unlock" xml:space="preserve">
+ <value>Session unlock</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Session.ConsoleConnect" xml:space="preserve">
+ <value>Console connect</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Session.ConsoleDisconnect" xml:space="preserve">
+ <value>Console disconnect</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Session.RemoteConnect" xml:space="preserve">
+ <value>Remote connect</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Session.RemoteDisconnect" xml:space="preserve">
+ <value>Remote disconnect</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Week.First" xml:space="preserve">
+ <value>first</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Week.Second" xml:space="preserve">
+ <value>second</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Week.Third" xml:space="preserve">
+ <value>third</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Week.Fourth" xml:space="preserve">
+ <value>fourth</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Week.Last" xml:space="preserve">
+ <value>last</value>
+ </data>
+ <data name="ScheduledTasks.Trigger.Week.Every" xml:space="preserve">
+ <value>every</value>
+ </data>
+ <data name="ScheduledTasks.TriggerDetail.Time" xml:space="preserve">
+ <value>At {0}</value>
+ </data>
+ <data name="ScheduledTasks.TriggerDetail.Daily" xml:space="preserve">
+ <value>Every {0} day(s), at {1}</value>
+ </data>
+ <data name="ScheduledTasks.TriggerDetail.Weekly" xml:space="preserve">
+ <value>Every {0} week(s) on {1}, at {2}</value>
+ </data>
+ <data name="ScheduledTasks.TriggerDetail.Monthly" xml:space="preserve">
+ <value>On day(s) {0} of {1}</value>
+ </data>
+ <data name="ScheduledTasks.TriggerDetail.MonthlyDOW" xml:space="preserve">
+ <value>{0} {1} of {2}</value>
+ </data>
+ <data name="ScheduledTasks.TriggerDetail.User" xml:space="preserve">
+ <value>for user {0}</value>
+ </data>
+ <data name="ScheduledTasks.TriggerDetail.UserDelay" xml:space="preserve">
+ <value>for user {0} after {1}</value>
+ </data>
+ <data name="ScheduledTasks.TriggerDetail.Delay" xml:space="preserve">
+ <value>after {0}</value>
+ </data>
+ <data name="ScheduledTasks.TriggerDetail.Repeat" xml:space="preserve">
+ <value> (repeat every {0})</value>
+ </data>
+ <data name="ScheduledTasks.TriggerDetail.RepeatFor" xml:space="preserve">
+ <value> (repeat every {0} for {1})</value>
+ </data>
+</root>
diff --git a/optimizerDuck/Services/Customize/CustomizeRegistry.cs b/optimizerDuck/Services/Customize/CustomizeRegistry.cs
index dc6564c..909f7ad 100644
--- a/optimizerDuck/Services/Customize/CustomizeRegistry.cs
+++ b/optimizerDuck/Services/Customize/CustomizeRegistry.cs
@@ -27,15 +27,27 @@ public class CustomizeRegistry
/// <summary>
/// Ensures categories have been discovered before the customize UI binds.
- /// If preloading has already completed, returns a completed task.
+ /// Concurrent callers share a single discovery; a failed discovery is retried.
/// </summary>
- public Task EnsurePreloadedAsync()
+ public async Task EnsurePreloadedAsync()
{
if (IsPreloaded)
- return Task.CompletedTask;
- return PreloadCategoriesAsync();
+ return;
+
+ _preloadTask ??= PreloadCategoriesAsync();
+ try
+ {
+ await _preloadTask.ConfigureAwait(false);
+ }
+ finally
+ {
+ if (!IsPreloaded)
+ _preloadTask = null;
+ }
}
+ private Task? _preloadTask;
+
/// <summary>Discovers all customize setting categories and their child settings via reflection, then populates <see cref="Categories"/>.</summary>
public async Task PreloadCategoriesAsync()
{
diff --git a/optimizerDuck/Services/Optimization/OptimizationRegistry.cs b/optimizerDuck/Services/Optimization/OptimizationRegistry.cs
index 838e5d3..918219a 100644
--- a/optimizerDuck/Services/Optimization/OptimizationRegistry.cs
+++ b/optimizerDuck/Services/Optimization/OptimizationRegistry.cs
@@ -20,15 +20,27 @@ public class OptimizationRegistry(ILoggerFactory loggerFactory)
/// <summary>
/// Ensures categories and applied-state are loaded before the optimize UI binds.
- /// If preloading has already completed, returns a completed task.
+ /// Concurrent callers share a single discovery; a failed discovery is retried.
/// </summary>
- public Task EnsurePreloadedAsync()
+ public async Task EnsurePreloadedAsync()
{
if (IsPreloaded)
- return Task.CompletedTask;
- return PreloadOptimizationsAsync();
+ return;
+
+ _preloadTask ??= PreloadOptimizationsAsync();
+ try
+ {
+ await _preloadTask.ConfigureAwait(false);
+ }
+ finally
+ {
+ if (!IsPreloaded)
+ _preloadTask = null;
+ }
}
+ private Task? _preloadTask;
+
/// <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()
{
diff --git a/optimizerDuck/Services/Optimization/Providers/RegistryService.cs b/optimizerDuck/Services/Optimization/Providers/RegistryService.cs
index 8ffacfd..f9e5955 100644
--- a/optimizerDuck/Services/Optimization/Providers/RegistryService.cs
+++ b/optimizerDuck/Services/Optimization/Providers/RegistryService.cs
@@ -189,11 +189,102 @@ public static class RegistryService
/// <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>
+ /// <remarks>A failed query (access denied, unknown root) is reported as "does not exist". Use <see cref="TryKeyExists" /> when that distinction matters.</remarks>
public static bool KeyExists(RegistryItem item, ILogger? logger = null)
{
return WithKey<bool>(item, key => true, logger, out _, out _, out _);
}
+ /// <summary>
+ /// Determines whether the specified registry key exists, distinguishing an absent key
+ /// from a failed query.
+ /// </summary>
+ /// <param name="exists">Whether the key exists; only meaningful on <c>true</c> return.</param>
+ /// <returns><c>false</c> when the query itself failed; absence must not be assumed then.</returns>
+ public static bool TryKeyExists(RegistryItem item, out bool exists, ILogger? logger = null)
+ {
+ exists = false;
+ if (!TryParsePath(item.Path, logger, out var rootKey, out var subPath))
+ return false;
+
+ if (
+ !TryOpenSubKey(
+ rootKey,
+ subPath,
+ out var key,
+ out var shouldDispose,
+ false,
+ false,
+ null,
+ logger,
+ out var openError,
+ out _
+ )
+ )
+ return openError is null; // absent key, not a failed query
+
+ try
+ {
+ exists = true;
+ return true;
+ }
+ finally
+ {
+ if (shouldDispose)
+ key?.Dispose();
+ }
+ }
+
+ /// <summary>
+ /// Reads a raw registry value, distinguishing an absent value from a failed read.
+ /// </summary>
+ /// <param name="value">The raw value, or <c>null</c> when absent or unreadable.</param>
+ /// <returns><c>false</c> when the read itself failed; a failed read is not "absent".</returns>
+ public static bool TryReadValue(RegistryItem item, out object? value, ILogger? logger = null)
+ {
+ value = null;
+ if (!TryParsePath(item.Path, logger, out var rootKey, out var subPath))
+ return false;
+
+ if (
+ !TryOpenSubKey(
+ rootKey,
+ subPath,
+ out var key,
+ out var shouldDispose,
+ false,
+ false,
+ null,
+ logger,
+ out var openError,
+ out _
+ )
+ )
+ // An absent key is a successful query with an absent value; an error is a failed query.
+ return openError is null;
+
+ try
+ {
+ value = key?.GetValue(
+ NormalizeValueName(item.Name),
+ null,
+ RegistryValueOptions.DoNotExpandEnvironmentNames
+ );
+ return true;
+ }
+ catch (Exception ex)
+ {
+ logger?.LogError(ex, "Failed to read registry {Path}:{Name}", item.Path, item.Name!);
+ value = null;
+ return false;
+ }
+ finally
+ {
+ if (shouldDispose)
+ key?.Dispose();
+ }
+ }
+
/// <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>
diff --git a/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs b/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs
index b20c847..b86aa66 100644
--- a/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs
+++ b/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs
@@ -1,7 +1,9 @@
using System.Collections.ObjectModel;
+using System.Globalization;
using Microsoft.Extensions.Logging;
using Microsoft.Win32.TaskScheduler;
using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Models.ScheduledTask;
using optimizerDuck.Domain.Revert.Steps;
using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.Configuration;
@@ -13,23 +15,30 @@ namespace optimizerDuck.Services.Optimization.Providers;
public static class ScheduledTaskService
{
- /// <summary>Checks whether a task at the given full path exists and is enabled.</summary>
- public static bool IsTaskEnabled(string fullPath, ILogger? logger = null)
+ /// <summary>
+ /// Reads whether a scheduled task exists and is enabled.
+ /// </summary>
+ /// <param name="fullPath">The full path of the task.</param>
+ /// <param name="logger">Optional logger for query diagnostics.</param>
+ /// <returns>
+ /// The task state. A failed query reports <see cref="TaskEnabledState.Unknown"/>,
+ /// never "disabled".
+ /// </returns>
+ public static TaskEnabledState GetTaskEnabledState(string fullPath, ILogger? logger = null)
{
try
{
using var ts = new TaskService();
var task = ts.GetTask(fullPath);
- return task is { Enabled: true };
+ if (task is null)
+ return TaskEnabledState.NotFound;
+
+ return task.Enabled ? TaskEnabledState.Enabled : TaskEnabledState.Disabled;
}
catch (Exception ex)
{
- logger?.LogDebug(
- "Failed to check task enabled state {Path}: {Error}",
- fullPath,
- ex.Message
- );
- return false;
+ logger?.LogWarning("Failed to check task state {Path}: {Error}", fullPath, ex.Message);
+ return TaskEnabledState.Unknown;
}
}
@@ -503,19 +512,208 @@ public static class ScheduledTaskService
}
}
+ /// <summary>Maps a task trigger type to its localization key, never raw library text.</summary>
+ private static string TriggerTranslationKey(TaskTriggerType type) =>
+ type switch
+ {
+ TaskTriggerType.Event => "ScheduledTasks.Trigger.Event",
+ TaskTriggerType.Time => "ScheduledTasks.Trigger.Time",
+ TaskTriggerType.Daily => "ScheduledTasks.Trigger.Daily",
+ TaskTriggerType.Weekly => "ScheduledTasks.Trigger.Weekly",
+ TaskTriggerType.Monthly => "ScheduledTasks.Trigger.Monthly",
+ TaskTriggerType.MonthlyDOW => "ScheduledTasks.Trigger.MonthlyDOW",
+ TaskTriggerType.Idle => "ScheduledTasks.Trigger.Idle",
+ TaskTriggerType.Registration => "ScheduledTasks.Trigger.Registration",
+ TaskTriggerType.Boot => "ScheduledTasks.Trigger.Boot",
+ TaskTriggerType.Logon => "ScheduledTasks.Trigger.Logon",
+ TaskTriggerType.SessionStateChange => "ScheduledTasks.Trigger.SessionStateChange",
+ _ => "ScheduledTasks.Trigger.Other",
+ };
+
+ /// <summary>
+ /// Builds localized display data for one trigger; unknown types fall back to raw text.
+ /// </summary>
+ private static ScheduledTaskTriggerInfo DescribeTrigger(Trigger trigger)
+ {
+ var info = DescribeCore(trigger);
+ var interval = trigger.Repetition?.Interval ?? TimeSpan.Zero;
+ if (interval <= TimeSpan.Zero)
+ return info;
+
+ var duration = trigger.Repetition!.Duration;
+ return duration > TimeSpan.Zero
+ ? info with
+ {
+ RepeatKey = "ScheduledTasks.TriggerDetail.RepeatFor",
+ RepeatArgs = [interval.ToString(), duration.ToString()],
+ }
+ : info with
+ {
+ RepeatKey = "ScheduledTasks.TriggerDetail.Repeat",
+ RepeatArgs = [interval.ToString()],
+ };
+ }
+
+ private static ScheduledTaskTriggerInfo DescribeCore(Trigger trigger)
+ {
+ return trigger switch
+ {
+ LogonTrigger logon => WithUser("Logon", logon.UserId, logon.Delay),
+ BootTrigger boot => WithDelay("Boot", boot.Delay),
+ RegistrationTrigger registration => WithDelay("Registration", registration.Delay),
+ IdleTrigger => new(TriggerTranslationKey(TaskTriggerType.Idle), null, [], null),
+ TimeTrigger time => new(
+ TriggerTranslationKey(TaskTriggerType.Time),
+ DetailKey("Time"),
+ [FormatTriggerTime(time.StartBoundary)],
+ null
+ ),
+ DailyTrigger daily => new(
+ TriggerTranslationKey(TaskTriggerType.Daily),
+ DetailKey("Daily"),
+ [
+ daily.DaysInterval.ToString(CultureInfo.InvariantCulture),
+ FormatTriggerTime(daily.StartBoundary),
+ ],
+ null
+ ),
+ WeeklyTrigger weekly => new(
+ TriggerTranslationKey(TaskTriggerType.Weekly),
+ DetailKey("Weekly"),
+ [
+ weekly.WeeksInterval.ToString(CultureInfo.InvariantCulture),
+ FormatDays(weekly.DaysOfWeek),
+ FormatTriggerTime(weekly.StartBoundary),
+ ],
+ null
+ ),
+ MonthlyTrigger monthly => new(
+ TriggerTranslationKey(TaskTriggerType.Monthly),
+ DetailKey("Monthly"),
+ [string.Join(", ", monthly.DaysOfMonth), FormatMonths(monthly.MonthsOfYear)],
+ null
+ ),
+ MonthlyDOWTrigger monthlyDow => new(
+ TriggerTranslationKey(TaskTriggerType.MonthlyDOW),
+ DetailKey("MonthlyDOW"),
+ [
+ ResolveWeekLabel(monthlyDow.WeeksOfMonth),
+ FormatDays(monthlyDow.DaysOfWeek),
+ FormatMonths(monthlyDow.MonthsOfYear),
+ ],
+ null
+ ),
+ SessionStateChangeTrigger session => DescribeSession(session),
+ _ => new(
+ TriggerTranslationKey(trigger.TriggerType),
+ null,
+ [],
+ trigger.ToString() ?? trigger.TriggerType.ToString()
+ ),
+ };
+ }
+
+ private static string Label(string name) => "ScheduledTasks.Trigger." + name;
+
+ private static string DetailKey(string name) => "ScheduledTasks.TriggerDetail." + name;
+
+ private static ScheduledTaskTriggerInfo WithUser(string label, string? userId, TimeSpan delay)
+ {
+ if (!string.IsNullOrWhiteSpace(userId) && delay > TimeSpan.Zero)
+ return new(Label(label), DetailKey("UserDelay"), [userId, delay.ToString()], null);
+ if (!string.IsNullOrWhiteSpace(userId))
+ return new(Label(label), DetailKey("User"), [userId], null);
+ return WithDelay(label, delay);
+ }
+
+ private static ScheduledTaskTriggerInfo WithDelay(string label, TimeSpan delay) =>
+ delay > TimeSpan.Zero
+ ? new(Label(label), DetailKey("Delay"), [delay.ToString()], null)
+ : new(Label(label), null, [], null);
+
+ /// <summary>
+ /// Describes a session-state trigger. Known states are label-only; anything else
+ /// falls back to the raw library text.
+ /// </summary>
+ private static ScheduledTaskTriggerInfo DescribeSession(SessionStateChangeTrigger session) =>
+ SessionLabelKey(session.StateChange) is { } label
+ ? new(label, null, [], null)
+ : new(
+ TriggerTranslationKey(TaskTriggerType.SessionStateChange),
+ null,
+ [],
+ session.ToString() ?? nameof(TaskSessionStateChangeType)
+ );
+
+ private static string? SessionLabelKey(TaskSessionStateChangeType state) =>
+ state switch
+ {
+ TaskSessionStateChangeType.SessionLock => "ScheduledTasks.Trigger.Session.Lock",
+ TaskSessionStateChangeType.SessionUnlock => "ScheduledTasks.Trigger.Session.Unlock",
+ TaskSessionStateChangeType.ConsoleConnect =>
+ "ScheduledTasks.Trigger.Session.ConsoleConnect",
+ TaskSessionStateChangeType.ConsoleDisconnect =>
+ "ScheduledTasks.Trigger.Session.ConsoleDisconnect",
+ TaskSessionStateChangeType.RemoteConnect =>
+ "ScheduledTasks.Trigger.Session.RemoteConnect",
+ TaskSessionStateChangeType.RemoteDisconnect =>
+ "ScheduledTasks.Trigger.Session.RemoteDisconnect",
+ _ => null,
+ };
+
+ private static string ResolveWeekLabel(WhichWeek weeks) =>
+ weeks switch
+ {
+ WhichWeek.FirstWeek => Loc.Instance["ScheduledTasks.Trigger.Week.First"],
+ WhichWeek.SecondWeek => Loc.Instance["ScheduledTasks.Trigger.Week.Second"],
+ WhichWeek.ThirdWeek => Loc.Instance["ScheduledTasks.Trigger.Week.Third"],
+ WhichWeek.FourthWeek => Loc.Instance["ScheduledTasks.Trigger.Week.Fourth"],
+ WhichWeek.LastWeek => Loc.Instance["ScheduledTasks.Trigger.Week.Last"],
+ _ => Loc.Instance["ScheduledTasks.Trigger.Week.Every"],
+ };
+
+ private static string FormatTriggerTime(DateTime boundary) =>
+ boundary.ToString("g", CultureInfo.CurrentCulture);
+
+ private static string FormatDays(DaysOfTheWeek days)
+ {
+ var culture = CultureInfo.CurrentCulture;
+ var names = new List<string>();
+ foreach (DayOfWeek day in Enum.GetValues<DayOfWeek>())
+ if (Enum.TryParse<DaysOfTheWeek>(day.ToString(), out var flag) && days.HasFlag(flag))
+ names.Add(culture.DateTimeFormat.GetDayName(day));
+ return string.Join(", ", names);
+ }
+
+ private static string FormatMonths(MonthsOfTheYear months)
+ {
+ var culture = CultureInfo.CurrentCulture;
+ var invariant = CultureInfo.InvariantCulture;
+ var names = new List<string>();
+ for (var month = 1; month <= 12; month++)
+ if (
+ Enum.TryParse<MonthsOfTheYear>(
+ invariant.DateTimeFormat.GetMonthName(month),
+ out var flag
+ ) && months.HasFlag(flag)
+ )
+ names.Add(culture.DateTimeFormat.GetMonthName(month));
+ return string.Join(", ", names);
+ }
+
private static ScheduledTaskModel MapTaskToModel(Task task)
{
var def = task.Definition;
var triggers = def.Triggers;
var actions = def.Actions;
- var triggerDescriptions = new List<string>();
+ var triggerInfos = new List<ScheduledTaskTriggerInfo>();
var hasLogon = false;
var hasBoot = false;
foreach (var t in triggers)
{
- triggerDescriptions.Add(t.ToString() ?? t.TriggerType.ToString());
+ triggerInfos.Add(DescribeTrigger(t));
if (t.TriggerType == TaskTriggerType.Logon)
hasLogon = true;
if (t.TriggerType == TaskTriggerType.Boot)
@@ -537,8 +735,7 @@ public static class ScheduledTaskService
Author = def.RegistrationInfo.Author,
IsEnabled = task.Enabled,
State = task.State.ToString(),
- TriggerSummary = string.Join("; ", triggerDescriptions),
- TriggerTypes = new ObservableCollection<string>(triggerDescriptions),
+ TriggerInfos = triggerInfos,
ActionSummary = actionSummary,
LastRunTime = task.LastRunTime == DateTime.MinValue ? null : task.LastRunTime,
NextRunTime = task.NextRunTime == DateTime.MinValue ? null : task.NextRunTime,
diff --git a/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs b/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs
index ec048d9..df762cf 100644
--- a/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs
+++ b/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs
@@ -323,25 +323,53 @@ public static class ServiceProcessService
};
process.Start();
+ // drain both pipes concurrently so a chatty child can never block on a full pipe.
var stdoutTask = process.StandardOutput.ReadToEndAsync();
var stderrTask = process.StandardError.ReadToEndAsync();
using var cts = new CancellationTokenSource(timeoutMs);
+ var timedOut = false;
try
{
- await process.WaitForExitAsync(cts.Token);
+ await process.WaitForExitAsync(cts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
+ timedOut = true;
try
{
- process.Kill();
+ process.Kill(entireProcessTree: true);
+ }
+ catch
+ {
+ // best effort
+ }
+
+ // bounded wait so ExitCode is never read on a live process.
+ try
+ {
+ process.WaitForExit(2000);
}
catch { }
}
- var stdout = await stdoutTask;
- var stderr = await stderrTask;
- return (process.ExitCode, stdout, stderr);
+ var stdout = await stdoutTask.ConfigureAwait(false);
+ var stderr = await stderrTask.ConfigureAwait(false);
+
+ // -1 means timeout (same convention as ProcessRunner), never a real exit code.
+ var exitCode = timedOut || !HasExited(process) ? -1 : process.ExitCode;
+ return (exitCode, stdout, stderr);
+ }
+
+ private static bool HasExited(Process process)
+ {
+ try
+ {
+ return process.HasExited;
+ }
+ catch
+ {
+ return false;
+ }
}
}
diff --git a/optimizerDuck/Services/Optimization/Providers/ServiceStrings.cs b/optimizerDuck/Services/Optimization/Providers/ServiceStrings.cs
index 2ed781a..ec33d38 100644
--- a/optimizerDuck/Services/Optimization/Providers/ServiceStrings.cs
+++ b/optimizerDuck/Services/Optimization/Providers/ServiceStrings.cs
@@ -62,6 +62,9 @@ public static class ServiceStrings
public const string ShellName = "Shell";
+ public const string StartupAppErrorUnsupportedLocation =
+ "Cannot toggle startup app '{0}': its location is not supported";
+
/// <summary>Formats a template with invariant culture (same as Loc.Invariant did).</summary>
public static string Format(string template, params object?[] args) =>
string.Format(CultureInfo.InvariantCulture, template, args);
diff --git a/optimizerDuck/Services/Optimization/Providers/ShellMapping.cs b/optimizerDuck/Services/Optimization/Providers/ShellMapping.cs
index 35c3026..508ba3d 100644
--- a/optimizerDuck/Services/Optimization/Providers/ShellMapping.cs
+++ b/optimizerDuck/Services/Optimization/Providers/ShellMapping.cs
@@ -25,7 +25,7 @@ internal static class ShellMapping
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
+ ? // best effort: force UTF-8 codepage for cmd
$"{arguments} {command}"
: $"{arguments} chcp 65001 > nul & {command}";
}
@@ -39,7 +39,6 @@ internal static class ShellMapping
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 a725922..7b7ac0f 100644
--- a/optimizerDuck/Services/Optimization/Providers/ShellService.cs
+++ b/optimizerDuck/Services/Optimization/Providers/ShellService.cs
@@ -61,8 +61,7 @@ public sealed class ShellService(ProcessRunner _runner)
{
var (_, fullCommandForUser) = SanitizeCommandForUser(fileName, 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.
+ // Best-effort UTF-8 codepage for cmd.exe; PowerShell already forces UTF-8 via its preamble.
var processArgs = fileName.Equals("cmd.exe", StringComparison.OrdinalIgnoreCase)
? ShellMapping.BuildCmdArguments(arguments, command)
: $"{arguments} {command}";
diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.cs
index 9adbbca..5b5ffaf 100644
--- a/optimizerDuck/Services/Revert/RevertManager.cs
+++ b/optimizerDuck/Services/Revert/RevertManager.cs
@@ -29,8 +29,7 @@ public class RevertManager(ILogger<RevertManager> _logger, ShellService _shell,
private static readonly ConcurrentDictionary<Guid, SemaphoreSlim> _fileLocks = new();
/// <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.
+ /// 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(
diff --git a/optimizerDuck/Services/UI/StartupManagerService.cs b/optimizerDuck/Services/UI/StartupManagerService.cs
index 3c4c09b..47ff977 100644
--- a/optimizerDuck/Services/UI/StartupManagerService.cs
+++ b/optimizerDuck/Services/UI/StartupManagerService.cs
@@ -66,7 +66,7 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)
apps
);
- // 2. Registry (32-bit view, redirected to Wow6432Node) — where 32-bit installers register
+ // 2. Registry (32-bit view, redirected to Wow6432Node), where 32-bit installers register
using var hklm32 = RegistryKey.OpenBaseKey(
RegistryHive.LocalMachine,
RegistryView.Registry32
@@ -148,7 +148,7 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)
// 32-bit Run entries keep their approved flags in the dedicated Run32/RunOnce32
// subkeys (default view), and Windows 11 treats them as disabled until an explicit
- // enable flag exists — unlike 64-bit entries, where a missing flag means enabled.
+ // enable flag exists, unlike 64-bit entries, where a missing flag means enabled.
var is32Bit =
location
is StartupAppLocation.RegistryHKLMRun32
@@ -486,42 +486,57 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)
/// <summary>Enables or disables a startup application by writing the StartupApproved registry flag.</summary>
/// <param name="app">The startup app to toggle.</param>
/// <param name="enable"><see langword="true"/> to enable, <see langword="false"/> to disable.</param>
- public async Task ToggleStartupApp(StartupApp app, bool enable)
+ /// <returns>The toggle outcome.</returns>
+ public Task<OpResult> ToggleStartupApp(StartupApp app, bool enable)
{
- await Task.Run(() =>
+ return Task.Run(() =>
{
try
{
- if (
+ var result =
app.Location
- is StartupAppLocation.RegistryHKCURun
- or StartupAppLocation.RegistryHKLMRun
- or StartupAppLocation.RegistryHKCURunOnce
- or StartupAppLocation.RegistryHKLMRunOnce
- or StartupAppLocation.RegistryHKLMRun32
- or StartupAppLocation.RegistryHKLMRunOnce32
- )
- ToggleRegistryStartupApp(app, enable);
- else if (app.Location == StartupAppLocation.UwpStartupTask)
- ToggleUwpStartupApp(app, enable);
- else // Folders
- ToggleFolderStartupApp(app, enable);
-
- logger.LogInformation("Toggled startup app {Name} to {Enable}", app.Name, enable);
+ is StartupAppLocation.RegistryHKCURun
+ or StartupAppLocation.RegistryHKLMRun
+ or StartupAppLocation.RegistryHKCURunOnce
+ or StartupAppLocation.RegistryHKLMRunOnce
+ or StartupAppLocation.RegistryHKLMRun32
+ or StartupAppLocation.RegistryHKLMRunOnce32
+ ? ToggleRegistryStartupApp(app, enable)
+ : app.Location == StartupAppLocation.UwpStartupTask
+ ? ToggleUwpStartupApp(app, enable)
+ : ToggleFolderStartupApp(app, enable);
+
+ if (result.Ok)
+ logger.LogInformation(
+ "Toggled startup app {Name} to {Enable}",
+ app.Name,
+ enable
+ );
+ else
+ logger.LogError(
+ "Failed to toggle startup app {Name}: {Error}",
+ app.Name,
+ result.Error
+ );
+
+ return result;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to toggle startup app {Name}", app.Name);
+ return OpResult.Fail(ex.Message, ex.ToString());
}
});
}
- private static void ToggleRegistryStartupApp(StartupApp app, bool enable)
+ private static OpResult ToggleRegistryStartupApp(StartupApp app, bool enable)
{
// Parse RootKey and SubKey from app.PathOrKey
var firstSlash = app.PathOrKey.IndexOf('\\');
if (firstSlash < 0)
- return;
+ return OpResult.Fail(
+ ServiceStrings.Format(ServiceStrings.StartupAppErrorUnsupportedLocation, app.Name)
+ );
var rootKeyStr = app.PathOrKey[..firstSlash];
var hive = rootKeyStr switch
@@ -531,7 +546,9 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)
_ => null,
};
if (hive == null)
- return;
+ return OpResult.Fail(
+ ServiceStrings.Format(ServiceStrings.StartupAppErrorUnsupportedLocation, app.Name)
+ );
// Write the flag; 32-bit entries use the dedicated Run32/RunOnce32 subkeys
var approvedSubKeyPath = GetApprovedSubKeyPath(app.Location);
@@ -543,6 +560,7 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)
app.OriginalValueNameOrFileName,
BuildApprovedData(enable)
);
+ return OpResult.Success();
}
/// <summary>
@@ -570,22 +588,30 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)
approvedKey.SetValue(valueName, data, RegistryValueKind.Binary);
}
- private static void ToggleUwpStartupApp(StartupApp app, bool enable)
+ private static OpResult ToggleUwpStartupApp(StartupApp app, bool enable)
{
// Packaged-app startup state: 2 = Enabled, 1 = DisabledByUser
var firstSlash = app.PathOrKey.IndexOf('\\');
if (firstSlash < 0)
- return;
+ return OpResult.Fail(
+ ServiceStrings.Format(ServiceStrings.StartupAppErrorUnsupportedLocation, app.Name)
+ );
var subKeyPath = app.PathOrKey[(firstSlash + 1)..];
using var taskKey = Registry.CurrentUser.CreateSubKey(
$@"{subKeyPath}\{app.OriginalValueNameOrFileName}",
true
);
+ if (taskKey == null)
+ return OpResult.Fail(
+ ServiceStrings.Format(ServiceStrings.StartupAppErrorUnsupportedLocation, app.Name)
+ );
+
taskKey.SetValue("State", enable ? 2 : 1, RegistryValueKind.DWord);
+ return OpResult.Success();
}
- private static void ToggleFolderStartupApp(StartupApp app, bool enable)
+ private static OpResult ToggleFolderStartupApp(StartupApp app, bool enable)
{
var rootKey =
app.Location == StartupAppLocation.CommonStartupFolder
@@ -597,12 +623,17 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)
using var approvedKey =
rootKey.OpenSubKey(approvedSubKeyPath, true)
?? rootKey.CreateSubKey(approvedSubKeyPath, true);
+ if (approvedKey == null)
+ return OpResult.Fail(
+ ServiceStrings.Format(ServiceStrings.StartupAppErrorUnsupportedLocation, app.Name)
+ );
approvedKey.SetValue(
app.OriginalValueNameOrFileName,
BuildApprovedData(enable),
RegistryValueKind.Binary
);
+ return OpResult.Success();
}
/// <summary>Retrieves all startup scheduled tasks from the Windows Task Scheduler, including their enabled state and icons.</summary>
@@ -620,8 +651,7 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)
TaskName = m.Name,
TaskPath = m.Path,
Description = m.Description,
- TriggerSummary = m.TriggerSummary,
- TriggerTypes = [.. m.TriggerTypes],
+ TriggerInfos = [.. m.TriggerInfos],
ActionSummary = m.ActionSummary,
IsEnabled = m.IsEnabled,
})
@@ -652,27 +682,38 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)
/// <summary>Enables or disables a startup scheduled task using the Task Scheduler API.</summary>
/// <param name="task">The startup task to toggle.</param>
/// <param name="enable"><see langword="true"/> to enable, <see langword="false"/> to disable.</param>
- public Task ToggleStartupTask(StartupTask task, bool enable)
+ /// <returns>The toggle outcome.</returns>
+ public Task<OpResult> ToggleStartupTask(StartupTask task, bool enable)
{
return Task.Run(() =>
{
try
{
var fullPath = task.TaskPath.TrimEnd('\\') + "\\" + task.TaskName;
- if (enable)
- {
- ScheduledTaskService.EnableTask(UiCall(), fullPath);
- logger.LogInformation("Enabled task {Name} ({Path})", task.TaskName, fullPath);
- }
+ var result = enable
+ ? ScheduledTaskService.EnableTask(UiCall(), fullPath)
+ : ScheduledTaskService.DisableTask(UiCall(), fullPath);
+
+ if (result.Ok)
+ logger.LogInformation(
+ "{Action} task {Name} ({Path})",
+ enable ? "Enabled" : "Disabled",
+ task.TaskName,
+ fullPath
+ );
else
- {
- ScheduledTaskService.DisableTask(UiCall(), fullPath);
- logger.LogInformation("Disabled task {Name} ({Path})", task.TaskName, fullPath);
- }
+ logger.LogError(
+ "Failed to toggle task {Name}: {Error}",
+ task.TaskName,
+ result.Error
+ );
+
+ return result;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to toggle task {Name}", task.TaskName);
+ return OpResult.Fail(ex.Message, ex.ToString());
}
});
}
diff --git a/optimizerDuck/UI/Pages/DashboardPage.xaml b/optimizerDuck/UI/Pages/DashboardPage.xaml
index b39c6d7..dad1a01 100644
--- a/optimizerDuck/UI/Pages/DashboardPage.xaml
+++ b/optimizerDuck/UI/Pages/DashboardPage.xaml
@@ -272,8 +272,7 @@
<StackPanel Grid.Row="0">
<ui:TextBlock FontTypography="BodyStrong">
- <Run Text="{Binding ViewModel.RuntimeRam.TotalGB, StringFormat='{}{0:F1}'}" />
- <Run Text="GB RAM" />
+ <Run Text="{ext:Loc Dashboard.SystemInfo.Ram.Total, {Binding ViewModel.RuntimeRam.TotalGB, StringFormat='{}{0:F1}'}}" />
</ui:TextBlock>
<ui:TextBlock FontTypography="Caption" Foreground="{DynamicResource TextFillColorSecondaryBrush}">
<Run Text="{ext:Loc Dashboard.SystemInfo.Ram.Used, {Binding ViewModel.RuntimeRam.UsedGB, StringFormat='{}{0:F1}'}}" />
@@ -340,8 +339,7 @@
Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"
CornerRadius="{StaticResource CornerRadiusSmall}">
<ui:TextBlock FontTypography="Caption">
- <Run Text="{Binding ViewModel.SystemInfo.PrimaryGpu.MemoryMB, Converter={StaticResource MBToGBConverter}}" />
- <Run Text="GB" />
+ <Run Text="{ext:Loc Dashboard.SystemInfo.Gpu.Memory, {Binding ViewModel.SystemInfo.PrimaryGpu.MemoryMB, Converter={StaticResource MBToGBConverter}}}" />
</ui:TextBlock>
</Border>
<Border
diff --git a/optimizerDuck/UI/Pages/Optimize/Categories/OptimizationPage.xaml b/optimizerDuck/UI/Pages/Optimize/Categories/OptimizationPage.xaml
index 1ab6f7e..ef62ad0 100644
--- a/optimizerDuck/UI/Pages/Optimize/Categories/OptimizationPage.xaml
+++ b/optimizerDuck/UI/Pages/Optimize/Categories/OptimizationPage.xaml
@@ -91,9 +91,7 @@
HorizontalAlignment="Left"
Symbol="ArrowSort24" />
<TextBlock Grid.Column="1" HorizontalAlignment="Left">
- <Run Text="{ext:Loc Common.SortBy.Risk}" />
- <Run Text=" &amp; " />
- <Run Text="{ext:Loc Common.SortBy.Status}" />
+ <Run Text="{ext:Loc Common.SortBy.RiskAndStatus}" />
</TextBlock>
</Grid>
</ComboBoxItem>
diff --git a/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs b/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs
index 1e09cfc..34b08b4 100644
--- a/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs
@@ -54,6 +54,7 @@ public partial class CustomizeItemViewModel(
private bool _isEnabled;
[ObservableProperty]
+ [NotifyCanExecuteChangedFor(nameof(ToggleCommand))]
private bool _isLoading;
public string Name => setting.Name;
@@ -127,9 +128,10 @@ public partial class CustomizeItemViewModel(
SubscribeToRegistryChanges();
}
- catch
+ catch (Exception ex)
{
- IsEnabled = false;
+ // keep state unloaded on read failure instead of showing it as off.
+ _logger.LogWarning(ex, "Failed to load customize setting {Setting}", setting.LogName());
}
}
@@ -241,12 +243,17 @@ public partial class CustomizeItemViewModel(
}
}
- [RelayCommand]
+ [RelayCommand(CanExecute = nameof(CanToggle))]
private void Toggle()
{
+ // the first call marks the executor busy synchronously, so a same-tick second click is ignored.
+ if (_executor.IsApplying)
+ return;
_ = _executor.ApplyWithDebounceAsync(!IsEnabled, ApplyCoreAsync, debounceMs: 0);
}
+ private bool CanToggle() => !IsLoading;
+
partial void OnCurrentValueChanged(object? value)
{
if (!_hasLoaded || ControlType == CustomizeControlType.Toggle)
@@ -298,7 +305,8 @@ public partial class CustomizeItemViewModel(
CurrentValue = current;
}
- if (Application.Current is App app)
+ // only flag reboot when the value was actually written.
+ if (applyResult.Ok && Application.Current is App app)
app.HasPendingChanges = true;
}
catch (Exception ex)
diff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.Dialogs.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.Dialogs.cs
index 007630a..9e69490 100644
--- a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.Dialogs.cs
+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.Dialogs.cs
@@ -4,6 +4,7 @@ using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
+using System.Windows.Data;
using System.Windows.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
@@ -88,12 +89,12 @@ public partial class OptimizationCategoryViewModel
};
if (canRetry)
{
- dialog.PrimaryButtonText = Loc.Instance["Button.Retry"];
- dialog.CloseButtonText = Loc.Instance["Button.Cancel"];
+ BindLocalized(dialog, ContentDialog.PrimaryButtonTextProperty, "Button.Retry");
+ BindLocalized(dialog, ContentDialog.CloseButtonTextProperty, "Button.Cancel");
}
else
{
- dialog.CloseButtonText = Loc.Instance["Button.Ok"];
+ BindLocalized(dialog, ContentDialog.CloseButtonTextProperty, "Button.Ok");
}
var result = await _contentDialogService.ShowAsync(dialog, CancellationToken.None);
@@ -252,14 +253,11 @@ public partial class OptimizationCategoryViewModel
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 dialog = new ContentDialog { Content = dialogContent };
+ BindLocalized(dialog, ContentDialog.TitleProperty, "RestorePoint.Title");
+ BindLocalized(dialog, ContentDialog.PrimaryButtonTextProperty, "Button.Ok");
+ BindLocalized(dialog, ContentDialog.SecondaryButtonTextProperty, "Button.Skip");
+ BindLocalized(dialog, ContentDialog.CloseButtonTextProperty, "Button.Cancel");
var result = await _contentDialogService.ShowAsync(dialog, CancellationToken.None);
if (result == ContentDialogResult.None)
@@ -363,6 +361,15 @@ public partial class OptimizationCategoryViewModel
return (true, false);
}
+ /// <summary>Binds a dialog property to a localization key so it follows runtime language changes.</summary>
+ private static void BindLocalized(ContentDialog dialog, DependencyProperty property, string key)
+ {
+ dialog.SetBinding(
+ property,
+ new Binding($"[{key}]") { Source = Loc.Instance, Mode = BindingMode.OneWay }
+ );
+ }
+
/// <summary>
/// Builds the dialog title for an optimization.
/// </summary>
diff --git a/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs
index c6b6072..41a02e6 100644
--- a/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs
@@ -327,35 +327,77 @@ public partial class StartupManagerViewModel : ViewModel
OnPropertyChanged(nameof(ShowRefreshButton));
}
+ private readonly HashSet<object> _suppressToggle = [];
+
private async void App_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
- if (e.PropertyName == nameof(StartupApp.IsEnabled) && sender is StartupApp app)
+ if (e.PropertyName != nameof(StartupApp.IsEnabled) || sender is not StartupApp app)
+ return;
+
+ // rollback re-assigns IsEnabled, so guard against re-entrancy.
+ if (!_suppressToggle.Add(app))
+ return;
+
+ try
{
- try
- {
- await _startupManagerService.ToggleStartupApp(app, app.IsEnabled);
- }
- catch (Exception ex)
+ var result = await _startupManagerService.ToggleStartupApp(app, app.IsEnabled);
+ if (!result.Ok)
{
- _logger.LogError(ex, "Failed to toggle startup app {Name}", app.Name);
+ // The write failed, so the real Windows state is unchanged: restore the
+ // toggle to it instead of leaving the UI claiming a state that is not applied.
+ _logger.LogWarning(
+ "Startup app toggle failed for {Name}: {Error}",
+ app.Name,
+ result.Error
+ );
+ app.IsEnabled = !app.IsEnabled;
}
}
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Failed to toggle startup app {Name}", app.Name);
+ app.IsEnabled = !app.IsEnabled;
+ }
+ finally
+ {
+ _suppressToggle.Remove(app);
+ }
}
private async void Task_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
- if (e.PropertyName == nameof(StartupTask.IsEnabled) && sender is StartupTask task)
+ if (e.PropertyName != nameof(StartupTask.IsEnabled) || sender is not StartupTask task)
+ return;
+
+ if (!_suppressToggle.Add(task))
+ return;
+
+ try
{
- try
+ var result = await _startupManagerService.ToggleStartupTask(task, task.IsEnabled);
+ if (result.Ok)
{
- await _startupManagerService.ToggleStartupTask(task, task.IsEnabled);
CrossPageEventBus.NotifyDataChanged<StartupAppsChanged>();
}
- catch (Exception ex)
+ else
{
- _logger.LogError(ex, "Failed to toggle startup task {Name}", task.TaskName);
+ _logger.LogWarning(
+ "Startup task toggle failed for {Name}: {Error}",
+ task.TaskName,
+ result.Error
+ );
+ task.IsEnabled = !task.IsEnabled;
}
}
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Failed to toggle startup task {Name}", task.TaskName);
+ task.IsEnabled = !task.IsEnabled;
+ }
+ finally
+ {
+ _suppressToggle.Remove(task);
+ }
}
private async Task ReloadTasksAsync()