Free, open-source Windows optimization tool for performance, privacy, and simplicity.
C# csharpdebloatdotnetgamingopen-sourceoptimizationoptimizeroptimizerduckperformanceprivacytweakertweakswindowswinui
refactor(stepdetails): typed records, codec, UI, tests
fatDucka9fa6ebac225
diff --git a/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.cs b/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.csindex f67b67a..efb5d86 100644--- a/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.cs+++ b/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.cs@@ -80,24 +80,6 @@ public class SystemRefreshServiceTestsAssert.Null(exception);}- [Fact]- public void SetDesktopIconsVisible_True_DoesNotThrow()- {- var exception = Record.Exception(() =>- SystemRefreshService.SetDesktopIconsVisible(showIcons: true)- );- Assert.Null(exception);- }-- [Fact]- public void SetDesktopIconsVisible_False_DoesNotThrow()- {- var exception = Record.Exception(() =>- SystemRefreshService.SetDesktopIconsVisible(showIcons: false)- );- Assert.Null(exception);- }-[Fact]public void RefreshDesktopIconVisibilityFromRegistry_DoesNotThrow(){@@ -106,23 +88,4 @@ public class SystemRefreshServiceTests);Assert.Null(exception);}-- [Fact]- public void SetDesktopIconsVisible_ToggleBackAndForth_DoesNotThrow()- {- var ex1 = Record.Exception(() =>- SystemRefreshService.SetDesktopIconsVisible(showIcons: true)- );- Assert.Null(ex1);-- var ex2 = Record.Exception(() =>- SystemRefreshService.SetDesktopIconsVisible(showIcons: false)- );- Assert.Null(ex2);-- var ex3 = Record.Exception(() =>- SystemRefreshService.SetDesktopIconsVisible(showIcons: true)- );- Assert.Null(ex3);- }}diff --git a/optimizerDuck.Test/Domain/Execution/ChangeDetailTests.cs b/optimizerDuck.Test/Domain/Execution/ChangeDetailTests.csnew file mode 100644index 0000000..45c63f0--- /dev/null+++ b/optimizerDuck.Test/Domain/Execution/ChangeDetailTests.cs@@ -0,0 +1,257 @@+using Newtonsoft.Json;+using optimizerDuck.Common.Helpers;+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.Test.TestDoubles;++namespace optimizerDuck.Test.Domain.Execution;++/// <summary>+/// The typed facts of a step: how long they live, what the kinds that move between two values+/// say they do, and how they survive the record file, including one written by an earlier build.+/// </summary>+public class ChangeDetailTests+{+ [Fact]+ public void OnlyTheKindsThatMoveBetweenTwoValuesSaySo()+ {+ var paired = EveryOperationDetail+ .Items.Where(detail => detail.HasValuePair)+ .Select(detail => detail.GetType().Name)+ .Order()+ .ToList();++ Assert.Equal(+ [+ "HibernationDetail",+ "PowerPlanActivateDetail",+ "PowerSettingDetail",+ "RegistryValueRemoveDetail",+ "RegistryValueWriteDetail",+ "ScheduledTaskDisableDetail",+ "ScheduledTaskEnableDetail",+ "ServiceStartupDetail",+ ],+ paired+ );+ }++ [Fact]+ public void EveryKindDeclaresAnOperationCodeAndTheFileKeepsTheOnesItAlreadyHad()+ {+ // The codes are the wire format, so decoding has to keep matching the names old records carry.+ var codes = EveryOperationDetail.Items.Select(detail => detail.Operation).Order().ToList();++ Assert.Equal(+ [+ "hibernation",+ "power.plan",+ "power.planInstall",+ "power.setting",+ "registry.createKey",+ "registry.delete",+ "registry.deleteKey",+ "registry.write",+ "service.startup",+ "task.disable",+ "task.enable",+ "usb.power",+ ],+ codes+ );+ }++ [Theory]+ [MemberData(nameof(EveryOperationDetail.All), MemberType = typeof(EveryOperationDetail))]+ public void WritingARecordAndReadingItBackKeepsEveryFact(ChangeDetail detail)+ {+ var step = StoredRoundTrip(detail);++ Assert.Equal(detail.Operation, step.Operation);+ Assert.Equal(detail, ChangeDetailCodec.Decode(step));+ }++ [Fact]+ public void ARecordFromAnEarlierBuildReadsTheSameAsBefore()+ {+ // Written by a build that had only the flat fields: no timings, no index, no display name.+ const string json = """+ {+ "Id": "5a4c1f9e-2c3a-4f5b-9c7d-8e1f2a3b4c5d",+ "OptimizationKey": "LegacyTest",+ "LogName": "Legacy test",+ "AppliedAt": "2026-01-02T03:04:05",+ "Operation": "Apply",+ "Outcome": "Success",+ "Steps": [+ {+ "Name": "Registry",+ "Description": "Write registry value",+ "Kind": "Change",+ "Ok": true,+ "Operation": "registry.write",+ "Target": "HKLM\\Test\\A",+ "ValueName": "V",+ "ValueType": "DWord",+ "PreviousValue": null,+ "NewValue": "0",+ "HasValuePair": true+ },+ {+ "Name": "Hibernation",+ "Description": "Disabled hibernation",+ "Kind": "Change",+ "Ok": true,+ "Operation": "hibernation",+ "PreviousValue": "Unknown",+ "NewValue": "Disabled",+ "HasValuePair": true+ },+ {+ "Name": "Service",+ "Description": "Change service startup type",+ "Kind": "Change",+ "Ok": true,+ "Operation": "service.startup",+ "Target": "DiagTrack",+ "ValueName": "Left over from the old bag",+ "PreviousValue": "Automatic",+ "NewValue": "Disabled",+ "HasValuePair": true+ }+ ]+ }+ """;++ var record = JsonConvert.DeserializeObject<ChangeRecord>(json);++ Assert.NotNull(record);+ Assert.Equal(3, record.Steps.Count);++ // A value that was not there still reads as absent, which is what the old row said.+ var written = Assert.IsType<RegistryValueWriteDetail>(+ ChangeDetailCodec.Decode(record.Steps[0])+ );+ Assert.Equal(@"HKLM\Test\A", written.Target);+ Assert.Equal("V", written.ValueName);+ Assert.Null(written.PreviousValue);+ Assert.Equal("0", written.NewValue);++ // A state the old build could not read is unknown, not a state it was in.+ var hibernation = Assert.IsType<HibernationDetail>(+ ChangeDetailCodec.Decode(record.Steps[1])+ );+ Assert.Null(hibernation.PreviousPresent);+ Assert.False(hibernation.NewPresent);++ // A field the operation has no meaning for is dropped rather than shown.+ var service = Assert.IsType<ServiceStartupDetail>(+ ChangeDetailCodec.Decode(record.Steps[2])+ );+ Assert.Equal("DiagTrack", service.ServiceName);+ var row = ChangeDetailPresentation.For(+ service,+ record.Steps[2].Kind,+ ChangeRecordOperation.Apply+ );+ Assert.DoesNotContain(row.Chips, chip => chip.Value == "Left over from the old bag");+ }++ [Fact]+ public void AnOperationThisBuildDoesNotKnowDecodesToNothingSoTheRowKeepsItsDescription()+ {+ var step = new ChangeRecordStep+ {+ Name = "SomeFutureProvider",+ Description = "Did something this build cannot word",+ Kind = ChangeKind.Change,+ Operation = "future.operation",+ Target = "Whatever",+ };++ Assert.Null(ChangeDetailCodec.Decode(step));+ Assert.Empty(+ ChangeDetailPresentation+ .For(ChangeDetailCodec.Decode(step), step.Kind, ChangeRecordOperation.Apply)+ .Chips+ );+ }++ [Fact]+ public void EachStepCarriesWhenItRanAndHowLongItTook()+ {+ var changes = new ChangeSet();++ changes.Add("First", "does nothing", true);+ Thread.Sleep(30);+ changes.Add("Second", "waits", true);++ var first = changes.Changes[0];+ var second = changes.Changes[1];++ Assert.NotNull(first.RecordedAt);+ Assert.NotNull(second.RecordedAt);+ Assert.True(+ second.ElapsedMs >= 25,+ $"expected the wait to be counted, got {second.ElapsedMs}"+ );+ Assert.True(changes.ElapsedMs >= second.ElapsedMs);+ Assert.True(changes.StartedAt <= first.RecordedAt);+ }++ [Fact]+ public void AStepRecordsTheCodeItFailedWithAndCountsItsFirstAttempt()+ {+ var changes = new ChangeSet();++ var written = changes.Add("Registry", "wrote a value", true);+ var refused = changes.Add("Service", "was refused", false, nativeErrorCode: 5);++ // Null is no code, which is not the same as zero.+ Assert.Null(written.NativeErrorCode);+ Assert.Equal(5, refused.NativeErrorCode);+ Assert.Equal(1, written.Attempt);+ Assert.Equal(1, refused.Attempt);+ }++ [Fact]+ public void ARunRecordsTheBuildAndTheWindowsVersionItRanOn()+ {+ var changes = new ChangeSet();+ changes.Add("Registry", "wrote a value", true);++ var record = ChangeRecord.From(changes, new StubItem(), "Success");++ Assert.Equal(Shared.FileVersion, record.AppVersion);+ Assert.False(string.IsNullOrWhiteSpace(record.WindowsVersion));+ Assert.NotNull(record.StartedAt);+ Assert.NotNull(record.ElapsedMs);+ }++ /// One step stored and read back the way the record file does it.+ private static ChangeRecordStep StoredRoundTrip(ChangeDetail detail)+ {+ var changes = new ChangeSet();+ changes.Add("Provider", "Description", true, detail: detail);++ var json = JsonConvert.SerializeObject(+ ChangeRecord.From(changes, new StubItem(), "Success"),+ Formatting.Indented+ );+ var read = JsonConvert.DeserializeObject<ChangeRecord>(json);++ Assert.NotNull(read);+ return Assert.Single(read.Steps);+ }++ private sealed class StubItem : StubOptimization+ {+ public override Task<ApplyResult> ApplyAsync(+ IProgress<ProcessingProgress> progress,+ OptimizationContext context+ ) => Task.FromResult(ApplyResult.True());+ }+}diff --git a/optimizerDuck.Test/Domain/UI/ChangeDetailPresentationTests.cs b/optimizerDuck.Test/Domain/UI/ChangeDetailPresentationTests.csnew file mode 100644index 0000000..4673c01--- /dev/null+++ b/optimizerDuck.Test/Domain/UI/ChangeDetailPresentationTests.cs@@ -0,0 +1,293 @@+using optimizerDuck.Domain.Execution;+using optimizerDuck.Domain.Optimizations.Models.Services;+using optimizerDuck.Domain.UI;+using optimizerDuck.Services.Configuration;+using optimizerDuck.Test.TestDoubles;++namespace optimizerDuck.Test.Domain.UI;++/// <summary>+/// How the record words one step: the action it states, the facts it shows, and the fact that+/// every kind of operation has a row of its own.+/// </summary>+public class ChangeDetailPresentationTests+{+ [Fact]+ public void TheFactsCoverEveryKindOfOperationTheDomainHas()+ {+ var kinds = typeof(ChangeDetail)+ .Assembly.GetTypes()+ .Where(type => type.IsSubclassOf(typeof(ChangeDetail)) && !type.IsAbstract)+ .Select(type => type.Name)+ .Order()+ .ToList();++ var covered = EveryOperationDetail+ .Items.Select(detail => detail.GetType().Name)+ .Order()+ .ToList();++ // A new kind of operation fails this until it is given facts and a row below.+ Assert.Equal(kinds, covered);+ }++ [Theory]+ [MemberData(nameof(EveryOperationDetail.All), MemberType = typeof(EveryOperationDetail))]+ public void EveryOperationStatesWhatItDidAndReadsDifferentlyWhenPutBack(ChangeDetail detail)+ {+ var applied = ChangeDetailPresentation.For(+ detail,+ ChangeKind.Change,+ ChangeRecordOperation.Apply+ );+ var reverted = ChangeDetailPresentation.For(+ detail,+ ChangeKind.Change,+ ChangeRecordOperation.Revert+ );++ Assert.False(string.IsNullOrEmpty(applied.ActionKey));+ Assert.NotEmpty(applied.Chips);+ Assert.False(string.IsNullOrEmpty(reverted.ActionKey));+ Assert.NotEqual(applied.ActionKey, reverted.ActionKey);+ }++ [Theory]+ [MemberData(nameof(EveryOperationDetail.All), MemberType = typeof(EveryOperationDetail))]+ public void EveryKeyARowCanShowResolvesToText(ChangeDetail detail)+ {+ // The module names its resource keys as literals, so a typo would reach the UI as a raw key.+ foreach (+ var operation in new[] { ChangeRecordOperation.Apply, ChangeRecordOperation.Revert }+ )+ foreach (var kind in new[] { ChangeKind.Change, ChangeKind.Skip })+ {+ var row = ChangeDetailPresentation.For(detail, kind, operation);+ var keys = row+ .Chips.SelectMany(chip =>+ chip.ValueIsKey ? new[] { chip.LabelKey, chip.Value } : [chip.LabelKey]+ )+ .ToList();++ if (row.ActionKey is { } action)+ keys.Add(action);++ foreach (var key in keys)+ {+ var text = Loc.Instance[key];+ Assert.False(string.IsNullOrWhiteSpace(text), $"no text for {key}");+ Assert.NotEqual(key, text);+ }+ }+ }++ [Fact]+ public void AStepThatWroteNothingStatesWhatItFoundAndNoAction()+ {+ var row = ChangeDetailPresentation.For(+ new ServiceStartupDetail+ {+ ServiceName = "DiagTrack",+ PreviousStartupType = ServiceStartupType.Disabled,+ },+ ChangeKind.Skip,+ ChangeRecordOperation.Apply+ );++ Assert.Null(row.ActionKey);+ Assert.Contains(row.Chips, chip => chip.Value == "DiagTrack" && chip.ValueIsKey == false);+ Assert.Contains(+ row.Chips,+ chip =>+ chip.LabelKey == "Optimizer.Details.Field.StartupState"+ && chip.Value == "Optimizer.Details.Value.Startup.Disabled"+ );+ }++ [Fact]+ public void EveryChipSaysWhetherItsValueIsAWordOrAValue()+ {+ var registry = ChangeDetailPresentation.For(+ new RegistryValueWriteDetail+ {+ Target = @"HKLM\Test\A",+ ValueName = "V",+ ValueType = "DWord",+ PreviousValue = "1",+ NewValue = "0",+ },+ ChangeKind.Change,+ ChangeRecordOperation.Apply+ );++ // A path, a name, a type and a value are shown as they are, never translated.+ Assert.Contains(+ registry.Chips,+ chip => chip.LabelKey == "Optimizer.Details.Field.Path" && !chip.ValueIsKey+ );+ Assert.Contains(registry.Chips, chip => chip.Value == "REG_DWORD" && !chip.ValueIsKey);++ // A startup type is one of the app's own words, so it travels as the key of its wording.+ var service = ChangeDetailPresentation.For(+ new ServiceStartupDetail+ {+ ServiceName = "DiagTrack",+ PreviousStartupType = ServiceStartupType.Automatic,+ NewStartupType = ServiceStartupType.Disabled,+ },+ ChangeKind.Change,+ ChangeRecordOperation.Apply+ );++ Assert.Contains(+ service.Chips,+ chip =>+ chip.LabelKey == "Optimizer.Details.Field.Previous"+ && chip.Value == "Optimizer.Details.Value.Startup.Automatic"+ && chip.ValueIsKey+ );+ Assert.Contains(+ service.Chips,+ chip =>+ chip.LabelKey == "Optimizer.Details.Field.New"+ && chip.Value == "Optimizer.Details.Value.Startup.Disabled"+ && chip.ValueIsKey+ );+ }++ [Fact]+ public void APreviousValueThatWasNotThereSaysSoAndAHibernationStateThatCouldNotBeReadSaysUnknown()+ {+ var absent = ChangeDetailPresentation.For(+ new RegistryValueWriteDetail+ {+ Target = @"HKLM\Test\A",+ ValueName = "V",+ NewValue = "0",+ },+ ChangeKind.Change,+ ChangeRecordOperation.Apply+ );++ Assert.Contains(+ absent.Chips,+ chip =>+ chip.LabelKey == "Optimizer.Details.Field.Previous"+ && chip.Value == "Optimizer.Details.Field.Previous.None"+ );++ // An unreadable state is its own answer: it is never shown as off, and never as absent.+ var unknown = ChangeDetailPresentation.For(+ new HibernationDetail { PreviousPresent = null, NewPresent = false },+ ChangeKind.Change,+ ChangeRecordOperation.Apply+ );++ Assert.Contains(+ unknown.Chips,+ chip =>+ chip.LabelKey == "Optimizer.Details.Field.Previous"+ && chip.Value == "Optimizer.Details.Value.Unknown"+ );+ Assert.DoesNotContain(+ unknown.Chips,+ chip => chip.Value == "Optimizer.Details.Field.Previous.None"+ );+ }++ [Fact]+ public void RestoringHibernationIsWordedAsTurningItBackOn()+ {+ var turnedBackOn = ChangeDetailPresentation.For(+ new HibernationDetail { PreviousPresent = false, NewPresent = true },+ ChangeKind.Change,+ ChangeRecordOperation.Revert+ );++ Assert.Equal("Optimizer.Details.Op.HibernationEnable", turnedBackOn.ActionKey);++ var restoredToAbsent = ChangeDetailPresentation.For(+ new HibernationDetail { PreviousPresent = true, NewPresent = false },+ ChangeKind.Change,+ ChangeRecordOperation.Revert+ );++ Assert.Equal("Optimizer.Details.Op.HibernationRestore", restoredToAbsent.ActionKey);+ }++ [Fact]+ public void TheUsbPassShowsHowManyDevicesItTouchedAndNothingElse()+ {+ var row = ChangeDetailPresentation.For(+ new UsbPowerDetail { DeviceCount = 3 },+ ChangeKind.Change,+ ChangeRecordOperation.Apply+ );++ var chip = Assert.Single(row.Chips);+ Assert.Equal("Optimizer.Details.Field.Devices", chip.LabelKey);+ Assert.Equal("3", chip.Value);+ }++ [Fact]+ public void APowerSettingShowsItsNameAndFallsBackToItsIdentifier()+ {+ var named = ChangeDetailPresentation.For(+ new PowerSettingDetail+ {+ SettingId = "1F0B4FA0-8E9E-4D8A-9C4B-1E0A2F5B7C31",+ SettingName = "Processor performance",+ PreviousValue = "AC 100 / DC 50",+ NewValue = "AC 80 / DC 40",+ },+ ChangeKind.Change,+ ChangeRecordOperation.Apply+ );++ Assert.Equal("Processor performance", named.ActionArg);+ Assert.Contains(+ named.Chips,+ chip =>+ chip.LabelKey == "Optimizer.Details.Field.Setting"+ && chip.Value == "Processor performance"+ );++ var unnamed = ChangeDetailPresentation.For(+ new PowerSettingDetail+ {+ SettingId = "1F0B4FA0-8E9E-4D8A-9C4B-1E0A2F5B7C31",+ PreviousValue = "AC 100 / DC 50",+ NewValue = "AC 80 / DC 40",+ },+ ChangeKind.Change,+ ChangeRecordOperation.Apply+ );++ Assert.Equal("1F0B4FA0-8E9E-4D8A-9C4B-1E0A2F5B7C31", unnamed.ActionArg);+ }++ [Fact]+ public void AReasonTheUiCannotWordIsLeftOutRatherThanShownAsACode()+ {+ var known = ChangeDetailPresentation.For(+ new ServiceStartupDetail { ServiceName = "Gone", Reason = "service.notFound" },+ ChangeKind.NotApplicable,+ ChangeRecordOperation.Apply+ );++ Assert.Contains(+ known.Chips,+ chip =>+ chip.LabelKey == "Optimizer.Details.Field.Reason"+ && chip.Value == "Optimizer.Details.Reason.ServiceNotFound"+ );++ var unknown = ChangeDetailPresentation.For(+ new ServiceStartupDetail { ServiceName = "Gone", Reason = "something.new" },+ ChangeKind.NotApplicable,+ ChangeRecordOperation.Apply+ );++ Assert.DoesNotContain(unknown.Chips, chip => chip.Value == "something.new");+ }+}diff --git a/optimizerDuck.Test/Services/History/ChangeRecordRetryTests.cs b/optimizerDuck.Test/Services/History/ChangeRecordRetryTests.csnew file mode 100644index 0000000..bb7c972--- /dev/null+++ b/optimizerDuck.Test/Services/History/ChangeRecordRetryTests.cs@@ -0,0 +1,186 @@+using System.IO;+using Microsoft.Extensions.Logging.Abstractions;+using optimizerDuck.Domain.Execution;+using optimizerDuck.Services.History;+using optimizerDuck.Services.Optimization;++namespace optimizerDuck.Test.Services.History;++/// <summary>+/// What a retry leaves in the record of the run: the step it recovered, the attempt it needed,+/// and the promise that a record which cannot be written changes nothing for the user.+/// </summary>+public class ChangeRecordRetryTests : IDisposable+{+ private readonly Guid _id = Guid.NewGuid();++ public void Dispose()+ {+ foreach (+ var path in new[]+ {+ ChangeRecordStore.PathFor(_id),+ ChangeRecordStore.PathFor(_id) + ".tmp",+ }+ )+ {+ try+ {+ if (File.Exists(path))+ File.Delete(path);+ }+ catch+ {+ // Ignore: a leftover record affects nothing else.+ }+ }+ }++ [Fact]+ public async Task ARetryThatRecoveredAStepRecordsTheAttemptThatSucceeded()+ {+ var failed = FailedStep();+ Seed(failed);++ var result = await OptimizationService.RetryFailedStepsWithResultsAsync(+ [failed],+ false,+ NullLogger.Instance,+ optimizationId: _id+ );++ Assert.Empty(result.FailedSteps);+ Assert.Equal(2, Assert.Single(result.RecoveredSteps).Attempt);++ var step = Assert.Single(Read()!.Steps);+ Assert.True(step.Ok);+ Assert.Equal(2, step.Attempt);+ Assert.Equal("registry.write", step.Operation);+ Assert.Equal(@"HKLM\Test\A", step.Target);+ Assert.Equal("0", step.NewValue);+ }++ [Fact]+ public async Task ARetryThatFailedAgainRecordsTheAttemptItReached()+ {+ var failed = FailedStep();+ Seed(failed);++ var again = failed with+ {+ Retry = _ => Task.FromResult(OpResult.Fail("Access denied again")),+ };++ var result = await OptimizationService.RetryFailedStepsWithResultsAsync(+ [again],+ false,+ NullLogger.Instance,+ optimizationId: _id+ );++ Assert.Empty(result.RecoveredSteps);+ Assert.Equal(2, Assert.Single(result.FailedSteps).Attempt);++ var step = Assert.Single(Read()!.Steps);+ Assert.False(step.Ok);+ Assert.Equal(2, step.Attempt);+ }++ [Fact]+ public async Task ARecordThatCannotBeWrittenLeavesTheRetryResultAlone()+ {+ var failed = FailedStep();+ Seed(failed);++ using (+ var _ = new FileStream(+ ChangeRecordStore.PathFor(_id),+ FileMode.Open,+ FileAccess.Read,+ FileShare.None+ )+ )+ {+ var result = await OptimizationService.RetryFailedStepsWithResultsAsync(+ [failed],+ false,+ NullLogger.Instance,+ optimizationId: _id+ );++ // A record that cannot be written is not an error the user sees.+ Assert.Empty(result.FailedSteps);+ Assert.Equal(2, Assert.Single(result.RecoveredSteps).Attempt);+ }++ Assert.False(Assert.Single(Read()!.Steps).Ok);+ }++ [Fact]+ public async Task ARetryWithoutAnItemToReportOnWritesNothing()+ {+ var failed = FailedStep();++ var result = await OptimizationService.RetryFailedStepsWithResultsAsync(+ [failed],+ false,+ NullLogger.Instance+ );++ Assert.Empty(result.FailedSteps);+ Assert.Null(Read());+ }++ private static Change FailedStep() =>+ new()+ {+ Index = 1,+ Name = "Registry",+ Description = "Write registry value: HKLM\\Test\\A",+ Kind = ChangeKind.Change,+ Ok = false,+ Error = "Access denied",+ Detail = new RegistryValueWriteDetail+ {+ Target = @"HKLM\Test\A",+ ValueName = "V",+ ValueType = "DWord",+ NewValue = "0",+ },+ Retry = call =>+ {+ call.Changes.Add(+ "Registry",+ "Wrote registry value: HKLM\\Test\\A",+ true,+ detail: new RegistryValueWriteDetail+ {+ Target = @"HKLM\Test\A",+ ValueName = "V",+ ValueType = "DWord",+ NewValue = "0",+ }+ );+ return Task.FromResult(OpResult.Success());+ },+ };++ private void Seed(Change failedStep) =>+ ChangeRecordStore.TryWrite(+ new ChangeRecord+ {+ Id = _id,+ OptimizationKey = "RetryRecordTest",+ LogName = "Retry record test",+ AppliedAt = DateTime.Now,+ StartedAt = DateTime.Now,+ ElapsedMs = 10,+ AppVersion = "0.0.0-test",+ WindowsVersion = "10.0.0",+ Outcome = "PartialSuccess",+ Steps = [ChangeRecord.StepOf(failedStep)],+ }+ );++ private ChangeRecord? Read() => ChangeRecordStore.TryRead(_id);+}diff --git a/optimizerDuck.Test/Services/History/ChangeRecordStoreTests.cs b/optimizerDuck.Test/Services/History/ChangeRecordStoreTests.csindex 05f4ad7..0929ea9 100644--- a/optimizerDuck.Test/Services/History/ChangeRecordStoreTests.cs+++ b/optimizerDuck.Test/Services/History/ChangeRecordStoreTests.cs@@ -11,11 +11,13 @@ public class ChangeRecordStoreTests : IDisposablepublic void Dispose(){- foreach (var path in new[]- {- ChangeRecordStore.PathFor(_id),- ChangeRecordStore.PathFor(_id) + ".tmp",- })+ foreach (+ var path in new[]+ {+ ChangeRecordStore.PathFor(_id),+ ChangeRecordStore.PathFor(_id) + ".tmp",+ }+ ){try{@@ -86,6 +88,61 @@ public class ChangeRecordStoreTests : IDisposableAssert.Equal(1, read.FailedCount);}+ [Fact]+ public void TryWrite_ThenTryRead_KeepsTheFactsOfTheRunAndItsSteps()+ {+ var record = NewRecord() with+ {+ StartedAt = new DateTime(2026, 1, 2, 3, 4, 0, DateTimeKind.Local),+ ElapsedMs = 1234,+ AppVersion = "9.9.9",+ WindowsVersion = "10.0.99999",+ Steps =+ [+ new ChangeRecordStep+ {+ Index = 1,+ Name = "Registry",+ Description = "Write registry value",+ Kind = ChangeKind.Change,+ Operation = "registry.write",+ Target = @"HKLM\Test\A",+ ValueName = "V",+ ValueType = "DWord",+ PreviousValue = "1",+ NewValue = "0",+ HasValuePair = true,+ NativeErrorCode = 5,+ RecordedAt = new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Local),+ ElapsedMs = 12,+ Attempt = 2,+ },+ ],+ };++ ChangeRecordStore.TryWrite(record);+ var read = ChangeRecordStore.TryRead(_id);++ Assert.NotNull(read);+ Assert.Equal("9.9.9", read.AppVersion);+ Assert.Equal("10.0.99999", read.WindowsVersion);+ Assert.Equal(1234, read.ElapsedMs);+ Assert.Equal(new DateTime(2026, 1, 2, 3, 4, 0, DateTimeKind.Local), read.StartedAt);++ var step = Assert.Single(read.Steps);+ Assert.Equal(1, step.Index);+ Assert.Equal(2, step.Attempt);+ Assert.Equal(5, step.NativeErrorCode);+ Assert.Equal(12, step.ElapsedMs);+ Assert.Equal(new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Local), step.RecordedAt);++ var detail = Assert.IsType<RegistryValueWriteDetail>(ChangeDetailCodec.Decode(step));+ Assert.Equal(@"HKLM\Test\A", detail.Target);+ Assert.Equal("V", detail.ValueName);+ Assert.Equal("1", detail.PreviousValue);+ Assert.Equal("0", detail.NewValue);+ }+[Fact]public void PathFor_IsOutsideTheRevertData(){diff --git a/optimizerDuck.Test/Services/OptimizationServices/RecycleBinServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/RecycleBinServiceTests.csindex f716d1d..bcc94f4 100644--- a/optimizerDuck.Test/Services/OptimizationServices/RecycleBinServiceTests.cs+++ b/optimizerDuck.Test/Services/OptimizationServices/RecycleBinServiceTests.cs@@ -3,8 +3,8 @@ using optimizerDuck.Services.System.Primitives;namespace optimizerDuck.Test.Services.OptimizationServices;/// <summary>-/// Live shell32 tests: real Recycle Bin state, no mocks. Nothing here destroys user data --/// the only emptying call runs on an empty bin, and the failure path targets an invalid root.+/// Live shell32 tests: real Recycle Bin state, no mocks. Nothing here destroys user data: the+/// queries only read, and the one emptying call targets an invalid root, which shell32 refuses./// </summary>public class RecycleBinServiceTests{@@ -58,30 +58,6 @@ public class RecycleBinServiceTestsAssert.NotEqual(0, errorCode);}- [Fact]- public void Empty_EmptyBin_Succeeds()- {- var totals = RecycleBinService.Query();- if (totals.ItemCount != 0)- {- Assert.Skip(- $"Recycle Bin holds {totals.ItemCount} item(s); emptying it here would destroy real user data, so this test only runs on an empty bin."- );- }-- var (succeeded, errorCode) = RecycleBinService.Empty();-- // A session without the desktop shell (a CI runner) answers the call with E_UNEXPECTED:- // there is nothing to empty there either, so that is an environment limit rather than a- // failure of the operation, and the app already reports it as "no space freed".- if (!succeeded && (uint)errorCode == 0x8000FFFF)- Assert.Skip(- "SHEmptyRecycleBin returned E_UNEXPECTED: no desktop shell in this session."- );-- Assert.True(succeeded, $"SHEmptyRecycleBin failed with 0x{errorCode:X8}");- }-[Fact]public void SuppressionFlags_AreTheThreeDocumentedOnes(){diff --git a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.csindex 0dbe257..f25a9f1 100644--- a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs+++ b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs@@ -65,7 +65,8 @@ public class RegistryServiceTests : IDisposableAssert.NotNull(step.CreatedSubKeys);Assert.Contains(step.CreatedSubKeys,- path => path.EndsWith(@"TestOptimizerDuck\CreatedByTest\Deeper", StringComparison.Ordinal)+ path =>+ path.EndsWith(@"TestOptimizerDuck\CreatedByTest\Deeper", StringComparison.Ordinal));}@@ -500,6 +501,7 @@ public class RegistryServiceTests : IDisposableRegistryService.Read<string>(new RegistryItem(nonEmptyKeyPath, "Value")));}+[Fact]public void Write_ValueAlreadySet_RecordsSkip(){@@ -559,6 +561,7 @@ public class RegistryServiceTests : IDisposableAssert.Equal(ChangeKind.NotApplicable, step.Kind);Assert.Null(step.Revert);}+[Fact]public void Write_RecordsTheFactsOfTheStep(){@@ -566,8 +569,9 @@ public class RegistryServiceTests : IDisposablevar call = NewCall();Assert.True(RegistryService.Write(call, new RegistryItem(path, "V", 1)).Ok);- var written = Assert.Single(call.Changes.Changes).Detail;- Assert.NotNull(written);+ var written = Assert.IsType<RegistryValueWriteDetail>(+ Assert.Single(call.Changes.Changes).Detail+ );Assert.Equal("registry.write", written.Operation);Assert.Equal(path, written.Target);Assert.Equal("V", written.ValueName);@@ -580,7 +584,8 @@ public class RegistryServiceTests : IDisposableAssert.True(RegistryService.Write(again, new RegistryItem(path, "V", 1)).Ok);var skipped = Assert.Single(again.Changes.Changes);Assert.Equal(ChangeKind.Skip, skipped.Kind);- Assert.Equal("1", skipped.Detail?.PreviousValue);- Assert.Equal("1", skipped.Detail?.NewValue);+ var skippedDetail = Assert.IsType<RegistryValueWriteDetail>(skipped.Detail);+ Assert.Equal("1", skippedDetail.PreviousValue);+ Assert.Equal("1", skippedDetail.NewValue);}}diff --git a/optimizerDuck.Test/Services/OptimizationServices/ShellServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/ShellServiceTests.csindex 2932ec5..f9456fc 100644--- a/optimizerDuck.Test/Services/OptimizationServices/ShellServiceTests.cs+++ b/optimizerDuck.Test/Services/OptimizationServices/ShellServiceTests.cs@@ -48,4 +48,37 @@ public class ShellServiceTestsAssert.Equal(0, result.ExitCode);}++ [Fact]+ public async Task AFailedCommandRecordsTheExitCodeItFailedWith()+ {+ var shell = NewShell();+ var call = new OpCall { Logger = NullLogger.Instance };++ var result = await shell.CMDAsync(+ "exit 3",+ call,+ ct: TestContext.Current.CancellationToken+ );++ Assert.False(result.Ok);+ var step = Assert.Single(call.Changes.Changes);+ Assert.Equal(3, step.NativeErrorCode);+ }++ [Fact]+ public async Task ACommandThatSucceedsRecordsNoCode()+ {+ var shell = NewShell();+ var call = new OpCall { Logger = NullLogger.Instance };++ var result = await shell.CMDAsync(+ "exit 0",+ call,+ ct: TestContext.Current.CancellationToken+ );++ Assert.True(result.Ok);+ Assert.Null(Assert.Single(call.Changes.Changes).NativeErrorCode);+ }}diff --git a/optimizerDuck.Test/Services/PowerPlanChangesTests.cs b/optimizerDuck.Test/Services/PowerPlanChangesTests.csindex 6940df1..db80e80 100644--- a/optimizerDuck.Test/Services/PowerPlanChangesTests.cs+++ b/optimizerDuck.Test/Services/PowerPlanChangesTests.cs@@ -81,7 +81,11 @@ public class PowerPlanChangesTestsvar plans = new StubPowerPlanService{WriteFunc = (_, _, _, _, _) =>- new SettingWriteResult(OpResult.Fail("PowerWriteDCValueIndex failed", null), 5u, 10u),+ new SettingWriteResult(+ OpResult.Fail("PowerWriteDCValueIndex failed", null),+ 5u,+ 10u+ ),};var call = NewCall();@@ -101,8 +105,11 @@ public class PowerPlanChangesTestsvar step = Assert.IsType<PowerSettingRevertStep>(change.Revert);Assert.Equal(5u, step.PreviousAcValue);Assert.Equal(10u, step.PreviousDcValue);- Assert.Equal("AC 5 / DC 10", change.Detail!.PreviousValue);- Assert.False(change.Detail.HasValuePair);+ var detail = Assert.IsType<PowerSettingDetail>(change.Detail);+ Assert.Equal("AC 5 / DC 10", detail.PreviousValue);++ // The write was refused, so the step has what it found and no after: it wrote nothing.+ Assert.Null(detail.NewValue);}[Fact]diff --git a/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs b/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.csindex 05efe71..406c94f 100644--- a/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs+++ b/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs@@ -129,30 +129,4 @@ public class DiskCleanupServiceTestsAssert.Empty(item.Path);Assert.False(item.CanOpenFolder);}-- [Fact]- public async Task CleanAsync_RecycleBinItem_ReportsNoFreedBytesForAnEmptyBin()- {- // The failing-empty half of the contract lives in RecycleBinServiceTests- // (Empty_InvalidRoot_FailsWithError): DiskCleanupService always empties every drive, so a- // failure cannot be forced here without either destroying real data or adding a- // test-only seam to the service.- var totals = RecycleBinService.Query();- if (totals.ItemCount != 0)- {- Assert.Skip(- $"Recycle Bin holds {totals.ItemCount} item(s); emptying it here would destroy real user data, so this test only runs on an empty bin."- );- }-- var service = NewService();- var item = DiskCleanupService.GetCleanupItems().Single(i => i.Id == "RecycleBin");-- await service.ScanAsync(item);- Assert.Equal(0, item.SizeBytes);-- var freed = await service.CleanAsync(item);-- Assert.Equal(0, freed);- }}diff --git a/optimizerDuck.Test/TestDoubles/EveryOperationDetail.cs b/optimizerDuck.Test/TestDoubles/EveryOperationDetail.csnew file mode 100644index 0000000..58e22d8--- /dev/null+++ b/optimizerDuck.Test/TestDoubles/EveryOperationDetail.cs@@ -0,0 +1,76 @@+using optimizerDuck.Domain.Execution;+using optimizerDuck.Domain.Optimizations.Models.Services;++namespace optimizerDuck.Test.TestDoubles;++/// <summary>+/// One step of every operation, with the facts that operation has. Shared by the tests that+/// have to make a statement about every kind at once, so a new kind is added in one place and+/// every such test fails until it is.+/// </summary>+public static class EveryOperationDetail+{+ public static IReadOnlyList<ChangeDetail> Items { get; } =+ [+ new RegistryValueWriteDetail+ {+ Target = @"HKLM\Test\A",+ ValueName = "V",+ ValueType = "DWord",+ PreviousValue = "1",+ NewValue = "0",+ },+ new RegistryValueRemoveDetail+ {+ Target = @"HKLM\Test\A",+ ValueName = "V",+ ValueType = "DWord",+ PreviousValue = "1",+ },+ new RegistryKeyCreateDetail { Target = @"HKLM\Test\A" },+ new RegistryKeyRemoveDetail { Target = @"HKLM\Test\A" },+ new ServiceStartupDetail+ {+ ServiceName = "DiagTrack",+ PreviousStartupType = ServiceStartupType.Automatic,+ NewStartupType = ServiceStartupType.Disabled,+ },+ new ScheduledTaskEnableDetail+ {+ TaskPath = @"\Microsoft\Test",+ PreviousEnabled = false,+ NewEnabled = true,+ },+ new ScheduledTaskDisableDetail+ {+ TaskPath = @"\Microsoft\Test",+ PreviousEnabled = true,+ NewEnabled = false,+ },+ new PowerPlanActivateDetail+ {+ PlanName = "Duck",+ PreviousPlanName = "Balanced",+ NewPlanName = "Duck",+ },+ new PowerPlanInstallDetail { PlanName = "Duck" },+ new PowerSettingDetail+ {+ SettingId = "1F0B4FA0-8E9E-4D8A-9C4B-1E0A2F5B7C31",+ SettingName = "Processor performance",+ PreviousValue = "AC 100 / DC 50",+ NewValue = "AC 80 / DC 40",+ },+ new HibernationDetail { PreviousPresent = true, NewPresent = false },+ new UsbPowerDetail { DeviceCount = 2 },+ ];++ public static TheoryData<ChangeDetail> All()+ {+ var data = new TheoryData<ChangeDetail>();+ foreach (var detail in Items)+ data.Add(detail);++ return data;+ }+}diff --git a/optimizerDuck.Test/UI/ViewModels/ChangeRecordStepViewModelTests.cs b/optimizerDuck.Test/UI/ViewModels/ChangeRecordStepViewModelTests.csindex 791d3af..3cfa9cd 100644--- a/optimizerDuck.Test/UI/ViewModels/ChangeRecordStepViewModelTests.cs+++ b/optimizerDuck.Test/UI/ViewModels/ChangeRecordStepViewModelTests.cs@@ -1,5 +1,6 @@using optimizerDuck.Domain.Execution;using optimizerDuck.Domain.Optimizations.Models;+using optimizerDuck.Domain.Optimizations.Models.Services;using optimizerDuck.Domain.UI;using optimizerDuck.Resources.Languages;using optimizerDuck.Services.Configuration;@@ -119,13 +120,11 @@ public class ChangeRecordStepViewModelTestsOk = false,Error = "Access denied",ErrorDetail = "System.UnauthorizedAccessException",- Detail = new ChangeDetail+ Detail = new ServiceStartupDetail{- Operation = "service.startup",- Target = "DiagTrack",- PreviousValue = "Automatic",- NewValue = "Disabled",- HasValuePair = true,+ ServiceName = "DiagTrack",+ PreviousStartupType = ServiceStartupType.Automatic,+ NewStartupType = ServiceStartupType.Disabled,},});@@ -139,6 +138,72 @@ public class ChangeRecordStepViewModelTestsAssert.Contains(row.Fields, field => field.Value == "DiagTrack");}+ [Fact]+ public void HowAStepWentIsShownOnlyWhenTheRecordCarriesIt()+ {+ var plain = new ChangeRecordStepViewModel(+ new ChangeRecordStep+ {+ Name = "Registry",+ Kind = ChangeKind.Change,+ RecordedAt = new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Local),+ ElapsedMs = 12,+ }+ );++ Assert.Contains(+ plain.Fields,+ field => field.Label == Loc.Instance["Optimizer.Details.Field.At"]+ );+ Assert.Contains(+ plain.Fields,+ field =>+ field.Label == Loc.Instance["Optimizer.Details.Field.Took"]+ && field.Value == "12 ms"+ );++ // A step that succeeded has no code and no second attempt to report.+ Assert.DoesNotContain(+ plain.Fields,+ field => field.Label == Loc.Instance["Optimizer.Details.Field.ErrorCode"]+ );+ Assert.DoesNotContain(+ plain.Fields,+ field => field.Label == Loc.Instance["Optimizer.Details.Field.Attempt"]+ );++ var retried = new ChangeRecordStepViewModel(+ new ChangeRecordStep+ {+ Name = "Service",+ Kind = ChangeKind.Change,+ Ok = false,+ Error = "Access denied",+ NativeErrorCode = 5,+ Attempt = 2,+ ElapsedMs = 1500,+ }+ );++ Assert.Contains(+ retried.Fields,+ field =>+ field.Label == Loc.Instance["Optimizer.Details.Field.ErrorCode"]+ && field.Value == "5"+ );+ Assert.Contains(+ retried.Fields,+ field =>+ field.Label == Loc.Instance["Optimizer.Details.Field.Attempt"] && field.Value == "2"+ );+ Assert.Contains(+ retried.Fields,+ field =>+ field.Label == Loc.Instance["Optimizer.Details.Field.Took"]+ && field.Value == "1.5 s"+ );+ }+[Fact]public void FailedStep_IsShownAsAFailureWithItsReason(){@@ -240,10 +305,9 @@ public class ChangeRecordRevertTestsName = "Service",Description = "Service 'Gone' not found (not present)",Kind = ChangeKind.NotApplicable,- Detail = new ChangeDetail+ Detail = new ServiceStartupDetail{- Operation = "service.startup",- Target = "Gone",+ ServiceName = "Gone",Reason = "service.notFound",},}@@ -266,13 +330,11 @@ public class ChangeRecordRevertTestsKind = ChangeKind.Change,Ok = false,Error = "Access denied",- Detail = new ChangeDetail+ Detail = new ServiceStartupDetail{- Operation = "service.startup",- Target = "X",- PreviousValue = "Automatic",- NewValue = "Disabled",- HasValuePair = true,+ ServiceName = "X",+ PreviousStartupType = ServiceStartupType.Automatic,+ NewStartupType = ServiceStartupType.Disabled,},};diff --git a/optimizerDuck/Domain/Execution/ChangeDetail.cs b/optimizerDuck/Domain/Execution/ChangeDetail.csindex 6d03ee8..dbda7db 100644--- a/optimizerDuck/Domain/Execution/ChangeDetail.cs+++ b/optimizerDuck/Domain/Execution/ChangeDetail.cs@@ -1,40 +1,215 @@+using optimizerDuck.Domain.Optimizations.Models.Services;+namespace optimizerDuck.Domain.Execution;/// <summary>-/// The structured facts of one recorded step, so the UI can say what happened in the user's-/// language instead of showing the English text written for the log. Providers fill what they-/// know; a step without a detail keeps its log description on screen.+/// The structured facts of one recorded step, as the kind of operation it actually is: one+/// record per operation, each carrying only the fields that operation has. A provider cannot+/// record a value name on a service step, and the view words a row from the kind it holds+/// instead of looking the operation up by name. Providers fill the record for their operation;+/// a step without a detail keeps its log description on screen./// </summary>-public sealed record ChangeDetail+public abstract record ChangeDetail{/// <summary>Stable operation name, for example <c>registry.write</c>. The UI localizes it.</summary>- public string? Operation { get; init; }+ public abstract string Operation { get; }++ /// <summary>+ /// Why a step wrote nothing, as a stable code the UI words itself, for example+ /// <c>service.notFound</c>. Null when there is nothing to explain. The one fact every kind+ /// may carry, because "why nothing was written" does not depend on what the operation is.+ /// </summary>+ public string? Reason { get; init; }- /// <summary>What was acted on: a key path, a service name, a task path.</summary>- public string? Target { get; init; }+ /// <summary>+ /// Whether this step moved between two values. A revert puts the pair back the other way+ /// round for those steps, and leaves a step that only counts things, like the USB power+ /// pass, exactly as it is. True is derived from the kind of operation, never passed in.+ /// </summary>+ public virtual bool HasValuePair => false;+}- /// <summary>The name of the value inside the target, when the operation has one.</summary>+/// <summary>Wrote a value inside a registry key, replacing whatever was there.</summary>+public sealed record RegistryValueWriteDetail : ChangeDetail+{+ public override string Operation => "registry.write";++ /// <summary>The key the value lives in.</summary>+ public required string Target { get; init; }++ /// <summary>The name of the value inside the key. Null for a key's default value.</summary>public string? ValueName { get; init; }/// <summary>The kind of data written, for example a registry value kind.</summary>public string? ValueType { get; init; }- /// <summary>The value before the step, when there was one. Null means there was none.</summary>+ /// <summary>The value before the step. Null means the value was not there at all.</summary>public string? PreviousValue { get; init; }- /// <summary>The value after the step, when it wrote one. Null means it removed one.</summary>+ /// <summary>The value after the step.</summary>public string? NewValue { get; init; }- /// <summary>- /// Why a step wrote nothing, as a stable code the UI words itself, for example- /// <c>service.notFound</c>. Null when there is nothing to explain.- /// </summary>- public string? Reason { get; init; }+ public override bool HasValuePair => true;+}++/// <summary>Removed a value from a registry key.</summary>+public sealed record RegistryValueRemoveDetail : ChangeDetail+{+ public override string Operation => "registry.delete";++ /// <summary>The key the value lived in.</summary>+ public required string Target { get; init; }++ /// <summary>The name of the value that was removed. Null for a key's default value.</summary>+ public string? ValueName { get; init; }++ /// <summary>The kind of data removed, for example a registry value kind.</summary>+ public string? ValueType { get; init; }++ /// <summary>What the value held before it was removed. Null if it held nothing readable.</summary>+ public string? PreviousValue { get; init; }++ public override bool HasValuePair => true;+}++/// <summary>Created a registry key.</summary>+public sealed record RegistryKeyCreateDetail : ChangeDetail+{+ public override string Operation => "registry.createKey";++ /// <summary>The key that was created.</summary>+ public required string Target { get; init; }+}++/// <summary>Deleted a registry key tree.</summary>+public sealed record RegistryKeyRemoveDetail : ChangeDetail+{+ public override string Operation => "registry.deleteKey";++ /// <summary>The key tree that was deleted.</summary>+ public required string Target { get; init; }+}++/// <summary>Changed how a Windows service starts.</summary>+public sealed record ServiceStartupDetail : ChangeDetail+{+ public override string Operation => "service.startup";++ /// <summary>The name of the service.</summary>+ public required string ServiceName { get; init; }++ /// <summary>The startup type before the step, when it could be read.</summary>+ public ServiceStartupType? PreviousStartupType { get; init; }++ /// <summary>The startup type after the step, when it was set.</summary>+ public ServiceStartupType? NewStartupType { get; init; }++ public override bool HasValuePair => true;+}++/// <summary>Enabled a scheduled task.</summary>+public sealed record ScheduledTaskEnableDetail : ChangeDetail+{+ public override string Operation => "task.enable";++ /// <summary>The full path of the task.</summary>+ public required string TaskPath { get; init; }++ /// <summary>Whether the task was enabled before the step. Null when that was not read.</summary>+ public bool? PreviousEnabled { get; init; }++ /// <summary>Whether the task is enabled after the step. Null when the step wrote nothing.</summary>+ public bool? NewEnabled { get; init; }++ public override bool HasValuePair => true;+}++/// <summary>Disabled a scheduled task.</summary>+public sealed record ScheduledTaskDisableDetail : ChangeDetail+{+ public override string Operation => "task.disable";++ /// <summary>The full path of the task.</summary>+ public required string TaskPath { get; init; }++ /// <summary>Whether the task was enabled before the step. Null when that was not read.</summary>+ public bool? PreviousEnabled { get; init; }++ /// <summary>Whether the task is enabled after the step. Null when the step wrote nothing.</summary>+ public bool? NewEnabled { get; init; }++ public override bool HasValuePair => true;+}++/// <summary>Made an existing power plan the active one.</summary>+public sealed record PowerPlanActivateDetail : ChangeDetail+{+ public override string Operation => "power.plan";++ /// <summary>The plan that was activated.</summary>+ public required string PlanName { get; init; }++ /// <summary>The plan that was active before the step, when it could be named.</summary>+ public string? PreviousPlanName { get; init; }++ /// <summary>The plan that is active after the step.</summary>+ public string? NewPlanName { get; init; }++ public override bool HasValuePair => true;+}++/// <summary>Installed a power plan from a file and activated it.</summary>+public sealed record PowerPlanInstallDetail : ChangeDetail+{+ public override string Operation => "power.planInstall";++ /// <summary>The plan that was installed.</summary>+ public required string PlanName { get; init; }+}++/// <summary>Changed the mains and battery values of one power setting.</summary>+public sealed record PowerSettingDetail : ChangeDetail+{+ public override string Operation => "power.setting";++ /// <summary>The setting's identifier, which is what a revert needs.</summary>+ public required string SettingId { get; init; }++ /// <summary>The setting's name as Windows reports it, when Windows can name it.</summary>+ public string? SettingName { get; init; }++ /// <summary>The values before the step, as one line.</summary>+ public string? PreviousValue { get; init; }++ /// <summary>The values after the step, as one line.</summary>+ public string? NewValue { get; init; }++ public override bool HasValuePair => true;+}++/// <summary>Turned hibernation and Fast Startup off.</summary>+public sealed record HibernationDetail : ChangeDetail+{+ public override string Operation => "hibernation";/// <summary>- /// Whether this step moved between two values. A revert puts the pair back the other way- /// round for those steps, and leaves a step that only counts things, like the USB power- /// pass, exactly as it is.+ /// Whether the hibernation file was there before the step. Null means the state could not+ /// be read, which is its own answer: a revert then leaves the system alone rather than+ /// guessing, and the row says the state is unknown./// </summary>- public bool HasValuePair { get; init; }+ public bool? PreviousPresent { get; init; }++ /// <summary>Whether the hibernation file is there after the step.</summary>+ public bool? NewPresent { get; init; }++ public override bool HasValuePair => true;+}++/// <summary>Turned USB power saving off across the machine's root hubs.</summary>+public sealed record UsbPowerDetail : ChangeDetail+{+ public override string Operation => "usb.power";++ /// <summary>How many devices the pass touched, or found already at the target.</summary>+ public int DeviceCount { get; init; }}diff --git a/optimizerDuck/Domain/Execution/ChangeDetailCodec.cs b/optimizerDuck/Domain/Execution/ChangeDetailCodec.csnew file mode 100644index 0000000..b06476c--- /dev/null+++ b/optimizerDuck/Domain/Execution/ChangeDetailCodec.cs@@ -0,0 +1,232 @@+using System.Globalization;+using optimizerDuck.Domain.Optimizations.Models.Services;++namespace optimizerDuck.Domain.Execution;++/// <summary>+/// The one place that maps the typed facts of a step to the flat fields the record file stores,+/// and back. The file keeps its field names and its shape, so a record written by an earlier+/// build still loads; what changes is that nothing else has to know how a detail is laid out.+/// </summary>+public static class ChangeDetailCodec+{+ /// <summary>+ /// The words the record file uses for a state that is on or off. Old records carry the same+ /// words, and the states they describe are still on or off, so one representation serves+ /// both and no record has to be rewritten.+ /// </summary>+ private const string StateEnabled = "Enabled";++ private const string StateDisabled = "Disabled";++ /// <summary>+ /// The step as the record file stores the facts of a detail, or the step with no facts when+ /// the provider recorded none. The detail fields are written from the kind the step is, so a+ /// field that operation has no meaning for stays empty.+ /// </summary>+ public static ChangeRecordStep WithDetail(this ChangeRecordStep step, ChangeDetail? detail)+ {+ if (detail is null)+ return step;++ // What every kind of step stores the same way: what it did, why it wrote nothing, and+ // whether it moved between two values. Each kind below adds the facts only it has.+ var stored = step with+ {+ Operation = detail.Operation,+ Reason = detail.Reason,+ HasValuePair = detail.HasValuePair,+ };++ return detail switch+ {+ RegistryValueWriteDetail value => stored with+ {+ Target = value.Target,+ ValueName = value.ValueName,+ ValueType = value.ValueType,+ PreviousValue = value.PreviousValue,+ NewValue = value.NewValue,+ },+ RegistryValueRemoveDetail value => stored with+ {+ Target = value.Target,+ ValueName = value.ValueName,+ ValueType = value.ValueType,+ PreviousValue = value.PreviousValue,+ },+ RegistryKeyCreateDetail key => stored with { Target = key.Target },+ RegistryKeyRemoveDetail key => stored with { Target = key.Target },+ ServiceStartupDetail service => stored with+ {+ Target = service.ServiceName,+ PreviousValue = service.PreviousStartupType?.ToString(),+ NewValue = service.NewStartupType?.ToString(),+ },+ ScheduledTaskEnableDetail task => stored with+ {+ Target = task.TaskPath,+ PreviousValue = StateWord(task.PreviousEnabled),+ NewValue = StateWord(task.NewEnabled),+ },+ ScheduledTaskDisableDetail task => stored with+ {+ Target = task.TaskPath,+ PreviousValue = StateWord(task.PreviousEnabled),+ NewValue = StateWord(task.NewEnabled),+ },+ PowerPlanActivateDetail plan => stored with+ {+ Target = plan.PlanName,+ PreviousValue = plan.PreviousPlanName,+ NewValue = plan.NewPlanName,+ },+ PowerPlanInstallDetail plan => stored with { Target = plan.PlanName },+ PowerSettingDetail setting => stored with+ {+ Target = setting.SettingId,+ DisplayName = setting.SettingName,+ PreviousValue = setting.PreviousValue,+ NewValue = setting.NewValue,+ },+ HibernationDetail hibernation => stored with+ {+ PreviousValue = StateWord(hibernation.PreviousPresent),+ NewValue = StateWord(hibernation.NewPresent),+ },+ UsbPowerDetail usb => stored with+ {+ NewValue = usb.DeviceCount.ToString(CultureInfo.InvariantCulture),+ },++ // A detail this build cannot lay out is stored without facts rather than as a guess.+ _ => step,+ };+ }++ /// <summary>+ /// The facts of a stored step, as the kind of operation it is, or <see langword="null" />+ /// for an operation this build does not know: that row falls back to the English description+ /// the log uses, and nothing else in the record changes. A stored value the operation has no+ /// meaning for is ignored rather than shown.+ /// </summary>+ public static ChangeDetail? Decode(ChangeRecordStep step)+ {+ // Every kind carries the reason, so the switch below only has to say what the operation is.+ return step.Operation switch+ {+ "registry.write" => new RegistryValueWriteDetail+ {+ Target = step.Target ?? string.Empty,+ ValueName = step.ValueName ?? string.Empty,+ ValueType = step.ValueType,+ PreviousValue = step.PreviousValue,+ NewValue = step.NewValue,+ Reason = step.Reason,+ },+ "registry.delete" => new RegistryValueRemoveDetail+ {+ Target = step.Target ?? string.Empty,+ ValueName = step.ValueName ?? string.Empty,+ ValueType = step.ValueType,+ PreviousValue = step.PreviousValue,+ Reason = step.Reason,+ },+ "registry.createKey" => new RegistryKeyCreateDetail+ {+ Target = step.Target ?? string.Empty,+ Reason = step.Reason,+ },+ "registry.deleteKey" => new RegistryKeyRemoveDetail+ {+ Target = step.Target ?? string.Empty,+ Reason = step.Reason,+ },+ "service.startup" => new ServiceStartupDetail+ {+ ServiceName = step.Target ?? string.Empty,+ PreviousStartupType = StartupType(step.PreviousValue),+ NewStartupType = StartupType(step.NewValue),+ Reason = step.Reason,+ },+ "task.enable" => new ScheduledTaskEnableDetail+ {+ TaskPath = step.Target ?? string.Empty,+ PreviousEnabled = State(step.PreviousValue) ?? false,+ NewEnabled = State(step.NewValue) ?? true,+ Reason = step.Reason,+ },+ "task.disable" => new ScheduledTaskDisableDetail+ {+ TaskPath = step.Target ?? string.Empty,+ PreviousEnabled = State(step.PreviousValue) ?? true,+ NewEnabled = State(step.NewValue) ?? false,+ Reason = step.Reason,+ },+ "power.plan" => new PowerPlanActivateDetail+ {+ PlanName = step.Target ?? string.Empty,+ PreviousPlanName = step.PreviousValue,+ NewPlanName = step.NewValue,+ Reason = step.Reason,+ },+ "power.planInstall" => new PowerPlanInstallDetail+ {+ PlanName = step.Target ?? string.Empty,+ Reason = step.Reason,+ },+ "power.setting" => new PowerSettingDetail+ {+ SettingId = step.Target ?? string.Empty,+ SettingName = step.DisplayName,+ PreviousValue = step.PreviousValue,+ NewValue = step.NewValue,+ Reason = step.Reason,+ },+ "hibernation" => new HibernationDetail+ {+ PreviousPresent = State(step.PreviousValue),+ NewPresent = State(step.NewValue),+ Reason = step.Reason,+ },+ "usb.power" => new UsbPowerDetail+ {+ DeviceCount = int.TryParse(+ step.NewValue,+ NumberStyles.Integer,+ CultureInfo.InvariantCulture,+ out var count+ )+ ? count+ : 0,+ Reason = step.Reason,+ },+ _ => null,+ };+ }++ /// <summary>The word the record file uses for a state, or null when the state is unknown.</summary>+ private static string? StateWord(bool? state) =>+ state switch+ {+ true => StateEnabled,+ false => StateDisabled,+ _ => null,+ };++ /// <summary>+ /// A state read back from the record file. A state the file does not carry, or one that+ /// says it is unknown, is unknown rather than off: a revert must not guess, and a row must+ /// not claim the machine was in a state it never recorded.+ /// </summary>+ private static bool? State(string? word) =>+ word switch+ {+ StateEnabled => true,+ StateDisabled => false,+ _ => null,+ };++ private static ServiceStartupType? StartupType(string? word) =>+ Enum.TryParse<ServiceStartupType>(word, out var parsed) ? parsed : null;+}diff --git a/optimizerDuck/Domain/Execution/ChangeRecord.cs b/optimizerDuck/Domain/Execution/ChangeRecord.csindex 029cedf..fd41d9f 100644--- a/optimizerDuck/Domain/Execution/ChangeRecord.cs+++ b/optimizerDuck/Domain/Execution/ChangeRecord.cs@@ -1,6 +1,7 @@using Newtonsoft.Json;using Newtonsoft.Json.Converters;using optimizerDuck.Common.Extensions;+using optimizerDuck.Common.Helpers;using optimizerDuck.Domain.Abstractions;namespace optimizerDuck.Domain.Execution;@@ -20,6 +21,17 @@ public sealed record ChangeRecordpublic DateTime AppliedAt { get; init; }+ /// <summary>When the run started, and how long it took, so the record says what it cost.</summary>+ public DateTime? StartedAt { get; init; }++ public long? ElapsedMs { get; init; }++ /// <summary>The build that wrote this record, so a report states which one produced it.</summary>+ public string? AppVersion { get; init; }++ /// <summary>The Windows version the run happened on, for the same reason.</summary>+ public string? WindowsVersion { get; init; }+/// <summary>Which run this record describes: the last apply, or the revert of it.</summary>[JsonConverter(typeof(StringEnumConverter))]public ChangeRecordOperation Operation { get; init; } = ChangeRecordOperation.Apply;@@ -33,8 +45,7 @@ public sealed record ChangeRecordpublic IReadOnlyList<ChangeRecordStep> Steps { get; init; } = [];/// <summary>Counts the steps that ended with one kind and did not fail.</summary>- public int CountOf(ChangeKind kind) =>- Steps.Count(step => step.Ok && step.Kind == kind);+ public int CountOf(ChangeKind kind) => Steps.Count(step => step.Ok && step.Kind == kind);public int ChangedCount => CountOf(ChangeKind.Change);@@ -56,7 +67,8 @@ public sealed record ChangeRecordRevertedAt = at,Steps =[- .. Steps.Where(step => step.Kind == ChangeKind.Change)+ .. Steps+ .Where(step => step.Kind == ChangeKind.Change).Select(step =>step.HasValuePair? step with@@ -73,41 +85,86 @@ public sealed record ChangeRecord/// <summary>Captures one finished apply. The record is a copy: nothing here is live state.</summary>public static ChangeRecord From(ChangeSet changes, IOptimization item, string outcome){+ ArgumentNullException.ThrowIfNull(changes);+return new ChangeRecord{Id = item.Id,OptimizationKey = item.OptimizationKey,LogName = item.LogName(),AppliedAt = DateTime.Now,+ StartedAt = changes.StartedAt,+ ElapsedMs = changes.ElapsedMs,+ AppVersion = Shared.FileVersion,+ WindowsVersion = Environment.OSVersion.Version.ToString(),Outcome = outcome,+ Steps = [.. changes.Changes.OrderBy(change => change.Index).Select(StepOf)],+ };+ }++ /// <summary>+ /// The same record as a retry leaves it: a step the retry took further takes the outcome the+ /// retry reached and counts one more attempt, and a step the retry did not touch keeps what+ /// it had. What the retry wrote is what the record then says, so the history shows a step+ /// that needed a second attempt instead of only that it once failed.+ /// </summary>+ /// <param name="recovered">The steps the retry recovered.</param>+ /// <param name="stillFailed">The steps that failed again.</param>+ /// <returns>The record as the retry leaves it.</returns>+ public ChangeRecord Retried(IReadOnlyList<Change> recovered, IReadOnlyList<Change> stillFailed)+ {+ ArgumentNullException.ThrowIfNull(recovered);+ ArgumentNullException.ThrowIfNull(stillFailed);++ var retried = new Dictionary<int, Change>();+ foreach (var change in recovered)+ retried[change.Index] = change;+ foreach (var change in stillFailed)+ retried[change.Index] = change;++ if (retried.Count == 0)+ return this;++ return this with+ {Steps =[- .. changes- .Changes.OrderBy(change => change.Index)- .Select(change => new ChangeRecordStep- {- Name = change.Name,- Description = change.Description,- Kind = change.Kind,- Ok = change.Ok,- Error = change.Error,- Operation = change.Detail?.Operation,- Target = change.Detail?.Target,- ValueName = change.Detail?.ValueName,- ValueType = change.Detail?.ValueType,- PreviousValue = change.Detail?.PreviousValue,- NewValue = change.Detail?.NewValue,- HasValuePair = change.Detail?.HasValuePair ?? false,- Reason = change.Detail?.Reason,- }),+ .. Steps.Select(step =>+ retried.TryGetValue(step.Index, out var change) ? StepOf(change) : step+ ),],};}++ /// <summary>+ /// One recorded step as the file stores it. The facts of the operation go through the codec,+ /// which is the only thing that knows how a detail is laid out.+ /// </summary>+ internal static ChangeRecordStep StepOf(Change change) =>+ new ChangeRecordStep+ {+ Index = change.Index,+ Name = change.Name,+ Description = change.Description,+ Kind = change.Kind,+ Ok = change.Ok,+ Error = change.Error,+ NativeErrorCode = change.NativeErrorCode,+ RecordedAt = change.RecordedAt,+ ElapsedMs = change.ElapsedMs,+ Attempt = change.Attempt,+ }.WithDetail(change.Detail);}/// <summary>One step of a recorded apply, with the reason it wrote nothing when it did not.</summary>public sealed record ChangeRecordStep{+ /// <summary>+ /// The step's position in the run, kept as the revert file keeps it, so a record that was+ /// rewritten after a retry can still match a step to the attempt that changed it.+ /// </summary>+ public int Index { get; init; }+public string Name { get; init; } = string.Empty;public string Description { get; init; } = string.Empty;@@ -119,11 +176,31 @@ public sealed record ChangeRecordSteppublic string? Error { get; init; }+ /// <summary>+ /// The code the failure came from, as the system reported it. Null when there was no code,+ /// which is not the same as zero.+ /// </summary>+ public int? NativeErrorCode { get; init; }++ /// <summary>When the step finished, and how long its own work took.</summary>+ public DateTime? RecordedAt { get; init; }++ public long? ElapsedMs { get; init; }++ /// <summary>Which attempt this step is: 1, or one more for each retry.</summary>+ public int Attempt { get; init; } = 1;+/// <summary>The structured facts of the step, when the provider recorded them.</summary>public string? Operation { get; init; }public string? Target { get; init; }+ /// <summary>+ /// How the target is named to the user when Windows can name it, for example a power+ /// setting's name. Null when the target's identifier is all there is to show.+ /// </summary>+ public string? DisplayName { get; init; }+public string? ValueName { get; init; }public string? ValueType { get; init; }diff --git a/optimizerDuck/Domain/Execution/ChangeSet.cs b/optimizerDuck/Domain/Execution/ChangeSet.csindex 8236dd5..eee0e99 100644--- a/optimizerDuck/Domain/Execution/ChangeSet.cs+++ b/optimizerDuck/Domain/Execution/ChangeSet.cs@@ -1,4 +1,5 @@-using optimizerDuck.Domain.Abstractions;+using System.Diagnostics;+using optimizerDuck.Domain.Abstractions;using optimizerDuck.Domain.Optimizations.Models;using optimizerDuck.Services.Configuration;@@ -13,7 +14,15 @@ public sealed class ChangeSet{private readonly List<Change> _changes = [];private readonly Lock _gate = new();+ private readonly Stopwatch _clock = Stopwatch.StartNew();private int _sequence;+ private long _lastRecordedMs;++ /// <summary>When the run that collects these changes started.</summary>+ public DateTime StartedAt { get; } = DateTime.Now;++ /// <summary>How long the run has been going, for the record of what it did.</summary>+ public long ElapsedMs => _clock.ElapsedMilliseconds;/// <summary>All recorded changes in execution order.</summary>public IReadOnlyList<Change> Changes@@ -95,8 +104,20 @@ public sealed class ChangeSet/// Records a step Windows refused, so nothing was written and no compensation is/// expected for it./// </summary>- public Change AddRefused(string name, string description, ChangeDetail? detail = null) =>- Add(name, description, true, detail: detail, kind: ChangeKind.Refused);+ public Change AddRefused(+ string name,+ string description,+ ChangeDetail? detail = null,+ int? nativeErrorCode = null+ ) =>+ Add(+ name,+ description,+ true,+ detail: detail,+ kind: ChangeKind.Refused,+ nativeErrorCode: nativeErrorCode+ );/// <summary>/// Records a step that modified the system on purpose with no way back, so no@@ -115,7 +136,8 @@ public sealed class ChangeSetstring? errorDetail = null,Func<OpCall, Task<OpResult>>? retry = null,ChangeKind kind = ChangeKind.Change,- ChangeDetail? detail = null+ ChangeDetail? detail = null,+ int? nativeErrorCode = null){var change = new Change@@ -129,10 +151,24 @@ public sealed class ChangeSetErrorDetail = errorDetail,Retry = retry,Detail = detail,+ NativeErrorCode = nativeErrorCode,};lock (_gate){- _changes.Add(change with { Index = ++_sequence });+ // The span since the previous step was recorded, which is the work this step did:+ // a provider records a step as soon as it finishes.+ var elapsedMs = _clock.ElapsedMilliseconds;+ var stepMs = elapsedMs - _lastRecordedMs;+ _lastRecordedMs = elapsedMs;++ _changes.Add(+ change with+ {+ Index = ++_sequence,+ ElapsedMs = stepMs,+ RecordedAt = DateTime.Now,+ }+ );return _changes[^1];}}@@ -196,6 +232,29 @@ public sealed record Changepublic string? ErrorDetail { get; init; }+ /// <summary>+ /// The code the failure came from, as the system reported it: a Windows error code for a+ /// native call, or a process exit code for a program. Null when there was no code, which is+ /// not the same as zero.+ /// </summary>+ public int? NativeErrorCode { get; init; }++ /// <summary>When the step finished, so a record says when each of its steps ran.</summary>+ public DateTime? RecordedAt { get; init; }++ /// <summary>+ /// How long the step's own work took, in milliseconds. It is measured as the time since the+ /// previous step was recorded, so a provider that records its step long after finishing is+ /// counted into its own duration.+ /// </summary>+ public long? ElapsedMs { get; init; }++ /// <summary>+ /// Which attempt this step is: 1 for the run that recorded it, one more for each retry that+ /// took it further.+ /// </summary>+ public int Attempt { get; init; } = 1;+public Func<OpCall, Task<OpResult>>? Retry { get; init; }}diff --git a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.csindex d57176f..922e7c4 100644--- a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs+++ b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs@@ -1,6 +1,6 @@using System.Collections.ObjectModel;-using System.IO;using System.Globalization;+using System.IO;using Microsoft.Extensions.Logging;using Newtonsoft.Json;using Newtonsoft.Json.Linq;@@ -68,12 +68,7 @@ public class PowerManagement : LocalizedObject, IOptimizationCategorycall.Changes.AddSkip(ServiceStrings.HibernationName,ServiceStrings.HibernationDescriptionDisable,- new ChangeDetail- {- Operation = HibernationAction,- PreviousValue = HibernationStateDisabled,- HasValuePair = true,- }+ new HibernationDetail { PreviousPresent = false, NewPresent = null });call.Logger.LogInformation("Hibernation already disabled, skipping");return OpResult.Success();@@ -89,22 +84,19 @@ public class PowerManagement : LocalizedObject, IOptimizationCategoryServiceStrings.HibernationDescriptionDisable,true,revert,- detail: new ChangeDetail+ detail: new HibernationDetail{- Operation = HibernationAction,- HasValuePair = true,- PreviousValue = wasPresent switch- {- true => HibernationStateEnabled,- false => HibernationStateDisabled,- _ => null,- },- NewValue = HibernationStateDisabled,+ PreviousPresent = wasPresent,+ NewPresent = false,});call.Logger.LogInformation("Disabled hibernation and Fast Startup. Previous state: {State}",- wasPresent is { } present ? present ? "Enabled" : "Disabled" : "Unknown"+ wasPresent is { } present+ ? present+ ? "Enabled"+ : "Disabled"+ : "Unknown");return OpResult.Success(revert);}@@ -132,10 +124,6 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory}}- internal const string HibernationAction = "hibernation";- internal const string HibernationStateEnabled = "Enabled";- internal const string HibernationStateDisabled = "Disabled";- internal const string UsbAction = "usb.power";internal const string UsbReasonNoDevices = "usb.noDevices";[Optimization(@@ -158,12 +146,7 @@ public class PowerManagement : LocalizedObject, IOptimizationCategorycontext.Changes.AddNotApplicable(ServiceStrings.UsbPowerName,ServiceStrings.UsbPowerInfoNoDevices,- new ChangeDetail- {- Operation = UsbAction,- NewValue = "0",- Reason = UsbReasonNoDevices,- }+ new UsbPowerDetail { DeviceCount = 0, Reason = UsbReasonNoDevices });return Task.FromResult(context.Changes.ToApplyResult());}@@ -228,7 +211,7 @@ public class PowerManagement : LocalizedObject, IOptimizationCategorycall.Changes.AddSkip(ServiceStrings.UsbPowerName,ServiceStrings.UsbPowerInfoAlreadyConfigured,- new ChangeDetail { Operation = UsbAction, NewValue = "0" }+ new UsbPowerDetail { DeviceCount = 0 });return OpResult.Success();}@@ -240,11 +223,7 @@ public class PowerManagement : LocalizedObject, IOptimizationCategorydescription,true,revertStep,- detail: new ChangeDetail- {- Operation = UsbAction,- NewValue = result.ChangedCount.ToString(CultureInfo.InvariantCulture),- }+ detail: new UsbPowerDetail { DeviceCount = result.ChangedCount });call.Logger.LogInformation("[USB][OK] power saving disabled, {Count} device(s) changed",diff --git a/optimizerDuck/Domain/UI/ChangeDetailPresentation.cs b/optimizerDuck/Domain/UI/ChangeDetailPresentation.csnew file mode 100644index 0000000..9ac1a22--- /dev/null+++ b/optimizerDuck/Domain/UI/ChangeDetailPresentation.cs@@ -0,0 +1,437 @@+using System.Globalization;+using optimizerDuck.Domain.Execution;+using optimizerDuck.Domain.Optimizations.Models.Services;+using Wpf.Ui.Controls;++namespace optimizerDuck.Domain.UI;++/// <summary>+/// One fact of a step, ready to be shown as a chip: a label, an icon and a value. The value is+/// either shown as it is, because a path or a number needs no translation, or it names a+/// resource key of its own, so a word such as a startup type follows the UI language.+/// </summary>+/// <param name="LabelKey">The resource key of the chip's label.</param>+/// <param name="Icon">The chip's icon.</param>+/// <param name="Value">The chip's value, or the key of its text when <paramref name="ValueIsKey" />.</param>+/// <param name="ValueIsKey">Whether the value names a resource key rather than being shown as it is.</param>+public sealed record DetailChip(+ string LabelKey,+ SymbolRegular Icon,+ string Value,+ bool ValueIsKey = false+);++/// <summary>+/// How the record words one step: the action it took, in the language of the run it belongs to,+/// and the facts it acted on.+/// </summary>+public sealed record ChangeDetailRow+{+ /// <summary>The resource key of the action, or null for a step that changed nothing.</summary>+ public string? ActionKey { get; init; }++ /// <summary>The action's argument, when the wording takes one.</summary>+ public string? ActionArg { get; init; }++ /// <summary>The facts of the step, in the order the record shows them.</summary>+ public IReadOnlyList<DetailChip> Chips { get; init; } = [];+}++/// <summary>+/// Maps the facts of a step to the row the record shows, next to+/// <see cref="ChangeKindPresentation" />. It is the only place that knows which fact belongs to+/// which operation and what it is called, so the view never looks an operation up by name.+/// </summary>+public static class ChangeDetailPresentation+{+ /// <summary>+ /// The row for one step, worded for the run it belongs to. A step that changed something+ /// states the action and, when it moved between two values, the pair it moved between;+ /// anything else states no action and shows the state it found instead. An operation this+ /// build does not know produces an empty row, which leaves the row on the log description.+ /// </summary>+ /// <param name="detail">The facts of the step, or null when it recorded none.</param>+ /// <param name="kind">What the step did, which decides whether it is phrased as an action.</param>+ /// <param name="operation">Which run the row belongs to, an apply or a revert.</param>+ public static ChangeDetailRow For(+ ChangeDetail? detail,+ ChangeKind kind,+ ChangeRecordOperation operation+ )+ {+ if (detail is null)+ return new ChangeDetailRow();++ var shape = ShapeOf(detail);+ var chips = new List<DetailChip>(shape.Chips);++ if (ReasonKey(detail.Reason) is { } reason)+ chips.Add(+ new DetailChip("Optimizer.Details.Field.Reason", SymbolRegular.Info24, reason, true)+ );++ // A step that changed something shows what it moved between; anything else shows the state+ // it found, because there is no after to speak of.+ if (kind == ChangeKind.Change && detail.HasValuePair)+ {+ if (shape.Pair is { } pair)+ {+ chips.Add(+ new DetailChip(+ "Optimizer.Details.Field.Previous",+ SymbolRegular.Clock24,+ pair.Previous ?? "Optimizer.Details.Field.Previous.None",+ pair.Previous is null || pair.PreviousIsKey+ )+ );++ if (pair.New is not null)+ chips.Add(+ new DetailChip(+ "Optimizer.Details.Field.New",+ SymbolRegular.Edit24,+ pair.New,+ pair.NewIsKey+ )+ );+ }+ }+ else if (shape.State is { } state)+ {+ chips.Add(state);+ }++ return new ChangeDetailRow+ {+ ActionKey =+ kind == ChangeKind.Change+ ? operation == ChangeRecordOperation.Revert+ ? shape.RevertKey+ : shape.ApplyKey+ : null,+ ActionArg = shape.ActionArg,+ Chips = chips,+ };+ }++ /// <summary>+ /// What each kind of operation shows: the wording of its action, the facts it always+ /// carries, the pair it moves between when it changes something, and the state a step that+ /// wrote nothing shows instead.+ /// </summary>+ private static DetailShape ShapeOf(ChangeDetail detail)+ {+ return detail switch+ {+ RegistryValueWriteDetail value => new DetailShape+ {+ ApplyKey = "Optimizer.Details.Op.RegistrySet",+ RevertKey = "Optimizer.Details.Op.RegistryRestore",+ ActionArg = value.ValueName,+ Chips = Facts(+ Chip("Optimizer.Details.Field.Path", SymbolRegular.FolderOpen24, value.Target),+ Chip(+ "Optimizer.Details.Field.ValueName",+ SymbolRegular.ToggleRight24,+ value.ValueName+ ),+ ValueType(value.ValueType)+ ),+ Pair = new DetailPair(value.PreviousValue, false, value.NewValue, false),+ State = Chip("Optimizer.Details.Field.Value", SymbolRegular.Edit24, value.NewValue),+ },+ RegistryValueRemoveDetail value => new DetailShape+ {+ ApplyKey = "Optimizer.Details.Op.RegistryDelete",+ RevertKey = "Optimizer.Details.Op.RegistryRestore",+ ActionArg = value.ValueName,+ Chips = Facts(+ Chip("Optimizer.Details.Field.Path", SymbolRegular.FolderOpen24, value.Target),+ Chip(+ "Optimizer.Details.Field.ValueName",+ SymbolRegular.ToggleRight24,+ value.ValueName+ ),+ ValueType(value.ValueType)+ ),+ Pair = new DetailPair(value.PreviousValue, false, null, false),+ State = Chip(+ "Optimizer.Details.Field.Value",+ SymbolRegular.Edit24,+ value.PreviousValue+ ),+ },+ RegistryKeyCreateDetail key => new DetailShape+ {+ ApplyKey = "Optimizer.Details.Op.RegistryCreateKey",+ RevertKey = "Optimizer.Details.Op.RegistryDeleteKey",+ Chips = Facts(+ Chip("Optimizer.Details.Field.Path", SymbolRegular.FolderOpen24, key.Target)+ ),+ },+ RegistryKeyRemoveDetail key => new DetailShape+ {+ ApplyKey = "Optimizer.Details.Op.RegistryDeleteKey",+ RevertKey = "Optimizer.Details.Op.RegistryRestoreKey",+ Chips = Facts(+ Chip("Optimizer.Details.Field.Path", SymbolRegular.FolderOpen24, key.Target)+ ),+ },+ ServiceStartupDetail service => new DetailShape+ {+ ApplyKey = "Optimizer.Details.Op.ServiceStartup",+ RevertKey = "Optimizer.Details.Op.ServiceRestore",+ ActionArg = service.ServiceName,+ Chips = Facts(+ Chip(+ "Optimizer.Details.Field.Service",+ SymbolRegular.Shield24,+ service.ServiceName+ )+ ),+ Pair = new DetailPair(+ StartupKey(service.PreviousStartupType),+ true,+ StartupKey(service.NewStartupType),+ true+ ),+ State = Chip(+ "Optimizer.Details.Field.StartupState",+ SymbolRegular.Shield24,+ StartupKey(service.NewStartupType ?? service.PreviousStartupType),+ true+ ),+ },+ ScheduledTaskEnableDetail task => new DetailShape+ {+ ApplyKey = "Optimizer.Details.Op.TaskEnable",+ RevertKey = "Optimizer.Details.Op.TaskDisable",+ ActionArg = task.TaskPath,+ Chips = TaskChips(task.TaskPath),+ Pair = new DetailPair(+ StateKey(task.PreviousEnabled),+ true,+ StateKey(task.NewEnabled),+ true+ ),+ State = Chip(+ "Optimizer.Details.Field.TaskState",+ SymbolRegular.Clock24,+ StateKey(task.NewEnabled ?? task.PreviousEnabled),+ true+ ),+ },+ ScheduledTaskDisableDetail task => new DetailShape+ {+ ApplyKey = "Optimizer.Details.Op.TaskDisable",+ RevertKey = "Optimizer.Details.Op.TaskEnable",+ ActionArg = task.TaskPath,+ Chips = TaskChips(task.TaskPath),+ Pair = new DetailPair(+ StateKey(task.PreviousEnabled),+ true,+ StateKey(task.NewEnabled),+ true+ ),+ State = Chip(+ "Optimizer.Details.Field.TaskState",+ SymbolRegular.Clock24,+ StateKey(task.NewEnabled ?? task.PreviousEnabled),+ true+ ),+ },+ PowerPlanActivateDetail plan => new DetailShape+ {+ ApplyKey = "Optimizer.Details.Op.PowerPlanActivate",+ RevertKey = "Optimizer.Details.Op.PowerPlanRestore",+ ActionArg = plan.PlanName,+ Chips = PlanChips(plan.PlanName),+ Pair = new DetailPair(plan.PreviousPlanName, false, plan.NewPlanName, false),+ },+ PowerPlanInstallDetail plan => new DetailShape+ {+ ApplyKey = "Optimizer.Details.Op.PowerPlanInstall",+ RevertKey = "Optimizer.Details.Op.PowerPlanUninstall",+ ActionArg = plan.PlanName,+ Chips = PlanChips(plan.PlanName),+ },+ PowerSettingDetail setting => new DetailShape+ {+ ApplyKey = "Optimizer.Details.Op.PowerSetting",+ RevertKey = "Optimizer.Details.Op.PowerSettingRestore",+ ActionArg = setting.SettingName ?? setting.SettingId,+ Chips = Facts(+ Chip(+ "Optimizer.Details.Field.Setting",+ SymbolRegular.Gauge24,+ setting.SettingName ?? setting.SettingId+ )+ ),+ Pair = new DetailPair(setting.PreviousValue, false, setting.NewValue, false),+ State = Chip(+ "Optimizer.Details.Field.Value",+ SymbolRegular.Edit24,+ setting.NewValue ?? setting.PreviousValue+ ),+ },+ HibernationDetail hibernation => new DetailShape+ {+ ApplyKey = "Optimizer.Details.Op.Hibernation",+ RevertKey =+ hibernation.NewPresent == true+ ? "Optimizer.Details.Op.HibernationEnable"+ : "Optimizer.Details.Op.HibernationRestore",+ Pair = new DetailPair(+ StateKey(hibernation.PreviousPresent) ?? "Optimizer.Details.Value.Unknown",+ true,+ StateKey(hibernation.NewPresent),+ true+ ),+ State = Chip(+ "Optimizer.Details.Field.HibernationState",+ SymbolRegular.BatteryCharge24,+ StateKey(hibernation.NewPresent ?? hibernation.PreviousPresent),+ true+ ),+ },+ UsbPowerDetail usb => new DetailShape+ {+ ApplyKey = "Optimizer.Details.Op.UsbPower",+ RevertKey = "Optimizer.Details.Op.UsbPowerRestore",+ Chips = Facts(+ new DetailChip(+ "Optimizer.Details.Field.Devices",+ SymbolRegular.NetworkAdapter16,+ usb.DeviceCount.ToString(CultureInfo.InvariantCulture)+ )+ ),+ },++ // An operation a record file names but this build does not know: its row keeps the+ // description the log wrote.+ _ => new DetailShape(),+ };+ }++ /// <summary>The chips of a row, without the ones that have nothing to show.</summary>+ private static IReadOnlyList<DetailChip> Facts(params DetailChip?[] chips) =>+ [.. chips.Where(chip => chip is not null).Select(chip => chip!)];++ private static IReadOnlyList<DetailChip> TaskChips(string taskPath) =>+ Facts(Chip("Optimizer.Details.Field.Task", SymbolRegular.Clock24, taskPath));++ private static IReadOnlyList<DetailChip> PlanChips(string planName) =>+ Facts(Chip("Optimizer.Details.Field.PowerPlan", SymbolRegular.BatteryCharge24, planName));++ /// <summary>A chip for one fact, or none when the step carries nothing to show in it.</summary>+ private static DetailChip? Chip(+ string labelKey,+ SymbolRegular icon,+ string? value,+ bool valueIsKey = false+ ) => string.IsNullOrEmpty(value) ? null : new DetailChip(labelKey, icon, value, valueIsKey);++ /// <summary>+ /// A registry value's kind as Windows itself names it, so the chip reads the same in every+ /// language and matches what a user sees in the registry editor.+ /// </summary>+ private static DetailChip? ValueType(string? valueType) =>+ valueType switch+ {+ null or "" => null,+ "DWord" => new DetailChip(+ "Optimizer.Details.Field.Type",+ SymbolRegular.Code24,+ "REG_DWORD"+ ),+ "QWord" => new DetailChip(+ "Optimizer.Details.Field.Type",+ SymbolRegular.Code24,+ "REG_QWORD"+ ),+ "String" => new DetailChip(+ "Optimizer.Details.Field.Type",+ SymbolRegular.Code24,+ "REG_SZ"+ ),+ "ExpandString" => new DetailChip(+ "Optimizer.Details.Field.Type",+ SymbolRegular.Code24,+ "REG_EXPAND_SZ"+ ),+ "MultiString" => new DetailChip(+ "Optimizer.Details.Field.Type",+ SymbolRegular.Code24,+ "REG_MULTI_SZ"+ ),+ "Binary" => new DetailChip(+ "Optimizer.Details.Field.Type",+ SymbolRegular.Code24,+ "REG_BINARY"+ ),+ _ => new DetailChip("Optimizer.Details.Field.Type", SymbolRegular.Code24, valueType),+ };++ private static string? StartupKey(ServiceStartupType? startupType) =>+ startupType switch+ {+ ServiceStartupType.Automatic => "Optimizer.Details.Value.Startup.Automatic",+ ServiceStartupType.AutomaticDelayedStart =>+ "Optimizer.Details.Value.Startup.AutomaticDelayed",+ ServiceStartupType.Manual => "Optimizer.Details.Value.Startup.Manual",+ ServiceStartupType.Disabled => "Optimizer.Details.Value.Startup.Disabled",+ _ => null,+ };++ /// <summary>+ /// A state that is on or off as the user reads it, or null when the state is not known: an+ /// unknown state is its own answer and is never shown as off.+ /// </summary>+ private static string? StateKey(bool? state) =>+ state switch+ {+ true => "Optimizer.Details.Value.Enabled",+ false => "Optimizer.Details.Value.Startup.Disabled",+ _ => null,+ };++ /// <summary>+ /// The sentence for a reason a provider recorded. A reason the UI does not know yet is left+ /// out rather than shown as a code.+ /// </summary>+ private static string? ReasonKey(string? reason) =>+ reason switch+ {+ "service.notFound" => "Optimizer.Details.Reason.ServiceNotFound",+ "task.notFound" => "Optimizer.Details.Reason.TaskNotFound",+ "registry.valueAbsent" => "Optimizer.Details.Reason.RegistryValueAbsent",+ "registry.keyExists" => "Optimizer.Details.Reason.RegistryKeyExists",+ "registry.keyAbsent" => "Optimizer.Details.Reason.RegistryKeyAbsent",+ "usb.noDevices" => "Optimizer.Details.Reason.UsbNoDevices",+ _ => null,+ };++ /// <summary>The two values a step moved between, which a revert reads the other way round.</summary>+ private sealed record DetailPair(+ string? Previous,+ bool PreviousIsKey,+ string? New,+ bool NewIsKey+ );++ /// <summary>Everything one kind of operation contributes to its row.</summary>+ private sealed record DetailShape+ {+ public string ApplyKey { get; init; } = string.Empty;++ public string? RevertKey { get; init; }++ public string? ActionArg { get; init; }++ public IReadOnlyList<DetailChip> Chips { get; init; } = [];++ public DetailPair? Pair { get; init; }++ public DetailChip? State { get; init; }+ }+}diff --git a/optimizerDuck/Resources/Languages/Translations.Designer.cs b/optimizerDuck/Resources/Languages/Translations.Designer.csindex 466160a..945f832 100644--- a/optimizerDuck/Resources/Languages/Translations.Designer.cs+++ b/optimizerDuck/Resources/Languages/Translations.Designer.cs@@ -3833,6 +3833,24 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to At.+ /// </summary>+ internal static string Optimizer_Details_Field_At {+ get {+ return ResourceManager.GetString("Optimizer.Details.Field.At", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Attempt.+ /// </summary>+ internal static string Optimizer_Details_Field_Attempt {+ get {+ return ResourceManager.GetString("Optimizer.Details.Field.Attempt", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to Devices./// </summary>@@ -3842,6 +3860,15 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to Error code.+ /// </summary>+ internal static string Optimizer_Details_Field_ErrorCode {+ get {+ return ResourceManager.GetString("Optimizer.Details.Field.ErrorCode", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to Hibernation state./// </summary>@@ -3959,6 +3986,15 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to Took.+ /// </summary>+ internal static string Optimizer_Details_Field_Took {+ get {+ return ResourceManager.GetString("Optimizer.Details.Field.Took", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to Type./// </summary>@@ -4328,6 +4364,33 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to Took.+ /// </summary>+ internal static string Optimizer_Details_Record_Took {+ get {+ return ResourceManager.GetString("Optimizer.Details.Record.Took", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to App version.+ /// </summary>+ internal static string Optimizer_Details_Record_Version {+ get {+ return ResourceManager.GetString("Optimizer.Details.Record.Version", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Windows.+ /// </summary>+ internal static string Optimizer_Details_Record_Windows {+ get {+ return ResourceManager.GetString("Optimizer.Details.Record.Windows", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to Already correct./// </summary>diff --git a/optimizerDuck/Resources/Languages/Translations.ar-SA.resx b/optimizerDuck/Resources/Languages/Translations.ar-SA.resxindex c0177f5..72d1243 100644--- a/optimizerDuck/Resources/Languages/Translations.ar-SA.resx+++ b/optimizerDuck/Resources/Languages/Translations.ar-SA.resx@@ -2546,5 +2546,26 @@<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>لا توجد منافذ USB جذرية على هذا الجهاز</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>المدة</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>الوقت</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>رمز الخطأ</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>المحاولة</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>إصدار التطبيق</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>إصدار Windows</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>المدة</value>+ </data></root>diff --git a/optimizerDuck/Resources/Languages/Translations.de-DE.resx b/optimizerDuck/Resources/Languages/Translations.de-DE.resxindex 50ba5b6..615b763 100644--- a/optimizerDuck/Resources/Languages/Translations.de-DE.resx+++ b/optimizerDuck/Resources/Languages/Translations.de-DE.resx@@ -2556,4 +2556,25 @@ Aktualisiere jetzt, um die neuesten Funktionen, Verbesserungen und Fehlerbehebun<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>Dieser PC hat keine USB-Root-Hubs</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>Dauer</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>Zeitpunkt</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>Fehlercode</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>Versuch</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>App-Version</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Windows-Version</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>Dauer</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.es-ES.resx b/optimizerDuck/Resources/Languages/Translations.es-ES.resxindex 0ecaa63..f7322ff 100644--- a/optimizerDuck/Resources/Languages/Translations.es-ES.resx+++ b/optimizerDuck/Resources/Languages/Translations.es-ES.resx@@ -4309,4 +4309,25 @@ Actualiza ahora para disfrutar de las nuevas funciones y mejoras.</value><data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>Este equipo no tiene concentradores USB raíz</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>Duración</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>Momento</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>Código de error</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>Intento</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>Versión de la aplicación</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Versión de Windows</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>Duración</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.fr-FR.resx b/optimizerDuck/Resources/Languages/Translations.fr-FR.resxindex 41fbdb7..74d803a 100644--- a/optimizerDuck/Resources/Languages/Translations.fr-FR.resx+++ b/optimizerDuck/Resources/Languages/Translations.fr-FR.resx@@ -2504,4 +2504,25 @@ Mettez à jour maintenant pour profiter des dernières fonctionnalités, amélio<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>Ce PC n'a pas de concentrateur USB racine</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>Durée</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>Moment</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>Code d'erreur</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>Tentative</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>Version de l'application</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Version de Windows</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>Durée</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.he-IL.resx b/optimizerDuck/Resources/Languages/Translations.he-IL.resxindex 841419d..3a3119f 100644--- a/optimizerDuck/Resources/Languages/Translations.he-IL.resx+++ b/optimizerDuck/Resources/Languages/Translations.he-IL.resx@@ -2561,4 +2561,25 @@<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>במחשב הזה אין רכזות USB</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>משך</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>זמן</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>קוד שגיאה</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>ניסיון</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>גרסת האפליקציה</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>גרסת Windows</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>משך</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.id-ID.resx b/optimizerDuck/Resources/Languages/Translations.id-ID.resxindex 91cc41c..b12a01a 100644--- a/optimizerDuck/Resources/Languages/Translations.id-ID.resx+++ b/optimizerDuck/Resources/Languages/Translations.id-ID.resx@@ -2561,4 +2561,25 @@ Perbarui sekarang untuk menikmati fitur terbaru, peningkatan, dan perbaikan bug.<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>PC ini tidak punya hub USB root</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>Durasi</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>Waktu</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>Kode kesalahan</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>Percobaan</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>Versi aplikasi</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Versi Windows</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>Durasi</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.it-IT.resx b/optimizerDuck/Resources/Languages/Translations.it-IT.resxindex 249b76e..4297da1 100644--- a/optimizerDuck/Resources/Languages/Translations.it-IT.resx+++ b/optimizerDuck/Resources/Languages/Translations.it-IT.resx@@ -2512,4 +2512,25 @@ Aggiorna ora per godere delle ultime funzionalità, miglioramenti e correzioni.<<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>Questo PC non ha hub USB root</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>Durata</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>Ora</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>Codice errore</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>Tentativo</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>Versione dell'app</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Versione di Windows</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>Durata</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.ja-JP.resx b/optimizerDuck/Resources/Languages/Translations.ja-JP.resxindex 3f6f837..11ae6f0 100644--- a/optimizerDuck/Resources/Languages/Translations.ja-JP.resx+++ b/optimizerDuck/Resources/Languages/Translations.ja-JP.resx@@ -2496,4 +2496,25 @@<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>この PC に USB ルート ハブがありません</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>所要時間</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>日時</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>エラー コード</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>試行</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>アプリのバージョン</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Windows のバージョン</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>所要時間</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.ko-KR.resx b/optimizerDuck/Resources/Languages/Translations.ko-KR.resxindex db235fb..072c324 100644--- a/optimizerDuck/Resources/Languages/Translations.ko-KR.resx+++ b/optimizerDuck/Resources/Languages/Translations.ko-KR.resx@@ -2495,4 +2495,25 @@<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>이 PC에는 USB 루트 허브가 없습니다</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>소요 시간</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>시각</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>오류 코드</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>시도</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>앱 버전</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Windows 버전</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>소요 시간</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.pl-PL.resx b/optimizerDuck/Resources/Languages/Translations.pl-PL.resxindex 77a77e6..cc5d137 100644--- a/optimizerDuck/Resources/Languages/Translations.pl-PL.resx+++ b/optimizerDuck/Resources/Languages/Translations.pl-PL.resx@@ -2504,4 +2504,25 @@ Zaktualizuj teraz, aby korzystać z najnowszych funkcji, ulepszeń i poprawek b<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>Ten komputer nie ma koncentratorów USB</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>Czas trwania</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>Czas</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>Kod błędu</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>Próba</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>Wersja aplikacji</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Wersja Windows</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>Czas trwania</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.pt-BR.resx b/optimizerDuck/Resources/Languages/Translations.pt-BR.resxindex caddf34..7c0e04a 100644--- a/optimizerDuck/Resources/Languages/Translations.pt-BR.resx+++ b/optimizerDuck/Resources/Languages/Translations.pt-BR.resx@@ -2504,4 +2504,25 @@ Atualize agora para desfrutar das últimas funcionalidades, melhorias e correç<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>Este PC não tem hubs USB raiz</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>Duração</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>Momento</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>Código de erro</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>Tentativa</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>Versão do aplicativo</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Versão do Windows</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>Duração</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resxindex 191b93a..610cab4 100644--- a/optimizerDuck/Resources/Languages/Translations.resx+++ b/optimizerDuck/Resources/Languages/Translations.resx@@ -2562,4 +2562,25 @@ Update now to enjoy the latest features, improvements, and bug fixes.</value><data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>This machine has no USB root hubs</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>Took</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>At</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>Error code</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>Attempt</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>App version</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Windows</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>Took</value>+ </data></root>diff --git a/optimizerDuck/Resources/Languages/Translations.ru-RU.resx b/optimizerDuck/Resources/Languages/Translations.ru-RU.resxindex 6cbe3e4..04bfebb 100644--- a/optimizerDuck/Resources/Languages/Translations.ru-RU.resx+++ b/optimizerDuck/Resources/Languages/Translations.ru-RU.resx@@ -2504,4 +2504,25 @@<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>На этом компьютере нет корневых USB-концентраторов</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>Затрачено</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>Время</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>Код ошибки</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>Попытка</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>Версия приложения</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Версия Windows</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>Затрачено</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.tr-TR.resx b/optimizerDuck/Resources/Languages/Translations.tr-TR.resxindex 2b70fd0..c2461d0 100644--- a/optimizerDuck/Resources/Languages/Translations.tr-TR.resx+++ b/optimizerDuck/Resources/Languages/Translations.tr-TR.resx@@ -2495,4 +2495,25 @@ En son özelliklerden, iyileştirmelerden ve hata düzeltmelerinden yararlanmak<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>Bu bilgisayarda USB kök hub yok</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>Süre</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>Zaman</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>Hata kodu</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>Deneme</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>Uygulama sürümü</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Windows sürümü</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>Süre</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx b/optimizerDuck/Resources/Languages/Translations.vi-VN.resxindex dc90677..db8e91f 100644--- a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx+++ b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx@@ -2496,4 +2496,25 @@ Cập nhật ngay để trải nghiệm các tính năng mới, cải tiến và<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>Máy không có thiết bị USB gốc nào</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>Thời gian</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>Thời điểm</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>Mã lỗi</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>Lần thử</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>Phiên bản ứng dụng</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Phiên bản Windows</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>Thời gian</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.zh-CN.resx b/optimizerDuck/Resources/Languages/Translations.zh-CN.resxindex e9df522..95b9e4c 100644--- a/optimizerDuck/Resources/Languages/Translations.zh-CN.resx+++ b/optimizerDuck/Resources/Languages/Translations.zh-CN.resx@@ -2512,4 +2512,25 @@<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>本机没有 USB 根集线器</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>耗时</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>时间</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>错误代码</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>尝试</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>应用版本</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Windows 版本</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>耗时</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.zh-TW.resx b/optimizerDuck/Resources/Languages/Translations.zh-TW.resxindex 0f577ef..b9d39ee 100644--- a/optimizerDuck/Resources/Languages/Translations.zh-TW.resx+++ b/optimizerDuck/Resources/Languages/Translations.zh-TW.resx@@ -2499,4 +2499,25 @@<data name="Optimizer.Details.Reason.UsbNoDevices" xml:space="preserve"><value>本機沒有 USB 根集線器</value></data>+ <data name="Optimizer.Details.Field.Took" xml:space="preserve">+ <value>耗時</value>+ </data>+ <data name="Optimizer.Details.Field.At" xml:space="preserve">+ <value>時間</value>+ </data>+ <data name="Optimizer.Details.Field.ErrorCode" xml:space="preserve">+ <value>錯誤碼</value>+ </data>+ <data name="Optimizer.Details.Field.Attempt" xml:space="preserve">+ <value>嘗試</value>+ </data>+ <data name="Optimizer.Details.Record.Version" xml:space="preserve">+ <value>應用程式版本</value>+ </data>+ <data name="Optimizer.Details.Record.Windows" xml:space="preserve">+ <value>Windows 版本</value>+ </data>+ <data name="Optimizer.Details.Record.Took" xml:space="preserve">+ <value>耗時</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.csindex 0972e4a..b5a0f87 100644--- a/optimizerDuck/Services/Optimization/OptimizationService.cs+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs@@ -438,7 +438,11 @@ public class OptimizationService(private static void MarkRecordReverted(IOptimization optimization, ILogger logger){var record = ChangeRecordStore.TryRead(optimization.Id, logger);- record ??= ChangeRecord.From(new ChangeSet(), optimization, nameof(ChangeRecordOperation.Revert));+ record ??= ChangeRecord.From(+ new ChangeSet(),+ optimization,+ nameof(ChangeRecordOperation.Revert)+ );ChangeRecordStore.TryWrite(record.Reverted(DateTime.Now), logger);}@@ -464,16 +468,15 @@ public class OptimizationService(// The record outlives the revert file, so it is read separately and never gates the// applied mark.var record = ChangeRecordStore.TryRead(opt.Id);- opt.State.AppliedSummary =- record is null- ? string.Empty- : Loc.Instance[- "Optimizer.UI.State.Applied.Summary",- record.ChangedCount,- record.CountOf(ChangeKind.Skip),- record.CountOf(ChangeKind.NotApplicable),- record.CountOf(ChangeKind.Refused)- ];+ opt.State.AppliedSummary = record is null+ ? string.Empty+ : Loc.Instance[+ "Optimizer.UI.State.Applied.Summary",+ record.ChangedCount,+ record.CountOf(ChangeKind.Skip),+ record.CountOf(ChangeKind.NotApplicable),+ record.CountOf(ChangeKind.Refused)+ ];}}@@ -599,8 +602,15 @@ public class OptimizationService(Index = step.Index,Name = capturedStep?.Name ?? step.Name,Description = capturedStep?.Description ?? step.Description,+ Kind = capturedStep?.Kind ?? step.Kind,Ok = true,Revert = capturedRevert,+ Detail = capturedStep?.Detail,+ NativeErrorCode = capturedStep?.NativeErrorCode,+ RecordedAt = capturedStep?.RecordedAt ?? step.RecordedAt,+ ElapsedMs = capturedStep?.ElapsedMs ?? step.ElapsedMs,+ // The step has now run twice, and the record says so.+ Attempt = step.Attempt + 1,};// A retry can recover more than one step, and each one carries the backup@@ -664,13 +674,52 @@ public class OptimizationService(if (!success)remainingFailedSteps.Add(- error != null ? step with { Error = error.Message } : step+ error != null+ ? step with+ {+ Error = error.Message,+ Attempt = step.Attempt + 1,+ }+ : step with+ {+ Attempt = step.Attempt + 1,+ });}+ // Best effort, like the record itself: what the retry reached is written back, and a record+ // that cannot be written changes neither the retry result nor the outcome already reported.+ if (optimizationId.HasValue)+ TryRecordRetry(optimizationId.Value, recoveredSteps, remainingFailedSteps, logger);+return new RetryFailedStepsResult(remainingFailedSteps, recoveredSteps);}+ /// <summary>+ /// Writes what a retry changed into the record of the run, never throwing: the record is a+ /// report, and a report that cannot be written is not a reason to fail the retry.+ /// </summary>+ private static void TryRecordRetry(+ Guid optimizationId,+ IReadOnlyList<Change> recovered,+ IReadOnlyList<Change> stillFailed,+ ILogger logger+ )+ {+ try+ {+ var record = ChangeRecordStore.TryRead(optimizationId, logger);+ if (record is null)+ return;++ ChangeRecordStore.TryWrite(record.Retried(recovered, stillFailed), logger);+ }+ catch (Exception ex)+ {+ logger.LogWarning(ex, "Failed to record the retry for {Id}", optimizationId);+ }+ }+private async Task TrySaveRevertDataAsync(ChangeSet changes,IOptimization optimization,diff --git a/optimizerDuck/Services/System/Primitives/PowerPlanChanges.cs b/optimizerDuck/Services/System/Primitives/PowerPlanChanges.csindex ae661d4..594cd16 100644--- a/optimizerDuck/Services/System/Primitives/PowerPlanChanges.cs+++ b/optimizerDuck/Services/System/Primitives/PowerPlanChanges.cs@@ -46,7 +46,7 @@ public static class PowerPlanChangescall.Changes.AddSkip(ServiceStrings.PowerPlanName,ServiceStrings.Format("Power plan {0} already active (skipped)", name),- PlanStep(ActivateAction, name, name, null)+ new PowerPlanActivateDetail { PlanName = name, PreviousPlanName = name });return OpResult.Success();}@@ -61,12 +61,13 @@ public static class PowerPlanChangesServiceStrings.Format("Activate power plan {0}", name),true,step,- detail: PlanStep(- ActivateAction,- name,- plans.GetSchemeName(previousId.Value) ?? previousId.Value.ToString(),- name- )+ detail: new PowerPlanActivateDetail+ {+ PlanName = name,+ PreviousPlanName =+ plans.GetSchemeName(previousId.Value) ?? previousId.Value.ToString(),+ NewPlanName = name,+ });return OpResult.Success(step);}@@ -118,7 +119,8 @@ public static class PowerPlanChangesreturn install;}- var name = plans.GetSchemeName(install.InstalledId.Value) ?? install.InstalledId.ToString();+ var name =+ plans.GetSchemeName(install.InstalledId.Value) ?? install.InstalledId.Value.ToString();var step = new PowerPlanRevertStep{PreviousSchemeId = install.PreviousId.Value,@@ -129,7 +131,7 @@ public static class PowerPlanChangesServiceStrings.Format("Install power plan {0}", name),true,step,- detail: PlanStep(InstallAction, name, null, null)+ detail: new PowerPlanInstallDetail { PlanName = name });return new InstallResult(OpResult.Success(step), install.InstalledId, install.PreviousId);}@@ -184,6 +186,13 @@ public static class PowerPlanChanges};}+ var facts = new PowerSettingDetail+ {+ SettingId = settingId.ToString(),+ SettingName = plans.GetSetting(schemeId, subgroupId, settingId)?.Name,+ PreviousValue = previousPair,+ };+if (!result.Ok || step is null){call.Changes.Add(@@ -205,15 +214,7 @@ public static class PowerPlanChangesdcValue)),- detail:- previousPair is null- ? null- : new ChangeDetail- {- Operation = SettingAction,- Target = settingId.ToString(),- PreviousValue = previousPair,- }+ detail: previousPair is null ? null : facts);return result;}@@ -223,36 +224,11 @@ public static class PowerPlanChangesdescription,true,step,- detail: new ChangeDetail+ detail: facts with{- Operation = SettingAction,- Target = settingId.ToString(),- PreviousValue = previousPair,NewValue = $"AC {acValue} / DC {dcValue}",- HasValuePair = true,});return OpResult.Success(step);}- internal const string ActivateAction = "power.plan";- internal const string InstallAction = "power.planInstall";- internal const string SettingAction = "power.setting";-- /// <summary>The facts of one power plan step, for a UI that localizes them.</summary>- private static ChangeDetail PlanStep(- string operation,- string? name,- string? previous,- string? current- )- {- return new ChangeDetail- {- Operation = operation,- Target = name,- PreviousValue = previous,- NewValue = current,- HasValuePair = operation is ActivateAction,- };- }}diff --git a/optimizerDuck/Services/System/Primitives/RegistryService.cs b/optimizerDuck/Services/System/Primitives/RegistryService.csindex 9ac6c39..658ff8c 100644--- a/optimizerDuck/Services/System/Primitives/RegistryService.cs+++ b/optimizerDuck/Services/System/Primitives/RegistryService.cs@@ -382,6 +382,14 @@ public static class RegistryServicevar backupKind = valueExists? regKey.GetValueKind(valueName): RegistryValueKind.Unknown;+ var facts = new RegistryValueWriteDetail+ {+ Target = item.Path,+ ValueName = item.Name,+ ValueType = item.Kind.ToString(),+ PreviousValue = DescribeValue(backupValue),+ NewValue = DescribeValue(item.Value),+ };if (valueExists@@ -394,17 +402,7 @@ public static class RegistryServiceitem.Path,item.Name!);- call.Changes.AddSkip(- name,- description,- RegistryDetail(- RegistryOperationWrite,- item,- previous: backupValue,- newValue: item.Value,- valueType: item.Kind.ToString()- )- );+ call.Changes.AddSkip(name, description, facts);return OpResult.Success();}@@ -429,19 +427,7 @@ public static class RegistryServiceitem.Kind,item.Value);- call.Changes.Add(- name,- description,- true,- revertStep,- detail: RegistryDetail(- RegistryOperationWrite,- item,- previous: backupValue,- newValue: item.Value,- valueType: item.Kind.ToString()- )- );+ call.Changes.Add(name, description, true, revertStep, detail: facts);return OpResult.Success(revertStep);}catch (UnauthorizedAccessException)@@ -576,11 +562,12 @@ public static class RegistryServicecall.Changes.AddNotApplicable(name,description,- RegistryDetail(- RegistryOperationDelete,- item,- reason: RegistryReasonValueAbsent- )+ new RegistryValueRemoveDetail+ {+ Target = item.Path,+ ValueName = item.Name,+ Reason = RegistryReasonValueAbsent,+ });return OpResult.Success();}@@ -603,12 +590,13 @@ public static class RegistryServicedescription,true,revertStep,- detail: RegistryDetail(- RegistryOperationDelete,- item,- previous: backupValue,- valueType: backupKind.ToString()- )+ detail: new RegistryValueRemoveDetail+ {+ Target = item.Path,+ ValueName = item.Name,+ ValueType = backupKind.ToString(),+ PreviousValue = DescribeValue(backupValue),+ });return OpResult.Success(revertStep);}@@ -708,11 +696,11 @@ public static class RegistryServicecall.Changes.AddNotApplicable(name,description,- RegistryDetail(- RegistryOperationCreateKey,- item,- reason: RegistryReasonKeyExists- )+ new RegistryKeyCreateDetail+ {+ Target = item.Path,+ Reason = RegistryReasonKeyExists,+ });return OpResult.Success();}@@ -733,7 +721,7 @@ public static class RegistryServicedescription,true,revertStep,- detail: RegistryDetail(RegistryOperationCreateKey, item)+ detail: new RegistryKeyCreateDetail { Target = item.Path });return OpResult.Success(revertStep);}@@ -800,11 +788,11 @@ public static class RegistryServicecall.Changes.AddNotApplicable(name,description,- RegistryDetail(- RegistryOperationDeleteKey,- item,- reason: RegistryReasonKeyAbsent- )+ new RegistryKeyRemoveDetail+ {+ Target = item.Path,+ Reason = RegistryReasonKeyAbsent,+ });return OpResult.Success();}@@ -844,7 +832,7 @@ public static class RegistryServicedescription,true,revertStep,- detail: RegistryDetail(RegistryOperationDeleteKey, item)+ detail: new RegistryKeyRemoveDetail { Target = item.Path });return OpResult.Success(revertStep);}@@ -1172,49 +1160,15 @@ public static class RegistryService}}- internal const string RegistryOperationWrite = "registry.write";- internal const string RegistryOperationDelete = "registry.delete";- internal const string RegistryOperationCreateKey = "registry.createKey";- internal const string RegistryOperationDeleteKey = "registry.deleteKey";internal const string RegistryReasonValueAbsent = "registry.valueAbsent";internal const string RegistryReasonKeyExists = "registry.keyExists";internal const string RegistryReasonKeyAbsent = "registry.keyAbsent";- /// <summary>- /// The facts of one registry step, for a UI that localizes them. The description on the- /// step stays English for the log.- /// </summary>- private static ChangeDetail RegistryDetail(- string operation,- RegistryItem item,- object? previous = null,- object? newValue = null,- string? valueType = null,- string? reason = null- )- {- // Moving or removing a value is a before and an after; creating or deleting a key is not.- var hasValuePair = operation- is RegistryOperationWrite- or RegistryOperationDelete;-- return new ChangeDetail- {- Operation = operation,- Target = item.Path,- ValueName = item.Name,- ValueType = valueType,- PreviousValue = previous is null ? null : DescribeValue(previous),- NewValue = newValue is null ? null : DescribeValue(newValue),- HasValuePair = hasValuePair,- Reason = reason,- };- }-- /// <summary>A value as it is shown to the user, never localized.</summary>- private static string DescribeValue(object value) =>+ /// <summary>A value as it is shown to the user, never localized. Nothing to show stays null.</summary>+ private static string? DescribeValue(object? value) =>value switch{+ null => null,Array array => string.Join(", ", array.Cast<object?>()),_ => Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty,};diff --git a/optimizerDuck/Services/System/Primitives/ScheduledTaskService.cs b/optimizerDuck/Services/System/Primitives/ScheduledTaskService.csindex 771769f..4ad4b7d 100644--- a/optimizerDuck/Services/System/Primitives/ScheduledTaskService.cs+++ b/optimizerDuck/Services/System/Primitives/ScheduledTaskService.cs@@ -65,8 +65,15 @@ public static class ScheduledTaskServicecall.Logger.LogInformation("Task {Path} not found, nothing to change", fullPath);call.Changes.AddNotApplicable(ServiceStrings.ScheduledTaskName,- ServiceStrings.Format(ServiceStrings.ScheduledTaskInfoSkippedNotFound, fullPath),- TaskStep(DisableAction, fullPath, null, null, TaskReasonNotFound)+ ServiceStrings.Format(+ ServiceStrings.ScheduledTaskInfoSkippedNotFound,+ fullPath+ ),+ new ScheduledTaskDisableDetail+ {+ TaskPath = fullPath,+ Reason = TaskReasonNotFound,+ });return OpResult.Success();}@@ -82,7 +89,11 @@ public static class ScheduledTaskServicefullPath,"disabled"),- TaskStep(DisableAction, fullPath, TaskStateDisabled, null)+ new ScheduledTaskDisableDetail+ {+ TaskPath = fullPath,+ PreviousEnabled = false,+ });return OpResult.Success();}@@ -100,7 +111,12 @@ public static class ScheduledTaskServicedescription,true,revertStep,- detail: TaskStep(DisableAction, fullPath, TaskStateEnabled, TaskStateDisabled)+ detail: new ScheduledTaskDisableDetail+ {+ TaskPath = fullPath,+ PreviousEnabled = true,+ NewEnabled = false,+ });return OpResult.Success(revertStep);}@@ -166,8 +182,15 @@ public static class ScheduledTaskServicecall.Logger.LogInformation("Task {Path} not found, nothing to change", fullPath);call.Changes.AddNotApplicable(ServiceStrings.ScheduledTaskName,- ServiceStrings.Format(ServiceStrings.ScheduledTaskInfoSkippedNotFound, fullPath),- TaskStep(EnableAction, fullPath, null, null, TaskReasonNotFound)+ ServiceStrings.Format(+ ServiceStrings.ScheduledTaskInfoSkippedNotFound,+ fullPath+ ),+ new ScheduledTaskEnableDetail+ {+ TaskPath = fullPath,+ Reason = TaskReasonNotFound,+ });return OpResult.Success();}@@ -183,7 +206,11 @@ public static class ScheduledTaskServicefullPath,"enabled"),- TaskStep(EnableAction, fullPath, TaskStateEnabled, null)+ new ScheduledTaskEnableDetail+ {+ TaskPath = fullPath,+ PreviousEnabled = true,+ });return OpResult.Success();}@@ -201,7 +228,12 @@ public static class ScheduledTaskServicedescription,true,revertStep,- detail: TaskStep(EnableAction, fullPath, TaskStateDisabled, TaskStateEnabled)+ detail: new ScheduledTaskEnableDetail+ {+ TaskPath = fullPath,+ PreviousEnabled = false,+ NewEnabled = true,+ });return OpResult.Success(revertStep);}@@ -796,33 +828,5 @@ public static class ScheduledTaskService}#endregion Helpers- internal const string DisableAction = "task.disable";- internal const string EnableAction = "task.enable";- internal const string TaskStateEnabled = "Enabled";- internal const string TaskStateDisabled = "Disabled";-- /// <summary>- /// The facts of one task step, for a UI that localizes them. The states travel as words so- /// the UI can translate them; the description on the step stays English.- /// </summary>internal const string TaskReasonNotFound = "task.notFound";-- private static ChangeDetail TaskStep(- string operation,- string fullPath,- string? current,- string? target,- string? reason = null- )- {- return new ChangeDetail- {- Operation = operation,- Target = fullPath,- PreviousValue = current,- NewValue = target,- HasValuePair = true,- Reason = reason,- };- }}diff --git a/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs b/optimizerDuck/Services/System/Primitives/ServiceProcessService.csindex 7aa079e..5fd7bf4 100644--- a/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs+++ b/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs@@ -76,7 +76,11 @@ public static class ServiceProcessServicecall.Changes.AddNotApplicable(ServiceStrings.ServiceName,skipDescription,- ServiceStep(item, null, null, ServiceReasonNotFound)+ new ServiceStartupDetail+ {+ ServiceName = item.Name,+ Reason = ServiceReasonNotFound,+ });return MapToOpResult(ServiceChangeResult.NotFound, null, null, null);}@@ -118,7 +122,11 @@ public static class ServiceProcessServicecall.Changes.AddSkip(ServiceStrings.ServiceName,alreadyDescription,- ServiceStep(item, originalStartupType, null)+ new ServiceStartupDetail+ {+ ServiceName = item.Name,+ PreviousStartupType = originalStartupType,+ });return MapToOpResult(ServiceChangeResult.AlreadyConfigured, null, null, null);}@@ -159,7 +167,12 @@ public static class ServiceProcessServicedescription,true,revertStep,- detail: ServiceStep(item, originalStartupType, item.StartupType)+ detail: new ServiceStartupDetail+ {+ ServiceName = item.Name,+ PreviousStartupType = originalStartupType,+ NewStartupType = item.StartupType,+ });return MapToOpResult(ServiceChangeResult.Success, revertStep, null, null);}@@ -178,7 +191,12 @@ public static class ServiceProcessServicecall.Changes.AddRefused(ServiceStrings.ServiceName,accessDeniedError,- ServiceStep(item, originalStartupType, null)+ new ServiceStartupDetail+ {+ ServiceName = item.Name,+ PreviousStartupType = originalStartupType,+ },+ nativeError);return MapToOpResult(ServiceChangeResult.AccessDenied,@@ -214,11 +232,13 @@ public static class ServiceProcessServiceerror,errorDetail,retryCall => ChangeServiceStartupTypeAsync(retryCall, item),- detail: ServiceStep(- item,- originalStartupType,- write.StartTypeWritten ? item.StartupType : null- )+ detail: new ServiceStartupDetail+ {+ ServiceName = item.Name,+ PreviousStartupType = originalStartupType,+ NewStartupType = write.StartTypeWritten ? item.StartupType : null,+ },+ nativeErrorCode: nativeError);return MapToOpResult(ServiceChangeResult.Failed, partialRevert, error, errorDetail);}@@ -414,7 +434,7 @@ public static class ServiceProcessService? $"ChangeServiceConfig2 (delayed auto start) threw after the start type was written: {exceptionText}": startTypeWritten? $"ChangeServiceConfig2 (delayed auto start) failed with Win32 error {nativeError}, after the start type was written"- : $"ChangeServiceConfig failed with Win32 error {nativeError}";+ : $"ChangeServiceConfig failed with Win32 error {nativeError}";/// <summary>/// Writes the start type, then the delayed flag for auto-start targets. Returns the Win32@@ -593,29 +613,6 @@ public static class ServiceProcessService[DllImport("advapi32.dll", SetLastError = true)][return: MarshalAs(UnmanagedType.Bool)]private static extern bool CloseServiceHandle(IntPtr serviceHandle);- internal const string ServiceOperationStartup = "service.startup";- /// <summary>- /// The facts of one service step, for a UI that localizes them. The startup types travel as- /// their names so the UI can translate them; the description on the step stays English.- /// </summary>internal const string ServiceReasonNotFound = "service.notFound";-- private static ChangeDetail ServiceStep(- ServiceItem item,- ServiceStartupType? current,- ServiceStartupType? target,- string? reason = null- )- {- return new ChangeDetail- {- Operation = ServiceOperationStartup,- Target = item.Name,- PreviousValue = current?.ToString(),- NewValue = target?.ToString(),- HasValuePair = true,- Reason = reason,- };- }}diff --git a/optimizerDuck/Services/System/Primitives/ShellService.cs b/optimizerDuck/Services/System/Primitives/ShellService.csindex 0b4cce8..4f77d5f 100644--- a/optimizerDuck/Services/System/Primitives/ShellService.cs+++ b/optimizerDuck/Services/System/Primitives/ShellService.cs@@ -165,7 +165,8 @@ public sealed class ShellServicepolicy,retryCall,CancellationToken.None- )+ ),+ nativeErrorCode: success ? null : result.ExitCode);return success ? OpResult.Success(revertStep) : OpResult.Fail(error!, errorDetail);diff --git a/optimizerDuck/Services/System/SystemInfoService.cs b/optimizerDuck/Services/System/SystemInfoService.csindex 1087626..ec1432e 100644--- a/optimizerDuck/Services/System/SystemInfoService.cs+++ b/optimizerDuck/Services/System/SystemInfoService.cs@@ -63,7 +63,7 @@ internal static class WmiHelperScopeCache.Clear();}- // ponytail: static log hook (same pattern as PowerReader.Configure); per-instance wiring if a second writer appears.+ // static log hook (same pattern as PowerReader.Configure); per-instance wiring if a second writer appears.private static Action<string, Exception>? _onQueryFailed;/// <summary>Wires a debug sink for failed WMI queries. Null detaches.</summary>diff --git a/optimizerDuck/UI/Dialogs/OptimizationDetailsDialog.xaml b/optimizerDuck/UI/Dialogs/OptimizationDetailsDialog.xamlindex 1dc0c09..06d4e5b 100644--- a/optimizerDuck/UI/Dialogs/OptimizationDetailsDialog.xaml+++ b/optimizerDuck/UI/Dialogs/OptimizationDetailsDialog.xaml@@ -12,6 +12,35 @@d:DesignHeight="760"d:DesignWidth="760"mc:Ignorable="d">+ <UserControl.Resources>+ <!-- One fact of a record: a chip with its own icon, label and value. -->+ <DataTemplate x:Key="RecordFieldChip">+ <Border+ Margin="0,0,6,6"+ Padding="6,2"+ Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"+ CornerRadius="{StaticResource CornerRadiusSmall}">+ <StackPanel Orientation="Horizontal">+ <ui:SymbolIcon+ Margin="0,0,6,0"+ FontSize="14"+ Foreground="{DynamicResource TextFillColorSecondaryBrush}"+ Symbol="{Binding Icon}" />+ <ui:TextBlock+ VerticalAlignment="Center"+ FontTypography="Caption"+ Foreground="{DynamicResource TextFillColorSecondaryBrush}"+ Text="{Binding Label}" />+ <ui:TextBlock+ Margin="6,0,0,0"+ VerticalAlignment="Center"+ FontTypography="Caption"+ Text="{Binding Value}"+ TextWrapping="Wrap" />+ </StackPanel>+ </Border>+ </DataTemplate>+ </UserControl.Resources><StackPanel><BorderMargin="0,0,0,12"@@ -61,8 +90,8 @@Symbol="{Binding Icon}" /><ui:TextBlockVerticalAlignment="Center"- Foreground="{DynamicResource TextFillColorSecondaryBrush}"FontTypography="Caption"+ Foreground="{DynamicResource TextFillColorSecondaryBrush}"Text="{Binding Display}" /></StackPanel></Border>@@ -74,9 +103,7 @@Grid.Row="3"Margin="0,4,0,0"ColumnDefinitions="Auto,Auto,*">- <controls:RiskBadge- Risk="{Binding Optimization.Risk}"- RiskVisual="{Binding Optimization.RiskVisual}" />+ <controls:RiskBadge Risk="{Binding Optimization.Risk}" RiskVisual="{Binding Optimization.RiskVisual}" /><BorderGrid.Column="1"@@ -132,8 +159,8 @@FontTypography="BodyStrong"Text="{ext:Loc OptimizationDetailsDialog.DetailedDescription}" /><ui:TextBlock- Foreground="{DynamicResource TextFillColorSecondaryBrush}"FontTypography="Body"+ Foreground="{DynamicResource TextFillColorSecondaryBrush}"Text="{Binding Optimization.ShortDescription}"TextWrapping="Wrap" /></StackPanel>@@ -211,6 +238,18 @@TextWrapping="Wrap"Visibility="{Binding HasRecord, Converter={StaticResource BooleanToVisibilityConverter}}" />+ <ItemsControl+ Margin="16,8,16,0"+ ItemTemplate="{StaticResource RecordFieldChip}"+ ItemsSource="{Binding RecordFacts}"+ Visibility="{Binding HasRecordFacts, Converter={StaticResource BooleanToVisibilityConverter}}">+ <ItemsControl.ItemsPanel>+ <ItemsPanelTemplate>+ <WrapPanel HorizontalAlignment="Left" />+ </ItemsPanelTemplate>+ </ItemsControl.ItemsPanel>+ </ItemsControl>+<ui:TextBlockMargin="16"Appearance="Disabled"@@ -219,9 +258,7 @@TextWrapping="Wrap"Visibility="{Binding HasRecord, Converter={StaticResource InverseBooleanToVisibilityConverter}}" />- <ItemsControl- ItemsSource="{Binding Steps}"- Visibility="{Binding HasRecord, Converter={StaticResource BooleanToVisibilityConverter}}">+ <ItemsControl ItemsSource="{Binding Steps}" Visibility="{Binding HasRecord, Converter={StaticResource BooleanToVisibilityConverter}}"><ItemsControl.ItemTemplate><DataTemplate><Border@@ -249,7 +286,7 @@<DataTrigger Binding="{Binding Kind}" Value="Irreversible"><Setter Property="Foreground" Value="{DynamicResource SystemFillColorCautionBrush}" /></DataTrigger>- <!-- last, so a failed step is red whatever its kind says -->+ <!-- last, so a failed step is red whatever its kind says --><DataTrigger Binding="{Binding Ok}" Value="False"><Setter Property="Foreground" Value="{DynamicResource SystemFillColorCriticalBrush}" /></DataTrigger>@@ -287,6 +324,7 @@<ItemsControlMargin="0,6,0,0"+ ItemTemplate="{StaticResource RecordFieldChip}"ItemsSource="{Binding Fields}"Visibility="{Binding HasFields, Converter={StaticResource BooleanToVisibilityConverter}}"><ItemsControl.ItemsPanel>@@ -294,35 +332,6 @@<WrapPanel HorizontalAlignment="Left" /></ItemsPanelTemplate></ItemsControl.ItemsPanel>- <ItemsControl.ItemTemplate>- <DataTemplate>- <Border- Margin="0,0,6,6"- Padding="6,2"- Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"- CornerRadius="{StaticResource CornerRadiusSmall}">- <StackPanel Orientation="Horizontal">- <ui:SymbolIcon- Margin="0,0,6,0"- FontSize="14"- Foreground="{DynamicResource TextFillColorSecondaryBrush}"- Symbol="{Binding Icon}" />- <ui:TextBlock- VerticalAlignment="Center"- FontTypography="Caption"- Foreground="{DynamicResource TextFillColorSecondaryBrush}"- Text="{Binding Label}" />- <ui:TextBlock- Margin="6,0,0,0"- VerticalAlignment="Center"- FontFamily="Consolas"- FontTypography="Caption"- Text="{Binding Value}"- TextWrapping="Wrap" />- </StackPanel>- </Border>- </DataTemplate>- </ItemsControl.ItemTemplate></ItemsControl><ui:TextBlock@@ -347,7 +356,7 @@Text="{ext:Loc OptimizationDetailsDialog.Other}" /><ui:CardAction- Margin="0,0,0,8"+ Margin="0,0,0,4"Command="{Binding ViewSourceOnGitHubCommand}"Cursor="Hand"Icon="{ui:SymbolIcon Code24}">@@ -357,8 +366,8 @@Text="{ext:Loc OptimizationDetailsDialog.Other.ViewSource.Title}"TextWrapping="Wrap" /><ui:TextBlock- Foreground="{DynamicResource TextFillColorSecondaryBrush}"FontTypography="Body"+ Foreground="{DynamicResource TextFillColorSecondaryBrush}"Text="{ext:Loc OptimizationDetailsDialog.Other.ViewSource.Description}"TextWrapping="Wrap" /></StackPanel>@@ -375,8 +384,8 @@Text="{ext:Loc OptimizationDetailsDialog.Other.OpenRecordFile.Title}"TextWrapping="Wrap" /><ui:TextBlock- Foreground="{DynamicResource TextFillColorSecondaryBrush}"FontTypography="Body"+ Foreground="{DynamicResource TextFillColorSecondaryBrush}"Text="{ext:Loc OptimizationDetailsDialog.Other.OpenRecordFile.Description}"TextWrapping="Wrap" /></StackPanel>@@ -393,8 +402,8 @@Text="{ext:Loc OptimizationDetailsDialog.Other.OpenRevertFile.Title}"TextWrapping="Wrap" /><ui:TextBlock- Foreground="{DynamicResource TextFillColorSecondaryBrush}"FontTypography="Body"+ Foreground="{DynamicResource TextFillColorSecondaryBrush}"Text="{ext:Loc OptimizationDetailsDialog.Other.OpenRevertFile.Description}"TextWrapping="Wrap" /></StackPanel>diff --git a/optimizerDuck/UI/ViewModels/Dialogs/ChangeRecordStepViewModel.cs b/optimizerDuck/UI/ViewModels/Dialogs/ChangeRecordStepViewModel.csindex 6a69cf6..10db470 100644--- a/optimizerDuck/UI/ViewModels/Dialogs/ChangeRecordStepViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Dialogs/ChangeRecordStepViewModel.cs@@ -1,3 +1,4 @@+using System.Globalization;using optimizerDuck.Domain.Execution;using optimizerDuck.Domain.UI;using optimizerDuck.Services.Configuration;@@ -20,9 +21,12 @@ public sealed class ChangeRecordStepViewModelChangeRecordOperation operation = ChangeRecordOperation.Apply){+ ArgumentNullException.ThrowIfNull(step);+Operation = operation;Kind = step.Kind;Ok = step.Ok;+ Index = step.Index;var display = ChangeKindPresentation.ForStep(step);Icon = display.Icon;@@ -34,8 +38,15 @@ public sealed class ChangeRecordStepViewModel// Only a step that changed something is phrased as an action. A step that wrote nothing// states what it found instead, so the row can never read as if it had written.- OperationLabel = step.Kind == ChangeKind.Change ? ResolveActionLabel(step, operation) : null;- Fields = BuildFields(step);+ var row = ChangeDetailPresentation.For(+ ChangeDetailCodec.Decode(step),+ step.Kind,+ operation+ );+ OperationLabel = row.ActionKey is null+ ? null+ : Loc.Instance[row.ActionKey, row.ActionArg ?? string.Empty];+ Fields = BuildFields(row, step);}/// <summary>Builds a row straight from a step that is still in memory, for the failure list.</summary>@@ -44,27 +55,8 @@ public sealed class ChangeRecordStepViewModelChange change,ChangeRecordOperation operation = ChangeRecordOperation.Apply)- : this(- new ChangeRecordStep- {- Name = change.Name,- Description = change.Description,- Kind = change.Kind,- Ok = change.Ok,- Error = change.Error,- Operation = change.Detail?.Operation,- Target = change.Detail?.Target,- ValueName = change.Detail?.ValueName,- ValueType = change.Detail?.ValueType,- PreviousValue = change.Detail?.PreviousValue,- NewValue = change.Detail?.NewValue,- HasValuePair = change.Detail?.HasValuePair ?? false,- Reason = change.Detail?.Reason,- },- operation- )+ : this(ChangeRecord.StepOf(change), operation){- Index = change.Index;ErrorDetail = change.ErrorDetail;}@@ -107,7 +99,7 @@ public sealed class ChangeRecordStepViewModelpublic bool HasOperation => !string.IsNullOrEmpty(OperationLabel);- /// <summary>The facts of the step: what it touched, and the values around it.</summary>+ /// <summary>The facts of the step: what it touched, the values around it, and how it went.</summary>public IReadOnlyList<RecordFieldViewModel> Fields { get; }public bool HasFields => Fields.Count > 0;@@ -117,153 +109,57 @@ public sealed class ChangeRecordStepViewModelpublic bool HasDetail => !string.IsNullOrWhiteSpace(Detail);- /// <summary>What the step did, worded for the run it belongs to.</summary>- private static string? ResolveActionLabel(ChangeRecordStep step, ChangeRecordOperation operation)- {- var target = step.Target ?? string.Empty;-- return operation == ChangeRecordOperation.Revert- ? RevertLabel(step, target)- : ApplyLabel(step, target);- }-- private static string? ApplyLabel(ChangeRecordStep step, string target)- {- return step.Operation switch- {- "registry.write" => Loc.Instance[- "Optimizer.Details.Op.RegistrySet",- step.ValueName ?? string.Empty- ],- "registry.delete" => Loc.Instance[- "Optimizer.Details.Op.RegistryDelete",- step.ValueName ?? string.Empty- ],- "registry.createKey" => Loc.Instance["Optimizer.Details.Op.RegistryCreateKey"],- "registry.deleteKey" => Loc.Instance["Optimizer.Details.Op.RegistryDeleteKey"],- "service.startup" => Loc.Instance["Optimizer.Details.Op.ServiceStartup", target],- "task.enable" => Loc.Instance["Optimizer.Details.Op.TaskEnable", target],- "task.disable" => Loc.Instance["Optimizer.Details.Op.TaskDisable", target],- "power.plan" => Loc.Instance["Optimizer.Details.Op.PowerPlanActivate", target],- "power.planInstall" => Loc.Instance["Optimizer.Details.Op.PowerPlanInstall", target],- "power.setting" => Loc.Instance["Optimizer.Details.Op.PowerSetting", target],- "hibernation" => Loc.Instance["Optimizer.Details.Op.Hibernation"],- "usb.power" => Loc.Instance["Optimizer.Details.Op.UsbPower"],- _ => null,- };- }-/// <summary>- /// A revert puts things back: a value is restored, a key created by the apply is deleted, a- /// task is toggled the other way, and hibernation is turned back on when it was on before.+ /// The facts of the operation, worded for the user, followed by how the step went: when it+ /// ran, how long it took, which attempt it is and the code behind a failure. A fact the+ /// record does not carry leaves its chip out rather than showing an empty one./// </summary>- private static string? RevertLabel(ChangeRecordStep step, string target)- {- return step.Operation switch- {- "registry.write" or "registry.delete" => Loc.Instance[- "Optimizer.Details.Op.RegistryRestore",- step.ValueName ?? string.Empty- ],- "registry.createKey" => Loc.Instance["Optimizer.Details.Op.RegistryDeleteKey"],- "registry.deleteKey" => Loc.Instance["Optimizer.Details.Op.RegistryRestoreKey"],- "service.startup" => Loc.Instance["Optimizer.Details.Op.ServiceRestore", target],- "task.enable" => Loc.Instance["Optimizer.Details.Op.TaskDisable", target],- "task.disable" => Loc.Instance["Optimizer.Details.Op.TaskEnable", target],- "power.plan" => Loc.Instance["Optimizer.Details.Op.PowerPlanRestore", target],- "power.planInstall" => Loc.Instance["Optimizer.Details.Op.PowerPlanUninstall", target],- "power.setting" => Loc.Instance["Optimizer.Details.Op.PowerSettingRestore", target],- "hibernation" => step.NewValue == "Enabled"- ? Loc.Instance["Optimizer.Details.Op.HibernationEnable"]- : Loc.Instance["Optimizer.Details.Op.HibernationRestore"],- "usb.power" => Loc.Instance["Optimizer.Details.Op.UsbPowerRestore"],- _ => null,- };- }-- private static List<RecordFieldViewModel> BuildFields(ChangeRecordStep step)+ private static List<RecordFieldViewModel> BuildFields(+ ChangeDetailRow row,+ ChangeRecordStep step+ ){- var fields = new List<RecordFieldViewModel>();- var target = step.Target ?? string.Empty;-- // The USB pass touches every root hub at once, so what it has to show is how many.- if (step.Operation == "usb.power")- {+ var fields = row+ .Chips.Select(chip => new RecordFieldViewModel(+ chip.Icon,+ Loc.Instance[chip.LabelKey],+ chip.ValueIsKey ? Loc.Instance[chip.Value] : chip.Value+ ))+ .ToList();++ if (step.RecordedAt is { } recordedAt)fields.Add(new RecordFieldViewModel(- SymbolRegular.NetworkAdapter16,- Loc.Instance["Optimizer.Details.Field.Devices"],- step.NewValue ?? "0"+ SymbolRegular.Clock24,+ Loc.Instance["Optimizer.Details.Field.At"],+ recordedAt.ToString("T", CultureInfo.CurrentCulture)));- return fields;- }-- var subject = SubjectOf(step.Operation);-- if (!string.IsNullOrEmpty(target))- fields.Add(new RecordFieldViewModel(subject.Icon, Loc.Instance[subject.LabelKey], target));- if (!string.IsNullOrEmpty(step.ValueName))+ if (step.ElapsedMs is { } elapsedMs)fields.Add(new RecordFieldViewModel(- SymbolRegular.ToggleRight24,- Loc.Instance["Optimizer.Details.Field.ValueName"],- step.ValueName+ SymbolRegular.Timer24,+ Loc.Instance["Optimizer.Details.Field.Took"],+ DescribeDuration(elapsedMs)));- if (!string.IsNullOrEmpty(step.ValueType))+ if (step.Attempt > 1)fields.Add(new RecordFieldViewModel(- SymbolRegular.Code24,- Loc.Instance["Optimizer.Details.Field.Type"],- DescribeValueType(step.ValueType)+ SymbolRegular.ArrowClockwise24,+ Loc.Instance["Optimizer.Details.Field.Attempt"],+ step.Attempt.ToString(CultureInfo.InvariantCulture)));- // Why nothing was written, in the words the user reads. Without it, "not applicable"- // leaves the row saying nothing about what the step expected to find.- if (Reason(step.Reason) is { } reason)+ if (step.NativeErrorCode is { } errorCode)fields.Add(new RecordFieldViewModel(- SymbolRegular.Info24,- Loc.Instance["Optimizer.Details.Field.Reason"],- reason- )- );-- // A step that changed something shows what it moved between. Anything else shows the- // state it found, because there is no after to speak of.- if (step.Kind != ChangeKind.Change || !step.HasValuePair)- {- var state = StateOf(step);- var value = step.NewValue ?? step.PreviousValue;-- if (state is { } chip && !string.IsNullOrEmpty(value))- fields.Add(- new RecordFieldViewModel(chip.Icon, Loc.Instance[chip.LabelKey], LocalizeValue(value))- );-- return fields;- }-- fields.Add(- new RecordFieldViewModel(- SymbolRegular.Clock24,- Loc.Instance["Optimizer.Details.Field.Previous"],- step.PreviousValue is null- ? Loc.Instance["Optimizer.Details.Field.Previous.None"]- : LocalizeValue(step.PreviousValue)- )- );-- if (step.NewValue is not null)- fields.Add(- new RecordFieldViewModel(- SymbolRegular.Edit24,- Loc.Instance["Optimizer.Details.Field.New"],- LocalizeValue(step.NewValue)+ SymbolRegular.ErrorCircle24,+ Loc.Instance["Optimizer.Details.Field.ErrorCode"],+ errorCode.ToString(CultureInfo.InvariantCulture)));@@ -271,21 +167,14 @@ public sealed class ChangeRecordStepViewModel}/// <summary>- /// The sentence for a reason a provider recorded. A reason the UI does not know yet is- /// left out rather than shown as a code.+ /// A duration as it is read at a glance: milliseconds while the step was quick, and seconds+ /// once it was not. Shared with the record's own facts, so a run and its steps read alike./// </summary>- private static string? Reason(string? reason)+ internal static string DescribeDuration(long elapsedMs){- return reason switch- {- "service.notFound" => Loc.Instance["Optimizer.Details.Reason.ServiceNotFound"],- "task.notFound" => Loc.Instance["Optimizer.Details.Reason.TaskNotFound"],- "registry.valueAbsent" => Loc.Instance["Optimizer.Details.Reason.RegistryValueAbsent"],- "registry.keyExists" => Loc.Instance["Optimizer.Details.Reason.RegistryKeyExists"],- "registry.keyAbsent" => Loc.Instance["Optimizer.Details.Reason.RegistryKeyAbsent"],- "usb.noDevices" => Loc.Instance["Optimizer.Details.Reason.UsbNoDevices"],- _ => null,- };+ return elapsedMs < 1000+ ? string.Format(CultureInfo.InvariantCulture, "{0} ms", elapsedMs)+ : string.Format(CultureInfo.InvariantCulture, "{0:0.0} s", elapsedMs / 1000.0);}/// <summary>@@ -307,79 +196,4 @@ public sealed class ChangeRecordStepViewModel_ => name,};}-- /// <summary>- /// A registry value type as Windows itself names it, so the chip reads the same in every- /// language and matches what a user sees in the registry editor.- /// </summary>- private static string DescribeValueType(string valueType)- {- return valueType switch- {- "DWord" => "REG_DWORD",- "QWord" => "REG_QWORD",- "String" => "REG_SZ",- "ExpandString" => "REG_EXPAND_SZ",- "MultiString" => "REG_MULTI_SZ",- "Binary" => "REG_BINARY",- _ => valueType,- };- }-- private static (string LabelKey, SymbolRegular Icon) SubjectOf(string? operation)- {- return operation switch- {- "service.startup" => ("Optimizer.Details.Field.Service", SymbolRegular.Shield24),- "task.enable" or "task.disable" => (- "Optimizer.Details.Field.Task",- SymbolRegular.Clock24- ),- "power.plan" or "power.planInstall" => (- "Optimizer.Details.Field.PowerPlan",- SymbolRegular.BatteryCharge24- ),- "power.setting" => ("Optimizer.Details.Field.Setting", SymbolRegular.Gauge24),- _ => ("Optimizer.Details.Field.Path", SymbolRegular.FolderOpen24),- };- }-- /// <summary>- /// What the state chip of a step that wrote nothing is called, named after the thing it- /// holds. A plan name or a device count is the whole story on its own, so they have none.- /// </summary>- private static (string LabelKey, SymbolRegular Icon)? StateOf(ChangeRecordStep step)- {- return step.Operation switch- {- "service.startup" => ("Optimizer.Details.Field.StartupState", SymbolRegular.Shield24),- "task.enable" or "task.disable" => (- "Optimizer.Details.Field.TaskState",- SymbolRegular.Clock24- ),- "hibernation" => (- "Optimizer.Details.Field.HibernationState",- SymbolRegular.BatteryCharge24- ),- "power.plan" or "power.planInstall" => null,- _ => ("Optimizer.Details.Field.Value", SymbolRegular.Edit24),- };- }-- /// <summary>- /// Turns the words a provider records into the words the user reads. A value that is not a- /// known word is shown as it is, because a path or a number needs no translation.- /// </summary>- private static string LocalizeValue(string value)- {- return value switch- {- "Automatic" => Loc.Instance["Optimizer.Details.Value.Startup.Automatic"],- "AutomaticDelayedStart" => Loc.Instance["Optimizer.Details.Value.Startup.AutomaticDelayed"],- "Manual" => Loc.Instance["Optimizer.Details.Value.Startup.Manual"],- "Disabled" => Loc.Instance["Optimizer.Details.Value.Startup.Disabled"],- "Enabled" => Loc.Instance["Optimizer.Details.Value.Enabled"],- _ => value,- };- }}diff --git a/optimizerDuck/UI/ViewModels/Dialogs/OptimizationDetailsViewModel.cs b/optimizerDuck/UI/ViewModels/Dialogs/OptimizationDetailsViewModel.csindex 939cbef..3e938dd 100644--- a/optimizerDuck/UI/ViewModels/Dialogs/OptimizationDetailsViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Dialogs/OptimizationDetailsViewModel.cs@@ -32,14 +32,14 @@ public partial class OptimizationDetailsViewModel(/// </summary>private readonly ChangeRecord? _record = ChangeRecordStore.TryRead(optimization.Id);private IReadOnlyList<ChangeRecordStepViewModel>? _steps;+ private IReadOnlyList<RecordFieldViewModel>? _recordFacts;/// <summary>/// The steps of the recorded run, worded for the run they belong to, so a revert reads as/// what it put back./// </summary>public IReadOnlyList<ChangeRecordStepViewModel> Steps =>- _steps ??=- [+ _steps ??= [.. (_record?.Steps ?? []).Select(step => new ChangeRecordStepViewModel(step,_record?.Operation ?? ChangeRecordOperation.Apply@@ -67,6 +67,54 @@ public partial class OptimizationDetailsViewModel(/// <summary>Whether the record describes a revert, which the header marks.</summary>public bool RecordIsRevert => _record?.Operation == ChangeRecordOperation.Revert;+ /// <summary>+ /// What the run itself was: the build that wrote the record and the Windows version it ran+ /// on, so a record read out of the app states its own context, and how long the run took. A+ /// record written by an earlier build carries none of these and shows no chip for them.+ /// </summary>+ public IReadOnlyList<RecordFieldViewModel> RecordFacts =>+ _recordFacts ??= BuildRecordFacts(_record);++ /// <summary>Whether the record carries any fact about the run itself.</summary>+ public bool HasRecordFacts => RecordFacts.Count > 0;++ private static IReadOnlyList<RecordFieldViewModel> BuildRecordFacts(ChangeRecord? record)+ {+ if (record is null)+ return [];++ var facts = new List<RecordFieldViewModel>();++ if (!string.IsNullOrEmpty(record.AppVersion))+ facts.Add(+ new RecordFieldViewModel(+ SymbolRegular.Info24,+ Loc.Instance["Optimizer.Details.Record.Version"],+ record.AppVersion+ )+ );++ if (!string.IsNullOrEmpty(record.WindowsVersion))+ facts.Add(+ new RecordFieldViewModel(+ SymbolRegular.Desktop24,+ Loc.Instance["Optimizer.Details.Record.Windows"],+ record.WindowsVersion+ )+ );++ if (record.ElapsedMs is { } elapsedMs)+ facts.Add(+ new RecordFieldViewModel(+ SymbolRegular.Timer24,+ Loc.Instance["Optimizer.Details.Record.Took"],+ ChangeRecordStepViewModel.DescribeDuration(elapsedMs)+ )+ );++ return facts;+ }+[RelayCommand]private async Task OpenRevertFileAsync(){