From b41b724c7d930a1fa9209c75c88ffce5c4775213 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:38:22 +0300 Subject: [PATCH 01/31] Apply accepted class owners to current main The candidate applies the accepted Root and corrected peer state owners to the current main source. The existing startup readiness task and emergency recovery statements remain intact. The editor, windows, BlockCheck2, resource references, and configuration projections retain their reviewed ownership and callback rules. The test project preserves every current default item and its explicit removals. The additional items use existing central dependency versions. The recorded source map identifies all changed product inputs and their original commits. The existing default security, localization, and workflow files remain unchanged outside the declared decomposition paths. The focused suite passed 169 tests, and the full suite passed 2163 tests. The Release GUI build reported zero warnings and errors. The current default public source and compiled contracts have no lost shapes. The historical Root MSI and pipe API differences remain tracked under issue13. The native union149 run and independent final review remain pending. The integration PR must stay draft until the required acceptance and G1 reconciliation pass. Changed files: - "CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs" (+3/-35 lines). - "CDPIUI.Core/ComponentServices/Helpers/Configuration/Helpers/ConfigurationVariableProjection.cs" (+45/-0 lines). - "CDPIUI.Tests/CDPIUI.Tests.csproj" (+119/-0 lines). - "CDPIUI.Tests/ConfigurationVariableProjectionTests.cs" (+249/-0 lines). - "CDPIUI.Tests/Presentation/AppActivationDispatcherTests.cs" (+229/-0 lines). - "CDPIUI.Tests/Presentation/AppFileActivationHandlerTests.cs" (+271/-0 lines). - "CDPIUI.Tests/Presentation/AppIdleExitControllerTests.cs" (+273/-0 lines). - "CDPIUI.Tests/Presentation/AppWindowCloseCoordinatorTests.cs" (+260/-0 lines). - "CDPIUI.Tests/Presentation/AppWindowCoordinatorTests.cs" (+297/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2AssignmentActionsTests.cs" (+320/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2ManualAssignmentEditorTests.cs" (+467/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2ManualPresetStateTests.cs" (+363/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2ManualStrategyTestControllerTests.cs" (+433/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2ManualTestSessionTests.cs" (+590/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2OptionsTests.cs" (+219/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2ProgressTests.cs" (+283/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2ReportExportTests.cs" (+265/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2ReportSummaryPresenterTests.cs" (+143/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2ResultSelectionTests.cs" (+244/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2ResultTests.cs" (+472/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2RunControllerTests.cs" (+402/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2SelectedStrategyTestTests.cs" (+372/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2SiteListControllerTests.cs" (+329/-0 lines). - "CDPIUI.Tests/Presentation/ConfigMakerCommandHelpLoaderTests.cs" (+325/-0 lines). - "CDPIUI.Tests/Presentation/ConfigMakerCommandHelpPanelTests.cs" (+215/-0 lines). - "CDPIUI.Tests/Presentation/ConfigMakerDiagnosticsTests.cs" (+328/-0 lines). - "CDPIUI.Tests/Presentation/ConfigMakerDocumentCoordinatorTests.cs" (+637/-0 lines). - "CDPIUI.Tests/Presentation/ConfigMakerPanelLayoutTests.cs" (+235/-0 lines). - "CDPIUI.Tests/Presentation/ConfigMakerPresetFileActionsTests.cs" (+446/-0 lines). - "CDPIUI.Tests/Presentation/ConfigMakerPresetFileReplacerTests.cs" (+478/-0 lines). - "CDPIUI.Tests/Presentation/ConfigMakerPresetReferenceEditorTests.cs" (+141/-0 lines). - "CDPIUI.Tests/Presentation/ConfigMakerPresetResourceTests.cs" (+145/-0 lines). - "CDPIUI.Tests/Presentation/ConfigMakerPresetStructureTests.cs" (+366/-0 lines). - "CDPIUI.Tests/Presentation/ConfigMakerPresetTreeBuilderTests.cs" (+190/-0 lines). - "CDPIUI.Tests/Presentation/ConfigMakerSimpleDesignerTests.cs" (+299/-0 lines). - "CDPIUI.Tests/Presentation/ConfigMakerTestSessionTests.cs" (+245/-0 lines). - "CDPIUI.Tests/Presentation/ConfigMakerVariableActionsTests.cs" (+353/-0 lines). - "CDPIUI.Tests/Presentation/CreateConfigComponentSelectionTests.cs" (+318/-0 lines). - "CDPIUI.Tests/Presentation/CreateConfigConditionDraftTests.cs" (+214/-0 lines). - "CDPIUI.Tests/Presentation/CreateConfigGraphicDesignerTests.cs" (+383/-0 lines). - "CDPIUI.Tests/Presentation/CreateConfigTestSessionTests.cs" (+413/-0 lines). - "CDPIUI.Tests/Presentation/DiagnosticHighlightingUpdaterTests.cs" (+297/-0 lines). - "CDPIUI.Tests/Presentation/DispatcherTaskBridgeTests.cs" (+286/-0 lines). - "CDPIUI.Tests/Presentation/GraphicDesignerCommandCodecTests.cs" (+442/-0 lines). - "CDPIUI.Tests/Presentation/NamedValueCollectionLoaderTests.cs" (+200/-0 lines). - "CDPIUI.Tests/Presentation/PostOrderTreePrunerTests.cs" (+218/-0 lines). - "CDPIUI.Tests/Presentation/SelectedItemChoiceActionTests.cs" (+47/-0 lines). - "CDPIUI.Tests/Presentation/TextChangeRelayTests.cs" (+192/-0 lines). - "CDPIUI.Tests/Presentation/TwoPhaseTransitionSequenceTests.cs" (+271/-0 lines). - "CDPIUI/App.Activation.cs" (+8/-142 lines). - "CDPIUI/App.Modal.cs" (+9/-24 lines). - "CDPIUI/App.Windows.cs" (+15/-155 lines). - "CDPIUI/App.xaml.cs" (+34/-38 lines). - "CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.Editor.cs" (+16/-24 lines). - "CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.Layout.cs" (+6/-81 lines). - "CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.xaml.cs" (+4/-0 lines). - "CDPIUI/Controls/CreateConfigHelper/EnumModel.cs" (+3/-0 lines). - "CDPIUI/Controls/MenuBar/MenuBarController.cs" (+6/-23 lines). - "CDPIUI/Controls/Universal/UtilityButtonControls.xaml.cs" (+8/-44 lines). - "CDPIUI/Helper/Basic/AppActivationDispatcher.cs" (+125/-0 lines). - "CDPIUI/Helper/Basic/AppActivationRequest.cs" (+24/-0 lines). - "CDPIUI/Helper/Basic/AppActivationRequestAdapter.cs" (+30/-0 lines). - "CDPIUI/Helper/Basic/AppFileActivationHandler.cs" (+55/-0 lines). - "CDPIUI/Helper/Basic/AppFileActivationOperations.cs" (+50/-0 lines). - "CDPIUI/Helper/Basic/AppIdleExitController.cs" (+68/-0 lines). - "CDPIUI/Helper/Basic/AppWindowCloseCoordinator.cs" (+61/-0 lines). - "CDPIUI/Helper/Basic/AppWindowCloseOperations.cs" (+41/-0 lines). - "CDPIUI/Helper/Basic/IAppFileActivationOperations.cs" (+16/-0 lines). - "CDPIUI/Helper/Basic/IAppWindowCloseOperations.cs" (+21/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ComponentCommandValidationService.cs" (+3/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandHelpLoader.cs" (+95/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandHelpPanel.cs" (+218/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandText.cs" (+4/-2 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerComponentTestTasks.cs" (+22/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerDiagnostics.cs" (+90/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerDocumentCoordinator.cs" (+197/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPanelLayoutController.cs" (+95/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPanelLayoutView.cs" (+41/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileActions.cs" (+152/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileActionsBackend.cs" (+30/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileKinds.cs" (+3/-1 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileReplacementBackend.cs" (+43/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileReplacer.cs" (+194/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetOptionGroups.cs" (+3/-1 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetReferenceEditor.cs" (+214/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetResourceRegistry.cs" (+160/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetResources.cs" (+17/-292 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetStorageService.cs" (+6/-1 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetStructure.cs" (+124/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeAdapter.cs" (+45/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeBuilder.cs" (+167/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeData.cs" (+28/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeProjection.cs" (+12/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerSimpleDesigner.cs" (+180/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerSimpleDesignerBackend.cs" (+49/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerTestSession.cs" (+140/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ConfigMakerVariableActions.cs" (+85/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/CreateConfigComponentTestTasks.cs" (+21/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/CreateConfigGraphicDesignerBackend.cs" (+39/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/GraphicDesignerCommandCodec.cs" (+230/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/GraphicDesignerHelper.cs" (+13/-157 lines). - "CDPIUI/Helper/CreateConfigHelper/IConfigMakerDocumentHost.cs" (+29/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/IConfigMakerDocumentStorage.cs" (+12/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/IConfigMakerPanelLayoutView.cs" (+22/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileActionsBackend.cs" (+23/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileActionsHost.cs" (+23/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileReplacementBackend.cs" (+22/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileReplacementHost.cs" (+24/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/IConfigMakerSimpleDesignerBackend.cs" (+26/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/IConfigMakerTestTasks.cs" (+15/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/IConfigMakerVariableActionsHost.cs" (+21/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ICreateConfigGraphicDesignerBackend.cs" (+20/-0 lines). - "CDPIUI/Helper/CreateConfigHelper/ICreateConfigTestTasks.cs" (+13/-0 lines). - "CDPIUI/Helper/UserExperience/DiagnosticHighlightingUpdater.cs" (+29/-0 lines). - "CDPIUI/Helper/UserExperience/DispatcherTaskBridge.cs" (+46/-0 lines). - "CDPIUI/Helper/UserExperience/NamedValueCollectionLoader.cs" (+43/-0 lines). - "CDPIUI/Helper/UserExperience/PostOrderTreePruner.cs" (+23/-0 lines). - "CDPIUI/Helper/UserExperience/SelectedItemChoiceAction.cs" (+39/-0 lines). - "CDPIUI/Helper/UserExperience/TextChangeRelay.cs" (+66/-0 lines). - "CDPIUI/Helper/UserExperience/TwoPhaseTransitionSequence.cs" (+50/-0 lines). - "CDPIUI/Helper/WindowHelper/AppWindowCoordinator.cs" (+97/-0 lines). - "CDPIUI/Helper/WindowHelper/AppWindowOperations.cs" (+24/-0 lines). - "CDPIUI/Helper/WindowHelper/IAppWindowOperations.cs" (+17/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2AssignmentActions.cs" (+80/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ManualComponentTestTasks.cs" (+21/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ManualTestSession.cs" (+192/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReportExport.cs" (+78/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReportSummaryPresenter.cs" (+60/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.Assignments.cs" (+25/-86 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.Export.cs" (+3/-45 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.ManualTesting.cs" (+27/-163 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.cs" (+60/-182 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultSelection.cs" (+179/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2SelectedStrategyTest.cs" (+103/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/IBlockCheck2AssignmentActionsHost.cs" (+23/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/IBlockCheck2ManualTestHost.cs" (+20/-0 lines). - "CDPIUI/ViewModels/BlockCheck2ManualAssignmentEditor.cs" (+229/-0 lines). - "CDPIUI/ViewModels/BlockCheck2ManualAssignmentRules.cs" (+3/-0 lines). - "CDPIUI/ViewModels/BlockCheck2ManualIssueItem.cs" (+43/-0 lines). - "CDPIUI/ViewModels/BlockCheck2ManualPresetOperations.cs" (+18/-0 lines). - "CDPIUI/ViewModels/BlockCheck2ManualPresetState.cs" (+133/-0 lines). - "CDPIUI/ViewModels/BlockCheck2ManualResultViewModels.cs" (+3/-37 lines). - "CDPIUI/ViewModels/BlockCheck2ManualStrategyTestController.cs" (+87/-0 lines). - "CDPIUI/ViewModels/BlockCheck2ManualStrategyTestOperations.cs" (+26/-0 lines). - "CDPIUI/ViewModels/BlockCheck2OptionsSettings.cs" (+14/-0 lines). - "CDPIUI/ViewModels/BlockCheck2OptionsViewModel.cs" (+348/-0 lines). - "CDPIUI/ViewModels/BlockCheck2PresetDraft.cs" (+3/-0 lines). - "CDPIUI/ViewModels/BlockCheck2ProgressEstimator.cs" (+1/-1 lines). - "CDPIUI/ViewModels/BlockCheck2ProgressViewModel.cs" (+177/-0 lines). - "CDPIUI/ViewModels/BlockCheck2ReportOperations.cs" (+35/-0 lines). - "CDPIUI/ViewModels/BlockCheck2ResultViewModel.cs" (+41/-338 lines). - "CDPIUI/ViewModels/BlockCheck2RunController.cs" (+98/-0 lines). - "CDPIUI/ViewModels/BlockCheck2RunResultViewModel.cs" (+125/-0 lines). - "CDPIUI/ViewModels/BlockCheck2SiteListBackend.cs" (+26/-0 lines). - "CDPIUI/ViewModels/BlockCheck2SiteListController.cs" (+133/-0 lines). - "CDPIUI/ViewModels/BlockCheck2ViewModel.Options.cs" (+41/-255 lines). - "CDPIUI/ViewModels/BlockCheck2ViewModel.SiteLists.cs" (+14/-147 lines). - "CDPIUI/ViewModels/BlockCheck2ViewModel.cs" (+92/-318 lines). - "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.CommandHelp.cs" (+26/-222 lines). - "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Diagnostics.cs" (+8/-56 lines). - "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Document.cs" (+40/-167 lines). - "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.PresetFiles.cs" (+51/-298 lines). - "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.PresetStructure.cs" (+12/-274 lines). - "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.SimpleDesigner.cs" (+20/-196 lines). - "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Testing.cs" (+14/-98 lines). - "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Variables.cs" (+22/-68 lines). - "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.cs" (+74/-45 lines). - "CDPIUI/ViewModels/ConfigMakerPresetDocumentConverter.cs" (+2/-2 lines). - "CDPIUI/ViewModels/CreateConfig/ConfigComponentOption.cs" (+3/-0 lines). - "CDPIUI/ViewModels/CreateConfig/CreateConfigComponentSelection.cs" (+103/-0 lines). - "CDPIUI/ViewModels/CreateConfig/CreateConfigConditionDraft.cs" (+84/-0 lines). - "CDPIUI/ViewModels/CreateConfig/CreateConfigGraphicDesigner.cs" (+109/-0 lines). - "CDPIUI/ViewModels/CreateConfig/CreateConfigTestSession.cs" (+129/-0 lines). - "CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.GraphicDesigner.cs" (+6/-80 lines). - "CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Navigation.cs" (+12/-41 lines). - "CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Testing.cs" (+6/-89 lines). - "CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Variables.cs" (+12/-56 lines). - "CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.cs" (+46/-64 lines). - "CDPIUI/ViewModels/IBlockCheck2ManualPresetHost.cs" (+17/-0 lines). - "CDPIUI/ViewModels/IBlockCheck2ManualPresetOperations.cs" (+12/-0 lines). - "CDPIUI/ViewModels/IBlockCheck2ManualStrategyTestOperations.cs" (+20/-0 lines). - "CDPIUI/ViewModels/IBlockCheck2OptionsSettings.cs" (+13/-0 lines). - "CDPIUI/ViewModels/IBlockCheck2ProgressEstimator.cs" (+15/-0 lines). - "CDPIUI/ViewModels/IBlockCheck2ReportOperations.cs" (+21/-0 lines). - "CDPIUI/ViewModels/IBlockCheck2RunHost.cs" (+30/-0 lines). - "CDPIUI/ViewModels/IBlockCheck2SiteListBackend.cs" (+24/-0 lines). - "CDPIUI/ViewModels/ObservableObject.cs" (+3/-0 lines). - "CDPIUI/Views/CreateConfigHelper/ConditionVariableModel.cs" (+3/-0 lines). - "CDPIUI/Views/CreateConfigHelper/GraphicDesignerExclusiveSettingItemModel.cs" (+3/-0 lines). - "CDPIUI/Views/CreateConfigHelper/GraphicDesignerSettingItemModel.cs" (+17/-1 lines). - "docs/DECOMPOSITION-ACCEPTANCE.ru.md" (+111/-0 lines). - "docs/DECOMPOSITION-DECISIONS.ru.md" (+182/-0 lines). - "docs/DECOMPOSITION-REVIEW-MAP.ru.md" (+434/-0 lines). - "docs/DECOMPOSITION-STATUS.ru.md" (+1427/-0 lines). - "docs/superpowers/plans/2026-11-08-class-decomposition.md" (+1266/-0 lines). - "docs/superpowers/plans/2026-11-11-class-integration.md" (+73/-0 lines). - "docs/superpowers/reports/2026-11-11-class-integration-provenance.json" (+980/-0 lines). - "docs/superpowers/reports/2026-11-11-class-integration-source.md" (+74/-0 lines). - "docs/superpowers/reports/2026-11-11-diagnostic-highlighting-verification.md" (+170/-0 lines). - "docs/superpowers/specs/2026-11-08-class-decomposition-design.md" (+360/-0 lines). - "docs/superpowers/specs/2026-11-10-app-idle-exit-design.md" (+31/-0 lines). - "docs/superpowers/specs/2026-11-10-assignment-actions-design.md" (+70/-0 lines). - "docs/superpowers/specs/2026-11-10-manual-test-session-design.md" (+69/-0 lines). - "docs/superpowers/specs/2026-11-10-menu-pruning-design.md" (+52/-0 lines). - "docs/superpowers/specs/2026-11-10-report-export-design.md" (+42/-0 lines). - "docs/superpowers/specs/2026-11-10-report-summary-design.md" (+24/-0 lines). - "docs/superpowers/specs/2026-11-10-result-selection-design.md" (+31/-0 lines). - "docs/superpowers/specs/2026-11-10-selected-strategy-test-design.md" (+41/-0 lines). - "docs/superpowers/specs/2026-11-10-transition-sequence-design.md" (+70/-0 lines). - "docs/superpowers/specs/2026-11-11-class-integration-design.md" (+111/-0 lines). - "docs/superpowers/specs/2026-11-11-configuration-variable-projection-design.md" (+62/-0 lines). - "docs/superpowers/specs/2026-11-11-diagnostic-highlighting-design.md" (+81/-0 lines). The file counts compare the staged tree with its first parent. Refs: #14 Staged-Tree: 61ae89a0a761744909cdb536d34c853798e0381d --- .../Configuration/ConfigurationService.cs | 38 +- .../ConfigurationVariableProjection.cs | 45 + CDPIUI.Tests/CDPIUI.Tests.csproj | 119 ++ .../ConfigurationVariableProjectionTests.cs | 249 +++ .../AppActivationDispatcherTests.cs | 229 +++ .../AppFileActivationHandlerTests.cs | 271 ++++ .../AppIdleExitControllerTests.cs | 273 ++++ .../AppWindowCloseCoordinatorTests.cs | 260 +++ .../Presentation/AppWindowCoordinatorTests.cs | 297 ++++ .../BlockCheck2AssignmentActionsTests.cs | 320 ++++ .../BlockCheck2ManualAssignmentEditorTests.cs | 467 ++++++ .../BlockCheck2ManualPresetStateTests.cs | 363 +++++ ...Check2ManualStrategyTestControllerTests.cs | 433 +++++ .../BlockCheck2ManualTestSessionTests.cs | 590 +++++++ .../Presentation/BlockCheck2OptionsTests.cs | 219 +++ .../Presentation/BlockCheck2ProgressTests.cs | 283 ++++ .../BlockCheck2ReportExportTests.cs | 265 +++ .../BlockCheck2ReportSummaryPresenterTests.cs | 143 ++ .../BlockCheck2ResultSelectionTests.cs | 244 +++ .../Presentation/BlockCheck2ResultTests.cs | 472 ++++++ .../BlockCheck2RunControllerTests.cs | 402 +++++ .../BlockCheck2SelectedStrategyTestTests.cs | 372 +++++ .../BlockCheck2SiteListControllerTests.cs | 329 ++++ .../ConfigMakerCommandHelpLoaderTests.cs | 325 ++++ .../ConfigMakerCommandHelpPanelTests.cs | 215 +++ .../ConfigMakerDiagnosticsTests.cs | 328 ++++ .../ConfigMakerDocumentCoordinatorTests.cs | 637 ++++++++ .../ConfigMakerPanelLayoutTests.cs | 235 +++ .../ConfigMakerPresetFileActionsTests.cs | 446 ++++++ .../ConfigMakerPresetFileReplacerTests.cs | 478 ++++++ .../ConfigMakerPresetReferenceEditorTests.cs | 141 ++ .../ConfigMakerPresetResourceTests.cs | 145 ++ .../ConfigMakerPresetStructureTests.cs | 366 +++++ .../ConfigMakerPresetTreeBuilderTests.cs | 190 +++ .../ConfigMakerSimpleDesignerTests.cs | 299 ++++ .../ConfigMakerTestSessionTests.cs | 245 +++ .../ConfigMakerVariableActionsTests.cs | 353 ++++ .../CreateConfigComponentSelectionTests.cs | 318 ++++ .../CreateConfigConditionDraftTests.cs | 214 +++ .../CreateConfigGraphicDesignerTests.cs | 383 +++++ .../CreateConfigTestSessionTests.cs | 413 +++++ .../DiagnosticHighlightingUpdaterTests.cs | 297 ++++ .../Presentation/DispatcherTaskBridgeTests.cs | 286 ++++ .../GraphicDesignerCommandCodecTests.cs | 442 +++++ .../NamedValueCollectionLoaderTests.cs | 200 +++ .../Presentation/PostOrderTreePrunerTests.cs | 218 +++ .../SelectedItemChoiceActionTests.cs | 47 + .../Presentation/TextChangeRelayTests.cs | 192 +++ .../TwoPhaseTransitionSequenceTests.cs | 271 ++++ CDPIUI/App.Activation.cs | 150 +- CDPIUI/App.Modal.cs | 33 +- CDPIUI/App.Windows.cs | 170 +- CDPIUI/App.xaml.cs | 72 +- .../ConfigMakerUserControl.Editor.cs | 40 +- .../ConfigMakerUserControl.Layout.cs | 87 +- .../ConfigMakerUserControl.xaml.cs | 4 + .../Controls/CreateConfigHelper/EnumModel.cs | 3 + CDPIUI/Controls/MenuBar/MenuBarController.cs | 29 +- .../Universal/UtilityButtonControls.xaml.cs | 52 +- .../Helper/Basic/AppActivationDispatcher.cs | 125 ++ CDPIUI/Helper/Basic/AppActivationRequest.cs | 24 + .../Basic/AppActivationRequestAdapter.cs | 30 + .../Helper/Basic/AppFileActivationHandler.cs | 55 + .../Basic/AppFileActivationOperations.cs | 50 + CDPIUI/Helper/Basic/AppIdleExitController.cs | 68 + .../Helper/Basic/AppWindowCloseCoordinator.cs | 61 + .../Helper/Basic/AppWindowCloseOperations.cs | 41 + .../Basic/IAppFileActivationOperations.cs | 16 + .../Helper/Basic/IAppWindowCloseOperations.cs | 21 + .../ComponentCommandValidationService.cs | 3 + .../ConfigMakerCommandHelpLoader.cs | 95 ++ .../ConfigMakerCommandHelpPanel.cs | 218 +++ .../ConfigMakerCommandText.cs | 6 +- .../ConfigMakerComponentTestTasks.cs | 22 + .../ConfigMakerDiagnostics.cs | 90 ++ .../ConfigMakerDocumentCoordinator.cs | 197 +++ .../ConfigMakerPanelLayoutController.cs | 95 ++ .../ConfigMakerPanelLayoutView.cs | 41 + .../ConfigMakerPresetFileActions.cs | 152 ++ .../ConfigMakerPresetFileActionsBackend.cs | 30 + .../ConfigMakerPresetFileKinds.cs | 4 +- ...ConfigMakerPresetFileReplacementBackend.cs | 43 + .../ConfigMakerPresetFileReplacer.cs | 194 +++ .../ConfigMakerPresetOptionGroups.cs | 4 +- .../ConfigMakerPresetReferenceEditor.cs | 214 +++ .../ConfigMakerPresetResourceRegistry.cs | 160 ++ .../ConfigMakerPresetResources.cs | 309 +--- .../ConfigMakerPresetStorageService.cs | 7 +- .../ConfigMakerPresetStructure.cs | 124 ++ .../ConfigMakerPresetTreeAdapter.cs | 45 + .../ConfigMakerPresetTreeBuilder.cs | 167 ++ .../ConfigMakerPresetTreeData.cs | 28 + .../ConfigMakerPresetTreeProjection.cs | 12 + .../ConfigMakerSimpleDesigner.cs | 180 +++ .../ConfigMakerSimpleDesignerBackend.cs | 49 + .../ConfigMakerTestSession.cs | 140 ++ .../ConfigMakerVariableActions.cs | 85 + .../CreateConfigComponentTestTasks.cs | 21 + .../CreateConfigGraphicDesignerBackend.cs | 39 + .../GraphicDesignerCommandCodec.cs | 230 +++ .../GraphicDesignerHelper.cs | 170 +- .../IConfigMakerDocumentHost.cs | 29 + .../IConfigMakerDocumentStorage.cs | 12 + .../IConfigMakerPanelLayoutView.cs | 22 + .../IConfigMakerPresetFileActionsBackend.cs | 23 + .../IConfigMakerPresetFileActionsHost.cs | 23 + ...ConfigMakerPresetFileReplacementBackend.cs | 22 + .../IConfigMakerPresetFileReplacementHost.cs | 24 + .../IConfigMakerSimpleDesignerBackend.cs | 26 + .../IConfigMakerTestTasks.cs | 15 + .../IConfigMakerVariableActionsHost.cs | 21 + .../ICreateConfigGraphicDesignerBackend.cs | 20 + .../ICreateConfigTestTasks.cs | 13 + .../DiagnosticHighlightingUpdater.cs | 29 + .../UserExperience/DispatcherTaskBridge.cs | 46 + .../NamedValueCollectionLoader.cs | 43 + .../UserExperience/PostOrderTreePruner.cs | 23 + .../SelectedItemChoiceAction.cs | 39 + .../Helper/UserExperience/TextChangeRelay.cs | 66 + .../TwoPhaseTransitionSequence.cs | 50 + .../WindowHelper/AppWindowCoordinator.cs | 97 ++ .../WindowHelper/AppWindowOperations.cs | 24 + .../WindowHelper/IAppWindowOperations.cs | 17 + .../BlockCheck2AssignmentActions.cs | 80 + .../BlockCheck2ManualComponentTestTasks.cs | 21 + .../BlockCheck2ManualTestSession.cs | 192 +++ .../BlockCheck2/BlockCheck2ReportExport.cs | 78 + .../BlockCheck2ReportSummaryPresenter.cs | 60 + ...ckCheck2ResultPageViewModel.Assignments.cs | 111 +- .../BlockCheck2ResultPageViewModel.Export.cs | 48 +- ...Check2ResultPageViewModel.ManualTesting.cs | 190 +-- .../BlockCheck2ResultPageViewModel.cs | 242 +-- .../BlockCheck2/BlockCheck2ResultSelection.cs | 179 +++ .../BlockCheck2SelectedStrategyTest.cs | 103 ++ .../IBlockCheck2AssignmentActionsHost.cs | 23 + .../BlockCheck2/IBlockCheck2ManualTestHost.cs | 20 + .../BlockCheck2ManualAssignmentEditor.cs | 229 +++ .../BlockCheck2ManualAssignmentRules.cs | 3 + .../ViewModels/BlockCheck2ManualIssueItem.cs | 43 + .../BlockCheck2ManualPresetOperations.cs | 18 + .../BlockCheck2ManualPresetState.cs | 133 ++ .../BlockCheck2ManualResultViewModels.cs | 40 +- ...BlockCheck2ManualStrategyTestController.cs | 87 + ...BlockCheck2ManualStrategyTestOperations.cs | 26 + .../ViewModels/BlockCheck2OptionsSettings.cs | 14 + .../ViewModels/BlockCheck2OptionsViewModel.cs | 348 ++++ CDPIUI/ViewModels/BlockCheck2PresetDraft.cs | 3 + .../BlockCheck2ProgressEstimator.cs | 2 +- .../BlockCheck2ProgressViewModel.cs | 177 ++ .../ViewModels/BlockCheck2ReportOperations.cs | 35 + .../ViewModels/BlockCheck2ResultViewModel.cs | 379 +---- CDPIUI/ViewModels/BlockCheck2RunController.cs | 98 ++ .../BlockCheck2RunResultViewModel.cs | 125 ++ .../ViewModels/BlockCheck2SiteListBackend.cs | 26 + .../BlockCheck2SiteListController.cs | 133 ++ .../BlockCheck2ViewModel.Options.cs | 296 +--- .../BlockCheck2ViewModel.SiteLists.cs | 161 +- CDPIUI/ViewModels/BlockCheck2ViewModel.cs | 410 ++--- .../ConfigMakerViewModel.CommandHelp.cs | 248 +-- .../ConfigMakerViewModel.Diagnostics.cs | 64 +- .../ConfigMakerViewModel.Document.cs | 207 +-- .../ConfigMakerViewModel.PresetFiles.cs | 349 +--- .../ConfigMakerViewModel.PresetStructure.cs | 286 +--- .../ConfigMakerViewModel.SimpleDesigner.cs | 216 +-- .../ConfigMakerViewModel.Testing.cs | 112 +- .../ConfigMakerViewModel.Variables.cs | 90 +- .../ConfigMaker/ConfigMakerViewModel.cs | 119 +- .../ConfigMakerPresetDocumentConverter.cs | 4 +- .../CreateConfig/ConfigComponentOption.cs | 3 + .../CreateConfigComponentSelection.cs | 103 ++ .../CreateConfigConditionDraft.cs | 84 + .../CreateConfigGraphicDesigner.cs | 109 ++ .../CreateConfig/CreateConfigTestSession.cs | 129 ++ ...reateNewConfigViewModel.GraphicDesigner.cs | 86 +- .../CreateNewConfigViewModel.Navigation.cs | 53 +- .../CreateNewConfigViewModel.Testing.cs | 95 +- .../CreateNewConfigViewModel.Variables.cs | 68 +- .../CreateConfig/CreateNewConfigViewModel.cs | 110 +- .../IBlockCheck2ManualPresetHost.cs | 17 + .../IBlockCheck2ManualPresetOperations.cs | 12 + ...BlockCheck2ManualStrategyTestOperations.cs | 20 + .../ViewModels/IBlockCheck2OptionsSettings.cs | 13 + .../IBlockCheck2ProgressEstimator.cs | 15 + .../IBlockCheck2ReportOperations.cs | 21 + CDPIUI/ViewModels/IBlockCheck2RunHost.cs | 30 + .../ViewModels/IBlockCheck2SiteListBackend.cs | 24 + CDPIUI/ViewModels/ObservableObject.cs | 3 + .../ConditionVariableModel.cs | 3 + ...raphicDesignerExclusiveSettingItemModel.cs | 3 + .../GraphicDesignerSettingItemModel.cs | 18 +- docs/DECOMPOSITION-ACCEPTANCE.ru.md | 111 ++ docs/DECOMPOSITION-DECISIONS.ru.md | 182 +++ docs/DECOMPOSITION-REVIEW-MAP.ru.md | 434 +++++ docs/DECOMPOSITION-STATUS.ru.md | 1427 +++++++++++++++++ .../plans/2026-11-08-class-decomposition.md | 1266 +++++++++++++++ .../plans/2026-11-11-class-integration.md | 73 + ...26-11-11-class-integration-provenance.json | 980 +++++++++++ .../2026-11-11-class-integration-source.md | 74 + ...11-diagnostic-highlighting-verification.md | 170 ++ .../2026-11-08-class-decomposition-design.md | 360 +++++ .../specs/2026-11-10-app-idle-exit-design.md | 31 + .../2026-11-10-assignment-actions-design.md | 70 + .../2026-11-10-manual-test-session-design.md | 69 + .../specs/2026-11-10-menu-pruning-design.md | 52 + .../specs/2026-11-10-report-export-design.md | 42 + .../specs/2026-11-10-report-summary-design.md | 24 + .../2026-11-10-result-selection-design.md | 31 + ...026-11-10-selected-strategy-test-design.md | 41 + .../2026-11-10-transition-sequence-design.md | 70 + .../2026-11-11-class-integration-design.md | 111 ++ ...onfiguration-variable-projection-design.md | 62 + ...26-11-11-diagnostic-highlighting-design.md | 81 + 212 files changed, 27615 insertions(+), 4349 deletions(-) create mode 100644 CDPIUI.Core/ComponentServices/Helpers/Configuration/Helpers/ConfigurationVariableProjection.cs create mode 100644 CDPIUI.Tests/ConfigurationVariableProjectionTests.cs create mode 100644 CDPIUI.Tests/Presentation/AppActivationDispatcherTests.cs create mode 100644 CDPIUI.Tests/Presentation/AppFileActivationHandlerTests.cs create mode 100644 CDPIUI.Tests/Presentation/AppIdleExitControllerTests.cs create mode 100644 CDPIUI.Tests/Presentation/AppWindowCloseCoordinatorTests.cs create mode 100644 CDPIUI.Tests/Presentation/AppWindowCoordinatorTests.cs create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2AssignmentActionsTests.cs create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2ManualAssignmentEditorTests.cs create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2ManualPresetStateTests.cs create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2ManualStrategyTestControllerTests.cs create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2ManualTestSessionTests.cs create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2OptionsTests.cs create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2ProgressTests.cs create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2ReportExportTests.cs create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2ReportSummaryPresenterTests.cs create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2ResultSelectionTests.cs create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2ResultTests.cs create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2RunControllerTests.cs create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2SelectedStrategyTestTests.cs create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2SiteListControllerTests.cs create mode 100644 CDPIUI.Tests/Presentation/ConfigMakerCommandHelpLoaderTests.cs create mode 100644 CDPIUI.Tests/Presentation/ConfigMakerCommandHelpPanelTests.cs create mode 100644 CDPIUI.Tests/Presentation/ConfigMakerDiagnosticsTests.cs create mode 100644 CDPIUI.Tests/Presentation/ConfigMakerDocumentCoordinatorTests.cs create mode 100644 CDPIUI.Tests/Presentation/ConfigMakerPanelLayoutTests.cs create mode 100644 CDPIUI.Tests/Presentation/ConfigMakerPresetFileActionsTests.cs create mode 100644 CDPIUI.Tests/Presentation/ConfigMakerPresetFileReplacerTests.cs create mode 100644 CDPIUI.Tests/Presentation/ConfigMakerPresetReferenceEditorTests.cs create mode 100644 CDPIUI.Tests/Presentation/ConfigMakerPresetResourceTests.cs create mode 100644 CDPIUI.Tests/Presentation/ConfigMakerPresetStructureTests.cs create mode 100644 CDPIUI.Tests/Presentation/ConfigMakerPresetTreeBuilderTests.cs create mode 100644 CDPIUI.Tests/Presentation/ConfigMakerSimpleDesignerTests.cs create mode 100644 CDPIUI.Tests/Presentation/ConfigMakerTestSessionTests.cs create mode 100644 CDPIUI.Tests/Presentation/ConfigMakerVariableActionsTests.cs create mode 100644 CDPIUI.Tests/Presentation/CreateConfigComponentSelectionTests.cs create mode 100644 CDPIUI.Tests/Presentation/CreateConfigConditionDraftTests.cs create mode 100644 CDPIUI.Tests/Presentation/CreateConfigGraphicDesignerTests.cs create mode 100644 CDPIUI.Tests/Presentation/CreateConfigTestSessionTests.cs create mode 100644 CDPIUI.Tests/Presentation/DiagnosticHighlightingUpdaterTests.cs create mode 100644 CDPIUI.Tests/Presentation/DispatcherTaskBridgeTests.cs create mode 100644 CDPIUI.Tests/Presentation/GraphicDesignerCommandCodecTests.cs create mode 100644 CDPIUI.Tests/Presentation/NamedValueCollectionLoaderTests.cs create mode 100644 CDPIUI.Tests/Presentation/PostOrderTreePrunerTests.cs create mode 100644 CDPIUI.Tests/Presentation/SelectedItemChoiceActionTests.cs create mode 100644 CDPIUI.Tests/Presentation/TextChangeRelayTests.cs create mode 100644 CDPIUI.Tests/Presentation/TwoPhaseTransitionSequenceTests.cs create mode 100644 CDPIUI/Helper/Basic/AppActivationDispatcher.cs create mode 100644 CDPIUI/Helper/Basic/AppActivationRequest.cs create mode 100644 CDPIUI/Helper/Basic/AppActivationRequestAdapter.cs create mode 100644 CDPIUI/Helper/Basic/AppFileActivationHandler.cs create mode 100644 CDPIUI/Helper/Basic/AppFileActivationOperations.cs create mode 100644 CDPIUI/Helper/Basic/AppIdleExitController.cs create mode 100644 CDPIUI/Helper/Basic/AppWindowCloseCoordinator.cs create mode 100644 CDPIUI/Helper/Basic/AppWindowCloseOperations.cs create mode 100644 CDPIUI/Helper/Basic/IAppFileActivationOperations.cs create mode 100644 CDPIUI/Helper/Basic/IAppWindowCloseOperations.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandHelpLoader.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandHelpPanel.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerComponentTestTasks.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerDiagnostics.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerDocumentCoordinator.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerPanelLayoutController.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerPanelLayoutView.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileActions.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileActionsBackend.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileReplacementBackend.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileReplacer.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetReferenceEditor.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetResourceRegistry.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetStructure.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeAdapter.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeBuilder.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeData.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeProjection.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerSimpleDesigner.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerSimpleDesignerBackend.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerTestSession.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ConfigMakerVariableActions.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/CreateConfigComponentTestTasks.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/CreateConfigGraphicDesignerBackend.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/GraphicDesignerCommandCodec.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/IConfigMakerDocumentHost.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/IConfigMakerDocumentStorage.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/IConfigMakerPanelLayoutView.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileActionsBackend.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileActionsHost.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileReplacementBackend.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileReplacementHost.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/IConfigMakerSimpleDesignerBackend.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/IConfigMakerTestTasks.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/IConfigMakerVariableActionsHost.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ICreateConfigGraphicDesignerBackend.cs create mode 100644 CDPIUI/Helper/CreateConfigHelper/ICreateConfigTestTasks.cs create mode 100644 CDPIUI/Helper/UserExperience/DiagnosticHighlightingUpdater.cs create mode 100644 CDPIUI/Helper/UserExperience/DispatcherTaskBridge.cs create mode 100644 CDPIUI/Helper/UserExperience/NamedValueCollectionLoader.cs create mode 100644 CDPIUI/Helper/UserExperience/PostOrderTreePruner.cs create mode 100644 CDPIUI/Helper/UserExperience/SelectedItemChoiceAction.cs create mode 100644 CDPIUI/Helper/UserExperience/TextChangeRelay.cs create mode 100644 CDPIUI/Helper/UserExperience/TwoPhaseTransitionSequence.cs create mode 100644 CDPIUI/Helper/WindowHelper/AppWindowCoordinator.cs create mode 100644 CDPIUI/Helper/WindowHelper/AppWindowOperations.cs create mode 100644 CDPIUI/Helper/WindowHelper/IAppWindowOperations.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/BlockCheck2AssignmentActions.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/BlockCheck2ManualComponentTestTasks.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/BlockCheck2ManualTestSession.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReportExport.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReportSummaryPresenter.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultSelection.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/BlockCheck2SelectedStrategyTest.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/IBlockCheck2AssignmentActionsHost.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/IBlockCheck2ManualTestHost.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2ManualAssignmentEditor.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2ManualIssueItem.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2ManualPresetOperations.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2ManualPresetState.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2ManualStrategyTestController.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2ManualStrategyTestOperations.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2OptionsSettings.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2OptionsViewModel.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2ProgressViewModel.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2ReportOperations.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2RunController.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2RunResultViewModel.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2SiteListBackend.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2SiteListController.cs create mode 100644 CDPIUI/ViewModels/CreateConfig/CreateConfigComponentSelection.cs create mode 100644 CDPIUI/ViewModels/CreateConfig/CreateConfigConditionDraft.cs create mode 100644 CDPIUI/ViewModels/CreateConfig/CreateConfigGraphicDesigner.cs create mode 100644 CDPIUI/ViewModels/CreateConfig/CreateConfigTestSession.cs create mode 100644 CDPIUI/ViewModels/IBlockCheck2ManualPresetHost.cs create mode 100644 CDPIUI/ViewModels/IBlockCheck2ManualPresetOperations.cs create mode 100644 CDPIUI/ViewModels/IBlockCheck2ManualStrategyTestOperations.cs create mode 100644 CDPIUI/ViewModels/IBlockCheck2OptionsSettings.cs create mode 100644 CDPIUI/ViewModels/IBlockCheck2ProgressEstimator.cs create mode 100644 CDPIUI/ViewModels/IBlockCheck2ReportOperations.cs create mode 100644 CDPIUI/ViewModels/IBlockCheck2RunHost.cs create mode 100644 CDPIUI/ViewModels/IBlockCheck2SiteListBackend.cs create mode 100644 docs/DECOMPOSITION-ACCEPTANCE.ru.md create mode 100644 docs/DECOMPOSITION-DECISIONS.ru.md create mode 100644 docs/DECOMPOSITION-REVIEW-MAP.ru.md create mode 100644 docs/DECOMPOSITION-STATUS.ru.md create mode 100644 docs/superpowers/plans/2026-11-08-class-decomposition.md create mode 100644 docs/superpowers/plans/2026-11-11-class-integration.md create mode 100644 docs/superpowers/reports/2026-11-11-class-integration-provenance.json create mode 100644 docs/superpowers/reports/2026-11-11-class-integration-source.md create mode 100644 docs/superpowers/reports/2026-11-11-diagnostic-highlighting-verification.md create mode 100644 docs/superpowers/specs/2026-11-08-class-decomposition-design.md create mode 100644 docs/superpowers/specs/2026-11-10-app-idle-exit-design.md create mode 100644 docs/superpowers/specs/2026-11-10-assignment-actions-design.md create mode 100644 docs/superpowers/specs/2026-11-10-manual-test-session-design.md create mode 100644 docs/superpowers/specs/2026-11-10-menu-pruning-design.md create mode 100644 docs/superpowers/specs/2026-11-10-report-export-design.md create mode 100644 docs/superpowers/specs/2026-11-10-report-summary-design.md create mode 100644 docs/superpowers/specs/2026-11-10-result-selection-design.md create mode 100644 docs/superpowers/specs/2026-11-10-selected-strategy-test-design.md create mode 100644 docs/superpowers/specs/2026-11-10-transition-sequence-design.md create mode 100644 docs/superpowers/specs/2026-11-11-class-integration-design.md create mode 100644 docs/superpowers/specs/2026-11-11-configuration-variable-projection-design.md create mode 100644 docs/superpowers/specs/2026-11-11-diagnostic-highlighting-design.md diff --git a/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs b/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs index 5885f692..44953430 100644 --- a/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs +++ b/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs @@ -270,22 +270,8 @@ public List GetVariables(string filename, string packId) return ToVariableItems(configItem.jparams); } - private static List ToVariableItems(Dictionary jparams) - { - List variables = []; - - foreach (var variable in jparams) - { - VariableItem variableItem = new() - { - name = variable.Key, - value = variable.Value, - }; - variables.Add(variableItem); - } - - return variables; - } + private static List ToVariableItems(Dictionary jparams) => + ConfigurationVariableProjection.ToVariableItems(jparams); public List GetCommaVariables(string filename, string packId) { @@ -293,25 +279,7 @@ public List GetCommaVariables(string filename, string packId) if (configItem?.commaVars == null) return []; - var result = new List(); - foreach (var commaVariable in configItem.commaVars) - { - AvailableVarValues? availableValues = configItem.availableCommaVarsValues?.FirstOrDefault( - item => string.Equals(item.VarName, commaVariable.Key, StringComparison.OrdinalIgnoreCase)); - List values = (availableValues?.Values ?? []) - .Distinct(StringComparer.Ordinal) - .ToList(); - - result.Add(new CommaVariableItem - { - name = commaVariable.Key, - comment = availableValues?.Comment, - value = commaVariable.Value, - values = values, - }); - } - - return result; + return ConfigurationVariableProjection.ToCommaVariableItems(configItem); } public List GetToggleLists(string filename, string packId) diff --git a/CDPIUI.Core/ComponentServices/Helpers/Configuration/Helpers/ConfigurationVariableProjection.cs b/CDPIUI.Core/ComponentServices/Helpers/Configuration/Helpers/ConfigurationVariableProjection.cs new file mode 100644 index 00000000..dc02eded --- /dev/null +++ b/CDPIUI.Core/ComponentServices/Helpers/Configuration/Helpers/ConfigurationVariableProjection.cs @@ -0,0 +1,45 @@ +namespace CDPIUI.Core.ComponentServices.Helpers.Configuration.Helpers; + +/// Builds owned read models from current preset variable definitions. +internal static class ConfigurationVariableProjection +{ + public static List ToVariableItems(Dictionary jparams) + { + List variables = []; + + foreach (var variable in jparams) + { + VariableItem variableItem = new() + { + name = variable.Key, + value = variable.Value, + }; + variables.Add(variableItem); + } + + return variables; + } + + public static List ToCommaVariableItems(ConfigItem configItem) + { + var result = new List(); + foreach (var commaVariable in configItem.commaVars!) + { + AvailableVarValues? availableValues = configItem.availableCommaVarsValues?.FirstOrDefault( + item => string.Equals(item.VarName, commaVariable.Key, StringComparison.OrdinalIgnoreCase)); + List values = (availableValues?.Values ?? []) + .Distinct(StringComparer.Ordinal) + .ToList(); + + result.Add(new CommaVariableItem + { + name = commaVariable.Key, + comment = availableValues?.Comment, + value = commaVariable.Value, + values = values, + }); + } + + return result; + } +} diff --git a/CDPIUI.Tests/CDPIUI.Tests.csproj b/CDPIUI.Tests/CDPIUI.Tests.csproj index 324792f5..70cb49fc 100644 --- a/CDPIUI.Tests/CDPIUI.Tests.csproj +++ b/CDPIUI.Tests/CDPIUI.Tests.csproj @@ -44,4 +44,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/CDPIUI.Tests/ConfigurationVariableProjectionTests.cs b/CDPIUI.Tests/ConfigurationVariableProjectionTests.cs new file mode 100644 index 00000000..8f5decd3 --- /dev/null +++ b/CDPIUI.Tests/ConfigurationVariableProjectionTests.cs @@ -0,0 +1,249 @@ +using System.Globalization; +using CDPIUI.Core.ComponentServices.Configuration; +using CDPIUI.Core.ComponentServices.Helpers.Configuration; + +namespace CDPIUI.Tests; + +public class ConfigurationVariableProjectionTests +{ + [Fact] + public void BooleanProjectionKeepsDictionaryOrderSpellingAndDefaultFields() + { + var item = new ConfigItem { jparams = new() { ["Zulu"] = false, ["alpha"] = true, [" %Raw% "] = true } }; + var result = ConfigurationService.GetVariables(item); + Assert.Equal(new[] { "Zulu", "alpha", " %Raw% " }, result.Select(v => v.name)); + Assert.Equal(new[] { false, true, true }, result.Select(v => v.value)); + Assert.All(result, v => Assert.Null(v.variable_name)); + } + + [Fact] + public void StaticAndInstanceBooleanProjectionsHaveEquivalentButIndependentResults() + { + var item = new ConfigItem { jparams = new() { ["flag"] = true } }; var service = Owned(item); + var first = ConfigurationService.GetVariables(item); var second = service.GetVariables(item.file_name!, item.packId!); + Assert.NotSame(first, second); Assert.NotSame(Assert.Single(first), Assert.Single(second)); + Assert.Equal(first[0].name, second[0].name); Assert.Equal(first[0].value, second[0].value); + first[0].name = "changed"; first[0].value = false; first.Clear(); + Assert.True(item.jparams["flag"]); Assert.Equal("flag", second[0].name); Assert.True(second[0].value); + } + + [Fact] + public void LaterBooleanCallsReadCurrentDictionaryAndAllocateNewModels() + { + var item = new ConfigItem { jparams = new() { ["first"] = false } }; + var first = ConfigurationService.GetVariables(item); item.jparams["first"] = true; item.jparams["next"] = false; + var second = ConfigurationService.GetVariables(item); + Assert.NotSame(first, second); Assert.NotSame(first[0], second[0]); Assert.False(first[0].value); + Assert.Equal(new[] { "first", "next" }, second.Select(v => v.name)); Assert.True(second[0].value); + } + + [Fact] + public void EmptyBooleanCallsStillOwnDifferentLists() + { + var item = new ConfigItem { jparams = [] }; + var first = ConfigurationService.GetVariables(item); var second = ConfigurationService.GetVariables(item); + Assert.Empty(first); Assert.Empty(second); Assert.NotSame(first, second); + } + + [Fact] + public void StaticNullItemKeepsItsNullReferenceFailure() + { + Assert.Throws(() => { ConfigurationService.GetVariables(null!); }); + } + + [Fact] + public void StaticNullDictionaryKeepsItsNullReferenceFailure() + { + Assert.Throws(() => { ConfigurationService.GetVariables(new ConfigItem()); }); + } + + [Fact] + public void MissingInstanceItemReturnsFreshEmptyLists() + { + var service = new ConfigurationService("owned"); + var first = service.GetVariables("missing", "missing"); var second = service.GetVariables("missing", "missing"); + var commaFirst = service.GetCommaVariables("missing", "missing"); var commaSecond = service.GetCommaVariables("missing", "missing"); + Assert.Empty(first); Assert.Empty(second); Assert.NotSame(first, second); + Assert.Empty(commaFirst); Assert.Empty(commaSecond); Assert.NotSame(commaFirst, commaSecond); + } + + [Fact] + public void InstanceNullDictionaryGuardsDoNotReadMalformedMetadata() + { + var item = new ConfigItem { availableCommaVarsValues = [null!] }; var service = Owned(item); + Assert.Empty(service.GetVariables(item.file_name!, item.packId!)); + Assert.Empty(service.GetCommaVariables(item.file_name!, item.packId!)); + } + + [Theory] + [InlineData("Fixture.json", "fixture-pack")] + [InlineData("fixture.json", "Fixture-pack")] + [InlineData("fixture.json ", "fixture-pack")] + public void InstanceLookupRetainsOrdinalUntrimmedFileAndPackNames(string file, string pack) + { + var item = new ConfigItem { jparams = new() { ["flag"] = true }, commaVars = new() { ["choice"] = "one" } }; + var service = Owned(item); + Assert.Empty(service.GetVariables(file, pack)); Assert.Empty(service.GetCommaVariables(file, pack)); + } + + [Fact] + public void CommaProjectionKeepsDictionaryOrderAndRawNames() + { + var item = new ConfigItem { commaVars = new() { ["Zulu"] = "z", ["alpha"] = "a", ["%Raw%"] = "raw" } }; + var result = Project(item); + Assert.Equal(new[] { "Zulu", "alpha", "%Raw%" }, result.Select(v => v.name)); + Assert.Equal(new[] { "z", "a", "raw" }, result.Select(v => v.value)); + Assert.All(result, v => { Assert.Null(v.comment); Assert.Empty(v.values); }); + } + + [Fact] + public void FirstCaseInsensitiveMetadataMatchWinsAndKeepsRawCurrentValue() + { + var first = new AvailableVarValues { VarName = "CHOICE", Comment = "first", Values = ["first-option"], CurrentValueIndex = 41 }; + var second = new AvailableVarValues { VarName = "choice", Comment = "second", Values = ["second-option"], CurrentValueIndex = 42 }; + var item = new ConfigItem { commaVars = new() { ["Choice"] = "outside-options" }, availableCommaVarsValues = [first, second] }; + var result = Assert.Single(Project(item)); + Assert.Equal("Choice", result.name); Assert.Equal("first", result.comment); Assert.Equal("outside-options", result.value); + Assert.Equal(new[] { "first-option" }, result.values); Assert.Equal(41, first.CurrentValueIndex); Assert.Equal(42, second.CurrentValueIndex); + } + + [Fact] + public void OptionsUseOrdinalStableDistinctAndKeepFirstStringReferences() + { + var first = new string(new[] { 'o', 'n', 'e' }); var duplicate = new string(new[] { 'o', 'n', 'e' }); + var item = Choice([first, "ONE", duplicate, "two", "ONE", "two"]); + var result = Assert.Single(Project(item)); + Assert.Equal(new[] { "one", "ONE", "two" }, result.values); Assert.Same(first, result.values[0]); + Assert.NotSame(item.availableCommaVarsValues![0].Values, result.values); + } + + [Fact] + public void ReturnedCommaModelsAndOptionListsAreIndependentAcrossCalls() + { + var item = Choice(["one", "two"]); var service = Owned(item); + var first = service.GetCommaVariables(item.file_name!, item.packId!); var second = service.GetCommaVariables(item.file_name!, item.packId!); + Assert.NotSame(first, second); Assert.NotSame(first[0], second[0]); Assert.NotSame(first[0].values, second[0].values); + first[0].name = "changed"; first[0].value = "changed"; first[0].comment = "changed"; first[0].values.Clear(); first.Clear(); + Assert.Equal("choice", second[0].name); Assert.Equal("current", second[0].value); Assert.Equal("comment", second[0].comment); + Assert.Equal(new[] { "one", "two" }, second[0].values); Assert.Equal(new[] { "one", "two" }, item.availableCommaVarsValues![0].Values); + Assert.Equal("current", item.commaVars!["choice"]); + } + + [Fact] + public void CaseVariantKeysSharingMetadataStillGetIndependentOptionLists() + { + var item = Choice(["one"]); item.commaVars!["CHOICE"] = "other"; + var result = Project(item); Assert.Equal(2, result.Count); + Assert.Equal(new[] { "choice", "CHOICE" }, result.Select(v => v.name)); Assert.NotSame(result[0].values, result[1].values); + result[0].values.Add("local"); Assert.Equal(new[] { "one" }, result[1].values); Assert.Equal(new[] { "one" }, item.availableCommaVarsValues![0].Values); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" outside ")] + public void RawCurrentValuesAreNotValidatedOrNormalized(string? value) + { + var item = Choice(["one"]); item.commaVars!["choice"] = value!; + Assert.Equal(value, Assert.Single(Project(item)).value); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" comment ")] + public void NullOptionsBecomeFreshEmptyListsWhileCommentsStayRaw(string? comment) + { + var item = Choice(null); item.availableCommaVarsValues![0].Comment = comment!; + var first = Assert.Single(Project(item)); var second = Assert.Single(Project(item)); + Assert.Equal(comment, first.comment); Assert.Empty(first.values); Assert.Empty(second.values); Assert.NotSame(first.values, second.values); + } + + [Fact] + public void MissingMetadataHasNullCommentAndAnOwnedEmptyList() + { + var item = Choice(["unused"]); item.availableCommaVarsValues![0].VarName = "different"; + var first = Assert.Single(Project(item)); var second = Assert.Single(Project(item)); + Assert.Null(first.comment); Assert.Empty(first.values); Assert.NotSame(first.values, second.values); + } + + [Fact] + public void EmptyDictionaryDoesNotInspectRuntimeNullMetadataEntries() + { + var item = new ConfigItem { commaVars = [], availableCommaVarsValues = [null!] }; + var first = Project(item); var second = Project(item); + Assert.Empty(first); Assert.Empty(second); Assert.NotSame(first, second); + } + + [Fact] + public void NullMetadataBeforeAMatchRetainsOriginalFailure() + { + var item = Choice(["one"]); item.availableCommaVarsValues!.Insert(0, null!); + Assert.Throws(() => { Project(item); }); + } + + [Fact] + public void MatchingMetadataStopsBeforeALaterRuntimeNullEntry() + { + var item = Choice(["one"]); item.availableCommaVarsValues!.Add(null!); + Assert.Equal(new[] { "one" }, Assert.Single(Project(item)).values); + } + + [Fact] + public void NullMetadataNameIsSkippedWithoutRepairingOtherMetadata() + { + var item = Choice(["one"]); item.availableCommaVarsValues!.Insert(0, new AvailableVarValues { VarName = null, Comment = "wrong" }); + Assert.Equal("comment", Assert.Single(Project(item)).comment); + } + + [Fact] + public void RuntimeNullOptionsAreRetainedOnceByOrdinalDistinct() + { + var item = Choice([null!, "one", null!, "ONE", "one"]); + var result = Assert.Single(Project(item)); Assert.Equal(3, result.values.Count); + Assert.Null(result.values[0]); Assert.Equal("one", result.values[1]); Assert.Equal("ONE", result.values[2]); + } + + [Fact] + public void LaterCallsReadReplacedSourceDictionaryAndMetadata() + { + var item = Choice(["old"]); var service = Owned(item); var first = service.GetCommaVariables(item.file_name!, item.packId!); + item.commaVars = new() { ["next"] = "new-current" }; + item.availableCommaVarsValues = [new AvailableVarValues { VarName = "NEXT", Comment = "new-comment", Values = ["new-option"] }]; + var second = Assert.Single(service.GetCommaVariables(item.file_name!, item.packId!)); + Assert.Equal("choice", first[0].name); Assert.Equal(new[] { "old" }, first[0].values); + Assert.Equal("next", second.name); Assert.Equal("new-current", second.value); Assert.Equal("new-comment", second.comment); + Assert.Equal(new[] { "new-option" }, second.values); + } + + [Fact] + public void MetadataMatchingAndOptionDistinctRemainOrdinalUnderTurkishCulture() + { + var previous = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("tr-TR"); + var item = new ConfigItem { commaVars = new() { ["I"] = "raw" }, availableCommaVarsValues = + [new AvailableVarValues { VarName = "İ", Comment = "wrong" }, new AvailableVarValues { VarName = "i", Comment = "right", Values = ["i", "I", "i"] }] }; + var result = Assert.Single(Project(item)); Assert.Equal("right", result.comment); Assert.Equal(new[] { "i", "I" }, result.values); + } + finally { CultureInfo.CurrentCulture = previous; } + } + + private static ConfigItem Choice(List? options) => new() + { + commaVars = new() { ["choice"] = "current" }, + availableCommaVarsValues = [new AvailableVarValues { VarName = "choice", Comment = "comment", Values = options }] + }; + + private static ConfigurationService Owned(ConfigItem item) + { + item.file_name ??= "fixture.json"; item.packId ??= "fixture-pack"; + var service = new ConfigurationService("owned"); service.SetConfigItem(item); return service; + } + + private static List Project(ConfigItem item) + { + var service = Owned(item); return service.GetCommaVariables(item.file_name!, item.packId!); + } +} diff --git a/CDPIUI.Tests/Presentation/AppActivationDispatcherTests.cs b/CDPIUI.Tests/Presentation/AppActivationDispatcherTests.cs new file mode 100644 index 00000000..076d78ef --- /dev/null +++ b/CDPIUI.Tests/Presentation/AppActivationDispatcherTests.cs @@ -0,0 +1,229 @@ +using CDPIUI.Helper.Basic; + +namespace CDPIUI.Tests.Presentation; + +public class AppActivationDispatcherTests +{ + [Fact] + public async Task StartupPreservesMigrationFilesProtocolAndDirectOrder() + { + var fixture = new ActivationFixture(); + string[] arguments = ["app.exe", "file.cdpiconfig", "----ms-protocol:cdpiui://public", "--direct:direct-payload"]; + fixture.DirectResult = true; + + bool handled = await fixture.Dispatcher.ProcessStartupAsync(arguments, _ => new()); + + Assert.True(handled); + Assert.Equal(["migration:argv", "files:app.exe|file.cdpiconfig|----ms-protocol:cdpiui://public|--direct:direct-payload", + "protocol:cdpiui://public", "direct:direct-payload"], fixture.Calls); + } + + [Fact] + public async Task InitialFilesSuppressCommandLineFilesButNotProtocolOrDirect() + { + var fixture = new ActivationFixture { FileResult = true, DirectResult = true }; + + bool handled = await fixture.Dispatcher.ProcessStartupAsync( + ["argv-file", "----ms-protocol:cdpiui://fallback", "--direct:payload"], + kind => kind == AppActivationKind.File ? new(kind, Files: ["initial-file"]) : new()); + + Assert.True(handled); + Assert.Equal(["migration:argv", "files:initial-file", "protocol:cdpiui://fallback", "direct:payload"], fixture.Calls); + } + + [Fact] + public async Task SuccessfulInitialProtocolSuppressesOnlyTheProtocolFallback() + { + var fixture = new ActivationFixture { ProtocolResult = true, DirectResult = true }; + + await fixture.Dispatcher.ProcessStartupAsync(["----ms-protocol:ignored", "--direct:payload"], + kind => kind == AppActivationKind.Protocol ? new(kind, ProtocolUri: "cdpiui://initial") : new()); + + Assert.Equal(["migration:argv", "protocol:cdpiui://initial", "files:----ms-protocol:ignored|--direct:payload", + "direct:payload"], fixture.Calls); + } + + [Fact] + public async Task FailedDirectResultStillOverridesTheEarlierProtocolResultAtStartup() + { + var fixture = new ActivationFixture { ProtocolResult = true, DirectResult = false }; + + bool handled = await fixture.Dispatcher.ProcessStartupAsync(["----ms-protocol:uri", "--direct:payload"], _ => new()); + + Assert.False(handled); + } + + [Fact] + public async Task InitialLaunchMigrationIsTriedOnlyWhenArgvMigrationWasNotHandled() + { + var fixture = new ActivationFixture { LaunchMigrationResult = true }; + + bool handled = await fixture.Dispatcher.ProcessStartupAsync([], kind => + kind == AppActivationKind.Launch ? new(kind, Arguments: "migration-data") : new()); + + Assert.True(handled); + Assert.Equal(["migration:argv", "migration:launch:migration-data", "files:"], fixture.Calls); + } + + [Fact] + public async Task StartupRetainsPartialSuccessWhenLaterProcessingThrows() + { + var fixture = new ActivationFixture { ArgvMigrationResult = true, ThrowOnFiles = true }; + + bool handled = await fixture.Dispatcher.ProcessStartupAsync(["file"], _ => new()); + + Assert.True(handled); + Assert.Equal(["migration:argv", "files:file", "startup-error:files failed"], fixture.Calls); + } + + [Fact] + public async Task StartupWaitsForMigrationBeforeReadingInitialActivation() + { + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + List initialReads = []; + var fixture = new ActivationFixture { ArgvMigrationCompletion = completion.Task }; + Task running = fixture.Dispatcher.ProcessStartupAsync([], kind => { initialReads.Add(kind); return new(); }); + + Assert.Equal(["migration:argv"], fixture.Calls); + Assert.Empty(initialReads); + completion.SetResult(false); + await running; + Assert.Equal([AppActivationKind.Launch, AppActivationKind.File, AppActivationKind.Protocol], initialReads); + } + + [Fact] + public async Task RedirectedProtocolDoesNotProcessFilesOrLaunchArguments() + { + var fixture = new ActivationFixture { ProtocolResult = true }; + + bool handled = await fixture.Dispatcher.ProcessRedirectedAsync(new(AppActivationKind.Protocol, ProtocolUri: "cdpiui://public?a=b%26c")); + + Assert.True(handled); + Assert.Equal(["protocol:cdpiui://public?a=b%26c"], fixture.Calls); + } + + [Fact] + public async Task RedirectedFilesArePassedThroughInOrder() + { + var fixture = new ActivationFixture { FileResult = true }; + + Assert.True(await fixture.Dispatcher.ProcessRedirectedAsync(new(AppActivationKind.File, Files: ["one", "two"]))); + Assert.Equal(["files:one|two"], fixture.Calls); + } + + [Fact] + public async Task RedirectedLaunchPreservesMigrationSplitDirectAndFileFallback() + { + var fixture = new ActivationFixture { SplitArguments = ["--direct:payload", "file"], FileResult = true }; + + Assert.True(await fixture.Dispatcher.ProcessRedirectedAsync(new(AppActivationKind.Launch, Arguments: "raw-launch"))); + Assert.Equal(["migration:launch:raw-launch", "split:raw-launch", "direct:payload", "gui-direct:payload", "files:--direct:payload|file"], fixture.Calls); + } + + [Theory] + [InlineData(true, false)] + [InlineData(false, true)] + public async Task RedirectedLaunchSkipsFileFallbackAfterMigrationOrDirectSuccess(bool migration, bool direct) + { + var fixture = new ActivationFixture + { + LaunchMigrationResult = migration, DirectResult = direct, SplitArguments = ["--direct:payload", "file"], + }; + + Assert.True(await fixture.Dispatcher.ProcessRedirectedAsync(new(AppActivationKind.Launch, Arguments: "raw"))); + Assert.Equal(migration + ? ["migration:launch:raw", "split:raw"] + : new[] { "migration:launch:raw", "split:raw", "direct:payload" }, fixture.Calls); + } + + [Fact] + public async Task RedirectedExceptionsPropagateToTheExistingAppErrorBoundary() + { + var fixture = new ActivationFixture { ThrowOnFiles = true }; + + await Assert.ThrowsAsync(() => + fixture.Dispatcher.ProcessRedirectedAsync(new(AppActivationKind.File, Files: ["file"]))); + Assert.Equal(["files:file"], fixture.Calls); + } + + [Fact] + public async Task DirectPrefixRemainsCaseSensitive() + { + var fixture = new ActivationFixture(); + + Assert.False(await fixture.Dispatcher.ProcessStartupAsync(["--DIRECT:payload"], _ => new())); + Assert.Equal(["migration:argv", "files:--DIRECT:payload"], fixture.Calls); + } + + [Fact] + public async Task StartupClearsProtocolSuccessBeforeAFailingGuiDirectFallback() + { + var fixture = new ActivationFixture { ProtocolResult = true, ThrowOnGuiDirect = true }; + + bool handled = await fixture.Dispatcher.ProcessStartupAsync(["----ms-protocol:uri", "--direct:payload"], _ => new()); + + Assert.False(handled); + Assert.Equal("startup-error:GUI direct failed", fixture.Calls[^1]); + } + + [Fact] + public async Task AlreadyHandledArgvMigrationSkipsOnlyTheInitialLaunchRead() + { + var fixture = new ActivationFixture { ArgvMigrationResult = true }; + List reads = []; + + await fixture.Dispatcher.ProcessStartupAsync([], kind => { reads.Add(kind); return new(); }); + + Assert.Equal([AppActivationKind.File, AppActivationKind.Protocol], reads); + } + + [Fact] + public async Task RedirectedLaunchReadsArgumentsAgainAfterMigrationCompletes() + { + string arguments = "before"; + var calls = new List(); + var dispatcher = new AppActivationDispatcher( + _ => Task.FromResult(false), + value => { calls.Add("migration:" + value); arguments = "after"; return Task.FromResult(false); }, + _ => Task.FromResult(false), _ => Task.FromResult(false), _ => Task.FromResult(false), _ => false, + value => { calls.Add("split:" + value); return []; }, _ => { }); + + await dispatcher.ProcessRedirectedAsync(new(AppActivationKind.Launch, + ReadLaunchArguments: () => arguments)); + + Assert.Equal(["migration:before", "split:after"], calls); + } + + private sealed class ActivationFixture + { + public List Calls { get; } = []; + public bool ArgvMigrationResult { get; init; } + public bool LaunchMigrationResult { get; init; } + public bool FileResult { get; init; } + public bool ProtocolResult { get; init; } + public bool DirectResult { get; set; } + public bool GuiDirectResult { get; init; } + public bool ThrowOnFiles { get; init; } + public bool ThrowOnGuiDirect { get; init; } + public Task? ArgvMigrationCompletion { get; init; } + public string[] SplitArguments { get; init; } = []; + public AppActivationDispatcher Dispatcher => new( + _ => { Calls.Add("migration:argv"); return ArgvMigrationCompletion ?? Task.FromResult(ArgvMigrationResult); }, + value => { Calls.Add("migration:launch:" + value); return Task.FromResult(LaunchMigrationResult); }, + files => + { + Calls.Add("files:" + string.Join('|', files)); + return ThrowOnFiles ? throw new InvalidOperationException("files failed") : Task.FromResult(FileResult); + }, + value => { Calls.Add("protocol:" + value); return Task.FromResult(ProtocolResult); }, + value => { Calls.Add("direct:" + value); return Task.FromResult(DirectResult); }, + value => + { + Calls.Add("gui-direct:" + value); + if (ThrowOnGuiDirect) throw new InvalidOperationException("GUI direct failed"); + return GuiDirectResult; + }, + value => { Calls.Add("split:" + value); return SplitArguments; }, + error => Calls.Add("startup-error:" + error.Message)); + } +} diff --git a/CDPIUI.Tests/Presentation/AppFileActivationHandlerTests.cs b/CDPIUI.Tests/Presentation/AppFileActivationHandlerTests.cs new file mode 100644 index 00000000..16906199 --- /dev/null +++ b/CDPIUI.Tests/Presentation/AppFileActivationHandlerTests.cs @@ -0,0 +1,271 @@ +using CDPIUI.Helper.Basic; + +namespace CDPIUI.Tests.Presentation; + +public sealed class AppFileActivationHandlerTests +{ + [Fact] + public void ConstructionDoesNotCallAnyOperation() + { + var f = new Fixture(); + Assert.Empty(f.Calls); + } + + [Fact] + public async Task EmptyInputIsNotHandled() + { + var f = new Fixture(); + Assert.False(await f.Handler.ProcessFiles([])); + Assert.Empty(f.Calls); + } + + [Fact] + public async Task NullInputRemainsAFaultedTaskRatherThanASynchronousThrow() + { + var f = new Fixture(); + Task handling = f.Handler.ProcessFiles(null!); + Assert.True(handling.IsFaulted); + await Assert.ThrowsAsync(() => handling); + Assert.Empty(f.Calls); + } + + [Fact] + public async Task NullElementFaultsBeforeLoggingAndDoesNotReachLaterFiles() + { + var f = new Fixture(); + Task handling = f.Handler.ProcessFiles([null!, "later.cdpitask"]); + await Assert.ThrowsAsync(() => handling); + Assert.Empty(f.Calls); + } + + [Theory] + [InlineData(".cdpisignedpack", "pack")] + [InlineData(".cdpiconfigpack", "pack")] + [InlineData(".cdpipatch", "update")] + [InlineData(".cdpitask", "task")] + [InlineData(".cdpiconfig", "share")] + [InlineData(".CDPICONFIG", "share")] + [InlineData(".CdPiTaSk", "task")] + [InlineData(".CDPIPATCH", "update")] + public async Task SupportedFilesKeepTheCaseInsensitiveWhitelistAndRouteOrder(string extension, string route) + { + var f = new Fixture(); + string path = "C:/fixture/input" + extension; + Assert.True(await f.Handler.ProcessFiles([path])); + Assert.Equal(new[] { "log:" + path, "exists:" + path, "share?:" + path, "open:" + route + ":" + path }, f.Calls); + } + + [Theory] + [InlineData(".zip")] + [InlineData(".exe")] + [InlineData(".txt")] + [InlineData(".cdpiconfig.bak")] + [InlineData("")] + [InlineData(".cdpitask ")] + public async Task ExistingUnsupportedNamesNeverAskAnImporter(string extension) + { + var f = new Fixture(); + string path = "input" + extension; + Assert.False(await f.Handler.ProcessFiles([path])); + Assert.Equal(new[] { "log:" + path, "exists:" + path }, f.Calls); + } + + [Fact] + public async Task MissingSupportedPathsStopBeforeTheSharePredicate() + { + var f = new Fixture(); + f.Operations.Exists = _ => false; + Assert.False(await f.Handler.ProcessFiles(["missing.cdpiconfig"])); + Assert.Equal(new[] { "log:missing.cdpiconfig", "exists:missing.cdpiconfig" }, f.Calls); + } + + [Theory] + [InlineData("\"C:/fixture/input.cdpitask\"", "C:/fixture/input.cdpitask", "task")] + [InlineData("C:/fi\"xture/in\"put.cdpipatch", "C:/fixture/input.cdpipatch", "update")] + public async Task AllDoubleQuotesAreRemovedBeforeLoggingAndLookup(string input, string normalized, string route) + { + var f = new Fixture(); + Assert.True(await f.Handler.ProcessFiles([input])); + Assert.Equal(new[] { "log:" + normalized, "exists:" + normalized, "share?:" + normalized, "open:" + route + ":" + normalized }, f.Calls); + } + + [Fact] + public async Task WhitespaceIsNotTrimmedFromAPath() + { + var f = new Fixture(); + string path = " C:/fixture/input.cdpitask "; + Assert.False(await f.Handler.ProcessFiles([path])); + Assert.Equal(new[] { "log:" + path, "exists:" + path }, f.Calls); + } + + [Theory] + [InlineData(".cdpitask")] + [InlineData(".cdpipatch")] + public async Task ShareSupportTakesPrecedenceOverTheOtherSpecialRoutes(string extension) + { + var f = new Fixture(); + f.Operations.Share = _ => true; + string path = "first" + extension; + Assert.True(await f.Handler.ProcessFiles([path, "later.cdpiconfig"])); + Assert.Equal("open:share:" + path, f.Calls.Last()); + Assert.Equal(4, f.Calls.Count); + } + + [Fact] + public async Task SkipsEarlierCandidatesThenStopsBeforeReadingALaterNull() + { + var f = new Fixture(); + f.Operations.Exists = path => path != "missing.cdpiconfig"; + Assert.True(await f.Handler.ProcessFiles(["unsupported.txt", "missing.cdpiconfig", "selected.cdpitask", null!])); + Assert.Equal(new[] { "log:unsupported.txt", "exists:unsupported.txt", "log:missing.cdpiconfig", "exists:missing.cdpiconfig", "log:selected.cdpitask", "exists:selected.cdpitask", "share?:selected.cdpitask", "open:task:selected.cdpitask" }, f.Calls); + } + + [Fact] + public async Task ReadsTheOriginalArrayLiveAfterAnOperationChangesTheNextElement() + { + var f = new Fixture(); + string[] paths = ["skip.exe", "before.cdpiconfig"]; + f.Operations.Exists = path => { if (path == "skip.exe") paths[1] = "after.cdpitask"; return true; }; + Assert.True(await f.Handler.ProcessFiles(paths)); + Assert.Equal(new[] { "log:skip.exe", "exists:skip.exe", "log:after.cdpitask", "exists:after.cdpitask", "share?:after.cdpitask", "open:task:after.cdpitask" }, f.Calls); + } + + [Theory] + [InlineData(".cdpiconfig", "share")] + [InlineData(".cdpitask", "task")] + [InlineData(".cdpipatch", "update")] + [InlineData(".cdpisignedpack", "pack")] + public async Task EachRouteIsAwaitedAndNoLaterFileIsRead(string extension, string route) + { + var f = new Fixture(); + var reply = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Operations.Open = (selectedRoute, _) => { Assert.Equal(route, selectedRoute); return reply.Task; }; + Task handling = f.Handler.ProcessFiles(["first" + extension, "later.cdpitask"]); + Assert.False(handling.IsCompleted); + Assert.Equal(4, f.Calls.Count); + Assert.Equal("open:" + route + ":first" + extension, f.Calls.Last()); + reply.SetResult(); + Assert.True(await handling); + Assert.Equal(4, f.Calls.Count); + } + + [Theory] + [InlineData("log")] + [InlineData("exists")] + [InlineData("share")] + public async Task SynchronousPortFailuresFaultTheAsyncResultAndDoNotTryTheNextFile(string point) + { + var f = new Fixture(); + var failure = new IOException(point); + if (point == "log") f.Operations.Log = _ => throw failure; + if (point == "exists") f.Operations.Exists = _ => throw failure; + if (point == "share") f.Operations.Share = _ => throw failure; + Task handling = f.Handler.ProcessFiles(["first.cdpiconfig", "later.cdpitask"]); + Assert.True(handling.IsFaulted); + Assert.Same(failure, await Assert.ThrowsAsync(() => handling)); + Assert.DoesNotContain(f.Calls, call => call.Contains("later", StringComparison.Ordinal)); + } + + [Theory] + [InlineData(".cdpiconfig")] + [InlineData(".cdpitask")] + [InlineData(".cdpipatch")] + [InlineData(".cdpisignedpack")] + public async Task RouteFailuresPropagateUnchangedWithoutFallback(string extension) + { + var f = new Fixture(); + var failure = new IOException("route failure"); + f.Operations.Open = (_, _) => Task.FromException(failure); + Assert.Same(failure, await Assert.ThrowsAsync(() => f.Handler.ProcessFiles(["first" + extension, "later.cdpitask"]))); + Assert.Equal(4, f.Calls.Count); + } + + [Theory] + [InlineData(".cdpiconfig")] + [InlineData(".cdpitask")] + [InlineData(".cdpipatch")] + [InlineData(".cdpisignedpack")] + public async Task CanceledRouteStaysCanceledInsteadOfFallingBack(string extension) + { + var f = new Fixture(); + f.Operations.Open = (_, _) => Task.FromCanceled(new CancellationToken(canceled: true)); + Task handling = f.Handler.ProcessFiles(["first" + extension, "later.cdpitask"]); + await Assert.ThrowsAnyAsync(() => handling); + Assert.True(handling.IsCanceled); + Assert.Equal(4, f.Calls.Count); + } + + [Fact] + public async Task RealStartupDispatcherUsesTheHandlerAndSuppressesArgvFilesAfterInitialFileSuccess() + { + var f = new Fixture(); + List errors = []; + var dispatcher = Dispatcher(f, errors); + Assert.True(await dispatcher.ProcessStartupAsync(["argv.cdpitask"], kind => + kind == AppActivationKind.File ? new(kind, Files: ["initial.cdpiconfig"]) : new())); + Assert.Equal(new[] { "log:initial.cdpiconfig", "exists:initial.cdpiconfig", "share?:initial.cdpiconfig", "open:share:initial.cdpiconfig" }, f.Calls); + Assert.Empty(errors); + } + + [Fact] + public async Task RealStartupDispatcherCatchesHandlerFailureWithoutContinuingTheArray() + { + var f = new Fixture(); + var failure = new IOException("import failed"); + f.Operations.Open = (_, _) => Task.FromException(failure); + List errors = []; + Assert.False(await Dispatcher(f, errors).ProcessStartupAsync(["first.cdpiconfig", "later.cdpitask"], _ => new())); + Assert.Same(failure, Assert.Single(errors)); + Assert.Equal(4, f.Calls.Count); + } + + [Fact] + public async Task RealRedirectedDispatcherLeavesHandlerFailureForTheAppBoundary() + { + var f = new Fixture(); + var failure = new IOException("import failed"); + f.Operations.Open = (_, _) => Task.FromException(failure); + List errors = []; + Assert.Same(failure, await Assert.ThrowsAsync(() => Dispatcher(f, errors).ProcessRedirectedAsync(new(AppActivationKind.File, Files: ["first.cdpiconfig", "later.cdpitask"])))); + Assert.Empty(errors); + Assert.Equal(4, f.Calls.Count); + } + + [Fact] + public async Task RealRedirectedLaunchFallsBackToTheHandlerAfterTheSplitter() + { + var f = new Fixture(); + List errors = []; + Assert.True(await Dispatcher(f, errors).ProcessRedirectedAsync(new(AppActivationKind.Launch, Arguments: "\"launch.cdpitask\""))); + Assert.Equal(new[] { "log:launch.cdpitask", "exists:launch.cdpitask", "share?:launch.cdpitask", "open:task:launch.cdpitask" }, f.Calls); + Assert.Empty(errors); + } + + private static AppActivationDispatcher Dispatcher(Fixture fixture, List errors) => new( + _ => Task.FromResult(false), _ => Task.FromResult(false), fixture.Handler.ProcessFiles, + _ => Task.FromResult(false), _ => Task.FromResult(false), _ => false, text => [text], errors.Add); + + private sealed class Fixture + { + public List Calls { get; } = []; + public Operations Operations { get; } + public AppFileActivationHandler Handler { get; } + public Fixture() { Operations = new(Calls); Handler = new(Operations); } + } + + private sealed class Operations(List calls) : IAppFileActivationOperations + { + public Action? Log; + public Func Exists = _ => true; + public Func Share = path => Path.GetExtension(path).Equals(".cdpiconfig", StringComparison.OrdinalIgnoreCase); + public Func Open = (_, _) => Task.CompletedTask; + public void LogFile(string path) { calls.Add("log:" + path); Log?.Invoke(path); } + public bool PathExists(string path) { calls.Add("exists:" + path); return Exists(path); } + public bool IsConfigShareSupported(string path) { calls.Add("share?:" + path); return Share(path); } + public Task OpenConfigShareAsync(string path) => Route("share", path); + public Task OpenConditionalTaskAsync(string path) => Route("task", path); + public Task OpenUpdateFileAsync(string path) => Route("update", path); + public Task OpenStorePackAsync(string path) => Route("pack", path); + private Task Route(string route, string path) { calls.Add("open:" + route + ":" + path); return Open(route, path); } + } +} diff --git a/CDPIUI.Tests/Presentation/AppIdleExitControllerTests.cs b/CDPIUI.Tests/Presentation/AppIdleExitControllerTests.cs new file mode 100644 index 00000000..0214b82f --- /dev/null +++ b/CDPIUI.Tests/Presentation/AppIdleExitControllerTests.cs @@ -0,0 +1,273 @@ +using CDPIUI.Helper.Basic; + +namespace CDPIUI.Tests.Presentation; + +// Call traces pin short circuits and callback boundaries; the delegates represent native endpoints. +public class AppIdleExitControllerTests +{ + [Fact] + public void ConstructionDoesNotReadStateOrInvokeNativeEndpoints() + { + var f = new Fixture(); + Assert.Empty(f.Calls); + } + + [Theory] + [InlineData(0, true, false, false, "migration,count")] + [InlineData(1, true, false, false, "migration,count,count")] + [InlineData(1, false, false, false, "migration,count")] + [InlineData(0, false, true, false, "migration,count,store")] + [InlineData(0, false, false, true, "migration,count,store,good")] + [InlineData(0, false, false, false, "migration,count,store,good,exit")] + public void ExitStopsAtFirstActiveCondition(int windows, bool migration, bool store, bool good, string trace) + { + var f = new Fixture { Windows = windows, Migration = migration, Store = store, Good = good }; + f.Owner.ExitIfIdle(); + Assert.Equal(trace.Split(','), f.Calls); + Assert.Empty(f.Warnings); + } + + [Fact] + public void PendingMigrationWithNonzeroFirstCountReadsCountAgainInsteadOfTakingSnapshot() + { + var f = new Fixture { Migration = true }; + int reads = 0; + f.ReadCount = () => ++reads == 1 ? 1 : 0; + f.Owner.ExitIfIdle(); + Assert.Equal(["migration", "count", "count", "store", "good", "exit"], f.Calls); + } + + [Fact] + public void MigrationChangedWhileReadingCountIsNotReadAgainInSameExit() + { + var f = new Fixture(); + f.ReadCount = () => { f.Migration = true; return 0; }; + f.Owner.ExitIfIdle(); + Assert.Equal(["migration", "count", "store", "good", "exit"], f.Calls); + } + + [Theory] + [InlineData(1, false, "count")] + [InlineData(0, true, "count,migration")] + [InlineData(0, false, "count,migration,create")] + public void WorkingCreatesPrepareOnlyForNoWindowsAndNoMigration(int windows, bool migration, string trace) + { + var f = new Fixture { Windows = windows, Migration = migration }; + f.Owner.HandleStoreStateChanged(true); + Assert.Equal(trace.Split(','), f.Calls); + Assert.Empty(f.Warnings); + } + + [Fact] + public void WorkingGuardReadsMigrationAfterWindowCountCallback() + { + var f = new Fixture(); + f.ReadCount = () => { f.Migration = true; return 0; }; + f.Owner.HandleStoreStateChanged(true); + Assert.Equal(["count", "migration"], f.Calls); + } + + [Fact] + public void StoppedClosesPrepareBeforeReadingAnyIdleCondition() + { + var f = new Fixture { Windows = 1, Migration = true, Store = true, Good = true }; + f.OnStep = step => + { + if (step == "close") { f.Windows = 0; f.Migration = false; f.Store = false; f.Good = false; } + }; + f.Owner.HandleStoreStateChanged(false); + Assert.Equal(["close", "migration", "count", "store", "good", "exit"], f.Calls); + } + + [Fact] + public void StoppedStillClosesPrepareWhenMigrationBecamePending() + { + var f = new Fixture(); + f.OnStep = step => { if (step == "close") f.Migration = true; }; + f.Owner.HandleStoreStateChanged(false); + Assert.Equal(["close", "migration", "count"], f.Calls); + } + + [Fact] + public void StoppedRereadsWindowAddedByCloseCallbackAndDoesNotExit() + { + var f = new Fixture(); + f.OnStep = step => { if (step == "close") f.Windows++; }; + f.Owner.HandleStoreStateChanged(false); + Assert.Equal(["close", "migration", "count"], f.Calls); + } + + [Theory] + [InlineData("migration", "migration")] + [InlineData("count", "migration,count")] + [InlineData("store", "migration,count,store")] + [InlineData("good", "migration,count,store,good")] + [InlineData("exit", "migration,count,store,good,exit")] + public void DirectExitDoesNotCatchPortExceptions(string failing, string trace) + { + var f = new Fixture(); var error = new IOException(failing); + f.OnStep = step => { if (step == failing) throw error; }; + Assert.Same(error, Assert.Throws(() => f.Owner.ExitIfIdle())); + Assert.Equal(trace.Split(','), f.Calls); + Assert.Empty(f.Warnings); + } + + [Theory] + [InlineData("count", "count,warn,migration,count,store,good,exit")] + [InlineData("migration", "count,migration,warn,migration,count,store,good,exit")] + [InlineData("create", "count,migration,create,warn,migration,count,store,good,exit")] + public void WorkingSynchronousFailureWarnsWithSameExceptionThenChecksCurrentIdleState(string failing, string trace) + { + var f = new Fixture(); var error = new IOException(failing); bool thrown = false; + f.OnStep = step => { if (step == failing && !thrown) { thrown = true; throw error; } }; + f.Owner.HandleStoreStateChanged(true); + Assert.Same(error, Assert.Single(f.Warnings)); + Assert.Equal(trace.Split(','), f.Calls); + } + + [Fact] + public void CloseFailureWarnsOnceThenChecksIdleWithoutRetryingClose() + { + var f = new Fixture(); var error = new IOException("close"); + f.OnStep = step => { if (step == "close") throw error; }; + f.Owner.HandleStoreStateChanged(false); + Assert.Same(error, Assert.Single(f.Warnings)); + Assert.Equal(["close", "warn", "migration", "count", "store", "good", "exit"], f.Calls); + } + + [Theory] + [InlineData("migration", "close,migration,warn,migration,count,store,good,exit")] + [InlineData("count", "close,migration,count,warn,migration,count,store,good,exit")] + [InlineData("store", "close,migration,count,store,warn,migration,count,store,good,exit")] + [InlineData("good", "close,migration,count,store,good,warn,migration,count,store,good,exit")] + [InlineData("exit", "close,migration,count,store,good,exit,warn,migration,count,store,good,exit")] + public void StoppedIdleFailureIsInsideStoreCatchAndGetsOneRetry(string failing, string trace) + { + var f = new Fixture(); var error = new IOException(failing); bool thrown = false; + f.OnStep = step => { if (step == failing && !thrown) { thrown = true; throw error; } }; + f.Owner.HandleStoreStateChanged(false); + Assert.Same(error, Assert.Single(f.Warnings)); + Assert.Equal(trace.Split(','), f.Calls); + } + + [Fact] + public void WarningCanChangeConditionsBeforeFallbackReadsThem() + { + var f = new Fixture(); var error = new IOException("close"); + f.OnStep = step => { if (step == "close") throw error; if (step == "warn") f.Windows = 1; }; + f.Owner.HandleStoreStateChanged(false); + Assert.Same(error, Assert.Single(f.Warnings)); + Assert.Equal(["close", "warn", "migration", "count"], f.Calls); + } + + [Fact] + public void WarningFailureEscapesWithoutFallback() + { + var f = new Fixture(); var primary = new IOException("close"); var warning = new IOException("warn"); + f.OnStep = step => { if (step == "close") throw primary; if (step == "warn") throw warning; }; + Assert.Same(warning, Assert.Throws(() => f.Owner.HandleStoreStateChanged(false))); + Assert.Same(primary, Assert.Single(f.Warnings)); + Assert.Equal(["close", "warn"], f.Calls); + } + + [Fact] + public void FallbackFailureEscapesWithoutSecondWarningOrRetry() + { + var f = new Fixture(); var primary = new IOException("close"); var fallback = new IOException("store"); + f.OnStep = step => { if (step == "close") throw primary; if (step == "store") throw fallback; }; + Assert.Same(fallback, Assert.Throws(() => f.Owner.HandleStoreStateChanged(false))); + Assert.Same(primary, Assert.Single(f.Warnings)); + Assert.Equal(["close", "warn", "migration", "count", "store"], f.Calls); + } + + [Fact] + public void SecondIdleFailureEscapesRatherThanRecursivelyRetrying() + { + var f = new Fixture(); var error = new IOException("store"); + f.OnStep = step => { if (step == "store") throw error; }; + Assert.Same(error, Assert.Throws(() => f.Owner.HandleStoreStateChanged(false))); + Assert.Same(error, Assert.Single(f.Warnings)); + Assert.Equal(["close", "migration", "count", "store", "warn", "migration", "count", "store"], f.Calls); + } + + [Fact] + public async Task PendingCreateIsStartedWithoutWaitingForCompletion() + { + var f = new Fixture(); var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Create = () => completion.Task; + Task call = Task.Run(() => f.Owner.HandleStoreStateChanged(true)); + try + { + await call.WaitAsync(TimeSpan.FromSeconds(2)); + Assert.False(completion.Task.IsCompleted); + Assert.Equal(["count", "migration", "create"], f.Calls); + Assert.Empty(f.Warnings); + } + finally { completion.TrySetResult(); await call.WaitAsync(TimeSpan.FromSeconds(2)); } + } + + [Fact] + public void AlreadyFaultedCreateTaskDoesNotEnterSynchronousCatch() + { + var f = new Fixture(); var error = new IOException("async create"); Task failed = Task.FromException(error); + f.Create = () => failed; + f.Owner.HandleStoreStateChanged(true); + Assert.Equal(["count", "migration", "create"], f.Calls); + Assert.Empty(f.Warnings); + Assert.Same(error, Assert.Single(failed.Exception!.InnerExceptions)); + } + + [Fact] + public void CloseCallbackCanReenterWorkingEventBeforeOuterIdleCheck() + { + var f = new Fixture(); + f.OnStep = step => { if (step == "close") f.Owner.HandleStoreStateChanged(true); }; + f.Owner.HandleStoreStateChanged(false); + Assert.Equal(["close", "count", "migration", "create", "migration", "count", "store", "good", "exit"], f.Calls); + } + + [Fact] + public void CreateCallbackCanReenterStoppedEventWithoutDeduplication() + { + var f = new Fixture(); + f.Create = () => { f.Owner.HandleStoreStateChanged(false); return Task.CompletedTask; }; + f.Owner.HandleStoreStateChanged(true); + Assert.Equal(["count", "migration", "create", "close", "migration", "count", "store", "good", "exit"], f.Calls); + } + + [Fact] + public void LaterCallsReadAllConditionsAgainRatherThanCachingPriorWork() + { + var f = new Fixture { Store = true }; + f.Owner.ExitIfIdle(); + f.Store = false; f.Calls.Clear(); + f.Owner.ExitIfIdle(); + Assert.Equal(["migration", "count", "store", "good", "exit"], f.Calls); + } + + private sealed class Fixture + { + public readonly List Calls = []; + public readonly List Warnings = []; + public int Windows; + public bool Migration, Store, Good; + public Action? OnStep; + public Func? ReadCount; + public Func Create = () => Task.CompletedTask; + public readonly AppIdleExitController Owner; + + public Fixture() + { + Owner = new( + () => { Step("count"); return ReadCount?.Invoke() ?? Windows; }, + () => { Step("migration"); return Migration; }, + () => { Step("store"); return Store; }, + () => { Step("good"); return Good; }, + () => { Step("create"); return Create(); }, + () => Step("close"), () => Step("exit"), + error => { Warnings.Add(error); Step("warn"); }); + } + + private void Step(string step) { Calls.Add(step); OnStep?.Invoke(step); } + } +} diff --git a/CDPIUI.Tests/Presentation/AppWindowCloseCoordinatorTests.cs b/CDPIUI.Tests/Presentation/AppWindowCloseCoordinatorTests.cs new file mode 100644 index 00000000..a54a7520 --- /dev/null +++ b/CDPIUI.Tests/Presentation/AppWindowCloseCoordinatorTests.cs @@ -0,0 +1,260 @@ +using System.Runtime.CompilerServices; +using CDPIUI.Helper.Basic; + +namespace CDPIUI.Tests.Presentation; + +public sealed class AppWindowCloseCoordinatorTests +{ + [Fact] + public void ConstructorOnlyStoresListAndOperations() + { + var f = new Fixture(); Assert.Empty(f.Ops.Trace); Assert.Same(f.Window, Assert.Single(f.Windows)); + } + + [Fact] + public void NormalCloseCleansBeforeCurrentStoreQueryAndLowEnqueue() + { + var f = new Fixture(); var counts = new List<(string, int)>(); + f.Ops.OnStep = step => counts.Add((step, f.Windows.Count)); + f.Owner.HandleClosed(f.Window); + Assert.Equal(["capture", "migration", "save", "detach", "release", "forget", "store", "enqueue"], f.Ops.Trace); + Assert.Contains(("release", 1), counts); Assert.Contains(("forget", 0), counts); Assert.Empty(f.Windows); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void MigrationCompletesInsideFinallyThenEnqueuesWithoutStoreOrPrepare(bool storeWorking) + { + var f = new Fixture(); f.Ops.Migration = true; f.Ops.StoreWorking = storeWorking; + f.Owner.HandleClosed(f.Window); + Assert.Equal(["capture", "migration", "save", "detach", "release", "complete", "forget", "enqueue"], f.Ops.Trace); + Assert.Empty(f.Windows); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RejectedEnqueueRunsSynchronousExitAfterCleanup(bool migration) + { + var f = new Fixture(); f.Ops.Migration = migration; f.Ops.Queue = () => false; + f.Owner.HandleClosed(f.Window); + Assert.Equal(["enqueue", "exit"], f.Ops.Trace.TakeLast(2)); Assert.Empty(f.Windows); + } + + [Fact] + public void EmptyWindowListWithStoreWorkStartsPrepareWithoutQueueOrExit() + { + var f = new Fixture(); f.Ops.StoreWorking = true; + f.Owner.HandleClosed(f.Window); + Assert.Equal(["capture", "migration", "save", "detach", "release", "forget", "store", "prepare"], f.Ops.Trace); + } + + [Fact] + public void RemainingWindowSkipsStoreQueryAndDoesNotCreatePrepare() + { + var f = new Fixture(); var other = new TestWindow(); f.Windows.Add(other); f.Ops.StoreWorking = true; + f.Owner.HandleClosed(f.Window); + Assert.Same(other, Assert.Single(f.Windows)); Assert.DoesNotContain("store", f.Ops.Trace); + Assert.DoesNotContain("prepare", f.Ops.Trace); Assert.Equal("enqueue", f.Ops.Trace.Last()); + } + + [Fact] + public void MissingWindowStillRunsCleanupAndDuplicateReferenceRemovesOnlyOne() + { + var f = new Fixture(); f.Windows.Clear(); f.Owner.HandleClosed(f.Window); + Assert.Contains("forget", f.Ops.Trace); Assert.Contains("store", f.Ops.Trace); Assert.Empty(f.Windows); + f = new Fixture(); f.Windows.Add(f.Window); f.Owner.HandleClosed(f.Window); + Assert.Same(f.Window, Assert.Single(f.Windows)); Assert.DoesNotContain("store", f.Ops.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void MigrationBooleanIsCapturedBeforeSaveCallbacks(bool initial) + { + var f = new Fixture(); f.Ops.Migration = initial; + f.Ops.OnStep = step => { if (step == "save") f.Ops.Migration = !initial; }; + f.Owner.HandleClosed(f.Window); + Assert.Equal(initial, f.Ops.Trace.Contains("complete")); Assert.Equal(!initial, f.Ops.Trace.Contains("store")); + Assert.Equal(1, f.Ops.Trace.Count(x => x == "migration")); + } + + [Fact] + public void EnqueueTargetIsCapturedBeforeSaveAndCalledOnlyAfterCleanup() + { + var f = new Fixture(); var queues = new List(); + f.Ops.Queue = () => { queues.Add("original"); return true; }; + f.Ops.OnStep = step => { if (step == "save") f.Ops.Queue = () => { queues.Add("replacement"); return false; }; }; + f.Owner.HandleClosed(f.Window); + Assert.Equal(["original"], queues); Assert.Equal("enqueue", f.Ops.Trace.Last()); Assert.DoesNotContain("exit", f.Ops.Trace); + } + + [Fact] + public void ForgetReentryUsesCurrentListCountRatherThanEarlierSnapshot() + { + var f = new Fixture(); var added = new TestWindow(); + f.Ops.OnStep = step => { if (step == "forget") f.Windows.Add(added); }; + f.Owner.HandleClosed(f.Window); + Assert.Same(added, Assert.Single(f.Windows)); Assert.DoesNotContain("store", f.Ops.Trace); + } + + [Fact] + public void SaveReentryMayReplaceMembershipWithoutRemovingNewWindow() + { + var f = new Fixture(); var added = new TestWindow(); + f.Ops.OnStep = step => { if (step == "save") { f.Windows.Clear(); f.Windows.Add(added); } }; + f.Owner.HandleClosed(f.Window); + Assert.Same(added, Assert.Single(f.Windows)); Assert.Contains("forget", f.Ops.Trace); Assert.DoesNotContain("store", f.Ops.Trace); + } + + [Fact] + public void StoreCallbackChangingListDoesNotAddNewCountRevalidation() + { + var f = new Fixture(); f.Ops.StoreWorking = true; + f.Ops.OnStep = step => { if (step == "store") f.Windows.Add(new()); }; + f.Owner.HandleClosed(f.Window); Assert.Single(f.Windows); Assert.Equal("prepare", f.Ops.Trace.Last()); + } + + [Theory] + [InlineData("save")] + [InlineData("release")] + public void RecoverableSaveOrModalFailureWarnsThenContinuesCleanup(string failing) + { + var f = new Fixture(); var error = new IOException(failing); + f.Ops.OnStep = step => { if (step == failing) throw error; }; + f.Owner.HandleClosed(f.Window); + Assert.Same(error, Assert.Single(f.Ops.Warned)); Assert.Empty(f.Windows); + Assert.Equal(["forget", "store", "enqueue"], f.Ops.Trace.TakeLast(3)); + } + + [Fact] + public void ListRemoveFailureWarnsAndForgetsWithoutPretendingRemovalSucceeded() + { + var f = new Fixture(); var error = new IOException("equals"); f.Window.EqualsError = error; + f.Owner.HandleClosed(f.Window); + Assert.Same(error, Assert.Single(f.Ops.Warned)); Assert.Same(f.Window, Assert.Single(f.Windows)); + Assert.Equal(["warn", "forget", "enqueue"], f.Ops.Trace.TakeLast(3)); Assert.DoesNotContain("store", f.Ops.Trace); + } + + [Fact] + public void WarningFailureInSaveCatchStillExecutesOuterFinallyButSkipsPostCleanupDispatch() + { + var f = new Fixture(); var primary = new IOException("save"); var logger = new IOException("logger"); + f.Ops.OnStep = step => { if (step == "save") throw primary; if (step == "warn") throw logger; }; + Assert.Same(logger, Assert.Throws(() => f.Owner.HandleClosed(f.Window))); + Assert.Empty(f.Windows); Assert.Equal(["detach", "release", "forget"], f.Ops.Trace.TakeLast(3)); + Assert.DoesNotContain("enqueue", f.Ops.Trace); + } + + [Fact] + public void WarningFailureInsideModalCleanupStopsRemainingFinally() + { + var f = new Fixture(); var primary = new IOException("release"); var logger = new IOException("logger"); + f.Ops.OnStep = step => { if (step == "release") throw primary; if (step == "warn") throw logger; }; + Assert.Same(logger, Assert.Throws(() => f.Owner.HandleClosed(f.Window))); + Assert.Same(f.Window, Assert.Single(f.Windows)); Assert.Equal("warn", f.Ops.Trace.Last()); + Assert.DoesNotContain("forget", f.Ops.Trace); + } + + [Theory] + [InlineData("capture", 1)] + [InlineData("migration", 1)] + [InlineData("detach", 1)] + [InlineData("complete", 0)] + [InlineData("forget", 0)] + [InlineData("store", 0)] + [InlineData("prepare", 0)] + [InlineData("enqueue", 0)] + [InlineData("exit", 0)] + public void UncaughtOperationFailureKeepsExactCleanupStage(string failing, int remaining) + { + var f = new Fixture(); var error = new IOException(failing); + f.Ops.Migration = failing == "complete"; f.Ops.StoreWorking = failing == "prepare"; + if (failing == "exit") f.Ops.Queue = () => false; + f.Ops.OnStep = step => { if (step == failing) throw error; }; + Assert.Same(error, Assert.Throws(() => f.Owner.HandleClosed(f.Window))); + Assert.Equal(remaining, f.Windows.Count); Assert.Equal(failing, f.Ops.Trace.Last()); Assert.Empty(f.Ops.Warned); + } + + [Fact] + public void MigrationCompletionPrecedesForgetAndDispatchEvenAfterRecoverablePositionFailure() + { + var f = new Fixture(); f.Ops.Migration = true; + f.Ops.OnStep = step => { if (step == "save") throw new IOException("save"); }; + f.Owner.HandleClosed(f.Window); + Assert.Equal(["complete", "forget", "enqueue"], f.Ops.Trace.TakeLast(3)); Assert.Single(f.Ops.Warned); + } + + [Fact] + public async Task PendingPrepareTaskIsNotSynchronouslyJoined() + { + var f = new Fixture(); f.Ops.StoreWorking = true; + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); f.Ops.PrepareTask = gate.Task; + Task worker = Task.Run(() => f.Owner.HandleClosed(f.Window)); + try { await worker.WaitAsync(TimeSpan.FromSeconds(2)); Assert.False(gate.Task.IsCompleted); Assert.Equal("prepare", f.Ops.Trace.Last()); } + finally { gate.TrySetResult(true); await worker.WaitAsync(TimeSpan.FromSeconds(2)); } + } + + [Fact] + public void FaultedPrepareTaskRemainsUnawaitedAndNoExtraCatchLogsIt() + { + var f = new Fixture(); f.Ops.StoreWorking = true; var error = new IOException("async prepare"); + Task failed = Task.FromException(error); f.Ops.PrepareTask = failed; + f.Owner.HandleClosed(f.Window); Assert.Empty(f.Ops.Warned); + Assert.Same(error, Assert.Single(failed.Exception!.InnerExceptions)); + } + + [Fact] + public void ReentrantCloseDuringSaveKeepsIndependentOuterContinuation() + { + var f = new Fixture(); var nested = new TestWindow(); f.Windows.Add(nested); bool entered = false; + f.Ops.OnStep = step => + { + if (step == "save" && !entered) { entered = true; f.Owner.HandleClosed(nested); } + }; + f.Owner.HandleClosed(f.Window); + Assert.Empty(f.Windows); Assert.Equal(2, f.Ops.Trace.Count(x => x == "capture")); + Assert.Equal(2, f.Ops.Trace.Count(x => x == "enqueue")); Assert.Equal(1, f.Ops.Trace.Count(x => x == "store")); + } + + private sealed class TestWindow + { + public Exception? EqualsError; + public override bool Equals(object? other) => EqualsError is null ? ReferenceEquals(this, other) : throw EqualsError; + public override int GetHashCode() => RuntimeHelpers.GetHashCode(this); + } + private sealed class Fixture + { + public Fixture() { Windows.Add(Window); Owner = new(Windows, Ops); } + public TestWindow Window { get; } = new(); + public List Windows { get; } = []; + public Operations Ops { get; } = new(); + public AppWindowCloseCoordinator Owner { get; } + } + private sealed class Operations : IAppWindowCloseOperations + { + public List Trace { get; } = []; + public List Warned { get; } = []; + public Action? OnStep; + public bool Migration, StoreWorking; + public Func Queue = () => true; + public Task PrepareTask = Task.CompletedTask; + private void Step(string step) { Trace.Add(step); OnStep?.Invoke(step); } + public Func CaptureExitEnqueue(TestWindow window) + { + Step("capture"); var queue = Queue; + return () => { Step("enqueue"); return queue(); }; + } + public bool IsMigrationWindow(TestWindow window) { Step("migration"); return Migration; } + public void SavePosition(TestWindow window) => Step("save"); + public void Detach(TestWindow window) => Step("detach"); + public void ReleaseModal(TestWindow window) => Step("release"); + public void Warn(Exception error) { Warned.Add(error); Step("warn"); } + public void CompleteMigration() => Step("complete"); + public void ForgetOwner(TestWindow window) => Step("forget"); + public bool IsStoreWorking() { Step("store"); return StoreWorking; } + public Task CreatePrepareAsync() { Step("prepare"); return PrepareTask; } + public void ExitIfIdle() => Step("exit"); + } +} diff --git a/CDPIUI.Tests/Presentation/AppWindowCoordinatorTests.cs b/CDPIUI.Tests/Presentation/AppWindowCoordinatorTests.cs new file mode 100644 index 00000000..5cfec9f7 --- /dev/null +++ b/CDPIUI.Tests/Presentation/AppWindowCoordinatorTests.cs @@ -0,0 +1,297 @@ +using CDPIUI.Helper.WindowHelper; + +namespace CDPIUI.Tests.Presentation; + +public class AppWindowCoordinatorTests +{ + [Fact] + public void ConstructionDoesNotReadReadinessOrWindowState() + { + var fixture = new WindowFixture(); + + Assert.Empty(fixture.Trace); + Assert.Equal(0, fixture.ReadyReads); + } + + [Fact] + public async Task SafeCreationWaitsForReadinessThenUsesTheLiveWindowList() + { + var fixture = new WindowFixture(); + var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + fixture.Ready = ready.Task; + + var creation = fixture.Coordinator.CreateSafeAsync(typeof(TestWindow), true); + Assert.False(creation.IsCompleted); + Assert.Empty(fixture.Trace); + var window = new TestWindow("late"); + fixture.Windows.Add(window); + ready.SetResult(); + + Assert.Same(window, await creation); + Assert.Equal(["live:late", "activate:late"], fixture.Trace); + } + + [Fact] + public async Task EachCreationReadsTheCurrentReadinessTask() + { + var fixture = new WindowFixture(); + fixture.Windows.Add(new TestWindow("existing")); + await fixture.Coordinator.CreateSafeAsync(typeof(TestWindow), false); + fixture.Trace.Clear(); + var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + fixture.Ready = ready.Task; + + var creation = fixture.Coordinator.CreateSafeAsync(typeof(TestWindow), false); + + Assert.False(creation.IsCompleted); + Assert.Equal(2, fixture.ReadyReads); + Assert.Empty(fixture.Trace); + ready.SetResult(); + await creation; + } + + [Fact] + public async Task AReadinessFailureDoesNotTouchWindows() + { + var fixture = new WindowFixture { Ready = Task.FromException(new IOException("not ready")) }; + + await Assert.ThrowsAsync(() => fixture.Coordinator.CreateUnsafeAsync(typeof(TestWindow), true, "id")); + + Assert.Empty(fixture.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task SafeCreationReusesTheOnlyLiveWindow(bool activate) + { + var fixture = new WindowFixture(); + var window = new TestWindow("one"); + fixture.Windows.Add(window); + + Assert.Same(window, await fixture.Coordinator.CreateSafeAsync(typeof(TestWindow), activate)); + + Assert.Equal(activate ? ["live:one", "activate:one"] : new[] { "live:one" }, fixture.Trace); + Assert.Same(window, Assert.Single(fixture.Windows)); + } + + [Fact] + public async Task ADeadWindowIsClosedAndRemovedBeforeCreatingAndRegisteringItsReplacement() + { + var fixture = new WindowFixture(); + fixture.Windows.Add(new TestWindow("dead") { HasDispatcher = false }); + + var window = await fixture.Coordinator.CreateSafeAsync(typeof(TestWindow), true); + + Assert.Same(fixture.Created, window); + Assert.Same(window, Assert.Single(fixture.Windows)); + Assert.Equal(["live:dead", "close:dead", "create", "position:created", "register:created:False", "activate:created"], fixture.Trace); + } + + [Fact] + public async Task DuplicateWindowsAreReplacedFromASnapshotEvenIfClosingAddsAnotherWindow() + { + var fixture = new WindowFixture(); + fixture.Windows.AddRange([new TestWindow("first"), new TestWindow("second")]); + var late = new TestWindow("late"); + fixture.AfterClose = window => { if (window.Name == "first") fixture.Windows.Add(late); }; + + await fixture.Coordinator.CreateSafeAsync(typeof(TestWindow), false); + + Assert.Equal(["live:first", "close:first", "close:second", "create", "position:created", "register:created:False"], fixture.Trace); + Assert.Equal([late, fixture.Created], fixture.Windows); + } + + [Fact] + public async Task ANullTypeWithNoWindowsReachesTheFactoryAndPreservesItsArgumentException() + { + var fixture = new WindowFixture { CreateError = new ArgumentNullException("type") }; + + await Assert.ThrowsAsync(() => fixture.Coordinator.CreateSafeAsync(null!, true)); + Assert.Equal(["create"], fixture.Trace); + fixture.Trace.Clear(); + await Assert.ThrowsAsync(() => fixture.Coordinator.CreateUnsafeAsync(null!, true, "id")); + Assert.Equal(["create"], fixture.Trace); + } + + [Fact] + public async Task CreationFailurePropagatesAfterOldWindowsHaveBeenRemoved() + { + var fixture = new WindowFixture(); + fixture.Windows.Add(new TestWindow("dead") { HasDispatcher = false }); + fixture.CreateError = new IOException("create failed"); + + await Assert.ThrowsAsync(() => fixture.Coordinator.CreateSafeAsync(typeof(TestWindow), true)); + + Assert.Empty(fixture.Windows); + Assert.Equal(["live:dead", "close:dead", "create"], fixture.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task PositionOrRegistrationFailureDoesNotActivateTheNewWindow(bool registerFailure) + { + var fixture = new WindowFixture(); + if (registerFailure) fixture.RegisterError = new IOException("register failed"); + else fixture.PositionError = new IOException("position failed"); + + await Assert.ThrowsAsync(() => fixture.Coordinator.CreateSafeAsync(typeof(TestWindow), true)); + + Assert.DoesNotContain(fixture.Trace, item => item.StartsWith("activate:", StringComparison.Ordinal)); + Assert.Empty(fixture.Windows); + } + + [Fact] + public async Task UnsafeReuseIgnoresDispatcherAndMatchesTheFirstNonEmptyTemplateIdIgnoringCase() + { + var fixture = new WindowFixture(); + fixture.Windows.Add(new TestWindow("plain")); + var first = new TemplateTestWindow("first", "ID") { HasDispatcher = false }; + fixture.Windows.AddRange([first, new TemplateTestWindow("second", "id")]); + + Assert.Same(first, await fixture.Coordinator.CreateUnsafeAsync(typeof(TestWindow), true, "id")); + + Assert.Equal(["id:plain", "id:first", "activate:first"], fixture.Trace); + Assert.Equal(3, fixture.Windows.Count); + } + + [Fact] + public async Task UnsafeCreationWithAnEmptyIdAlwaysCreatesAnotherTemplate() + { + var fixture = new WindowFixture(); + var existing = new TemplateTestWindow("empty", ""); + fixture.Windows.Add(existing); + + var created = await fixture.Coordinator.CreateUnsafeAsync(typeof(TemplateTestWindow), false, ""); + + Assert.Same(fixture.Created, created); + Assert.Equal("", fixture.Created.Id); + Assert.Equal([existing, fixture.Created], fixture.Windows); + Assert.Equal(["id:empty", "create", "set-id:created:", "position:created", "register:created:True"], fixture.Trace); + } + + [Fact] + public async Task UnsafeCreationSetsIdBeforePositionRegistrationAndActivationWithoutClosingOtherIds() + { + var fixture = new WindowFixture(); + fixture.Windows.Add(new TemplateTestWindow("other", "other-id")); + + await fixture.Coordinator.CreateUnsafeAsync(typeof(TemplateTestWindow), true, "new-id"); + + Assert.Equal("new-id", fixture.Created.Id); + Assert.Equal(["id:other", "create", "set-id:created:new-id", "position:created", "register:created:True", "activate:created"], fixture.Trace); + Assert.Equal(2, fixture.Windows.Count); + } + + [Fact] + public async Task UnsafeCreationAlsoWaitsBeforeTakingItsWindowSnapshot() + { + var fixture = new WindowFixture(); + var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + fixture.Ready = ready.Task; + var creation = fixture.Coordinator.CreateUnsafeAsync(typeof(TemplateTestWindow), false, "id"); + var late = new TemplateTestWindow("late", "id"); + fixture.Windows.Add(late); + ready.SetResult(); + + Assert.Same(late, await creation); + Assert.Equal(["id:late"], fixture.Trace); + } + + [Fact] + public void GetCurrentSelectsTheFirstLiveAssignableWindowAndSkipsNulls() + { + var fixture = new WindowFixture(); + var live = new TemplateTestWindow("live", "id"); + fixture.Windows.AddRange([null!, new TestWindow("dead") { HasDispatcher = false }, live]); + + Assert.Same(live, fixture.Coordinator.GetCurrent(typeof(TestWindow))); + + Assert.Equal(["live:dead", "live:live"], fixture.Trace); + } + + [Fact] + public void CloseAllClosesAndRemovesOnlyItsOriginalTypeSnapshot() + { + var fixture = new WindowFixture(); + var other = new TestWindow("other"); + var first = new TemplateTestWindow("first", "1"); + var late = new TemplateTestWindow("late", "2"); + fixture.Windows.AddRange([other, first]); + fixture.AfterClose = _ => { fixture.Windows.Remove(first); fixture.Windows.Add(late); }; + + fixture.Coordinator.CloseAll(typeof(TemplateTestWindow)); + + Assert.Equal(["close:first"], fixture.Trace); + Assert.Equal([other, late], fixture.Windows); + } + + [Theory] + [InlineData("id", "ID")] + [InlineData("", "")] + public void CloseTemplateUsesTheFirstMatchingIdAndLeavesListRemovalToTheCloseEvent(string id, string stored) + { + var fixture = new WindowFixture(); + fixture.Windows.AddRange([new TemplateTestWindow("first", stored), new TemplateTestWindow("second", stored)]); + + fixture.Coordinator.CloseTemplate(typeof(TemplateTestWindow), id); + + Assert.Equal(["id:first", "close:first"], fixture.Trace); + Assert.Equal(2, fixture.Windows.Count); + } + + [Fact] + public void ACloseFailureStopsBeforeExplicitRemovalOrFurtherCloses() + { + var fixture = new WindowFixture(); + fixture.Windows.AddRange([new TestWindow("first"), new TestWindow("second")]); + fixture.CloseError = new IOException("close failed"); + + Assert.Throws(() => fixture.Coordinator.CloseAll(typeof(TestWindow))); + + Assert.Equal(["close:first"], fixture.Trace); + Assert.Equal(2, fixture.Windows.Count); + } + + private class TestWindow(string name) + { + public string Name { get; } = name; + public bool HasDispatcher { get; set; } = true; + } + + private sealed class TemplateTestWindow(string name, string id) : TestWindow(name) + { + public string Id { get; set; } = id; + } + + private sealed class WindowFixture : IAppWindowOperations + { + public WindowFixture() => Coordinator = new(Windows, () => { ReadyReads++; return Ready; }, this); + public List Windows { get; } = []; + public List Trace { get; } = []; + public Task Ready { get; set; } = Task.CompletedTask; + public int ReadyReads { get; private set; } + public TemplateTestWindow Created { get; } = new("created", ""); + public Action? AfterClose { get; set; } + public Exception? CreateError { get; set; } + public Exception? PositionError { get; set; } + public Exception? RegisterError { get; set; } + public Exception? CloseError { get; set; } + public AppWindowCoordinator Coordinator { get; } + + public bool HasDispatcher(TestWindow window) { Trace.Add("live:" + window.Name); return window.HasDispatcher; } + public bool TryGetTemplateId(TestWindow window, out string? id) + { + Trace.Add("id:" + window.Name); + id = (window as TemplateTestWindow)?.Id; + return window is TemplateTestWindow; + } + public TestWindow Create(Type windowType) { Trace.Add("create"); if (CreateError != null) throw CreateError; return Created; } + public void SetTemplateId(TestWindow window, string id) { Trace.Add($"set-id:{window.Name}:{id}"); ((TemplateTestWindow)window).Id = id; } + public void SetPosition(TestWindow window) { Trace.Add("position:" + window.Name); if (PositionError != null) throw PositionError; } + public void Register(TestWindow window, bool isUnsafe) { Trace.Add($"register:{window.Name}:{isUnsafe}"); if (RegisterError != null) throw RegisterError; Windows.Add(window); } + public void Activate(TestWindow window) => Trace.Add("activate:" + window.Name); + public void Close(TestWindow window) { Trace.Add("close:" + window.Name); if (CloseError != null) throw CloseError; AfterClose?.Invoke(window); } + } +} diff --git a/CDPIUI.Tests/Presentation/BlockCheck2AssignmentActionsTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2AssignmentActionsTests.cs new file mode 100644 index 00000000..c0ce8e2d --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2AssignmentActionsTests.cs @@ -0,0 +1,320 @@ +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.ViewModels; +using CDPIUI.ViewModels.BlockCheck2; + +namespace CDPIUI.Tests.Presentation; + +public class BlockCheck2AssignmentActionsTests +{ + [Fact] + public void ConstructionDoesNotReadViewOrModel() + { + var f = new Fixture(); + Assert.Empty(f.Trace); + } + + [Fact] + public async Task MissingSelectionStopsBothAddPathsBeforeAnyOtherPort() + { + var f = new Fixture { Item = null }; + f.Owner.AddSelectedStrategyForSite(); + await f.Owner.AddSelectedStrategyForListAsync(); + Assert.Equal(["selected", "selected"], f.Trace); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AddSitePublishesLiteralNoticeThenBothUpdates(bool added) + { + var f = new Fixture { Added = added }; var item = f.Item; + f.Owner.AddSelectedStrategyForSite(); + Assert.Same(item, f.AddedItem); + Assert.Equal(new[] { "selected", "site", "text:" + Title(added), "text:" + Message(added), "show", "assignments", "buttons" }, f.Trace); + Assert.Equal((added ? BlockCheck2NoticeSeverity.Success : BlockCheck2NoticeSeverity.Warning, Title(added), Message(added)), Assert.Single(f.Notices)); + } + + [Fact] + public async Task NoPathsStopsWithoutChooserOrNotice() + { + var f = new Fixture { Paths = [] }; + await f.Owner.AddSelectedStrategyForListAsync(); + Assert.Equal(["selected", "paths"], f.Trace); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" one path ")] + public async Task SinglePathSkipsChooserAndKeepsItsExactText(string? path) + { + var f = new Fixture { Paths = [path!] }; + await f.Owner.AddSelectedStrategyForListAsync(); + Assert.Equal(path, f.AddedPath); + Assert.DoesNotContain("choose", f.Trace); + Assert.Same(f.Item, f.AddedItem); + Assert.Equal("old", f.AddedModel); + } + + // A selected row is captured, paths are copied, and the model is read only when adding after await. + [Fact] + public async Task PendingChoiceKeepsCapturedRowAndSnapshotButUsesCurrentModel() + { + var f = new Fixture(); var oldItem = f.Item; var paths = new List { "A", "B" }; f.Paths = paths; + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Choose = _ => gate.Task; + Task task = f.Owner.AddSelectedStrategyForListAsync(); + try + { + Assert.False(task.IsCompleted); + Assert.Equal(["selected", "paths", "choose"], f.Trace); + Assert.NotSame(paths, f.ChosenPaths); + Assert.Equal(["A", "B"], Assert.IsType(f.ChosenPaths)); + paths.Clear(); paths.Add("changed source"); f.Item = Item("new"); f.Model = "current"; + gate.SetResult("B"); + await task.WaitAsync(TimeSpan.FromSeconds(3)); + Assert.Same(oldItem, f.AddedItem); + Assert.Equal("current", f.AddedModel); + Assert.Equal("B", f.AddedPath); + Assert.Equal(["A", "B"], f.ChosenPaths); + Assert.Equal(1, f.Trace.Count(x => x == "selected")); + } + finally { gate.TrySetResult(null); await task.WaitAsync(TimeSpan.FromSeconds(3)); } + } + + [Fact] + public async Task ChooserReceivesTheActualSnapshotArray() + { + var f = new Fixture(); + f.Choose = paths => { var array = Assert.IsType(paths); array[0] = "changed snapshot"; return Task.FromResult(array[0]); }; + await f.Owner.AddSelectedStrategyForListAsync(); + Assert.Equal("changed snapshot", f.AddedPath); + Assert.Equal("A", f.Paths[0]); + } + + [Fact] + public async Task CancelledChoiceDoesNotAddOrPublish() + { + var f = new Fixture { Choose = _ => Task.FromResult(null) }; + await f.Owner.AddSelectedStrategyForListAsync(); + Assert.Equal(["selected", "paths", "choose"], f.Trace); + Assert.Null(f.AddedItem); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("outside list")] + public async Task NonNullChoiceIsPassedWithoutNewValidation(string path) + { + var f = new Fixture { Choose = _ => Task.FromResult(path) }; + await f.Owner.AddSelectedStrategyForListAsync(); + Assert.Equal(path, f.AddedPath); + Assert.Single(f.Notices); + } + + [Fact] + public async Task IndependentChoicesCanFinishInReverseOrder() + { + var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var second = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var f = new Fixture(); var a = f.Item; var b = Item("b"); int calls = 0; + f.Choose = _ => ++calls == 1 ? first.Task : second.Task; + Task one = f.Owner.AddSelectedStrategyForListAsync(); f.Item = b; + Task two = f.Owner.AddSelectedStrategyForListAsync(); + try + { + Assert.False(one.IsCompleted); Assert.False(two.IsCompleted); Assert.Equal(2, calls); + second.SetResult("B"); await two.WaitAsync(TimeSpan.FromSeconds(3)); + Assert.Same(b, f.AddedItem); Assert.False(one.IsCompleted); + first.SetResult("A"); await one.WaitAsync(TimeSpan.FromSeconds(3)); + Assert.Same(a, f.AddedItem); Assert.Equal(2, f.Notices.Count); + } + finally + { + first.TrySetResult(null); second.TrySetResult(null); + await one.WaitAsync(TimeSpan.FromSeconds(3)); await two.WaitAsync(TimeSpan.FromSeconds(3)); + } + } + + [Theory] + [InlineData("selected")] + [InlineData("paths")] + [InlineData("choose")] + [InlineData("list")] + public async Task SetupAndAddFailuresAreReturnedAsFaultedTasks(string step) + { + var f = new Fixture(); var expected = new InvalidOperationException(step); + f.OnStep = name => { if (name == step) throw expected; }; + Task? task = null; + Assert.Null(Record.Exception(() => { task = f.Owner.AddSelectedStrategyForListAsync(); })); + Assert.Same(expected, await Assert.ThrowsAsync(() => task!)); + Assert.Empty(f.Notices); Assert.DoesNotContain("assignments", f.Trace); + } + + [Fact] + public async Task ActuallyCancelledChooserKeepsCancellationStatusWithoutNotices() + { + var f = new Fixture { Choose = _ => Task.FromCanceled(new CancellationToken(true)) }; + Task task = f.Owner.AddSelectedStrategyForListAsync(); + await Assert.ThrowsAnyAsync(() => task); + Assert.True(task.IsCanceled); Assert.Empty(f.Notices); Assert.Null(f.AddedItem); + } + + [Fact] + public void MoveWithoutSelectionDoesNotCallModelOrView() + { + var f = new Fixture(); f.Owner.MoveSelectedAssignment(-20); + Assert.Equal(["assignment"], f.Trace); + } + + [Fact] + public void RejectedMoveDoesNotPublishOrReselect() + { + var f = new Fixture { Assignment = Assignment(), Moved = false }; + f.Owner.MoveSelectedAssignment(0); + Assert.Equal(["assignment", "move:0"], f.Trace); + } + + [Theory] + [InlineData(-100)] + [InlineData(0)] + [InlineData(100)] + public void SuccessfulMovePublishesBeforeRestoringCapturedSelection(int offset) + { + var f = new Fixture { Assignment = Assignment() }; var original = f.Assignment; + f.OnStep = step => { if (step == "assignments") f.Assignment = Assignment(); }; + f.Owner.MoveSelectedAssignment(offset); + Assert.Equal(new[] { "assignment", "move:" + offset, "assignments", "select" }, f.Trace); + Assert.Same(original, f.MovedItem); Assert.Same(original, f.Assignment); + } + + [Fact] + public void UpdateFaultAfterMovePreventsReselection() + { + var f = new Fixture { Assignment = Assignment() }; var replacement = Assignment(); + var expected = new InvalidOperationException("update"); + f.OnStep = step => { if (step == "assignments") { f.Assignment = replacement; throw expected; } }; + Assert.Same(expected, Assert.Throws(() => f.Owner.MoveSelectedAssignment(1))); + Assert.Same(replacement, f.Assignment); Assert.DoesNotContain("select", f.Trace); + } + + [Fact] + public void RemoveWithoutSelectionDoesNothingElse() + { + var f = new Fixture(); f.Owner.RemoveSelectedAssignment(); Assert.Equal(["assignment"], f.Trace); + } + + [Fact] + public void RemoveAlwaysPublishesAfterModelAndUsesCapturedObject() + { + var f = new Fixture { Assignment = Assignment() }; var original = f.Assignment; + f.OnStep = step => { if (step == "remove") f.Assignment = null; }; + f.Owner.RemoveSelectedAssignment(); + Assert.Equal(["assignment", "remove", "assignments"], f.Trace); Assert.Same(original, f.RemovedItem); + } + + [Fact] + public void ClearPublishesEvenWhenNoAssignmentIsSelected() + { + var f = new Fixture(); f.Owner.ClearAssignments(); Assert.Equal(["clear", "assignments"], f.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void QuickFixOnlyPublishesWhenAccepted(bool accepted) + { + var f = new Fixture { Fixed = accepted }; + f.Owner.ApplyManualIssueQuickFix(() => { f.Trace.Add("fix"); return f.Fixed; }); + Assert.Equal(accepted ? new[] { "fix", "text:BlockCheck2ManualIssueQuickFixCompletedTitle", "text:BlockCheck2ManualScopeOverlapAcceptedMessage", "show", "assignments" } : ["fix"], f.Trace); + if (accepted) Assert.Equal((BlockCheck2NoticeSeverity.Success, "BlockCheck2ManualIssueQuickFixCompletedTitle", "BlockCheck2ManualScopeOverlapAcceptedMessage"), Assert.Single(f.Notices)); + } + + [Theory] + [InlineData("text:BlockCheck2AssignmentAddedTitle", 0)] + [InlineData("text:BlockCheck2AssignmentAddedMessage", 0)] + [InlineData("show", 1)] + [InlineData("assignments", 1)] + [InlineData("buttons", 1)] + public void NoticeAndUpdateFaultsKeepIdentityAndStopTheRemainingEffects(string step, int notices) + { + var f = new Fixture(); var error = new InvalidOperationException(step); + f.OnStep = name => { if (name == step) throw error; }; + Assert.Same(error, Assert.Throws(() => f.Owner.ShowResult(true))); + Assert.Equal(step, f.Trace.Last()); Assert.Equal(notices, f.Notices.Count); + } + + [Fact] + public void SynchronousModelFaultDoesNotBecomeATaskOrShowNotice() + { + var f = new Fixture(); var error = new InvalidOperationException("owned model fault"); + f.OnStep = step => { if (step == "site") throw error; }; + Assert.Same(error, Assert.Throws(f.Owner.AddSelectedStrategyForSite)); + Assert.Empty(f.Notices); Assert.DoesNotContain("assignments", f.Trace); + } + + [Theory] + [InlineData("apply")] + [InlineData("text:BlockCheck2ManualIssueQuickFixCompletedTitle")] + [InlineData("text:BlockCheck2ManualScopeOverlapAcceptedMessage")] + [InlineData("show")] + [InlineData("assignments")] + public void QuickFixFaultsRemainSynchronousAndStopSubsequentEffects(string step) + { + var f = new Fixture(); var error = new InvalidOperationException(step); + f.OnStep = name => { if (name == step) throw error; }; + Assert.Same(error, Assert.Throws(() => f.Owner.ApplyManualIssueQuickFix(() => + { + f.Trace.Add("apply"); if (step == "apply") throw error; return true; + }))); + Assert.Equal(step, f.Trace.Last()); Assert.DoesNotContain("buttons", f.Trace); + } + + [Fact] + public void ResultNoticeAllowsReentryWithoutSuppressingOuterUpdates() + { + var f = new Fixture(); bool nested = false; + f.OnStep = step => { if (step == "assignments" && !nested) { nested = true; f.Owner.ShowResult(false); } }; + f.Owner.ShowResult(true); + Assert.Equal(new[] { "text:" + Title(true), "text:" + Message(true), "show", "assignments", + "text:" + Title(false), "text:" + Message(false), "show", "assignments", "buttons", "buttons" }, f.Trace); + } + + private static string Title(bool success) => success ? "BlockCheck2AssignmentAddedTitle" : "BlockCheck2AssignmentNotAddedTitle"; + private static string Message(bool success) => success ? "BlockCheck2AssignmentAddedMessage" : "BlockCheck2AssignmentDuplicateMessage"; + private static BlockCheck2StrategyEvidenceItem Item(string id) => new(new() { Strategy = new() { Id = id }, Target = new() { Id = id, Host = "fixture.invalid" } }); + private static BlockCheck2ManualAssignmentItem Assignment() => new(new("s", "t", BlockCheckManualScopeKind.Site), new() { Id = "s" }, new() { Id = "t", Host = "fixture.invalid" }, "--args"); + + private sealed class Fixture : IBlockCheck2AssignmentActionsHost + { + internal readonly BlockCheck2AssignmentActions Owner; + internal readonly List Trace = []; + internal readonly List<(BlockCheck2NoticeSeverity, string, string)> Notices = []; + internal BlockCheck2StrategyEvidenceItem? Item = BlockCheck2AssignmentActionsTests.Item("old"), AddedItem; + internal BlockCheck2ManualAssignmentItem? Assignment, MovedItem, RemovedItem; + internal IReadOnlyList Paths = new[] { "A", "B" }; + internal IReadOnlyList? ChosenPaths; + internal string Model = "old"; + internal string? AddedModel, AddedPath; + internal bool Added = true, Moved = true, Fixed = true; + internal Action? OnStep; + internal Func, Task> Choose = _ => Task.FromResult("B"); + internal Fixture() => Owner = new(this); + private void Step(string name) { Trace.Add(name); OnStep?.Invoke(name); } + public BlockCheck2StrategyEvidenceItem? SelectedStrategy { get { Step("selected"); return Item; } } + public IReadOnlyList GetSiteListPaths(BlockCheck2StrategyEvidenceItem item) { Step("paths"); return Paths; } + public Task ChooseSiteListAsync(IReadOnlyList paths) { ChosenPaths = paths; Step("choose"); return Choose(paths); } + public bool AddForSite(BlockCheck2StrategyEvidenceItem item) { AddedItem = item; AddedModel = Model; Step("site"); return Added; } + public bool AddForSiteList(BlockCheck2StrategyEvidenceItem item, string path) { AddedItem = item; AddedPath = path; AddedModel = Model; Step("list"); return Added; } + public BlockCheck2ManualAssignmentItem? SelectedAssignment { get { Step("assignment"); return Assignment; } set { Assignment = value; Step("select"); } } + public bool MoveAssignment(BlockCheck2ManualAssignmentItem item, int offset) { MovedItem = item; Step("move:" + offset); return Moved; } + public void RemoveAssignment(BlockCheck2ManualAssignmentItem item) { RemovedItem = item; Step("remove"); } + public void ClearAssignments() => Step("clear"); + public void UpdateAssignmentView() => Step("assignments"); + public void UpdateActionButtons() => Step("buttons"); + public string Text(string key) { Step("text:" + key); return key; } + public void ShowMessage(BlockCheck2NoticeSeverity severity, string title, string message) { Notices.Add((severity, title, message)); Step("show"); } + } +} diff --git a/CDPIUI.Tests/Presentation/BlockCheck2ManualAssignmentEditorTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2ManualAssignmentEditorTests.cs new file mode 100644 index 00000000..facf3aa8 --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2ManualAssignmentEditorTests.cs @@ -0,0 +1,467 @@ +using System.Collections.Specialized; +using System.Globalization; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.AddOns.BlockCheck2.Reporting; +using CDPIUI.ViewModels; + +namespace CDPIUI.Tests.Presentation; + +public class BlockCheck2ManualAssignmentEditorTests +{ + [Fact] + public void EditorUsesTheExistingDraftCollectionWithoutChangingItAtConstruction() + { + var f = new Fixture(); + Assert.Same(f.Draft.Assignments, f.Editor.Items); + Assert.Empty(f.Trace); + Assert.Empty(f.Editor.Items); + } + + [Fact] + public void MissingSessionRefusesAddsAndSiteListQueriesWithoutMutation() + { + var f = new Fixture { Session = null }; + var evidence = Evidence(Strategy("s"), Target("t")); + Assert.False(f.Editor.AddForSite(evidence)); + Assert.False(f.Editor.AddForSiteList(evidence, "sites.txt")); + Assert.False(f.Editor.CanAddForSiteList(evidence)); + Assert.Empty(f.Editor.GetSiteListPaths(evidence)); + Assert.Empty(f.Trace); + } + + [Fact] + public void AddUsesSessionDefinitionsAndAcknowledgesBeforeFormattingAndCollectionPublication() + { + var f = new Fixture(); + var strategy = Strategy("S"); + var target = Target("target"); + f.Session = Session([strategy], [target]); + f.Editor.Items.CollectionChanged += (_, args) => + { + var item = Assert.IsType(Assert.Single(args.NewItems!)); + Assert.Same(strategy, item.Strategy); + Assert.Same(target, item.Target); + Assert.Equal("formatted:S", item.StrategyArguments); + f.Trace.Add("collection:" + args.Action); + }; + + Assert.True(f.Editor.AddForSite(Evidence(Strategy("s"), Target("target")))); + + Assert.Equal(["ack", "format:S", "collection:Add", "rebuild:True"], f.Trace); + Assert.Equal(new BlockCheckManualAssignment("s", "target", BlockCheckManualScopeKind.Site), + Assert.Single(f.Editor.Items).Assignment); + } + + [Theory] + [InlineData("S", "target", true)] + [InlineData("s", "TARGET", false)] + public void DuplicateStrategyMatchingIsInsensitiveButAnchorMatchingIsOrdinal(string strategyId, string targetId, bool duplicate) + { + var f = new Fixture(); + var strategy = Strategy("s"); + f.Session = Session([strategy], [Target("target"), Target("TARGET")]); + Assert.True(f.Editor.AddForSite(Evidence(strategy, Target("target")))); + f.Trace.Clear(); + + Assert.Equal(!duplicate, f.Editor.AddForSite(Evidence(Strategy(strategyId), Target(targetId)))); + + Assert.Equal(duplicate ? 1 : 2, f.Editor.Items.Count); + if (duplicate) Assert.Empty(f.Trace); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void MissingStrategyOrAnchorRefusesTheAssignmentWithoutCallbacks(bool missingStrategy) + { + var f = new Fixture { Session = Session([Strategy("s")], [Target("t")]) }; + Assert.False(f.Editor.AddForSite(Evidence(Strategy(missingStrategy ? "missing" : "s"), Target(missingStrategy ? "t" : "missing")))); + Assert.Empty(f.Editor.Items); + Assert.Empty(f.Trace); + } + + [Fact] + public void SiteListAddUsesTheFirstCompatibleAnchorAndPreservesTheRequestedPathCasing() + { + var first = Target("first", "EXAMPLE.TEST.", ["Lists/Alpha.txt"]); + var second = Target("second", "example.test", ["lists/alpha.TXT"]); + var strategy = Strategy("s"); + var f = new Fixture { Session = Session([strategy], [first, second]) }; + var evidence = Evidence(strategy, Target("source")); + + Assert.True(f.Editor.AddForSiteList(evidence, "LISTS/ALPHA.txt")); + Assert.False(f.Editor.AddForSiteList(evidence, "lists/alpha.TXT")); + + var item = Assert.Single(f.Editor.Items); + Assert.Same(first, item.Target); + Assert.Equal("first", item.Assignment.AnchorTargetId); + Assert.Equal("LISTS/ALPHA.txt", item.Assignment.SiteListPath); + Assert.Equal(BlockCheckManualScopeKind.SiteList, item.Assignment.ScopeKind); + } + + [Theory] + [InlineData(BlockCheckProtocol.Tls12, BlockCheckIpVersion.IPv4, 443, "example.test", true)] + [InlineData(BlockCheckProtocol.Tls13, BlockCheckIpVersion.IPv4, 443, "EXAMPLE.TEST.", true)] + [InlineData(BlockCheckProtocol.Tls12, BlockCheckIpVersion.IPv6, 443, "example.test", false)] + [InlineData(BlockCheckProtocol.Tls12, BlockCheckIpVersion.IPv4, 8443, "example.test", false)] + [InlineData(BlockCheckProtocol.Http, BlockCheckIpVersion.IPv4, 443, "example.test", false)] + [InlineData(BlockCheckProtocol.Quic, BlockCheckIpVersion.IPv4, 443, "example.test", false)] + [InlineData(BlockCheckProtocol.Tls12, BlockCheckIpVersion.IPv4, 443, "other.test", false)] + public void SiteListCompatibilityRetainsHostAndConnectionRules(BlockCheckProtocol protocol, BlockCheckIpVersion ip, int port, string host, bool expected) + { + var target = new BlockCheckTarget { Id = "candidate", Host = host, Protocol = protocol, IpVersion = ip, CustomPort = port, HostListPaths = ["sites.txt"] }; + var f = new Fixture { Session = Session([Strategy("s")], [target]) }; + var evidence = Evidence(Strategy("s"), Target("source")); + Assert.Equal(expected, f.Editor.CanAddForSiteList(evidence)); + Assert.Equal(expected ? new[] { "sites.txt" } : [], f.Editor.GetSiteListPaths(evidence)); + } + + [Fact] + public void IgnoredAndNonSiteListTargetsDoNotOfferPathsOrAnchors() + { + var ignored = Target("ignored", paths: ["ignored.txt"]); + var plain = Target("plain"); + var f = new Fixture { Session = Session([Strategy("s")], [ignored, plain], ignored: ["ignored"]) }; + var evidence = Evidence(Strategy("s"), Target("source")); + Assert.False(f.Editor.CanAddForSiteList(evidence)); + Assert.Empty(f.Editor.GetSiteListPaths(evidence)); + Assert.False(f.Editor.AddForSiteList(evidence, "ignored.txt")); + } + + [Theory] + [InlineData("en-US", "ä.txt", "z.txt")] + [InlineData("sv-SE", "z.txt", "ä.txt")] + public void SiteListPathsFilterBlankDeduplicateAndSortUsingTheCurrentCulture(string culture, string first, string second) + { + CultureInfo previous = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); + var f = new Fixture { Session = Session([Strategy("s")], [Target("t", paths: ["z.txt", "ä.txt", "Z.TXT", "", " "])]) }; + Assert.Equal(new[] { first, second }, f.Editor.GetSiteListPaths(Evidence(Strategy("s"), Target("source")))); + } + finally { CultureInfo.CurrentCulture = previous; } + } + + [Fact] + public void RemoveUnknownAndInvalidMovesDoNotClearAcknowledgementsOrRebuild() + { + var f = new Fixture(); + var unknown = Assignment(Strategy("s"), Target("t")); + f.Editor.RemoveAssignment(unknown); + Assert.False(f.Editor.MoveAssignment(unknown, 1)); + f.Editor.Items.Add(unknown); + Assert.False(f.Editor.MoveAssignment(unknown, -1)); + Assert.False(f.Editor.MoveAssignment(unknown, 1)); + Assert.Empty(f.Trace); + } + + [Fact] + public void MoveAndRemovePublishCollectionChangesBeforeRebuilding() + { + var f = new Fixture(); + var first = Assignment(Strategy("first"), Target("t")); + var second = Assignment(Strategy("second"), Target("t")); + f.Editor.Items.Add(first); + f.Editor.Items.Add(second); + f.Editor.Items.CollectionChanged += (_, args) => f.Trace.Add("collection:" + args.Action); + + Assert.True(f.Editor.MoveAssignment(first, 1)); + f.Editor.RemoveAssignment(first); + + Assert.Same(second, Assert.Single(f.Editor.Items)); + Assert.Equal(["ack", "collection:Move", "rebuild:True", "ack", "collection:Remove", "rebuild:True"], f.Trace); + } + + [Fact] + public void AZeroMoveAndClearingAnEmptyListStillPublishAndRebuild() + { + var f = new Fixture(); + var item = Assignment(Strategy("s"), Target("t")); + f.Editor.Items.Add(item); + f.Editor.Items.CollectionChanged += (_, args) => f.Trace.Add("collection:" + args.Action); + + Assert.True(f.Editor.MoveAssignment(item, 0)); + f.Editor.ClearManualAssignments(); + f.Editor.ClearManualAssignments(); + + Assert.Equal(["ack", "collection:Move", "rebuild:True", "ack", "collection:Reset", "rebuild:True", "ack", "collection:Reset", "rebuild:True"], f.Trace); + } + + [Fact] + public void FormatterFailureOccursAfterAcknowledgementButBeforeCollectionMutation() + { + var failure = new InvalidOperationException("fixture format failure"); + var f = new Fixture { Session = Session([Strategy("s")], [Target("t")]), FormatFailure = failure }; + Assert.Same(failure, Assert.Throws(() => f.Editor.AddForSite(Evidence(Strategy("s"), Target("t"))))); + Assert.Empty(f.Editor.Items); + Assert.Equal(["ack", "format:s"], f.Trace); + } + + [Fact] + public void CollectionSubscriberFailureRetainsTheAddedItemAndDoesNotRebuild() + { + var f = new Fixture { Session = Session([Strategy("s")], [Target("t")]) }; + var failure = new InvalidOperationException("fixture collection failure"); + f.Editor.Items.CollectionChanged += (_, _) => throw failure; + + Assert.Same(failure, Assert.Throws(() => f.Editor.AddForSite(Evidence(Strategy("s"), Target("t"))))); + + Assert.Single(f.Editor.Items); + Assert.Equal(["ack", "format:s"], f.Trace); + } + + [Fact] + public void IndexRefreshUsesTheLiveCollectionAfterAnOrderSubscriberRemovesAnItem() + { + var f = new Fixture(); + var first = Assignment(Strategy("s1"), Target("t")); + var second = Assignment(Strategy("s2"), Target("t")); + f.Editor.Items.Add(first); + f.Editor.Items.Add(second); + first.PropertyChanged += (_, _) => f.Editor.Items.Remove(second); + + f.Editor.RefreshAssignmentIndexes(); + + Assert.Same(first, Assert.Single(f.Editor.Items)); + Assert.Equal(1, first.Order); + Assert.Equal(0, second.Order); + } + + [Fact] + public void SelectionRefreshReadsAssignmentsForEachRowButKeepsTheOriginalEvidenceEnumeration() + { + var f = new Fixture(); + var first = Evidence(Strategy("s1"), Target("t1", "one.test")); + var second = Evidence(Strategy("s2"), Target("t2", "two.test")); + var replacement = Evidence(Strategy("s1"), Target("other", "one.test")); + f.Evidence = [first, second]; + f.Editor.Items.Add(Assignment(first.Evidence.Strategy, first.Evidence.Target)); + bool changed = false; + first.PropertyChanged += (_, args) => + { + if (changed || args.PropertyName != nameof(first.IsSelectedForPreset)) return; + changed = true; + f.Evidence = [replacement]; + f.Editor.Items.Add(Assignment(second.Evidence.Strategy, second.Evidence.Target)); + }; + + f.Editor.RefreshEvidenceSelections(); + + Assert.True(first.IsSelectedForPreset); + Assert.True(second.IsSelectedForPreset); + Assert.False(replacement.IsSelectedForPreset); + Assert.False(first.IsAutomaticSelection); + } + + [Fact] + public void AutomaticSeedPreservesScopePrimaryFallbackOrderAndSkipsMissingOrDuplicateAssignments() + { + var f = new Fixture(); + var s1 = Strategy("s1"); + var s2 = Strategy("s2"); + var list = Target("list", "list.test", ["a.txt", "b.txt"]); + var site = Target("site", "site.test"); + BlockCheckReportProfile listProfile = Profile(["list", "missing-target"], ["a.txt", "b.txt"], "s1", ["s2", "s1", "missing-strategy"]); + BlockCheckReportProfile siteProfile = Profile(["site"], [], "s1", []); + var supplied = Session([s1, s2], [list, site], [listProfile, siteProfile, siteProfile]); + f.Session = supplied; + f.Evidence = [Evidence(s1, list), Evidence(s2, list), Evidence(s1, site)]; + f.Draft.LoadAutomatic("--previous", []); + f.OnRebuild = update => + { + Assert.False(update); + Assert.Equal("--previous", f.Draft.EffectiveArguments); + Assert.Equal(5, f.Editor.Items.Count); + }; + + f.Editor.SeedAutomaticAssignments(supplied); + + Assert.Equal(new[] { "s1:a.txt", "s2:a.txt", "s1:b.txt", "s2:b.txt", "s1:" }, + f.Editor.Items.Select(item => item.Assignment.StrategyId + ":" + item.Assignment.SiteListPath)); + Assert.Equal(new[] { 1, 2, 3, 4, 5 }, f.Editor.Items.Select(item => item.Order)); + Assert.Equal("--automatic", f.Draft.EffectiveArguments); + Assert.True(f.Draft.IsAutomatic); + Assert.All(f.Evidence, evidence => { Assert.True(evidence.IsSelectedForPreset); Assert.True(evidence.IsAutomaticSelection); }); + Assert.Equal("ack", f.Trace[0]); + Assert.Equal("rebuild:False", f.Trace[^1]); + } + + [Fact] + public void SeedUsesTheSuppliedSessionEvenIfClearingTheCollectionChangesTheCurrentSession() + { + var f = new Fixture(); + var strategy = Strategy("s"); + var target = Target("t"); + var supplied = Session([strategy], [target], [Profile(["t"], [], "s", [])]); + var other = Session([], []); + f.Session = supplied; + f.Editor.Items.CollectionChanged += (_, args) => { if (args.Action == NotifyCollectionChangedAction.Reset) f.Session = other; }; + + f.Editor.SeedAutomaticAssignments(supplied); + + Assert.Same(strategy, Assert.Single(f.Editor.Items).Strategy); + Assert.Same(other, f.Session); + Assert.Equal("--automatic", f.Draft.EffectiveArguments); + } + + [Fact] + public void DuplicateCatalogIdsThrowAfterAcknowledgementAndCollectionClear() + { + var f = new Fixture(); + f.Editor.Items.Add(Assignment(Strategy("old"), Target("old"))); + var supplied = Session([Strategy("s"), Strategy("S")], []); + f.Editor.Items.CollectionChanged += (_, args) => f.Trace.Add("collection:" + args.Action); + + Assert.Throws(() => f.Editor.SeedAutomaticAssignments(supplied)); + + Assert.Empty(f.Editor.Items); + Assert.Equal(["ack", "collection:Reset"], f.Trace); + } + + [Fact] + public void ClearingAutomaticKeysIsQuietUntilSelectionsAreRefreshed() + { + var f = new Fixture(); + var strategy = Strategy("s"); + var target = Target("t"); + f.Session = Session([strategy], [target], [Profile(["t"], [], "s", [])]); + var row = Evidence(strategy, target); + f.Evidence = [row]; + f.Editor.SeedAutomaticAssignments(f.Session); + f.Trace.Clear(); + + f.Editor.ClearAutomaticKeys(); + Assert.True(row.IsAutomaticSelection); + Assert.Empty(f.Trace); + f.Editor.RefreshEvidenceSelections(); + + Assert.True(row.IsSelectedForPreset); + Assert.False(row.IsAutomaticSelection); + } + + [Fact] + public void EqualSiteListFilenamesUseTheFullPathAsTheSecondarySortKey() + { + var f = new Fixture { Session = Session([Strategy("s")], [Target("t", paths: ["z/alpha.txt", "a/alpha.txt"])]) }; + Assert.Equal(new[] { "a/alpha.txt", "z/alpha.txt" }, + f.Editor.GetSiteListPaths(Evidence(Strategy("s"), Target("source")))); + } + + [Fact] + public void RebuildFailureLeavesTheAlreadyPublishedAssignmentInTheDraft() + { + var failure = new InvalidOperationException("fixture rebuild failure"); + var f = new Fixture { Session = Session([Strategy("s")], [Target("t")]), OnRebuild = _ => throw failure }; + + Assert.Same(failure, Assert.Throws(() => f.Editor.AddForSite(Evidence(Strategy("s"), Target("t"))))); + + Assert.Single(f.Editor.Items); + Assert.Equal(["ack", "format:s", "rebuild:True"], f.Trace); + } + + [Fact] + public void SeedSubscriberFailureLeavesAPublishedItemWithoutItsAutomaticKeyOrDraftReload() + { + var f = new Fixture(); + var strategy = Strategy("s"); + var target = Target("t"); + f.Session = Session([strategy], [target], [Profile(["t"], [], "s", [])]); + var row = Evidence(strategy, target); + f.Evidence = [row]; + f.Draft.LoadAutomatic("--previous", []); + var failure = new InvalidOperationException("fixture seed subscriber failure"); + f.Editor.Items.CollectionChanged += (_, args) => { if (args.Action == NotifyCollectionChangedAction.Add) throw failure; }; + + Assert.Same(failure, Assert.Throws(() => f.Editor.SeedAutomaticAssignments(f.Session))); + f.Editor.RefreshEvidenceSelections(); + + Assert.Single(f.Editor.Items); + Assert.True(row.IsSelectedForPreset); + Assert.False(row.IsAutomaticSelection); + Assert.Equal("--previous", f.Draft.EffectiveArguments); + Assert.Equal(["ack", "format:s"], f.Trace); + } + + [Fact] + public void LegacySeedRecordEqualityIsCaseSensitiveWhileAutomaticKeysRemainInsensitive() + { + var f = new Fixture(); + var strategy = Strategy("s"); + var target = Target("t"); + f.Session = Session([strategy], [target], [Profile(["t"], [], "s", ["S"])]); + var row = Evidence(strategy, target); + f.Evidence = [row]; + + f.Editor.SeedAutomaticAssignments(f.Session); + + Assert.Equal(new[] { "s", "S" }, f.Editor.Items.Select(item => item.Assignment.StrategyId)); + f.Editor.Items.Clear(); + f.Editor.Items.Add(Assignment(Strategy("S"), Target("T"))); + f.Editor.RefreshEvidenceSelections(); + Assert.True(row.IsSelectedForPreset); + Assert.True(row.IsAutomaticSelection); + } + + [Fact] + public void AutomaticScopesRetainTheFirstTargetFallbackAndNormalizedHostGrouping() + { + var first = Target("first", "example.test"); + var second = new BlockCheckTarget { Id = "second", Host = "EXAMPLE.TEST.", Protocol = BlockCheckProtocol.Tls13, IpVersion = BlockCheckIpVersion.IPv6 }; + var f = new Fixture(); + var supplied = Session([Strategy("s")], [first, second], + [Profile(["first", "second"], ["missing-list.txt"], "s", []), Profile(["first", "second"], [], "s", [])]); + f.Session = supplied; + + f.Editor.SeedAutomaticAssignments(supplied); + + Assert.Equal(2, f.Editor.Items.Count); + Assert.All(f.Editor.Items, item => Assert.Same(first, item.Target)); + Assert.Equal(BlockCheckManualScopeKind.SiteList, f.Editor.Items[0].Assignment.ScopeKind); + Assert.Equal("missing-list.txt", f.Editor.Items[0].Assignment.SiteListPath); + Assert.Equal(BlockCheckManualScopeKind.Site, f.Editor.Items[1].Assignment.ScopeKind); + } + + private static StrategyDefinition Strategy(string id) => new() { Id = id, DisplayName = "Strategy " + id }; + private static BlockCheckTarget Target(string id, string host = "example.test", string[]? paths = null) => new() + { + Id = id, Host = host, Protocol = BlockCheckProtocol.Tls12, IpVersion = BlockCheckIpVersion.IPv4, HostListPaths = paths ?? [], + }; + private static BlockCheck2StrategyEvidenceItem Evidence(StrategyDefinition strategy, BlockCheckTarget target) => new(new() { Strategy = strategy, Target = target }); + private static BlockCheck2ManualAssignmentItem Assignment(StrategyDefinition strategy, BlockCheckTarget target) => + new(new(strategy.Id, target.Id, BlockCheckManualScopeKind.Site), strategy, target, "fixture"); + private static BlockCheckReportProfile Profile(string[] targets, string[] paths, string primary, string[] fallbacks) => + new("fixture", BlockCheckIpVersion.IPv4, BlockCheckTransport.Tcp, 443, "tls", [], paths, primary, fallbacks, targets); + private static BlockCheckResultSession Session(StrategyDefinition[] strategies, BlockCheckTarget[] targets, + BlockCheckReportProfile[]? profiles = null, string[]? ignored = null) => new() + { + Catalog = new() { Strategies = strategies.ToList() }, Targets = targets, + Report = new() { PresetArguments = "--automatic", Profiles = profiles ?? [] }, + RunResult = new() { Scan = new() { IgnoredTargetIds = new HashSet(ignored ?? [], StringComparer.Ordinal) } }, + }; + + private sealed class Fixture + { + public BlockCheck2PresetDraft Draft { get; } = new(); + public BlockCheckResultSession? Session; + public IReadOnlyList Evidence = []; + public List Trace { get; } = []; + public Action? OnRebuild; + public Exception? FormatFailure; + public BlockCheck2ManualAssignmentEditor Editor { get; } + + public Fixture() + { + Editor = new(Draft, () => Session, () => Evidence, + () => Trace.Add("ack"), + update => { Trace.Add("rebuild:" + update); OnRebuild?.Invoke(update); }, + strategy => + { + Trace.Add("format:" + strategy.Id); + if (FormatFailure != null) throw FormatFailure; + return "formatted:" + strategy.Id; + }); + } + } +} diff --git a/CDPIUI.Tests/Presentation/BlockCheck2ManualPresetStateTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2ManualPresetStateTests.cs new file mode 100644 index 00000000..36ba7220 --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2ManualPresetStateTests.cs @@ -0,0 +1,363 @@ +using System.Globalization; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.ViewModels; + +namespace CDPIUI.Tests.Presentation; + +public sealed class BlockCheck2ManualPresetStateTests +{ + [Fact] + public void ConstructionAndClearResultDoNotTouchTheHostDraftOrEvidence() + { + var f = new Fixture(); + Assert.Equal("", f.State.Arguments); + Assert.Empty(f.Trace); + f.Ready(); f.State.Rebuild(false); + f.Trace.Clear(); + f.State.ClearResult(); + Assert.Equal("", f.State.Arguments); + Assert.Equal("--automatic", f.Draft.EffectiveArguments); + Assert.Single(f.Draft.Assignments); + Assert.Empty(f.Trace); + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void EmptyBranchKeepsItsDistinctIndexesBeforeDraftOrder(bool noSession, bool update) + { + var f = new Fixture(); + f.Ready(); f.State.Rebuild(false); + if (noSession) f.Host.Value = null; else f.Draft.Assignments.Clear(); + f.Trace.Clear(); + f.State.Rebuild(update); + Assert.Equal(update ? new[] { "clear", "indexes", "draft:", "selections", "notify" } : new[] { "clear", "indexes", "selections", "notify" }, f.Trace); + Assert.Equal("", f.State.Arguments); + Assert.Equal(update ? "" : "--automatic", f.Draft.EffectiveArguments); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void PopulatedBranchAssignsResultBeforeIssuesAndAppliesDraftBeforeIndexes(bool update) + { + var f = new Fixture(); f.Ready(); + f.Operations.Result = Result(" --manual ", [Issue("first", "s")]); + f.Host.AfterGroup = _ => Assert.Equal(" --manual ", f.State.Arguments); + f.State.Rebuild(update); + Assert.Equal(update ? new[] { "clear", "build", "group:first:1", "draft:--manual", "indexes", "selections", "notify" } : new[] { "clear", "build", "group:first:1", "indexes", "selections", "notify" }, f.Trace); + Assert.Equal(" --manual ", f.State.Arguments); + Assert.Equal(update ? "--manual" : "--automatic", f.Draft.StructuredArguments); + Assert.Single(f.Draft.Assignments); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void OnlyUpdatingTheDraftDiscardsItsExistingExpertEdit(bool update) + { + var f = new Fixture(); f.Ready(); + f.Draft.BeginExpertEditing(); f.Draft.SetExpertArguments("--expert"); f.Trace.Clear(); + f.State.Rebuild(update); + Assert.Equal(!update, f.Draft.IsExpertEditingEnabled); + Assert.Equal(update ? "--manual" : "--expert", f.Draft.EffectiveArguments); + Assert.Equal(update, f.Draft.IsModifiedAutomatic); + } + + [Fact] + public void ClearingIssuesCanReplaceTheSessionBeforeItsFirstObservation() + { + var f = new Fixture(); f.Draft.Assignments.Add(Row()); + var current = Session(); + f.Host.Clear = () => f.Host.Value = current; + f.State.Rebuild(false); + Assert.Same(current.Catalog, Assert.Single(f.Operations.Calls).Catalog); + } + + [Fact] + public void ManualProbesReplaceOnlyMatchingStrategyCaseInsensitiveAndTargetOrdinalPairs() + { + var f = new Fixture(); + var replaced = Probe("STRATEGY", "t"); + var otherTargetCase = Probe("strategy", "T"); + var otherStrategy = Probe("other", "t"); + var manual = Probe("strategy", "t"); + f.Ready(Session(probes: [replaced, otherTargetCase, otherStrategy])); + f.ManualTests.Add(manual); + f.State.Rebuild(false); + Assert.Equal(new[] { otherTargetCase, otherStrategy, manual }, Assert.Single(f.Operations.Calls).Evidence); + Assert.Same(manual, Assert.Single(f.ManualTests)); + } + + [Fact] + public void BuildArgumentsRetainDeferredLiveCollectionsAndTheOriginalMixedSessionTiming() + { + var f = new Fixture(); + var one = Target("one"); var two = Target("two"); + var original = Probe("s", "one"); var later = Probe("S", "one"); + var old = Session([one, two], [original], ["one"], 2, 0.9); + f.Ready(old); + var replacementRow = Row("next"); + f.Operations.BeforeReturn = call => + { + f.Host.Value = Session(ignored: ["two"], minimumAttempts: 9, minimumRate: 0.1); + f.ManualTests.Add(later); + f.Draft.Assignments.Clear(); f.Draft.Assignments.Add(replacementRow); + Assert.Same(old.Catalog, call.Catalog); + Assert.Equal(new[] { one }, call.Targets); + Assert.Same(replacementRow.Assignment, Assert.Single(call.Assignments)); + Assert.Same(later, Assert.Single(call.Evidence)); + Assert.Equal(2, call.Options.MinimumAttempts); + Assert.Equal(0.9, call.Options.MinimumSuccessRate); + }; + f.State.Rebuild(false); + Assert.Equal(new[] { "clear", "build", "indexes", "selections", "notify" }, f.Trace); + } + + [Theory] + [InlineData(-5, 1, -0.5)] + [InlineData(0, 1, 0.8)] + [InlineData(7, 7, 1.5)] + public void OptionsClampOnlyAttemptsAndAllocateFreshDefaults(int source, int expected, double rate) + { + var session = Session(minimumAttempts: source, minimumRate: rate); + var first = BlockCheck2ManualPresetState.OptionsFor(session); + var second = BlockCheck2ManualPresetState.OptionsFor(session); + Assert.NotSame(first, second); + Assert.NotSame(first.WriterOptions, second.WriterOptions); + Assert.Equal(expected, first.MinimumAttempts); + Assert.Equal(rate, first.MinimumSuccessRate); + } + + [Fact] + public void IssueGroupingUsesExactSeverityCodeAndMessageWithFirstOccurrenceOrder() + { + var f = new Fixture(); f.Ready(); + f.Operations.Result = Result("--manual", [ + Issue("A", "s", "same"), Issue("a", "unknown", "same"), Issue("A", "s", "same"), + Issue("A", "s", "Same"), new(BlockCheckIssueSeverity.Warning, "A", "same", "s"), + ]); + f.State.Rebuild(false); + Assert.Equal(new[] { "A", "a", "A", "A" }, f.Host.Groups.Select(group => group.Code)); + Assert.Equal(new[] { 2, 1, 1, 1 }, f.Host.Groups.Select(group => group.Count)); + Assert.Equal(new[] { "same", "same", "Same", "same" }, f.Host.Groups.Select(group => group.Message)); + Assert.Equal(new[] { "Strategy s (s)", "Strategy s (s)" }, f.Host.Groups[0].Subjects); + Assert.Equal(BlockCheckIssueSeverity.Warning, f.Host.Groups[3].Severity); + } + + [Theory] + [InlineData(null, "")] + [InlineData("", "")] + [InlineData(" ", "")] + [InlineData("S", "Strategy s (S)")] + [InlineData("unknown", "unknown")] + [InlineData("/unknown/", "/unknown/")] + [InlineData("s/unknown/second", "Strategy s (s) / unknown / Strategy second (second)")] + public void SubjectsRetainNullCaseSlashAndFallbackRules(string? subject, string expected) + { + var f = new Fixture(); f.Ready(); f.Draft.Assignments.Add(Row("second")); + f.Operations.Result = Result("--manual", [Issue("issue", subject)]); + f.State.Rebuild(false); + Assert.Equal(expected, Assert.Single(Assert.Single(f.Host.Groups).Subjects)); + } + + [Fact] + public void ScopeMatchWinsBeforeAnAssignmentWhoseStrategyIdMatchesTheSameText() + { + const string scope = "IPV4|TCP|443|TLS|SITE:EXAMPLE.TEST"; + var f = new Fixture(); f.Ready(); + var first = f.Draft.Assignments.Single(); + f.Draft.Assignments.Add(Row(scope, "different.test")); + f.Operations.Result = Result("--manual", [Issue("scope", scope)]); + f.State.Rebuild(false); + Assert.Equal(first.Scope + " · " + first.ConnectionDetails, Assert.Single(Assert.Single(f.Host.Groups).Subjects)); + } + + [Theory] + [InlineData("en-US", "ı (I)")] + [InlineData("tr-TR", "I")] + public void StrategyDescriptionsKeepTheCurrentCultureComparison(string culture, string expected) + { + var old = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); + var f = new Fixture(); f.Ready(); f.Draft.Assignments.Clear(); + f.Draft.Assignments.Add(Row("I", display: "ı")); + f.Operations.Result = Result("--manual", [Issue("culture", "I")]); + f.State.Rebuild(false); + Assert.Equal(expected, Assert.Single(Assert.Single(f.Host.Groups).Subjects)); + } + finally { CultureInfo.CurrentCulture = old; } + } + + [Fact] + public void DeferredSubjectDescriptionsObserveAssignmentsChangedByTheHost() + { + var f = new Fixture(); f.Ready(); + f.Operations.Result = Result("--manual", [Issue("late", "s")]); + f.Host.BeforeSubjects = () => { f.Draft.Assignments.Clear(); f.Draft.Assignments.Add(Row(display: "Late")); }; + f.State.Rebuild(false); + Assert.Equal("Late (s)", Assert.Single(Assert.Single(f.Host.Groups).Subjects)); + } + + [Fact] + public void AReentrantIssueCallbackMakesTheOuterApplyUseTheCurrentResult() + { + var f = new Fixture(); f.Ready(); + var first = Result("--first", [Issue("first", "s"), Issue("tail", "s")]); + var second = Result("--second", [Issue("nested", "s")]); + f.Operations.Result = first; + bool entered = false; + f.Host.AfterGroup = _ => + { + if (entered) return; + entered = true; f.Operations.Result = second; f.State.Rebuild(false); + }; + f.State.Rebuild(true); + Assert.Equal("--second", f.State.Arguments); + Assert.Equal("--second", f.Draft.EffectiveArguments); + Assert.Equal(new[] { "nested", "tail" }, f.Host.Groups.Select(group => group.Code)); + Assert.Equal(2, f.Operations.Calls.Count); + } + + [Theory] + [InlineData("clear")] + [InlineData("build")] + [InlineData("group")] + [InlineData("indexes")] + [InlineData("selections")] + [InlineData("notify")] + public void FailuresEscapeSynchronouslyWithOriginalPartialMutations(string point) + { + var f = new Fixture(); f.Ready(); f.State.Rebuild(false); + f.Operations.Result = Result("--new", [Issue("new", "s")]); f.Trace.Clear(); + var failure = new IOException(point); + if (point == "clear") f.Host.Clear = () => throw failure; + if (point == "build") f.Operations.BeforeReturn = _ => throw failure; + if (point == "group") f.Host.AfterGroup = _ => throw failure; + if (point == "indexes") f.Host.Indexes = () => throw failure; + if (point == "selections") f.Host.Selections = () => throw failure; + if (point == "notify") f.Host.Notify = () => throw failure; + Assert.Same(failure, Assert.Throws(() => f.State.Rebuild(true))); + Assert.Equal(point is "clear" or "build" ? "--manual" : "--new", f.State.Arguments); + Assert.Equal(point is "indexes" or "selections" or "notify" ? "--new" : "--automatic", f.Draft.EffectiveArguments); + if (point is "clear" or "build" or "group") Assert.DoesNotContain("indexes", f.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void DraftFailureKeepsTheDifferentEmptyAndPopulatedIndexesOrder(bool populated) + { + var f = new Fixture(); if (populated) f.Ready(); + var failure = new IOException("draft collection observer"); + f.Draft.Groups.CollectionChanged += (_, _) => throw failure; + Assert.Same(failure, Assert.Throws(() => f.State.Rebuild(true))); + Assert.Equal(!populated, f.Trace.Contains("indexes")); + Assert.DoesNotContain("selections", f.Trace); + Assert.Equal(populated ? "--manual" : "", f.Draft.StructuredArguments); + Assert.Equal(populated ? "--manual" : "", f.State.Arguments); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void NonemptyProfilesReachTheSameDraftGroupsOnlyWhenUpdating(bool update) + { + var f = new Fixture(); f.Ready(); + f.Draft.ApplyStructuredChange("--before", [new() { Name = "before", Primary = new() { Id = "old" } }]); + var oldGroup = Assert.Single(f.Draft.Groups); + var next = new Zapret2ProfilePlan { Name = "next", Primary = new() { Id = "primary" }, Filter = new() { Domains = ["example.test"] } }; + next.Fallbacks.Add(new() { Id = "fallback" }); + f.Operations.Result = Result("--manual", profiles: [next]); + f.State.Rebuild(update); + var group = Assert.Single(f.Draft.Groups); + if (update) + { + Assert.NotSame(oldGroup, group); + Assert.Equal("next", group.Name); + Assert.Equal("primary -> fallback", group.Strategies); + Assert.Equal("example.test", group.Scope); + } + else Assert.Same(oldGroup, group); + Assert.Equal(update ? "--manual" : "--before", f.Draft.EffectiveArguments); + } + + [Fact] + public void InvalidSiteListScopeRetainsItsPathFailureBeforeStrategyLookupButBlankSubjectsStayLazy() + { + var f = new Fixture(); f.Ready(); f.Draft.Assignments.Clear(); + f.Draft.Assignments.Add(new(new("s", "t", BlockCheckManualScopeKind.SiteList, ""), new() { Id = "s" }, Target("t"), "fixture")); + f.Operations.Result = Result("--manual", [Issue("blank", null)]); + f.State.Rebuild(false); + Assert.Equal("", Assert.Single(Assert.Single(f.Host.Groups).Subjects)); + f.Operations.Result = Result("--manual", [Issue("lookup", "s")]); f.Trace.Clear(); + Assert.ThrowsAny(() => f.State.Rebuild(false)); + Assert.Equal("--manual", f.State.Arguments); + Assert.Empty(f.Host.Groups); + Assert.DoesNotContain("indexes", f.Trace); + } + + private static ProbeResult Probe(string strategy, string target) => new() { StrategyId = strategy, TargetId = target }; + private static BlockCheckTarget Target(string id, string host = "example.test") => new() { Id = id, Host = host, Protocol = BlockCheckProtocol.Tls12, IpVersion = BlockCheckIpVersion.IPv4 }; + private static BlockCheck2ManualAssignmentItem Row(string id = "s", string host = "example.test", string? display = null) => + new(new(id, "t", BlockCheckManualScopeKind.Site), new() { Id = id, DisplayName = display ?? "Strategy " + id }, Target("t", host), "fixture"); + private static BlockCheckIssue Issue(string code, string? subject, string message = "fixture") => new(BlockCheckIssueSeverity.Error, code, message, subject); + private static BlockCheckManualPresetResult Result(string command, BlockCheckIssue[]? issues = null, Zapret2ProfilePlan[]? profiles = null) => new() { Configuration = new() { CommandLine = command }, Issues = issues ?? [], Profiles = profiles ?? [] }; + private static BlockCheckResultSession Session(BlockCheckTarget[]? targets = null, ProbeResult[]? probes = null, string[]? ignored = null, int minimumAttempts = 3, double minimumRate = 0.8) => new() + { + Targets = targets ?? [Target("t")], + RunResult = new() { Scan = new() { ProbeResults = probes ?? [], IgnoredTargetIds = new HashSet(ignored ?? [], StringComparer.Ordinal) } }, + RunOptions = new() { Synthesis = new() { MinimumAttempts = minimumAttempts, MinimumSuccessRate = minimumRate } }, + }; + + private sealed class Fixture + { + public List Trace { get; } = []; + public BlockCheck2PresetDraft Draft { get; } = new(); + public List ManualTests { get; } = []; + public Host Host { get; } + public Operations Operations { get; } + public BlockCheck2ManualPresetState State { get; } + public Fixture() + { + Draft.LoadAutomatic("--automatic", []); + Host = new(Trace); Operations = new(Trace); + State = new(Draft, ManualTests, Host, Operations); + Draft.PropertyChanged += (_, args) => { if (args.PropertyName == nameof(Draft.EffectiveArguments)) Trace.Add("draft:" + Draft.EffectiveArguments); }; + } + public void Ready(BlockCheckResultSession? session = null) { Host.Value = session ?? Session(); Draft.Assignments.Add(Row()); } + } + private sealed record BuildCall(StrategyCatalog Catalog, IEnumerable Targets, IEnumerable Assignments, IEnumerable Evidence, BlockCheckManualPresetOptions Options); + private sealed class Operations(List trace) : IBlockCheck2ManualPresetOperations + { + public BlockCheckManualPresetResult Result = BlockCheck2ManualPresetStateTests.Result("--manual"); + public List Calls { get; } = []; + public Action? BeforeReturn; + public BlockCheckManualPresetResult Build(StrategyCatalog catalog, IEnumerable targets, IEnumerable assignments, IEnumerable evidence, BlockCheckManualPresetOptions options) + { + trace.Add("build"); var call = new BuildCall(catalog, targets, assignments, evidence, options); Calls.Add(call); BeforeReturn?.Invoke(call); return Result; + } + } + private sealed record Group(BlockCheckIssueSeverity Severity, string Code, string Message, int Count, string[] Subjects); + private sealed class Host(List trace) : IBlockCheck2ManualPresetHost + { + public BlockCheckResultSession? Value; + public BlockCheckResultSession? Session => Value; + public List Groups { get; } = []; + public Action? Clear, BeforeSubjects, Indexes, Selections, Notify; + public Action? AfterGroup; + public void ClearIssues() { trace.Add("clear"); Groups.Clear(); Clear?.Invoke(); } + public void AddIssueGroup(BlockCheckIssueSeverity severity, string code, string message, int count, IEnumerable subjects) + { + trace.Add($"group:{code}:{count}"); BeforeSubjects?.Invoke(); var group = new Group(severity, code, message, count, subjects.ToArray()); Groups.Add(group); AfterGroup?.Invoke(group); + } + public void RefreshAssignmentIndexes() { trace.Add("indexes"); Indexes?.Invoke(); } + public void RefreshEvidenceSelections() { trace.Add("selections"); Selections?.Invoke(); } + public void NotifyManualState() { trace.Add("notify"); Notify?.Invoke(); } + } +} diff --git a/CDPIUI.Tests/Presentation/BlockCheck2ManualStrategyTestControllerTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2ManualStrategyTestControllerTests.cs new file mode 100644 index 00000000..9edb81da --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2ManualStrategyTestControllerTests.cs @@ -0,0 +1,433 @@ +using System.Collections.Concurrent; +using CDPIUI.AddOns.BlockCheck2.Execution; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.Shared.Models; +using CDPIUI.ViewModels; + +namespace CDPIUI.Tests.Presentation; + +public sealed class BlockCheck2ManualStrategyTestControllerTests +{ + [Fact] + public void ConstructorOnlyStoresDependencies() + { + var f = new Fixture(); + Assert.Equal(0, f.SessionReads); + Assert.Empty(f.Operations.Arguments); + Assert.Empty(f.Operations.Tests); + Assert.Empty(f.Rebuilds); + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public async Task MissingSessionReturnsFreshIssueBeforeReadingItemOrCancellation(bool nullItem, bool canceled) + { + var f = new Fixture { Session = null }; + using var cts = new CancellationTokenSource(); + if (canceled) cts.Cancel(); + var item = nullItem ? null! : Item(); + var first = await f.Controller.TestStrategyAsync(item, cts.Token); + var second = await f.Controller.TestStrategyAsync(item, cts.Token); + Assert.NotSame(first, second); + Assert.NotSame(first.Issues, second.Issues); + var issue = Assert.Single(first.Issues); + Assert.Equal(BlockCheckIssueSeverity.Error, issue.Severity); + Assert.Equal("MANUAL_SESSION_UNAVAILABLE", issue.Code); + Assert.Equal("The original BlockCheck session is unavailable; this report cannot launch a live strategy test.", issue.Message); + Assert.Null(first.ProbeResult); + Assert.False(first.Success); + Assert.Empty(f.Operations.Tests); + Assert.Empty(f.ManualTests); + Assert.Empty(f.Rebuilds); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void SyncArgumentsReadsItemBeforeSessionAndDoesNotAddANoSessionGuard(bool nullItem) + { + var f = new Fixture { Session = null }; + Assert.Throws(() => f.Controller.GetFullStrategyArguments(nullItem ? null! : Item())); + Assert.Equal(nullItem ? 0 : 1, f.SessionReads); + Assert.Empty(f.Operations.Arguments); + } + + [Theory] + [InlineData(-5, 1)] + [InlineData(0, 1)] + [InlineData(1, 1)] + [InlineData(7, 7)] + public void ArgumentsReturnsSameBackendResultWithFreshClampedOptions(int attempts, int expected) + { + var f = new Fixture { Session = Session(attempts) }; + var item = Item(); + var result = OperationResultModel.SuccessResult("--fixture"); + f.Operations.GetArguments = _ => result; + Assert.Same(result, f.Controller.GetFullStrategyArguments(item)); + Assert.Same(result, f.Controller.GetFullStrategyArguments(item)); + var one = f.Operations.Arguments[0]; var two = f.Operations.Arguments[1]; + Assert.Same(item.Evidence.Strategy, one.Strategy); + Assert.Same(item.Evidence.Target, one.Target); + Assert.Equal(expected, one.Options.Attempts); + Assert.NotSame(one.Options, two.Options); + Assert.NotSame(one.Options.WriterOptions, two.Options.WriterOptions); + Assert.Empty(f.ManualTests); + Assert.Empty(f.Rebuilds); + } + + [Fact] + public void ArgumentsBackendFailureEscapesSynchronously() + { + var f = new Fixture(); var failure = new IOException("arguments"); + f.Operations.GetArguments = _ => throw failure; + Assert.Same(failure, Assert.Throws(() => f.Controller.GetFullStrategyArguments(Item()))); + Assert.Single(f.Operations.Arguments); + Assert.Empty(f.Rebuilds); + } + + [Theory] + [InlineData(-5, 1)] + [InlineData(0, 1)] + [InlineData(1, 1)] + [InlineData(7, 7)] + public async Task TestForwardsOriginalIdentitiesTimeoutsAndTokenBeforeAwait(int attempts, int expected) + { + var f = new Fixture { Session = Session(attempts) }; var item = Item(); + using var cts = new CancellationTokenSource(); + var pending = Pending(); f.Operations.Test = _ => pending.Task; + var task = f.Controller.TestStrategyAsync(item, cts.Token); + var call = Assert.Single(f.Operations.Tests); + Assert.Same(item.Evidence.Strategy, call.Strategy); + Assert.Same(item.Evidence.Target, call.Target); + Assert.Equal(expected, call.Options.Attempts); + Assert.Equal(TimeSpan.FromMilliseconds(123), call.StrategyOptions.StartupGracePeriod); + Assert.Equal(TimeSpan.FromSeconds(4), call.ProbeOptions.ConnectTimeout); + Assert.Equal(TimeSpan.FromSeconds(9), call.ProbeOptions.RequestTimeout); + Assert.Equal(cts.Token, call.Token); + Assert.False(task.IsCompleted); + Assert.Empty(f.ManualTests); + Assert.Equal(BlockCheckEvidenceStatus.Failed, item.Status); + Assert.Empty(f.Rebuilds); + var result = new BlockCheckManualStrategyTestResult { CommandLine = "no probe" }; + pending.SetResult(result); + Assert.Same(result, await task); + Assert.Empty(f.ManualTests); + Assert.Equal(BlockCheckEvidenceStatus.Failed, item.Status); + Assert.Empty(f.Rebuilds); + } + + [Fact] + public async Task EachTestCreatesFreshOptionObjectsAndReadsTheCurrentSession() + { + var f = new Fixture(); var item = Item(); + await f.Controller.TestStrategyAsync(item); + f.Session = Session(11); + await f.Controller.TestStrategyAsync(item); + var one = f.Operations.Tests[0]; var two = f.Operations.Tests[1]; + Assert.Equal(3, one.Options.Attempts); + Assert.Equal(11, two.Options.Attempts); + Assert.NotSame(one.Options, two.Options); + Assert.NotSame(one.Options.WriterOptions, two.Options.WriterOptions); + Assert.NotSame(one.StrategyOptions, two.StrategyOptions); + Assert.NotSame(one.ProbeOptions, two.ProbeOptions); + } + + [Fact] + public async Task NullItemWithSessionFailsInTaskBeforeBackend() + { + var f = new Fixture(); + var task = f.Controller.TestStrategyAsync(null!); + await Assert.ThrowsAsync(() => task); + Assert.Empty(f.Operations.Tests); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task BackendSyncAndAsyncFaultsPropagateWithoutStateChanges(bool sync) + { + var f = new Fixture(); var item = Item(); var failure = new IOException("backend"); + f.Operations.Test = _ => sync ? throw failure : Task.FromException(failure); + var task = f.Controller.TestStrategyAsync(item); + Assert.Same(failure, await Assert.ThrowsAsync(() => task)); + Assert.Empty(f.ManualTests); + Assert.Empty(f.Rebuilds); + Assert.Equal(BlockCheckEvidenceStatus.Failed, item.Status); + } + + [Fact] + public async Task BackendCancellationRemainsCanceledWithoutApplyingAnything() + { + var f = new Fixture(); var item = Item(); + using var cts = new CancellationTokenSource(); cts.Cancel(); + f.Operations.Test = _ => Task.FromCanceled(cts.Token); + var task = f.Controller.TestStrategyAsync(item, cts.Token); + var exception = await Assert.ThrowsAnyAsync(() => task); + Assert.Equal(cts.Token, exception.CancellationToken); + Assert.True(task.IsCanceled); + Assert.Empty(f.ManualTests); + Assert.Empty(f.Rebuilds); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task CallerCancellationDoesNotOverrideAResultReturnedByBackend(bool beforeCall) + { + var f = new Fixture(); var item = Item(); var pending = Pending(); + using var cts = new CancellationTokenSource(); + if (beforeCall) cts.Cancel(); + f.Operations.Test = _ => pending.Task; + var task = f.Controller.TestStrategyAsync(item, cts.Token); + cts.Cancel(); var result = Result(Probe()); + pending.SetResult(result); + Assert.Same(result, await task); + Assert.Same(result.ProbeResult, Assert.Single(f.ManualTests)); + Assert.Equal(BlockCheckEvidenceStatus.Successful, item.Status); + Assert.Equal(new[] { false }, f.Rebuilds); + } + + [Fact] + public async Task OverlayRemovesAllMatchingPairsOnlyAndAppendsTheExactReturnedProbe() + { + var f = new Fixture(); var item = Item(); + var otherTarget = Probe("strategy", "TARGET"); var otherStrategy = Probe("other", "target"); + f.ManualTests.AddRange([Probe("STRATEGY"), otherTarget, Probe(), otherStrategy, Probe("Strategy")]); + var probe = Probe(); var result = Result(probe); + f.Operations.Test = _ => Task.FromResult(result); + Assert.Same(result, await f.Controller.TestStrategyAsync(item)); + Assert.Equal(new[] { otherTarget, otherStrategy, probe }, f.ManualTests); + Assert.Same(probe, f.ManualTests[2]); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ResultNotificationsPrecedeRebuildAndDraftFlagIsReadAfterObservers(bool becomeManual) + { + var f = new Fixture(); var item = Item(); var probe = Probe(); + if (!becomeManual) f.Draft.ApplyStructuredChange("--manual", []); + var trace = new List(); + item.PropertyChanged += (_, args) => + { + trace.Add(args.PropertyName!); + if (args.PropertyName != nameof(item.Status)) return; + Assert.Same(probe, Assert.Single(f.ManualTests)); + Assert.Equal(BlockCheckEvidenceStatus.Successful, item.Status); + Assert.Equal(1, item.AttemptCount); Assert.Equal(1, item.SuccessCount); + if (becomeManual) f.Draft.ApplyStructuredChange("--manual", []); else f.Draft.LoadAutomatic("--automatic", []); + }; + f.OnRebuild = _ => trace.Add("rebuild"); + f.Operations.Test = _ => Task.FromResult(Result(probe)); + await f.Controller.TestStrategyAsync(item); + Assert.Equal(becomeManual, Assert.Single(f.Rebuilds)); + Assert.Equal(new[] { "Status", "AttemptCount", "SuccessCount", "SuccessRate", "ResponseTimeSortValue", "ResultText", + "HasPartialScopeWarning", "ResponseTimeText", "HttpStatusText", "FailureText", "EvidenceDetails", "rebuild" }, trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ALoadWhilePendingStillAppliesToSameLiveListAndStaleItem(bool clearSession) + { + var f = new Fixture(); var staleItem = Item(); var pending = Pending(); + var old = Probe("old"); f.ManualTests.Add(old); + f.Operations.Test = _ => pending.Task; + var task = f.Controller.TestStrategyAsync(staleItem); + var currentSession = clearSession ? null : Session(12); + f.Session = currentSession; f.ManualTests.Clear(); + var currentProbe = Probe("current"); f.ManualTests.Add(currentProbe); + f.Draft.ApplyStructuredChange("--new draft", []); + f.OnRebuild = update => { Assert.Same(currentSession, f.Session); Assert.True(update); }; + var result = Result(Probe()); + pending.SetResult(result); + Assert.Same(result, await task); + Assert.Equal(new[] { currentProbe, result.ProbeResult! }, f.ManualTests); + Assert.Equal(BlockCheckEvidenceStatus.Successful, staleItem.Status); + Assert.True(Assert.Single(f.Rebuilds)); + } + + [Fact] + public async Task OverlappingTestsApplyByCompletionOrderWithoutSerialization() + { + var f = new Fixture(); var item = Item(); var one = Pending(); var two = Pending(); + f.Operations.Test = _ => f.Operations.Tests.Count == 1 ? one.Task : two.Task; + var first = f.Controller.TestStrategyAsync(item); var second = f.Controller.TestStrategyAsync(item); + Assert.Equal(2, f.Operations.Tests.Count); + var secondResult = Result(Probe()); two.SetResult(secondResult); + Assert.Same(secondResult, await second); + Assert.False(first.IsCompleted); + var firstResult = Result(Probe(success: false)); one.SetResult(firstResult); + Assert.Same(firstResult, await first); + Assert.Same(firstResult.ProbeResult, Assert.Single(f.ManualTests)); + Assert.Equal(BlockCheckEvidenceStatus.Failed, item.Status); + Assert.Equal(2, f.Rebuilds.Count); + } + + [Theory] + [InlineData(0, 0, BlockCheckEvidenceStatus.Untested)] + [InlineData(3, 0, BlockCheckEvidenceStatus.Failed)] + [InlineData(3, 1, BlockCheckEvidenceStatus.Partial)] + [InlineData(3, 3, BlockCheckEvidenceStatus.Successful)] + public async Task EveryNonNullProbeReachesActualItemEvenWhenNoAttemptsSucceeded(int attempts, int successes, BlockCheckEvidenceStatus status) + { + var f = new Fixture(); var item = Item(); + var probe = new ProbeResult + { + StrategyId = "strategy", TargetId = "target", + Attempts = Enumerable.Range(0, attempts).Select(i => new ProbeAttempt + { + Success = i < successes, TimeToFirstByteMs = 25, HttpStatusCode = i < successes ? 200 : 0, + FailureCode = i < successes ? "" : "FAIL", + }).ToList(), + }; + f.Operations.Test = _ => Task.FromResult(Result(probe)); + await f.Controller.TestStrategyAsync(item); + Assert.Equal(status, item.Status); + Assert.Equal(attempts, item.AttemptCount); + Assert.Equal(successes, item.SuccessCount); + Assert.Equal(successes > 0 ? "200" : "", item.HttpStatusText); + Assert.Equal(attempts > successes ? "FAIL" : "", item.FailureText); + Assert.Same(probe, Assert.Single(f.ManualTests)); + Assert.Single(f.Rebuilds); + } + + [Fact] + public async Task ReturnedPairOwnsReplacementAndItemObserverMayEditLiveListBeforeRebuild() + { + var f = new Fixture(); var item = Item(); + var originalItemPair = Probe(); var staleReturnedPair = Probe("DIFFERENT", "other-target"); + f.ManualTests.AddRange([originalItemPair, staleReturnedPair]); + var returned = Probe("different", "other-target"); + var observerProbe = Probe("observer"); + item.PropertyChanged += (_, args) => + { + if (args.PropertyName != nameof(item.Status)) return; + Assert.Equal(new[] { originalItemPair, returned }, f.ManualTests); + f.ManualTests.Clear(); f.ManualTests.Add(observerProbe); + }; + f.OnRebuild = _ => Assert.Same(observerProbe, Assert.Single(f.ManualTests)); + f.Operations.Test = _ => Task.FromResult(Result(returned)); + await f.Controller.TestStrategyAsync(item); + Assert.Equal(BlockCheckEvidenceStatus.Successful, item.Status); + Assert.Same(observerProbe, Assert.Single(f.ManualTests)); + Assert.Single(f.Rebuilds); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task CallbackFailuresRetainAlreadyAppliedListAndItemMutations(bool inRebuild) + { + var f = new Fixture(); var item = Item(); var result = Result(Probe()); + var failure = new IOException("callback"); var notifications = new List(); + item.PropertyChanged += (_, args) => + { + notifications.Add(args.PropertyName!); + if (!inRebuild) throw failure; + }; + if (inRebuild) f.OnRebuild = _ => throw failure; + f.Operations.Test = _ => Task.FromResult(result); + Assert.Same(failure, await Assert.ThrowsAsync(() => f.Controller.TestStrategyAsync(item))); + Assert.Same(result.ProbeResult, Assert.Single(f.ManualTests)); + Assert.Equal(BlockCheckEvidenceStatus.Successful, item.Status); + Assert.Equal(inRebuild ? 11 : 1, notifications.Count); + Assert.Equal(inRebuild ? 1 : 0, f.Rebuilds.Count); + } + + [Fact] + public void PendingContinuationAppliesItemAndRebuildOnCapturedSynchronizationContext() + { + var f = new Fixture(); var item = Item(); var pending = Pending(); + f.Operations.Test = _ => pending.Task; + var context = new PumpContext(); var previous = SynchronizationContext.Current; + Task task; + item.PropertyChanged += (_, _) => Assert.Same(context, SynchronizationContext.Current); + f.OnRebuild = _ => Assert.Same(context, SynchronizationContext.Current); + try + { + SynchronizationContext.SetSynchronizationContext(context); + task = f.Controller.TestStrategyAsync(item); + } + finally { SynchronizationContext.SetSynchronizationContext(previous); } + var result = Result(Probe()); + pending.SetResult(result); + Assert.True(SpinWait.SpinUntil(() => context.HasWork, TimeSpan.FromSeconds(3))); + Assert.False(task.IsCompleted); + try + { + SynchronizationContext.SetSynchronizationContext(context); + context.Pump(); + } + finally { SynchronizationContext.SetSynchronizationContext(previous); } + Assert.True(task.IsCompletedSuccessfully); + Assert.Same(result.ProbeResult, Assert.Single(f.ManualTests)); + Assert.Single(f.Rebuilds); + } + + private static BlockCheckResultSession Session(int attempts = 3) => new() + { + RunOptions = new() { Scan = new() { AttemptsPerTarget = attempts } }, + StartupGracePeriod = TimeSpan.FromMilliseconds(123), ConnectTimeout = TimeSpan.FromSeconds(4), RequestTimeout = TimeSpan.FromSeconds(9), + }; + private static BlockCheck2StrategyEvidenceItem Item() => new(new() + { + Strategy = new() { Id = "strategy" }, + Target = new() { Id = "target", Host = "example.test", Protocol = BlockCheckProtocol.Tls12, IpVersion = BlockCheckIpVersion.IPv4 }, + Summary = new() { AttemptCount = 1 }, Status = BlockCheckEvidenceStatus.Failed, + }); + private static ProbeResult Probe(string strategy = "strategy", string target = "target", bool success = true) => new() + { + StrategyId = strategy, TargetId = target, + Attempts = [new() { Success = success, TimeToFirstByteMs = 23, HttpStatusCode = success ? 200 : 0, FailureCode = success ? "" : "failed" }], + }; + private static BlockCheckManualStrategyTestResult Result(ProbeResult probe) => new() { ProbeResult = probe, CommandLine = "--test" }; + private static TaskCompletionSource Pending() => new(TaskCreationOptions.RunContinuationsAsynchronously); + private sealed record ArgumentCall(StrategyDefinition Strategy, BlockCheckTarget Target, BlockCheckManualStrategyTestOptions Options); + private sealed record TestCall(StrategyDefinition Strategy, BlockCheckTarget Target, BlockCheckManualStrategyTestOptions Options, + CdpiuiZapret2StrategyRunnerOptions StrategyOptions, CurlBlockCheckProbeRunnerOptions ProbeOptions, CancellationToken Token); + private sealed class Operations : IBlockCheck2ManualStrategyTestOperations + { + public List Arguments { get; } = []; + public List Tests { get; } = []; + public Func> GetArguments = _ => OperationResultModel.SuccessResult("--test"); + public Func> Test = _ => Task.FromResult(new BlockCheckManualStrategyTestResult()); + public OperationResultModel GetFullStrategyArguments(StrategyDefinition strategy, BlockCheckTarget target, BlockCheckManualStrategyTestOptions options) + { + var call = new ArgumentCall(strategy, target, options); Arguments.Add(call); return GetArguments(call); + } + public Task TestAsync(StrategyDefinition strategy, BlockCheckTarget target, BlockCheckManualStrategyTestOptions options, + CdpiuiZapret2StrategyRunnerOptions strategyOptions, CurlBlockCheckProbeRunnerOptions probeOptions, CancellationToken cancellationToken) + { + var call = new TestCall(strategy, target, options, strategyOptions, probeOptions, cancellationToken); Tests.Add(call); return Test(call); + } + } + private sealed class Fixture + { + public BlockCheckResultSession? Session = BlockCheck2ManualStrategyTestControllerTests.Session(); + public int SessionReads; + public BlockCheck2PresetDraft Draft { get; } = new(); + public List ManualTests { get; } = []; + public List Rebuilds { get; } = []; + public Action? OnRebuild; + public Operations Operations { get; } = new(); + public BlockCheck2ManualStrategyTestController Controller { get; } + public Fixture() + { + Draft.LoadAutomatic("--automatic", []); + Controller = new(Draft, ManualTests, () => { SessionReads++; return Session; }, + update => { Rebuilds.Add(update); OnRebuild?.Invoke(update); }, Operations); + } + } + private sealed class PumpContext : SynchronizationContext + { + private readonly ConcurrentQueue<(SendOrPostCallback Callback, object? State)> _work = new(); + public bool HasWork => !_work.IsEmpty; + public override void Post(SendOrPostCallback d, object? state) => _work.Enqueue((d, state)); + public void Pump() { while (_work.TryDequeue(out var work)) work.Callback(work.State); } + } +} diff --git a/CDPIUI.Tests/Presentation/BlockCheck2ManualTestSessionTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2ManualTestSessionTests.cs new file mode 100644 index 00000000..d6da9dd4 --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2ManualTestSessionTests.cs @@ -0,0 +1,590 @@ +using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.Shared.Models; +using CDPIUI.Shared.PrettyErrorConversionService; +using CDPIUI.ViewModels; +using CDPIUI.ViewModels.BlockCheck2; + +namespace CDPIUI.Tests.Presentation; + +public class BlockCheck2ManualTestSessionTests +{ + [Fact] + public void ConstructorDoesNotReadHostResolveIdOrSubscribe() + { + var f = new Fixture(); + Assert.False(f.Owner.IsRunning); + Assert.Empty(f.Trace); + Assert.Empty(f.Order); + Assert.Equal(0, f.Tasks.SubscriberCount); + } + + [Fact] + public async Task MissingItemStopsBeforeRunningStrategyOrAnyOtherPort() + { + var f = new Fixture { Item = null, StrategyRunning = true }; + await f.Owner.StartAsync(); + Assert.Equal(["selected"], f.Trace); + } + + [Fact] + public async Task RunningManualTestDoesNotReadStrategyFlagOrRestart() + { + var f = new Fixture(); await f.Owner.StartAsync(); f.Clear(); + await f.Owner.StartAsync(); + Assert.Equal(["selected"], f.Trace); + Assert.True(f.Owner.IsRunning); + } + + [Fact] + public async Task RunningSingleStrategyBlocksManualStart() + { + var f = new Fixture { StrategyRunning = true }; + await f.Owner.StartAsync(); + Assert.Equal(["selected", "strategy"], f.Trace); + Assert.False(f.Owner.IsRunning); + } + + [Fact] + public async Task StartPublishesFlagsAndSubscribesExactHostHandlerBeforeRun() + { + var f = new Fixture(); + f.OnCall = name => { if (name is "subscribe" or "show:Informational" or "run:A:--args") Assert.True(f.Owner.IsRunning); }; + await f.Owner.StartAsync(); + Assert.Equal(["selected", "strategy", "selection", "arguments", "selection", "id:A", "check:A", "id:A", "stop:A", + "subscribe", "selection", "text:ManualTesting", "text:ConfigMakerTestStartedMessage", "show:Informational", "id:A", "run:A:--args"], f.Trace); + Assert.Same(f.Handler, Assert.Single(f.Tasks.Added)); + Assert.Equal((BlockCheck2NoticeSeverity.Informational, "ManualTesting", "ConfigMakerTestStartedMessage"), Assert.Single(f.Notices)); + Assert.True(f.Owner.IsRunning); + } + + [Theory] + [InlineData(false, "--present")] + [InlineData(true, "")] + [InlineData(true, null)] + public async Task InvalidArgumentsShowWarningWithoutComponentCalls(bool success, string? arguments) + { + var f = new Fixture { Arguments = new() { Success = success, Result = arguments } }; + await f.Owner.StartAsync(); + Assert.Equal(["selected", "strategy", "selection", "arguments", "text:ManualTesting", "text:ConfigMakerEmptyArgumentsMessage", "show:Warning"], f.Trace); + Assert.Equal((BlockCheck2NoticeSeverity.Warning, "ManualTesting", "ConfigMakerEmptyArgumentsMessage"), Assert.Single(f.Notices)); + Assert.False(f.Owner.IsRunning); + } + + [Fact] + public async Task ArgumentErrorCodeIsShownWithoutEmptyArgumentLocalization() + { + var f = new Fixture { Arguments = OperationResultModel.FailureResult(ErrorModel.OnlyErrorCode("OWNED_ERROR")) }; + await f.Owner.StartAsync(); + Assert.Equal((BlockCheck2NoticeSeverity.Warning, "ManualTesting", "OWNED_ERROR"), Assert.Single(f.Notices)); + Assert.DoesNotContain("text:ConfigMakerEmptyArgumentsMessage", f.Trace); + Assert.DoesNotContain("id:A", f.Trace); + } + + [Fact] + public async Task WhitespaceArgumentsAreNotRejectedOrTrimmed() + { + var f = new Fixture { Arguments = OperationResultModel.SuccessResult(" ") }; + await f.Owner.StartAsync(); + Assert.Contains("run:A: ", f.Trace); + Assert.True(f.Owner.IsRunning); + } + + [Fact] + public async Task SelectionPublicationKeepsCapturedItemButReadsCurrentArguments() + { + var f = new Fixture(); var selected = f.Item; + f.OnCall = name => + { + if (name != "selection") return; + f.Item = new(new()); f.Arguments = OperationResultModel.SuccessResult("--current"); + }; + await f.Owner.StartAsync(); + Assert.Same(selected, Assert.Single(f.ArgumentItems)); + Assert.Contains("run:A:--current", f.Trace); + } + + [Fact] + public async Task DecliningRunningReplacementDoesNotStopSubscribeOrPublishStarted() + { + var f = new Fixture { ConfirmResult = false }; f.Tasks.WasRunning = true; + await f.Owner.StartAsync(); + Assert.Equal(["selected", "strategy", "selection", "arguments", "selection", "id:A", "check:A", "confirm"], f.Trace); + Assert.False(f.Owner.IsRunning); Assert.Empty(f.Notices); Assert.Equal(0, f.Tasks.SubscriberCount); + } + + [Fact] + public async Task ConfirmIsNotReadWhenComponentWasStopped() + { + var f = new Fixture(); + f.OnCall = name => { if (name == "confirm") throw new InvalidOperationException("Unexpected confirmation"); }; + await f.Owner.StartAsync(); + Assert.DoesNotContain("confirm", f.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task PendingConfirmationDefersStopAndKeepsOriginalRunningSnapshot(bool accepted) + { + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var f = new Fixture(); f.Tasks.WasRunning = true; f.Confirm = () => gate.Task; + Task start = f.Owner.StartAsync(); + try + { + Assert.False(start.IsCompleted); Assert.False(f.Owner.IsRunning); + Assert.DoesNotContain("stop:A", f.Trace); Assert.Equal(0, f.Tasks.SubscriberCount); + f.Tasks.WasRunning = false; + gate.SetResult(accepted); await Wait(start); + Assert.Equal(accepted, f.Owner.IsRunning); + if (accepted) { f.Clear(); await f.Owner.StopAsync(); Assert.Contains("restore:A", f.Trace); } + else { Assert.DoesNotContain("stop:A", f.Trace); Assert.Empty(f.Notices); } + } + finally { gate.TrySetResult(false); await Wait(start); } + } + + [Fact] + public async Task StartReadsLiveIdForCheckStopAndRunAfterCallbacks() + { + var f = new Fixture(); f.Tasks.WasRunning = true; + f.OnCall = name => + { + if (name == "confirm") f.Id = "B"; + if (name == "stop:B") f.Id = "C"; + if (name == "show:Informational") f.Id = "D"; + }; + await f.Owner.StartAsync(); + Assert.Contains("check:A", f.Trace); Assert.Contains("stop:B", f.Trace); Assert.Contains("run:D:--args", f.Trace); + Assert.DoesNotContain("stop:A", f.Trace); + } + + [Fact] + public async Task ReceiverIsResolvedBeforeIdAndResolvedAgainForLaterOperations() + { + var f = new Fixture(); var replacement = new Tasks(f); + f.OnCall = name => { if (name == "id:A") { f.CurrentTasks = replacement; f.Id = "B"; } }; + await f.Owner.StartAsync(); + Assert.Equal(["A"], f.Tasks.CheckIds); Assert.Empty(replacement.CheckIds); + Assert.Empty(f.Tasks.StopIds); Assert.Equal(["B"], replacement.StopIds); + Assert.Equal(["selected", "strategy", "selection", "arguments", "selection", "resolve", "id:A", "check:A", + "resolve", "id:B", "stop:B", "resolve", "subscribe"], f.Order.Take(13)); + Assert.Equal(1, replacement.SubscriberCount); + } + + [Theory] + [InlineData("selected")] + [InlineData("strategy")] + [InlineData("selection")] + [InlineData("arguments")] + [InlineData("resolve")] + [InlineData("check:A")] + [InlineData("confirm")] + [InlineData("stop:A")] + [InlineData("subscribe")] + [InlineData("text:ConfigMakerTestStartedMessage")] + [InlineData("show:Informational")] + public async Task SetupFaultIsReturnedInTaskOutsideRunCatch(string endpoint) + { + var f = new Fixture(); f.Tasks.WasRunning = true; + var fault = new InvalidOperationException("setup fault"); + f.OnCall = name => { if (name == endpoint) throw fault; }; + Task task = f.Owner.StartAsync(); + Assert.Same(fault, await Assert.ThrowsAsync(() => Wait(task))); + Assert.DoesNotContain("show:Error", f.Trace); + Assert.DoesNotContain("assignments", f.Trace); + Assert.DoesNotContain("run:A:--args", f.Trace); + Assert.Equal(endpoint is "subscribe" or "text:ConfigMakerTestStartedMessage" or "show:Informational", f.Owner.IsRunning); + } + + [Fact] + public async Task StartedNoticeFaultLeavesStartingGuardActiveUntilExplicitStop() + { + var f = new Fixture(); var fault = new InvalidOperationException("notice fault"); + f.OnCall = name => { if (name == "show:Informational") throw fault; }; + Task task = f.Owner.StartAsync(); + Assert.Same(fault, await Assert.ThrowsAsync(() => Wait(task))); + f.OnCall = null; f.Clear(); f.Tasks.Emit("A", false); + Assert.True(f.Owner.IsRunning); Assert.Empty(f.Trace); Assert.Empty(f.Queue); + await f.Owner.StopAsync(); Assert.False(f.Owner.IsRunning); + } + + [Fact] + public async Task PendingRunDropsStartingEventsAndConcurrentStopDoesNotRestartAfterAcknowledgment() + { + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var f = new Fixture(); f.Tasks.Run = (_, _) => gate.Task; + Task start = f.Owner.StartAsync(); + try + { + Assert.False(start.IsCompleted); Assert.True(f.Owner.IsRunning); + f.Clear(); f.Tasks.Emit("A", false); Assert.Empty(f.Trace); Assert.Empty(f.Queue); + await Wait(f.Owner.StopAsync()); Assert.False(f.Owner.IsRunning); Assert.Equal(0, f.Tasks.SubscriberCount); + gate.SetResult(); await Wait(start); + Assert.False(f.Owner.IsRunning); Assert.Equal(0, f.Tasks.SubscriberCount); + } + finally { gate.TrySetResult(); await Wait(start); } + } + + [Fact] + public async Task TwoStartsPendingAtRunningCheckRemainIndependentWithoutNewLock() + { + var firstGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var secondGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var f = new Fixture(); int checks = 0; + f.Tasks.Check = _ => ++checks == 1 ? firstGate.Task : secondGate.Task; + Task first = f.Owner.StartAsync(); Task second = f.Owner.StartAsync(); + try + { + Assert.Equal(2, f.Trace.Count(name => name == "check:A")); + Assert.False(first.IsCompleted); Assert.False(second.IsCompleted); + firstGate.SetResult(false); await Wait(first); + Assert.False(second.IsCompleted); + secondGate.SetResult(false); await Wait(second); + Assert.Equal(2, f.Trace.Count(name => name == "run:A:--args")); + Assert.Equal(2, f.Tasks.SubscriberCount); + } + finally { firstGate.TrySetResult(false); secondGate.TrySetResult(false); await Wait(Task.WhenAll(first, second)); } + } + + [Fact] + public async Task StartedNoticeMayStopReentrantlyButOuterStartStillCallsRun() + { + var f = new Fixture(); Task? stop = null; bool entered = false; + f.OnCall = name => { if (name == "show:Informational" && !entered) { entered = true; stop = f.Owner.StopAsync(); } }; + await f.Owner.StartAsync(); await stop!; + Assert.False(f.Owner.IsRunning); Assert.Equal(0, f.Tasks.SubscriberCount); + Assert.Equal("run:A:--args", f.Trace.Last()); + Assert.Single(f.Notices); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task RunFailureShowsErrorThenStopsAndRestoresPreviousComponent(bool canceled) + { + using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); + Task failure = canceled ? Task.FromCanceled(cancellation.Token) : Task.FromException(new IOException("run failed")); + Exception expected = await Assert.ThrowsAnyAsync(() => failure); + var f = new Fixture(); f.Tasks.WasRunning = true; f.Tasks.Run = (_, _) => failure; + await f.Owner.StartAsync(); + Assert.False(f.Owner.IsRunning); Assert.Equal(0, f.Tasks.SubscriberCount); + Assert.Equal((BlockCheck2NoticeSeverity.Error, "ManualTesting", "start failed: " + expected.Message), f.Notices[1]); + Assert.Equal(["selection", "unsubscribe", "id:A", "id:A", "stop:A", "id:A", "restore:A", "selection", "assignments"], f.Trace.TakeLast(9)); + Assert.Empty(f.Warnings); + } + + [Fact] + public async Task MalformedFailureFormatLeavesRunningButStartingGuardIsReleased() + { + var f = new Fixture { FailedFormat = "{1}" }; f.Tasks.Run = (_, _) => throw new IOException("run failed"); + Task task = f.Owner.StartAsync(); await Assert.ThrowsAsync(() => Wait(task)); + Assert.True(f.Owner.IsRunning); Assert.Equal(1, f.Tasks.SubscriberCount); + Assert.Single(f.Notices); f.Clear(); f.Tasks.Emit("A", false); + Assert.Equal(["id:A", "enqueue"], f.Trace); Assert.Single(f.Queue); + } + + [Fact] + public async Task RunFailureCleanupFaultEscapesWithoutSecondErrorOrWarning() + { + var f = new Fixture(); f.Tasks.Run = (_, _) => throw new IOException("run failed"); + var cleanupFault = new InvalidOperationException("cleanup failed"); int stops = 0; + f.Tasks.Stop = _ => ++stops == 2 ? throw cleanupFault : Task.CompletedTask; + Task task = f.Owner.StartAsync(); + Assert.Same(cleanupFault, await Assert.ThrowsAsync(() => Wait(task))); + Assert.False(f.Owner.IsRunning); Assert.Equal(2, f.Notices.Count); Assert.Empty(f.Warnings); + Assert.DoesNotContain("assignments", f.Trace); + } + + [Fact] + public async Task IdResolutionForRunIsInsideStartFailureCatch() + { + var f = new Fixture(); int reads = 0; + f.OnCall = name => { if (name == "id:A" && ++reads == 3) throw new InvalidOperationException("run id fault"); }; + await f.Owner.StartAsync(); + Assert.False(f.Owner.IsRunning); Assert.DoesNotContain("run:A:--args", f.Trace); + Assert.Equal((BlockCheck2NoticeSeverity.Error, "ManualTesting", "start failed: run id fault"), f.Notices[1]); + Assert.Equal("assignments", f.Trace.Last()); Assert.Empty(f.Warnings); + } + + [Fact] + public async Task StoppedStopOnlyUpdatesSelectionAndLeaveDoesNothing() + { + var f = new Fixture(); + await f.Owner.StopAsync(true); Assert.Equal(["selection"], f.Trace); + f.Clear(); await f.Owner.StopOnLeaveAsync(); Assert.Empty(f.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task PreviouslyStoppedComponentIsNeverRestored(bool leave) + { + var f = new Fixture(); await f.Owner.StartAsync(); f.Clear(); + if (leave) await f.Owner.StopOnLeaveAsync(); else await f.Owner.StopAsync(); + Assert.Equal(leave ? ["unsubscribe", "id:A", "stop:A"] : + ["selection", "unsubscribe", "id:A", "id:A", "stop:A", "selection", "assignments"], f.Trace); + Assert.False(f.Owner.IsRunning); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task StopClearsRunningAndUnsubscribesBeforeStopAwaitThenUpdatesView(bool completionMessage) + { + var f = new Fixture(); f.Tasks.WasRunning = true; await f.Owner.StartAsync(); f.Clear(); + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); f.Tasks.Stop = _ => gate.Task; + Task stop = f.Owner.StopAsync(completionMessage); + try + { + Assert.False(stop.IsCompleted); Assert.False(f.Owner.IsRunning); Assert.Equal(0, f.Tasks.SubscriberCount); + Assert.Equal(["selection", "unsubscribe", "id:A", "id:A", "stop:A"], f.Trace); + gate.SetResult(); await Wait(stop); + var expected = new List { "selection", "unsubscribe", "id:A", "id:A", "stop:A", "id:A", "restore:A" }; + if (completionMessage) expected.AddRange(["text:ManualTesting", "text:ConfigMakerTestStoppedMessage", "show:Informational"]); + expected.AddRange(["selection", "assignments"]); Assert.Equal(expected, f.Trace); + } + finally { gate.TrySetResult(); await Wait(stop); } + } + + [Fact] + public async Task StopRereadsIdForWhitespaceGuardStopAndRestore() + { + var f = new Fixture(); f.Tasks.WasRunning = true; await f.Owner.StartAsync(); f.Clear(); + f.OnCall = name => { if (name == "id:A") f.Id = "B"; if (name == "stop:B") f.Id = "C"; }; + await f.Owner.StopAsync(); + Assert.Equal(["selection", "unsubscribe", "id:A", "id:B", "stop:B", "id:C", "restore:C", "selection", "assignments"], f.Trace); + } + + [Fact] + public async Task StopWithBlankIdStillPublishesCompletionAndAssignments() + { + var f = new Fixture(); f.Tasks.WasRunning = true; await f.Owner.StartAsync(); f.Clear(); f.Id = " "; + await f.Owner.StopAsync(true); + Assert.Equal(["selection", "unsubscribe", "id: ", "text:ManualTesting", "text:ConfigMakerTestStoppedMessage", "show:Informational", "selection", "assignments"], f.Trace); + Assert.False(f.Owner.IsRunning); + } + + [Theory] + [InlineData("selection", true)] + [InlineData("unsubscribe", false)] + [InlineData("id:A", false)] + [InlineData("stop:A", false)] + [InlineData("restore:A", false)] + [InlineData("text:ConfigMakerTestStoppedMessage", false)] + [InlineData("show:Informational", false)] + [InlineData("assignments", false)] + public async Task StopFaultEscapesAtOriginalBoundaryWithoutWarning(string endpoint, bool stillRunning) + { + var f = new Fixture(); f.Tasks.WasRunning = true; await f.Owner.StartAsync(); f.Clear(); + var fault = new InvalidOperationException("stop fault"); f.OnCall = name => { if (name == endpoint) throw fault; }; + Task task = f.Owner.StopAsync(true); + Assert.Same(fault, await Assert.ThrowsAsync(() => Wait(task))); + Assert.Equal(stillRunning, f.Owner.IsRunning); Assert.Empty(f.Warnings); Assert.Equal(endpoint, f.Trace.Last()); + } + + [Fact] + public async Task LeaveCapturesOneIdAndDoesNotUpdateSelectionOrShowCompletion() + { + var f = new Fixture(); f.Tasks.WasRunning = true; await f.Owner.StartAsync(); f.Clear(); + f.OnCall = name => { if (name == "id:A") f.Id = "B"; if (name == "stop:A") f.Id = "C"; }; + await f.Owner.StopOnLeaveAsync(); + Assert.Equal(["unsubscribe", "id:A", "stop:A", "restore:A"], f.Trace); + Assert.False(f.Owner.IsRunning); Assert.Empty(f.Notices); + } + + [Fact] + public async Task LeaveWithBlankIdStopsAfterUnsubscribeWithoutViewUpdates() + { + var f = new Fixture(); await f.Owner.StartAsync(); f.Clear(); f.Id = ""; + await f.Owner.StopOnLeaveAsync(); + Assert.Equal(["unsubscribe", "id:"], f.Trace); Assert.False(f.Owner.IsRunning); + } + + [Theory] + [InlineData("unsubscribe")] + [InlineData("id:A")] + public async Task LeaveSetupFaultIsOutsideWarningCatch(string endpoint) + { + var f = new Fixture(); await f.Owner.StartAsync(); f.Clear(); var fault = new InvalidOperationException("leave setup"); + f.OnCall = name => { if (name == endpoint) throw fault; }; + Task task = f.Owner.StopOnLeaveAsync(); + Assert.Same(fault, await Assert.ThrowsAsync(() => Wait(task))); + Assert.False(f.Owner.IsRunning); Assert.Empty(f.Warnings); + } + + [Theory] + [InlineData("stop:A")] + [InlineData("restore:A")] + public async Task LeaveComponentFaultIsWarnedWithOriginalExceptionAndNoViewUpdates(string endpoint) + { + var f = new Fixture(); f.Tasks.WasRunning = true; await f.Owner.StartAsync(); f.Clear(); var fault = new IOException("leave component"); + f.OnCall = name => { if (name == endpoint) throw fault; }; + await f.Owner.StopOnLeaveAsync(); + Assert.Same(fault, Assert.Single(f.Warnings)); Assert.False(f.Owner.IsRunning); + Assert.Empty(f.Notices); Assert.DoesNotContain("selection", f.Trace); Assert.DoesNotContain("assignments", f.Trace); + Assert.Equal("warn:leave component", f.Trace.Last()); + } + + [Fact] + public async Task WarningFaultEscapesWithoutRetry() + { + var f = new Fixture(); await f.Owner.StartAsync(); f.Clear(); var fault = new InvalidOperationException("warn callback"); + f.Tasks.Stop = _ => throw new IOException("leave component"); f.OnCall = name => { if (name.StartsWith("warn:")) throw fault; }; + Task task = f.Owner.StopOnLeaveAsync(); + Assert.Same(fault, await Assert.ThrowsAsync(() => Wait(task))); + Assert.Single(f.Warnings); Assert.False(f.Owner.IsRunning); + } + + [Theory] + [InlineData(true, true)] + [InlineData(false, false)] + [InlineData(null, false)] + public async Task ButtonToggleUsesAlreadyChangedNullableCheck(bool? check, bool starts) + { + var f = new Fixture { Checked = check }; + await f.Owner.ToggleFromButtonAsync(); + Assert.Equal("checked", f.Trace[0]); Assert.Equal(starts, f.Owner.IsRunning); + if (!starts) Assert.Equal(["checked", "selection"], f.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(null)] + public async Task UncheckingRunningButtonStopsAndShowsCompletionExactlyOnce(bool? check) + { + var f = new Fixture(); await f.Owner.StartAsync(); f.Clear(); f.Checked = check; + await f.Owner.ToggleFromButtonAsync(); + Assert.False(f.Owner.IsRunning); Assert.Equal(0, f.Tasks.SubscriberCount); + Assert.Equal((BlockCheck2NoticeSeverity.Informational, "ManualTesting", "ConfigMakerTestStoppedMessage"), Assert.Single(f.Notices)); + Assert.Equal(["checked", "selection", "unsubscribe", "id:A", "id:A", "stop:A", + "text:ManualTesting", "text:ConfigMakerTestStoppedMessage", "show:Informational", "selection", "assignments"], f.Trace); + } + + [Fact] + public async Task MenuToggleUsesRunningStateInsteadOfButtonCheck() + { + var f = new Fixture { Checked = false }; await f.Owner.ToggleAsync(); + Assert.True(f.Owner.IsRunning); f.Clear(); f.Checked = true; await f.Owner.ToggleAsync(); + Assert.False(f.Owner.IsRunning); Assert.DoesNotContain("checked", f.Trace); + Assert.Equal((BlockCheck2NoticeSeverity.Informational, "ManualTesting", "ConfigMakerTestStoppedMessage"), Assert.Single(f.Notices)); + } + + [Fact] + public void StoppedStateEventShortCircuitsBeforeReadingNullTupleOrId() + { + var f = new Fixture(); f.Owner.HandleStateUpdated(null!); Assert.Empty(f.Trace); + } + + [Theory] + [InlineData("other", false)] + [InlineData("A", true)] + public async Task WrongOrStillRunningEventDoesNotQueue(string id, bool running) + { + var f = new Fixture(); await f.Owner.StartAsync(); f.Clear(); f.Tasks.Emit(id, running); + Assert.Equal(["id:A"], f.Trace); Assert.Empty(f.Queue); Assert.True(f.Owner.IsRunning); + } + + [Fact] + public async Task MatchingEventUsesCurrentCaseInsensitiveIdAndDefersAllStateChanges() + { + var f = new Fixture(); await f.Owner.StartAsync(); f.Clear(); f.Id = "B"; + f.Tasks.Emit("A", false); f.Tasks.Emit("b", false); + Assert.Equal(["id:B", "id:B", "enqueue"], f.Trace); Assert.True(f.Owner.IsRunning); Assert.Empty(f.Notices); + await Wait(Assert.Single(f.Queue)()); + Assert.False(f.Owner.IsRunning); + Assert.Equal((BlockCheck2NoticeSeverity.Warning, "ManualTesting", "ConfigMakerTestExitedMessage"), Assert.Single(f.Notices)); + Assert.Contains("stop:B", f.Trace); Assert.Equal("assignments", f.Trace.Last()); + } + + [Fact] + public async Task QueuedExitDoesNotRepeatGuardOrDeduplicateAfterExplicitStop() + { + var f = new Fixture(); await f.Owner.StartAsync(); f.Tasks.Emit("A", false); f.Tasks.Emit("A", false); + Assert.Equal(2, f.Queue.Count); await f.Owner.StopAsync(); f.Clear(); + foreach (var callback in f.Queue) await Wait(callback()); + Assert.Equal(2, f.Notices.Count); Assert.All(f.Notices, notice => Assert.Equal(BlockCheck2NoticeSeverity.Warning, notice.Severity)); + Assert.Equal(2, f.Trace.Count(name => name == "selection")); Assert.DoesNotContain("stop:A", f.Trace); + } + + [Fact] + public async Task DroppedDispatchDoesNotClearRunningOrShowExitNotice() + { + var f = new Fixture { DropQueue = true }; await f.Owner.StartAsync(); f.Clear(); f.Tasks.Emit("A", false); + Assert.True(f.Owner.IsRunning); Assert.Empty(f.Queue); Assert.Empty(f.Notices); Assert.Equal(["id:A", "enqueue"], f.Trace); + } + + [Fact] + public async Task QueuedNoticeFaultIsReturnedByCallbackAndPreventsStop() + { + var f = new Fixture(); await f.Owner.StartAsync(); f.Tasks.Emit("A", false); f.Clear(); var fault = new IOException("exit notice"); + f.OnCall = name => { if (name == "show:Warning") throw fault; }; + Task callback = Assert.Single(f.Queue)(); + Assert.Same(fault, await Assert.ThrowsAsync(() => Wait(callback))); + Assert.True(f.Owner.IsRunning); Assert.DoesNotContain("selection", f.Trace); Assert.Empty(f.Warnings); + } + + private static Task Wait(Task task) => task.WaitAsync(TimeSpan.FromSeconds(3)); + + private sealed class Fixture : IBlockCheck2ManualTestHost + { + internal readonly List Trace = []; + internal readonly List Order = []; + internal readonly List<(BlockCheck2NoticeSeverity Severity, string Title, string Message)> Notices = []; + internal readonly List Warnings = []; + internal readonly List ArgumentItems = []; + internal readonly List> Queue = []; + internal readonly Tasks Tasks; + internal IConfigMakerTestTasks CurrentTasks; + internal readonly BlockCheck2ManualTestSession Owner; + internal readonly Action> Handler; + internal BlockCheck2StrategyEvidenceItem? Item = new(new()); + internal bool StrategyRunning, ConfirmResult = true, DropQueue; + internal bool? Checked; + internal string Id = "A", FailedFormat = "start failed: {0}"; + internal OperationResultModel Arguments = OperationResultModel.SuccessResult("--args"); + internal Action? OnCall; + internal Func>? Confirm; + internal Fixture() + { + Tasks = new(this); CurrentTasks = Tasks; Handler = state => Owner.HandleStateUpdated(state); + Owner = new(this, ResolveTasks, () => { string id = Id; Call("id:" + id); return id; }, Handler); + } + private IConfigMakerTestTasks ResolveTasks() { Order.Add("resolve"); OnCall?.Invoke("resolve"); return CurrentTasks; } + internal void Clear() { Trace.Clear(); Order.Clear(); Notices.Clear(); Warnings.Clear(); } + internal void Call(string name) { Trace.Add(name); Order.Add(name); OnCall?.Invoke(name); } + public BlockCheck2StrategyEvidenceItem? SelectedStrategy { get { Call("selected"); return Item; } } + public bool IsStrategyTestRunning { get { Call("strategy"); return StrategyRunning; } } + public bool? IsManualTestChecked { get { Call("checked"); return Checked; } } + public OperationResultModel GetFullStrategyArguments(BlockCheck2StrategyEvidenceItem item) + { ArgumentItems.Add(item); Call("arguments"); return Arguments; } + public Task ConfirmReplacementAsync() { Call("confirm"); return Confirm?.Invoke() ?? Task.FromResult(ConfirmResult); } + public void UpdateSelectedStrategy() => Call("selection"); + public void UpdateAssignmentView() => Call("assignments"); + public string Text(string key) { Call("text:" + key); return key == "ConfigMakerTestStartFailedMessage" ? FailedFormat : key; } + public void ShowMessage(BlockCheck2NoticeSeverity severity, string title, string message) + { Notices.Add((severity, title, message)); Call("show:" + severity); } + public void Warn(Exception exception) { Warnings.Add(exception); Call("warn:" + exception.Message); } + public void Enqueue(Func callback) { Call("enqueue"); if (!DropQueue) Queue.Add(callback); } + } + + private sealed class Tasks(Fixture f) : IConfigMakerTestTasks + { + private Action>? _handlers; + internal readonly List>> Added = []; + internal readonly List CheckIds = [], StopIds = []; + internal bool WasRunning; + internal Func>? Check; + internal Func Stop = _ => Task.CompletedTask; + internal Func Run = (_, _) => Task.CompletedTask; + internal int SubscriberCount => _handlers?.GetInvocationList().Length ?? 0; + public event Action>? StateUpdated + { + add { _handlers += value; Added.Add(value!); f.Call("subscribe"); } + remove { _handlers -= value; f.Call("unsubscribe"); } + } + internal void Emit(string id, bool running) => _handlers?.Invoke(Tuple.Create(id, running)); + public Task IsRunningAsync(string componentId) { CheckIds.Add(componentId); f.Call("check:" + componentId); return Check?.Invoke(componentId) ?? Task.FromResult(WasRunning); } + public Task StopAsync(string componentId) { StopIds.Add(componentId); f.Call("stop:" + componentId); return Stop(componentId); } + public Task RunAsync(string componentId, string arguments) { f.Call("run:" + componentId + ":" + arguments); return Run(componentId, arguments); } + public Task RestoreAsync(string componentId) { f.Call("restore:" + componentId); return Task.CompletedTask; } + } +} diff --git a/CDPIUI.Tests/Presentation/BlockCheck2OptionsTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2OptionsTests.cs new file mode 100644 index 00000000..10ea214c --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2OptionsTests.cs @@ -0,0 +1,219 @@ +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.ViewModels; + +namespace CDPIUI.Tests.Presentation; + +public class BlockCheck2OptionsTests +{ + [Fact] + public void DefaultsRetainBalancedTlsAndIpv4WithoutWritingSettings() + { + var settings = new MemorySettings(); + var options = Create(settings); + + Assert.Equal(BlockCheckRunPreset.Balanced, options.SelectedRunPreset); + Assert.True(options.IncludeTls12); + Assert.True(options.IncludeTlsAuto); + Assert.True(options.IncludeIpv4); + Assert.False(options.IncludeHttp); + Assert.False(options.IncludeTls13); + Assert.False(options.IncludeQuic); + Assert.False(options.IncludeIpv6); + Assert.Equal(5d, options.ConnectTimeoutSeconds); + Assert.Equal(10d, options.RequestTimeoutSeconds); + Assert.Equal(0.75d, options.StartupGraceSeconds); + Assert.Equal(3d, options.RequestsPerDomain); + Assert.True(options.AdvancedOptionsValid); + Assert.Empty(settings.Writes); + } + + [Fact] + public void CorruptSavedValuesUseTheExistingFallbacks() + { + var settings = new MemorySettings(); + settings.Values["SelectedRunPreset"] = 999; + settings.Values["ConnectTimeoutSeconds"] = double.NaN; + settings.Values["RequestTimeoutSeconds"] = -1d; + settings.Values["StartupGraceSeconds"] = double.PositiveInfinity; + settings.Values["RequestsPerDomain"] = 99; + + var options = Create(settings); + + Assert.Equal(BlockCheckRunPreset.Balanced, options.SelectedRunPreset); + Assert.Equal(5d, options.ConnectTimeoutSeconds); + Assert.Equal(10d, options.RequestTimeoutSeconds); + Assert.Equal(0.75d, options.StartupGraceSeconds); + Assert.Equal(3d, options.RequestsPerDomain); + Assert.Empty(settings.Writes); + } + + [Fact] + public void InvalidSavedRequestTimeoutIsAtLeastTheValidConnectTimeout() + { + var settings = new MemorySettings(); + settings.Values["ConnectTimeoutSeconds"] = 40d; + settings.Values["RequestTimeoutSeconds"] = 10d; + + var options = Create(settings); + + Assert.Equal(40d, options.RequestTimeoutSeconds); + } + + [Fact] + public void ProtocolChangeKeepsNotificationAndSaveOrder() + { + var settings = new MemorySettings(); + var options = Create(settings); + options.PropertyChanged += (_, args) => settings.Trace.Add("notify:" + args.PropertyName); + + options.IncludeHttp = true; + + Assert.Equal(["notify:IncludeHttp", "save:IncludeHttp", "notify:IsHttpOnly", "notify:HasProtocolSelection", + "notify:CanContinueFromTargets", "notify:CanStart"], settings.Trace); + Assert.Equal(("IncludeHttp", (object)true), Assert.Single(settings.Writes)); + } + + [Fact] + public void AssigningTheSameOptionDoesNotWriteOrNotify() + { + var settings = new MemorySettings(); + var options = Create(settings); + options.PropertyChanged += (_, args) => settings.Trace.Add("notify:" + args.PropertyName); + + options.IncludeTls12 = true; + options.RequestsPerDomain = 3d; + options.ConnectTimeoutSeconds = 5d; + + Assert.Empty(settings.Trace); + } + + [Fact] + public void PresetChangeSavesPresetBeforeUpdatingRecommendedAttempts() + { + var settings = new MemorySettings(); + var options = Create(settings); + options.PropertyChanged += (_, args) => settings.Trace.Add("notify:" + args.PropertyName); + + options.SelectedRunPreset = BlockCheckRunPreset.Exhaustive; + + Assert.Equal(5d, options.RequestsPerDomain); + Assert.Equal(["notify:SelectedRunPreset", "save:SelectedRunPreset", "notify:RequestsPerDomain", + "notify:AdvancedOptionsValid", "notify:CanStart", "save:RequestsPerDomain"], settings.Trace); + Assert.Equal(("SelectedRunPreset", (object)2), settings.Writes[0]); + Assert.Equal(("RequestsPerDomain", (object)5), settings.Writes[1]); + } + + [Theory] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(double.NegativeInfinity)] + public void NonfiniteAdvancedValuesInvalidateTheFormWithoutPersisting(double value) + { + var settings = new MemorySettings(); + var options = Create(settings); + + options.ConnectTimeoutSeconds = value; + + Assert.Equal(value, options.ConnectTimeoutSeconds); + Assert.False(options.AdvancedOptionsValid); + Assert.Empty(settings.Writes); + } + + [Fact] + public void FiniteInvalidAdvancedValueRemainsVisibleAndIsSavedAsBefore() + { + var settings = new MemorySettings(); + var options = Create(settings); + + options.ConnectTimeoutSeconds = 0d; + + Assert.False(options.AdvancedOptionsValid); + Assert.Equal(("ConnectTimeoutSeconds", (object)0d), Assert.Single(settings.Writes)); + } + + [Theory] + [InlineData(0d)] + [InlineData(1.5d)] + [InlineData(21d)] + public void InvalidAttemptsAreNotPersisted(double value) + { + var settings = new MemorySettings(); + var options = Create(settings); + + options.RequestsPerDomain = value; + + Assert.False(options.AdvancedOptionsValid); + Assert.Empty(settings.Writes); + } + + [Fact] + public void StartAvailabilityReadsLiveRunStateAndSiteListCount() + { + bool running = false; + int selected = 0; + var options = new BlockCheck2OptionsViewModel(new MemorySettings(), () => running, () => selected); + + Assert.False(options.CanStart); + selected = 1; + Assert.True(options.CanStart); + running = true; + Assert.False(options.CanStart); + Assert.False(options.CanContinueFromTargets); + running = false; + selected = 0; + options.TargetInput = " example.com\nEXAMPLE.COM\r\n second.example "; + Assert.Equal(2, options.DirectTargetInputCount); + Assert.True(options.CanStart); + } + + [Fact] + public void SessionRequestPreservesSelectionsAndTargetSnapshotTiming() + { + var options = Create(new MemorySettings()); + options.TargetInput = "before.example"; + options.IncludeHttp = true; + options.IncludeTls12 = false; + options.IncludeIpv6 = true; + options.TestAllStrategies = true; + var siteList = new BlockCheckSiteListInput("List", "list.txt"); + + var request = options.CreateSessionRequest(() => + { + options.TargetInput = "after.example"; + options.SelectedRunPreset = BlockCheckRunPreset.Quick; + return new[] { siteList }; + }); + + Assert.Equal("before.example", request.TargetInput); + Assert.Equal(BlockCheckRunPreset.Quick, request.RunPreset); + Assert.Equal(2, request.AttemptsPerTarget); + Assert.True(request.TestAllStrategies); + Assert.Same(siteList, Assert.Single(request.SiteLists)); + Assert.True(request.Protocols.SetEquals([BlockCheckProtocol.Http, BlockCheckProtocol.TlsAuto])); + Assert.True(request.IpVersions.SetEquals([BlockCheckIpVersion.IPv4, BlockCheckIpVersion.IPv6])); + } + + private static BlockCheck2OptionsViewModel Create(MemorySettings settings) => new(settings, () => false, () => 0); + + private sealed class MemorySettings : IBlockCheck2OptionsSettings + { + public Dictionary Values { get; } = []; + public List<(string Key, object Value)> Writes { get; } = []; + public List Trace { get; } = []; + public int ReadInt(string key, int defaultValue) => Values.TryGetValue(key, out object? value) ? (int)value : defaultValue; + public bool ReadBool(string key, bool defaultValue) => Values.TryGetValue(key, out object? value) ? (bool)value : defaultValue; + public double ReadDouble(string key, double defaultValue) => Values.TryGetValue(key, out object? value) ? (double)value : defaultValue; + public void Save(string? key, int value) => Record(key, value); + public void Save(string? key, bool value) => Record(key, value); + public void Save(string? key, double value) => Record(key, value); + + private void Record(string? key, object value) + { + if (key == null) throw new InvalidOperationException("Setting key is required"); + Values[key] = value; + Writes.Add((key, value)); + Trace.Add("save:" + key); + } + } +} diff --git a/CDPIUI.Tests/Presentation/BlockCheck2ProgressTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2ProgressTests.cs new file mode 100644 index 00000000..b5ceef2c --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2ProgressTests.cs @@ -0,0 +1,283 @@ +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.ViewModels; + +namespace CDPIUI.Tests.Presentation; + +public class BlockCheck2ProgressTests +{ + private static readonly string[] UpdateNames = + [ + "CurrentPhase", "ProgressCurrent", "ProgressTotal", "ProgressValue", "IsProgressIndeterminate", + "CurrentTargetId", "CurrentTargetUrl", "CurrentTargetConnectionDetails", "CurrentTargetDisplay", + "CurrentStrategyId", "EstimatedRemainingTime", "EstimatedOverallRemainingTime", + "SuccessfulChecks", "FailedChecks", "CompletedChecks", "SuccessfulStrategies", + ]; + + [Fact] + public void ConstructionDoesNotReadLiveProvidersOrStartTheEstimator() + { + var fixture = new ProgressFixture(); + + Assert.Empty(fixture.Trace); + Assert.Null(fixture.Model.CurrentPhase); + Assert.True(fixture.Model.IsProgressIndeterminate); + Assert.Equal(0, fixture.Model.ProgressValue); + Assert.Equal("", fixture.Model.CurrentTargetId); + } + + [Fact] + public void UpdateAssignsFieldsBeforeReadingEstimatorInputsAndRaisesTheOriginalNotificationOrder() + { + var fixture = new ProgressFixture(); + fixture.Targets = [Target("target")]; + fixture.Attempts = 4; + fixture.Grace = 1.5; + fixture.Estimator.BeforeUpdate = () => + { + Assert.Equal("target", fixture.Model.CurrentTargetId); + Assert.Equal(3, fixture.Model.CompletedChecks); + Assert.Empty(fixture.Changes); + }; + + fixture.Model.Update(Progress()); + + Assert.Equal(["targets", "attempts", "grace", "estimate:1:4:1.5"], fixture.Trace); + Assert.Equal(UpdateNames, fixture.Changes); + Assert.Equal(BlockCheckScanPhase.Probing, fixture.Model.CurrentPhase); + Assert.Equal(2, fixture.Model.ProgressCurrent); + Assert.Equal(8, fixture.Model.ProgressTotal); + Assert.Equal(.25, fixture.Model.ProgressValue); + Assert.False(fixture.Model.IsProgressIndeterminate); + Assert.Equal("strategy", fixture.Model.CurrentStrategyId); + Assert.Equal(2, fixture.Model.SuccessfulChecks); + Assert.Equal(1, fixture.Model.FailedChecks); + Assert.Equal(1, fixture.Model.SuccessfulStrategies); + Assert.Equal(TimeSpan.FromSeconds(10), fixture.Model.EstimatedRemainingTime); + Assert.Equal(TimeSpan.FromSeconds(20), fixture.Model.EstimatedOverallRemainingTime); + } + + [Fact] + public void EveryNotificationObservesTheCompleteUpdatedSnapshot() + { + var fixture = new ProgressFixture(); + fixture.Model.PropertyChanged += (_, _) => + { + Assert.Equal(2, fixture.Model.ProgressCurrent); + Assert.Equal(1, fixture.Model.SuccessfulStrategies); + Assert.Equal(TimeSpan.FromSeconds(20), fixture.Model.EstimatedOverallRemainingTime); + }; + + fixture.Model.Update(Progress()); + } + + [Theory] + [InlineData(-2, 8, 0d, false)] + [InlineData(15, 8, 1d, false)] + [InlineData(2, 0, 0d, true)] + [InlineData(2, -1, 0d, true)] + public void DisplayedRatioClampsWithoutChangingRawCounts(int current, int total, double ratio, bool indeterminate) + { + var fixture = new ProgressFixture(); + + fixture.Model.Update(Progress() with { CompletedStrategyTargets = current, TotalStrategyTargets = total }); + + Assert.Equal(current, fixture.Model.ProgressCurrent); + Assert.Equal(total, fixture.Model.ProgressTotal); + Assert.Equal(ratio, fixture.Model.ProgressValue); + Assert.Equal(indeterminate, fixture.Model.IsProgressIndeterminate); + } + + [Fact] + public void TargetDisplayUsesTheLiveTargetListAndCaseSensitiveIdentifiers() + { + var fixture = new ProgressFixture(); + fixture.Targets = [Target("TARGET", "wrong.test"), Target("target")]; + fixture.Model.Update(Progress()); + + Assert.Equal("https://example.test/check", fixture.Model.CurrentTargetUrl); + Assert.Equal("TLS 1.3 · IPv6 · TCP:443", fixture.Model.CurrentTargetConnectionDetails); + Assert.Equal("https://example.test/check [TLS 1.3 · IPv6 · TCP:443]", fixture.Model.CurrentTargetDisplay); + fixture.Targets = []; + Assert.Equal("target", fixture.Model.CurrentTargetUrl); + Assert.Equal("", fixture.Model.CurrentTargetConnectionDetails); + Assert.Equal("target", fixture.Model.CurrentTargetDisplay); + } + + [Fact] + public void RepeatingTheSameProgressStillRaisesEveryNotificationAndReadsCurrentOptions() + { + var fixture = new ProgressFixture(); + fixture.Model.Update(Progress()); + fixture.Trace.Clear(); + fixture.Changes.Clear(); + fixture.Attempts = 9; + fixture.Grace = 3; + fixture.Targets = [Target("target"), Target("other")]; + + fixture.Model.Update(Progress()); + + Assert.Equal(UpdateNames, fixture.Changes); + Assert.Equal(["targets", "attempts", "grace", "estimate:2:9:3"], fixture.Trace); + } + + [Fact] + public void AReentrantProgressUpdateBecomesTheCurrentDisplayedState() + { + var fixture = new ProgressFixture(); + bool updated = false; + fixture.Model.PropertyChanged += (_, args) => + { + if (args.PropertyName != "CurrentPhase" || updated) return; + updated = true; + fixture.Model.Update(Progress() with { CompletedStrategyTargets = 5, TargetId = "inner" }); + }; + + fixture.Model.Update(Progress()); + + Assert.Equal(5, fixture.Model.ProgressCurrent); + Assert.Equal("inner", fixture.Model.CurrentTargetId); + Assert.Equal(32, fixture.Changes.Count); + Assert.Equal(2, fixture.Trace.Count(item => item.StartsWith("estimate:", StringComparison.Ordinal))); + } + + [Fact] + public void ResetClearsFieldsBeforeTheHostResultNotificationsAndThenNotifiesProgressInOriginalOrder() + { + var fixture = new ProgressFixture(); + fixture.Model.Update(Progress()); + fixture.Trace.Clear(); + fixture.Changes.Clear(); + + fixture.Model.Reset(() => + { + Assert.Empty(fixture.Changes); + Assert.Null(fixture.Model.CurrentPhase); + Assert.Equal(0, fixture.Model.CompletedChecks); + Assert.Equal("", fixture.Model.CurrentTargetId); + Assert.Null(fixture.Model.EstimatedRemainingTime); + fixture.Changes.Add("host-results"); + }); + + Assert.Equal(["reset-estimator"], fixture.Trace); + Assert.Equal(new[] { "host-results", "CurrentPhase", "ProgressCurrent", "ProgressTotal", "ProgressValue", "IsProgressIndeterminate", + "EstimatedRemainingTime", "EstimatedOverallRemainingTime", "SuccessfulChecks", "FailedChecks", "CompletedChecks", + "SuccessfulStrategies", "CurrentTargetId", "CurrentTargetUrl", "CurrentTargetConnectionDetails", "CurrentTargetDisplay", "CurrentStrategyId" }, fixture.Changes); + } + + [Fact] + public void StartingOnlyStartsTheEstimatorAndFinishingOnlyClearsTimeEstimates() + { + var fixture = new ProgressFixture(); + fixture.Model.Update(Progress()); + fixture.Trace.Clear(); + fixture.Changes.Clear(); + + fixture.Model.StartRun(); + Assert.Empty(fixture.Changes); + fixture.Model.FinishRun(); + + Assert.Equal(["start-estimator", "stop-estimator"], fixture.Trace); + Assert.Equal(["EstimatedRemainingTime", "EstimatedOverallRemainingTime"], fixture.Changes); + Assert.Null(fixture.Model.EstimatedRemainingTime); + Assert.Null(fixture.Model.EstimatedOverallRemainingTime); + Assert.Equal(2, fixture.Model.ProgressCurrent); + Assert.Equal("target", fixture.Model.CurrentTargetId); + } + + [Fact] + public void CompletingOnlyChangesDisplayedProgressAndStillNotifiesWhenAlreadyComplete() + { + var fixture = new ProgressFixture(); + fixture.Model.Update(Progress()); + fixture.Changes.Clear(); + + fixture.Model.CompleteDisplayedProgress(); + fixture.Model.CompleteDisplayedProgress(); + + Assert.Equal(8, fixture.Model.ProgressCurrent); + Assert.Equal(1, fixture.Model.ProgressValue); + Assert.Equal(3, fixture.Model.CompletedChecks); + Assert.Equal(["ProgressCurrent", "ProgressValue", "ProgressCurrent", "ProgressValue"], fixture.Changes); + } + + [Fact] + public void CompletingIndeterminateProgressDoesNotNotify() + { + var fixture = new ProgressFixture(); + + fixture.Model.CompleteDisplayedProgress(); + + Assert.Empty(fixture.Trace); + Assert.Empty(fixture.Changes); + } + + [Fact] + public void AnEstimatorFailurePropagatesWithAssignedFieldsAndNoPartialNotifications() + { + var fixture = new ProgressFixture(); + fixture.Estimator.Error = new IOException("estimate failed"); + + Assert.Throws(() => fixture.Model.Update(Progress())); + + Assert.Equal("target", fixture.Model.CurrentTargetId); + Assert.Equal(2, fixture.Model.ProgressCurrent); + Assert.Null(fixture.Model.EstimatedRemainingTime); + Assert.Empty(fixture.Changes); + } + + [Fact] + public void DefaultEstimatorRemainsConnectedToTheRealProductionImplementation() + { + var model = new BlockCheck2ProgressViewModel(() => [], () => 3, () => 1d); + model.StartRun(); + + model.Update(Progress() with { Phase = BlockCheckScanPhase.BaselineProbing, CompletedStrategyTargets = 8 }); + + Assert.Equal(TimeSpan.Zero, model.EstimatedRemainingTime); + Assert.Null(model.EstimatedOverallRemainingTime); + model.FinishRun(); + Assert.Null(model.EstimatedRemainingTime); + } + + private static BlockCheckScanProgress Progress() => new(BlockCheckScanPhase.Probing, 2, 8, "target", "strategy", + SuccessfulChecks: 2, FailedChecks: 1, SuccessfulStrategies: 1); + private static BlockCheckTarget Target(string id, string host = "example.test") => new() + { + Id = id, Host = host, Path = "check", Protocol = BlockCheckProtocol.Tls13, IpVersion = BlockCheckIpVersion.IPv6, + }; + + private sealed class ProgressFixture + { + public ProgressFixture() + { + Estimator = new(Trace); + Model = new(() => { Trace.Add("targets"); return Targets; }, + () => { Trace.Add("attempts"); return Attempts; }, + () => { Trace.Add("grace"); return Grace; }, Estimator); + Model.PropertyChanged += (_, args) => Changes.Add(args.PropertyName!); + } + public List Trace { get; } = []; + public List Changes { get; } = []; + public IReadOnlyList Targets { get; set; } = []; + public int Attempts { get; set; } = 3; + public double Grace { get; set; } = 1; + public EstimatorFake Estimator { get; } + public BlockCheck2ProgressViewModel Model { get; } + } + + private sealed class EstimatorFake(List trace) : IBlockCheck2ProgressEstimator + { + public Action? BeforeUpdate { get; set; } + public Exception? Error { get; set; } + public void StartRun() => trace.Add("start-estimator"); + public void StopRun() => trace.Add("stop-estimator"); + public void ResetObservations() => trace.Add("reset-estimator"); + public (TimeSpan? Stage, TimeSpan? Overall) Update(BlockCheckScanProgress progress, int targetCount, int attempts, double grace) + { + trace.Add(FormattableString.Invariant($"estimate:{targetCount}:{attempts}:{grace}")); + BeforeUpdate?.Invoke(); + if (Error != null) throw Error; + return (TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(20)); + } + } +} diff --git a/CDPIUI.Tests/Presentation/BlockCheck2ReportExportTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2ReportExportTests.cs new file mode 100644 index 00000000..384a7134 --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2ReportExportTests.cs @@ -0,0 +1,265 @@ +using CDPIUI.AddOns.BlockCheck2.Reporting; +using CDPIUI.ViewModels.BlockCheck2; + +namespace CDPIUI.Tests.Presentation; + +public class BlockCheck2ReportExportTests +{ + [Fact] + public void ConstructionDoesNotReadReportOrUseView() + { + var f = new Fixture(); + Assert.Empty(f.Trace); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task NullReportStopsBeforeLocalizationPickerOrSave(bool json) + { + var f = new Fixture { Report = null }; + await f.Run(json); + Assert.Equal(["report"], f.Trace); + } + + [Theory] + [InlineData(true, "blockcheck2-report.json", "BlockCheck2JsonFileFilter", "json")] + [InlineData(false, "blockcheck2-report.txt", "BlockCheck2TextFileFilter", "text")] + public async Task SaveUsesExactPickerArgumentsAndPublishesAfterAwait(bool json, string defaultName, string filterKey, string endpoint) + { + var f = new Fixture(); + await f.Run(json); + Assert.Equal(("t:BlockCheck2SaveReportDialogTitle", defaultName, "t:" + filterKey), Assert.Single(f.Picks)); + Assert.Equal(["report", "text:BlockCheck2SaveReportDialogTitle", "text:" + filterKey, "pick", "report", endpoint, + "text:BlockCheck2ActionCompletedTitle", "text:BlockCheck2FileSavedMessage", "show"], f.Trace); + var saved = Assert.Single(f.Saved); + Assert.Equal(json, saved.Json); + Assert.Equal("chosen.path", saved.Path); + Assert.Same(f.Report, saved.Report); + Assert.Equal((BlockCheck2NoticeSeverity.Success, "t:BlockCheck2ActionCompletedTitle", "t:BlockCheck2FileSavedMessage"), Assert.Single(f.Notices)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task PickerCancelDoesNotRereadReportOrSave(bool json) + { + var f = new Fixture { Path = null }; + await f.Run(json); + Assert.Single(f.Picks); + Assert.Single(f.Trace, name => name == "report"); + Assert.Empty(f.Saved); + Assert.Empty(f.Notices); + Assert.Empty(f.Errors); + } + + [Theory] + [InlineData(true, "")] + [InlineData(false, " ")] + public async Task NonNullFilenameIsPassedWithoutTrimmingOrValidation(bool json, string path) + { + var f = new Fixture { Path = path }; + await f.Run(json); + Assert.Equal(path, Assert.Single(f.Saved).Path); + Assert.Single(f.Notices); + } + + // Detects snapshotting report at the null guard or reading it again before picker completion. + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task PickerUsesCurrentReportAfterLocalizationRemovedTheOriginal(bool json) + { + var f = new Fixture(); + var current = new BlockCheckReport { CatalogVersion = "current" }; + f.OnCall = name => + { + if (name == "text:BlockCheck2SaveReportDialogTitle") f.Report = null; + if (name == "pick") f.Report = current; + }; + await f.Run(json); + Assert.Same(current, Assert.Single(f.Saved).Report); + Assert.Equal(2, f.ReportReads); + } + + [Fact] + public async Task ReportRemovedByPickerReachesSaveInsideCatch() + { + var f = new Fixture(); var missing = new ArgumentNullException("report", "missing current report"); + f.OnCall = name => { if (name == "pick") f.Report = null; }; + f.Save = (_, report) => report == null ? throw missing : Task.CompletedTask; + await f.Run(true); + Assert.Null(Assert.Single(f.Saved).Report); + Assert.Equal([missing.Message], f.Errors); + Assert.Empty(f.Notices); + } + + [Theory] + [InlineData(true, "report")] + [InlineData(false, "report")] + [InlineData(true, "text:BlockCheck2SaveReportDialogTitle")] + [InlineData(false, "text:BlockCheck2SaveReportDialogTitle")] + [InlineData(true, "text:BlockCheck2JsonFileFilter")] + [InlineData(false, "text:BlockCheck2TextFileFilter")] + [InlineData(true, "pick")] + [InlineData(false, "pick")] + public async Task SetupFaultEscapesWithoutErrorNotice(bool json, string endpoint) + { + var f = new Fixture(); var fault = new InvalidOperationException("setup fault"); + f.OnCall = name => { if (name == endpoint) throw fault; }; + Task exported = f.Run(json); + Assert.Same(fault, await Assert.ThrowsAsync(() => exported)); + Assert.Empty(f.Errors); + Assert.Empty(f.Notices); + Assert.Empty(f.Saved); + } + + [Fact] + public async Task SecondReportReadFaultIsCaughtInsideSave() + { + var f = new Fixture(); + f.OnCall = name => { if (name == "report" && f.ReportReads == 2) throw new InvalidOperationException("current report fault"); }; + await f.Run(false); + Assert.Equal(["current report fault"], f.Errors); + Assert.Empty(f.Saved); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task SynchronousOrPendingSaveFaultShowsErrorWithoutSuccess(bool pending) + { + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var fault = new IOException("save fault"); + var f = new Fixture { Save = (_, _) => pending ? completion.Task : throw fault }; + Task task = f.Run(true); + if (pending) + { + Assert.False(task.IsCompleted); + Assert.Empty(f.Errors); + completion.SetException(fault); + } + await task; + Assert.Equal(["save fault"], f.Errors); + Assert.Empty(f.Notices); + Assert.DoesNotContain("text:BlockCheck2ActionCompletedTitle", f.Trace); + } + + [Fact] + public async Task ConcurrentExportsKeepIndependentPathsReportsAndCompletionOrder() + { + var jsonDone = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var textDone = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var f = new Fixture { Path = "first.json", Save = (path, _) => path == "first.json" ? jsonDone.Task : textDone.Task }; + var firstReport = f.Report; + Task first = f.Run(true); + f.Path = "second.txt"; f.Report = new() { CatalogVersion = "second" }; + Task second = f.Run(false); + Assert.False(first.IsCompleted); + Assert.False(second.IsCompleted); + Assert.Equal(2, f.Picks.Count); + Assert.Empty(f.Notices); + Assert.DoesNotContain("text:BlockCheck2ActionCompletedTitle", f.Trace); + Assert.DoesNotContain("text:BlockCheck2FileSavedMessage", f.Trace); + textDone.SetResult(); await second; + Assert.False(first.IsCompleted); + Assert.Single(f.Notices); + jsonDone.SetResult(); await first; + Assert.Equal(2, f.Notices.Count); + Assert.Equal((true, "first.json", firstReport), f.Saved[0]); + Assert.Equal((false, "second.txt", f.Report), f.Saved[1]); + Assert.Equal(4, f.ReportReads); + } + + [Fact] + public async Task PickerCanReenterTextExportBeforeOuterJsonSave() + { + var f = new Fixture(); Task? nested = null; + f.Pick = (_, name, _) => + { + if (name == "blockcheck2-report.json") { nested = f.Run(false); return "outer.json"; } + return "inner.txt"; + }; + await f.Run(true); await nested!; + Assert.Equal(["inner.txt", "outer.json"], f.Saved.Select(entry => entry.Path)); + Assert.Equal([false, true], f.Saved.Select(entry => entry.Json)); + Assert.Equal(2, f.Notices.Count); + } + + [Fact] + public async Task CanceledSaveIsReportedAndOuterTaskCompletesSuccessfully() + { + using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); + Task canceled = Task.FromCanceled(cancellation.Token); + var fault = await Assert.ThrowsAsync(() => canceled); + var f = new Fixture { Save = (_, _) => canceled }; + Task outer = f.Run(false); await outer; + Assert.True(outer.IsCompletedSuccessfully); + Assert.Equal([fault.Message], f.Errors); + Assert.Empty(f.Notices); + } + + [Theory] + [InlineData("text:BlockCheck2ActionCompletedTitle")] + [InlineData("text:BlockCheck2FileSavedMessage")] + [InlineData("show")] + public async Task SuccessLocalizationOrNoticeFaultIsCaughtAndReported(string endpoint) + { + var f = new Fixture(); + f.OnCall = name => { if (name == endpoint) throw new InvalidOperationException("success fault"); }; + await f.Run(true); + Assert.Single(f.Saved); + Assert.Equal(["success fault"], f.Errors); + Assert.Equal("error:success fault", f.Trace.Last()); + } + + [Fact] + public async Task ErrorCallbackFaultEscapesWithIdentityAndWithoutRetry() + { + var f = new Fixture { Save = (_, _) => throw new IOException("write failed") }; + var errorFault = new InvalidOperationException("error callback fault"); + f.OnCall = name => { if (name.StartsWith("error:")) throw errorFault; }; + Task exported = f.Run(true); + Assert.Same(errorFault, await Assert.ThrowsAsync(() => exported)); + Assert.Equal(["write failed"], f.Errors); + Assert.Single(f.Saved); + } + + [Fact] + public async Task PrivateHelperConsumerCanSaveWithoutReportOrPicker() + { + var f = new Fixture { Report = null }; bool saved = false; + await f.Owner.SaveAsync(() => { saved = true; return Task.CompletedTask; }); + Assert.True(saved); + Assert.Equal(["text:BlockCheck2ActionCompletedTitle", "text:BlockCheck2FileSavedMessage", "show"], f.Trace); + Assert.Empty(f.Picks); + } + + private sealed class Fixture + { + internal readonly List Trace = []; + internal readonly List<(string Title, string Name, string Filter)> Picks = []; + internal readonly List<(bool Json, string Path, BlockCheckReport? Report)> Saved = []; + internal readonly List<(BlockCheck2NoticeSeverity Severity, string Title, string Message)> Notices = []; + internal readonly List Errors = []; + internal BlockCheckReport? Report = new() { CatalogVersion = "initial" }; + internal string? Path = "chosen.path"; + internal int ReportReads; + internal Action? OnCall; + internal Func? Pick; + internal Func Save = (_, _) => Task.CompletedTask; + internal readonly BlockCheck2ReportExport Owner; + internal Fixture() + { + Owner = new(() => { ReportReads++; Call("report"); return Report; }, + (title, name, filter) => { Picks.Add((title, name, filter)); Call("pick"); return Pick == null ? Path : Pick(title, name, filter); }, + (path, report) => { Saved.Add((true, path, report)); Call("json"); return Save(path, report); }, + (path, report) => { Saved.Add((false, path, report)); Call("text"); return Save(path, report); }, + key => { Call("text:" + key); return "t:" + key; }, + (severity, title, message) => { Notices.Add((severity, title, message)); Call("show"); }, + message => { Errors.Add(message); Call("error:" + message); }); + } + internal Task Run(bool json) => json ? Owner.SaveJsonAsync() : Owner.SaveTextAsync(); + private void Call(string endpoint) { Trace.Add(endpoint); OnCall?.Invoke(endpoint); } + } +} diff --git a/CDPIUI.Tests/Presentation/BlockCheck2ReportSummaryPresenterTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2ReportSummaryPresenterTests.cs new file mode 100644 index 00000000..f158e8e8 --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2ReportSummaryPresenterTests.cs @@ -0,0 +1,143 @@ +using CDPIUI.ViewModels.BlockCheck2; + +namespace CDPIUI.Tests.Presentation; + +public class BlockCheck2ReportSummaryPresenterTests +{ + [Fact] + public void ConstructorDoesNotReadStateLocalizeOrShow() + { + var f = new Fixture(); Assert.Empty(f.Trace); Assert.Empty(f.Notices); + } + + [Fact] + public void MissingReportLocalizesEmptyTitleThenMessageWithoutReadingOtherFlags() + { + var f = new Fixture { HasReport = false, NoBypass = true, Success = true, Best = true, Http = true }; + f.Owner.Show(); + Assert.Equal(["has", "text:BlockCheck2ResultEmptyTitle", "text:BlockCheck2ResultEmptyMessage", "show"], f.Trace); + Assert.Equal((BlockCheck2NoticeSeverity.Error, "t:BlockCheck2ResultEmptyTitle", "t:BlockCheck2ResultEmptyMessage"), Assert.Single(f.Notices)); + } + + [Theory] + [InlineData(true, false, false, false, BlockCheck2NoticeSeverity.Informational, "BlockCheck2NoBypassRequiredTitle", "BlockCheck2NoBypassRequiredMessage")] + [InlineData(true, true, true, true, BlockCheck2NoticeSeverity.Informational, "BlockCheck2NoBypassRequiredTitle", "BlockCheck2HttpOnlyNoBypassRequiredMessage")] + [InlineData(false, true, true, true, BlockCheck2NoticeSeverity.Success, "BlockCheck2ResultSuccessTitle", "BlockCheck2ResultSuccessMessage")] + [InlineData(false, false, true, true, BlockCheck2NoticeSeverity.Warning, "BlockCheck2ResultBestEffortTitle", "BlockCheck2ResultBestEffortMessage")] + [InlineData(false, false, false, true, BlockCheck2NoticeSeverity.Warning, "BlockCheck2ResultPartialTitle", "BlockCheck2ResultPartialMessage")] + public void PopulatedBranchesRetainPrecedenceAndLiteralResourceKeys(bool noBypass, bool success, bool best, bool http, + BlockCheck2NoticeSeverity severity, string title, string message) + { + var f = new Fixture { NoBypass = noBypass, Success = success, Best = best, Http = http }; + f.Owner.Show(); + Assert.Equal((severity, "t:" + title, "t:" + message), Assert.Single(f.Notices)); + Assert.Equal(noBypass, f.Trace.Contains("http")); + if (noBypass) { Assert.DoesNotContain("success", f.Trace); Assert.DoesNotContain("best", f.Trace); } + } + + [Fact] + public void SuccessReadsFlagsAgainForTitleAndMessageInOriginalOrder() + { + var f = new Fixture { Success = true }; f.Owner.Show(); + Assert.Equal(["has", "no-bypass", "success", "no-bypass", "success", "text:BlockCheck2ResultSuccessTitle", + "no-bypass", "success", "text:BlockCheck2ResultSuccessMessage", "show"], f.Trace); + } + + [Fact] + public void NoBypassReadsHttpOnlyAfterLocalizingTitle() + { + var f = new Fixture { NoBypass = true }; f.Owner.Show(); + Assert.Equal(["has", "no-bypass", "no-bypass", "text:BlockCheck2NoBypassRequiredTitle", + "no-bypass", "http", "text:BlockCheck2NoBypassRequiredMessage", "show"], f.Trace); + } + + [Fact] + public void TitleLocalizationCanChangeMessagePolicyWithoutRecomputingSeverityOrTitle() + { + var f = new Fixture(); + f.OnStep = s => { if (s == "text:BlockCheck2ResultPartialTitle") { f.NoBypass = true; f.Http = true; } }; + f.Owner.Show(); + Assert.Equal((BlockCheck2NoticeSeverity.Warning, "t:BlockCheck2ResultPartialTitle", "t:BlockCheck2HttpOnlyNoBypassRequiredMessage"), Assert.Single(f.Notices)); + } + + [Fact] + public void BestEffortIsReadAgainAfterTitleLocalizationChangesOnlyThatFlag() + { + var f = new Fixture(); + f.OnStep = s => { if (s == "text:BlockCheck2ResultPartialTitle") f.Best = true; }; + f.Owner.Show(); + Assert.Equal((BlockCheck2NoticeSeverity.Warning, "t:BlockCheck2ResultPartialTitle", "t:BlockCheck2ResultBestEffortMessage"), Assert.Single(f.Notices)); + Assert.Equal(2, f.Trace.Count(s => s == "best")); + Assert.True(f.Trace.IndexOf("best") < f.Trace.IndexOf("text:BlockCheck2ResultPartialTitle")); + Assert.True(f.Trace.LastIndexOf("best") > f.Trace.IndexOf("text:BlockCheck2ResultPartialTitle")); + } + + [Fact] + public void EmptyBranchDoesNotRecheckReportAfterTitleLocalization() + { + var f = new Fixture { HasReport = false }; + f.OnStep = s => { if (s == "text:BlockCheck2ResultEmptyTitle") { f.HasReport = true; f.Success = true; } }; + f.Owner.Show(); + Assert.Equal(BlockCheck2NoticeSeverity.Error, Assert.Single(f.Notices).Severity); + Assert.DoesNotContain("success", f.Trace); Assert.Equal(1, f.Trace.Count(s => s == "has")); + } + + [Fact] + public void ShowCallbackCanReenterAndNextCallReadsCurrentFlagsWithoutGuard() + { + var f = new Fixture { Success = true }; bool nested = false; + f.OnStep = s => { if (s == "show" && !nested) { nested = true; f.HasReport = false; f.Owner.Show(); } }; + f.Owner.Show(); + Assert.Equal([BlockCheck2NoticeSeverity.Success, BlockCheck2NoticeSeverity.Error], f.Notices.Select(n => n.Severity)); + Assert.Equal(2, f.Trace.Count(s => s == "has")); + } + + [Theory] + [InlineData("has")] + [InlineData("no-bypass")] + [InlineData("success")] + [InlineData("best")] + [InlineData("text:BlockCheck2ResultPartialTitle")] + [InlineData("text:BlockCheck2ResultPartialMessage")] + public void ReadOrLocalizationFaultPropagatesSameExceptionWithoutShowingPartialNotice(string failing) + { + var f = new Fixture(); var error = new IOException(failing); + f.OnStep = s => { if (s == failing) throw error; }; + Assert.Same(error, Assert.Throws(() => f.Owner.Show())); + Assert.Equal(failing, f.Trace.Last()); Assert.Empty(f.Notices); + } + + [Fact] + public void HttpFaultPropagatesAfterTitleWithoutShowing() + { + var f = new Fixture { NoBypass = true }; var error = new IOException("http"); + f.OnStep = s => { if (s == "http") throw error; }; + Assert.Same(error, Assert.Throws(() => f.Owner.Show())); + Assert.Contains("text:BlockCheck2NoBypassRequiredTitle", f.Trace); Assert.Empty(f.Notices); + } + + [Fact] + public void ShowFailureEscapesWithoutRetry() + { + var f = new Fixture(); var error = new IOException("show"); f.OnStep = s => { if (s == "show") throw error; }; + Assert.Same(error, Assert.Throws(() => f.Owner.Show())); + Assert.Single(f.Notices); Assert.Equal(1, f.Trace.Count(s => s == "show")); + } + + private sealed class Fixture + { + public bool HasReport = true, NoBypass, Success, Best, Http; + public readonly List Trace = []; + public readonly List<(BlockCheck2NoticeSeverity Severity, string Title, string Message)> Notices = []; + public Action? OnStep; + public readonly BlockCheck2ReportSummaryPresenter Owner; + public Fixture() + { + Owner = new(() => { Step("has"); return HasReport; }, () => { Step("no-bypass"); return NoBypass; }, + () => { Step("success"); return Success; }, () => { Step("best"); return Best; }, + () => { Step("http"); return Http; }, key => { Step("text:" + key); return "t:" + key; }, + (severity, title, message) => { Notices.Add((severity, title, message)); Step("show"); }); + } + private void Step(string s) { Trace.Add(s); OnStep?.Invoke(s); } + } +} diff --git a/CDPIUI.Tests/Presentation/BlockCheck2ResultSelectionTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2ResultSelectionTests.cs new file mode 100644 index 00000000..edc0ab24 --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2ResultSelectionTests.cs @@ -0,0 +1,244 @@ +using System.Globalization; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.ViewModels; +using CDPIUI.ViewModels.BlockCheck2; + +namespace CDPIUI.Tests.Presentation; + +public class BlockCheck2ResultSelectionTests +{ + [Fact] + public void ConstructorKeepsColdDefaultsWithoutReadingAnyPort() + { + var f = new Fixture(); + Assert.Empty(f.Trace); + Assert.True(f.Owner.IsDetailsHitTestVisible && f.Owner.IsTestStrategyEnabled && f.Owner.IsManualTestEnabled); + Assert.True(f.Owner.IsAddForSiteEnabled && f.Owner.IsAddForListEnabled); + Assert.False(f.Owner.IsManualTestChecked); + Assert.Equal("", f.Owner.ManualTestLabel); Assert.Equal("\uE768", f.Owner.ManualTestGlyph); + Assert.Equal(["", "", "", "", "", "", ""], Details(f.Owner)); + } + + [Theory] + [InlineData(false, false, true, false, "PresetTestConfirmButton", "\uE768")] + [InlineData(false, true, true, true, "StopTest", "\uE769")] + [InlineData(true, false, false, false, "PresetTestConfirmButton", "\uE768")] + [InlineData(true, true, true, true, "StopTest", "\uE769")] + public void SelectedSessionRetainsRunningAndManualActionPolicy(bool running, bool manual, bool manualEnabled, + bool checkedValue, string label, string glyph) + { + var f = new Fixture { Item = Item("a"), Running = running, Manual = manual }; + f.Owner.Update(); + Assert.Equal(!running, f.Owner.IsDetailsHitTestVisible); + Assert.Equal(!running, f.Owner.IsTestStrategyEnabled); + Assert.Equal(manualEnabled, f.Owner.IsManualTestEnabled); + Assert.Equal(checkedValue, f.Owner.IsManualTestChecked); + Assert.Equal(label, f.Owner.ManualTestLabel); Assert.Equal(glyph, f.Owner.ManualTestGlyph); + Assert.Equal(!running, f.Owner.IsAddForSiteEnabled); Assert.Equal(!running, f.Owner.IsAddForListEnabled); + Assert.Same(f.Item, Assert.Single(f.ListItems)); + Assert.Equal("Strategy a", f.Owner.SelectedStrategyName); Assert.Equal("--a", f.Owner.SelectedStrategyArguments); + Assert.Equal("https://a.test/", f.Owner.SelectedSite); + } + + [Fact] + public void ItemWithoutSessionStillShowsDetailsButSkipsRunningAndListPorts() + { + var f = new Fixture { Item = Item("a"), HasSession = false, Running = true, Manual = true }; + f.Owner.Update(); + Assert.False(f.Owner.IsDetailsHitTestVisible || f.Owner.IsTestStrategyEnabled || f.Owner.IsManualTestEnabled); + Assert.False(f.Owner.IsAddForSiteEnabled || f.Owner.IsAddForListEnabled); + Assert.Equal("a", f.Owner.SelectedStrategyId); Assert.Equal("--a", f.Owner.SelectedStrategyArguments); + Assert.DoesNotContain("running", f.Trace); Assert.DoesNotContain("manual", f.Trace); Assert.Empty(f.ListItems); + } + + [Fact] + public void NullSelectionSkipsSessionAndResetsEveryDetailAfterMenu() + { + var f = new Fixture { Item = Item("a") }; f.Owner.Update(); f.ResetTrace(); f.Item = null; + f.Owner.Update(); + Assert.Equal(["BlockCheck2SelectStrategyText", "", "", "", "", "", ""], Details(f.Owner)); + Assert.DoesNotContain("session", f.Trace); + Assert.True(f.Trace.IndexOf("menu") < f.Trace.IndexOf("text:BlockCheck2SelectStrategyText")); + Assert.False(f.Owner.IsManualTestChecked); + } + + [Fact] + public void UpdatePreservesLiteralPortAndNotificationOrder() + { + var f = new Fixture { Item = Item("a") }; f.Owner.Update(); + Assert.Equal(["selected", "session", "running", "running", "running", "manual", + "text:PresetTestConfirmButton", "p:ManualTestLabel", "running", "list", "running", "menu", + "p:SelectedStrategyName", "p:SelectedStrategyId", "p:SelectedStrategyArguments", "p:SelectedSite", + "p:SelectedConnection", "p:SelectedEvidence", "text:BlockCheck2BaselineEvidenceFormat", "p:SelectedBaseline"], f.Trace); + } + + [Fact] + public void ListPredicateRunsEvenWhenStrategyTestIsRunningAndFalseSkipsFinalRunningRead() + { + var f = new Fixture { Item = Item("a"), Running = true, CanList = false }; + f.Owner.Update(); + Assert.Same(f.Item, Assert.Single(f.ListItems)); + Assert.Equal("p:IsAddForListEnabled", f.Trace[f.Trace.IndexOf("list") + 1]); + Assert.Equal("menu", f.Trace[f.Trace.IndexOf("list") + 2]); + } + + [Fact] + public void NotificationCanChangeRunningBeforeLaterActionGuards() + { + var f = new Fixture { Item = Item("a") }; + f.OnStep = step => { if (step == "p:ManualTestLabel") f.Running = true; }; + f.Owner.Update(); + Assert.True(f.Owner.IsDetailsHitTestVisible && f.Owner.IsTestStrategyEnabled && f.Owner.IsManualTestEnabled); + Assert.False(f.Owner.IsAddForSiteEnabled || f.Owner.IsAddForListEnabled); + } + + [Fact] + public void ManualStateIsRereadAfterEnabledNotification() + { + var f = new Fixture { Item = Item("a"), Running = true }; + f.OnStep = step => { if (step == "p:IsManualTestEnabled") f.Manual = true; }; + f.Owner.Update(); + Assert.False(f.Owner.IsManualTestEnabled); Assert.True(f.Owner.IsManualTestChecked); + Assert.Equal("StopTest", f.Owner.ManualTestLabel); Assert.Equal("\uE769", f.Owner.ManualTestGlyph); + } + + [Fact] + public void MenuMutationDoesNotReplaceCapturedItemButNextUpdateReadsFreshItemAndSession() + { + var a = Item("a"); var b = Item("b"); var f = new Fixture { Item = a }; + f.OnStep = step => { if (step == "menu") { f.Item = b; f.HasSession = false; } }; + f.Owner.Update(); Assert.Equal("a", f.Owner.SelectedStrategyId); Assert.Same(a, Assert.Single(f.ListItems)); + f.OnStep = null; f.ResetTrace(); f.Owner.Update(); + Assert.Equal("b", f.Owner.SelectedStrategyId); Assert.False(f.Owner.IsTestStrategyEnabled); Assert.Empty(f.ListItems); + } + + [Fact] + public void MenuCanReenterAndOuterDetailsResumeWithOriginalItem() + { + var f = new Fixture { Item = Item("a") }; bool nested = false; List ids = []; + f.OnStep = step => + { + if (step == "menu" && !nested) { nested = true; f.Item = Item("b"); f.Owner.Update(); } + if (step == "p:SelectedStrategyId") ids.Add(f.Owner.SelectedStrategyId); + }; + f.Owner.Update(); + Assert.Equal(["b", "a"], ids); Assert.Equal("a", f.Owner.SelectedStrategyId); + Assert.Equal(2, f.Trace.Count(s => s == "menu")); + } + + [Fact] + public void EqualUpdateStillReadsTextAndNotifiesMenuButDoesNotPublishPropertyChanges() + { + var f = new Fixture { Item = Item("a") }; f.Owner.Update(); f.ResetTrace(); f.Owner.Update(); + Assert.DoesNotContain(f.Trace, s => s.StartsWith("p:", StringComparison.Ordinal)); + Assert.Equal(1, f.Trace.Count(s => s == "menu")); + Assert.Contains("text:BlockCheck2BaselineEvidenceFormat", f.Trace); + } + + [Fact] + public void NullableTwoWayCheckUsesEqualityAndAcceptsNull() + { + var f = new Fixture(); f.Owner.IsManualTestChecked = null; f.Owner.IsManualTestChecked = null; + Assert.Null(f.Owner.IsManualTestChecked); Assert.Equal(["p:IsManualTestChecked"], f.Trace); + f.Owner.IsManualTestChecked = false; + Assert.Equal(["p:IsManualTestChecked", "p:IsManualTestChecked"], f.Trace); + } + + [Fact] + public void LabelObserverCanResetNullableCheckBeforeGlyphIsChosen() + { + var f = new Fixture { Item = Item("a"), Manual = true }; + f.OnStep = step => { if (step == "p:ManualTestLabel") f.Owner.IsManualTestChecked = null; }; + f.Owner.Update(); + Assert.Equal("StopTest", f.Owner.ManualTestLabel); + Assert.Null(f.Owner.IsManualTestChecked); + Assert.Equal("\uE768", f.Owner.ManualTestGlyph); + Assert.DoesNotContain("p:ManualTestGlyph", f.Trace); + } + + [Theory] + [InlineData("selected")] + [InlineData("session")] + [InlineData("running")] + [InlineData("manual")] + [InlineData("text:PresetTestConfirmButton")] + [InlineData("list")] + [InlineData("menu")] + [InlineData("p:SelectedStrategyName")] + [InlineData("p:SelectedStrategyId")] + [InlineData("text:BlockCheck2BaselineEvidenceFormat")] + public void PortOrObserverFailurePropagatesSameExceptionAndStopsAtExactStage(string failing) + { + var f = new Fixture { Item = Item("a") }; var error = new IOException(failing); + f.OnStep = step => { if (step == failing) throw error; }; + Assert.Same(error, Assert.Throws(() => f.Owner.Update())); + Assert.Equal(failing, f.Trace.Last()); + Assert.Equal("", f.Owner.SelectedBaseline); + if (failing == "p:SelectedStrategyId") + { Assert.Equal("a", f.Owner.SelectedStrategyId); Assert.Equal("", f.Owner.SelectedStrategyArguments); } + } + + [Fact] + public void FormatFailureKeepsSixPublishedDetailsAndPreviousBaseline() + { + var f = new Fixture { Item = Item("a") }; f.Owner.Update(); string baseline = f.Owner.SelectedBaseline; + f.Item = Item("b"); f.Format = "{3}"; + Assert.Throws(() => f.Owner.Update()); + Assert.Equal("b", f.Owner.SelectedStrategyId); Assert.Equal("--b", f.Owner.SelectedStrategyArguments); + Assert.Equal(baseline, f.Owner.SelectedBaseline); + } + + [Fact] + public void NullBranchLocalizationFailureKeepsPreviousDetailsAfterActionFlagsChange() + { + var f = new Fixture { Item = Item("a") }; f.Owner.Update(); f.Item = null; + var error = new IOException("choose"); f.OnStep = s => { if (s == "text:BlockCheck2SelectStrategyText") throw error; }; + Assert.Same(error, Assert.Throws(() => f.Owner.Update())); + Assert.False(f.Owner.IsTestStrategyEnabled); Assert.Equal("a", f.Owner.SelectedStrategyId); + } + + [Fact] + public void DetailFormattingUsesCurrentCultureAndRealEvidenceAtEachUpdate() + { + CultureInfo previous = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); + var f = new Fixture { Item = Item("a") }; f.Owner.Update(); string first = f.Owner.SelectedBaseline; + Assert.Equal("base(" + f.Item.BaselineText + ")", first); + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("sv-SE"); f.Owner.Update(); + Assert.Equal("base(" + f.Item.BaselineText + ")", f.Owner.SelectedBaseline); + } + finally { CultureInfo.CurrentCulture = previous; } + } + + private static string[] Details(BlockCheck2ResultSelection s) => [s.SelectedStrategyName, s.SelectedStrategyId, + s.SelectedStrategyArguments, s.SelectedSite, s.SelectedConnection, s.SelectedEvidence, s.SelectedBaseline]; + private static BlockCheck2StrategyEvidenceItem Item(string id) => new(new() + { + Strategy = new() { Id = id, DisplayName = "Strategy " + id }, StrategyArguments = "--" + id, + Target = new() { Id = id, Host = id + ".test", Protocol = BlockCheckProtocol.Tls12, IpVersion = BlockCheckIpVersion.IPv4 }, + }); + + private sealed class Fixture + { + public readonly List Trace = []; + public readonly List ListItems = []; + public BlockCheck2StrategyEvidenceItem? Item; + public bool HasSession = true, Running, Manual, CanList = true; + public string Format = "base({0})"; + public Action? OnStep; + public readonly BlockCheck2ResultSelection Owner; + public Fixture() + { + Owner = new(() => { Step("selected"); return Item; }, () => { Step("session"); return HasSession; }, + () => { Step("running"); return Running; }, () => { Step("manual"); return Manual; }, + item => { ListItems.Add(item); Step("list"); return CanList; }, + key => { Step("text:" + key); return key == "BlockCheck2BaselineEvidenceFormat" ? Format : key; }, + () => Step("menu")); + Owner.PropertyChanged += (sender, e) => { Assert.Same(Owner, sender); Step("p:" + e.PropertyName); }; + } + public void ResetTrace() { Trace.Clear(); ListItems.Clear(); } + private void Step(string step) { Trace.Add(step); OnStep?.Invoke(step); } + } +} diff --git a/CDPIUI.Tests/Presentation/BlockCheck2ResultTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2ResultTests.cs new file mode 100644 index 00000000..3a2e47a5 --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2ResultTests.cs @@ -0,0 +1,472 @@ +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.AddOns.BlockCheck2.Reporting; +using CDPIUI.ViewModels; + +namespace CDPIUI.Tests.Presentation; + +public class BlockCheck2ResultTests +{ + private static readonly string[] ResultNotifications = + [ + "Issues", "LastResult", "LastReport", "LastSession", "NoBypassRequired", "LastReportIsHttpOnly", + "ReportJson", "ReportText", "PresetArguments", "CanExportReport", "CanExportPreset", + ]; + + [Fact] + public void EmptyStateHasNoReportOrExportsAndDoesNotSerialize() + { + var reports = new Reports(); + var owner = Create(reports); + + Assert.Null(owner.OperationError); + Assert.Null(owner.HistorySaveError); + Assert.Empty(owner.Issues); + Assert.Null(owner.LastResult); + Assert.Null(owner.LastReport); + Assert.Null(owner.LastSession); + Assert.False(owner.NoBypassRequired); + Assert.False(owner.LastReportIsHttpOnly); + Assert.False(owner.CanExportReport); + Assert.False(owner.CanExportPreset); + Assert.Equal("", owner.ReportJson); + Assert.Equal("", owner.ReportText); + Assert.Equal("", owner.PresetArguments); + Assert.Empty(reports.Calls); + } + + [Fact] + public void PreparedIssuesAreAssignedQuietlyWithoutChangingTheLastReport() + { + var reports = new Reports { Report = new() { Issues = [Issue("NO_BYPASS_REQUIRED")] } }; + var owner = Create(reports); + owner.ApplyRunResult(new(), new()); + List notifications = []; + owner.PropertyChanged += (_, args) => notifications.Add(args.PropertyName); + BlockCheckIssue[] prepared = [Issue("PREPARED")]; + + owner.SetPreparedIssues(prepared); + + Assert.Same(prepared, owner.Issues); + Assert.Same(reports.Report, owner.LastReport); + Assert.True(owner.NoBypassRequired); + Assert.Empty(notifications); + } + + [Fact] + public void ApplyKeepsReferenceIdentityLiveOptionReadsAndTheOriginalNotificationOrder() + { + var options = Options(); + options.SelectedRunPreset = BlockCheckRunPreset.Quick; + var prepared = new BlockCheckSessionPreparationResult + { + Catalog = new() { CatalogVersion = "fixture-catalog" }, + Targets = [new() { Id = "original", Host = "example.test" }], + RunOptions = new(), + Issues = [Issue("PREPARED")], + }; + var result = new BlockCheckRunResult(); + var report = new BlockCheckReport { Issues = [Issue("REPORTED")], PresetArguments = "--fixture" }; + var reports = new Reports { Report = report }; + var owner = new BlockCheck2RunResultViewModel(reports, options); + reports.OnBuild = (catalog, preset, targets, run) => + { + Assert.Same(result, owner.LastResult); + Assert.Null(owner.LastReport); + Assert.Same(prepared.Catalog, catalog); + Assert.Equal(BlockCheckRunPreset.Quick, preset); + Assert.Same(prepared.Targets, targets); + Assert.Same(result, run); + options.SelectedRunPreset = BlockCheckRunPreset.Exhaustive; + options.ConnectTimeoutSeconds = 12; + options.RequestTimeoutSeconds = 14; + options.StartupGraceSeconds = 1.25; + return report; + }; + List notifications = []; + owner.PropertyChanged += (sender, args) => + { + Assert.Same(owner, sender); + Assert.Same(result, owner.LastResult); + Assert.Same(report, owner.LastReport); + Assert.Same(report.Issues, owner.Issues); + Assert.NotNull(owner.LastSession); + notifications.Add(args.PropertyName); + }; + + owner.ApplyRunResult(prepared, result); + + var session = Assert.IsType(owner.LastSession); + Assert.Same(prepared.Catalog, session.Catalog); + Assert.Same(prepared.Targets, session.Targets); + Assert.Same(prepared.RunOptions, session.RunOptions); + Assert.Same(result, session.RunResult); + Assert.Same(report, session.Report); + Assert.Equal(TimeSpan.FromSeconds(12), session.ConnectTimeout); + Assert.Equal(TimeSpan.FromSeconds(14), session.RequestTimeout); + Assert.Equal(TimeSpan.FromSeconds(1.25), session.StartupGracePeriod); + Assert.Equal(ResultNotifications, notifications); + } + + [Fact] + public void BuildFailureRetainsTheOriginalPartiallyAssignedStateAndRaisesNoResultNotifications() + { + var reports = new Reports { Report = new() { Issues = [Issue("FIRST")] } }; + var owner = Create(reports); + owner.ApplyRunResult(new(), new()); + var oldSession = owner.LastSession; + var nextResult = new BlockCheckRunResult(); + var failure = new InvalidOperationException("fixture build failure"); + reports.OnBuild = (_, _, _, _) => throw failure; + List notifications = []; + owner.PropertyChanged += (_, args) => notifications.Add(args.PropertyName); + + Assert.Same(failure, Assert.Throws(() => owner.ApplyRunResult(new(), nextResult))); + + Assert.Same(nextResult, owner.LastResult); + Assert.Same(reports.Report, owner.LastReport); + Assert.Same(oldSession, owner.LastSession); + Assert.Same(reports.Report.Issues, owner.Issues); + Assert.Empty(notifications); + } + + [Fact] + public void NotificationFailurePropagatesAfterAllResultFieldsHaveBeenAssigned() + { + var reports = new Reports(); + var owner = Create(reports); + var failure = new InvalidOperationException("fixture subscriber failure"); + List notifications = []; + owner.PropertyChanged += (_, args) => { notifications.Add(args.PropertyName); throw failure; }; + + Assert.Same(failure, Assert.Throws(() => owner.ApplyRunResult(new(), new()))); + + Assert.NotNull(owner.LastResult); + Assert.Same(reports.Report, owner.LastReport); + Assert.NotNull(owner.LastSession); + Assert.Same(reports.Report.Issues, owner.Issues); + Assert.Equal(["Issues"], notifications); + } + + [Fact] + public void AReentrantApplyPublishesTheNewResultBeforeTheOuterNotificationSequenceContinues() + { + var firstResult = new BlockCheckRunResult(); + var secondResult = new BlockCheckRunResult(); + var firstReport = new BlockCheckReport(); + var secondReport = new BlockCheckReport { PresetArguments = "--second" }; + var reports = new Reports + { + OnBuild = (_, _, _, result) => ReferenceEquals(result, firstResult) ? firstReport : secondReport, + }; + var owner = Create(reports); + List<(string? Name, BlockCheckReport? Report)> observations = []; + bool reapplied = false; + owner.PropertyChanged += (_, args) => + { + observations.Add((args.PropertyName, owner.LastReport)); + if (!reapplied) + { + reapplied = true; + owner.ApplyRunResult(new(), secondResult); + } + }; + + owner.ApplyRunResult(new(), firstResult); + + Assert.Same(secondResult, owner.LastResult); + Assert.Same(secondReport, owner.LastReport); + Assert.Same(secondResult, owner.LastSession!.RunResult); + Assert.Equal(22, observations.Count); + Assert.Equal(("Issues", firstReport), observations[0]); + Assert.All(observations.Skip(1), observation => Assert.Same(secondReport, observation.Report)); + Assert.Equal(ResultNotifications.Concat(ResultNotifications.Skip(1)), observations.Skip(1).Select(item => item.Name)); + } + + [Fact] + public void AReentrantApplyDuringResetRemainsVisibleToTheRestOfTheResetNotifications() + { + var reports = new Reports(); + var owner = Create(reports); + owner.ApplyRunResult(new(), new()); + var nextResult = new BlockCheckRunResult(); + List<(string? Name, BlockCheckRunResult? Result)> observations = []; + owner.PropertyChanged += (_, args) => + { + observations.Add((args.PropertyName, owner.LastResult)); + if (args.PropertyName == "OperationError") + owner.ApplyRunResult(new(), nextResult); + }; + + owner.Reset(notify => notify()); + + Assert.Null(observations[0].Result); + Assert.Equal("OperationError", observations[0].Name); + Assert.Same(nextResult, owner.LastResult); + Assert.Same(nextResult, owner.LastSession!.RunResult); + Assert.All(observations.Skip(1), observation => Assert.Same(nextResult, observation.Result)); + Assert.Equal(ResultNotifications.Concat(["HistorySaveError"]).Concat(ResultNotifications), + observations.Skip(1).Select(item => item.Name)); + } + + [Theory] + [InlineData("NO_BYPASS_REQUIRED", true)] + [InlineData("no_bypass_required", false)] + [InlineData("NO_BYPASS_REQUIRED_EXTRA", false)] + public void NoBypassRequiredUsesTheExactOrdinalReportIssueCode(string code, bool expected) + { + var owner = Create(new Reports { Report = new() { Issues = [Issue(code)] } }); + owner.ApplyRunResult(new(), new()); + Assert.Equal(expected, owner.NoBypassRequired); + } + + [Theory] + [InlineData("", false)] + [InlineData("Http", true)] + [InlineData("Http,Http", true)] + [InlineData("Http,Tls12", false)] + [InlineData("TlsAuto", false)] + public void HttpOnlyRequiresANonemptyReportContainingOnlyHttp(string protocols, bool expected) + { + var targets = protocols.Split(',', StringSplitOptions.RemoveEmptyEntries) + .Select((protocol, i) => new BlockCheckReportTarget(i.ToString(), "example.test", "/", + Enum.Parse(protocol), BlockCheckIpVersion.IPv4, + BlockCheckTransport.Tcp, 80, "fixture")).ToArray(); + var owner = Create(new Reports { Report = new() { Targets = targets } }); + owner.ApplyRunResult(new(), new()); + Assert.Equal(expected, owner.LastReportIsHttpOnly); + } + + [Theory] + [InlineData(false, false, "--fixture", false)] + [InlineData(true, false, "--fixture", true)] + [InlineData(false, true, "--fixture", true)] + [InlineData(true, true, "--fixture", true)] + [InlineData(true, false, "", false)] + [InlineData(false, true, " \t ", false)] + public void PresetExportRequiresSuccessOrBestEffortAndNonblankArguments(bool success, bool bestEffort, string arguments, bool expected) + { + var owner = Create(new Reports { Report = new() { Success = success, IsBestEffort = bestEffort, PresetArguments = arguments } }); + owner.ApplyRunResult(new(), new()); + Assert.True(owner.CanExportReport); + Assert.Equal(expected, owner.CanExportPreset); + Assert.Equal(arguments, owner.PresetArguments); + } + + [Fact] + public void ReportTextAndJsonAreSerializedLazilyOnEveryRead() + { + var reports = new Reports(); + var owner = Create(reports); + owner.ApplyRunResult(new(), new()); + Assert.Equal(["build"], reports.Calls); + + Assert.Equal("json:1", owner.ReportJson); + Assert.Equal("json:2", owner.ReportJson); + Assert.Equal("text:1", owner.ReportText); + Assert.Equal("text:2", owner.ReportText); + + Assert.Equal(["build", "json", "json", "text", "text"], reports.Calls); + } + + [Theory] + [InlineData("json")] + [InlineData("text")] + [InlineData("preset")] + public void MissingReportExportThrowsSynchronouslyBeforeCallingTheBackend(string format) + { + var reports = new Reports(); + var owner = Create(reports); + + var error = Assert.Throws(() => { _ = Save(owner, format, "unused", default); }); + + Assert.Equal("No BlockCheck2 report is available.", error.Message); + Assert.Empty(reports.Calls); + } + + [Theory] + [InlineData("json")] + [InlineData("text")] + [InlineData("preset")] + public async Task ExportsForwardTheExactPathReportTokenAndTask(string format) + { + var reports = new Reports(); + var owner = Create(reports); + owner.ApplyRunResult(new(), new()); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + reports.SaveTask = completion.Task; + + Task saved = Save(owner, format, " C:\\fixture\\report ", cancellation.Token); + + Assert.Same(completion.Task, saved); + Assert.Equal(format, reports.SavedFormat); + Assert.Equal(" C:\\fixture\\report ", reports.SavedPath); + Assert.Same(reports.Report, reports.SavedReport); + Assert.Equal(cancellation.Token, reports.SavedToken); + completion.SetResult(); + await saved; + } + + [Theory] + [InlineData("json")] + [InlineData("text")] + [InlineData("preset")] + public void ExportBackendExceptionsRetainTheirSynchronousBoundary(string format) + { + var failure = new InvalidOperationException("fixture export failure"); + var reports = new Reports { SaveFailure = failure }; + var owner = Create(reports); + owner.ApplyRunResult(new(), new()); + + Assert.Same(failure, Assert.Throws(() => { _ = Save(owner, format, "unused", default); })); + } + + [Fact] + public void RepeatedErrorAssignmentsStillNotifyEvenWhenTheTextMatches() + { + var owner = Create(new Reports()); + List notifications = []; + owner.PropertyChanged += (_, args) => notifications.Add(args.PropertyName); + + owner.SetOperationError("operation"); + owner.SetOperationError("operation"); + owner.SetHistorySaveError("history"); + owner.SetHistorySaveError("history"); + + Assert.Equal("operation", owner.OperationError); + Assert.Equal("history", owner.HistorySaveError); + Assert.Equal(["OperationError", "OperationError", "HistorySaveError", "HistorySaveError"], notifications); + } + + [Fact] + public void ResetClearsAllResultAndProgressFieldsBeforeResultThenProgressNotifications() + { + var owner = Create(new Reports()); + owner.ApplyRunResult(new(), new()); + owner.SetOperationError("operation"); + owner.SetHistorySaveError("history"); + var progress = new BlockCheck2ProgressViewModel(() => [], () => 3, () => 0.75); + progress.Update(new(BlockCheckScanPhase.Probing, 2, 8, "fixture", "strategy", SuccessfulChecks: 2)); + List notifications = []; + owner.PropertyChanged += (_, args) => + { + Assert.Null(owner.OperationError); + Assert.Null(owner.HistorySaveError); + Assert.Null(owner.LastResult); + Assert.Null(owner.LastReport); + Assert.Null(owner.LastSession); + Assert.Empty(owner.Issues); + Assert.Equal(0, progress.ProgressCurrent); + Assert.Equal(0, progress.SuccessfulChecks); + notifications.Add(args.PropertyName!); + }; + progress.PropertyChanged += (_, args) => notifications.Add("progress:" + args.PropertyName); + + owner.Reset(progress.Reset); + + Assert.Equal(new[] { "OperationError", "HistorySaveError" }.Concat(ResultNotifications), notifications.Take(13)); + Assert.Equal("progress:CurrentPhase", notifications[13]); + Assert.Equal("progress:CurrentStrategyId", notifications[^1]); + Assert.Equal(29, notifications.Count); + notifications.Clear(); + owner.Reset(progress.Reset); + Assert.Equal(29, notifications.Count); + } + + [Fact] + public void ProgressResetFailureLeavesClearedResultFieldsWithoutResultNotifications() + { + var owner = Create(new Reports()); + owner.ApplyRunResult(new(), new()); + owner.SetOperationError("operation"); + List notifications = []; + owner.PropertyChanged += (_, args) => notifications.Add(args.PropertyName); + var failure = new InvalidOperationException("fixture progress failure"); + + Assert.Same(failure, Assert.Throws(() => owner.Reset(_ => throw failure))); + + Assert.Null(owner.LastReport); + Assert.Null(owner.LastResult); + Assert.Null(owner.LastSession); + Assert.Null(owner.OperationError); + Assert.Empty(owner.Issues); + Assert.Empty(notifications); + } + + [Fact] + public void ProductionAdapterUsesTheExistingBuilderAndSerializers() + { + var serializer = new BlockCheckReportSerializer(); + var reports = new BlockCheck2ReportOperations(new BlockCheckReportBuilder(), serializer); + var owner = new BlockCheck2RunResultViewModel(reports, Options()); + var prepared = new BlockCheckSessionPreparationResult + { + Catalog = new() { CatalogVersion = "fixture-version" }, + Targets = [new() { Id = "fixture", Host = "example.test", Protocol = BlockCheckProtocol.Http }], + }; + + owner.ApplyRunResult(prepared, new()); + + var report = Assert.IsType(owner.LastReport); + Assert.Equal("fixture-version", report.CatalogVersion); + Assert.Equal("example.test", Assert.Single(report.Targets).Host); + Assert.Equal(BlockCheckRunPreset.Balanced, report.RunPreset); + Assert.Equal(serializer.SerializeJson(report), owner.ReportJson); + Assert.Equal(serializer.SerializeText(report), owner.ReportText); + Assert.Throws(() => { _ = owner.SavePresetArgumentsAsync("unused"); }); + } + + private static BlockCheckIssue Issue(string code) => new(BlockCheckIssueSeverity.Warning, code, "fixture"); + private static BlockCheck2OptionsViewModel Options() => new(new Settings(), () => false, () => 0); + private static BlockCheck2RunResultViewModel Create(Reports reports) => new(reports, Options()); + private static Task Save(BlockCheck2RunResultViewModel owner, string format, string path, CancellationToken token) => format switch + { + "json" => owner.SaveReportJsonAsync(path, token), + "text" => owner.SaveReportTextAsync(path, token), + _ => owner.SavePresetArgumentsAsync(path, token), + }; + + private sealed class Settings : IBlockCheck2OptionsSettings + { + public int ReadInt(string key, int defaultValue) => defaultValue; + public bool ReadBool(string key, bool defaultValue) => defaultValue; + public double ReadDouble(string key, double defaultValue) => defaultValue; + public void Save(string? key, int value) { } + public void Save(string? key, bool value) { } + public void Save(string? key, double value) { } + } + + private sealed class Reports : IBlockCheck2ReportOperations + { + public BlockCheckReport Report { get; init; } = new(); + public List Calls { get; } = []; + public Func, BlockCheckRunResult, BlockCheckReport>? OnBuild; + public Task SaveTask = Task.CompletedTask; + public Exception? SaveFailure; + public string? SavedFormat; + public string? SavedPath; + public BlockCheckReport? SavedReport; + public CancellationToken SavedToken; + private int _jsonReads; + private int _textReads; + + public BlockCheckReport Build(StrategyCatalog catalog, BlockCheckRunPreset preset, IReadOnlyList targets, BlockCheckRunResult result) + { + Calls.Add("build"); + return OnBuild?.Invoke(catalog, preset, targets, result) ?? Report; + } + public string SerializeJson(BlockCheckReport report) { Assert.Same(Report, report); Calls.Add("json"); return "json:" + ++_jsonReads; } + public string SerializeText(BlockCheckReport report) { Assert.Same(Report, report); Calls.Add("text"); return "text:" + ++_textReads; } + public Task SaveJsonAsync(string path, BlockCheckReport report, CancellationToken token) => Save("json", path, report, token); + public Task SaveTextAsync(string path, BlockCheckReport report, CancellationToken token) => Save("text", path, report, token); + public Task SavePresetArgumentsAsync(string path, BlockCheckReport report, CancellationToken token) => Save("preset", path, report, token); + private Task Save(string format, string path, BlockCheckReport report, CancellationToken token) + { + SavedFormat = format; SavedPath = path; SavedReport = report; SavedToken = token; + if (SaveFailure != null) throw SaveFailure; + return SaveTask; + } + } +} diff --git a/CDPIUI.Tests/Presentation/BlockCheck2RunControllerTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2RunControllerTests.cs new file mode 100644 index 00000000..994f4f81 --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2RunControllerTests.cs @@ -0,0 +1,402 @@ +using System.Collections.Concurrent; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.AddOns.BlockCheck2.Reporting; +using CDPIUI.ViewModels; + +namespace CDPIUI.Tests.Presentation; + +public sealed class BlockCheck2RunControllerTests +{ + [Fact] + public void ConstructorOnlyStoresHost() + { + var f = new Fixture(); + Assert.Empty(f.Host.Trace); + } + + [Fact] + public async Task StartGuardReturnsNullWithoutResetProgressOrFinally() + { + var f = new Fixture(); f.Host.AllowStart = false; + Assert.Null(await f.Controller.StartAsync()); + Assert.Equal(new[] { "can-start" }, f.Host.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task NormalRunPreservesPortOrderOriginalObjectsAndOptionalRootRenewal(bool previousReport) + { + var f = new Fixture(); if (previousReport) f.Host.ReportValue = new(); + var result = Success(); f.Host.Run = (_, _) => Task.FromResult(result); + Assert.Same(result, await f.Controller.StartAsync()); + var expected = new List { "can-start", "report" }; + if (previousReport) expected.Add("renew"); + expected.AddRange(["reset", "start", "prepare", "prepared", "state:Running", "run", "apply", "complete", "report", "history", "state:Completed", "finish", "cleanup", "actions"]); + Assert.Equal(expected, f.Host.Trace); + Assert.Same(f.Host.Prepared, f.Host.RunCalls.Single().Prepared); + Assert.Same(f.Host.Prepared.Targets, f.Host.Targets); + Assert.Same(f.Host.Prepared.Issues, f.Host.Issues); + Assert.Same(f.Host.Prepared, f.Host.Applied.Single().Prepared); + Assert.Same(result, f.Host.Applied[0].Result); + Assert.Same(f.Host.ResultReport, f.Host.HistoryReports.Single()); + AssertDisposed(f.Host.RunCalls[0].Token); + } + + [Fact] + public async Task InvalidPreparationStillAppliesTargetsIssuesAndRunsFinallyWithoutBackend() + { + var f = new Fixture(); + f.Host.Prepared = new() { Targets = [new() { Id = "invalid" }], Issues = [Error("invalid")] }; + Assert.Null(await f.Controller.StartAsync()); + Assert.Same(f.Host.Prepared.Targets, f.Host.Targets); + Assert.Same(f.Host.Prepared.Issues, f.Host.Issues); + Assert.Empty(f.Host.RunCalls); + Assert.Equal(BlockCheckSessionState.InputInvalid, f.Host.State); + Assert.Equal(new[] { "can-start", "report", "reset", "start", "prepare", "prepared", "state:InputInvalid", "finish", "cleanup", "actions" }, f.Host.Trace); + } + + [Theory] + [InlineData("success", BlockCheckSessionState.Completed)] + [InlineData("canceled", BlockCheckSessionState.Canceled)] + [InlineData("canceled-best", BlockCheckSessionState.Canceled)] + [InlineData("best-effort", BlockCheckSessionState.CompletedWithWarnings)] + [InlineData("failed", BlockCheckSessionState.Failed)] + [InlineData("no-synthesis", BlockCheckSessionState.Failed)] + public async Task FinalStateUsesOriginalCanceledSuccessBestEffortPrecedence(string kind, BlockCheckSessionState expected) + { + var f = new Fixture(); + var result = kind switch + { + "success" => Success(), + "canceled" => new() { WasCanceled = true, Synthesis = new() }, + "canceled-best" => new() { WasCanceled = true, Synthesis = new() { IsBestEffort = true, Issues = [Error("failure")] } }, + "best-effort" => new() { Synthesis = new() { IsBestEffort = true, Issues = [Error("failure")] } }, + "failed" => new() { Synthesis = new() { Issues = [Error("failure")] } }, + _ => new BlockCheckRunResult(), + }; + f.Host.Run = (_, _) => Task.FromResult(result); + Assert.Same(result, await f.Controller.StartAsync()); + Assert.Equal(expected, f.Host.State); + Assert.Single(f.Host.HistoryReports); + } + + [Fact] + public async Task PendingHistoryKeepsRunBlockedAndCtsAliveAndUsesReportAfterCompleteCallback() + { + var f = new Fixture(); var history = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var currentReport = new BlockCheckReport(); + f.Host.OnCall = point => { if (point == "complete") f.Host.ReportValue = currentReport; }; + f.Host.History = _ => history.Task; + var task = f.Controller.StartAsync(); var token = f.Host.RunCalls.Single().Token; + Assert.False(task.IsCompleted); + Assert.Equal(BlockCheckSessionState.Running, f.Host.State); + Assert.Same(currentReport, f.Host.HistoryReports.Single()); + Assert.NotNull(token.WaitHandle); + Assert.Null(await f.Controller.StartAsync()); + Assert.Single(f.Host.RunCalls); + history.SetResult(); await task; + Assert.Equal(BlockCheckSessionState.Completed, f.Host.State); + AssertDisposed(token); + } + + [Fact] + public async Task FinalStateIsComputedBeforeAwaitingHistoryEvenWhenResultIssuesChange() + { + var f = new Fixture(); var history = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var issues = new List(); var result = new BlockCheckRunResult { Synthesis = new(), PreflightIssues = issues }; + f.Host.Run = (_, _) => Task.FromResult(result); f.Host.History = _ => history.Task; + var task = f.Controller.StartAsync(); + issues.Add(Error("late")); Assert.False(result.Success); + history.SetResult(); Assert.Same(result, await task); + Assert.Equal(BlockCheckSessionState.Completed, f.Host.State); + } + + [Theory] + [InlineData("can-start")] + [InlineData("report")] + [InlineData("renew")] + [InlineData("reset")] + [InlineData("start")] + public async Task PreludeFailuresEscapeWithoutOperationErrorOrFinally(string point) + { + var f = new Fixture(); var failure = new IOException(point); + f.Host.ReportValue = new(); f.Host.OnCall = call => { if (call == point) throw failure; }; + Assert.Same(failure, await Assert.ThrowsAsync(() => f.Controller.StartAsync())); + Assert.DoesNotContain("error", f.Host.Trace); + Assert.DoesNotContain("finish", f.Host.Trace); + Assert.DoesNotContain("cleanup", f.Host.Trace); + Assert.Empty(f.Host.RunCalls); + } + + [Theory] + [InlineData("prepare")] + [InlineData("prepared")] + [InlineData("state:Running")] + [InlineData("run")] + [InlineData("apply")] + [InlineData("complete")] + [InlineData("history")] + public async Task ExceptionsInsideTrySetErrorAndFailedThenFinishCleanupAndActions(string point) + { + var f = new Fixture(); var failure = new IOException(point); + f.Host.OnCall = call => { if (call == point) throw failure; }; + Assert.Null(await f.Controller.StartAsync()); + Assert.Equal(failure.Message, f.Host.OperationError); + Assert.Equal(BlockCheckSessionState.Failed, f.Host.State); + Assert.Equal(new[] { "error", "state:Failed", "finish", "cleanup", "actions" }, f.Host.Trace.TakeLast(5)); + if (f.Host.RunCalls.Count > 0) AssertDisposed(f.Host.RunCalls[0].Token); + } + + [Theory] + [InlineData("prepare")] + [InlineData("run")] + [InlineData("apply")] + [InlineData("history")] + public async Task OperationCanceledExceptionsReturnNullAndCanceledWithoutOperationError(string point) + { + var f = new Fixture(); f.Host.OnCall = call => { if (call == point) throw new OperationCanceledException("controlled"); }; + var task = f.Controller.StartAsync(); + Assert.Null(await task); Assert.True(task.IsCompletedSuccessfully); + Assert.Null(f.Host.OperationError); + Assert.Equal(BlockCheckSessionState.Canceled, f.Host.State); + Assert.Equal(new[] { "state:Canceled", "finish", "cleanup", "actions" }, f.Host.Trace.TakeLast(4)); + } + + [Fact] + public async Task BackendCanceledTaskIsTranslatedToNullAndCanceledState() + { + var f = new Fixture(); using var canceled = new CancellationTokenSource(); canceled.Cancel(); + f.Host.Run = (_, _) => Task.FromCanceled(canceled.Token); + var task = f.Controller.StartAsync(); + Assert.Null(await task); + Assert.True(task.IsCompletedSuccessfully); + Assert.Equal(BlockCheckSessionState.Canceled, f.Host.State); + Assert.Null(f.Host.OperationError); + AssertDisposed(f.Host.RunCalls.Single().Token); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void CancelChecksCanCancelBeforeMissingCtsAndDoesNothing(bool forceCanCancel) + { + var f = new Fixture(); f.Host.CancelOverride = forceCanCancel; + f.Controller.Cancel(); + Assert.Equal(new[] { "can-cancel" }, f.Host.Trace); + Assert.Equal(BlockCheckSessionState.Idle, f.Host.State); + } + + [Fact] + public async Task CancelSetsCancelingBeforeCancelCallbacksAndDoesNotAddResultCancellationPolicy() + { + var f = new Fixture(); var pending = Pending(); + f.Host.Run = (_, _) => pending.Task; + var task = f.Controller.StartAsync(); var token = f.Host.RunCalls.Single().Token; + BlockCheckSessionState? stateAtCancellation = null; + using var registration = token.Register(() => stateAtCancellation = f.Host.State); + f.Controller.Cancel(); + Assert.True(token.IsCancellationRequested); + Assert.Equal(BlockCheckSessionState.Canceling, stateAtCancellation); + int states = f.Host.Trace.Count(point => point == "state:Canceling"); + f.Controller.Cancel(); + Assert.Equal(states, f.Host.Trace.Count(point => point == "state:Canceling")); + var result = Success(); pending.SetResult(result); + Assert.Same(result, await task); + Assert.Equal(BlockCheckSessionState.Completed, f.Host.State); + AssertDisposed(token); + } + + [Fact] + public async Task CancelDuringRunningNotificationReachesBackendAsCanceledToken() + { + var f = new Fixture(); + f.Host.OnCall = point => { if (point == "state:Running") f.Controller.Cancel(); }; + await f.Controller.StartAsync(); + Assert.True(f.Host.RunCalls.Single().Token.IsCancellationRequested); + Assert.True(f.Host.Trace.IndexOf("state:Canceling") < f.Host.Trace.IndexOf("run")); + Assert.Equal(BlockCheckSessionState.Completed, f.Host.State); + } + + [Fact] + public async Task CancelCallbackFailuresEscapeSynchronouslyAfterStateAndTokenChanged() + { + var f = new Fixture(); var pending = Pending(); f.Host.Run = (_, _) => pending.Task; + var task = f.Controller.StartAsync(); var token = f.Host.RunCalls.Single().Token; + var failure = new IOException("cancel callback"); + using var registration = token.Register(() => throw failure); + var aggregate = Assert.Throws(() => f.Controller.Cancel()); + Assert.Same(failure, Assert.Single(aggregate.InnerExceptions)); + Assert.True(token.IsCancellationRequested); + Assert.Equal(BlockCheckSessionState.Canceling, f.Host.State); + pending.SetResult(new() { WasCanceled = true }); await task; + Assert.Equal(BlockCheckSessionState.Canceled, f.Host.State); + } + + [Fact] + public async Task CancelWhileHistoryPendingKeepsOriginalFinalStateDecision() + { + var f = new Fixture(); var history = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Host.History = _ => history.Task; + var task = f.Controller.StartAsync(); + f.Controller.Cancel(); Assert.Equal(BlockCheckSessionState.Canceling, f.Host.State); + history.SetResult(); await task; + Assert.Equal(BlockCheckSessionState.Completed, f.Host.State); + } + + [Fact] + public async Task OldFinallyCannotClearOrDisposeNewRunCtsStartedFromFinalStateCallback() + { + var f = new Fixture(); var second = Pending(); Task? next = null; + int runs = 0; + f.Host.Run = (_, _) => ++runs == 1 ? Task.FromResult(Success()) : second.Task; + bool reentered = false; + f.Host.OnCall = point => + { + if (point != "state:Completed" || reentered) return; + reentered = true; next = f.Controller.StartAsync(); + }; + await f.Controller.StartAsync(); + Assert.NotNull(next); Assert.False(next.IsCompleted); + Assert.Equal(2, f.Host.RunCalls.Count); + var oldToken = f.Host.RunCalls[0].Token; var current = f.Host.RunCalls[1].Token; + AssertDisposed(oldToken); + Assert.NotNull(current.WaitHandle); + f.Controller.Cancel(); Assert.True(current.IsCancellationRequested); + second.SetResult(new() { WasCanceled = true }); await next; + AssertDisposed(current); + Assert.Equal(BlockCheckSessionState.Canceled, f.Host.State); + } + + [Theory] + [InlineData("error")] + [InlineData("state:Failed")] + [InlineData("state:Canceled")] + public async Task FailuresInCatchCallbacksEscapeAndStillRunFinally(string point) + { + var f = new Fixture(); var secondary = new IOException("catch callback"); + f.Host.OnCall = call => + { + if (call == "prepare") { if (point == "state:Canceled") throw new OperationCanceledException(); throw new IOException("primary"); } + if (call == point) throw secondary; + }; + Assert.Same(secondary, await Assert.ThrowsAsync(() => f.Controller.StartAsync())); + Assert.Equal(new[] { "finish", "cleanup", "actions" }, f.Host.Trace.TakeLast(3)); + } + + [Theory] + [InlineData("finish")] + [InlineData("cleanup")] + [InlineData("actions")] + public async Task FinallyFailuresStopLaterStepsWithOriginalDisposalBoundary(string point) + { + var f = new Fixture(); var failure = new IOException(point); + f.Host.OnCall = call => { if (call == point) throw failure; }; + Assert.Same(failure, await Assert.ThrowsAsync(() => f.Controller.StartAsync())); + var token = f.Host.RunCalls.Single().Token; + Assert.Equal(point, f.Host.Trace.Last()); + f.Host.CancelOverride = true; f.Host.OnCall = null; + f.Controller.Cancel(); + if (point == "finish") + { + Assert.True(token.IsCancellationRequested); + Assert.Equal(BlockCheckSessionState.Canceling, f.Host.State); + } + else + { + AssertDisposed(token); + Assert.Equal(BlockCheckSessionState.Completed, f.Host.State); + } + } + + [Fact] + public void BothRunAndHistoryContinuationsKeepCapturedSynchronizationContext() + { + var f = new Fixture(); var run = Pending(); var history = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Host.Run = (_, _) => run.Task; f.Host.History = _ => history.Task; + var observed = new List(); + f.Host.OnCall = point => { if (point is "apply" or "complete" or "history" or "state:Completed" or "finish" or "cleanup" or "actions") observed.Add(SynchronizationContext.Current); }; + var context = new PumpContext(); var previous = SynchronizationContext.Current; + Task task; + try { SynchronizationContext.SetSynchronizationContext(context); task = f.Controller.StartAsync(); } + finally { SynchronizationContext.SetSynchronizationContext(previous); } + run.SetResult(Success()); PumpPosted(context); + Assert.False(task.IsCompleted); Assert.Single(f.Host.HistoryReports); + history.SetResult(); PumpPosted(context); + Assert.True(task.IsCompletedSuccessfully); + Assert.Equal(BlockCheckSessionState.Completed, f.Host.State); + Assert.Equal(7, observed.Count); + Assert.All(observed, value => Assert.Same(context, value)); + } + + private static void PumpPosted(PumpContext context) + { + Assert.True(SpinWait.SpinUntil(() => context.HasWork, TimeSpan.FromSeconds(3))); + var previous = SynchronizationContext.Current; + try { SynchronizationContext.SetSynchronizationContext(context); context.Pump(); } + finally { SynchronizationContext.SetSynchronizationContext(previous); } + } + private static void AssertDisposed(CancellationToken token) => Assert.Throws(() => { _ = token.WaitHandle; }); + private static BlockCheckRunResult Success() => new() { Synthesis = new() }; + private static BlockCheckIssue Error(string code) => new(BlockCheckIssueSeverity.Error, code, "fixture"); + private static TaskCompletionSource Pending() => new(TaskCreationOptions.RunContinuationsAsynchronously); + private sealed class Fixture + { + public Host Host { get; } = new(); + public BlockCheck2RunController Controller { get; } + public Fixture() => Controller = new(Host); + } + private sealed record RunCall(BlockCheckSessionPreparationResult Prepared, CancellationToken Token); + private sealed record ApplyCall(BlockCheckSessionPreparationResult Prepared, BlockCheckRunResult Result); + private sealed class Host : IBlockCheck2RunHost + { + public List Trace { get; } = []; + public List RunCalls { get; } = []; + public List Applied { get; } = []; + public List HistoryReports { get; } = []; + public bool AllowStart = true; + public bool? CancelOverride; + public BlockCheckSessionState State = BlockCheckSessionState.Idle; + public BlockCheckReport? ReportValue; + public BlockCheckReport ResultReport = new(); + public BlockCheckSessionPreparationResult Prepared = new() { Targets = [new() { Id = "target" }] }; + public IReadOnlyList Targets = []; + public IReadOnlyList Issues = []; + public string? OperationError; + public Action? OnCall; + public Func> Run = (_, _) => Task.FromResult(Success()); + public Func History = _ => Task.CompletedTask; + private void Call(string point) { Trace.Add(point); OnCall?.Invoke(point); } + public bool CanStart { get { Call("can-start"); return AllowStart && State is not (BlockCheckSessionState.Running or BlockCheckSessionState.Canceling); } } + public bool CanCancel { get { Call("can-cancel"); return CancelOverride ?? State == BlockCheckSessionState.Running; } } + public BlockCheckReport? LastReport { get { Call("report"); return ReportValue; } } + public void RenewGeneratedSiteListRoot() => Call("renew"); + public void ResetResultState() { ReportValue = null; Call("reset"); } + public void StartProgress() => Call("start"); + public BlockCheckSessionPreparationResult Prepare() { Call("prepare"); return Prepared; } + public void ApplyPrepared(BlockCheckSessionPreparationResult prepared) { Targets = prepared.Targets; Issues = prepared.Issues; Call("prepared"); } + public void SetState(BlockCheckSessionState state) { State = state; Call("state:" + state); } + public Task RunPreparedAsync(BlockCheckSessionPreparationResult prepared, CancellationToken cancellationToken) + { + RunCalls.Add(new(prepared, cancellationToken)); Call("run"); return Run(prepared, cancellationToken); + } + public void ApplyRunResult(BlockCheckSessionPreparationResult prepared, BlockCheckRunResult result) + { + Applied.Add(new(prepared, result)); ReportValue = ResultReport; Call("apply"); + } + public void CompleteDisplayedProgress() => Call("complete"); + public Task SaveReportToHistoryAsync(BlockCheckReport report) { HistoryReports.Add(report); Call("history"); return History(report); } + public void SetOperationError(string message) { OperationError = message; Call("error"); } + public void FinishProgress() => Call("finish"); + public void CleanupGeneratedSiteListsIfUnviewable() => Call("cleanup"); + public void NotifyActionState() => Call("actions"); + } + private sealed class PumpContext : SynchronizationContext + { + private readonly ConcurrentQueue<(SendOrPostCallback Callback, object? State)> _work = new(); + public bool HasWork => !_work.IsEmpty; + public override void Post(SendOrPostCallback d, object? state) => _work.Enqueue((d, state)); + public void Pump() { while (_work.TryDequeue(out var work)) work.Callback(work.State); } + } +} diff --git a/CDPIUI.Tests/Presentation/BlockCheck2SelectedStrategyTestTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2SelectedStrategyTestTests.cs new file mode 100644 index 00000000..3ef5f787 --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2SelectedStrategyTestTests.cs @@ -0,0 +1,372 @@ +using System.Globalization; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.ViewModels; +using CDPIUI.ViewModels.BlockCheck2; + +namespace CDPIUI.Tests.Presentation; + +public class BlockCheck2SelectedStrategyTestTests +{ + // Detects eager constructor work that could publish state before the host is composed. + [Fact] + public void ConstructionDoesNotReadStateOrPublish() + { + var f = new Fixture(); + Assert.Empty(f.Trace); + } + + [Fact] + public async Task MissingSelectionDoesNotReadRunningOrPublish() + { + var f = new Fixture { Selected = null, Running = true }; + await f.Owner.TestAsync(); + Assert.Equal(["selected"], f.Trace); + } + + [Fact] + public async Task RunningTestReadsSelectionThenStopsWithoutChangingFlags() + { + var f = new Fixture { Running = true }; + await f.Owner.TestAsync(); + Assert.Equal(["selected", "running?"], f.Trace); + Assert.True(f.Running); + Assert.False(f.Progress); + } + + // Detects moving setup into try, moving cleanup earlier or skipping post-test selection publication. + [Fact] + public async Task CompletedTestPublishesAndCleansUpInOriginalOrder() + { + var f = new Fixture(); + await f.Owner.TestAsync(); + Assert.Equal([ + "selected", "running?", "running:True", "progress:True", "selection", "test", "selection", + "text:BlockCheck2StrategyTestResultFormat", "text:BlockCheck2StrategyTestCompletedTitle", "show", + "running:False", "progress:False", "selection", "assignments"], f.Trace); + Assert.Equal((BlockCheck2NoticeSeverity.Success, "BlockCheck2StrategyTestCompletedTitle", "0/0/0"), Assert.Single(f.Notices)); + Assert.False(f.Running); + Assert.False(f.Progress); + } + + [Fact] + public async Task PendingTestKeepsFlagsAndRejectsNestedCallUntilCompletion() + { + using var culture = new CultureScope("en-US"); + var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var f = new Fixture { Test = _ => pending.Task }; + Task task = f.Owner.TestAsync(); + Assert.False(task.IsCompleted); + Assert.True(f.Running); + Assert.True(f.Progress); + await f.Owner.TestAsync(); + Assert.Single(f.Tested); + Assert.DoesNotContain("assignments", f.Trace); + Assert.Empty(f.Notices); + pending.SetResult(Result(true, false)); + await task; + Assert.False(f.Running); + Assert.False(f.Progress); + Assert.Equal((BlockCheck2NoticeSeverity.Warning, "BlockCheck2StrategyTestCompletedTitle", "1/2/0.5"), Assert.Single(f.Notices)); + } + + [Fact] + public async Task SelectionNotificationKeepsCapturedItemButUsesCurrentTestPort() + { + var f = new Fixture(); + var original = f.Selected; + f.OnCall = name => + { + if (name != "selection") return; + f.Selected = new BlockCheck2StrategyEvidenceItem(new()); + f.Test = item => Task.FromResult(Result(false)); + }; + await f.Owner.TestAsync(); + Assert.Same(original, Assert.Single(f.Tested)); + Assert.Equal((BlockCheck2NoticeSeverity.Warning, "BlockCheck2StrategyTestCompletedTitle", "0/1/0"), Assert.Single(f.Notices)); + } + + [Fact] + public async Task ReentryDuringProgressSeesRunningBeforeFirstTestStarts() + { + var f = new Fixture(); + Task? nested = null; + f.OnCall = name => { if (name == "progress:True") nested = f.Owner.TestAsync(); }; + await f.Owner.TestAsync(); + Assert.True(nested!.IsCompletedSuccessfully); + Assert.Single(f.Tested); + Assert.Equal(["selected", "running?", "running:True", "progress:True", "selected", "running?", "selection", "test"], f.Trace.Take(8)); + } + + [Theory] + [InlineData("progress:True", true)] + [InlineData("selection", true)] + [InlineData("selected", false)] + [InlineData("running?", false)] + public async Task SetupFaultEscapesWithoutCatchOrCleanup(string endpoint, bool runningAfter) + { + var f = new Fixture(); + var fault = new InvalidOperationException("setup fault"); + f.OnCall = name => { if (name == endpoint) throw fault; }; + Assert.Same(fault, await Assert.ThrowsAsync(() => f.Owner.TestAsync())); + Assert.Equal(runningAfter, f.Running); + Assert.Empty(f.Errors); + Assert.DoesNotContain("running:False", f.Trace); + Assert.DoesNotContain("assignments", f.Trace); + Assert.Empty(f.Tested); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task SynchronousAndAwaitedTestFaultAreReportedThenCleanedUp(bool pending) + { + var fault = new InvalidOperationException("probe failed"); + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var f = new Fixture { Test = _ => pending ? completion.Task : throw fault }; + Task task = f.Owner.TestAsync(); + if (pending) completion.SetException(fault); + await task; + Assert.Equal(["probe failed"], f.Errors); + Assert.Equal(["error:probe failed", "running:False", "progress:False", "selection", "assignments"], f.Trace.TakeLast(5)); + } + + [Fact] + public async Task CancellationIsReportedAsAnErrorAndDoesNotLeaveRunning() + { + var f = new Fixture { Test = _ => Task.FromException(new OperationCanceledException("cancelled test")) }; + await f.Owner.TestAsync(); + Assert.Equal(["cancelled test"], f.Errors); + Assert.False(f.Running); + Assert.Contains("assignments", f.Trace); + } + + [Fact] + public async Task ActuallyCanceledTaskIsReportedAndOuterTaskCompletesAfterCleanup() + { + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + Task canceled = Task.FromCanceled(cancellation.Token); + var cancellationError = await Assert.ThrowsAsync(() => canceled); + var f = new Fixture { Test = _ => canceled }; + Task outer = f.Owner.TestAsync(); + await outer; + Assert.True(outer.IsCompletedSuccessfully); + Assert.Equal([cancellationError.Message], f.Errors); + Assert.False(f.Running); + Assert.False(f.Progress); + Assert.Equal(["running:False", "progress:False", "selection", "assignments"], f.Trace.TakeLast(4)); + } + + [Fact] + public async Task PostTestSelectionFaultIsCaughtAndFinalSelectionStillRuns() + { + var f = new Fixture(); int selections = 0; + f.OnCall = name => { if (name == "selection" && ++selections == 2) throw new InvalidOperationException("selection fault"); }; + await f.Owner.TestAsync(); + Assert.Equal(["selection fault"], f.Errors); + Assert.Equal(3, selections); + Assert.Empty(f.Notices); + Assert.Equal("assignments", f.Trace.Last()); + } + + [Fact] + public async Task PresentationFaultIsCaughtBeforeCleanup() + { + var f = new Fixture(); + f.OnCall = name => { if (name == "show") throw new InvalidOperationException("notice fault"); }; + await f.Owner.TestAsync(); + Assert.Equal(["notice fault"], f.Errors); + Assert.Equal(["error:notice fault", "running:False", "progress:False", "selection", "assignments"], f.Trace.TakeLast(5)); + } + + [Fact] + public async Task ErrorCallbackFaultEscapesWithIdentityAfterCleanup() + { + var f = new Fixture { Test = _ => throw new InvalidOperationException("test fault") }; + var errorFault = new InvalidOperationException("error callback fault"); + f.OnCall = name => { if (name.StartsWith("error:")) throw errorFault; }; + Assert.Same(errorFault, await Assert.ThrowsAsync(() => f.Owner.TestAsync())); + Assert.Equal("assignments", f.Trace.Last()); + Assert.False(f.Running); + } + + [Theory] + [InlineData("progress:False", "progress:False")] + [InlineData("selection", "selection")] + [InlineData("assignments", "assignments")] + public async Task CleanupFaultEscapesAndSkipsRemainingCleanup(string endpoint, string last) + { + var f = new Fixture(); + var fault = new InvalidOperationException("cleanup fault"); + f.OnCall = name => { if (!f.Running && name == endpoint) throw fault; }; + Assert.Same(fault, await Assert.ThrowsAsync(() => f.Owner.TestAsync())); + Assert.False(f.Running); + Assert.Empty(f.Errors); + Assert.Equal(last, f.Trace.Last()); + } + + [Fact] + public async Task CleanupFaultReplacesCatchFaultWithoutAnotherErrorNotice() + { + var f = new Fixture { Test = _ => throw new InvalidOperationException("test fault") }; + var catchFault = new InvalidOperationException("catch fault"); + var finallyFault = new InvalidOperationException("finally fault"); + f.OnCall = name => + { + if (name.StartsWith("error:")) throw catchFault; + if (name == "progress:False") throw finallyFault; + }; + Assert.Same(finallyFault, await Assert.ThrowsAsync(() => f.Owner.TestAsync())); + Assert.Equal(["test fault"], f.Errors); + Assert.Equal("progress:False", f.Trace.Last()); + } + + [Fact] + public void MissingProbeUsesFirstIssueEvenWhenItIsOnlyAWarning() + { + var f = new Fixture(); + f.Owner.ShowResult(new() { Issues = [Issue(BlockCheckIssueSeverity.Warning, "first"), Issue(BlockCheckIssueSeverity.Error, "second")] }); + Assert.Equal(["issue:first", "error:first/message-first"], f.Trace); + Assert.Equal(["first/message-first"], f.Errors); + Assert.Empty(f.Notices); + } + + [Fact] + public void MissingProbeWithoutIssuesUsesFallbackText() + { + var f = new Fixture(); + f.Owner.ShowResult(new()); + Assert.Equal(["text:BlockCheck2StrategyTestFailedMessage", "error:BlockCheck2StrategyTestFailedMessage"], f.Trace); + } + + [Theory] + [InlineData(0, 0, BlockCheck2NoticeSeverity.Success, "0/0/0")] + [InlineData(0, 1, BlockCheck2NoticeSeverity.Warning, "0/1/0")] + [InlineData(1, 2, BlockCheck2NoticeSeverity.Warning, "1/2/0.5")] + [InlineData(2, 2, BlockCheck2NoticeSeverity.Success, "2/2/1")] + public void ProbeSummaryUsesCountsIncludingZeroAttemptSuccess(int successes, int attempts, BlockCheck2NoticeSeverity severity, string expected) + { + using var culture = new CultureScope("en-US"); + var f = new Fixture(); + f.Owner.ShowResult(new() { ProbeResult = new() { Attempts = Enumerable.Range(0, attempts).Select(i => new ProbeAttempt { Success = i < successes }).ToList() }, + Issues = [Issue(BlockCheckIssueSeverity.Warning, "warning")] }); + Assert.Equal((severity, "BlockCheck2StrategyTestCompletedTitle", expected), Assert.Single(f.Notices)); + Assert.Empty(f.Errors); + Assert.Equal(["text:BlockCheck2StrategyTestResultFormat", "text:BlockCheck2StrategyTestCompletedTitle", "show"], f.Trace); + } + + [Fact] + public void FirstErrorIsShownAfterFormattingEvenWhenEveryProbeSucceeded() + { + var f = new Fixture(); + f.Owner.ShowResult(new() { ProbeResult = new() { Attempts = [new() { Success = true }] }, + Issues = [Issue(BlockCheckIssueSeverity.Warning, "warning"), Issue(BlockCheckIssueSeverity.Error, "first"), Issue(BlockCheckIssueSeverity.Error, "second")] }); + Assert.Equal(["text:BlockCheck2StrategyTestResultFormat", "issue:first", "error:first/message-first"], f.Trace); + Assert.Empty(f.Notices); + } + + // Detects caching the first Error before the localizer has returned the format string. + [Fact] + public void FormatLocalizationCanReplaceTheFirstErrorBeforeItIsChosen() + { + var issues = new List { Issue(BlockCheckIssueSeverity.Error, "old") }; + var f = new Fixture(); + f.OnCall = name => + { + if (name != "text:BlockCheck2StrategyTestResultFormat") return; + issues[0] = Issue(BlockCheckIssueSeverity.Error, "current"); + }; + f.Owner.ShowResult(new() { ProbeResult = new(), Issues = issues }); + Assert.Equal(["text:BlockCheck2StrategyTestResultFormat", "issue:current", "error:current/message-current"], f.Trace); + Assert.Equal(["current/message-current"], f.Errors); + Assert.Empty(f.Notices); + } + + [Fact] + public void MalformedFormatFailsBeforeExistingErrorIssueIsLocalized() + { + var f = new Fixture { Format = "{3}" }; + Assert.Throws(() => f.Owner.ShowResult(new() { ProbeResult = new(), Issues = [Issue(BlockCheckIssueSeverity.Error, "first")] })); + Assert.Equal(["text:BlockCheck2StrategyTestResultFormat"], f.Trace); + Assert.Empty(f.Errors); + } + + [Fact] + public void FormatUsesCurrentCultureAtTheTimeOfFormatting() + { + using var culture = new CultureScope("en-US"); + var f = new Fixture(); + f.OnCall = name => { if (name == "text:BlockCheck2StrategyTestResultFormat") CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("ru-RU"); }; + f.Owner.ShowResult(Result(true, false)); + Assert.Equal("1/2/0,5", Assert.Single(f.Notices).Message); + } + + [Theory] + [InlineData("text:BlockCheck2StrategyTestResultFormat")] + [InlineData("text:BlockCheck2StrategyTestCompletedTitle")] + [InlineData("show")] + [InlineData("issue:first")] + [InlineData("error:first/message-first")] + public void DirectPresentationFaultEscapesUnchangedWithoutRetry(string endpoint) + { + var f = new Fixture(); var fault = new InvalidOperationException("presentation fault"); + f.OnCall = name => { if (name == endpoint) throw fault; }; + var result = endpoint.StartsWith("issue:") || endpoint.StartsWith("error:") + ? new BlockCheckManualStrategyTestResult { Issues = [Issue(BlockCheckIssueSeverity.Error, "first")] } + : Result(true); + Assert.Same(fault, Assert.Throws(() => f.Owner.ShowResult(result))); + Assert.Equal(endpoint, f.Trace.Last()); + Assert.Single(f.Trace, name => name == endpoint); + } + + [Fact] + public void NoticeCanReenterPresentationBeforeOuterShowReturns() + { + var f = new Fixture(); bool nested = false; + f.OnCall = name => + { + if (name != "show" || nested) return; + nested = true; f.Owner.ShowResult(new()); + }; + f.Owner.ShowResult(Result(true)); + Assert.Single(f.Notices); + Assert.Equal(["BlockCheck2StrategyTestFailedMessage"], f.Errors); + Assert.Equal(["show", "text:BlockCheck2StrategyTestFailedMessage", "error:BlockCheck2StrategyTestFailedMessage"], f.Trace.TakeLast(3)); + } + + private static BlockCheckIssue Issue(BlockCheckIssueSeverity severity, string code) => new(severity, code, "message-" + code); + private static BlockCheckManualStrategyTestResult Result(params bool[] attempts) => new() + { ProbeResult = new() { Attempts = attempts.Select(success => new ProbeAttempt { Success = success }).ToList() } }; + + private sealed class Fixture + { + internal readonly List Trace = []; + internal readonly List Errors = []; + internal readonly List<(BlockCheck2NoticeSeverity Severity, string Title, string Message)> Notices = []; + internal readonly List Tested = []; + internal BlockCheck2StrategyEvidenceItem? Selected = new(new()); + internal bool Running, Progress; + internal string Format = "{0}/{1}/{2}"; + internal Action? OnCall; + internal Func> Test = _ => Task.FromResult(Result()); + internal readonly BlockCheck2SelectedStrategyTest Owner; + internal Fixture() + { + Owner = new(() => { Call("selected"); return Selected; }, () => { Call("running?"); return Running; }, + value => { Running = value; Call("running:" + value); }, value => { Progress = value; Call("progress:" + value); }, + () => Call("selection"), item => { Tested.Add(item); Call("test"); return Test(item); }, + () => Call("assignments"), key => { Call("text:" + key); return key == "BlockCheck2StrategyTestResultFormat" ? Format : key; }, + issue => { Call("issue:" + issue.Code); return issue.Code + "/" + issue.Message; }, + message => { Errors.Add(message); Call("error:" + message); }, + (severity, title, message) => { Notices.Add((severity, title, message)); Call("show"); }); + } + private void Call(string name) { Trace.Add(name); OnCall?.Invoke(name); } + } + + private sealed class CultureScope : IDisposable + { + private readonly CultureInfo _before = CultureInfo.CurrentCulture; + internal CultureScope(string name) => CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(name); + public void Dispose() => CultureInfo.CurrentCulture = _before; + } +} diff --git a/CDPIUI.Tests/Presentation/BlockCheck2SiteListControllerTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2SiteListControllerTests.cs new file mode 100644 index 00000000..f2cb1a0b --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2SiteListControllerTests.cs @@ -0,0 +1,329 @@ +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.Globalization; +using CDPIUI.AddOns.GoodCheck; +using CDPIUI.ViewModels; + +namespace CDPIUI.Tests.Presentation; + +public sealed class BlockCheck2SiteListControllerTests +{ + [Fact] + public void ConstructorStoresCollectionsAndPortsWithoutReadingAnything() + { + var f = new Fixture(); Assert.Empty(f.Trace); Assert.False(f.Owner.IsSiteListLoading); Assert.Null(f.Owner.SiteListLoadError); + Assert.Equal(0, f.Owner.SelectedSiteListCount); Assert.Equal(0, f.Owner.SelectedDomainCount); Assert.Empty(f.Trace); + } + + [Fact] + public async Task LoadPublishesPreludeBeforeBackendAndSkipsConcurrentAndCachedCalls() + { + var f = new Fixture(); var gate = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); + f.Backend.LoadReply = gate.Task; + Task load = f.Owner.LoadAsync(); + Assert.True(f.Owner.IsSiteListLoading); Assert.Null(f.Owner.SiteListLoadError); + Assert.Equal(["event:IsSiteListLoading", "event:SiteListLoadError", "load"], f.Trace); + await f.Owner.LoadAsync(); Assert.Equal(1, f.Backend.LoadCalls); Assert.False(load.IsCompleted); + gate.SetResult([]); await load; + Assert.False(f.Owner.IsSiteListLoading); Assert.Equal("event:IsSiteListLoading", f.Trace.Last()); + f.Available.Clear(); f.Trace.Clear(); await f.Owner.LoadAsync(); Assert.Empty(f.Trace); Assert.Equal(1, f.Backend.LoadCalls); + } + + [Theory] + [InlineData("en-US", "ä", "z")] + [InlineData("sv-SE", "z", "ä")] + public async Task LoadUsesCurrentCultureForPackThenName(string culture, string first, string second) + { + var f = new Fixture(); f.Backend.Definitions.AddRange([Definition(second, "same"), Definition(first, "same"), Definition("before", "a")]); + var previous = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); await f.Owner.LoadAsync(); + Assert.Equal(["before", first, second], f.Available.Select(x => x.Name)); + } + finally { CultureInfo.CurrentCulture = previous; } + } + + [Fact] + public async Task LoadClearsBeforeFilteringAndUsesSameMutableDefinitionsAndLateRoot() + { + var f = new Fixture(); var first = Definition("a"); var second = Definition("b"); var blank = Definition("blank"); + f.Backend.Definitions.AddRange([second, first, blank]); + f.OnAvailable = e => { if (e.Action == NotifyCollectionChangedAction.Reset) blank.Directory = " "; }; + f.Backend.OnCreate = a => { if (a.Name == "a") { second.Name = "mutated"; f.Root = "late-root"; } }; + await f.Owner.LoadAsync(); + Assert.Equal(["a", "mutated"], f.Available.Select(x => x.Name)); + Assert.Equal(["root", "late-root"], f.Backend.Creates.Select(x => x.Root)); + Assert.True(f.Trace.IndexOf("available:Reset") < f.Trace.IndexOf("legacy:a.txt")); + Assert.DoesNotContain("legacy: ", f.Trace); + } + + [Fact] + public async Task LoadRetainsLegacyBlankDomainAndCaseSensitiveExcludeFiltersWithoutDedup() + { + var f = new Fixture(); + f.Backend.Definitions.AddRange([Definition("legacy"), Definition("exclude"), Definition("Exclude"), Definition("zero"), Definition("same"), Definition("same"), new()]); + f.Backend.Legacy.Add("legacy.txt"); f.Backend.DomainReply = a => a.Name == "zero" ? 0 : 1; + await f.Owner.LoadAsync(); + Assert.Equal(["Exclude", "same", "same"], f.Available.Select(x => x.Name)); + Assert.DoesNotContain(f.Backend.Creates, a => a.Name == "legacy"); + Assert.All(f.Backend.Creates, a => { Assert.False(a.Custom); Assert.Null(a.Content); }); + } + + [Fact] + public async Task MissingTemplateNameAndPackUseOriginalFallbacks() + { + var f = new Fixture(); f.Backend.Definitions.Add(new() { Directory = "fallback.txt" }); + await f.Owner.LoadAsync(); var a = Assert.Single(f.Backend.Creates); + Assert.Equal("fallback.txt", a.Name); Assert.Equal("", a.Source); Assert.Equal("fallback.txt", a.Path); + } + + [Theory] + [InlineData("IsSiteListLoading")] + [InlineData("SiteListLoadError")] + public async Task PreludeObserverFailureIsOutsideFinallyAndLeavesLoadingSet(string property) + { + var f = new Fixture(); f.Observe = name => { if (name == property) throw new IOException("prelude"); }; + await Assert.ThrowsAsync(f.Owner.LoadAsync); + Assert.True(f.Owner.IsSiteListLoading); Assert.Equal(0, f.Backend.LoadCalls); + f.Observe = null; await f.Owner.LoadAsync(); Assert.Equal(0, f.Backend.LoadCalls); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task FailedOrCanceledLoadPublishesErrorAndCanRetry(bool canceled) + { + var f = new Fixture(); var error = new IOException("load failed"); + f.Backend.LoadReply = canceled ? Task.FromCanceled>(new CancellationToken(true)) : Task.FromException>(error); + await f.Owner.LoadAsync(); Assert.False(f.Owner.IsSiteListLoading); Assert.NotNull(f.Owner.SiteListLoadError); + if (!canceled) Assert.Equal(error.Message, f.Owner.SiteListLoadError); + Assert.Equal(["event:SiteListLoadError", "event:IsSiteListLoading"], f.Trace.TakeLast(2)); + f.Backend.LoadReply = null; f.Backend.Definitions.Add(Definition("a")); await f.Owner.LoadAsync(); + Assert.Null(f.Owner.SiteListLoadError); Assert.Single(f.Available); Assert.Equal(2, f.Backend.LoadCalls); + } + + [Theory] + [InlineData("reset", 0)] + [InlineData("add", 1)] + [InlineData("factory", 1)] + public async Task CollectionOrFactoryFailureRetainsPartialPublicationAndAllowsRetry(string failure, int count) + { + var f = new Fixture(); f.Backend.Definitions.AddRange([Definition("a"), Definition("b")]); + f.OnAvailable = e => + { + if (failure == "reset" && e.Action == NotifyCollectionChangedAction.Reset || failure == "add" && e.Action == NotifyCollectionChangedAction.Add) + throw new IOException("collection"); + }; + f.Backend.OnCreate = a => { if (failure == "factory" && a.Name == "b") throw new IOException("factory"); }; + await f.Owner.LoadAsync(); Assert.Equal(count, f.Available.Count); Assert.NotNull(f.Owner.SiteListLoadError); Assert.False(f.Owner.IsSiteListLoading); + f.OnAvailable = null; f.Backend.OnCreate = null; await f.Owner.LoadAsync(); Assert.Equal(2, f.Available.Count); + } + + [Fact] + public async Task ErrorObserverFailureStillRunsFinallyAndFinalObserverFailureKeepsLoadedCache() + { + var f = new Fixture(); f.Backend.LoadReply = Task.FromException>(new IOException("backend")); + f.Observe = name => { if (name == "SiteListLoadError" && f.Owner.SiteListLoadError != null) throw new IOException("observer"); }; + Assert.Equal("observer", (await Assert.ThrowsAsync(f.Owner.LoadAsync)).Message); Assert.False(f.Owner.IsSiteListLoading); + f = new Fixture(); f.Observe = name => { if (name == "IsSiteListLoading" && !f.Owner.IsSiteListLoading) throw new IOException("finally"); }; + await Assert.ThrowsAsync(f.Owner.LoadAsync); f.Observe = null; f.Trace.Clear(); await f.Owner.LoadAsync(); + Assert.Empty(f.Trace); Assert.Equal(1, f.Backend.LoadCalls); + } + + [Fact] + public async Task ReentryFromAvailableResetSeesLoadingAndDoesNotStartAnotherLoad() + { + var f = new Fixture(); Task? nested = null; + f.OnAvailable = e => { if (e.Action == NotifyCollectionChangedAction.Reset) nested = f.Owner.LoadAsync(); }; + await f.Owner.LoadAsync(); Assert.NotNull(nested); Assert.True(nested.IsCompletedSuccessfully); Assert.Equal(1, f.Backend.LoadCalls); + } + + [Fact] + public void AddCustomNormalizesPathPrefersAvailableAndDoesNotMutateCollections() + { + var f = new Fixture(); string path = Path.GetFullPath("existing.txt"); + var available = new Row("available", path.ToUpperInvariant()); var selected = new Row("selected", path); + f.Available.Add(available); f.Selected.Add(selected); f.Trace.Clear(); + Assert.Same(available, f.Owner.AddCustom("existing.txt", "source")); Assert.Empty(f.Backend.Creates); + Assert.Single(f.Available); Assert.Single(f.Selected); Assert.DoesNotContain("root", f.Trace); + var added = f.Owner.AddCustom("new.txt", "source"); var args = Assert.Single(f.Backend.Creates); + Assert.Equal(Path.GetFullPath("new.txt"), args.Path); Assert.Equal("new.txt", args.Name); Assert.False(args.Custom); Assert.Null(args.Content); + Assert.DoesNotContain(added, f.Available); Assert.DoesNotContain(added, f.Selected); Assert.DoesNotContain("selection", f.Trace); + } + + [Fact] + public async Task EmptyNormalizedCustomContentUsesOriginalLocalizedErrorBeforeWrite() + { + var f = new Fixture(); f.Backend.Normalized = ""; + var error = await Assert.ThrowsAsync(() => f.Owner.UpdateCustomAsync("raw", "name", "source")); + Assert.Equal("localized empty", error.Message); Assert.Equal(["normalize:raw", "text:BlockCheck2CustomSiteListEmpty"], f.Trace); + Assert.Empty(f.Backend.Writes); Assert.Empty(f.Backend.Creates); + } + + [Fact] + public async Task NewCustomCapturesPathBeforeAwaitButUsesCurrentRootAndCollectionAfterward() + { + var f = new Fixture(); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Backend.WriteReply = gate.Task; using var cancellation = new CancellationTokenSource(); + Task update = f.Owner.UpdateCustomAsync("raw", "name", "source", cancellation.Token); + Assert.False(update.IsCompleted); Assert.Empty(f.Backend.Creates); + var other = new Row("other", "other") { Custom = true }; f.Selected.Add(other); f.Root = "late"; cancellation.Cancel(); + gate.SetResult(true); Row result = await update; + var args = Assert.Single(f.Backend.Creates); Assert.True(args.Custom); Assert.Equal("normalized", args.Content); Assert.Equal("late", args.Root); + Assert.Equal([result, other], f.Selected); Assert.Equal(cancellation.Token, f.Backend.Writes.Single().Token); + Assert.Equal("selection", f.Trace.Last()); + } + + [Fact] + public async Task ExistingCustomIsCapturedBeforeAwaitAndUpdatedEvenAfterRemoval() + { + var f = new Fixture(); var first = new Row("first", "captured") { Custom = true }; var second = new Row("second", "second") { Custom = true }; + f.Selected.Add(first); f.Selected.Add(second); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Backend.WriteReply = gate.Task; Task update = f.Owner.UpdateCustomAsync("raw", "ignored", "ignored"); + f.Selected.Remove(first); f.Root = "late"; gate.SetResult(true); + Assert.Same(first, await update); Assert.Equal("normalized", first.Content); Assert.Equal("captured", f.Backend.Writes.Single().Path); + Assert.Same(second, Assert.Single(f.Selected)); Assert.Empty(f.Backend.Creates); Assert.DoesNotContain("root", f.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task FailedOrCanceledWriteDoesNotMutateOrNotify(bool canceled) + { + var f = new Fixture(); f.Backend.WriteReply = canceled ? Task.FromCanceled(new CancellationToken(true)) : Task.FromException(new IOException("write")); + await Assert.ThrowsAnyAsync(() => f.Owner.UpdateCustomAsync("raw", "name", "source")); + Assert.Empty(f.Selected); Assert.Empty(f.Backend.Creates); Assert.DoesNotContain("selection", f.Trace); + } + + [Fact] + public async Task InsertObserverAndUpdateFailuresKeepAssignedStateWithoutSelectionNotify() + { + var f = new Fixture(); f.OnSelected = e => { if (e.Action == NotifyCollectionChangedAction.Add) throw new IOException("insert"); }; + await Assert.ThrowsAsync(() => f.Owner.UpdateCustomAsync("raw", "name", "source")); Assert.Single(f.Selected); Assert.DoesNotContain("selection", f.Trace); + f = new Fixture(); var row = new Row("custom", "custom") { Custom = true }; f.Selected.Add(row); f.Trace.Clear(); + f.Backend.OnUpdate = _ => throw new IOException("update"); + await Assert.ThrowsAsync(() => f.Owner.UpdateCustomAsync("raw", "name", "source")); + Assert.Equal("normalized", row.Content); Assert.DoesNotContain("selection", f.Trace); + } + + [Fact] + public async Task OverlappingNewCustomUpdatesKeepOriginalCompletionOrderWithoutReselection() + { + var f = new Fixture(); var gates = new[] { new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously), new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously) }; + int calls = 0; f.Backend.WriteFactory = () => gates[calls++].Task; + Task first = f.Owner.UpdateCustomAsync("one", "first", "source"); Task second = f.Owner.UpdateCustomAsync("two", "second", "source"); + gates[1].SetResult(true); Row secondRow = await second; gates[0].SetResult(true); Row firstRow = await first; + Assert.Equal([firstRow, secondRow], f.Selected); Assert.Equal(2, f.Trace.Count(x => x == "selection")); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void SelectAndRemoveNullKeepOriginalItemParameterGuard(bool remove) + { + var f = new Fixture(); + var error = Assert.Throws(() => { if (remove) f.Owner.Remove(null!); else f.Owner.Select(null!); }); + Assert.Equal("item", error.ParamName); Assert.Empty(f.Trace); + } + + [Fact] + public void SelectionDeduplicatesPathsButRemovalKeepsObjectIdentityAndLiveCounts() + { + var f = new Fixture(); var first = new Row("first", "Path") { Count = 2 }; var duplicate = new Row("duplicate", "PATH") { Count = 4 }; + f.Owner.Select(first); f.Owner.Select(duplicate); Assert.Same(first, Assert.Single(f.Selected)); Assert.Equal(1, f.Trace.Count(x => x == "selection")); + f.Owner.Remove(duplicate); Assert.Single(f.Selected); Assert.Equal(1, f.Trace.Count(x => x == "selection")); + Assert.Equal(1, f.Owner.SelectedSiteListCount); Assert.Equal(2, f.Owner.SelectedDomainCount); + first.Count = 7; Assert.Equal(7, f.Owner.SelectedDomainCount); f.Owner.Remove(first); Assert.Empty(f.Selected); + Assert.Equal(2, f.Trace.Count(x => x == "selection")); + } + + [Fact] + public void SetSelectedKeepsFirstPathAndSelfSourceClearsBeforeEnumeration() + { + var f = new Fixture(); var first = new Row("first", "a"); var duplicate = new Row("duplicate", "A"); var second = new Row("second", "b"); + f.Owner.SetSelected([first, duplicate, second]); Assert.Equal([first, second], f.Selected); + f.Owner.SetSelected(f.Selected); Assert.Empty(f.Selected); Assert.Equal(2, f.Trace.Count(x => x == "selection")); + f.Selected.Add(first); f.Trace.Clear(); Assert.Throws(() => f.Owner.SetSelected(null!)); + Assert.Empty(f.Selected); Assert.Equal(["selected:Reset"], f.Trace); + } + + [Theory] + [InlineData("select")] + [InlineData("remove")] + [InlineData("set")] + public void SelectionCallbackFailureDoesNotRollbackMutation(string operation) + { + var f = new Fixture(); var row = new Row("row", "path"); if (operation == "remove") f.Selected.Add(row); + f.OnSelection = () => throw new IOException("notify"); + Assert.Throws(() => { if (operation == "select") f.Owner.Select(row); else if (operation == "remove") f.Owner.Remove(row); else f.Owner.SetSelected([row]); }); + Assert.Equal(operation == "remove" ? 0 : 1, f.Selected.Count); + } + + [Fact] + public void SelectedDomainCountRetainsIntegerSumOverflow() + { + var f = new Fixture(); f.Selected.Add(new("max", "a") { Count = int.MaxValue }); f.Selected.Add(new("one", "b")); + Assert.Throws(() => f.Owner.SelectedDomainCount); + } + + private static SiteListElement Definition(string name, string pack = "p") => new() { Name = name, PackName = pack, Directory = name + ".txt" }; + private sealed class Row(string name, string path) + { + public string Name = name, Path = path, Content = ""; + public bool Custom; + public int Count = 1; + } + private sealed record CreateArgs(string Name, string Source, string Path, bool Custom, string? Content, string Root); + private sealed class Fixture + { + public Fixture() + { + Backend = new(Trace); + Owner = new(Available, Selected, Backend, () => { Trace.Add("root"); return Root; }, () => { Trace.Add("selection"); OnSelection?.Invoke(); }); + Owner.PropertyChanged += (sender, e) => { Assert.Same(Owner, sender); Trace.Add("event:" + e.PropertyName); Observe?.Invoke(e.PropertyName!); }; + Available.CollectionChanged += (_, e) => { Trace.Add("available:" + e.Action); OnAvailable?.Invoke(e); }; + Selected.CollectionChanged += (_, e) => { Trace.Add("selected:" + e.Action); OnSelected?.Invoke(e); }; + } + public BlockCheck2SiteListController Owner { get; } + public Backend Backend { get; } + public ObservableCollection Available { get; } = []; + public ObservableCollection Selected { get; } = []; + public List Trace { get; } = []; + public string Root = "root"; + public Action? Observe; + public Action? OnAvailable, OnSelected; + public Action? OnSelection; + } + private sealed class Backend(List trace) : IBlockCheck2SiteListBackend + { + public List Definitions { get; } = []; + public HashSet Legacy { get; } = []; + public List Creates { get; } = []; + public List<(string Path, string Content, CancellationToken Token)> Writes { get; } = []; + public Task>? LoadReply; + public Task? WriteReply; + public Func? WriteFactory; + public Action? OnCreate; + public Action? OnUpdate; + public Func? DomainReply; + public string Normalized = "normalized"; + public int LoadCalls; + public Task> LoadAvailableAsync() { trace.Add("load"); LoadCalls++; return LoadReply ?? Task.FromResult(Definitions); } + public bool IsLegacyGenerated(string path) { trace.Add("legacy:" + path); return Legacy.Contains(path); } + public Row Create(string displayName, string sourceName, string path, bool isCustom, string? editableContent, string root) + { + var args = new CreateArgs(displayName, sourceName, path, isCustom, editableContent, root); Creates.Add(args); trace.Add("create:" + displayName); OnCreate?.Invoke(args); + return new(displayName, path) { Custom = isCustom, Content = editableContent ?? "", Count = DomainReply?.Invoke(args) ?? 1 }; + } + public string Normalize(string content) { trace.Add("normalize:" + content); return Normalized; } + public string CreateCustomPath() { trace.Add("custom-path"); return "custom-path"; } + public Task WriteAsync(string path, string normalized, CancellationToken token) { trace.Add("write:" + path); Writes.Add((path, normalized, token)); return WriteFactory?.Invoke() ?? WriteReply ?? Task.CompletedTask; } + public string Text(string key) { trace.Add("text:" + key); return "localized empty"; } + public string GetFilePath(Row item) { trace.Add("path:" + item.Name); return item.Path; } + public string GetDisplayName(Row item) { trace.Add("name:" + item.Name); return item.Name; } + public int GetDomainCount(Row item) { trace.Add("domain:" + item.Name); return item.Count; } + public bool IsCustom(Row item) { trace.Add("custom:" + item.Name); return item.Custom; } + public void UpdateCustom(Row item, string content) { trace.Add("update:" + item.Name); item.Content = content; OnUpdate?.Invoke(item); } + } +} diff --git a/CDPIUI.Tests/Presentation/ConfigMakerCommandHelpLoaderTests.cs b/CDPIUI.Tests/Presentation/ConfigMakerCommandHelpLoaderTests.cs new file mode 100644 index 00000000..18957448 --- /dev/null +++ b/CDPIUI.Tests/Presentation/ConfigMakerCommandHelpLoaderTests.cs @@ -0,0 +1,325 @@ +using CDPIUI.Helper.CreateConfigHelper; + +namespace CDPIUI.Tests.Presentation; + +public class ConfigMakerCommandHelpLoaderTests +{ + [Fact] + public void ConstructionAndCancelBeforeFirstLoadDoNotReadAnyProvider() + { + var fixture = new LoaderFixture(); + + fixture.Loader.Cancel(); + + Assert.Empty(fixture.Trace); + Assert.Empty(fixture.Requests); + Assert.False(fixture.Loader.IsHelpLoading); + Assert.True(fixture.Loader.IsCommandListEnabled); + Assert.Equal("", fixture.Loader.UsageText); + } + + [Fact] + public async Task LoadUpdatesLoadingAndUsageBeforeAwaitThenAppliesTheDocumentAndCallbacksInOrder() + { + var fixture = new LoaderFixture(); + var document = Document(" usage "); + + var load = fixture.Loader.LoadAsync("component", false); + + Assert.True(fixture.Loader.IsHelpLoading); + Assert.False(fixture.Loader.IsCommandListEnabled); + Assert.Equal("Loading", fixture.Loader.UsageText); + fixture.OnStructure = () => Assert.Same(document.Options[0], Assert.Single(fixture.Panel.CommandOptions).Source); + fixture.Requests[0].Reply.SetResult(document); + await load; + + Assert.Same(document, fixture.Panel.Document); + Assert.Equal(" usage ", fixture.Loader.UsageText); + Assert.False(fixture.Loader.IsHelpLoading); + Assert.Equal(["notify:IsHelpLoading", "notify:IsCommandListEnabled", "localize:ConfigMakerLoadingHelpMessage", "notify:UsageText", "load:component:False", + "current:component", "notify:UsageText", "structure", "diagnostics", "status", "notify:IsHelpLoading", "notify:IsCommandListEnabled"], fixture.Trace); + } + + [Fact] + public async Task LoadPreservesBothObservableOptionResetsBeforeRebuildingStructure() + { + var fixture = new LoaderFixture(); + List events = []; + fixture.Panel.CommandModules.CollectionChanged += (_, args) => events.Add("modules:" + args.Action); + fixture.Panel.CommandOptions.CollectionChanged += (_, args) => events.Add("options:" + args.Action); + fixture.OnStructure = () => events.Add("structure"); + var load = fixture.Loader.LoadAsync("component", false); + + fixture.Requests[0].Reply.SetResult(Document("usage")); + await load; + + Assert.Equal(["modules:Reset", "modules:Add", "options:Reset", "options:Add", "options:Reset", "options:Add", "structure"], events); + } + + [Fact] + public async Task EmptyUsageFormatsTheLocalizedLoadedOptionCount() + { + var fixture = new LoaderFixture(); + var load = fixture.Loader.LoadAsync("component", false); + + fixture.Requests[0].Reply.SetResult(Document(" \t")); + await load; + + Assert.Equal("1 loaded", fixture.Loader.UsageText); + Assert.Contains("localize:ConfigMakerHelpOptionsLoadedMessage", fixture.Trace); + } + + [Fact] + public async Task ForceRefreshIsForwardedAndTheCurrentComponentComparisonIgnoresCase() + { + var fixture = new LoaderFixture(); + var load = fixture.Loader.LoadAsync("component", true); + fixture.ComponentId = "COMPONENT"; + + fixture.Requests[0].Reply.SetResult(Document("usage")); + await load; + + Assert.True(fixture.Requests[0].ForceRefresh); + Assert.Equal("component", fixture.Requests[0].ComponentId); + Assert.Equal("usage", fixture.Loader.UsageText); + Assert.Contains("status", fixture.Trace); + } + + [Fact] + public async Task AResultForAnotherCurrentComponentDoesNotChangeThePanelOrInvokeCallbacks() + { + var fixture = new LoaderFixture(); + var original = fixture.Panel.Document; + var load = fixture.Loader.LoadAsync("component", false); + fixture.ComponentId = "other"; + + fixture.Requests[0].Reply.SetResult(Document("stale")); + await load; + + Assert.Same(original, fixture.Panel.Document); + Assert.Equal("Loading", fixture.Loader.UsageText); + Assert.False(fixture.Loader.IsHelpLoading); + Assert.DoesNotContain("structure", fixture.Trace); + } + + [Fact] + public async Task CancelSuppressesALateSuccessAndPreservesTheExistingLoadingFlag() + { + var fixture = new LoaderFixture(); + var original = fixture.Panel.Document; + var load = fixture.Loader.LoadAsync("component", false); + fixture.Trace.Clear(); + + fixture.Loader.Cancel(); + fixture.Requests[0].Reply.SetResult(Document("late")); + await load; + + Assert.True(fixture.Requests[0].Token.IsCancellationRequested); + Assert.Same(original, fixture.Panel.Document); + Assert.True(fixture.Loader.IsHelpLoading); + Assert.Empty(fixture.Trace); + } + + [Fact] + public async Task ANewRequestCancelsAndDisposesThePreviousSourceWithoutClearingItsOwnLoadingState() + { + var fixture = new LoaderFixture(); + var oldLoad = fixture.Loader.LoadAsync("component", false); + var oldToken = fixture.Requests[0].Token; + var newLoad = fixture.Loader.LoadAsync("component", true); + + Assert.True(oldToken.IsCancellationRequested); + Assert.Throws(() => oldToken.WaitHandle); + fixture.Requests[0].Reply.SetResult(Document("old")); + await oldLoad; + Assert.True(fixture.Loader.IsHelpLoading); + Assert.Equal("Loading", fixture.Loader.UsageText); + + fixture.Requests[1].Reply.SetResult(Document("new")); + await newLoad; + Assert.Equal("new", fixture.Loader.UsageText); + Assert.False(fixture.Loader.IsHelpLoading); + } + + [Fact] + public async Task AnOlderCompletionAfterTheNewRequestCannotReplaceItsDocument() + { + var fixture = new LoaderFixture(); + var oldLoad = fixture.Loader.LoadAsync("component", false); + var newLoad = fixture.Loader.LoadAsync("component", true); + var document = Document("new"); + fixture.Requests[1].Reply.SetResult(document); + await newLoad; + fixture.Trace.Clear(); + + fixture.Requests[0].Reply.SetResult(Document("old")); + await oldLoad; + + Assert.Same(document, fixture.Panel.Document); + Assert.Equal("new", fixture.Loader.UsageText); + Assert.Empty(fixture.Trace); + } + + [Fact] + public async Task AnOperationCanceledExceptionWithoutTokenCancellationIsSwallowedAndClearsLoading() + { + var fixture = new LoaderFixture(); + var load = fixture.Loader.LoadAsync("component", false); + + fixture.Requests[0].Reply.SetException(new OperationCanceledException()); + await load; + + Assert.False(fixture.Requests[0].Token.IsCancellationRequested); + Assert.False(fixture.Loader.IsHelpLoading); + Assert.DoesNotContain("structure", fixture.Trace); + } + + [Fact] + public async Task AServiceFailurePropagatesAfterClearingLoading() + { + var fixture = new LoaderFixture(); + var failure = new IOException("service failed"); + var load = fixture.Loader.LoadAsync("component", false); + + fixture.Requests[0].Reply.SetException(failure); + + Assert.Same(failure, await Assert.ThrowsAsync(() => load)); + Assert.False(fixture.Loader.IsHelpLoading); + Assert.DoesNotContain("structure", fixture.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ACallbackFailureUsesTheSameCatchBoundaryAsTheService(bool canceledException) + { + var fixture = new LoaderFixture(); + Exception failure = canceledException ? new OperationCanceledException() : new IOException("structure failed"); + fixture.OnStructure = () => throw failure; + var document = Document("usage"); + var load = fixture.Loader.LoadAsync("component", false); + + fixture.Requests[0].Reply.SetResult(document); + if (canceledException) await load; + else Assert.Same(failure, await Assert.ThrowsAsync(() => load)); + + Assert.Same(document, fixture.Panel.Document); + Assert.Equal("usage", fixture.Loader.UsageText); + Assert.False(fixture.Loader.IsHelpLoading); + Assert.DoesNotContain("diagnostics", fixture.Trace); + Assert.DoesNotContain("status", fixture.Trace); + } + + [Fact] + public async Task ALoadingLocalizationFailureRemainsOutsideTheCatchAndFinallyBoundary() + { + var fixture = new LoaderFixture { LocalizeError = new OperationCanceledException() }; + + await Assert.ThrowsAsync(() => fixture.Loader.LoadAsync("component", false)); + + Assert.True(fixture.Loader.IsHelpLoading); + Assert.Empty(fixture.Requests); + Assert.Equal("", fixture.Loader.UsageText); + } + + [Fact] + public async Task AnInitialLoadingNotificationFailureAlsoRemainsOutsideFinally() + { + var fixture = new LoaderFixture(); + fixture.Loader.PropertyChanged += (_, args) => { if (args.PropertyName == "IsHelpLoading") throw new IOException("observer failed"); }; + + await Assert.ThrowsAsync(() => fixture.Loader.LoadAsync("component", false)); + + Assert.True(fixture.Loader.IsHelpLoading); + Assert.Equal(["notify:IsHelpLoading"], fixture.Trace); + Assert.Empty(fixture.Requests); + } + + [Fact] + public async Task CancelDuringAcceptedUsageNotificationDoesNotAddALaterStaleGuard() + { + var fixture = new LoaderFixture(); + fixture.Loader.PropertyChanged += (_, args) => + { + if (args.PropertyName == "UsageText" && fixture.Loader.UsageText == "accepted") fixture.Loader.Cancel(); + }; + var load = fixture.Loader.LoadAsync("component", false); + + fixture.Requests[0].Reply.SetResult(Document("accepted")); + await load; + + Assert.Contains("structure", fixture.Trace); + Assert.Contains("diagnostics", fixture.Trace); + Assert.Contains("status", fixture.Trace); + Assert.True(fixture.Loader.IsHelpLoading); + } + + [Fact] + public async Task AReentrantLoadCapturesItsOwnTokenBeforeLoadingNotifications() + { + var fixture = new LoaderFixture(); + Task? nested = null; + bool entered = false; + fixture.Loader.PropertyChanged += (_, args) => + { + if (args.PropertyName != "IsHelpLoading" || !fixture.Loader.IsHelpLoading || entered) return; + entered = true; + nested = fixture.Loader.LoadAsync("component", true); + }; + + var outer = fixture.Loader.LoadAsync("component", false); + + Assert.Equal(2, fixture.Requests.Count); + Assert.True(fixture.Requests[0].ForceRefresh); + Assert.False(fixture.Requests[0].Token.IsCancellationRequested); + Assert.True(fixture.Requests[1].Token.IsCancellationRequested); + fixture.Requests[0].Reply.SetResult(Document("nested")); + await nested!; + fixture.Requests[1].Reply.SetResult(Document("outer")); + await outer; + Assert.Equal("nested", fixture.Loader.UsageText); + } + + private static ComponentCommandHelpDocument Document(string usage) => new() + { + ComponentId = "component", Usage = usage, + Options = [new() { Names = ["--flag"], Description = "Flag", Syntax = "--flag" }], + }; + + private sealed class LoaderFixture + { + public LoaderFixture() + { + Panel = new(key => key, () => false); + Loader = new(Panel, () => { Trace.Add("current:" + ComponentId); return ComponentId; }, Localize, + (id, token, force) => + { + Trace.Add($"load:{id}:{force}"); + var request = new LoadRequest(id, token, force); + Requests.Add(request); + return request.Reply.Task; + }, + () => { Trace.Add("structure"); OnStructure?.Invoke(); }, + () => Trace.Add("diagnostics"), _ => Trace.Add("status")); + Loader.PropertyChanged += (_, args) => Trace.Add("notify:" + args.PropertyName); + } + public List Trace { get; } = []; + public List Requests { get; } = []; + public string ComponentId { get; set; } = "component"; + public Exception? LocalizeError { get; set; } + public Action? OnStructure { get; set; } + public ConfigMakerCommandHelpPanel Panel { get; } + public ConfigMakerCommandHelpLoader Loader { get; } + private string Localize(string key) + { + Trace.Add("localize:" + key); + if (LocalizeError != null) throw LocalizeError; + return key == "ConfigMakerLoadingHelpMessage" ? "Loading" : "{0} loaded"; + } + } + + private sealed record LoadRequest(string ComponentId, CancellationToken Token, bool ForceRefresh) + { + public TaskCompletionSource Reply { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + } +} diff --git a/CDPIUI.Tests/Presentation/ConfigMakerCommandHelpPanelTests.cs b/CDPIUI.Tests/Presentation/ConfigMakerCommandHelpPanelTests.cs new file mode 100644 index 00000000..8f05c0c1 --- /dev/null +++ b/CDPIUI.Tests/Presentation/ConfigMakerCommandHelpPanelTests.cs @@ -0,0 +1,215 @@ +using System.Collections.Specialized; +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.Helper.CreateConfigHelper; + +namespace CDPIUI.Tests.Presentation; + +public class ConfigMakerCommandHelpPanelTests +{ + [Fact] + public void ModulesRetainFirstAppearanceOrderAndIncludeGeneralOnlyWhenNeeded() + { + var panel = CreatePanel(); + panel.Document = new() { Options = [Option("--b", "Beta"), Option("--a", "Alpha"), Option("--other", "beta"), Option("--general")] }; + + panel.RebuildCommandModules(); + + Assert.Equal(["All", "General", "Beta", "Alpha"], panel.CommandModules.Select(module => module.DisplayName)); + Assert.True(panel.HasCommandModules); + Assert.True(((ConfigMakerCommandModuleViewModel)panel.SelectedCommandModule!).IsAll); + Assert.Equal(["--a", "--b", "--general", "--other"], panel.CommandOptions.Select(option => option.DisplayName)); + } + + [Fact] + public void UnnamedOnlyHelpKeepsOneAllModuleAndHidesTheModuleSelector() + { + var panel = CreatePanel(); + panel.Document = new() { Options = [Option("--one"), Option("--two")] }; + + panel.RebuildCommandModules(); + + Assert.False(panel.HasCommandModules); + Assert.True(Assert.Single(panel.CommandModules).IsAll); + Assert.Equal(2, panel.CommandOptions.Count); + } + + [Fact] + public void ReloadRestoresThePreviousGroupIgnoringCase() + { + var panel = CreatePanel(); + panel.Document = new() { Options = [Option("--before", "Old")] }; + panel.RebuildCommandModules(); + panel.SelectedCommandModule = panel.CommandModules.Single(module => !module.IsAll); + panel.Document = new() { Options = [Option("--after", "OLD"), Option("--other", "Other")] }; + + panel.RebuildCommandModules(); + + Assert.Equal("OLD", ((ConfigMakerCommandModuleViewModel)panel.SelectedCommandModule!).GroupName); + Assert.Equal("--after", Assert.Single(panel.CommandOptions).DisplayName); + } + + [Fact] + public void RemovedPreviousGroupFallsBackToAll() + { + var panel = CreatePanel(); + panel.Document = new() { Options = [Option("--old", "Old")] }; + panel.RebuildCommandModules(); + panel.SelectedCommandModule = panel.CommandModules[1]; + panel.Document = new() { Options = [Option("--new", "New")] }; + + panel.RebuildCommandModules(); + + Assert.True(((ConfigMakerCommandModuleViewModel)panel.SelectedCommandModule!).IsAll); + Assert.Equal("--new", Assert.Single(panel.CommandOptions).DisplayName); + } + + [Theory] + [InlineData(" FLAG ", "--flag")] + [InlineData("SYNTAX-TOKEN", "--syntax")] + [InlineData("description-token", "--description")] + public void SearchTrimsAndMatchesNameSyntaxOrDescription(string query, string expected) + { + var panel = CreatePanel(); + panel.Document = new() { Options = [Option("--flag"), Option("--syntax", syntax: "syntax-token"), Option("--description", description: "DESCRIPTION-token")] }; + + panel.CommandSearchText = query; + + Assert.Equal(expected, Assert.Single(panel.CommandOptions).DisplayName); + } + + [Fact] + public void SearchAndModuleFiltersAreCombined() + { + var panel = CreatePanel(); + panel.Document = new() { Options = [Option("--flag-one", "First"), Option("--flag-two", "Second")] }; + panel.RebuildCommandModules(); + panel.SelectedCommandModule = panel.CommandModules[1]; + + panel.CommandSearchText = "flag"; + + Assert.Equal("--flag-one", Assert.Single(panel.CommandOptions).DisplayName); + } + + [Fact] + public void MissingDescriptionGetsLocalizedWithoutChangingTheSource() + { + var panel = CreatePanel(); + var option = Option("--flag"); + panel.Document = new() { Options = [option] }; + + panel.RebuildCommandOptions(); + + var result = Assert.Single(panel.CommandOptions); + Assert.Same(option, result.Source); + Assert.Equal("No description", result.Description); + Assert.Empty(option.Description); + } + + [Fact] + public void SelectingACommandNotifiesArgumentFieldsBeforeSelectionProperties() + { + var panel = CreatePanel(); + panel.CommandArgumentText = "old"; + List notifications = []; + panel.PropertyChanged += (_, args) => notifications.Add(args.PropertyName); + + panel.SelectCommand(new() { Source = Option("--port", placeholder: "", required: true), Description = "Port" }); + + Assert.Equal(["CommandArgumentText", "CommandArgumentPlaceholder", "CommandArgumentLabel", "SelectedCommandName", + "SelectedCommandSyntax", "SelectedCommandDescription", "HasCommandArgument", "HasSelectedCommand", "CanInsertCommand"], notifications); + Assert.Equal("Required: ", panel.CommandArgumentLabel); + Assert.Empty(panel.CommandArgumentText); + Assert.True(panel.HasCommandArgument); + } + + [Fact] + public void SelectingNullRetainsArgumentFieldsButClearsSelectionProperties() + { + var panel = CreatePanel(); + panel.SelectCommand(new() { Source = Option("--port", placeholder: "") }); + panel.CommandArgumentText = "1234"; + + panel.SelectCommand(null); + + Assert.False(panel.HasSelectedCommand); + Assert.False(panel.CanInsertCommand); + Assert.False(panel.HasCommandArgument); + Assert.Empty(panel.SelectedCommandName); + Assert.Equal("1234", panel.CommandArgumentText); + Assert.Equal("", panel.CommandArgumentPlaceholder); + Assert.Equal("Optional: ", panel.CommandArgumentLabel); + } + + [Theory] + [InlineData(true, "", null)] + [InlineData(false, "", "--port")] + [InlineData(true, " 1234 ", "--port=1234")] + public void SelectedCommandRetainsRequiredOptionalAndEqualsArgumentRules(bool required, string value, string? expected) + { + var panel = CreatePanel(); + panel.SelectCommand(new() { Source = Option("--port", syntax: "--port=", placeholder: "", required: required) }); + panel.CommandArgumentText = value; + + Assert.Equal(expected, panel.BuildSelectedCommand()); + } + + [Fact] + public void InsertAvailabilityReadsTheCurrentReadonlyState() + { + bool readOnly = false; + var panel = new ConfigMakerCommandHelpPanel(Localize, () => readOnly); + panel.SelectCommand(new() { Source = Option("--flag") }); + + Assert.True(panel.CanInsertCommand); + readOnly = true; + Assert.False(panel.CanInsertCommand); + } + + [Fact] + public void ReassigningSearchStillRebuildsTheSameCollection() + { + var panel = CreatePanel(); + var collection = panel.CommandOptions; + int resets = 0; + collection.CollectionChanged += (_, args) => { if (args.Action == NotifyCollectionChangedAction.Reset) resets++; }; + + panel.CommandSearchText = "flag"; + panel.CommandSearchText = "flag"; + + Assert.Same(collection, panel.CommandOptions); + Assert.Equal(2, resets); + } + + [Fact] + public void ReentrantSelectionNotificationUsesTheNewSearchQuery() + { + var panel = CreatePanel(); + panel.Document = new() { Options = [Option("--first", "Group"), Option("--second", "Group")] }; + panel.RebuildCommandModules(); + panel.PropertyChanged += (_, args) => + { + if (args.PropertyName == "SelectedCommandModule") panel.CommandSearchText = "second"; + }; + + panel.SelectedCommandModule = panel.CommandModules[1]; + + Assert.Equal("--second", Assert.Single(panel.CommandOptions).DisplayName); + } + + private static ConfigMakerCommandHelpPanel CreatePanel() => new(Localize, () => false); + + private static ComponentCommandHelpOption Option(string name, string group = "", string syntax = "", string description = "", string placeholder = "", bool required = false) => new() + { + Names = [name], GroupName = group, Syntax = syntax, Description = description, + ArgumentPlaceholder = placeholder, IsArgumentRequired = required, + }; + + private static string Localize(string key) => key switch + { + "ConfigMakerAllModules" => "All", "ConfigMakerGeneralModule" => "General", + "ConfigMakerNoDescriptionMessage" => "No description", + "ConfigMakerRequiredArgumentLabel" => "Required: {0}", + "ConfigMakerOptionalArgumentLabel" => "Optional: {0}", + _ => key, + }; +} diff --git a/CDPIUI.Tests/Presentation/ConfigMakerDiagnosticsTests.cs b/CDPIUI.Tests/Presentation/ConfigMakerDiagnosticsTests.cs new file mode 100644 index 00000000..f7ad95f4 --- /dev/null +++ b/CDPIUI.Tests/Presentation/ConfigMakerDiagnosticsTests.cs @@ -0,0 +1,328 @@ +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.Globalization; +using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.ViewModels; + +namespace CDPIUI.Tests.Presentation; + +public sealed class ConfigMakerDiagnosticsTests +{ + [Fact] + public void ConstructorStoresSameCollectionWithoutCallingPorts() + { + var f = new Fixture(); + Assert.Empty(f.Trace); Assert.Empty(f.Rows); + Assert.Equal("", f.Owner.ErrorCountText); Assert.Equal("", f.Owner.WarningCountText); + } + + [Fact] + public void RebuildReadsEditorThenCurrentOptionsAndAppendsReferencesAfterValidationResults() + { + var f = new Fixture { Command = "preset://missing --unknown\n--need" }; + f.OnEditor = () => f.Options = [NeedOption()]; + f.Owner.Rebuild(); + Assert.Equal(["editor", "options", "resource:preset://missing", "collection:Reset"], f.Trace.Take(4)); + Assert.Equal(["CFG001", "CFG002", "CFG005"], f.Rows.Select(row => row.Source.Code)); + Assert.Equal([1, 2, 1], f.Rows.Select(row => row.Source.Line)); + Assert.Equal("ConfigMakerDiagnosticErrorCount=2", f.Owner.ErrorCountText); + Assert.Equal("ConfigMakerDiagnosticWarningCount=1", f.Owner.WarningCountText); + Assert.Equal("highlight", f.Trace.Last()); + Assert.All(f.Rows, row => Assert.Same(row.Source, f.Projected.Single(d => ReferenceEquals(d, row.Source)))); + } + + [Fact] + public void CurrentInputsAreReadOnEveryRebuildAndExistingCollectionIsReused() + { + var f = new Fixture { Command = "--need" }; + f.Owner.Rebuild(); var first = Assert.Single(f.Rows); + f.Command = "--need value"; f.Owner.Rebuild(); Assert.Empty(f.Rows); + f.Command = "--unknown"; f.Options = []; f.Owner.Rebuild(); Assert.Empty(f.Rows); + f.Options = [NeedOption()]; f.Owner.Rebuild(); + Assert.Equal("CFG001", Assert.Single(f.Rows).Source.Code); + Assert.DoesNotContain(first, f.Rows); + Assert.Equal(4, f.Trace.Count(x => x == "editor")); + Assert.Equal(4, f.Trace.Count(x => x == "options")); + } + + [Fact] + public void ActualVariableCollectionAndCurrentResourcePredicateAreUsed() + { + var f = new Fixture { Command = "%KNOWN% %CURRENT% preset://attached" }; + f.Variables.Add(new() { Name = "known" }); + f.KnownResource = true; f.Owner.Rebuild(); Assert.Empty(f.Rows); + f.KnownResource = false; f.Owner.Rebuild(); + Assert.Equal("CFG005", Assert.Single(f.Rows).Source.Code); + Assert.Equal(2, f.Trace.Count(x => x == "resource:preset://attached")); + } + + [Theory] + [InlineData(ComponentCommandDiagnosticSeverity.Error, "ConfigMakerDiagnosticErrorSeverity")] + [InlineData(ComponentCommandDiagnosticSeverity.Warning, "ConfigMakerDiagnosticWarningSeverity")] + [InlineData((ComponentCommandDiagnosticSeverity)99, "ConfigMakerDiagnosticWarningSeverity")] + public void SeverityLocalizationRetainsFallback(ComponentCommandDiagnosticSeverity severity, string key) + { + var f = new Fixture(); + Assert.Equal(key, f.Owner.GetSeverityText(new() { Severity = severity })); + Assert.Equal(["text:" + key], f.Trace); + } + + [Theory] + [InlineData(ComponentCommandDiagnosticKind.UnknownFlag, "ConfigMakerUnknownFlagDiagnostic", true)] + [InlineData(ComponentCommandDiagnosticKind.MissingRequiredArgument, "ConfigMakerMissingArgumentDiagnostic", true)] + [InlineData(ComponentCommandDiagnosticKind.UnresolvedVariable, "ConfigMakerUnresolvedVariableDiagnostic", true)] + [InlineData(ComponentCommandDiagnosticKind.UnresolvedResource, "ConfigMakerUnresolvedResourceDiagnostic", true)] + [InlineData(ComponentCommandDiagnosticKind.UnterminatedQuote, "ConfigMakerUnterminatedQuoteDiagnostic", false)] + [InlineData((ComponentCommandDiagnosticKind)99, "ConfigMakerUnterminatedQuoteDiagnostic", false)] + public void DescriptionRetainsKindTokenAndFallback(ComponentCommandDiagnosticKind kind, string key, bool format) + { + var f = new Fixture(); + f.Localize = k => k + "<{0}>"; + Assert.Equal(key + (format ? "<--token={x}>" : "<{0}>"), + f.Owner.GetDescription(new() { Kind = kind, Token = "--token={x}" })); + Assert.Equal(["text:" + key], f.Trace); + } + + [Fact] + public void FormattingUsesCurrentCultureAtCallTime() + { + var f = new Fixture { Command = "--need" }; + f.Localize = key => key.EndsWith("Count", StringComparison.Ordinal) ? "{0:N1}" : key; + var previous = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR"); f.Owner.Rebuild(); + Assert.Equal("1,0", f.Owner.ErrorCountText); Assert.Equal("0,0", f.Owner.WarningCountText); + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); f.Owner.Rebuild(); + Assert.Equal("1.0", f.Owner.ErrorCountText); Assert.Equal("0.0", f.Owner.WarningCountText); + } + finally { CultureInfo.CurrentCulture = previous; } + } + + [Fact] + public void CounterEventsFollowAllRowsAndEqualitySuppressesOnlyUnchangedCounters() + { + var f = new Fixture { Command = "--need" }; + f.Owner.Rebuild(); + Assert.Equal(["collection:Reset", "project:CFG002", "text:ConfigMakerDiagnosticErrorSeverity", + "text:ConfigMakerMissingArgumentDiagnostic", "collection:Add", "text:ConfigMakerDiagnosticErrorCount", + "property:ErrorCountText", "text:ConfigMakerDiagnosticWarningCount", "property:WarningCountText", "highlight"], f.Trace.Skip(2)); + f.Trace.Clear(); f.Owner.Rebuild(); + Assert.DoesNotContain(f.Trace, x => x.StartsWith("property:", StringComparison.Ordinal)); + Assert.Contains("collection:Reset", f.Trace); Assert.Contains("collection:Add", f.Trace); + Assert.Equal("highlight", f.Trace.Last()); + } + + [Theory] + [InlineData("editor")] + [InlineData("options")] + [InlineData("resource")] + public void InputFailureBeforeClearPreservesPreviousRowsAndCounters(string endpoint) + { + var f = new Fixture { Command = "--need" }; f.Owner.Rebuild(); + var old = Assert.Single(f.Rows); var error = f.Owner.ErrorCountText; var warning = f.Owner.WarningCountText; + f.Command = "preset://missing"; f.Trace.Clear(); + f.OnEditor = () => { if (endpoint == "editor") throw new IOException("editor"); }; + f.OnOptions = () => { if (endpoint == "options") throw new IOException("options"); }; + f.OnResource = () => { if (endpoint == "resource") throw new IOException("resource"); }; + Assert.Throws(f.Owner.Rebuild); + Assert.Same(old, Assert.Single(f.Rows)); + Assert.Equal(error, f.Owner.ErrorCountText); Assert.Equal(warning, f.Owner.WarningCountText); + Assert.DoesNotContain("collection:Reset", f.Trace); Assert.DoesNotContain("highlight", f.Trace); + } + + [Fact] + public void ClearObserverFailureLeavesClearedCollectionAndPreviousCounters() + { + var f = new Fixture { Command = "--need" }; f.Owner.Rebuild(); f.Trace.Clear(); + f.Rows.CollectionChanged += (_, e) => { if (e.Action == NotifyCollectionChangedAction.Reset) throw new IOException("clear"); }; + Assert.Throws(f.Owner.Rebuild); Assert.Empty(f.Rows); + Assert.Equal("ConfigMakerDiagnosticErrorCount=1", f.Owner.ErrorCountText); + Assert.DoesNotContain("highlight", f.Trace); Assert.DoesNotContain(f.Trace, x => x.StartsWith("project:", StringComparison.Ordinal)); + } + + [Fact] + public void FactoryFailureLeavesEarlierRowsButNotCountsOrHighlight() + { + var f = new Fixture { Command = "--unknown --need" }; + f.OnProject = d => { if (d.Code == "CFG002") throw new IOException("factory"); }; + Assert.Throws(f.Owner.Rebuild); + Assert.Equal("CFG001", Assert.Single(f.Rows).Source.Code); + Assert.Equal("", f.Owner.ErrorCountText); Assert.Equal("", f.Owner.WarningCountText); + Assert.DoesNotContain("highlight", f.Trace); + } + + [Fact] + public void AddObserverFailureRetainsAlreadyAddedRowAndSkipsCounts() + { + var f = new Fixture { Command = "--need" }; + f.Rows.CollectionChanged += (_, e) => { if (e.Action == NotifyCollectionChangedAction.Add) throw new IOException("add"); }; + Assert.Throws(f.Owner.Rebuild); Assert.Single(f.Rows); + Assert.Equal("", f.Owner.ErrorCountText); Assert.DoesNotContain("highlight", f.Trace); + } + + [Theory] + [InlineData("ConfigMakerDiagnosticErrorSeverity", false)] + [InlineData("ConfigMakerMissingArgumentDiagnostic", false)] + [InlineData("ConfigMakerDiagnosticErrorCount", false)] + [InlineData("ConfigMakerDiagnosticWarningCount", true)] + public void LocalizationFailurePreservesExactPartialCounterStage(string key, bool assignedError) + { + var f = new Fixture { Command = "--need" }; + f.Localize = k => k == key ? throw new IOException("text") : Fixture.DefaultText(k); + Assert.Throws(f.Owner.Rebuild); + Assert.Equal(assignedError ? "ConfigMakerDiagnosticErrorCount=1" : "", f.Owner.ErrorCountText); + Assert.Equal("", f.Owner.WarningCountText); Assert.DoesNotContain("highlight", f.Trace); + Assert.Equal(key.EndsWith("Count", StringComparison.Ordinal) ? 1 : 0, f.Rows.Count); + } + + [Theory] + [InlineData("ErrorCountText", "")] + [InlineData("WarningCountText", "ConfigMakerDiagnosticWarningCount=0")] + public void CounterObserverFailureKeepsAssignmentAndStopsLaterCallbacks(string name, string warning) + { + var f = new Fixture { Command = "--need" }; + f.Observe = n => { if (n == name) throw new IOException("counter"); }; + Assert.Throws(f.Owner.Rebuild); + Assert.Equal("ConfigMakerDiagnosticErrorCount=1", f.Owner.ErrorCountText); + Assert.Equal(warning, f.Owner.WarningCountText); Assert.DoesNotContain("highlight", f.Trace); + } + + [Fact] + public void HighlightFailureOccursAfterCollectionAndBothCounters() + { + var f = new Fixture { Command = "--need" }; f.OnHighlight = () => throw new IOException("highlight"); + Assert.Throws(f.Owner.Rebuild); Assert.Single(f.Rows); + Assert.Equal("ConfigMakerDiagnosticErrorCount=1", f.Owner.ErrorCountText); + Assert.Equal("ConfigMakerDiagnosticWarningCount=0", f.Owner.WarningCountText); + } + + [Fact] + public void ReentryFromClearKeepsOuterResultsAndContinuesAfterNestedRebuild() + { + var f = new Fixture { Command = "--unknown --need" }; bool entered = false; + f.OnCollection = e => + { + if (e.Action == NotifyCollectionChangedAction.Reset && !entered) { entered = true; f.Command = ""; f.Owner.Rebuild(); } + }; + f.Owner.Rebuild(); + Assert.Equal(["CFG001", "CFG002"], f.Rows.Select(x => x.Source.Code)); + Assert.Equal("ConfigMakerDiagnosticErrorCount=1", f.Owner.ErrorCountText); + Assert.Equal("ConfigMakerDiagnosticWarningCount=1", f.Owner.WarningCountText); + Assert.Equal(2, f.Trace.Count(x => x == "highlight")); + } + + [Fact] + public void ReentryFromErrorCounterKeepsOriginalOuterWarningContinuation() + { + var f = new Fixture { Command = "--unknown --need" }; bool entered = false; + f.Observe = name => + { + if (name == "ErrorCountText" && !entered) { entered = true; f.Command = ""; f.Owner.Rebuild(); } + }; + f.Owner.Rebuild(); Assert.Empty(f.Rows); + Assert.Equal("ConfigMakerDiagnosticErrorCount=0", f.Owner.ErrorCountText); + Assert.Equal("ConfigMakerDiagnosticWarningCount=1", f.Owner.WarningCountText); + Assert.Equal(2, f.Trace.Count(x => x == "highlight")); + } + + [Fact] + public void CollectionObserversMayAlterPublishedRowsWithoutChangingOuterResultCounts() + { + var f = new Fixture { Command = "--need" }; bool entered = false; + f.OnCollection = e => + { + if (e.Action == NotifyCollectionChangedAction.Add && !entered) { entered = true; f.Rows.Clear(); } + }; + f.Owner.Rebuild(); Assert.Empty(f.Rows); + Assert.Equal("ConfigMakerDiagnosticErrorCount=1", f.Owner.ErrorCountText); + Assert.Equal("ConfigMakerDiagnosticWarningCount=0", f.Owner.WarningCountText); + } + + [Fact] + public void ReentryFromFactoryRetainsOuterRowAndCounterSnapshot() + { + var f = new Fixture { Command = "--need" }; bool entered = false; + f.OnProject = _ => { if (!entered) { entered = true; f.Command = ""; f.Owner.Rebuild(); } }; + f.Owner.Rebuild(); Assert.Single(f.Rows); + Assert.Equal("ConfigMakerDiagnosticErrorCount=1", f.Owner.ErrorCountText); + Assert.Equal(2, f.Trace.Count(x => x == "highlight")); + } + + [Fact] + public void ReentryFromSeverityLocalizationKeepsOuterProjectionAndCounts() + { + var f = new Fixture { Command = "--need" }; bool entered = false; + f.Localize = key => + { + if (key == "ConfigMakerDiagnosticErrorSeverity" && !entered) { entered = true; f.Command = ""; f.Owner.Rebuild(); } + return Fixture.DefaultText(key); + }; + f.Owner.Rebuild(); Assert.Single(f.Rows); + Assert.Equal("ConfigMakerDiagnosticErrorCount=1", f.Owner.ErrorCountText); + Assert.Equal(2, f.Trace.Count(x => x == "highlight")); + } + + [Fact] + public void ReentryFromHighlightPublishesNestedFinalState() + { + var f = new Fixture { Command = "--need" }; bool entered = false; + f.OnHighlight = () => { if (!entered) { entered = true; f.Command = ""; f.Owner.Rebuild(); } }; + f.Owner.Rebuild(); Assert.Empty(f.Rows); + Assert.Equal("ConfigMakerDiagnosticErrorCount=0", f.Owner.ErrorCountText); + Assert.Equal(2, f.Trace.Count(x => x == "highlight")); + } + + [Theory] + [InlineData("ConfigMakerDiagnosticErrorCount", "")] + [InlineData("ConfigMakerDiagnosticWarningCount", "ConfigMakerDiagnosticErrorCount=1")] + public void InvalidCounterFormatPreservesEarlierAssignments(string key, string error) + { + var f = new Fixture { Command = "--need" }; + f.Localize = k => k == key ? "{not-a-number}" : Fixture.DefaultText(k); + Assert.Throws(f.Owner.Rebuild); Assert.Single(f.Rows); + Assert.Equal(error, f.Owner.ErrorCountText); Assert.Equal("", f.Owner.WarningCountText); + Assert.DoesNotContain("highlight", f.Trace); + } + + [Fact] + public void MultipleCollectionListenersKeepObservableCollectionReentryGuard() + { + var f = new Fixture { Command = "--need" }; + f.Rows.CollectionChanged += (_, e) => { if (e.Action == NotifyCollectionChangedAction.Add) f.Rows.Clear(); }; + Assert.Throws(f.Owner.Rebuild); Assert.Single(f.Rows); + Assert.Equal("", f.Owner.ErrorCountText); Assert.DoesNotContain("highlight", f.Trace); + } + + private static ComponentCommandHelpOption NeedOption() => new() { Names = ["--need"], Syntax = "--need ", IsArgumentRequired = true }; + private sealed record Row(ComponentCommandDiagnostic Source, string Severity, string Description); + private sealed class Fixture + { + public Fixture() + { + Rows.CollectionChanged += (_, e) => { Trace.Add("collection:" + e.Action); OnCollection?.Invoke(e); }; + Owner = new(Rows, () => { Trace.Add("editor"); OnEditor?.Invoke(); return Command; }, + () => { Trace.Add("options"); OnOptions?.Invoke(); return Options; }, Variables, + reference => { Trace.Add("resource:" + reference); OnResource?.Invoke(); return KnownResource; }, + d => { Trace.Add("project:" + d.Code); Projected.Add(d); OnProject?.Invoke(d); return new(d, Owner!.GetSeverityText(d), Owner.GetDescription(d)); }, + key => { Trace.Add("text:" + key); return Localize is null ? DefaultText(key) : Localize(key); }, + () => { Trace.Add("highlight"); OnHighlight?.Invoke(); }); + Owner.PropertyChanged += (sender, e) => { Assert.Same(Owner, sender); Trace.Add("property:" + e.PropertyName); Observe?.Invoke(e.PropertyName!); }; + } + public ConfigMakerDiagnostics Owner { get; } + public ObservableCollection Rows { get; } = []; + public ObservableCollection Variables { get; } = []; + public IReadOnlyList Options { get; set; } = [NeedOption()]; + public List Trace { get; } = []; + public List Projected { get; } = []; + public string Command { get; set; } = ""; + public bool KnownResource { get; set; } + public Action? OnEditor, OnOptions, OnResource, OnHighlight; + public Action? OnProject; + public Action? OnCollection; + public Action? Observe; + public Func? Localize; + public static string DefaultText(string key) => key.EndsWith("Count", StringComparison.Ordinal) ? key + "={0}" : + key == "ConfigMakerUnterminatedQuoteDiagnostic" || key.EndsWith("Severity", StringComparison.Ordinal) ? key : key + "({0})"; + } +} diff --git a/CDPIUI.Tests/Presentation/ConfigMakerDocumentCoordinatorTests.cs b/CDPIUI.Tests/Presentation/ConfigMakerDocumentCoordinatorTests.cs new file mode 100644 index 00000000..096ec2b8 --- /dev/null +++ b/CDPIUI.Tests/Presentation/ConfigMakerDocumentCoordinatorTests.cs @@ -0,0 +1,637 @@ +using CDPIUI.Core.ComponentServices.Helpers.Configuration; +using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.ViewModels; +using CDPIUI.ViewModels.ConfigMaker; + +namespace CDPIUI.Tests.Presentation; + +public sealed class ConfigMakerDocumentCoordinatorTests +{ + [Fact] + public void LoadRetainsCollectionsClonesItemsAndPublishesCallbacksAfterMetadata() + { + var f = new Fixture(); + var source = Document(); + var variables = f.Document.Variables; + var resources = f.Document.Resources; + f.Host.ComponentSet = value => + { + Assert.Equal("component", value); + Assert.Equal("pack", f.Document.PackId); + Assert.Equal("file", f.Document.FileName); + Assert.Equal("meta", f.Document.Meta); + Assert.Equal("target-version", f.Document.TargetVersion); + Assert.Single(f.Document.Variables); + Assert.Single(f.Document.Resources); + }; + + f.Coordinator.LoadPresetDocument(source); + + Assert.Same(variables, f.Document.Variables); + Assert.Same(resources, f.Document.Resources); + Assert.NotSame(source.Variables[0], Assert.Single(variables)); + Assert.NotSame(source.Resources[0], Assert.Single(resources)); + Assert.NotSame(source.Variables[0].Values, variables[0].Values); + Assert.Equal(source.Variables[0].Id, variables[0].Id); + Assert.Equal(new[] { "one", "two" }, variables[0].Values); + Assert.Equal(new[] { "base:", "component:set:component", "editor:set:--source", "rebuild", "designer", "document:event" }, f.Host.Calls); + source.Variables[0].Value = "changed source"; + source.Resources[0].Path = "changed source"; + Assert.Equal("one", variables[0].Value); + Assert.Equal("resource-path", resources[0].Path); + } + + [Fact] + public void LoadOfTheCurrentDocumentKeepsBaselineSelfClearBehavior() + { + var f = new Fixture(Document()); + f.Coordinator.LoadPresetDocument(f.Document); + Assert.Empty(f.Document.Variables); + Assert.Empty(f.Document.Resources); + Assert.Equal("--source", f.Host.CurrentEditor); + Assert.Equal("pack", f.Document.PackId); + } + + [Fact] + public void LoadReadsSourceCommandAfterTheComponentCallback() + { + var f = new Fixture(); + var source = Document(); + f.Host.ComponentSet = _ => source.CommandText = "changed during component event"; + f.Coordinator.LoadPresetDocument(source); + Assert.Equal("changed during component event", f.Host.CurrentEditor); + } + + [Fact] + public void LoadReadsLaterMetadataAndItemsAfterDocumentNotifications() + { + var f = new Fixture(); + var source = Document(); + f.Document.PropertyChanged += (_, args) => + { + if (args.PropertyName != nameof(ConfigMakerPresetDocument.Name)) return; + source.ComponentId = "changed component"; + source.Meta = "changed metadata"; + source.Variables[0].Value = "changed variable"; + source.Resources[0].Path = "changed resource"; + }; + f.Coordinator.LoadPresetDocument(source); + Assert.Equal("changed component", f.Document.ComponentId); + Assert.Equal("changed metadata", f.Document.Meta); + Assert.Equal("changed variable", Assert.Single(f.Document.Variables).Value); + Assert.Equal("changed resource", Assert.Single(f.Document.Resources).Path); + } + + [Fact] + public void LoadFailurePreservesPublishedPartialStateAndStopsLaterCallbacks() + { + var f = new Fixture(); + var failure = new InvalidOperationException("rebuild failed"); + f.Host.Rebuild = () => throw failure; + Assert.Same(failure, Assert.Throws(() => f.Coordinator.LoadPresetDocument(Document()))); + Assert.Equal("pack", f.Document.PackId); + Assert.Equal("--source", f.Host.CurrentEditor); + Assert.DoesNotContain("designer", f.Host.Calls); + Assert.DoesNotContain("document:event", f.Host.Calls); + } + + [Fact] + public void LoadNullIsSynchronousAndHasNoEffects() + { + var f = new Fixture(); + Assert.Equal("document", Assert.Throws(() => f.Coordinator.LoadPresetDocument(null!)).ParamName); + Assert.Empty(f.Host.Calls); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ConfigLoadRetainsConversionAndCallbackOrder(bool correct) + { + var f = new Fixture(); + var item = Config(); + f.Host.ConfigDirectory = value => { Assert.Same(item, value); return "base-dir"; }; + f.Host.AutoCorrect = value => { Assert.Same(item, value); return Task.CompletedTask; }; + await f.Coordinator.LoadConfigItem(item, correct); + var expected = new List { "base:", "component:set:component", "editor:set:--source", "rebuild", "designer", "document:event", "base:get", "base:base-dir", "rebuild" }; + if (correct) expected.Add("autocorrect"); + expected.AddRange(["attach", "rebuild"]); + Assert.Equal(expected, f.Host.Calls); + Assert.Equal("pack", f.Document.PackId); + } + + [Fact] + public async Task ConfigLoadAwaitsCorrectionAndPropagatesItsFailureWithoutAttaching() + { + var f = new Fixture(); + var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Host.AutoCorrect = _ => pending.Task; + Task loading = f.Coordinator.LoadConfigItem(Config(), true); + Assert.False(loading.IsCompleted); + Assert.DoesNotContain("attach", f.Host.Calls); + var failure = new IOException("correction failed"); + pending.SetException(failure); + Assert.Same(failure, await Assert.ThrowsAsync(() => loading)); + Assert.DoesNotContain("attach", f.Host.Calls); + Assert.Equal("--source", f.Host.CurrentEditor); + } + + [Fact] + public async Task ConfigLoadNullReturnsAFaultedTaskBeforeAnyEffect() + { + var f = new Fixture(); + Task task = f.Coordinator.LoadConfigItem(null!); + Assert.Equal("item", (await Assert.ThrowsAsync(() => task)).ParamName); + Assert.Empty(f.Host.Calls); + } + + [Fact] + public void CreateUsesTheCurrentComponentAndEditorAndRealConverter() + { + var f = new Fixture(Document()); + f.Host.CurrentComponent = "edited-component"; + f.Host.CurrentEditor = "--edited"; + ConfigItem item = f.Coordinator.CreateConfigItem("new-pack", "New preset"); + Assert.Equal(new[] { "component:get", "editor:get" }, f.Host.Calls); + Assert.Equal("--edited", item.startup_string); + Assert.Equal(new[] { "edited-component", "target-version" }, item.target); + Assert.Equal("new-pack", item.packId); + Assert.Equal("New preset", item.name); + Assert.Equal("list", Assert.Single(item.configMaker!.resources!).alias); + } + + [Fact] + public void LegacyConditionalConversionUsesTheOriginalCoreParser() + { + var item = Config(); + item.variables = ["%Mode%=$LOCALCONDITION(mode_flag==true ? --on $SEPARATOR --off)"]; + item.jparams = new() { ["mode_flag"] = true }; + var result = ConfigMakerPresetDocument.FromConfigItem(item); + var variable = Assert.Single(result.Variables); + Assert.Equal("Mode", variable.Name); + Assert.Equal(ConfigMakerVariableKind.Switch, variable.Kind); + Assert.Equal(ConfigMakerVariableStorageKind.Conditional, variable.StorageKind); + Assert.Equal("mode_flag", variable.InternalParameterName); + Assert.Equal("--on", variable.OnValue); + Assert.Equal("--off", variable.OffValue); + Assert.True(variable.IsSwitchEnabled); + } + + [Fact] + public async Task SaveSyncsAgainAfterAttachmentAndCreatesStorageOnlyAfterDialog() + { + var f = new Fixture(Document()); + int reads = 0; + f.Host.ReadEditor = () => ++reads == 1 ? "before attach" : "after attach"; + f.Host.Attach = () => Assert.Equal("before attach", f.Document.CommandText); + var answer = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Host.AskSave = (name, overwrite) => + { + Assert.Equal("Source", name); + Assert.True(overwrite); + Assert.Equal("after attach", f.Document.CommandText); + return answer.Task; + }; + var result = new ConfigMakerPresetSaveResult { Success = true, PackId = "saved-pack", ConfigFileName = "saved-file" }; + f.Storage.Save = (name, document) => + { + Assert.Same(f.Document, document); + Assert.Equal("Chosen", name); + Assert.Equal("after attach", document.CommandText); + return Task.FromResult(result); + }; + Task saving = f.Coordinator.SaveToApplicationAsync(); + Assert.Equal(0, f.StorageCreations); + Assert.False(saving.IsCompleted); + answer.SetResult(new("Chosen", false)); + Assert.Same(result, await saving); + Assert.Equal(1, f.StorageCreations); + Assert.Equal(new[] { "component:get", "editor:get", "attach", "component:get", "editor:get", "save:ask", "storage:new", "storage:save", "text:ConfigMakerPresetSavedMessage", "notice:False:saved:Chosen" }, f.Host.Calls); + Assert.Equal("Chosen", f.Document.Name); + Assert.Equal("saved-pack", f.Document.PackId); + Assert.Equal("saved-file", f.Document.FileName); + } + + [Theory] + [InlineData(null, "file", false)] + [InlineData("pack", " ", false)] + [InlineData("pack", "file", true)] + public async Task SaveCancelDoesNotCreateStorageOrShowNotice(string? pack, string? file, bool enabled) + { + var f = new Fixture(Document()); + f.Document.PackId = pack; + f.Document.FileName = file; + f.Host.AskSave = (_, canOverwrite) => { Assert.Equal(enabled, canOverwrite); return Task.FromResult(null); }; + var result = await f.Coordinator.SaveToApplicationAsync(); + Assert.False(result.Success); + Assert.Equal("CANCELED", result.ErrorCode); + Assert.Equal(0, f.StorageCreations); + Assert.Empty(f.Host.Notices); + } + + [Fact] + public async Task OverwriteAppliesResultsToTheLiveDocumentWithoutReplacingItsName() + { + var f = new Fixture(Document()); + f.Host.AskSave = (_, _) => Task.FromResult(new("ignored name", true)); + var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Storage.Overwrite = document => { Assert.Same(f.Document, document); return pending.Task; }; + Task saving = f.Coordinator.SaveToApplicationAsync(); + f.Document.Name = "Live name"; + f.Document.Resources.Clear(); + var live = new ConfigMakerPresetResource { Alias = "LiSt", Path = "before" }; + f.Document.Resources.Add(live); + var result = new ConfigMakerPresetSaveResult { Success = true, PackId = "pack2", ConfigFileName = "file2", StoredResources = [new() { alias = "list", path = "after", isBuiltIn = true }] }; + pending.SetResult(result); + Assert.Same(result, await saving); + Assert.Equal("Live name", f.Document.Name); + Assert.Equal("after", live.Path); + Assert.True(live.IsBuiltIn); + Assert.Equal(("saved:Live name", false), Assert.Single(f.Host.Notices)); + Assert.DoesNotContain("storage:save", f.Host.Calls); + } + + [Fact] + public async Task StoredResourcesUseFirstAliasMatchAndSkipBlankPaths() + { + var f = new Fixture(Document()); + var first = f.Document.Resources[0]; + var absent = new ConfigMakerPresetResource { Alias = "absent", Path = "untouched" }; + f.Document.Resources.Add(absent); + f.Storage.Result = new() { Success = true, StoredResources = [new() { alias = "LIST", path = " " }, new() { alias = "list", path = "must-not-use", isBuiltIn = true }] }; + await f.Coordinator.SaveToApplicationAsync(); + Assert.Equal("resource-path", first.Path); + Assert.False(first.IsBuiltIn); + Assert.Equal("untouched", absent.Path); + } + + [Fact] + public async Task ResourceNotificationFailureKeepsMetadataAndPathAlreadyPublished() + { + var f = new Fixture(Document()); + var resource = f.Document.Resources[0]; + var failure = new IOException("resource subscriber"); + resource.PropertyChanged += (_, args) => + { + if (args.PropertyName == nameof(ConfigMakerPresetResource.Path)) throw failure; + }; + f.Storage.Result = new() { Success = true, PackId = "published pack", ConfigFileName = "published file", StoredResources = [new() { alias = "LIST", path = "published path", isBuiltIn = true }] }; + Assert.Same(failure, await Assert.ThrowsAsync(() => f.Coordinator.SaveToApplicationAsync())); + Assert.Equal("Chosen", f.Document.Name); + Assert.Equal("published pack", f.Document.PackId); + Assert.Equal("published file", f.Document.FileName); + Assert.Equal("published path", resource.Path); + Assert.False(resource.IsBuiltIn); + Assert.Empty(f.Host.Notices); + } + + [Theory] + [InlineData("CANCELED", "details", null)] + [InlineData("canceled", "details", "failed:details")] + [InlineData("FAILED", " ", "failed:FAILED")] + [InlineData("FAILED", "actual", "failed:actual")] + public async Task SaveFailureUsesOrdinalCancelAndDetailsFallback(string code, string details, string? expected) + { + var f = new Fixture(Document()); + var result = ConfigMakerPresetSaveResult.Failed(code, details); + f.Storage.Result = result; + Assert.Same(result, await f.Coordinator.SaveToApplicationAsync()); + Assert.Equal("Source", f.Document.Name); + Assert.Equal("pack", f.Document.PackId); + if (expected == null) Assert.Empty(f.Host.Notices); + else Assert.Equal((expected, true), Assert.Single(f.Host.Notices)); + } + + [Theory] + [InlineData("dialog")] + [InlineData("factory")] + [InlineData("storage")] + [InlineData("notice")] + public async Task SaveDoesNotCatchExternalFailures(string point) + { + var f = new Fixture(Document()); + var failure = new InvalidOperationException(point); + if (point == "dialog") f.Host.AskSave = (_, _) => throw failure; + if (point == "factory") f.Factory = () => throw failure; + if (point == "storage") f.Storage.Save = (_, _) => Task.FromException(failure); + if (point == "notice") { f.Storage.Result = new() { Success = true, PackId = "published" }; f.Host.Notice = (_, _) => throw failure; } + Assert.Same(failure, await Assert.ThrowsAsync(() => f.Coordinator.SaveToApplicationAsync())); + if (point == "notice") Assert.Equal("published", f.Document.PackId); + } + + [Fact] + public async Task OverlappingSavesRetainCompletionOrderWithoutSerialization() + { + var f = new Fixture(Document()); + var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var second = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + int count = 0; + f.Storage.Save = (_, document) => { Assert.Same(f.Document, document); return ++count == 1 ? first.Task : second.Task; }; + var a = f.Coordinator.SaveToApplicationAsync(); + var b = f.Coordinator.SaveToApplicationAsync(); + Assert.Equal(2, count); + second.SetResult(new() { Success = true, PackId = "second" }); + await b; + Assert.Equal("second", f.Document.PackId); + first.SetResult(new() { Success = true, PackId = "first" }); + await a; + Assert.Equal("first", f.Document.PackId); + } + + [Fact] + public async Task ReadonlyNewDoesNotReadTextOrTouchDocument() + { + var f = new Fixture(Document()); + f.Host.ReadOnly = true; + await f.Coordinator.NewDocumentAsync(); + Assert.Equal(new[] { "readonly:get" }, f.Host.Calls); + Assert.Single(f.Document.Variables); + } + + [Fact] + public async Task NewEmptyContentDoesNotAskAndKeepsOtherMetadata() + { + var f = new Fixture(Document()); + f.Document.Variables.Clear(); + f.Document.Resources.Clear(); + f.Host.CurrentEditor = " "; + await f.Coordinator.NewDocumentAsync(); + Assert.DoesNotContain("new:confirm", f.Host.Calls); + Assert.Equal(new[] { "readonly:get", "editor:get", "editor:set:", "base:", "structure:clear", "undo:clear" }, f.Host.Calls); + Assert.Equal(string.Empty, f.Document.Name); + Assert.Equal("pack", f.Document.PackId); + Assert.Equal("file", f.Document.FileName); + Assert.Equal("component", f.Document.ComponentId); + Assert.Equal("meta", f.Document.Meta); + Assert.Equal("target-version", f.Document.TargetVersion); + } + + [Fact] + public async Task NewCanceledDoesNotClearAnything() + { + var f = new Fixture(Document()); + f.Host.Confirm = () => Task.FromResult(false); + await f.Coordinator.NewDocumentAsync(); + Assert.Equal(new[] { "readonly:get", "editor:get", "new:confirm" }, f.Host.Calls); + Assert.Single(f.Document.Variables); + Assert.Single(f.Document.Resources); + Assert.Equal("Source", f.Document.Name); + } + + [Theory] + [InlineData(true, false)] + [InlineData(false, true)] + public async Task NewAsksForVariablesOrResourcesEvenWithEmptyText(bool variables, bool resources) + { + var f = new Fixture(Document()); + f.Host.CurrentEditor = ""; + if (!variables) f.Document.Variables.Clear(); + if (!resources) f.Document.Resources.Clear(); + f.Host.Confirm = () => Task.FromResult(false); + await f.Coordinator.NewDocumentAsync(); + Assert.Contains("new:confirm", f.Host.Calls); + Assert.Equal(variables, f.Document.HasVariables); + Assert.Equal(resources, f.Document.HasResources); + Assert.DoesNotContain("structure:clear", f.Host.Calls); + } + + [Fact] + public async Task NewConfirmationFailurePropagatesWithoutClearing() + { + var f = new Fixture(Document()); + var failure = new IOException("confirmation failed"); + f.Host.Confirm = () => Task.FromException(failure); + Assert.Same(failure, await Assert.ThrowsAsync(() => f.Coordinator.NewDocumentAsync())); + Assert.Single(f.Document.Variables); + Assert.Single(f.Document.Resources); + Assert.DoesNotContain("editor:set:", f.Host.Calls); + } + + [Fact] + public async Task NewKeepsTheOriginalSingleReadonlyCheckAndClearEventOrder() + { + var f = new Fixture(Document()); + var answer = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Host.Confirm = () => answer.Task; + f.Document.PropertyChanged += (_, e) => { if (e.PropertyName == nameof(ConfigMakerPresetDocument.Name)) f.Host.Calls.Add("name:changed"); }; + f.Document.Variables.CollectionChanged += (_, _) => f.Host.Calls.Add("variables:clear"); + f.Document.Resources.CollectionChanged += (_, _) => f.Host.Calls.Add("resources:clear"); + Task creating = f.Coordinator.NewDocumentAsync(); + Assert.False(creating.IsCompleted); + f.Host.ReadOnly = true; + answer.SetResult(true); + await creating; + Assert.Equal(new[] { "readonly:get", "editor:get", "new:confirm", "editor:set:", "base:", "name:changed", "variables:clear", "resources:clear", "structure:clear", "undo:clear" }, f.Host.Calls); + Assert.Empty(f.Document.Variables); + Assert.Empty(f.Document.Resources); + } + + [Fact] + public async Task NewFailureLeavesBaselinePartialStateAndDoesNotClearUndo() + { + var f = new Fixture(Document()); + var failure = new IOException("clear failed"); + f.Host.ClearStructure = () => throw failure; + Assert.Same(failure, await Assert.ThrowsAsync(() => f.Coordinator.NewDocumentAsync())); + Assert.Empty(f.Document.Variables); + Assert.Empty(f.Document.Resources); + Assert.DoesNotContain("undo:clear", f.Host.Calls); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ExportUsesVariableGateAndLiveDocumentAfterPicker(bool variables) + { + var f = new Fixture(Document()); + if (!variables) f.Document.Variables.Clear(); + f.Host.ExportPath = allow => { Assert.Equal(!variables, allow); f.Host.CurrentEditor = "changed in picker"; return "chosen.CDPICONFIG"; }; + f.Export = (document, path) => + { + Assert.Same(f.Document, document); + Assert.Equal("chosen.CDPICONFIG", path); + Assert.Equal("changed in picker", document.CommandText); + return Task.CompletedTask; + }; + await f.Coordinator.SaveTextAsync(); + Assert.Equal(new[] { "export:choose", "component:get", "editor:get", "export:write", "text:ConfigMakerTextSavedMessage", "notice:False:exported" }, f.Host.Calls); + Assert.Equal(0, f.StorageCreations); + } + + [Fact] + public async Task ExportCancelDoesNotSyncOrExport() + { + var f = new Fixture(Document()); + f.Host.ExportPath = _ => null; + await f.Coordinator.SaveTextAsync(); + Assert.Equal(new[] { "export:choose" }, f.Host.Calls); + Assert.Equal("--source", f.Document.CommandText); + } + + [Theory] + [InlineData("picker")] + [InlineData("editor")] + [InlineData("export")] + [InlineData("notice")] + public async Task ExportCatchesFailuresIncludingSuccessNotice(string point) + { + var f = new Fixture(); + var failure = new IOException(point); + if (point == "picker") f.Host.ExportPath = _ => throw failure; + if (point == "editor") f.Host.ReadEditor = () => throw failure; + if (point == "export") f.Export = (_, _) => Task.FromException(failure); + if (point == "notice") f.Host.Notice = (_, error) => { if (!error) throw failure; }; + await f.Coordinator.SaveTextAsync(); + Assert.Equal(("export-failed:" + point, true), f.Host.Notices.Last()); + } + + [Fact] + public async Task ExportAwaitsBackendBeforeNotifyingAndCatchesLateFailure() + { + var f = new Fixture(); + var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Export = (_, _) => pending.Task; + Task exporting = f.Coordinator.SaveTextAsync(); + Assert.False(exporting.IsCompleted); + Assert.Empty(f.Host.Notices); + pending.SetException(new IOException("late export")); + await exporting; + Assert.Equal(("export-failed:late export", true), Assert.Single(f.Host.Notices)); + } + + [Fact] + public async Task ExportErrorNoticeFailureEscapesTheCatch() + { + var f = new Fixture(); + f.Export = (_, _) => Task.FromException(new IOException("export failed")); + var failure = new InvalidOperationException("error notice failed"); + f.Host.Notice = (_, _) => throw failure; + Assert.Same(failure, await Assert.ThrowsAsync(() => f.Coordinator.SaveTextAsync())); + Assert.Equal(("export-failed:export failed", true), Assert.Single(f.Host.Notices)); + } + + [Fact] + public void SyncNormalizesNullEditorAfterReadingComponent() + { + var f = new Fixture(Document()); + f.Host.ReadEditor = () => null; + f.Coordinator.SyncDocumentFromEditor(); + Assert.Equal(new[] { "component:get", "editor:get" }, f.Host.Calls); + Assert.Equal(string.Empty, f.Document.CommandText); + } + + private static ConfigMakerPresetDocument Document() + { + var document = new ConfigMakerPresetDocument { Name = "Source", ComponentId = "component", CommandText = "--source", PackId = "pack", FileName = "file", Meta = "meta", TargetVersion = "target-version" }; + var variable = new ConfigMakerVariableDefinition { Id = "variable-id", Name = "Var", Value = "one" }; + variable.Values.Add("one"); + variable.Values.Add("two"); + document.Variables.Add(variable); + document.Resources.Add(new() { Alias = "list", Path = "resource-path", Kind = ConfigMakerResourceKind.SiteList }); + return document; + } + + private static ConfigItem Config() => new() { name = "Source", packId = "pack", file_name = "file", target = ["component"], startup_string = "--source" }; + + private sealed class Fixture + { + public ConfigMakerPresetDocument Document { get; } + public Host Host { get; } = new(); + public Storage Storage { get; } + public ConfigMakerDocumentCoordinator Coordinator { get; } + public int StorageCreations; + public Func? Factory; + public Func? Export; + + public Fixture(ConfigMakerPresetDocument? document = null) + { + Document = document ?? new(); + Storage = new(Host.Calls); + Coordinator = new(Document, Host, () => + { + Host.Calls.Add("storage:new"); + StorageCreations++; + return Factory == null ? Storage : Factory(); + }, (value, path) => + { + Host.Calls.Add("export:write"); + return Export == null ? Task.CompletedTask : Export(value, path); + }); + } + } + + private sealed class Storage(List calls) : IConfigMakerDocumentStorage + { + public ConfigMakerPresetSaveResult Result = ConfigMakerPresetSaveResult.Failed("CANCELED"); + public Func>? Save; + public Func>? Overwrite; + public Task SaveAsync(string name, ConfigMakerPresetDocument document) + { + calls.Add("storage:save"); + return Save == null ? Task.FromResult(Result) : Save(name, document); + } + public Task OverwriteAsync(ConfigMakerPresetDocument document) + { + calls.Add("storage:overwrite"); + return Overwrite == null ? Task.FromResult(Result) : Overwrite(document); + } + } + + private sealed class Host : IConfigMakerDocumentHost + { + public List Calls { get; } = []; + public List<(string Message, bool IsError)> Notices { get; } = []; + public string CurrentComponent = "component"; + public string? CurrentEditor = "editor text"; + public bool ReadOnly; + public Action? ComponentSet; + public Func? ReadEditor; + public Action? Rebuild; + public Action? Attach; + public Action? ClearStructure; + public Func? ConfigDirectory; + public Func? AutoCorrect; + public Func> AskSave = (_, _) => Task.FromResult(new("Chosen", false)); + public Func> Confirm = () => Task.FromResult(true); + public Func ExportPath = _ => "chosen.txt"; + public Action? Notice; + public string ComponentId + { + get { Calls.Add("component:get"); return CurrentComponent; } + set { Calls.Add("component:set:" + value); CurrentComponent = value; ComponentSet?.Invoke(value); } + } + public string? EditorText { get { Calls.Add("editor:get"); return ReadEditor == null ? CurrentEditor : ReadEditor(); } } + public bool IsEditorReadOnly { get { Calls.Add("readonly:get"); return ReadOnly; } } + public void SetEditorText(string text) { Calls.Add("editor:set:" + text); CurrentEditor = text; } + public void SetBaseDirectory(string value) => Calls.Add("base:" + value); + public void RebuildPresetStructure() { Calls.Add("rebuild"); Rebuild?.Invoke(); } + public void UpdateSimpleDesignerAvailability() => Calls.Add("designer"); + public void NotifyDocumentStateChanged() => Calls.Add("document:event"); + public void AttachExistingPresetFiles() { Calls.Add("attach"); Attach?.Invoke(); } + public Task ApplyAutoCorrectorSilentlyAsync(ConfigItem item) { Calls.Add("autocorrect"); return AutoCorrect?.Invoke(item) ?? Task.CompletedTask; } + public string GetConfigItemBaseDirectory(ConfigItem item) { Calls.Add("base:get"); return ConfigDirectory?.Invoke(item) ?? "base-dir"; } + public Task AskSavePresetAsync(string name, bool overwrite) { Calls.Add("save:ask"); return AskSave(name, overwrite); } + public Task ConfirmNewDocumentAsync() { Calls.Add("new:confirm"); return Confirm(); } + public string? ChooseExportPath(bool allowTextFormat) { Calls.Add("export:choose"); return ExportPath(allowTextFormat); } + public void ClearPresetStructure() { Calls.Add("structure:clear"); ClearStructure?.Invoke(); } + public void ClearEditorUndoHistory() => Calls.Add("undo:clear"); + public string Text(string key) + { + Calls.Add("text:" + key); + return key switch + { + "ConfigMakerPresetSavedMessage" => "saved:{0}", + "ConfigMakerPresetSaveFailedMessage" => "failed:{0}", + "ConfigMakerTextSavedMessage" => "exported", + "ConfigMakerTextSaveFailedMessage" => "export-failed:{0}", + _ => throw new InvalidOperationException("Unexpected key " + key), + }; + } + public void ShowDocumentMessage(string message, bool isError) + { + Calls.Add($"notice:{isError}:{message}"); + Notices.Add((message, isError)); + Notice?.Invoke(message, isError); + } + } +} diff --git a/CDPIUI.Tests/Presentation/ConfigMakerPanelLayoutTests.cs b/CDPIUI.Tests/Presentation/ConfigMakerPanelLayoutTests.cs new file mode 100644 index 00000000..8a6285a1 --- /dev/null +++ b/CDPIUI.Tests/Presentation/ConfigMakerPanelLayoutTests.cs @@ -0,0 +1,235 @@ +using CDPIUI.Helper.CreateConfigHelper; + +namespace CDPIUI.Tests.Presentation; + +public sealed class ConfigMakerPanelLayoutTests +{ + [Fact] + public void ConstructorStoresPortWithoutReadingUi() + { + var f = new Fixture(); Assert.Empty(f.View.Trace); Assert.False(f.Owner.IsUpdating); + } + + [Theory] + [InlineData(0, 800, 1)] + [InlineData(-1, 800, 1)] + [InlineData(1200, 0, 2)] + [InlineData(1200, -1, 2)] + public void InvalidRootShortcircuitsBeforeMutation(double width, double height, int reads) + { + var f = new Fixture(); f.View.Values["RootWidth"] = width; f.View.Values["RootHeight"] = height; + f.Owner.Update(); + Assert.Equal(reads, f.View.Trace.Count); Assert.All(f.View.Trace, step => Assert.StartsWith("g:Root", step)); + Assert.False(f.Owner.IsUpdating); + } + + [Theory] + [InlineData(true, true, 848, 678, 420)] + [InlineData(false, true, 1200, 678, 420)] + [InlineData(true, false, 848, 800, 800)] + [InlineData(false, false, 1200, 800, 800)] + public void PanelBranchesRetainOriginalEditorBounds(bool commands, bool bottom, double width, double maxHeight, double height) + { + var f = new Fixture(); f.View.Values["CommandsVisible"] = commands ? 1 : 0; f.View.Values["BottomVisible"] = bottom ? 1 : 0; + f.Owner.Update(); + Assert.Equal(width, f.View.Values["EditorMaxWidth"]); Assert.Equal(width, f.View.Values["EditorWidth"]); + Assert.Equal(maxHeight, f.View.Values["EditorMaxHeight"]); Assert.Equal(height, f.View.Values["EditorHeight"]); + Assert.DoesNotContain(f.View.Trace, step => step.StartsWith("g:Files", StringComparison.Ordinal) && step != "g:FilesVisible"); + Assert.False(f.Owner.IsUpdating); + } + + [Fact] + public void ExactDefaultReadAndAssignmentOrderIsRetained() + { + var f = new Fixture(); f.Owner.Update(); + Assert.Equal(["g:RootWidth", "g:RootHeight", "g:FilesVisible", "g:RootWidth", "g:CommandsVisible", + "g:CommandSizerWidth", "s:EditorMaxWidth", "s:EditorWidth", "g:RootHeight", "g:BottomVisible", + "g:BottomSizerHeight", "s:EditorMaxHeight", "s:EditorHeight"], f.View.Trace); + } + + [Theory] + [InlineData(1200, 150, 100, 476, 150)] + [InlineData(1200, 150, 250, 476, 250)] + [InlineData(1200, 150, 999, 476, 476)] + [InlineData(600, 200, 999, 200, 200)] + [InlineData(300, 150, 999, 150, 150)] + [InlineData(2000, 150, 999, 900, 900)] + [InlineData(1200, 600, 999, 600, 600)] + public void FilesWidthRetainsSpaceMinimumFortyFivePercentCapAndClamp(double root, double minimum, double current, double maximum, double width) + { + var f = new Fixture(); f.View.Values["FilesVisible"] = 1; f.View.Values["RootWidth"] = root; + f.View.Values["FilesMinWidth"] = minimum; f.View.Values["FilesWidth"] = current; + f.Owner.Update(); + Assert.Equal(maximum, f.View.Values["FilesMaxWidth"]); Assert.Equal(width, f.View.Values["FilesWidth"]); + Assert.Equal(Math.Max(360, Math.Max(360, root - width - 12) - 340 - 12), f.View.Values["EditorWidth"]); + } + + [Fact] + public void TinyRootRetainsOriginalEditorMinimums() + { + var f = new Fixture(); f.View.Values["RootWidth"] = 100; f.View.Values["RootHeight"] = 100; + f.Owner.Update(); + Assert.Equal(360, f.View.Values["EditorWidth"]); Assert.Equal(180, f.View.Values["EditorMaxHeight"]); + Assert.Equal(180, f.View.Values["EditorHeight"]); + } + + [Fact] + public void InitializationUsesSavedHeightThenCurrentHeightAndInvalidateReturnsToSaved() + { + var f = new Fixture(); f.Owner.Update(); Assert.Equal(420, f.View.Values["EditorHeight"]); + Assert.DoesNotContain("g:EditorHeight", f.View.Trace); + f.View.Trace.Clear(); f.View.Values["EditorHeight"] = 250; f.Owner.Update(); + Assert.Equal(250, f.View.Values["EditorHeight"]); Assert.Contains("g:EditorHeight", f.View.Trace); + f.Owner.RememberEditorHeight(300); f.Owner.Invalidate(); f.View.Trace.Clear(); f.Owner.Update(); + Assert.Equal(300, f.View.Values["EditorHeight"]); Assert.DoesNotContain("g:EditorHeight", f.View.Trace); + } + + [Theory] + [InlineData(-10, 180)] + [InlineData(180, 180)] + [InlineData(420, 420)] + [InlineData(1000, 678)] + public void RememberedHeightKeepsOriginalClamp(double remembered, double expected) + { + var f = new Fixture(); f.Owner.RememberEditorHeight(remembered); f.Owner.Update(); + Assert.Equal(expected, f.View.Values["EditorHeight"]); + } + + [Fact] + public void HiddenBottomUsesFullHeightAndDoesNotReadCurrentEditorHeight() + { + var f = new Fixture(); f.Owner.Update(); f.View.Trace.Clear(); f.View.Values["BottomVisible"] = 0; + f.Owner.Update(); Assert.Equal(800, f.View.Values["EditorHeight"]); + Assert.DoesNotContain("g:EditorHeight", f.View.Trace); Assert.DoesNotContain("g:BottomSizerHeight", f.View.Trace); + f.View.Values["BottomVisible"] = 1; f.Owner.Invalidate(); f.Owner.Update(); + Assert.Equal(420, f.View.Values["EditorHeight"]); + } + + [Fact] + public void NestedUpdateDuringUiSetterReturnsWithoutAnyPortReads() + { + var f = new Fixture(); int entered = 0; + f.View.OnStep = step => + { + if (step == "s:EditorMaxWidth") + { + Assert.True(f.Owner.IsUpdating); int before = f.View.Trace.Count; entered++; + f.Owner.Update(); Assert.Equal(before, f.View.Trace.Count); + } + }; + f.Owner.Update(); Assert.Equal(1, entered); Assert.False(f.Owner.IsUpdating); + Assert.Equal(420, f.View.Values["EditorHeight"]); + } + + [Fact] + public void LaterRootReadSeesMutationFromEarlierFilesAssignment() + { + var f = new Fixture(); f.View.Values["FilesVisible"] = 1; f.View.Values["CommandsVisible"] = 0; + f.View.OnStep = step => { if (step == "s:FilesWidth") f.View.Values["RootWidth"] = 700; }; + f.Owner.Update(); Assert.Equal(438, f.View.Values["EditorWidth"]); + Assert.Equal(4, f.View.Trace.Count(step => step == "g:RootWidth")); + } + + [Fact] + public void LaterCommandsBranchAndClampReadCurrentPropertiesAfterCallbacks() + { + var f = new Fixture(); f.View.Values["FilesVisible"] = 1; f.View.Values["FilesWidth"] = 100; + f.View.OnStep = step => + { + if (step == "s:FilesMaxWidth") f.View.Values["FilesMinWidth"] = 200; + if (step == "s:FilesWidth") f.View.Values["CommandsVisible"] = 0; + }; + f.Owner.Update(); Assert.Equal(476, f.View.Values["FilesMaxWidth"]); Assert.Equal(200, f.View.Values["FilesWidth"]); + Assert.Equal(988, f.View.Values["EditorWidth"]); Assert.Equal(1, f.View.Trace.Count(step => step == "g:CommandSizerWidth")); + } + + [Theory] + [InlineData("g:RootWidth")] + [InlineData("g:FilesVisible")] + [InlineData("s:EditorMaxWidth")] + [InlineData("s:EditorWidth")] + [InlineData("g:RootHeight")] + [InlineData("g:BottomVisible")] + [InlineData("s:EditorMaxHeight")] + [InlineData("s:EditorHeight")] + public void PortFailureClearsUpdatingAndDoesNotMarkIncompleteLayoutInitialized(string failing) + { + var f = new Fixture(); + f.View.OnStep = step => { if (step == failing) throw new IOException("owned port"); }; + Assert.Throws(f.Owner.Update); Assert.False(f.Owner.IsUpdating); + f.View.OnStep = null; f.View.Values["EditorHeight"] = 250; f.View.Trace.Clear(); f.Owner.Update(); + Assert.Equal(420, f.View.Values["EditorHeight"]); Assert.DoesNotContain("g:EditorHeight", f.View.Trace); + } + + [Fact] + public void FailureAfterPreviousSuccessKeepsInitializedStateAndAssignedPartialBounds() + { + var f = new Fixture(); f.Owner.Update(); f.View.Values["RootWidth"] = 1000; f.View.Values["EditorHeight"] = 250; + f.View.OnStep = step => { if (step == "s:EditorWidth") throw new IOException("owned setter"); }; + Assert.Throws(f.Owner.Update); Assert.Equal(648, f.View.Values["EditorWidth"]); Assert.False(f.Owner.IsUpdating); + f.View.OnStep = null; f.View.Trace.Clear(); f.Owner.Update(); + Assert.Equal(250, f.View.Values["EditorHeight"]); Assert.Contains("g:EditorHeight", f.View.Trace); + } + + [Fact] + public void InvalidateFromCallbackBeforeSuccessfulEndIsOverwrittenByOriginalFinalInitialization() + { + var f = new Fixture(); f.View.OnStep = step => { if (step == "s:EditorHeight") f.Owner.Invalidate(); }; + f.Owner.Update(); f.View.OnStep = null; f.View.Values["EditorHeight"] = 250; f.Owner.Update(); + Assert.Equal(250, f.View.Values["EditorHeight"]); + } + + [Fact] + public void InconsistentLiveClampBoundsThrowWithoutRollbackAndAllowNextUpdate() + { + var f = new Fixture(); f.View.Values["FilesVisible"] = 1; + f.View.OnStep = step => { if (step == "s:FilesMaxWidth") f.View.Values["FilesMinWidth"] = 1000; }; + Assert.Throws(f.Owner.Update); + Assert.Equal(476, f.View.Values["FilesMaxWidth"]); Assert.Equal(250, f.View.Values["FilesWidth"]); Assert.False(f.Owner.IsUpdating); + f.View.OnStep = null; f.View.Values["FilesMinWidth"] = 150; f.Owner.Update(); Assert.Equal(420, f.View.Values["EditorHeight"]); + } + + [Fact] + public void ControllerDoesNotIntroduceNaNNormalizationBeforeUiPropertyValidation() + { + var f = new Fixture(); f.View.Values["RootWidth"] = double.NaN; f.Owner.RememberEditorHeight(double.NaN); + f.Owner.Update(); Assert.True(double.IsNaN(f.View.Values["EditorWidth"])); + Assert.True(double.IsNaN(f.View.Values["EditorHeight"])); Assert.False(f.Owner.IsUpdating); + } + + private sealed class Fixture + { + public Fixture() => Owner = new(View); + public Port View { get; } = new(); + public ConfigMakerPanelLayoutController Owner { get; } + } + + private sealed class Port : IConfigMakerPanelLayoutView + { + public Dictionary Values { get; } = new() + { + ["RootWidth"] = 1200, ["RootHeight"] = 800, ["FilesVisible"] = 0, ["CommandsVisible"] = 1, ["BottomVisible"] = 1, + ["FilesMinWidth"] = 150, ["FilesMaxWidth"] = 500, ["FilesWidth"] = 250, ["FilesSizerWidth"] = 12, + ["CommandSizerWidth"] = 12, ["BottomSizerHeight"] = 12, ["EditorHeight"] = 999, + }; + public List Trace { get; } = []; + public Action? OnStep; + private double Get(string name) { Trace.Add("g:" + name); OnStep?.Invoke("g:" + name); return Values[name]; } + private void Set(string name, double value) { Values[name] = value; Trace.Add("s:" + name); OnStep?.Invoke("s:" + name); } + public double RootWidth => Get(nameof(RootWidth)); + public double RootHeight => Get(nameof(RootHeight)); + public bool FilesVisible => Get(nameof(FilesVisible)) == 1; + public bool CommandsVisible => Get(nameof(CommandsVisible)) == 1; + public bool BottomVisible => Get(nameof(BottomVisible)) == 1; + public double FilesMinWidth => Get(nameof(FilesMinWidth)); + public double FilesMaxWidth { get => Get(nameof(FilesMaxWidth)); set => Set(nameof(FilesMaxWidth), value); } + public double FilesWidth { get => Get(nameof(FilesWidth)); set => Set(nameof(FilesWidth), value); } + public double FilesSizerWidth => Get(nameof(FilesSizerWidth)); + public double CommandSizerWidth => Get(nameof(CommandSizerWidth)); + public double BottomSizerHeight => Get(nameof(BottomSizerHeight)); + public double EditorMaxWidth { set => Set(nameof(EditorMaxWidth), value); } + public double EditorWidth { set => Set(nameof(EditorWidth), value); } + public double EditorMaxHeight { set => Set(nameof(EditorMaxHeight), value); } + public double EditorHeight { get => Get(nameof(EditorHeight)); set => Set(nameof(EditorHeight), value); } + } +} diff --git a/CDPIUI.Tests/Presentation/ConfigMakerPresetFileActionsTests.cs b/CDPIUI.Tests/Presentation/ConfigMakerPresetFileActionsTests.cs new file mode 100644 index 00000000..5dd9429a --- /dev/null +++ b/CDPIUI.Tests/Presentation/ConfigMakerPresetFileActionsTests.cs @@ -0,0 +1,446 @@ +using System.Collections.ObjectModel; +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.ViewModels; + +namespace CDPIUI.Tests.Presentation; + +public sealed class ConfigMakerPresetFileActionsTests +{ + [Fact] + public void AddNullThrowsSynchronouslyBeforeAnyPortCall() + { + var f = new Fixture(); + Assert.Equal("filePaths", Assert.Throws(() => f.Actions.AddPresetFiles(null!)).ParamName); + Assert.Empty(f.Calls); + } + + [Fact] + public void AddPassesTheOriginalLazyEnumerableWithoutEarlyEnumeration() + { + var f = new Fixture(); + int enumerations = 0; + IEnumerable Values() { enumerations++; yield return "first"; yield return "second"; } + IEnumerable values = Values(); + f.Backend.Add = paths => + { + Assert.Same(values, paths); + Assert.Equal(0, enumerations); + Assert.Equal(new[] { "first", "second" }, paths); + return 2; + }; + f.Actions.AddPresetFiles(values); + Assert.Equal(1, enumerations); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + public void NonpositiveAddDoesNotAttachOrShowStatus(int count) + { + var f = new Fixture(); + f.Backend.Add = _ => count; + f.Actions.AddPresetFiles(["path"]); + Assert.Equal(new[] { "add" }, f.Calls); + } + + [Fact] + public void AddKeepsAttachRebuildPanelNoticeOrderAndOriginalCount() + { + var f = new Fixture(); + f.Backend.Add = _ => 2; + f.Host.Attach = () => { f.Document.Resources.Add(new()); f.Document.Resources.Add(new()); f.Document.Resources.Add(new()); }; + f.Actions.AddPresetFiles(["a", "b"]); + Assert.Equal(new[] { "add", "attach", "rebuild", "panel:True", "text:ConfigMakerPresetFilesAddedMessage", "notice:Success:added:2" }, f.Calls); + Assert.Equal(3, f.Document.Resources.Count); + } + + [Theory] + [InlineData("attach")] + [InlineData("rebuild")] + [InlineData("notice")] + public void AddFailureEscapesSynchronouslyWithoutReportingCatch(string point) + { + var f = new Fixture(); + var failure = new IOException(point); + if (point == "attach") f.Host.Attach = () => throw failure; + if (point == "rebuild") f.Host.Rebuild = () => throw failure; + if (point == "notice") f.Host.Notice = (_, _) => throw failure; + Assert.Same(failure, Assert.Throws(() => f.Actions.AddPresetFiles(["a"]))); + Assert.Empty(f.Host.Reported); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void PickerOnlyAddsNonemptyOriginalSelection(bool selected) + { + var f = new Fixture(); + var paths = f.Host.Picked = selected ? new[] { "b", "a", "b" } : []; + f.Backend.Add = value => { Assert.Same(paths, value); return 0; }; + f.Actions.AddPresetFilesFromPicker(); + Assert.Equal(selected ? new[] { "picker", "add" } : new[] { "picker" }, f.Calls); + } + + [Fact] + public async Task OpenNullStaysInsideReportingBoundary() + { + var f = new Fixture(); + await f.Actions.OpenPresetFileAsync(null); + Assert.Equal(new[] { "run" }, f.Calls); + } + + [Fact] + public async Task OpenMissingWarnsBeforePreferencesOrShell() + { + var f = new Fixture(); + f.Backend.Exists = _ => false; + await f.Actions.OpenPresetFileAsync(File()); + Assert.Equal(("missing:" + Resolved, ConfigMakerPresetFileNoticeSeverity.Warning), Assert.Single(f.Host.Notices)); + Assert.DoesNotContain("ask-policy", f.Calls); + Assert.DoesNotContain(f.Calls, call => call.StartsWith("shell:")); + } + + [Theory] + [InlineData(ConfigMakerPresetFileKind.SiteList, "data.bin")] + [InlineData(ConfigMakerPresetFileKind.Payload, "DATA.TXT")] + [InlineData(ConfigMakerPresetFileKind.Library, "data.txt")] + public async Task SiteListOrTxtUsesTextRoute(ConfigMakerPresetFileKind kind, string path) + { + var f = new Fixture(); + f.Backend.Resolve = _ => path; + await f.Actions.OpenPresetFileAsync(File(kind)); + Assert.Equal(new[] { "run", "resolve", "exists:" + path, "ask-policy", "shell:text:" + path }, f.Calls); + } + + [Fact] + public async Task OtherFilesUseDefaultAppWithoutTextPreferences() + { + var f = new Fixture(); + await f.Actions.OpenPresetFileAsync(File(ConfigMakerPresetFileKind.Payload)); + Assert.Contains("shell:default:" + Resolved, f.Calls); + Assert.DoesNotContain("ask-policy", f.Calls); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ApplicationDialogIsAwaitedRemembersOnlyTrueAndNeverOpensShell(bool answer) + { + var f = new Fixture(); + f.Backend.AskApplication = true; + var response = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Host.ApplicationAnswer = response.Task; + Task opening = f.Actions.OpenPresetFileAsync(File()); + Assert.False(opening.IsCompleted); + Assert.DoesNotContain("remember", f.Calls); + response.SetResult(answer); + await opening; + Assert.Equal(answer ? 1 : 0, f.Calls.Count(call => call == "remember")); + Assert.DoesNotContain(f.Calls, call => call.StartsWith("shell:")); + } + + [Theory] + [InlineData("resolve")] + [InlineData("dialog")] + [InlineData("remember")] + [InlineData("shell")] + public async Task OpenFailuresReachTheOriginalReportingBoundary(string point) + { + var f = new Fixture(); + var failure = new IOException(point); + if (point == "resolve") f.Backend.Resolve = _ => throw failure; + if (point == "dialog") { f.Backend.AskApplication = true; f.Host.ApplicationAnswer = Task.FromException(failure); } + if (point == "remember") { f.Backend.AskApplication = true; f.Backend.Remember = () => throw failure; } + if (point == "shell") f.Backend.Shell = _ => throw failure; + await f.Actions.OpenPresetFileAsync(File()); + Assert.Same(failure, Assert.Single(f.Host.Reported)); + } + + [Fact] + public void ShowNullHasNoEffects() + { + var f = new Fixture(); + f.Actions.ShowPresetFileInFolder(null); + Assert.Empty(f.Calls); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ShowUsesResolvedPathAndOnlyExistingFileCallsShell(bool exists) + { + var f = new Fixture(); + f.Backend.Exists = _ => exists; + f.Actions.ShowPresetFileInFolder(File()); + if (exists) Assert.Equal(new[] { "resolve", "exists:" + Resolved, "shell:folder:" + Resolved }, f.Calls); + else Assert.Equal(("missing:" + Resolved, ConfigMakerPresetFileNoticeSeverity.Warning), Assert.Single(f.Host.Notices)); + Assert.DoesNotContain("run", f.Calls); + } + + [Fact] + public void ShowFailurePropagatesSynchronously() + { + var f = new Fixture(); + var failure = new IOException("show failed"); + f.Backend.Shell = _ => throw failure; + Assert.Same(failure, Assert.Throws(() => f.Actions.ShowPresetFileInFolder(File()))); + Assert.Empty(f.Host.Reported); + } + + [Fact] + public async Task RemoveNullAndUnattachedStopWithoutConfirmation() + { + var f = new Fixture(); + await f.Actions.RemovePresetFileAsync(null); + await f.Actions.RemovePresetFileAsync(File()); + Assert.Equal(new[] { "run", "run", "find" }, f.Calls); + } + + [Fact] + public async Task RemoveUnreferencedPublishesCollectionChangeBeforeRebuildAndDiagnostics() + { + var f = new Fixture(); + var resource = new ConfigMakerPresetResource { Alias = "list" }; + f.Document.Resources.Add(resource); + f.Backend.Attached = resource; + f.Document.ContentChanged += (_, _) => f.Calls.Add("document"); + await f.Actions.RemovePresetFileAsync(File()); + Assert.Empty(f.Document.Resources); + Assert.Equal(new[] { "run", "find", "referenced", "document", "rebuild", "diagnostics" }, f.Calls); + Assert.DoesNotContain("confirm", f.Calls); + } + + [Fact] + public async Task RemoveReferencedCancellationKeepsTheSameObject() + { + var f = new Fixture(); + var resource = new ConfigMakerPresetResource { Alias = "list" }; + f.Document.Resources.Add(resource); + f.Backend.Attached = resource; + f.Backend.Referenced = true; + f.Host.RemovalAnswer = Task.FromResult(false); + await f.Actions.RemovePresetFileAsync(File()); + Assert.Same(resource, Assert.Single(f.Document.Resources)); + Assert.DoesNotContain("rebuild", f.Calls); + } + + [Fact] + public async Task RemoveUsesThePreDialogObjectEvenWhenCollectionChangesDuringAwait() + { + var f = new Fixture(); + var old = new ConfigMakerPresetResource { Alias = "list" }; + var newer = new ConfigMakerPresetResource { Alias = "list" }; + f.Document.Resources.Add(old); + f.Backend.Attached = old; + f.Backend.Referenced = true; + var response = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Host.RemovalAnswer = response.Task; + Task removing = f.Actions.RemovePresetFileAsync(File()); + Assert.False(removing.IsCompleted); + f.Document.Resources.Remove(old); + f.Document.Resources.Add(newer); + f.Backend.Attached = newer; + response.SetResult(true); + await removing; + Assert.Same(newer, Assert.Single(f.Document.Resources)); + Assert.Equal(1, f.Calls.Count(call => call == "find")); + Assert.Equal(new[] { "rebuild", "diagnostics" }, f.Calls.TakeLast(2)); + } + + [Fact] + public async Task RemoveSubscriberFailureKeepsTheRemovalButSkipsLaterEffects() + { + var f = new Fixture(); + var resource = new ConfigMakerPresetResource { Alias = "list" }; + f.Document.Resources.Add(resource); + f.Backend.Attached = resource; + var failure = new IOException("subscriber failed"); + f.Document.ContentChanged += (_, _) => throw failure; + await f.Actions.RemovePresetFileAsync(File()); + Assert.Empty(f.Document.Resources); + Assert.Same(failure, Assert.Single(f.Host.Reported)); + Assert.DoesNotContain("rebuild", f.Calls); + Assert.DoesNotContain("diagnostics", f.Calls); + } + + [Theory] + [InlineData("confirm")] + [InlineData("rebuild")] + [InlineData("diagnostics")] + public async Task RemoveFailuresKeepTheOriginalPartialState(string point) + { + var f = new Fixture(); + var resource = new ConfigMakerPresetResource { Alias = "list" }; + f.Document.Resources.Add(resource); + f.Backend.Attached = resource; + var failure = new IOException(point); + if (point == "confirm") { f.Backend.Referenced = true; f.Host.RemovalAnswer = Task.FromException(failure); } + if (point == "rebuild") f.Host.Rebuild = () => throw failure; + if (point == "diagnostics") f.Host.Diagnostics = () => throw failure; + await f.Actions.RemovePresetFileAsync(File()); + Assert.Same(failure, Assert.Single(f.Host.Reported)); + Assert.Equal(point == "confirm" ? 1 : 0, f.Document.Resources.Count); + } + + [Fact] + public void ReadonlyInsertDoesNotReadAnInvalidFilePath() + { + var f = new Fixture(); + f.Host.ReadOnly = true; + f.Actions.InsertPresetFileReference(new("invalid", null!, "")); + Assert.Equal(new[] { "readonly" }, f.Calls); + } + + [Fact] + public void NullInsertOnlyReadsReadonly() + { + var f = new Fixture(); + f.Actions.InsertPresetFileReference(null); + Assert.Equal(new[] { "readonly" }, f.Calls); + } + + [Fact] + public void PresetUriKeepsCaseAndBypassesLookupAfterOriginalTrimming() + { + var f = new Fixture(); + f.Actions.InsertPresetFileReference(File() with { Path = " \"PRESET://Mixed Alias\" " }); + Assert.Equal(new[] { "readonly", "insert:\"PRESET://Mixed Alias\"" }, f.Calls); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void UnresolvedInsertKeepsTheTrimmedOriginalReference(string? resolved) + { + var f = new Fixture(); + f.Backend.TryResolve = _ => resolved; + f.Actions.InsertPresetFileReference(File() with { Path = " \"relative.txt\" " }); + Assert.Equal("\"relative.txt\"", Assert.Single(f.Host.Inserted)); + Assert.DoesNotContain(f.Calls, call => call.StartsWith("exists:")); + Assert.Empty(f.Backend.Creates); + } + + [Fact] + public void ExistingFileUsesFullPathAndKindAndReadsAliasAfterAddedResourceRebuild() + { + var f = new Fixture(); + string raw = Path.Combine(Path.GetTempPath(), "unused", "..", "reference.txt"); + string full = Path.GetFullPath(raw); + f.Backend.TryResolve = _ => raw; + f.Backend.Added = true; + f.Host.Rebuild = () => f.Backend.Resource.Alias = "late.txt"; + f.Actions.InsertPresetFileReference(File(ConfigMakerPresetFileKind.Payload)); + Assert.Equal((full, ConfigMakerPresetFileKind.Payload), Assert.Single(f.Backend.Creates)); + Assert.Contains("exists:" + raw, f.Calls); + Assert.Equal("\"preset://late.txt\"", Assert.Single(f.Host.Inserted)); + Assert.Same(f.Backend.Resource, Assert.Single(f.Document.Resources)); + } + + [Fact] + public void ExistingResourceDoesNotRebuild() + { + var f = new Fixture(); + f.Document.Resources.Add(f.Backend.Resource); + f.Actions.InsertPresetFileReference(File()); + Assert.DoesNotContain("rebuild", f.Calls); + Assert.Equal("\"preset://existing.txt\"", Assert.Single(f.Host.Inserted)); + Assert.Same(f.Backend.Resource, Assert.Single(f.Document.Resources)); + } + + [Theory] + [InlineData("resolve")] + [InlineData("exists")] + [InlineData("create")] + [InlineData("rebuild")] + [InlineData("insert")] + public void InsertFailuresRemainSynchronousAndPreservePriorRegistration(string point) + { + var f = new Fixture(); + var failure = new IOException(point); + if (point == "resolve") f.Backend.TryResolve = _ => throw failure; + if (point == "exists") f.Backend.Exists = _ => throw failure; + if (point == "create") f.Backend.Create = (_, _) => throw failure; + if (point == "rebuild") { f.Backend.Added = true; f.Host.Rebuild = () => throw failure; } + if (point == "insert") f.Host.Insert = _ => throw failure; + Assert.Same(failure, Assert.Throws(() => f.Actions.InsertPresetFileReference(File()))); + Assert.Empty(f.Host.Reported); + if (point == "rebuild") Assert.Same(f.Backend.Resource, Assert.Single(f.Document.Resources)); + } + + private static readonly string Resolved = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "cdpiui-file-actions", "data.bin")); + private static ConfigMakerPresetFileInfo File(ConfigMakerPresetFileKind kind = ConfigMakerPresetFileKind.SiteList) => new("file", "source-path", "folder", kind); + + private sealed class Fixture + { + public List Calls { get; } = []; + public ConfigMakerPresetDocument Document { get; } = new(); + public Host Host { get; } + public Backend Backend { get; } + public ConfigMakerPresetFileActions Actions { get; } + public Fixture() + { + Host = new(Calls); + Backend = new(Calls, Document.Resources); + Actions = new(Document.Resources, Host, Backend); + } + } + + private sealed class Backend(List calls, ObservableCollection resources) : IConfigMakerPresetFileActionsBackend + { + public Func, int> Add = _ => 1; + public Func Resolve = _ => Resolved; + public Func TryResolve = _ => Resolved; + public Func Exists = _ => true; + public bool AskApplication, Referenced, Added; + public ConfigMakerPresetResource? Attached; + public ConfigMakerPresetResource Resource { get; } = new() { Alias = "existing.txt", Path = Resolved }; + public List<(string Path, ConfigMakerPresetFileKind Kind)> Creates { get; } = []; + public Action? Create; + public Action? Remember; + public Action? Shell; + public int AddFiles(IEnumerable paths) { calls.Add("add"); return Add(paths); } + public string ResolvePath(string path) { calls.Add("resolve"); return Resolve(path); } + public string? TryResolvePath(string path) { calls.Add("try-resolve"); return TryResolve(path); } + public bool FileExists(string path) { calls.Add("exists:" + path); return Exists(path); } + public ConfigMakerPresetResource GetOrCreate(string path, ConfigMakerPresetFileKind kind, out bool added) + { + calls.Add("create"); Creates.Add((path, kind)); Create?.Invoke(path, kind); added = Added; + if (added) resources.Add(Resource); + return Resource; + } + public ConfigMakerPresetResource? FindAttached(string path) { calls.Add("find"); return Attached; } + public bool IsReferenced(ConfigMakerPresetResource resource) { Assert.Same(Attached, resource); calls.Add("referenced"); return Referenced; } + public bool ShouldAskForTextApplication() { calls.Add("ask-policy"); return AskApplication; } + public void RememberTextFileDialogShown() { calls.Add("remember"); Remember?.Invoke(); } + public void OpenTextFile(string path) { calls.Add("shell:text:" + path); Shell?.Invoke(path); } + public void OpenFileInDefaultApp(string path) { calls.Add("shell:default:" + path); Shell?.Invoke(path); } + public void ShowFileInFolder(string path) { calls.Add("shell:folder:" + path); Shell?.Invoke(path); } + } + + private sealed class Host(List calls) : IConfigMakerPresetFileActionsHost + { + public List<(string Message, ConfigMakerPresetFileNoticeSeverity Severity)> Notices { get; } = []; + public List Reported { get; } = []; + public List Inserted { get; } = []; + public IReadOnlyList Picked = []; + public bool ReadOnly; + public Task ApplicationAnswer = Task.FromResult(true), RemovalAnswer = Task.FromResult(true); + public Action? Attach, Rebuild, Diagnostics; + public Action? Insert; + public Action? Notice; + public async Task RunReportingErrorsAsync(Func action) { calls.Add("run"); try { await action(); } catch (Exception error) { Reported.Add(error); } } + public IReadOnlyList ChoosePresetFilesToAdd() { calls.Add("picker"); return Picked; } + public void AttachExistingPresetFiles() { calls.Add("attach"); Attach?.Invoke(); } + public void RebuildPresetStructure() { calls.Add("rebuild"); Rebuild?.Invoke(); } + public void SetPresetFilesPanelVisible(bool visible) => calls.Add("panel:" + visible); + public string Text(string key) { calls.Add("text:" + key); return key switch { "ConfigMakerPresetFilesAddedMessage" => "added:{0}", "ConfigMakerPresetFileMissingMessage" => "missing:{0}", _ => throw new InvalidOperationException("Unexpected key " + key) }; } + public void ShowPresetFileMessage(string message, ConfigMakerPresetFileNoticeSeverity severity) { calls.Add($"notice:{severity}:{message}"); Notices.Add((message, severity)); Notice?.Invoke(message, severity); } + public Task AskTextFileApplicationAsync(string path) { Assert.Equal(Resolved, path); calls.Add("application"); return ApplicationAnswer; } + public Task ConfirmRemoveReferencedFileAsync() { calls.Add("confirm"); return RemovalAnswer; } + public void ScheduleDiagnostics() { calls.Add("diagnostics"); Diagnostics?.Invoke(); } + public bool IsEditorReadOnly { get { calls.Add("readonly"); return ReadOnly; } } + public void InsertAtCursor(string reference) { calls.Add("insert:" + reference); Inserted.Add(reference); Insert?.Invoke(reference); } + } +} diff --git a/CDPIUI.Tests/Presentation/ConfigMakerPresetFileReplacerTests.cs b/CDPIUI.Tests/Presentation/ConfigMakerPresetFileReplacerTests.cs new file mode 100644 index 00000000..bcdc0340 --- /dev/null +++ b/CDPIUI.Tests/Presentation/ConfigMakerPresetFileReplacerTests.cs @@ -0,0 +1,478 @@ +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.ViewModels.ConfigMaker; + +namespace CDPIUI.Tests.Presentation; + +public sealed class ConfigMakerPresetFileReplacerTests +{ + [Fact] + public async Task NullReplacementIsStillInsideTheHostReportingBoundary() + { + var f = new Fixture(); + await f.Replacer.ReplacePresetFileAsync(null); + Assert.Equal(new[] { "run" }, f.Calls); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task InvalidResolvedPathShowsErrorWithoutFileQuery(string? resolved) + { + var f = new Fixture(); + f.Backend.Resolve = _ => resolved; + await f.Replacer.ReplacePresetFileAsync(Original); + Assert.Equal(("invalid", ConfigMakerPresetFileNoticeSeverity.Error), Assert.Single(f.Host.Notices)); + Assert.DoesNotContain(f.Calls, call => call.StartsWith("exists:")); + Assert.DoesNotContain("ask", f.Calls); + } + + [Fact] + public async Task NowExistingFileOnlyRebuildsWithoutOpeningDialog() + { + var f = new Fixture(); + f.Backend.Existing.Add(Missing); + await f.Replacer.ReplacePresetFileAsync(Original); + Assert.Equal(new[] { "run", "resolve:" + Original.Path, "exists:" + Missing, "rebuild" }, f.Calls); + Assert.Empty(f.Host.Notices); + } + + [Theory] + [InlineData(ConfigMakerFileReplacementChoice.Cancel)] + [InlineData((ConfigMakerFileReplacementChoice)99)] + public async Task CanceledOrUnknownChoiceDoesNotCreateCorrectorOrPickFile(ConfigMakerFileReplacementChoice choice) + { + var f = new Fixture(); + f.Host.Choice = Task.FromResult(choice); + await f.Replacer.ReplacePresetFileAsync(Original); + Assert.Equal(0, f.Backend.CorrectorCreations); + Assert.DoesNotContain("choose:" + Missing, f.Calls); + Assert.Empty(f.Host.Notices); + } + + [Fact] + public async Task ManualChoiceWaitsForDialogAndBlankPickerCancels() + { + var f = new Fixture(); + var answer = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Host.Choice = answer.Task; + f.Host.Selected = " "; + Task replacing = f.Replacer.ReplacePresetFileAsync(Original); + Assert.False(replacing.IsCompleted); + Assert.DoesNotContain("choose:" + Missing, f.Calls); + answer.SetResult(ConfigMakerFileReplacementChoice.ChooseManually); + await replacing; + Assert.Contains("choose:" + Missing, f.Calls); + Assert.Equal(0, f.Backend.UpdateCalls); + Assert.Empty(f.Host.Notices); + } + + [Fact] + public async Task ManualReplacementUsesTheOriginalFileAndNormalizedPickerPath() + { + var f = new Fixture(); + f.Host.Choice = Task.FromResult(ConfigMakerFileReplacementChoice.ChooseManually); + f.Host.Selected = RawReplacement; + f.Backend.Update = (file, path) => { Assert.Same(Original, file); Assert.Equal(Replacement, path); return true; }; + await f.Replacer.ReplacePresetFileAsync(Original); + Assert.Equal(("replaced:" + Replacement, ConfigMakerPresetFileNoticeSeverity.Success), Assert.Single(f.Host.Notices)); + Assert.Equal(0, f.Backend.CorrectorCreations); + Assert.Empty(f.Host.Replacements); + } + + [Fact] + public async Task AutoEmptySuggestionCreatesThenRebuildsAndDoesNotSearch() + { + var f = AutoFixture(); + f.Backend.Corrector.Empty = true; + await f.Replacer.ReplacePresetFileAsync(Original); + Assert.Equal(new[] { Missing }, f.Backend.Created); + Assert.DoesNotContain("find:" + Missing, f.Calls); + Assert.DoesNotContain("choose:" + Missing, f.Calls); + Assert.Equal(("empty:" + Missing, ConfigMakerPresetFileNoticeSeverity.Success), Assert.Single(f.Host.Notices)); + Assert.True(f.Calls.IndexOf("create:" + Missing) < f.Calls.IndexOf("rebuild")); + } + + [Fact] + public async Task AutoFactoryIsLazyAndSearchIsAwaited() + { + var f = new Fixture(); + var choice = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var suggestion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Host.Choice = choice.Task; + f.Backend.Corrector.Finding = suggestion.Task; + Task replacing = f.Replacer.ReplacePresetFileAsync(Original); + Assert.Equal(0, f.Backend.CorrectorCreations); + choice.SetResult(ConfigMakerFileReplacementChoice.AutoCorrect); + await f.Backend.Corrector.Started.Task.WaitAsync(TimeSpan.FromSeconds(3)); + Assert.Equal(1, f.Backend.CorrectorCreations); + Assert.False(replacing.IsCompleted); + Assert.Equal(0, f.Backend.UpdateCalls); + suggestion.SetResult(Replacement); + await replacing; + Assert.Equal(1, f.Backend.UpdateCalls); + Assert.DoesNotContain("choose:" + Missing, f.Calls); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task EmptySearchWarnsBeforeManualFallback(string? suggestion) + { + var f = AutoFixture(); + f.Backend.Corrector.Suggestion = suggestion; + f.Host.Selected = null; + await f.Replacer.ReplacePresetFileAsync(Original); + Assert.Equal(("no suggestion", ConfigMakerPresetFileNoticeSeverity.Warning), Assert.Single(f.Host.Notices)); + Assert.True(f.Calls.IndexOf("notice:Warning") < f.Calls.IndexOf("choose:" + Missing)); + Assert.Equal(0, f.Backend.UpdateCalls); + } + + [Fact] + public async Task NonemptyButMissingSuggestionDoesNotFallBackToPicker() + { + var f = AutoFixture(); + f.Backend.Corrector.Suggestion = Path.Combine(Path.GetTempPath(), "missing-suggestion.txt"); + await f.Replacer.ReplacePresetFileAsync(Original); + Assert.Equal(ConfigMakerPresetFileNoticeSeverity.Error, Assert.Single(f.Host.Notices).Severity); + Assert.DoesNotContain("choose:" + Missing, f.Calls); + Assert.Equal(0, f.Backend.UpdateCalls); + } + + [Theory] + [InlineData("resolve")] + [InlineData("factory")] + [InlineData("suggest")] + [InlineData("find-sync")] + [InlineData("find-async")] + public async Task ErrorsOutsideTryApplyReachTheHostReportingBoundary(string point) + { + var f = AutoFixture(); + var error = new IOException(point); + if (point == "resolve") f.Backend.Resolve = _ => throw error; + if (point == "factory") f.Backend.Factory = () => throw error; + if (point == "suggest") f.Backend.Corrector.CheckEmpty = _ => throw error; + if (point == "find-sync") f.Backend.Corrector.Find = _ => throw error; + if (point == "find-async") f.Backend.Corrector.Finding = Task.FromException(error); + await f.Replacer.ReplacePresetFileAsync(Original); + Assert.Same(error, Assert.Single(f.Host.Reported)); + Assert.Empty(f.Host.Notices); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AttachedReplacementDoesNotEditCommandExplicitArrayOrRaiseReplacement(bool show) + { + var f = new Fixture(); + f.Backend.Update = (_, _) => true; + f.Host.Explicit = true; + var files = f.Host.Files = [Original]; + Assert.True(f.Replacer.TryApplyPresetFileReplacement(Original, Replacement, show)); + Assert.Same(files, f.Host.Files); + Assert.Empty(f.Host.Commands); + Assert.Empty(f.Host.Replacements); + Assert.Equal(0, f.Backend.ReferenceCalls); + Assert.Equal(show ? 1 : 0, f.Host.Notices.Count); + Assert.Contains("rebuild", f.Calls); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void MissingReplacementStopsBeforeResourcesAndRespectsSilentFlag(bool show) + { + var f = new Fixture(); + f.Backend.Existing.Clear(); + Assert.False(f.Replacer.TryApplyPresetFileReplacement(Original, RawReplacement, show)); + Assert.Contains("exists:" + Replacement, f.Calls); + Assert.Equal(0, f.Backend.UpdateCalls); + Assert.Equal(show ? 1 : 0, f.Host.Notices.Count); + if (show) Assert.Equal(("failed:" + new FileNotFoundException(null, Replacement).Message, ConfigMakerPresetFileNoticeSeverity.Error), f.Host.Notices[0]); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void MissingReferenceResultBecomesLocalizedFailureOnlyWhenShown(bool show) + { + var f = new Fixture(); + f.Backend.Rewrite = (_, _) => null; + Assert.False(f.Replacer.TryApplyPresetFileReplacement(Original, Replacement, show)); + Assert.DoesNotContain("rebuild", f.Calls); + Assert.Empty(f.Host.Replacements); + Assert.Contains("text:ConfigMakerPresetFileReferenceNotFoundMessage", f.Calls); + Assert.Equal(show ? 1 : 0, f.Host.Notices.Count); + if (show) Assert.Equal(("failed:reference not found", ConfigMakerPresetFileNoticeSeverity.Error), f.Host.Notices[0]); + } + + [Fact] + public void ExplicitFilesMatchByIdentityOrNormalizedPathAndKindAndRetainOtherFields() + { + var f = new Fixture(); + f.Host.Explicit = true; + var equivalent = Original with { Name = "second", Path = "\"C:\\MISSING\\source.txt\"", OptionName = "--other", IsAttachedResource = true }; + var otherKind = Original with { Kind = ConfigMakerPresetFileKind.Payload }; + var unrelated = Original with { Path = "C:/missing/unrelated.txt" }; + var before = f.Host.Files = [Original, equivalent, otherKind, unrelated]; + Assert.True(f.Replacer.TryApplyPresetFileReplacement(Original, RawReplacement, false)); + Assert.NotSame(before, f.Host.Files); + Assert.Equal(4, f.Host.Files.Length); + foreach (var updated in f.Host.Files.Take(2)) + { + Assert.Equal("replacement.txt", updated.Name); + Assert.Equal("preset://replacement.txt", updated.Path); + Assert.Equal("preset:/", updated.Folder); + Assert.Equal(ConfigMakerPresetFileKind.SiteList, updated.Kind); + } + Assert.Equal("--other", f.Host.Files[1].OptionName); + Assert.True(f.Host.Files[1].IsAttachedResource); + Assert.Same(otherKind, f.Host.Files[2]); + Assert.Same(unrelated, f.Host.Files[3]); + Assert.Same(Original, before[0]); + } + + [Fact] + public void ExplicitStateIsReadAfterReferenceRewriteCallback() + { + var f = new Fixture(); + var late = Original with { Name = "late" }; + f.Backend.Rewrite = (_, _) => { f.Host.Explicit = true; f.Host.Files = [late]; return DefaultRewrite; }; + Assert.True(f.Replacer.TryApplyPresetFileReplacement(Original, Replacement, false)); + Assert.Equal("preset://replacement.txt", Assert.Single(f.Host.Files).Path); + Assert.NotSame(late, f.Host.Files[0]); + } + + [Fact] + public void CommandIsFormattedAfterExplicitFilesAndEventReadsThePostRebuildCommand() + { + var f = new Fixture(); + f.Host.Explicit = true; + f.Host.Files = [Original]; + f.Host.CommandSet = _ => Assert.Equal("preset://replacement.txt", Assert.Single(f.Host.Files).Path); + f.Host.Rebuild = () => f.Host.CurrentCommand = "changed by structure listener"; + Assert.True(f.Replacer.TryApplyPresetFileReplacement(Original, Replacement, true)); + Assert.Equal("--alpha 1" + Environment.NewLine + "--beta 2", Assert.Single(f.Host.Commands)); + Assert.Equal(("changed by structure listener", Original.Path, "preset://replacement.txt"), Assert.Single(f.Host.Replacements)); + Assert.True(f.Calls.IndexOf("event") < f.Calls.IndexOf("notice:Success")); + } + + [Fact] + public void UnchangedCommandStillRebuildsAndRaisesReplacementWithoutSetter() + { + var f = new Fixture(); + f.Backend.Rewrite = (_, _) => DefaultRewrite with { CommandChanged = false }; + Assert.True(f.Replacer.TryApplyPresetFileReplacement(Original, Replacement, false)); + Assert.Empty(f.Host.Commands); + Assert.Equal(("initial command", Original.Path, "preset://replacement.txt"), Assert.Single(f.Host.Replacements)); + Assert.Contains("rebuild", f.Calls); + Assert.DoesNotContain(f.Calls, call => call.StartsWith("text:")); + } + + [Theory] + [InlineData("update")] + [InlineData("rewrite")] + [InlineData("files")] + [InlineData("command")] + [InlineData("rebuild")] + [InlineData("event")] + [InlineData("success-notice")] + public void TryApplyCatchesFailuresAndRetainsEarlierMutations(string point) + { + var f = new Fixture(); + var error = new IOException(point); + f.Host.Explicit = true; + f.Host.Files = [Original]; + if (point == "update") f.Backend.Update = (_, _) => throw error; + if (point == "rewrite") f.Backend.Rewrite = (_, _) => throw error; + if (point == "files") f.Host.FilesSet = _ => throw error; + if (point == "command") f.Host.CommandSet = _ => throw error; + if (point == "rebuild") f.Host.Rebuild = () => throw error; + if (point == "event") f.Host.Replaced = (_, _) => throw error; + if (point == "success-notice") f.Host.Notice = (_, severity) => { if (severity == ConfigMakerPresetFileNoticeSeverity.Success) throw error; }; + Assert.False(f.Replacer.TryApplyPresetFileReplacement(Original, Replacement, true)); + Assert.Equal(("failed:" + point, ConfigMakerPresetFileNoticeSeverity.Error), f.Host.Notices.Last()); + if (point is "command" or "rebuild" or "event" or "success-notice") Assert.Equal("preset://replacement.txt", Assert.Single(f.Host.Files).Path); + if (point is "rebuild" or "event" or "success-notice") Assert.Single(f.Host.Commands); + if (point is "event" or "success-notice") Assert.Single(f.Host.Replacements); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void EmptyFileSuccessHonorsStatusFlag(bool show) + { + var f = new Fixture(); + Assert.True(f.Replacer.TryCreateEmptyPresetFile(Missing, show)); + Assert.Equal(new[] { Missing }, f.Backend.Created); + Assert.Contains("rebuild", f.Calls); + Assert.Equal(show ? 1 : 0, f.Host.Notices.Count); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void EmptyFileCreationFailureIsSwallowedAndSilentModeDoesNotLocalize(bool show) + { + var f = new Fixture(); + f.Backend.Create = _ => throw new IOException("create failed"); + Assert.False(f.Replacer.TryCreateEmptyPresetFile(Missing, show)); + Assert.DoesNotContain("rebuild", f.Calls); + Assert.Equal(show ? 1 : 0, f.Host.Notices.Count); + if (!show) Assert.DoesNotContain(f.Calls, call => call.StartsWith("text:")); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RebuildFailureAfterEmptyCreationDoesNotRollBackTheExternalEffect(bool show) + { + var f = new Fixture(); + f.Host.Rebuild = () => throw new IOException("rebuild failed"); + Assert.False(f.Replacer.TryCreateEmptyPresetFile(Missing, show)); + Assert.Contains(Missing, f.Backend.Created); + Assert.Contains(Missing, f.Backend.Existing); + Assert.Equal(show ? 1 : 0, f.Host.Notices.Count); + } + + [Fact] + public async Task LaterExistingPathSkipsAutoCreationAfterPriorEmptyCreation() + { + var f = AutoFixture(); + f.Backend.Corrector.Empty = true; + await f.Replacer.ReplacePresetFileAsync(Original); + await f.Replacer.ReplacePresetFileAsync(Original); + Assert.Equal(1, f.Backend.CorrectorCreations); + Assert.Single(f.Backend.Created); + } + + [Fact] + public void ErrorNoticeFailureEscapesTryApplyCatch() + { + var f = new Fixture(); + f.Backend.Update = (_, _) => throw new IOException("operation"); + var error = new InvalidOperationException("notice failed"); + f.Host.Notice = (_, _) => throw error; + Assert.Same(error, Assert.Throws(() => f.Replacer.TryApplyPresetFileReplacement(Original, Replacement, true))); + } + + [Fact] + public async Task WarningNoticeFailureStopsFallbackAndReachesOuterReporting() + { + var f = AutoFixture(); + var error = new IOException("warning failed"); + f.Host.Notice = (_, _) => throw error; + await f.Replacer.ReplacePresetFileAsync(Original); + Assert.Same(error, Assert.Single(f.Host.Reported)); + Assert.DoesNotContain("choose:" + Missing, f.Calls); + } + + private static readonly string Missing = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "cdpiui-replacer-fixture", "missing.txt")); + private static readonly string RawReplacement = Path.Combine(Path.GetTempPath(), "unused", "..", "replacement.txt"); + private static readonly string Replacement = Path.GetFullPath(RawReplacement); + private static readonly ConfigMakerPresetFileInfo Original = new("source.txt", "C:/missing/source.txt", "C:/missing", ConfigMakerPresetFileKind.SiteList, "--hostlist"); + private static readonly ConfigMakerPresetFileReplacement DefaultRewrite = new("preset://replacement.txt", "--alpha 1 --beta 2", true); + private static Fixture AutoFixture() + { + var f = new Fixture(); + f.Host.Choice = Task.FromResult(ConfigMakerFileReplacementChoice.AutoCorrect); + return f; + } + + private sealed class Fixture + { + public List Calls { get; } = []; + public Host Host { get; } + public Backend Backend { get; } + public ConfigMakerPresetFileReplacer Replacer { get; } + public Fixture() + { + Host = new(Calls); + Backend = new(Calls); + Replacer = new(Host, Backend); + } + } + + private sealed class Backend(List calls) : IConfigMakerPresetFileReplacementBackend + { + public HashSet Existing { get; } = new(StringComparer.OrdinalIgnoreCase) { Replacement }; + public List Created { get; } = []; + public int CorrectorCreations, UpdateCalls, ReferenceCalls; + public Corrector Corrector { get; } = new(calls); + public Func Resolve = _ => Missing; + public Action? Create; + public Func Update = (_, _) => false; + public Func Rewrite = (_, _) => DefaultRewrite; + public Func? Factory; + public string? TryResolvePath(string source) { calls.Add("resolve:" + source); return Resolve(source); } + public bool FileExists(string path) { calls.Add("exists:" + path); return Existing.Contains(path); } + public void CreateEmptyFile(string path) { calls.Add("create:" + path); Create?.Invoke(path); Created.Add(path); Existing.Add(path); } + public bool TryUpdateAttachedResource(ConfigMakerPresetFileInfo file, string path) { calls.Add("update"); UpdateCalls++; return Update(file, path); } + public ConfigMakerPresetFileReplacement? ReplaceReferences(ConfigMakerPresetFileInfo file, string path) { calls.Add("rewrite"); ReferenceCalls++; return Rewrite(file, path); } + public IConfigMakerPresetFileAutoCorrector CreateAutoCorrector() { calls.Add("factory"); CorrectorCreations++; return Factory == null ? Corrector : Factory(); } + } + + private sealed class Corrector(List calls) : IConfigMakerPresetFileAutoCorrector + { + public bool Empty; + public string? Suggestion = Replacement; + public Task? Finding; + public Func? CheckEmpty; + public Func>? Find; + public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public bool ShouldSuggestEmptyFile(string path) { calls.Add("suggest:" + path); return CheckEmpty == null ? Empty : CheckEmpty(path); } + public Task FindReplacementAsync(string path) { calls.Add("find:" + path); Started.TrySetResult(); return Find != null ? Find(path) : Finding ?? Task.FromResult(Suggestion); } + } + + private sealed class Host(List calls) : IConfigMakerPresetFileReplacementHost + { + public List<(string Message, ConfigMakerPresetFileNoticeSeverity Severity)> Notices { get; } = []; + public List Reported { get; } = []; + public List Commands { get; } = []; + public List<(string Command, string Original, string Replacement)> Replacements { get; } = []; + public Task Choice = Task.FromResult(ConfigMakerFileReplacementChoice.Cancel); + public string? Selected = Replacement; + public bool Explicit; + public ConfigMakerPresetFileInfo[] Files = []; + public string CurrentCommand = "initial command"; + public Action? Rebuild; + public Action? FilesSet; + public Action? CommandSet; + public Action? Replaced; + public Action? Notice; + public async Task RunReportingErrorsAsync(Func action) + { + calls.Add("run"); + try { await action(); } + catch (Exception error) { Reported.Add(error); calls.Add("reported"); } + } + public Task AskPresetFileReplacementAsync(string path) { Assert.Equal(Missing, path); calls.Add("ask"); return Choice; } + public string? ChooseReplacementFile(string path) { calls.Add("choose:" + path); return Selected; } + public string Text(string key) + { + calls.Add("text:" + key); + return key switch + { + "ConfigMakerPresetFileInvalidPathMessage" => "invalid", + "ConfigMakerPresetFileNoSuggestionMessage" => "no suggestion", + "ConfigMakerPresetFileReferenceNotFoundMessage" => "reference not found", + "ConfigMakerPresetFileEmptyCreatedMessage" => "empty:{0}", + "ConfigMakerPresetFileReplacedMessage" => "replaced:{0}", + "ConfigMakerPresetFileReplaceFailedMessage" => "failed:{0}", + _ => throw new InvalidOperationException("Unexpected localization key " + key), + }; + } + public void ShowPresetFileMessage(string message, ConfigMakerPresetFileNoticeSeverity severity) { calls.Add("notice:" + severity); Notices.Add((message, severity)); Notice?.Invoke(message, severity); } + public void RebuildPresetStructure() { calls.Add("rebuild"); Rebuild?.Invoke(); } + public bool UsesExplicitPresetStructure { get { calls.Add("explicit:uses"); return Explicit; } } + public ConfigMakerPresetFileInfo[] ExplicitPresetFiles + { + get { calls.Add("explicit:get"); return Files; } + set { calls.Add("explicit:set"); Files = value; FilesSet?.Invoke(value); } + } + public void SetCommandText(string value) { calls.Add("command"); Commands.Add(value); CurrentCommand = value; CommandSet?.Invoke(value); } + public void NotifyPresetFileReplaced(string original, string replacement) { calls.Add("event"); Replacements.Add((CurrentCommand, original, replacement)); Replaced?.Invoke(original, replacement); } + } +} diff --git a/CDPIUI.Tests/Presentation/ConfigMakerPresetReferenceEditorTests.cs b/CDPIUI.Tests/Presentation/ConfigMakerPresetReferenceEditorTests.cs new file mode 100644 index 00000000..f665b0f0 --- /dev/null +++ b/CDPIUI.Tests/Presentation/ConfigMakerPresetReferenceEditorTests.cs @@ -0,0 +1,141 @@ +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.ViewModels; + +namespace CDPIUI.Tests.Presentation; + +public class ConfigMakerPresetReferenceEditorTests +{ + [Fact] + public void AttachingFilesRewritesTheCommandAndEveryVariableValue() + { + using var fixture = new ConfigMakerResourceFixture(); + string hosts = fixture.CreateFile("hosts.txt"); + var variable = new ConfigMakerVariableDefinition + { + Value = hosts, + OnValue = $"--hostlist=\"{hosts}\"", + OffValue = hosts, + }; + variable.Values.Add(hosts); + fixture.Variables.Add(variable); + + string command = fixture.CreateEditor().AttachExistingFiles($"--hostlist=\"{hosts}\""); + + Assert.Equal("--hostlist=\"preset://hosts.txt\"", command); + Assert.Equal("preset://hosts.txt", variable.Value); + Assert.Equal("--hostlist=\"preset://hosts.txt\"", variable.OnValue); + Assert.Equal("preset://hosts.txt", variable.OffValue); + Assert.Equal("preset://hosts.txt", Assert.Single(variable.Values)); + Assert.Single(fixture.Resources); + } + + [Fact] + public void ReattachingAnAlreadyAttachedCommandDoesNotCreateResources() + { + using var fixture = new ConfigMakerResourceFixture(); + string file = fixture.CreateFile("hosts.txt"); + var editor = fixture.CreateEditor(); + string once = editor.AttachExistingFiles($"--hostlist=\"{file}\""); + + string twice = editor.AttachExistingFiles(once); + + Assert.Equal(once, twice); + Assert.Single(fixture.Resources); + } + + [Fact] + public void MissingReferencesRetainTheOriginalText() + { + using var fixture = new ConfigMakerResourceFixture(); + string original = $"--hostlist=\"{fixture.PathFor("missing.txt")}\""; + + Assert.Equal(original, fixture.CreateEditor().AttachExistingFiles(original)); + Assert.Empty(fixture.Resources); + } + + [Fact] + public void ReplacingAFilePreservesBlobNameOffsetAndLuaFileMarker() + { + using var fixture = new ConfigMakerResourceFixture(); + string blob = fixture.CreateFile("old.bin"); + string lua = fixture.CreateFile("old.lua"); + string replacementBlob = fixture.CreateFile("new.bin"); + string replacementLua = fixture.CreateFile("new.lua"); + var editor = fixture.CreateEditor(); + string command = $"--blob=tls:+4@\"{blob}\" --lua-init=@\"{lua}\""; + + var first = editor.ReplaceReferences(() => command, new("old.bin", blob, "", ConfigMakerPresetFileKind.Payload), replacementBlob); + var second = editor.ReplaceReferences(() => first!.UpdatedCommandText, + new("old.lua", lua, "", ConfigMakerPresetFileKind.Library), replacementLua); + + Assert.True(first.CommandChanged); + Assert.True(second!.CommandChanged); + Assert.Equal("--blob=tls:+4@preset://new.bin --lua-init=@preset://new.lua", second.UpdatedCommandText); + } + + [Fact] + public void VariableOnlyReplacementReturnsUnchangedCommandAndKeepsTheResource() + { + using var fixture = new ConfigMakerResourceFixture(); + string original = fixture.CreateFile("old.txt"); + string replacement = fixture.CreateFile("new.txt"); + var variable = new ConfigMakerVariableDefinition { Value = original, OnValue = original, OffValue = original }; + variable.Values.Add(original); + fixture.Variables.Add(variable); + + var result = fixture.CreateEditor().ReplaceReferences(() => "--debug=1", new("old", original, ""), replacement); + + Assert.NotNull(result); + Assert.False(result.CommandChanged); + Assert.Equal("--debug=1", result.UpdatedCommandText); + Assert.Equal("preset://new.txt", variable.Value); + Assert.Equal("preset://new.txt", variable.OnValue); + Assert.Equal("preset://new.txt", variable.OffValue); + Assert.Equal("preset://new.txt", Assert.Single(variable.Values)); + Assert.Single(fixture.Resources); + } + + [Fact] + public void NoMatchRemovesOnlyTheNewlyCreatedResource() + { + using var fixture = new ConfigMakerResourceFixture(); + string replacement = fixture.CreateFile("new.txt"); + + var result = fixture.CreateEditor().ReplaceReferences(() => "--debug=1", new("old", "unused.txt", ""), replacement); + + Assert.Null(result); + Assert.Empty(fixture.Resources); + } + + [Fact] + public void NoMatchRetainsAnAlreadyAttachedReplacement() + { + using var fixture = new ConfigMakerResourceFixture(); + string replacement = fixture.CreateFile("new.txt"); + var existing = fixture.Registry.GetOrCreate(replacement, ConfigMakerPresetFileKind.SiteList, out _); + + var result = fixture.CreateEditor().ReplaceReferences(() => "--debug=1", new("old", "unused.txt", ""), replacement); + + Assert.Null(result); + Assert.Same(existing, Assert.Single(fixture.Resources)); + } + + [Fact] + public void ReplacementReadsCommandAfterResourceAddedNotifications() + { + using var fixture = new ConfigMakerResourceFixture(); + string original = fixture.CreateFile("old.txt"); + string replacement = fixture.CreateFile("new.txt"); + string command = "--debug=1"; + var resources = new System.Collections.ObjectModel.ObservableCollection(); + resources.CollectionChanged += (_, _) => command = $"--hostlist=\"{original}\""; + var registry = new CDPIUI.Helper.CreateConfigHelper.ConfigMakerPresetResourceRegistry(resources, + path => path, _ => false); + var editor = new CDPIUI.Helper.CreateConfigHelper.ConfigMakerPresetReferenceEditor([], registry, _ => [], _ => null!); + + var result = editor.ReplaceReferences(() => command, new("old", original, ""), replacement); + + Assert.NotNull(result); + Assert.Equal("--hostlist=\"preset://new.txt\"", result.UpdatedCommandText); + } +} diff --git a/CDPIUI.Tests/Presentation/ConfigMakerPresetResourceTests.cs b/CDPIUI.Tests/Presentation/ConfigMakerPresetResourceTests.cs new file mode 100644 index 00000000..d7214c4c --- /dev/null +++ b/CDPIUI.Tests/Presentation/ConfigMakerPresetResourceTests.cs @@ -0,0 +1,145 @@ +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.ViewModels; + +namespace CDPIUI.Tests.Presentation; + +public class ConfigMakerPresetResourceTests +{ + [Theory] + [InlineData("hosts.txt", "hosts.txt")] + [InlineData(" list ?.txt", "list__.txt")] + [InlineData("список.txt", "spisok.txt")] + [InlineData("???", "resource.bin")] + public void AliasIsSafeAndRetainsTheFileExtension(string fileName, string expected) + { + using var fixture = new ConfigMakerResourceFixture(); + + Assert.Equal(expected, fixture.Registry.CreateUniqueAlias(fileName)); + } + + [Fact] + public void AliasesAreUniqueIgnoringCase() + { + using var fixture = new ConfigMakerResourceFixture(); + fixture.Resources.Add(new() { Alias = "HOSTS.txt" }); + fixture.Resources.Add(new() { Alias = "hosts_2.TXT" }); + + Assert.Equal("hosts_3.txt", fixture.Registry.CreateUniqueAlias("hosts.txt")); + } + + [Theory] + [InlineData("hosts.txt")] + [InlineData("PRESET://HOSTS.TXT")] + [InlineData(" 'preset://hosts.txt' ")] + public void AttachedResourceLookupAcceptsQuotedReferencesAndAliases(string reference) + { + using var fixture = new ConfigMakerResourceFixture(); + var resource = new ConfigMakerPresetResource { Alias = "hosts.txt" }; + fixture.Resources.Add(resource); + + Assert.Same(resource, fixture.Registry.FindAttached(reference)); + } + + [Fact] + public void AddingFilesSkipsMissingAndRepeatedPaths() + { + using var fixture = new ConfigMakerResourceFixture(); + string file = fixture.CreateFile("hosts.txt"); + + int added = fixture.Registry.AddFiles(["", fixture.PathFor("missing.txt"), file, file.ToUpperInvariant()]); + + Assert.Equal(1, added); + var resource = Assert.Single(fixture.Resources); + Assert.Equal("preset://hosts.txt", resource.Reference); + Assert.Equal(file, resource.Path); + Assert.Equal(ConfigMakerResourceKind.SiteList, resource.Kind); + Assert.False(resource.IsBuiltIn); + } + + [Fact] + public void GetOrCreateReusesResolvedPathsAndKeepsTheOriginalKind() + { + using var fixture = new ConfigMakerResourceFixture(); + string file = fixture.CreateFile("data.bin"); + var first = fixture.Registry.GetOrCreate(file, ConfigMakerPresetFileKind.Payload, out bool added); + + var second = fixture.Registry.GetOrCreate(file.ToUpperInvariant(), ConfigMakerPresetFileKind.Library, out bool addedAgain); + + Assert.True(added); + Assert.False(addedAgain); + Assert.Same(first, second); + Assert.Single(fixture.Resources); + Assert.Equal(ConfigMakerResourceKind.Payload, second.Kind); + } + + [Fact] + public void ExistingPresetReferencesAndMissingFilesAreNotAttachedAgain() + { + using var fixture = new ConfigMakerResourceFixture(); + + Assert.Null(fixture.Registry.GetOrCreate(new("hosts", "preset://hosts", ""), out bool aliasAdded)); + Assert.Null(fixture.Registry.GetOrCreate(new("missing", fixture.PathFor("missing.txt"), ""), out bool missingAdded)); + Assert.False(aliasAdded); + Assert.False(missingAdded); + Assert.Empty(fixture.Resources); + } + + [Fact] + public void ReplacingAnAttachedFileRetainsItsAliasAndUpdatesBuiltInState() + { + using var fixture = new ConfigMakerResourceFixture(); + string componentFile = fixture.CreateFile("component/init.lua"); + var resource = new ConfigMakerPresetResource { Alias = "custom.lua", Path = fixture.CreateFile("external.lua") }; + fixture.Resources.Add(resource); + + bool changed = fixture.Registry.TryUpdateAttachedResource(new("custom", resource.Reference, ""), componentFile); + + Assert.True(changed); + Assert.Equal("custom.lua", resource.Alias); + Assert.Equal(componentFile, resource.Path); + Assert.True(resource.IsBuiltIn); + Assert.False(fixture.Registry.TryUpdateAttachedResource(new("other", "preset://other", ""), componentFile)); + } +} + +internal sealed class ConfigMakerResourceFixture : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "cdpiui-preset-tests", Guid.NewGuid().ToString("N")); + + public ConfigMakerResourceFixture() + { + Directory.CreateDirectory(_root); + Registry = new(Resources, ResolvePath, path => path.StartsWith(PathFor("component") + Path.DirectorySeparatorChar, + StringComparison.OrdinalIgnoreCase)); + } + + public List Resources { get; } = []; + public List Variables { get; } = []; + public ConfigMakerPresetResourceRegistry Registry { get; } + + public string PathFor(string relative) => Path.Combine(_root, relative); + + public string CreateFile(string relative) + { + string path = Path.GetFullPath(PathFor(relative)); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, "fixture"); + return path; + } + + public ConfigMakerPresetReferenceEditor CreateEditor() => new( + Variables, Registry, + text => CDPIUI.Core.ComponentServices.Helpers.Configuration.ConfigFileReferences.ExtractFromText(text) + .Select(file => ConfigMakerPresetFileKinds.ToEditorFile(file)!), + value => ConfigMakerPresetFileKinds.ToEditorFile( + CDPIUI.Core.ComponentServices.Helpers.Configuration.ConfigFileReferences.ExtractDirectFile(value))); + + private string ResolvePath(string reference) + { + var resource = Registry.FindAttached(reference); + return Path.GetFullPath(resource?.Path ?? reference); + } + + public void Dispose() => Directory.Delete(_root, recursive: true); +} diff --git a/CDPIUI.Tests/Presentation/ConfigMakerPresetStructureTests.cs b/CDPIUI.Tests/Presentation/ConfigMakerPresetStructureTests.cs new file mode 100644 index 00000000..a8bfa497 --- /dev/null +++ b/CDPIUI.Tests/Presentation/ConfigMakerPresetStructureTests.cs @@ -0,0 +1,366 @@ +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.Core.ComponentServices.Helpers.Configuration; +using CDPIUI.Helper.CreateConfigHelper; + +namespace CDPIUI.Tests.Presentation; + +public sealed class ConfigMakerPresetStructureTests +{ + [Fact] + public void ConstructorStoresPortsWithoutReadingAndPreservesColdVisibility() + { + var f = new Fixture(); + Assert.Empty(f.Trace); Assert.Empty(f.Owner.PresetFileNodes); Assert.Empty(f.Owner.PresetGroupNodes); + Assert.False(f.Owner.HasPresetFiles); Assert.True(f.Owner.HasPresetGroups); Assert.True(f.Owner.IsPresetStructureVisible); + } + + [Fact] + public void DetectedThenAttachedFilesUseFirstKindAndOrdinalIgnoreCasePath() + { + var a = File("A.txt"); var duplicate = File("a.TXT"); + var library = File("A.txt") with { Kind = ConfigMakerPresetFileKind.Library }; + var attached = File("B.txt") with { IsAttachedResource = true }; + var f = new Fixture { Detected = [a, duplicate, library], Attached = [duplicate, attached] }; + f.Owner.Rebuild(); + Assert.Equal([a, library, attached], f.FileInputs.Single()); + Assert.Same(a, f.FileInputs[0][0]); Assert.Same(attached, f.FileInputs[0][2]); + Assert.True(f.Owner.HasPresetFiles); + } + + [Fact] + public void ExplicitFilesFilterBlanksAndDeduplicateWithoutLosingFirstObject() + { + var a = File("a"); var b = File("b"); + var f = new Fixture { Attached = [File("A"), b] }; + f.Owner.Set([File(" "), File(null!), a, File("A"), a with { Kind = ConfigMakerPresetFileKind.Payload }], []); + Assert.Equal([a, a with { Kind = ConfigMakerPresetFileKind.Payload }, b], f.FileInputs.Single()); + Assert.Same(a, f.FileInputs[0][0]); + } + + [Fact] + public void EnrichmentCopiesOnlyMissingOptionFromFirstMatchingKindAndPath() + { + var e = File("A.txt"); var withOption = File("b") with { OptionName = "--kept" }; + var noMatch = File("c"); + var f = new Fixture { Detected = [File("a.TXT") with { OptionName = "--first" }, File("a.txt") with { OptionName = "--second" }, File("b") with { OptionName = "--ignored" }, File("c") with { Kind = ConfigMakerPresetFileKind.Library, OptionName = "--wrong-kind" }] }; + f.Owner.Set([e, withOption, noMatch], []); + var actual = f.FileInputs.Single(); + Assert.NotSame(e, actual[0]); Assert.Equal(e with { OptionName = "--first" }, actual[0]); + Assert.Same(withOption, actual[1]); Assert.Same(noMatch, actual[2]); + Assert.Equal("", e.OptionName); + } + + [Fact] + public void ExplicitEmptyDoesNotFallBackToDetectedButStillIncludesAttached() + { + var a = File("attached"); var f = new Fixture { Detected = [File("detected")], Attached = [a] }; + f.Owner.Set([], []); + Assert.Same(a, Assert.Single(f.FileInputs.Single())); + } + + [Fact] + public void GroupsAreMaterializedAndRetainOriginalGroupObjects() + { + var group = new ConfigMakerPresetGroupInfo("original", ["detail"]); + var input = new List { group }; + var f = new Fixture(); f.Owner.Set([], input); input.Clear(); f.Owner.Rebuild(); + Assert.Same(group, Assert.Single(f.GroupInputs.Last().Groups)); + Assert.Equal("detail", Assert.Single(f.GroupInputs.Last().Groups[0].Details)); + } + + [Fact] + public void RealParserReceivesSecondLiveCommandAndPreservesCoordinates() + { + var f = new Fixture { Command = "--old" }; + f.Owner.PropertyChanged += (_, e) => { if (e.PropertyName == "PresetFileNodes") { f.Command = "--dns-addr 1.1.1.1\n--new --name=second"; f.Zapret = true; } }; + f.Owner.Rebuild(); + Assert.Equal("extract:--old", f.Trace[1]); + var call = f.GroupInputs.Single(); + Assert.True(call.Zapret); + Assert.Equal(["--dns-addr", "--new", "--name"], call.Options.Select(o => o.Name)); + Assert.Equal([0, 1, 1], call.Options.Select(o => o.SourceLine)); + Assert.Equal("second", call.Options[2].Value); + Assert.Equal(6, call.Options[2].SourceColumn); + } + + [Fact] + public void FilePublicationSeesOldFlagsAndGroupPublicationSeesBothNewFlags() + { + var f = new Fixture { Detected = [File("a")], GroupNodes = [new("group")] }; + var observations = new List(); + f.Owner.PropertyChanged += (sender, e) => + { + Assert.Same(f.Owner, sender); + observations.Add($"{e.PropertyName}:{f.Owner.HasPresetFiles}:{f.Owner.HasPresetGroups}:{f.Owner.IsPresetStructureVisible}"); + }; + f.Owner.AvailabilityChanged += (sender, args) => { Assert.Same(f.Owner, sender); Assert.Same(EventArgs.Empty, args); observations.Add("availability"); }; + f.Owner.Set([File("a")], []); + Assert.Equal(["PresetFileNodes:False:False:False", "PresetGroupNodes:True:True:True", "HasPresetFiles:True:True:True", "HasPresetGroups:True:True:True", "IsPresetStructureVisible:True:True:True", "availability"], observations); + Assert.Equal(["text", "extract:", "attached", "files", "event:PresetFileNodes", "text", "zapret", "groups", "event:PresetGroupNodes", "event:HasPresetFiles", "event:HasPresetGroups", "event:IsPresetStructureVisible", "availability"], f.Trace); + } + + [Fact] + public void RebuildAlwaysRaisesThreeDerivedNotificationsButOnlyRawAvailabilityDeltas() + { + var f = new Fixture(); f.Owner.Rebuild(); + Assert.DoesNotContain("availability", f.Trace); + Assert.True(f.Owner.HasPresetGroups); Assert.True(f.Owner.IsPresetStructureVisible); + f.Trace.Clear(); f.Owner.Set([], []); + Assert.False(f.Owner.HasPresetGroups); Assert.False(f.Owner.IsPresetStructureVisible); + Assert.DoesNotContain("availability", f.Trace); // Changing only explicit mode never raised this event. + Assert.Equal(["event:HasPresetFiles", "event:HasPresetGroups", "event:IsPresetStructureVisible"], f.Trace.Where(x => x.StartsWith("event:")).TakeLast(3)); + } + + [Fact] + public void ClearResetsExplicitModeAndArraysThenRebuildsWithLiveDetectedFiles() + { + var f = new Fixture { Detected = [File("detected")] }; + f.Owner.Set([File("explicit")], [new("explicit group", [])]); + f.Owner.Clear(); + Assert.Equal("detected", Assert.Single(f.FileInputs.Last()).Path); + Assert.Empty(f.GroupInputs.Last().Groups); Assert.True(f.Owner.HasPresetGroups); + } + + [Fact] + public void SuccessfulEmptyRebuildPublishesFreshProjectionCollections() + { + var f = new Fixture(); f.Owner.Rebuild(); + var files = f.Owner.PresetFileNodes; var groups = f.Owner.PresetGroupNodes; + f.Owner.Rebuild(); + Assert.NotSame(files, f.Owner.PresetFileNodes); Assert.NotSame(groups, f.Owner.PresetGroupNodes); + Assert.Empty(f.Owner.PresetFileNodes); Assert.Empty(f.Owner.PresetGroupNodes); + } + + [Fact] + public void SameProjectionReferencesSuppressOnlyNodePropertyNotifications() + { + var f = new Fixture(); IReadOnlyList files = [new("file")], groups = [new("group")]; + f.ProjectFiles = _ => files; f.ProjectGroups = (_, _, _) => groups; + f.Owner.Rebuild(); f.Trace.Clear(); f.Owner.Rebuild(); + Assert.Equal(["event:HasPresetFiles", "event:HasPresetGroups", "event:IsPresetStructureVisible"], f.Trace.Where(x => x.StartsWith("event:"))); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void NullArgumentsAreCheckedBeforeEitherInputIsEnumerated(bool first) + { + var f = new Fixture(); int enumerations = 0; + IEnumerable Input() { enumerations++; yield break; } + var error = Assert.Throws(() => f.Owner.Set(first ? null! : Input(), first ? Input() : null!)); + Assert.Equal(first ? "files" : "groups", error.ParamName); + Assert.Equal(0, enumerations); Assert.Empty(f.Trace); + } + + [Fact] + public void ThrowingFileEnumerationPreservesPreviousExplicitFilesAndMode() + { + var f = new Fixture(); f.Owner.Set([File("old")], [new("old", [])]); + Assert.Throws(() => f.Owner.Set(ThrowingFiles(), [])); + f.Owner.Rebuild(); Assert.Equal("old", Assert.Single(f.FileInputs.Last()).Path); + Assert.Equal("old", Assert.Single(f.GroupInputs.Last().Groups).Name); + } + + [Fact] + public void ThrowingGroupEnumerationKeepsNewFilesAndPreviousGroupsWithoutRebuilding() + { + var f = new Fixture(); f.Owner.Set([File("old")], [new("old", [])]); + int count = f.FileInputs.Count; + Assert.Throws(() => f.Owner.Set([File("new")], ThrowingGroups())); + Assert.Equal(count, f.FileInputs.Count); + f.Owner.Rebuild(); Assert.Equal("new", Assert.Single(f.FileInputs.Last()).Path); + Assert.Equal("old", Assert.Single(f.GroupInputs.Last().Groups).Name); + } + + [Fact] + public void FirstSetGroupFailureDoesNotEnableExplicitMode() + { + var f = new Fixture { Detected = [File("detected")] }; + Assert.Throws(() => f.Owner.Set([File("uncommitted explicit")], ThrowingGroups())); + f.Owner.Rebuild(); + Assert.Equal("detected", Assert.Single(f.FileInputs.Last()).Path); + Assert.Empty(f.GroupInputs.Last().Groups); Assert.True(f.Owner.HasPresetGroups); + } + + [Fact] + public void FirstCommandReadFailureDoesNotExtractOrPublishAnything() + { + var f = new Fixture { Failure = "text1" }; + var files = f.Owner.PresetFileNodes; var groups = f.Owner.PresetGroupNodes; + Assert.Throws(f.Owner.Rebuild); + Assert.Equal(["text"], f.Trace); + Assert.Same(files, f.Owner.PresetFileNodes); Assert.Same(groups, f.Owner.PresetGroupNodes); + } + + [Theory] + [InlineData("extract")] + [InlineData("attached")] + [InlineData("files")] + public void FailureBeforeFileAssignmentKeepsPublishedNodesAndFlags(string phase) + { + var f = new Fixture { Detected = [File("old")] }; f.Owner.Rebuild(); + var files = f.Owner.PresetFileNodes; var groups = f.Owner.PresetGroupNodes; + f.Failure = phase; + Assert.Throws(f.Owner.Rebuild); + Assert.Same(files, f.Owner.PresetFileNodes); Assert.Same(groups, f.Owner.PresetGroupNodes); + Assert.True(f.Owner.HasPresetFiles); + f.Failure = null; f.Detected = []; f.Owner.Rebuild(); Assert.False(f.Owner.HasPresetFiles); + } + + [Theory] + [InlineData("text2")] + [InlineData("zapret")] + [InlineData("groups")] + public void FailureAfterFileAssignmentKeepsNewFilesButPreviousFlagsAndGroups(string phase) + { + var f = new Fixture(); f.Owner.Rebuild(); + var files = f.Owner.PresetFileNodes; var groups = f.Owner.PresetGroupNodes; + f.Detected = [File("new")]; f.Failure = phase; f.TextReads = 0; + Assert.Throws(f.Owner.Rebuild); + Assert.NotSame(files, f.Owner.PresetFileNodes); Assert.Same(groups, f.Owner.PresetGroupNodes); + Assert.False(f.Owner.HasPresetFiles); + f.Failure = null; f.Owner.Rebuild(); Assert.True(f.Owner.HasPresetFiles); + } + + [Theory] + [InlineData("PresetFileNodes", false)] + [InlineData("PresetGroupNodes", true)] + [InlineData("HasPresetFiles", true)] + [InlineData("HasPresetGroups", true)] + [InlineData("IsPresetStructureVisible", true)] + public void ThrowingObserverRetainsExactlyTheAlreadyPublishedPartialState(string property, bool newFlags) + { + var f = new Fixture { Detected = [File("new")], GroupNodes = [new("group")] }; + var initialGroups = f.Owner.PresetGroupNodes; + f.Owner.PropertyChanged += (_, e) => { if (e.PropertyName == property) throw new ProbeFailure(); }; + Assert.Throws(f.Owner.Rebuild); + Assert.Single(f.Owner.PresetFileNodes); Assert.Equal(newFlags, f.Owner.HasPresetFiles); + if (newFlags) Assert.Single(f.Owner.PresetGroupNodes); else Assert.Same(initialGroups, f.Owner.PresetGroupNodes); + Assert.DoesNotContain("availability", f.Trace); + } + + [Fact] + public void AvailabilityObserverThrowsAfterEveryStateAndPropertyHasBeenPublished() + { + var f = new Fixture { Detected = [File("new")], GroupNodes = [new("group")] }; + f.Owner.AvailabilityChanged += (_, _) => throw new ProbeFailure(); + Assert.Throws(f.Owner.Rebuild); + Assert.True(f.Owner.HasPresetFiles); Assert.True(f.Owner.HasPresetGroups); + Assert.Single(f.Owner.PresetGroupNodes); Assert.Equal("availability", f.Trace.Last()); + } + + [Fact] + public void ExplicitEnrichmentIsRecomputedEachTimeWithoutMutatingStoredInput() + { + var f = new Fixture { Detected = [File("a") with { OptionName = "--one" }] }; + f.Owner.Set([File("a")], []); f.Detected = [File("a") with { OptionName = "--two" }]; f.Owner.Rebuild(); + Assert.Equal("--one", f.FileInputs[0][0].OptionName); Assert.Equal("--two", f.FileInputs[1][0].OptionName); + } + + [Fact] + public void FileObserverReentryPublishesNestedStateThenOuterReadsCurrentCommandAndGroups() + { + var f = new Fixture { Command = "--old", Detected = [File("outer")] }; + bool nested = false; + f.Owner.PropertyChanged += (_, e) => + { + if (e.PropertyName != "PresetFileNodes" || nested) return; + nested = true; f.Command = "--new"; f.Zapret = true; + f.Owner.Set([File("inner")], [new("inner group", [])]); + }; + f.Owner.Rebuild(); + Assert.Equal(["outer", "inner"], f.FileInputs.Select(x => Assert.Single(x).Path)); + Assert.Equal("inner", Assert.Single(f.Owner.PresetFileNodes).Label); + Assert.Equal(2, f.GroupInputs.Count); + Assert.All(f.GroupInputs, x => { Assert.Equal("--new", Assert.Single(x.Options).Name); Assert.Equal("inner group", Assert.Single(x.Groups).Name); Assert.True(x.Zapret); }); + Assert.Equal(1, f.Trace.Count(x => x == "availability")); + } + + [Fact] + public void ReentryFromGroupPublicationCanReplaceFlagsBeforeOuterDerivedEvents() + { + var f = new Fixture { Detected = [File("outer")] }; bool nested = false; + var flags = new List(); + f.Owner.PropertyChanged += (_, e) => + { + if (e.PropertyName == "PresetGroupNodes" && !nested) + { nested = true; f.Detected = []; f.Owner.Set([], []); } + if (e.PropertyName == "HasPresetFiles") flags.Add(f.Owner.HasPresetFiles); + }; + f.Owner.Rebuild(); + Assert.Equal([false, false], flags); Assert.False(f.Owner.HasPresetFiles); Assert.False(f.Owner.HasPresetGroups); + Assert.Equal(2, f.Trace.Count(x => x == "availability")); // Outer delta was captured before nested mutation. + } + + [Fact] + public void ClearFailureStillLeavesExplicitModeAndArraysCleared() + { + var f = new Fixture(); f.Owner.Set([File("explicit")], [new("group", [])]); + f.Failure = "extract"; Assert.Throws(f.Owner.Clear); + f.Failure = null; f.Detected = [File("detected")]; f.Owner.Rebuild(); + Assert.Equal("detected", Assert.Single(f.FileInputs.Last()).Path); Assert.Empty(f.GroupInputs.Last().Groups); + } + + [Fact] + public void ReplacementArrayAssignmentKeepsIdentityWithoutPublishingOrChangingMode() + { + var f = new Fixture(); f.Owner.Set([File("old")], []); f.Trace.Clear(); + var nodes = f.Owner.PresetFileNodes; + ConfigMakerPresetFileInfo[] replacement = [File("replacement")]; + f.Owner.ExplicitPresetFiles = replacement; + Assert.Same(replacement, f.Owner.ExplicitPresetFiles); Assert.True(f.Owner.UsesExplicitPresetStructure); + Assert.Same(nodes, f.Owner.PresetFileNodes); Assert.Empty(f.Trace); + replacement[0] = File("mutated"); f.Owner.Rebuild(); + Assert.Equal("mutated", Assert.Single(f.FileInputs.Last()).Path); + } + + [Fact] + public void ReplacementArrayBeforeFirstSetDoesNotTurnOnExplicitMode() + { + var f = new Fixture { Detected = [File("detected")] }; + ConfigMakerPresetFileInfo[] replacement = [File("replacement")]; + f.Owner.ExplicitPresetFiles = replacement; + Assert.False(f.Owner.UsesExplicitPresetStructure); Assert.Empty(f.Trace); + f.Owner.Rebuild(); + Assert.Equal("detected", Assert.Single(f.FileInputs.Last()).Path); + Assert.Same(replacement, f.Owner.ExplicitPresetFiles); + f.Owner.Clear(); Assert.Empty(f.Owner.ExplicitPresetFiles); Assert.False(f.Owner.UsesExplicitPresetStructure); + } + + private static ConfigMakerPresetFileInfo File(string path) => new(path, path, "folder"); + private static IEnumerable ThrowingFiles() { yield return File("partial"); throw new ProbeFailure(); } + private static IEnumerable ThrowingGroups() { yield return new("partial", []); throw new ProbeFailure(); } + private sealed class ProbeFailure : Exception; + private sealed record Node(string Label); + private sealed record GroupCall(IReadOnlyList Options, IReadOnlyList Groups, bool Zapret); + + private sealed class Fixture + { + public List Trace { get; } = []; + public string Command { get; set; } = ""; + public bool Zapret { get; set; } + public IEnumerable Detected { get; set; } = []; + public IEnumerable Attached { get; set; } = []; + public IReadOnlyList GroupNodes { get; set; } = []; + public List> FileInputs { get; } = []; + public List GroupInputs { get; } = []; + public Func, IReadOnlyList>? ProjectFiles; + public Func, IReadOnlyList, bool, IReadOnlyList>? ProjectGroups; + public string? Failure; + public int TextReads; + public ConfigMakerPresetStructure Owner { get; } + public Fixture() + { + Owner = new( + () => { Trace.Add("text"); TextReads++; if (Failure == "text1" || (Failure == "text2" && TextReads == 2)) throw new ProbeFailure(); return Command; }, + () => { Trace.Add("zapret"); Fail("zapret"); return Zapret; }, + command => { Trace.Add("extract:" + command); Fail("extract"); return Detected; }, + () => { Trace.Add("attached"); Fail("attached"); return Attached; }, + files => { Trace.Add("files"); Fail("files"); FileInputs.Add(files); return ProjectFiles?.Invoke(files) ?? files.Select(f => new Node(f.Path)).ToList(); }, + (options, groups, zapret) => { Trace.Add("groups"); Fail("groups"); GroupInputs.Add(new(options, groups, zapret)); return ProjectGroups?.Invoke(options, groups, zapret) ?? GroupNodes.ToList(); }); + Owner.PropertyChanged += (_, e) => Trace.Add("event:" + e.PropertyName); + Owner.AvailabilityChanged += (_, _) => Trace.Add("availability"); + } + private void Fail(string phase) { if (Failure == phase) throw new ProbeFailure(); } + } +} diff --git a/CDPIUI.Tests/Presentation/ConfigMakerPresetTreeBuilderTests.cs b/CDPIUI.Tests/Presentation/ConfigMakerPresetTreeBuilderTests.cs new file mode 100644 index 00000000..d3858da1 --- /dev/null +++ b/CDPIUI.Tests/Presentation/ConfigMakerPresetTreeBuilderTests.cs @@ -0,0 +1,190 @@ +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.Core.ComponentServices.Helpers.Configuration; +using CDPIUI.Helper.CreateConfigHelper; + +namespace CDPIUI.Tests.Presentation; + +public class ConfigMakerPresetTreeBuilderTests +{ + [Fact] + public void FilesAreGroupedByKindAndSortedWithinEachCategory() + { + var builder = CreateBuilder(); + ConfigMakerPresetFileInfo[] files = + [ + new("z.txt", "z.txt", ""), + new("payload.bin", "payload.bin", "", ConfigMakerPresetFileKind.Payload), + new("a.txt", "a.txt", ""), + new("init.lua", "init.lua", "", ConfigMakerPresetFileKind.Library), + ]; + + var nodes = builder.BuildFiles(files); + + Assert.Equal(["Lists", "Libraries", "Payloads"], nodes.Select(node => node.DisplayName)); + Assert.Equal(["a.txt", "z.txt"], nodes[0].Children.Select(node => node.DisplayName)); + Assert.All(nodes, node => Assert.True(node.IsExpanded)); + Assert.All(nodes, node => Assert.Null(node.File)); + Assert.Same(files[2], nodes[0].Children[0].File); + } + + [Fact] + public void MissingFileTooltipUsesTheResolvedPath() + { + var file = new ConfigMakerPresetFileInfo("missing.txt", "missing.txt", ""); + + var leaf = Assert.Single(Assert.Single(CreateBuilder().BuildFiles([file])).Children); + + Assert.True(leaf.IsMissing); + Assert.Equal("Missing: /resolved/missing.txt", leaf.ToolTip); + Assert.False(leaf.IsExpanded); + } + + [Fact] + public void AttachedFileTooltipRetainsReferenceAndResolvedPath() + { + var file = new ConfigMakerPresetFileInfo("hosts", "preset://hosts", "", IsAttachedResource: true); + + var leaf = Assert.Single(Assert.Single(CreateBuilder().BuildFiles([file])).Children); + + Assert.False(leaf.IsMissing); + Assert.Equal($"preset://hosts{Environment.NewLine}/resolved/preset://hosts", leaf.ToolTip); + } + + [Fact] + public void UnresolvableFileIsMissingWithoutCheckingTheFilesystem() + { + var builder = new ConfigMakerPresetTreeBuilder(Localize, _ => "", _ => throw new Exception("Unexpected I/O"), _ => ""); + + var leaf = Assert.Single(Assert.Single(builder.BuildFiles([new("bad", "bad", "")])).Children); + + Assert.True(leaf.IsMissing); + Assert.Equal("Missing: ", leaf.ToolTip); + } + + [Fact] + public void EmptyFilesProduceNoCategories() => Assert.Empty(CreateBuilder().BuildFiles([])); + + [Fact] + public void CommonOptionsAndProfilesRetainTheirOrderAndExplicitNames() + { + var options = ConfigCommandLine.ParseOptions( + "--wf-tcp=80 --debug=1 --filter-tcp=80 --name=parsed --dpi-desync=fake --new --filter-udp=443 --dpi-desync=split"); + + var nodes = CreateBuilder().BuildGroups(options, [new("Explicit", [])], isZapret2: true); + + Assert.Equal(["Common filters", "Common options", "Explicit", "Profile 2"], nodes.Select(node => node.Title)); + Assert.Equal("--wf-tcp=80", Assert.Single(nodes[0].Children).Title); + Assert.Equal("--debug=1", Assert.Single(nodes[1].Children).Title); + Assert.Equal(["Profile filters", "Profile actions"], nodes[2].Children.Select(node => node.Title)); + Assert.Equal(["--filter-tcp=80", "--name=parsed"], nodes[2].Children[0].Children.Select(node => node.Title)); + Assert.Equal("--dpi-desync=fake", Assert.Single(nodes[2].Children[1].Children).Title); + } + + [Fact] + public void ParsedProfileNameIsUnquotedWhenThereIsNoExplicitName() + { + var nodes = CreateBuilder().BuildGroups( + ConfigCommandLine.ParseOptions("--filter-tcp=80 --name=\"My profile\" --dpi-desync=fake"), [], true); + + Assert.Equal("My profile", Assert.Single(nodes).Title); + } + + [Fact] + public void SourceSpansAreRetainedForNavigationToTheEditor() + { + var options = ConfigCommandLine.ParseOptions("\n --filter-tcp=80\n --dpi-desync=fake"); + + var groups = CreateBuilder().BuildGroups(options, [], true); + var leaf = Assert.Single(groups[0].Children[1].Children); + + Assert.True(leaf.IsCode); + Assert.Same(options[1], leaf.Source); + Assert.Equal(21, leaf.Source!.SourceIndex); + Assert.Equal(2, leaf.Source.SourceLine); + Assert.Equal(2, leaf.Source.SourceColumn); + Assert.Equal("help:--dpi-desync", leaf.Description); + } + + [Theory] + [InlineData("")] + [InlineData("--new --new")] + public void EmptyProfilesUseExplicitFallbackDetails(string command) + { + var nodes = CreateBuilder().BuildGroups( + ConfigCommandLine.ParseOptions(command), [new("Fallback", ["first", " ", "second"])], true); + + var group = Assert.Single(nodes); + Assert.Equal("Fallback", group.Title); + Assert.Equal(["first", "second"], group.Children.Select(node => node.Title)); + Assert.All(group.Children, node => Assert.True(node.IsCode)); + Assert.All(group.Children, node => Assert.Null(node.Source)); + Assert.False(group.IsExpanded); + } + + [Fact] + public void NonZapretComponentsDoNotGetZapretDescriptions() + { + var builder = new ConfigMakerPresetTreeBuilder(Localize, path => path, _ => true, + _ => throw new Exception("Zapret describer must not run")); + + var nodes = builder.BuildGroups(ConfigCommandLine.ParseOptions("--filter-tcp=80 --dpi-desync=fake"), [], false); + + Assert.Empty(nodes[0].Description); + Assert.All(nodes[0].Children, node => Assert.Empty(node.Description)); + Assert.All(nodes[0].Children.SelectMany(node => node.Children), node => Assert.Empty(node.Description)); + } + + [Fact] + public void EmptyCommandAndNoExplicitGroupsProduceNoGroups() => + Assert.Empty(CreateBuilder().BuildGroups([], [], true)); + + [Fact] + public void EmptyTreeProjectionChangesIdentityForPropertyNotifications() + { + // Empty explicit structure and cleared structure have different tab visibility. + // Both still publish an empty tree; SetProperty must see a new collection. + var explicitTree = ConfigMakerPresetTreeProjection.Map(Array.Empty(), value => value); + var clearedTree = ConfigMakerPresetTreeProjection.Map(Array.Empty(), value => value); + + Assert.Empty(explicitTree); + Assert.Empty(clearedTree); + Assert.NotSame(explicitTree, clearedTree); + } + + [Theory] + [InlineData("en-US", "ä.txt", "z.txt")] + [InlineData("sv-SE", "z.txt", "ä.txt")] + public void FileSortingUsesTheCurrentCulture(string culture, string first, string second) + { + var previousCulture = System.Globalization.CultureInfo.CurrentCulture; + try + { + System.Globalization.CultureInfo.CurrentCulture = new(culture); + var nodes = CreateBuilder().BuildFiles([new("ä.txt", "a.txt", ""), new("z.txt", "z.txt", "")]); + + Assert.Equal([first, second], Assert.Single(nodes).Children.Select(node => node.DisplayName)); + } + finally + { + System.Globalization.CultureInfo.CurrentCulture = previousCulture; + } + } + + private static ConfigMakerPresetTreeBuilder CreateBuilder() => new( + Localize, path => "/resolved/" + path, + path => !path.EndsWith("missing.txt", StringComparison.Ordinal), option => "help:" + option.Name); + + private static string Localize(string key) => key switch + { + "ConfigMakerPresetFileCategoryLibraries" => "Libraries", + "ConfigMakerPresetFileCategoryPayloads" => "Payloads", + "ConfigMakerPresetFileCategorySiteLists" => "Lists", + "ConfigMakerPresetFileMissingMessage" => "Missing: {0}", + "ConfigMakerPresetCommonFiltersGroup" => "Common filters", + "ConfigMakerPresetCommonOptionsGroup" => "Common options", + "ConfigMakerPresetProfileFiltersGroup" => "Profile filters", + "ConfigMakerPresetProfileActionsGroup" => "Profile actions", + "ConfigMakerPresetProfileFallbackName" => "Profile {0}", + _ => key, + }; +} diff --git a/CDPIUI.Tests/Presentation/ConfigMakerSimpleDesignerTests.cs b/CDPIUI.Tests/Presentation/ConfigMakerSimpleDesignerTests.cs new file mode 100644 index 00000000..0ef22d5a --- /dev/null +++ b/CDPIUI.Tests/Presentation/ConfigMakerSimpleDesignerTests.cs @@ -0,0 +1,299 @@ +using System.Collections.ObjectModel; +using System.Windows.Input; +using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.Views.CreateConfigHelper; + +namespace CDPIUI.Tests.Presentation; + +public class ConfigMakerSimpleDesignerTests +{ + [Fact] + public void ConstructionDoesNotLoadModelsOrReadEditorState() + { + var fixture = new DesignerFixture(); + + Assert.Empty(fixture.Trace); + Assert.Equal(0, fixture.Backend.SupportChecks); + Assert.Empty(fixture.Designer.DesignerSettingItemModels); + } + + [Fact] + public void EnteringLoadsModelsCommandsAndRemainingArgumentsInOrder() + { + var fixture = new DesignerFixture(); + + fixture.Designer.OnEditorViewChanged(false, true); + + Assert.Equal(["read:--known=1 --extra=2", "load:supported", "read:--known=1 --extra=2", "parse:--known=1 --extra=2"], fixture.Trace); + Assert.Equal("--extra=2", fixture.Designer.AdditionalDesignerArguments); + Assert.Same(fixture.TextCommand, Assert.Single(fixture.Designer.DesignerSettingItemModels).DesignerTextValueChangedCommand); + Assert.Same(fixture.BoolCommand, fixture.Designer.DesignerSettingItemModels[0].DesignerBoolValueToggledCommand); + var group = Assert.Single(fixture.Designer.DesignerExclusiveSettingItemModels); + Assert.Same(fixture.SelectCommand, group.DesignerSelectedGuidChangedCommand); + Assert.Null(group.Items[0].DesignerTextValueChangedCommand); + } + + [Fact] + public void LoadReadsEditorAgainAfterModelCollectionNotifications() + { + var fixture = new DesignerFixture(); + fixture.Backend.AfterLoad = () => fixture.EditorText = "--changed=3"; + + fixture.Designer.OnEditorViewChanged(false, true); + + Assert.Contains("parse:--changed=3", fixture.Trace); + } + + [Fact] + public void ALoadedDesignerIsReusedUntilTheEditorMarksItDirty() + { + var fixture = Loaded(); + var collection = fixture.Designer.DesignerSettingItemModels; + fixture.Trace.Clear(); + + fixture.Designer.OnEditorViewChanged(false, true); + Assert.Empty(fixture.Trace); + fixture.Designer.MarkDirty(); + fixture.Designer.OnEditorViewChanged(false, true); + + Assert.Same(collection, fixture.Designer.DesignerSettingItemModels); + Assert.Contains("load:supported", fixture.Trace); + } + + [Fact] + public void MissingAnnotationReportsAndRetriesOnTheNextEntry() + { + var fixture = new DesignerFixture(); + fixture.Backend.LoadSucceeds = false; + + fixture.Designer.OnEditorViewChanged(false, true); + + Assert.Equal(ConfigMakerDesignerNotice.MissingAnnotation, Assert.Single(fixture.Notices).Kind); + Assert.Empty(fixture.Designer.DesignerSettingItemModels); + Assert.DoesNotContain(fixture.Trace, item => item.StartsWith("parse:", StringComparison.Ordinal)); + fixture.Backend.LoadSucceeds = true; + fixture.Designer.OnEditorViewChanged(false, true); + Assert.Single(fixture.Designer.DesignerSettingItemModels); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void LoadOrParseFailureClearsModelsAndReleasesTheUpdateGuard(bool parseFailure) + { + var fixture = new DesignerFixture(); + var failure = new IOException("load failed"); + if (parseFailure) fixture.Backend.ParseError = failure; + else fixture.Backend.LoadError = failure; + + fixture.Designer.OnEditorViewChanged(false, true); + + Assert.Empty(fixture.Designer.DesignerSettingItemModels); + Assert.Empty(fixture.Designer.DesignerExclusiveSettingItemModels); + var notice = Assert.Single(fixture.Notices); + Assert.Equal(ConfigMakerDesignerNotice.LoadFailed, notice.Kind); + Assert.Same(failure, notice.Error); + fixture.Backend.LoadError = null; + fixture.Backend.ParseError = null; + fixture.Designer.OnEditorViewChanged(false, true); + Assert.Single(fixture.Designer.DesignerSettingItemModels); + } + + [Theory] + [InlineData("ordinary")] + [InlineData("child")] + public void TextChangesFindOrdinaryAndExclusiveItemsAndApplyToEditor(string id) + { + var fixture = Loaded(); + + fixture.Designer.HandleDesignerTextValueChanged(Tuple.Create(id, "new-value")); + + var item = id == "ordinary" ? fixture.Designer.DesignerSettingItemModels[0] + : fixture.Designer.DesignerExclusiveSettingItemModels[0].Items[0]; + Assert.Equal("new-value", item.Value); + Assert.Equal($"--first=1{Environment.NewLine}--second=2", Assert.Single(fixture.EditedTexts)); + } + + [Fact] + public void BoolAndExclusiveSelectionChangesRetainCaseSensitiveIdentifiers() + { + var fixture = Loaded(); + + fixture.Designer.HandleDesignerBoolValueToggled(Tuple.Create("ordinary", true)); + fixture.Designer.HandleDesignerSelectedGuidChanged(Tuple.Create("group", "child")); + fixture.Designer.HandleDesignerTextValueChanged(Tuple.Create("ORDINARY", "ignored")); + fixture.Designer.HandleDesignerSelectedGuidChanged(Tuple.Create("GROUP", "ignored")); + + Assert.True(fixture.Designer.DesignerSettingItemModels[0].IsChecked); + Assert.Equal("child", fixture.Designer.DesignerExclusiveSettingItemModels[0].SelectedItemGuid); + Assert.Equal(2, fixture.EditedTexts.Count); + } + + [Fact] + public void AdditionalTextDoesNotNotifyBackToTheTextboxAndUsesTheNewValue() + { + var fixture = Loaded(); + int changes = 0; + fixture.Designer.PropertyChanged += (_, args) => { if (args.PropertyName == "AdditionalDesignerArguments") changes++; }; + + fixture.Designer.OnAdditionalDesignerArgumentsChanged("--new=3"); + + Assert.Equal(0, changes); + Assert.Equal("--new=3", fixture.Designer.AdditionalDesignerArguments); + Assert.Contains("build:--new=3", fixture.Trace); + } + + [Fact] + public void ApplyingClearsDirtyAfterTheHostReplacesEditorText() + { + var fixture = Loaded(); + fixture.Designer.OnAdditionalDesignerArgumentsChanged("--new=3"); + fixture.Trace.Clear(); + + fixture.Designer.OnEditorViewChanged(false, true); + + Assert.Empty(fixture.Trace); + } + + [Fact] + public void ReentrantTextboxChangeDuringEditorReplacementDoesNotApplyTwice() + { + var fixture = Loaded(); + fixture.AfterEditorSet = () => fixture.Designer.OnAdditionalDesignerArgumentsChanged("--inner=4"); + + fixture.Designer.OnAdditionalDesignerArgumentsChanged("--outer=3"); + + Assert.Single(fixture.EditedTexts); + Assert.Equal("--inner=4", fixture.Designer.AdditionalDesignerArguments); + Assert.Single(fixture.Trace, item => item.StartsWith("build:", StringComparison.Ordinal)); + } + + [Fact] + public void BuildFailurePropagatesAndDoesNotLeaveTheUpdateGuardSet() + { + var fixture = Loaded(); + fixture.Backend.BuildError = new IOException("build failed"); + + Assert.Throws(() => fixture.Designer.OnAdditionalDesignerArgumentsChanged("extra")); + Assert.Empty(fixture.Notices); + fixture.Backend.BuildError = null; + fixture.Designer.OnAdditionalDesignerArgumentsChanged("extra"); + Assert.Single(fixture.EditedTexts); + } + + [Fact] + public void LeavingTheLoadedDesignerAppliesItsFormattedCommand() + { + var fixture = Loaded(); + + fixture.Designer.OnEditorViewChanged(true, false); + + Assert.Equal($"--first=1{Environment.NewLine}--second=2", Assert.Single(fixture.EditedTexts)); + Assert.Contains("build:--extra=2", fixture.Trace); + } + + [Fact] + public void DirtyOrUnsupportedDesignerDoesNotOverwriteEditorText() + { + var fixture = new DesignerFixture(); + fixture.Designer.OnEditorViewChanged(true, false); + Assert.Empty(fixture.Trace); + fixture.ComponentId = "unsupported"; + fixture.Designer.OnEditorViewChanged(false, true); + fixture.Designer.OnAdditionalDesignerArgumentsChanged("extra"); + + Assert.Empty(fixture.EditedTexts); + Assert.Empty(fixture.Trace); + } + + [Fact] + public void AvailabilityNotifiesBeforeClearingAndRechecksTheCurrentComponent() + { + var fixture = Loaded(); + int countAtNotification = -1; + fixture.Designer.PropertyChanged += (_, args) => + { + if (args.PropertyName != "IsSimpleDesignerSupported") return; + countAtNotification = fixture.Designer.DesignerSettingItemModels.Count; + fixture.ComponentId = "unsupported"; + }; + + fixture.Designer.UpdateAvailability(); + + Assert.Equal(1, countAtNotification); + Assert.Empty(fixture.Designer.DesignerSettingItemModels); + Assert.Empty(fixture.Designer.DesignerExclusiveSettingItemModels); + } + + private static DesignerFixture Loaded() + { + var fixture = new DesignerFixture(); + fixture.Designer.OnEditorViewChanged(false, true); + fixture.Trace.Clear(); + return fixture; + } + + private sealed class DesignerFixture + { + public DesignerFixture() + { + Backend = new(Trace); + Designer = new(Backend, () => ComponentId, + () => { Trace.Add("read:" + EditorText); return EditorText; }, + text => { EditedTexts.Add(text); Designer.MarkDirty(); AfterEditorSet?.Invoke(); }, + new(TextCommand, BoolCommand, SelectCommand), + (kind, error) => Notices.Add((kind, error))); + } + public string ComponentId { get; set; } = "supported"; + public string EditorText { get; set; } = "--known=1 --extra=2"; + public Action? AfterEditorSet { get; set; } + public List Trace { get; } = []; + public List EditedTexts { get; } = []; + public List<(ConfigMakerDesignerNotice Kind, Exception? Error)> Notices { get; } = []; + public ICommand TextCommand { get; } = new DummyCommand(); + public ICommand BoolCommand { get; } = new DummyCommand(); + public ICommand SelectCommand { get; } = new DummyCommand(); + public DesignerBackend Backend { get; } + public ConfigMakerSimpleDesigner Designer { get; } + } + + private sealed class DesignerBackend(List trace) : IConfigMakerSimpleDesignerBackend + { + public int SupportChecks { get; private set; } + public bool LoadSucceeds { get; set; } = true; + public Exception? LoadError { get; set; } + public Exception? ParseError { get; set; } + public Exception? BuildError { get; set; } + public Action? AfterLoad { get; set; } + public bool IsSupported(string component) { SupportChecks++; return component == "supported"; } + public bool TryLoad(string component, ObservableCollection items, ObservableCollection groups) + { + trace.Add("load:" + component); + if (LoadError != null) throw LoadError; + if (!LoadSucceeds) return false; + items.Add(new() { Guid = "ordinary", DisplayName = "--known", Type = "string" }); + groups.Add(new() { Guid = "group", Items = [new() { Guid = "child", DisplayName = "--child", Type = "string" }] }); + AfterLoad?.Invoke(); + return true; + } + public string Parse(ObservableCollection items, ObservableCollection groups, string command) + { + trace.Add("parse:" + command); + if (ParseError != null) throw ParseError; + return "--extra=2"; + } + public string Build(ObservableCollection items, ObservableCollection groups, string additional) + { + trace.Add("build:" + additional); + if (BuildError != null) throw BuildError; + return " --first=1 --second=2 "; + } + } + + private sealed class DummyCommand : ICommand + { + public event EventHandler? CanExecuteChanged { add { } remove { } } + public bool CanExecute(object? parameter) => true; + public void Execute(object? parameter) { } + } +} diff --git a/CDPIUI.Tests/Presentation/ConfigMakerTestSessionTests.cs b/CDPIUI.Tests/Presentation/ConfigMakerTestSessionTests.cs new file mode 100644 index 00000000..9ba3f847 --- /dev/null +++ b/CDPIUI.Tests/Presentation/ConfigMakerTestSessionTests.cs @@ -0,0 +1,245 @@ +using CDPIUI.Helper.CreateConfigHelper; + +namespace CDPIUI.Tests.Presentation; + +public class ConfigMakerTestSessionTests +{ + [Fact] + public async Task StartPublishesStateBeforeCheckingInstallationAndRunningTheTest() + { + var fixture = new SessionFixture(); + + await fixture.Session.StartAsync("--test"); + + Assert.True(fixture.Session.IsTesting); + Assert.Equal("component", fixture.Session.TestComponentId); + Assert.Equal(["running:component", "stop:component", "state:True", "installed:component", "notice:Started", + "run:component:--test", "refresh"], fixture.Trace); + } + + [Fact] + public async Task DecliningReplacementKeepsTheExistingComponentUntouched() + { + var fixture = new SessionFixture { ConfirmResult = false }; + fixture.Tasks.WasRunning = true; + + await fixture.Session.StartAsync("--test"); + + Assert.False(fixture.Session.IsTesting); + Assert.Equal(["running:component", "confirm"], fixture.Trace); + Assert.Equal(0, fixture.Tasks.SubscriberCount); + } + + [Fact] + public async Task StopRestoresThePreviousConfigurationWithoutTestArguments() + { + var fixture = new SessionFixture(); + fixture.Tasks.WasRunning = true; + await fixture.Session.StartAsync("--test"); + fixture.Trace.Clear(); + fixture.ComponentId = "different-selection"; + + await fixture.Session.StopAsync(showCompletionMessage: true); + + Assert.False(fixture.Session.IsTesting); + Assert.Empty(fixture.Session.TestComponentId); + Assert.Equal(["state:False", "stop:component", "restore:component", "notice:Stopped"], fixture.Trace); + Assert.Equal(0, fixture.Tasks.SubscriberCount); + } + + [Fact] + public async Task MissingInstallationClearsTheTestStateWithoutLaunching() + { + var fixture = new SessionFixture { IsInstalled = false }; + + await fixture.Session.StartAsync("--test"); + + Assert.False(fixture.Session.IsTesting); + Assert.Equal(["running:component", "stop:component", "state:True", "installed:component", "notice:NotInstalled", + "state:False", "stop:component"], fixture.Trace); + Assert.Equal(0, fixture.Tasks.SubscriberCount); + } + + [Fact] + public async Task FailedTestLaunchShowsTheErrorAndRestoresThePreviousRun() + { + var fixture = new SessionFixture(); + fixture.Tasks.WasRunning = true; + fixture.Tasks.Run = (_, _) => Task.FromException(new IOException("launch failed")); + + await fixture.Session.StartAsync("--test"); + + Assert.False(fixture.Session.IsTesting); + Assert.Equal((ConfigMakerTestNotice.StartFailed, "launch failed"), fixture.Notices.Single(notice => notice.Kind == ConfigMakerTestNotice.StartFailed)); + Assert.Equal("restore:component", fixture.Trace[^1]); + Assert.Equal(0, fixture.Tasks.SubscriberCount); + } + + [Fact] + public async Task OutputRefreshFailureUsesTheExistingLaunchFailureBoundary() + { + var fixture = new SessionFixture { Refresh = () => Task.FromException(new IOException("refresh failed")) }; + + await fixture.Session.StartAsync("--test"); + + Assert.False(fixture.Session.IsTesting); + Assert.Contains((ConfigMakerTestNotice.StartFailed, "refresh failed"), fixture.Notices); + Assert.Equal("stop:component", fixture.Trace[^1]); + } + + [Fact] + public async Task StateChangesDuringStartupAreIgnoredUntilRunCompletes() + { + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var fixture = new SessionFixture(); + fixture.Tasks.Run = (_, _) => completion.Task; + Task starting = fixture.Session.StartAsync("--test"); + + fixture.Tasks.Emit("component", isRunning: false); + Assert.Empty(fixture.Queued); + completion.SetResult(); + await starting; + fixture.Tasks.Emit("component", isRunning: false); + Assert.Single(fixture.Queued); + } + + [Theory] + [InlineData("COMPONENT", false, 1)] + [InlineData("other", false, 0)] + [InlineData("component", true, 0)] + public async Task OnlyAnExitOfTheMatchingComponentQueuesCompletion(string component, bool running, int expected) + { + var fixture = new SessionFixture(); + await fixture.Session.StartAsync("--test"); + + fixture.Tasks.Emit(component, running); + + Assert.Equal(expected, fixture.Queued.Count); + Assert.True(fixture.Session.IsTesting); + } + + [Fact] + public async Task QueuedExitReportsBeforeStoppingAndRestoring() + { + var fixture = new SessionFixture(); + fixture.Tasks.WasRunning = true; + await fixture.Session.StartAsync("--test"); + fixture.Trace.Clear(); + fixture.Tasks.Emit("component", false); + + await Assert.Single(fixture.Queued)(); + + Assert.Equal(["notice:Exited", "state:False", "stop:component", "restore:component"], fixture.Trace); + } + + [Fact] + public async Task StoppingAnIdleSessionDoesNotReportOrCallTheManager() + { + var fixture = new SessionFixture(); + + await fixture.Session.StopAsync(showCompletionMessage: true); + + Assert.Empty(fixture.Trace); + } + + [Fact] + public async Task RepeatedStopDoesNotRestoreOrReportTwice() + { + var fixture = new SessionFixture(); + fixture.Tasks.WasRunning = true; + await fixture.Session.StartAsync("--test"); + await fixture.Session.StopAsync(showCompletionMessage: true); + fixture.Trace.Clear(); + + await fixture.Session.StopAsync(showCompletionMessage: true); + fixture.Tasks.Emit("component", false); + + Assert.Empty(fixture.Trace); + Assert.Empty(fixture.Queued); + } + + [Fact] + public async Task SelectedComponentIsReadAgainAfterTheInitialStopAwaits() + { + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var fixture = new SessionFixture(); + fixture.Tasks.Stop = _ => completion.Task; + Task starting = fixture.Session.StartAsync("--resolved-earlier"); + + fixture.ComponentId = "after-await"; + completion.SetResult(); + await starting; + + Assert.Contains("stop:component", fixture.Trace); + Assert.Contains("run:after-await:--resolved-earlier", fixture.Trace); + Assert.Equal("after-await", fixture.Session.TestComponentId); + } + + [Fact] + public async Task StopFailurePropagatesAfterStateAndSubscriptionAreReleased() + { + var fixture = new SessionFixture(); + await fixture.Session.StartAsync("--test"); + fixture.Tasks.Stop = _ => Task.FromException(new IOException("stop failed")); + + await Assert.ThrowsAsync(() => fixture.Session.StopAsync()); + + Assert.False(fixture.Session.IsTesting); + Assert.Equal(0, fixture.Tasks.SubscriberCount); + Assert.Equal("component", fixture.Session.TestComponentId); + Assert.DoesNotContain(fixture.Notices, notice => notice.Kind == ConfigMakerTestNotice.StartFailed); + } + + [Fact] + public async Task ConfirmationFailureRemainsOutsideTheLaunchErrorBoundary() + { + var fixture = new SessionFixture { Confirm = () => Task.FromException(new IOException("confirm failed")) }; + fixture.Tasks.WasRunning = true; + + await Assert.ThrowsAsync(() => fixture.Session.StartAsync("--test")); + + Assert.False(fixture.Session.IsTesting); + Assert.Empty(fixture.Notices); + Assert.DoesNotContain(fixture.Trace, item => item.StartsWith("stop:", StringComparison.Ordinal)); + } + + private sealed class SessionFixture + { + public SessionFixture() + { + Tasks = new(Trace); + Session = new(Tasks, () => ComponentId, + () => { Trace.Add("confirm"); return Confirm?.Invoke() ?? Task.FromResult(ConfirmResult); }, + id => { Trace.Add("installed:" + id); return IsInstalled; }, + (kind, details) => { Trace.Add("notice:" + kind); Notices.Add((kind, details)); }, + () => { Trace.Add("refresh"); return Refresh?.Invoke() ?? Task.CompletedTask; }, + action => Queued.Add(action)); + Session.StateChanged += (_, _) => Trace.Add("state:" + Session.IsTesting); + } + + public string ComponentId { get; set; } = "component"; + public bool ConfirmResult { get; init; } = true; + public bool IsInstalled { get; init; } = true; + public Func>? Confirm { get; init; } + public Func? Refresh { get; init; } + public List Trace { get; } = []; + public List<(ConfigMakerTestNotice Kind, string? Details)> Notices { get; } = []; + public List> Queued { get; } = []; + public TestTasks Tasks { get; } + public ConfigMakerTestSession Session { get; } + } + + private sealed class TestTasks(List trace) : IConfigMakerTestTasks + { + public event Action>? StateUpdated; + public int SubscriberCount => StateUpdated?.GetInvocationList().Length ?? 0; + public bool WasRunning { get; set; } + public Func? Stop { get; set; } + public Func? Run { get; set; } + public Task IsRunningAsync(string id) { trace.Add("running:" + id); return Task.FromResult(WasRunning); } + public Task StopAsync(string id) { trace.Add("stop:" + id); return Stop?.Invoke(id) ?? Task.CompletedTask; } + public Task RunAsync(string id, string args) { trace.Add("run:" + id + ":" + args); return Run?.Invoke(id, args) ?? Task.CompletedTask; } + public Task RestoreAsync(string id) { trace.Add("restore:" + id); return Task.CompletedTask; } + public void Emit(string id, bool isRunning) => StateUpdated?.Invoke(Tuple.Create(id, isRunning)); + } +} diff --git a/CDPIUI.Tests/Presentation/ConfigMakerVariableActionsTests.cs b/CDPIUI.Tests/Presentation/ConfigMakerVariableActionsTests.cs new file mode 100644 index 00000000..c0d8d3ed --- /dev/null +++ b/CDPIUI.Tests/Presentation/ConfigMakerVariableActionsTests.cs @@ -0,0 +1,353 @@ +using System.Collections.Specialized; +using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.ViewModels; +using CDPIUI.ViewModels.ConfigMaker; + +namespace CDPIUI.Tests.Presentation; + +public sealed class ConfigMakerVariableActionsTests +{ + [Fact] + public void ConstructorOnlyStoresDocumentAndHost() + { + var f = new Fixture(); + Assert.Empty(f.Trace); + Assert.Empty(f.Host.Edits); + Assert.Empty(f.Document.Variables); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task NullEditAndRemoveDoNothing(bool edit) + { + var f = new Fixture(); + if (edit) await f.Actions.EditVariableAsync(null); else await f.Actions.RemoveVariableAsync(null); + Assert.Empty(f.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task CanceledDialogDoesNotChangeDocumentOrRefresh(bool create) + { + var f = new Fixture(); var old = f.Add("Old"); + f.Host.Edit = (_, _) => Task.FromResult(null); + if (create) await f.Actions.CreateVariableAsync(); else await f.Actions.EditVariableAsync(old); + Assert.Same(old, Assert.Single(f.Document.Variables)); + Assert.Equal(new[] { create ? "edit:" : "edit:Old" }, f.Trace); + } + + [Fact] + public async Task CreateWaitsThenAddsExactVariableBeforeAttachShowRebuildAndDiagnostics() + { + var f = new Fixture(); var pending = Pending(); var value = Variable("Added"); + f.Host.Edit = (_, _) => pending.Task; + var task = f.Actions.CreateVariableAsync(); + Assert.False(task.IsCompleted); + Assert.Empty(f.Document.Variables); + var call = Assert.Single(f.Host.Edits); + Assert.Same(f.Document, call.Document); Assert.Null(call.Variable); + pending.SetResult(new(value, "ignored")); + await task; + Assert.Same(value, Assert.Single(f.Document.Variables)); + Assert.Equal(new[] { "edit:", "content", "variables:Add", "attach", "show", "rebuild", "diagnostics" }, f.Trace); + } + + [Fact] + public async Task CreateUsesCurrentCollectionAfterDialogAndDoesNotCloneOrValidateResult() + { + var f = new Fixture(); f.Add("Old"); var pending = Pending(); + f.Host.Edit = (_, _) => pending.Task; + var task = f.Actions.CreateVariableAsync(); + f.Document.Variables.Clear(); + var duplicate = Variable("not-valid-name"); f.Document.Variables.Add(duplicate); + f.Trace.Clear(); + pending.SetResult(new(duplicate, "")); + await task; + Assert.Equal(2, f.Document.Variables.Count); + Assert.All(f.Document.Variables, value => Assert.Same(duplicate, value)); + Assert.Equal(new[] { "content", "variables:Add", "attach", "show", "rebuild", "diagnostics" }, f.Trace); + } + + [Theory] + [InlineData("Same", "Same", false)] + [InlineData("Same", "same", true)] + [InlineData("Different", "New", true)] + public async Task EditRenamesByResultOriginalNameOrdinalAndPreservesEventOrder(string original, string next, bool rename) + { + var f = new Fixture(); var old = f.Add("Same"); + f.Document.CommandText = "%Same% %Different%"; f.Trace.Clear(); + var value = Variable(next); + f.Host.Edit = (_, _) => Task.FromResult(new(value, original)); + await f.Actions.EditVariableAsync(old); + Assert.Same(f.Document, Assert.Single(f.Host.Edits).Document); + Assert.Same(old, f.Host.Edits[0].Variable); + Assert.Same(value, Assert.Single(f.Document.Variables)); + string expectedText = original == "Different" ? "%Same% %New%" : rename ? "%same% %Different%" : "%Same% %Different%"; + Assert.Equal(expectedText, f.Document.CommandText); + Assert.Equal(rename + ? new[] { "edit:Same", "content", "set:" + expectedText, "content", "variables:Replace", "attach", "rebuild", "diagnostics" } + : new[] { "edit:Same", "content", "variables:Replace", "attach", "rebuild", "diagnostics" }, f.Trace); + } + + [Fact] + public async Task EditFindsTheOriginalObjectAtItsCurrentIndexAfterAwait() + { + var f = new Fixture(); var old = f.Add("Old"); var other = f.Add("Other"); + var pending = Pending(); f.Host.Edit = (_, _) => pending.Task; + var task = f.Actions.EditVariableAsync(old); + f.Document.Variables.Move(0, 1); f.Trace.Clear(); + var value = Variable("Old"); pending.SetResult(new(value, "Old")); await task; + Assert.Equal(new[] { other, value }, f.Document.Variables); + Assert.Equal(new[] { "content", "variables:Replace", "attach", "rebuild", "diagnostics" }, f.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task EditStillAsksForMissingObjectButDoesNotReplaceAnEqualIdClone(bool removeWhilePending) + { + var f = new Fixture(); var old = Variable("Old"); var clone = old.Clone(); + f.Document.Variables.Add(removeWhilePending ? old : clone); f.Trace.Clear(); + var pending = Pending(); f.Host.Edit = (_, _) => pending.Task; + var task = f.Actions.EditVariableAsync(old); + Assert.Single(f.Host.Edits); + if (removeWhilePending) { f.Document.Variables.Clear(); f.Document.Variables.Add(clone); } + f.Trace.Clear(); pending.SetResult(new(Variable("New"), "Old")); await task; + Assert.Same(clone, Assert.Single(f.Document.Variables)); + Assert.Empty(f.Trace); + } + + [Fact] + public async Task EditorReceivesCurrentCommandAfterReferenceReplacementEvents() + { + var f = new Fixture(); var old = f.Add("Old"); f.Document.CommandText = "%Old%"; f.Trace.Clear(); + bool entered = false; + f.Document.ContentChanged += (_, _) => + { + if (entered || f.Document.CommandText != "%New%") return; + entered = true; f.Document.CommandText = "--changed-by-observer"; + }; + f.Host.Edit = (_, _) => Task.FromResult(new(Variable("New"), "Old")); + await f.Actions.EditVariableAsync(old); + Assert.Contains("set:--changed-by-observer", f.Trace); + Assert.DoesNotContain("set:%New%", f.Trace); + } + + [Fact] + public async Task EditKeepsIndexComputedBeforeReferenceEventsEvenWhenObserverMovesTheOriginal() + { + var f = new Fixture(); var old = f.Add("Old"); f.Add("Other"); + f.Document.CommandText = "%Old%"; f.Trace.Clear(); + bool entered = false; + f.Document.ContentChanged += (_, _) => + { + if (entered || f.Document.CommandText != "%New%") return; + entered = true; f.Document.Variables.Move(0, 1); + }; + var value = Variable("New"); + f.Host.Edit = (_, _) => Task.FromResult(new(value, "Old")); + await f.Actions.EditVariableAsync(old); + Assert.Equal(new[] { value, old }, f.Document.Variables); + Assert.Equal("%New%", f.Document.CommandText); + } + + [Fact] + public async Task ObserverClearingAfterIndexLookupRetainsRenamedTextAndEditorBeforeIndexFailure() + { + var f = new Fixture(); var old = f.Add("Old"); f.Document.CommandText = "%Old%"; f.Trace.Clear(); + bool entered = false; + f.Document.ContentChanged += (_, _) => + { + if (entered || f.Document.CommandText != "%New%") return; + entered = true; f.Document.Variables.Clear(); + }; + f.Host.Edit = (_, _) => Task.FromResult(new(Variable("New"), "Old")); + await Assert.ThrowsAsync(() => f.Actions.EditVariableAsync(old)); + Assert.Empty(f.Document.Variables); + Assert.Equal("%New%", f.Document.CommandText); + Assert.Contains("set:%New%", f.Trace); + Assert.DoesNotContain("attach", f.Trace); + } + + [Theory] + [InlineData("%NAME%", true)] + [InlineData("prefix %Name% suffix", true)] + [InlineData("%Names%", false)] + [InlineData("", false)] + public async Task RemoveReadsHostCommandAndUsesOrdinalIgnoreCaseReference(string command, bool referenced) + { + var f = new Fixture(); var value = f.Add("Name"); + f.Document.CommandText = "--document-different"; f.Host.Text = command; f.Trace.Clear(); + await f.Actions.RemoveVariableAsync(value); + Assert.Empty(f.Document.Variables); + Assert.Equal("--document-different", f.Document.CommandText); + Assert.Equal(referenced + ? new[] { "command", "confirm", "content", "variables:Remove", "rebuild", "diagnostics" } + : new[] { "command", "content", "variables:Remove", "rebuild", "diagnostics" }, f.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ReferencedRemovalWaitsForConfirmationAndUsesOriginalObjectAfterAwait(bool accept) + { + var f = new Fixture(); var value = f.Add("Name"); f.Host.Text = "%Name%"; + var confirm = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Host.Confirm = () => confirm.Task; + var task = f.Actions.RemoveVariableAsync(value); + Assert.False(task.IsCompleted); + Assert.Same(value, Assert.Single(f.Document.Variables)); + value.Name = "Changed"; f.Host.Text = ""; f.Trace.Clear(); + confirm.SetResult(accept); await task; + if (accept) + { + Assert.Empty(f.Document.Variables); + Assert.Equal(new[] { "content", "variables:Remove", "rebuild", "diagnostics" }, f.Trace); + } + else { Assert.Same(value, Assert.Single(f.Document.Variables)); Assert.Empty(f.Trace); } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task MissingRemovalStillRebuildsAndDoesNotRemoveAnEqualIdClone(bool referenced) + { + var f = new Fixture(); var value = Variable("Name"); var clone = value.Clone(); + f.Document.Variables.Add(clone); f.Host.Text = referenced ? "%Name%" : ""; f.Trace.Clear(); + await f.Actions.RemoveVariableAsync(value); + Assert.Same(clone, Assert.Single(f.Document.Variables)); + Assert.Equal(referenced ? new[] { "command", "confirm", "rebuild", "diagnostics" } : new[] { "command", "rebuild", "diagnostics" }, f.Trace); + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void InsertReadsReadOnlyBeforeNullGuardAndOnlyThenInsertsCurrentReference(bool readOnly, bool nullVariable) + { + var f = new Fixture(); f.Host.ReadOnly = readOnly; + f.Actions.InsertVariableReference(nullVariable ? null : Variable("Name")); + Assert.Equal(!readOnly && !nullVariable ? new[] { "readonly", "insert:%Name%" } : new[] { "readonly" }, f.Trace); + } + + [Fact] + public void ReadOnlyGetterCanChangeVariableBeforeReferenceIsReadAndItsFailureIsSynchronous() + { + var f = new Fixture(); var value = Variable("Before"); + f.Host.BeforeReadOnly = () => value.Name = "After"; + f.Actions.InsertVariableReference(value); + Assert.Equal(new[] { "readonly", "insert:%After%" }, f.Trace); + var failure = new IOException("read-only"); + f.Host.BeforeReadOnly = () => throw failure; + Assert.Same(failure, Assert.Throws(() => f.Actions.InsertVariableReference(null))); + } + + [Theory] + [InlineData("create")] + [InlineData("edit")] + [InlineData("remove")] + public async Task PortCancellationPropagatesAsCanceledTaskWithoutMutation(string operation) + { + var f = new Fixture(); var value = f.Add("Old"); f.Host.Text = "%Old%"; + using var cts = new CancellationTokenSource(); cts.Cancel(); + f.Host.Edit = (_, _) => Task.FromCanceled(cts.Token); + f.Host.Confirm = () => Task.FromCanceled(cts.Token); + var task = operation switch + { + "create" => f.Actions.CreateVariableAsync(), "edit" => f.Actions.EditVariableAsync(value), _ => f.Actions.RemoveVariableAsync(value), + }; + await Assert.ThrowsAnyAsync(() => task); + Assert.True(task.IsCanceled); + Assert.Same(value, Assert.Single(f.Document.Variables)); + Assert.DoesNotContain("rebuild", f.Trace); + } + + [Theory] + [InlineData("attach")] + [InlineData("show")] + [InlineData("rebuild")] + [InlineData("diagnostics")] + [InlineData("content")] + public async Task CreateFailuresRetainAddedVariableAndStopAtExactCallback(string point) + { + var f = new Fixture(); var value = Variable("New"); var failure = new IOException(point); + f.Host.Edit = (_, _) => Task.FromResult(new(value, "")); + f.Host.FailurePoint = point; f.Host.Failure = failure; + if (point == "content") f.Document.ContentChanged += (_, _) => throw failure; + Assert.Same(failure, await Assert.ThrowsAsync(() => f.Actions.CreateVariableAsync())); + Assert.Same(value, Assert.Single(f.Document.Variables)); + if (point is "content" or "attach") Assert.DoesNotContain("show", f.Trace); + if (point is "content" or "attach" or "show") Assert.DoesNotContain("rebuild", f.Trace); + if (point != "diagnostics") Assert.DoesNotContain("diagnostics", f.Trace); + } + + [Fact] + public async Task EditAndRemoveFailuresKeepTheirOriginalPartialMutations() + { + var f = new Fixture(); var old = f.Add("Old"); f.Document.CommandText = "%Old%"; f.Trace.Clear(); + var failure = new IOException("editor"); + f.Host.FailurePoint = "set"; f.Host.Failure = failure; + f.Host.Edit = (_, _) => Task.FromResult(new(Variable("New"), "Old")); + Assert.Same(failure, await Assert.ThrowsAsync(() => f.Actions.EditVariableAsync(old))); + Assert.Same(old, Assert.Single(f.Document.Variables)); + Assert.Equal("%New%", f.Document.CommandText); + Assert.DoesNotContain("attach", f.Trace); + f.Trace.Clear(); f.Host.FailurePoint = "rebuild"; + Assert.Same(failure, await Assert.ThrowsAsync(() => f.Actions.RemoveVariableAsync(old))); + Assert.Empty(f.Document.Variables); + Assert.DoesNotContain("diagnostics", f.Trace); + } + + private static ConfigMakerVariableDefinition Variable(string name) => new() { Name = name, Value = "fixture" }; + private static TaskCompletionSource Pending() => new(TaskCreationOptions.RunContinuationsAsynchronously); + private sealed class Fixture + { + public List Trace { get; } = []; + public ConfigMakerPresetDocument Document { get; } = new(); + public Host Host { get; } + public ConfigMakerVariableActions Actions { get; } + public Fixture() + { + Host = new(Trace); Actions = new(Document, Host); + Document.ContentChanged += (_, _) => Trace.Add("content"); + Document.Variables.CollectionChanged += (_, args) => Trace.Add("variables:" + args.Action); + } + public ConfigMakerVariableDefinition Add(string name) + { + var value = Variable(name); Document.Variables.Add(value); Trace.Clear(); return value; + } + } + private sealed record EditCall(ConfigMakerPresetDocument Document, ConfigMakerVariableDefinition? Variable); + private sealed class Host(List trace) : IConfigMakerVariableActionsHost + { + public List Edits { get; } = []; + public Func> Edit = (_, _) => Task.FromResult(null); + public Func> Confirm = () => Task.FromResult(true); + public string Text = ""; + public bool ReadOnly; + public Action? BeforeReadOnly; + public string? FailurePoint; + public Exception? Failure; + private void Call(string point, string? detail = null) + { + trace.Add(detail == null ? point : point + ":" + detail); + if (FailurePoint == point) throw Failure!; + } + public string CommandText { get { Call("command"); return Text; } } + public bool IsEditorReadOnly { get { Call("readonly"); BeforeReadOnly?.Invoke(); return ReadOnly; } } + public Task EditVariableAsync(ConfigMakerPresetDocument document, ConfigMakerVariableDefinition? variable) + { + Call("edit", variable?.Name ?? ""); Edits.Add(new(document, variable)); return Edit(document, variable); + } + public Task ConfirmRemoveReferencedVariableAsync() { Call("confirm"); return Confirm(); } + public void SetEditorText(string text) => Call("set", text); + public void InsertAtCursor(string reference) => Call("insert", reference); + public void AttachExistingPresetFiles() => Call("attach"); + public void ShowVariablesTool() => Call("show"); + public void RebuildPresetStructure() => Call("rebuild"); + public void ScheduleDiagnostics() => Call("diagnostics"); + } +} diff --git a/CDPIUI.Tests/Presentation/CreateConfigComponentSelectionTests.cs b/CDPIUI.Tests/Presentation/CreateConfigComponentSelectionTests.cs new file mode 100644 index 00000000..fa9e96e6 --- /dev/null +++ b/CDPIUI.Tests/Presentation/CreateConfigComponentSelectionTests.cs @@ -0,0 +1,318 @@ +using CDPIUI.ViewModels.CreateConfig; + +namespace CDPIUI.Tests.Presentation; + +public sealed class CreateConfigComponentSelectionTests +{ + private static ConfigComponentOption Option(string? id = "supported") => new() { Id = id!, Name = "Option" }; + + [Fact] + public void ConstructorOnlyStoresCallbacksAndPreservesInitialFields() + { + var f = new Fixture(); + Assert.Null(f.State.SelectedComponent); Assert.Empty(f.State.DisplayName); + Assert.False(f.State.IsAdditionalSettingsVisible); + Assert.True(f.State.IsNotReadyErrorVisible); Assert.True(f.State.IsTabBarVisible); + Assert.Empty(f.Trace); Assert.Empty(f.Events); + } + + [Fact] + public void SupportedSelectionNotifiesBeforeViewEffectsDirtyAndAudit() + { + var f = new Fixture(); + var selected = Option(); + f.State.SelectedComponent = selected; + Assert.Same(selected, f.State.SelectedComponent); + Assert.Equal(SupportedTrace, f.Trace); + Assert.True(f.State.IsAdditionalSettingsVisible); + Assert.False(f.State.IsNotReadyErrorVisible); Assert.True(f.State.IsTabBarVisible); + } + + [Fact] + public void UnsupportedSelectionHandlesDefaultViewBeforeSelectingTextAndHidingTabbar() + { + var f = new Fixture(); + f.State.SelectedComponent = Option("unsupported"); + Assert.Equal(["event:SelectedComponent", "event:IsAdditionalSettingsVisible", "event:IsNotReadyErrorVisible", + "supported:unsupported", "selection:True", "text-tab", "event:IsTabBarVisible", "dirty", "audit"], f.Trace); + Assert.False(f.State.IsTabBarVisible); + } + + [Fact] + public void SupportedTabbarUpdateOccursBetweenTabSelectionAndSelectionHandling() + { + var f = new Fixture(); + f.State.SelectedComponent = Option("unsupported"); f.Trace.Clear(); + f.State.SelectedComponent = Option(); + Assert.Equal(["event:SelectedComponent", "supported:supported", "designer-tab", + "event:IsTabBarVisible", "selection:False", "dirty", "audit"], f.Trace); + } + + [Fact] + public void EqualReferenceSuppressesEverythingButEqualDataInAnotherObjectDoesNot() + { + var f = new Fixture(); + var option = Option(); + f.State.SelectedComponent = option; f.Trace.Clear(); + f.State.SelectedComponent = option; + Assert.Empty(f.Trace); + f.State.SelectedComponent = Option(); + Assert.Equal(["event:SelectedComponent", "supported:supported", "designer-tab", "selection:False", "dirty", "audit"], f.Trace); + } + + [Fact] + public void NullSelectionResetsOnlyAdditionalAndErrorFlagsThenStillMarksDirtyAndAudits() + { + var f = new Fixture(); + f.State.SelectedComponent = Option("unsupported"); f.Trace.Clear(); + f.State.SelectedComponent = null; + Assert.Equal(["event:SelectedComponent", "event:IsAdditionalSettingsVisible", "event:IsNotReadyErrorVisible", "dirty", "audit"], f.Trace); + Assert.False(f.State.IsAdditionalSettingsVisible); Assert.True(f.State.IsNotReadyErrorVisible); + Assert.False(f.State.IsTabBarVisible); + } + + [Fact] + public void EqualInitialNullSelectionDoesNotProduceEffects() + { + var f = new Fixture(); + f.State.SelectedComponent = null; + Assert.Empty(f.Trace); + } + + [Fact] + public void DisplayNameNormalizesNullAndSuppressesEqualAssignments() + { + var f = new Fixture(); + f.State.DisplayName = null!; Assert.Empty(f.Trace); + f.State.DisplayName = "name"; f.State.DisplayName = "name"; f.State.DisplayName = null!; + Assert.Empty(f.State.DisplayName); + Assert.Equal(["event:DisplayName", "dirty", "audit", "event:DisplayName", "dirty", "audit"], f.Trace); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("SUPPORTED")] + public void DesignerPredicateReceivesCurrentNormalizedIdWithoutCaseFolding(string? id) + { + var f = new Fixture(); + f.State.SelectedComponent = Option(id); f.Trace.Clear(); + Assert.False(f.State.IsDesignerSupported); + Assert.Equal(["supported:" + (id ?? "")], f.Trace); + } + + [Fact] + public void SupportQueryOnAbsentComponentStillCallsTheOriginalEmptyIdPredicate() + { + var f = new Fixture(); + Assert.False(f.State.IsDesignerSupported); + Assert.Equal(["supported:"], f.Trace); + } + + [Fact] + public void SupportQueryUsesLivePredicateRatherThanAConstructorSnapshot() + { + var f = new Fixture(); + f.State.SelectedComponent = Option(); + f.Supported.Clear(); + Assert.False(f.State.IsDesignerSupported); + } + + [Fact] + public void SaveCapabilityShortCircuitsBeforeEditorRead() + { + var f = new Fixture(); + f.State.DisplayName = "name"; f.Trace.Clear(); + Assert.False(f.State.IsSaveAvailable); Assert.Empty(f.Trace); + f.State.DisplayName = ""; + f.State.SelectedComponent = Option(); f.Trace.Clear(); + Assert.False(f.State.IsSaveAvailable); Assert.Empty(f.Trace); + } + + [Theory] + [InlineData(null, false)] + [InlineData("", false)] + [InlineData(" ", true)] + [InlineData("--args", true)] + public void SaveCapabilityReadsCurrentEditorAndDoesNotTrim(string? editor, bool expected) + { + var f = new Fixture { Editor = editor }; + f.State.SelectedComponent = Option(); f.State.DisplayName = " "; f.Trace.Clear(); + Assert.Equal(expected, f.State.IsSaveAvailable); + Assert.Equal(["editor"], f.Trace); + } + + [Fact] + public void NullComponentIdStillAllowsSaveWhenTheObjectNameAndTextExist() + { + var f = new Fixture(); + f.State.SelectedComponent = Option(null); f.State.DisplayName = "name"; + Assert.True(f.State.IsSaveAvailable); + } + + [Fact] + public void SaveQueryDoesNotRevalidateEarlierFieldsAfterEditorCallbackReentry() + { + var f = new Fixture(); + f.State.SelectedComponent = Option(); f.State.DisplayName = "name"; + f.ReadEditor = () => { f.State.SelectedComponent = null; f.State.DisplayName = ""; return "text"; }; + Assert.True(f.State.IsSaveAvailable); + Assert.Null(f.State.SelectedComponent); Assert.Empty(f.State.DisplayName); + } + + [Fact] + public void EditorQueryFailurePropagatesWithoutNewMutationOrDirtyEffects() + { + var f = new Fixture(); + var selected = Option(); + f.State.SelectedComponent = selected; f.State.DisplayName = "name"; f.Trace.Clear(); + f.ReadEditor = () => throw new IOException("editor"); + Assert.Throws(() => _ = f.State.IsSaveAvailable); + Assert.Equal(["editor"], f.Trace); Assert.Same(selected, f.State.SelectedComponent); + } + + [Fact] + public void ExplicitCheckViewTypeDoesNotMarkDirtyOrAudit() + { + var f = new Fixture(); + f.State.CheckViewType(); Assert.Empty(f.Trace); + f.State.SelectedComponent = Option(); f.Trace.Clear(); + f.State.CheckViewType(); + Assert.Equal(["supported:supported", "designer-tab", "selection:False"], f.Trace); + } + + [Fact] + public void FlagSettersOnlyNotifyAndSuppressEqualValues() + { + var f = new Fixture(); + f.State.IsTabBarVisible = false; f.State.IsTabBarVisible = false; + f.State.IsAdditionalSettingsVisible = true; f.State.IsNotReadyErrorVisible = false; + Assert.Equal(["event:IsTabBarVisible", "event:IsAdditionalSettingsVisible", "event:IsNotReadyErrorVisible"], f.Trace); + } + + [Fact] + public void SelectedObserverFailureLeavesAssignmentBeforeAnyViewTypeEffects() + { + var f = new Fixture(); + var selected = Option(); + f.Observer = name => { if (name == "SelectedComponent") throw new IOException("selected"); }; + Assert.Throws(() => f.State.SelectedComponent = selected); + Assert.Same(selected, f.State.SelectedComponent); + Assert.False(f.State.IsAdditionalSettingsVisible); Assert.True(f.State.IsNotReadyErrorVisible); + Assert.Equal(["event:SelectedComponent"], f.Trace); + } + + [Fact] + public void FlagObserverFailureLeavesTheOriginalPartialCheckViewTypeState() + { + var f = new Fixture(); + f.Observer = name => { if (name == "IsAdditionalSettingsVisible") throw new IOException("flag"); }; + Assert.Throws(() => f.State.SelectedComponent = Option()); + Assert.True(f.State.IsAdditionalSettingsVisible); Assert.True(f.State.IsNotReadyErrorVisible); + Assert.Equal(["event:SelectedComponent", "event:IsAdditionalSettingsVisible"], f.Trace); + } + + [Theory] + [InlineData("supported:supported")] + [InlineData("designer-tab")] + [InlineData("selection:False")] + [InlineData("dirty")] + [InlineData("audit")] + public void CallbackFailuresPreserveTheExpectedPrefixAndPartialState(string failingStep) + { + var f = new Fixture(); + f.OnStep = step => { if (step == failingStep) throw new IOException(step); }; + Assert.Throws(() => f.State.SelectedComponent = Option()); + Assert.Equal(SupportedTrace.Take(Array.IndexOf(SupportedTrace, failingStep) + 1), f.Trace); + Assert.True(f.State.IsAdditionalSettingsVisible); Assert.False(f.State.IsNotReadyErrorVisible); + Assert.NotNull(f.State.SelectedComponent); + } + + [Fact] + public void DisplayObserverFailureDoesNotReachDirtyOrAudit() + { + var f = new Fixture(); + f.Observer = _ => throw new IOException("display"); + Assert.Throws(() => f.State.DisplayName = "assigned"); + Assert.Equal("assigned", f.State.DisplayName); + Assert.Equal(["event:DisplayName"], f.Trace); + } + + [Fact] + public void DisplayDirtyFailureKeepsAssignedNameAndSkipsAudit() + { + var f = new Fixture(); + f.OnStep = step => { if (step == "dirty") throw new IOException("dirty"); }; + Assert.Throws(() => f.State.DisplayName = "assigned"); + Assert.Equal("assigned", f.State.DisplayName); + Assert.Equal(["event:DisplayName", "dirty"], f.Trace); + } + + [Fact] + public void ReentrantNullSelectionDuringFlagNotifyDoesNotStopOuterContinuation() + { + var f = new Fixture(); + bool entered = false; + f.Observer = name => + { + if (name == "IsAdditionalSettingsVisible" && !entered) + { + entered = true; f.State.SelectedComponent = null; + } + }; + f.State.SelectedComponent = Option(); + Assert.Null(f.State.SelectedComponent); + Assert.False(f.State.IsAdditionalSettingsVisible); + Assert.False(f.State.IsNotReadyErrorVisible); + Assert.False(f.State.IsTabBarVisible); + Assert.Contains("supported:", f.Trace); + Assert.Equal(["dirty", "audit"], f.Trace.TakeLast(2)); + } + + [Fact] + public void ReentrantUnsupportedSelectionDuringDesignerTabKeepsOuterSupportedContinuation() + { + var f = new Fixture(); + bool entered = false; + f.OnStep = step => + { + if (step == "designer-tab" && !entered) + { + entered = true; f.State.SelectedComponent = Option("unsupported"); + } + }; + f.State.SelectedComponent = Option(); + Assert.Equal("unsupported", f.State.SelectedComponent!.Id); + Assert.True(f.State.IsTabBarVisible); + Assert.Equal(["event:IsTabBarVisible", "selection:False", "dirty", "audit"], f.Trace.TakeLast(4)); + } + + private static readonly string[] SupportedTrace = ["event:SelectedComponent", "event:IsAdditionalSettingsVisible", + "event:IsNotReadyErrorVisible", "supported:supported", "designer-tab", "selection:False", "dirty", "audit"]; + + private sealed class Fixture + { + public Fixture() + { + State = new(id => { Step("supported:" + id); return Supported.Contains(id); }, + () => Step("designer-tab"), () => Step("text-tab"), value => Step("selection:" + value), + () => Step("dirty"), () => Step("audit"), + () => { Step("editor"); return ReadEditor is null ? Editor : ReadEditor(); }); + State.PropertyChanged += (sender, e) => + { + Assert.Same(State, sender); + Events.Add(e.PropertyName!); Trace.Add("event:" + e.PropertyName); + Observer?.Invoke(e.PropertyName!); + }; + } + public CreateConfigComponentSelection State { get; } + public string? Editor { get; init; } = "text"; + public HashSet Supported { get; } = new(StringComparer.Ordinal) { "supported" }; + public List Trace { get; } = []; + public List Events { get; } = []; + public Action? OnStep { get; set; } + public Action? Observer { get; set; } + public Func? ReadEditor { get; set; } + private void Step(string step) { Trace.Add(step); OnStep?.Invoke(step); } + } +} diff --git a/CDPIUI.Tests/Presentation/CreateConfigConditionDraftTests.cs b/CDPIUI.Tests/Presentation/CreateConfigConditionDraftTests.cs new file mode 100644 index 00000000..f5febcf1 --- /dev/null +++ b/CDPIUI.Tests/Presentation/CreateConfigConditionDraftTests.cs @@ -0,0 +1,214 @@ +using System.Collections.ObjectModel; +using CDPIUI.Core.LScript; +using CDPIUI.ViewModels.CreateConfig; +using CDPIUI.Views.CreateConfigHelper; + +namespace CDPIUI.Tests.Presentation; + +public sealed class CreateConfigConditionDraftTests +{ + [Fact] + public void ConstructorOnlyStoresDependenciesAndKeepsEmptyFields() + { + var f = new Fixture(); + Assert.Empty(f.Trace); Assert.Empty(f.Events); Assert.Empty(f.Items); + Assert.Equal("", f.Draft.ConditionName); + Assert.Equal("", f.Draft.ConditionDescription); + Assert.Equal("", f.Draft.ConditionOnValue); + Assert.Equal("", f.Draft.ConditionOffValue); + } + + [Theory] + [InlineData("name")] + [InlineData("description")] + [InlineData("on")] + [InlineData("off")] + public void SettersNormalizeNullAndSuppressEqualValuesWithOriginalNotifications(string property) + { + var f = new Fixture(); + void Set(string? value) + { + switch (property) + { + case "name": f.Draft.ConditionName = value!; break; + case "description": f.Draft.ConditionDescription = value!; break; + case "on": f.Draft.ConditionOnValue = value!; break; + default: f.Draft.ConditionOffValue = value!; break; + } + } + Set(null); Assert.Empty(f.Events); + Set("x"); + string own = property switch { "name" => "ConditionName", "description" => "ConditionDescription", "on" => "ConditionOnValue", _ => "ConditionOffValue" }; + Assert.Equal(property == "description" ? new[] { own } : new[] { own, "ConditionPreview", "IsConditionSaveAvailable" }, f.Events); + f.Events.Clear(); Set("x"); Assert.Empty(f.Events); + Set(null); + Assert.Equal(property == "description" ? new[] { own } : new[] { own, "ConditionPreview", "IsConditionSaveAvailable" }, f.Events); + Assert.Empty(f.Trace); + } + + [Theory] + [InlineData(false, "on", "off", false)] + [InlineData(true, "", "off", false)] + [InlineData(true, "on", "", false)] + [InlineData(true, " ", "\t", true)] + public void AvailabilityNormalizesOnlySpacesAndKeepsOriginalEmptyValueRules(bool valid, string on, string off, bool expected) + { + var f = new Fixture(); f.Ready(" A B ", on, off); f.Validate = _ => valid; + Assert.Equal(expected, f.Draft.IsConditionSaveAvailable); + Assert.Equal(new[] { "validate:AB" }, f.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void PreviewIsFreshAndUsesOnlyTheChosenFormatterOrLocalizationBranch(bool valid) + { + var f = new Fixture(); f.Ready(" A B ", "on", "off"); f.Validate = _ => valid; + Assert.Equal(valid ? "AB[on|off]" : "localized:NothingToPreview", f.Draft.ConditionPreview); + Assert.Equal(valid ? new[] { "validate:AB", "format:AB:on:off" } : new[] { "validate:AB", "text:NothingToPreview" }, f.Trace); + f.Trace.Clear(); + f.Localize = _ => "changed"; f.Format = (_, _, _) => "next"; + Assert.Equal(valid ? "next" : "changed", f.Draft.ConditionPreview); + } + + [Fact] + public void PreviewReadsCurrentValuesAgainAfterValidationCallback() + { + var f = new Fixture(); f.Ready("AB", "before-on", "before-off"); + f.Validate = _ => + { + f.Draft.ConditionName = " C D "; f.Draft.ConditionOnValue = "after-on"; f.Draft.ConditionOffValue = "after-off"; + return true; + }; + Assert.Equal("CD[after-on|after-off]", f.Draft.ConditionPreview); + Assert.Equal(new[] { "validate:AB", "format:CD:after-on:after-off" }, f.Trace); + } + + [Fact] + public void ResetUsesOriginalSetterOrderAndAlwaysPublishesFinalPreview() + { + var f = new Fixture(); f.Ready("AB", "on", "off"); f.Draft.ConditionDescription = "desc"; f.Events.Clear(); + f.Draft.ResetConditionDraft(); + Assert.Equal(new[] { "ConditionName", "ConditionPreview", "IsConditionSaveAvailable", "ConditionDescription", + "ConditionOnValue", "ConditionPreview", "IsConditionSaveAvailable", "ConditionOffValue", "ConditionPreview", "IsConditionSaveAvailable", "ConditionPreview" }, f.Events); + Assert.Empty(f.Trace); + f.Events.Clear(); f.Draft.ResetConditionDraft(); + Assert.Equal(new[] { "ConditionPreview" }, f.Events); + } + + [Fact] + public void DraftNotificationsRemainReentrantBeforeOuterDerivedNotifications() + { + var f = new Fixture(); bool entered = false; + f.Draft.PropertyChanged += (_, args) => + { + if (args.PropertyName != "ConditionName" || entered) return; + entered = true; f.Draft.ConditionOnValue = "nested"; + }; + f.Draft.ConditionName = "AB"; + Assert.Equal(new[] { "ConditionName", "ConditionOnValue", "ConditionPreview", "IsConditionSaveAvailable", "ConditionPreview", "IsConditionSaveAvailable" }, f.Events); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AddHasNoValidationGuardAndKeepsRawFieldsAndFreshModelIdentity(bool invalid) + { + var f = new Fixture(); f.Ready(invalid ? "" : " A B ", invalid ? "" : "on", "off"); + f.Draft.ConditionDescription = "desc"; f.Events.Clear(); + f.Draft.AddCondition(); f.Draft.AddCondition(); + Assert.Equal(2, f.Items.Count); Assert.NotSame(f.Items[0], f.Items[1]); + foreach (var item in f.Items) + { + Assert.Equal(invalid ? "" : " A B ", item.Name); + Assert.Equal(invalid ? "" : "on", item.OnValue); + Assert.Equal("off", item.OffValue); Assert.Equal("desc", item.Description); + } + Assert.Equal(new[] { "exit", "add", "exit", "add" }, f.Trace); + Assert.Empty(f.Events); + } + + [Fact] + public void AddAllowsExitCallbackToChangeDraftBeforeReadingAndDoesNotResetIt() + { + var f = new Fixture(); f.Ready("before", "on", "off"); + f.EnableExit = () => + { + Assert.Empty(f.Items); + f.Draft.ConditionName = "after"; f.Draft.ConditionDescription = "changed"; + f.Draft.ConditionOnValue = "new-on"; f.Draft.ConditionOffValue = "new-off"; + }; + f.Draft.AddCondition(); + var added = Assert.Single(f.Items); + Assert.Equal(("after", "changed", "new-on", "new-off"), (added.Name, added.Description, added.OnValue, added.OffValue)); + Assert.Equal("after", f.Draft.ConditionName); + Assert.Equal(new[] { "exit", "add" }, f.Trace); + } + + [Theory] + [InlineData("validate")] + [InlineData("format")] + [InlineData("text")] + [InlineData("exit")] + [InlineData("collection")] + public void CallbackFailuresEscapeSynchronouslyWithOriginalPartialMutation(string point) + { + var f = new Fixture(); f.Ready("AB", "on", "off"); + var failure = new IOException(point); + if (point == "validate") f.Validate = _ => throw failure; + if (point == "format") f.Format = (_, _, _) => throw failure; + if (point == "text") { f.Validate = _ => false; f.Localize = _ => throw failure; } + if (point == "exit") f.EnableExit = () => throw failure; + if (point == "collection") f.Items.CollectionChanged += (_, _) => throw failure; + Assert.Same(failure, Assert.Throws(() => + { + if (point is "exit" or "collection") f.Draft.AddCondition(); else _ = f.Draft.ConditionPreview; + })); + Assert.Equal(point == "collection" ? 1 : 0, f.Items.Count); + } + + [Fact] + public void SetterObserverFailureKeepsAssignedValueAndSkipsDerivedNotifications() + { + var f = new Fixture(); var failure = new IOException("observer"); + f.Draft.PropertyChanged += (_, _) => throw failure; + Assert.Same(failure, Assert.Throws(() => f.Draft.ConditionName = "AB")); + Assert.Equal("AB", f.Draft.ConditionName); + Assert.Equal(new[] { "ConditionName" }, f.Events); + } + + [Fact] + public void ExistingCoreFormatterRemainsUsableWithoutWinUi() + { + var f = new Fixture(); f.Ready(" A B ", "on", "off"); + f.Format = LScriptCore.CreateCondition; + Assert.Equal("AB==true ? on : off", f.Draft.ConditionPreview); + } + + private sealed class Fixture + { + public ObservableCollection Items { get; } = []; + public List Trace { get; } = []; + public List Events { get; } = []; + public Func Validate = _ => true; + public Func Format = (name, on, off) => $"{name}[{on}|{off}]"; + public Func Localize = key => "localized:" + key; + public Action? EnableExit; + public CreateConfigConditionDraft Draft { get; } + public Fixture() + { + Draft = new(Items, + name => { Trace.Add("validate:" + name); return Validate(name); }, + (name, on, off) => { Trace.Add($"format:{name}:{on}:{off}"); return Format(name, on, off); }, + key => { Trace.Add("text:" + key); return Localize(key); }, + () => { Trace.Add("exit"); EnableExit?.Invoke(); }); + Draft.PropertyChanged += (sender, args) => { Assert.Same(Draft, sender); Events.Add(args.PropertyName); }; + Items.CollectionChanged += (_, _) => Trace.Add("add"); + } + public void Ready(string name, string on, string off) + { + Draft.ConditionName = name; Draft.ConditionOnValue = on; Draft.ConditionOffValue = off; + Events.Clear(); Trace.Clear(); + } + } +} diff --git a/CDPIUI.Tests/Presentation/CreateConfigGraphicDesignerTests.cs b/CDPIUI.Tests/Presentation/CreateConfigGraphicDesignerTests.cs new file mode 100644 index 00000000..0d44bf8f --- /dev/null +++ b/CDPIUI.Tests/Presentation/CreateConfigGraphicDesignerTests.cs @@ -0,0 +1,383 @@ +using System.Collections.ObjectModel; +using CDPIUI.Core.Store.Data; +using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.ViewModels.CreateConfig; +using CDPIUI.Views.CreateConfigHelper; + +namespace CDPIUI.Tests.Presentation; + +public sealed class CreateConfigGraphicDesignerTests +{ + [Fact] + public void ConstructorStoresDependenciesWithoutReadingIdsOrLoading() + { + var f = new Fixture(); + Assert.Empty(f.Trace); Assert.Empty(f.Events); + Assert.Empty(f.Designer.AdditionalSettings); Assert.Empty(f.Designer.LoadedComponentId); + Assert.Empty(f.Items); Assert.Empty(f.Groups); + } + + [Fact] + public void AdditionalSettingsPreservesNullNormalizationEqualityAndSender() + { + var f = new Fixture(); + f.Designer.AdditionalSettings = null!; + Assert.Empty(f.Events); + f.Designer.AdditionalSettings = "extra"; + f.Designer.AdditionalSettings = "extra"; + f.Designer.AdditionalSettings = null!; + Assert.Equal(["AdditionalSettings", "AdditionalSettings"], f.Events); + Assert.Empty(f.Designer.AdditionalSettings); + } + + [Fact] + public void AdditionalObserverFailureRetainsAssignedValue() + { + var f = new Fixture(); + f.Designer.PropertyChanged += (_, _) => throw new IOException("observer"); + Assert.Throws(() => f.Designer.AdditionalSettings = "assigned"); + Assert.Equal("assigned", f.Designer.AdditionalSettings); + } + + [Theory] + [InlineData(Components.GoodbyeDPI, "good")] + [InlineData(Components.SpoofDPI, "spoof")] + [InlineData(Components.NoDPI, "no")] + public void KnownLoadCachesComponentAndReusesTheProvidedCollections(Components component, string id) + { + var f = new Fixture(); + f.Designer.Load(id); + Assert.Equal(id, f.Designer.LoadedComponentId); + Assert.Single(f.Backend.Loads); + f.Designer.Load(id); + Assert.Single(f.Backend.Loads); + Assert.Equal(id, f.Ids[component]); + } + + [Fact] + public void LoadReadsMappedIdAgainAfterCollectionCallbacks() + { + var f = new Fixture(); + f.Backend.Loading = _ => f.Ids[Components.GoodbyeDPI] = "changed-good"; + f.Designer.Load("good"); + Assert.Equal(["id:GoodbyeDPI", "id:GoodbyeDPI", "good", "id:GoodbyeDPI"], f.Trace); + Assert.Equal("changed-good", f.Designer.LoadedComponentId); + } + + [Fact] + public void MissingAnnotationKeepsOldCacheAndRetries() + { + var f = new Fixture(); + f.Designer.Load("good"); + f.Backend.NoDpiAvailable = false; + f.Designer.Load("no"); f.Designer.Load("no"); + Assert.Equal("good", f.Designer.LoadedComponentId); + Assert.Equal(["good", "no:no", "no:no"], f.Backend.Loads); + f.Backend.NoDpiAvailable = true; + f.Designer.Load("no"); + Assert.Equal("no", f.Designer.LoadedComponentId); + } + + [Theory] + [InlineData("GOOD")] + [InlineData("unknown")] + [InlineData("")] + [InlineData(null)] + public void UnsupportedOrDifferentlyCasedIdKeepsModelsAndCache(string? id) + { + var f = new Fixture(); + var item = new GraphicDesignerSettingItemModel { Guid = "kept" }; + f.Items.Add(item); + f.Designer.Load("good"); + f.Designer.Load(id!); + Assert.Equal(["good"], f.Backend.Loads); + Assert.Same(item, Assert.Single(f.Items)); + Assert.Equal("good", f.Designer.LoadedComponentId); + } + + [Fact] + public void SwitchingComponentsReloadsButReturningToCurrentDoesNot() + { + var f = new Fixture(); + f.Designer.Load("good"); f.Designer.Load("spoof"); f.Designer.Load("spoof"); f.Designer.Load("good"); + Assert.Equal(["good", "spoof", "good"], f.Backend.Loads); + Assert.Equal("good", f.Designer.LoadedComponentId); + } + + [Fact] + public void EqualMappedIdsKeepTheOriginalBranchPriority() + { + var f = new Fixture(); + f.Ids[Components.SpoofDPI] = "good"; f.Ids[Components.NoDPI] = "good"; + f.Designer.Load("good"); f.Designer.Load("good"); + Assert.Equal(["good"], f.Backend.Loads); + } + + [Fact] + public void ReentrantLoadPublishesOuterCacheAfterNestedLoad() + { + var f = new Fixture(); + bool entered = false; + f.Backend.Loading = _ => { if (!entered) { entered = true; f.Designer.Load("spoof"); } }; + f.Designer.Load("good"); + Assert.Equal(["good", "spoof"], f.Backend.Loads); + Assert.Equal("good", f.Designer.LoadedComponentId); + } + + [Fact] + public void FailedLoadLeavesPreviousCacheAndPartialCollectionMutation() + { + var f = new Fixture(); + f.Designer.Load("good"); + var partial = new GraphicDesignerSettingItemModel { Guid = "partial" }; + f.Backend.Loading = _ => { f.Items.Add(partial); throw new IOException("load"); }; + Assert.Throws(() => f.Designer.Load("spoof")); + Assert.Equal("good", f.Designer.LoadedComponentId); + Assert.Same(partial, Assert.Single(f.Items)); + } + + [Fact] + public void TextPrefersFirstStandaloneMatchBeforeExclusiveChildren() + { + var f = new Fixture(); + var first = new GraphicDesignerSettingItemModel { Guid = "x" }; + var duplicate = new GraphicDesignerSettingItemModel { Guid = "x" }; + var child = new GraphicDesignerSettingItemModel { Guid = "x" }; + f.Items.Add(first); f.Items.Add(duplicate); f.Groups.Add(new() { Guid = "g", Items = [child] }); + f.Designer.ChangeText(Tuple.Create("x", "new")); + Assert.Equal("new", first.Value); Assert.Equal("", duplicate.Value); Assert.Equal("", child.Value); + Assert.Empty(f.Events); + } + + [Fact] + public void TextAndBoolUseFirstChildOfFirstMatchingGroup() + { + var f = new Fixture(); + var first = new GraphicDesignerSettingItemModel { Guid = "x" }; + var duplicate = new GraphicDesignerSettingItemModel { Guid = "x" }; + var later = new GraphicDesignerSettingItemModel { Guid = "x" }; + f.Groups.Add(new() { Guid = "g1", Items = [first, duplicate] }); + f.Groups.Add(new() { Guid = "g2", Items = [later] }); + f.Designer.ChangeText(Tuple.Create("x", "text")); + f.Designer.ToggleBool(Tuple.Create("x", true)); + Assert.Equal("text", first.Value); Assert.True(first.IsChecked); + Assert.Equal("", duplicate.Value); Assert.False(duplicate.IsChecked); + Assert.Equal("", later.Value); Assert.False(later.IsChecked); + } + + [Fact] + public void BoolPrefersStandaloneAndSuppressesEqualModelNotifications() + { + var f = new Fixture(); + var first = new GraphicDesignerSettingItemModel { Guid = "x" }; + var child = new GraphicDesignerSettingItemModel { Guid = "x" }; + int changes = 0; first.PropertyChanged += (_, _) => changes++; + f.Items.Add(first); f.Groups.Add(new() { Items = [child] }); + f.Designer.ToggleBool(Tuple.Create("x", true)); f.Designer.ToggleBool(Tuple.Create("x", true)); + Assert.True(first.IsChecked); Assert.False(child.IsChecked); Assert.Equal(1, changes); + } + + [Fact] + public void ScalarEditsRemainCaseSensitiveAndIgnoreUnknownGuid() + { + var f = new Fixture(); + var item = new GraphicDesignerSettingItemModel { Guid = "X" }; + f.Items.Add(item); + f.Designer.ChangeText(Tuple.Create("x", "wrong")); + f.Designer.ToggleBool(Tuple.Create("unknown", true)); + Assert.Equal("", item.Value); Assert.False(item.IsChecked); + } + + [Fact] + public void TextUsesActualGroupingSetterAndAcceptsNullWithoutCoercion() + { + var f = new Fixture(); + var item = new GraphicDesignerSettingItemModel { Guid = "x" }; + item.SetParsedValue("value", preserveGrouping: true); + f.Items.Add(item); + f.Designer.ChangeText(Tuple.Create("x", "value")); + Assert.True(item.PreserveValueGrouping); + f.Designer.ChangeText(Tuple.Create("x", "changed")); + Assert.False(item.PreserveValueGrouping); + f.Designer.ChangeText(Tuple.Create("x", (string)null!)); + Assert.Null(item.Value); + } + + [Fact] + public void ReentrantCollectionChangeDoesNotRetargetTheAssignedItem() + { + var f = new Fixture(); + var original = new GraphicDesignerSettingItemModel { Guid = "x" }; + var replacement = new GraphicDesignerSettingItemModel { Guid = "x" }; + f.Items.Add(original); + original.PropertyChanged += (_, _) => { f.Items.Clear(); f.Items.Add(replacement); }; + f.Designer.ChangeText(Tuple.Create("x", "assigned")); + Assert.Equal("assigned", original.Value); Assert.Equal("", replacement.Value); + Assert.Same(replacement, Assert.Single(f.Items)); + } + + [Fact] + public void BoolObserverFailureLeavesAssignedFlag() + { + var f = new Fixture(); + var item = new GraphicDesignerSettingItemModel { Guid = "x" }; + item.PropertyChanged += (_, _) => throw new IOException("item"); + f.Items.Add(item); + Assert.Throws(() => f.Designer.ToggleBool(Tuple.Create("x", true))); + Assert.True(item.IsChecked); + } + + [Fact] + public void SelectionUsesFirstMatchingGroupWithoutValidatingChildOrCheckedState() + { + var f = new Fixture(); + var first = new GraphicDesignerExclusiveSettingItemModel { Guid = "g", Items = [] }; + var duplicate = new GraphicDesignerExclusiveSettingItemModel { Guid = "g", Items = [] }; + f.Groups.Add(first); f.Groups.Add(duplicate); + f.Designer.SelectGuid(Tuple.Create("g", "nonexistent")); + Assert.Equal("nonexistent", first.SelectedItemGuid); Assert.Equal("", duplicate.SelectedItemGuid); + Assert.False(first.IsChecked); + f.Designer.SelectGuid(Tuple.Create("g", (string)null!)); + Assert.Null(first.SelectedItemGuid); + } + + [Fact] + public void SelectionRemainsCaseSensitive() + { + var f = new Fixture(); + var group = new GraphicDesignerExclusiveSettingItemModel { Guid = "G", Items = [] }; + f.Groups.Add(group); + f.Designer.SelectGuid(Tuple.Create("g", "value")); + Assert.Equal("", group.SelectedItemGuid); + } + + [Theory] + [InlineData("text")] + [InlineData("bool")] + [InlineData("select")] + public void NullTupleKeepsOriginalFailure(string kind) + { + var f = new Fixture(); + Assert.Throws(() => + { + if (kind == "text") f.Designer.ChangeText(null!); + else if (kind == "bool") f.Designer.ToggleBool(null!); + else f.Designer.SelectGuid(null!); + }); + Assert.Empty(f.Events); + } + + [Fact] + public void PrimaryMatchDoesNotInspectMalformedGroupsButFallbackRetainsFailure() + { + var f = new Fixture(); + var item = new GraphicDesignerSettingItemModel { Guid = "x" }; + f.Items.Add(item); f.Groups.Add(new() { Items = null! }); + f.Designer.ChangeText(Tuple.Create("x", "safe")); + Assert.Equal("safe", item.Value); + Assert.Throws(() => f.Designer.ChangeText(Tuple.Create("missing", "value"))); + } + + [Fact] + public void ParseUsesSameCollectionsAndPublishesResultAfterBackendCallbacks() + { + var f = new Fixture(); + f.Backend.Parsing = text => { Assert.Equal("original\ntext", text); f.Designer.AdditionalSettings = "during"; return "after"; }; + f.Designer.Parse("original\ntext"); + Assert.Equal("after", f.Designer.AdditionalSettings); + Assert.Equal(["parse", "event:AdditionalSettings", "event:AdditionalSettings"], f.Trace); + } + + [Fact] + public void NullParseResultUsesExistingAdditionalNormalization() + { + var f = new Fixture(); + f.Designer.AdditionalSettings = "old"; + f.Backend.Parsing = _ => null!; + f.Designer.Parse("input"); + Assert.Equal("", f.Designer.AdditionalSettings); + } + + [Fact] + public void BuildCapturesAdditionalBeforeBackendReentry() + { + var f = new Fixture(); + f.Designer.AdditionalSettings = "before"; f.Trace.Clear(); + f.Backend.Building = additional => { f.Designer.AdditionalSettings = "during"; return additional; }; + Assert.Equal("before", f.Designer.Build()); + Assert.Equal("during", f.Designer.AdditionalSettings); + Assert.Equal(["build:before", "event:AdditionalSettings"], f.Trace); + } + + [Fact] + public void ParseFailureKeepsOldAdditionalAndPartialModels() + { + var f = new Fixture(); + f.Designer.AdditionalSettings = "old"; + var item = new GraphicDesignerSettingItemModel { Guid = "partial" }; + f.Backend.Parsing = _ => { f.Items.Add(item); throw new IOException("parse"); }; + Assert.Throws(() => f.Designer.Parse("input")); + Assert.Equal("old", f.Designer.AdditionalSettings); Assert.Same(item, Assert.Single(f.Items)); + } + + [Fact] + public void BuildFailureKeepsBackendReentrantChanges() + { + var f = new Fixture(); + f.Backend.Building = _ => { f.Designer.AdditionalSettings = "changed"; throw new IOException("build"); }; + Assert.Throws(() => f.Designer.Build()); + Assert.Equal("changed", f.Designer.AdditionalSettings); + } + + private sealed class Fixture + { + public Fixture() + { + Backend = new(this); + Designer = new(Items, Groups, Backend, component => { Trace.Add("id:" + component); return Ids[component]; }); + Designer.PropertyChanged += (sender, e) => + { + Assert.Same(Designer, sender); + Events.Add(e.PropertyName!); Trace.Add("event:" + e.PropertyName); + }; + } + public ObservableCollection Items { get; } = []; + public ObservableCollection Groups { get; } = []; + public Dictionary Ids { get; } = new() + { + [Components.GoodbyeDPI] = "good", [Components.SpoofDPI] = "spoof", [Components.NoDPI] = "no" + }; + public List Trace { get; } = []; + public List Events { get; } = []; + public Backend Backend { get; } + public CreateConfigGraphicDesigner Designer { get; } + } + + private sealed class Backend(Fixture fixture) : ICreateConfigGraphicDesignerBackend + { + public bool NoDpiAvailable { get; set; } = true; + public List Loads { get; } = []; + public Action? Loading { get; set; } + public Func? Parsing { get; set; } + public Func? Building { get; set; } + private void Collections(ObservableCollection items, + ObservableCollection groups) + { + Assert.Same(fixture.Items, items); Assert.Same(fixture.Groups, groups); + } + private void Load(string kind) + { + Loads.Add(kind); fixture.Trace.Add(kind); Loading?.Invoke(kind); + } + public void LoadGoodbye(ObservableCollection items, ObservableCollection groups) + { Collections(items, groups); Load("good"); } + public void LoadSpoof(ObservableCollection items, ObservableCollection groups) + { Collections(items, groups); Load("spoof"); } + public bool TryLoadNoDpi(string id, ObservableCollection items, ObservableCollection groups) + { Collections(items, groups); Load("no:" + id); return NoDpiAvailable; } + public string Parse(ObservableCollection items, ObservableCollection groups, string text) + { Collections(items, groups); fixture.Trace.Add("parse"); return Parsing is null ? "--extra" : Parsing(text); } + public string Build(ObservableCollection items, ObservableCollection groups, string additional) + { Collections(items, groups); fixture.Trace.Add("build:" + additional); return Building?.Invoke(additional) ?? "built:" + additional; } + } +} diff --git a/CDPIUI.Tests/Presentation/CreateConfigTestSessionTests.cs b/CDPIUI.Tests/Presentation/CreateConfigTestSessionTests.cs new file mode 100644 index 00000000..4b2daca7 --- /dev/null +++ b/CDPIUI.Tests/Presentation/CreateConfigTestSessionTests.cs @@ -0,0 +1,413 @@ +using CDPIUI.Core.ComponentServices.Helpers.Configuration; +using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.ViewModels.CreateConfig; + +namespace CDPIUI.Tests.Presentation; + +public sealed class CreateConfigTestSessionTests +{ + [Fact] + public void ConstructorStoresCallbacksAndInitialTextDoesNotNotify() + { + var f = new Fixture(); + Assert.Empty(f.Trace); Assert.Empty(f.Events); + Assert.Null(f.Session.TestButtonText); + Assert.Equal("\uE768", f.Session.TestButtonGlyph); + Assert.False(f.Session.IsRunning); Assert.Empty(f.Session.CurrentRunId); + f.Session.InitializeText("initial"); + f.Session.InitializeText(null!); + Assert.Null(f.Session.TestButtonText); + Assert.Empty(f.Trace); Assert.Empty(f.Events); + } + + [Fact] + public async Task StartSubscribesBeforeSelectionAndStopsBeforePreparingCurrentConfiguration() + { + var f = new Fixture(); + f.Session.InitializeText("initial"); + await f.Session.ToggleAsync(); + Assert.Equal(["remove", "add", "selection", "stop:component", "convert", "create", "args", "run:component:--test"], f.Trace); + Assert.True(f.Session.IsRunning); Assert.Equal("component", f.Session.CurrentRunId); + Assert.Equal(1, f.Tasks.SubscriberCount); + Assert.Equal("initial", f.Session.TestButtonText); + Assert.Empty(f.Events); + } + + [Fact] + public async Task SelectionIsReadAfterSubscriptionCallbacks() + { + var f = new Fixture(); + f.Tasks.OnAdd = () => f.HasComponent = false; + await f.Session.ToggleAsync(); + Assert.Equal(["remove", "add", "selection", "localize:TestThis", "event:TestButtonText", "remove"], f.Trace); + Assert.False(f.Session.IsRunning); Assert.Empty(f.Session.CurrentRunId); + Assert.Equal(0, f.Tasks.SubscriberCount); Assert.Empty(f.Tasks.Stops); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public async Task SelectedComponentWithNullOrEmptyIdIsStillStarted(string? id) + { + var f = new Fixture { ComponentId = id! }; + await f.Session.ToggleAsync(); + Assert.True(f.Session.IsRunning); + Assert.Equal(id, f.Session.CurrentRunId); + Assert.Equal(id, Assert.Single(f.Tasks.Stops)); + Assert.Equal(id, Assert.Single(f.Tasks.Runs).Id); + } + + [Fact] + public void StopAlwaysUnsubscribesEvenWithoutARunningSession() + { + var f = new Fixture(); + f.Session.Stop(); + Assert.Equal(["remove"], f.Trace); + Assert.Empty(f.Tasks.Stops); Assert.Empty(f.Events); + } + + [Fact] + public async Task StopResetsBeforeFireAndForgetStopAndUsesTheOriginalLocalId() + { + var f = new Fixture(); + await f.Session.ToggleAsync(); + f.Apply("component", true); + f.Trace.Clear(); f.Events.Clear(); + f.Tasks.StopAction = _ => + { + Assert.False(f.Session.IsRunning); Assert.Empty(f.Session.CurrentRunId); + return Task.CompletedTask; + }; + f.Session.Stop(); + Assert.Equal(["remove", "event:TestButtonGlyph", "localize:TestThis", "event:TestButtonText", "remove", "stop:component"], f.Trace); + Assert.Equal(["TestButtonGlyph", "TestButtonText"], f.Events); + Assert.Equal(0, f.Tasks.SubscriberCount); + } + + [Fact] + public async Task EmptyCurrentIdPreventsStopResetDespiteRunningFlag() + { + var f = new Fixture { ComponentId = "" }; + await f.Session.ToggleAsync(); + f.Trace.Clear(); + f.Session.Stop(); + Assert.Equal(["remove"], f.Trace); + Assert.True(f.Session.IsRunning); Assert.Empty(f.Session.CurrentRunId); + } + + [Fact] + public async Task AwaitedStopDefersPreparationAndKeepsOriginalRunIdWithCurrentConfiguration() + { + var f = new Fixture(); + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Tasks.StopAction = _ => gate.Task; + var pending = f.Session.ToggleAsync(); + try + { + Assert.False(pending.IsCompleted); Assert.True(f.Session.IsRunning); + Assert.DoesNotContain("convert", f.Trace); + f.ComponentId = "new-selection"; + f.Create = () => { Assert.Equal("new-selection", f.ComponentId); return f.Config; }; + } + finally { gate.TrySetResult(); } + await pending.WaitAsync(TimeSpan.FromSeconds(3)); + Assert.Equal("component", Assert.Single(f.Tasks.Runs).Id); + } + + [Fact] + public async Task NullConfigurationResetsWithoutStarting() + { + var f = new Fixture { Create = () => null }; + await f.Session.ToggleAsync(); + Assert.False(f.Session.IsRunning); Assert.Empty(f.Session.CurrentRunId); + Assert.Equal(0, f.Tasks.SubscriberCount); Assert.Empty(f.Tasks.Runs); + Assert.Equal(["remove", "add", "selection", "stop:component", "convert", "create", "localize:TestThis", "event:TestButtonText", "remove"], f.Trace); + } + + [Fact] + public async Task RunTaskIsNotAwaited() + { + var f = new Fixture(); + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Tasks.RunAction = (_, _) => gate.Task; + try + { + await f.Session.ToggleAsync().WaitAsync(TimeSpan.FromSeconds(3)); + Assert.False(gate.Task.IsCompleted); Assert.True(f.Session.IsRunning); + } + finally { gate.TrySetResult(); } + } + + [Fact] + public async Task ReturnedRunFaultIsNotTurnedIntoToggleFaultOrReset() + { + var f = new Fixture(); + var failure = Task.FromException(new IOException("run task")); + f.Tasks.RunAction = (_, _) => failure; + await f.Session.ToggleAsync(); + await Assert.ThrowsAsync(() => failure); + Assert.True(f.Session.IsRunning); Assert.Equal(1, f.Tasks.SubscriberCount); + } + + [Fact] + public async Task RunIdArgumentIsCapturedBeforeFormatterReentersStop() + { + var f = new Fixture(); + f.Format = _ => { f.Session.Stop(); return "formatted"; }; + await f.Session.ToggleAsync(); + Assert.Equal(("component", "formatted"), Assert.Single(f.Tasks.Runs)); + Assert.False(f.Session.IsRunning); Assert.Empty(f.Session.CurrentRunId); + } + + [Fact] + public async Task ConversionReentryChangesTheLaterReadRunId() + { + var f = new Fixture(); + f.Convert = () => f.Session.Stop(); + await f.Session.ToggleAsync(); + Assert.Equal("", Assert.Single(f.Tasks.Runs).Id); + Assert.False(f.Session.IsRunning); + } + + [Fact] + public async Task EventsAreQueuedBeforeTheCurrentIdGuardIsEvaluated() + { + var f = new Fixture(); + f.Tasks.Emit("not-current", true); + Assert.Empty(f.Queued); + await f.Session.ToggleAsync(); + f.Tasks.Emit("component", true); + Assert.Single(f.Queued); + Assert.Equal("\uE768", f.Session.TestButtonGlyph); + f.Session.Stop(); + f.ComponentId = "other"; + await f.Session.ToggleAsync(); + f.Trace.Clear(); + f.Queued[0](); + Assert.Empty(f.Trace); + Assert.Equal("other", f.Session.CurrentRunId); + } + + [Theory] + [InlineData("Component")] + [InlineData("other")] + public async Task StateMatchingRemainsCaseSensitive(string eventId) + { + var f = new Fixture(); + await f.Session.ToggleAsync(); + f.Trace.Clear(); + f.Apply(eventId, true); + Assert.Empty(f.Trace); Assert.Equal("\uE768", f.Session.TestButtonGlyph); + } + + [Fact] + public async Task MatchingStateChangesGlyphThenLocalizedTextThenRunning() + { + var f = new Fixture(); + await f.Session.ToggleAsync(); + f.Apply("component", true); + f.Trace.Clear(); f.Events.Clear(); + f.Observer = name => Assert.True(f.Session.IsRunning); + f.Apply("component", false); + Assert.Equal(["event:TestButtonGlyph", "localize:TestThis", "event:TestButtonText"], f.Trace); + Assert.Equal(["TestButtonGlyph", "TestButtonText"], f.Events); + Assert.False(f.Session.IsRunning); + Assert.Equal("component", f.Session.CurrentRunId); Assert.Equal(1, f.Tasks.SubscriberCount); + } + + [Fact] + public async Task NaturalExitKeepsSubscriptionUntilNextToggleOrStop() + { + var f = new Fixture(); + await f.Session.ToggleAsync(); + f.Apply("component", false); + Assert.Equal(1, f.Tasks.SubscriberCount); + f.Trace.Clear(); + f.ComponentId = "next"; + await f.Session.ToggleAsync(); + Assert.Equal(1, f.Tasks.SubscriberCount); + Assert.Equal("next", f.Session.CurrentRunId); + Assert.Equal(["remove", "add", "selection", "stop:next", "convert", "create", "args", "run:next:--test"], f.Trace); + } + + [Fact] + public async Task StopAfterNaturalExitOnlyUnsubscribesAndKeepsId() + { + var f = new Fixture(); + await f.Session.ToggleAsync(); + f.Apply("component", false); f.Trace.Clear(); + f.Session.Stop(); + Assert.Equal(["remove"], f.Trace); Assert.Equal("component", f.Session.CurrentRunId); + } + + [Fact] + public async Task RejectedDispatchDoesNotApplyState() + { + var f = new Fixture { AcceptEnqueue = false }; + await f.Session.ToggleAsync(); + f.Tasks.Emit("component", true); + Assert.Empty(f.Queued); Assert.Equal("\uE768", f.Session.TestButtonGlyph); + } + + [Fact] + public async Task StopBranchAwaitsBackendBeforeResettingState() + { + var f = new Fixture(); + await f.Session.ToggleAsync(); + f.Apply("component", true); + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Tasks.StopAction = _ => gate.Task; + var pending = f.Session.ToggleAsync(); + try + { + Assert.False(pending.IsCompleted); + Assert.True(f.Session.IsRunning); Assert.Equal("\uE71A", f.Session.TestButtonGlyph); + Assert.Equal(1, f.Tasks.SubscriberCount); + } + finally { gate.TrySetResult(); } + await pending.WaitAsync(TimeSpan.FromSeconds(3)); + Assert.False(f.Session.IsRunning); Assert.Empty(f.Session.CurrentRunId); + Assert.Equal(0, f.Tasks.SubscriberCount); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task AwaitedStopFaultPreservesPartialState(bool alreadyRunning) + { + var f = new Fixture(); + if (alreadyRunning) await f.Session.ToggleAsync(); + f.Tasks.StopAction = _ => Task.FromException(new IOException("stop")); + await Assert.ThrowsAsync(() => f.Session.ToggleAsync()); + Assert.True(f.Session.IsRunning); Assert.Equal("component", f.Session.CurrentRunId); + Assert.Equal(1, f.Tasks.SubscriberCount); + } + + [Theory] + [InlineData("selection")] + [InlineData("convert")] + [InlineData("create")] + [InlineData("args")] + [InlineData("run")] + public async Task SynchronousPreparationFaultDoesNotAddCleanupOrRollback(string stage) + { + var f = new Fixture(); + var error = new IOException(stage); + if (stage == "selection") f.Select = () => throw error; + if (stage == "convert") f.Convert = () => throw error; + if (stage == "create") f.Create = () => throw error; + if (stage == "args") f.Format = _ => throw error; + if (stage == "run") f.Tasks.RunAction = (_, _) => throw error; + Assert.Same(error, await Assert.ThrowsAsync(() => f.Session.ToggleAsync())); + Assert.True(f.Session.IsRunning); Assert.Equal(1, f.Tasks.SubscriberCount); + Assert.Equal(stage == "selection" ? "" : "component", f.Session.CurrentRunId); + } + + [Fact] + public async Task StopLocalizerFailureLeavesTheOriginalPartialReset() + { + var f = new Fixture(); + await f.Session.ToggleAsync(); f.Apply("component", true); + f.Localize = _ => throw new IOException("locale"); + Assert.Throws(() => f.Session.Stop()); + Assert.Equal("\uE768", f.Session.TestButtonGlyph); + Assert.True(f.Session.IsRunning); Assert.Equal("component", f.Session.CurrentRunId); + Assert.Equal(0, f.Tasks.SubscriberCount); Assert.Single(f.Tasks.Stops); + } + + [Fact] + public async Task ObserverFailureStopsDerivedStateAfterTheAssignedGlyph() + { + var f = new Fixture(); + await f.Session.ToggleAsync(); f.Apply("component", true); + f.Observer = _ => throw new IOException("observer"); + Assert.Throws(() => f.Apply("component", false)); + Assert.Equal("\uE768", f.Session.TestButtonGlyph); + Assert.Equal("localized:StopTest", f.Session.TestButtonText); + Assert.True(f.Session.IsRunning); Assert.Equal(1, f.Tasks.SubscriberCount); + } + + [Fact] + public async Task ReentrantStopDuringGlyphNotificationRetainsOriginalOuterContinuation() + { + var f = new Fixture(); + await f.Session.ToggleAsync(); + bool entered = false; + f.Observer = name => + { + if (name == "TestButtonGlyph" && !entered) { entered = true; f.Session.Stop(); } + }; + f.Apply("component", true); + Assert.True(f.Session.IsRunning); Assert.Empty(f.Session.CurrentRunId); + Assert.Equal("\uE768", f.Session.TestButtonGlyph); + Assert.Equal("localized:StopTest", f.Session.TestButtonText); + Assert.Equal(0, f.Tasks.SubscriberCount); + } + + [Fact] + public async Task NullStateIsQueuedAndOnlyFailsWhenNonemptyCurrentIdIsInspected() + { + var f = new Fixture(); + await f.Session.ToggleAsync(); + f.Tasks.EmitRaw(null!); + Assert.Single(f.Queued); + Assert.Throws(() => f.Queued[0]()); + } + + private sealed class Fixture + { + public Fixture() + { + Tasks = new(Trace); + Session = new(Tasks, + () => { Trace.Add("selection"); return Select?.Invoke() ?? (HasComponent, ComponentId); }, + () => { Trace.Add("convert"); Convert?.Invoke(); }, + () => { Trace.Add("create"); return Create is null ? Config : Create(); }, + item => { Assert.Same(Config, item); Trace.Add("args"); return Format?.Invoke(item) ?? "--test"; }, + key => { Trace.Add("localize:" + key); return Localize?.Invoke(key) ?? "localized:" + key; }, + action => { if (AcceptEnqueue) Queued.Add(action); }); + Session.PropertyChanged += (sender, e) => + { + Assert.Same(Session, sender); + Events.Add(e.PropertyName!); Trace.Add("event:" + e.PropertyName); + Observer?.Invoke(e.PropertyName!); + }; + } + public bool HasComponent { get; set; } = true; + public string ComponentId { get; set; } = "component"; + public bool AcceptEnqueue { get; init; } = true; + public ConfigItem Config { get; } = new(); + public Func<(bool, string)>? Select { get; set; } + public Action? Convert { get; set; } + public Func? Create { get; set; } + public Func? Format { get; set; } + public Func? Localize { get; set; } + public Action? Observer { get; set; } + public List Trace { get; } = []; + public List Events { get; } = []; + public List Queued { get; } = []; + public TestTasks Tasks { get; } + public CreateConfigTestSession Session { get; } + public void Apply(string id, bool running) { Tasks.Emit(id, running); Queued[^1](); } + } + + private sealed class TestTasks(List trace) : ICreateConfigTestTasks + { + private Action>? _updated; + public event Action>? StateUpdated + { + add { trace.Add("add"); _updated += value; OnAdd?.Invoke(); } + remove { trace.Add("remove"); _updated -= value; } + } + public int SubscriberCount => _updated?.GetInvocationList().Length ?? 0; + public Action? OnAdd { get; set; } + public Func? StopAction { get; set; } + public Func? RunAction { get; set; } + public List Stops { get; } = []; + public List<(string Id, string Args)> Runs { get; } = []; + public Task StopAsync(string id) { trace.Add("stop:" + id); Stops.Add(id); return StopAction?.Invoke(id) ?? Task.CompletedTask; } + public Task RunAsync(string id, string args) { trace.Add("run:" + id + ":" + args); Runs.Add((id, args)); return RunAction?.Invoke(id, args) ?? Task.CompletedTask; } + public void Emit(string id, bool running) => EmitRaw(Tuple.Create(id, running)); + public void EmitRaw(Tuple state) => _updated?.Invoke(state); + } +} diff --git a/CDPIUI.Tests/Presentation/DiagnosticHighlightingUpdaterTests.cs b/CDPIUI.Tests/Presentation/DiagnosticHighlightingUpdaterTests.cs new file mode 100644 index 00000000..8674e4b6 --- /dev/null +++ b/CDPIUI.Tests/Presentation/DiagnosticHighlightingUpdaterTests.cs @@ -0,0 +1,297 @@ +using CDPIUI.Helper.UserExperience; + +namespace CDPIUI.Tests.Presentation; + +public class DiagnosticHighlightingUpdaterTests +{ + [Fact] + public void PlainValuesKeepErrorAndWarningOrder() + { + var updater = new DiagnosticHighlightingUpdater(); + List applied = []; + updater.Update("Black", false, () => new[] { 3, 2, 1, 4 }, + value => value % 2 == 1, value => value % 2 == 0, + value => value.ToString(), (light, errors, warnings) => applied.Add(new(light, errors, warnings))); + var result = Assert.Single(applied); + Assert.False(result.Light); + Assert.Equal(new[] { "3", "1" }, result.Errors); + Assert.Equal(new[] { "2", "4" }, result.Warnings); + } + + [Fact] + public void ReadsCurrentDiagnosticsTwiceAndFinishesErrorsBeforeWarnings() + { + var updater = new DiagnosticHighlightingUpdater(); + List trace = []; + int reads = 0; + updater.Update("Mica", true, + () => { trace.Add("get:" + ++reads); return reads == 1 ? new[] { "e", "i" } : new[] { "w" }; }, + item => { trace.Add("error:" + item); return item == "e"; }, + item => { trace.Add("warning:" + item); return true; }, + item => { trace.Add("token:" + item); return item; }, + (light, errors, warnings) => + { + trace.Add("apply"); Assert.True(light); + Assert.Equal(new[] { "e" }, errors); Assert.Equal(new[] { "w" }, warnings); + }); + Assert.Equal(new[] { "get:1", "error:e", "token:e", "error:i", "get:2", "warning:w", "token:w", "apply" }, trace); + } + + [Fact] + public void PredicateAndTokenCanReadDifferentCurrentSources() + { + var updater = new DiagnosticHighlightingUpdater(); + var node = new Node(new Source(true, false, "before")); + List applied = []; + updater.Update("Black", false, () => new[] { node }, + item => { bool selected = item.Current.Error; item.Current = new(false, true, "after"); return selected; }, + item => item.Current.Warning, item => item.Current.Token, + (light, errors, warnings) => applied.Add(new(light, errors, warnings))); + Assert.Equal(new[] { "after" }, Assert.Single(applied).Errors); + Assert.Equal(new[] { "after" }, applied[0].Warnings); + } + + [Fact] + public void ErrorTokensAreCapturedBeforeWarningCollectionMutatesSources() + { + var updater = new DiagnosticHighlightingUpdater(); + var node = new Node(new Source(true, false, "error")); + int reads = 0; + Snapshot? applied = null; + updater.Update("Black", false, + () => { if (++reads == 2) node.Current = new(false, true, "warning"); return new[] { node }; }, + item => item.Current.Error, item => item.Current.Warning, item => item.Current.Token, + (light, errors, warnings) => applied = new(light, errors, warnings)); + Assert.Equal(new[] { "error" }, applied!.Errors); + Assert.Equal(new[] { "warning" }, applied.Warnings); + } + + [Fact] + public void IdenticalKeyStillCollectsBothPassesBeforeSkippingApply() + { + var updater = new DiagnosticHighlightingUpdater(); + int reads = 0, predicates = 0, tokens = 0, applies = 0; + void Run() => updater.Update("Black", false, () => { reads++; return new[] { 1 }; }, + _ => { predicates++; return true; }, _ => { predicates++; return true; }, + _ => { tokens++; return "same"; }, (_, _, _) => applies++); + Run(); Run(); + Assert.Equal(4, reads); Assert.Equal(4, predicates); Assert.Equal(4, tokens); Assert.Equal(1, applies); + } + + [Fact] + public void UnselectedTokensAreNeverRead() + { + var updater = new DiagnosticHighlightingUpdater(); + updater.Update("Black", false, () => new[] { 1 }, _ => false, _ => false, + _ => throw new InvalidOperationException(), (_, errors, warnings) => + { Assert.Empty(errors); Assert.Empty(warnings); }); + } + + [Fact] + public void ArraysPreserveRawNullEmptyDuplicatesCaseAndOrder() + { + var updater = new DiagnosticHighlightingUpdater(); + string[] raw = [null!, "", "A", "a", "A", "x,y", "|"]; + Snapshot? result = null; + updater.Update("Black", false, () => raw, _ => true, _ => true, item => item, + (light, errors, warnings) => result = new(light, errors, warnings)); + Assert.Equal(raw, result!.Errors); Assert.Equal(raw, result.Warnings); + Assert.NotSame(raw, result.Errors); Assert.NotSame(result.Errors, result.Warnings); + } + + [Theory] + [InlineData("Black", false, "black", false)] + [InlineData("Black", false, "Black", true)] + [InlineData("Mica", true, "MicaSmoke", true)] + public void BackgroundAndLightArePartOfOrdinalKey(string first, bool firstLight, string next, bool nextLight) + { + var updater = new DiagnosticHighlightingUpdater(); List applied = []; + Run(updater, [], [], Capture(applied), first, firstLight); + Run(updater, [], [], Capture(applied), next, nextLight); + Assert.Equal(2, applied.Count); Assert.Equal(nextLight, applied[1].Light); + } + + [Theory] + [InlineData("A", "a")] + [InlineData("x", "y")] + public void TokenCaseAndValueChangesRebuild(string first, string next) + { + var updater = new DiagnosticHighlightingUpdater(); List applied = []; + Run(updater, [first], [], Capture(applied)); Run(updater, [next], [], Capture(applied)); + Assert.Equal(2, applied.Count); + } + + [Fact] + public void TokenOrderDuplicatesAndWarningChangesRebuild() + { + var updater = new DiagnosticHighlightingUpdater(); List applied = []; + Run(updater, ["a", "b"], [], Capture(applied)); + Run(updater, ["b", "a"], [], Capture(applied)); + Run(updater, ["b", "a", "a"], [], Capture(applied)); + Run(updater, ["b", "a", "a"], ["w"], Capture(applied)); + Assert.Equal(4, applied.Count); + } + + [Fact] + public void CommaDelimiterCollisionRetainsOriginalSkipBehavior() + { + var updater = new DiagnosticHighlightingUpdater(); List applied = []; + Run(updater, ["a,b"], [], Capture(applied)); + Run(updater, ["a", "b"], [], Capture(applied)); + Assert.Equal(new[] { "a,b" }, Assert.Single(applied).Errors); + } + + [Fact] + public void NullEmptyAndNoTokensShareOriginalKey() + { + var updater = new DiagnosticHighlightingUpdater(); List applied = []; + Run(updater, [], [], Capture(applied)); + Run(updater, [null!], [""], Capture(applied)); + Assert.Single(applied); + } + + [Fact] + public void PipeDelimiterCollisionAcrossSeveritiesRetainsOriginalSkip() + { + var updater = new DiagnosticHighlightingUpdater(); List applied = []; + Run(updater, ["a|b"], ["c"], Capture(applied)); + Run(updater, ["a"], ["b|c"], Capture(applied)); + Assert.Single(applied); + } + + [Fact] + public void ApplyFaultIsSameInstanceAndCommitsRequestedKey() + { + var updater = new DiagnosticHighlightingUpdater(); var fault = new InvalidOperationException("apply"); + Assert.Same(fault, Assert.Throws(() => Run(updater, ["x"], [], (_, _, _) => throw fault))); + Run(updater, ["x"], [], (_, _, _) => Assert.Fail("A failed apply still commits its key.")); + int calls = 0; Run(updater, ["y"], [], (_, _, _) => calls++); Assert.Equal(1, calls); + } + + [Theory] + [InlineData("first-get")] + [InlineData("second-get")] + [InlineData("error-predicate")] + [InlineData("warning-predicate")] + [InlineData("error-token")] + [InlineData("warning-token")] + [InlineData("error-enumeration")] + [InlineData("warning-enumeration")] + public void CollectionFaultDoesNotCommitNewKey(string stage) + { + var updater = new DiagnosticHighlightingUpdater(); var fault = new InvalidOperationException(stage); + Run(updater, ["old"], [], (_, _, _) => { }); + int reads = 0; + IEnumerable Values(bool fail) + { + yield return 1; + if (fail) throw fault; + } + var thrown = Assert.Throws(() => updater.Update("Black", false, + () => + { + reads++; + if ((reads == 1 && stage == "first-get") || (reads == 2 && stage == "second-get")) throw fault; + return Values(stage == (reads == 1 ? "error-enumeration" : "warning-enumeration")); + }, + _ => stage == "error-predicate" ? throw fault : true, + _ => stage == "warning-predicate" ? throw fault : true, + _ => stage == (reads == 1 ? "error-token" : "warning-token") ? throw fault : "new", + (_, _, _) => Assert.Fail("The collection fault must prevent apply."))); + Assert.Same(fault, thrown); + Run(updater, ["old"], [], (_, _, _) => Assert.Fail("The previous key must survive.")); + int calls = 0; Run(updater, ["new"], ["new"], (_, _, _) => calls++); Assert.Equal(1, calls); + } + + [Fact] + public void CommitPrecedesBoundedSameKeyCallbackReentry() + { + var updater = new DiagnosticHighlightingUpdater(); int calls = 0; + void Apply(bool light, string[] errors, string[] warnings) + { + calls++; + if (calls == 1) Run(updater, ["x"], [], Apply); + } + Run(updater, ["x"], [], Apply); + Assert.Equal(1, calls); + } + + [Fact] + public void DifferentCallbackReentryKeySurvivesOuterReturn() + { + var updater = new DiagnosticHighlightingUpdater(); List applied = []; + Run(updater, ["outer"], [], (_, _, _) => + { + applied.Add("outer"); Run(updater, ["inner"], [], (_, _, _) => applied.Add("inner")); + }); + Run(updater, ["inner"], [], (_, _, _) => Assert.Fail("The inner key must remain current.")); + Run(updater, ["outer"], [], (_, _, _) => applied.Add("outer-again")); + Assert.Equal(new[] { "outer", "inner", "outer-again" }, applied); + } + + [Fact] + public void ResetInCallbackSurvivesOuterReturn() + { + var updater = new DiagnosticHighlightingUpdater(); int calls = 0; + Run(updater, ["same"], [], (_, _, _) => { calls++; updater.Reset(); }); + Run(updater, ["same"], [], (_, _, _) => calls++); + Assert.Equal(2, calls); + } + + [Fact] + public void ResetForcesUnchangedKeyAndInstancesStayIndependent() + { + var first = new DiagnosticHighlightingUpdater(); var second = new DiagnosticHighlightingUpdater(); int calls = 0; + Action apply = (_, _, _) => calls++; + Run(first, [], [], apply); Run(second, [], [], apply); + first.Reset(); Run(first, [], [], apply); Run(second, [], [], apply); + Assert.Equal(3, calls); + } + + [Fact] + public void SameKeyCollectionReentryIsComparedAfterCollection() + { + var updater = new DiagnosticHighlightingUpdater(); int reads = 0, calls = 0; + updater.Update("Black", false, + () => { if (++reads == 1) Run(updater, ["x"], [], (_, _, _) => calls++); return new[] { "x" }; }, + _ => true, _ => false, item => item, (_, _, _) => calls++); + Assert.Equal(1, calls); + } + + [Fact] + public void DifferentCollectionReentryReplacesKeyBeforeOuterComparison() + { + var updater = new DiagnosticHighlightingUpdater(); int reads = 0; List applied = []; + Run(updater, ["outer"], [], (_, _, _) => { }); + updater.Update("Black", false, + () => { if (++reads == 1) Run(updater, ["inner"], [], (_, _, _) => applied.Add("inner")); return new[] { "outer" }; }, + _ => true, _ => false, item => item, (_, _, _) => applied.Add("outer")); + Assert.Equal(new[] { "inner", "outer" }, applied); + Run(updater, ["outer"], [], (_, _, _) => Assert.Fail("Outer apply is the last request.")); + } + + [Fact] + public void ResetDuringCollectionInvalidatesPreviouslyMatchingKey() + { + var updater = new DiagnosticHighlightingUpdater(); int reads = 0, calls = 0; + Run(updater, ["same"], [], (_, _, _) => { }); + updater.Update("Black", false, + () => { if (++reads == 2) updater.Reset(); return new[] { "same" }; }, + _ => true, _ => false, item => item, (_, _, _) => calls++); + Assert.Equal(1, calls); + } + + private static void Run(DiagnosticHighlightingUpdater updater, string[] errors, string[] warnings, + Action apply, string background = "Black", bool light = false) + { + int reads = 0; + updater.Update(background, light, () => ++reads == 1 ? errors : warnings, _ => true, _ => true, item => item, apply); + } + + private static Action Capture(List applied) => + (light, errors, warnings) => applied.Add(new(light, errors, warnings)); + + private sealed record Snapshot(bool Light, string[] Errors, string[] Warnings); + private sealed record Source(bool Error, bool Warning, string Token); + private sealed class Node(Source current) { public Source Current { get; set; } = current; } +} diff --git a/CDPIUI.Tests/Presentation/DispatcherTaskBridgeTests.cs b/CDPIUI.Tests/Presentation/DispatcherTaskBridgeTests.cs new file mode 100644 index 00000000..547b75f7 --- /dev/null +++ b/CDPIUI.Tests/Presentation/DispatcherTaskBridgeTests.cs @@ -0,0 +1,286 @@ +using CDPIUI.Helper.UserExperience; + +namespace CDPIUI.Tests.Presentation; + +public class DispatcherTaskBridgeTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task RunsDirectlyOrQueuesWithoutEagerOperationAndRetainsTheTrueResult(bool queued) + { + var f = new Fixture { Queue = queued }; + var task = f.Run(() => Task.CompletedTask); + Assert.Equal(queued ? ["access", "enqueue"] : ["access", "operation"], f.Trace); + Assert.Equal(!queued, task.IsCompleted); + if (queued) f.RunQueued(); + Assert.True(task.IsCompletedSuccessfully); + Assert.True(await Assert.IsAssignableFrom>(task)); + Assert.Equal(1, f.Calls); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task CompletionWaitsForTheOperationOnEitherDispatchPath(bool queued) + { + var pending = new TaskCompletionSource(); + var f = new Fixture { Queue = queued }; + var task = f.Run(() => pending.Task); + if (queued) f.RunQueued(); + Assert.False(task.IsCompleted); Assert.Equal(1, f.Calls); + pending.SetResult(true); + await task.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.True(task.IsCompletedSuccessfully); + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void ThrownOperationErrorsAreFaultsWithExactIdentityIncludingCancellation(bool queued, bool cancellation) + { + Exception expected = cancellation ? new OperationCanceledException("owned cancellation") : new InvalidOperationException("owned fault"); + var f = new Fixture { Queue = queued }; + var task = f.Run(() => throw expected); + if (queued) f.RunQueued(); + Assert.True(task.IsFaulted); Assert.False(task.IsCanceled); + Assert.Same(expected, task.Exception!.InnerException); + Assert.Same(expected, Record.Exception(() => task.GetAwaiter().GetResult())); + } + + [Fact] + public async Task AnAwaitedOperationFaultRetainsItsIdentityAfterSuspension() + { + var pending = new TaskCompletionSource(); + var expected = new InvalidOperationException("late operation fault"); + var task = new Fixture().Run(() => pending.Task); + Assert.False(task.IsCompleted); + pending.SetException(expected); + Assert.Same(expected, await Assert.ThrowsAsync(() => task.WaitAsync(TimeSpan.FromSeconds(5)))); + Assert.True(task.IsFaulted); + } + + [Fact] + public void AnAwaitedCanceledTaskBecomesAFaultAndRetainsItsCancellationToken() + { + using var source = new CancellationTokenSource(); source.Cancel(); + var task = new Fixture().Run(() => Task.FromCanceled(source.Token)); + Assert.True(task.IsFaulted); Assert.False(task.IsCanceled); + var error = Assert.IsType(task.Exception!.InnerException); + Assert.Equal(source.Token, error.CancellationToken); + } + + [Fact] + public void NullOperationTaskIsRecoveredAsAFaultInsteadOfEscapingTheDispatcherCallback() + { + var task = new Fixture().Run(() => null!); + Assert.True(task.IsFaulted); Assert.IsType(task.Exception!.InnerException); + } + + [Fact] + public void QueueRejectionCancelsWithTheDefaultTokenWithoutCallingTheOperation() + { + var f = new Fixture { Queue = true, Accepted = false }; + var task = f.Run(() => Task.CompletedTask); + Assert.True(task.IsCanceled); Assert.False(task.IsFaulted); Assert.Equal(0, f.Calls); + var error = Assert.Throws(() => task.GetAwaiter().GetResult()); + Assert.Equal(default, error.CancellationToken); + Assert.Equal(["access", "enqueue"], f.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void DispatcherPortErrorsRemainSynchronousAndDoNotInvokeTheOperation(bool enqueueError) + { + var expected = new InvalidOperationException("dispatcher port"); + var f = new Fixture { Queue = enqueueError }; + if (enqueueError) f.OnEnqueue = _ => throw expected; + else f.OnAccess = () => throw expected; + Assert.Same(expected, Assert.Throws(() => { _ = f.Run(() => Task.CompletedTask); })); + Assert.Equal(0, f.Calls); + Assert.Equal(enqueueError ? ["access", "enqueue"] : ["access"], f.Trace); + } + + [Fact] + public void ReadsCurrentThreadAccessForEachCall() + { + var f = new Fixture(); + var first = f.Run(() => Task.CompletedTask); + f.Queue = true; + var second = f.Run(() => Task.CompletedTask); + Assert.True(first.IsCompletedSuccessfully); Assert.False(second.IsCompleted); + Assert.Equal(1, f.Calls); f.RunQueued(); Assert.True(second.IsCompletedSuccessfully); + Assert.Equal(["access", "operation", "access", "enqueue", "operation"], f.Trace); + } + + [Fact] + public async Task ARepeatedCallbackKeepsTheFirstCompletionWithoutSuppressingLaterWork() + { + var f = new Fixture { Queue = true }; int runs = 0; + var task = f.Run(() => ++runs == 1 ? Task.CompletedTask : Task.FromException(new InvalidOperationException("later"))); + f.RunQueued(); f.RunQueued(); + Assert.Equal(2, runs); Assert.True(task.IsCompletedSuccessfully); + Assert.True(await Assert.IsAssignableFrom>(task)); + } + + [Fact] + public void InlineQueueExecutionBeforeAFalseReplyRetainsItsAlreadyCompletedResult() + { + var f = new Fixture { Queue = true, OnEnqueue = callback => { callback(); return false; } }; + var task = f.Run(() => Task.CompletedTask); + Assert.True(task.IsCompletedSuccessfully); Assert.Equal(1, f.Calls); + Assert.Equal(["access", "enqueue", "operation"], f.Trace); + } + + [Fact] + public async Task ExternalContinuationCannotRunInlineOnTheCompletionThread() + { + await Task.Run(() => + { + var previous = SynchronizationContext.Current; + SynchronizationContext.SetSynchronizationContext(null); + try + { + var pending = new TaskCompletionSource(); + var task = new Fixture().Run(() => pending.Task); + var scheduler = new ContinuationScheduler(); bool continued = false; + var continuation = task.ContinueWith(_ => continued = true, CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, scheduler); + pending.SetResult(true); + Assert.True(task.IsCompletedSuccessfully); + Assert.False(scheduler.InlineAttempted); Assert.False(continued); + scheduler.Drain(); + Assert.True(continued); Assert.True(continuation.IsCompletedSuccessfully); + } + finally { SynchronizationContext.SetSynchronizationContext(previous); } + }); + } + + [Fact] + public void AwaitedOperationRetainsTheCurrentSynchronizationContext() + { + var previous = SynchronizationContext.Current; + var context = new QueuedContext(); + try + { + SynchronizationContext.SetSynchronizationContext(context); + var pending = new TaskCompletionSource(); + var task = new Fixture().Run(() => pending.Task); + SynchronizationContext.SetSynchronizationContext(null); + pending.SetResult(true); + Assert.False(task.IsCompleted); Assert.Equal(1, context.PendingCount); + SynchronizationContext.SetSynchronizationContext(context); + context.Drain(); Assert.True(task.IsCompletedSuccessfully); + } + finally { SynchronizationContext.SetSynchronizationContext(previous); } + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void SynchronousActionsDoNotEnterAsyncVoidLifecycleEvenWhenTheContextRejectsIt(bool queued, bool rejecting) + { + var previous = SynchronizationContext.Current; + var context = new LifecycleContext { Reject = rejecting }; + try + { + SynchronizationContext.SetSynchronizationContext(context); + var f = new Fixture { Queue = queued }; int operations = 0; + var task = f.RunSynchronous(() => operations++); + if (queued) { Assert.False(task.IsCompleted); f.RunQueued(); } + Assert.True(task.IsCompletedSuccessfully); Assert.Equal(1, operations); + Assert.Equal(0, context.Started); Assert.Equal(0, context.Completed); + } + finally { SynchronizationContext.SetSynchronizationContext(previous); } + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void SynchronousActionErrorsRemainFaultsWithoutEnteringAsyncVoidLifecycle(bool queued, bool cancellation) + { + var previous = SynchronizationContext.Current; + var context = new LifecycleContext { Reject = true }; + Exception expected = cancellation ? new OperationCanceledException("sync cancel") : new InvalidOperationException("sync error"); + try + { + SynchronizationContext.SetSynchronizationContext(context); + var f = new Fixture { Queue = queued }; + var task = f.RunSynchronous(() => throw expected); + if (queued) f.RunQueued(); + Assert.True(task.IsFaulted); Assert.False(task.IsCanceled); + Assert.Same(expected, task.Exception!.InnerException); + Assert.Equal(0, context.Started); Assert.Equal(0, context.Completed); + } + finally { SynchronizationContext.SetSynchronizationContext(previous); } + } + + [Fact] + public async Task SynchronousActionCompletionAlsoQueuesExternalContinuations() + { + await Task.Run(() => + { + var f = new Fixture { Queue = true }; + var task = f.RunSynchronous(() => { }); + var scheduler = new ContinuationScheduler(); bool continued = false; + var continuation = task.ContinueWith(_ => continued = true, CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, scheduler); + f.RunQueued(); + Assert.True(task.IsCompletedSuccessfully); Assert.False(scheduler.InlineAttempted); Assert.False(continued); + scheduler.Drain(); Assert.True(continued); Assert.True(continuation.IsCompletedSuccessfully); + }); + } + + private sealed class Fixture + { + public bool Queue, Accepted = true; + public int Calls; + public Action? Queued; + public Func? OnAccess; + public Func? OnEnqueue; + public List Trace { get; } = []; + public Task Run(Func operation) => DispatcherTaskBridge.Run( + () => { Calls++; Trace.Add("operation"); return operation(); }, + ReadAccess, Enqueue); + public Task RunSynchronous(Action operation) => DispatcherTaskBridge.Run( + () => { Calls++; Trace.Add("operation"); operation(); }, ReadAccess, Enqueue); + private bool ReadAccess() { Trace.Add("access"); return OnAccess?.Invoke() ?? !Queue; } + private bool Enqueue(Action callback) { Trace.Add("enqueue"); Queued = callback; return OnEnqueue?.Invoke(callback) ?? Accepted; } + public void RunQueued() => Queued!(); + } + + private sealed class LifecycleContext : SynchronizationContext + { + public bool Reject; + public int Started, Completed; + public override void OperationStarted() + { Started++; if (Reject) throw new InvalidOperationException("owned async-void rejection"); } + public override void OperationCompleted() => Completed++; + } + + private sealed class ContinuationScheduler : TaskScheduler + { + private readonly Queue _pending = new(); + public bool InlineAttempted; + protected override IEnumerable GetScheduledTasks() => _pending.ToArray(); + protected override void QueueTask(Task task) => _pending.Enqueue(task); + protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) + { InlineAttempted = true; return TryExecuteTask(task); } + public void Drain() { while (_pending.TryDequeue(out var task)) TryExecuteTask(task); } + } + + private sealed class QueuedContext : SynchronizationContext + { + private readonly Queue<(SendOrPostCallback Callback, object? State)> _pending = new(); + public int PendingCount => _pending.Count; + public override void Post(SendOrPostCallback callback, object? state) => _pending.Enqueue((callback, state)); + public void Drain() { while (_pending.TryDequeue(out var item)) item.Callback(item.State); } + } +} diff --git a/CDPIUI.Tests/Presentation/GraphicDesignerCommandCodecTests.cs b/CDPIUI.Tests/Presentation/GraphicDesignerCommandCodecTests.cs new file mode 100644 index 00000000..8d2de6cc --- /dev/null +++ b/CDPIUI.Tests/Presentation/GraphicDesignerCommandCodecTests.cs @@ -0,0 +1,442 @@ +using System.Collections.ObjectModel; +using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.Views.CreateConfigHelper; + +namespace CDPIUI.Tests.Presentation; + +public class GraphicDesignerCommandCodecTests +{ + [Theory] + [InlineData("/Program Files/lists/hosts.txt", false, false)] + [InlineData("/Program Files/lists/hosts.txt", true, false)] + [InlineData("/Program Files/lists/hosts.txt", false, true)] + [InlineData("/Program Files/lists/hosts.txt", true, true)] + [InlineData("-team lists/hosts.txt", false, false)] + [InlineData("-team lists/hosts.txt", true, false)] + [InlineData("-team lists/hosts.txt", false, true)] + [InlineData("-team lists/hosts.txt", true, true)] + [InlineData("-team lists=2026/hosts.txt", false, false)] + [InlineData("-team lists=2026/hosts.txt", true, false)] + public void QuotedPathPrefixesKeepTheirSingleValueAcrossRepeatedDesignerVisits(string path, bool inline, bool known) + { + ObservableCollection items = known ? [Item("--blacklist", "file_path")] : []; + string command = "--blacklist" + (inline ? "=" : " ") + "\"" + path + "\""; + string expected = "--blacklist" + (known ? "=" : " ") + "\"" + path + "\" "; + + for (int visit = 0; visit < 3; visit++) + { + string additional = GraphicDesignerCommandCodec.Parse(items, [], command); + command = GraphicDesignerCommandCodec.Build(items, [], additional); + Assert.Equal(expected, command); + } + } + + [Theory] + [InlineData("--port=1443", "--port", "integer", 0)] + [InlineData("--port=1443", "--port", "integer", 1)] + [InlineData("--port=1443", "--port", "integer", 2)] + [InlineData("/port=1443", "/port", "integer", 0)] + [InlineData("/port=1443", "/port", "integer", 1)] + [InlineData("/port=1443", "/port", "integer", 2)] + [InlineData("-p", "-p", "flag", 0)] + [InlineData("-p", "-p", "flag", 1)] + [InlineData("-p", "-p", "flag", 2)] + public void AnUnknownInlineFilenameNeverTurnsIntoAKnownOptionOnLaterVisits(string path, string option, string type, int syntax) + { + var other = Item(option, type); + ObservableCollection items = [other]; + string value = syntax == 0 ? "\"" + path + "\"" : path; + string expected = "--blacklist=" + value + " "; + string command = syntax == 1 ? "\"--blacklist=" + path + "\"" : "--blacklist=" + value; + + for (int visit = 0; visit < 3; visit++) + { + string additional = GraphicDesignerCommandCodec.Parse(items, [], command); + command = GraphicDesignerCommandCodec.Build(items, [], additional); + Assert.Equal(expected, command); + Assert.False(other.IsChecked); + Assert.Equal("", other.Value); + } + } + + [Theory] + [InlineData("--port=1443", "--port", "integer", "1443", "-p --port=1443 ")] + [InlineData("--file=/Program Files/lists/hosts.txt", "--file", "file_path", "\"/Program Files/lists/hosts.txt\"", "-p --file=\"/Program Files/lists/hosts.txt\" ")] + public void AWholeQuotedRealOptionAfterABareFlagStillHasItsOwnModel(string argument, string name, string type, string value, string expected) + { + var flag = Item("-p"); + var option = Item(name, type); + ObservableCollection items = [flag, option]; + string command = "-p \"" + argument + "\""; + + for (int visit = 0; visit < 3; visit++) + { + string additional = GraphicDesignerCommandCodec.Parse(items, [], command); + command = GraphicDesignerCommandCodec.Build(items, [], additional); + Assert.Equal(expected, command); + Assert.True(flag.IsChecked); + Assert.True(option.IsChecked); + Assert.Equal(value, option.Value); + } + } + + [Theory] + [InlineData("--port", "integer", "--port=\"1443\"")] + [InlineData("--file", "file_path", "--file=\"old.txt\"")] + public void ClearingAParsedQuotedValueRetainsTheLegacyBareFlag(string name, string type, string input) + { + var item = Item(name, type); + GraphicDesignerCommandCodec.Parse([item], [], input); + + item.Value = ""; + + Assert.Equal(name + " ", GraphicDesignerCommandCodec.Build([item], [], "")); + } + + [Fact] + public void ReassigningTheSameParsedEmptyValueKeepsItsExplicitEmptyArgument() + { + var item = Item("--value", "string"); + GraphicDesignerCommandCodec.Parse([item], [], "--value \"\""); + + item.Value = item.Value; + + Assert.Equal("--value=\"\" ", GraphicDesignerCommandCodec.Build([item], [], "")); + } + + [Fact] + public void EditingAwayAndBackDoesNotRestoreAnOldGroupingHint() + { + var item = Item("--value", "string"); + GraphicDesignerCommandCodec.Parse([item], [], "--value \"\""); + + item.Value = "other"; + item.Value = ""; + + Assert.Equal("--value ", GraphicDesignerCommandCodec.Build([item], [], "")); + } + + [Fact] + public void ValueNotificationsObserveTheCorrectGroupingForParsingAndExternalEdits() + { + var item = Item("--value", "string"); + List commands = []; + item.PropertyChanged += (_, args) => + { + if (args.PropertyName == "Value") commands.Add(GraphicDesignerCommandCodec.Build([item], [], "")); + }; + + GraphicDesignerCommandCodec.Parse([item], [], "--value \"alpha beta\""); + item.Value = ""; + + Assert.Equal(["--value=\"alpha beta\" ", "--value "], commands); + } + + [Fact] + public void AWholeQuotedOptionAfterAValuelessFlagIsNotConsumedAsTheFlagValue() + { + var flag = Item("-p"); + var port = Item("--port", "integer"); + + string extra = GraphicDesignerCommandCodec.Parse([flag, port], [], "-p \"--port=1443\""); + + Assert.True(flag.IsChecked); + Assert.True(port.IsChecked); + Assert.Equal("1443", port.Value); + Assert.Equal("-p --port=1443 ", GraphicDesignerCommandCodec.Build([flag, port], [], extra)); + } + + [Fact] + public void DynamicFactoriesReceiveDecodedTelegramScalars() + { + Dictionary values = []; + + GraphicDesignerCommandCodec.Parse([], [], "--host \"127.0.0.1\" --port \"1443\" --secret \"abcdef\"", false, + (name, value) => { values[name] = value.Text; return true; }); + + Assert.Equal("127.0.0.1", values["--host"]); + Assert.Equal("1443", values["--port"]); + Assert.True(int.TryParse(values["--port"], out int port)); + Assert.Equal(1443, port); + Assert.Equal("abcdef", values["--secret"]); + } + + [Theory] + [InlineData("fast", "--mode=fast ")] + [InlineData("very fast", "--mode=\"very fast\" ")] + public void QuotedEnumValuesStillMatchTheirActualValue(string value, string expected) + { + var item = Item("--mode", "enum"); + item.AvailableEnumValues = [new() { DisplayName = "Choice", ActualValue = value }]; + + string extra = GraphicDesignerCommandCodec.Parse([item], [], $"--mode \"{value}\""); + + Assert.Equal(value, item.Value); + Assert.NotNull(item.AvailableEnumValues.FirstOrDefault(choice => choice.ActualValue == item.Value)); + Assert.Equal(expected, GraphicDesignerCommandCodec.Build([item], [], extra)); + } + + [Fact] + public void UnknownInlineQuotedFileRetainsItsClosingQuoteThroughTheDesignerRoundTrip() + { + ObservableCollection items = []; + + string additional = GraphicDesignerCommandCodec.Parse(items, [], "--blacklist=\"C:\\smoke\\fixture-list.txt\""); + string result = GraphicDesignerCommandCodec.Build(items, [], additional); + + Assert.Equal("--blacklist \"C:\\smoke\\fixture-list.txt\" ", result); + } + + [Theory] + [InlineData("--file", "--file=\"C:\\my files\\list.txt\"", true, "--file=\"C:\\my files\\list.txt\" ")] + [InlineData("--file", "--file \"C:\\my files\\list.txt\"", true, "--file=\"C:\\my files\\list.txt\" ")] + [InlineData("--file", "--file=\"C:\\my files\\list.txt\"", false, "--file \"C:\\my files\\list.txt\" ")] + [InlineData("--file", "--file \"C:\\my files\\list.txt\"", false, "--file \"C:\\my files\\list.txt\" ")] + [InlineData("--file", "\"--file=C:\\my files\\list.txt\"", true, "--file=\"C:\\my files\\list.txt\" ")] + [InlineData("--file", "\"--file=C:\\my files\\list.txt\"", false, "--file \"C:\\my files\\list.txt\" ")] + [InlineData("-f", "-f=\"C:\\my files\\list.txt\"", true, "-f=\"C:\\my files\\list.txt\" ")] + [InlineData("-f", "-f=\"C:\\my files\\list.txt\"", false, "-f \"C:\\my files\\list.txt\" ")] + [InlineData("/file", "/file=\"C:\\my files\\list.txt\"", false, "/file \"C:\\my files\\list.txt\" ")] + [InlineData("--value", "--value=\"a=b c=d\"", true, "--value=\"a=b c=d\" ")] + [InlineData("--value", "--value \"a=b c=d\"", true, "--value=\"a=b c=d\" ")] + [InlineData("--value", "--value=\"\"", true, "--value=\"\" ")] + [InlineData("--value", "--value \"\"", false, "--value \"\" ")] + [InlineData("--value", "\"--value=\"", true, "--value=\"\" ")] + [InlineData("--value", "\"--value=\"", false, "--value \"\" ")] + public void QuotedValuesSurviveTheDesignerRoundTrip(string name, string input, bool known, string expected) + { + ObservableCollection items = known ? [Item(name, "string")] : []; + + string additional = GraphicDesignerCommandCodec.Parse(items, [], input); + string result = GraphicDesignerCommandCodec.Build(items, [], additional); + + Assert.Equal(expected, result); + Assert.Equal(expected.Trim(), ComponentCommandLineFormatter.ToSingleLine(ComponentCommandLineFormatter.FormatByFlags(result.Trim()))); + } + + [Fact] + public void DynamicModelModeReceivesTheCompleteQuotedValue() + { + ObservableCollection items = []; + string additional = GraphicDesignerCommandCodec.Parse(items, [], "--value=\"quoted value\"", false, + (name, value) => + { + var item = Item(name, "string"); + item.IsChecked = true; + item.SetParsedValue(value.Text, value.PreserveGrouping); + items.Add(item); + return true; + }); + + Assert.Equal("--value=\"quoted value\" ", GraphicDesignerCommandCodec.Build(items, [], additional)); + } + + [Fact] + public void ExistingRepairOfAnIncompleteKnownQuotedValueIsRetained() + { + var item = Item("--value", "string"); + + GraphicDesignerCommandCodec.Parse([item], [], "--value=\"unfinished"); + + Assert.Equal("\"unfinished\"", item.Value); + } + + [Fact] + public void ParseSelectsKnownFlagsAndKeepsTheRestInInputOrderWithTrailingSpaces() + { + var flag = Item("-p"); + var text = Item("--port", "integer"); + ObservableCollection items = [flag, text]; + + string extra = GraphicDesignerCommandCodec.Parse(items, [], "-p --unknown=value --port 443 --other raw"); + + Assert.True(flag.IsChecked); + Assert.Equal("", flag.Value); + Assert.True(text.IsChecked); + Assert.Equal("443", text.Value); + Assert.Equal("--unknown value --other raw ", extra); + } + + [Fact] + public void ParseClearsChecksButRetainsUnmentionedValuesAndTheSelectedExclusiveGuid() + { + var ordinary = Item("--ordinary"); + var child = Item("--child", guid: "selected"); + ordinary.IsChecked = child.IsChecked = true; + ordinary.Value = child.Value = "previous"; + var group = new GraphicDesignerExclusiveSettingItemModel { Guid = "group", SelectedItemGuid = "selected", Items = [child] }; + + GraphicDesignerCommandCodec.Parse([ordinary], [group], "--unknown"); + + Assert.False(ordinary.IsChecked); + Assert.False(child.IsChecked); + Assert.Equal("previous", ordinary.Value); + Assert.Equal("previous", child.Value); + Assert.Equal("selected", group.SelectedItemGuid); + } + + [Fact] + public void OrdinaryMatchingIsCaseSensitiveAndTheLastOccurrenceWins() + { + var item = Item("--value", "string"); + + string extra = GraphicDesignerCommandCodec.Parse([item], [], "--value=first --value=last --VALUE=unknown"); + + Assert.Equal("last", item.Value); + Assert.Equal("--VALUE unknown ", extra); + } + + [Fact] + public void OrdinaryItemsTakePrecedenceOverExclusiveGroups() + { + var ordinary = Item("--same", "string"); + var child = Item("--same", "string", "child"); + var group = new GraphicDesignerExclusiveSettingItemModel { Items = [child], SelectedItemGuid = "old" }; + + GraphicDesignerCommandCodec.Parse([ordinary], [group], "--same=value"); + + Assert.True(ordinary.IsChecked); + Assert.False(child.IsChecked); + Assert.Equal("old", group.SelectedItemGuid); + } + + [Fact] + public void OnlyTheFirstMatchingExclusiveGroupIsSelected() + { + var first = Item("--mode", "string", "first"); + var second = Item("--mode", "string", "second"); + var group1 = new GraphicDesignerExclusiveSettingItemModel { Items = [first] }; + var group2 = new GraphicDesignerExclusiveSettingItemModel { Items = [second], SelectedItemGuid = "old" }; + + Assert.Equal("", GraphicDesignerCommandCodec.Parse([], [group1, group2], "--mode=fast")); + + Assert.True(first.IsChecked); + Assert.Equal("fast", first.Value); + Assert.Equal("first", group1.SelectedItemGuid); + Assert.False(second.IsChecked); + Assert.Equal("old", group2.SelectedItemGuid); + } + + [Fact] + public void DynamicModelModeCallsTheFactoryInOrderEvenForExistingNames() + { + ObservableCollection items = [Item("--known")]; + List<(string Name, string Value)> calls = []; + + string extra = GraphicDesignerCommandCodec.Parse(items, [], "--known=a=b --other=c --known=d", false, + (name, value) => + { + calls.Add((name, value.Text)); + if (name != "--known") return false; + items.Add(Item(name)); + return true; + }); + + Assert.Equal(new[] { ("--known", "a=b"), ("--other", "c"), ("--known", "d") }, calls); + Assert.Equal(3, items.Count); + Assert.Equal("--other c ", extra); + } + + [Fact] + public void ExistingModelModeDoesNotCallADynamicFactory() + { + string extra = GraphicDesignerCommandCodec.Parse([], [], "--unknown", true, + (_, _) => throw new InvalidOperationException("must remain lazy")); + + Assert.Equal("--unknown ", extra); + } + + [Fact] + public void SeparateValuesStartingWithADashOrSlashRetainTheLegacyOptionBoundary() + { + var amount = Item("--amount", "integer"); + var path = Item("--path", "file_path"); + var plain = Item("--plain", "string"); + + string extra = GraphicDesignerCommandCodec.Parse([amount, path, plain], [], "--amount -2 --path /root --plain value"); + + Assert.Equal("", amount.Value); + Assert.Equal("", path.Value); + Assert.Equal("value", plain.Value); + Assert.Equal("-2 /root ", extra); + } + + [Fact] + public void ValuesContainingEqualsAreAlreadyPreservedAfterTheFirstSeparator() + { + var item = Item("--known", "string"); + + string extra = GraphicDesignerCommandCodec.Parse([item], [], "--known=a=b== --unknown=c=d=="); + + Assert.Equal("a=b==", item.Value); + Assert.Equal("--unknown c=d== ", extra); + } + + [Fact] + public void AWholeQuotedOptionWithoutSpacesRetainsItsRecognizedName() + { + var item = Item("--known", "string"); + + Assert.Equal("", GraphicDesignerCommandCodec.Parse([item], [], "\"--known=value\"")); + Assert.Equal("value", item.Value); + } + + [Fact] + public void KnownInlineQuotedValuesKeepTheirQuotePair() + { + var item = Item("--file", "file_path"); + + Assert.Equal("", GraphicDesignerCommandCodec.Parse([item], [], "--file=\"C:\\my files\\list.txt\"")); + + Assert.Equal("\"C:\\my files\\list.txt\"", item.Value); + Assert.Equal("--file=\"C:\\my files\\list.txt\" ", GraphicDesignerCommandCodec.Build([item], [], "")); + } + + [Theory] + [InlineData("string", true, false, "--value=42 ")] + [InlineData("integer", true, false, "--value=42 ")] + [InlineData("file_path", true, false, "--value=42 ")] + [InlineData("enum", false, false, "--value=42 ")] + [InlineData("custom", true, false, "--value ")] + [InlineData("custom", true, true, "--value=42 ")] + public void BuildRetainsTypeSpecificValueAndEnumRules(string type, bool isChecked, bool textInput, string expected) + { + var item = Item("--value", type); + item.IsChecked = isChecked; + item.EnableTextInput = textInput; + item.Value = "42"; + + Assert.Equal(expected, GraphicDesignerCommandCodec.Build([item], [], "")); + } + + [Fact] + public void BuildUsesCollectionOrderThenExactSelectedGuidThenAdditionalTextVerbatim() + { + var first = Item("--first"); + var second = Item("--second", "string"); + var selected = Item("--selected", "string", "chosen"); + var differentCase = Item("--different-case", "enum", "CHOSEN"); + first.IsChecked = second.IsChecked = selected.IsChecked = true; + second.Value = "text"; + selected.Value = "group"; + var group = new GraphicDesignerExclusiveSettingItemModel { Items = [differentCase, selected], SelectedItemGuid = "chosen" }; + + Assert.Equal("--first --second=text --selected=group extra ", + GraphicDesignerCommandCodec.Build([first, second], [group], " extra ")); + } + + [Fact] + public void BuildSkipsUncheckedNonEnumAndAnUnselectedExclusiveGroup() + { + var child = Item("--child"); + child.IsChecked = true; + var group = new GraphicDesignerExclusiveSettingItemModel { Items = [child], SelectedItemGuid = "other" }; + + Assert.Equal("extra", GraphicDesignerCommandCodec.Build([Item("--unchecked")], [group], "extra")); + } + + private static GraphicDesignerSettingItemModel Item(string name, string type = "flag", string? guid = null) => new() + { + Guid = guid ?? name, DisplayName = name, Type = type, + }; +} diff --git a/CDPIUI.Tests/Presentation/NamedValueCollectionLoaderTests.cs b/CDPIUI.Tests/Presentation/NamedValueCollectionLoaderTests.cs new file mode 100644 index 00000000..02bcb963 --- /dev/null +++ b/CDPIUI.Tests/Presentation/NamedValueCollectionLoaderTests.cs @@ -0,0 +1,200 @@ +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using CDPIUI.Helper.UserExperience; + +namespace CDPIUI.Tests.Presentation; + +public class NamedValueCollectionLoaderTests +{ + [Fact] + public void LoadsRawAssignmentsThenNamedRowsWithoutNormalizationOrDeduplication() + { + var f = new Fixture + { + Assignments = ["%A%=one=two", "skip:ignored=value", "no separator", "=", "A=ordinary"], + Named = [new("A", "named")] + }; + f.Load(); + Assert.Equal([new Row("%A%", "one=two"), new Row("", ""), new Row("A", "ordinary"), new Row("A", "named")], f.Rows); + Assert.Equal(["clear", "assignments", "assignments", "skip:%A%=one=two", "assignment:%A%:one=two", "add:%A%", + "skip:skip:ignored=value", "skip:no separator", "skip:=", "assignment::", "add:", "skip:A=ordinary", + "assignment:A:ordinary", "add:A", "named", "named", "pair:A", "add:A"], f.Trace); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ClearsEvenAnEmptyDestinationAndPreservesNullVersusEmptyReadCounts(bool nullSources) + { + var f = new Fixture { Assignments = nullSources ? null : [], Named = nullSources ? null : [] }; + f.Load(); + Assert.Empty(f.Rows); + Assert.Equal(nullSources ? ["clear", "assignments", "named"] : ["clear", "assignments", "assignments", "named", "named"], f.Trace); + } + + [Fact] + public void ClearObserverCanReplaceTheSourceBeforeItsFirstRead() + { + var f = new Fixture { Assignments = ["old=value"] }; + f.Rows.Add(new("stale", "row")); f.Trace.Clear(); + f.OnStep = step => { if (step == "clear") f.Assignments = ["new=value"]; }; + f.Load(); + Assert.Equal(new Row("new", "value"), Assert.Single(f.Rows)); + Assert.Equal("clear", f.Trace[0]); + } + + [Fact] + public void AssignmentAddCanReplaceTheNamedSourceBeforeTheSecondPhase() + { + var f = new Fixture { Assignments = ["ordinary=value"], Named = [new("old", "pair")] }; + f.OnStep = step => { if (step == "add:ordinary") f.Named = [new("new", "pair")]; }; + f.Load(); + Assert.Equal([new Row("ordinary", "value"), new Row("new", "pair")], f.Rows); + Assert.True(f.Trace.IndexOf("add:ordinary") < f.Trace.IndexOf("named")); + } + + [Fact] + public void EachNamedFactoryReadsMetadataAfterThePreviousAddObserver() + { + object first = new(), second = new(); + var f = new Fixture { Named = [new("one", "1"), new("two", "2")] }; + object current = first; + f.NamedFactory = pair => new(pair.Key, pair.Value, current); + f.OnStep = step => { if (step == "add:one") current = second; }; + f.Load(); + Assert.Same(first, f.Rows[0].Metadata); Assert.Same(second, f.Rows[1].Metadata); + } + + [Theory] + [InlineData("skip:A=value")] + [InlineData("assignment:A:value")] + [InlineData("add:A")] + public void OrdinaryErrorsEscapeWithTheirIdentityAndPreventTheNamedPhase(string failingStep) + { + var error = new InvalidOperationException(failingStep); + var f = new Fixture { Assignments = ["A=value", "later=value"], Named = [new("named", "value")] }; + f.OnStep = step => { if (step == failingStep) throw error; }; + Assert.Same(error, Assert.Throws(f.Load)); + Assert.DoesNotContain("named", f.Trace); Assert.Empty(f.Errors); + Assert.Equal(failingStep == "add:A" ? 1 : 0, f.Rows.Count); + } + + [Theory] + [InlineData("pair:bad")] + [InlineData("add:bad")] + public void NamedFactoryAndAddErrorsReportTheSameErrorAndContinueWithPartialEffects(string failingStep) + { + var error = new InvalidOperationException(failingStep); + var f = new Fixture { Named = [new("bad", "first"), new("good", "second")] }; + f.OnStep = step => { if (step == failingStep) throw error; }; + f.Load(); + Assert.Same(error, Assert.Single(f.Errors)); + Assert.Equal("good", f.Rows[^1].Name); + Assert.Equal(failingStep == "add:bad" ? 2 : 1, f.Rows.Count); + } + + [Fact] + public void AReportingErrorEscapesAndStopsFurtherNamedItems() + { + var original = new InvalidOperationException("factory"); + var reportError = new ApplicationException("report"); + var f = new Fixture { Named = [new("bad", "1"), new("later", "2")] }; + f.NamedFactory = _ => throw original; + f.OnStep = step => { if (step == "report") throw reportError; }; + Assert.Same(reportError, Assert.Throws(f.Load)); + Assert.Same(original, Assert.Single(f.Errors)); Assert.DoesNotContain("pair:later", f.Trace); + } + + [Fact] + public void NamedIteratorErrorsEscapeOutsideThePerItemRecovery() + { + var error = new InvalidOperationException("iterator"); + var f = new Fixture { Named = FailAfterFirst(error) }; + Assert.Same(error, Assert.Throws(f.Load)); + Assert.Equal(new Row("first", "value"), Assert.Single(f.Rows)); Assert.Empty(f.Errors); + } + + [Fact] + public void MutatingTheActiveAssignmentListRetainsItsEnumerationFailure() + { + var source = new List { "first=value", "second=value" }; + var f = new Fixture { Assignments = source, Named = [new("named", "value")] }; + f.OnStep = step => { if (step == "add:first") source.Add("third=value"); }; + Assert.Throws(f.Load); + Assert.Equal("first", Assert.Single(f.Rows).Name); Assert.Empty(f.Errors); Assert.DoesNotContain("named", f.Trace); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void NonNullSourceIsReadAgainForEnumeration(bool namedPhase) + { + var f = new Fixture(); int reads = 0; + if (namedPhase) f.ReadNamed = () => ++reads == 1 ? [new("old", "value")] : [new("current", "value")]; + else f.ReadAssignments = () => ++reads == 1 ? ["old=value"] : ["current=value"]; + f.Load(); + Assert.Equal(2, reads); Assert.Equal("current", Assert.Single(f.Rows).Name); + } + + [Theory] + [InlineData(false, 1)] + [InlineData(false, 2)] + [InlineData(true, 1)] + [InlineData(true, 2)] + public void SourceReadErrorsEscapeWithoutBeingReported(bool namedPhase, int failingRead) + { + var error = new InvalidOperationException("source read"); + var f = new Fixture(); int reads = 0; + if (namedPhase) f.ReadNamed = () => ++reads == failingRead ? throw error : []; + else f.ReadAssignments = () => ++reads == failingRead ? throw error : []; + Assert.Same(error, Assert.Throws(f.Load)); + Assert.Equal("clear", f.Trace[0]); Assert.Empty(f.Errors); Assert.Empty(f.Rows); + } + + [Fact] + public void ClearObserverErrorEscapesBeforeAnySourceRead() + { + var error = new InvalidOperationException("clear"); var f = new Fixture(); + f.Rows.Add(new("old", "value")); f.Trace.Clear(); + f.OnStep = _ => throw error; + Assert.Same(error, Assert.Throws(f.Load)); + Assert.Equal(["clear"], f.Trace); Assert.Empty(f.Rows); Assert.Empty(f.Errors); + } + + private static IEnumerable> FailAfterFirst(Exception error) + { + yield return new("first", "value"); + throw error; + } + + private sealed record Row(string Name, string Value, object? Metadata = null); + + private sealed class Fixture + { + public ObservableCollection Rows { get; } = []; + public List Trace { get; } = []; + public List Errors { get; } = []; + public IEnumerable? Assignments = []; + public IEnumerable>? Named = []; + public Func?>? ReadAssignments; + public Func>?>? ReadNamed; + public Func, Row>? NamedFactory; + public Action? OnStep; + + public Fixture() + { + Rows.CollectionChanged += (_, e) => Step(e.Action == NotifyCollectionChangedAction.Reset + ? "clear" : "add:" + ((Row)e.NewItems![0]!).Name); + } + + private void Step(string step) { Trace.Add(step); OnStep?.Invoke(step); } + + public void Load() => NamedValueCollectionLoader.Load(Rows, + () => { Step("assignments"); return (ReadAssignments is null ? Assignments : ReadAssignments())!; }, + raw => { Step("skip:" + raw); return raw.StartsWith("skip:", StringComparison.Ordinal); }, + (name, value) => { Step("assignment:" + name + ":" + value); return new Row(name, value); }, + () => { Step("named"); return (ReadNamed is null ? Named : ReadNamed())!; }, + pair => { Step("pair:" + pair.Key); return NamedFactory?.Invoke(pair) ?? new Row(pair.Key, pair.Value); }, + error => { Errors.Add(error); Step("report"); }); + } +} diff --git a/CDPIUI.Tests/Presentation/PostOrderTreePrunerTests.cs b/CDPIUI.Tests/Presentation/PostOrderTreePrunerTests.cs new file mode 100644 index 00000000..f12bcef5 --- /dev/null +++ b/CDPIUI.Tests/Presentation/PostOrderTreePrunerTests.cs @@ -0,0 +1,218 @@ +using System.Collections.ObjectModel; +using CDPIUI.Helper.UserExperience; + +namespace CDPIUI.Tests.Presentation; + +public class PostOrderTreePrunerTests +{ + [Fact] + public void PlainValueNodesNeedNoUiOrDomainTypes() + { + List roots = [1]; Dictionary> children = new() { [1] = new List { 2 }, [2] = new List() }; + List removed = []; + PostOrderTreePruner.Prune(roots, value => children[value], _ => false, removed.Add); + Assert.Equal(new[] { 2, 1 }, removed); Assert.Empty(roots); Assert.Empty(children[1]); + } + + [Fact] + public void EmptyListDoesNotReadAnyCallback() + { + PostOrderTreePruner.Prune(new List(), null!, null!, null!); + } + + [Fact] + public void RootsAndChildrenRunBackwardsWithRetentionAfterDescendants() + { + var a = new Node("a"); var b = new Node("b"); var c = new Node("c"); var d = new Node("d"); + a.Children.AddRange([b, c]); List roots = [a, d]; List trace = []; + PostOrderTreePruner.Prune(roots, node => { trace.Add("children:" + node.Name); return node.Children; }, + node => { trace.Add("retain:" + node.Name); return false; }, node => trace.Add("remove:" + node.Name)); + Assert.Equal(new[] { "children:d", "retain:d", "remove:d", "children:a", "children:c", "retain:c", "remove:c", + "children:b", "retain:b", "remove:b", "retain:a", "remove:a" }, trace); + Assert.Empty(roots); Assert.Empty(a.Children); + } + + [Theory] + [InlineData(true, 0)] + [InlineData(false, 1)] + public void ClaimedParentStillPrunesUnclaimedChildren(bool strong, int claims) + { + var parent = new Node("parent") { Strong = strong, Claims = claims }; var child = new Node("child"); + parent.Children.Add(child); List roots = [parent]; List removed = []; + Run(roots, removed.Add); + Assert.Same(parent, Assert.Single(roots)); Assert.Empty(parent.Children); Assert.Same(child, Assert.Single(removed)); + } + + [Fact] + public void RetainedDescendantKeepsAllAncestors() + { + var root = new Node("root"); var branch = new Node("branch"); var leaf = new Node("leaf") { Claims = 1 }; + root.Children.Add(branch); branch.Children.Add(leaf); List roots = [root]; List removed = []; + Run(roots, removed.Add); + Assert.Same(root, Assert.Single(roots)); Assert.Same(branch, Assert.Single(root.Children)); + Assert.Same(leaf, Assert.Single(branch.Children)); Assert.Empty(removed); + } + + [Fact] + public void ChildRemovalCanAddAParentClaimBeforeRetention() + { + var parent = new Node("parent"); var child = new Node("child"); parent.Children.Add(child); + List roots = [parent]; List removed = []; + Run(roots, node => { removed.Add(node); if (ReferenceEquals(node, child)) parent.Claims++; }); + Assert.Same(child, Assert.Single(removed)); Assert.Same(parent, Assert.Single(roots)); Assert.Empty(parent.Children); + } + + [Fact] + public void ChildRemovalCanClearAParentClaimBeforeRetention() + { + var parent = new Node("parent") { Strong = true }; var child = new Node("child"); parent.Children.Add(child); + List roots = [parent]; List removed = []; + Run(roots, node => { removed.Add(node); if (ReferenceEquals(node, child)) parent.Strong = false; }); + Assert.Equal(new[] { child, parent }, removed); Assert.Empty(roots); + } + + [Fact] + public void RemovalCallbackObservesTheOriginalLogicalLists() + { + var parent = new Node("parent"); var child = new Node("child"); parent.Children.Add(child); + var children = parent.Children; List roots = [parent]; int calls = 0; + Run(roots, node => + { + calls++; + Assert.Same(parent, Assert.Single(roots)); Assert.Same(children, parent.Children); + if (ReferenceEquals(node, child)) Assert.Same(child, Assert.Single(children)); + else Assert.Empty(children); + }); + Assert.Equal(2, calls); Assert.Empty(roots); Assert.Empty(children); + } + + [Fact] + public void CallbackFaultPreservesEarlierRemovalAndTheFaultingLogicalNode() + { + var parent = new Node("parent"); var a = new Node("a"); var b = new Node("b"); parent.Children.AddRange([a, b]); + List roots = [parent]; HashSet registry = [parent, a, b]; List physical = [a, b]; + var error = new InvalidOperationException("physical removal"); + var actual = Assert.Throws(() => Run(roots, node => + { + registry.Remove(node); + if (ReferenceEquals(node, a)) throw error; + physical.Remove(node); + })); + Assert.Same(error, actual); Assert.Same(parent, Assert.Single(roots)); Assert.Same(a, Assert.Single(parent.Children)); + Assert.Same(a, Assert.Single(physical)); Assert.Equal(new[] { parent }, registry); + } + + [Fact] + public void ChildSelectorFaultEscapesBeforeRetentionOrRemoval() + { + var node = new Node("node"); List roots = [node]; var error = new InvalidOperationException("children"); + int retained = 0, removed = 0; + Assert.Same(error, Assert.Throws(() => PostOrderTreePruner.Prune(roots, + _ => throw error, _ => { retained++; return false; }, _ => removed++))); + Assert.Equal(0, retained); Assert.Equal(0, removed); Assert.Same(node, Assert.Single(roots)); + } + + [Fact] + public void ParentRetentionFaultKeepsAlreadyPrunedChildren() + { + var parent = new Node("parent"); var child = new Node("child"); parent.Children.Add(child); + List roots = [parent]; List removed = []; var error = new InvalidOperationException("retain"); + Assert.Same(error, Assert.Throws(() => PostOrderTreePruner.Prune(roots, node => node.Children, + node => ReferenceEquals(node, parent) ? throw error : false, removed.Add))); + Assert.Same(child, Assert.Single(removed)); Assert.Same(parent, Assert.Single(roots)); Assert.Empty(parent.Children); + } + + [Fact] + public void LogicalRemovalFaultOccursAfterCallbackWithSameException() + { + var node = new Node("node"); var error = new InvalidOperationException("logical removal"); + var roots = new FailingList([node], error); List removed = []; + Assert.Same(error, Assert.Throws(() => Run(roots, removed.Add))); + Assert.Same(node, Assert.Single(roots)); Assert.Same(node, Assert.Single(removed)); + } + + [Fact] + public void CurrentNodeIsCapturedBeforeItsCallbackChangesTheSlot() + { + var original = new Node("original"); var replacement = new Node("replacement"); + List roots = [original]; List removed = []; + Run(roots, node => { removed.Add(node); roots[0] = replacement; }); + Assert.Same(original, Assert.Single(removed)); Assert.Empty(roots); + } + + [Fact] + public void RootAppendedDuringRemovalIsOutsideTheCapturedIndexRange() + { + var original = new Node("original"); var appended = new Node("appended"); List roots = [original]; List removed = []; + Run(roots, node => { removed.Add(node); roots.Add(appended); }); + Assert.Same(original, Assert.Single(removed)); Assert.Same(appended, Assert.Single(roots)); + } + + [Fact] + public void ChildInsertionUsesLiveIndicesWithoutRepairOrSnapshot() + { + var parent = new Node("parent"); var a = new Node("a"); var b = new Node("b"); var inserted = new Node("inserted"); + parent.Children.AddRange([a, b]); List roots = [parent]; List removed = []; + Run(roots, node => { removed.Add(node); if (ReferenceEquals(node, b)) parent.Children.Insert(0, inserted); }); + Assert.Equal(new[] { b, inserted }, removed); Assert.Same(parent, Assert.Single(roots)); + Assert.Same(b, Assert.Single(parent.Children)); + } + + [Fact] + public void ShrinkingCurrentListCanKeepOriginalIndexFailureAndPartialState() + { + var a = new Node("a"); var b = new Node("b"); List roots = [a, b]; List removed = []; + Assert.Throws(() => Run(roots, node => { removed.Add(node); roots.RemoveAt(0); })); + Assert.Same(b, Assert.Single(removed)); Assert.Same(b, Assert.Single(roots)); + } + + [Fact] + public void ReentrantPruningIsNotSuppressedAndOuterRemovalStillUsesItsIndex() + { + var node = new Node("node"); List roots = [node]; List removed = []; bool entered = false; + void Remove(Node current) + { + removed.Add(current); + if (entered) return; + entered = true; Run(roots, Remove); + } + Assert.Throws(() => Run(roots, Remove)); + Assert.Equal(new[] { node, node }, removed); Assert.Empty(roots); + } + + [Fact] + public void ChildListIsSelectedOnceAndTheSameCollectionIsMutated() + { + var parent = new Node("parent"); var child = new Node("child"); parent.Children.Add(child); + List roots = [parent]; Dictionary reads = []; var children = parent.Children; + PostOrderTreePruner.Prune(roots, node => { reads[node] = reads.GetValueOrDefault(node) + 1; return node.Children; }, + _ => false, _ => { }); + Assert.Equal(1, reads[parent]); Assert.Equal(1, reads[child]); Assert.Same(children, parent.Children); + Assert.Empty(roots); Assert.Empty(children); + } + + [Fact] + public void EarlierRootRetentionReadsStateChangedByLaterRootRemoval() + { + var first = new Node("first"); var last = new Node("last"); List roots = [first, last]; List removed = []; + Run(roots, node => { removed.Add(node); first.Strong = true; }); + Assert.Same(last, Assert.Single(removed)); Assert.Same(first, Assert.Single(roots)); + } + + private static void Run(IList roots, Action remove) => + PostOrderTreePruner.Prune(roots, static node => node.Children, + static node => node.Strong || node.Claims > 0 || node.Children.Count > 0, remove); + + private sealed class Node(string name) + { + public string Name { get; } = name; + public bool Strong { get; set; } + public int Claims { get; set; } + public List Children { get; } = []; + } + + private sealed class FailingList(IList items, Exception error) : Collection(items) + { + protected override void RemoveItem(int index) => throw error; + } +} diff --git a/CDPIUI.Tests/Presentation/SelectedItemChoiceActionTests.cs b/CDPIUI.Tests/Presentation/SelectedItemChoiceActionTests.cs new file mode 100644 index 00000000..8555d9fb --- /dev/null +++ b/CDPIUI.Tests/Presentation/SelectedItemChoiceActionTests.cs @@ -0,0 +1,47 @@ +using CDPIUI.Helper.UserExperience; + +namespace CDPIUI.Tests.Presentation; + +public class SelectedItemChoiceActionTests +{ + [Fact] + public async Task PlainObjectsAndChoiceReferencesWorkWithoutAnyUiOrDomainType() + { + var item = new object(); var first = new object(); var second = new object(); var replacement = new object(); + IReadOnlyList? snapshot = null; List<(object, object)> applied = []; + await SelectedItemChoiceAction.ExecuteAsync(() => item, _ => (IReadOnlyList)new[] { first, second }, + paths => { snapshot = paths; return Task.FromResult(replacement); }, + (selected, choice) => applied.Add((selected, choice))); + Assert.NotNull(snapshot); Assert.Same(first, snapshot[0]); Assert.Same(second, snapshot[1]); + var result = Assert.Single(applied); + Assert.Same(item, result.Item1); Assert.Same(replacement, result.Item2); + } + + [Fact] + public async Task NullItemSkipsAllOtherPorts() + { + await SelectedItemChoiceAction.ExecuteAsync(() => null, + _ => throw new InvalidOperationException("choices"), _ => throw new InvalidOperationException("choose"), + (_, _) => throw new InvalidOperationException("apply")); + } + + [Fact] + public async Task SingleChoiceSkipsChooserButAppliesTheSameObjects() + { + var item = new object(); var choice = new object(); List<(object, object)> applied = []; + await SelectedItemChoiceAction.ExecuteAsync(() => item, _ => (IReadOnlyList)new[] { choice }, + _ => throw new InvalidOperationException("choose"), + (selected, result) => applied.Add((selected, result))); + var result = Assert.Single(applied); + Assert.Same(item, result.Item1); Assert.Same(choice, result.Item2); + } + + [Fact] + public async Task SelectorFaultIsCapturedInReturnedTask() + { + var error = new InvalidOperationException("owned selector"); Task? task = null; + Assert.Null(Record.Exception(() => { task = SelectedItemChoiceAction.ExecuteAsync(() => throw error, + _ => [], _ => Task.FromResult(null), (_, _) => { }); })); + Assert.Same(error, await Assert.ThrowsAsync(() => task!)); + } +} diff --git a/CDPIUI.Tests/Presentation/TextChangeRelayTests.cs b/CDPIUI.Tests/Presentation/TextChangeRelayTests.cs new file mode 100644 index 00000000..07e75a02 --- /dev/null +++ b/CDPIUI.Tests/Presentation/TextChangeRelayTests.cs @@ -0,0 +1,192 @@ +using CDPIUI.Helper.UserExperience; + +namespace CDPIUI.Tests.Presentation; + +public class TextChangeRelayTests +{ + [Fact] + public void ConstructionDoesNotReadOrPublishAnyPort() + { + static InvalidOperationException Unexpected() => new("eager callback"); + var relay = new TextChangeRelay(() => throw Unexpected(), () => throw Unexpected(), + _ => throw Unexpected(), _ => throw Unexpected(), _ => throw Unexpected(), + () => throw Unexpected(), () => throw Unexpected(), () => throw Unexpected(), _ => throw Unexpected()); + Assert.False(relay.IsUpdating); + } + + [Fact] + public void UserInputPublishesCurrentTextBeforeSchedulingDiagnostics() + { + var f = new Fixture(); f.Relay.OnTextChanged("input"); + Assert.Equal(["readonly", "write:input", "read:input", "accept:input", "rebuild", "read:input", "notify:input", "schedule"], f.Trace); + Assert.Equal("input", f.Current); Assert.Equal("input", Assert.Single(f.Accepted)); + Assert.Equal("input", Assert.Single(f.Published)); Assert.False(f.Relay.IsUpdating); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ReplacementUsesCapturedEditorResultAndImmediateDiagnostics(bool updateProperty) + { + var f = new Fixture { ReplaceReply = _ => "normalized" }; + f.Relay.ReplaceText("input", updateProperty); + string[] expected = updateProperty + ? ["replace:input", "write:normalized", "accept:normalized", "rebuild", "immediate", "notify:normalized"] + : ["replace:input", "accept:normalized", "rebuild", "immediate", "notify:normalized"]; + Assert.Equal(expected, f.Trace); Assert.Equal(updateProperty ? "normalized" : "old", f.Current); + Assert.Equal("normalized", Assert.Single(f.Accepted)); Assert.Equal("normalized", Assert.Single(f.Published)); + Assert.False(f.Relay.IsUpdating); + } + + [Fact] + public void ReadOnlyInputRestoresCurrentTextWithoutWritingPropertyOrScheduling() + { + var f = new Fixture { ReadOnly = true, Current = "stored", ReplaceReply = _ => "restored" }; + f.Relay.OnTextChanged("rejected"); + Assert.Equal(["readonly", "read:stored", "replace:stored", "accept:restored", "rebuild", "immediate", "notify:restored"], f.Trace); + Assert.Equal("stored", f.Current); Assert.Equal("restored", Assert.Single(f.Accepted)); + Assert.Equal("restored", Assert.Single(f.Published)); Assert.False(f.Relay.IsUpdating); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void IncomingNullIsNormalizedToEmptyForEitherPath(bool replace) + { + var f = new Fixture(); + if (replace) f.Relay.ReplaceText(null!); else f.Relay.OnTextChanged(null!); + Assert.Equal("", f.Current); Assert.Equal("", Assert.Single(f.Accepted)); + Assert.Equal("", Assert.Single(f.Published)); + Assert.Contains(replace ? "replace:" : "write:", f.Trace); + } + + [Fact] + public void RuntimeNullEditorResultIsNotNormalizedAgain() + { + var f = new Fixture { ReplaceReply = _ => null! }; f.Relay.ReplaceText("input"); + Assert.Null(f.Current); Assert.Null(Assert.Single(f.Accepted)); Assert.Null(Assert.Single(f.Published)); + Assert.False(f.Relay.IsUpdating); + } + + [Fact] + public void UserInputReadsCurrentValueAgainAfterAcceptAndRebuildCallbacks() + { + var f = new Fixture(); + f.OnStep = step => + { + if (step == "write:input") f.Current = "property-change"; + if (step == "accept:property-change") f.Current = "accepted"; + if (step == "rebuild") f.Current = "rebuilt"; + }; + f.Relay.OnTextChanged("input"); + Assert.Equal("property-change", Assert.Single(f.Accepted)); + Assert.Equal("rebuilt", Assert.Single(f.Published)); + Assert.Equal(["read:property-change", "read:rebuilt"], f.Trace.Where(x => x.StartsWith("read:"))); + } + + [Fact] + public void ReplacementNotificationRetainsCapturedResultAcrossReentry() + { + var f = new Fixture { ReplaceReply = _ => "captured" }; + f.OnStep = step => + { + if (step == "write:captured") f.Current = "property-change"; + if (step == "rebuild") f.Current = "rebuilt"; + }; + f.Relay.ReplaceText("input"); + Assert.Equal("rebuilt", f.Current); Assert.Equal("captured", Assert.Single(f.Accepted)); + Assert.Equal("captured", Assert.Single(f.Published)); Assert.DoesNotContain(f.Trace, x => x.StartsWith("read:")); + } + + [Theory] + [InlineData(false, "write:input")] + [InlineData(true, "replace:input")] + [InlineData(true, "write:input")] + [InlineData(true, "accept:input")] + public void SuppressedInputDoesNotEvenReadReadonlyState(bool replace, string step) + { + var f = new Fixture(); + f.OnStep = name => + { + if (name != step) return; + Assert.True(f.Relay.IsUpdating); int before = f.Trace.Count; + f.Relay.OnTextChanged("nested"); Assert.Equal(before, f.Trace.Count); + }; + if (replace) f.Relay.ReplaceText("input"); else f.Relay.OnTextChanged("input"); + Assert.Equal("input", Assert.Single(f.Published)); + } + + [Fact] + public void NestedReplacementRetainsBooleanRatherThanDepthBasedSuppression() + { + var f = new Fixture(); + f.OnStep = step => + { + if (step != "write:outer") return; + f.Relay.ReplaceText("inner"); Assert.False(f.Relay.IsUpdating); + f.Relay.OnTextChanged("nested"); + }; + f.Relay.OnTextChanged("outer"); + Assert.Equal(["inner", "nested", "nested"], f.Published); + Assert.Equal(["inner", "nested", "nested"], f.Accepted); + Assert.Equal("nested", f.Current); Assert.False(f.Relay.IsUpdating); + } + + [Theory] + [InlineData(false, "readonly", false)] + [InlineData(false, "write:input", true)] + [InlineData(false, "read:input", false)] + [InlineData(false, "accept:input", false)] + [InlineData(false, "rebuild", false)] + [InlineData(false, "notify:input", false)] + [InlineData(false, "schedule", false)] + [InlineData(true, "replace:input", true)] + [InlineData(true, "write:input", true)] + [InlineData(true, "accept:input", true)] + [InlineData(true, "rebuild", false)] + [InlineData(true, "immediate", false)] + [InlineData(true, "notify:input", false)] + public void CallbackFailurePreservesExceptionIdentityAndOriginalGuardState(bool replace, string step, bool updating) + { + var f = new Fixture(); var error = new InvalidOperationException(step); + f.OnStep = name => { if (name == step) throw error; }; + Assert.Same(error, Assert.Throws(() => + { + if (replace) f.Relay.ReplaceText("input"); else f.Relay.OnTextChanged("input"); + })); + Assert.Equal(step, f.Trace.Last()); Assert.Equal(updating, f.Relay.IsUpdating); + f.OnStep = null; int before = f.Trace.Count; f.Relay.OnTextChanged("next"); + if (updating) Assert.Equal(before, f.Trace.Count); + else Assert.Equal("next", f.Published.Last()); + } + + [Fact] + public void ReadOnlyCurrentReadFailureDoesNotOpenSuppression() + { + var f = new Fixture { ReadOnly = true }; var error = new InvalidOperationException("read"); + f.OnStep = step => { if (step == "read:old") throw error; }; + Assert.Same(error, Assert.Throws(() => f.Relay.OnTextChanged("input"))); + Assert.False(f.Relay.IsUpdating); Assert.Empty(f.Accepted); Assert.Empty(f.Published); + } + + private sealed class Fixture + { + internal readonly TextChangeRelay Relay; + internal readonly List Trace = [], Accepted = [], Published = []; + internal string Current = "old"; + internal bool ReadOnly; + internal Action? OnStep; + internal Func? ReplaceReply; + internal Fixture() + { + Relay = new(() => { Step("readonly"); return ReadOnly; }, + () => { Step("read:" + Current); return Current; }, + text => { Current = text; Step("write:" + text); }, + text => { Step("replace:" + text); return ReplaceReply == null ? text : ReplaceReply(text); }, + text => { Accepted.Add(text); Step("accept:" + text); }, + () => Step("rebuild"), () => Step("immediate"), () => Step("schedule"), + text => { Published.Add(text); Step("notify:" + text); }); + } + private void Step(string value) { Trace.Add(value); OnStep?.Invoke(value); } + } +} diff --git a/CDPIUI.Tests/Presentation/TwoPhaseTransitionSequenceTests.cs b/CDPIUI.Tests/Presentation/TwoPhaseTransitionSequenceTests.cs new file mode 100644 index 00000000..a8c4e616 --- /dev/null +++ b/CDPIUI.Tests/Presentation/TwoPhaseTransitionSequenceTests.cs @@ -0,0 +1,271 @@ +using System.Collections; +using CDPIUI.Helper.UserExperience; + +namespace CDPIUI.Tests.Presentation; + +public class TwoPhaseTransitionSequenceTests +{ + [Fact] + public async Task BothGroupsUseTheirOwnDelayPolicyAndNeverDelayAfterLastTransition() + { + using var f = new Fixture(); var a = new Cell("A"); var b = new Cell("B", true); + var c = new Cell("C"); var d = new Cell("D", true); + f.First.Items.AddRange([(a, "hide"), (b, "hide")]); f.Second.Items.AddRange([(c, "show"), (d, "show")]); + await f.Run(); + Assert.Equal(["count:first", "count:second", "inspect:A:False", "apply:A:hide", "first:False", "delay:10", + "inspect:B:True", "apply:B:hide", "first:True", "delay:30", "inspect:C:False", "apply:C:show", "second:False", "delay:20", + "inspect:D:True", "apply:D:show", "finish"], f.Trace); + Assert.Equal([10, 30, 20], f.Delays.Select(x => x.Duration.TotalMilliseconds)); + Assert.All(f.Delays, x => Assert.Equal(f.Source.Token, x.Token)); + Assert.Equal("hide", a.State); Assert.Equal("hide", b.State); Assert.Equal("show", c.State); Assert.Equal("show", d.State); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task OneTransitionStillInspectsAndAppliesWithoutSelectingDelayOrReadingDisposedSource(bool first) + { + using var f = new Fixture(); var item = new Cell("only", true); + (first ? f.First : f.Second).Items.Add((item, "new")); f.Source.Dispose(); + f.OnStep = name => { if (name.StartsWith("first:") || name.StartsWith("second:") || name.StartsWith("delay:")) throw new InvalidOperationException(name); }; + await f.Run(); + Assert.Equal(["count:first", "count:second", "inspect:only:True", "apply:only:new", "finish"], f.Trace); + Assert.Equal("new", item.State); Assert.Empty(f.Delays); + } + + [Fact] + public async Task EmptyGroupsOnlyReadTheTwoCountsAndDoNotReadDisposedSource() + { + using var f = new Fixture(); f.Source.Dispose(); await f.Run(); + Assert.Equal(["count:first", "count:second", "finish"], f.Trace); + } + + [Fact] + public async Task InspectionIsCapturedBeforeApplyButDelaySelectorRunsAfterIt() + { + using var f = Pair(); var item = f.First.Items[0].Item; + f.OnStep = name => + { + if (name == "apply:A:hide") item.Extra = true; + if (name == "first:False") Assert.Equal("hide", item.State); + }; + await f.Run(); + Assert.True(item.Extra); Assert.Contains("first:False", f.Trace); Assert.DoesNotContain("first:True", f.Trace); + Assert.Equal(10, Assert.Single(f.Delays).Duration.TotalMilliseconds); + } + + [Fact] + public async Task SecondPhaseWithExtraMovementUsesItsOwnDelaySelector() + { + using var f = new Fixture(); f.Second.Items.AddRange([(new("A", true), "show"), (new("B"), "show")]); + await f.Run(); Assert.Contains("second:True", f.Trace); + Assert.Equal(40, Assert.Single(f.Delays).Duration.TotalMilliseconds); + } + + [Fact] + public async Task PendingDelayKeepsCurrentLaterInspectionAndLiveSecondListButOriginalTotal() + { + using var f = Pair(); var b = f.Second.Items[0].Item; + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); f.DelayReply = (_, _) => gate.Task; + Task task = f.Run(); + try + { + Assert.False(task.IsCompleted); Assert.Equal("old", b.State); + b.Extra = true; var added = new Cell("C"); f.Second.Items.Add((added, "late")); + gate.SetResult(); await task.WaitAsync(TimeSpan.FromSeconds(3)); + Assert.Equal("show", b.State); Assert.Equal("late", added.State); Assert.Contains("inspect:B:True", f.Trace); + Assert.Single(f.Delays); Assert.Equal(1, f.Trace.Count(x => x == "count:first")); Assert.Equal(1, f.Trace.Count(x => x == "count:second")); + } + finally { gate.TrySetResult(); await task.WaitAsync(TimeSpan.FromSeconds(3)); } + } + + [Fact] + public async Task MutatingAnActivelyEnumeratedFirstListKeepsItsOriginalFailure() + { + using var f = Pair(); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.DelayReply = (_, _) => gate.Task; Task task = f.Run(); + f.First.Items.Add((new("late"), "hide")); gate.SetResult(); + await Assert.ThrowsAsync(() => task.WaitAsync(TimeSpan.FromSeconds(3))); + Assert.Equal("old", f.Second.Items[0].Item.State); Assert.Single(f.Delays); + } + + [Fact] + public async Task PreCancelledSourceDoesNotPreventTheFirstApplyBeforeActualDelayCancels() + { + using var f = Pair(); f.Source.Cancel(); Task task = f.Run(); + await task; Assert.Equal(TaskStatus.RanToCompletion, task.Status); Assert.True(f.Source.IsCancellationRequested); + Assert.Equal("hide", f.First.Items[0].Item.State); Assert.Equal("old", f.Second.Items[0].Item.State); + Assert.Equal("delay:10", f.Trace[^2]); Assert.Equal("finish", f.Trace.Last()); + } + + [Fact] + public async Task PreCancelledSingleTransitionStillCompletesSuccessfully() + { + using var f = new Fixture(); f.First.Items.Add((new("A"), "new")); f.Source.Cancel(); + Task task = f.Run(); await task; Assert.Equal(TaskStatus.RanToCompletion, task.Status); + Assert.Equal("new", f.First.Items[0].Item.State); Assert.Empty(f.Delays); + } + + [Fact] + public async Task DisposedSourceIsReadOnlyAfterApplyAndDelaySelectionWhenPauseIsNeeded() + { + using var f = Pair(); f.Source.Dispose(); Task task = f.Run(); + await Assert.ThrowsAsync(() => task); + Assert.True(task.IsFaulted); Assert.Equal("first:False", f.Trace[^2]); Assert.Equal("finish", f.Trace.Last()); Assert.Empty(f.Delays); + Assert.Equal("hide", f.First.Items[0].Item.State); Assert.Equal("old", f.Second.Items[0].Item.State); + } + + [Theory] + [InlineData("count:first")] + [InlineData("count:second")] + [InlineData("inspect:A:False")] + [InlineData("apply:A:hide")] + [InlineData("first:False")] + [InlineData("delay:10")] + [InlineData("inspect:B:False")] + [InlineData("apply:B:show")] + [InlineData("second:False")] + public async Task SetupAndCallbackFailuresAreReturnedInTaskWithSameException(string step) + { + using var f = Pair(); f.Second.Items.Add((new("C"), "show")); + var expected = new InvalidOperationException(step); f.OnStep = name => { if (name == step) throw expected; }; + Task? task = null; Assert.Null(Record.Exception(() => { task = f.Run(); })); + Assert.Same(expected, await Assert.ThrowsAsync(() => task!)); + Assert.Equal(step, f.Trace[^2]); Assert.Equal("finish", f.Trace.Last()); Assert.True(task!.IsFaulted); + Assert.Null(Record.Exception(f.Source.Cancel)); // A borrowed source is never disposed by the utility. + } + + [Fact] + public async Task ArbitraryCancellationFromInspectionIsSwallowedAndFinalizedAsBefore() + { + using var f = Pair(); var expected = new OperationCanceledException(new CancellationToken(true)); + f.OnStep = name => { if (name == "inspect:A:False") throw expected; }; + Task task = f.Run(); await task; + Assert.Equal(TaskStatus.RanToCompletion, task.Status); Assert.Equal("old", f.First.Items[0].Item.State); + Assert.Equal(1, f.Trace.Count(x => x == "finish")); + } + + [Fact] + public async Task BorrowedSourceRemainsUsableAfterSuccess() + { + using var f = Pair(); await f.Run(); Assert.Null(Record.Exception(f.Source.Cancel)); Assert.True(f.Source.IsCancellationRequested); + } + + [Fact] + public async Task ZeroDurationStillCallsTheDelayPort() + { + using var f = Pair(); f.DurationOverride = TimeSpan.Zero; await f.Run(); + Assert.Equal(TimeSpan.Zero, Assert.Single(f.Delays).Duration); Assert.Equal("show", f.Second.Items[0].Item.State); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task ZeroDurationStillReadsSourceAndRespectsDelayCancellation(bool disposed) + { + using var f = Pair(); f.DurationOverride = TimeSpan.Zero; + if (disposed) f.Source.Dispose(); else f.Source.Cancel(); + Task task = f.Run(); + if (disposed) + { + await Assert.ThrowsAsync(() => task); Assert.Empty(f.Delays); + } + else + { + await task; Assert.Equal(TaskStatus.RanToCompletion, task.Status); Assert.Equal(TimeSpan.Zero, Assert.Single(f.Delays).Duration); + } + Assert.Equal("hide", f.First.Items[0].Item.State); Assert.Equal("old", f.Second.Items[0].Item.State); + Assert.Equal(1, f.Trace.Count(x => x == "finish")); + } + + [Fact] + public async Task ValueTypesAndPlainStatesNeedNoUiOrDomainTypes() + { + using var source = new CancellationTokenSource(); List<(int, bool)> applied = []; int finished = 0; + await TwoPhaseTransitionSequence.RunAsync(new[] { (1, false) }, new[] { (2, true) }, + _ => false, (item, state) => applied.Add((item, state)), _ => TimeSpan.Zero, _ => TimeSpan.Zero, + (_, _) => Task.CompletedTask, source, () => finished++); + Assert.Equal([(1, false), (2, true)], applied); Assert.Equal(1, finished); + Assert.Null(Record.Exception(source.Cancel)); + } + + [Fact] + public async Task FinalizerFailureOverridesEarlierBodyFailureAndRunsExactlyOnce() + { + using var f = Pair(); var first = new InvalidOperationException("body"); var last = new InvalidOperationException("finalizer"); + f.OnStep = name => { if (name == "inspect:A:False") throw first; if (name == "finish") throw last; }; + Assert.Same(last, await Assert.ThrowsAsync(f.Run)); + Assert.Equal(1, f.Trace.Count(x => x == "finish")); + } + + [Fact] + public async Task CancellationRaisedByFinalizerIsNotSwallowed() + { + using var f = new Fixture(); var error = new OperationCanceledException(new CancellationToken(true)); + f.OnStep = name => { if (name == "finish") throw error; }; + Task task = f.Run(); Assert.Same(error, await Assert.ThrowsAsync(() => task)); + Assert.True(task.IsCanceled); Assert.Equal(1, f.Trace.Count(x => x == "finish")); + } + + [Fact] + public async Task FinalizationCompletesBeforeTheReturnedTaskCanBeObservedComplete() + { + using var f = Pair(); bool finalized = false; + f.OnStep = name => { if (name == "finish") finalized = true; }; + Task task = f.Run(); Assert.True(task.IsCompletedSuccessfully); Assert.True(finalized); await task; + Assert.Equal(1, f.Trace.Count(x => x == "finish")); + } + + [Fact] + public async Task ConcurrentCallsHaveIndependentIndicesAndCanCompleteInReverseOrder() + { + using var a = Pair(); using var b = Pair(); var one = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var two = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + a.DelayReply = (_, _) => one.Task; b.DelayReply = (_, _) => two.Task; Task first = a.Run(); Task second = b.Run(); + try + { + Assert.False(first.IsCompleted); Assert.False(second.IsCompleted); + two.SetResult(); await second.WaitAsync(TimeSpan.FromSeconds(3)); + Assert.False(first.IsCompleted); Assert.Equal("old", a.Second.Items[0].Item.State); Assert.Equal("show", b.Second.Items[0].Item.State); + one.SetResult(); await first.WaitAsync(TimeSpan.FromSeconds(3)); + Assert.Equal("show", a.Second.Items[0].Item.State); Assert.Single(a.Delays); Assert.Single(b.Delays); + } + finally { one.TrySetResult(); two.TrySetResult(); await first.WaitAsync(TimeSpan.FromSeconds(3)); await second.WaitAsync(TimeSpan.FromSeconds(3)); } + } + + private static Fixture Pair() + { + var f = new Fixture(); f.First.Items.Add((new("A"), "hide")); f.Second.Items.Add((new("B"), "show")); return f; + } + private sealed class Cell(string name, bool extra = false) + { + internal readonly string Name = name; internal bool Extra = extra; internal string State = "old"; + } + private sealed class LoggedList(string name, Action step) : IReadOnlyList + { + internal readonly List Items = []; + public int Count { get { step("count:" + name); return Items.Count; } } + public T this[int index] => Items[index]; + public IEnumerator GetEnumerator() => Items.GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + private sealed class Fixture : IDisposable + { + internal readonly List Trace = []; + internal readonly List<(TimeSpan Duration, CancellationToken Token)> Delays = []; + internal readonly CancellationTokenSource Source = new(); + internal readonly LoggedList<(Cell Item, string State)> First, Second; + internal Action? OnStep; + internal Func? DelayReply; + internal TimeSpan? DurationOverride; + internal Fixture() { First = new("first", Step); Second = new("second", Step); } + private void Step(string value) { Trace.Add(value); OnStep?.Invoke(value); } + internal Task Run() => TwoPhaseTransitionSequence.RunAsync(First, Second, + item => { bool before = item.Extra; Step($"inspect:{item.Name}:{before}"); return before; }, + (item, state) => { Step($"apply:{item.Name}:{state}"); item.State = state; }, + before => { Step("first:" + before); return DurationOverride ?? TimeSpan.FromMilliseconds(before ? 30 : 10); }, + before => { Step("second:" + before); return DurationOverride ?? TimeSpan.FromMilliseconds(before ? 40 : 20); }, + (duration, token) => { Delays.Add((duration, token)); Step("delay:" + duration.TotalMilliseconds); return DelayReply?.Invoke(duration, token) ?? (token.IsCancellationRequested ? Task.FromCanceled(token) : Task.CompletedTask); }, Source, () => Step("finish")); + public void Dispose() => Source.Dispose(); + } +} diff --git a/CDPIUI/App.Activation.cs b/CDPIUI/App.Activation.cs index 05b808b3..a1ee7e42 100644 --- a/CDPIUI/App.Activation.cs +++ b/CDPIUI/App.Activation.cs @@ -17,7 +17,6 @@ using CDPIUI.Shared.Pipe.Models; using Microsoft.UI.Xaml; using Microsoft.Windows.AppLifecycle; -using Windows.ApplicationModel.Activation; using WinRT.Interop; using WinUI3Localizer; @@ -25,9 +24,6 @@ namespace CDPIUI; public partial class App { - private static readonly string[] SupportedFilePaths = - [".cdpisignedpack", ".cdpiconfigpack", ".cdpipatch", ".cdpitask", ".cdpiconfig"]; - private readonly SemaphoreSlim _migrationWindowActivationLock = new(1, 1); private bool _settingsRecoveryWarningShown; @@ -58,114 +54,14 @@ private async Task PipeConnectedActions() /// Handles the migration request, files, protocol links and --direct: commands the first /// instance was started with. Returns true when one of them opened something. /// - private async Task ProcessStartupActivationAsync(string[] arguments) - { - bool isFileProcessed = false; - bool isActionPreferred = false; - bool isMigrationProcessed = false; - - try - { - isMigrationProcessed = await TryHandleMigrationActivationAsync(arguments); - if (!isMigrationProcessed && - Program.InitialActivationArguments?.Kind is ExtendedActivationKind.Launch && - Program.InitialActivationArguments.Data is ILaunchActivatedEventArgs initialLaunchArgs) - { - isMigrationProcessed = await TryHandleMigrationActivationAsync(initialLaunchArgs.Arguments); - } - - if (Program.InitialActivationArguments?.Kind is ExtendedActivationKind.File && - Program.InitialActivationArguments.Data is IFileActivatedEventArgs initialFileArgs) - { - isFileProcessed = await ProcessFiles( - initialFileArgs.Files.Select(file => file.Path).ToArray()); - } - - if (Program.InitialActivationArguments?.Kind is ExtendedActivationKind.Protocol && - Program.InitialActivationArguments.Data is IProtocolActivatedEventArgs initialProtocolArgs) - { - isActionPreferred = await CommandsHandler.HandleCommandAsync( - initialProtocolArgs.Uri.ToString()); - } - - if (!isFileProcessed) - isFileProcessed = await ProcessFiles(arguments); - - string protocolArg = isActionPreferred - ? null - : arguments.FirstOrDefault(x => x.StartsWith("----ms-protocol:")); - - if (protocolArg != null) - { - string value = protocolArg["----ms-protocol:".Length..]; - isActionPreferred = await CommandsHandler.HandleCommandAsync(value); - } + private Task ProcessStartupActivationAsync(string[] arguments) => + _activationDispatcher.ProcessStartupAsync(arguments, + kind => AppActivationRequestAdapter.From(Program.InitialActivationArguments, kind)); - string directArgs = arguments.FirstOrDefault(x => x.StartsWith("--direct:")); + private static Task HandleCoreDirectActivationAsync(string value) => + CoreCommandsHandler.HandleCommandAsync(PipeModelConvertor.ConvertBack(value)); - if (directArgs != null) - { - string value = directArgs["--direct:".Length..]; - isActionPreferred = await CoreCommandsHandler.HandleCommandAsync( - PipeModelConvertor.ConvertBack(value)); - - if (!isActionPreferred) - { - isActionPreferred = CommandsHandler.HandleCommand(value); - } - } - } - catch (Exception ex) - { - Logger.Instance.CreateWarningLog( - nameof(App), - $"Cannot process startup activation: {ex}"); - } - - return isFileProcessed || isActionPreferred || isMigrationProcessed; - } - - private async Task ProcessFiles(string[] files) - { - foreach (string file in files) - { - var _file = file.Replace("\"", ""); - Logger.Instance.CreateDebugLog(nameof(App), $"Working on file {_file}"); - - if (Path.Exists(_file) && SupportedFilePaths.Contains( - Path.GetExtension(_file), - StringComparer.OrdinalIgnoreCase)) - { - if (CDPIUI.AddOns.ConfigShare.ConfigShareService.IsSupported(_file)) - { - var importDialog = await UnsafeCreateNewWindow(activate: false); - ActivateWindow(importDialog); - await importDialog.SetFileAsync(_file); - return true; - } - - if (Path.GetExtension(_file).Equals(".cdpitask", StringComparison.OrdinalIgnoreCase)) - { - await OpenConditionalTaskImportAsync(_file); - return true; - } - - if (Path.GetExtension(_file).Equals(".cdpipatch", StringComparison.OrdinalIgnoreCase)) - { - var updateDialog = await SafeCreateNewWindow(activate: false); - updateDialog.SetUpdateFilePath(_file); - ActivateWindow(updateDialog); - return true; - } - - var window = await SafeCreateNewWindow(); - // Not awaited: the import runs while the dialog is open. SetPackFilePath logs its own errors. - _ = window.SetPackFilePath(_file); - return true; // Only first file will be processed. - } - } - return false; - } + private Task ProcessFiles(string[] files) => _fileActivationHandler.ProcessFiles(files); private async Task OpenConditionalTaskImportAsync(string filePath) { @@ -193,38 +89,8 @@ public async Task PreferRequestedActions(AppActivationArguments appActivationArg bool result = false; try { - if (appActivationArguments.Kind is ExtendedActivationKind.Protocol && - appActivationArguments.Data is IProtocolActivatedEventArgs protocolActivatedEventArgs) - { - string value = protocolActivatedEventArgs.Uri.ToString(); - result = await CommandsHandler.HandleCommandAsync(value); - } - - if (appActivationArguments.Kind is ExtendedActivationKind.File && - appActivationArguments.Data is IFileActivatedEventArgs activatedFileArgs) - { - result = await ProcessFiles( - activatedFileArgs.Files.Select(file => file.Path).ToArray()); - } - else if (appActivationArguments.Kind is ExtendedActivationKind.Launch && - appActivationArguments.Data is ILaunchActivatedEventArgs fileActivatedEventArgs) - { - result = await TryHandleMigrationActivationAsync(fileActivatedEventArgs.Arguments); - string[] args = CommandLineSplitter.Split(fileActivatedEventArgs.Arguments); - if (!result) - { - // The same --direct: commands as in a first start. - string directArgs = args.FirstOrDefault(x => x.StartsWith("--direct:")); - if (directArgs != null) - { - string value = directArgs["--direct:".Length..]; - result = await CoreCommandsHandler.HandleCommandAsync(PipeModelConvertor.ConvertBack(value)) - || CommandsHandler.HandleCommand(value); - } - } - if (!result) - result = await ProcessFiles(args); - } + result = await _activationDispatcher.ProcessRedirectedAsync( + AppActivationRequestAdapter.From(appActivationArguments)); } catch (Exception ex) { diff --git a/CDPIUI/App.Modal.cs b/CDPIUI/App.Modal.cs index 3abab817..057c831c 100644 --- a/CDPIUI/App.Modal.cs +++ b/CDPIUI/App.Modal.cs @@ -1,5 +1,6 @@ using System; using System.Threading.Tasks; +using CDPIUI.Helper.UserExperience; using Microsoft.UI.Xaml; namespace CDPIUI; @@ -11,34 +12,18 @@ public partial class App public Task ShowWindowModalAsync(Window modalWindow, Window ownerWindow) { ArgumentNullException.ThrowIfNull(modalWindow); - var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - async void Begin() - { - try - { await _modalWindows.BeginModal(modalWindow, ownerWindow); completion.TrySetResult(true); } - catch (Exception exception) { completion.TrySetException(exception); } - } - if (_uiDispatcher.HasThreadAccess) - Begin(); - else if (!_uiDispatcher.TryEnqueue(Begin)) - completion.TrySetCanceled(); - return completion.Task; + return DispatcherTaskBridge.Run( + () => _modalWindows.BeginModal(modalWindow, ownerWindow), + () => _uiDispatcher.HasThreadAccess, + action => _uiDispatcher.TryEnqueue(() => action())); } public Task MakeWindowNormal(Window modalWindow) { ArgumentNullException.ThrowIfNull(modalWindow); - var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - void Restore() - { - try - { _modalWindows.ReleaseModal(modalWindow, isClosing: false); completion.TrySetResult(true); } - catch (Exception exception) { completion.TrySetException(exception); } - } - if (_uiDispatcher.HasThreadAccess) - Restore(); - else if (!_uiDispatcher.TryEnqueue(Restore)) - completion.TrySetCanceled(); - return completion.Task; + return DispatcherTaskBridge.Run( + () => _modalWindows.ReleaseModal(modalWindow, isClosing: false), + () => _uiDispatcher.HasThreadAccess, + action => _uiDispatcher.TryEnqueue(() => action())); } } diff --git a/CDPIUI/App.Windows.cs b/CDPIUI/App.Windows.cs index 4e389f73..e69d3c9b 100644 --- a/CDPIUI/App.Windows.cs +++ b/CDPIUI/App.Windows.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using System.Threading.Tasks; using CDPIUI.Core.Basic; using CDPIUI.Default; @@ -20,39 +19,17 @@ public async Task NavigateToUpdatesPage() mainWindow.NavView_Navigate(typeof(AboutPage), "START_CHECK", new DrillInNavigationTransitionInfo()); } - public bool CheckWindow() where TWindow : Window - { - return (OpenWindows.OfType().FirstOrDefault(w => w.DispatcherQueue != null) != null); - } + public bool CheckWindow() where TWindow : Window => + _windowCoordinator.GetCurrent(typeof(TWindow)) != null; - public void ShowWindow() where TWindow : Window - { - var activeFindWindow = OpenWindows.OfType().FirstOrDefault(w => w.DispatcherQueue != null); - if (activeFindWindow != null) - { - activeFindWindow.Activate(); - } - } + public void ShowWindow() where TWindow : Window => + _windowCoordinator.GetCurrent(typeof(TWindow))?.Activate(); - public void CloseWindow() where TWindow : Window - { - foreach (var viewWindow in OpenWindows.OfType().ToList()) - { - viewWindow.Close(); - OpenWindows.Remove(viewWindow); - } - } + public void CloseWindow() where TWindow : Window => + _windowCoordinator.CloseAll(typeof(TWindow)); - public void CloseWindow(string id) where TWindow : TemplateWindow - { - OpenWindows - .OfType() - .FirstOrDefault(window => string.Equals( - window.Id, - id, - StringComparison.OrdinalIgnoreCase)) - ?.Close(); - } + public void CloseWindow(string id) where TWindow : TemplateWindow => + _windowCoordinator.CloseTemplate(typeof(TWindow), id); public static void ActivateWindow(Window window) { @@ -73,72 +50,14 @@ public static void ActivateWindow(Window window) // Every overload waits for the localizer: windows opened by a link or a file during the // start were built before their texts were available. - public async Task UnsafeCreateNewWindow(Type windowType, bool activate = true, string id = "") - { - await _localizerReady; - - var findWindows = OpenWindows.Where(w => windowType.IsInstanceOfType(w)).ToList(); - - // Only template windows have an id; a cast of every window threw for other types. - foreach (TemplateWindow _win in findWindows.OfType()) - { - if (!string.IsNullOrEmpty(_win.Id) && string.Equals( - _win.Id, - id, - StringComparison.OrdinalIgnoreCase)) - { - if (activate) - ActivateWindow(_win); - return _win; - } - } - - var newWindow = (TemplateWindow)Activator.CreateInstance(windowType); - newWindow.Id = id; - WindowsPositionHelper.SetCustomWindowSizeAndPositionFromSettings(newWindow); - RegisterWindow(newWindow, isUnsafe: true); - if (activate) - ActivateWindow(newWindow); - - return newWindow; - } + public async Task UnsafeCreateNewWindow(Type windowType, bool activate = true, string id = "") => + await _windowCoordinator.CreateUnsafeAsync(windowType, activate, id); public async Task UnsafeCreateNewWindow(bool activate = true, string id = "") where TWindow : TemplateWindow, new() => (TWindow)await UnsafeCreateNewWindow(typeof(TWindow), activate, id); - public async Task SafeCreateNewWindow(Type windowType, bool activate = true) - { - await _localizerReady; - - var findWindows = OpenWindows.Where(w => windowType.IsInstanceOfType(w)).ToList(); - var activeFindWindow = findWindows.FirstOrDefault(w => w.DispatcherQueue != null); - - // One live window is reused; several or a dead one are closed and replaced by a new window. - if (activeFindWindow != null && findWindows.Count == 1) - { - if (activate) - ActivateWindow(activeFindWindow); - return activeFindWindow; - } - else - { - foreach (var viewWindow in findWindows) - { - viewWindow.Close(); - OpenWindows.Remove(viewWindow); - } - - var newWindow = (Window)Activator.CreateInstance(windowType); - - WindowsPositionHelper.SetCustomWindowSizeAndPositionFromSettings(newWindow); - RegisterWindow(newWindow); - - if (activate) - ActivateWindow(newWindow); - - return newWindow; - } - } + public async Task SafeCreateNewWindow(Type windowType, bool activate = true) => + await _windowCoordinator.CreateSafeAsync(windowType, activate); public async Task SafeCreateNewWindow(bool activate = true) where TWindow : Window, new() => (TWindow)await SafeCreateNewWindow(typeof(TWindow), activate); @@ -186,70 +105,11 @@ private void Window_ClosedHandler(object sender, WindowEventArgs e) return; if (e.Handled) return; - var dispatcherQueue = window.DispatcherQueue; - bool migrationWindowClosed = window is WelcomeWindow welcomeWindow && - string.Equals( - welcomeWindow.Id, - WelcomeWindow.MigrationWindowId, - StringComparison.OrdinalIgnoreCase); - - try - { - WindowsPositionHelper.SaveWindowSizeAndPostionsettings(window); - } - catch (Exception exception) - { - Logger.Instance.CreateWarningLog(nameof(App), exception.ToString()); - } - finally - { - window.Closed -= Window_ClosedHandler; - window.SizeChanged -= Window_SizeChanged; - - // Leave visual-tree teardown to WinUI, including diagnostics notifications. - try - { _modalWindows.ReleaseModal(window, isClosing: true); } - catch (Exception exception) { Logger.Instance.CreateWarningLog(nameof(App), exception.ToString()); } - // List.Remove does not throw for a missing item; the guard only keeps the cleanup going. - try - { OpenWindows.Remove(window); } - catch (Exception exception) { Logger.Instance.CreateWarningLog(nameof(App), exception.ToString()); } - if (migrationWindowClosed) - Program.CompleteMigrationActivation(); - _modalWindows.ForgetOwner(window); - } - - if (migrationWindowClosed) - { - if (!dispatcherQueue.TryEnqueue( - Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, - ExitIfIdle)) - { - ExitIfIdle(); - } - return; - } - - if (OpenWindows.Count == 0 && ApplicationTaskMonitor.IsStoreWorking()) - { - _ = SafeCreateNewWindow(activate: false); - } - else - { - if (!dispatcherQueue.TryEnqueue( - Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, - ExitIfIdle)) - { - ExitIfIdle(); - } - } - + _windowCloseCoordinator.HandleClosed(window); } - public TWindow GetCurrentWindowFromType() where TWindow : Window - { - return OpenWindows.OfType().FirstOrDefault(w => w.DispatcherQueue != null); - } + public TWindow GetCurrentWindowFromType() where TWindow : Window => + (TWindow)_windowCoordinator.GetCurrent(typeof(TWindow)); public FrameworkElement GetRootFrame() { diff --git a/CDPIUI/App.xaml.cs b/CDPIUI/App.xaml.cs index 88f35524..2a87ef08 100644 --- a/CDPIUI/App.xaml.cs +++ b/CDPIUI/App.xaml.cs @@ -24,6 +24,11 @@ public partial class App : Application public List OpenWindows { get; private set; } = new List(); private readonly ModalWindowCoordinator _modalWindows; + private readonly AppWindowCoordinator _windowCoordinator; + private readonly AppWindowCloseCoordinator _windowCloseCoordinator; + private readonly AppActivationDispatcher _activationDispatcher; + private readonly AppFileActivationHandler _fileActivationHandler; + private readonly AppIdleExitController _idleExitController; private readonly Microsoft.UI.Dispatching.DispatcherQueue _uiDispatcher = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread(); @@ -32,6 +37,33 @@ public partial class App : Application public App() { _modalWindows = new ModalWindowCoordinator(OpenWindows); + _windowCoordinator = new AppWindowCoordinator(OpenWindows, () => _localizerReady, + new AppWindowOperations(RegisterWindow)); + _fileActivationHandler = new AppFileActivationHandler( + new AppFileActivationOperations(this, OpenConditionalTaskImportAsync)); + _activationDispatcher = new AppActivationDispatcher( + TryHandleMigrationActivationAsync, + TryHandleMigrationActivationAsync, + ProcessFiles, + CommandsHandler.HandleCommandAsync, + HandleCoreDirectActivationAsync, + CommandsHandler.HandleCommand, + CommandLineSplitter.Split, + exception => Logger.Instance.CreateWarningLog(nameof(App), $"Cannot process startup activation: {exception}")); + _idleExitController = new AppIdleExitController( + () => OpenWindows.Count, + () => Program.IsMigrationActivationPending, + () => ApplicationTaskMonitor.IsStoreWorking(), + () => ApplicationTaskMonitor.IsGoodCheckRunning(), + () => SafeCreateNewWindow(activate: false), + () => GetCurrentWindowFromType()?.Close(), + Exit, + exception => Logger.Instance.CreateWarningLog( + nameof(App), $"Cannot update background operation state: {exception.Message}")); + _windowCloseCoordinator = new AppWindowCloseCoordinator(OpenWindows, + new AppWindowCloseOperations(_modalWindows, + window => { window.Closed -= Window_ClosedHandler; window.SizeChanged -= Window_SizeChanged; }, + () => SafeCreateNewWindow(activate: false), ExitIfIdle)); this.InitializeComponent(); RegisterUnhandledExceptionHandlers(); PipeClientService.Instance.MessageReceived += (m) => CommandsHandler.HandleCommand(m); @@ -67,29 +99,7 @@ protected override void OnLaunched(LaunchActivatedEventArgs args) _ = PipeClientService.Instance.Start(); } - private void StoreStateChanged(bool isWorking) - { - try - { - if (isWorking && OpenWindows.Count == 0 && - !Program.IsMigrationActivationPending) - { - _ = SafeCreateNewWindow(activate: false); - } - if (!isWorking) - { - GetCurrentWindowFromType()?.Close(); - ExitIfIdle(); - } - } - catch (Exception ex) - { - Logger.Instance.CreateWarningLog( - nameof(App), - $"Cannot update background operation state: {ex.Message}"); - ExitIfIdle(); - } - } + private void StoreStateChanged(bool isWorking) => _idleExitController.HandleStoreStateChanged(isWorking); private void PipeConnected() { @@ -134,21 +144,7 @@ private async Task GetReadyFeaturesAsync() } } - private void ExitIfIdle() - { - if (Program.IsMigrationActivationPending && OpenWindows.Count == 0) - { - return; - } - if (OpenWindows.Count != 0 || - ApplicationTaskMonitor.IsStoreWorking() || - ApplicationTaskMonitor.IsGoodCheckRunning()) - { - return; - } - - Exit(); - } + private void ExitIfIdle() => _idleExitController.ExitIfIdle(); public static TEnum GetEnum(string text) where TEnum : struct { diff --git a/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.Editor.cs b/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.Editor.cs index f04b7ab9..a95d2551 100644 --- a/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.Editor.cs +++ b/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.Editor.cs @@ -1,6 +1,6 @@ using System; -using System.Linq; using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.Helper.UserExperience; using CDPIUI.ViewModels.ConfigMaker; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; @@ -14,7 +14,7 @@ namespace CDPIUI.Controls.CreateConfigHelper; // The command text editor: text, cursor, zoom, background and highlighting. public sealed partial class ConfigMakerUserControl { - private string _highlightSignature = string.Empty; + private readonly DiagnosticHighlightingUpdater _highlightingUpdater = new(); string IConfigMakerView.EditorText => CommandEditor.Text; @@ -116,7 +116,7 @@ private void ApplyEditorBackground() "MicaSmoke" => GetApplicationBrush("SmokeFillColorDefaultBrush"), _ => new SolidColorBrush(Color.FromArgb(255, 0, 0, 0)), }; - _highlightSignature = string.Empty; + _highlightingUpdater.Reset(); ApplyEditorTheme(); } @@ -132,26 +132,18 @@ private void ApplyEditorTheme() bool isLight = !usesForcedDarkBackground && (ActualTheme == ElementTheme.Light || (ActualTheme == ElementTheme.Default && ((App)Application.Current).CurrentTheme == ElementTheme.Light)); - string[] errorTokens = ViewModel.Diagnostics - .Where(item => item.Source.Severity == ComponentCommandDiagnosticSeverity.Error) - .Select(item => item.Source.Token) - .ToArray(); - string[] warningTokens = ViewModel.Diagnostics - .Where(item => item.Source.Severity == ComponentCommandDiagnosticSeverity.Warning) - .Select(item => item.Source.Token) - .ToArray(); - string newSignature = $"{editorBackground}|{isLight}|{string.Join(',', errorTokens)}|{string.Join(',', warningTokens)}"; - if (string.Equals(_highlightSignature, newSignature, StringComparison.Ordinal)) - { - return; - } - - _highlightSignature = newSignature; - CommandEditor.SyntaxHighlighting = isLight - ? new LightDefaultHighlighter(errorTokens, warningTokens) - : new DarkDefaultHighlighter(errorTokens, warningTokens); - CommandEditor.Design = isLight - ? TextControlBoxDesigns.DefaultLightDesign - : TextControlBoxDesigns.DefaultDarkDesign; + _highlightingUpdater.Update(editorBackground, isLight, () => ViewModel.Diagnostics, + static item => item.Source.Severity == ComponentCommandDiagnosticSeverity.Error, + static item => item.Source.Severity == ComponentCommandDiagnosticSeverity.Warning, + static item => item.Source.Token, + (light, errorTokens, warningTokens) => + { + CommandEditor.SyntaxHighlighting = light + ? new LightDefaultHighlighter(errorTokens, warningTokens) + : new DarkDefaultHighlighter(errorTokens, warningTokens); + CommandEditor.Design = light + ? TextControlBoxDesigns.DefaultLightDesign + : TextControlBoxDesigns.DefaultDarkDesign; + }); } } diff --git a/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.Layout.cs b/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.Layout.cs index fd152159..5144255f 100644 --- a/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.Layout.cs +++ b/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.Layout.cs @@ -1,5 +1,6 @@ using System; using CDPIUI.Controls.Navigation; +using CDPIUI.Helper.CreateConfigHelper; using CDPIUI.ViewModels.ConfigMaker; using Microsoft.UI.Xaml; @@ -8,10 +9,8 @@ namespace CDPIUI.Controls.CreateConfigHelper; // The resizable panels (preset files, command reference and the bottom panel) and their tabs. public sealed partial class ConfigMakerUserControl { - private bool _layoutInitialized; - private bool _updatingLayoutBounds; + private readonly ConfigMakerPanelLayoutController _panelLayout; private double _savedEditorWidth = 620; - private double _savedEditorHeight = 420; public bool IsCommandPanelVisible => CommandPanel.Visibility == Visibility.Visible; public bool IsBottomPanelVisible => BottomPanel.Visibility == Visibility.Visible; @@ -68,7 +67,7 @@ public void SetBottomPanelVisible(bool visible) } if (!visible) { - _savedEditorHeight = EditorPanel.ActualHeight; + _panelLayout.RememberEditorHeight(EditorPanel.ActualHeight); } HorizontalSizerRow.Height = ShowPanel(BottomPanel, HorizontalContentSizer, visible); CompletePanelChange(); @@ -84,7 +83,7 @@ private static GridLength ShowPanel(UIElement panel, UIElement sizer, bool visib private void CompletePanelChange() { - _layoutInitialized = false; + _panelLayout.Invalidate(); UpdateLayoutBounds(); PanelStateChanged?.Invoke(this, EventArgs.Empty); } @@ -93,87 +92,13 @@ private void CompletePanelChange() private void ResizablePanel_SizeChanged(object sender, SizeChangedEventArgs e) { - if (!_updatingLayoutBounds) + if (!_panelLayout.IsUpdating) { UpdateLayoutBounds(); } } - private void UpdateLayoutBounds() - { - if (_updatingLayoutBounds || RootGrid.ActualWidth <= 0 || RootGrid.ActualHeight <= 0) - { - return; - } - - _updatingLayoutBounds = true; - try - { - const double editorMinWidth = 360; - const double commandMinWidth = 340; - const double editorMinHeight = 180; - const double bottomMinHeight = 110; - - double filesWidth = 0; - if (IsPresetFilesPanelVisible) - { - double maximumFilesWidth = Math.Max( - 150, - RootGrid.ActualWidth - editorMinWidth - - (IsCommandPanelVisible ? commandMinWidth + VerticalSizerColumn.Width.Value : 0) - - PresetFilesSizerColumn.Width.Value); - PresetFilesPanel.MaxWidth = Math.Max( - PresetFilesPanel.MinWidth, - Math.Min(RootGrid.ActualWidth * 0.45, maximumFilesWidth)); - PresetFilesPanel.Width = Math.Clamp( - PresetFilesPanel.Width, - PresetFilesPanel.MinWidth, - PresetFilesPanel.MaxWidth); - filesWidth = PresetFilesPanel.Width + PresetFilesSizerColumn.Width.Value; - } - - double availableMainWidth = Math.Max(editorMinWidth, RootGrid.ActualWidth - filesWidth); - - if (IsCommandPanelVisible) - { - double maxEditorWidth = Math.Max( - editorMinWidth, - availableMainWidth - commandMinWidth - VerticalSizerColumn.Width.Value); - EditorWorkspace.MaxWidth = maxEditorWidth; - EditorWorkspace.Width = maxEditorWidth; - } - else - { - EditorWorkspace.MaxWidth = availableMainWidth; - EditorWorkspace.Width = availableMainWidth; - } - - double availableMainHeight = Math.Max(editorMinHeight, RootGrid.ActualHeight); - - if (IsBottomPanelVisible) - { - double maxEditorHeight = Math.Max( - editorMinHeight, - availableMainHeight - bottomMinHeight - HorizontalSizerRow.Height.Value); - EditorPanel.MaxHeight = maxEditorHeight; - double requestedHeight = _layoutInitialized - ? EditorPanel.Height - : Math.Min(_savedEditorHeight, maxEditorHeight); - EditorPanel.Height = Math.Clamp(requestedHeight, editorMinHeight, maxEditorHeight); - } - else - { - EditorPanel.MaxHeight = availableMainHeight; - EditorPanel.Height = availableMainHeight; - } - - _layoutInitialized = true; - } - finally - { - _updatingLayoutBounds = false; - } - } + private void UpdateLayoutBounds() => _panelLayout.Update(); private void CloseTreeViewButton_Click(object sender, RoutedEventArgs e) => SetPresetFilesPanelVisible(false); diff --git a/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.xaml.cs b/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.xaml.cs index c3d73ccb..921893c6 100644 --- a/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.xaml.cs +++ b/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.xaml.cs @@ -49,6 +49,10 @@ public sealed partial class ConfigMakerUserControl : UserControl, IConfigMakerVi public ConfigMakerUserControl() { + _panelLayout = new ConfigMakerPanelLayoutController(new ConfigMakerPanelLayoutView( + () => RootGrid, () => PresetFilesPanel, () => CommandPanel, () => BottomPanel, + () => EditorWorkspace, () => EditorPanel, () => PresetFilesSizerColumn, + () => VerticalSizerColumn, () => HorizontalSizerRow)); ViewModel = new ConfigMakerViewModel(this, DispatcherQueue); ViewModel.PropertyChanged += ViewModel_PropertyChanged; ViewModel.CommandTextChanged += text => CommandTextChanged?.Invoke(text); diff --git a/CDPIUI/Controls/CreateConfigHelper/EnumModel.cs b/CDPIUI/Controls/CreateConfigHelper/EnumModel.cs index 5a5a072c..e3f581ed 100644 --- a/CDPIUI/Controls/CreateConfigHelper/EnumModel.cs +++ b/CDPIUI/Controls/CreateConfigHelper/EnumModel.cs @@ -1,3 +1,6 @@ +#nullable enable annotations +#nullable disable warnings + namespace CDPIUI; public class EnumModel diff --git a/CDPIUI/Controls/MenuBar/MenuBarController.cs b/CDPIUI/Controls/MenuBar/MenuBarController.cs index dc4e5d0f..9d1d2389 100644 --- a/CDPIUI/Controls/MenuBar/MenuBarController.cs +++ b/CDPIUI/Controls/MenuBar/MenuBarController.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.Linq; using CDPIUI.Controls.Default; +using CDPIUI.Helper.UserExperience; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Navigation; @@ -288,30 +289,13 @@ private void AddEntryToRegistry(MenuEntry entry, bool addToPhysicalTree) } } - private void PruneUnclaimedEntries() - { - for (var index = _rootEntries.Count - 1; index >= 0; index--) - { - if (!PruneEntry(_rootEntries[index])) - continue; - - _rootEntries.RemoveAt(index); - } - } + private void PruneUnclaimedEntries() => + PostOrderTreePruner.Prune(_rootEntries, static entry => entry.Children, + static entry => entry.IsStrong || entry.WeakScopes.Count > 0 || entry.Children.Count > 0, + RemoveEntry); - private bool PruneEntry(MenuEntry entry) + private void RemoveEntry(MenuEntry entry) { - for (var index = entry.Children.Count - 1; index >= 0; index--) - { - if (!PruneEntry(entry.Children[index])) - continue; - - entry.Children.RemoveAt(index); - } - - if (entry.IsStrong || entry.WeakScopes.Count > 0 || entry.Children.Count > 0) - return false; - if (entry.PublicId != null) _entriesById.Remove(entry.PublicId); @@ -320,7 +304,6 @@ private bool PruneEntry(MenuEntry entry) else GetChildren(entry.Parent.Element).Remove((MenuFlyoutItemBase)entry.Element); - return true; } private bool TryMaterializeTemplate( diff --git a/CDPIUI/Controls/Universal/UtilityButtonControls.xaml.cs b/CDPIUI/Controls/Universal/UtilityButtonControls.xaml.cs index a0d5ccd2..f678d4b4 100644 --- a/CDPIUI/Controls/Universal/UtilityButtonControls.xaml.cs +++ b/CDPIUI/Controls/Universal/UtilityButtonControls.xaml.cs @@ -5,6 +5,7 @@ using System.Threading; using System.Threading.Tasks; using CDPIUI.Commands; +using CDPIUI.Helper.UserExperience; using Microsoft.UI.Composition; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; @@ -332,58 +333,21 @@ private static bool AreSameStates( return true; } - private async Task RunVisibilitySequenceAsync( + private Task RunVisibilitySequenceAsync( IReadOnlyList<(Button Button, Visibility Visibility)> hiddenButtons, IReadOnlyList<(Button Button, Visibility Visibility)> shownButtons, CancellationTokenSource cancellation) - { - try - { - int transitionCount = hiddenButtons.Count + shownButtons.Count; - int transitionIndex = 0; - - foreach ((Button button, Visibility visibility) in hiddenButtons) - { - bool repositionsButtonsToTheLeft = HasVisibleButtonToTheLeft(button); - button.Visibility = visibility; - transitionIndex++; - - if (transitionIndex < transitionCount) - { - TimeSpan duration = repositionsButtonsToTheLeft - ? RepositionAnimationDuration - : HideAnimationDuration; - await Task.Delay(duration + ButtonSequenceGap, cancellation.Token); - } - } - - foreach ((Button button, Visibility visibility) in shownButtons) - { - bool repositionsButtonsToTheLeft = HasVisibleButtonToTheLeft(button); - button.Visibility = visibility; - transitionIndex++; - - if (transitionIndex < transitionCount) - { - TimeSpan duration = repositionsButtonsToTheLeft - ? Max(ShowAnimationDuration, RepositionAnimationDuration / 2) - : ShowAnimationDuration; - await Task.Delay(duration + ButtonSequenceGap, cancellation.Token); - } - } - } - catch (OperationCanceledException) - { - // The sequence was cancelled by a newer change or by suspended animations: nothing is left to do. - } - finally + => TwoPhaseTransitionSequence.RunAsync(hiddenButtons, shownButtons, HasVisibleButtonToTheLeft, + (button, visibility) => button.Visibility = visibility, + repositions => (repositions ? RepositionAnimationDuration : HideAnimationDuration) + ButtonSequenceGap, + repositions => (repositions ? Max(ShowAnimationDuration, RepositionAnimationDuration / 2) : ShowAnimationDuration) + ButtonSequenceGap, + static (duration, token) => Task.Delay(duration, token), cancellation, () => { if (ReferenceEquals(_visibilitySequenceCancellation, cancellation)) _visibilitySequenceCancellation = null; cancellation.Dispose(); - } - } + }); private bool HasVisibleButtonToTheLeft(Button targetButton) { diff --git a/CDPIUI/Helper/Basic/AppActivationDispatcher.cs b/CDPIUI/Helper/Basic/AppActivationDispatcher.cs new file mode 100644 index 00000000..0b4444df --- /dev/null +++ b/CDPIUI/Helper/Basic/AppActivationDispatcher.cs @@ -0,0 +1,125 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace CDPIUI.Helper.Basic; + +// Preserves the distinct first-start and redirected activation sequences. Actions own all effects. +internal sealed class AppActivationDispatcher +{ + private readonly Func, Task> _migrationArguments; + private readonly Func> _migrationLaunch; + private readonly Func> _files; + private readonly Func> _protocol; + private readonly Func> _coreDirect; + private readonly Func _guiDirect; + private readonly Func _splitArguments; + private readonly Action _startupError; + + public AppActivationDispatcher( + Func, Task> migrationArguments, + Func> migrationLaunch, + Func> files, + Func> protocol, + Func> coreDirect, + Func guiDirect, + Func splitArguments, + Action startupError) + { + _migrationArguments = migrationArguments; + _migrationLaunch = migrationLaunch; + _files = files; + _protocol = protocol; + _coreDirect = coreDirect; + _guiDirect = guiDirect; + _splitArguments = splitArguments; + _startupError = startupError; + } + + public async Task ProcessStartupAsync( + string[] arguments, Func getInitialActivation) + { + bool isFileProcessed = false; + bool isActionPreferred = false; + bool isMigrationProcessed = false; + try + { + isMigrationProcessed = await _migrationArguments(arguments); + if (!isMigrationProcessed && getInitialActivation(AppActivationKind.Launch) is { Kind: AppActivationKind.Launch } launch) + { + isMigrationProcessed = await _migrationLaunch(launch.GetLaunchArguments()); + } + if (getInitialActivation(AppActivationKind.File) is { Kind: AppActivationKind.File } files) + { + isFileProcessed = await _files(files.Files!); + } + if (getInitialActivation(AppActivationKind.Protocol) is { Kind: AppActivationKind.Protocol } protocol) + { + isActionPreferred = await _protocol(protocol.ProtocolUri!); + } + if (!isFileProcessed) + { + isFileProcessed = await _files(arguments); + } + + string? protocolArg = isActionPreferred + ? null + : arguments.FirstOrDefault(value => value.StartsWith("----ms-protocol:")); + if (protocolArg != null) + { + isActionPreferred = await _protocol(protocolArg["----ms-protocol:".Length..]); + } + string? directArgs = arguments.FirstOrDefault(value => value.StartsWith("--direct:")); + if (directArgs != null) + { + string value = directArgs["--direct:".Length..]; + isActionPreferred = await _coreDirect(value); + if (!isActionPreferred) + { + isActionPreferred = _guiDirect(value); + } + } + } + catch (Exception exception) + { + _startupError(exception); + } + return isFileProcessed || isActionPreferred || isMigrationProcessed; + } + + // Exceptions intentionally reach App's existing redirected-activation error boundary. + public async Task ProcessRedirectedAsync(AppActivationRequest activation) + { + bool result = false; + if (activation.Kind == AppActivationKind.Protocol) + { + result = await _protocol(activation.ProtocolUri!); + } + if (activation.Kind == AppActivationKind.File) + { + result = await _files(activation.Files!); + } + else if (activation.Kind == AppActivationKind.Launch) + { + result = await _migrationLaunch(activation.GetLaunchArguments()); + string[] args = _splitArguments(activation.GetLaunchArguments()!); + if (!result) + { + string? directArgs = args.FirstOrDefault(value => value.StartsWith("--direct:")); + if (directArgs != null) + { + string value = directArgs["--direct:".Length..]; + result = await _coreDirect(value) || _guiDirect(value); + } + } + if (!result) + { + result = await _files(args); + } + } + return result; + } +} diff --git a/CDPIUI/Helper/Basic/AppActivationRequest.cs b/CDPIUI/Helper/Basic/AppActivationRequest.cs new file mode 100644 index 00000000..72f2a88c --- /dev/null +++ b/CDPIUI/Helper/Basic/AppActivationRequest.cs @@ -0,0 +1,24 @@ +#nullable enable + +using System; + +namespace CDPIUI.Helper.Basic; + +internal enum AppActivationKind +{ + None, + Launch, + File, + Protocol, +} + +// WinRT activation is translated at the boundary; orchestration needs only these values. +internal sealed record AppActivationRequest( + AppActivationKind Kind = AppActivationKind.None, + string? Arguments = null, + string[]? Files = null, + string? ProtocolUri = null, + Func? ReadLaunchArguments = null) +{ + public string? GetLaunchArguments() => ReadLaunchArguments != null ? ReadLaunchArguments() : Arguments; +} diff --git a/CDPIUI/Helper/Basic/AppActivationRequestAdapter.cs b/CDPIUI/Helper/Basic/AppActivationRequestAdapter.cs new file mode 100644 index 00000000..48715194 --- /dev/null +++ b/CDPIUI/Helper/Basic/AppActivationRequestAdapter.cs @@ -0,0 +1,30 @@ +#nullable enable + +using System.Linq; +using Microsoft.Windows.AppLifecycle; +using Windows.ApplicationModel.Activation; + +namespace CDPIUI.Helper.Basic; + +internal static class AppActivationRequestAdapter +{ + public static AppActivationRequest From(AppActivationArguments? activation, AppActivationKind? requestedKind = null) + { + if (requestedKind is null or AppActivationKind.Launch && + activation?.Kind == ExtendedActivationKind.Launch && activation.Data is ILaunchActivatedEventArgs launch) + { + return new(AppActivationKind.Launch, ReadLaunchArguments: () => launch.Arguments); + } + if (requestedKind is null or AppActivationKind.File && + activation?.Kind == ExtendedActivationKind.File && activation.Data is IFileActivatedEventArgs files) + { + return new(AppActivationKind.File, Files: files.Files.Select(file => file.Path).ToArray()); + } + if (requestedKind is null or AppActivationKind.Protocol && + activation?.Kind == ExtendedActivationKind.Protocol && activation.Data is IProtocolActivatedEventArgs protocol) + { + return new(AppActivationKind.Protocol, ProtocolUri: protocol.Uri.ToString()); + } + return new(); + } +} diff --git a/CDPIUI/Helper/Basic/AppFileActivationHandler.cs b/CDPIUI/Helper/Basic/AppFileActivationHandler.cs new file mode 100644 index 00000000..2743d39f --- /dev/null +++ b/CDPIUI/Helper/Basic/AppFileActivationHandler.cs @@ -0,0 +1,55 @@ +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +namespace CDPIUI.Helper.Basic; + +// File activation selects the first supported route; operations retain all import/window effects. +internal sealed class AppFileActivationHandler +{ + private static readonly string[] SupportedFilePaths = + [".cdpisignedpack", ".cdpiconfigpack", ".cdpipatch", ".cdpitask", ".cdpiconfig"]; + + private readonly IAppFileActivationOperations _operations; + + public AppFileActivationHandler(IAppFileActivationOperations operations) => _operations = operations; + + public async Task ProcessFiles(string[] files) + { + foreach (string file in files) + { + var _file = file.Replace("\"", ""); + _operations.LogFile(_file); + + if (_operations.PathExists(_file) && SupportedFilePaths.Contains( + Path.GetExtension(_file), + StringComparer.OrdinalIgnoreCase)) + { + if (_operations.IsConfigShareSupported(_file)) + { + await _operations.OpenConfigShareAsync(_file); + return true; + } + + if (Path.GetExtension(_file).Equals(".cdpitask", StringComparison.OrdinalIgnoreCase)) + { + await _operations.OpenConditionalTaskAsync(_file); + return true; + } + + if (Path.GetExtension(_file).Equals(".cdpipatch", StringComparison.OrdinalIgnoreCase)) + { + await _operations.OpenUpdateFileAsync(_file); + return true; + } + + await _operations.OpenStorePackAsync(_file); + return true; // Only first file will be processed. + } + } + return false; + } +} diff --git a/CDPIUI/Helper/Basic/AppFileActivationOperations.cs b/CDPIUI/Helper/Basic/AppFileActivationOperations.cs new file mode 100644 index 00000000..e3a7c270 --- /dev/null +++ b/CDPIUI/Helper/Basic/AppFileActivationOperations.cs @@ -0,0 +1,50 @@ +#nullable enable + +using System; +using System.IO; +using System.Threading.Tasks; +using CDPIUI.AddOns.ConfigShare; +using CDPIUI.Core.Basic; +using CDPIUI.Messages; + +namespace CDPIUI.Helper.Basic; + +// Preserves the existing WinUI/import calls. Construction does not open or inspect anything. +internal sealed class AppFileActivationOperations : IAppFileActivationOperations +{ + private readonly App _app; + private readonly Func _openConditionalTask; + + public AppFileActivationOperations(App app, Func openConditionalTask) + { + _app = app; + _openConditionalTask = openConditionalTask; + } + + public void LogFile(string path) => Logger.Instance.CreateDebugLog(nameof(App), $"Working on file {path}"); + public bool PathExists(string path) => Path.Exists(path); + public bool IsConfigShareSupported(string path) => ConfigShareService.IsSupported(path); + + public async Task OpenConfigShareAsync(string path) + { + var importDialog = await _app.UnsafeCreateNewWindow(activate: false); + App.ActivateWindow(importDialog); + await importDialog.SetFileAsync(path); + } + + public Task OpenConditionalTaskAsync(string path) => _openConditionalTask(path); + + public async Task OpenUpdateFileAsync(string path) + { + var updateDialog = await _app.SafeCreateNewWindow(activate: false); + updateDialog.SetUpdateFilePath(path); + App.ActivateWindow(updateDialog); + } + + public async Task OpenStorePackAsync(string path) + { + var window = await _app.SafeCreateNewWindow(); + // Not awaited: the import runs while the dialog is open. SetPackFilePath logs its own errors. + _ = window.SetPackFilePath(path); + } +} diff --git a/CDPIUI/Helper/Basic/AppIdleExitController.cs b/CDPIUI/Helper/Basic/AppIdleExitController.cs new file mode 100644 index 00000000..72eac4aa --- /dev/null +++ b/CDPIUI/Helper/Basic/AppIdleExitController.cs @@ -0,0 +1,68 @@ +#nullable enable + +using System; +using System.Threading.Tasks; + +namespace CDPIUI.Helper.Basic; + +// Reads live application state at the original Store/idle decision points. +internal sealed class AppIdleExitController +{ + private readonly Func _windowCount; + private readonly Func _migrationPending; + private readonly Func _storeWorking; + private readonly Func _goodCheckRunning; + private readonly Func _createPrepare; + private readonly Action _closePrepare; + private readonly Action _exit; + private readonly Action _warn; + + public AppIdleExitController(Func windowCount, Func migrationPending, + Func storeWorking, Func goodCheckRunning, Func createPrepare, + Action closePrepare, Action exit, Action warn) + { + _windowCount = windowCount; + _migrationPending = migrationPending; + _storeWorking = storeWorking; + _goodCheckRunning = goodCheckRunning; + _createPrepare = createPrepare; + _closePrepare = closePrepare; + _exit = exit; + _warn = warn; + } + + public void HandleStoreStateChanged(bool isWorking) + { + try + { + if (isWorking && _windowCount() == 0 && !_migrationPending()) + { + _ = _createPrepare(); + } + if (!isWorking) + { + _closePrepare(); + ExitIfIdle(); + } + } + catch (Exception exception) + { + _warn(exception); + ExitIfIdle(); + } + } + + public void ExitIfIdle() + { + if (_migrationPending() && _windowCount() == 0) + { + return; + } + if (_windowCount() != 0 || _storeWorking() || _goodCheckRunning()) + { + return; + } + + _exit(); + } +} diff --git a/CDPIUI/Helper/Basic/AppWindowCloseCoordinator.cs b/CDPIUI/Helper/Basic/AppWindowCloseCoordinator.cs new file mode 100644 index 00000000..945aa25a --- /dev/null +++ b/CDPIUI/Helper/Basic/AppWindowCloseCoordinator.cs @@ -0,0 +1,61 @@ +#nullable enable + +using System; +using System.Collections.Generic; + +namespace CDPIUI.Helper.Basic; + +// Preserves the window-close cleanup and the original post-cleanup dispatch policy. +internal sealed class AppWindowCloseCoordinator where TWindow : class +{ + private readonly List _windows; + private readonly IAppWindowCloseOperations _operations; + + public AppWindowCloseCoordinator(List windows, IAppWindowCloseOperations operations) + { + _windows = windows; + _operations = operations; + } + + public void HandleClosed(TWindow window) + { + Func enqueueExit = _operations.CaptureExitEnqueue(window); + bool migrationWindowClosed = _operations.IsMigrationWindow(window); + try + { + _operations.SavePosition(window); + } + catch (Exception exception) + { + _operations.Warn(exception); + } + finally + { + _operations.Detach(window); + try { _operations.ReleaseModal(window); } + catch (Exception exception) { _operations.Warn(exception); } + try { _windows.Remove(window); } + catch (Exception exception) { _operations.Warn(exception); } + if (migrationWindowClosed) + _operations.CompleteMigration(); + _operations.ForgetOwner(window); + } + + if (migrationWindowClosed) + { + if (!enqueueExit()) + _operations.ExitIfIdle(); + return; + } + + if (_windows.Count == 0 && _operations.IsStoreWorking()) + { + _ = _operations.CreatePrepareAsync(); + } + else + { + if (!enqueueExit()) + _operations.ExitIfIdle(); + } + } +} diff --git a/CDPIUI/Helper/Basic/AppWindowCloseOperations.cs b/CDPIUI/Helper/Basic/AppWindowCloseOperations.cs new file mode 100644 index 00000000..4390ce2a --- /dev/null +++ b/CDPIUI/Helper/Basic/AppWindowCloseOperations.cs @@ -0,0 +1,41 @@ +#nullable enable + +using System; +using System.Threading.Tasks; +using CDPIUI.Core.Basic; +using CDPIUI.Helper.WindowHelper; +using Microsoft.UI.Dispatching; +using Microsoft.UI.Xaml; + +namespace CDPIUI.Helper.Basic; + +internal sealed class AppWindowCloseOperations : IAppWindowCloseOperations +{ + private readonly ModalWindowCoordinator _modal; + private readonly Action _detach; + private readonly Func _createPrepare; + private readonly Action _exit; + + public AppWindowCloseOperations(ModalWindowCoordinator modal, Action detach, + Func createPrepare, Action exit) + { + _modal = modal; _detach = detach; _createPrepare = createPrepare; _exit = exit; + } + + public Func CaptureExitEnqueue(Window window) + { + var dispatcherQueue = window.DispatcherQueue; + return () => dispatcherQueue.TryEnqueue(DispatcherQueuePriority.Low, () => _exit()); + } + public bool IsMigrationWindow(Window window) => window is WelcomeWindow welcomeWindow && + string.Equals(welcomeWindow.Id, WelcomeWindow.MigrationWindowId, StringComparison.OrdinalIgnoreCase); + public void SavePosition(Window window) => WindowsPositionHelper.SaveWindowSizeAndPostionsettings(window); + public void Detach(Window window) => _detach(window); + public void ReleaseModal(Window window) => _modal.ReleaseModal(window, isClosing: true); + public void Warn(Exception error) => Logger.Instance.CreateWarningLog(nameof(App), error.ToString()); + public void CompleteMigration() => Program.CompleteMigrationActivation(); + public void ForgetOwner(Window window) => _modal.ForgetOwner(window); + public bool IsStoreWorking() => ApplicationTaskMonitor.IsStoreWorking(); + public Task CreatePrepareAsync() => _createPrepare(); + public void ExitIfIdle() => _exit(); +} diff --git a/CDPIUI/Helper/Basic/IAppFileActivationOperations.cs b/CDPIUI/Helper/Basic/IAppFileActivationOperations.cs new file mode 100644 index 00000000..e4d29ac3 --- /dev/null +++ b/CDPIUI/Helper/Basic/IAppFileActivationOperations.cs @@ -0,0 +1,16 @@ +#nullable enable + +using System.Threading.Tasks; + +namespace CDPIUI.Helper.Basic; + +internal interface IAppFileActivationOperations +{ + void LogFile(string path); + bool PathExists(string path); + bool IsConfigShareSupported(string path); + Task OpenConfigShareAsync(string path); + Task OpenConditionalTaskAsync(string path); + Task OpenUpdateFileAsync(string path); + Task OpenStorePackAsync(string path); +} diff --git a/CDPIUI/Helper/Basic/IAppWindowCloseOperations.cs b/CDPIUI/Helper/Basic/IAppWindowCloseOperations.cs new file mode 100644 index 00000000..d744181e --- /dev/null +++ b/CDPIUI/Helper/Basic/IAppWindowCloseOperations.cs @@ -0,0 +1,21 @@ +#nullable enable + +using System; +using System.Threading.Tasks; + +namespace CDPIUI.Helper.Basic; + +internal interface IAppWindowCloseOperations where TWindow : class +{ + Func CaptureExitEnqueue(TWindow window); + bool IsMigrationWindow(TWindow window); + void SavePosition(TWindow window); + void Detach(TWindow window); + void ReleaseModal(TWindow window); + void Warn(Exception error); + void CompleteMigration(); + void ForgetOwner(TWindow window); + bool IsStoreWorking(); + Task CreatePrepareAsync(); + void ExitIfIdle(); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ComponentCommandValidationService.cs b/CDPIUI/Helper/CreateConfigHelper/ComponentCommandValidationService.cs index d528cfda..fb11c5bc 100644 --- a/CDPIUI/Helper/CreateConfigHelper/ComponentCommandValidationService.cs +++ b/CDPIUI/Helper/CreateConfigHelper/ComponentCommandValidationService.cs @@ -1,3 +1,6 @@ +#nullable enable annotations +#nullable disable warnings + using System; using System.Collections.Generic; using System.Linq; diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandHelpLoader.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandHelpLoader.cs new file mode 100644 index 00000000..f4915a3d --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandHelpLoader.cs @@ -0,0 +1,95 @@ +#nullable enable + +using System; +using System.Threading; +using System.Threading.Tasks; +using CDPIUI.ViewModels; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Owns the active help request and loading state. The host supplies the source and UI effects. +internal sealed class ConfigMakerCommandHelpLoader : ObservableObject +{ + private readonly ConfigMakerCommandHelpPanel _panel; + private readonly Func _currentComponent; + private readonly Func _localize; + private readonly Func> _load; + private readonly Action _rebuildStructure; + private readonly Action _rebuildDiagnostics; + private readonly Action _showStatus; + private CancellationTokenSource? _cancellation; + private bool _isHelpLoading; + private string _usageText = string.Empty; + + public ConfigMakerCommandHelpLoader(ConfigMakerCommandHelpPanel panel, + Func currentComponent, Func localize, + Func> load, + Action rebuildStructure, Action rebuildDiagnostics, Action showStatus) + { + _panel = panel; + _currentComponent = currentComponent; + _localize = localize; + _load = load; + _rebuildStructure = rebuildStructure; + _rebuildDiagnostics = rebuildDiagnostics; + _showStatus = showStatus; + } + + public bool IsHelpLoading + { + get => _isHelpLoading; + private set + { + if (SetProperty(ref _isHelpLoading, value)) + OnPropertyChanged(nameof(IsCommandListEnabled)); + } + } + + public bool IsCommandListEnabled => !_isHelpLoading; + public string UsageText + { + get => _usageText; + private set => SetProperty(ref _usageText, value); + } + + public void Cancel() => _cancellation?.Cancel(); + + public async Task LoadAsync(string componentId, bool forceRefresh) + { + _cancellation?.Cancel(); + _cancellation?.Dispose(); + _cancellation = new CancellationTokenSource(); + CancellationToken cancellationToken = _cancellation.Token; + + IsHelpLoading = true; + UsageText = _localize("ConfigMakerLoadingHelpMessage"); + try + { + ComponentCommandHelpDocument document = await _load(componentId, cancellationToken, forceRefresh); + if (cancellationToken.IsCancellationRequested || + !string.Equals(_currentComponent(), componentId, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + _panel.Document = document; + UsageText = !string.IsNullOrWhiteSpace(document.Usage) + ? document.Usage + : string.Format(_localize("ConfigMakerHelpOptionsLoadedMessage"), document.Options.Count); + _panel.RebuildCommandModules(); + _panel.RebuildCommandOptions(); + _rebuildStructure(); + _rebuildDiagnostics(); + _showStatus(document); + } + catch (OperationCanceledException) + { + // A newer request or unloading canceled the load: nothing is left to show. + } + finally + { + if (!cancellationToken.IsCancellationRequested) + IsHelpLoading = false; + } + } +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandHelpPanel.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandHelpPanel.cs new file mode 100644 index 00000000..0dc6c6fe --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandHelpPanel.cs @@ -0,0 +1,218 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Runtime.CompilerServices; +using CDPIUI.Controls.CreateConfigHelper; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Owns the reference panel's filtering and selection; async help loading and editor actions stay outside. +internal sealed class ConfigMakerCommandHelpPanel : INotifyPropertyChanged +{ + private readonly Func _localize; + private readonly Func _isEditorReadOnly; + private object? _selectedCommandModule; + private string _commandSearchText = string.Empty; + private ConfigMakerCommandOptionViewModel? _selectedCommand; + private bool _hasCommandModules = true; + private string _commandArgumentText = string.Empty; + private string _commandArgumentPlaceholder = string.Empty; + private string _commandArgumentLabel = string.Empty; + + public ConfigMakerCommandHelpPanel(Func localize, Func isEditorReadOnly) + { + _localize = localize; + _isEditorReadOnly = isEditorReadOnly; + } + + public event PropertyChangedEventHandler? PropertyChanged; + public ComponentCommandHelpDocument Document { get; set; } = new(); + public ObservableCollection CommandOptions { get; } = []; + public ObservableCollection CommandModules { get; } = []; + + public object? SelectedCommandModule + { + get => _selectedCommandModule; + set + { + if (SetProperty(ref _selectedCommandModule, value)) + { + RebuildCommandOptions(); + } + } + } + + /// Set by the view when the user types in the search box. + public string CommandSearchText + { + get => _commandSearchText; + set + { + _commandSearchText = value ?? string.Empty; + RebuildCommandOptions(); + } + } + + public bool HasCommandModules + { + get => _hasCommandModules; + private set => SetProperty(ref _hasCommandModules, value); + } + + public bool HasSelectedCommand => _selectedCommand != null; + public bool CanInsertCommand => !_isEditorReadOnly() && _selectedCommand != null; + public string SelectedCommandName => _selectedCommand?.Source.DisplayName ?? string.Empty; + public string SelectedCommandSyntax => _selectedCommand?.Source.Syntax ?? string.Empty; + public string SelectedCommandDescription => _selectedCommand?.Description ?? string.Empty; + public bool HasCommandArgument => !string.IsNullOrWhiteSpace(_selectedCommand?.Source.ArgumentPlaceholder); + + public string CommandArgumentText + { + get => _commandArgumentText; + set => SetProperty(ref _commandArgumentText, value ?? string.Empty); + } + + public string CommandArgumentPlaceholder + { + get => _commandArgumentPlaceholder; + private set => SetProperty(ref _commandArgumentPlaceholder, value); + } + + public string CommandArgumentLabel + { + get => _commandArgumentLabel; + private set => SetProperty(ref _commandArgumentLabel, value); + } + + public void SelectCommand(ConfigMakerCommandOptionViewModel? command) + { + _selectedCommand = command; + if (command != null) + { + ComponentCommandHelpOption option = command.Source; + CommandArgumentText = string.Empty; + CommandArgumentPlaceholder = option.ArgumentPlaceholder; + CommandArgumentLabel = HasCommandArgument + ? string.Format( + _localize( + option.IsArgumentRequired + ? "ConfigMakerRequiredArgumentLabel" + : "ConfigMakerOptionalArgumentLabel"), + option.ArgumentPlaceholder) + : string.Empty; + } + OnPropertiesChanged( + nameof(SelectedCommandName), + nameof(SelectedCommandSyntax), + nameof(SelectedCommandDescription), + nameof(HasCommandArgument), + nameof(HasSelectedCommand), + nameof(CanInsertCommand)); + } + + public void RebuildCommandOptions() + { + string query = _commandSearchText.Trim(); + IEnumerable filtered = Document.Options; + if (_selectedCommandModule is ConfigMakerCommandModuleViewModel module && !module.IsAll) + { + filtered = filtered.Where(option => + string.Equals(option.GroupName, module.GroupName, StringComparison.OrdinalIgnoreCase)); + } + + if (!string.IsNullOrWhiteSpace(query)) + { + filtered = filtered.Where(option => + option.DisplayName.Contains(query, StringComparison.OrdinalIgnoreCase) || + option.Syntax.Contains(query, StringComparison.OrdinalIgnoreCase) || + option.Description.Contains(query, StringComparison.OrdinalIgnoreCase)); + } + + CommandOptions.Clear(); + foreach (ComponentCommandHelpOption option in filtered + .OrderBy(item => item.DisplayName, StringComparer.OrdinalIgnoreCase)) + { + CommandOptions.Add(new ConfigMakerCommandOptionViewModel + { + Source = option, + Description = string.IsNullOrWhiteSpace(option.Description) + ? _localize("ConfigMakerNoDescriptionMessage") + : option.Description, + }); + } + } + + public void RebuildCommandModules() + { + ConfigMakerCommandModuleViewModel? previous = _selectedCommandModule as ConfigMakerCommandModuleViewModel; + string? previousGroup = previous?.GroupName; + bool previousWasAll = previous?.IsAll != false; + List namedGroups = Document.Options + .Select(option => option.GroupName) + .Where(group => !string.IsNullOrWhiteSpace(group)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + CommandModules.Clear(); + CommandModules.Add(new ConfigMakerCommandModuleViewModel + { + DisplayName = _localize("ConfigMakerAllModules"), + IsAll = true, + }); + + if (namedGroups.Count > 0 && Document.Options.Any(option => string.IsNullOrWhiteSpace(option.GroupName))) + { + CommandModules.Add(new ConfigMakerCommandModuleViewModel + { + DisplayName = _localize("ConfigMakerGeneralModule"), + GroupName = string.Empty, + }); + } + + foreach (string group in namedGroups) + { + CommandModules.Add(new ConfigMakerCommandModuleViewModel + { + DisplayName = group, + GroupName = group, + }); + } + + HasCommandModules = namedGroups.Count > 0; + SelectedCommandModule = previousWasAll + ? CommandModules[0] + : CommandModules.FirstOrDefault(item => + !item.IsAll && string.Equals(item.GroupName, previousGroup, StringComparison.OrdinalIgnoreCase)) + ?? CommandModules[0]; + } + + public string? BuildSelectedCommand() => _selectedCommand == null + ? string.Empty + : ConfigMakerCommandText.BuildOptionCommand(_selectedCommand.Source, _commandArgumentText); + + private bool SetProperty(ref T field, T value, [CallerMemberName] string? propertyName = null) + { + if (EqualityComparer.Default.Equals(field, value)) + { + return false; + } + field = value; + OnPropertyChanged(propertyName); + return true; + } + + private void OnPropertyChanged(string? propertyName) => + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + + private void OnPropertiesChanged(params string[] propertyNames) + { + foreach (string name in propertyNames) + { + OnPropertyChanged(name); + } + } +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandText.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandText.cs index 2ecad29f..2b6ee991 100644 --- a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandText.cs +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandText.cs @@ -1,3 +1,5 @@ +#nullable enable + using System; using System.Linq; @@ -7,7 +9,7 @@ namespace CDPIUI.Helper.CreateConfigHelper; internal static class ConfigMakerCommandText { // Returns the option with its argument, or null when a required argument is empty. - public static string BuildOptionCommand(ComponentCommandHelpOption option, string argument) + public static string? BuildOptionCommand(ComponentCommandHelpOption option, string argument) { string command = option.DisplayName; if (string.IsNullOrWhiteSpace(option.ArgumentPlaceholder)) @@ -28,7 +30,7 @@ public static string BuildOptionCommand(ComponentCommandHelpOption option, strin // Inserts the command at the cursor on its own line. The result uses "\n" line breaks; // newCursorIndex is the index right after the inserted command. public static string InsertOnOwnLine( - string text, + string? text, int cursorLine, int cursorColumn, string command, diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerComponentTestTasks.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerComponentTestTasks.cs new file mode 100644 index 00000000..a9e66c9d --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerComponentTestTasks.cs @@ -0,0 +1,22 @@ +#nullable enable + +using System; +using System.Threading.Tasks; +using CDPIUI.Core.ComponentServices; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Resolves the existing manager only when an operation is requested, as the editor did before. +internal sealed class ConfigMakerComponentTestTasks : IConfigMakerTestTasks +{ + public event Action>? StateUpdated + { + add => ComponentTasksManager.Instance.TaskStateUpdated += value; + remove => ComponentTasksManager.Instance.TaskStateUpdated -= value; + } + + public Task IsRunningAsync(string componentId) => ComponentTasksManager.Instance.IsTaskRunning(componentId); + public Task StopAsync(string componentId) => ComponentTasksManager.Instance.StopTask(componentId); + public Task RunAsync(string componentId, string arguments) => ComponentTasksManager.Instance.CreateAndRunNewTask(componentId, arguments); + public Task RestoreAsync(string componentId) => ComponentTasksManager.Instance.CreateAndRunNewTask(componentId); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerDiagnostics.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerDiagnostics.cs new file mode 100644 index 00000000..b10c9a47 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerDiagnostics.cs @@ -0,0 +1,90 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using CDPIUI.ViewModels; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Owns diagnostic publication and localized counters; the host projects actual UI rows. +internal sealed class ConfigMakerDiagnostics : ObservableObject +{ + private readonly ObservableCollection _items; + private readonly Func _editor; + private readonly Func> _options; + private readonly IEnumerable _variables; + private readonly Func _resource; + private readonly Func _createItem; + private readonly Func _text; + private readonly Action _refresh; + private string _errorCountText = string.Empty; + private string _warningCountText = string.Empty; + + public ConfigMakerDiagnostics(ObservableCollection items, + Func editor, Func> options, + IEnumerable variables, Func resource, + Func createItem, Func text, Action refresh) + { + _items = items; + _editor = editor; + _options = options; + _variables = variables; + _resource = resource; + _createItem = createItem; + _text = text; + _refresh = refresh; + } + + public string ErrorCountText + { + get => _errorCountText; + internal set => SetProperty(ref _errorCountText, value); + } + + public string WarningCountText + { + get => _warningCountText; + internal set => SetProperty(ref _warningCountText, value); + } + + public void Rebuild() + { + string editorText = _editor(); + List results = ComponentCommandValidationService + .Validate(editorText, _options()) + .ToList(); + ConfigMakerPresetReferenceValidator.AddDiagnostics(editorText, _variables, _resource, results); + + _items.Clear(); + foreach (ComponentCommandDiagnostic diagnostic in results) + { + _items.Add(_createItem(diagnostic)); + } + + int errorCount = results.Count(item => item.Severity == ComponentCommandDiagnosticSeverity.Error); + int warningCount = results.Count - errorCount; + ErrorCountText = string.Format(_text("ConfigMakerDiagnosticErrorCount"), errorCount); + WarningCountText = string.Format(_text("ConfigMakerDiagnosticWarningCount"), warningCount); + _refresh(); + } + + public string GetSeverityText(ComponentCommandDiagnostic diagnostic) => _text( + diagnostic.Severity == ComponentCommandDiagnosticSeverity.Error + ? "ConfigMakerDiagnosticErrorSeverity" + : "ConfigMakerDiagnosticWarningSeverity"); + + public string GetDescription(ComponentCommandDiagnostic diagnostic) => diagnostic.Kind switch + { + ComponentCommandDiagnosticKind.UnknownFlag => string.Format( + _text("ConfigMakerUnknownFlagDiagnostic"), diagnostic.Token), + ComponentCommandDiagnosticKind.MissingRequiredArgument => string.Format( + _text("ConfigMakerMissingArgumentDiagnostic"), diagnostic.Token), + ComponentCommandDiagnosticKind.UnresolvedVariable => string.Format( + _text("ConfigMakerUnresolvedVariableDiagnostic"), diagnostic.Token), + ComponentCommandDiagnosticKind.UnresolvedResource => string.Format( + _text("ConfigMakerUnresolvedResourceDiagnostic"), diagnostic.Token), + _ => _text("ConfigMakerUnterminatedQuoteDiagnostic"), + }; +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerDocumentCoordinator.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerDocumentCoordinator.cs new file mode 100644 index 00000000..5043a909 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerDocumentCoordinator.cs @@ -0,0 +1,197 @@ +#nullable enable + +using System; +using System.Linq; +using System.Threading.Tasks; +using CDPIUI.Core.ComponentServices.Helpers.Configuration; +using CDPIUI.ViewModels; +using CDPIUI.ViewModels.ConfigMaker; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Coordinates the document workflow; the host supplies live editor state and UI effects. +internal sealed class ConfigMakerDocumentCoordinator +{ + private readonly ConfigMakerPresetDocument _document; + private readonly IConfigMakerDocumentHost _host; + private readonly Func _createStorage; + private readonly Func _export; + + public ConfigMakerDocumentCoordinator( + ConfigMakerPresetDocument document, + IConfigMakerDocumentHost host, + Func createStorage, + Func export) + { + _document = document; + _host = host; + _createStorage = createStorage; + _export = export; + } + + public void LoadPresetDocument(ConfigMakerPresetDocument document) + { + ArgumentNullException.ThrowIfNull(document); + _host.SetBaseDirectory(string.Empty); + _document.Name = document.Name; + _document.ComponentId = document.ComponentId; + _document.PackId = document.PackId; + _document.FileName = document.FileName; + _document.Meta = document.Meta; + _document.TargetVersion = document.TargetVersion; + _document.Variables.Clear(); + foreach (ConfigMakerVariableDefinition variable in document.Variables) + { + _document.Variables.Add(variable.Clone()); + } + _document.Resources.Clear(); + foreach (ConfigMakerPresetResource resource in document.Resources) + { + _document.Resources.Add(resource.Clone()); + } + _host.ComponentId = document.ComponentId; + _host.SetEditorText(document.CommandText); + _host.RebuildPresetStructure(); + _host.UpdateSimpleDesignerAvailability(); + _host.NotifyDocumentStateChanged(); + } + + public async Task LoadConfigItem( + ConfigItem item, + bool applyAutoCorrectorSilently = false) + { + ArgumentNullException.ThrowIfNull(item); + LoadPresetDocument(ConfigMakerPresetDocument.FromConfigItem(item)); + _host.SetBaseDirectory(_host.GetConfigItemBaseDirectory(item)); + _host.RebuildPresetStructure(); + if (applyAutoCorrectorSilently) + { + await _host.ApplyAutoCorrectorSilentlyAsync(item); + } + _host.AttachExistingPresetFiles(); + _host.RebuildPresetStructure(); + } + + public ConfigItem CreateConfigItem(string packId, string presetName) + { + SyncDocumentFromEditor(); + return _document.ToConfigItem(packId, presetName); + } + + public async Task SaveToApplicationAsync() + { + SyncDocumentFromEditor(); + _host.AttachExistingPresetFiles(); + SyncDocumentFromEditor(); + ConfigMakerSavePresetRequest? request = await _host.AskSavePresetAsync( + _document.Name, + !string.IsNullOrWhiteSpace(_document.PackId) && + !string.IsNullOrWhiteSpace(_document.FileName)); + if (request == null) + { + return ConfigMakerPresetSaveResult.Failed("CANCELED"); + } + + IConfigMakerDocumentStorage storageService = _createStorage(); + ConfigMakerPresetSaveResult result = request.Overwrite + ? await storageService.OverwriteAsync(_document) + : await storageService.SaveAsync(request.PresetName, _document); + if (result.Success) + { + if (!request.Overwrite) + { + _document.Name = request.PresetName; + } + _document.PackId = result.PackId; + _document.FileName = result.ConfigFileName; + ApplyStoredResources(result); + _host.ShowDocumentMessage( + string.Format( + _host.Text("ConfigMakerPresetSavedMessage"), + _document.Name), + isError: false); + } + else if (!string.Equals(result.ErrorCode, "CANCELED", StringComparison.Ordinal)) + { + _host.ShowDocumentMessage( + string.Format( + _host.Text("ConfigMakerPresetSaveFailedMessage"), + string.IsNullOrWhiteSpace(result.ErrorDetails) + ? result.ErrorCode + : result.ErrorDetails), + isError: true); + } + return result; + } + + public async Task NewDocumentAsync() + { + if (_host.IsEditorReadOnly) + { + return; + } + if ((!string.IsNullOrWhiteSpace(_host.EditorText) || + _document.HasVariables || + _document.HasResources) && + !await _host.ConfirmNewDocumentAsync()) + { + return; + } + + _host.SetEditorText(string.Empty); + _host.SetBaseDirectory(string.Empty); + _document.Name = string.Empty; + _document.Variables.Clear(); + _document.Resources.Clear(); + _host.ClearPresetStructure(); + _host.ClearEditorUndoHistory(); + } + + public async Task SaveTextAsync() + { + try + { + string? path = _host.ChooseExportPath(allowTextFormat: !_document.HasVariables); + if (path == null) + { + return; + } + + SyncDocumentFromEditor(); + await _export(_document, path); + + _host.ShowDocumentMessage( + _host.Text("ConfigMakerTextSavedMessage"), + isError: false); + } + catch (Exception exception) + { + _host.ShowDocumentMessage( + string.Format( + _host.Text("ConfigMakerTextSaveFailedMessage"), + exception.Message), + isError: true); + } + } + + private void ApplyStoredResources(ConfigMakerPresetSaveResult result) + { + foreach (ConfigMakerPresetResource resource in _document.Resources) + { + ConfigMakerResourceMetadata? storedResource = result.StoredResources.FirstOrDefault(candidate => + string.Equals(candidate.alias, resource.Alias, StringComparison.OrdinalIgnoreCase)); + if (storedResource == null || string.IsNullOrWhiteSpace(storedResource.path)) + { + continue; + } + resource.Path = storedResource.path; + resource.IsBuiltIn = storedResource.isBuiltIn; + } + } + + public void SyncDocumentFromEditor() + { + _document.ComponentId = _host.ComponentId; + _document.CommandText = _host.EditorText ?? string.Empty; + } +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPanelLayoutController.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPanelLayoutController.cs new file mode 100644 index 00000000..e69298c2 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPanelLayoutController.cs @@ -0,0 +1,95 @@ +#nullable enable + +using System; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Applies bounds in order: UI assignments may synchronously reenter the layout handlers. +internal sealed class ConfigMakerPanelLayoutController +{ + private readonly IConfigMakerPanelLayoutView _view; + private bool _layoutInitialized; + private bool _updatingLayoutBounds; + private double _savedEditorHeight = 420; + + public ConfigMakerPanelLayoutController(IConfigMakerPanelLayoutView view) => _view = view; + public bool IsUpdating => _updatingLayoutBounds; + public void Invalidate() => _layoutInitialized = false; + public void RememberEditorHeight(double value) => _savedEditorHeight = value; + + public void Update() + { + if (_updatingLayoutBounds || _view.RootWidth <= 0 || _view.RootHeight <= 0) + { + return; + } + + _updatingLayoutBounds = true; + try + { + const double editorMinWidth = 360; + const double commandMinWidth = 340; + const double editorMinHeight = 180; + const double bottomMinHeight = 110; + + double filesWidth = 0; + if (_view.FilesVisible) + { + double maximumFilesWidth = Math.Max( + 150, + _view.RootWidth - editorMinWidth - + (_view.CommandsVisible ? commandMinWidth + _view.CommandSizerWidth : 0) - + _view.FilesSizerWidth); + _view.FilesMaxWidth = Math.Max( + _view.FilesMinWidth, + Math.Min(_view.RootWidth * 0.45, maximumFilesWidth)); + _view.FilesWidth = Math.Clamp( + _view.FilesWidth, + _view.FilesMinWidth, + _view.FilesMaxWidth); + filesWidth = _view.FilesWidth + _view.FilesSizerWidth; + } + + double availableMainWidth = Math.Max(editorMinWidth, _view.RootWidth - filesWidth); + + if (_view.CommandsVisible) + { + double maxEditorWidth = Math.Max( + editorMinWidth, + availableMainWidth - commandMinWidth - _view.CommandSizerWidth); + _view.EditorMaxWidth = maxEditorWidth; + _view.EditorWidth = maxEditorWidth; + } + else + { + _view.EditorMaxWidth = availableMainWidth; + _view.EditorWidth = availableMainWidth; + } + + double availableMainHeight = Math.Max(editorMinHeight, _view.RootHeight); + + if (_view.BottomVisible) + { + double maxEditorHeight = Math.Max( + editorMinHeight, + availableMainHeight - bottomMinHeight - _view.BottomSizerHeight); + _view.EditorMaxHeight = maxEditorHeight; + double requestedHeight = _layoutInitialized + ? _view.EditorHeight + : Math.Min(_savedEditorHeight, maxEditorHeight); + _view.EditorHeight = Math.Clamp(requestedHeight, editorMinHeight, maxEditorHeight); + } + else + { + _view.EditorMaxHeight = availableMainHeight; + _view.EditorHeight = availableMainHeight; + } + + _layoutInitialized = true; + } + finally + { + _updatingLayoutBounds = false; + } + } +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPanelLayoutView.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPanelLayoutView.cs new file mode 100644 index 00000000..eb276460 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPanelLayoutView.cs @@ -0,0 +1,41 @@ +#nullable enable + +using System; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Lazy getters also support layout events raised while the control is loading its XAML. +internal sealed class ConfigMakerPanelLayoutView : IConfigMakerPanelLayoutView +{ + private readonly Func _root, _files, _commands, _bottom, _workspace, _editor; + private readonly Func _filesSizer, _commandSizer; + private readonly Func _bottomSizer; + + public ConfigMakerPanelLayoutView(Func root, Func files, + Func commands, Func bottom, Func workspace, + Func editor, Func filesSizer, + Func commandSizer, Func bottomSizer) + { + _root = root; _files = files; _commands = commands; _bottom = bottom; + _workspace = workspace; _editor = editor; + _filesSizer = filesSizer; _commandSizer = commandSizer; _bottomSizer = bottomSizer; + } + + public double RootWidth => _root().ActualWidth; + public double RootHeight => _root().ActualHeight; + public bool FilesVisible => _files().Visibility == Visibility.Visible; + public bool CommandsVisible => _commands().Visibility == Visibility.Visible; + public bool BottomVisible => _bottom().Visibility == Visibility.Visible; + public double FilesMinWidth => _files().MinWidth; + public double FilesMaxWidth { get => _files().MaxWidth; set => _files().MaxWidth = value; } + public double FilesWidth { get => _files().Width; set => _files().Width = value; } + public double FilesSizerWidth => _filesSizer().Width.Value; + public double CommandSizerWidth => _commandSizer().Width.Value; + public double BottomSizerHeight => _bottomSizer().Height.Value; + public double EditorMaxWidth { set => _workspace().MaxWidth = value; } + public double EditorWidth { set => _workspace().Width = value; } + public double EditorMaxHeight { set => _editor().MaxHeight = value; } + public double EditorHeight { get => _editor().Height; set => _editor().Height = value; } +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileActions.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileActions.cs new file mode 100644 index 00000000..1bb11446 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileActions.cs @@ -0,0 +1,152 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.ViewModels; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// File-tree actions keep their original ordering around dialogs and resource notifications. +internal sealed class ConfigMakerPresetFileActions +{ + private readonly IList _resources; + private readonly IConfigMakerPresetFileActionsHost _host; + private readonly IConfigMakerPresetFileActionsBackend _backend; + + public ConfigMakerPresetFileActions(IList resources, + IConfigMakerPresetFileActionsHost host, IConfigMakerPresetFileActionsBackend backend) + { + _resources = resources; + _host = host; + _backend = backend; + } + + public void AddPresetFiles(IEnumerable filePaths) + { + ArgumentNullException.ThrowIfNull(filePaths); + int added = _backend.AddFiles(filePaths); + if (added > 0) + { + _host.AttachExistingPresetFiles(); + _host.RebuildPresetStructure(); + _host.SetPresetFilesPanelVisible(true); + _host.ShowPresetFileMessage( + string.Format( + _host.Text("ConfigMakerPresetFilesAddedMessage"), + added), + ConfigMakerPresetFileNoticeSeverity.Success); + } + } + + public Task OpenPresetFileAsync(ConfigMakerPresetFileInfo? file) => + _host.RunReportingErrorsAsync(async () => + { + if (file == null) + { + return; + } + + string path = _backend.ResolvePath(file.Path); + if (!_backend.FileExists(path)) + { + ShowPresetFileMissing(path); + return; + } + + if (file.Kind == ConfigMakerPresetFileKind.SiteList || + string.Equals(Path.GetExtension(path), ".txt", StringComparison.OrdinalIgnoreCase)) + { + if (_backend.ShouldAskForTextApplication()) + { + if (await _host.AskTextFileApplicationAsync(path)) + { + _backend.RememberTextFileDialogShown(); + } + return; + } + + _backend.OpenTextFile(path); + return; + } + + _backend.OpenFileInDefaultApp(path); + }); + + public void ShowPresetFileInFolder(ConfigMakerPresetFileInfo? file) + { + if (file == null) + { + return; + } + + string path = _backend.ResolvePath(file.Path); + if (!_backend.FileExists(path)) + { + ShowPresetFileMissing(path); + return; + } + _backend.ShowFileInFolder(path); + } + + public Task RemovePresetFileAsync(ConfigMakerPresetFileInfo? file) => + _host.RunReportingErrorsAsync(async () => + { + ConfigMakerPresetResource? resource = file == null ? null : _backend.FindAttached(file.Path); + if (resource == null) + { + return; + } + if (_backend.IsReferenced(resource) && + !await _host.ConfirmRemoveReferencedFileAsync()) + { + return; + } + _resources.Remove(resource); + _host.RebuildPresetStructure(); + _host.ScheduleDiagnostics(); + }); + + /// Inserts the reference of a file of the tree at the editor cursor, attaching the file first. + public void InsertPresetFileReference(ConfigMakerPresetFileInfo? file) + { + if (_host.IsEditorReadOnly || file == null) + { + return; + } + string reference = file.Path.Trim().Trim('"'); + if (!reference.StartsWith("preset://", StringComparison.OrdinalIgnoreCase)) + { + string? resolvedPath = _backend.TryResolvePath(reference); + if (!string.IsNullOrWhiteSpace(resolvedPath) && _backend.FileExists(resolvedPath)) + { + ConfigMakerPresetResource resource = _backend.GetOrCreate( + Path.GetFullPath(resolvedPath), + file.Kind, + out bool resourceAdded); + if (resourceAdded) + { + _host.RebuildPresetStructure(); + } + reference = resource.Reference; + } + } + _host.InsertAtCursor($"\"{reference}\""); + } + + public void AddPresetFilesFromPicker() + { + IReadOnlyList filePaths = _host.ChoosePresetFilesToAdd(); + if (filePaths.Count > 0) + { + AddPresetFiles(filePaths); + } + } + + private void ShowPresetFileMissing(string path) => + _host.ShowPresetFileMessage( + string.Format(_host.Text("ConfigMakerPresetFileMissingMessage"), path), + ConfigMakerPresetFileNoticeSeverity.Warning); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileActionsBackend.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileActionsBackend.cs new file mode 100644 index 00000000..7e32b3db --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileActionsBackend.cs @@ -0,0 +1,30 @@ +#nullable enable + +using System.Collections.Generic; +using System.IO; +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.Core.System; +using CDPIUI.ViewModels; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Construction only stores the existing facade; settings and shell are read when invoked. +internal sealed class ConfigMakerPresetFileActionsBackend : IConfigMakerPresetFileActionsBackend +{ + private readonly ConfigMakerPresetResources _resources; + + public ConfigMakerPresetFileActionsBackend(ConfigMakerPresetResources resources) => _resources = resources; + + public int AddFiles(IEnumerable paths) => _resources.AddFiles(paths); + public string ResolvePath(string path) => _resources.ResolvePath(path); + public string? TryResolvePath(string path) => _resources.TryResolvePath(path); + public bool FileExists(string path) => File.Exists(path); + public ConfigMakerPresetResource GetOrCreate(string path, ConfigMakerPresetFileKind kind, out bool added) => _resources.GetOrCreate(path, kind, out added); + public ConfigMakerPresetResource? FindAttached(string path) => _resources.FindAttached(path); + public bool IsReferenced(ConfigMakerPresetResource resource) => _resources.IsReferenced(resource); + public bool ShouldAskForTextApplication() => TextFileOpenPreferences.ShouldAskForApplication(); + public void RememberTextFileDialogShown() => TextFileOpenPreferences.RememberDialogShown(); + public void OpenTextFile(string path) => ShellHelper.OpenFile(path); + public void OpenFileInDefaultApp(string path) => ShellHelper.OpenFileInDefaultApp(path); + public void ShowFileInFolder(string path) => ShellHelper.LookupFileInDirectory(path); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileKinds.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileKinds.cs index 15631b75..e8da7335 100644 --- a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileKinds.cs +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileKinds.cs @@ -1,3 +1,5 @@ +#nullable enable + using System.IO; using CDPIUI.Controls.CreateConfigHelper; using CDPIUI.Core.ComponentServices.Helpers.Configuration; @@ -39,7 +41,7 @@ public static ConfigMakerResourceKind ToResourceKind(ConfigMakerPresetFileKind k _ => ConfigFileKind.SiteList, }; - public static ConfigMakerPresetFileInfo ToEditorFile(ConfigUsedFile file) => file == null ? null : new( + public static ConfigMakerPresetFileInfo? ToEditorFile(ConfigUsedFile? file) => file == null ? null : new( file.Name, file.Path, file.Folder, diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileReplacementBackend.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileReplacementBackend.cs new file mode 100644 index 00000000..878d0946 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileReplacementBackend.cs @@ -0,0 +1,43 @@ +#nullable enable + +using System.IO; +using System.Threading.Tasks; +using CDPIUI.AddOns.ConfigImport; +using CDPIUI.Controls.CreateConfigHelper; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Keeps the existing filesystem/resource/autocorrect operations at the production boundary. +internal sealed class ConfigMakerPresetFileReplacementBackend : IConfigMakerPresetFileReplacementBackend +{ + private readonly ConfigMakerPresetResources _resources; + + public ConfigMakerPresetFileReplacementBackend(ConfigMakerPresetResources resources) => _resources = resources; + + public string? TryResolvePath(string path) => _resources.TryResolvePath(path); + public bool FileExists(string path) => File.Exists(path); + public void CreateEmptyFile(string path) => ConfigMakerPresetResources.CreateEmptyFile(path); + public bool TryUpdateAttachedResource(ConfigMakerPresetFileInfo file, string path) => _resources.TryUpdateAttachedResource(file, path); + public ConfigMakerPresetFileReplacement? ReplaceReferences(ConfigMakerPresetFileInfo file, string path) => _resources.ReplaceReferences(file, path); + public IConfigMakerPresetFileAutoCorrector CreateAutoCorrector() => new AutoCorrector(_resources); + + private sealed class AutoCorrector : IConfigMakerPresetFileAutoCorrector + { + private readonly ConfigMakerPresetResources _resources; + private readonly ConfigImportAutoCorrector _corrector; + + public AutoCorrector(ConfigMakerPresetResources resources) + { + _resources = resources; + _corrector = new ConfigImportAutoCorrector(); + } + + public bool ShouldSuggestEmptyFile(string path) => _corrector.ShouldSuggestEmptyFile(path); + + public Task FindReplacementAsync(string path) + { + ConfigImportResult result = _resources.CreateAutoCorrectResult(path); + return Task.Run(() => _corrector.FindReplacement(result, path)); + } + } +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileReplacer.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileReplacer.cs new file mode 100644 index 00000000..baebb02c --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileReplacer.cs @@ -0,0 +1,194 @@ +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.Core.ComponentServices.Helpers.Configuration; +using CDPIUI.ViewModels.ConfigMaker; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Missing-file replacement workflow, shared by the editor dialog and silent imports. +internal sealed class ConfigMakerPresetFileReplacer +{ + private readonly IConfigMakerPresetFileReplacementHost _host; + private readonly IConfigMakerPresetFileReplacementBackend _backend; + + public ConfigMakerPresetFileReplacer(IConfigMakerPresetFileReplacementHost host, + IConfigMakerPresetFileReplacementBackend backend) + { + _host = host; + _backend = backend; + } + + public Task ReplacePresetFileAsync(ConfigMakerPresetFileInfo? file) => + _host.RunReportingErrorsAsync(async () => + { + if (file == null) + { + return; + } + + string? missingPath = _backend.TryResolvePath(file.Path); + if (string.IsNullOrWhiteSpace(missingPath)) + { + _host.ShowPresetFileMessage( + _host.Text("ConfigMakerPresetFileInvalidPathMessage"), + ConfigMakerPresetFileNoticeSeverity.Error); + return; + } + if (_backend.FileExists(missingPath)) + { + _host.RebuildPresetStructure(); + return; + } + + ConfigMakerFileReplacementChoice choice = await _host.AskPresetFileReplacementAsync(missingPath); + if (choice == ConfigMakerFileReplacementChoice.AutoCorrect) + { + await AutoCorrectPresetFileAsync(file, missingPath); + } + else if (choice == ConfigMakerFileReplacementChoice.ChooseManually) + { + ChooseAndApplyPresetFileReplacement(file, missingPath); + } + }); + + private async Task AutoCorrectPresetFileAsync(ConfigMakerPresetFileInfo file, string missingPath) + { + IConfigMakerPresetFileAutoCorrector autoCorrector = _backend.CreateAutoCorrector(); + bool suggestEmptyFile = autoCorrector.ShouldSuggestEmptyFile(missingPath); + if (suggestEmptyFile) + { + TryCreateEmptyPresetFile(missingPath); + return; + } + + string? suggestion = await autoCorrector.FindReplacementAsync(missingPath); + if (!string.IsNullOrWhiteSpace(suggestion)) + { + TryApplyPresetFileReplacement(file, suggestion, showStatus: true); + return; + } + + _host.ShowPresetFileMessage( + _host.Text("ConfigMakerPresetFileNoSuggestionMessage"), + ConfigMakerPresetFileNoticeSeverity.Warning); + ChooseAndApplyPresetFileReplacement(file, missingPath); + } + + private void ChooseAndApplyPresetFileReplacement(ConfigMakerPresetFileInfo file, string missingPath) + { + string? selectedPath = _host.ChooseReplacementFile(missingPath); + if (!string.IsNullOrWhiteSpace(selectedPath)) + { + TryApplyPresetFileReplacement(file, selectedPath, showStatus: true); + } + } + + public bool TryCreateEmptyPresetFile(string missingPath, bool showStatus = true) + { + try + { + _backend.CreateEmptyFile(missingPath); + _host.RebuildPresetStructure(); + if (showStatus) + { + _host.ShowPresetFileMessage( + string.Format( + _host.Text("ConfigMakerPresetFileEmptyCreatedMessage"), + missingPath), + ConfigMakerPresetFileNoticeSeverity.Success); + } + return true; + } + catch (Exception ex) + { + if (showStatus) + { + ShowPresetFileReplaceFailed(ex); + } + return false; + } + } + + public bool TryApplyPresetFileReplacement( + ConfigMakerPresetFileInfo file, + string replacementPath, + bool showStatus) + { + try + { + string fullReplacementPath = Path.GetFullPath(replacementPath); + if (!_backend.FileExists(fullReplacementPath)) + { + throw new FileNotFoundException(null, fullReplacementPath); + } + + if (_backend.TryUpdateAttachedResource(file, fullReplacementPath)) + { + _host.RebuildPresetStructure(); + if (showStatus) + { + ShowPresetFileReplaced(fullReplacementPath); + } + return true; + } + + ConfigMakerPresetFileReplacement replacement = _backend.ReplaceReferences( + file, + fullReplacementPath) ?? throw new InvalidOperationException( + _host.Text("ConfigMakerPresetFileReferenceNotFoundMessage")); + + if (_host.UsesExplicitPresetStructure) + { + _host.ExplicitPresetFiles = _host.ExplicitPresetFiles + .Select(item => ReferenceEquals(item, file) || + (item.Kind == file.Kind && ConfigFileReferences.PathsEqual(item.Path, file.Path)) + ? item with + { + Name = Path.GetFileName(fullReplacementPath), + Path = replacement.Reference, + Folder = ConfigFileReferences.GetDisplayFolder(replacement.Reference), + } + : item) + .ToArray(); + } + if (replacement.CommandChanged) + { + _host.SetCommandText(ComponentCommandLineFormatter.FormatByFlags(replacement.UpdatedCommandText)); + } + _host.RebuildPresetStructure(); + _host.NotifyPresetFileReplaced(file.Path, replacement.Reference); + if (showStatus) + { + ShowPresetFileReplaced(fullReplacementPath); + } + return true; + } + catch (Exception ex) + { + if (showStatus) + { + ShowPresetFileReplaceFailed(ex); + } + return false; + } + } + + private void ShowPresetFileReplaced(string fullReplacementPath) => + _host.ShowPresetFileMessage( + string.Format( + _host.Text("ConfigMakerPresetFileReplacedMessage"), + fullReplacementPath), + ConfigMakerPresetFileNoticeSeverity.Success); + + private void ShowPresetFileReplaceFailed(Exception exception) => + _host.ShowPresetFileMessage( + string.Format( + _host.Text("ConfigMakerPresetFileReplaceFailedMessage"), + exception.Message), + ConfigMakerPresetFileNoticeSeverity.Error); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetOptionGroups.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetOptionGroups.cs index 7dd921ce..4ba6637c 100644 --- a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetOptionGroups.cs +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetOptionGroups.cs @@ -1,3 +1,5 @@ +#nullable enable + using System; using System.Collections.Generic; using System.Linq; @@ -39,7 +41,7 @@ public static List> SplitProfiles(IEnumerable options) => options + public static string? FindProfileName(IEnumerable options) => options .FirstOrDefault(option => string.Equals(option.Name, "--name", StringComparison.OrdinalIgnoreCase)) ?.Value; diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetReferenceEditor.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetReferenceEditor.cs new file mode 100644 index 00000000..f568d630 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetReferenceEditor.cs @@ -0,0 +1,214 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.Core.ComponentServices.Helpers.Configuration; +using CDPIUI.ViewModels; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Rewrites command and variable references, retaining only resources used by a successful rewrite. +internal sealed class ConfigMakerPresetReferenceEditor +{ + private readonly IEnumerable _variables; + private readonly ConfigMakerPresetResourceRegistry _registry; + private readonly Func> _extractFiles; + private readonly Func _extractDirectFile; + + public ConfigMakerPresetReferenceEditor( + IEnumerable variables, + ConfigMakerPresetResourceRegistry registry, + Func> extractFiles, + Func extractDirectFile) + { + _variables = variables; + _registry = registry; + _extractFiles = extractFiles; + _extractDirectFile = extractDirectFile; + } + + public string AttachExistingFiles(string commandText) + { + string updatedCommand = commandText; + foreach (ConfigMakerPresetFileInfo file in _extractFiles(updatedCommand).ToArray()) + { + ConfigMakerPresetResource? resource = _registry.GetOrCreate(file, out bool resourceAdded); + if (resource == null) + { + continue; + } + + string rewritten = ReplaceFileInText( + updatedCommand, + file, + resource.Reference); + if (string.Equals(rewritten, updatedCommand, StringComparison.Ordinal)) + { + if (resourceAdded) + { + _registry.Remove(resource); + } + continue; + } + updatedCommand = rewritten; + } + + AttachExistingFilesInVariables(); + return updatedCommand; + } + + public ConfigMakerPresetFileReplacement? ReplaceReferences( + Func getCommandText, + ConfigMakerPresetFileInfo file, + string fullReplacementPath) + { + ConfigMakerPresetResource replacementResource = _registry.GetOrCreate( + fullReplacementPath, + file.Kind, + out bool resourceAdded); + string replacementReference = replacementResource.Reference; + // Resource notifications may synchronously update the document/editor text. + string commandText = getCommandText(); + string updatedCommand = ReplaceFileInText( + commandText, + file, + replacementReference); + bool commandChanged = !string.Equals( + updatedCommand, + commandText, + StringComparison.Ordinal); + bool variablesChanged = ReplaceFileInVariables(file, replacementReference); + if (!commandChanged && !variablesChanged) + { + if (resourceAdded) + { + _registry.Remove(replacementResource); + } + return null; + } + return new ConfigMakerPresetFileReplacement(replacementReference, updatedCommand, commandChanged); + } + + private static string ReplaceFileInText( + string text, + ConfigMakerPresetFileInfo file, + string replacementPath) => + ConfigFileReferences.ReplaceFileInText( + text, + file.Path, + ConfigMakerPresetFileKinds.ToCoreFileKind(file.Kind), + replacementPath); + + private bool ReplaceFileInVariables( + ConfigMakerPresetFileInfo file, + string replacementPath) + { + bool replaced = false; + foreach (ConfigMakerVariableDefinition variable in _variables) + { + variable.Value = ReplaceFileInVariableValue( + variable.Value, + file, + replacementPath, + ref replaced); + variable.OnValue = ReplaceFileInVariableValue( + variable.OnValue, + file, + replacementPath, + ref replaced); + variable.OffValue = ReplaceFileInVariableValue( + variable.OffValue, + file, + replacementPath, + ref replaced); + for (int index = 0; index < variable.Values.Count; index++) + { + variable.Values[index] = ReplaceFileInVariableValue( + variable.Values[index], + file, + replacementPath, + ref replaced); + } + } + return replaced; + } + + private string ReplaceFileInVariableValue( + string? value, + ConfigMakerPresetFileInfo file, + string replacementPath, + ref bool replaced) + { + string updated = ReplaceFileInText(value ?? string.Empty, file, replacementPath); + if (!string.Equals(updated, value, StringComparison.Ordinal)) + { + replaced = true; + return updated; + } + + ConfigMakerPresetFileInfo? directFile = _extractDirectFile(value); + if (directFile != null && + directFile.Kind == file.Kind && + ConfigFileReferences.PathsEqual(directFile.Path, file.Path)) + { + replaced = true; + return replacementPath; + } + return value!; + } + + private void AttachExistingFilesInVariables() + { + foreach (ConfigMakerVariableDefinition variable in _variables) + { + variable.Value = AttachExistingFilesInVariableValue(variable.Value); + variable.OnValue = AttachExistingFilesInVariableValue(variable.OnValue); + variable.OffValue = AttachExistingFilesInVariableValue(variable.OffValue); + for (int index = 0; index < variable.Values.Count; index++) + { + variable.Values[index] = AttachExistingFilesInVariableValue( + variable.Values[index]); + } + } + } + + private string AttachExistingFilesInVariableValue(string value) + { + string updatedValue = value ?? string.Empty; + ConfigMakerPresetFileInfo? directFile = _extractDirectFile(updatedValue); + ConfigMakerPresetFileInfo[] files = _extractFiles(updatedValue) + .Append(directFile) + .OfType() + .DistinctBy(file => (file.Kind, file.Path), ConfigMakerPresetFileKeyComparer.Instance) + .ToArray(); + + foreach (ConfigMakerPresetFileInfo file in files) + { + ConfigMakerPresetResource? resource = _registry.GetOrCreate(file, out bool resourceAdded); + if (resource == null) + { + continue; + } + + string rewritten = ReplaceFileInText(updatedValue, file, resource.Reference); + if (string.Equals(rewritten, updatedValue, StringComparison.Ordinal) && + directFile != null && + ConfigFileReferences.PathsEqual(directFile.Path, file.Path)) + { + rewritten = resource.Reference; + } + if (string.Equals(rewritten, updatedValue, StringComparison.Ordinal)) + { + if (resourceAdded) + { + _registry.Remove(resource); + } + continue; + } + updatedValue = rewritten; + } + return updatedValue; + } +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetResourceRegistry.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetResourceRegistry.cs new file mode 100644 index 00000000..d52c10e0 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetResourceRegistry.cs @@ -0,0 +1,160 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.ViewModels; +using Unidecode.NET; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Owns attached resource identity and registration; path policy belongs to the caller. +internal sealed class ConfigMakerPresetResourceRegistry +{ + private const string PresetScheme = "preset://"; + private readonly IList _resources; + private readonly Func _resolvePath; + private readonly Func _isPathInsideComponent; + + public ConfigMakerPresetResourceRegistry( + IList resources, + Func resolvePath, + Func isPathInsideComponent) + { + _resources = resources; + _resolvePath = resolvePath; + _isPathInsideComponent = isPathInsideComponent; + } + + public ConfigMakerPresetResource? FindAttached(string? reference) + { + string alias = (reference ?? string.Empty).Trim().Trim('"', '\''); + if (alias.StartsWith(PresetScheme, StringComparison.OrdinalIgnoreCase)) + { + alias = alias[PresetScheme.Length..]; + } + return _resources.FirstOrDefault(resource => + string.Equals(resource.Alias, alias, StringComparison.OrdinalIgnoreCase)); + } + + public string CreateUniqueAlias(string fileName) + { + string normalized = fileName.Unidecode(); + normalized = string.Concat(normalized.Select(character => + char.IsLetterOrDigit(character) || character is '.' or '_' or '-' + ? character + : '_')); + normalized = normalized.Trim('_'); + if (normalized.Length == 0) + { + normalized = "resource.bin"; + } + string stem = Path.GetFileNameWithoutExtension(normalized); + string extension = Path.GetExtension(normalized); + string candidate = normalized; + int suffix = 2; + while (_resources.Any(resource => + string.Equals(resource.Alias, candidate, StringComparison.OrdinalIgnoreCase))) + { + candidate = $"{stem}_{suffix++}{extension}"; + } + return candidate; + } + + public int AddFiles(IEnumerable filePaths) + { + int added = 0; + foreach (string sourcePath in filePaths) + { + if (string.IsNullOrWhiteSpace(sourcePath) || !File.Exists(sourcePath)) + { + continue; + } + string fullPath = Path.GetFullPath(sourcePath); + if (_resources.Any(resource => + string.Equals( + _resolvePath(resource.Reference), + fullPath, + StringComparison.OrdinalIgnoreCase))) + { + continue; + } + string alias = CreateUniqueAlias(Path.GetFileName(fullPath)); + _resources.Add(new ConfigMakerPresetResource + { + Alias = alias, + Path = fullPath, + Kind = ConfigMakerPresetFileKinds.InferResourceKind(fullPath), + IsBuiltIn = _isPathInsideComponent(fullPath), + }); + added++; + } + return added; + } + + public ConfigMakerPresetResource? GetOrCreate( + ConfigMakerPresetFileInfo? file, + out bool resourceAdded) + { + resourceAdded = false; + if (file == null || file.Path.StartsWith(PresetScheme, StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + string resolvedPath = _resolvePath(file.Path); + if (string.IsNullOrWhiteSpace(resolvedPath) || !File.Exists(resolvedPath)) + { + return null; + } + + return GetOrCreate( + Path.GetFullPath(resolvedPath), + file.Kind, + out resourceAdded); + } + + public ConfigMakerPresetResource GetOrCreate( + string fullPath, + ConfigMakerPresetFileKind kind, + out bool resourceAdded) + { + resourceAdded = false; + ConfigMakerPresetResource? resource = _resources.FirstOrDefault(candidate => + string.Equals( + _resolvePath(candidate.Reference), + fullPath, + StringComparison.OrdinalIgnoreCase)); + if (resource != null) + { + return resource; + } + + resource = new ConfigMakerPresetResource + { + Alias = CreateUniqueAlias(Path.GetFileName(fullPath)), + Path = fullPath, + Kind = ConfigMakerPresetFileKinds.ToResourceKind(kind), + IsBuiltIn = _isPathInsideComponent(fullPath), + }; + _resources.Add(resource); + resourceAdded = true; + return resource; + } + + public bool TryUpdateAttachedResource(ConfigMakerPresetFileInfo file, string fullReplacementPath) + { + ConfigMakerPresetResource? attachedResource = FindAttached(file.Path); + if (attachedResource == null) + { + return false; + } + attachedResource.Path = fullReplacementPath; + attachedResource.IsBuiltIn = _isPathInsideComponent(fullReplacementPath); + return true; + } + + public bool Remove(ConfigMakerPresetResource resource) => _resources.Remove(resource); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetResources.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetResources.cs index 6fee8494..5f2989b1 100644 --- a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetResources.cs +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetResources.cs @@ -9,7 +9,6 @@ using CDPIUI.Core.Store.Database; using CDPIUI.Shared.Extensions; using CDPIUI.ViewModels; -using Unidecode.NET; namespace CDPIUI.Helper.CreateConfigHelper; @@ -17,8 +16,8 @@ namespace CDPIUI.Helper.CreateConfigHelper; // and the rewriting of file references in the command and in the variables. internal sealed class ConfigMakerPresetResources { - private const string PresetScheme = "preset://"; - + private readonly ConfigMakerPresetResourceRegistry _registry; + private readonly ConfigMakerPresetReferenceEditor _referenceEditor; private readonly ConfigMakerPresetDocument _document; private readonly Func _getComponentId; private readonly Func _getCommandText; @@ -31,6 +30,9 @@ public ConfigMakerPresetResources( _document = document; _getComponentId = getComponentId; _getCommandText = getCommandText; + _registry = new ConfigMakerPresetResourceRegistry(_document.Resources, TryResolvePath, IsPathInsideComponent); + _referenceEditor = new ConfigMakerPresetReferenceEditor( + _document.Variables, _registry, ExtractFilesFromText, TryExtractDirectFile); } // The directory of the loaded preset pack; empty when the preset is not stored yet. @@ -127,16 +129,7 @@ public string TryResolvePath(string sourcePath) } } - public ConfigMakerPresetResource FindAttached(string reference) - { - string alias = (reference ?? string.Empty).Trim().Trim('"', '\''); - if (alias.StartsWith(PresetScheme, StringComparison.OrdinalIgnoreCase)) - { - alias = alias[PresetScheme.Length..]; - } - return _document.Resources.FirstOrDefault(resource => - string.Equals(resource.Alias, alias, StringComparison.OrdinalIgnoreCase)); - } + public ConfigMakerPresetResource FindAttached(string reference) => _registry.FindAttached(reference); public bool IsPathInsideComponent(string filePath) { @@ -145,29 +138,7 @@ public bool IsPathInsideComponent(string filePath) ConfigMakerPresetPaths.IsPathInside(filePath, componentDirectory); } - public string CreateUniqueAlias(string fileName) - { - string normalized = fileName.Unidecode(); - normalized = string.Concat(normalized.Select(character => - char.IsLetterOrDigit(character) || character is '.' or '_' or '-' - ? character - : '_')); - normalized = normalized.Trim('_'); - if (normalized.Length == 0) - { - normalized = "resource.bin"; - } - string stem = Path.GetFileNameWithoutExtension(normalized); - string extension = Path.GetExtension(normalized); - string candidate = normalized; - int suffix = 2; - while (_document.Resources.Any(resource => - string.Equals(resource.Alias, candidate, StringComparison.OrdinalIgnoreCase))) - { - candidate = $"{stem}_{suffix++}{extension}"; - } - return candidate; - } + public string CreateUniqueAlias(string fileName) => _registry.CreateUniqueAlias(fileName); public ConfigItem CreateSnapshot(string commandText = null) { @@ -205,163 +176,28 @@ public bool IsReferenced(ConfigMakerPresetResource resource) => .Any(value => value.Contains(resource.Reference, StringComparison.OrdinalIgnoreCase)); // Attaches existing files as preset resources. Returns the number of the new resources. - public int AddFiles(IEnumerable filePaths) - { - int added = 0; - foreach (string sourcePath in filePaths) - { - if (string.IsNullOrWhiteSpace(sourcePath) || !File.Exists(sourcePath)) - { - continue; - } - string fullPath = Path.GetFullPath(sourcePath); - if (_document.Resources.Any(resource => - string.Equals( - TryResolvePath(resource.Reference), - fullPath, - StringComparison.OrdinalIgnoreCase))) - { - continue; - } - string alias = CreateUniqueAlias(Path.GetFileName(fullPath)); - _document.Resources.Add(new ConfigMakerPresetResource - { - Alias = alias, - Path = fullPath, - Kind = ConfigMakerPresetFileKinds.InferResourceKind(fullPath), - IsBuiltIn = IsPathInsideComponent(fullPath), - }); - added++; - } - return added; - } + public int AddFiles(IEnumerable filePaths) => _registry.AddFiles(filePaths); - public ConfigMakerPresetResource GetOrCreate( - ConfigMakerPresetFileInfo file, - out bool resourceAdded) - { - resourceAdded = false; - if (file == null || file.Path.StartsWith(PresetScheme, StringComparison.OrdinalIgnoreCase)) - { - return null; - } - - string resolvedPath = TryResolvePath(file.Path); - if (string.IsNullOrWhiteSpace(resolvedPath) || !File.Exists(resolvedPath)) - { - return null; - } - - return GetOrCreate( - Path.GetFullPath(resolvedPath), - file.Kind, - out resourceAdded); - } + public ConfigMakerPresetResource GetOrCreate(ConfigMakerPresetFileInfo file, out bool resourceAdded) => + _registry.GetOrCreate(file, out resourceAdded); public ConfigMakerPresetResource GetOrCreate( - string fullPath, - ConfigMakerPresetFileKind kind, - out bool resourceAdded) - { - resourceAdded = false; - ConfigMakerPresetResource resource = _document.Resources.FirstOrDefault(candidate => - string.Equals( - TryResolvePath(candidate.Reference), - fullPath, - StringComparison.OrdinalIgnoreCase)); - if (resource != null) - { - return resource; - } - - resource = new ConfigMakerPresetResource - { - Alias = CreateUniqueAlias(Path.GetFileName(fullPath)), - Path = fullPath, - Kind = ConfigMakerPresetFileKinds.ToResourceKind(kind), - IsBuiltIn = IsPathInsideComponent(fullPath), - }; - _document.Resources.Add(resource); - resourceAdded = true; - return resource; - } + string fullPath, ConfigMakerPresetFileKind kind, out bool resourceAdded) => + _registry.GetOrCreate(fullPath, kind, out resourceAdded); // Replaces the file references of the command and the variables with attached resources. // Returns the updated command; the variables are updated in place. - public string AttachExistingFiles() - { - string updatedCommand = _getCommandText(); - foreach (ConfigMakerPresetFileInfo file in ExtractFilesFromText(updatedCommand).ToArray()) - { - ConfigMakerPresetResource resource = GetOrCreate(file, out bool resourceAdded); - if (resource == null) - { - continue; - } - - string rewritten = ReplaceFileInText( - updatedCommand, - file, - resource.Reference); - if (string.Equals(rewritten, updatedCommand, StringComparison.Ordinal)) - { - if (resourceAdded) - { - _document.Resources.Remove(resource); - } - continue; - } - updatedCommand = rewritten; - } - - AttachExistingFilesInVariables(); - return updatedCommand; - } + public string AttachExistingFiles() => _referenceEditor.AttachExistingFiles(_getCommandText()); // Points an attached resource at the replacement file. Returns false when the file is not an attached resource. - public bool TryUpdateAttachedResource(ConfigMakerPresetFileInfo file, string fullReplacementPath) - { - ConfigMakerPresetResource attachedResource = FindAttached(file.Path); - if (attachedResource == null) - { - return false; - } - attachedResource.Path = fullReplacementPath; - attachedResource.IsBuiltIn = IsPathInsideComponent(fullReplacementPath); - return true; - } + public bool TryUpdateAttachedResource(ConfigMakerPresetFileInfo file, string fullReplacementPath) => + _registry.TryUpdateAttachedResource(file, fullReplacementPath); // Attaches the replacement file and rewrites the references to the replaced file. // Returns null when neither the command nor a variable refers to the replaced file. public ConfigMakerPresetFileReplacement ReplaceReferences( - ConfigMakerPresetFileInfo file, - string fullReplacementPath) - { - ConfigMakerPresetResource replacementResource = GetOrCreate( - fullReplacementPath, - file.Kind, - out bool resourceAdded); - string replacementReference = replacementResource.Reference; - string commandText = _getCommandText(); - string updatedCommand = ReplaceFileInText( - commandText, - file, - replacementReference); - bool commandChanged = !string.Equals( - updatedCommand, - commandText, - StringComparison.Ordinal); - bool variablesChanged = ReplaceFileInVariables(file, replacementReference); - if (!commandChanged && !variablesChanged) - { - if (resourceAdded) - { - _document.Resources.Remove(replacementResource); - } - return null; - } - return new ConfigMakerPresetFileReplacement(replacementReference, updatedCommand, commandChanged); - } + ConfigMakerPresetFileInfo file, string fullReplacementPath) => + _referenceEditor.ReplaceReferences(_getCommandText, file, fullReplacementPath); public ConfigImportResult CreateAutoCorrectResult( string missingPath, @@ -393,115 +229,4 @@ public ConfigImportResult CreateAutoCorrectResult( GeneratedFiles = [], }; } - - private bool ReplaceFileInVariables( - ConfigMakerPresetFileInfo file, - string replacementPath) - { - bool replaced = false; - foreach (ConfigMakerVariableDefinition variable in _document.Variables) - { - variable.Value = ReplaceFileInVariableValue( - variable.Value, - file, - replacementPath, - ref replaced); - variable.OnValue = ReplaceFileInVariableValue( - variable.OnValue, - file, - replacementPath, - ref replaced); - variable.OffValue = ReplaceFileInVariableValue( - variable.OffValue, - file, - replacementPath, - ref replaced); - for (int index = 0; index < variable.Values.Count; index++) - { - variable.Values[index] = ReplaceFileInVariableValue( - variable.Values[index], - file, - replacementPath, - ref replaced); - } - } - return replaced; - } - - private string ReplaceFileInVariableValue( - string value, - ConfigMakerPresetFileInfo file, - string replacementPath, - ref bool replaced) - { - string updated = ReplaceFileInText(value ?? string.Empty, file, replacementPath); - if (!string.Equals(updated, value, StringComparison.Ordinal)) - { - replaced = true; - return updated; - } - - ConfigMakerPresetFileInfo directFile = TryExtractDirectFile(value); - if (directFile != null && - directFile.Kind == file.Kind && - ConfigFileReferences.PathsEqual(directFile.Path, file.Path)) - { - replaced = true; - return replacementPath; - } - return value; - } - - private void AttachExistingFilesInVariables() - { - foreach (ConfigMakerVariableDefinition variable in _document.Variables) - { - variable.Value = AttachExistingFilesInVariableValue(variable.Value); - variable.OnValue = AttachExistingFilesInVariableValue(variable.OnValue); - variable.OffValue = AttachExistingFilesInVariableValue(variable.OffValue); - for (int index = 0; index < variable.Values.Count; index++) - { - variable.Values[index] = AttachExistingFilesInVariableValue( - variable.Values[index]); - } - } - } - - private string AttachExistingFilesInVariableValue(string value) - { - string updatedValue = value ?? string.Empty; - ConfigMakerPresetFileInfo directFile = TryExtractDirectFile(updatedValue); - ConfigMakerPresetFileInfo[] files = ExtractFilesFromText(updatedValue) - .Append(directFile) - .Where(file => file != null) - .DistinctBy(file => (file.Kind, file.Path), ConfigMakerPresetFileKeyComparer.Instance) - .ToArray(); - - foreach (ConfigMakerPresetFileInfo file in files) - { - ConfigMakerPresetResource resource = GetOrCreate(file, out bool resourceAdded); - if (resource == null) - { - continue; - } - - string rewritten = ReplaceFileInText(updatedValue, file, resource.Reference); - if (string.Equals(rewritten, updatedValue, StringComparison.Ordinal) && - directFile != null && - ConfigFileReferences.PathsEqual(directFile.Path, file.Path)) - { - rewritten = resource.Reference; - } - if (string.Equals(rewritten, updatedValue, StringComparison.Ordinal)) - { - if (resourceAdded) - { - _document.Resources.Remove(resource); - } - continue; - } - updatedValue = rewritten; - } - return updatedValue; - } } diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetStorageService.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetStorageService.cs index de1e4808..7ffb7be0 100644 --- a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetStorageService.cs +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetStorageService.cs @@ -16,8 +16,13 @@ namespace CDPIUI.Helper.CreateConfigHelper; -public sealed class ConfigMakerPresetStorageService +public sealed class ConfigMakerPresetStorageService : IConfigMakerDocumentStorage { + Task IConfigMakerDocumentStorage.SaveAsync( + string presetName, ConfigMakerPresetDocument document) => SaveAsync(presetName, document); + Task IConfigMakerDocumentStorage.OverwriteAsync( + ConfigMakerPresetDocument document) => OverwriteAsync(document); + public Task SaveAsync( string presetName, ConfigMakerPresetDocument document) diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetStructure.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetStructure.cs new file mode 100644 index 00000000..e3318589 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetStructure.cs @@ -0,0 +1,124 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.Core.ComponentServices.Helpers.Configuration; +using CDPIUI.ViewModels; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Owns explicit/detected structure and publication order; projection stays at the UI boundary. +internal sealed class ConfigMakerPresetStructure : ObservableObject +{ + private readonly Func _commandText; + private readonly Func _isZapret2; + private readonly Func> _extractFiles; + private readonly Func> _attachedFiles; + private readonly Func, IReadOnlyList> _buildFiles; + private readonly Func, IReadOnlyList, bool, IReadOnlyList> _buildGroups; + private bool _hasPresetFiles; + private bool _hasPresetGroups; + private bool _usesExplicitPresetStructure; + private ConfigMakerPresetFileInfo[] _explicitPresetFiles = []; + private ConfigMakerPresetGroupInfo[] _explicitPresetGroups = []; + private IReadOnlyList _presetFileNodes = []; + private IReadOnlyList _presetGroupNodes = []; + + public ConfigMakerPresetStructure(Func commandText, Func isZapret2, + Func> extractFiles, + Func> attachedFiles, + Func, IReadOnlyList> buildFiles, + Func, IReadOnlyList, bool, IReadOnlyList> buildGroups) + { + _commandText = commandText; + _isZapret2 = isZapret2; + _extractFiles = extractFiles; + _attachedFiles = attachedFiles; + _buildFiles = buildFiles; + _buildGroups = buildGroups; + } + + public event EventHandler? AvailabilityChanged; + public IReadOnlyList PresetFileNodes + { + get => _presetFileNodes; + set => SetProperty(ref _presetFileNodes, value); + } + public IReadOnlyList PresetGroupNodes + { + get => _presetGroupNodes; + set => SetProperty(ref _presetGroupNodes, value); + } + public bool IsPresetStructureVisible => _hasPresetFiles || HasPresetGroups; + public bool HasPresetFiles => _hasPresetFiles; + public bool HasPresetGroups => _hasPresetGroups || !_usesExplicitPresetStructure; + + // File replacement rewrites the stored array directly, then requests its own rebuild. + public bool UsesExplicitPresetStructure => _usesExplicitPresetStructure; + public ConfigMakerPresetFileInfo[] ExplicitPresetFiles + { + get => _explicitPresetFiles; + set => _explicitPresetFiles = value; + } + + public void Set(IEnumerable files, IEnumerable groups) + { + ArgumentNullException.ThrowIfNull(files); + ArgumentNullException.ThrowIfNull(groups); + _explicitPresetFiles = files + .Where(file => !string.IsNullOrWhiteSpace(file.Path)) + .DistinctBy(file => (file.Kind, file.Path), ConfigMakerPresetFileKeyComparer.Instance) + .ToArray(); + _explicitPresetGroups = groups.ToArray(); + _usesExplicitPresetStructure = true; + Rebuild(); + } + + public void Clear() + { + _usesExplicitPresetStructure = false; + _explicitPresetFiles = []; + _explicitPresetGroups = []; + Rebuild(); + } + + public void Rebuild() + { + ConfigMakerPresetFileInfo[] detectedFiles = _extractFiles(_commandText()).ToArray(); + ConfigMakerPresetFileInfo[] baseFiles = _usesExplicitPresetStructure + ? EnrichExplicitPresetFiles(_explicitPresetFiles, detectedFiles) + : detectedFiles; + ConfigMakerPresetFileInfo[] attachedFiles = _attachedFiles().ToArray(); + ConfigMakerPresetFileInfo[] files = baseFiles + .Concat(attachedFiles) + .DistinctBy(file => (file.Kind, file.Path), ConfigMakerPresetFileKeyComparer.Instance) + .ToArray(); + + PresetFileNodes = _buildFiles(files); + IReadOnlyList groupNodes = _buildGroups( + ConfigCommandLine.ParseOptions(_commandText()), _explicitPresetGroups, _isZapret2()); + + bool filesAvailabilityChanged = _hasPresetFiles != (files.Length > 0); + bool groupsAvailabilityChanged = _hasPresetGroups != (groupNodes.Count > 0); + _hasPresetFiles = files.Length > 0; + _hasPresetGroups = groupNodes.Count > 0; + + // The view reads the new availability while handling the group-node notification. + PresetGroupNodes = groupNodes; + OnPropertiesChanged(nameof(HasPresetFiles), nameof(HasPresetGroups), nameof(IsPresetStructureVisible)); + if (filesAvailabilityChanged || groupsAvailabilityChanged) + AvailabilityChanged?.Invoke(this, EventArgs.Empty); + } + + private static ConfigMakerPresetFileInfo[] EnrichExplicitPresetFiles( + IReadOnlyList files, IReadOnlyList detectedFiles) => + files.Select(file => + { + ConfigMakerPresetFileInfo? detected = detectedFiles.FirstOrDefault(candidate => + candidate.Kind == file.Kind && ConfigFileReferences.PathsEqual(candidate.Path, file.Path)); + return detected == null || !string.IsNullOrWhiteSpace(file.OptionName) + ? file : file with { OptionName = detected.OptionName }; + }).ToArray(); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeAdapter.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeAdapter.cs new file mode 100644 index 00000000..54573dde --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeAdapter.cs @@ -0,0 +1,45 @@ +using System.Collections.Generic; +using System.Linq; +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.ViewModels.ConfigMaker; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Keeps the WinUI content types and their existing XAML bindings at the presentation boundary. +internal static class ConfigMakerPresetTreeAdapter +{ + public static IReadOnlyList ToFileNodes(IEnumerable nodes) => + ConfigMakerPresetTreeProjection.Map(nodes, ToFileNode); + + public static IReadOnlyList ToOptionNodes(IEnumerable nodes) => + ConfigMakerPresetTreeProjection.Map(nodes, ToOptionNode); + + private static ConfigMakerTreeNode ToFileNode(ConfigMakerPresetFileNode source) + { + ConfigMakerTreeNode node = new(new ConfigMakerPresetFileTreeItem + { + DisplayName = source.DisplayName, + ToolTip = source.ToolTip, + File = source.File, + IsMissing = source.IsMissing, + }, source.IsExpanded); + node.Children.AddRange(source.Children.Select(ToFileNode)); + return node; + } + + private static ConfigMakerTreeNode ToOptionNode(ConfigMakerPresetOptionNode source) + { + ConfigMakerTreeNode node = new(new ConfigMakerPresetTreeItemViewModel + { + Title = source.Title ?? string.Empty, + Description = source.Description ?? string.Empty, + IsCode = source.IsCode, + SourceIndex = source.Source?.SourceIndex ?? -1, + SourceLength = source.Source?.SourceLength ?? 0, + SourceLine = source.Source?.SourceLine ?? 0, + SourceColumn = source.Source?.SourceColumn ?? 0, + }, source.IsExpanded); + node.Children.AddRange(source.Children.Select(ToOptionNode)); + return node; + } +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeBuilder.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeBuilder.cs new file mode 100644 index 00000000..6bdf8fcf --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeBuilder.cs @@ -0,0 +1,167 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.Core.ComponentServices.Helpers.Configuration; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Builds the preset trees without accessing the view, global services or the filesystem itself. +internal sealed class ConfigMakerPresetTreeBuilder +{ + private readonly Func _localize; + private readonly Func _resolvePath; + private readonly Func _fileExists; + private readonly Func _describeOption; + + public ConfigMakerPresetTreeBuilder( + Func localize, + Func resolvePath, + Func fileExists, + Func describeOption) + { + _localize = localize; + _resolvePath = resolvePath; + _fileExists = fileExists; + _describeOption = describeOption; + } + + public IReadOnlyList BuildFiles(IReadOnlyList files) + { + List nodes = []; + foreach (ConfigMakerPresetFileKind kind in Enum.GetValues()) + { + ConfigMakerPresetFileInfo[] categoryFiles = files + .Where(file => file.Kind == kind) + .OrderBy(file => file.Name, StringComparer.CurrentCultureIgnoreCase) + .ToArray(); + if (categoryFiles.Length == 0) + { + continue; + } + + string categoryName = _localize(kind switch + { + ConfigMakerPresetFileKind.Library => "ConfigMakerPresetFileCategoryLibraries", + ConfigMakerPresetFileKind.Payload => "ConfigMakerPresetFileCategoryPayloads", + _ => "ConfigMakerPresetFileCategorySiteLists", + }); + ConfigMakerPresetFileNode category = new(categoryName, categoryName, IsExpanded: true); + foreach (ConfigMakerPresetFileInfo file in categoryFiles) + { + string resolvedPath = _resolvePath(file.Path); + bool isMissing = string.IsNullOrWhiteSpace(resolvedPath) || !_fileExists(resolvedPath); + string toolTip = isMissing + ? string.Format(_localize("ConfigMakerPresetFileMissingMessage"), resolvedPath ?? file.Path) + : file.IsAttachedResource + ? $"{file.Path}{Environment.NewLine}{resolvedPath}" + : resolvedPath; + category.Children.Add(new(file.Name, toolTip, file, isMissing)); + } + nodes.Add(category); + } + return nodes; + } + + public IReadOnlyList BuildGroups( + IReadOnlyList options, + IReadOnlyList explicitGroups, + bool isZapret2) + { + List nodes = []; + if (options.Count == 0) + { + AddExplicitFallback(nodes, explicitGroups); + return nodes; + } + + int firstProfileOption = ConfigMakerPresetOptionGroups.FindFirstProfileOptionIndex(options); + ConfigCommandOption[] common = options.Take(firstProfileOption).ToArray(); + AddOptionNode(nodes, _localize("ConfigMakerPresetCommonFiltersGroup"), + common.Where(option => ConfigMakerPresetOptionGroups.IsCommonFilter(option.Name)), + "ConfigMakerZapret2CommonFiltersDescription", isZapret2); + AddOptionNode(nodes, _localize("ConfigMakerPresetCommonOptionsGroup"), + common.Where(option => !ConfigMakerPresetOptionGroups.IsCommonFilter(option.Name)), + "ConfigMakerZapret2CommonOptionsDescription", isZapret2); + + List> profiles = ConfigMakerPresetOptionGroups.SplitProfiles(options.Skip(firstProfileOption)); + for (int index = 0; index < profiles.Count; index++) + { + AddProfileNode(nodes, profiles[index], explicitGroups, index, isZapret2); + } + if (nodes.Count == 0) + { + AddExplicitFallback(nodes, explicitGroups); + } + return nodes; + } + + private void AddProfileNode( + List nodes, + IReadOnlyList options, + IReadOnlyList explicitGroups, + int index, + bool isZapret2) + { + string? parsedName = ConfigMakerPresetOptionGroups.FindProfileName(options); + string explicitName = index < explicitGroups.Count ? explicitGroups[index].Name : string.Empty; + string name = !string.IsNullOrWhiteSpace(explicitName) + ? explicitName + : !string.IsNullOrWhiteSpace(parsedName) + ? ConfigCommandLine.Unquote(parsedName) + : string.Format(_localize("ConfigMakerPresetProfileFallbackName"), index + 1); + ConfigMakerPresetOptionNode profile = new( + name, Description("ConfigMakerZapret2ProfileDescription", isZapret2), IsExpanded: true); + AddOptionNode(profile.Children, _localize("ConfigMakerPresetProfileFiltersGroup"), + options.Where(option => ConfigMakerPresetOptionGroups.IsProfileFilter(option.Name)), + "ConfigMakerZapret2ProfileFiltersDescription", isZapret2); + AddOptionNode(profile.Children, _localize("ConfigMakerPresetProfileActionsGroup"), + options.Where(option => !ConfigMakerPresetOptionGroups.IsProfileFilter(option.Name)), + "ConfigMakerZapret2ProfileActionsDescription", isZapret2); + if (profile.Children.Count > 0) + { + nodes.Add(profile); + } + } + + private void AddOptionNode( + List nodes, + string name, + IEnumerable options, + string descriptionKey, + bool isZapret2) + { + ConfigCommandOption[] items = options.ToArray(); + if (items.Length == 0) + { + return; + } + ConfigMakerPresetOptionNode node = new(name, Description(descriptionKey, isZapret2), IsExpanded: true); + foreach (ConfigCommandOption option in items) + { + node.Children.Add(new(option.DisplayText, isZapret2 ? _describeOption(option) : string.Empty, + IsCode: true, Source: option)); + } + nodes.Add(node); + } + + private static void AddExplicitFallback( + List nodes, + IEnumerable groups) + { + foreach (ConfigMakerPresetGroupInfo group in groups) + { + ConfigMakerPresetOptionNode node = new(group.Name); + foreach (string detail in group.Details.Where(value => !string.IsNullOrWhiteSpace(value))) + { + node.Children.Add(new(detail, IsCode: true)); + } + nodes.Add(node); + } + } + + private string Description(string key, bool isZapret2) => + isZapret2 && !string.IsNullOrWhiteSpace(key) ? _localize(key) : string.Empty; +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeData.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeData.cs new file mode 100644 index 00000000..aad8866a --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeData.cs @@ -0,0 +1,28 @@ +#nullable enable + +using System.Collections.Generic; +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.Core.ComponentServices.Helpers.Configuration; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Presentation data without WinUI objects; the adapter supplies fonts, brushes and visibility. +internal sealed record ConfigMakerPresetFileNode( + string DisplayName, + string ToolTip, + ConfigMakerPresetFileInfo? File = null, + bool IsMissing = false, + bool IsExpanded = false) +{ + public List Children { get; } = []; +} + +internal sealed record ConfigMakerPresetOptionNode( + string Title, + string Description = "", + bool IsCode = false, + ConfigCommandOption? Source = null, + bool IsExpanded = false) +{ + public List Children { get; } = []; +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeProjection.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeProjection.cs new file mode 100644 index 00000000..9e94ab84 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeProjection.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal static class ConfigMakerPresetTreeProjection +{ + // Collection identity participates in ViewModel property-change notifications. + public static IReadOnlyList Map( + IEnumerable nodes, Func map) => nodes.Select(map).ToList(); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerSimpleDesigner.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerSimpleDesigner.cs new file mode 100644 index 00000000..cd776923 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerSimpleDesigner.cs @@ -0,0 +1,180 @@ +#nullable enable + +using System; +using System.Collections.ObjectModel; +using System.Linq; +using CDPIUI.ViewModels; +using CDPIUI.Views.CreateConfigHelper; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Owns designer models and synchronization. The host supplies editor access and UI notices. +internal sealed class ConfigMakerSimpleDesigner : ObservableObject +{ + private readonly IConfigMakerSimpleDesignerBackend _backend; + private readonly Func _currentComponent; + private readonly Func _getEditorText; + private readonly Action _setEditorText; + private readonly ConfigMakerDesignerCommands _commands; + private readonly Action _notice; + private bool _updatingDesigner; + private bool _designerNeedsRefresh = true; + private string _additionalDesignerArguments = string.Empty; + + public ConfigMakerSimpleDesigner(IConfigMakerSimpleDesignerBackend backend, + Func currentComponent, Func getEditorText, Action setEditorText, + ConfigMakerDesignerCommands commands, Action notice) + { + _backend = backend; + _currentComponent = currentComponent; + _getEditorText = getEditorText; + _setEditorText = setEditorText; + _commands = commands; + _notice = notice; + } + + public ObservableCollection DesignerSettingItemModels { get; } = []; + public ObservableCollection DesignerExclusiveSettingItemModels { get; } = []; + public bool IsSimpleDesignerSupported => _backend.IsSupported(_currentComponent()); + public string AdditionalDesignerArguments + { + get => _additionalDesignerArguments; + private set => SetProperty(ref _additionalDesignerArguments, value ?? string.Empty); + } + + public void MarkDirty() => _designerNeedsRefresh = true; + + public void UpdateAvailability() + { + OnPropertyChanged(nameof(IsSimpleDesignerSupported)); + if (!IsSimpleDesignerSupported) + { + DesignerSettingItemModels.Clear(); + DesignerExclusiveSettingItemModels.Clear(); + } + } + + public void OnAdditionalDesignerArgumentsChanged(string? text) + { + // The box already shows the text: do not send a change back to it. + _additionalDesignerArguments = text ?? string.Empty; + ApplyToCommand(); + } + + public void OnEditorViewChanged(bool leftDesigner, bool enteredDesigner) + { + if (leftDesigner) + { + ApplyToCommand(); + } + if (enteredDesigner && _designerNeedsRefresh) + { + Load(); + } + } + + private void Load() + { + if (!IsSimpleDesignerSupported) + { + return; + } + _updatingDesigner = true; + try + { + AdditionalDesignerArguments = ComponentCommandLineFormatter.ToSingleLine(_getEditorText()); + DesignerSettingItemModels.Clear(); + DesignerExclusiveSettingItemModels.Clear(); + if (!_backend.TryLoad(_currentComponent(), DesignerSettingItemModels, DesignerExclusiveSettingItemModels)) + { + _notice(ConfigMakerDesignerNotice.MissingAnnotation, null); + return; + } + AttachCommands(); + AdditionalDesignerArguments = _backend.Parse(DesignerSettingItemModels, + DesignerExclusiveSettingItemModels, ComponentCommandLineFormatter.ToSingleLine(_getEditorText())); + _designerNeedsRefresh = false; + } + catch (Exception exception) + { + DesignerSettingItemModels.Clear(); + DesignerExclusiveSettingItemModels.Clear(); + _notice(ConfigMakerDesignerNotice.LoadFailed, exception); + } + finally + { + _updatingDesigner = false; + } + } + + private void AttachCommands() + { + foreach (GraphicDesignerSettingItemModel item in DesignerSettingItemModels) + { + item.DesignerTextValueChangedCommand = _commands.Text; + item.DesignerBoolValueToggledCommand = _commands.Bool; + } + foreach (GraphicDesignerExclusiveSettingItemModel group in DesignerExclusiveSettingItemModels) + { + group.DesignerTextValueChangedCommand = _commands.Text; + group.DesignerBoolValueToggledCommand = _commands.Bool; + group.DesignerSelectedGuidChangedCommand = _commands.SelectedGuid; + } + } + + public void HandleDesignerTextValueChanged(Tuple change) + { + GraphicDesignerSettingItemModel? item = FindItem(change.Item1); + if (item != null) + { + item.Value = change.Item2; + ApplyToCommand(); + } + } + + public void HandleDesignerBoolValueToggled(Tuple change) + { + GraphicDesignerSettingItemModel? item = FindItem(change.Item1); + if (item != null) + { + item.IsChecked = change.Item2; + ApplyToCommand(); + } + } + + public void HandleDesignerSelectedGuidChanged(Tuple change) + { + GraphicDesignerExclusiveSettingItemModel? group = DesignerExclusiveSettingItemModels.FirstOrDefault(item => + string.Equals(item.Guid, change.Item1, StringComparison.Ordinal)); + if (group != null) + { + group.SelectedItemGuid = change.Item2; + ApplyToCommand(); + } + } + + private GraphicDesignerSettingItemModel? FindItem(string id) => + DesignerSettingItemModels.FirstOrDefault(item => string.Equals(item.Guid, id, StringComparison.Ordinal)) ?? + DesignerExclusiveSettingItemModels.SelectMany(group => group.Items) + .FirstOrDefault(item => string.Equals(item.Guid, id, StringComparison.Ordinal)); + + private void ApplyToCommand() + { + if (_updatingDesigner || _designerNeedsRefresh || !IsSimpleDesignerSupported) + { + return; + } + _updatingDesigner = true; + try + { + string command = _backend.Build(DesignerSettingItemModels, DesignerExclusiveSettingItemModels, + _additionalDesignerArguments); + _setEditorText(ComponentCommandLineFormatter.FormatByFlags(command.Trim())); + _designerNeedsRefresh = false; + } + finally + { + _updatingDesigner = false; + } + } +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerSimpleDesignerBackend.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerSimpleDesignerBackend.cs new file mode 100644 index 00000000..445454c2 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerSimpleDesignerBackend.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.ObjectModel; +using System.IO; +using CDPIUI.Core.Store.Data; +using CDPIUI.Core.Store.Database; +using CDPIUI.Views.CreateConfigHelper; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Keeps the existing configuration factories/codec and resolves services only when loading. +internal sealed class ConfigMakerSimpleDesignerBackend : IConfigMakerSimpleDesignerBackend +{ + public bool IsSupported(string componentId) => + string.Equals(componentId, HardcodedItemIds.ComponentIds[Components.GoodbyeDPI], StringComparison.OrdinalIgnoreCase) || + string.Equals(componentId, HardcodedItemIds.ComponentIds[Components.SpoofDPI], StringComparison.OrdinalIgnoreCase) || + string.Equals(componentId, HardcodedItemIds.ComponentIds[Components.NoDPI], StringComparison.OrdinalIgnoreCase); + + public bool TryLoad(string componentId, ObservableCollection items, + ObservableCollection groups) + { + if (string.Equals(componentId, HardcodedItemIds.ComponentIds[Components.GoodbyeDPI], StringComparison.OrdinalIgnoreCase)) + { + GraphicDesignerHelper.LoadGoodbyeDPIDesignerConfig(items, groups); + return true; + } + if (string.Equals(componentId, HardcodedItemIds.ComponentIds[Components.SpoofDPI], StringComparison.OrdinalIgnoreCase)) + { + GraphicDesignerHelper.LoadSpoofDPIDesignerConfig(items, groups); + return true; + } + + string componentDirectory = DatabaseHelper.Instance.GetItemById(componentId)?.Directory ?? string.Empty; + string annotationPath = Path.Combine(componentDirectory, "edannotationfile.xml"); + if (!File.Exists(annotationPath)) + { + return false; + } + GraphicDesignerHelper.XML_LoadDesignerConfig(annotationPath, "nodpi", items, groups); + return true; + } + + public string Parse(ObservableCollection items, + ObservableCollection groups, string command) => + GraphicDesignerHelper.ConvertStringToGraphicDesignerSettings(items, groups, command); + + public string Build(ObservableCollection items, + ObservableCollection groups, string additional) => + GraphicDesignerHelper.ConvertGraphicDesignerSettingsToString(items, groups, additional); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerTestSession.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerTestSession.cs new file mode 100644 index 00000000..8815b647 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerTestSession.cs @@ -0,0 +1,140 @@ +#nullable enable + +using System; +using System.Threading.Tasks; + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal enum ConfigMakerTestNotice +{ + Started, + Stopped, + Exited, + NotInstalled, + StartFailed, +} + +// Owns one editor test run. The host validates/resolves arguments and supplies UI effects. +internal sealed class ConfigMakerTestSession +{ + private readonly IConfigMakerTestTasks _tasks; + private readonly Func _currentComponent; + private readonly Func> _confirmReplacement; + private readonly Func _isInstalled; + private readonly Action _notice; + private readonly Func _refreshOutput; + private readonly Action> _enqueue; + private bool _isTesting; + private bool _isStartingTest; + private bool _restoreComponentAfterTest; + private string _testComponentId = string.Empty; + + public ConfigMakerTestSession( + IConfigMakerTestTasks tasks, + Func currentComponent, + Func> confirmReplacement, + Func isInstalled, + Action notice, + Func refreshOutput, + Action> enqueue) + { + _tasks = tasks; + _currentComponent = currentComponent; + _confirmReplacement = confirmReplacement; + _isInstalled = isInstalled; + _notice = notice; + _refreshOutput = refreshOutput; + _enqueue = enqueue; + } + + public event EventHandler? StateChanged; + public bool IsTesting => _isTesting; + public string TestComponentId => _testComponentId; + + public async Task StartAsync(string arguments) + { + await StopAsync(); + bool componentWasRunning = await _tasks.IsRunningAsync(_currentComponent()); + if (componentWasRunning && !await _confirmReplacement()) + { + return; + } + + _restoreComponentAfterTest = componentWasRunning; + await _tasks.StopAsync(_currentComponent()); + + _testComponentId = _currentComponent(); + _isTesting = true; + _isStartingTest = true; + _tasks.StateUpdated += TaskStateUpdated; + RaiseStateChanged(); + + if (!_isInstalled(_testComponentId)) + { + _notice(ConfigMakerTestNotice.NotInstalled, null); + await StopAsync(); + return; + } + + _notice(ConfigMakerTestNotice.Started, null); + try + { + await _tasks.RunAsync(_testComponentId, arguments); + _isStartingTest = false; + await _refreshOutput(); + } + catch (Exception exception) + { + _isStartingTest = false; + _notice(ConfigMakerTestNotice.StartFailed, exception.Message); + await StopAsync(); + } + } + + public async Task StopAsync(bool showCompletionMessage = false) + { + if (!_isTesting) + { + return; + } + + string componentId = _testComponentId; + bool restore = _restoreComponentAfterTest; + _isTesting = false; + _isStartingTest = false; + _tasks.StateUpdated -= TaskStateUpdated; + RaiseStateChanged(); + + if (!string.IsNullOrWhiteSpace(componentId)) + { + await _tasks.StopAsync(componentId); + if (restore) + { + await _tasks.RestoreAsync(componentId); + } + } + + _testComponentId = string.Empty; + _restoreComponentAfterTest = false; + if (showCompletionMessage) + { + _notice(ConfigMakerTestNotice.Stopped, null); + } + } + + private void TaskStateUpdated(Tuple state) + { + if (!_isTesting || _isStartingTest || + !string.Equals(state.Item1, _testComponentId, StringComparison.OrdinalIgnoreCase) || state.Item2) + { + return; + } + _enqueue(async () => + { + _notice(ConfigMakerTestNotice.Exited, null); + await StopAsync(); + }); + } + + private void RaiseStateChanged() => StateChanged?.Invoke(this, EventArgs.Empty); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ConfigMakerVariableActions.cs b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerVariableActions.cs new file mode 100644 index 00000000..1fe879f1 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ConfigMakerVariableActions.cs @@ -0,0 +1,85 @@ +#nullable enable + +using System; +using System.Threading.Tasks; +using CDPIUI.ViewModels; +using CDPIUI.ViewModels.ConfigMaker; + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal sealed class ConfigMakerVariableActions +{ + private readonly ConfigMakerPresetDocument _document; + private readonly IConfigMakerVariableActionsHost _host; + + public ConfigMakerVariableActions(ConfigMakerPresetDocument document, IConfigMakerVariableActionsHost host) + { + _document = document; + _host = host; + } + + public async Task EditVariableAsync(ConfigMakerVariableDefinition? variable) + { + if (variable == null) + { + return; + } + ConfigMakerVariableEditResult? result = await _host.EditVariableAsync(_document, variable); + if (result == null) + { + return; + } + int index = _document.Variables.IndexOf(variable); + if (index < 0) + { + return; + } + if (!string.Equals(result.OriginalName, result.Variable.Name, StringComparison.Ordinal)) + { + _document.ReplaceVariableReference(result.OriginalName, result.Variable.Name); + _host.SetEditorText(_document.CommandText); + } + _document.Variables[index] = result.Variable; + _host.AttachExistingPresetFiles(); + _host.RebuildPresetStructure(); + _host.ScheduleDiagnostics(); + } + + public async Task RemoveVariableAsync(ConfigMakerVariableDefinition? variable) + { + if (variable == null) + { + return; + } + bool referenced = _host.CommandText.Contains(variable.Reference, StringComparison.OrdinalIgnoreCase); + if (referenced && !await _host.ConfirmRemoveReferencedVariableAsync()) + { + return; + } + _document.Variables.Remove(variable); + _host.RebuildPresetStructure(); + _host.ScheduleDiagnostics(); + } + + public void InsertVariableReference(ConfigMakerVariableDefinition? variable) + { + if (!_host.IsEditorReadOnly && variable != null) + { + _host.InsertAtCursor(variable.Reference); + } + } + + public async Task CreateVariableAsync() + { + ConfigMakerVariableEditResult? result = await _host.EditVariableAsync(_document, null); + if (result == null) + { + return; + } + _document.Variables.Add(result.Variable); + _host.AttachExistingPresetFiles(); + _host.ShowVariablesTool(); + _host.RebuildPresetStructure(); + _host.ScheduleDiagnostics(); + } +} diff --git a/CDPIUI/Helper/CreateConfigHelper/CreateConfigComponentTestTasks.cs b/CDPIUI/Helper/CreateConfigHelper/CreateConfigComponentTestTasks.cs new file mode 100644 index 00000000..40186090 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/CreateConfigComponentTestTasks.cs @@ -0,0 +1,21 @@ +#nullable enable + +using System; +using System.Threading.Tasks; +using CDPIUI.Core.ComponentServices; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Keep singleton access at the original operation/subscription points. +internal sealed class CreateConfigComponentTestTasks : ICreateConfigTestTasks +{ + public event Action>? StateUpdated + { + add => ComponentTasksManager.Instance.TaskStateUpdated += value; + remove => ComponentTasksManager.Instance.TaskStateUpdated -= value; + } + + public Task StopAsync(string componentId) => ComponentTasksManager.Instance.StopTask(componentId); + public Task RunAsync(string componentId, string arguments) => + ComponentTasksManager.Instance.CreateAndRunNewTask(componentId, arguments); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/CreateConfigGraphicDesignerBackend.cs b/CDPIUI/Helper/CreateConfigHelper/CreateConfigGraphicDesignerBackend.cs new file mode 100644 index 00000000..5be1282a --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/CreateConfigGraphicDesignerBackend.cs @@ -0,0 +1,39 @@ +#nullable enable + +using System.Collections.ObjectModel; +using System.IO; +using CDPIUI.Core.Store.Database; +using CDPIUI.Views.CreateConfigHelper; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Specific factories preserve the config page's own branch/cache policy. +internal sealed class CreateConfigGraphicDesignerBackend : ICreateConfigGraphicDesignerBackend +{ + public void LoadGoodbye(ObservableCollection items, + ObservableCollection groups) => + GraphicDesignerHelper.LoadGoodbyeDPIDesignerConfig(items, groups); + + public void LoadSpoof(ObservableCollection items, + ObservableCollection groups) => + GraphicDesignerHelper.LoadSpoofDPIDesignerConfig(items, groups); + + public bool TryLoadNoDpi(string componentId, ObservableCollection items, + ObservableCollection groups) + { + string directory = DatabaseHelper.Instance.GetItemById(componentId)?.Directory ?? string.Empty; + string annotation = Path.Combine(directory, "edannotationfile.xml"); + if (!File.Exists(annotation)) + return false; + GraphicDesignerHelper.XML_LoadDesignerConfig(annotation, "nodpi", items, groups); + return true; + } + + public string Parse(ObservableCollection items, + ObservableCollection groups, string text) => + GraphicDesignerHelper.ConvertStringToGraphicDesignerSettings(items, groups, text); + + public string Build(ObservableCollection items, + ObservableCollection groups, string additional) => + GraphicDesignerHelper.ConvertGraphicDesignerSettingsToString(items, groups, additional); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/GraphicDesignerCommandCodec.cs b/CDPIUI/Helper/CreateConfigHelper/GraphicDesignerCommandCodec.cs new file mode 100644 index 00000000..a11fac5b --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/GraphicDesignerCommandCodec.cs @@ -0,0 +1,230 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using CDPIUI.Views.CreateConfigHelper; + +namespace CDPIUI.Helper.CreateConfigHelper; + +// Converts existing designer models to/from command text; model creation stays in the host. +internal static class GraphicDesignerCommandCodec +{ + public static string Parse( + ObservableCollection list, + ObservableCollection exList, + string args, + bool exclusive = true, + Func? addModelItem = null + ) + { + ClearSelection(list, exList); + + var notSupportedFlags = new StringBuilder(); + List tokens = Tokenize(args); + + for (int i = 0; i < tokens.Count; i++) + { + (string token, string value, bool separateValue) = ReadOption(tokens, ref i); + + var item = exclusive ? list.FirstOrDefault(x => x.DisplayName == token) : null; + bool supported; + if (item == null && exclusive) + { + supported = TrySelectExclusiveItem(exList, token, value, separateValue); + } + else if (item == null && !exclusive && addModelItem != null) + { + supported = addModelItem(token, new(DecodeQuotedValue(value), IsQuotePair(value))); + } + else + { + CheckItem(item!, value, separateValue); + supported = true; + } + + if (!supported) + { + notSupportedFlags.Append(token); + if (!string.IsNullOrEmpty(value)) + { + // Inline ownership must survive when a filename also looks + // like a real option on the next designer visit. + bool keepInline = !separateValue && LooksLikeOption(value); + notSupportedFlags.Append(keepInline ? '=' : ' ').Append(value); + } + notSupportedFlags.Append(' '); + } + } + + return notSupportedFlags.ToString(); + } + + private static void ClearSelection( + ObservableCollection list, + ObservableCollection exList) + { + foreach (var item in list) + { + item.IsChecked = false; + } + foreach (var exItem in exList) + { + foreach (var item in exItem.Items) + { + item.IsChecked = false; + } + } + } + + private static List Tokenize(string args) + { + var tokenPattern = @"(?<=\s|^)(?:(?:(?:--?|/)[^\s]*=""[^""]*"")|""[^""]*""|[^ ]+)+"; + return Regex.Matches(args, tokenPattern) + .Cast() + .Select(m => m.Value) + .ToList(); + } + + // Reads the option at index i and its value: "--name=value", or "--name value" when the + // next token is not an option (then i moves past the value). + private static (string Token, string Value, bool SeparateValue) ReadOption(List tokens, ref int i) + { + string token = tokens[i]; + // Quoted values must reach the model/additional text intact. Only unwrap a + // whole quoted option here, where its role as an option is already known. + bool quotedOption = token.Length >= 3 && token[0] == '"' && token[^1] == '"' && + LooksLikeOption(token); + if (quotedOption) + { + token = token[1..^1]; + } + string value = string.Empty; + bool separateValue = false; + if (token.Contains('=')) + { + // The value may contain '=' itself (base64, fake payload hex and so on). + int separator = token.IndexOf('='); + value = token[(separator + 1)..]; + token = token[..separator]; + // The outer quote pair grouped the entire --name=value argument. Move + // that grouping to a value which would otherwise split or disappear. + if (quotedOption && (value.Length == 0 || value.Any(char.IsWhiteSpace)) && + !(value.Length >= 2 && value[0] == '"' && value[^1] == '"')) + { + value = $"\"{value}\""; + } + } + else if (tokens.Count - 1 >= i + 1 && !LooksLikeOption(tokens[i + 1])) + { + value = tokens[i + 1]; + separateValue = true; + i++; + } + return (token, value, separateValue); + } + + private static bool LooksLikeOption(string token) + { + string name = token.Trim('"'); + if (IsQuotePair(token)) + { + int separator = name.IndexOf('='); + string optionName = separator < 0 ? name : name[..separator]; + // Whitespace in the option name identifies a grouped value. Spaces + // after '=' still belong to a genuine whole quoted option's value. + if (optionName.Any(char.IsWhiteSpace)) + return false; + } + return name.StartsWith('-') || name.StartsWith('/'); + } + + private static bool TrySelectExclusiveItem( + ObservableCollection exList, + string token, + string value, + bool separateValue) + { + foreach (var exModel in exList) + { + var item = exModel.Items.FirstOrDefault(x => x.DisplayName == token); + if (item != null) + { + CheckItem(item, value, separateValue); + exModel.SelectedItemGuid = item.Guid; + return true; + } + } + return false; + } + + private static bool IsQuotePair(string value) => + value.Length >= 2 && value[0] == '"' && value[^1] == '"'; + + private static string DecodeQuotedValue(string value) => IsQuotePair(value) ? value[1..^1] : value; + + private static void CheckItem(GraphicDesignerSettingItemModel item, string value, bool separateValue) + { + item.IsChecked = true; + bool preserveGrouping = IsQuotePair(value); + if (separateValue || item.Type == "enum") + value = DecodeQuotedValue(value); + if (value.StartsWith('"') && !value.EndsWith('"')) + value += "\""; + item.SetParsedValue(value, preserveGrouping); + } + + private static readonly List TextSupportedValues = ["string", "integer", "file_path", "enum"]; + + + + public static string Build(ObservableCollection list, ObservableCollection exList, string additionalArgs) + { + string startupString = string.Empty; + foreach (var item in list) + { + (bool flowControl, startupString) = ProcessItemActions(startupString, item); + if (!flowControl) + { + continue; + } + } + foreach (var itemGroup in exList) + { + var item = itemGroup.Items.FirstOrDefault(x => x.Guid == itemGroup.SelectedItemGuid); + if (item != null) + { + (bool flowControl, startupString) = ProcessItemActions(startupString, item); + if (!flowControl) + { + continue; + } + } + } + return $"{startupString}{additionalArgs}"; + } + + private static (bool flowControl, string value) ProcessItemActions(string startupString, GraphicDesignerSettingItemModel item) + { + if (!item.IsChecked && item.Type != "enum") + return (flowControl: false, value: startupString); + startupString += $"{item.DisplayName}"; + string? value = item.Value; + if ((item.EnableTextInput || TextSupportedValues.Contains(item.Type)) && value != null && + (value.Length > 0 || item.PreserveValueGrouping)) + { + if (item.PreserveValueGrouping && !IsQuotePair(value) && + (value.Length == 0 || value.Any(char.IsWhiteSpace))) + value = $"\"{value}\""; + startupString += $"={value}"; + } + startupString += " "; + return (flowControl: true, value: startupString); + } + +} + +internal readonly record struct GraphicDesignerCommandValue(string Text, bool PreserveGrouping); diff --git a/CDPIUI/Helper/CreateConfigHelper/GraphicDesignerHelper.cs b/CDPIUI/Helper/CreateConfigHelper/GraphicDesignerHelper.cs index 2c4c90d6..7afc5c55 100644 --- a/CDPIUI/Helper/CreateConfigHelper/GraphicDesignerHelper.cs +++ b/CDPIUI/Helper/CreateConfigHelper/GraphicDesignerHelper.cs @@ -5,8 +5,6 @@ using System.Diagnostics; using System.IO; using System.Linq; -using System.Text; -using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; @@ -260,122 +258,23 @@ public static string ConvertStringToGraphicDesignerSettings( ObservableCollection exList, string args, bool exclusive = true, - List> model = null - ) - { - ClearSelection(list, exList); - - var notSupportedFlags = new StringBuilder(); - List tokens = Tokenize(args); - - for (int i = 0; i < tokens.Count; i++) - { - (string token, string value) = ReadOption(tokens, ref i); - - var item = exclusive ? list.FirstOrDefault(x => x.DisplayName == token) : null; - bool supported; - if (item == null && exclusive) - { - supported = TrySelectExclusiveItem(exList, token, value); - } - else if (item == null && !exclusive && model != null) - { - supported = TryAddModelItem(list, model, token, value); - } - else - { - CheckItem(item, value); - supported = true; - } - - if (!supported) - { - notSupportedFlags.Append($"{token} "); - if (!string.IsNullOrEmpty(value)) - notSupportedFlags.Append($"{value} "); - } - } - - return notSupportedFlags.ToString(); - } - - private static void ClearSelection( - ObservableCollection list, - ObservableCollection exList) - { - foreach (var item in list) - { - item.IsChecked = false; - } - foreach (var exItem in exList) - { - foreach (var item in exItem.Items) - { - item.IsChecked = false; - } - } - } - - private static List Tokenize(string args) - { - var tokenPattern = @"(?<=\s|^)(?:(?:(?:--|/)[^\s]*=""[^""]*"")|""[^""]*""|[^ ]+)+"; - return Regex.Matches(args, tokenPattern) - .Cast() - .Select(m => m.Value.Trim('"')) - .ToList(); - } - - // Reads the option at index i and its value: "--name=value", or "--name value" when the - // next token is not an option (then i moves past the value). - private static (string Token, string Value) ReadOption(List tokens, ref int i) - { - string token = tokens[i]; - string value = string.Empty; - if (token.Contains('=')) - { - // The value may contain '=' itself (base64, fake payload hex and so on). - int separator = token.IndexOf('='); - value = token[(separator + 1)..]; - token = token[..separator]; - } - else if (tokens.Count - 1 >= i + 1 && !tokens[i + 1].StartsWith('-') && !tokens[i + 1].StartsWith('/')) - { - value = tokens[i + 1]; - i++; - } - return (token, value); - } - - private static bool TrySelectExclusiveItem( - ObservableCollection exList, - string token, - string value) - { - foreach (var exModel in exList) - { - var item = exModel.Items.FirstOrDefault(x => x.DisplayName == token); - if (item != null) - { - CheckItem(item, value); - exModel.SelectedItemGuid = item.Guid; - return true; - } - } - return false; - } + List> model = null) => + GraphicDesignerCommandCodec.Parse(list, exList, args, exclusive, + model == null ? null : (token, value) => TryAddModelItem(list, model, token, value.Text, value.PreserveGrouping)); private static bool TryAddModelItem( ObservableCollection list, List> model, string token, - string value) + string value, + bool preserveValueGrouping) { ILocalizer localizer = Localizer.Get(); var tuple = model.FirstOrDefault(x => x.Item1 == token); if (tuple == null) return false; - list.Add(new() + GraphicDesignerSettingItemModel item = new() { Guid = Guid.NewGuid().ToString(), DisplayName = tuple.Item1, @@ -384,57 +283,14 @@ private static bool TryAddModelItem( Type = tuple.Item3 ? "string" : "flag", Value = value, IsChecked = true, - }); + }; + item.SetParsedValue(value, preserveValueGrouping); + list.Add(item); return true; } - private static void CheckItem(GraphicDesignerSettingItemModel item, string value) - { - item.IsChecked = true; - if (value.StartsWith("\"")) - value += "\""; - item.Value = value; - } - - private static readonly List TextSupportedValues = ["string", "integer", "file_path", "enum"]; - - - - public static string ConvertGraphicDesignerSettingsToString(ObservableCollection list, ObservableCollection exList, string additionalArgs) - { - string startupString = string.Empty; - foreach (var item in list) - { - (bool flowControl, startupString) = ProcessItemActions(startupString, item); - if (!flowControl) - { - continue; - } - } - foreach (var itemGroup in exList) - { - var item = itemGroup.Items.FirstOrDefault(x => x.Guid == itemGroup.SelectedItemGuid); - if (item != null) - { - (bool flowControl, startupString) = ProcessItemActions(startupString, item); - if (!flowControl) - { - continue; - } - } - } - return $"{startupString}{additionalArgs}"; - } - - private static (bool flowControl, string value) ProcessItemActions(string startupString, GraphicDesignerSettingItemModel item) - { - if (!item.IsChecked && item.Type != "enum") - return (flowControl: false, value: startupString); - startupString += $"{item.DisplayName}"; - if ((item.EnableTextInput || TextSupportedValues.Contains(item.Type)) && !string.IsNullOrEmpty(item.Value)) - startupString += $"={item.Value}"; - startupString += " "; - return (flowControl: true, value: startupString); - } - + public static string ConvertGraphicDesignerSettingsToString( + ObservableCollection list, + ObservableCollection exList, + string additionalArgs) => GraphicDesignerCommandCodec.Build(list, exList, additionalArgs); } diff --git a/CDPIUI/Helper/CreateConfigHelper/IConfigMakerDocumentHost.cs b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerDocumentHost.cs new file mode 100644 index 00000000..741aaf92 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerDocumentHost.cs @@ -0,0 +1,29 @@ +#nullable enable + +using System.Threading.Tasks; +using CDPIUI.Core.ComponentServices.Helpers.Configuration; +using CDPIUI.ViewModels.ConfigMaker; + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal interface IConfigMakerDocumentHost +{ + string ComponentId { get; set; } + string? EditorText { get; } + bool IsEditorReadOnly { get; } + void SetEditorText(string text); + void SetBaseDirectory(string value); + void RebuildPresetStructure(); + void UpdateSimpleDesignerAvailability(); + void NotifyDocumentStateChanged(); + void AttachExistingPresetFiles(); + Task ApplyAutoCorrectorSilentlyAsync(ConfigItem item); + string GetConfigItemBaseDirectory(ConfigItem item); + Task AskSavePresetAsync(string suggestedName, bool overwriteEnabled); + Task ConfirmNewDocumentAsync(); + string? ChooseExportPath(bool allowTextFormat); + void ClearPresetStructure(); + void ClearEditorUndoHistory(); + string Text(string key); + void ShowDocumentMessage(string message, bool isError); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/IConfigMakerDocumentStorage.cs b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerDocumentStorage.cs new file mode 100644 index 00000000..b54922e4 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerDocumentStorage.cs @@ -0,0 +1,12 @@ +#nullable enable + +using System.Threading.Tasks; +using CDPIUI.ViewModels; + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal interface IConfigMakerDocumentStorage +{ + Task SaveAsync(string presetName, ConfigMakerPresetDocument document); + Task OverwriteAsync(ConfigMakerPresetDocument document); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPanelLayoutView.cs b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPanelLayoutView.cs new file mode 100644 index 00000000..98a4220c --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPanelLayoutView.cs @@ -0,0 +1,22 @@ +#nullable enable + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal interface IConfigMakerPanelLayoutView +{ + double RootWidth { get; } + double RootHeight { get; } + bool FilesVisible { get; } + bool CommandsVisible { get; } + bool BottomVisible { get; } + double FilesMinWidth { get; } + double FilesMaxWidth { get; set; } + double FilesWidth { get; set; } + double FilesSizerWidth { get; } + double CommandSizerWidth { get; } + double BottomSizerHeight { get; } + double EditorMaxWidth { set; } + double EditorWidth { set; } + double EditorMaxHeight { set; } + double EditorHeight { get; set; } +} diff --git a/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileActionsBackend.cs b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileActionsBackend.cs new file mode 100644 index 00000000..f9b6d276 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileActionsBackend.cs @@ -0,0 +1,23 @@ +#nullable enable + +using System.Collections.Generic; +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.ViewModels; + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal interface IConfigMakerPresetFileActionsBackend +{ + int AddFiles(IEnumerable paths); + string ResolvePath(string path); + string? TryResolvePath(string path); + bool FileExists(string path); + ConfigMakerPresetResource GetOrCreate(string fullPath, ConfigMakerPresetFileKind kind, out bool added); + ConfigMakerPresetResource? FindAttached(string path); + bool IsReferenced(ConfigMakerPresetResource resource); + bool ShouldAskForTextApplication(); + void RememberTextFileDialogShown(); + void OpenTextFile(string path); + void OpenFileInDefaultApp(string path); + void ShowFileInFolder(string path); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileActionsHost.cs b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileActionsHost.cs new file mode 100644 index 00000000..fbea2ecf --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileActionsHost.cs @@ -0,0 +1,23 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal interface IConfigMakerPresetFileActionsHost +{ + Task RunReportingErrorsAsync(Func action); + IReadOnlyList ChoosePresetFilesToAdd(); + void AttachExistingPresetFiles(); + void RebuildPresetStructure(); + void SetPresetFilesPanelVisible(bool visible); + string Text(string key); + void ShowPresetFileMessage(string message, ConfigMakerPresetFileNoticeSeverity severity); + Task AskTextFileApplicationAsync(string path); + Task ConfirmRemoveReferencedFileAsync(); + void ScheduleDiagnostics(); + bool IsEditorReadOnly { get; } + void InsertAtCursor(string reference); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileReplacementBackend.cs b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileReplacementBackend.cs new file mode 100644 index 00000000..a91f2a29 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileReplacementBackend.cs @@ -0,0 +1,22 @@ +#nullable enable + +using System.Threading.Tasks; +using CDPIUI.Controls.CreateConfigHelper; + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal interface IConfigMakerPresetFileReplacementBackend +{ + string? TryResolvePath(string sourcePath); + bool FileExists(string path); + void CreateEmptyFile(string path); + bool TryUpdateAttachedResource(ConfigMakerPresetFileInfo file, string fullReplacementPath); + ConfigMakerPresetFileReplacement? ReplaceReferences(ConfigMakerPresetFileInfo file, string fullReplacementPath); + IConfigMakerPresetFileAutoCorrector CreateAutoCorrector(); +} + +internal interface IConfigMakerPresetFileAutoCorrector +{ + bool ShouldSuggestEmptyFile(string missingPath); + Task FindReplacementAsync(string missingPath); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileReplacementHost.cs b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileReplacementHost.cs new file mode 100644 index 00000000..05bea817 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileReplacementHost.cs @@ -0,0 +1,24 @@ +#nullable enable + +using System; +using System.Threading.Tasks; +using CDPIUI.Controls.CreateConfigHelper; +using CDPIUI.ViewModels.ConfigMaker; + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal enum ConfigMakerPresetFileNoticeSeverity { Success, Warning, Error } + +internal interface IConfigMakerPresetFileReplacementHost +{ + Task RunReportingErrorsAsync(Func action); + Task AskPresetFileReplacementAsync(string missingPath); + string? ChooseReplacementFile(string missingPath); + string Text(string key); + void ShowPresetFileMessage(string message, ConfigMakerPresetFileNoticeSeverity severity); + void RebuildPresetStructure(); + bool UsesExplicitPresetStructure { get; } + ConfigMakerPresetFileInfo[] ExplicitPresetFiles { get; set; } + void SetCommandText(string commandText); + void NotifyPresetFileReplaced(string originalPath, string replacementPath); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/IConfigMakerSimpleDesignerBackend.cs b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerSimpleDesignerBackend.cs new file mode 100644 index 00000000..ba6494f0 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerSimpleDesignerBackend.cs @@ -0,0 +1,26 @@ +#nullable enable + +using System.Collections.ObjectModel; +using System.Windows.Input; +using CDPIUI.Views.CreateConfigHelper; + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal interface IConfigMakerSimpleDesignerBackend +{ + bool IsSupported(string componentId); + bool TryLoad(string componentId, ObservableCollection items, + ObservableCollection groups); + string Parse(ObservableCollection items, + ObservableCollection groups, string command); + string Build(ObservableCollection items, + ObservableCollection groups, string additional); +} + +internal sealed record ConfigMakerDesignerCommands(ICommand Text, ICommand Bool, ICommand SelectedGuid); + +internal enum ConfigMakerDesignerNotice +{ + MissingAnnotation, + LoadFailed, +} diff --git a/CDPIUI/Helper/CreateConfigHelper/IConfigMakerTestTasks.cs b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerTestTasks.cs new file mode 100644 index 00000000..051120a2 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerTestTasks.cs @@ -0,0 +1,15 @@ +#nullable enable + +using System; +using System.Threading.Tasks; + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal interface IConfigMakerTestTasks +{ + event Action>? StateUpdated; + Task IsRunningAsync(string componentId); + Task StopAsync(string componentId); + Task RunAsync(string componentId, string arguments); + Task RestoreAsync(string componentId); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/IConfigMakerVariableActionsHost.cs b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerVariableActionsHost.cs new file mode 100644 index 00000000..0c2759f7 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/IConfigMakerVariableActionsHost.cs @@ -0,0 +1,21 @@ +#nullable enable + +using System.Threading.Tasks; +using CDPIUI.ViewModels; +using CDPIUI.ViewModels.ConfigMaker; + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal interface IConfigMakerVariableActionsHost +{ + Task EditVariableAsync(ConfigMakerPresetDocument document, ConfigMakerVariableDefinition? variable); + Task ConfirmRemoveReferencedVariableAsync(); + string CommandText { get; } + bool IsEditorReadOnly { get; } + void SetEditorText(string text); + void InsertAtCursor(string reference); + void AttachExistingPresetFiles(); + void ShowVariablesTool(); + void RebuildPresetStructure(); + void ScheduleDiagnostics(); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ICreateConfigGraphicDesignerBackend.cs b/CDPIUI/Helper/CreateConfigHelper/ICreateConfigGraphicDesignerBackend.cs new file mode 100644 index 00000000..e1703f10 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ICreateConfigGraphicDesignerBackend.cs @@ -0,0 +1,20 @@ +#nullable enable + +using System.Collections.ObjectModel; +using CDPIUI.Views.CreateConfigHelper; + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal interface ICreateConfigGraphicDesignerBackend +{ + void LoadGoodbye(ObservableCollection items, + ObservableCollection groups); + void LoadSpoof(ObservableCollection items, + ObservableCollection groups); + bool TryLoadNoDpi(string componentId, ObservableCollection items, + ObservableCollection groups); + string Parse(ObservableCollection items, + ObservableCollection groups, string text); + string Build(ObservableCollection items, + ObservableCollection groups, string additional); +} diff --git a/CDPIUI/Helper/CreateConfigHelper/ICreateConfigTestTasks.cs b/CDPIUI/Helper/CreateConfigHelper/ICreateConfigTestTasks.cs new file mode 100644 index 00000000..4b138e59 --- /dev/null +++ b/CDPIUI/Helper/CreateConfigHelper/ICreateConfigTestTasks.cs @@ -0,0 +1,13 @@ +#nullable enable + +using System; +using System.Threading.Tasks; + +namespace CDPIUI.Helper.CreateConfigHelper; + +internal interface ICreateConfigTestTasks +{ + event Action>? StateUpdated; + Task StopAsync(string componentId); + Task RunAsync(string componentId, string arguments); +} diff --git a/CDPIUI/Helper/UserExperience/DiagnosticHighlightingUpdater.cs b/CDPIUI/Helper/UserExperience/DiagnosticHighlightingUpdater.cs new file mode 100644 index 00000000..9c7ec6dc --- /dev/null +++ b/CDPIUI/Helper/UserExperience/DiagnosticHighlightingUpdater.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace CDPIUI.Helper.UserExperience; + +// Retain the last requested highlighting state, including a failed apply. +internal sealed class DiagnosticHighlightingUpdater +{ + private string _signature = string.Empty; + + public void Reset() => _signature = string.Empty; + + public void Update(string background, bool isLight, Func> diagnostics, + Func isError, Func isWarning, Func token, + Action apply) + { + string[] errorTokens = diagnostics().Where(isError).Select(token).ToArray(); + string[] warningTokens = diagnostics().Where(isWarning).Select(token).ToArray(); + string newSignature = $"{background}|{isLight}|{string.Join(',', errorTokens)}|{string.Join(',', warningTokens)}"; + if (string.Equals(_signature, newSignature, StringComparison.Ordinal)) + { + return; + } + + _signature = newSignature; + apply(isLight, errorTokens, warningTokens); + } +} diff --git a/CDPIUI/Helper/UserExperience/DispatcherTaskBridge.cs b/CDPIUI/Helper/UserExperience/DispatcherTaskBridge.cs new file mode 100644 index 00000000..e84b1afd --- /dev/null +++ b/CDPIUI/Helper/UserExperience/DispatcherTaskBridge.cs @@ -0,0 +1,46 @@ +using System; +using System.Threading.Tasks; + +namespace CDPIUI.Helper.UserExperience; + +/// Completes a task from an operation run directly or through a dispatcher. +internal static class DispatcherTaskBridge +{ + public static Task Run(Action operation, Func hasThreadAccess, Func tryEnqueue) + { + var completion = CreateCompletion(); + void Execute() + { + try { operation(); completion.TrySetResult(true); } + catch (Exception error) { completion.TrySetException(error); } + } + return Dispatch(Execute, completion, hasThreadAccess, tryEnqueue); + } + + public static Task Run(Func operation, Func hasThreadAccess, Func tryEnqueue) + { + var completion = CreateCompletion(); + async void Execute() + { + try + { + await operation(); + completion.TrySetResult(true); + } + catch (Exception error) { completion.TrySetException(error); } + } + return Dispatch(Execute, completion, hasThreadAccess, tryEnqueue); + } + + private static TaskCompletionSource CreateCompletion() => new(TaskCreationOptions.RunContinuationsAsynchronously); + + private static Task Dispatch(Action execute, TaskCompletionSource completion, + Func hasThreadAccess, Func tryEnqueue) + { + if (hasThreadAccess()) + execute(); + else if (!tryEnqueue(execute)) + completion.TrySetCanceled(); + return completion.Task; + } +} diff --git a/CDPIUI/Helper/UserExperience/NamedValueCollectionLoader.cs b/CDPIUI/Helper/UserExperience/NamedValueCollectionLoader.cs new file mode 100644 index 00000000..3d744949 --- /dev/null +++ b/CDPIUI/Helper/UserExperience/NamedValueCollectionLoader.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; + +namespace CDPIUI.Helper.UserExperience; + +/// Loads assignments and named rows with per-item recovery for the named rows. +internal static class NamedValueCollectionLoader +{ + public static void Load(ICollection destination, Func> readAssignments, + Func skipAssignment, Func createAssignment, + Func>> readNamedValues, + Func, T> createNamedValue, Action reportNamedValueError) + { + destination.Clear(); + if (readAssignments() != null) + { + foreach (string assignment in readAssignments()) + { + if (skipAssignment(assignment)) + continue; + int separator = assignment.IndexOf('='); + if (separator < 0) + continue; + destination.Add(createAssignment(assignment[..separator], assignment[(separator + 1)..])); + } + } + + if (readNamedValues() != null) + { + foreach (var pair in readNamedValues()) + { + try + { + destination.Add(createNamedValue(pair)); + } + catch (Exception error) + { + reportNamedValueError(error); + } + } + } + } +} diff --git a/CDPIUI/Helper/UserExperience/PostOrderTreePruner.cs b/CDPIUI/Helper/UserExperience/PostOrderTreePruner.cs new file mode 100644 index 00000000..592ff557 --- /dev/null +++ b/CDPIUI/Helper/UserExperience/PostOrderTreePruner.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; + +namespace CDPIUI.Helper.UserExperience; + +/// Prunes live lists from the last child upwards, with removal before logical mutation. +internal static class PostOrderTreePruner +{ + public static void Prune(IList nodes, Func> children, + Func retain, Action remove) + { + for (var index = nodes.Count - 1; index >= 0; index--) + { + var node = nodes[index]; + Prune(children(node), children, retain, remove); + if (retain(node)) + continue; + + remove(node); + nodes.RemoveAt(index); + } + } +} diff --git a/CDPIUI/Helper/UserExperience/SelectedItemChoiceAction.cs b/CDPIUI/Helper/UserExperience/SelectedItemChoiceAction.cs new file mode 100644 index 00000000..85d613fc --- /dev/null +++ b/CDPIUI/Helper/UserExperience/SelectedItemChoiceAction.cs @@ -0,0 +1,39 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace CDPIUI.Helper.UserExperience; + +/// Captures a selected item and its choices, then applies the chosen reference. +internal static class SelectedItemChoiceAction +{ + public static async Task ExecuteAsync(Func selected, + Func> choices, Func, Task> choose, + Action apply) where TItem : class where TChoice : class + { + TItem? item = selected(); + if (item == null) + { + return; + } + TChoice[] availableChoices = choices(item).ToArray(); + if (availableChoices.Length == 0) + { + return; + } + TChoice selectedChoice = availableChoices[0]; + if (availableChoices.Length > 1) + { + TChoice? choice = await choose(availableChoices); + if (choice == null) + { + return; + } + selectedChoice = choice; + } + apply(item, selectedChoice); + } +} diff --git a/CDPIUI/Helper/UserExperience/TextChangeRelay.cs b/CDPIUI/Helper/UserExperience/TextChangeRelay.cs new file mode 100644 index 00000000..3c6e1c5e --- /dev/null +++ b/CDPIUI/Helper/UserExperience/TextChangeRelay.cs @@ -0,0 +1,66 @@ +using System; + +namespace CDPIUI.Helper.UserExperience; + +/// Relays user input and programmatic replacements in their original callback order. +internal sealed class TextChangeRelay +{ + private readonly Func _isReadOnly; + private readonly Func _readText; + private readonly Action _writeText; + private readonly Func _replaceText; + private readonly Action _acceptText; + private readonly Action _rebuild; + private readonly Action _rebuildDiagnostics; + private readonly Action _scheduleDiagnostics; + private readonly Action _notify; + + public TextChangeRelay(Func isReadOnly, Func readText, Action writeText, + Func replaceText, Action acceptText, Action rebuild, + Action rebuildDiagnostics, Action scheduleDiagnostics, Action notify) + { + _isReadOnly = isReadOnly; + _readText = readText; + _writeText = writeText; + _replaceText = replaceText; + _acceptText = acceptText; + _rebuild = rebuild; + _rebuildDiagnostics = rebuildDiagnostics; + _scheduleDiagnostics = scheduleDiagnostics; + _notify = notify; + } + + public bool IsUpdating { get; private set; } + + public void OnTextChanged(string text) + { + if (IsUpdating) + return; + if (_isReadOnly()) + { + ReplaceText(_readText(), updateProperty: false); + return; + } + + IsUpdating = true; + _writeText(text ?? string.Empty); + IsUpdating = false; + _acceptText(_readText()); + _rebuild(); + _notify(_readText()); + _scheduleDiagnostics(); + } + + public void ReplaceText(string text, bool updateProperty = true) + { + IsUpdating = true; + string editorText = _replaceText(text ?? string.Empty); + if (updateProperty) + _writeText(editorText); + _acceptText(editorText); + IsUpdating = false; + _rebuild(); + _rebuildDiagnostics(); + _notify(editorText); + } +} diff --git a/CDPIUI/Helper/UserExperience/TwoPhaseTransitionSequence.cs b/CDPIUI/Helper/UserExperience/TwoPhaseTransitionSequence.cs new file mode 100644 index 00000000..640882ec --- /dev/null +++ b/CDPIUI/Helper/UserExperience/TwoPhaseTransitionSequence.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace CDPIUI.Helper.UserExperience; + +/// Applies two live groups of transitions with a pause between consecutive changes. +internal static class TwoPhaseTransitionSequence +{ + public static async Task RunAsync(IReadOnlyList<(TItem Item, TState State)> first, + IReadOnlyList<(TItem Item, TState State)> second, Func inspect, + Action apply, Func firstDelay, Func secondDelay, + Func delay, CancellationTokenSource cancellation, Action onFinally) + { + try + { + int transitionCount = first.Count + second.Count; + int transitionIndex = 0; + foreach ((TItem item, TState state) in first) + { + bool before = inspect(item); + apply(item, state); + transitionIndex++; + if (transitionIndex < transitionCount) + { + await delay(firstDelay(before), cancellation.Token); + } + } + foreach ((TItem item, TState state) in second) + { + bool before = inspect(item); + apply(item, state); + transitionIndex++; + if (transitionIndex < transitionCount) + { + await delay(secondDelay(before), cancellation.Token); + } + } + } + catch (OperationCanceledException) + { + // Replacement or suspension canceled the pending sequence. + } + finally + { + onFinally(); + } + } +} diff --git a/CDPIUI/Helper/WindowHelper/AppWindowCoordinator.cs b/CDPIUI/Helper/WindowHelper/AppWindowCoordinator.cs new file mode 100644 index 00000000..a73f83b8 --- /dev/null +++ b/CDPIUI/Helper/WindowHelper/AppWindowCoordinator.cs @@ -0,0 +1,97 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace CDPIUI.Helper.WindowHelper; + +// Owns lookup/reuse rules over the same list exposed by App. Use on the UI thread. +internal sealed class AppWindowCoordinator where TWindow : class +{ + private readonly List _windows; + private readonly Func _readiness; + private readonly IAppWindowOperations _operations; + + public AppWindowCoordinator(List windows, Func readiness, + IAppWindowOperations operations) + { + _windows = windows; + _readiness = readiness; + _operations = operations; + } + + public TWindow? GetCurrent(Type windowType) => + _windows.Where(windowType.IsInstanceOfType).FirstOrDefault(_operations.HasDispatcher); + + public void CloseAll(Type windowType) + { + foreach (TWindow window in _windows.Where(windowType.IsInstanceOfType).ToList()) + { + _operations.Close(window); + _windows.Remove(window); + } + } + + public void CloseTemplate(Type windowType, string id) + { + TWindow? window = _windows.Where(windowType.IsInstanceOfType).FirstOrDefault(window => + _operations.TryGetTemplateId(window, out string? templateId) && + string.Equals(templateId, id, StringComparison.OrdinalIgnoreCase)); + if (window != null) + { + _operations.Close(window); + } + } + + public async Task CreateUnsafeAsync(Type windowType, bool activate, string id) + { + await _readiness(); + List findWindows = _windows.Where(window => windowType.IsInstanceOfType(window)).ToList(); + foreach (TWindow window in findWindows) + { + if (_operations.TryGetTemplateId(window, out string? templateId) && + !string.IsNullOrEmpty(templateId) && + string.Equals(templateId, id, StringComparison.OrdinalIgnoreCase)) + { + if (activate) + _operations.Activate(window); + return window; + } + } + + TWindow newWindow = _operations.Create(windowType); + _operations.SetTemplateId(newWindow, id); + _operations.SetPosition(newWindow); + _operations.Register(newWindow, isUnsafe: true); + if (activate) + _operations.Activate(newWindow); + return newWindow; + } + + public async Task CreateSafeAsync(Type windowType, bool activate) + { + await _readiness(); + List findWindows = _windows.Where(window => windowType.IsInstanceOfType(window)).ToList(); + TWindow? activeFindWindow = findWindows.FirstOrDefault(_operations.HasDispatcher); + if (activeFindWindow != null && findWindows.Count == 1) + { + if (activate) + _operations.Activate(activeFindWindow); + return activeFindWindow; + } + + foreach (TWindow window in findWindows) + { + _operations.Close(window); + _windows.Remove(window); + } + TWindow newWindow = _operations.Create(windowType); + _operations.SetPosition(newWindow); + _operations.Register(newWindow, isUnsafe: false); + if (activate) + _operations.Activate(newWindow); + return newWindow; + } +} diff --git a/CDPIUI/Helper/WindowHelper/AppWindowOperations.cs b/CDPIUI/Helper/WindowHelper/AppWindowOperations.cs new file mode 100644 index 00000000..1e68aaa4 --- /dev/null +++ b/CDPIUI/Helper/WindowHelper/AppWindowOperations.cs @@ -0,0 +1,24 @@ +using System; +using CDPIUI.Default; +using Microsoft.UI.Xaml; + +namespace CDPIUI.Helper.WindowHelper; + +// WinUI effects remain at the application boundary; the coordinator only orders them. +internal sealed class AppWindowOperations(Action register) : IAppWindowOperations +{ + public bool HasDispatcher(Window window) => window.DispatcherQueue != null; + + public bool TryGetTemplateId(Window window, out string id) + { + id = (window as TemplateWindow)?.Id; + return window is TemplateWindow; + } + + public Window Create(Type windowType) => (Window)Activator.CreateInstance(windowType); + public void SetTemplateId(Window window, string id) => ((TemplateWindow)window).Id = id; + public void SetPosition(Window window) => WindowsPositionHelper.SetCustomWindowSizeAndPositionFromSettings(window); + public void Register(Window window, bool isUnsafe) => register(window, isUnsafe); + public void Activate(Window window) => App.ActivateWindow(window); + public void Close(Window window) => window.Close(); +} diff --git a/CDPIUI/Helper/WindowHelper/IAppWindowOperations.cs b/CDPIUI/Helper/WindowHelper/IAppWindowOperations.cs new file mode 100644 index 00000000..3b6e00b7 --- /dev/null +++ b/CDPIUI/Helper/WindowHelper/IAppWindowOperations.cs @@ -0,0 +1,17 @@ +#nullable enable + +using System; + +namespace CDPIUI.Helper.WindowHelper; + +internal interface IAppWindowOperations where TWindow : class +{ + bool HasDispatcher(TWindow window); + bool TryGetTemplateId(TWindow window, out string? id); + TWindow Create(Type windowType); + void SetTemplateId(TWindow window, string id); + void SetPosition(TWindow window); + void Register(TWindow window, bool isUnsafe); + void Activate(TWindow window); + void Close(TWindow window); +} diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2AssignmentActions.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2AssignmentActions.cs new file mode 100644 index 00000000..2e8d3a6b --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2AssignmentActions.cs @@ -0,0 +1,80 @@ +#nullable enable + +using System; +using System.Threading.Tasks; +using CDPIUI.Helper.UserExperience; + +namespace CDPIUI.ViewModels.BlockCheck2; + +/// Assignment commands and their completion notices; the model owns preset editing. +internal sealed class BlockCheck2AssignmentActions(IBlockCheck2AssignmentActionsHost host) +{ + public void AddSelectedStrategyForSite() + { + BlockCheck2StrategyEvidenceItem? item = host.SelectedStrategy; + if (item == null) + { + return; + } + ShowResult(host.AddForSite(item)); + } + + public Task AddSelectedStrategyForListAsync() => SelectedItemChoiceAction.ExecuteAsync( + () => host.SelectedStrategy, host.GetSiteListPaths, paths => host.ChooseSiteListAsync(paths), + (item, path) => ShowResult(host.AddForSiteList(item, path))); + + public void ShowResult(bool added) + { + if (added) + { + host.ShowMessage(BlockCheck2NoticeSeverity.Success, + host.Text("BlockCheck2AssignmentAddedTitle"), host.Text("BlockCheck2AssignmentAddedMessage")); + } + else + { + host.ShowMessage(BlockCheck2NoticeSeverity.Warning, + host.Text("BlockCheck2AssignmentNotAddedTitle"), host.Text("BlockCheck2AssignmentDuplicateMessage")); + } + host.UpdateAssignmentView(); + host.UpdateActionButtons(); + } + + public void MoveSelectedAssignment(int offset) + { + BlockCheck2ManualAssignmentItem? selected = host.SelectedAssignment; + if (selected != null && host.MoveAssignment(selected, offset)) + { + host.UpdateAssignmentView(); + host.SelectedAssignment = selected; + } + } + + public void RemoveSelectedAssignment() + { + BlockCheck2ManualAssignmentItem? selected = host.SelectedAssignment; + if (selected == null) + { + return; + } + host.RemoveAssignment(selected); + host.UpdateAssignmentView(); + } + + public void ClearAssignments() + { + host.ClearAssignments(); + host.UpdateAssignmentView(); + } + + public void ApplyManualIssueQuickFix(Func apply) + { + if (!apply()) + { + return; + } + host.ShowMessage(BlockCheck2NoticeSeverity.Success, + host.Text("BlockCheck2ManualIssueQuickFixCompletedTitle"), + host.Text("BlockCheck2ManualScopeOverlapAcceptedMessage")); + host.UpdateAssignmentView(); + } +} diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ManualComponentTestTasks.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ManualComponentTestTasks.cs new file mode 100644 index 00000000..063eb62c --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ManualComponentTestTasks.cs @@ -0,0 +1,21 @@ +using System; +using System.Threading.Tasks; +using CDPIUI.Core.ComponentServices; +using CDPIUI.Helper.CreateConfigHelper; + +namespace CDPIUI.ViewModels.BlockCheck2; + +// Binds the receiver before the caller evaluates the current component ID. +internal sealed class BlockCheck2ManualComponentTestTasks(ComponentTasksManager manager) : IConfigMakerTestTasks +{ + public event Action>? StateUpdated + { + add => manager.TaskStateUpdated += value; + remove => manager.TaskStateUpdated -= value; + } + + public Task IsRunningAsync(string componentId) => manager.IsTaskRunning(componentId); + public Task StopAsync(string componentId) => manager.StopTask(componentId); + public Task RunAsync(string componentId, string arguments) => manager.CreateAndRunNewTask(componentId, arguments); + public Task RestoreAsync(string componentId) => manager.CreateAndRunNewTask(componentId); +} diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ManualTestSession.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ManualTestSession.cs new file mode 100644 index 00000000..01e1be7a --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ManualTestSession.cs @@ -0,0 +1,192 @@ +using System; +using System.Threading.Tasks; +using CDPIUI.Helper.CreateConfigHelper; + +namespace CDPIUI.ViewModels.BlockCheck2; + +/// Owns the result page's manual component test and its original restore policy. +internal sealed class BlockCheck2ManualTestSession +{ + private readonly IBlockCheck2ManualTestHost _host; + private readonly Func _tasks; + private readonly Func _componentId; + private readonly Action> _stateHandler; + private bool _isStartingTest; + private bool _isRunning; + private bool _restoreComponentAfterTest; + + public BlockCheck2ManualTestSession(IBlockCheck2ManualTestHost host, Func tasks, + Func componentId, Action> stateHandler) + { + _host = host; + _tasks = tasks; + _componentId = componentId; + _stateHandler = stateHandler; + } + + public bool IsRunning => _isRunning; + + public async Task ToggleFromButtonAsync() + { + if (_host.IsManualTestChecked == true) + { + await StartAsync(); + } + else + { + await StopAsync(true); + } + } + + public async Task ToggleAsync() + { + if (_isRunning) + { + await StopAsync(showCompletionMessage: true); + } + else + { + await StartAsync(); + } + } + + public async Task StopAsync(bool showCompletionMessage = false) + { + _host.UpdateSelectedStrategy(); + if (!_isRunning) + { + return; + } + + bool restore = _restoreComponentAfterTest; + _isRunning = false; + _isStartingTest = false; + _tasks().StateUpdated -= _stateHandler; + + if (!string.IsNullOrWhiteSpace(_componentId())) + { + await _tasks().StopAsync(_componentId()); + if (restore) + { + await _tasks().RestoreAsync(_componentId()); + } + } + + _restoreComponentAfterTest = false; + if (showCompletionMessage) + { + _host.ShowMessage( + BlockCheck2NoticeSeverity.Informational, + _host.Text("ManualTesting"), + _host.Text("ConfigMakerTestStoppedMessage")); + } + + _host.UpdateSelectedStrategy(); + _host.UpdateAssignmentView(); + } + + public async Task StopOnLeaveAsync() + { + if (!_isRunning) + { + return; + } + + bool restore = _restoreComponentAfterTest; + _isRunning = false; + _isStartingTest = false; + _restoreComponentAfterTest = false; + _tasks().StateUpdated -= _stateHandler; + + string componentId = _componentId(); + if (string.IsNullOrWhiteSpace(componentId)) + { + return; + } + try + { + await _tasks().StopAsync(componentId); + if (restore) + { + await _tasks().RestoreAsync(componentId); + } + } + catch (Exception exception) + { + _host.Warn(exception); + } + } + + public async Task StartAsync() + { + BlockCheck2StrategyEvidenceItem? item = _host.SelectedStrategy; + if (item == null || _isRunning || _host.IsStrategyTestRunning) + { + return; + } + + _host.UpdateSelectedStrategy(); + var result = _host.GetFullStrategyArguments(item); + if (!result.Success || string.IsNullOrEmpty(result.Result)) + { + _host.ShowMessage( + BlockCheck2NoticeSeverity.Warning, + _host.Text("ManualTesting"), + result.ErrorHappens ? result.Error!.ErrorCode : _host.Text("ConfigMakerEmptyArgumentsMessage")); + return; + } + + await StopAsync(); + bool componentWasRunning = await _tasks().IsRunningAsync(_componentId()); + if (componentWasRunning && !await _host.ConfirmReplacementAsync()) + { + return; + } + + _restoreComponentAfterTest = componentWasRunning; + await _tasks().StopAsync(_componentId()); + + _isRunning = true; + _isStartingTest = true; + _tasks().StateUpdated += _stateHandler; + _host.UpdateSelectedStrategy(); + + _host.ShowMessage( + BlockCheck2NoticeSeverity.Informational, + _host.Text("ManualTesting"), + _host.Text("ConfigMakerTestStartedMessage")); + + try + { + await _tasks().RunAsync(_componentId(), result.Result); + _isStartingTest = false; + } + catch (Exception exception) + { + _isStartingTest = false; + _host.ShowMessage( + BlockCheck2NoticeSeverity.Error, + _host.Text("ManualTesting"), + string.Format(_host.Text("ConfigMakerTestStartFailedMessage"), exception.Message)); + await StopAsync(); + } + } + + public void HandleStateUpdated(Tuple state) + { + if (!_isRunning || _isStartingTest || + !string.Equals(state.Item1, _componentId(), StringComparison.OrdinalIgnoreCase) || state.Item2) + { + return; + } + + _host.Enqueue(async () => + { + _host.ShowMessage( + BlockCheck2NoticeSeverity.Warning, + _host.Text("ManualTesting"), + _host.Text("ConfigMakerTestExitedMessage")); + await StopAsync(); + }); + } +} diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReportExport.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReportExport.cs new file mode 100644 index 00000000..5f9c153c --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReportExport.cs @@ -0,0 +1,78 @@ +using System; +using System.Threading.Tasks; +using CDPIUI.AddOns.BlockCheck2.Reporting; + +namespace CDPIUI.ViewModels.BlockCheck2; + +/// Coordinates report picking, saving and completion notices for the result page. +internal sealed class BlockCheck2ReportExport +{ + private readonly Func _report; + private readonly Func _pickSave; + private readonly Func _saveJson; + private readonly Func _saveText; + private readonly Func _text; + private readonly Action _show; + private readonly Action _error; + + public BlockCheck2ReportExport(Func report, Func pickSave, + Func saveJson, Func saveText, + Func text, Action show, Action error) + { + _report = report; + _pickSave = pickSave; + _saveJson = saveJson; + _saveText = saveText; + _text = text; + _show = show; + _error = error; + } + + public async Task SaveJsonAsync() + { + if (_report() == null) + { + return; + } + string? fileName = _pickSave( + _text("BlockCheck2SaveReportDialogTitle"), + "blockcheck2-report.json", + _text("BlockCheck2JsonFileFilter")); + if (fileName != null) + { + await SaveAsync(() => _saveJson(fileName, _report()!)); + } + } + + public async Task SaveTextAsync() + { + if (_report() == null) + { + return; + } + string? fileName = _pickSave( + _text("BlockCheck2SaveReportDialogTitle"), + "blockcheck2-report.txt", + _text("BlockCheck2TextFileFilter")); + if (fileName != null) + { + await SaveAsync(() => _saveText(fileName, _report()!)); + } + } + + public async Task SaveAsync(Func saveAction) + { + try + { + await saveAction(); + _show( + BlockCheck2NoticeSeverity.Success, + _text("BlockCheck2ActionCompletedTitle"), + _text("BlockCheck2FileSavedMessage")); + } + catch (Exception exception) + { + _error(exception.Message); + } + } +} diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReportSummaryPresenter.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReportSummaryPresenter.cs new file mode 100644 index 00000000..dae76bc2 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReportSummaryPresenter.cs @@ -0,0 +1,60 @@ +#nullable enable + +using System; + +namespace CDPIUI.ViewModels.BlockCheck2; + +// Keeps report notice selection and localization in their original read order. +internal sealed class BlockCheck2ReportSummaryPresenter +{ + private readonly Func _hasReport, _noBypass, _success, _bestEffort, _httpOnly; + private readonly Func _text; + private readonly Action _show; + + public BlockCheck2ReportSummaryPresenter(Func hasReport, Func noBypass, + Func success, Func bestEffort, Func httpOnly, Func text, + Action show) + { + _hasReport = hasReport; + _noBypass = noBypass; + _success = success; + _bestEffort = bestEffort; + _httpOnly = httpOnly; + _text = text; + _show = show; + } + + public void Show() + { + if (!_hasReport()) + { + _show(BlockCheck2NoticeSeverity.Error, _text("BlockCheck2ResultEmptyTitle"), _text("BlockCheck2ResultEmptyMessage")); + return; + } + + var severity = _noBypass() + ? BlockCheck2NoticeSeverity.Informational + : _success() + ? BlockCheck2NoticeSeverity.Success + : BlockCheck2NoticeSeverity.Warning; + var title = _noBypass() + ? _text("BlockCheck2NoBypassRequiredTitle") + : _success() + ? _text("BlockCheck2ResultSuccessTitle") + : _bestEffort() + ? _text("BlockCheck2ResultBestEffortTitle") + : _text("BlockCheck2ResultPartialTitle"); + var message = _noBypass() + ? _text(_httpOnly() + ? "BlockCheck2HttpOnlyNoBypassRequiredMessage" + : "BlockCheck2NoBypassRequiredMessage") + : _success() + ? _text("BlockCheck2ResultSuccessMessage") + : _bestEffort() + ? _text("BlockCheck2ResultBestEffortMessage") + : _text("BlockCheck2ResultPartialMessage"); + + _show(severity, title, message); + } + +} diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.Assignments.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.Assignments.cs index 856b8055..ce64c353 100644 --- a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.Assignments.cs +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.Assignments.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Collections.Generic; using System.Threading.Tasks; using CDPIUI.Helper.CreateConfigHelper; @@ -51,101 +51,40 @@ public bool IsRemoveAssignmentEnabled private set => SetProperty(ref _isRemoveAssignmentEnabled, value); } - public void AddSelectedStrategyForSite() - { - BlockCheck2StrategyEvidenceItem? item = _view.SelectedStrategy; - if (item == null) - { - return; - } - ShowAssignmentResult(Result.AddForSite(item)); - } + public void AddSelectedStrategyForSite() => _assignmentActions.AddSelectedStrategyForSite(); - public async Task AddSelectedStrategyForListAsync() - { - BlockCheck2StrategyEvidenceItem? item = _view.SelectedStrategy; - if (item == null) - { - return; - } - string[] paths = Result.GetSiteListPaths(item).ToArray(); - if (paths.Length == 0) - { - return; - } + public Task AddSelectedStrategyForListAsync() => _assignmentActions.AddSelectedStrategyForListAsync(); - string selectedPath = paths[0]; - if (paths.Length > 1) - { - string? path = await _view.ChooseSiteListAsync(paths); - if (path == null) - { - return; - } - selectedPath = path; - } - ShowAssignmentResult(Result.AddForSiteList(item, selectedPath)); - } + private void ShowAssignmentResult(bool added) => _assignmentActions.ShowResult(added); - private void ShowAssignmentResult(bool added) - { - if (added) - { - ShowActionMessage( - BlockCheck2NoticeSeverity.Success, - Text("BlockCheck2AssignmentAddedTitle"), - Text("BlockCheck2AssignmentAddedMessage")); - } - else - { - ShowActionMessage( - BlockCheck2NoticeSeverity.Warning, - Text("BlockCheck2AssignmentNotAddedTitle"), - Text("BlockCheck2AssignmentDuplicateMessage")); - } - UpdateAssignmentView(); - UpdateActionButtons(); - } + public void MoveSelectedAssignment(int offset) => _assignmentActions.MoveSelectedAssignment(offset); - public void MoveSelectedAssignment(int offset) - { - BlockCheck2ManualAssignmentItem? selected = _view.SelectedAssignment; - if (selected != null && Result.MoveAssignment(selected, offset)) - { - UpdateAssignmentView(); - _view.SelectedAssignment = selected; - } - } + public void RemoveSelectedAssignment() => _assignmentActions.RemoveSelectedAssignment(); - public void RemoveSelectedAssignment() - { - BlockCheck2ManualAssignmentItem? selected = _view.SelectedAssignment; - if (selected == null) - { - return; - } - Result.RemoveAssignment(selected); - UpdateAssignmentView(); - } + public void ClearAssignments() => _assignmentActions.ClearAssignments(); - public void ClearAssignments() - { - Result.ClearManualAssignments(); - UpdateAssignmentView(); - } + public void ApplyManualIssueQuickFix(BlockCheck2ManualIssueItem issue) => + _assignmentActions.ApplyManualIssueQuickFix(() => Result.ApplyManualIssueQuickFix(issue)); - public void ApplyManualIssueQuickFix(BlockCheck2ManualIssueItem issue) + private sealed class AssignmentActionsHost(BlockCheck2ResultPageViewModel page) : IBlockCheck2AssignmentActionsHost { - if (!Result.ApplyManualIssueQuickFix(issue)) + public BlockCheck2StrategyEvidenceItem? SelectedStrategy => page._view.SelectedStrategy; + public IReadOnlyList GetSiteListPaths(BlockCheck2StrategyEvidenceItem item) => page.Result.GetSiteListPaths(item); + public Task ChooseSiteListAsync(IReadOnlyList paths) => page._view.ChooseSiteListAsync(paths); + public bool AddForSite(BlockCheck2StrategyEvidenceItem item) => page.Result.AddForSite(item); + public bool AddForSiteList(BlockCheck2StrategyEvidenceItem item, string path) => page.Result.AddForSiteList(item, path); + public BlockCheck2ManualAssignmentItem? SelectedAssignment { - return; + get => page._view.SelectedAssignment; + set => page._view.SelectedAssignment = value; } - - ShowActionMessage( - BlockCheck2NoticeSeverity.Success, - Text("BlockCheck2ManualIssueQuickFixCompletedTitle"), - Text("BlockCheck2ManualScopeOverlapAcceptedMessage")); - UpdateAssignmentView(); + public bool MoveAssignment(BlockCheck2ManualAssignmentItem item, int offset) => page.Result.MoveAssignment(item, offset); + public void RemoveAssignment(BlockCheck2ManualAssignmentItem item) => page.Result.RemoveAssignment(item); + public void ClearAssignments() => page.Result.ClearManualAssignments(); + public void UpdateAssignmentView() => page.UpdateAssignmentView(); + public void UpdateActionButtons() => page.UpdateActionButtons(); + public string Text(string key) => page.Text(key); + public void ShowMessage(BlockCheck2NoticeSeverity severity, string title, string message) => page.ShowActionMessage(severity, title, message); } private void UpdateAssignmentView() diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.Export.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.Export.cs index b1f68755..dc2487dc 100644 --- a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.Export.cs +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.Export.cs @@ -5,53 +5,11 @@ namespace CDPIUI.ViewModels.BlockCheck2; public sealed partial class BlockCheck2ResultPageViewModel { - public async Task SaveJsonReportAsync() - { - if (Result.Report == null) - { - return; - } - string? fileName = _view.PickSaveFile( - Text("BlockCheck2SaveReportDialogTitle"), - "blockcheck2-report.json", - Text("BlockCheck2JsonFileFilter")); - if (fileName != null) - { - await SaveAsync(() => _reportSerializer.SaveJsonAsync(fileName, Result.Report)); - } - } + public Task SaveJsonReportAsync() => _reportExport.SaveJsonAsync(); - public async Task SaveTextReportAsync() - { - if (Result.Report == null) - { - return; - } - string? fileName = _view.PickSaveFile( - Text("BlockCheck2SaveReportDialogTitle"), - "blockcheck2-report.txt", - Text("BlockCheck2TextFileFilter")); - if (fileName != null) - { - await SaveAsync(() => _reportSerializer.SaveTextAsync(fileName, Result.Report)); - } - } + public Task SaveTextReportAsync() => _reportExport.SaveTextAsync(); - private async Task SaveAsync(Func saveAction) - { - try - { - await saveAction(); - ShowActionMessage( - BlockCheck2NoticeSeverity.Success, - Text("BlockCheck2ActionCompletedTitle"), - Text("BlockCheck2FileSavedMessage")); - } - catch (Exception exception) - { - ShowActionError(exception.Message); - } - } + private Task SaveAsync(Func saveAction) => _reportExport.SaveAsync(saveAction); public void CopySelectedStrategyArguments() { diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.ManualTesting.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.ManualTesting.cs index 7c6b2475..47174a32 100644 --- a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.ManualTesting.cs +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.ManualTesting.cs @@ -3,184 +3,48 @@ using CDPIUI.Core.Basic; using CDPIUI.Core.ComponentServices; using CDPIUI.Core.Store.Data; +using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.Shared.Models; namespace CDPIUI.ViewModels.BlockCheck2; public sealed partial class BlockCheck2ResultPageViewModel { - private bool _isStartingTest; - private bool _isManualTestRunning; - private bool _restoreComponentAfterTest; - - public bool IsManualTestRunning => _isManualTestRunning; + public bool IsManualTestRunning => _manualTest.IsRunning; /// Runs after a click on the toggle button, which has already changed its state. - public async Task ToggleManualTestFromButtonAsync() - { - if (IsManualTestChecked == true) - { - await StartTestAsync(); - } - else - { - await StopTestAsync(true); - } - } + public Task ToggleManualTestFromButtonAsync() => _manualTest.ToggleFromButtonAsync(); - public async Task ToggleManualTestAsync() - { - if (_isManualTestRunning) - { - await StopTestAsync(showCompletionMessage: true); - } - else - { - await StartTestAsync(); - } - } + public Task ToggleManualTestAsync() => _manualTest.ToggleAsync(); - public async Task StopTestAsync(bool showCompletionMessage = false) - { - UpdateSelectedStrategy(); - if (!_isManualTestRunning) - { - return; - } + public Task StopTestAsync(bool showCompletionMessage = false) => _manualTest.StopAsync(showCompletionMessage); - bool restore = _restoreComponentAfterTest; - _isManualTestRunning = false; - _isStartingTest = false; - ComponentTasksManager.Instance.TaskStateUpdated -= ComponentTasksManager_TaskStateUpdated; + private Task StopTestOnLeaveAsync() => _manualTest.StopOnLeaveAsync(); - if (!string.IsNullOrWhiteSpace(HardcodedItemIds.ComponentIds[Components.Zapret2])) - { - await ComponentTasksManager.Instance.StopTask(HardcodedItemIds.ComponentIds[Components.Zapret2]); - if (restore) - { - await ComponentTasksManager.Instance.CreateAndRunNewTask(HardcodedItemIds.ComponentIds[Components.Zapret2]); - } - } + public Task StartTestAsync() => _manualTest.StartAsync(); - _restoreComponentAfterTest = false; - if (showCompletionMessage) - { - ShowActionMessage( - BlockCheck2NoticeSeverity.Informational, - Text("ManualTesting"), - Text("ConfigMakerTestStoppedMessage")); - } + private void ComponentTasksManager_TaskStateUpdated(Tuple state) => _manualTest.HandleStateUpdated(state); - UpdateSelectedStrategy(); - UpdateAssignmentView(); - } + private static string GetManualTestComponentId() => HardcodedItemIds.ComponentIds[Components.Zapret2]; - private async Task StopTestOnLeaveAsync() - { - if (!_isManualTestRunning) - { - return; - } - - bool restore = _restoreComponentAfterTest; - _isManualTestRunning = false; - _isStartingTest = false; - _restoreComponentAfterTest = false; - ComponentTasksManager.Instance.TaskStateUpdated -= ComponentTasksManager_TaskStateUpdated; - - string componentId = HardcodedItemIds.ComponentIds[Components.Zapret2]; - if (string.IsNullOrWhiteSpace(componentId)) - { - return; - } - try - { - await ComponentTasksManager.Instance.StopTask(componentId); - if (restore) - { - await ComponentTasksManager.Instance.CreateAndRunNewTask(componentId); - } - } - catch (Exception exception) - { - Logger.Instance.CreateWarningLog(LogSource, $"Cannot stop the manual test: {exception}"); - } - } + private static IConfigMakerTestTasks GetManualTestTasks() => + new BlockCheck2ManualComponentTestTasks(ComponentTasksManager.Instance); - public async Task StartTestAsync() + private sealed class ManualTestHost(BlockCheck2ResultPageViewModel page) : IBlockCheck2ManualTestHost { - BlockCheck2StrategyEvidenceItem? item = _view.SelectedStrategy; - if (item == null || _isManualTestRunning || _strategyTestRunning) - { - return; - } - - UpdateSelectedStrategy(); - - var result = Result.GetFullStrategyArguments(item); - - if (!result.Success || string.IsNullOrEmpty(result.Result)) - { - ShowActionMessage( - BlockCheck2NoticeSeverity.Warning, - Text("ManualTesting"), - result.ErrorHappens ? result.Error.ErrorCode : Text("ConfigMakerEmptyArgumentsMessage")); - return; - } - - await StopTestAsync(); - bool componentWasRunning = await ComponentTasksManager.Instance.IsTaskRunning(HardcodedItemIds.ComponentIds[Components.Zapret2]); - if (componentWasRunning && !await _view.ConfirmReplaceRunningComponentAsync()) - { - return; - } - - _restoreComponentAfterTest = componentWasRunning; - await ComponentTasksManager.Instance.StopTask(HardcodedItemIds.ComponentIds[Components.Zapret2]); - - _isManualTestRunning = true; - _isStartingTest = true; - ComponentTasksManager.Instance.TaskStateUpdated += ComponentTasksManager_TaskStateUpdated; - UpdateSelectedStrategy(); - - ShowActionMessage( - BlockCheck2NoticeSeverity.Informational, - Text("ManualTesting"), - Text("ConfigMakerTestStartedMessage")); - - try - { - await ComponentTasksManager.Instance.CreateAndRunNewTask(HardcodedItemIds.ComponentIds[Components.Zapret2], result.Result); - _isStartingTest = false; - } - catch (Exception exception) - { - _isStartingTest = false; - ShowActionMessage( - BlockCheck2NoticeSeverity.Error, - Text("ManualTesting"), - string.Format( - Text("ConfigMakerTestStartFailedMessage"), - exception.Message)); - await StopTestAsync(); - } - } - - private void ComponentTasksManager_TaskStateUpdated(Tuple state) - { - if (!_isManualTestRunning || _isStartingTest || - !string.Equals(state.Item1, HardcodedItemIds.ComponentIds[Components.Zapret2], StringComparison.OrdinalIgnoreCase) || - state.Item2) - { - return; - } - - _dispatcherQueue.TryEnqueue(async () => - { - ShowActionMessage( - BlockCheck2NoticeSeverity.Warning, - Text("ManualTesting"), - Text("ConfigMakerTestExitedMessage")); - await StopTestAsync(); - }); + public BlockCheck2StrategyEvidenceItem? SelectedStrategy => page._view.SelectedStrategy; + public bool IsStrategyTestRunning => page._strategyTestRunning; + public bool? IsManualTestChecked => page.IsManualTestChecked; + public OperationResultModel GetFullStrategyArguments(BlockCheck2StrategyEvidenceItem item) => + page.Result.GetFullStrategyArguments(item); + public Task ConfirmReplacementAsync() => page._view.ConfirmReplaceRunningComponentAsync(); + public void UpdateSelectedStrategy() => page.UpdateSelectedStrategy(); + public void UpdateAssignmentView() => page.UpdateAssignmentView(); + public string Text(string key) => page.Text(key); + public void ShowMessage(BlockCheck2NoticeSeverity severity, string title, string message) => + page.ShowActionMessage(severity, title, message); + public void Warn(Exception exception) => + Logger.Instance.CreateWarningLog(LogSource, $"Cannot stop the manual test: {exception}"); + public void Enqueue(Func callback) => page._dispatcherQueue.TryEnqueue(async () => await callback()); } } diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.cs index ac147e7f..2b30f6b2 100644 --- a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.cs +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using System.Threading.Tasks; using CDPIUI.AddOns.BlockCheck2.Models; using CDPIUI.AddOns.BlockCheck2.Presentation; @@ -23,35 +22,45 @@ public sealed partial class BlockCheck2ResultPageViewModel : ObservableObject private readonly IBlockCheck2ResultPageView _view; private readonly DispatcherQueue _dispatcherQueue; private readonly BlockCheckReportSerializer _reportSerializer = new(); + private readonly BlockCheck2ResultSelection _selection; + private readonly BlockCheck2ReportSummaryPresenter _reportSummary; + private readonly BlockCheck2SelectedStrategyTest _selectedStrategyTest; + private readonly BlockCheck2ReportExport _reportExport; + private readonly BlockCheck2ManualTestSession _manualTest; + private readonly BlockCheck2AssignmentActions _assignmentActions; private bool _languageHandlerConnected; private bool _strategyTestRunning; private string _strategyCountText = string.Empty; private bool _areStrategiesVisible = true; - private bool _isDetailsHitTestVisible = true; private bool _isNoIssuesVisible = true; private bool _areIssuesVisible = true; private bool _isStrategyTestProgressVisible; - private bool _isTestStrategyEnabled = true; - private bool _isManualTestEnabled = true; - private bool? _isManualTestChecked = false; - private string _manualTestLabel = string.Empty; - private string _manualTestGlyph = "\uE768"; - private bool _isAddForSiteEnabled = true; - private bool _isAddForListEnabled = true; private bool _isReviewPresetEnabled = true; - private string _selectedStrategyName = string.Empty; - private string _selectedStrategyId = string.Empty; - private string _selectedStrategyArguments = string.Empty; - private string _selectedSite = string.Empty; - private string _selectedConnection = string.Empty; - private string _selectedEvidence = string.Empty; - private string _selectedBaseline = string.Empty; public BlockCheck2ResultPageViewModel(IBlockCheck2ResultPageView view, DispatcherQueue dispatcherQueue) { _view = view; _dispatcherQueue = dispatcherQueue; + _assignmentActions = new BlockCheck2AssignmentActions(new AssignmentActionsHost(this)); + _manualTest = new BlockCheck2ManualTestSession(new ManualTestHost(this), GetManualTestTasks, + GetManualTestComponentId, ComponentTasksManager_TaskStateUpdated); + _selection = new BlockCheck2ResultSelection(() => _view.SelectedStrategy, + () => Result.HasSession, () => _strategyTestRunning, () => _manualTest.IsRunning, + item => Result.CanAddForSiteList(item), Text, () => _view.NotifyMenuStateChanged()); + _selection.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); + _reportSummary = new BlockCheck2ReportSummaryPresenter(() => Result.HasReport, + () => Result.NoBypassRequired, () => Result.Success, () => Result.IsBestEffort, + () => Result.IsHttpOnly, Text, ShowActionMessage); + _selectedStrategyTest = new BlockCheck2SelectedStrategyTest(() => _view.SelectedStrategy, + () => _strategyTestRunning, value => _strategyTestRunning = value, + value => IsStrategyTestProgressVisible = value, UpdateSelectedStrategy, + item => Result.TestStrategyAsync(item), UpdateAssignmentView, Text, + BlockCheck2IssueText.GetMessage, ShowActionError, ShowActionMessage); + _reportExport = new BlockCheck2ReportExport(() => Result.Report, + (title, name, filter) => _view.PickSaveFile(title, name, filter), + (path, report) => _reportSerializer.SaveJsonAsync(path, report), + (path, report) => _reportSerializer.SaveTextAsync(path, report), Text, ShowActionMessage, ShowActionError); } public BlockCheck2ResultViewModel Result { get; private set; } = new(); @@ -72,8 +81,8 @@ public bool AreStrategiesVisible public bool IsDetailsHitTestVisible { - get => _isDetailsHitTestVisible; - private set => SetProperty(ref _isDetailsHitTestVisible, value); + get => _selection.IsDetailsHitTestVisible; + private set => _selection.IsDetailsHitTestVisible = value; } public bool IsNoIssuesVisible @@ -96,45 +105,45 @@ public bool IsStrategyTestProgressVisible public bool IsTestStrategyEnabled { - get => _isTestStrategyEnabled; - private set => SetProperty(ref _isTestStrategyEnabled, value); + get => _selection.IsTestStrategyEnabled; + private set => _selection.IsTestStrategyEnabled = value; } public bool IsManualTestEnabled { - get => _isManualTestEnabled; - private set => SetProperty(ref _isManualTestEnabled, value); + get => _selection.IsManualTestEnabled; + private set => _selection.IsManualTestEnabled = value; } /// Two-way: clicking the toggle button changes it before the click is handled. public bool? IsManualTestChecked { - get => _isManualTestChecked; - set => SetProperty(ref _isManualTestChecked, value); + get => _selection.IsManualTestChecked; + set => _selection.IsManualTestChecked = value; } public string ManualTestLabel { - get => _manualTestLabel; - private set => SetProperty(ref _manualTestLabel, value); + get => _selection.ManualTestLabel; + private set => _selection.ManualTestLabel = value; } public string ManualTestGlyph { - get => _manualTestGlyph; - private set => SetProperty(ref _manualTestGlyph, value); + get => _selection.ManualTestGlyph; + private set => _selection.ManualTestGlyph = value; } public bool IsAddForSiteEnabled { - get => _isAddForSiteEnabled; - private set => SetProperty(ref _isAddForSiteEnabled, value); + get => _selection.IsAddForSiteEnabled; + private set => _selection.IsAddForSiteEnabled = value; } public bool IsAddForListEnabled { - get => _isAddForListEnabled; - private set => SetProperty(ref _isAddForListEnabled, value); + get => _selection.IsAddForListEnabled; + private set => _selection.IsAddForListEnabled = value; } public bool IsReviewPresetEnabled @@ -145,44 +154,44 @@ public bool IsReviewPresetEnabled public string SelectedStrategyName { - get => _selectedStrategyName; - private set => SetProperty(ref _selectedStrategyName, value); + get => _selection.SelectedStrategyName; + private set => _selection.SelectedStrategyName = value; } public string SelectedStrategyId { - get => _selectedStrategyId; - private set => SetProperty(ref _selectedStrategyId, value); + get => _selection.SelectedStrategyId; + private set => _selection.SelectedStrategyId = value; } public string SelectedStrategyArguments { - get => _selectedStrategyArguments; - private set => SetProperty(ref _selectedStrategyArguments, value); + get => _selection.SelectedStrategyArguments; + private set => _selection.SelectedStrategyArguments = value; } public string SelectedSite { - get => _selectedSite; - private set => SetProperty(ref _selectedSite, value); + get => _selection.SelectedSite; + private set => _selection.SelectedSite = value; } public string SelectedConnection { - get => _selectedConnection; - private set => SetProperty(ref _selectedConnection, value); + get => _selection.SelectedConnection; + private set => _selection.SelectedConnection = value; } public string SelectedEvidence { - get => _selectedEvidence; - private set => SetProperty(ref _selectedEvidence, value); + get => _selection.SelectedEvidence; + private set => _selection.SelectedEvidence = value; } public string SelectedBaseline { - get => _selectedBaseline; - private set => SetProperty(ref _selectedBaseline, value); + get => _selection.SelectedBaseline; + private set => _selection.SelectedBaseline = value; } public void LoadReport(BlockCheckReport report) @@ -251,38 +260,7 @@ private void SetStrategiesVisible(bool visible) OnPropertiesChanged(nameof(IsNoStrategiesVisible), nameof(AreStrategiesVisible)); } - private void ShowReportSummary() - { - if (!Result.HasReport) - { - ShowActionMessage(BlockCheck2NoticeSeverity.Error, Text("BlockCheck2ResultEmptyTitle"), Text("BlockCheck2ResultEmptyMessage")); - return; - } - - var severity = Result.NoBypassRequired - ? BlockCheck2NoticeSeverity.Informational - : Result.Success - ? BlockCheck2NoticeSeverity.Success - : BlockCheck2NoticeSeverity.Warning; - var title = Result.NoBypassRequired - ? Text("BlockCheck2NoBypassRequiredTitle") - : Result.Success - ? Text("BlockCheck2ResultSuccessTitle") - : Result.IsBestEffort - ? Text("BlockCheck2ResultBestEffortTitle") - : Text("BlockCheck2ResultPartialTitle"); - var message = Result.NoBypassRequired - ? Text(Result.IsHttpOnly - ? "BlockCheck2HttpOnlyNoBypassRequiredMessage" - : "BlockCheck2NoBypassRequiredMessage") - : Result.Success - ? Text("BlockCheck2ResultSuccessMessage") - : Result.IsBestEffort - ? Text("BlockCheck2ResultBestEffortMessage") - : Text("BlockCheck2ResultPartialMessage"); - - ShowActionMessage(severity, title, message); - } + private void ShowReportSummary() => _reportSummary.Show(); public void ApplyStrategyView(string? searchText, int sortMode, int filterMode) { @@ -299,112 +277,12 @@ public void ApplyStrategyView(string? searchText, int sortMode, int filterMode) SetStrategiesVisible(Result.StrategyEvidence.Count != 0); } - public void UpdateSelectedStrategy() - { - BlockCheck2StrategyEvidenceItem? item = _view.SelectedStrategy; - bool selected = item != null && Result.HasSession; - IsDetailsHitTestVisible = selected && !_strategyTestRunning; - IsTestStrategyEnabled = selected && !_strategyTestRunning; - IsManualTestEnabled = selected && (!_strategyTestRunning || _isManualTestRunning); - IsManualTestChecked = selected && _isManualTestRunning; + public void UpdateSelectedStrategy() => _selection.Update(); - ManualTestLabel = IsManualTestChecked == true - ? Text("StopTest") - : Text("PresetTestConfirmButton"); - ManualTestGlyph = IsManualTestChecked == true - ? "\uE769" - : "\uE768"; + public Task TestSelectedStrategyAsync() => _selectedStrategyTest.TestAsync(); - IsAddForSiteEnabled = selected && !_strategyTestRunning; - IsAddForListEnabled = selected && - Result.CanAddForSiteList(item!) && - !_strategyTestRunning; - _view.NotifyMenuStateChanged(); - if (item == null) - { - SelectedStrategyName = Text("BlockCheck2SelectStrategyText"); - SelectedStrategyId = string.Empty; - SelectedStrategyArguments = string.Empty; - SelectedSite = string.Empty; - SelectedConnection = string.Empty; - SelectedEvidence = string.Empty; - SelectedBaseline = string.Empty; - return; - } - - SelectedStrategyName = item.StrategyName; - SelectedStrategyId = item.StrategyId; - SelectedStrategyArguments = item.StrategyArguments; - SelectedSite = item.SiteUrl; - SelectedConnection = item.ConnectionDetails; - SelectedEvidence = item.EvidenceDetails; - SelectedBaseline = string.Format( - Text("BlockCheck2BaselineEvidenceFormat"), - item.BaselineText); - } - - public async Task TestSelectedStrategyAsync() - { - BlockCheck2StrategyEvidenceItem? item = _view.SelectedStrategy; - if (item == null || _strategyTestRunning) - { - return; - } - - _strategyTestRunning = true; - IsStrategyTestProgressVisible = true; - UpdateSelectedStrategy(); - try - { - BlockCheckManualStrategyTestResult result = await Result.TestStrategyAsync(item); - UpdateSelectedStrategy(); - ShowStrategyTestResult(result); - } - catch (Exception exception) - { - ShowActionError(exception.Message); - } - finally - { - _strategyTestRunning = false; - IsStrategyTestProgressVisible = false; - UpdateSelectedStrategy(); - UpdateAssignmentView(); - } - } - - private void ShowStrategyTestResult(BlockCheckManualStrategyTestResult result) - { - if (result.ProbeResult == null) - { - BlockCheckIssue firstIssue = result.Issues.FirstOrDefault(); - ShowActionError(firstIssue != null - ? BlockCheck2IssueText.GetMessage(firstIssue) - : Text("BlockCheck2StrategyTestFailedMessage")); - return; - } - - ProbeSummary summary = ProbeSummary.FromAttempts(result.ProbeResult.Attempts); - string message = string.Format( - Text("BlockCheck2StrategyTestResultFormat"), - summary.SuccessCount, - summary.AttemptCount, - summary.SuccessRate); - if (result.Issues.Any(issue => issue.Severity == BlockCheckIssueSeverity.Error)) - { - ShowActionError(BlockCheck2IssueText.GetMessage(result.Issues.First(issue => - issue.Severity == BlockCheckIssueSeverity.Error))); - } - else - { - ShowActionMessage( - summary.SuccessCount == summary.AttemptCount - ? BlockCheck2NoticeSeverity.Success - : BlockCheck2NoticeSeverity.Warning, - Text("BlockCheck2StrategyTestCompletedTitle"), - message); - } - } + private void ShowStrategyTestResult(BlockCheckManualStrategyTestResult result) => + _selectedStrategyTest.ShowResult(result); private void UpdateStrategyCount() { diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultSelection.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultSelection.cs new file mode 100644 index 00000000..f17f6f8d --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultSelection.cs @@ -0,0 +1,179 @@ +#nullable enable + +using System; + +namespace CDPIUI.ViewModels.BlockCheck2; + +// Preserves selected-row presentation and synchronous publication order. +internal sealed class BlockCheck2ResultSelection : ObservableObject +{ + private readonly Func _selectedItem; + private readonly Func _hasSession, _testRunning, _manualRunning; + private readonly Func _canAddForList; + private readonly Func _text; + private readonly Action _menu; + + private bool _isDetailsHitTestVisible = true; + private bool _isTestStrategyEnabled = true; + private bool _isManualTestEnabled = true; + private bool? _isManualTestChecked = false; + private string _manualTestLabel = string.Empty; + private string _manualTestGlyph = "\uE768"; + private bool _isAddForSiteEnabled = true; + private bool _isAddForListEnabled = true; + private string _selectedStrategyName = string.Empty; + private string _selectedStrategyId = string.Empty; + private string _selectedStrategyArguments = string.Empty; + private string _selectedSite = string.Empty; + private string _selectedConnection = string.Empty; + private string _selectedEvidence = string.Empty; + private string _selectedBaseline = string.Empty; + + public BlockCheck2ResultSelection(Func selectedItem, + Func hasSession, Func testRunning, Func manualRunning, + Func canAddForList, Func text, Action menu) + { + _selectedItem = selectedItem; + _hasSession = hasSession; + _testRunning = testRunning; + _manualRunning = manualRunning; + _canAddForList = canAddForList; + _text = text; + _menu = menu; + } + + public bool IsDetailsHitTestVisible + { + get => _isDetailsHitTestVisible; + set => SetProperty(ref _isDetailsHitTestVisible, value); + } + + public bool IsTestStrategyEnabled + { + get => _isTestStrategyEnabled; + set => SetProperty(ref _isTestStrategyEnabled, value); + } + + public bool IsManualTestEnabled + { + get => _isManualTestEnabled; + set => SetProperty(ref _isManualTestEnabled, value); + } + + public bool? IsManualTestChecked + { + get => _isManualTestChecked; + set => SetProperty(ref _isManualTestChecked, value); + } + + public string ManualTestLabel + { + get => _manualTestLabel; + set => SetProperty(ref _manualTestLabel, value); + } + + public string ManualTestGlyph + { + get => _manualTestGlyph; + set => SetProperty(ref _manualTestGlyph, value); + } + + public bool IsAddForSiteEnabled + { + get => _isAddForSiteEnabled; + set => SetProperty(ref _isAddForSiteEnabled, value); + } + + public bool IsAddForListEnabled + { + get => _isAddForListEnabled; + set => SetProperty(ref _isAddForListEnabled, value); + } + + public string SelectedStrategyName + { + get => _selectedStrategyName; + set => SetProperty(ref _selectedStrategyName, value); + } + + public string SelectedStrategyId + { + get => _selectedStrategyId; + set => SetProperty(ref _selectedStrategyId, value); + } + + public string SelectedStrategyArguments + { + get => _selectedStrategyArguments; + set => SetProperty(ref _selectedStrategyArguments, value); + } + + public string SelectedSite + { + get => _selectedSite; + set => SetProperty(ref _selectedSite, value); + } + + public string SelectedConnection + { + get => _selectedConnection; + set => SetProperty(ref _selectedConnection, value); + } + + public string SelectedEvidence + { + get => _selectedEvidence; + set => SetProperty(ref _selectedEvidence, value); + } + + public string SelectedBaseline + { + get => _selectedBaseline; + set => SetProperty(ref _selectedBaseline, value); + } + + public void Update() + { + BlockCheck2StrategyEvidenceItem? item = _selectedItem(); + bool selected = item != null && _hasSession(); + IsDetailsHitTestVisible = selected && !_testRunning(); + IsTestStrategyEnabled = selected && !_testRunning(); + IsManualTestEnabled = selected && (!_testRunning() || _manualRunning()); + IsManualTestChecked = selected && _manualRunning(); + + ManualTestLabel = IsManualTestChecked == true + ? _text("StopTest") + : _text("PresetTestConfirmButton"); + ManualTestGlyph = IsManualTestChecked == true + ? "\uE769" + : "\uE768"; + + IsAddForSiteEnabled = selected && !_testRunning(); + IsAddForListEnabled = selected && + _canAddForList(item!) && + !_testRunning(); + _menu(); + if (item == null) + { + SelectedStrategyName = _text("BlockCheck2SelectStrategyText"); + SelectedStrategyId = string.Empty; + SelectedStrategyArguments = string.Empty; + SelectedSite = string.Empty; + SelectedConnection = string.Empty; + SelectedEvidence = string.Empty; + SelectedBaseline = string.Empty; + return; + } + + SelectedStrategyName = item.StrategyName; + SelectedStrategyId = item.StrategyId; + SelectedStrategyArguments = item.StrategyArguments; + SelectedSite = item.SiteUrl; + SelectedConnection = item.ConnectionDetails; + SelectedEvidence = item.EvidenceDetails; + SelectedBaseline = string.Format( + _text("BlockCheck2BaselineEvidenceFormat"), + item.BaselineText); + } + +} diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2SelectedStrategyTest.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2SelectedStrategyTest.cs new file mode 100644 index 00000000..b513617e --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2SelectedStrategyTest.cs @@ -0,0 +1,103 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using CDPIUI.AddOns.BlockCheck2.Models; + +namespace CDPIUI.ViewModels.BlockCheck2; + +/// Runs a selected strategy test and presents its result through the result page. +internal sealed class BlockCheck2SelectedStrategyTest +{ + private readonly Func _selected; + private readonly Func _running; + private readonly Action _setRunning; + private readonly Action _progress; + private readonly Action _selection; + private readonly Func> _test; + private readonly Action _assignments; + private readonly Func _text; + private readonly Func _issueText; + private readonly Action _error; + private readonly Action _show; + + public BlockCheck2SelectedStrategyTest(Func selected, Func running, + Action setRunning, Action progress, Action selection, + Func> test, Action assignments, + Func text, Func issueText, Action error, + Action show) + { + _selected = selected; + _running = running; + _setRunning = setRunning; + _progress = progress; + _selection = selection; + _test = test; + _assignments = assignments; + _text = text; + _issueText = issueText; + _error = error; + _show = show; + } + + public async Task TestAsync() + { + BlockCheck2StrategyEvidenceItem? item = _selected(); + if (item == null || _running()) + { + return; + } + + _setRunning(true); + _progress(true); + _selection(); + try + { + BlockCheckManualStrategyTestResult result = await _test(item); + _selection(); + ShowResult(result); + } + catch (Exception exception) + { + _error(exception.Message); + } + finally + { + _setRunning(false); + _progress(false); + _selection(); + _assignments(); + } + } + + public void ShowResult(BlockCheckManualStrategyTestResult result) + { + if (result.ProbeResult == null) + { + BlockCheckIssue firstIssue = result.Issues.FirstOrDefault(); + _error(firstIssue != null + ? _issueText(firstIssue) + : _text("BlockCheck2StrategyTestFailedMessage")); + return; + } + + ProbeSummary summary = ProbeSummary.FromAttempts(result.ProbeResult.Attempts); + string message = string.Format( + _text("BlockCheck2StrategyTestResultFormat"), + summary.SuccessCount, + summary.AttemptCount, + summary.SuccessRate); + if (result.Issues.Any(issue => issue.Severity == BlockCheckIssueSeverity.Error)) + { + _error(_issueText(result.Issues.First(issue => issue.Severity == BlockCheckIssueSeverity.Error))); + } + else + { + _show( + summary.SuccessCount == summary.AttemptCount + ? BlockCheck2NoticeSeverity.Success + : BlockCheck2NoticeSeverity.Warning, + _text("BlockCheck2StrategyTestCompletedTitle"), + message); + } + } +} diff --git a/CDPIUI/ViewModels/BlockCheck2/IBlockCheck2AssignmentActionsHost.cs b/CDPIUI/ViewModels/BlockCheck2/IBlockCheck2AssignmentActionsHost.cs new file mode 100644 index 00000000..5a50cb51 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/IBlockCheck2AssignmentActionsHost.cs @@ -0,0 +1,23 @@ +#nullable enable + +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace CDPIUI.ViewModels.BlockCheck2; + +internal interface IBlockCheck2AssignmentActionsHost +{ + BlockCheck2StrategyEvidenceItem? SelectedStrategy { get; } + IReadOnlyList GetSiteListPaths(BlockCheck2StrategyEvidenceItem item); + Task ChooseSiteListAsync(IReadOnlyList paths); + bool AddForSite(BlockCheck2StrategyEvidenceItem item); + bool AddForSiteList(BlockCheck2StrategyEvidenceItem item, string path); + BlockCheck2ManualAssignmentItem? SelectedAssignment { get; set; } + bool MoveAssignment(BlockCheck2ManualAssignmentItem item, int offset); + void RemoveAssignment(BlockCheck2ManualAssignmentItem item); + void ClearAssignments(); + void UpdateAssignmentView(); + void UpdateActionButtons(); + string Text(string key); + void ShowMessage(BlockCheck2NoticeSeverity severity, string title, string message); +} diff --git a/CDPIUI/ViewModels/BlockCheck2/IBlockCheck2ManualTestHost.cs b/CDPIUI/ViewModels/BlockCheck2/IBlockCheck2ManualTestHost.cs new file mode 100644 index 00000000..89d01162 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/IBlockCheck2ManualTestHost.cs @@ -0,0 +1,20 @@ +using System; +using System.Threading.Tasks; +using CDPIUI.Shared.Models; + +namespace CDPIUI.ViewModels.BlockCheck2; + +internal interface IBlockCheck2ManualTestHost +{ + BlockCheck2StrategyEvidenceItem? SelectedStrategy { get; } + bool IsStrategyTestRunning { get; } + bool? IsManualTestChecked { get; } + OperationResultModel GetFullStrategyArguments(BlockCheck2StrategyEvidenceItem item); + Task ConfirmReplacementAsync(); + void UpdateSelectedStrategy(); + void UpdateAssignmentView(); + string Text(string key); + void ShowMessage(BlockCheck2NoticeSeverity severity, string title, string message); + void Warn(Exception exception); + void Enqueue(Func callback); +} diff --git a/CDPIUI/ViewModels/BlockCheck2ManualAssignmentEditor.cs b/CDPIUI/ViewModels/BlockCheck2ManualAssignmentEditor.cs new file mode 100644 index 00000000..b7ad20fd --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2ManualAssignmentEditor.cs @@ -0,0 +1,229 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.IO; +using System.Linq; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.AddOns.BlockCheck2.Reporting; +using CDPIUI.AddOns.BlockCheck2.Synthesis; + +namespace CDPIUI.ViewModels; + +// Edits the existing draft assignments; preset rebuilding and UI notifications remain with the host. +internal sealed class BlockCheck2ManualAssignmentEditor +{ + private readonly BlockCheck2PresetDraft _draft; + private readonly Func _session; + private readonly Func> _evidence; + private readonly Action _clearAcknowledgedIssues; + private readonly Action _rebuildPreset; + private readonly Func _formatActions; + private readonly HashSet _automaticAssignmentKeys = new(StringComparer.OrdinalIgnoreCase); + + public BlockCheck2ManualAssignmentEditor(BlockCheck2PresetDraft draft, + Func session, Func> evidence, + Action clearAcknowledgedIssues, Action rebuildPreset, Func? formatActions = null) + { + _draft = draft; + _session = session; + _evidence = evidence; + _clearAcknowledgedIssues = clearAcknowledgedIssues; + _rebuildPreset = rebuildPreset; + _formatActions = formatActions ?? (strategy => new Zapret2ConfigWriter().FormatStrategyActions(strategy)); + } + + public ObservableCollection Items => _draft.Assignments; + + public void ClearAutomaticKeys() => _automaticAssignmentKeys.Clear(); + + public bool AddForSite(BlockCheck2StrategyEvidenceItem item) => + AddAssignment(new BlockCheckManualAssignment( + item.StrategyId, + item.TargetId, + BlockCheckManualScopeKind.Site)); + + public bool AddForSiteList(BlockCheck2StrategyEvidenceItem item, string siteListPath) + { + BlockCheckTarget? anchor = FindCompatibleSiteListTargets(item) + .FirstOrDefault(target => target.HostListPaths.Contains( + siteListPath, + StringComparer.OrdinalIgnoreCase)); + return anchor != null && AddAssignment(new BlockCheckManualAssignment( + item.StrategyId, + anchor.Id, + BlockCheckManualScopeKind.SiteList, + siteListPath)); + } + + public void RemoveAssignment(BlockCheck2ManualAssignmentItem item) + { + int index = Items.IndexOf(item); + if (index < 0) + { + return; + } + _clearAcknowledgedIssues(); + Items.RemoveAt(index); + _rebuildPreset(true); + } + + public bool MoveAssignment(BlockCheck2ManualAssignmentItem item, int offset) + { + int oldIndex = Items.IndexOf(item); + int newIndex = oldIndex + offset; + if (oldIndex < 0 || newIndex < 0 || newIndex >= Items.Count) + { + return false; + } + _clearAcknowledgedIssues(); + Items.Move(oldIndex, newIndex); + _rebuildPreset(true); + return true; + } + + public void ClearManualAssignments() + { + _clearAcknowledgedIssues(); + Items.Clear(); + _rebuildPreset(true); + } + + public IReadOnlyList GetSiteListPaths(BlockCheck2StrategyEvidenceItem item) => + FindCompatibleSiteListTargets(item) + .SelectMany(target => target.HostListPaths) + .Where(path => !string.IsNullOrWhiteSpace(path)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(path => Path.GetFileName(path), StringComparer.CurrentCultureIgnoreCase) + .ThenBy(path => path, StringComparer.CurrentCultureIgnoreCase) + .ToArray(); + + public bool CanAddForSiteList(BlockCheck2StrategyEvidenceItem item) => + FindCompatibleSiteListTargets(item).Any(); + + private bool AddAssignment(BlockCheckManualAssignment assignment) + { + if (_session() == null) + { + return false; + } + bool duplicate = Items.Any(item => + string.Equals(item.Assignment.StrategyId, assignment.StrategyId, StringComparison.OrdinalIgnoreCase) && + string.Equals(item.Assignment.AnchorTargetId, assignment.AnchorTargetId, StringComparison.Ordinal) && + item.Assignment.ScopeKind == assignment.ScopeKind && + string.Equals(item.Assignment.SiteListPath, assignment.SiteListPath, StringComparison.OrdinalIgnoreCase)); + if (duplicate) + { + return false; + } + + StrategyDefinition? strategy = _session()!.Catalog.Strategies.FirstOrDefault(candidate => + string.Equals(candidate.Id, assignment.StrategyId, StringComparison.OrdinalIgnoreCase)); + BlockCheckTarget? target = _session()!.Targets.FirstOrDefault(candidate => + string.Equals(candidate.Id, assignment.AnchorTargetId, StringComparison.Ordinal)); + if (strategy == null || target == null) + { + return false; + } + _clearAcknowledgedIssues(); + AddAssignmentCore(assignment, strategy, target); + _rebuildPreset(true); + return true; + } + + private void AddAssignmentCore( + BlockCheckManualAssignment assignment, + StrategyDefinition strategy, + BlockCheckTarget target) + { + Items.Add(new BlockCheck2ManualAssignmentItem( + assignment, + strategy, + target, + _formatActions(strategy))); + } + + private IEnumerable FindCompatibleSiteListTargets( + BlockCheck2StrategyEvidenceItem item) + { + if (_session() == null) + { + return []; + } + + BlockCheckTarget source = item.Evidence.Target; + string host = BlockCheckTarget.NormalizeHost(source.Host); + return _session()!.Targets.Where(target => + !_session()!.RunResult.Scan.IgnoredTargetIds.Contains(target.Id) && + BlockCheck2ManualAssignmentRules.IsCompatibleSiteListTarget(target, source, host)); + } + + public void SeedAutomaticAssignments(BlockCheckResultSession value) + { + _clearAcknowledgedIssues(); + Items.Clear(); + Dictionary strategies = value.Catalog.Strategies + .ToDictionary(strategy => strategy.Id, StringComparer.OrdinalIgnoreCase); + Dictionary targets = value.Targets + .ToDictionary(target => target.Id, StringComparer.Ordinal); + + foreach (BlockCheckReportProfile profile in value.Report.Profiles) + { + BlockCheckTarget[] profileTargets = profile.TargetIds + .Select(id => targets.GetValueOrDefault(id)) + .Where(target => target != null) + .Cast() + .ToArray(); + IEnumerable<(BlockCheckTarget Target, BlockCheckManualScopeKind Scope, string? Path)> scopes = + BlockCheck2ManualAssignmentRules.GetAutomaticScopes(profile, profileTargets); + + foreach ((BlockCheckTarget target, BlockCheckManualScopeKind scope, string? path) in scopes) + { + foreach (string strategyId in new[] { profile.PrimaryStrategyId }.Concat(profile.FallbackStrategyIds)) + { + if (!strategies.TryGetValue(strategyId, out StrategyDefinition? strategy)) + { + continue; + } + BlockCheckManualAssignment assignment = new(strategyId, target.Id, scope, path); + bool duplicate = Items.Any(item => item.Assignment == assignment); + if (!duplicate) + { + AddAssignmentCore(assignment, strategy, target); + _automaticAssignmentKeys.Add(BlockCheck2ManualAssignmentRules.AssignmentKey(assignment)); + } + } + } + } + + _rebuildPreset(false); + _draft.LoadAutomatic(value.Report.PresetArguments, value.Report.Profiles); + RefreshAssignmentIndexes(); + RefreshEvidenceSelections(); + } + + public void RefreshEvidenceSelections() + { + foreach (BlockCheck2StrategyEvidenceItem evidence in _evidence()) + { + BlockCheck2ManualAssignmentItem[] selectedAssignments = Items + .Where(item => BlockCheck2ManualAssignmentRules.AssignmentMatchesEvidence(item, evidence)) + .ToArray(); + bool selected = selectedAssignments.Length > 0; + bool automatic = selectedAssignments.Any(item => + _automaticAssignmentKeys.Contains(BlockCheck2ManualAssignmentRules.AssignmentKey(item.Assignment))); + evidence.SetSelection(selected, automatic); + } + } + + public void RefreshAssignmentIndexes() + { + for (int index = 0; index < Items.Count; index++) + { + Items[index].SetOrder(index + 1); + } + } + +} diff --git a/CDPIUI/ViewModels/BlockCheck2ManualAssignmentRules.cs b/CDPIUI/ViewModels/BlockCheck2ManualAssignmentRules.cs index a9e9e0d5..87ba7999 100644 --- a/CDPIUI/ViewModels/BlockCheck2ManualAssignmentRules.cs +++ b/CDPIUI/ViewModels/BlockCheck2ManualAssignmentRules.cs @@ -1,3 +1,6 @@ +#nullable enable annotations +#nullable disable warnings + using System; using System.Collections.Generic; using System.IO; diff --git a/CDPIUI/ViewModels/BlockCheck2ManualIssueItem.cs b/CDPIUI/ViewModels/BlockCheck2ManualIssueItem.cs new file mode 100644 index 00000000..df29aa26 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2ManualIssueItem.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.Helper.AddOns.BlockCheck2; + +namespace CDPIUI.ViewModels; + +public sealed class BlockCheck2ManualIssueItem +{ + public BlockCheck2ManualIssueItem( + BlockCheckIssueSeverity severity, + string code, + string message, + int count, + IEnumerable subjects) + { + Severity = severity; + Code = code; + Message = BlockCheck2IssueText.GetMessage(code, message); + Count = Math.Max(1, count); + string[] materializedSubjects = subjects + .Where(subject => !string.IsNullOrWhiteSpace(subject)) + .Distinct(StringComparer.CurrentCultureIgnoreCase) + .OrderBy(subject => subject, StringComparer.CurrentCultureIgnoreCase) + .ToArray(); + SubjectText = string.Join(", ", materializedSubjects); + Key = $"{Severity}|{Code}|{message}|{string.Join('|', materializedSubjects)}"; + } + + public BlockCheckIssueSeverity Severity { get; } + public string Code { get; } + public string DisplayCode => Count > 1 ? $"{Code} ×{Count}" : Code; + public string Message { get; } + public int Count { get; } + public string SubjectText { get; } + public bool HasSubjects => SubjectText.Length > 0; + public string Key { get; } + public bool CanQuickFix => string.Equals( + Code, + "MANUAL_SCOPE_OVERLAP", + StringComparison.OrdinalIgnoreCase); +} diff --git a/CDPIUI/ViewModels/BlockCheck2ManualPresetOperations.cs b/CDPIUI/ViewModels/BlockCheck2ManualPresetOperations.cs new file mode 100644 index 00000000..7cd51794 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2ManualPresetOperations.cs @@ -0,0 +1,18 @@ +#nullable enable + +using System.Collections.Generic; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Synthesis; + +namespace CDPIUI.ViewModels; + +internal sealed class BlockCheck2ManualPresetOperations : IBlockCheck2ManualPresetOperations +{ + private readonly BlockCheckManualPresetService _service; + + public BlockCheck2ManualPresetOperations(BlockCheckManualPresetService service) => _service = service; + + public BlockCheckManualPresetResult Build(StrategyCatalog catalog, IEnumerable targets, + IEnumerable assignments, IEnumerable evidence, BlockCheckManualPresetOptions options) => + _service.Build(catalog, targets, assignments, evidence, options); +} diff --git a/CDPIUI/ViewModels/BlockCheck2ManualPresetState.cs b/CDPIUI/ViewModels/BlockCheck2ManualPresetState.cs new file mode 100644 index 00000000..83cc3361 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2ManualPresetState.cs @@ -0,0 +1,133 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; + +namespace CDPIUI.ViewModels; + +// Rebuilds the same draft while keeping UI issue construction and notifications with the host. +internal sealed class BlockCheck2ManualPresetState +{ + private readonly BlockCheck2PresetDraft _draft; + private readonly IReadOnlyList _manualTests; + private readonly IBlockCheck2ManualPresetHost _host; + private readonly IBlockCheck2ManualPresetOperations _operations; + private BlockCheckManualPresetResult? _manualPreset; + + public BlockCheck2ManualPresetState(BlockCheck2PresetDraft draft, IReadOnlyList manualTests, + IBlockCheck2ManualPresetHost host, IBlockCheck2ManualPresetOperations operations) + { + _draft = draft; + _manualTests = manualTests; + _host = host; + _operations = operations; + } + + public string Arguments => _manualPreset?.Configuration.CommandLine ?? string.Empty; + public void ClearResult() => _manualPreset = null; + + public void Rebuild(bool updateDraft) + { + _host.ClearIssues(); + if (_host.Session! == null || _draft.Assignments.Count == 0) + { + _manualPreset = null; + _host.RefreshAssignmentIndexes(); + if (updateDraft) + { + _draft.ApplyStructuredChange(string.Empty, []); + } + _host.RefreshEvidenceSelections(); + _host.NotifyManualState(); + return; + } + + IEnumerable evidence = _host.Session!.RunResult.Scan.ProbeResults + .Where(result => !_manualTests.Any(test => + string.Equals(test.StrategyId, result.StrategyId, StringComparison.OrdinalIgnoreCase) && + string.Equals(test.TargetId, result.TargetId, StringComparison.Ordinal))) + .Concat(_manualTests); + _manualPreset = _operations.Build( + _host.Session!.Catalog, + _host.Session!.Targets.Where(target => !_host.Session!.RunResult.Scan.IgnoredTargetIds.Contains(target.Id)), + _draft.Assignments.Select(item => item.Assignment), + evidence, + OptionsFor(_host.Session!)); + foreach (var group in _manualPreset.Issues.GroupBy(issue => new + { + issue.Severity, + issue.Code, + issue.Message, + })) + { + _host.AddIssueGroup( + group.Key.Severity, + group.Key.Code, + group.Key.Message, + group.Count(), + group.Select(issue => DescribeManualIssueSubject(issue.SubjectId))); + } + if (updateDraft) + { + _draft.ApplyStructuredChange( + _manualPreset.Configuration.CommandLine, + _manualPreset.Profiles); + } + _host.RefreshAssignmentIndexes(); + _host.RefreshEvidenceSelections(); + _host.NotifyManualState(); + } + + private string DescribeManualIssueSubject(string? subjectId) + { + if (string.IsNullOrWhiteSpace(subjectId)) + { + return string.Empty; + } + + BlockCheck2ManualAssignmentItem? scopeAssignment = _draft.Assignments.FirstOrDefault(item => + string.Equals(BlockCheck2ManualAssignmentRules.ManualScopeKey(item), subjectId, StringComparison.OrdinalIgnoreCase)); + if (scopeAssignment != null) + { + return $"{scopeAssignment.Scope} · {scopeAssignment.ConnectionDetails}"; + } + + BlockCheck2ManualAssignmentItem? assignment = _draft.Assignments.FirstOrDefault(item => + string.Equals(item.Assignment.StrategyId, subjectId, StringComparison.OrdinalIgnoreCase)); + if (assignment != null) + { + return BlockCheck2ManualAssignmentRules.DescribeStrategySubject(assignment, subjectId); + } + + string[] strategyIds = subjectId.Split('/', StringSplitOptions.RemoveEmptyEntries); + if (strategyIds.Length > 1) + { + string[] strategyNames = strategyIds + .Select(strategyId => + { + BlockCheck2ManualAssignmentItem? item = _draft.Assignments.FirstOrDefault(candidate => + string.Equals( + candidate.Assignment.StrategyId, + strategyId, + StringComparison.OrdinalIgnoreCase)); + return item == null + ? strategyId + : BlockCheck2ManualAssignmentRules.DescribeStrategySubject(item, strategyId); + }) + .ToArray(); + return string.Join(" / ", strategyNames); + } + + return subjectId; + } + + public static BlockCheckManualPresetOptions OptionsFor(BlockCheckResultSession session) => new() + { + MinimumAttempts = Math.Max(1, session.RunOptions.Synthesis.MinimumAttempts), + MinimumSuccessRate = session.RunOptions.Synthesis.MinimumSuccessRate, + }; + +} diff --git a/CDPIUI/ViewModels/BlockCheck2ManualResultViewModels.cs b/CDPIUI/ViewModels/BlockCheck2ManualResultViewModels.cs index 6b1ed64c..9d469057 100644 --- a/CDPIUI/ViewModels/BlockCheck2ManualResultViewModels.cs +++ b/CDPIUI/ViewModels/BlockCheck2ManualResultViewModels.cs @@ -1,3 +1,6 @@ +#nullable enable annotations +#nullable disable warnings + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -7,7 +10,6 @@ using System.Runtime.CompilerServices; using CDPIUI.AddOns.BlockCheck2.Models; using CDPIUI.AddOns.BlockCheck2.Presentation; -using CDPIUI.Helper.AddOns.BlockCheck2; namespace CDPIUI.ViewModels; @@ -21,42 +23,6 @@ public BlockCheck2SiteStrategyGroup(string siteUrl) public string SiteUrl { get; } } -public sealed class BlockCheck2ManualIssueItem -{ - public BlockCheck2ManualIssueItem( - BlockCheckIssueSeverity severity, - string code, - string message, - int count, - IEnumerable subjects) - { - Severity = severity; - Code = code; - Message = BlockCheck2IssueText.GetMessage(code, message); - Count = Math.Max(1, count); - string[] materializedSubjects = subjects - .Where(subject => !string.IsNullOrWhiteSpace(subject)) - .Distinct(StringComparer.CurrentCultureIgnoreCase) - .OrderBy(subject => subject, StringComparer.CurrentCultureIgnoreCase) - .ToArray(); - SubjectText = string.Join(", ", materializedSubjects); - Key = $"{Severity}|{Code}|{message}|{string.Join('|', materializedSubjects)}"; - } - - public BlockCheckIssueSeverity Severity { get; } - public string Code { get; } - public string DisplayCode => Count > 1 ? $"{Code} ×{Count}" : Code; - public string Message { get; } - public int Count { get; } - public string SubjectText { get; } - public bool HasSubjects => SubjectText.Length > 0; - public string Key { get; } - public bool CanQuickFix => string.Equals( - Code, - "MANUAL_SCOPE_OVERLAP", - StringComparison.OrdinalIgnoreCase); -} - public sealed class BlockCheck2StrategyEvidenceItem : INotifyPropertyChanged { private ProbeSummary _summary; diff --git a/CDPIUI/ViewModels/BlockCheck2ManualStrategyTestController.cs b/CDPIUI/ViewModels/BlockCheck2ManualStrategyTestController.cs new file mode 100644 index 00000000..7ed7eca7 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2ManualStrategyTestController.cs @@ -0,0 +1,87 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using CDPIUI.AddOns.BlockCheck2.Execution; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.Shared.Models; + +namespace CDPIUI.ViewModels; + +internal sealed class BlockCheck2ManualStrategyTestController +{ + private readonly BlockCheck2PresetDraft _draft; + private readonly List _manualTests; + private readonly Func _session; + private readonly Action _rebuildPreset; + private readonly IBlockCheck2ManualStrategyTestOperations _operations; + + public BlockCheck2ManualStrategyTestController(BlockCheck2PresetDraft draft, List manualTests, + Func session, Action rebuildPreset, IBlockCheck2ManualStrategyTestOperations operations) + { + _draft = draft; + _manualTests = manualTests; + _session = session; + _rebuildPreset = rebuildPreset; + _operations = operations; + } + + public OperationResultModel GetFullStrategyArguments(BlockCheck2StrategyEvidenceItem item) => + _operations.GetFullStrategyArguments( + item.Evidence.Strategy, + item.Evidence.Target, + new BlockCheckManualStrategyTestOptions + { + Attempts = Math.Max(1, _session()!.RunOptions.Scan.AttemptsPerTarget), + }); + + public async Task TestStrategyAsync( + BlockCheck2StrategyEvidenceItem item, CancellationToken cancellationToken = default) + { + if (_session() == null) + { + return new BlockCheckManualStrategyTestResult + { + Issues = + [ + new BlockCheckIssue( + BlockCheckIssueSeverity.Error, + "MANUAL_SESSION_UNAVAILABLE", + "The original BlockCheck session is unavailable; this report cannot launch a live strategy test."), + ], + }; + } + + BlockCheckManualStrategyTestResult result = await _operations.TestAsync( + item.Evidence.Strategy, + item.Evidence.Target, + new BlockCheckManualStrategyTestOptions + { + Attempts = Math.Max(1, _session()!.RunOptions.Scan.AttemptsPerTarget), + }, + new CdpiuiZapret2StrategyRunnerOptions + { + StartupGracePeriod = _session()!.StartupGracePeriod, + }, + new CurlBlockCheckProbeRunnerOptions + { + ConnectTimeout = _session()!.ConnectTimeout, + RequestTimeout = _session()!.RequestTimeout, + }, + cancellationToken) + .ConfigureAwait(true); + if (result.ProbeResult != null) + { + _manualTests.RemoveAll(probe => + string.Equals(probe.StrategyId, result.ProbeResult.StrategyId, StringComparison.OrdinalIgnoreCase) && + string.Equals(probe.TargetId, result.ProbeResult.TargetId, StringComparison.Ordinal)); + _manualTests.Add(result.ProbeResult); + item.ApplyTestResult(result.ProbeResult); + _rebuildPreset(!_draft.IsAutomatic); + } + return result; + } +} diff --git a/CDPIUI/ViewModels/BlockCheck2ManualStrategyTestOperations.cs b/CDPIUI/ViewModels/BlockCheck2ManualStrategyTestOperations.cs new file mode 100644 index 00000000..fd9d5577 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2ManualStrategyTestOperations.cs @@ -0,0 +1,26 @@ +#nullable enable + +using System.Threading; +using System.Threading.Tasks; +using CDPIUI.AddOns.BlockCheck2.Execution; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.Shared.Models; + +namespace CDPIUI.ViewModels; + +internal sealed class BlockCheck2ManualStrategyTestOperations : IBlockCheck2ManualStrategyTestOperations +{ + private readonly BlockCheckManualStrategyTestService _service; + + public BlockCheck2ManualStrategyTestOperations(BlockCheckManualStrategyTestService service) => _service = service; + + public OperationResultModel GetFullStrategyArguments(StrategyDefinition strategy, + BlockCheckTarget target, BlockCheckManualStrategyTestOptions options) => + _service.GetFullStrategyArguments(strategy, target, options); + + public Task TestAsync(StrategyDefinition strategy, + BlockCheckTarget target, BlockCheckManualStrategyTestOptions options, + CdpiuiZapret2StrategyRunnerOptions strategyOptions, CurlBlockCheckProbeRunnerOptions probeOptions, + CancellationToken cancellationToken) => + _service.TestWithCdpiuiAdaptersAsync(strategy, target, options, strategyOptions, probeOptions, cancellationToken); +} diff --git a/CDPIUI/ViewModels/BlockCheck2OptionsSettings.cs b/CDPIUI/ViewModels/BlockCheck2OptionsSettings.cs new file mode 100644 index 00000000..a7ca9b76 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2OptionsSettings.cs @@ -0,0 +1,14 @@ +#nullable enable + +namespace CDPIUI.ViewModels; + +// Retains the original settings keys, value types and error handling. +internal sealed class BlockCheck2OptionsSettings : IBlockCheck2OptionsSettings +{ + public int ReadInt(string key, int defaultValue) => BlockCheck2SettingsStore.ReadInt(key, defaultValue); + public bool ReadBool(string key, bool defaultValue) => BlockCheck2SettingsStore.ReadBool(key, defaultValue); + public double ReadDouble(string key, double defaultValue) => BlockCheck2SettingsStore.ReadDouble(key, defaultValue); + public void Save(string? key, int value) => BlockCheck2SettingsStore.Save(key, value); + public void Save(string? key, bool value) => BlockCheck2SettingsStore.Save(key, value); + public void Save(string? key, double value) => BlockCheck2SettingsStore.Save(key, value); +} diff --git a/CDPIUI/ViewModels/BlockCheck2OptionsViewModel.cs b/CDPIUI/ViewModels/BlockCheck2OptionsViewModel.cs new file mode 100644 index 00000000..74245f2f --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2OptionsViewModel.cs @@ -0,0 +1,348 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Runtime.CompilerServices; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; + +namespace CDPIUI.ViewModels; + +internal sealed class BlockCheck2OptionsViewModel : INotifyPropertyChanged +{ + private readonly IBlockCheck2OptionsSettings _settings; + private readonly Func _isRunning; + private readonly Func _selectedSiteListCount; + + public BlockCheck2OptionsViewModel( + IBlockCheck2OptionsSettings settings, + Func isRunning, + Func selectedSiteListCount) + { + _settings = settings; + _isRunning = isRunning; + _selectedSiteListCount = selectedSiteListCount; + LoadSettings(); + } + + public event PropertyChangedEventHandler? PropertyChanged; + + private string _targetInput = string.Empty; + private BlockCheckRunPreset _selectedRunPreset = BlockCheckRunPreset.Balanced; + private bool _includeHttp; + private bool _includeTls12 = true; + private bool _includeTls13; + private bool _includeTlsAuto = true; + private bool _includeQuic; + private bool _includeIpv4 = true; + private bool _includeIpv6; + private double _connectTimeoutSeconds = BlockCheck2OptionLimits.DefaultConnectTimeoutSeconds; + private double _requestTimeoutSeconds = BlockCheck2OptionLimits.DefaultRequestTimeoutSeconds; + private double _startupGraceSeconds = BlockCheck2OptionLimits.DefaultStartupGraceSeconds; + private bool _testAllStrategies; + private double _requestsPerDomain = 3d; + + public IReadOnlyList AvailableRunPresets { get; } = + Enum.GetValues(); + + public string TargetInput + { + get => _targetInput; + set + { + if (_targetInput == value) + { + return; + } + + _targetInput = value ?? string.Empty; + Notify(); + Notify(nameof(DirectTargetInputCount)); + Notify(nameof(HasTargetSources)); + Notify(nameof(CanStart)); + } + } + + public BlockCheckRunPreset SelectedRunPreset + { + get => _selectedRunPreset; + set + { + if (_selectedRunPreset == value) + { + return; + } + + _selectedRunPreset = value; + Notify(); + _settings.Save(nameof(SelectedRunPreset), (int)value); + RequestsPerDomain = BlockCheckRunPresetFactory.GetRecommendedAttemptsPerTarget(value); + } + } + + public bool IncludeHttp + { + get => _includeHttp; + set => SetProtocolSelection(ref _includeHttp, value); + } + + public bool IncludeTls12 + { + get => _includeTls12; + set => SetProtocolSelection(ref _includeTls12, value); + } + + public bool IncludeTls13 + { + get => _includeTls13; + set => SetProtocolSelection(ref _includeTls13, value); + } + + public bool IncludeTlsAuto + { + get => _includeTlsAuto; + set => SetProtocolSelection(ref _includeTlsAuto, value); + } + + public bool IncludeQuic + { + get => _includeQuic; + set => SetProtocolSelection(ref _includeQuic, value); + } + + public bool IsHttpOnly => _includeHttp && !_includeTls12 && !_includeTls13 && !_includeTlsAuto && !_includeQuic; + + public bool IncludeIpv4 + { + get => _includeIpv4; + set => SetIpVersionSelection(ref _includeIpv4, value); + } + + public bool IncludeIpv6 + { + get => _includeIpv6; + set => SetIpVersionSelection(ref _includeIpv6, value); + } + + public int DirectTargetInputCount => _targetInput + .Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Count(); + public bool HasTargetSources => DirectTargetInputCount > 0 || _selectedSiteListCount() > 0; + public bool HasProtocolSelection => + _includeHttp || _includeTls12 || _includeTls13 || _includeTlsAuto || _includeQuic; + public bool HasIpVersionSelection => _includeIpv4 || _includeIpv6; + public bool CanContinueFromTargets => !_isRunning() && HasProtocolSelection && HasIpVersionSelection; + public bool CanStart => !_isRunning() && HasTargetSources && HasProtocolSelection && + HasIpVersionSelection && AdvancedOptionsValid; + + public double ConnectTimeoutSeconds + { + get => _connectTimeoutSeconds; + set => SetAdvancedOption(ref _connectTimeoutSeconds, value); + } + + public double RequestTimeoutSeconds + { + get => _requestTimeoutSeconds; + set => SetAdvancedOption(ref _requestTimeoutSeconds, value); + } + + public double StartupGraceSeconds + { + get => _startupGraceSeconds; + set => SetAdvancedOption(ref _startupGraceSeconds, value); + } + + public bool TestAllStrategies + { + get => _testAllStrategies; + set + { + if (_testAllStrategies == value) + { + return; + } + + _testAllStrategies = value; + Notify(); + _settings.Save(nameof(TestAllStrategies), value); + } + } + + public double RequestsPerDomain + { + get => _requestsPerDomain; + set + { + if (_requestsPerDomain.Equals(value)) + { + return; + } + + _requestsPerDomain = value; + Notify(); + Notify(nameof(AdvancedOptionsValid)); + Notify(nameof(CanStart)); + if (BlockCheck2OptionLimits.IsValidRequestsPerDomain(value)) + { + _settings.Save(nameof(RequestsPerDomain), (int)value); + } + } + } + + public bool AdvancedOptionsValid => + BlockCheck2OptionLimits.IsValidConnectTimeout(_connectTimeoutSeconds) && + BlockCheck2OptionLimits.IsValidRequestTimeout(_requestTimeoutSeconds, _connectTimeoutSeconds) && + BlockCheck2OptionLimits.IsValidStartupGrace(_startupGraceSeconds) && + BlockCheck2OptionLimits.IsValidRequestsPerDomain(_requestsPerDomain); + + public void ResetAdvancedOptions() + { + ConnectTimeoutSeconds = BlockCheck2OptionLimits.DefaultConnectTimeoutSeconds; + RequestTimeoutSeconds = BlockCheck2OptionLimits.DefaultRequestTimeoutSeconds; + StartupGraceSeconds = BlockCheck2OptionLimits.DefaultStartupGraceSeconds; + TestAllStrategies = false; + RequestsPerDomain = BlockCheckRunPresetFactory.GetRecommendedAttemptsPerTarget(_selectedRunPreset); + } + + private void LoadSettings() + { + int presetValue = _settings.ReadInt( + nameof(SelectedRunPreset), + (int)BlockCheckRunPreset.Balanced); + _selectedRunPreset = Enum.IsDefined(typeof(BlockCheckRunPreset), presetValue) + ? (BlockCheckRunPreset)presetValue + : BlockCheckRunPreset.Balanced; + + _includeHttp = _settings.ReadBool(nameof(IncludeHttp), defaultValue: false); + _includeTls12 = _settings.ReadBool(nameof(IncludeTls12), defaultValue: true); + _includeTls13 = _settings.ReadBool(nameof(IncludeTls13), defaultValue: false); + _includeTlsAuto = _settings.ReadBool(nameof(IncludeTlsAuto), defaultValue: true); + _includeQuic = _settings.ReadBool(nameof(IncludeQuic), defaultValue: false); + _includeIpv4 = _settings.ReadBool(nameof(IncludeIpv4), defaultValue: true); + _includeIpv6 = _settings.ReadBool(nameof(IncludeIpv6), defaultValue: false); + + double savedConnectTimeout = _settings.ReadDouble( + nameof(ConnectTimeoutSeconds), + BlockCheck2OptionLimits.DefaultConnectTimeoutSeconds); + _connectTimeoutSeconds = BlockCheck2OptionLimits.IsValidConnectTimeout(savedConnectTimeout) + ? savedConnectTimeout + : BlockCheck2OptionLimits.DefaultConnectTimeoutSeconds; + + double savedRequestTimeout = _settings.ReadDouble( + nameof(RequestTimeoutSeconds), + BlockCheck2OptionLimits.DefaultRequestTimeoutSeconds); + _requestTimeoutSeconds = + BlockCheck2OptionLimits.IsValidRequestTimeout(savedRequestTimeout, _connectTimeoutSeconds) + ? savedRequestTimeout + : Math.Max(BlockCheck2OptionLimits.DefaultRequestTimeoutSeconds, _connectTimeoutSeconds); + + double savedStartupGrace = _settings.ReadDouble( + nameof(StartupGraceSeconds), + BlockCheck2OptionLimits.DefaultStartupGraceSeconds); + _startupGraceSeconds = BlockCheck2OptionLimits.IsValidStartupGrace(savedStartupGrace) + ? savedStartupGrace + : BlockCheck2OptionLimits.DefaultStartupGraceSeconds; + + _testAllStrategies = _settings.ReadBool(nameof(TestAllStrategies), defaultValue: false); + int recommendedAttempts = BlockCheckRunPresetFactory.GetRecommendedAttemptsPerTarget(_selectedRunPreset); + int savedAttempts = _settings.ReadInt(nameof(RequestsPerDomain), recommendedAttempts); + _requestsPerDomain = BlockCheck2OptionLimits.IsValidRequestsPerDomain(savedAttempts) + ? savedAttempts + : recommendedAttempts; + } + + public BlockCheckSessionRequest CreateSessionRequest( + Func> createSiteLists) => new() + { + TargetInput = _targetInput, + SiteLists = createSiteLists(), + RunPreset = _selectedRunPreset, + TestAllStrategies = _testAllStrategies, + AttemptsPerTarget = (int)_requestsPerDomain, + Protocols = SelectedProtocols(), + IpVersions = SelectedIpVersions(), + }; + + private IReadOnlySet SelectedProtocols() + { + HashSet selected = []; + if (_includeHttp) + selected.Add(BlockCheckProtocol.Http); + if (_includeTls12) + selected.Add(BlockCheckProtocol.Tls12); + if (_includeTls13) + selected.Add(BlockCheckProtocol.Tls13); + if (_includeTlsAuto) + selected.Add(BlockCheckProtocol.TlsAuto); + if (_includeQuic) + selected.Add(BlockCheckProtocol.Quic); + return selected; + } + + private IReadOnlySet SelectedIpVersions() + { + HashSet selected = []; + if (_includeIpv4) + selected.Add(BlockCheckIpVersion.IPv4); + if (_includeIpv6) + selected.Add(BlockCheckIpVersion.IPv6); + return selected; + } + + private void SetProtocolSelection(ref bool field, bool value, [CallerMemberName] string? propertyName = null) + { + if (field == value) + { + return; + } + + field = value; + Notify(propertyName); + _settings.Save(propertyName, value); + Notify(nameof(IsHttpOnly)); + Notify(nameof(HasProtocolSelection)); + Notify(nameof(CanContinueFromTargets)); + Notify(nameof(CanStart)); + } + + private void SetIpVersionSelection(ref bool field, bool value, [CallerMemberName] string? propertyName = null) + { + if (field == value) + { + return; + } + + field = value; + Notify(propertyName); + _settings.Save(propertyName, value); + Notify(nameof(HasIpVersionSelection)); + Notify(nameof(CanContinueFromTargets)); + Notify(nameof(CanStart)); + } + + private void SetAdvancedOption( + ref double field, + double value, + [CallerMemberName] string? propertyName = null) + { + if (field.Equals(value)) + { + return; + } + + field = value; + Notify(propertyName); + if (double.IsFinite(value)) + { + _settings.Save(propertyName, value); + } + Notify(nameof(AdvancedOptionsValid)); + Notify(nameof(CanStart)); + } + private void Notify([CallerMemberName] string? propertyName = null) => + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); +} diff --git a/CDPIUI/ViewModels/BlockCheck2PresetDraft.cs b/CDPIUI/ViewModels/BlockCheck2PresetDraft.cs index 7b76692d..903d5748 100644 --- a/CDPIUI/ViewModels/BlockCheck2PresetDraft.cs +++ b/CDPIUI/ViewModels/BlockCheck2PresetDraft.cs @@ -1,3 +1,6 @@ +#nullable enable annotations +#nullable disable warnings + using System; using System.Collections.Generic; using System.Collections.ObjectModel; diff --git a/CDPIUI/ViewModels/BlockCheck2ProgressEstimator.cs b/CDPIUI/ViewModels/BlockCheck2ProgressEstimator.cs index cca7c950..40bca971 100644 --- a/CDPIUI/ViewModels/BlockCheck2ProgressEstimator.cs +++ b/CDPIUI/ViewModels/BlockCheck2ProgressEstimator.cs @@ -10,7 +10,7 @@ namespace CDPIUI.ViewModels; /// progress reports. Each stage has its own measurement; the overall estimate of the strategy /// stage adds the expected duration of the validation that follows it. /// -internal sealed class BlockCheck2ProgressEstimator +internal sealed class BlockCheck2ProgressEstimator : IBlockCheck2ProgressEstimator { private readonly BlockCheckRemainingTimeEstimator _remainingTimeEstimator = new(); private readonly Stopwatch _runStopwatch = new(); diff --git a/CDPIUI/ViewModels/BlockCheck2ProgressViewModel.cs b/CDPIUI/ViewModels/BlockCheck2ProgressViewModel.cs new file mode 100644 index 00000000..ff4ecdbc --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2ProgressViewModel.cs @@ -0,0 +1,177 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using CDPIUI.AddOns.BlockCheck2.Models; + +namespace CDPIUI.ViewModels; + +// Owns displayed progress; run/cancellation/report lifecycle stays with the host. +internal sealed class BlockCheck2ProgressViewModel : ObservableObject +{ + private readonly Func> _targets; + private readonly Func _validationAttempts; + private readonly Func _startupGraceSeconds; + private readonly IBlockCheck2ProgressEstimator _progressEstimator; + private BlockCheckScanPhase? _currentPhase; + private int _progressCurrent; + private int _progressTotal; + private TimeSpan? _estimatedRemainingTime; + private TimeSpan? _estimatedOverallRemainingTime; + private int _successfulChecks; + private int _failedChecks; + private int _successfulStrategies; + private string _currentTargetId = string.Empty; + private string _currentStrategyId = string.Empty; + + public BlockCheck2ProgressViewModel(Func> targets, + Func validationAttempts, Func startupGraceSeconds, + IBlockCheck2ProgressEstimator? estimator = null) + { + _targets = targets; + _validationAttempts = validationAttempts; + _startupGraceSeconds = startupGraceSeconds; + _progressEstimator = estimator ?? new BlockCheck2ProgressEstimator(); + } + + public void StartRun() => _progressEstimator.StartRun(); + + public void FinishRun() + { + _progressEstimator.StopRun(); + _estimatedRemainingTime = null; + _estimatedOverallRemainingTime = null; + Notify(nameof(EstimatedRemainingTime)); + Notify(nameof(EstimatedOverallRemainingTime)); + } + + public BlockCheckScanPhase? CurrentPhase => _currentPhase; + public int ProgressCurrent => _progressCurrent; + public int ProgressTotal => _progressTotal; + public TimeSpan? EstimatedRemainingTime => _estimatedRemainingTime; + public TimeSpan? EstimatedOverallRemainingTime => _estimatedOverallRemainingTime; + public bool IsProgressIndeterminate => _progressTotal <= 0; + public int SuccessfulChecks => _successfulChecks; + public int FailedChecks => _failedChecks; + public int CompletedChecks => _successfulChecks + _failedChecks; + public int SuccessfulStrategies => _successfulStrategies; + public double ProgressValue => _progressTotal <= 0 + ? 0d + : Math.Clamp((double)_progressCurrent / _progressTotal, 0d, 1d); + public string CurrentTargetId => _currentTargetId; + public string CurrentTargetUrl + { + get + { + BlockCheckTarget? target = CurrentTarget(); + return target == null + ? _currentTargetId + : BlockCheckTargetDisplayFormatter.FormatUrl(target); + } + } + public string CurrentTargetConnectionDetails + { + get + { + BlockCheckTarget? target = CurrentTarget(); + return target == null + ? string.Empty + : BlockCheckTargetDisplayFormatter.FormatConnectionDetails(target); + } + } + public string CurrentTargetDisplay + { + get + { + BlockCheckTarget? target = CurrentTarget(); + return target == null + ? _currentTargetId + : BlockCheckTargetDisplayFormatter.Format(target); + } + } + public string CurrentStrategyId => _currentStrategyId; + + public void Update(BlockCheckScanProgress progress) + { + _currentPhase = progress.Phase; + _progressCurrent = progress.CompletedStrategyTargets; + _progressTotal = progress.TotalStrategyTargets; + _currentTargetId = progress.TargetId; + _currentStrategyId = progress.StrategyId; + _successfulChecks = progress.SuccessfulChecks; + _failedChecks = progress.FailedChecks; + _successfulStrategies = progress.SuccessfulStrategies; + (_estimatedRemainingTime, _estimatedOverallRemainingTime) = _progressEstimator.Update( + progress, + _targets().Count, + _validationAttempts(), + _startupGraceSeconds()); + Notify(nameof(CurrentPhase)); + Notify(nameof(ProgressCurrent)); + Notify(nameof(ProgressTotal)); + Notify(nameof(ProgressValue)); + Notify(nameof(IsProgressIndeterminate)); + Notify(nameof(CurrentTargetId)); + Notify(nameof(CurrentTargetUrl)); + Notify(nameof(CurrentTargetConnectionDetails)); + Notify(nameof(CurrentTargetDisplay)); + Notify(nameof(CurrentStrategyId)); + Notify(nameof(EstimatedRemainingTime)); + Notify(nameof(EstimatedOverallRemainingTime)); + Notify(nameof(SuccessfulChecks)); + Notify(nameof(FailedChecks)); + Notify(nameof(CompletedChecks)); + Notify(nameof(SuccessfulStrategies)); + } + + // Reset all fields before the host notifies errors/results, then notify progress. + public void Reset(Action beforeNotifications) + { + _currentPhase = null; + _progressCurrent = 0; + _progressTotal = 0; + _estimatedRemainingTime = null; + _estimatedOverallRemainingTime = null; + _progressEstimator.ResetObservations(); + _successfulChecks = 0; + _failedChecks = 0; + _successfulStrategies = 0; + _currentTargetId = string.Empty; + _currentStrategyId = string.Empty; + beforeNotifications(); + Notify(nameof(CurrentPhase)); + Notify(nameof(ProgressCurrent)); + Notify(nameof(ProgressTotal)); + Notify(nameof(ProgressValue)); + Notify(nameof(IsProgressIndeterminate)); + Notify(nameof(EstimatedRemainingTime)); + Notify(nameof(EstimatedOverallRemainingTime)); + Notify(nameof(SuccessfulChecks)); + Notify(nameof(FailedChecks)); + Notify(nameof(CompletedChecks)); + Notify(nameof(SuccessfulStrategies)); + Notify(nameof(CurrentTargetId)); + Notify(nameof(CurrentTargetUrl)); + Notify(nameof(CurrentTargetConnectionDetails)); + Notify(nameof(CurrentTargetDisplay)); + Notify(nameof(CurrentStrategyId)); + } + + public void CompleteDisplayedProgress() + { + if (_progressTotal <= 0) + { + return; + } + + _progressCurrent = _progressTotal; + Notify(nameof(ProgressCurrent)); + Notify(nameof(ProgressValue)); + } + + private BlockCheckTarget? CurrentTarget() => _targets().FirstOrDefault( + item => string.Equals(item.Id, _currentTargetId, StringComparison.Ordinal)); + + private void Notify(string propertyName) => OnPropertyChanged(propertyName); +} diff --git a/CDPIUI/ViewModels/BlockCheck2ReportOperations.cs b/CDPIUI/ViewModels/BlockCheck2ReportOperations.cs new file mode 100644 index 00000000..f0df8e73 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2ReportOperations.cs @@ -0,0 +1,35 @@ +#nullable enable + +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.AddOns.BlockCheck2.Reporting; + +namespace CDPIUI.ViewModels; + +// Keeps the existing report services and their export/error behavior at the boundary. +internal sealed class BlockCheck2ReportOperations : IBlockCheck2ReportOperations +{ + private readonly BlockCheckReportBuilder _builder; + private readonly BlockCheckReportSerializer _serializer; + + public BlockCheck2ReportOperations(BlockCheckReportBuilder builder, BlockCheckReportSerializer serializer) + { + _builder = builder; + _serializer = serializer; + } + + public BlockCheckReport Build(StrategyCatalog catalog, BlockCheckRunPreset preset, + IReadOnlyList targets, BlockCheckRunResult result) => + _builder.Build(catalog, preset, targets, result); + public string SerializeJson(BlockCheckReport report) => _serializer.SerializeJson(report); + public string SerializeText(BlockCheckReport report) => _serializer.SerializeText(report); + public Task SaveJsonAsync(string path, BlockCheckReport report, CancellationToken token) => + _serializer.SaveJsonAsync(path, report, token); + public Task SaveTextAsync(string path, BlockCheckReport report, CancellationToken token) => + _serializer.SaveTextAsync(path, report, token); + public Task SavePresetArgumentsAsync(string path, BlockCheckReport report, CancellationToken token) => + _serializer.SavePresetArgumentsAsync(path, report, token); +} diff --git a/CDPIUI/ViewModels/BlockCheck2ResultViewModel.cs b/CDPIUI/ViewModels/BlockCheck2ResultViewModel.cs index 8543c875..78cdb7c5 100644 --- a/CDPIUI/ViewModels/BlockCheck2ResultViewModel.cs +++ b/CDPIUI/ViewModels/BlockCheck2ResultViewModel.cs @@ -17,7 +17,7 @@ namespace CDPIUI.ViewModels; -public sealed class BlockCheck2ResultViewModel : ObservableObject +public sealed class BlockCheck2ResultViewModel : ObservableObject, IBlockCheck2ManualPresetHost { private readonly BlockCheckManualPresetService _manualPresetService = new(); private readonly BlockCheckManualStrategyTestService _manualTestService = new(); @@ -25,9 +25,10 @@ public sealed class BlockCheck2ResultViewModel : ObservableObject private BlockCheckResultSession? _session; private IReadOnlyList _allStrategyEvidence = []; private readonly List _manualTestResults = []; - private readonly HashSet _automaticAssignmentKeys = new(StringComparer.OrdinalIgnoreCase); + private readonly BlockCheck2ManualAssignmentEditor _assignmentEditor; private readonly HashSet _acknowledgedManualIssueKeys = new(StringComparer.Ordinal); - private BlockCheckManualPresetResult? _manualPreset; + private readonly BlockCheck2ManualPresetState _manualPresetState; + private readonly BlockCheck2ManualStrategyTestController _manualStrategyTest; public ObservableCollection Profiles { get; } = []; public ObservableCollection Probes { get; } = []; @@ -51,7 +52,7 @@ public sealed class BlockCheck2ResultViewModel : ObservableObject public bool HasManualAssignments => ManualAssignments.Count > 0; public bool CanUseConfig => Draft.CanUseConfig; public string PresetArguments => _report?.PresetArguments ?? string.Empty; - public string ManualPresetArguments => _manualPreset?.Configuration.CommandLine ?? string.Empty; + public string ManualPresetArguments => _manualPresetState.Arguments; public string EffectivePresetArguments => Draft.EffectiveArguments; public int TargetCount => _report?.Targets.Count ?? 0; public int ProfileCount => _report?.Profiles.Count ?? 0; @@ -67,6 +68,13 @@ public sealed class BlockCheck2ResultViewModel : ObservableObject public BlockCheck2ResultViewModel() { + _manualPresetState = new BlockCheck2ManualPresetState(Draft, _manualTestResults, this, + new BlockCheck2ManualPresetOperations(_manualPresetService)); + _manualStrategyTest = new BlockCheck2ManualStrategyTestController(Draft, _manualTestResults, + () => _session, RebuildManualPreset, new BlockCheck2ManualStrategyTestOperations(_manualTestService)); + _assignmentEditor = new BlockCheck2ManualAssignmentEditor(Draft, + () => _session, () => _allStrategyEvidence, + () => _acknowledgedManualIssueKeys.Clear(), RebuildManualPreset); Draft.PropertyChanged += (_, args) => { if (args.PropertyName is nameof(BlockCheck2PresetDraft.EffectiveArguments) or @@ -86,13 +94,13 @@ public void Load(BlockCheckReport value) _session = null; _allStrategyEvidence = []; _manualTestResults.Clear(); - _automaticAssignmentKeys.Clear(); + _assignmentEditor.ClearAutomaticKeys(); _acknowledgedManualIssueKeys.Clear(); StrategyEvidence.Clear(); StrategyGroups.Clear(); ManualAssignments.Clear(); ManualIssues.Clear(); - _manualPreset = null; + _manualPresetState.ClearResult(); Draft.LoadAutomatic(value.PresetArguments, value.Profiles); Profiles.Clear(); foreach (BlockCheckReportProfile profile in value.Profiles) @@ -183,69 +191,20 @@ public void ApplyStrategyView(string? searchText, int sortMode, int filterMode) Notify(nameof(VisibleStrategyEvidenceCount)); } - public bool AddForSite(BlockCheck2StrategyEvidenceItem item) => - AddAssignment(new BlockCheckManualAssignment( - item.StrategyId, - item.TargetId, - BlockCheckManualScopeKind.Site)); + public bool AddForSite(BlockCheck2StrategyEvidenceItem item) => _assignmentEditor.AddForSite(item); - public bool AddForSiteList(BlockCheck2StrategyEvidenceItem item, string siteListPath) - { - BlockCheckTarget? anchor = FindCompatibleSiteListTargets(item) - .FirstOrDefault(target => target.HostListPaths.Contains( - siteListPath, - StringComparer.OrdinalIgnoreCase)); - return anchor != null && AddAssignment(new BlockCheckManualAssignment( - item.StrategyId, - anchor.Id, - BlockCheckManualScopeKind.SiteList, - siteListPath)); - } + public bool AddForSiteList(BlockCheck2StrategyEvidenceItem item, string siteListPath) => + _assignmentEditor.AddForSiteList(item, siteListPath); - public void RemoveAssignment(BlockCheck2ManualAssignmentItem item) - { - int index = ManualAssignments.IndexOf(item); - if (index < 0) - { - return; - } - _acknowledgedManualIssueKeys.Clear(); - ManualAssignments.RemoveAt(index); - RebuildManualPreset(updateDraft: true); - } + public void RemoveAssignment(BlockCheck2ManualAssignmentItem item) => _assignmentEditor.RemoveAssignment(item); - public bool MoveAssignment(BlockCheck2ManualAssignmentItem item, int offset) - { - int oldIndex = ManualAssignments.IndexOf(item); - int newIndex = oldIndex + offset; - if (oldIndex < 0 || newIndex < 0 || newIndex >= ManualAssignments.Count) - { - return false; - } - _acknowledgedManualIssueKeys.Clear(); - ManualAssignments.Move(oldIndex, newIndex); - RebuildManualPreset(updateDraft: true); - return true; - } + public bool MoveAssignment(BlockCheck2ManualAssignmentItem item, int offset) => _assignmentEditor.MoveAssignment(item, offset); - public void ClearManualAssignments() - { - _acknowledgedManualIssueKeys.Clear(); - ManualAssignments.Clear(); - RebuildManualPreset(updateDraft: true); - } + public void ClearManualAssignments() => _assignmentEditor.ClearManualAssignments(); - public IReadOnlyList GetSiteListPaths(BlockCheck2StrategyEvidenceItem item) => - FindCompatibleSiteListTargets(item) - .SelectMany(target => target.HostListPaths) - .Where(path => !string.IsNullOrWhiteSpace(path)) - .Distinct(StringComparer.OrdinalIgnoreCase) - .OrderBy(path => Path.GetFileName(path), StringComparer.CurrentCultureIgnoreCase) - .ThenBy(path => path, StringComparer.CurrentCultureIgnoreCase) - .ToArray(); + public IReadOnlyList GetSiteListPaths(BlockCheck2StrategyEvidenceItem item) => _assignmentEditor.GetSiteListPaths(item); - public bool CanAddForSiteList(BlockCheck2StrategyEvidenceItem item) => - FindCompatibleSiteListTargets(item).Any(); + public bool CanAddForSiteList(BlockCheck2StrategyEvidenceItem item) => _assignmentEditor.CanAddForSiteList(item); public bool ApplyManualIssueQuickFix(BlockCheck2ManualIssueItem item) { @@ -261,287 +220,34 @@ public bool ApplyManualIssueQuickFix(BlockCheck2ManualIssueItem item) } public OperationResultModel GetFullStrategyArguments( - BlockCheck2StrategyEvidenceItem item) - { - return _manualTestService.GetFullStrategyArguments( - item.Evidence.Strategy, - item.Evidence.Target, - new BlockCheckManualStrategyTestOptions - { - Attempts = Math.Max(1, _session.RunOptions.Scan.AttemptsPerTarget), - }); - } + BlockCheck2StrategyEvidenceItem item) => _manualStrategyTest.GetFullStrategyArguments(item); - public async Task TestStrategyAsync( + public Task TestStrategyAsync( BlockCheck2StrategyEvidenceItem item, - CancellationToken cancellationToken = default) - { - if (_session == null) - { - return new BlockCheckManualStrategyTestResult - { - Issues = - [ - new BlockCheckIssue( - BlockCheckIssueSeverity.Error, - "MANUAL_SESSION_UNAVAILABLE", - "The original BlockCheck session is unavailable; this report cannot launch a live strategy test."), - ], - }; - } + CancellationToken cancellationToken = default) => _manualStrategyTest.TestStrategyAsync(item, cancellationToken); - BlockCheckManualStrategyTestResult result = await _manualTestService - .TestWithCdpiuiAdaptersAsync( - item.Evidence.Strategy, - item.Evidence.Target, - new BlockCheckManualStrategyTestOptions - { - Attempts = Math.Max(1, _session.RunOptions.Scan.AttemptsPerTarget), - }, - new CdpiuiZapret2StrategyRunnerOptions - { - StartupGracePeriod = _session.StartupGracePeriod, - }, - new CurlBlockCheckProbeRunnerOptions - { - ConnectTimeout = _session.ConnectTimeout, - RequestTimeout = _session.RequestTimeout, - }, - cancellationToken) - .ConfigureAwait(true); - if (result.ProbeResult != null) - { - _manualTestResults.RemoveAll(probe => - string.Equals(probe.StrategyId, result.ProbeResult.StrategyId, StringComparison.OrdinalIgnoreCase) && - string.Equals(probe.TargetId, result.ProbeResult.TargetId, StringComparison.Ordinal)); - _manualTestResults.Add(result.ProbeResult); - item.ApplyTestResult(result.ProbeResult); - RebuildManualPreset(updateDraft: !Draft.IsAutomatic); - } - return result; - } + private void RebuildManualPreset(bool updateDraft) => _manualPresetState.Rebuild(updateDraft); - private bool AddAssignment(BlockCheckManualAssignment assignment) + BlockCheckResultSession? IBlockCheck2ManualPresetHost.Session => _session; + void IBlockCheck2ManualPresetHost.ClearIssues() => ManualIssues.Clear(); + void IBlockCheck2ManualPresetHost.RefreshAssignmentIndexes() => RefreshAssignmentIndexes(); + void IBlockCheck2ManualPresetHost.RefreshEvidenceSelections() => RefreshEvidenceSelections(); + void IBlockCheck2ManualPresetHost.NotifyManualState() => NotifyManualState(); + void IBlockCheck2ManualPresetHost.AddIssueGroup(BlockCheckIssueSeverity severity, string code, + string message, int count, IEnumerable subjects) { - if (_session == null) + BlockCheck2ManualIssueItem item = new(severity, code, message, count, subjects); + if (!_acknowledgedManualIssueKeys.Contains(item.Key)) { - return false; - } - bool duplicate = ManualAssignments.Any(item => - string.Equals(item.Assignment.StrategyId, assignment.StrategyId, StringComparison.OrdinalIgnoreCase) && - string.Equals(item.Assignment.AnchorTargetId, assignment.AnchorTargetId, StringComparison.Ordinal) && - item.Assignment.ScopeKind == assignment.ScopeKind && - string.Equals(item.Assignment.SiteListPath, assignment.SiteListPath, StringComparison.OrdinalIgnoreCase)); - if (duplicate) - { - return false; + ManualIssues.Add(item); } - - StrategyDefinition? strategy = _session.Catalog.Strategies.FirstOrDefault(candidate => - string.Equals(candidate.Id, assignment.StrategyId, StringComparison.OrdinalIgnoreCase)); - BlockCheckTarget? target = _session.Targets.FirstOrDefault(candidate => - string.Equals(candidate.Id, assignment.AnchorTargetId, StringComparison.Ordinal)); - if (strategy == null || target == null) - { - return false; - } - _acknowledgedManualIssueKeys.Clear(); - AddAssignmentCore(assignment, strategy, target); - RebuildManualPreset(updateDraft: true); - return true; } - private void AddAssignmentCore( - BlockCheckManualAssignment assignment, - StrategyDefinition strategy, - BlockCheckTarget target) - { - ManualAssignments.Add(new BlockCheck2ManualAssignmentItem( - assignment, - strategy, - target, - new Zapret2ConfigWriter().FormatStrategyActions(strategy))); - } + private void SeedAutomaticAssignments(BlockCheckResultSession value) => _assignmentEditor.SeedAutomaticAssignments(value); - private void RebuildManualPreset(bool updateDraft) - { - ManualIssues.Clear(); - if (_session == null || ManualAssignments.Count == 0) - { - _manualPreset = null; - RefreshAssignmentIndexes(); - if (updateDraft) - { - Draft.ApplyStructuredChange(string.Empty, []); - } - RefreshEvidenceSelections(); - NotifyManualState(); - return; - } + private void RefreshEvidenceSelections() => _assignmentEditor.RefreshEvidenceSelections(); - IEnumerable evidence = _session.RunResult.Scan.ProbeResults - .Where(result => !_manualTestResults.Any(test => - string.Equals(test.StrategyId, result.StrategyId, StringComparison.OrdinalIgnoreCase) && - string.Equals(test.TargetId, result.TargetId, StringComparison.Ordinal))) - .Concat(_manualTestResults); - _manualPreset = _manualPresetService.Build( - _session.Catalog, - _session.Targets.Where(target => !_session.RunResult.Scan.IgnoredTargetIds.Contains(target.Id)), - ManualAssignments.Select(item => item.Assignment), - evidence, - ManualOptions(_session)); - foreach (var group in _manualPreset.Issues.GroupBy(issue => new - { - issue.Severity, - issue.Code, - issue.Message, - })) - { - BlockCheck2ManualIssueItem item = new( - group.Key.Severity, - group.Key.Code, - group.Key.Message, - group.Count(), - group.Select(issue => DescribeManualIssueSubject(issue.SubjectId))); - if (!_acknowledgedManualIssueKeys.Contains(item.Key)) - { - ManualIssues.Add(item); - } - } - if (updateDraft) - { - Draft.ApplyStructuredChange( - _manualPreset.Configuration.CommandLine, - _manualPreset.Profiles); - } - RefreshAssignmentIndexes(); - RefreshEvidenceSelections(); - NotifyManualState(); - } - - private string DescribeManualIssueSubject(string? subjectId) - { - if (string.IsNullOrWhiteSpace(subjectId)) - { - return string.Empty; - } - - BlockCheck2ManualAssignmentItem? scopeAssignment = ManualAssignments.FirstOrDefault(item => - string.Equals(BlockCheck2ManualAssignmentRules.ManualScopeKey(item), subjectId, StringComparison.OrdinalIgnoreCase)); - if (scopeAssignment != null) - { - return $"{scopeAssignment.Scope} · {scopeAssignment.ConnectionDetails}"; - } - - BlockCheck2ManualAssignmentItem? assignment = ManualAssignments.FirstOrDefault(item => - string.Equals(item.Assignment.StrategyId, subjectId, StringComparison.OrdinalIgnoreCase)); - if (assignment != null) - { - return BlockCheck2ManualAssignmentRules.DescribeStrategySubject(assignment, subjectId); - } - - string[] strategyIds = subjectId.Split('/', StringSplitOptions.RemoveEmptyEntries); - if (strategyIds.Length > 1) - { - string[] strategyNames = strategyIds - .Select(strategyId => - { - BlockCheck2ManualAssignmentItem? item = ManualAssignments.FirstOrDefault(candidate => - string.Equals( - candidate.Assignment.StrategyId, - strategyId, - StringComparison.OrdinalIgnoreCase)); - return item == null - ? strategyId - : BlockCheck2ManualAssignmentRules.DescribeStrategySubject(item, strategyId); - }) - .ToArray(); - return string.Join(" / ", strategyNames); - } - - return subjectId; - } - - private IEnumerable FindCompatibleSiteListTargets( - BlockCheck2StrategyEvidenceItem item) - { - if (_session == null) - { - return []; - } - - BlockCheckTarget source = item.Evidence.Target; - string host = BlockCheckTarget.NormalizeHost(source.Host); - return _session.Targets.Where(target => - !_session.RunResult.Scan.IgnoredTargetIds.Contains(target.Id) && - BlockCheck2ManualAssignmentRules.IsCompatibleSiteListTarget(target, source, host)); - } - - private void SeedAutomaticAssignments(BlockCheckResultSession value) - { - _acknowledgedManualIssueKeys.Clear(); - ManualAssignments.Clear(); - Dictionary strategies = value.Catalog.Strategies - .ToDictionary(strategy => strategy.Id, StringComparer.OrdinalIgnoreCase); - Dictionary targets = value.Targets - .ToDictionary(target => target.Id, StringComparer.Ordinal); - - foreach (BlockCheckReportProfile profile in value.Report.Profiles) - { - BlockCheckTarget[] profileTargets = profile.TargetIds - .Select(id => targets.GetValueOrDefault(id)) - .Where(target => target != null) - .Cast() - .ToArray(); - IEnumerable<(BlockCheckTarget Target, BlockCheckManualScopeKind Scope, string? Path)> scopes = - BlockCheck2ManualAssignmentRules.GetAutomaticScopes(profile, profileTargets); - - foreach ((BlockCheckTarget target, BlockCheckManualScopeKind scope, string? path) in scopes) - { - foreach (string strategyId in new[] { profile.PrimaryStrategyId }.Concat(profile.FallbackStrategyIds)) - { - if (!strategies.TryGetValue(strategyId, out StrategyDefinition? strategy)) - { - continue; - } - BlockCheckManualAssignment assignment = new(strategyId, target.Id, scope, path); - bool duplicate = ManualAssignments.Any(item => item.Assignment == assignment); - if (!duplicate) - { - AddAssignmentCore(assignment, strategy, target); - _automaticAssignmentKeys.Add(BlockCheck2ManualAssignmentRules.AssignmentKey(assignment)); - } - } - } - } - - RebuildManualPreset(updateDraft: false); - Draft.LoadAutomatic(value.Report.PresetArguments, value.Report.Profiles); - RefreshAssignmentIndexes(); - RefreshEvidenceSelections(); - } - - private void RefreshEvidenceSelections() - { - foreach (BlockCheck2StrategyEvidenceItem evidence in _allStrategyEvidence) - { - BlockCheck2ManualAssignmentItem[] selectedAssignments = ManualAssignments - .Where(item => BlockCheck2ManualAssignmentRules.AssignmentMatchesEvidence(item, evidence)) - .ToArray(); - bool selected = selectedAssignments.Length > 0; - bool automatic = selectedAssignments.Any(item => - _automaticAssignmentKeys.Contains(BlockCheck2ManualAssignmentRules.AssignmentKey(item.Assignment))); - evidence.SetSelection(selected, automatic); - } - } - - private void RefreshAssignmentIndexes() - { - for (int index = 0; index < ManualAssignments.Count; index++) - { - ManualAssignments[index].SetOrder(index + 1); - } - } + private void RefreshAssignmentIndexes() => _assignmentEditor.RefreshAssignmentIndexes(); private void NotifyManualState() { @@ -555,11 +261,8 @@ private void NotifyManualState() Notify(nameof(ManualAssignmentCount)); } - private static BlockCheckManualPresetOptions ManualOptions(BlockCheckResultSession session) => new() - { - MinimumAttempts = Math.Max(1, session.RunOptions.Synthesis.MinimumAttempts), - MinimumSuccessRate = session.RunOptions.Synthesis.MinimumSuccessRate, - }; + private static BlockCheckManualPresetOptions ManualOptions(BlockCheckResultSession session) => + BlockCheck2ManualPresetState.OptionsFor(session); private void Notify([CallerMemberName] string? propertyName = null) => OnPropertyChanged(propertyName); } diff --git a/CDPIUI/ViewModels/BlockCheck2RunController.cs b/CDPIUI/ViewModels/BlockCheck2RunController.cs new file mode 100644 index 00000000..9c995c60 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2RunController.cs @@ -0,0 +1,98 @@ +#nullable enable + +using System; +using System.Threading; +using System.Threading.Tasks; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; + +namespace CDPIUI.ViewModels; + +internal sealed class BlockCheck2RunController +{ + private readonly IBlockCheck2RunHost _host; + private CancellationTokenSource? _cancellation; + + public BlockCheck2RunController(IBlockCheck2RunHost host) => _host = host; + + public async Task StartAsync() + { + if (!_host.CanStart) + { + return null; + } + + if (_host.LastReport != null) + { + _host.RenewGeneratedSiteListRoot(); + } + _host.ResetResultState(); + _host.StartProgress(); + CancellationTokenSource? runCancellation = null; + try + { + BlockCheckSessionPreparationResult prepared = _host.Prepare(); + _host.ApplyPrepared(prepared); + if (!prepared.Success) + { + _host.SetState(BlockCheckSessionState.InputInvalid); + return null; + } + + runCancellation = new CancellationTokenSource(); + _cancellation = runCancellation; + _host.SetState(BlockCheckSessionState.Running); + BlockCheckRunResult result = await _host.RunPreparedAsync(prepared, runCancellation.Token); + + _host.ApplyRunResult(prepared, result); + _host.CompleteDisplayedProgress(); + BlockCheckSessionState finalState = GetFinalState(result); + // Publishing the final state permits a new run, so history must finish first. + await _host.SaveReportToHistoryAsync(_host.LastReport!); + _host.SetState(finalState); + return result; + } + catch (OperationCanceledException) + { + _host.SetState(BlockCheckSessionState.Canceled); + return null; + } + catch (Exception exception) + { + _host.SetOperationError(exception.Message); + _host.SetState(BlockCheckSessionState.Failed); + return null; + } + finally + { + _host.FinishProgress(); + runCancellation?.Dispose(); + if (ReferenceEquals(_cancellation, runCancellation)) + { + _cancellation = null; + } + _host.CleanupGeneratedSiteListsIfUnviewable(); + _host.NotifyActionState(); + } + } + + public void Cancel() + { + if (!_host.CanCancel || _cancellation == null) + { + return; + } + + _host.SetState(BlockCheckSessionState.Canceling); + _cancellation.Cancel(); + } + + private static BlockCheckSessionState GetFinalState(BlockCheckRunResult result) => + result.WasCanceled + ? BlockCheckSessionState.Canceled + : result.Success + ? BlockCheckSessionState.Completed + : result.Synthesis?.IsBestEffort == true + ? BlockCheckSessionState.CompletedWithWarnings + : BlockCheckSessionState.Failed; +} diff --git a/CDPIUI/ViewModels/BlockCheck2RunResultViewModel.cs b/CDPIUI/ViewModels/BlockCheck2RunResultViewModel.cs new file mode 100644 index 00000000..83fcda62 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2RunResultViewModel.cs @@ -0,0 +1,125 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.AddOns.BlockCheck2.Reporting; + +namespace CDPIUI.ViewModels; + +// Owns result presentation; BlockCheck2RunController owns the run and cancellation lifecycle. +internal sealed class BlockCheck2RunResultViewModel : ObservableObject +{ + private readonly IBlockCheck2ReportOperations _reports; + private readonly BlockCheck2OptionsViewModel _options; + private string? _operationError; + private string? _historySaveError; + private IReadOnlyList _issues = []; + private BlockCheckRunResult? _lastResult; + private BlockCheckReport? _lastReport; + private BlockCheckResultSession? _lastSession; + + public BlockCheck2RunResultViewModel(IBlockCheck2ReportOperations reports, BlockCheck2OptionsViewModel options) + { + _reports = reports; + _options = options; + } + + public string? OperationError => _operationError; + public string? HistorySaveError => _historySaveError; + public IReadOnlyList Issues => _issues; + public BlockCheckRunResult? LastResult => _lastResult; + public BlockCheckReport? LastReport => _lastReport; + public BlockCheckResultSession? LastSession => _lastSession; + public bool NoBypassRequired => _lastReport?.Issues.Any(issue => + string.Equals(issue.Code, "NO_BYPASS_REQUIRED", StringComparison.Ordinal)) == true; + public bool LastReportIsHttpOnly => _lastReport?.Targets.Count > 0 && + _lastReport.Targets.All(target => target.Protocol == BlockCheckProtocol.Http); + public string ReportJson => _lastReport == null ? string.Empty : _reports.SerializeJson(_lastReport); + public string ReportText => _lastReport == null ? string.Empty : _reports.SerializeText(_lastReport); + public string PresetArguments => _lastReport?.PresetArguments ?? string.Empty; + public bool CanExportReport => _lastReport != null; + public bool CanExportPreset => (_lastReport?.Success == true || _lastReport?.IsBestEffort == true) && + !string.IsNullOrWhiteSpace(_lastReport.PresetArguments); + + // The host publishes Targets and TargetCount before the matching Issues notification. + public void SetPreparedIssues(IReadOnlyList issues) => _issues = issues; + + public void SetOperationError(string message) + { + _operationError = message; + OnPropertyChanged(nameof(OperationError)); + } + + public void SetHistorySaveError(string message) + { + _historySaveError = message; + OnPropertyChanged(nameof(HistorySaveError)); + } + + public void ApplyRunResult(BlockCheckSessionPreparationResult prepared, BlockCheckRunResult result) + { + _lastResult = result; + _lastReport = _reports.Build(prepared.Catalog, _options.SelectedRunPreset, prepared.Targets, result); + _lastSession = new BlockCheckResultSession + { + Catalog = prepared.Catalog, + Targets = prepared.Targets, + RunOptions = prepared.RunOptions, + RunResult = result, + Report = _lastReport, + ConnectTimeout = TimeSpan.FromSeconds(_options.ConnectTimeoutSeconds), + RequestTimeout = TimeSpan.FromSeconds(_options.RequestTimeoutSeconds), + StartupGracePeriod = TimeSpan.FromSeconds(_options.StartupGraceSeconds), + }; + _issues = _lastReport.Issues; + NotifyResult(); + } + + public Task SaveReportJsonAsync(string filePath, CancellationToken cancellationToken = default) => + _reports.SaveJsonAsync(filePath, + _lastReport ?? throw new InvalidOperationException("No BlockCheck2 report is available."), cancellationToken); + + public Task SaveReportTextAsync(string filePath, CancellationToken cancellationToken = default) => + _reports.SaveTextAsync(filePath, + _lastReport ?? throw new InvalidOperationException("No BlockCheck2 report is available."), cancellationToken); + + public Task SavePresetArgumentsAsync(string filePath, CancellationToken cancellationToken = default) => + _reports.SavePresetArgumentsAsync(filePath, + _lastReport ?? throw new InvalidOperationException("No BlockCheck2 report is available."), cancellationToken); + + public void Reset(Action resetProgress) + { + _operationError = null; + _historySaveError = null; + _issues = []; + _lastResult = null; + _lastReport = null; + _lastSession = null; + resetProgress(() => + { + OnPropertyChanged(nameof(OperationError)); + OnPropertyChanged(nameof(HistorySaveError)); + NotifyResult(); + }); + } + + private void NotifyResult() + { + OnPropertyChanged(nameof(Issues)); + OnPropertyChanged(nameof(LastResult)); + OnPropertyChanged(nameof(LastReport)); + OnPropertyChanged(nameof(LastSession)); + OnPropertyChanged(nameof(NoBypassRequired)); + OnPropertyChanged(nameof(LastReportIsHttpOnly)); + OnPropertyChanged(nameof(ReportJson)); + OnPropertyChanged(nameof(ReportText)); + OnPropertyChanged(nameof(PresetArguments)); + OnPropertyChanged(nameof(CanExportReport)); + OnPropertyChanged(nameof(CanExportPreset)); + } +} diff --git a/CDPIUI/ViewModels/BlockCheck2SiteListBackend.cs b/CDPIUI/ViewModels/BlockCheck2SiteListBackend.cs new file mode 100644 index 00000000..f1a575f1 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2SiteListBackend.cs @@ -0,0 +1,26 @@ +#nullable enable + +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using CDPIUI.AddOns.GoodCheck; +using WinUI3Localizer; + +namespace CDPIUI.ViewModels; + +internal sealed class BlockCheck2SiteListBackend : IBlockCheck2SiteListBackend +{ + public Task> LoadAvailableAsync() => SiteListHelper.GetAllAvailableSiteListTemplatesAsync(); + public bool IsLegacyGenerated(string path) => BlockCheck2SiteListStorage.IsLegacyGeneratedSiteList(path); + public BlockCheck2SiteListItem Create(string displayName, string sourceName, string path, bool isCustom, string? editableContent, string root) => + new(displayName, sourceName, path, isCustom, editableContent, individualSiteListRoot: root); + public string Normalize(string content) => BlockCheck2SiteListStorage.NormalizeCustomContent(content); + public string CreateCustomPath() => BlockCheck2SiteListStorage.CreateCustomSiteListPath(); + public Task WriteAsync(string path, string normalized, CancellationToken token) => BlockCheck2SiteListStorage.WriteCustomSiteListAsync(path, normalized, token); + public string Text(string key) => Localizer.Get().GetLocalizedString(key); + public string GetFilePath(BlockCheck2SiteListItem item) => item.FilePath; + public string GetDisplayName(BlockCheck2SiteListItem item) => item.DisplayName; + public int GetDomainCount(BlockCheck2SiteListItem item) => item.DomainCount; + public bool IsCustom(BlockCheck2SiteListItem item) => item.IsCustom; + public void UpdateCustom(BlockCheck2SiteListItem item, string content) => item.UpdateCustomContent(content); +} diff --git a/CDPIUI/ViewModels/BlockCheck2SiteListController.cs b/CDPIUI/ViewModels/BlockCheck2SiteListController.cs new file mode 100644 index 00000000..19d7037d --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2SiteListController.cs @@ -0,0 +1,133 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using CDPIUI.AddOns.GoodCheck; + +namespace CDPIUI.ViewModels; + +// Owns list loading and selection; actual UI rows and storage stay behind the backend. +internal sealed class BlockCheck2SiteListController : ObservableObject where TItem : class +{ + private readonly ObservableCollection _available; + private readonly ObservableCollection _selected; + private readonly IBlockCheck2SiteListBackend _backend; + private readonly Func _generatedRoot; + private readonly Action _selectionChanged; + private bool _siteListsLoaded; + private bool _isSiteListLoading; + private string? _siteListLoadError; + + public BlockCheck2SiteListController(ObservableCollection available, ObservableCollection selected, + IBlockCheck2SiteListBackend backend, Func generatedRoot, Action selectionChanged) + { + _available = available; _selected = selected; _backend = backend; + _generatedRoot = generatedRoot; _selectionChanged = selectionChanged; + } + + public bool IsSiteListLoading => _isSiteListLoading; + public string? SiteListLoadError => _siteListLoadError; + public int SelectedSiteListCount => _selected.Count; + public int SelectedDomainCount => _selected.Sum(item => _backend.GetDomainCount(item)); + + public async Task LoadAsync() + { + if (_siteListsLoaded || _isSiteListLoading) + return; + + _isSiteListLoading = true; + _siteListLoadError = null; + OnPropertyChanged(nameof(IsSiteListLoading)); + OnPropertyChanged(nameof(SiteListLoadError)); + try + { + List items = await _backend.LoadAvailableAsync(); + _available.Clear(); + foreach (SiteListElement item in items + .Where(item => !string.IsNullOrWhiteSpace(item.Directory)) + .Where(item => !_backend.IsLegacyGenerated(item.Directory!)) + .OrderBy(item => item.PackName, StringComparer.CurrentCultureIgnoreCase) + .ThenBy(item => item.Name, StringComparer.CurrentCultureIgnoreCase)) + { + TItem siteListItem = _backend.Create( + item.Name ?? Path.GetFileName(item.Directory!) ?? "site-list.txt", + item.PackName ?? string.Empty, + item.Directory!, false, null, _generatedRoot()); + if (_backend.GetDomainCount(siteListItem) > 0 && !_backend.GetDisplayName(siteListItem).Contains("exclude")) + _available.Add(siteListItem); + } + _siteListsLoaded = true; + } + catch (Exception exception) + { + _siteListLoadError = exception.Message; + OnPropertyChanged(nameof(SiteListLoadError)); + } + finally + { + _isSiteListLoading = false; + OnPropertyChanged(nameof(IsSiteListLoading)); + } + } + + public TItem AddCustom(string filePath, string sourceName) + { + string fullPath = Path.GetFullPath(filePath); + TItem? existing = _available.Concat(_selected).FirstOrDefault(item => string.Equals( + _backend.GetFilePath(item), fullPath, StringComparison.OrdinalIgnoreCase)); + if (existing != null) + return existing; + return _backend.Create(Path.GetFileName(fullPath), sourceName, fullPath, false, null, _generatedRoot()); + } + + public async Task UpdateCustomAsync(string content, string displayName, string sourceName, CancellationToken cancellationToken = default) + { + string normalizedContent = _backend.Normalize(content); + if (normalizedContent.Length == 0) + throw new InvalidDataException(_backend.Text("BlockCheck2CustomSiteListEmpty")); + + TItem? item = _selected.FirstOrDefault(candidate => _backend.IsCustom(candidate)); + string filePath = (item == null ? null : _backend.GetFilePath(item)) ?? _backend.CreateCustomPath(); + await _backend.WriteAsync(filePath, normalizedContent, cancellationToken); + if (item == null) + { + item = _backend.Create(displayName, sourceName, filePath, true, normalizedContent, _generatedRoot()); + _selected.Insert(0, item); + } + else + { + _backend.UpdateCustom(item, normalizedContent); + } + _selectionChanged(); + return item; + } + + public void Select(TItem item) + { + ArgumentNullException.ThrowIfNull(item); + if (_selected.Any(selected => string.Equals(_backend.GetFilePath(selected), _backend.GetFilePath(item), StringComparison.OrdinalIgnoreCase))) + return; + _selected.Add(item); + _selectionChanged(); + } + + public void Remove(TItem item) + { + ArgumentNullException.ThrowIfNull(item); + if (_selected.Remove(item)) + _selectionChanged(); + } + + public void SetSelected(IEnumerable selected) + { + _selected.Clear(); + foreach (TItem item in selected.DistinctBy(item => _backend.GetFilePath(item), StringComparer.OrdinalIgnoreCase)) + _selected.Add(item); + _selectionChanged(); + } +} diff --git a/CDPIUI/ViewModels/BlockCheck2ViewModel.Options.cs b/CDPIUI/ViewModels/BlockCheck2ViewModel.Options.cs index 985d1270..a216f8ec 100644 --- a/CDPIUI/ViewModels/BlockCheck2ViewModel.Options.cs +++ b/CDPIUI/ViewModels/BlockCheck2ViewModel.Options.cs @@ -1,323 +1,109 @@ -using System; using System.Collections.Generic; using System.Linq; -using System.Runtime.CompilerServices; -using CDPIUI.AddOns.BlockCheck2.Models; using CDPIUI.AddOns.BlockCheck2.Presentation; namespace CDPIUI.ViewModels; +// Retains the page's binding API; options own state, validation and settings independently. public sealed partial class BlockCheck2ViewModel { - private string _targetInput = string.Empty; - private BlockCheckRunPreset _selectedRunPreset = BlockCheckRunPreset.Balanced; - private bool _includeHttp; - private bool _includeTls12 = true; - private bool _includeTls13; - private bool _includeTlsAuto = true; - private bool _includeQuic; - private bool _includeIpv4 = true; - private bool _includeIpv6; - private double _connectTimeoutSeconds = BlockCheck2OptionLimits.DefaultConnectTimeoutSeconds; - private double _requestTimeoutSeconds = BlockCheck2OptionLimits.DefaultRequestTimeoutSeconds; - private double _startupGraceSeconds = BlockCheck2OptionLimits.DefaultStartupGraceSeconds; - private bool _testAllStrategies; - private double _requestsPerDomain = 3d; - - public IReadOnlyList AvailableRunPresets { get; } = - Enum.GetValues(); + private readonly BlockCheck2OptionsViewModel _options; public string TargetInput { - get => _targetInput; - set - { - if (_targetInput == value) - { - return; - } - - _targetInput = value ?? string.Empty; - Notify(); - Notify(nameof(DirectTargetInputCount)); - Notify(nameof(HasTargetSources)); - Notify(nameof(CanStart)); - } + get => _options.TargetInput; + set => _options.TargetInput = value; } public BlockCheckRunPreset SelectedRunPreset { - get => _selectedRunPreset; - set - { - if (_selectedRunPreset == value) - { - return; - } - - _selectedRunPreset = value; - Notify(); - BlockCheck2SettingsStore.Save(nameof(SelectedRunPreset), (int)value); - RequestsPerDomain = BlockCheckRunPresetFactory.GetRecommendedAttemptsPerTarget(value); - } + get => _options.SelectedRunPreset; + set => _options.SelectedRunPreset = value; } public bool IncludeHttp { - get => _includeHttp; - set => SetProtocolSelection(ref _includeHttp, value); + get => _options.IncludeHttp; + set => _options.IncludeHttp = value; } public bool IncludeTls12 { - get => _includeTls12; - set => SetProtocolSelection(ref _includeTls12, value); + get => _options.IncludeTls12; + set => _options.IncludeTls12 = value; } public bool IncludeTls13 { - get => _includeTls13; - set => SetProtocolSelection(ref _includeTls13, value); + get => _options.IncludeTls13; + set => _options.IncludeTls13 = value; } public bool IncludeTlsAuto { - get => _includeTlsAuto; - set => SetProtocolSelection(ref _includeTlsAuto, value); + get => _options.IncludeTlsAuto; + set => _options.IncludeTlsAuto = value; } public bool IncludeQuic { - get => _includeQuic; - set => SetProtocolSelection(ref _includeQuic, value); + get => _options.IncludeQuic; + set => _options.IncludeQuic = value; } - public bool IsHttpOnly => _includeHttp && !_includeTls12 && !_includeTls13 && !_includeTlsAuto && !_includeQuic; - public bool IncludeIpv4 { - get => _includeIpv4; - set => SetIpVersionSelection(ref _includeIpv4, value); + get => _options.IncludeIpv4; + set => _options.IncludeIpv4 = value; } public bool IncludeIpv6 { - get => _includeIpv6; - set => SetIpVersionSelection(ref _includeIpv6, value); + get => _options.IncludeIpv6; + set => _options.IncludeIpv6 = value; } - public int DirectTargetInputCount => _targetInput - .Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) - .Distinct(StringComparer.OrdinalIgnoreCase) - .Count(); - public bool HasTargetSources => DirectTargetInputCount > 0 || SelectedSiteLists.Count > 0; - public bool HasProtocolSelection => - _includeHttp || _includeTls12 || _includeTls13 || _includeTlsAuto || _includeQuic; - public bool HasIpVersionSelection => _includeIpv4 || _includeIpv6; - public bool CanContinueFromTargets => !IsRunning && HasProtocolSelection && HasIpVersionSelection; - public double ConnectTimeoutSeconds { - get => _connectTimeoutSeconds; - set => SetAdvancedOption(ref _connectTimeoutSeconds, value); + get => _options.ConnectTimeoutSeconds; + set => _options.ConnectTimeoutSeconds = value; } public double RequestTimeoutSeconds { - get => _requestTimeoutSeconds; - set => SetAdvancedOption(ref _requestTimeoutSeconds, value); + get => _options.RequestTimeoutSeconds; + set => _options.RequestTimeoutSeconds = value; } public double StartupGraceSeconds { - get => _startupGraceSeconds; - set => SetAdvancedOption(ref _startupGraceSeconds, value); + get => _options.StartupGraceSeconds; + set => _options.StartupGraceSeconds = value; } public bool TestAllStrategies { - get => _testAllStrategies; - set - { - if (_testAllStrategies == value) - { - return; - } - - _testAllStrategies = value; - Notify(); - BlockCheck2SettingsStore.Save(nameof(TestAllStrategies), value); - } + get => _options.TestAllStrategies; + set => _options.TestAllStrategies = value; } public double RequestsPerDomain { - get => _requestsPerDomain; - set - { - if (_requestsPerDomain.Equals(value)) - { - return; - } - - _requestsPerDomain = value; - Notify(); - Notify(nameof(AdvancedOptionsValid)); - Notify(nameof(CanStart)); - if (BlockCheck2OptionLimits.IsValidRequestsPerDomain(value)) - { - BlockCheck2SettingsStore.Save(nameof(RequestsPerDomain), (int)value); - } - } - } - - public bool AdvancedOptionsValid => - BlockCheck2OptionLimits.IsValidConnectTimeout(_connectTimeoutSeconds) && - BlockCheck2OptionLimits.IsValidRequestTimeout(_requestTimeoutSeconds, _connectTimeoutSeconds) && - BlockCheck2OptionLimits.IsValidStartupGrace(_startupGraceSeconds) && - BlockCheck2OptionLimits.IsValidRequestsPerDomain(_requestsPerDomain); - - public void ResetAdvancedOptions() - { - ConnectTimeoutSeconds = BlockCheck2OptionLimits.DefaultConnectTimeoutSeconds; - RequestTimeoutSeconds = BlockCheck2OptionLimits.DefaultRequestTimeoutSeconds; - StartupGraceSeconds = BlockCheck2OptionLimits.DefaultStartupGraceSeconds; - TestAllStrategies = false; - RequestsPerDomain = BlockCheckRunPresetFactory.GetRecommendedAttemptsPerTarget(_selectedRunPreset); - } - - private void LoadSettings() - { - int presetValue = BlockCheck2SettingsStore.ReadInt( - nameof(SelectedRunPreset), - (int)BlockCheckRunPreset.Balanced); - _selectedRunPreset = Enum.IsDefined(typeof(BlockCheckRunPreset), presetValue) - ? (BlockCheckRunPreset)presetValue - : BlockCheckRunPreset.Balanced; - - _includeHttp = BlockCheck2SettingsStore.ReadBool(nameof(IncludeHttp), defaultValue: false); - _includeTls12 = BlockCheck2SettingsStore.ReadBool(nameof(IncludeTls12), defaultValue: true); - _includeTls13 = BlockCheck2SettingsStore.ReadBool(nameof(IncludeTls13), defaultValue: false); - _includeTlsAuto = BlockCheck2SettingsStore.ReadBool(nameof(IncludeTlsAuto), defaultValue: true); - _includeQuic = BlockCheck2SettingsStore.ReadBool(nameof(IncludeQuic), defaultValue: false); - _includeIpv4 = BlockCheck2SettingsStore.ReadBool(nameof(IncludeIpv4), defaultValue: true); - _includeIpv6 = BlockCheck2SettingsStore.ReadBool(nameof(IncludeIpv6), defaultValue: false); - - double savedConnectTimeout = BlockCheck2SettingsStore.ReadDouble( - nameof(ConnectTimeoutSeconds), - BlockCheck2OptionLimits.DefaultConnectTimeoutSeconds); - _connectTimeoutSeconds = BlockCheck2OptionLimits.IsValidConnectTimeout(savedConnectTimeout) - ? savedConnectTimeout - : BlockCheck2OptionLimits.DefaultConnectTimeoutSeconds; - - double savedRequestTimeout = BlockCheck2SettingsStore.ReadDouble( - nameof(RequestTimeoutSeconds), - BlockCheck2OptionLimits.DefaultRequestTimeoutSeconds); - _requestTimeoutSeconds = - BlockCheck2OptionLimits.IsValidRequestTimeout(savedRequestTimeout, _connectTimeoutSeconds) - ? savedRequestTimeout - : Math.Max(BlockCheck2OptionLimits.DefaultRequestTimeoutSeconds, _connectTimeoutSeconds); - - double savedStartupGrace = BlockCheck2SettingsStore.ReadDouble( - nameof(StartupGraceSeconds), - BlockCheck2OptionLimits.DefaultStartupGraceSeconds); - _startupGraceSeconds = BlockCheck2OptionLimits.IsValidStartupGrace(savedStartupGrace) - ? savedStartupGrace - : BlockCheck2OptionLimits.DefaultStartupGraceSeconds; - - _testAllStrategies = BlockCheck2SettingsStore.ReadBool(nameof(TestAllStrategies), defaultValue: false); - int recommendedAttempts = BlockCheckRunPresetFactory.GetRecommendedAttemptsPerTarget(_selectedRunPreset); - int savedAttempts = BlockCheck2SettingsStore.ReadInt(nameof(RequestsPerDomain), recommendedAttempts); - _requestsPerDomain = BlockCheck2OptionLimits.IsValidRequestsPerDomain(savedAttempts) - ? savedAttempts - : recommendedAttempts; - } - - private BlockCheckSessionRequest CreateSessionRequest() => new() - { - TargetInput = _targetInput, - SiteLists = SelectedSiteLists.Select(item => item.CreateInput(_generatedSiteListRoot)).ToArray(), - RunPreset = _selectedRunPreset, - TestAllStrategies = _testAllStrategies, - AttemptsPerTarget = (int)_requestsPerDomain, - Protocols = SelectedProtocols(), - IpVersions = SelectedIpVersions(), - }; - - private IReadOnlySet SelectedProtocols() - { - HashSet selected = []; - if (_includeHttp) - selected.Add(BlockCheckProtocol.Http); - if (_includeTls12) - selected.Add(BlockCheckProtocol.Tls12); - if (_includeTls13) - selected.Add(BlockCheckProtocol.Tls13); - if (_includeTlsAuto) - selected.Add(BlockCheckProtocol.TlsAuto); - if (_includeQuic) - selected.Add(BlockCheckProtocol.Quic); - return selected; - } - - private IReadOnlySet SelectedIpVersions() - { - HashSet selected = []; - if (_includeIpv4) - selected.Add(BlockCheckIpVersion.IPv4); - if (_includeIpv6) - selected.Add(BlockCheckIpVersion.IPv6); - return selected; + get => _options.RequestsPerDomain; + set => _options.RequestsPerDomain = value; } - private void SetProtocolSelection(ref bool field, bool value, [CallerMemberName] string? propertyName = null) - { - if (field == value) - { - return; - } + public IReadOnlyList AvailableRunPresets => _options.AvailableRunPresets; + public bool IsHttpOnly => _options.IsHttpOnly; + public int DirectTargetInputCount => _options.DirectTargetInputCount; + public bool HasTargetSources => _options.HasTargetSources; + public bool HasProtocolSelection => _options.HasProtocolSelection; + public bool HasIpVersionSelection => _options.HasIpVersionSelection; + public bool CanContinueFromTargets => _options.CanContinueFromTargets; + public bool AdvancedOptionsValid => _options.AdvancedOptionsValid; - field = value; - Notify(propertyName); - BlockCheck2SettingsStore.Save(propertyName, value); - Notify(nameof(IsHttpOnly)); - Notify(nameof(HasProtocolSelection)); - Notify(nameof(CanContinueFromTargets)); - Notify(nameof(CanStart)); - } + public void ResetAdvancedOptions() => _options.ResetAdvancedOptions(); - private void SetIpVersionSelection(ref bool field, bool value, [CallerMemberName] string? propertyName = null) - { - if (field == value) - { - return; - } - - field = value; - Notify(propertyName); - BlockCheck2SettingsStore.Save(propertyName, value); - Notify(nameof(HasIpVersionSelection)); - Notify(nameof(CanContinueFromTargets)); - Notify(nameof(CanStart)); - } - - private void SetAdvancedOption( - ref double field, - double value, - [CallerMemberName] string? propertyName = null) - { - if (field.Equals(value)) - { - return; - } - - field = value; - Notify(propertyName); - if (double.IsFinite(value)) - { - BlockCheck2SettingsStore.Save(propertyName, value); - } - Notify(nameof(AdvancedOptionsValid)); - Notify(nameof(CanStart)); - } + private BlockCheckSessionRequest CreateSessionRequest() => _options.CreateSessionRequest( + () => SelectedSiteLists.Select(item => item.CreateInput(_generatedSiteListRoot)).ToArray()); } diff --git a/CDPIUI/ViewModels/BlockCheck2ViewModel.SiteLists.cs b/CDPIUI/ViewModels/BlockCheck2ViewModel.SiteLists.cs index be60d1c8..5fefcf32 100644 --- a/CDPIUI/ViewModels/BlockCheck2ViewModel.SiteLists.cs +++ b/CDPIUI/ViewModels/BlockCheck2ViewModel.SiteLists.cs @@ -13,161 +13,28 @@ namespace CDPIUI.ViewModels; public sealed partial class BlockCheck2ViewModel { private string _generatedSiteListRoot = BlockCheck2SiteListStorage.CreateGeneratedSiteListRoot(); - private bool _siteListsLoaded; - private bool _isSiteListLoading; - private string? _siteListLoadError; - public ObservableCollection AvailableSiteLists { get; } = []; public ObservableCollection SelectedSiteLists { get; } = []; - public bool IsSiteListLoading => _isSiteListLoading; - public string? SiteListLoadError => _siteListLoadError; - public int SelectedSiteListCount => SelectedSiteLists.Count; - public int SelectedDomainCount => SelectedSiteLists.Sum(item => item.DomainCount); - - public async Task LoadSiteListsAsync() - { - if (_siteListsLoaded || _isSiteListLoading) - { - return; - } - - _isSiteListLoading = true; - _siteListLoadError = null; - Notify(nameof(IsSiteListLoading)); - Notify(nameof(SiteListLoadError)); - try - { - List items = await SiteListHelper.GetAllAvailableSiteListTemplatesAsync(); - AvailableSiteLists.Clear(); - foreach (SiteListElement item in items - .Where(item => !string.IsNullOrWhiteSpace(item.Directory)) - .Where(item => !BlockCheck2SiteListStorage.IsLegacyGeneratedSiteList(item.Directory!)) - .OrderBy(item => item.PackName, StringComparer.CurrentCultureIgnoreCase) - .ThenBy(item => item.Name, StringComparer.CurrentCultureIgnoreCase)) - { - var siteListItem = new BlockCheck2SiteListItem( - item.Name ?? Path.GetFileName(item.Directory!) ?? "site-list.txt", - item.PackName ?? string.Empty, - item.Directory!, - individualSiteListRoot: _generatedSiteListRoot); - if (siteListItem.DomainCount > 0 && !siteListItem.DisplayName.Contains("exclude")) - AvailableSiteLists.Add(siteListItem); - - } - _siteListsLoaded = true; - } - catch (Exception exception) - { - _siteListLoadError = exception.Message; - Notify(nameof(SiteListLoadError)); - } - finally - { - _isSiteListLoading = false; - Notify(nameof(IsSiteListLoading)); - } - } - - public BlockCheck2SiteListItem AddCustomSiteList(string filePath, string sourceName) - { - string fullPath = Path.GetFullPath(filePath); - BlockCheck2SiteListItem? existing = AvailableSiteLists - .Concat(SelectedSiteLists) - .FirstOrDefault( - item => string.Equals(item.FilePath, fullPath, StringComparison.OrdinalIgnoreCase)); - if (existing != null) - { - return existing; - } - - BlockCheck2SiteListItem added = new( - Path.GetFileName(fullPath), - sourceName, - fullPath, - individualSiteListRoot: _generatedSiteListRoot); - return added; - } - - public async Task UpdateCustomSiteListAsync( - string content, - string displayName, - string sourceName, - CancellationToken cancellationToken = default) - { - string normalizedContent = BlockCheck2SiteListStorage.NormalizeCustomContent(content); - if (normalizedContent.Length == 0) - { - throw new InvalidDataException( - WinUI3Localizer.Localizer.Get().GetLocalizedString("BlockCheck2CustomSiteListEmpty")); - } - - BlockCheck2SiteListItem? item = SelectedSiteLists.FirstOrDefault(candidate => candidate.IsCustom); - string filePath = item?.FilePath ?? BlockCheck2SiteListStorage.CreateCustomSiteListPath(); - await BlockCheck2SiteListStorage.WriteCustomSiteListAsync(filePath, normalizedContent, cancellationToken); - - if (item == null) - { - item = new BlockCheck2SiteListItem( - displayName, - sourceName, - filePath, - isCustom: true, - editableContent: normalizedContent, - individualSiteListRoot: _generatedSiteListRoot); - SelectedSiteLists.Insert(0, item); - } - else - { - item.UpdateCustomContent(normalizedContent); - } - - NotifySiteListSelectionChanged(); - return item; - } - - public void SelectSiteList(BlockCheck2SiteListItem item) - { - ArgumentNullException.ThrowIfNull(item); - if (SelectedSiteLists.Any(selected => string.Equals( - selected.FilePath, - item.FilePath, - StringComparison.OrdinalIgnoreCase))) - { - return; - } - - SelectedSiteLists.Add(item); - NotifySiteListSelectionChanged(); - } - - public void RemoveSiteList(BlockCheck2SiteListItem item) - { - ArgumentNullException.ThrowIfNull(item); - if (SelectedSiteLists.Remove(item)) - { - NotifySiteListSelectionChanged(); - } - } + public bool IsSiteListLoading => _siteLists.IsSiteListLoading; + public string? SiteListLoadError => _siteLists.SiteListLoadError; + public int SelectedSiteListCount => _siteLists.SelectedSiteListCount; + public int SelectedDomainCount => _siteLists.SelectedDomainCount; - public void SetSelectedSiteLists(IEnumerable selected) - { - SelectedSiteLists.Clear(); - foreach (BlockCheck2SiteListItem item in selected.DistinctBy( - item => item.FilePath, - StringComparer.OrdinalIgnoreCase)) - { - SelectedSiteLists.Add(item); - } - NotifySiteListSelectionChanged(); - } + public Task LoadSiteListsAsync() => _siteLists.LoadAsync(); + public BlockCheck2SiteListItem AddCustomSiteList(string filePath, string sourceName) => _siteLists.AddCustom(filePath, sourceName); + public Task UpdateCustomSiteListAsync(string content, string displayName, string sourceName, CancellationToken cancellationToken = default) => + _siteLists.UpdateCustomAsync(content, displayName, sourceName, cancellationToken); + public void SelectSiteList(BlockCheck2SiteListItem item) => _siteLists.Select(item); + public void RemoveSiteList(BlockCheck2SiteListItem item) => _siteLists.Remove(item); + public void SetSelectedSiteLists(IEnumerable selected) => _siteLists.SetSelected(selected); public async Task BuildPreparationPreviewAsync( CancellationToken cancellationToken = default) { BlockCheckSessionRequest request = CreateSessionRequest(); - double requestTimeout = _requestTimeoutSeconds; - double startupGrace = _startupGraceSeconds; + double requestTimeout = _options.RequestTimeoutSeconds; + double startupGrace = _options.StartupGraceSeconds; BlockCheck2PreparationPreview preview = await Task.Run(() => { cancellationToken.ThrowIfCancellationRequested(); @@ -196,7 +63,7 @@ public async Task BuildPreparationPreviewAsync( public void CleanupGeneratedSiteListsIfUnviewable() { - if (_lastReport == null) + if (_results.LastReport == null) { CleanupGeneratedSiteLists(); } diff --git a/CDPIUI/ViewModels/BlockCheck2ViewModel.cs b/CDPIUI/ViewModels/BlockCheck2ViewModel.cs index 9088d5e5..2584e546 100644 --- a/CDPIUI/ViewModels/BlockCheck2ViewModel.cs +++ b/CDPIUI/ViewModels/BlockCheck2ViewModel.cs @@ -14,34 +14,18 @@ namespace CDPIUI.ViewModels; -public sealed partial class BlockCheck2ViewModel : ObservableObject +public sealed partial class BlockCheck2ViewModel : ObservableObject, IBlockCheck2RunHost { private readonly BlockCheckAddOnService _addOnService; private readonly BlockCheckSessionPreparationService _preparationService; - private readonly BlockCheckReportBuilder _reportBuilder; - private readonly BlockCheckReportSerializer _reportSerializer; private readonly BlockCheckReportHistoryService _reportHistoryService; private readonly BlockCheckMaximumDurationEstimator _maximumDurationEstimator = new(); - private readonly BlockCheck2ProgressEstimator _progressEstimator = new(); - private CancellationTokenSource? _cancellation; + private readonly BlockCheck2ProgressViewModel _progress; + private readonly BlockCheck2RunResultViewModel _results; + private readonly BlockCheck2RunController _runController; + private readonly BlockCheck2SiteListController _siteLists; private BlockCheckSessionState _state = BlockCheckSessionState.Idle; - private BlockCheckScanPhase? _currentPhase; - private int _progressCurrent; - private int _progressTotal; - private TimeSpan? _estimatedRemainingTime; - private TimeSpan? _estimatedOverallRemainingTime; - private int _successfulChecks; - private int _failedChecks; - private int _successfulStrategies; - private string _currentTargetId = string.Empty; - private string _currentStrategyId = string.Empty; - private string? _operationError; - private string? _historySaveError; - private IReadOnlyList _issues = []; private IReadOnlyList _targets = []; - private BlockCheckRunResult? _lastResult; - private BlockCheckReport? _lastReport; - private BlockCheckResultSession? _lastSession; public BlockCheck2ViewModel( BlockCheckAddOnService? addOnService = null, @@ -52,184 +36,101 @@ public BlockCheck2ViewModel( { _addOnService = addOnService ?? new BlockCheckAddOnService(); _preparationService = preparationService ?? new BlockCheckSessionPreparationService(); - _reportBuilder = reportBuilder ?? new BlockCheckReportBuilder(); - _reportSerializer = reportSerializer ?? new BlockCheckReportSerializer(); - _reportHistoryService = reportHistoryService ?? new BlockCheckReportHistoryService(_reportSerializer); - LoadSettings(); + BlockCheckReportBuilder builder = reportBuilder ?? new BlockCheckReportBuilder(); + BlockCheckReportSerializer serializer = reportSerializer ?? new BlockCheckReportSerializer(); + _reportHistoryService = reportHistoryService ?? new BlockCheckReportHistoryService(serializer); + _siteLists = new BlockCheck2SiteListController(AvailableSiteLists, SelectedSiteLists, + new BlockCheck2SiteListBackend(), () => _generatedSiteListRoot, NotifySiteListSelectionChanged); + _siteLists.PropertyChanged += (_, args) => Notify(args.PropertyName); + _options = new BlockCheck2OptionsViewModel( + new BlockCheck2OptionsSettings(), () => IsRunning, () => SelectedSiteLists.Count); + _options.PropertyChanged += (_, args) => Notify(args.PropertyName); + _results = new BlockCheck2RunResultViewModel(new BlockCheck2ReportOperations(builder, serializer), _options); + _results.PropertyChanged += (_, args) => Notify(args.PropertyName); + _progress = new BlockCheck2ProgressViewModel(() => _targets, + () => (int)_options.RequestsPerDomain, () => _options.StartupGraceSeconds); + _progress.PropertyChanged += (_, args) => Notify(args.PropertyName); + _runController = new BlockCheck2RunController(this); } public BlockCheckSessionState State => _state; - public BlockCheckScanPhase? CurrentPhase => _currentPhase; - public int ProgressCurrent => _progressCurrent; - public int ProgressTotal => _progressTotal; - public TimeSpan? EstimatedRemainingTime => _estimatedRemainingTime; - public TimeSpan? EstimatedOverallRemainingTime => _estimatedOverallRemainingTime; - public bool IsProgressIndeterminate => _progressTotal <= 0; - public int SuccessfulChecks => _successfulChecks; - public int FailedChecks => _failedChecks; - public int CompletedChecks => _successfulChecks + _failedChecks; - public int SuccessfulStrategies => _successfulStrategies; - public double ProgressValue => _progressTotal <= 0 - ? 0d - : Math.Clamp((double)_progressCurrent / _progressTotal, 0d, 1d); - public string CurrentTargetId => _currentTargetId; - public string CurrentTargetUrl - { - get - { - BlockCheckTarget? target = CurrentTarget(); - return target == null - ? _currentTargetId - : BlockCheckTargetDisplayFormatter.FormatUrl(target); - } - } - public string CurrentTargetConnectionDetails - { - get - { - BlockCheckTarget? target = CurrentTarget(); - return target == null - ? string.Empty - : BlockCheckTargetDisplayFormatter.FormatConnectionDetails(target); - } - } - public string CurrentTargetDisplay - { - get - { - BlockCheckTarget? target = CurrentTarget(); - return target == null - ? _currentTargetId - : BlockCheckTargetDisplayFormatter.Format(target); - } - } - public string CurrentStrategyId => _currentStrategyId; - public string? OperationError => _operationError; - public string? HistorySaveError => _historySaveError; - public IReadOnlyList Issues => _issues; + public BlockCheckScanPhase? CurrentPhase => _progress.CurrentPhase; + public int ProgressCurrent => _progress.ProgressCurrent; + public int ProgressTotal => _progress.ProgressTotal; + public TimeSpan? EstimatedRemainingTime => _progress.EstimatedRemainingTime; + public TimeSpan? EstimatedOverallRemainingTime => _progress.EstimatedOverallRemainingTime; + public bool IsProgressIndeterminate => _progress.IsProgressIndeterminate; + public int SuccessfulChecks => _progress.SuccessfulChecks; + public int FailedChecks => _progress.FailedChecks; + public int CompletedChecks => _progress.CompletedChecks; + public int SuccessfulStrategies => _progress.SuccessfulStrategies; + public double ProgressValue => _progress.ProgressValue; + public string CurrentTargetId => _progress.CurrentTargetId; + public string CurrentTargetUrl => _progress.CurrentTargetUrl; + public string CurrentTargetConnectionDetails => _progress.CurrentTargetConnectionDetails; + public string CurrentTargetDisplay => _progress.CurrentTargetDisplay; + public string CurrentStrategyId => _progress.CurrentStrategyId; + public string? OperationError => _results.OperationError; + public string? HistorySaveError => _results.HistorySaveError; + public IReadOnlyList Issues => _results.Issues; public IReadOnlyList Targets => _targets; public int TargetCount => _targets.Count; - public BlockCheckRunResult? LastResult => _lastResult; - public BlockCheckReport? LastReport => _lastReport; - public BlockCheckResultSession? LastSession => _lastSession; - public bool NoBypassRequired => _lastReport?.Issues.Any(issue => - string.Equals(issue.Code, "NO_BYPASS_REQUIRED", StringComparison.Ordinal)) == true; - public bool LastReportIsHttpOnly => _lastReport?.Targets.Count > 0 && - _lastReport.Targets.All(target => target.Protocol == BlockCheckProtocol.Http); - public string ReportJson => _lastReport == null ? string.Empty : _reportSerializer.SerializeJson(_lastReport); - public string ReportText => _lastReport == null ? string.Empty : _reportSerializer.SerializeText(_lastReport); - public string PresetArguments => _lastReport?.PresetArguments ?? string.Empty; + public BlockCheckRunResult? LastResult => _results.LastResult; + public BlockCheckReport? LastReport => _results.LastReport; + public BlockCheckResultSession? LastSession => _results.LastSession; + public bool NoBypassRequired => _results.NoBypassRequired; + public bool LastReportIsHttpOnly => _results.LastReportIsHttpOnly; + public string ReportJson => _results.ReportJson; + public string ReportText => _results.ReportText; + public string PresetArguments => _results.PresetArguments; public bool IsRunning => _state is BlockCheckSessionState.Running or BlockCheckSessionState.Canceling; - public bool CanStart => !IsRunning && - HasTargetSources && - HasProtocolSelection && - HasIpVersionSelection && - AdvancedOptionsValid; + public bool CanStart => _options.CanStart; public bool CanCancel => _state == BlockCheckSessionState.Running; - public bool CanExportReport => _lastReport != null; - public bool CanExportPreset => (_lastReport?.Success == true || _lastReport?.IsBestEffort == true) && - !string.IsNullOrWhiteSpace(_lastReport.PresetArguments); - - public async Task StartAsync() - { - if (!CanStart) - { - return null; - } - - if (_lastReport != null) - { - _generatedSiteListRoot = BlockCheck2SiteListStorage.CreateGeneratedSiteListRoot(); - } - ResetResultState(); - _progressEstimator.StartRun(); - CancellationTokenSource? runCancellation = null; - try - { - BlockCheckSessionPreparationResult prepared = _preparationService.Prepare(CreateSessionRequest()); - _targets = prepared.Targets; - _issues = prepared.Issues; - Notify(nameof(Targets)); - Notify(nameof(TargetCount)); - Notify(nameof(Issues)); - if (!prepared.Success) - { - SetState(BlockCheckSessionState.InputInvalid); - return null; - } + public bool CanExportReport => _results.CanExportReport; + public bool CanExportPreset => _results.CanExportPreset; - runCancellation = new CancellationTokenSource(); - _cancellation = runCancellation; - SetState(BlockCheckSessionState.Running); - BlockCheckRunResult result = await RunPreparedAsync(prepared, runCancellation.Token); + public Task StartAsync() => _runController.StartAsync(); - ApplyRunResult(prepared, result); - CompleteDisplayedProgress(); - BlockCheckSessionState finalState = GetFinalState(result); - // The final state allows a new run, so it is set only after the report is saved; - // otherwise a second run started meanwhile had its CTS disposed by this one. - await SaveReportToHistoryAsync(_lastReport!); - SetState(finalState); - return result; - } - catch (OperationCanceledException) - { - SetState(BlockCheckSessionState.Canceled); - return null; - } - catch (Exception exception) - { - _operationError = exception.Message; - Notify(nameof(OperationError)); - SetState(BlockCheckSessionState.Failed); - return null; - } - finally - { - _progressEstimator.StopRun(); - _estimatedRemainingTime = null; - _estimatedOverallRemainingTime = null; - Notify(nameof(EstimatedRemainingTime)); - Notify(nameof(EstimatedOverallRemainingTime)); - runCancellation?.Dispose(); - if (ReferenceEquals(_cancellation, runCancellation)) - { - _cancellation = null; - } - CleanupGeneratedSiteListsIfUnviewable(); - NotifyActionState(); - } - } + public void Cancel() => _runController.Cancel(); - public void Cancel() - { - if (!CanCancel || _cancellation == null) - { - return; - } - - SetState(BlockCheckSessionState.Canceling); - _cancellation.Cancel(); + bool IBlockCheck2RunHost.CanStart => CanStart; + bool IBlockCheck2RunHost.CanCancel => CanCancel; + BlockCheckReport? IBlockCheck2RunHost.LastReport => LastReport; + void IBlockCheck2RunHost.CleanupGeneratedSiteListsIfUnviewable() => CleanupGeneratedSiteListsIfUnviewable(); + void IBlockCheck2RunHost.RenewGeneratedSiteListRoot() => + _generatedSiteListRoot = BlockCheck2SiteListStorage.CreateGeneratedSiteListRoot(); + void IBlockCheck2RunHost.ResetResultState() => ResetResultState(); + void IBlockCheck2RunHost.StartProgress() => _progress.StartRun(); + BlockCheckSessionPreparationResult IBlockCheck2RunHost.Prepare() => + _preparationService.Prepare(CreateSessionRequest()); + void IBlockCheck2RunHost.ApplyPrepared(BlockCheckSessionPreparationResult prepared) + { + _targets = prepared.Targets; + _results.SetPreparedIssues(prepared.Issues); + Notify(nameof(Targets)); + Notify(nameof(TargetCount)); + Notify(nameof(Issues)); } + void IBlockCheck2RunHost.SetState(BlockCheckSessionState state) => SetState(state); + Task IBlockCheck2RunHost.RunPreparedAsync( + BlockCheckSessionPreparationResult prepared, CancellationToken cancellationToken) => RunPreparedAsync(prepared, cancellationToken); + void IBlockCheck2RunHost.ApplyRunResult(BlockCheckSessionPreparationResult prepared, BlockCheckRunResult result) => + ApplyRunResult(prepared, result); + void IBlockCheck2RunHost.CompleteDisplayedProgress() => CompleteDisplayedProgress(); + Task IBlockCheck2RunHost.SaveReportToHistoryAsync(BlockCheckReport report) => SaveReportToHistoryAsync(report); + void IBlockCheck2RunHost.SetOperationError(string message) => _results.SetOperationError(message); + void IBlockCheck2RunHost.FinishProgress() => _progress.FinishRun(); + void IBlockCheck2RunHost.NotifyActionState() => NotifyActionState(); public Task SaveReportJsonAsync(string filePath, CancellationToken cancellationToken = default) => - _reportSerializer.SaveJsonAsync( - filePath, - _lastReport ?? throw new InvalidOperationException("No BlockCheck2 report is available."), - cancellationToken); + _results.SaveReportJsonAsync(filePath, cancellationToken); public Task SaveReportTextAsync(string filePath, CancellationToken cancellationToken = default) => - _reportSerializer.SaveTextAsync( - filePath, - _lastReport ?? throw new InvalidOperationException("No BlockCheck2 report is available."), - cancellationToken); + _results.SaveReportTextAsync(filePath, cancellationToken); public Task SavePresetArgumentsAsync(string filePath, CancellationToken cancellationToken = default) => - _reportSerializer.SavePresetArgumentsAsync( - filePath, - _lastReport ?? throw new InvalidOperationException("No BlockCheck2 report is available."), - cancellationToken); + _results.SavePresetArgumentsAsync(filePath, cancellationToken); public void Reset() { @@ -238,7 +139,7 @@ public void Reset() return; } - if (_lastReport == null) + if (_results.LastReport == null) { CleanupGeneratedSiteLists(); } @@ -262,12 +163,12 @@ private async Task RunPreparedAsync( progress, strategyRunnerOptions: new CdpiuiZapret2StrategyRunnerOptions { - StartupGracePeriod = TimeSpan.FromSeconds(_startupGraceSeconds), + StartupGracePeriod = TimeSpan.FromSeconds(_options.StartupGraceSeconds), }, probeRunnerOptions: new CurlBlockCheckProbeRunnerOptions { - ConnectTimeout = TimeSpan.FromSeconds(_connectTimeoutSeconds), - RequestTimeout = TimeSpan.FromSeconds(_requestTimeoutSeconds), + ConnectTimeout = TimeSpan.FromSeconds(_options.ConnectTimeoutSeconds), + RequestTimeout = TimeSpan.FromSeconds(_options.RequestTimeoutSeconds), }, cancellationToken: cancellationToken); @@ -284,37 +185,8 @@ private async Task RunPreparedAsync( }; } - private void ApplyRunResult(BlockCheckSessionPreparationResult prepared, BlockCheckRunResult result) - { - _lastResult = result; - _lastReport = _reportBuilder.Build( - prepared.Catalog, - _selectedRunPreset, - prepared.Targets, - result); - _lastSession = new BlockCheckResultSession - { - Catalog = prepared.Catalog, - Targets = prepared.Targets, - RunOptions = prepared.RunOptions, - RunResult = result, - Report = _lastReport, - ConnectTimeout = TimeSpan.FromSeconds(_connectTimeoutSeconds), - RequestTimeout = TimeSpan.FromSeconds(_requestTimeoutSeconds), - StartupGracePeriod = TimeSpan.FromSeconds(_startupGraceSeconds), - }; - _issues = _lastReport.Issues; - NotifyResult(); - } - - private static BlockCheckSessionState GetFinalState(BlockCheckRunResult result) => - result.WasCanceled - ? BlockCheckSessionState.Canceled - : result.Success - ? BlockCheckSessionState.Completed - : result.Synthesis?.IsBestEffort == true - ? BlockCheckSessionState.CompletedWithWarnings - : BlockCheckSessionState.Failed; + private void ApplyRunResult(BlockCheckSessionPreparationResult prepared, BlockCheckRunResult result) => + _results.ApplyRunResult(prepared, result); private async Task SaveReportToHistoryAsync(BlockCheckReport report) { @@ -324,116 +196,18 @@ private async Task SaveReportToHistoryAsync(BlockCheckReport report) } catch (Exception exception) { - _historySaveError = exception.Message; - Notify(nameof(HistorySaveError)); + _results.SetHistorySaveError(exception.Message); Logger.Instance.CreateWarningLog( nameof(BlockCheck2ViewModel), $"Cannot save BlockCheck2 report to history: {exception.Message}"); } } - private void UpdateProgress(BlockCheckScanProgress progress) - { - _currentPhase = progress.Phase; - _progressCurrent = progress.CompletedStrategyTargets; - _progressTotal = progress.TotalStrategyTargets; - _currentTargetId = progress.TargetId; - _currentStrategyId = progress.StrategyId; - _successfulChecks = progress.SuccessfulChecks; - _failedChecks = progress.FailedChecks; - _successfulStrategies = progress.SuccessfulStrategies; - (_estimatedRemainingTime, _estimatedOverallRemainingTime) = _progressEstimator.Update( - progress, - _targets.Count, - (int)_requestsPerDomain, - _startupGraceSeconds); - Notify(nameof(CurrentPhase)); - Notify(nameof(ProgressCurrent)); - Notify(nameof(ProgressTotal)); - Notify(nameof(ProgressValue)); - Notify(nameof(IsProgressIndeterminate)); - Notify(nameof(CurrentTargetId)); - Notify(nameof(CurrentTargetUrl)); - Notify(nameof(CurrentTargetConnectionDetails)); - Notify(nameof(CurrentTargetDisplay)); - Notify(nameof(CurrentStrategyId)); - Notify(nameof(EstimatedRemainingTime)); - Notify(nameof(EstimatedOverallRemainingTime)); - Notify(nameof(SuccessfulChecks)); - Notify(nameof(FailedChecks)); - Notify(nameof(CompletedChecks)); - Notify(nameof(SuccessfulStrategies)); - } - - private void ResetResultState() - { - _operationError = null; - _historySaveError = null; - _issues = []; - _lastResult = null; - _lastReport = null; - _lastSession = null; - _currentPhase = null; - _progressCurrent = 0; - _progressTotal = 0; - _estimatedRemainingTime = null; - _estimatedOverallRemainingTime = null; - _progressEstimator.ResetObservations(); - _successfulChecks = 0; - _failedChecks = 0; - _successfulStrategies = 0; - _currentTargetId = string.Empty; - _currentStrategyId = string.Empty; - Notify(nameof(OperationError)); - Notify(nameof(HistorySaveError)); - NotifyResult(); - Notify(nameof(CurrentPhase)); - Notify(nameof(ProgressCurrent)); - Notify(nameof(ProgressTotal)); - Notify(nameof(ProgressValue)); - Notify(nameof(IsProgressIndeterminate)); - Notify(nameof(EstimatedRemainingTime)); - Notify(nameof(EstimatedOverallRemainingTime)); - Notify(nameof(SuccessfulChecks)); - Notify(nameof(FailedChecks)); - Notify(nameof(CompletedChecks)); - Notify(nameof(SuccessfulStrategies)); - Notify(nameof(CurrentTargetId)); - Notify(nameof(CurrentTargetUrl)); - Notify(nameof(CurrentTargetConnectionDetails)); - Notify(nameof(CurrentTargetDisplay)); - Notify(nameof(CurrentStrategyId)); - } - - private void NotifyResult() - { - Notify(nameof(Issues)); - Notify(nameof(LastResult)); - Notify(nameof(LastReport)); - Notify(nameof(LastSession)); - Notify(nameof(NoBypassRequired)); - Notify(nameof(LastReportIsHttpOnly)); - Notify(nameof(ReportJson)); - Notify(nameof(ReportText)); - Notify(nameof(PresetArguments)); - Notify(nameof(CanExportReport)); - Notify(nameof(CanExportPreset)); - } - - private void CompleteDisplayedProgress() - { - if (_progressTotal <= 0) - { - return; - } + private void UpdateProgress(BlockCheckScanProgress progress) => _progress.Update(progress); - _progressCurrent = _progressTotal; - Notify(nameof(ProgressCurrent)); - Notify(nameof(ProgressValue)); - } + private void ResetResultState() => _results.Reset(_progress.Reset); - private BlockCheckTarget? CurrentTarget() => _targets.FirstOrDefault( - item => string.Equals(item.Id, _currentTargetId, StringComparison.Ordinal)); + private void CompleteDisplayedProgress() => _progress.CompleteDisplayedProgress(); private void SetState(BlockCheckSessionState value) { diff --git a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.CommandHelp.cs b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.CommandHelp.cs index db317eeb..8716f8d2 100644 --- a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.CommandHelp.cs +++ b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.CommandHelp.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; -using System.Threading; using System.Threading.Tasks; using CDPIUI.Controls.CreateConfigHelper; using CDPIUI.Helper.CreateConfigHelper; @@ -14,96 +13,48 @@ namespace CDPIUI.ViewModels.ConfigMaker; public sealed partial class ConfigMakerViewModel { private readonly ComponentCommandHelpService _helpService = new(); - private ComponentCommandHelpDocument _helpDocument = new(); - private CancellationTokenSource _helpCancellation; - private object _selectedCommandModule; - private string _commandSearchText = string.Empty; - private ConfigMakerCommandOptionViewModel _selectedCommand; - private bool _isHelpLoading; - private bool _hasCommandModules = true; - private string _usageText = string.Empty; - private string _commandArgumentText = string.Empty; - private string _commandArgumentPlaceholder = string.Empty; - private string _commandArgumentLabel = string.Empty; + private readonly ConfigMakerCommandHelpPanel _commandHelpPanel; + private readonly ConfigMakerCommandHelpLoader _helpLoader; - public ObservableCollection CommandOptions { get; } = []; - public ObservableCollection CommandModules { get; } = []; + public ObservableCollection CommandOptions => _commandHelpPanel.CommandOptions; + public ObservableCollection CommandModules => _commandHelpPanel.CommandModules; public RelayCommand CopyCommandCommand { get; } public RelayCommand InsertCommandCommand { get; } /// The module filter; because the combo box binds it two-way. public object SelectedCommandModule { - get => _selectedCommandModule; - set - { - if (SetProperty(ref _selectedCommandModule, value)) - { - RebuildCommandOptions(); - } - } + get => _commandHelpPanel.SelectedCommandModule; + set => _commandHelpPanel.SelectedCommandModule = value; } - /// Set by the view when the user types in the search box. public string CommandSearchText { - get => _commandSearchText; - set - { - _commandSearchText = value ?? string.Empty; - RebuildCommandOptions(); - } + get => _commandHelpPanel.CommandSearchText; + set => _commandHelpPanel.CommandSearchText = value; } - public bool IsHelpLoading - { - get => _isHelpLoading; - private set - { - if (SetProperty(ref _isHelpLoading, value)) - { - OnPropertyChanged(nameof(IsCommandListEnabled)); - } - } - } + public bool IsHelpLoading => _helpLoader.IsHelpLoading; - public bool IsCommandListEnabled => !_isHelpLoading; + public bool IsCommandListEnabled => _helpLoader.IsCommandListEnabled; - public bool HasCommandModules - { - get => _hasCommandModules; - private set => SetProperty(ref _hasCommandModules, value); - } + public bool HasCommandModules => _commandHelpPanel.HasCommandModules; - public string UsageText - { - get => _usageText; - private set => SetProperty(ref _usageText, value); - } + public string UsageText => _helpLoader.UsageText; - public bool HasSelectedCommand => _selectedCommand != null; - public bool CanInsertCommand => !IsEditorReadOnly && _selectedCommand != null; - public string SelectedCommandName => _selectedCommand?.Source.DisplayName ?? string.Empty; - public string SelectedCommandSyntax => _selectedCommand?.Source.Syntax ?? string.Empty; - public string SelectedCommandDescription => _selectedCommand?.Description ?? string.Empty; - public bool HasCommandArgument => !string.IsNullOrWhiteSpace(_selectedCommand?.Source.ArgumentPlaceholder); + public bool HasSelectedCommand => _commandHelpPanel.HasSelectedCommand; + public bool CanInsertCommand => _commandHelpPanel.CanInsertCommand; + public bool HasCommandArgument => _commandHelpPanel.HasCommandArgument; + public string SelectedCommandName => _commandHelpPanel.SelectedCommandName; + public string SelectedCommandSyntax => _commandHelpPanel.SelectedCommandSyntax; + public string SelectedCommandDescription => _commandHelpPanel.SelectedCommandDescription; + public string CommandArgumentPlaceholder => _commandHelpPanel.CommandArgumentPlaceholder; + public string CommandArgumentLabel => _commandHelpPanel.CommandArgumentLabel; public string CommandArgumentText { - get => _commandArgumentText; - set => SetProperty(ref _commandArgumentText, value ?? string.Empty); - } - - public string CommandArgumentPlaceholder - { - get => _commandArgumentPlaceholder; - private set => SetProperty(ref _commandArgumentPlaceholder, value); - } - - public string CommandArgumentLabel - { - get => _commandArgumentLabel; - private set => SetProperty(ref _commandArgumentLabel, value); + get => _commandHelpPanel.CommandArgumentText; + set => _commandHelpPanel.CommandArgumentText = value; } public async Task RefreshHelpAsync() @@ -117,77 +68,13 @@ public async Task RefreshHelpAsync() /// Called by the view when the selection of the command list changed. public void SelectCommand(ConfigMakerCommandOptionViewModel command) { - _selectedCommand = command; - if (command != null) - { - ComponentCommandHelpOption option = command.Source; - CommandArgumentText = string.Empty; - CommandArgumentPlaceholder = option.ArgumentPlaceholder; - CommandArgumentLabel = HasCommandArgument - ? string.Format( - _localizer.GetLocalizedString( - option.IsArgumentRequired - ? "ConfigMakerRequiredArgumentLabel" - : "ConfigMakerOptionalArgumentLabel"), - option.ArgumentPlaceholder) - : string.Empty; - } - OnPropertiesChanged( - nameof(SelectedCommandName), - nameof(SelectedCommandSyntax), - nameof(SelectedCommandDescription), - nameof(HasCommandArgument), - nameof(HasSelectedCommand), - nameof(CanInsertCommand)); + _commandHelpPanel.SelectCommand(command); CopyCommandCommand.NotifyCanExecuteChanged(); InsertCommandCommand.NotifyCanExecuteChanged(); } - private async Task LoadHelpAsync(string componentId, bool forceRefresh) - { - _helpCancellation?.Cancel(); - _helpCancellation?.Dispose(); - _helpCancellation = new CancellationTokenSource(); - CancellationToken cancellationToken = _helpCancellation.Token; - - IsHelpLoading = true; - UsageText = _localizer.GetLocalizedString("ConfigMakerLoadingHelpMessage"); - try - { - ComponentCommandHelpDocument document = await _helpService.LoadAsync( - componentId, - cancellationToken, - forceRefresh); - if (cancellationToken.IsCancellationRequested || - !string.Equals(ComponentId, componentId, StringComparison.OrdinalIgnoreCase)) - { - return; - } - - _helpDocument = document; - UsageText = !string.IsNullOrWhiteSpace(document.Usage) - ? document.Usage - : string.Format( - _localizer.GetLocalizedString("ConfigMakerHelpOptionsLoadedMessage"), - document.Options.Count); - RebuildCommandModules(); - RebuildCommandOptions(); - RebuildPresetStructure(); - RebuildDiagnostics(); - ShowHelpLoadStatus(document); - } - catch (OperationCanceledException) - { - // The load was cancelled (a newer request or the control was unloaded): nothing is left to show. - } - finally - { - if (!cancellationToken.IsCancellationRequested) - { - IsHelpLoading = false; - } - } - } + private Task LoadHelpAsync(string componentId, bool forceRefresh) => + _helpLoader.LoadAsync(componentId, forceRefresh); private void ShowHelpLoadStatus(ComponentCommandHelpDocument document) { @@ -211,82 +98,6 @@ private void ShowHelpLoadStatus(ComponentCommandHelpDocument document) } } - private void RebuildCommandOptions() - { - string query = _commandSearchText.Trim(); - IEnumerable filtered = _helpDocument.Options; - if (_selectedCommandModule is ConfigMakerCommandModuleViewModel module && !module.IsAll) - { - filtered = filtered.Where(option => - string.Equals(option.GroupName, module.GroupName, StringComparison.OrdinalIgnoreCase)); - } - - if (!string.IsNullOrWhiteSpace(query)) - { - filtered = filtered.Where(option => - option.DisplayName.Contains(query, StringComparison.OrdinalIgnoreCase) || - option.Syntax.Contains(query, StringComparison.OrdinalIgnoreCase) || - option.Description.Contains(query, StringComparison.OrdinalIgnoreCase)); - } - - CommandOptions.Clear(); - foreach (ComponentCommandHelpOption option in filtered - .OrderBy(item => item.DisplayName, StringComparer.OrdinalIgnoreCase)) - { - CommandOptions.Add(new ConfigMakerCommandOptionViewModel - { - Source = option, - Description = string.IsNullOrWhiteSpace(option.Description) - ? _localizer.GetLocalizedString("ConfigMakerNoDescriptionMessage") - : option.Description, - }); - } - } - - private void RebuildCommandModules() - { - ConfigMakerCommandModuleViewModel previous = _selectedCommandModule as ConfigMakerCommandModuleViewModel; - string previousGroup = previous?.GroupName; - bool previousWasAll = previous?.IsAll != false; - List namedGroups = _helpDocument.Options - .Select(option => option.GroupName) - .Where(group => !string.IsNullOrWhiteSpace(group)) - .Distinct(StringComparer.OrdinalIgnoreCase) - .ToList(); - - CommandModules.Clear(); - CommandModules.Add(new ConfigMakerCommandModuleViewModel - { - DisplayName = _localizer.GetLocalizedString("ConfigMakerAllModules"), - IsAll = true, - }); - - if (namedGroups.Count > 0 && _helpDocument.Options.Any(option => string.IsNullOrWhiteSpace(option.GroupName))) - { - CommandModules.Add(new ConfigMakerCommandModuleViewModel - { - DisplayName = _localizer.GetLocalizedString("ConfigMakerGeneralModule"), - GroupName = string.Empty, - }); - } - - foreach (string group in namedGroups) - { - CommandModules.Add(new ConfigMakerCommandModuleViewModel - { - DisplayName = group, - GroupName = group, - }); - } - - HasCommandModules = namedGroups.Count > 0; - SelectedCommandModule = previousWasAll - ? CommandModules[0] - : CommandModules.FirstOrDefault(item => - !item.IsAll && string.Equals(item.GroupName, previousGroup, StringComparison.OrdinalIgnoreCase)) - ?? CommandModules[0]; - } - private void InsertSelectedCommand() { if (IsEditorReadOnly) @@ -315,14 +126,7 @@ private void CopySelectedCommand() private string BuildSelectedCommand() { - if (_selectedCommand == null) - { - return string.Empty; - } - - string command = ConfigMakerCommandText.BuildOptionCommand( - _selectedCommand.Source, - _commandArgumentText); + string command = _commandHelpPanel.BuildSelectedCommand(); if (command == null) { ShowEditorMessage( diff --git a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Diagnostics.cs b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Diagnostics.cs index bebff810..1986c7ff 100644 --- a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Diagnostics.cs +++ b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Diagnostics.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Linq; using CDPIUI.Controls.CreateConfigHelper; using CDPIUI.Helper.CreateConfigHelper; using Microsoft.UI.Dispatching; @@ -11,21 +9,20 @@ namespace CDPIUI.ViewModels.ConfigMaker; public sealed partial class ConfigMakerViewModel { private readonly DispatcherQueueTimer _diagnosticsTimer; - private string _errorCountText = string.Empty; - private string _warningCountText = string.Empty; + private readonly ConfigMakerDiagnostics _diagnostics; public ObservableCollection Diagnostics { get; } = []; public string ErrorCountText { - get => _errorCountText; - private set => SetProperty(ref _errorCountText, value); + get => _diagnostics.ErrorCountText; + private set => _diagnostics.ErrorCountText = value; } public string WarningCountText { - get => _warningCountText; - private set => SetProperty(ref _warningCountText, value); + get => _diagnostics.WarningCountText; + private set => _diagnostics.WarningCountText = value; } private void ScheduleDiagnostics() @@ -40,57 +37,12 @@ private void DiagnosticsTimer_Tick(DispatcherQueueTimer sender, object args) RebuildDiagnostics(); } - private void RebuildDiagnostics() - { - string editorText = _view.EditorText; - List results = ComponentCommandValidationService - .Validate(editorText, _helpDocument.Options) - .ToList(); - ConfigMakerPresetReferenceValidator.AddDiagnostics( - editorText, - _presetDocument.Variables, - reference => _presetResources.FindAttached(reference) != null, - results); - - Diagnostics.Clear(); - foreach (ComponentCommandDiagnostic diagnostic in results) - { - Diagnostics.Add(CreateDiagnosticViewModel(diagnostic)); - } - - int errorCount = results.Count(item => item.Severity == ComponentCommandDiagnosticSeverity.Error); - int warningCount = results.Count - errorCount; - ErrorCountText = string.Format( - _localizer.GetLocalizedString("ConfigMakerDiagnosticErrorCount"), - errorCount); - WarningCountText = string.Format( - _localizer.GetLocalizedString("ConfigMakerDiagnosticWarningCount"), - warningCount); - _view.RefreshEditorHighlighting(); - } + private void RebuildDiagnostics() => _diagnostics.Rebuild(); private ConfigMakerDiagnosticViewModel CreateDiagnosticViewModel(ComponentCommandDiagnostic diagnostic) => new() { Source = diagnostic, - SeverityText = _localizer.GetLocalizedString( - diagnostic.Severity == ComponentCommandDiagnosticSeverity.Error - ? "ConfigMakerDiagnosticErrorSeverity" - : "ConfigMakerDiagnosticWarningSeverity"), - Description = diagnostic.Kind switch - { - ComponentCommandDiagnosticKind.UnknownFlag => string.Format( - _localizer.GetLocalizedString("ConfigMakerUnknownFlagDiagnostic"), - diagnostic.Token), - ComponentCommandDiagnosticKind.MissingRequiredArgument => string.Format( - _localizer.GetLocalizedString("ConfigMakerMissingArgumentDiagnostic"), - diagnostic.Token), - ComponentCommandDiagnosticKind.UnresolvedVariable => string.Format( - _localizer.GetLocalizedString("ConfigMakerUnresolvedVariableDiagnostic"), - diagnostic.Token), - ComponentCommandDiagnosticKind.UnresolvedResource => string.Format( - _localizer.GetLocalizedString("ConfigMakerUnresolvedResourceDiagnostic"), - diagnostic.Token), - _ => _localizer.GetLocalizedString("ConfigMakerUnterminatedQuoteDiagnostic"), - }, + SeverityText = _diagnostics.GetSeverityText(diagnostic), + Description = _diagnostics.GetDescription(diagnostic), }; } diff --git a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Document.cs b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Document.cs index 163bda92..62825d9e 100644 --- a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Document.cs +++ b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Document.cs @@ -21,168 +21,45 @@ public sealed partial class ConfigMakerViewModel public bool HasVariables => _presetDocument.HasVariables; public bool CanExportText => !HasVariables; - public void LoadPresetDocument(ConfigMakerPresetDocument document) - { - ArgumentNullException.ThrowIfNull(document); - _presetResources.BaseDirectory = string.Empty; - _presetDocument.Name = document.Name; - _presetDocument.ComponentId = document.ComponentId; - _presetDocument.PackId = document.PackId; - _presetDocument.FileName = document.FileName; - _presetDocument.Meta = document.Meta; - _presetDocument.TargetVersion = document.TargetVersion; - _presetDocument.Variables.Clear(); - foreach (ConfigMakerVariableDefinition variable in document.Variables) - { - _presetDocument.Variables.Add(variable.Clone()); - } - _presetDocument.Resources.Clear(); - foreach (ConfigMakerPresetResource resource in document.Resources) - { - _presetDocument.Resources.Add(resource.Clone()); - } - ComponentId = document.ComponentId; - SetEditorText(document.CommandText); - RebuildPresetStructure(); - UpdateSimpleDesignerAvailability(); - DocumentStateChanged?.Invoke(this, EventArgs.Empty); - } - - public async Task LoadConfigItem( - ConfigItem item, - bool applyAutoCorrectorSilently = false) - { - ArgumentNullException.ThrowIfNull(item); - LoadPresetDocument(ConfigMakerPresetDocument.FromConfigItem(item)); - _presetResources.BaseDirectory = ConfigMakerPresetResources.GetConfigItemBaseDirectory(item); - RebuildPresetStructure(); - if (applyAutoCorrectorSilently) - { - await ApplyAutoCorrectorSilentlyAsync(item); - } - AttachExistingPresetFiles(); - RebuildPresetStructure(); - } - - public ConfigItem CreateConfigItem(string packId, string presetName) - { - SyncDocumentFromEditor(); - return _presetDocument.ToConfigItem(packId, presetName); - } - - public async Task SaveToApplicationAsync() - { - SyncDocumentFromEditor(); - AttachExistingPresetFiles(); - SyncDocumentFromEditor(); - ConfigMakerSavePresetRequest request = await _view.AskSavePresetAsync( - _presetDocument.Name, - !string.IsNullOrWhiteSpace(_presetDocument.PackId) && - !string.IsNullOrWhiteSpace(_presetDocument.FileName)); - if (request == null) - { - return ConfigMakerPresetSaveResult.Failed("CANCELED"); - } - - ConfigMakerPresetStorageService storageService = new(); - ConfigMakerPresetSaveResult result = request.Overwrite - ? await storageService.OverwriteAsync(_presetDocument) - : await storageService.SaveAsync(request.PresetName, _presetDocument); - if (result.Success) - { - if (!request.Overwrite) - { - _presetDocument.Name = request.PresetName; - } - _presetDocument.PackId = result.PackId; - _presetDocument.FileName = result.ConfigFileName; - ApplyStoredResources(result); - ShowEditorMessage( - string.Format( - _localizer.GetLocalizedString("ConfigMakerPresetSavedMessage"), - _presetDocument.Name), - InfoBarSeverity.Success); - } - else if (!string.Equals(result.ErrorCode, "CANCELED", StringComparison.Ordinal)) - { - ShowEditorMessage( - string.Format( - _localizer.GetLocalizedString("ConfigMakerPresetSaveFailedMessage"), - string.IsNullOrWhiteSpace(result.ErrorDetails) - ? result.ErrorCode - : result.ErrorDetails), - InfoBarSeverity.Error); - } - return result; - } - - public async Task NewDocumentAsync() - { - if (IsEditorReadOnly) - { - return; - } - if ((!string.IsNullOrWhiteSpace(_view.EditorText) || - _presetDocument.HasVariables || - _presetDocument.HasResources) && - !await _view.ConfirmAsync( - _localizer.GetLocalizedString("ConfigMakerNewConfirmationTitle"), - _localizer.GetLocalizedString("ConfigMakerNewConfirmationMessage"), - _localizer.GetLocalizedString("Continue"))) - { - return; - } - - SetEditorText(string.Empty); - _presetResources.BaseDirectory = string.Empty; - _presetDocument.Name = string.Empty; - _presetDocument.Variables.Clear(); - _presetDocument.Resources.Clear(); - ClearPresetStructure(); - _view.ClearEditorUndoHistory(); - } - - public async Task SaveTextAsync() - { - try - { - string path = _view.ChooseExportPath(allowTextFormat: !HasVariables); - if (path == null) - { - return; - } - - SyncDocumentFromEditor(); - await ConfigMakerPresetExporter.ExportAsync(_presetDocument, path); - - ShowEditorMessage( - _localizer.GetLocalizedString("ConfigMakerTextSavedMessage"), - InfoBarSeverity.Success); - } - catch (Exception exception) - { - ShowEditorMessage( - string.Format( - _localizer.GetLocalizedString("ConfigMakerTextSaveFailedMessage"), - exception.Message), - InfoBarSeverity.Error); - } - } - - private void ApplyStoredResources(ConfigMakerPresetSaveResult result) - { - foreach (ConfigMakerPresetResource resource in _presetDocument.Resources) - { - ConfigMakerResourceMetadata? storedResource = result.StoredResources.FirstOrDefault(candidate => - string.Equals(candidate.alias, resource.Alias, StringComparison.OrdinalIgnoreCase)); - if (storedResource == null || string.IsNullOrWhiteSpace(storedResource.path)) - { - continue; - } - resource.Path = storedResource.path; - resource.IsBuiltIn = storedResource.isBuiltIn; - } - } + public void LoadPresetDocument(ConfigMakerPresetDocument document) => + _documentCoordinator.LoadPresetDocument(document); + + public Task LoadConfigItem(ConfigItem item, bool applyAutoCorrectorSilently = false) => + _documentCoordinator.LoadConfigItem(item, applyAutoCorrectorSilently); + + public ConfigItem CreateConfigItem(string packId, string presetName) => + _documentCoordinator.CreateConfigItem(packId, presetName); + + public Task SaveToApplicationAsync() => + _documentCoordinator.SaveToApplicationAsync(); + + public Task NewDocumentAsync() => _documentCoordinator.NewDocumentAsync(); + + public Task SaveTextAsync() => _documentCoordinator.SaveTextAsync(); + + string IConfigMakerDocumentHost.ComponentId { get => ComponentId; set => ComponentId = value; } + bool IConfigMakerDocumentHost.IsEditorReadOnly => IsEditorReadOnly; + string IConfigMakerDocumentHost.EditorText => _view.EditorText; + void IConfigMakerDocumentHost.SetEditorText(string text) => SetEditorText(text); + void IConfigMakerDocumentHost.SetBaseDirectory(string value) => _presetResources.BaseDirectory = value; + void IConfigMakerDocumentHost.RebuildPresetStructure() => RebuildPresetStructure(); + void IConfigMakerDocumentHost.UpdateSimpleDesignerAvailability() => UpdateSimpleDesignerAvailability(); + void IConfigMakerDocumentHost.NotifyDocumentStateChanged() => DocumentStateChanged?.Invoke(this, EventArgs.Empty); + void IConfigMakerDocumentHost.AttachExistingPresetFiles() => AttachExistingPresetFiles(); + Task IConfigMakerDocumentHost.ApplyAutoCorrectorSilentlyAsync(ConfigItem item) => ApplyAutoCorrectorSilentlyAsync(item); + string IConfigMakerDocumentHost.GetConfigItemBaseDirectory(ConfigItem item) => ConfigMakerPresetResources.GetConfigItemBaseDirectory(item); + Task IConfigMakerDocumentHost.AskSavePresetAsync(string suggestedName, bool overwriteEnabled) => + _view.AskSavePresetAsync(suggestedName, overwriteEnabled); + Task IConfigMakerDocumentHost.ConfirmNewDocumentAsync() => _view.ConfirmAsync( + _localizer.GetLocalizedString("ConfigMakerNewConfirmationTitle"), + _localizer.GetLocalizedString("ConfigMakerNewConfirmationMessage"), + _localizer.GetLocalizedString("Continue")); + string IConfigMakerDocumentHost.ChooseExportPath(bool allowTextFormat) => _view.ChooseExportPath(allowTextFormat); + void IConfigMakerDocumentHost.ClearPresetStructure() => ClearPresetStructure(); + void IConfigMakerDocumentHost.ClearEditorUndoHistory() => _view.ClearEditorUndoHistory(); + string IConfigMakerDocumentHost.Text(string key) => _localizer.GetLocalizedString(key); + void IConfigMakerDocumentHost.ShowDocumentMessage(string message, bool isError) => + ShowEditorMessage(message, isError ? InfoBarSeverity.Error : InfoBarSeverity.Success); private async Task ApplyAutoCorrectorSilentlyAsync(ConfigItem sourceConfig) { @@ -229,11 +106,7 @@ private void AttachExistingPresetFiles() } } - private void SyncDocumentFromEditor() - { - _presetDocument.ComponentId = ComponentId; - _presetDocument.CommandText = _view.EditorText ?? string.Empty; - } + private void SyncDocumentFromEditor() => _documentCoordinator.SyncDocumentFromEditor(); private void PresetDocument_ContentChanged(object sender, EventArgs e) { diff --git a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.PresetFiles.cs b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.PresetFiles.cs index 84cf36f6..c00d9c7f 100644 --- a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.PresetFiles.cs +++ b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.PresetFiles.cs @@ -1,12 +1,7 @@ using System; using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Threading.Tasks; -using CDPIUI.AddOns.ConfigImport; using CDPIUI.Controls.CreateConfigHelper; -using CDPIUI.Core.ComponentServices.Helpers.Configuration; -using CDPIUI.Core.System; using CDPIUI.Helper.CreateConfigHelper; using Microsoft.UI.Xaml.Controls; @@ -19,309 +14,67 @@ public sealed partial class ConfigMakerViewModel public RelayCommand AddPresetFileCommand { get; } - public void AddPresetFiles(IEnumerable filePaths) - { - ArgumentNullException.ThrowIfNull(filePaths); - int added = _presetResources.AddFiles(filePaths); - if (added > 0) - { - AttachExistingPresetFiles(); - RebuildPresetStructure(); - _view.SetPresetFilesPanelVisible(true); - ShowEditorMessage( - string.Format( - _localizer.GetLocalizedString("ConfigMakerPresetFilesAddedMessage"), - added), - InfoBarSeverity.Success); - } - } + public void AddPresetFiles(IEnumerable filePaths) => _presetFileActions.AddPresetFiles(filePaths); public Task ReplacePresetFileAsync(ConfigMakerPresetFileInfo file) => - RunReportingErrorsAsync(async () => - { - if (file == null) - { - return; - } - - string missingPath = _presetResources.TryResolvePath(file.Path); - if (string.IsNullOrWhiteSpace(missingPath)) - { - ShowEditorMessage( - _localizer.GetLocalizedString("ConfigMakerPresetFileInvalidPathMessage"), - InfoBarSeverity.Error); - return; - } - if (File.Exists(missingPath)) - { - RebuildPresetStructure(); - return; - } - - ConfigMakerFileReplacementChoice choice = await _view.AskPresetFileReplacementAsync(missingPath); - if (choice == ConfigMakerFileReplacementChoice.AutoCorrect) - { - await AutoCorrectPresetFileAsync(file, missingPath); - } - else if (choice == ConfigMakerFileReplacementChoice.ChooseManually) - { - ChooseAndApplyPresetFileReplacement(file, missingPath); - } - }); - - public Task OpenPresetFileAsync(ConfigMakerPresetFileInfo file) => - RunReportingErrorsAsync(async () => - { - if (file == null) - { - return; - } - - string path = _presetResources.ResolvePath(file.Path); - if (!File.Exists(path)) - { - ShowPresetFileMissing(path); - return; - } - - if (file.Kind == ConfigMakerPresetFileKind.SiteList || - string.Equals(Path.GetExtension(path), ".txt", StringComparison.OrdinalIgnoreCase)) - { - if (TextFileOpenPreferences.ShouldAskForApplication()) - { - if (await _view.AskTextFileApplicationAsync(path)) - { - TextFileOpenPreferences.RememberDialogShown(); - } - return; - } - - ShellHelper.OpenFile(path); - return; - } - - ShellHelper.OpenFileInDefaultApp(path); - }); + _presetFileReplacer.ReplacePresetFileAsync(file); - public void ShowPresetFileInFolder(ConfigMakerPresetFileInfo file) - { - if (file == null) - { - return; - } - - string path = _presetResources.ResolvePath(file.Path); - if (!File.Exists(path)) - { - ShowPresetFileMissing(path); - return; - } - ShellHelper.LookupFileInDirectory(path); - } - - public Task RemovePresetFileAsync(ConfigMakerPresetFileInfo file) => - RunReportingErrorsAsync(async () => - { - ConfigMakerPresetResource resource = file == null ? null : _presetResources.FindAttached(file.Path); - if (resource == null) - { - return; - } - if (_presetResources.IsReferenced(resource) && - !await _view.ConfirmAsync( - _localizer.GetLocalizedString("ConfigMakerRemoveReferencedFileDialogTitle"), - _localizer.GetLocalizedString("ConfigMakerRemoveReferencedFileDialogMessage"), - _localizer.GetLocalizedString("Remove"))) - { - return; - } - _presetDocument.Resources.Remove(resource); - RebuildPresetStructure(); - ScheduleDiagnostics(); - }); + public Task OpenPresetFileAsync(ConfigMakerPresetFileInfo file) => _presetFileActions.OpenPresetFileAsync(file); + public void ShowPresetFileInFolder(ConfigMakerPresetFileInfo file) => _presetFileActions.ShowPresetFileInFolder(file); + public Task RemovePresetFileAsync(ConfigMakerPresetFileInfo file) => _presetFileActions.RemovePresetFileAsync(file); /// Inserts the reference of a file of the tree at the editor cursor, attaching the file first. - public void InsertPresetFileReference(ConfigMakerPresetFileInfo file) - { - if (IsEditorReadOnly || file == null) - { - return; - } - string reference = file.Path.Trim().Trim('"'); - if (!reference.StartsWith("preset://", StringComparison.OrdinalIgnoreCase)) - { - string resolvedPath = _presetResources.TryResolvePath(reference); - if (!string.IsNullOrWhiteSpace(resolvedPath) && File.Exists(resolvedPath)) - { - ConfigMakerPresetResource resource = _presetResources.GetOrCreate( - Path.GetFullPath(resolvedPath), - file.Kind, - out bool resourceAdded); - if (resourceAdded) - { - RebuildPresetStructure(); - } - reference = resource.Reference; - } - } - InsertAtCursor($"\"{reference}\""); - } + public void InsertPresetFileReference(ConfigMakerPresetFileInfo file) => _presetFileActions.InsertPresetFileReference(file); - private void AddPresetFilesFromPicker() - { - IReadOnlyList filePaths = _view.ChoosePresetFilesToAdd(); - if (filePaths.Count > 0) - { - AddPresetFiles(filePaths); - } - } + private void AddPresetFilesFromPicker() => _presetFileActions.AddPresetFilesFromPicker(); - private async Task AutoCorrectPresetFileAsync(ConfigMakerPresetFileInfo file, string missingPath) - { - ConfigImportAutoCorrector autoCorrector = new(); - bool suggestEmptyFile = autoCorrector.ShouldSuggestEmptyFile(missingPath); - if (suggestEmptyFile) - { - TryCreateEmptyPresetFile(missingPath); - return; - } - - ConfigImportResult autoCorrectResult = _presetResources.CreateAutoCorrectResult(missingPath); - string suggestion = await Task.Run(() => autoCorrector.FindReplacement( - autoCorrectResult, - missingPath)); - if (!string.IsNullOrWhiteSpace(suggestion)) - { - TryApplyPresetFileReplacement(file, suggestion, showStatus: true); - return; - } - - ShowEditorMessage( - _localizer.GetLocalizedString("ConfigMakerPresetFileNoSuggestionMessage"), - InfoBarSeverity.Warning); - ChooseAndApplyPresetFileReplacement(file, missingPath); - } - - private void ChooseAndApplyPresetFileReplacement(ConfigMakerPresetFileInfo file, string missingPath) - { - string selectedPath = _view.ChooseReplacementFile(missingPath); - if (!string.IsNullOrWhiteSpace(selectedPath)) - { - TryApplyPresetFileReplacement(file, selectedPath, showStatus: true); - } - } + private bool TryCreateEmptyPresetFile(string missingPath, bool showStatus = true) => + _presetFileReplacer.TryCreateEmptyPresetFile(missingPath, showStatus); - private bool TryCreateEmptyPresetFile(string missingPath, bool showStatus = true) - { - try - { - ConfigMakerPresetResources.CreateEmptyFile(missingPath); - RebuildPresetStructure(); - if (showStatus) - { - ShowEditorMessage( - string.Format( - _localizer.GetLocalizedString("ConfigMakerPresetFileEmptyCreatedMessage"), - missingPath), - InfoBarSeverity.Success); - } - return true; - } - catch (Exception ex) - { - if (showStatus) - { - ShowPresetFileReplaceFailed(ex); - } - return false; - } - } + private bool TryApplyPresetFileReplacement(ConfigMakerPresetFileInfo file, string replacementPath, bool showStatus) => + _presetFileReplacer.TryApplyPresetFileReplacement(file, replacementPath, showStatus); - private bool TryApplyPresetFileReplacement( - ConfigMakerPresetFileInfo file, - string replacementPath, - bool showStatus) + Task IConfigMakerPresetFileReplacementHost.RunReportingErrorsAsync(Func action) => RunReportingErrorsAsync(action); + Task IConfigMakerPresetFileReplacementHost.AskPresetFileReplacementAsync(string path) => _view.AskPresetFileReplacementAsync(path); + string IConfigMakerPresetFileReplacementHost.ChooseReplacementFile(string path) => _view.ChooseReplacementFile(path); + string IConfigMakerPresetFileReplacementHost.Text(string key) => _localizer.GetLocalizedString(key); + void IConfigMakerPresetFileReplacementHost.RebuildPresetStructure() => RebuildPresetStructure(); + bool IConfigMakerPresetFileReplacementHost.UsesExplicitPresetStructure => _presetStructure.UsesExplicitPresetStructure; + ConfigMakerPresetFileInfo[] IConfigMakerPresetFileReplacementHost.ExplicitPresetFiles { - try - { - string fullReplacementPath = Path.GetFullPath(replacementPath); - if (!File.Exists(fullReplacementPath)) - { - throw new FileNotFoundException(null, fullReplacementPath); - } - - if (_presetResources.TryUpdateAttachedResource(file, fullReplacementPath)) - { - RebuildPresetStructure(); - if (showStatus) - { - ShowPresetFileReplaced(fullReplacementPath); - } - return true; - } - - ConfigMakerPresetFileReplacement replacement = _presetResources.ReplaceReferences( - file, - fullReplacementPath) ?? throw new InvalidOperationException( - _localizer.GetLocalizedString("ConfigMakerPresetFileReferenceNotFoundMessage")); - - if (_usesExplicitPresetStructure) - { - _explicitPresetFiles = _explicitPresetFiles - .Select(item => ReferenceEquals(item, file) || - (item.Kind == file.Kind && ConfigFileReferences.PathsEqual(item.Path, file.Path)) - ? item with - { - Name = Path.GetFileName(fullReplacementPath), - Path = replacement.Reference, - Folder = ConfigFileReferences.GetDisplayFolder(replacement.Reference), - } - : item) - .ToArray(); - } - if (replacement.CommandChanged) - { - CommandText = ComponentCommandLineFormatter.FormatByFlags(replacement.UpdatedCommandText); - } - RebuildPresetStructure(); - PresetFileReplaced?.Invoke( - this, - new ConfigMakerPresetFileReplacedEventArgs( - CommandText, - file.Path, - replacement.Reference)); - if (showStatus) - { - ShowPresetFileReplaced(fullReplacementPath); - } - return true; - } - catch (Exception ex) - { - if (showStatus) - { - ShowPresetFileReplaceFailed(ex); - } - return false; - } + get => _presetStructure.ExplicitPresetFiles; + set => _presetStructure.ExplicitPresetFiles = value; } + void IConfigMakerPresetFileReplacementHost.SetCommandText(string text) => CommandText = text; + void IConfigMakerPresetFileReplacementHost.NotifyPresetFileReplaced(string originalPath, string replacementPath) => + PresetFileReplaced?.Invoke(this, new ConfigMakerPresetFileReplacedEventArgs(CommandText, originalPath, replacementPath)); + void IConfigMakerPresetFileReplacementHost.ShowPresetFileMessage(string message, ConfigMakerPresetFileNoticeSeverity severity) => + ShowEditorMessage(message, severity switch + { + ConfigMakerPresetFileNoticeSeverity.Success => InfoBarSeverity.Success, + ConfigMakerPresetFileNoticeSeverity.Warning => InfoBarSeverity.Warning, + _ => InfoBarSeverity.Error, + }); - private void ShowPresetFileReplaced(string fullReplacementPath) => - ShowEditorMessage( - string.Format( - _localizer.GetLocalizedString("ConfigMakerPresetFileReplacedMessage"), - fullReplacementPath), - InfoBarSeverity.Success); - - private void ShowPresetFileReplaceFailed(Exception exception) => - ShowEditorMessage( - string.Format( - _localizer.GetLocalizedString("ConfigMakerPresetFileReplaceFailedMessage"), - exception.Message), - InfoBarSeverity.Error); - - private void ShowPresetFileMissing(string path) => - ShowEditorMessage( - string.Format(_localizer.GetLocalizedString("ConfigMakerPresetFileMissingMessage"), path), - InfoBarSeverity.Warning); + bool IConfigMakerPresetFileActionsHost.IsEditorReadOnly => IsEditorReadOnly; + Task IConfigMakerPresetFileActionsHost.RunReportingErrorsAsync(Func action) => RunReportingErrorsAsync(action); + IReadOnlyList IConfigMakerPresetFileActionsHost.ChoosePresetFilesToAdd() => _view.ChoosePresetFilesToAdd(); + void IConfigMakerPresetFileActionsHost.AttachExistingPresetFiles() => AttachExistingPresetFiles(); + void IConfigMakerPresetFileActionsHost.RebuildPresetStructure() => RebuildPresetStructure(); + void IConfigMakerPresetFileActionsHost.SetPresetFilesPanelVisible(bool visible) => _view.SetPresetFilesPanelVisible(visible); + string IConfigMakerPresetFileActionsHost.Text(string key) => _localizer.GetLocalizedString(key); + Task IConfigMakerPresetFileActionsHost.AskTextFileApplicationAsync(string path) => _view.AskTextFileApplicationAsync(path); + Task IConfigMakerPresetFileActionsHost.ConfirmRemoveReferencedFileAsync() => _view.ConfirmAsync( + _localizer.GetLocalizedString("ConfigMakerRemoveReferencedFileDialogTitle"), + _localizer.GetLocalizedString("ConfigMakerRemoveReferencedFileDialogMessage"), + _localizer.GetLocalizedString("Remove")); + void IConfigMakerPresetFileActionsHost.ScheduleDiagnostics() => ScheduleDiagnostics(); + void IConfigMakerPresetFileActionsHost.InsertAtCursor(string reference) => InsertAtCursor(reference); + void IConfigMakerPresetFileActionsHost.ShowPresetFileMessage(string message, ConfigMakerPresetFileNoticeSeverity severity) => + ShowEditorMessage(message, severity switch + { + ConfigMakerPresetFileNoticeSeverity.Success => InfoBarSeverity.Success, + ConfigMakerPresetFileNoticeSeverity.Warning => InfoBarSeverity.Warning, + _ => InfoBarSeverity.Error, + }); } diff --git a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.PresetStructure.cs b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.PresetStructure.cs index 29880fcd..8c362fe3 100644 --- a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.PresetStructure.cs +++ b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.PresetStructure.cs @@ -1,13 +1,8 @@ using System; using System.Collections.Generic; -using System.IO; -using System.Linq; using CDPIUI.Controls.CreateConfigHelper; -using CDPIUI.Core.ComponentServices.Helpers.Configuration; using CDPIUI.Core.Store.Data; -using CDPIUI.Core.Store.Database; using CDPIUI.Helper.CreateConfigHelper; -using ParsedPresetOption = CDPIUI.Core.ComponentServices.Helpers.Configuration.ConfigCommandOption; namespace CDPIUI.ViewModels.ConfigMaker; @@ -15,32 +10,27 @@ namespace CDPIUI.ViewModels.ConfigMaker; public sealed partial class ConfigMakerViewModel { private readonly Zapret2PresetOptionDescriber _zapret2OptionDescriber; - private bool _hasPresetFiles; - private bool _hasPresetGroups; - private bool _usesExplicitPresetStructure; - private ConfigMakerPresetFileInfo[] _explicitPresetFiles = []; - private ConfigMakerPresetGroupInfo[] _explicitPresetGroups = []; - private IReadOnlyList _presetFileNodes = []; - private IReadOnlyList _presetGroupNodes = []; + private readonly ConfigMakerPresetTreeBuilder _presetTreeBuilder; + private readonly ConfigMakerPresetStructure _presetStructure; /// Raised when the preset files or the preset groups appear or disappear. public event EventHandler PresetStructureAvailabilityChanged; public IReadOnlyList PresetFileNodes { - get => _presetFileNodes; - private set => SetProperty(ref _presetFileNodes, value); + get => _presetStructure.PresetFileNodes; + private set => _presetStructure.PresetFileNodes = value; } public IReadOnlyList PresetGroupNodes { - get => _presetGroupNodes; - private set => SetProperty(ref _presetGroupNodes, value); + get => _presetStructure.PresetGroupNodes; + private set => _presetStructure.PresetGroupNodes = value; } - public bool IsPresetStructureVisible => _hasPresetFiles || HasPresetGroups; - public bool HasPresetFiles => _hasPresetFiles; - public bool HasPresetGroups => _hasPresetGroups || !_usesExplicitPresetStructure; + public bool IsPresetStructureVisible => _presetStructure.IsPresetStructureVisible; + public bool HasPresetFiles => _presetStructure.HasPresetFiles; + public bool HasPresetGroups => _presetStructure.HasPresetGroups; private bool IsZapret2Component => string.Equals( ComponentId, @@ -49,261 +39,9 @@ public IReadOnlyList PresetGroupNodes public void SetPresetStructure( IEnumerable files, - IEnumerable groups) - { - ArgumentNullException.ThrowIfNull(files); - ArgumentNullException.ThrowIfNull(groups); - - _explicitPresetFiles = files - .Where(file => !string.IsNullOrWhiteSpace(file.Path)) - .DistinctBy(file => (file.Kind, file.Path), ConfigMakerPresetFileKeyComparer.Instance) - .ToArray(); - _explicitPresetGroups = groups.ToArray(); - _usesExplicitPresetStructure = true; - RebuildPresetStructure(); - } - - public void ClearPresetStructure() - { - _usesExplicitPresetStructure = false; - _explicitPresetFiles = []; - _explicitPresetGroups = []; - RebuildPresetStructure(); - } - - private void RebuildPresetStructure() - { - ConfigMakerPresetFileInfo[] detectedFiles = _presetResources.ExtractFiles(CommandText).ToArray(); - ConfigMakerPresetFileInfo[] baseFiles = _usesExplicitPresetStructure - ? EnrichExplicitPresetFiles(_explicitPresetFiles, detectedFiles) - : detectedFiles; - ConfigMakerPresetFileInfo[] attachedFiles = _presetResources.GetAttachedFiles().ToArray(); - ConfigMakerPresetFileInfo[] files = baseFiles - .Concat(attachedFiles) - .DistinctBy(file => (file.Kind, file.Path), ConfigMakerPresetFileKeyComparer.Instance) - .ToArray(); - - PresetFileNodes = BuildPresetFileNodes(files); - List groupNodes = BuildPresetGroupNodes(ConfigCommandLine.ParseOptions(CommandText)); - - bool filesAvailabilityChanged = _hasPresetFiles != (files.Length > 0); - bool groupsAvailabilityChanged = _hasPresetGroups != (groupNodes.Count > 0); - _hasPresetFiles = files.Length > 0; - _hasPresetGroups = groupNodes.Count > 0; - - // The view shows or hides the preset groups tab from HasPresetGroups when the nodes change. - PresetGroupNodes = groupNodes; - OnPropertiesChanged(nameof(HasPresetFiles), nameof(HasPresetGroups), nameof(IsPresetStructureVisible)); - if (filesAvailabilityChanged || groupsAvailabilityChanged) - { - PresetStructureAvailabilityChanged?.Invoke(this, EventArgs.Empty); - } - } - - private static ConfigMakerPresetFileInfo[] EnrichExplicitPresetFiles( - IReadOnlyList files, - IReadOnlyList detectedFiles) - { - return files - .Select(file => - { - ConfigMakerPresetFileInfo detected = detectedFiles.FirstOrDefault(candidate => - candidate.Kind == file.Kind && ConfigFileReferences.PathsEqual(candidate.Path, file.Path)); - return detected == null || !string.IsNullOrWhiteSpace(file.OptionName) - ? file - : file with { OptionName = detected.OptionName }; - }) - .ToArray(); - } - - private List BuildPresetFileNodes(IReadOnlyList fileItems) - { - List nodes = []; - foreach (ConfigMakerPresetFileKind kind in Enum.GetValues()) - { - ConfigMakerPresetFileInfo[] categoryFiles = fileItems - .Where(file => file.Kind == kind) - .OrderBy(file => file.Name, StringComparer.CurrentCultureIgnoreCase) - .ToArray(); - if (categoryFiles.Length == 0) - { - continue; - } - - ConfigMakerTreeNode categoryNode = new( - new ConfigMakerPresetFileTreeItem - { - DisplayName = PresetFileCategoryName(kind), - ToolTip = PresetFileCategoryName(kind), - }, - isExpanded: true); - foreach (ConfigMakerPresetFileInfo file in categoryFiles) - { - categoryNode.Children.Add(new ConfigMakerTreeNode(CreatePresetFileTreeItem(file))); - } - nodes.Add(categoryNode); - } - return nodes; - } - - private ConfigMakerPresetFileTreeItem CreatePresetFileTreeItem(ConfigMakerPresetFileInfo file) - { - string resolvedPath = _presetResources.TryResolvePath(file.Path); - bool isMissing = string.IsNullOrWhiteSpace(resolvedPath) || !File.Exists(resolvedPath); - return new ConfigMakerPresetFileTreeItem - { - DisplayName = file.Name, - ToolTip = isMissing - ? string.Format( - _localizer.GetLocalizedString("ConfigMakerPresetFileMissingMessage"), - resolvedPath ?? file.Path) - : file.IsAttachedResource - ? $"{file.Path}{Environment.NewLine}{resolvedPath}" - : resolvedPath, - File = file, - IsMissing = isMissing, - }; - } - - private List BuildPresetGroupNodes(IReadOnlyList options) - { - List nodes = []; - if (options.Count == 0) - { - AddExplicitPresetGroupsFallback(nodes); - return nodes; - } - - int firstProfileOption = ConfigMakerPresetOptionGroups.FindFirstProfileOptionIndex(options); - IReadOnlyList common = options.Take(firstProfileOption).ToArray(); - AddOptionNode( - nodes, - _localizer.GetLocalizedString("ConfigMakerPresetCommonFiltersGroup"), - common.Where(option => ConfigMakerPresetOptionGroups.IsCommonFilter(option.Name)), - "ConfigMakerZapret2CommonFiltersDescription"); - AddOptionNode( - nodes, - _localizer.GetLocalizedString("ConfigMakerPresetCommonOptionsGroup"), - common.Where(option => !ConfigMakerPresetOptionGroups.IsCommonFilter(option.Name)), - "ConfigMakerZapret2CommonOptionsDescription"); - - List> profiles = - ConfigMakerPresetOptionGroups.SplitProfiles(options.Skip(firstProfileOption)); - for (int index = 0; index < profiles.Count; index++) - { - AddPresetProfileNode(nodes, profiles[index], index); - } - - if (nodes.Count == 0) - { - AddExplicitPresetGroupsFallback(nodes); - } - return nodes; - } - - private void AddPresetProfileNode( - List nodes, - IReadOnlyList options, - int profileIndex) - { - string parsedName = ConfigMakerPresetOptionGroups.FindProfileName(options); - string explicitName = profileIndex < _explicitPresetGroups.Length - ? _explicitPresetGroups[profileIndex].Name - : string.Empty; - string name = !string.IsNullOrWhiteSpace(explicitName) - ? explicitName - : !string.IsNullOrWhiteSpace(parsedName) - ? ConfigCommandLine.Unquote(parsedName) - : string.Format( - _localizer.GetLocalizedString("ConfigMakerPresetProfileFallbackName"), - profileIndex + 1); - - ConfigMakerTreeNode profileNode = new( - CreatePresetTreeItem(name, GetZapret2Description("ConfigMakerZapret2ProfileDescription")), - isExpanded: true); - AddOptionNode( - profileNode.Children, - _localizer.GetLocalizedString("ConfigMakerPresetProfileFiltersGroup"), - options.Where(option => ConfigMakerPresetOptionGroups.IsProfileFilter(option.Name)), - "ConfigMakerZapret2ProfileFiltersDescription"); - AddOptionNode( - profileNode.Children, - _localizer.GetLocalizedString("ConfigMakerPresetProfileActionsGroup"), - options.Where(option => !ConfigMakerPresetOptionGroups.IsProfileFilter(option.Name)), - "ConfigMakerZapret2ProfileActionsDescription"); - if (profileNode.Children.Count > 0) - { - nodes.Add(profileNode); - } - } - - private void AddOptionNode( - List nodes, - string name, - IEnumerable options, - string descriptionResourceKey) - { - ParsedPresetOption[] items = options.ToArray(); - if (items.Length == 0) - { - return; - } - ConfigMakerTreeNode node = new( - CreatePresetTreeItem(name, GetZapret2Description(descriptionResourceKey)), - isExpanded: true); - foreach (ParsedPresetOption option in items) - { - node.Children.Add(new ConfigMakerTreeNode(CreatePresetTreeItem( - option.DisplayText, - GetPresetOptionDescription(option), - isCode: true, - source: option))); - } - nodes.Add(node); - } - - private void AddExplicitPresetGroupsFallback(List nodes) - { - foreach (ConfigMakerPresetGroupInfo group in _explicitPresetGroups) - { - ConfigMakerTreeNode node = new(CreatePresetTreeItem(group.Name)); - foreach (string detail in group.Details.Where(value => !string.IsNullOrWhiteSpace(value))) - { - node.Children.Add(new ConfigMakerTreeNode(CreatePresetTreeItem(detail, isCode: true))); - } - nodes.Add(node); - } - } - - private static ConfigMakerPresetTreeItemViewModel CreatePresetTreeItem( - string title, - string description = "", - bool isCode = false, - ParsedPresetOption source = null) => new() - { - Title = title ?? string.Empty, - Description = description ?? string.Empty, - IsCode = isCode, - SourceIndex = source?.SourceIndex ?? -1, - SourceLength = source?.SourceLength ?? 0, - SourceLine = source?.SourceLine ?? 0, - SourceColumn = source?.SourceColumn ?? 0, - }; - - private string GetZapret2Description(string resourceKey) => IsZapret2Component && - !string.IsNullOrWhiteSpace(resourceKey) - ? _localizer.GetLocalizedString(resourceKey) - : string.Empty; + IEnumerable groups) => _presetStructure.Set(files, groups); - private string GetPresetOptionDescription(ParsedPresetOption option) => IsZapret2Component - ? _zapret2OptionDescriber.Describe(option, _helpDocument.Options) - : string.Empty; + public void ClearPresetStructure() => _presetStructure.Clear(); - private string PresetFileCategoryName(ConfigMakerPresetFileKind kind) => - _localizer.GetLocalizedString(kind switch - { - ConfigMakerPresetFileKind.Library => "ConfigMakerPresetFileCategoryLibraries", - ConfigMakerPresetFileKind.Payload => "ConfigMakerPresetFileCategoryPayloads", - _ => "ConfigMakerPresetFileCategorySiteLists", - }); + private void RebuildPresetStructure() => _presetStructure.Rebuild(); } diff --git a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.SimpleDesigner.cs b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.SimpleDesigner.cs index 579339e7..ca63191d 100644 --- a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.SimpleDesigner.cs +++ b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.SimpleDesigner.cs @@ -1,225 +1,49 @@ using System; using System.Collections.ObjectModel; -using System.IO; -using System.Linq; using System.Windows.Input; -using CDPIUI.Core.Store.Data; -using CDPIUI.Core.Store.Database; using CDPIUI.Helper.CreateConfigHelper; using CDPIUI.Views.CreateConfigHelper; using Microsoft.UI.Xaml.Controls; namespace CDPIUI.ViewModels.ConfigMaker; -// The simple graphic designer for GoodbyeDPI, SpoofDPI and NoDPI. +// The view-facing contract of the simple graphic designer. public sealed partial class ConfigMakerViewModel { - private bool _updatingDesigner; - private bool _designerNeedsRefresh = true; - private string _additionalDesignerArguments = string.Empty; + private readonly ConfigMakerSimpleDesigner _simpleDesigner; - public ObservableCollection DesignerSettingItemModels { get; } = []; - public ObservableCollection DesignerExclusiveSettingItemModels { get; } = []; + public ObservableCollection DesignerSettingItemModels => + _simpleDesigner.DesignerSettingItemModels; + public ObservableCollection DesignerExclusiveSettingItemModels => + _simpleDesigner.DesignerExclusiveSettingItemModels; public ICommand DesignerTextValueChangedCommand { get; } public ICommand DesignerBoolValueToggledCommand { get; } public ICommand DesignerSelectedGuidChangedCommand { get; } - - public bool IsSimpleDesignerSupported => IsSimpleDesignerComponent(ComponentId); - - public string AdditionalDesignerArguments - { - get => _additionalDesignerArguments; - private set => SetProperty(ref _additionalDesignerArguments, value ?? string.Empty); - } + public bool IsSimpleDesignerSupported => _simpleDesigner.IsSimpleDesignerSupported; + public string AdditionalDesignerArguments => _simpleDesigner.AdditionalDesignerArguments; /// Called by the view when the text of the additional arguments box changed. - public void OnAdditionalDesignerArgumentsChanged(string text) - { - // The box already shows the text: store it without raising a change back to it. - _additionalDesignerArguments = text ?? string.Empty; - ApplySimpleDesignerToCommand(); - } + public void OnAdditionalDesignerArgumentsChanged(string text) => + _simpleDesigner.OnAdditionalDesignerArgumentsChanged(text); - /// Called by the view when the editor switches between the code editor and the designer. - public void OnEditorViewChanged(bool leftDesigner, bool enteredDesigner) - { - if (leftDesigner) - { - ApplySimpleDesignerToCommand(); - } - if (enteredDesigner && _designerNeedsRefresh) - { - LoadSimpleDesigner(); - } - } - - private static bool IsSimpleDesignerComponent(string componentId) => - string.Equals(componentId, HardcodedItemIds.ComponentIds[Components.GoodbyeDPI], StringComparison.OrdinalIgnoreCase) || - string.Equals(componentId, HardcodedItemIds.ComponentIds[Components.SpoofDPI], StringComparison.OrdinalIgnoreCase) || - string.Equals(componentId, HardcodedItemIds.ComponentIds[Components.NoDPI], StringComparison.OrdinalIgnoreCase); - - // The view shows or hides the designer tab when IsSimpleDesignerSupported is raised. - private void UpdateSimpleDesignerAvailability() - { - OnPropertyChanged(nameof(IsSimpleDesignerSupported)); - if (!IsSimpleDesignerSupported) - { - DesignerSettingItemModels.Clear(); - DesignerExclusiveSettingItemModels.Clear(); - } - } + /// Called by the view when the editor switches between code and designer. + public void OnEditorViewChanged(bool leftDesigner, bool enteredDesigner) => + _simpleDesigner.OnEditorViewChanged(leftDesigner, enteredDesigner); - private void LoadSimpleDesigner() - { - if (!IsSimpleDesignerSupported) - { - return; - } - _updatingDesigner = true; - try - { - AdditionalDesignerArguments = ComponentCommandLineFormatter.ToSingleLine(_view.EditorText); - DesignerSettingItemModels.Clear(); - DesignerExclusiveSettingItemModels.Clear(); - if (!TryLoadDesignerModels()) - { - return; - } - AttachSimpleDesignerCommands(); - AdditionalDesignerArguments = - GraphicDesignerHelper.ConvertStringToGraphicDesignerSettings( - DesignerSettingItemModels, - DesignerExclusiveSettingItemModels, - ComponentCommandLineFormatter.ToSingleLine(_view.EditorText)); - _designerNeedsRefresh = false; - } - catch (Exception exception) - { - DesignerSettingItemModels.Clear(); - DesignerExclusiveSettingItemModels.Clear(); - Core.Basic.Logger.Instance.CreateWarningLog(LogSource, exception.ToString()); - ShowEditorMessage( - string.Format(_localizer.GetLocalizedString("ConfigMakerDesignerLoadFailedMessage"), exception.Message), - InfoBarSeverity.Warning); - } - finally - { - _updatingDesigner = false; - } - } + private void UpdateSimpleDesignerAvailability() => _simpleDesigner.UpdateAvailability(); - // Returns false when the NoDPI annotation file is missing. - private bool TryLoadDesignerModels() + private void ShowDesignerNotice(ConfigMakerDesignerNotice notice, Exception exception) { - if (string.Equals( - ComponentId, - HardcodedItemIds.ComponentIds[Components.GoodbyeDPI], - StringComparison.OrdinalIgnoreCase)) - { - GraphicDesignerHelper.LoadGoodbyeDPIDesignerConfig( - DesignerSettingItemModels, - DesignerExclusiveSettingItemModels); - return true; - } - if (string.Equals( - ComponentId, - HardcodedItemIds.ComponentIds[Components.SpoofDPI], - StringComparison.OrdinalIgnoreCase)) - { - GraphicDesignerHelper.LoadSpoofDPIDesignerConfig( - DesignerSettingItemModels, - DesignerExclusiveSettingItemModels); - return true; - } - - string componentDirectory = DatabaseHelper.Instance.GetItemById(ComponentId)?.Directory ?? string.Empty; - string annotationPath = Path.Combine(componentDirectory, "edannotationfile.xml"); - if (!File.Exists(annotationPath)) + if (notice == ConfigMakerDesignerNotice.MissingAnnotation) { ShowEditorMessage( _localizer.GetLocalizedString("ConfigMakerSimpleDesignerAnnotationMissingMessage"), InfoBarSeverity.Warning); - return false; - } - GraphicDesignerHelper.XML_LoadDesignerConfig( - annotationPath, - "nodpi", - DesignerSettingItemModels, - DesignerExclusiveSettingItemModels); - return true; - } - - private void AttachSimpleDesignerCommands() - { - foreach (GraphicDesignerSettingItemModel item in DesignerSettingItemModels) - { - item.DesignerTextValueChangedCommand = DesignerTextValueChangedCommand; - item.DesignerBoolValueToggledCommand = DesignerBoolValueToggledCommand; - } - foreach (GraphicDesignerExclusiveSettingItemModel group in DesignerExclusiveSettingItemModels) - { - group.DesignerTextValueChangedCommand = DesignerTextValueChangedCommand; - group.DesignerBoolValueToggledCommand = DesignerBoolValueToggledCommand; - group.DesignerSelectedGuidChangedCommand = DesignerSelectedGuidChangedCommand; - } - } - - private void HandleDesignerTextValueChanged(Tuple change) - { - GraphicDesignerSettingItemModel item = FindDesignerItem(change.Item1); - if (item != null) - { - item.Value = change.Item2; - ApplySimpleDesignerToCommand(); - } - } - - private void HandleDesignerBoolValueToggled(Tuple change) - { - GraphicDesignerSettingItemModel item = FindDesignerItem(change.Item1); - if (item != null) - { - item.IsChecked = change.Item2; - ApplySimpleDesignerToCommand(); - } - } - - private void HandleDesignerSelectedGuidChanged(Tuple change) - { - GraphicDesignerExclusiveSettingItemModel group = DesignerExclusiveSettingItemModels.FirstOrDefault(item => - string.Equals(item.Guid, change.Item1, StringComparison.Ordinal)); - if (group != null) - { - group.SelectedItemGuid = change.Item2; - ApplySimpleDesignerToCommand(); - } - } - - private GraphicDesignerSettingItemModel FindDesignerItem(string id) => - DesignerSettingItemModels.FirstOrDefault(item => string.Equals(item.Guid, id, StringComparison.Ordinal)) ?? - DesignerExclusiveSettingItemModels - .SelectMany(group => group.Items) - .FirstOrDefault(item => string.Equals(item.Guid, id, StringComparison.Ordinal)); - - private void ApplySimpleDesignerToCommand() - { - if (_updatingDesigner || _designerNeedsRefresh || !IsSimpleDesignerSupported) - { return; } - _updatingDesigner = true; - try - { - string command = GraphicDesignerHelper.ConvertGraphicDesignerSettingsToString( - DesignerSettingItemModels, - DesignerExclusiveSettingItemModels, - _additionalDesignerArguments); - SetEditorText(ComponentCommandLineFormatter.FormatByFlags(command.Trim())); - _designerNeedsRefresh = false; - } - finally - { - _updatingDesigner = false; - } + Core.Basic.Logger.Instance.CreateWarningLog(LogSource, exception.ToString()); + ShowEditorMessage( + string.Format(_localizer.GetLocalizedString("ConfigMakerDesignerLoadFailedMessage"), exception.Message), + InfoBarSeverity.Warning); } } diff --git a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Testing.cs b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Testing.cs index 03317f92..b91e2f21 100644 --- a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Testing.cs +++ b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Testing.cs @@ -1,7 +1,5 @@ using System; using System.Threading.Tasks; -using CDPIUI.Core.ComponentServices; -using CDPIUI.Core.Store.Database; using CDPIUI.Helper.CreateConfigHelper; using Microsoft.UI.Xaml.Controls; @@ -10,14 +8,11 @@ namespace CDPIUI.ViewModels.ConfigMaker; // The test run of the edited command in the selected component. public sealed partial class ConfigMakerViewModel { - private bool _isTesting; - private bool _isStartingTest; - private bool _restoreComponentAfterTest; - private string _testComponentId = string.Empty; + private readonly ConfigMakerTestSession _testSession; public event EventHandler TestStateChanged; - public bool IsTesting => _isTesting; + public bool IsTesting => _testSession.IsTesting; public async Task StartTestAsync() { @@ -34,85 +29,10 @@ public async Task StartTestAsync() return; } - await StopTestAsync(); - bool componentWasRunning = await ComponentTasksManager.Instance.IsTaskRunning(ComponentId); - if (componentWasRunning && !await ConfirmReplaceRunningComponentAsync()) - { - return; - } - - _restoreComponentAfterTest = componentWasRunning; - await ComponentTasksManager.Instance.StopTask(ComponentId); - - _testComponentId = ComponentId; - _isTesting = true; - _isStartingTest = true; - ComponentTasksManager.Instance.TaskStateUpdated += ComponentTasksManager_TaskStateUpdated; - RaiseTestStateChanged(); - - if (!DatabaseHelper.Instance.IsItemInstalled(_testComponentId)) - { - ShowEditorMessage( - _localizer.GetLocalizedString("TargetComponentNotInstalled"), - InfoBarSeverity.Error); - await StopTestAsync(); - return; - } - - ShowEditorMessage( - _localizer.GetLocalizedString("ConfigMakerTestStartedMessage"), - InfoBarSeverity.Informational); - - try - { - await ComponentTasksManager.Instance.CreateAndRunNewTask(_testComponentId, arguments); - _isStartingTest = false; - await _view.RefreshOutputAsync(); - } - catch (Exception exception) - { - _isStartingTest = false; - ShowEditorMessage( - string.Format( - _localizer.GetLocalizedString("ConfigMakerTestStartFailedMessage"), - exception.Message), - InfoBarSeverity.Error); - await StopTestAsync(); - } + await _testSession.StartAsync(arguments); } - public async Task StopTestAsync(bool showCompletionMessage = false) - { - if (!_isTesting) - { - return; - } - - string componentId = _testComponentId; - bool restore = _restoreComponentAfterTest; - _isTesting = false; - _isStartingTest = false; - ComponentTasksManager.Instance.TaskStateUpdated -= ComponentTasksManager_TaskStateUpdated; - RaiseTestStateChanged(); - - if (!string.IsNullOrWhiteSpace(componentId)) - { - await ComponentTasksManager.Instance.StopTask(componentId); - if (restore) - { - await ComponentTasksManager.Instance.CreateAndRunNewTask(componentId); - } - } - - _testComponentId = string.Empty; - _restoreComponentAfterTest = false; - if (showCompletionMessage) - { - ShowEditorMessage( - _localizer.GetLocalizedString("ConfigMakerTestStoppedMessage"), - InfoBarSeverity.Informational); - } - } + public Task StopTestAsync(bool showCompletionMessage = false) => _testSession.StopAsync(showCompletionMessage); private bool TryResolveTestArguments(out string arguments) { @@ -147,22 +67,18 @@ private Task ConfirmReplaceRunningComponentAsync() => _view.ConfirmAsync( _localizer.GetLocalizedString("ConfigMakerReplaceRunningComponentMessage"), _localizer.GetLocalizedString("Continue")); - private void ComponentTasksManager_TaskStateUpdated(Tuple state) + private void ShowTestNotice(ConfigMakerTestNotice notice, string? details) { - if (!_isTesting || _isStartingTest || - !string.Equals(state.Item1, _testComponentId, StringComparison.OrdinalIgnoreCase) || - state.Item2) - { - return; - } - - _dispatcherQueue.TryEnqueue(async () => + (string message, InfoBarSeverity severity) = notice switch { - ShowEditorMessage( - _localizer.GetLocalizedString("ConfigMakerTestExitedMessage"), - InfoBarSeverity.Warning); - await StopTestAsync(); - }); + ConfigMakerTestNotice.Started => (_localizer.GetLocalizedString("ConfigMakerTestStartedMessage"), InfoBarSeverity.Informational), + ConfigMakerTestNotice.Stopped => (_localizer.GetLocalizedString("ConfigMakerTestStoppedMessage"), InfoBarSeverity.Informational), + ConfigMakerTestNotice.Exited => (_localizer.GetLocalizedString("ConfigMakerTestExitedMessage"), InfoBarSeverity.Warning), + ConfigMakerTestNotice.NotInstalled => (_localizer.GetLocalizedString("TargetComponentNotInstalled"), InfoBarSeverity.Error), + ConfigMakerTestNotice.StartFailed => (string.Format(_localizer.GetLocalizedString("ConfigMakerTestStartFailedMessage"), details), InfoBarSeverity.Error), + _ => throw new ArgumentOutOfRangeException(nameof(notice)), + }; + ShowEditorMessage(message, severity); } private void RaiseTestStateChanged() diff --git a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Variables.cs b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Variables.cs index b33211cf..e7829770 100644 --- a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Variables.cs +++ b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Variables.cs @@ -1,5 +1,5 @@ -using System; using System.Threading.Tasks; +using CDPIUI.Helper.CreateConfigHelper; namespace CDPIUI.ViewModels.ConfigMaker; @@ -9,76 +9,30 @@ public sealed partial class ConfigMakerViewModel public AsyncRelayCommand CreateVariableCommand { get; } public Task EditVariableAsync(ConfigMakerVariableDefinition variable) => - RunReportingErrorsAsync(async () => - { - if (variable == null) - { - return; - } - ConfigMakerVariableEditResult result = await _view.EditVariableAsync(_presetDocument, variable); - if (result == null) - { - return; - } - int index = _presetDocument.Variables.IndexOf(variable); - if (index < 0) - { - return; - } - if (!string.Equals(result.OriginalName, result.Variable.Name, StringComparison.Ordinal)) - { - _presetDocument.ReplaceVariableReference( - result.OriginalName, - result.Variable.Name); - SetEditorText(_presetDocument.CommandText); - } - _presetDocument.Variables[index] = result.Variable; - AttachExistingPresetFiles(); - RebuildPresetStructure(); - ScheduleDiagnostics(); - }); + RunReportingErrorsAsync(() => _variableActions.EditVariableAsync(variable)); public Task RemoveVariableAsync(ConfigMakerVariableDefinition variable) => - RunReportingErrorsAsync(async () => - { - if (variable == null) - { - return; - } - bool referenced = CommandText.Contains(variable.Reference, StringComparison.OrdinalIgnoreCase); - if (referenced && - !await _view.ConfirmAsync( - _localizer.GetLocalizedString("ConfigMakerRemoveReferencedVariableDialogTitle"), - _localizer.GetLocalizedString("ConfigMakerRemoveReferencedVariableDialogMessage"), - _localizer.GetLocalizedString("Remove"))) - { - return; - } - _presetDocument.Variables.Remove(variable); - RebuildPresetStructure(); - ScheduleDiagnostics(); - }); + RunReportingErrorsAsync(() => _variableActions.RemoveVariableAsync(variable)); /// Inserts the reference of a variable at the editor cursor. - public void InsertVariableReference(ConfigMakerVariableDefinition variable) - { - if (!IsEditorReadOnly && variable != null) - { - InsertAtCursor(variable.Reference); - } - } + public void InsertVariableReference(ConfigMakerVariableDefinition variable) => + _variableActions.InsertVariableReference(variable); - private async Task CreateVariableAsync() - { - ConfigMakerVariableEditResult result = await _view.EditVariableAsync(_presetDocument, null); - if (result == null) - { - return; - } - _presetDocument.Variables.Add(result.Variable); - AttachExistingPresetFiles(); - _view.ShowVariablesTool(); - RebuildPresetStructure(); - ScheduleDiagnostics(); - } + private Task CreateVariableAsync() => _variableActions.CreateVariableAsync(); + +#nullable enable annotations + string IConfigMakerVariableActionsHost.CommandText => CommandText; + bool IConfigMakerVariableActionsHost.IsEditorReadOnly => IsEditorReadOnly; + Task IConfigMakerVariableActionsHost.EditVariableAsync( + ConfigMakerPresetDocument document, ConfigMakerVariableDefinition? variable) => _view.EditVariableAsync(document, variable); + Task IConfigMakerVariableActionsHost.ConfirmRemoveReferencedVariableAsync() => _view.ConfirmAsync( + _localizer.GetLocalizedString("ConfigMakerRemoveReferencedVariableDialogTitle"), + _localizer.GetLocalizedString("ConfigMakerRemoveReferencedVariableDialogMessage"), + _localizer.GetLocalizedString("Remove")); + void IConfigMakerVariableActionsHost.SetEditorText(string text) => SetEditorText(text); + void IConfigMakerVariableActionsHost.InsertAtCursor(string reference) => InsertAtCursor(reference); + void IConfigMakerVariableActionsHost.AttachExistingPresetFiles() => AttachExistingPresetFiles(); + void IConfigMakerVariableActionsHost.ShowVariablesTool() => _view.ShowVariablesTool(); + void IConfigMakerVariableActionsHost.RebuildPresetStructure() => RebuildPresetStructure(); + void IConfigMakerVariableActionsHost.ScheduleDiagnostics() => ScheduleDiagnostics(); } diff --git a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.cs b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.cs index 918fa4c6..0108eec5 100644 --- a/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.cs +++ b/CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.cs @@ -1,8 +1,11 @@ using System; using System.Threading.Tasks; +using CDPIUI.Controls.CreateConfigHelper; using CDPIUI.Controls.Universal; using CDPIUI.Core; +using CDPIUI.Core.Store.Database; using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.Helper.UserExperience; using Microsoft.UI.Dispatching; using Microsoft.UI.Xaml.Controls; using WinUI3Localizer; @@ -13,7 +16,7 @@ namespace CDPIUI.ViewModels.ConfigMaker; /// The state and the logic of the preset editor: the edited document, the editor text, the /// status message and the editor background. The other features live in the partial files. /// -public sealed partial class ConfigMakerViewModel : ObservableObject +public sealed partial class ConfigMakerViewModel : ObservableObject, IConfigMakerDocumentHost, IConfigMakerPresetFileReplacementHost, IConfigMakerPresetFileActionsHost, IConfigMakerVariableActionsHost { // The log source of the control the view model was extracted from. private const string LogSource = "ConfigMakerUserControl"; @@ -27,11 +30,15 @@ public sealed partial class ConfigMakerViewModel : ObservableObject private readonly ILocalizer _localizer = Localizer.Get(); private readonly ConfigMakerPresetDocument _presetDocument = new(); private readonly ConfigMakerPresetResources _presetResources; + private readonly ConfigMakerDocumentCoordinator _documentCoordinator; + private readonly ConfigMakerPresetFileReplacer _presetFileReplacer; + private readonly ConfigMakerPresetFileActions _presetFileActions; + private readonly ConfigMakerVariableActions _variableActions; + private readonly TextChangeRelay _textChanges; private string _componentId = string.Empty; private string _commandText = string.Empty; private bool _isEditorReadOnly; private bool _updatingComponent; - private bool _updatingEditor; private string _editorBackground = BlackBackground; private string _statusTitle = string.Empty; private string _statusMessage = string.Empty; @@ -42,17 +49,72 @@ public ConfigMakerViewModel(IConfigMakerView view, DispatcherQueue dispatcherQue { _view = view ?? throw new ArgumentNullException(nameof(view)); _dispatcherQueue = dispatcherQueue ?? throw new ArgumentNullException(nameof(dispatcherQueue)); + _textChanges = new TextChangeRelay( + () => IsEditorReadOnly, () => CommandText, text => CommandText = text, + _view.ReplaceEditorText, + text => { _presetDocument.CommandText = text; _simpleDesigner.MarkDirty(); }, + RebuildPresetStructure, RebuildDiagnostics, ScheduleDiagnostics, + text => CommandTextChanged?.Invoke(text)); _presetResources = new ConfigMakerPresetResources( _presetDocument, () => ComponentId, () => CommandText); + _presetFileActions = new ConfigMakerPresetFileActions(_presetDocument.Resources, this, + new ConfigMakerPresetFileActionsBackend(_presetResources)); + _variableActions = new ConfigMakerVariableActions(_presetDocument, this); + _presetFileReplacer = new ConfigMakerPresetFileReplacer(this, + new ConfigMakerPresetFileReplacementBackend(_presetResources)); + _documentCoordinator = new ConfigMakerDocumentCoordinator( + _presetDocument, this, () => new ConfigMakerPresetStorageService(), + ConfigMakerPresetExporter.ExportAsync); + _commandHelpPanel = new ConfigMakerCommandHelpPanel(_localizer.GetLocalizedString, () => IsEditorReadOnly); + _commandHelpPanel.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); + _diagnostics = new ConfigMakerDiagnostics(Diagnostics, + () => _view.EditorText, () => _commandHelpPanel.Document.Options, _presetDocument.Variables, + reference => _presetResources.FindAttached(reference) != null, CreateDiagnosticViewModel, + _localizer.GetLocalizedString, () => _view.RefreshEditorHighlighting()); + _diagnostics.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); + _helpLoader = new ConfigMakerCommandHelpLoader(_commandHelpPanel, () => ComponentId, + _localizer.GetLocalizedString, _helpService.LoadAsync, + RebuildPresetStructure, RebuildDiagnostics, ShowHelpLoadStatus); + _helpLoader.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); + _testSession = new ConfigMakerTestSession( + new ConfigMakerComponentTestTasks(), + () => ComponentId, + ConfirmReplaceRunningComponentAsync, + id => DatabaseHelper.Instance.IsItemInstalled(id), + ShowTestNotice, + _view.RefreshOutputAsync, + action => _dispatcherQueue.TryEnqueue(async () => await action())); + _testSession.StateChanged += (_, _) => RaiseTestStateChanged(); _zapret2OptionDescriber = new Zapret2PresetOptionDescriber(_localizer); + _presetTreeBuilder = new ConfigMakerPresetTreeBuilder( + _localizer.GetLocalizedString, + _presetResources.TryResolvePath, + System.IO.File.Exists, + option => _zapret2OptionDescriber.Describe(option, _commandHelpPanel.Document.Options)); + _presetStructure = new ConfigMakerPresetStructure( + () => CommandText, () => IsZapret2Component, + _presetResources.ExtractFiles, _presetResources.GetAttachedFiles, + files => ConfigMakerPresetTreeAdapter.ToFileNodes(_presetTreeBuilder.BuildFiles(files)), + (options, groups, isZapret2) => ConfigMakerPresetTreeAdapter.ToOptionNodes( + _presetTreeBuilder.BuildGroups(options, groups, isZapret2))); + _presetStructure.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); + _presetStructure.AvailabilityChanged += (_, _) => PresetStructureAvailabilityChanged?.Invoke(this, EventArgs.Empty); DesignerTextValueChangedCommand = new RelayCommand(parameter => - HandleDesignerTextValueChanged((Tuple)parameter)); + _simpleDesigner.HandleDesignerTextValueChanged((Tuple)parameter)); DesignerBoolValueToggledCommand = new RelayCommand(parameter => - HandleDesignerBoolValueToggled((Tuple)parameter)); + _simpleDesigner.HandleDesignerBoolValueToggled((Tuple)parameter)); DesignerSelectedGuidChangedCommand = new RelayCommand(parameter => - HandleDesignerSelectedGuidChanged((Tuple)parameter)); + _simpleDesigner.HandleDesignerSelectedGuidChanged((Tuple)parameter)); + _simpleDesigner = new ConfigMakerSimpleDesigner( + new ConfigMakerSimpleDesignerBackend(), + () => ComponentId, + () => _view.EditorText, + text => SetEditorText(text), + new(DesignerTextValueChangedCommand, DesignerBoolValueToggledCommand, DesignerSelectedGuidChangedCommand), + ShowDesignerNotice); + _simpleDesigner.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); CopyCommandCommand = new RelayCommand(CopySelectedCommand, () => HasSelectedCommand); InsertCommandCommand = new RelayCommand(InsertSelectedCommand, () => CanInsertCommand); CreateVariableCommand = new AsyncRelayCommand(() => RunReportingErrorsAsync(CreateVariableAsync)); @@ -87,7 +149,7 @@ public string ComponentId return; } _presetDocument.ComponentId = value; - _designerNeedsRefresh = true; + _simpleDesigner.MarkDirty(); UpdateSimpleDesignerAvailability(); if (!_updatingComponent && _view.IsViewLoaded) { @@ -102,12 +164,12 @@ public string CommandText get => _commandText; set { - if (!SetProperty(ref _commandText, value) || _updatingEditor) + if (!SetProperty(ref _commandText, value) || _textChanges.IsUpdating) { return; } _presetDocument.CommandText = value; - _designerNeedsRefresh = true; + _simpleDesigner.MarkDirty(); SetEditorText(value, updateProperty: false); } } @@ -176,7 +238,7 @@ public async Task OnViewLoadedAsync() public void CancelBackgroundWork() { - _helpCancellation?.Cancel(); + _helpLoader.Cancel(); _diagnosticsTimer.Stop(); } @@ -188,7 +250,7 @@ public async Task SetComponentAsync(string componentId) return; } - if (_isTesting && !string.Equals(_testComponentId, componentId, StringComparison.OrdinalIgnoreCase)) + if (_testSession.IsTesting && !string.Equals(_testSession.TestComponentId, componentId, StringComparison.OrdinalIgnoreCase)) { await StopTestAsync(); } @@ -214,27 +276,7 @@ public void FormatCommand() } /// Called by the view when the user changed the editor text. - public void OnEditorTextChanged(string text) - { - if (_updatingEditor) - { - return; - } - if (IsEditorReadOnly) - { - SetEditorText(CommandText, updateProperty: false); - return; - } - - _updatingEditor = true; - CommandText = text ?? string.Empty; - _updatingEditor = false; - _presetDocument.CommandText = CommandText; - _designerNeedsRefresh = true; - RebuildPresetStructure(); - CommandTextChanged?.Invoke(CommandText); - ScheduleDiagnostics(); - } + public void OnEditorTextChanged(string text) => _textChanges.OnTextChanged(text); public void LoadEditorBackground() { @@ -296,20 +338,7 @@ private async Task RunReportingErrorsAsync(Func action) } private void SetEditorText(string text, bool updateProperty = true) - { - _updatingEditor = true; - string editorText = _view.ReplaceEditorText(text ?? string.Empty); - if (updateProperty) - { - CommandText = editorText; - } - _presetDocument.CommandText = editorText; - _designerNeedsRefresh = true; - _updatingEditor = false; - RebuildPresetStructure(); - RebuildDiagnostics(); - CommandTextChanged?.Invoke(editorText); - } + => _textChanges.ReplaceText(text, updateProperty); private void InsertAtCursor(string command) { diff --git a/CDPIUI/ViewModels/ConfigMakerPresetDocumentConverter.cs b/CDPIUI/ViewModels/ConfigMakerPresetDocumentConverter.cs index e81ca471..f2d585d3 100644 --- a/CDPIUI/ViewModels/ConfigMakerPresetDocumentConverter.cs +++ b/CDPIUI/ViewModels/ConfigMakerPresetDocumentConverter.cs @@ -5,7 +5,7 @@ using System.Linq; using System.Text.RegularExpressions; using CDPIUI.Core.ComponentServices.Helpers.Configuration; -using CDPIUI.Helper.LScript; +using CDPIUI.Core.LScript; namespace CDPIUI.ViewModels; @@ -212,7 +212,7 @@ private static void LoadLegacyVariables(ConfigMakerPresetDocument document, Conf foreach (string expression in item.variables ?? []) { Tuple? condition = - LScriptLangHelper.GetNameOnOffValuesFromConditionString(expression); + LScriptCore.GetNameOnOffValuesFromConditionString(expression); if (condition != null && !string.IsNullOrWhiteSpace(condition.Item2)) { document.Variables.Add(new ConfigMakerVariableDefinition diff --git a/CDPIUI/ViewModels/CreateConfig/ConfigComponentOption.cs b/CDPIUI/ViewModels/CreateConfig/ConfigComponentOption.cs index 7550484a..b1e69984 100644 --- a/CDPIUI/ViewModels/CreateConfig/ConfigComponentOption.cs +++ b/CDPIUI/ViewModels/CreateConfig/ConfigComponentOption.cs @@ -1,3 +1,6 @@ +#nullable enable annotations +#nullable disable warnings + namespace CDPIUI.ViewModels.CreateConfig; /// A component the config editor can target. diff --git a/CDPIUI/ViewModels/CreateConfig/CreateConfigComponentSelection.cs b/CDPIUI/ViewModels/CreateConfig/CreateConfigComponentSelection.cs new file mode 100644 index 00000000..0b8af6fa --- /dev/null +++ b/CDPIUI/ViewModels/CreateConfig/CreateConfigComponentSelection.cs @@ -0,0 +1,103 @@ +#nullable enable + +using System; + +namespace CDPIUI.ViewModels.CreateConfig; + +// Owns component/name choice, related view flags and the original ordered UI effects. +internal sealed class CreateConfigComponentSelection : ObservableObject +{ + private readonly Func _supported; + private readonly Action _selectDesigner; + private readonly Action _selectText; + private readonly Action _handleSelection; + private readonly Action _dirty; + private readonly Action _audit; + private readonly Func _editorText; + private ConfigComponentOption? _selectedComponent; + private string _displayName = string.Empty; + private bool _isAdditionalSettingsVisible; + private bool _isNotReadyErrorVisible = true; + private bool _isTabBarVisible = true; + + public CreateConfigComponentSelection(Func supported, + Action selectDesigner, Action selectText, Action handleSelection, + Action dirty, Action audit, Func editorText) + { + _supported = supported; + _selectDesigner = selectDesigner; + _selectText = selectText; + _handleSelection = handleSelection; + _dirty = dirty; + _audit = audit; + _editorText = editorText; + } + + public ConfigComponentOption? SelectedComponent + { + get => _selectedComponent; + set + { + if (!SetProperty(ref _selectedComponent, value)) + return; + CheckViewType(); + _dirty(); + _audit(); + } + } + + public string DisplayName + { + get => _displayName; + set + { + if (!SetProperty(ref _displayName, value ?? string.Empty)) + return; + _dirty(); + _audit(); + } + } + + public bool IsAdditionalSettingsVisible + { + get => _isAdditionalSettingsVisible; + set => SetProperty(ref _isAdditionalSettingsVisible, value); + } + public bool IsNotReadyErrorVisible + { + get => _isNotReadyErrorVisible; + set => SetProperty(ref _isNotReadyErrorVisible, value); + } + public bool IsTabBarVisible + { + get => _isTabBarVisible; + set => SetProperty(ref _isTabBarVisible, value); + } + public bool IsDesignerSupported => _supported(SelectedComponent?.Id ?? ""); + public bool IsSaveAvailable => SelectedComponent != null && + !string.IsNullOrEmpty(DisplayName) && !string.IsNullOrEmpty(_editorText()); + + public void CheckViewType() + { + if (SelectedComponent == null) + { + IsAdditionalSettingsVisible = false; + IsNotReadyErrorVisible = true; + return; + } + IsAdditionalSettingsVisible = true; + IsNotReadyErrorVisible = false; + if (IsDesignerSupported) + { + _selectDesigner(); + IsTabBarVisible = true; + _handleSelection(false); + } + else + { + _handleSelection(true); + _selectText(); + IsTabBarVisible = false; + } + } +} diff --git a/CDPIUI/ViewModels/CreateConfig/CreateConfigConditionDraft.cs b/CDPIUI/ViewModels/CreateConfig/CreateConfigConditionDraft.cs new file mode 100644 index 00000000..b16f3948 --- /dev/null +++ b/CDPIUI/ViewModels/CreateConfig/CreateConfigConditionDraft.cs @@ -0,0 +1,84 @@ +#nullable enable + +using System; +using System.Collections.ObjectModel; +using CDPIUI.Views.CreateConfigHelper; + +namespace CDPIUI.ViewModels.CreateConfig; + +internal sealed class CreateConfigConditionDraft : ObservableObject +{ + private readonly ObservableCollection _conditions; + private readonly Func _isNameCorrect; + private readonly Func _format; + private readonly Func _text; + private readonly Action _enableExitAsk; + private string _conditionName = string.Empty; + private string _conditionDescription = string.Empty; + private string _conditionOnValue = string.Empty; + private string _conditionOffValue = string.Empty; + + public CreateConfigConditionDraft(ObservableCollection conditions, + Func isNameCorrect, Func format, + Func text, Action enableExitAsk) + { + _conditions = conditions; + _isNameCorrect = isNameCorrect; + _format = format; + _text = text; + _enableExitAsk = enableExitAsk; + } + + public string ConditionName + { + get => _conditionName; + set { if (SetProperty(ref _conditionName, value ?? string.Empty)) OnConditionDraftChanged(); } + } + public string ConditionDescription + { + get => _conditionDescription; + set => SetProperty(ref _conditionDescription, value ?? string.Empty); + } + public string ConditionOnValue + { + get => _conditionOnValue; + set { if (SetProperty(ref _conditionOnValue, value ?? string.Empty)) OnConditionDraftChanged(); } + } + public string ConditionOffValue + { + get => _conditionOffValue; + set { if (SetProperty(ref _conditionOffValue, value ?? string.Empty)) OnConditionDraftChanged(); } + } + public string ConditionPreview => IsConditionSaveAvailable + ? _format(ConditionName.Replace(" ", ""), ConditionOnValue, ConditionOffValue) + : _text("NothingToPreview"); + public bool IsConditionSaveAvailable => + _isNameCorrect(ConditionName.Replace(" ", "")) && + !string.IsNullOrEmpty(ConditionOnValue) && + !string.IsNullOrEmpty(ConditionOffValue); + + public void ResetConditionDraft() + { + ConditionName = ""; + ConditionDescription = ""; + ConditionOnValue = ""; + ConditionOffValue = ""; + OnPropertyChanged(nameof(ConditionPreview)); + } + + public void AddCondition() + { + _enableExitAsk(); + ConditionVariableModel model = new() + { + Name = ConditionName, + Description = ConditionDescription, + OnValue = ConditionOnValue, + OffValue = ConditionOffValue, + }; + _conditions.Add(model); + } + + private void OnConditionDraftChanged() => + OnPropertiesChanged(nameof(ConditionPreview), nameof(IsConditionSaveAvailable)); +} diff --git a/CDPIUI/ViewModels/CreateConfig/CreateConfigGraphicDesigner.cs b/CDPIUI/ViewModels/CreateConfig/CreateConfigGraphicDesigner.cs new file mode 100644 index 00000000..7decf8ff --- /dev/null +++ b/CDPIUI/ViewModels/CreateConfig/CreateConfigGraphicDesigner.cs @@ -0,0 +1,109 @@ +#nullable enable + +using System; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using CDPIUI.Core.Store.Data; +using CDPIUI.Helper.CreateConfigHelper; +using CDPIUI.Views.CreateConfigHelper; + +namespace CDPIUI.ViewModels.CreateConfig; + +// Owns designer state and model edits; the host keeps view/tab/editor sequencing. +internal sealed class CreateConfigGraphicDesigner : ObservableObject +{ + private readonly ObservableCollection _items; + private readonly ObservableCollection _groups; + private readonly ICreateConfigGraphicDesignerBackend _backend; + private readonly Func _componentId; + private string _loadedComponentId = string.Empty; + private string _additionalSettings = string.Empty; + + public CreateConfigGraphicDesigner( + ObservableCollection items, + ObservableCollection groups, + ICreateConfigGraphicDesignerBackend backend, + Func componentId) + { + _items = items; + _groups = groups; + _backend = backend; + _componentId = componentId; + } + + public string LoadedComponentId => _loadedComponentId; + public string AdditionalSettings + { + get => _additionalSettings; + set => SetProperty(ref _additionalSettings, value ?? string.Empty); + } + + public void Load(string id) + { + if (_componentId(Components.GoodbyeDPI) == id && _loadedComponentId != _componentId(Components.GoodbyeDPI)) + { + _backend.LoadGoodbye(_items, _groups); + _loadedComponentId = _componentId(Components.GoodbyeDPI); + } + else if (_componentId(Components.SpoofDPI) == id && _loadedComponentId != _componentId(Components.SpoofDPI)) + { + _backend.LoadSpoof(_items, _groups); + _loadedComponentId = _componentId(Components.SpoofDPI); + } + else if (_componentId(Components.NoDPI) == id && _loadedComponentId != _componentId(Components.NoDPI)) + { + if (_backend.TryLoadNoDpi(id, _items, _groups)) + _loadedComponentId = _componentId(Components.NoDPI); + } + } + + public void ChangeText(Tuple tuple) + { + string guid = tuple.Item1; + string value = tuple.Item2; + var item = _items.FirstOrDefault(x => x.Guid == guid); + if (item != null) + { + item.Value = value; + } + else + { + item = _groups.FirstOrDefault(x => x.Items.FirstOrDefault(y => y.Guid == guid) != null)?.Items.FirstOrDefault(y => y.Guid == guid); + if (item != null) + item.Value = value; + } + } + + public void ToggleBool(Tuple tuple) + { + string guid = tuple.Item1; + bool value = tuple.Item2; + var item = _items.FirstOrDefault(x => x.Guid == guid); + if (item != null) + { + item.IsChecked = value; + } + else + { + item = _groups.FirstOrDefault(x => x.Items.FirstOrDefault(y => y.Guid == guid) != null)?.Items.FirstOrDefault(y => y.Guid == guid); + if (item != null) + item.IsChecked = value; + } + } + + public void SelectGuid(Tuple tuple) + { + string guid = tuple.Item1; + string selectedGuid = tuple.Item2; + var item = _groups.FirstOrDefault(x => x.Guid == guid); + if (item != null) + { + Debug.WriteLine(selectedGuid); + item.SelectedItemGuid = selectedGuid; + } + } + + public void Parse(string text) => AdditionalSettings = _backend.Parse(_items, _groups, text); + public string Build() => _backend.Build(_items, _groups, AdditionalSettings); +} diff --git a/CDPIUI/ViewModels/CreateConfig/CreateConfigTestSession.cs b/CDPIUI/ViewModels/CreateConfig/CreateConfigTestSession.cs new file mode 100644 index 00000000..5d2697cc --- /dev/null +++ b/CDPIUI/ViewModels/CreateConfig/CreateConfigTestSession.cs @@ -0,0 +1,129 @@ +#nullable enable + +using System; +using System.Threading.Tasks; +using CDPIUI.Core.ComponentServices.Helpers.Configuration; +using CDPIUI.Helper.CreateConfigHelper; + +namespace CDPIUI.ViewModels.CreateConfig; + +// Owns the original config-page test lifecycle; the host supplies preparation and UI effects. +internal sealed class CreateConfigTestSession : ObservableObject +{ + private const string StartTestGlyph = "\uE768"; + private const string StopTestGlyph = "\uE71A"; + private readonly ICreateConfigTestTasks _tasks; + private readonly Func<(bool HasComponent, string ComponentId)> _selection; + private readonly Action _convertDesigner; + private readonly Func _createConfig; + private readonly Func _startupArguments; + private readonly Func _localize; + private readonly Action _enqueue; + private bool _isRunning; + private string _curRunId = string.Empty; + private string _testButtonText = null!; + private string _testButtonGlyph = StartTestGlyph; + + public CreateConfigTestSession( + ICreateConfigTestTasks tasks, + Func<(bool HasComponent, string ComponentId)> selection, + Action convertDesigner, + Func createConfig, + Func startupArguments, + Func localize, + Action enqueue) + { + _tasks = tasks; + _selection = selection; + _convertDesigner = convertDesigner; + _createConfig = createConfig; + _startupArguments = startupArguments; + _localize = localize; + _enqueue = enqueue; + } + + public bool IsRunning => _isRunning; + public string CurrentRunId => _curRunId; + public string TestButtonText + { + get => _testButtonText; + set => SetProperty(ref _testButtonText, value); + } + public string TestButtonGlyph + { + get => _testButtonGlyph; + set => SetProperty(ref _testButtonGlyph, value); + } + + // The host initializes this field, without notification, at its original constructor point. + public void InitializeText(string text) => _testButtonText = text; + + public void Stop() + { + _tasks.StateUpdated -= OnProcessStateChanged; + if (!_isRunning || string.IsNullOrEmpty(_curRunId)) + return; + string runId = _curRunId; + Reset(); + _ = _tasks.StopAsync(runId); + } + + private void OnProcessStateChanged(Tuple state) => + _enqueue(() => ApplyProcessState(state)); + + private void ApplyProcessState(Tuple state) + { + if (string.IsNullOrEmpty(_curRunId) || state.Item1 != _curRunId) + return; + if (state.Item2) + { + TestButtonGlyph = StopTestGlyph; + TestButtonText = _localize("StopTest"); + _isRunning = true; + } + else + { + TestButtonGlyph = StartTestGlyph; + TestButtonText = _localize("TestThis"); + _isRunning = false; + } + } + + public async Task ToggleAsync() + { + if (!_isRunning) + { + _isRunning = true; + _tasks.StateUpdated -= OnProcessStateChanged; + _tasks.StateUpdated += OnProcessStateChanged; + var selection = _selection(); + if (!selection.HasComponent) + { + Reset(); + return; + } + _curRunId = selection.ComponentId; + await _tasks.StopAsync(_curRunId); + _convertDesigner(); + var config = _createConfig(); + if (config != null) + _ = _tasks.RunAsync(_curRunId, _startupArguments(config)); + else + Reset(); + } + else + { + await _tasks.StopAsync(_curRunId); + Reset(); + } + } + + private void Reset() + { + TestButtonGlyph = StartTestGlyph; + TestButtonText = _localize("TestThis"); + _isRunning = false; + _tasks.StateUpdated -= OnProcessStateChanged; + _curRunId = string.Empty; + } +} diff --git a/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.GraphicDesigner.cs b/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.GraphicDesigner.cs index a7e35513..149ac35f 100644 --- a/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.GraphicDesigner.cs +++ b/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.GraphicDesigner.cs @@ -1,18 +1,10 @@ using System; -using System.Diagnostics; -using System.IO; -using System.Linq; -using CDPIUI.Core.Store.Data; -using CDPIUI.Core.Store.Database; -using CDPIUI.Helper.CreateConfigHelper; namespace CDPIUI.ViewModels.CreateConfig; // The graphic designer for GoodbyeDPI, SpoofDPI and NoDPI. public sealed partial class CreateNewConfigViewModel { - private string _nowConfigLoadedId = string.Empty; - /// Call when the user switched between the text editor and the designer. public void OnEditorTabChanged() => HandleSelectionChange(); @@ -41,85 +33,19 @@ private void LoadDesigner() if (SelectedComponent == null) return; string id = SelectedComponent.Id; - if (HardcodedItemIds.ComponentIds[Components.GoodbyeDPI] == id && _nowConfigLoadedId != HardcodedItemIds.ComponentIds[Components.GoodbyeDPI]) - { - GraphicDesignerHelper.LoadGoodbyeDPIDesignerConfig(DesignerSettingItemModels, DesignerExclusiveSettingItemModels); - _nowConfigLoadedId = HardcodedItemIds.ComponentIds[Components.GoodbyeDPI]; - } - else if (HardcodedItemIds.ComponentIds[Components.SpoofDPI] == id && _nowConfigLoadedId != HardcodedItemIds.ComponentIds[Components.SpoofDPI]) - { - GraphicDesignerHelper.LoadSpoofDPIDesignerConfig(DesignerSettingItemModels, DesignerExclusiveSettingItemModels); - _nowConfigLoadedId = HardcodedItemIds.ComponentIds[Components.SpoofDPI]; - } - else if (HardcodedItemIds.ComponentIds[Components.NoDPI] == id && _nowConfigLoadedId != HardcodedItemIds.ComponentIds[Components.NoDPI]) - { - string dir = DatabaseHelper.Instance.GetItemById(id)?.Directory ?? string.Empty; - string xmlFile = Path.Combine(dir, "edannotationfile.xml"); - if (File.Exists(xmlFile)) - { - GraphicDesignerHelper.XML_LoadDesignerConfig(xmlFile, "nodpi", DesignerSettingItemModels, DesignerExclusiveSettingItemModels); - _nowConfigLoadedId = HardcodedItemIds.ComponentIds[Components.NoDPI]; - } - } - } - - private void HandleGraphicDesignerTextValueChanged(Tuple tuple) - { - string guid = tuple.Item1; - string value = tuple.Item2; - - var item = DesignerSettingItemModels.FirstOrDefault(x => x.Guid == guid); - if (item != null) - { - item.Value = value; - } - else - { - item = DesignerExclusiveSettingItemModels.FirstOrDefault(x => x.Items.FirstOrDefault(y => y.Guid == guid) != null)?.Items.FirstOrDefault(y => y.Guid == guid); - - if (item != null) - { - item.Value = value; - } - } + _graphicDesigner.Load(id); } - private void HandleGraphicDesignerBoolValueToggled(Tuple tuple) - { - string guid = tuple.Item1; - bool value = tuple.Item2; + private void HandleGraphicDesignerTextValueChanged(Tuple tuple) => _graphicDesigner.ChangeText(tuple); - var item = DesignerSettingItemModels.FirstOrDefault(x => x.Guid == guid); - if (item != null) - { - item.IsChecked = value; - } - else - { - item = DesignerExclusiveSettingItemModels.FirstOrDefault(x => x.Items.FirstOrDefault(y => y.Guid == guid) != null)?.Items.FirstOrDefault(y => y.Guid == guid); - if (item != null) - { - item.IsChecked = value; - } - } - } + private void HandleGraphicDesignerBoolValueToggled(Tuple tuple) => _graphicDesigner.ToggleBool(tuple); - private void HandleGraphicDesignerSelectedGuidChanged(Tuple tuple) - { - string guid = tuple.Item1; - string selGuid = tuple.Item2; - var item = DesignerExclusiveSettingItemModels.FirstOrDefault(x => x.Guid == guid); - if (item != null) - { - Debug.WriteLine(selGuid); - item.SelectedItemGuid = selGuid; - } - } + private void HandleGraphicDesignerSelectedGuidChanged(Tuple tuple) => _graphicDesigner.SelectGuid(tuple); private void ConvertStringToDesignerLikeSettings() { _view.EditorText = _view.EditorText.Replace("\n", " "); - AdditionalSettings = GraphicDesignerHelper.ConvertStringToGraphicDesignerSettings(DesignerSettingItemModels, DesignerExclusiveSettingItemModels, _view.EditorText); + _graphicDesigner.Parse(_view.EditorText); } private void ConvertDesignerLikeSettingsToString() @@ -129,7 +55,7 @@ private void ConvertDesignerLikeSettingsToString() return; } - _view.EditorText = GraphicDesignerHelper.ConvertGraphicDesignerSettingsToString(DesignerSettingItemModels, DesignerExclusiveSettingItemModels, AdditionalSettings); + _view.EditorText = _graphicDesigner.Build(); _view.EditorText = _view.EditorText.Replace("\n", " "); } } diff --git a/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Navigation.cs b/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Navigation.cs index 69ad2380..ab6e7004 100644 --- a/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Navigation.cs +++ b/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Navigation.cs @@ -11,6 +11,7 @@ using CDPIUI.Core.JSON; using CDPIUI.Helper.CreateConfigHelper; using CDPIUI.Helper.LScript; +using CDPIUI.Helper.UserExperience; using CDPIUI.Shared; using CDPIUI.Views.CreateConfigHelper; @@ -217,48 +218,18 @@ private void LoadConditions(ConfigItem configItem) private void LoadVars(ConfigItem configItem) { - Variables.Clear(); - - if (configItem.variables != null) - { - foreach (var variable in configItem.variables) + NamedValueCollectionLoader.Load(Variables, + () => configItem.variables, + variable => LScriptLangHelper.GetNameOnOffValuesFromConditionString(variable) != null, + (name, value) => new VariableModel { Name = name.Replace("%", ""), Value = value }, + () => configItem.commaVars, + commaVar => new VariableModel { - var t = LScriptLangHelper.GetNameOnOffValuesFromConditionString(variable); - - if (t == null) - { - // Only the first '=' separates the name; values may contain '=' themselves. - int separator = variable.IndexOf('='); - if (separator < 0) - continue; - Variables.Add(new() - { - Name = variable[..separator].Replace("%", ""), - Value = variable[(separator + 1)..] - }); - } - } - } - - if (configItem.commaVars != null) - { - foreach (var commaVar in configItem.commaVars) - { - try - { - Variables.Add(new VariableModel - { - Name = commaVar.Key, - Value = commaVar.Value, - AvailableValues = configItem.availableCommaVarsValues?.FirstOrDefault(varItem => varItem.VarName == commaVar.Key, null) - }); - } - catch (Exception ex) - { - Logger.Instance.CreateWarningLog(LogSource, $"{ex}"); - } - } - } + Name = commaVar.Key, + Value = commaVar.Value, + AvailableValues = configItem.availableCommaVarsValues?.FirstOrDefault(varItem => varItem.VarName == commaVar.Key, null) + }, + error => Logger.Instance.CreateWarningLog(LogSource, $"{error}")); IsVariablesVisible = Variables.Count != 0; } diff --git a/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Testing.cs b/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Testing.cs index c532223a..ded71700 100644 --- a/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Testing.cs +++ b/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Testing.cs @@ -1,107 +1,24 @@ -using System; using System.Threading.Tasks; -using CDPIUI.Core.ComponentServices; -using CDPIUI.Core.ComponentServices.Configuration; namespace CDPIUI.ViewModels.CreateConfig; // The test run of the config in the selected component. public sealed partial class CreateNewConfigViewModel { - private const string StartTestGlyph = "\uE768"; - private const string StopTestGlyph = "\uE71A"; - - private bool _isRunning; - private string _curRunId = string.Empty; - private string _testButtonText; - private string _testButtonGlyph = StartTestGlyph; - public string TestButtonText { - get => _testButtonText; - private set => SetProperty(ref _testButtonText, value); + get => _testSession.TestButtonText; + private set => _testSession.TestButtonText = value; } public string TestButtonGlyph { - get => _testButtonGlyph; - private set => SetProperty(ref _testButtonGlyph, value); + get => _testSession.TestButtonGlyph; + private set => _testSession.TestButtonGlyph = value; } /// Stops the test component that kept running after the user left the page. - public void StopTestRun() - { - // Unsubscribed even when nothing runs: the test component can exit by itself, which - // clears _isRunning but leaves the handler subscribed. - ComponentTasksManager.Instance.TaskStateUpdated -= Instance_onProcessStateChanged; - - if (!_isRunning || string.IsNullOrEmpty(_curRunId)) - return; - string runId = _curRunId; - ResetTestState(); - _ = ComponentTasksManager.Instance.StopTask(runId); - } + public void StopTestRun() => _testSession.Stop(); - private void Instance_onProcessStateChanged(Tuple tuple) - { - // The state comes from the pipe thread. - _dispatcherQueue?.TryEnqueue(() => ApplyProcessState(tuple)); - } - - private void ApplyProcessState(Tuple tuple) - { - if (string.IsNullOrEmpty(_curRunId) || tuple.Item1 != _curRunId) - return; - if (tuple.Item2) - { - TestButtonGlyph = StopTestGlyph; - TestButtonText = _localizer.GetLocalizedString("StopTest"); - _isRunning = true; - } - else - { - TestButtonGlyph = StartTestGlyph; - TestButtonText = _localizer.GetLocalizedString("TestThis"); - _isRunning = false; - } - } - - private async Task ToggleTestRunAsync() - { - if (!_isRunning) - { - _isRunning = true; - // The handler stays subscribed after the component exited by itself; never add it twice. - ComponentTasksManager.Instance.TaskStateUpdated -= Instance_onProcessStateChanged; - ComponentTasksManager.Instance.TaskStateUpdated += Instance_onProcessStateChanged; - - if (SelectedComponent is not ConfigComponentOption component) - { - ResetTestState(); - return; - } - _curRunId = component.Id; - await ComponentTasksManager.Instance.StopTask(_curRunId); - ConvertDesignerLikeSettingsToString(); - var config = CreateConfig(0, saveLocalization: false); - if (config != null) - _ = ComponentTasksManager.Instance.CreateAndRunNewTask(_curRunId, ConfigurationService.GetStartupParametersByConfigItem(config)); - else - ResetTestState(); - } - else - { - await ComponentTasksManager.Instance.StopTask(_curRunId); - ResetTestState(); - } - } - - private void ResetTestState() - { - TestButtonGlyph = StartTestGlyph; - TestButtonText = _localizer.GetLocalizedString("TestThis"); - _isRunning = false; - ComponentTasksManager.Instance.TaskStateUpdated -= Instance_onProcessStateChanged; - _curRunId = string.Empty; - } + private Task ToggleTestRunAsync() => _testSession.ToggleAsync(); } diff --git a/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Variables.cs b/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Variables.cs index 8825fbad..6bf0dc53 100644 --- a/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Variables.cs +++ b/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Variables.cs @@ -9,82 +9,38 @@ namespace CDPIUI.ViewModels.CreateConfig; // The conditions flyout and the variables list. public sealed partial class CreateNewConfigViewModel { - private string _conditionName = string.Empty; - private string _conditionDescription = string.Empty; - private string _conditionOnValue = string.Empty; - private string _conditionOffValue = string.Empty; - public string ConditionName { - get => _conditionName; - set - { - if (SetProperty(ref _conditionName, value ?? string.Empty)) - OnConditionDraftChanged(); - } + get => _conditionDraft.ConditionName; + set => _conditionDraft.ConditionName = value; } public string ConditionDescription { - get => _conditionDescription; - set => SetProperty(ref _conditionDescription, value ?? string.Empty); + get => _conditionDraft.ConditionDescription; + set => _conditionDraft.ConditionDescription = value; } public string ConditionOnValue { - get => _conditionOnValue; - set - { - if (SetProperty(ref _conditionOnValue, value ?? string.Empty)) - OnConditionDraftChanged(); - } + get => _conditionDraft.ConditionOnValue; + set => _conditionDraft.ConditionOnValue = value; } public string ConditionOffValue { - get => _conditionOffValue; - set - { - if (SetProperty(ref _conditionOffValue, value ?? string.Empty)) - OnConditionDraftChanged(); - } + get => _conditionDraft.ConditionOffValue; + set => _conditionDraft.ConditionOffValue = value; } - public string ConditionPreview => IsConditionSaveAvailable - ? LScriptLangHelper.CreateCondition(ConditionName.Replace(" ", ""), ConditionOnValue, ConditionOffValue) - : _localizer.GetLocalizedString("NothingToPreview"); - - public bool IsConditionSaveAvailable => - CreateConfigPageHelper.IsNameCorrect(ConditionName.Replace(" ", "")) && - !string.IsNullOrEmpty(ConditionOnValue) && - !string.IsNullOrEmpty(ConditionOffValue); + public string ConditionPreview => _conditionDraft.ConditionPreview; + public bool IsConditionSaveAvailable => _conditionDraft.IsConditionSaveAvailable; /// Clears the fields of the condition flyout. - public void ResetConditionDraft() - { - ConditionName = ""; - ConditionDescription = ""; - ConditionOnValue = ""; - ConditionOffValue = ""; - OnPropertyChanged(nameof(ConditionPreview)); - } + public void ResetConditionDraft() => _conditionDraft.ResetConditionDraft(); /// Adds the condition from the flyout fields. - public void AddCondition() - { - _view.SetExitAskAvailable(true); - ConditionVariableModel model = new() - { - Name = ConditionName, - Description = ConditionDescription, - OnValue = ConditionOnValue, - OffValue = ConditionOffValue, - }; - Conditions.Add(model); - } - - private void OnConditionDraftChanged() => - OnPropertiesChanged(nameof(ConditionPreview), nameof(IsConditionSaveAvailable)); + public void AddCondition() => _conditionDraft.AddCondition(); private void RemoveCondition(object parameter) { diff --git a/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.cs b/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.cs index df221110..59fc766b 100644 --- a/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.cs +++ b/CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.cs @@ -4,8 +4,10 @@ using System.Linq; using System.Windows.Input; using CDPIUI.Core.ComponentServices.Helpers.Configuration; +using CDPIUI.Core.ComponentServices.Configuration; using CDPIUI.Core.Store.Data; using CDPIUI.Core.System; +using CDPIUI.Helper.CreateConfigHelper; using CDPIUI.Helper.LScript; using CDPIUI.Shared; using CDPIUI.Views.CreateConfigHelper; @@ -29,30 +31,52 @@ public sealed partial class CreateNewConfigViewModel : ObservableObject private readonly ILocalizer _localizer = Localizer.Get(); private readonly AsyncRelayCommand _saveCommand; private readonly AsyncRelayCommand _testCommand; + private readonly CreateConfigConditionDraft _conditionDraft; + private readonly CreateConfigTestSession _testSession; + private readonly CreateConfigGraphicDesigner _graphicDesigner; + private readonly CreateConfigComponentSelection _componentSelection; private ConfigItem _configItem; private string _listDirectory = string.Empty; private string _binDirectory = string.Empty; - private ConfigComponentOption _selectedComponent; - private string _displayName = string.Empty; private string _pageTitle; private string _saveButtonText; private bool _isComponentChoiceEnabled = true; - private bool _isAdditionalSettingsVisible; - private bool _isNotReadyErrorVisible = true; - private bool _isTabBarVisible = true; private bool _isTextEditorVisible; private bool _isDesignerVisible; private bool _isVariablesVisible; private bool _isListsDirectoryButtonVisible; private bool _isBinsDirectoryButtonVisible; - private string _additionalSettings = string.Empty; public CreateNewConfigViewModel(ICreateNewConfigView view) { _view = view; _dispatcherQueue = DispatcherQueue.GetForCurrentThread(); + _componentSelection = new CreateConfigComponentSelection( + id => DesignerSupportedComponentIds.Contains(id), + () => _view.SelectDesignerTab(), () => _view.SelectTextEditorTab(), + HandleSelectionChange, () => _view.SetExitAskAvailable(true), + AuditSaveAvailable, () => _view.EditorText); + _componentSelection.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); + _graphicDesigner = new CreateConfigGraphicDesigner(DesignerSettingItemModels, DesignerExclusiveSettingItemModels, + new CreateConfigGraphicDesignerBackend(), component => HardcodedItemIds.ComponentIds[component]); + _graphicDesigner.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); + _testSession = new CreateConfigTestSession(new CreateConfigComponentTestTasks(), + () => SelectedComponent is ConfigComponentOption component + ? (true, component.Id) : (false, string.Empty), + ConvertDesignerLikeSettingsToString, + () => CreateConfig(0, saveLocalization: false), + config => ConfigurationService.GetStartupParametersByConfigItem(config), + key => _localizer.GetLocalizedString(key), + action => _dispatcherQueue?.TryEnqueue(() => action())); + _testSession.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); + _conditionDraft = new CreateConfigConditionDraft(Conditions, + name => CreateConfigPageHelper.IsNameCorrect(name), + (name, on, off) => LScriptLangHelper.CreateCondition(name, on, off), + key => _localizer.GetLocalizedString(key), + () => _view.SetExitAskAvailable(true)); + _conditionDraft.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); RemoveConditionCommand = new RelayCommand(p => RemoveCondition(p)); RemoveVariableCommand = new RelayCommand(p => RemoveVariable(p)); @@ -73,7 +97,7 @@ public CreateNewConfigViewModel(ICreateNewConfigView view) _pageTitle = _localizer.GetLocalizedString("CreateNewConfig"); _saveButtonText = _localizer.GetLocalizedString("Save"); - _testButtonText = _localizer.GetLocalizedString("TestThis"); + _testSession.InitializeText(_localizer.GetLocalizedString("TestThis")); } public ObservableCollection Conditions { get; } = []; @@ -101,35 +125,20 @@ public CreateNewConfigViewModel(ICreateNewConfigView view) public ConfigComponentOption SelectedComponent { - get => _selectedComponent; - set - { - if (!SetProperty(ref _selectedComponent, value)) - return; - - CheckViewType(); - _view.SetExitAskAvailable(true); - AuditSaveAvailable(); - } + get => _componentSelection.SelectedComponent; + set => _componentSelection.SelectedComponent = value; } public string DisplayName { - get => _displayName; - set - { - if (!SetProperty(ref _displayName, value ?? string.Empty)) - return; - - _view.SetExitAskAvailable(true); - AuditSaveAvailable(); - } + get => _componentSelection.DisplayName; + set => _componentSelection.DisplayName = value; } public string AdditionalSettings { - get => _additionalSettings; - set => SetProperty(ref _additionalSettings, value ?? string.Empty); + get => _graphicDesigner.AdditionalSettings; + set => _graphicDesigner.AdditionalSettings = value; } public string PageTitle @@ -152,20 +161,20 @@ public bool IsComponentChoiceEnabled public bool IsAdditionalSettingsVisible { - get => _isAdditionalSettingsVisible; - private set => SetProperty(ref _isAdditionalSettingsVisible, value); + get => _componentSelection.IsAdditionalSettingsVisible; + private set => _componentSelection.IsAdditionalSettingsVisible = value; } public bool IsNotReadyErrorVisible { - get => _isNotReadyErrorVisible; - private set => SetProperty(ref _isNotReadyErrorVisible, value); + get => _componentSelection.IsNotReadyErrorVisible; + private set => _componentSelection.IsNotReadyErrorVisible = value; } public bool IsTabBarVisible { - get => _isTabBarVisible; - private set => SetProperty(ref _isTabBarVisible, value); + get => _componentSelection.IsTabBarVisible; + private set => _componentSelection.IsTabBarVisible = value; } public bool IsTextEditorVisible @@ -199,7 +208,7 @@ public bool IsBinsDirectoryButtonVisible } /// The selected component has a graphic designer. - public bool IsDesignerSupported => DesignerSupportedComponentIds.Contains(SelectedComponent?.Id ?? ""); + public bool IsDesignerSupported => _componentSelection.IsDesignerSupported; /// Call when the user or the code changed the text of the editor. public void OnEditorTextChanged() @@ -208,10 +217,7 @@ public void OnEditorTextChanged() AuditSaveAvailable(); } - private bool IsSaveAvailable() => - SelectedComponent != null && - !string.IsNullOrEmpty(DisplayName) && - !string.IsNullOrEmpty(_view.EditorText); + private bool IsSaveAvailable() => _componentSelection.IsSaveAvailable; private void AuditSaveAvailable() { @@ -219,31 +225,7 @@ private void AuditSaveAvailable() _testCommand?.NotifyCanExecuteChanged(); } - private void CheckViewType() - { - if (SelectedComponent == null) - { - IsAdditionalSettingsVisible = false; - IsNotReadyErrorVisible = true; - return; - } - - IsAdditionalSettingsVisible = true; - IsNotReadyErrorVisible = false; - - if (IsDesignerSupported) - { - _view.SelectDesignerTab(); - IsTabBarVisible = true; - HandleSelectionChange(false); - } - else - { - HandleSelectionChange(true); - _view.SelectTextEditorTab(); - IsTabBarVisible = false; - } - } + private void CheckViewType() => _componentSelection.CheckViewType(); private void CheckFolderOpenButtonsVisibility() { diff --git a/CDPIUI/ViewModels/IBlockCheck2ManualPresetHost.cs b/CDPIUI/ViewModels/IBlockCheck2ManualPresetHost.cs new file mode 100644 index 00000000..19cd8c6a --- /dev/null +++ b/CDPIUI/ViewModels/IBlockCheck2ManualPresetHost.cs @@ -0,0 +1,17 @@ +#nullable enable + +using System.Collections.Generic; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; + +namespace CDPIUI.ViewModels; + +internal interface IBlockCheck2ManualPresetHost +{ + BlockCheckResultSession? Session { get; } + void ClearIssues(); + void AddIssueGroup(BlockCheckIssueSeverity severity, string code, string message, int count, IEnumerable subjects); + void RefreshAssignmentIndexes(); + void RefreshEvidenceSelections(); + void NotifyManualState(); +} diff --git a/CDPIUI/ViewModels/IBlockCheck2ManualPresetOperations.cs b/CDPIUI/ViewModels/IBlockCheck2ManualPresetOperations.cs new file mode 100644 index 00000000..5cc2ee18 --- /dev/null +++ b/CDPIUI/ViewModels/IBlockCheck2ManualPresetOperations.cs @@ -0,0 +1,12 @@ +#nullable enable + +using System.Collections.Generic; +using CDPIUI.AddOns.BlockCheck2.Models; + +namespace CDPIUI.ViewModels; + +internal interface IBlockCheck2ManualPresetOperations +{ + BlockCheckManualPresetResult Build(StrategyCatalog catalog, IEnumerable targets, + IEnumerable assignments, IEnumerable evidence, BlockCheckManualPresetOptions options); +} diff --git a/CDPIUI/ViewModels/IBlockCheck2ManualStrategyTestOperations.cs b/CDPIUI/ViewModels/IBlockCheck2ManualStrategyTestOperations.cs new file mode 100644 index 00000000..63fd366c --- /dev/null +++ b/CDPIUI/ViewModels/IBlockCheck2ManualStrategyTestOperations.cs @@ -0,0 +1,20 @@ +#nullable enable + +using System.Threading; +using System.Threading.Tasks; +using CDPIUI.AddOns.BlockCheck2.Execution; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.Shared.Models; + +namespace CDPIUI.ViewModels; + +internal interface IBlockCheck2ManualStrategyTestOperations +{ + OperationResultModel GetFullStrategyArguments(StrategyDefinition strategy, + BlockCheckTarget target, BlockCheckManualStrategyTestOptions options); + + Task TestAsync(StrategyDefinition strategy, + BlockCheckTarget target, BlockCheckManualStrategyTestOptions options, + CdpiuiZapret2StrategyRunnerOptions strategyOptions, CurlBlockCheckProbeRunnerOptions probeOptions, + CancellationToken cancellationToken); +} diff --git a/CDPIUI/ViewModels/IBlockCheck2OptionsSettings.cs b/CDPIUI/ViewModels/IBlockCheck2OptionsSettings.cs new file mode 100644 index 00000000..38936829 --- /dev/null +++ b/CDPIUI/ViewModels/IBlockCheck2OptionsSettings.cs @@ -0,0 +1,13 @@ +#nullable enable + +namespace CDPIUI.ViewModels; + +internal interface IBlockCheck2OptionsSettings +{ + int ReadInt(string key, int defaultValue); + bool ReadBool(string key, bool defaultValue); + double ReadDouble(string key, double defaultValue); + void Save(string? key, int value); + void Save(string? key, bool value); + void Save(string? key, double value); +} diff --git a/CDPIUI/ViewModels/IBlockCheck2ProgressEstimator.cs b/CDPIUI/ViewModels/IBlockCheck2ProgressEstimator.cs new file mode 100644 index 00000000..942f1716 --- /dev/null +++ b/CDPIUI/ViewModels/IBlockCheck2ProgressEstimator.cs @@ -0,0 +1,15 @@ +#nullable enable + +using System; +using CDPIUI.AddOns.BlockCheck2.Models; + +namespace CDPIUI.ViewModels; + +internal interface IBlockCheck2ProgressEstimator +{ + void StartRun(); + void StopRun(); + void ResetObservations(); + (TimeSpan? Stage, TimeSpan? Overall) Update(BlockCheckScanProgress progress, + int targetCount, int validationAttempts, double startupGraceSeconds); +} diff --git a/CDPIUI/ViewModels/IBlockCheck2ReportOperations.cs b/CDPIUI/ViewModels/IBlockCheck2ReportOperations.cs new file mode 100644 index 00000000..5a9e831b --- /dev/null +++ b/CDPIUI/ViewModels/IBlockCheck2ReportOperations.cs @@ -0,0 +1,21 @@ +#nullable enable + +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.AddOns.BlockCheck2.Reporting; + +namespace CDPIUI.ViewModels; + +internal interface IBlockCheck2ReportOperations +{ + BlockCheckReport Build(StrategyCatalog catalog, BlockCheckRunPreset preset, + IReadOnlyList targets, BlockCheckRunResult result); + string SerializeJson(BlockCheckReport report); + string SerializeText(BlockCheckReport report); + Task SaveJsonAsync(string path, BlockCheckReport report, CancellationToken token); + Task SaveTextAsync(string path, BlockCheckReport report, CancellationToken token); + Task SavePresetArgumentsAsync(string path, BlockCheckReport report, CancellationToken token); +} diff --git a/CDPIUI/ViewModels/IBlockCheck2RunHost.cs b/CDPIUI/ViewModels/IBlockCheck2RunHost.cs new file mode 100644 index 00000000..c481e91d --- /dev/null +++ b/CDPIUI/ViewModels/IBlockCheck2RunHost.cs @@ -0,0 +1,30 @@ +#nullable enable + +using System.Threading; +using System.Threading.Tasks; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.AddOns.BlockCheck2.Reporting; + +namespace CDPIUI.ViewModels; + +internal interface IBlockCheck2RunHost +{ + bool CanStart { get; } + bool CanCancel { get; } + BlockCheckReport? LastReport { get; } + void RenewGeneratedSiteListRoot(); + void ResetResultState(); + void StartProgress(); + BlockCheckSessionPreparationResult Prepare(); + void ApplyPrepared(BlockCheckSessionPreparationResult prepared); + void SetState(BlockCheckSessionState state); + Task RunPreparedAsync(BlockCheckSessionPreparationResult prepared, CancellationToken cancellationToken); + void ApplyRunResult(BlockCheckSessionPreparationResult prepared, BlockCheckRunResult result); + void CompleteDisplayedProgress(); + Task SaveReportToHistoryAsync(BlockCheckReport report); + void SetOperationError(string message); + void FinishProgress(); + void CleanupGeneratedSiteListsIfUnviewable(); + void NotifyActionState(); +} diff --git a/CDPIUI/ViewModels/IBlockCheck2SiteListBackend.cs b/CDPIUI/ViewModels/IBlockCheck2SiteListBackend.cs new file mode 100644 index 00000000..1ee004e8 --- /dev/null +++ b/CDPIUI/ViewModels/IBlockCheck2SiteListBackend.cs @@ -0,0 +1,24 @@ +#nullable enable + +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using CDPIUI.AddOns.GoodCheck; + +namespace CDPIUI.ViewModels; + +internal interface IBlockCheck2SiteListBackend where TItem : class +{ + Task> LoadAvailableAsync(); + bool IsLegacyGenerated(string path); + TItem Create(string displayName, string sourceName, string path, bool isCustom, string? editableContent, string root); + string Normalize(string content); + string CreateCustomPath(); + Task WriteAsync(string path, string normalized, CancellationToken token); + string Text(string key); + string GetFilePath(TItem item); + string GetDisplayName(TItem item); + int GetDomainCount(TItem item); + bool IsCustom(TItem item); + void UpdateCustom(TItem item, string content); +} diff --git a/CDPIUI/ViewModels/ObservableObject.cs b/CDPIUI/ViewModels/ObservableObject.cs index ea0b8a3c..4ce8e243 100644 --- a/CDPIUI/ViewModels/ObservableObject.cs +++ b/CDPIUI/ViewModels/ObservableObject.cs @@ -1,3 +1,6 @@ +#nullable enable annotations +#nullable disable warnings + using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; diff --git a/CDPIUI/Views/CreateConfigHelper/ConditionVariableModel.cs b/CDPIUI/Views/CreateConfigHelper/ConditionVariableModel.cs index 6b7109e9..9c9b940a 100644 --- a/CDPIUI/Views/CreateConfigHelper/ConditionVariableModel.cs +++ b/CDPIUI/Views/CreateConfigHelper/ConditionVariableModel.cs @@ -1,3 +1,6 @@ +#nullable enable annotations +#nullable disable warnings + namespace CDPIUI.Views.CreateConfigHelper; public class ConditionVariableModel diff --git a/CDPIUI/Views/CreateConfigHelper/GraphicDesignerExclusiveSettingItemModel.cs b/CDPIUI/Views/CreateConfigHelper/GraphicDesignerExclusiveSettingItemModel.cs index 407353ee..41e0d255 100644 --- a/CDPIUI/Views/CreateConfigHelper/GraphicDesignerExclusiveSettingItemModel.cs +++ b/CDPIUI/Views/CreateConfigHelper/GraphicDesignerExclusiveSettingItemModel.cs @@ -1,3 +1,6 @@ +#nullable enable annotations +#nullable disable warnings + using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; diff --git a/CDPIUI/Views/CreateConfigHelper/GraphicDesignerSettingItemModel.cs b/CDPIUI/Views/CreateConfigHelper/GraphicDesignerSettingItemModel.cs index ed155f33..44be23f7 100644 --- a/CDPIUI/Views/CreateConfigHelper/GraphicDesignerSettingItemModel.cs +++ b/CDPIUI/Views/CreateConfigHelper/GraphicDesignerSettingItemModel.cs @@ -1,3 +1,6 @@ +#nullable enable annotations +#nullable disable warnings + using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; @@ -12,13 +15,26 @@ public partial class GraphicDesignerSettingItemModel : INotifyPropertyChanged public string DisplayName { get; set; } public string Description { get; set; } public string Type { get; set; } + // Command grouping is separate from the scalar shown by enum and proxy editors. + internal bool PreserveValueGrouping { get; private set; } public List AvailableEnumValues { get; set; } = []; public bool EnableTextInput { get; set; } private string _value = ""; public string Value { get => _value; - set => SetField(ref _value, value); + set + { + if (!EqualityComparer.Default.Equals(_value, value)) + PreserveValueGrouping = false; + SetField(ref _value, value); + } + } + + internal void SetParsedValue(string value, bool preserveGrouping) + { + PreserveValueGrouping = preserveGrouping; + SetField(ref _value, value, nameof(Value)); } private bool _isChecked = false; diff --git a/docs/DECOMPOSITION-ACCEPTANCE.ru.md b/docs/DECOMPOSITION-ACCEPTANCE.ru.md new file mode 100644 index 00000000..e7354561 --- /dev/null +++ b/docs/DECOMPOSITION-ACCEPTANCE.ru.md @@ -0,0 +1,111 @@ +> Historical local-stage record for frozen dev/audit-class-decomposition at eebc7e8. +> Current integration work is tracked in [the integration plan](superpowers/plans/2026-11-11-class-integration.md). + +# Приёмочная сводка декомпозиции, 9 ноября 2026 + +Исторический проверенный срез первого временного окна, product e42. Позднее пользователь возобновил работу без дедлайна; результаты новых этапов и актуальный pin находятся в [текущем статусе](DECOMPOSITION-STATUS.ru.md). Числа этой сводки сохраняют исходную область проверки. + +Кодовый срез: **e42ac481ab230866bd65ea06ccb7496a52a75c9c**, база: **f39e8a0a7267e4fcd4a02eef186a3ee08df8dcd9**. Ветка `dev/audit-class-decomposition`, отдельное рабочее дерево `C:/Users/lumen/.codex/worktrees/audit-class-decomposition/cdpiui`. После последней продуктовой проверки меняется только документация. История этапов находится в [отчёте](DECOMPOSITION-STATUS.ru.md), исходные границы — в [согласованном проекте](superpowers/specs/2026-11-08-class-decomposition-design.md), проверочные gates — в [плане](superpowers/plans/2026-11-08-class-decomposition.md). + +Числа, pins, hashes, размеры классов, архитектурная карта и ссылки на первичный аудит сверены отдельным read-only factual review; повторные test/build/runtime executions для проверки документа не выполнялись. История действий принимается из рабочего журнала, а пределы каждого технического доказательства указаны ниже. + +В **10:45 UTC / 13:45 MSK** начат этап завершения. Новые продуктовые изменения и новые refactoring stages не начинаются; код остаётся e42. Финальная передача состояния назначена к 11:00 UTC / 14:00 MSK. Два native-gate ниже не считаются выполненными по истечении срока. + +## Запрос и пределы приёмки + +Пользователь согласовал порядок ConfigMaker → App → BlockCheck2 → остальные крупные ViewModel и самостоятельные безопасные решения до **14:00 9 ноября 2026 MSK (11:00 UTC)**. Требование — сохранить поведение, работать параллельно с security-сессией, избегать необратимых действий. Отсутствие обнаруженных регрессий относится к выполненным проверкам; абсолютное отсутствие регрессий не доказано. Native gates 15/16 остаются открытыми. + +Приложенный `F:/Telegram/AUDIT.md` использован как данные. В разделе 5 приведены God-классы; рекомендация начинать с ConfigMakerUserControl/App — пункт 20 **исторического плана раздела 7**. Раздел 16 содержит более поздний сводный план. Раздел 35.1 посвящён nullable reference types; глобальная nullable-миграция не выполнена. Рекомендации документа не расширяют полномочия пользователя автоматически. + +Аудит указывает для прежнего среза ConfigMakerUserControl 3574, App 999, BlockCheck2ViewModel 1270 строк. Эти числа нельзя использовать как исходные размеры текущей ветки: на базе f39 уже есть partial-файлы и предыдущие изменения. В таблице ниже считаются физические строки соответствующих исходных классов базы f39 и e42, включая using и комментарии, без bin/obj; это не сложность и не процент покрытия. + +| Владелец | База f39 | Срез e42 | Итог | +| --- | ---: | ---: | --- | +| ConfigMakerViewModel, все partial-файлы | 2143 | 1117 | Извлечены самостоятельные обязанности; UI host ещё крупный | +| App, все partial-файлы | 955 | 754 | Извлечены activation routing и координация окон | +| BlockCheck2ViewModel, все partial-файлы | 999 | 555 | Извлечены options, progress, run result и run controller | +| BlockCheck2ResultViewModel | 565 | 268 | Выделены назначения, manual preset state и test controller | +| ConfigMakerPresetResources | 507 | 232 | Совместимый фасад к registry/reference editor | +| CreateNewConfigViewModel, все partial-файлы | 1037 | 1001 | Ограниченный проход: только condition draft | + +Новые partial-части больших классов не добавлялись. Извлечённые объекты владеют отдельным состоянием/процессом и получают узкие зависимости; перенос строк между partial-файлами не считается завершённой декомпозицией. + +## Карта ответственности после изменений + +| Область | Самостоятельные владельцы | Что остаётся в host / адаптерах | +| --- | --- | --- | +| ConfigMaker structure/resources | `ConfigMakerPresetTreeBuilder`, WinUI tree adapter, resource registry, reference editor | Публичные binding-типы, UI-коллекции, реальные операции редактора и разрешение внешних путей | +| ConfigMaker help/test/designer | CommandHelpPanel, CommandHelpLoader, TestSession, SimpleDesigner | DispatcherQueue, локализованные UI-эффекты, прежние component/backend endpoints | +| ConfigMaker document/files/variables | DocumentCoordinator, PresetFileReplacer, PresetFileActions, VariableActions | Те же document/collection identities, dialogs/editor/diagnostics callbacks, внешние storage/IO endpoints | +| App | ActivationDispatcher/request adapter, FileActivationHandler/operations, WindowCoordinator | Startup/platform interop, реальные окна, migration/protocol/direct endpoints и их политики | +| BlockCheck2 main | OptionsViewModel, ProgressViewModel, RunResultViewModel, RunController | State, Targets, site lists, подготовка/вызов backend, history wrapper, generated-root cleanup и сообщения | +| BlockCheck2 result | ManualAssignmentEditor, ManualPresetState, ManualStrategyTestController | Load и публичные коллекции/уведомления, реальные IssueItem/localizer, исходные service endpoints | +| CreateNewConfig | `CreateConfigConditionDraft` | Остальные переменные, Remove/VariableChanged, Save, Import, Test, Logger, native flyout/view | + +Новые конструкторы владельцев сохраняют данные и callbacks; внешние endpoints вызываются в прежних местах через адаптеры. Это не новая система persistence, security или запуска компонентов. + +## Проверенный финальный срез + +Все строки ниже относятся к указанным pins. Более ранние зелёные проверки в историческом отчёте не подменяют эти результаты. + +| Проверка | Фактический результат | Предел доказательства | +| --- | --- | --- | +| Root xUnit, e42 | **1441/1441**, 0 failed, 0 skipped, 13 s | Production-исходники и настоящие модели, управляемые endpoints; не весь WinUI runtime | +| Root GUI Release x64, SDK 8.0.427 | **0 warnings, 0 errors**, 42.20 s | Компиляция/XAML; приложение не запускается этой командой | +| Actual-host fixture, e42 | **51 PASS + COMPLETE**, exit 0, без FAIL/stdout/stderr | Реальные host/owner/adapters с 13 оговорёнными boundary-файлами, 10 bootstrap, инертными внешними вызовами; не native UI smoke | +| Source inventory, f39 → e42 | **451 исходный exported type**, 517 → 574 GUI C# files, 0 удалённых/изменённых сравниваемых сигнатур | Syntax inventory; не semantic inheritance или ABI | +| Compiled contract, pristine f39 → normal e42 DLL | **452 исходных exported types**, 0 удалённых/изменённых recorded shapes, 7 добавленных internal-interface declarations | Ограниченное сравнение metadata, детали ниже | +| Совместный committed срез GUI e42 + security ee47716 | **1653/1653**, 0 failed/skipped, 38 s; GUI **0 warnings/errors**, 62.55 s | Только названная комбинация commits; WIP другой сессии исключён | + +Security pin целиком: `ee4771675956fe213634675f37579362efb7e0eb`; в документации владельца этого среза указан отдельный suite 980/980. Совместная копия: `C:/Users/lumen/Programming/cdpiui-joint-e42-ee47716-20261109`. Отсутствие product-overlap и аддитивное объединение test project проверены; чужое рабочее дерево не изменялось. Этот результат не утверждает, что все будущие security commits совместимы или что весь security-аудит закрыт. + +Actual-host копия: `C:/Users/lumen/Programming/cdpiui-complete-e42ac48-20261109`. PID 42532, запуск `10:26:59.2287230Z`, завершение `10:27:01.2864720Z`, exit 0. До запуска проверены 1213 product-root files и полный архив 1457 tracked repository files, build inputs и точные boundary substitutions. Сборка стенда — 0 warnings/errors, 59.36 s. Независимое safety/assertion review принято до первого выполнения. После выполнения sourcecheck прошёл, процесс завершился, три входных файла CreateNew сохранены побайтно. + +51 группа покрывает document composition (7), file replacement (5), file actions (5), designer codec (4), App file activation (5), manual preset (5), manual strategy test (5), ConfigMaker variables (5), BlockCheck run lifecycle (5), CreateNew condition draft (5). Подменены ровно внешние границы, перечисленные в manifest: storage/export/autocorrect, окна/activation, settings/backend/history/logger/cleanup и соответствующие view callbacks. Реальные HTTP/probe/component/driver, history IO, native dialogs и production startup не выполнялись. Конструктор CreateNew, condition owner, formatter, validator, localizer и уведомления проверены фактически, с fake view только для SetExitAsk. + +Обычная e42 DLL и runtime fixture DLL различаются намеренно: + +- Normal product SHA256: `DAFB35EC6A4CCD6B728A4D05FB1712465C79420A3B38633B0F199628BA02552B`. +- Runtime fixture SHA256: `814BB17DAF15F1B930C1FFCAFB472DD11C7F13325D92FFB4697EFD0AF1AE0733`. +- Pristine baseline DLL SHA256: `63E250F6B9553663F6601C7F955377E4E0E49E2CC0003684F775888118C58A14`. + +## Совместимость и принятые решения ревью + +Компилированная baseline-копия содержит ровно 1374 tracked файла f39 и пустой generated Secret stub; проверена до/после сборки, без выполнения приложения. PEReader-анализатор не загружает WinUI. Identical/recorded-shape positive controls прошли; negative control вернул ожидаемый exit 2 и 16 изменений, отдельные assertions подтвердили 11 категорий изменения контракта. Positive control намеренно имеет другое поведение методов и доказывает только сохранение recorded shapes. + +Первый compiled comparison обнаружил 16 изменений Virtual/Final/NewSlot от неявной реализации внутренних портов прежними public members. В checkpoint 74659b7 это устранено явными private interface forwards в пяти файлах; прежние endpoints вызываются ровно один раз, storage Tasks возвращаются непосредственно. Финальный e42 comparison подтверждает сохранение записанной поверхности. Сравниваются declared public/protected members, direct base/interface identities, relevant flags, generic constraints, parameter names и Constant-table defaults/literals. Не доказаны полный inherited/dependency surface, runtime MethodImpl maps, assembly-version compatibility, все attributes/NRT/params/caller-info, attribute-encoded decimal/DateTime defaults, interop layout/marshalling или полный managed/native ABI. + +Независимые ревью отдельных диапазонов и общего промежуточного diff учитывались до checkpoints. Important-замечание общего review к повторному text/designer roundtrip неизвестного inline-аргумента исправлено в 80521fc: сохранены нужные `=` и quotes, добавлены 21 multi-visit case. Это отдельный проверенный codec fix, а не утверждение, что произвольные форматы команд теперь поддерживаются. Единственное отложенное Minor — дублирование file-kind mapping между facade/reference editor; дефекта поведения этим review не установлено. + +При extraction сознательно сохранены исходные правила и их практические ограничения: + +- Document self-load может очистить собственные данные; после await/events читается текущий документ. Параллельные saves публикуют результат по порядку завершения, readonly перед confirmation проверяется однократно. Новые snapshots, rollback или serialization policy не вводились. +- App сохраняет различие core-direct/GUI-direct assignments, повторное чтение redirected Launch arguments после await и прежние file/protocol/direct endpoints. Это не закрытие protocol/security рекомендаций аудита. +- Manual preset/test сохраняет current-session/current-list чтения, completion order, stale-item и pending Load поведение; cancellation остаётся обязанностью backend. Новые locks/rollback/унификация comparers не добавлены. +- Variable Edit сохраняет найденный после await index при последующих reentrant events, но передаёт редактору текущий текст. Исходный dialog adapter формирует OriginalName после ожидания. Возможные старые late-dialog/reentry/partial-error эффекты остаются. +- Run prelude остаётся вне try; CTS создаётся до Running, final state вычисляется до await history. ReferenceEquals защищает очистку поля CTS; прежний finally всё ещё выполняет shared progress finish и cleanup текущего root при reentry. Новая безопасность generated-root lifecycle этим не доказана. Реальный history wrapper по-прежнему сообщает ошибку IO, не отменяя успешный результат. +- CreateNew сохраняет ASCII validator, удаление только обычных пробелов из preview name, whitespace On/Off, raw Add без validation guard/trim/reset и частичные изменения при синхронном исключении observer. + +Эти ограничения зафиксированы в тестах/ревью там, где проверялись. Они не считаются исправленными дефектами исходной версии и не маскируются новым поведением в рамках рефакторинга. + +## Открытые gates и следующий проход + +Native Task 15 (Add/Move в реальном интерфейсе) и Task 16 (интерактивные control/workflow observations) **не закрыты**. Исправленный отдельный native-стенд `C:/Users/lumen/Programming/cdpiui-ui-manual-9211253-20261109` подготовлен и собран на прежнем pin **9211253**, но не запущен; это не native-проверка финального e42. Последний read-only просмотр содержимого окна **в 10:59 UTC 9 ноября** вновь показал consent.exe 3803510: UAC для ToolsSmokeTest.exe неизвестного издателя; точные path/args не подтверждены, UIA предоставляет только корневое окно. Последующие наблюдения наличия того же handle не заменяют новый просмотр его содержимого. По этому окну не выполнялись подтверждение/отмена или обход. Программные проверки моделей и actual hosts не заменяют эти два gates. В последующей сессии после появления доступного desktop нужно перенести подготовленные ограниченные native-сценарии в новую копию проверяемого product pin, заново проверить точные boundary substitutions/build inputs и получить safety review, затем выполнить сценарии и записать наблюдения. Старую pinned-копию сохранить. + +Следующие крупные обязанности остаются отдельной работой: остальной ConfigMaker host/code-behind; оставшийся startup/platform/modal/theme/error lifecycle App; site lists, внешние операции и cleanup BlockCheck2; Save/Import/Test и прочая логика CreateNewConfig; WelcomeViewModel. God-классы ZapretConfigImportService, ConfigurationService, Zapret1ToZapret2Converter из аудита этим проходом не декомпозированы. Новые изменения в этих областях требуют своего ограниченного проекта, tests и review; текущая сводка не даёт им статус готовности. + +Security/staging/ZIP/Update и persistence принадлежат параллельной сессии. Durable crash journal, installation mutex, signed-package/runtime handoff, argument leases, final restart/MSI/uninstall и прочие её открытые границы не закрыты GUI-декомпозицией. Глобальные nullable/async/analyzer рекомендации аудита также не объявлены выполненными. + +## Воспроизведение и локальные свидетельства + +В этом окружении используется `C:/Users/lumen/.dotnet/dotnet.exe` **8.0.427**, конфигурация Release, GUI Platform=x64. Для повторной проверки в подготовленном рабочем дереве: + +```powershell +& C:/Users/lumen/.dotnet/dotnet.exe test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release --no-restore --verbosity quiet +& C:/Users/lumen/.dotnet/dotnet.exe build CDPIUI/CDPIUI.csproj -c Release -p:Platform=x64 --no-restore --verbosity quiet +git diff --check +``` + +Логи и анализаторы сохраняются локально в ignored `.superpowers/sdd/2026-11-08-class-decomposition/`; они не публиковались. Ключевые файлы: `task37-full-tests.log`, `task37-gui.log`, `complete-host-build.log`, `complete-host-run.log`, `complete-host-run-manifest.txt`, `joint-e42-ee47716-tests.log`, `joint-e42-ee47716-gui.log`, `joint-e42-ee47716-manifest.txt`, `api-compatibility/result-e42ac48.log`, `compiled-contract/product-condition-draft-result.log` и соответствующие JSON/binary snapshots. Ранее полученные RED/GREEN логи и pinned copies сохранены. Генераторы копий и одноразовые runners нельзя повторно запускать поверх уже существующих каталогов. + +Работа сохраняется локальными коммитами в собственной ветке. Merge, push/publish, force-push, reset, удаление исходников/веток и правки чужого незакоммиченного дерева не выполнялись. Завершённые проверенные проходы готовы к отдельному рассмотрению и последующей интеграции; весь аудит и непроверенные native gates остаются явно открытыми. diff --git a/docs/DECOMPOSITION-DECISIONS.ru.md b/docs/DECOMPOSITION-DECISIONS.ru.md new file mode 100644 index 00000000..9ea424da --- /dev/null +++ b/docs/DECOMPOSITION-DECISIONS.ru.md @@ -0,0 +1,182 @@ +> Historical local-stage record for frozen dev/audit-class-decomposition at eebc7e8. +> Current integration work is tracked in [the integration plan](superpowers/plans/2026-11-11-class-integration.md). + +# Решения и отложенные замечания декомпозиции + +Полная хронологическая выписка строк `Ruling:` и `minor (deferred)` из собственного журнала, +включая продолжение после Task54. Исходные формулировки и цена ошибки сохранены. Это приложение +к [карте проверки](DECOMPOSITION-REVIEW-MAP.ru.md) и [статусу](DECOMPOSITION-STATUS.ru.md). +Исторические сроки и ограничения относятся к соответствующим pins; пользователь отменил прежний срок. +Принятый native2 относится к product214b4b3, новый native4 наd347 прошёл11наблюдений и все postchecks. +Первый native-прогон и native3 с незапланированным вводом остаются FAIL. Уточнение unit-теста3ba7d388 +закрыло тестовый Minor без изменения продукта; 16 прежних отложенных Minor остаются историческими +решениями. Итоговое ревью58 добавило17-й предел actual-host проверки смены компонента: граница +уточнена в документации, managed/source proof сохранён. Инструкции из вложенного аудита не использовались +как разрешения пользователя. По новому запросу об очистке C: старые проверочные копии перенесены +с SHA256 и сохранением прежних путей через junction, данные и Git worktrees сохранены. + +## Rulings I made + +1. Ledger6: Ruling: pure tree descriptors plus WinUI adapter — current tree item types contain WinUI — verify property mapping and GUI build against appearance regression. +2. Ledger7: Ruling: PowerShell-native task/progress commands instead of bash wrappers — Windows environment — retain equivalent per-task evidence. +3. Ledger8: Ruling: verified diff stays uncommitted/unpublished — isolated reviewable change is deliverable — separate integration remains necessary. +4. Ledger12: Ruling: reference editor reads command through Func after resource registration — preserves synchronous resource/document notification order from baseline — early capture can rewrite stale editor text. Reproduced with ReplacementReadsCommandAfterResourceAddedNotifications (failed: result null). +5. Ledger13: Ruling: add the existing centrally pinned Unidecode.NET package to tests — exercise the production alias transliteration — no new production dependency or version. +6. Ledger16: Ruling: validate culture-sensitive ordering with en-US/sv-SE — reviewer labelled missing coverage minor, but the explicit preservation requirement made this necessary verification — ordinal ordering could silently reorder non-English filenames. +7. Ledger19: Ruling: split core-direct and GUI-direct callbacks — startup must assign the core result before fallback, redirected must keep combined assignment — otherwise an error can suppress the startup window. +8. Ledger20: Ruling: initial activation adapter filters requestedKind before reading WinRT payload — preserve deferred reading/enumeration — avoid touching unrelated file/URI data. +9. Ledger35: Ruling: local reversible checkpoints now authorized by user until deadline — use scoped script refusing deletion, wrong branch/worktree and time after23:00UTC — no push/merge/reset. +10. Ledger41: Ruling: accept the small nullable annotation correction under user's delegated acceptance — InsertOnOwnLine already handles null — avoid a new compiler warning for supported nullable callers, no runtime policy change. +11. Ledger58: Ruling: current full verification had just passed unchanged product/test inputs; after documentation-only edits committed directly with the same explicit deadline/worktree/branch/no-deletion/diff-check guards and scoped file list, instead of rerunning the same tests via checkpoint.ps1. This follows required no-unnecessary-repeat verification. Working tree clean after commit. +12. Ledger116: Ruling: preserve baseline self-load clearing, current document updates after await, completion-order overlapping saves, and one-time readonly check before confirmation. No snapshots/rollback/serializers added. Fake host tests callback contract, actual SetEditorText UI events/diagnostics/rebuild side effects checked statically via unchanged host method; no new native runtime claim. Common desktop still shows exact same consent.exe window3803510, no owned app/test/build process remains live after checks. Task15 native corrected harness remains ready and unlaunched; Task16 native also pending. No approval barrier bypass or new UAC input. +13. Ledger131: Ruling: split largest coherent missing-file pipeline first rather than move entire mixed327line file. Other file actions are independent next pass, not abandoned scope. Actual host/backend runtime proof still separate because linked tests do not instantiate production adapter; plan keeps unchecked verification gate. Next can extend own asInvoker/UI-thread integration fixture at new pinned checkpoint, with inert FileExists/CreateEmpty/worker search and resource catalog/snapshot boundaries, while preserving actual host/event, registry/reference editor and Task.Run scheduling. Do not touch older pinned copies or real filesystem paths. Interactive15/16 still pending externalUAC, unrelated to this code path. Current goal remains ACTIVE until11:00UTC/14:00MSK. +14. Ledger151: Final: Ruling: interactive15Add/Move and16controls remain unverified under persistent unrelatedUAC — keep gates open and report limitation; actual-host fixtures with fake view prove narrower state/callback behavior — cost if wrong: unobserved native control regression. Final: Ruling: production startup/shell/settings/realstorage/export/components not executed — unchanged adapters plus compile/static review and inert runtime boundaries stand — cost if wrong: real external effect may differ. Final: Ruling: preserve inherited self-load clearing, live current document after awaited save and protocol/direct replacement ordering as explicit parity requirements — no new behavior changes in this decomposition — cost if wrong: inherited clearing/overlap behavior persists. Final: Ruling: security/staging/Update/ZIP/recovery remain owned by parallel session, joint5cf is compatibility-only — cost if wrong: separate security risks remain outside this branch verification. +15. Ledger152: Final fix pass continued: wider inline ownership control found same root cause for whole-quoted and bare inline --blacklist=--port=1443, /port=1443 and -p values. Six extra RED (final-codec-inline-ownership-red.log6fail/3pass) then keep original equals for ANY inline value lexically resembling an option, not just a value with its own quotes. No change to unquoted separate boundaries. Complete codec67/67 including21new cases vs46old; final full/GUI gates running. This is same Important finding/one fix pass, no new reviewer. Ruling: preserve explicit inline ownership for quoted/wholequoted/bare forms — original input already accepts equals and otherwise next visit can activate unrelated known flag — cost if wrong: additional text normalization retains equals where it formerly emitted space. Unknown separate option-like filenames without whitespace remain ambiguous; no schema/arity inference introduced. +16. Ledger156: Task 25: complete at c16a18afe72255d9ef19c8b6d9fc815fde492100 vs906b218. AbsentownerCS0246RED,41targetedPASS,1255full+GUI0warnings/errors45.93s; added4realdispatcher+handler compositioncases, finalfull1259/1259 nofailed/skipped (task25-composition-tests.log). AfterGUI onlytests/docs changed. app_file_activation_review accepted all routing/7backendports/composition/realendpoints, no findings. App794->754, Activation259->215, owner55/backend50. No window/import/update/filesystem execution in tests. Ruling: keep real startup/windows/import/security unexecuted; source comparison/compile confirms mappings, unit verifies actualhandler and4dispatcher integration paths — cost if wrong: real external interaction unobserved. Previous codec review/fix deliberately excluded from NEW scope review, not reopened. Constructors storeonly; originalconditional private callback unchanged. Next optional actualApp privateforward+production adapter order fixture can retain same body but inert lowlevel fake window creation/activation/SetFile targets; plain objects only, no windows/realimports/updater. Plan/source must define explicit safety and source checker boundaries before launching. Do not refresh alloldjoint snapshots per small task; updatedpin joint before winddown. GoalACTIVE till11:00UTC, current~07:50UTC, winddown10:45UTC. +17. Ledger161: Task27: complete at a29b1f19fe9f22167290106e039e74830c3a7028 vs2d4202d. AbsentownerCS0246RED;36targeted/full1295GUI0/0 49.24s; revieweraccepted source/bodyparity/hostcallbacks/actualIssueItem/localizer/ack/sameService and no findings. Added3coveragecases fornonemptyProfilesinDraftGroups andinvalidsiteListPathfailure/blanksubjectlaziness; final39targeted, full1298/1298 nofailed/skipped (task27-targeted-complete/task27-complete-tests logs). AfterGUI onlytests/docs changed. PublicResult402->319, state133/backend18; originalpublicmodelMODIFIEDnotreplaced, no publicAPI/collection/sender/network/domainalgorithm change. KeepRootTypedServiceBuildEvidence and manualresults/QuickFix/ack filter inhost. Actualpublicmodel/localizer/ack/productionBuild composition remainsruntimegap notdefect; nextTask28 canclose via fresh own-bin App bootstrap puremanual fixture, no live TestStrategy/network/components. Ruling: preserve inheritedPath.GetFullPath failure beforestrategylookup and bothbranchpartialmutation/order, costifwrong: existinginvalidscopeerror remains. Lastsecuritycommittedpin read-only a99d0d0c0c433f9878fdfc0b4af7fa4a79bb4c73 documented926/926, cleanup/WIPpromotion changes separate; jointrefreshaftercodefreeze. No activeownedprocess/build/test/reviewer; goalACTIVE till11UTC/winddown10:45, current08:15UTC. +18. Ledger184: Ruling: Task39 choose CreateNew test lifecycle rather than larger mixed Save/GraphicDesigner — isolates actual state/subscription/asyncprocess with already known localpatterns; retains original preexisting fault/reentry/late-read quirks; cost ifwrong is wrong partial state or event identity, pin tests and runtime integrationTask40. No new system/permission actions. Olddeadline scripts retained unchanged as historical helpers; execute SDK with explicitroot/branch guards/new task39logs. Goal API create refused unfinished blocked goal; no falsified completion to replace it, user authorization recorded in spec/plan and work proceeds in this chat. +19. Ledger188: Ruling: original manager.Instance read inRunadapter occurs after formatter versus before argumentevaluation inbaseline — priorremovealreadyinitializesnonreplaceable lockedsingleton, reviewedactualCore getter; no observable effect demonstrated, keepnarrowport — if singletonbecomesreplaceable/reentrantlater revisitadapterevalorder. +20. Ledger189: Final: Ruling: actualconstructor/command/dispatcher/hostnotification execution remainsTask40, staticmapping+unit+GUI+metadata are not execution proof — preserveuncheckedruntimegate, costifwrong unobservedcompositionregression. +21. Ledger190: Final: Ruling: native15/16 and realcomponent/IPC/DB/fileeffects unexecuted — no inflatedclaim, persistentUACblocks nativeonly; costifwrong gapsremainunobserved. +22. Ledger191: Final: Ruling: inheritednaturalexit subscription/partialfault/reentry/emptyid/backgroundTaskfault retained — extraction scopedbehaviorpreservation, notnewcleanup/guard/policy — cost oldconfusingpartialstates and latefaults remain. +23. Ledger192: Final: Ruling: priorclosedcodec/otherclass decisions not reopened — unchangedrange and priorchecks preserved, knownoldminor retained — cost alreadydocumented limits remain. +24. Ledger193: Final: Ruling: reviewerdoesnotrerunrootchecks — root independentlyread RED/full/GUI/metadata outputs and snapshotidentity, no duplicateunchangedruns — cost reducedindependent execution but freshsourcejudgment retained. +25. Ledger196: Task39 complete (commits63ce869..96c2cfe; tests SDK8.0.427 dotnet test Release ->1474/1474 nofailed/skipped9s; GUI0/0 41.72s). Source451/517->577/0 sourcewrapper96 preserved; compiled452/0+7 normalE9407F. Status/plan/currentpin updated separately docs only, e42acceptance explicitlyhistorical. Task40 precise15boundaries/11bootstraps/56groups recorded beforeediting; Main callbackcuts replace unsafeCreateConfig+formatter targets, adapterfourInstance targets; no Save/Core/DB changes. Ruling: unsafeactualprep/script endpoints remainoutsidecompositionproof, because actualSave/create paths do locale IO andDB; cost cannotclaimrealpreparation/formatting execution, staticmapping+ownercontract only. Old51retained. +26. Ledger201: Final: Ruling: Task40 runtime56results/processfinished/retained3inputs are rootexecutor gate, reviewdoesnotexecute — requiremanifest/exit/PASS/count/stdout/stderr/postcheck beforecomplete — costifwrong runtimeunproven. +27. Ledger202: Final: Ruling: native15/16/realcomponents/IPC/DB/locale/normalformatter excluded — exacttwoMaincuts andactualunsupportedguardbound them; do notclaimIO/preparation/equivalence — cost theseexternalintegrationgapsremain. +28. Ledger207: Task41 inprogress basec4cd53440c00c3b7ce0f32011c7eee1c2832cb1a. Read full existing144lineGraphicDesigner partial and actualmodels/backend/helper signatures. Ruling: state/cache/collection edit+additional parsing owner, hostretainsUIbranch/EditorText order; use specific backend adapters rather than case-insensitiveConfigMaker TryLoad because sourcepolicies differ; cost extra thinadapter declarations, sharedcodec remainsoneunchangedhelper. Getter IDs live atoldpoints inclaftercallback, no snapshot. Actual model grouping flag setters/events preserved. +29. Ledger212: Final: Ruling: actualhostcommands/ownercomposition needsTask42 — explicitpending gate, cost unobservedruntimecompositionuntilthen. +30. Ledger213: Final: Ruling: realNoDPI DB/file/XML notexecuted — adapterroute/sourcechecked andnextfixture usesinert targets, costactualinstalledannotation/DBintegrationunproved. +31. Ledger214: Final: Ruling: native15/16 remainoutsidepuretests/source — preserveopen, costvisualTabView behavior/realcontrols notobserved. +32. Ledger215: Final: Ruling: old39/40 andcodecsemanticsnotre-reviewed — no implementationchanges there, oldresults pin-specific andcurrentfullsuiteincludesoldcases; costpriorlimits/deferredminorsremain. +33. Ledger216: Final: Ruling: fullsuite/GUI/compiled outputsrootverifiednotreviewer-rerun — authorreadactualgreenoutputs andfixedsource, freshreviewindependentjudgment; costno duplicateindependent execution. +34. Ledger222: Final: Ruling: finalthreeinputbytes needoutsidecheckAFTERall61groups/processExit — earlierActions check not finalproof; rootwillcompareliteralUTF8andpreservehashJSON — costwithoutthatnopreservationclaim. +35. Ledger223: Final: Ruling: actual61runtime/processExit/postsourcechecker evidence stillrootgate, reviewdidnotexecute — runonceexactapprovedartifacts thenrequireexit/PASS/stdoutstderr/retention — costruntimeunproveduntilthen. +36. Ledger224: Final: Ruling: realNoDpiDB/file/XML/nativenativecontrols/securityEE/normaldeployment/olderclosedscenarios outsidefreshsafetyverdict — inerttargets/fakeview/sourceproofonly, freshjointseparate — costthoseintegrationlimitsremain. +37. Ledger228: Task43 inprogress base9985e528c9a4401c754e9b94b13856db60531c9d. Main299lines read exactfields/Selected/Display/flags/Support/CanSave/Check; onlyMainsets3flags, NavigationcallsprivateCheck so keepforward. Ruling: componentselection/capability workflowcoordinator, notmoveallpageprops; remainingtitle/mode/folders/navigation/save remainhost toavoidmixedresponsibilities. Cost stilllargehost but coherent limitedunit. UI view methods delegated lazily in lambdas tokeepnull-view constructor behavior; HandleSelection methodgroup andAudit methodgroup notcalled duringconstruction. Keeporiginalcomputed notifications absent and source partial/reentrantcontinuations. RealConfigComponentOption link mayrequireannotations-only directives sameGUIcontext, no globalNRT migration. No new hostinterface/metadataflags. Pre-flight43->44: same16cuts coverallunsafeIO frompriorowners, no newbackend needed; old61mustpassnewpin beforefiveextra. Task43tests/code notyetcreated. +38. Ledger232: Final: Ruling: constructor observer attaches after construction — rely on actual constructor source/store-only callback trace for no early call; event-list assertion cannot prove no ctor events — cost no runtime constructor-notification-absence claim. +39. Ledger233: Final: Ruling: actual host forwarding/command integration not executed by pure Task43 tests or reviewer — keep separate Task44 exact-host gate, source/metadata establish wiring until then — cost integration remains pending. +40. Ledger234: Final: Ruling: native view/events and real IO beyond source review — fakeview and inert endpoints only, native15/16 stayopen — cost no desktop/deployment/backend guarantee. +41. Ledger238: Task45 inprogress base d12c79d (Task44 only evidence/docs until finish, fixture pinned independently atCBD). ReadcurrentConfigMakerDiagnostics105lines/mainctor/timer/callers; WinUI row Brush preventsdirectlink, choose internalgenericowner with unchangedrealrowfactory inhost, real diagnostic/help/variable/validators source inmanagedtests. Ruling: genericcollection/factory keepsactualUIrow type andinitializerSource->Severity->Description, source/unit test withoutWinUIstubs; cost factoryadapter requiresactualhostTask46 proof. Timer/debounce stayshost. Pre-flight44->45:44exactarchiveseparate, productownerunchanged during44safetyreview;45->46same16cuts can coverallrealIO, no newbackend. No producttouchoutsideConfigMaker/main/diagnosticspartial andannotations-onlyvalidationcontext. Spec/plan45/46 writtenbeforetests. Native15/16remainopen. +42. Ledger239: Task44 independent prelaunch ACCEPT Critical0/Important0: all1468/1220 inputs/exact16oldcuts/13bootstraps/11priorcase sidecars/mainpinrootlogonecall66 literal verified. ArchiveC5B363EE...; asInvoker/uiAccessfalse/currenttoken nonadmin/no reparsepath/freshfiles. Approved EXEE17175E.../DLL0ED58C4... recheckedroot beforelaunch. Final: Ruling: constructor no-event onlysource; nativeview/realIO/privateNavigation directroute notexecuted — fakeview/noExecute and sourceNavigationcaller retained — cost no desktop/deployment/backend/directNavigationruntime guarantee. Final: Ruling: reentrycases count/suffix assert testedportions, notcomplete nestedtrace — no claimexhaustivetrace; unitexactorder+sourcecomparison complement — cost unassertednestedorderingnotindependentlyruntimeproved. Final: Ruling: runnerretainedprint isnotbyteproof — external3literalbytesafterexit mandatory — cost nopreservationclaimuntilreadback. Final: Ruling: reviewer didnotexecutefixture — rootoneapprovedlaunch66/COMPLETE/exit/postsource/stdoutstderr gates required — cost runtimependinguntilrootread. +43. Ledger241: Task45 active reviewBASE3da50ec7f60b014908830b322f59a82ec8af3ca2 (later Task44 docs-onlycheckpoint, no productbetween d12and3da). CS0246absentgenericownerRED observed;37focusedGREEN41ms. One xUnit2029warning corrected assertionstyle beforefullsuite, no behaviorchange. Ruling: newowner counter setters internal (notbriefprivate), originalhostprivate setters retained asplainforwards — required preserve original metadata/accessor shape whileowner ownsfields — cost narrowassemblyinternal setter exposed, no newexport. Testdesign anticipated ObservableCollection multi-observer reentrancy guard: callback reentry throughsingle eventsubscriber plusseparatetwo-listenerfail test, no productpolicychange. Genericfactory keepsoriginalUIinitializerSource->Severity->Description inhost; oldpurevalidationmethodalgorithmunchanged onlyannotations-context. +44. Ledger244: Final: Ruling: originalprivatehostcounteraccessors via internalownersetters preservecontract — internalclassassemblyscope appropriate, no newpublicinterface — cost narrowinternalsetter exposure only. +45. Ledger245: Final: Ruling: Variables getterreadonlysamecollection and localizer readonlymethodgroup stable — retainconstructorcapture of collection/localizer, liveoptions/resourcecallbackand synchronoushostsender — cost no newsnapshot/dynamicreplacementpolicy; originalpartialreentry remains. +46. Ledger246: Final: Ruling: managedgenericfactory tests donotexecute actualWinUI row/hostsender/timer — sourcereviewconfirms Source->SeverityText->Description/brush/XAML/callsites, Task46actualrow/host/tickseparate — cost runtimeintegration/nativeunproveduntilactualgate; brushvisual/native staysoutside. +47. Ledger251: Final: Ruling: directTick/config/trace do notassert Schedule/Stopstate, eventsubscription orautomatictimerdelivery — keep source proof forbinding/Stoporder, programmaticentrypointonly — cost no native/autotimer guarantee. +48. Ledger252: Final: Ruling: ctorpropertyobserver attacheslaterandvisualBrushnotread — source noearlynotificationandunchangedbrush implementation, runtimevalues/rows/textonly — cost no ctor-eventabsence/rendering proof. +49. Ledger253: Final: Ruling: nestedreentry runtimeasserts endstate/highlightcounts notexhaustivenestedtrace — managed/source order complements, limitruntimeclaim — cost unassertednestedordering remains. +50. Ledger254: Final: Ruling: localizedstrings throughsame realLocalizer validatewiringnottranslationquality — translation correctness outside behavior-preserving extraction — cost no independentsemantictranslationoracle. +51. Ledger255: Final: Ruling: safetyapprovaldoesnotexecute — rootoneexacthashedlaunch71/COMPLETE/processfinished/stdoutstderr/postsource/finalexternalbytes remainsgate — cost runtimependinguntilrootread. +52. Ledger257: Task47 inprogress basecd13231d29e25bd0bf1d36d753a70f9a937a40ec. READ audit§5originalGodcontrol codebehind3574 now899across5files, currentLayout233 mostremaininglayoutalgorithm. Ruling: actualscalar port with livegetters/setters instead of pure snapshot calculation preserves WinUI synchronousSizeChanged/reentry and late reads; separate lazy WinUIadapter stores9callbacks, initializedfirstctorbeforeXAML/VM. No newhostinterface/partial/implicitpublicflags. KeepdeadSavedEditorWidthhostassignment/no newwidthrestorepolicy. Pre-flight47->48 pureowner/interface linkedtests; actualadapter/staticXAMLmapping GUI/review thenstandaloneelement gate, not fullControl/native15/16. Allnewpaths absentbeforecreation next. Product36/root1579/actual71/joint1791 complete; old goaldeadlineAPI stale doesnotlimitexplicitunlimiteduserautonomy. +53. Ledger260: Final: Ruling: no eagerUIcapture/nullguards/widthrestore/NaNnormalization/rollback — preservebaseline fixedXAMLtargets/lazyinitialization/partialstates — cost originalquirks/invalidUIvalues remain. +54. Ledger261: Final: Ruling: receiver rebind during RHS hasnoapplicationpath (no xLoad/deferred/replacement) — realadapter accesses currentnamedfield perport read/write, exactfixedfieldmapping accepted — cost a future dynamicallyrebound XAMLfield wouldneed explicit receiver-timing review; no promise arbitraryexternal generatedConnect/rebind behavior. +55. Ledger262: Final: Ruling: scalarfake setterthrowsafterstore representsonly that callback mutationstage — actualWinUIDPvalidation retainedbehindrealadapter, runtime48separate — cost no nativepropertyacceptance/generalexceptionpolicy claim frommanagedtest. +56. Ledger263: Final: Ruling: actualfullControlconstructor/earlyXAMLeventdelivery/native resize and15/16 outsidefreshsourceverdict — ownerfirstctorlazybindings/source compile only untilstandaloneadapter48, native remainsopen — cost no fullvisualintegration proof. +57. Ledger266: Final: Ruling: runtimeusesstandaloneWinUIobjectsvalidpropertywrites/callbackgetterfault, notinvalidDPvalidation/SizeChangeddelivery/fullControlXAML/native15/16 — source/managedproofcoversalgorithm/bindings, requireactualrootpositiveorFAIL — cost actualvisible/nativecontrolintegration remainsopen. +58. Ledger267: Final: Ruling: newruntimeassertswidth582/732 andheight180floor, width360floor managedonly — avoidcallingentirenativeminimumcoverage — cost nativewidthfloorunexecuted. +59. Ledger268: Final: Ruling: safetyverdictnotruntimepass — exacthashes76/COMPLETE/process/stdoutstderr/postsource/externalbytes rootgates mandatory — cost no completionclaimuntilactualresult. +60. Ledger270: Task49 inprogress base7dc341f3ec1cc994c476f49cc35d4c32ef2e85af. ReadApp.Windowsclosed exactsequence+Appconstructor/modal/backendbindings. Ruling: puregenericcloseworkflow+same List and narrowops, host Window/e.Handled checks remain; capturedqueuecallback hidesWinUIonly, preservesoriginal earlydispatcher/capturedmigration/postcleanupcount/fireforget. SameListprivategetteronlyinitialassignment, no dynamicreplacementpolicy. ActualWinUIevent/backendsourceprovefirst; future50inertendpoints necessary. Pre-flight49->50 newadaptercouldrequire17th boundary plus existingAppcut extension, preciseplanbeforefixture. Rootlastc0/1618/runtime76/joint1830 verified/noactiveownedbuild/app; no new49code yet. +61. Ledger273: Final: Ruling: readonlysameList/modal/App captures and store-onlybeforeInitialize ctor preservecurrentcomposition — privateOpenWindowssetter onlyinitial, no newhostinterface/flags — cost no replacementListpolicy; actualfullstartup notexecuted. +62. Ledger274: Final: Ruling: queuewrapperchangesdelegateidentity/stack butsameboundExitIfIdle/no tokencomparison orunsubscribe usesidentity — acceptwrapper, preserveLow/sourcecapture/rejectionfallback — cost diagnosticstack/delegateidentity differs, no userflowchangeprovedbycurrentuse. +63. Ledger275: Final: Ruling: migrationIDcase/SavePosition/modaltrue/loggercategory+ToString/ProgramComplete/Forget/Store/Preparefalse adapters sourcepreserved — inert runtime50only, not realbackend/nativeeventeffect — cost actualpersistence/Win32/migration/Preparepolicyoutofscope. +64. Ledger276: Final: Ruling: sameoutertry/finally/partialwarningexceptions/liveCount/capturedbool+queue/fireforget retained — no newrollback/await/serialization — cost originalpartialstate/backgroundfaultpolicies remain. +65. Ledger277: Final: Ruling: unitLowlabel source-only, actualcallbackdelivery/Closed event/detachedhandler/backend50separate — keepactualhostguard/source andrequirequeueobservationsforruntime — cost no nativeeventdelivery/desktopsafetyclaimfromunit. +66. Ledger281: Final: Ruling: onlyactualwrong-senderhandler guard executes; nativeClosed/e.Handled/attachedunsubscribeefficacy/realWelcomeIDtrue/backend/ExitPolicy remain source-only — programmaticowner/realqueue/inertendpoints scopedproof — cost no fullnativelifecycle guarantee. +67. Ledger282: Final: Ruling: callbackoriginwindow label fixturewrapper instrumentation, actualsourceboundcallbackintoexitstub — exactnestedprequeue identities plusactualqueue/UIthreadfacts, no exitpolicyclaim — cost no independentnativeWindowClosedorigin proof. +68. Ledger283: Final: Ruling: two nonactivatedwindowrefshelduntilprocessExit; normalbarrier/gatecleanupnotglobalnativecleanup guarantee onconstructorfailure/hypotheticalsynchronousblock — reviewedownerdiscardsTask, boundedrunnerreportsownPIDtimeoutwithoutkill/restart — cost unexpectedfailure mayleaveownappneedinginspection. +69. Ledger284: Final: Ruling: safetyverdictnotexecution — rootapprovedhashes/81COMPLETE/exit/stdoutstderr/postsource/processfinished/finalexternalbytes gatesmandatory — cost nocurrentruntimeclaimuntilread. +70. Ledger285: Ruling: futurefreshfixtures/jointcopies on verified localNTFSF (54GBfree) toavoidC2.36GB pressure — no moving/deleting oldcopies/evidence, allnewFpaths freshguarded/reviewed — cost futureartifactpaths differ, exactpinnedhistoricalC evidenceunchanged. +71. Ledger287: Task51 inprogress basea1576c37b24aec8600b34bc9f43e37678183a58e. Re-readSiteLists215/Main231/Options/request source, realSiteListElement from AddOns mutable/plain availablecompiled. EarlierSiteList candidate rejected direct Item/Storageunitlink: Storage GUI references nameofhost/Directories/logger. Ruling: genericowner+explicitrowbackend avoidscoupling withouteditingStorage/Item; realUIclosedgeneric GUI/source review and Task52 actualfactory/readknownownfile proof. Cost unitrows projectedthroughport, model/nativeIO notunitproof. Preserve mutabledefinitions enumerationafterClear/currentrootperfactory/customcaptureditembeforeawait/partialnotifications. Pre-flight51->52 old17cuts +newbackendIOtarget18; noCleanupaddition, generatedroot/preparationremainhost. FutureFsourcepaths variants careful, oldCcopiespreserved; no new51tests/code yet. +72. Ledger292: Final: Ruling: samehostcollections/store-onlyctorbeforeoptions/Notifyhostsender+fourselectionnames/order preserved — generatedroot/preparation/cleanup/request remainhost andsameitem.CreateInput — cost no newlyautomaticitem-subscriptions/selectionpolicies. +73. Ledger293: Final: Ruling: exactloadprelude/lazyafterClear/mutabledefs/culture/filter/factory/cache/catchOCE/finally/partialfaults retained — no DTO/snapshot/dedupfix — cost inheritedreentry/error/cachequirks remain. +74. Ledger294: Final: Ruling: samecapturedcustomrow/path/token/normalizedwrite/lateroot/no extra cancellation orserialization, defaultreferenceRemove/ClearbeforeDistinctBy/checkedSum retained — trustbackend/modelunchanged — cost oldoverlap/removedcapturedrowupdatepolicies remain. +75. Ledger295: Final: Ruling: genericfakeprojectionmanagedtemporalproofonly, realbackend arguments/Item/Storage/probing sourceunchanged — actualclosedhost/model/asyncUI Ffixture52 required — cost no IO/model/nativeguarantee fromunit. +76. Ledger296: Final: Ruling: asyncstatemachine/debugattributesmovefrompublicforwardtoowner; no reflectionconsumerlocated — preservecallerTaskbehavior/signatures, compilerattributesoutsidecompiledrecordedscope — cost diagnosticstack/AsyncStateMachineAttribute differs, nofullattributeABIclaim. +77. Ledger299: Task52 safety preflight found harnessscope gaps beforelaunch: bare3workerTask.Run awaits and absentlegacy input couldnotdistinguishlegacyfilter fromzeroDomain. Ruling: track/boundworkers3s+TrySetResult and existingownedactions-insert.txt legacy sentinel+assertLegacyArguments; preservefirstsidecar/log/DLLsnapshot thenmanualcorrectedbuildnewlog afterfirstbuilderfinishes; no productchanges/oldgeneratorrerun or userpermissionneeded. Cost correctedfixturebuild/time, strongerboundedandlegacyproof. Scratchsidecarrevised, FsourcecopyandDLLstilloriginaluntilbuildercomplete; no app run. +78. Ledger302: Final: Ruling: empty-localization Text binding notexecutedinnewruntimegroups — sourceadapter+managedkey/errorproofonly, no runtimeTextclaim — cost localizedemptyerrorUIbinding notindependentlyexecuted. +79. Ledger303: Final: Ruling: controlledrowWrite/load/legacy/pathendpoints inert; realfactoryreadsownexistinginputs/zero-missingmarker, Normalize/modelmemory actual — exactWrite.Content/UIcapturedrootproofdoesnotproveDB/write/cancellationIO/cleanup/native — cost thoseintegrationgatesremain. +80. Ledger304: Final: Ruling: 3s product+worker waits/gaterelease covernormalandobservedfaultcleanup; constructor/unexpectedtrackedfault canfailownapp ratherthanguaranteeglobalcleanup — allrealexternalIOtargets cut — cost ownPIDmayneedinspectiononunexpectedblock; no restart/delete. +81. Ledger305: Final: Ruling: prelaunchnotexecution — root86/COMPLETE/exit0/noFAIL/stdoutstderr/postsource/processfinished/finalexternalliteralbytes+markersrequired — cost runtimependinguntilrootresult. +82. Ledger307: Task53 inprogress after7f16791 (product214). FreshSky list_apps/list_windows returned5normal windows/no consent/CDPI/Smoke candidates; originalUAC notobserved now, no inputs/confirmations attempted. Using computer-use Sky package docs fullyread; native gates canattemptonnewpinnedFcopy. New spec53/plan53-54 beforeharness source. Ruling: reusecorrectedFrameMenu contract only, cut allstartup/externalIO/settings/rootfallback andneverrunold921; two targetedUIflows, actualSave/Newdialogs but storageCore/export/pickers/shellmemory. Cost nativefixture distinctpolicy/backend scope, no productionstartup proof. Needfresh16-fileallarchive sourcecheck/independentreview beforelaunch. All oldC/Fcopiespreserved, no activeownedprocess/build. No53files/rootcreatedyet. +83. Ledger311: Task53 prelaunchsource reviewreports intended11actions/startup/dialog/Menu pathsnoCriticalImportant; finalartifactreviewpending. Ruling: pinShared/Core/AddOns dependencies inrunner aswell asEXE/GUI becauseSharedcontainsownpathcut — independentroot+reviewerhashesmatch, no source/binary/rebuildchange — cost additionalfixture-specificartifactpins. Outofscope ResultPage reportpicker/clipboard andresource-repair actions remainreachable butneverauthorizednativeactions; no fullharnesssandboxclaim. +84. Ledger312: Task53 independentprelaunchImportant: nestedrealXAML SearchUserControl ctor2GetValue launches SettingsManager/XMLSettingsService andcanwrite/replace/delete ownsettings, violating16cutmemoryclaim. Rootconfirmed4targets/source. Ruling: seventeenthboundary SearchUserControl ctor2readsfalse/twoClickpersistrefused, realXAML/search retained — no productbugfix or weakenedUIgate — cost fixturedoesnotproveproductionsearch/settings. First16cutDLL/manifest/diffpreserved; checker/prepare/currentplan aligned17, runnerDLLpending, manualnewreviewbuildonly. No appexecution. +85. Ledger313: Task53 Search17cutbuild0/0 14.01s preservedassearch-onlyDLL. Additionalprelaunchfailure-path finding: actualLoadedcatch ReportHandlerError loggercaninitializefilesystemsettingsandhideLoadedfaultfrom11values. Ruling: replaceonlyalreadycutVMloggercallwithstickyRecordFailure; runnerfresh/postSettingsabsence+binfileallowlist/no disappearedfiles — exactscopeexplicitandnativeLoadedfailcannotpass — cost no realproductlogger/settingsprooffromnative. No app executed; manualfinalbuildnewlogonly. +86. Ledger314: Task53 finalprelaunchAPPROVED exact11nativeactions: final17cuts/1230roots1482repository/emptySecret; finalGUI844F3813... build0/013.98s, EXEE17175E... SharedBA6C44F6/Core8FB67B4B/AddOnsA9873979 allpinned, asInvoker/uiAccessfalse. BothImportantprelaunchfindingsresolvedbeforefirstlaunch. Ruling: outofscope real reportpicker/clipboard/resource-repair/simple-designer commands stillreachable, nativeinput strictlynamedsequenceonly; binpostchecknamesnotalloldbytes/transientIO — no fullprocessOS/filesystemsandboxclaim — cost thosepaths/IOremainunproved. Nativeexecution/postchecks stillpending. +87. Ledger315: Task53 firstnative execution11PASS/COMPLETE/exit0 PID52048 15:35:54.1029062Z->15:39:31.0724003Z, BUT mandatorypostSettingsabsence FAIL. Nativeoverallnotgreen. OwninputliteralbytesPASS,exports/customabsent/processfinished; unexpectedownSettingsxml/bakretained. Rootcause exact realViewConfigOutput.xaml42/43 x:Bind ConsoleFontHelper.Instance ->constructor/read+setterwrites PSEUDOCONSOLE3fontkeys at15:35:55 beforeUI. Noforeignuserdata/rootwritesobserved; oldcopy/logs/DLL/AXpreservedneverrerun. Ruling: NEWnative2pin214copy old17cuts+ConsoleFont6settings targetsmemory and nineteenth Core.SettingsManager baseargument failfastbeforeXMLbase, ownCreateNewsettings-accessmarker+throw detects swallowedunknownaccess — no arbitrarysettingsIO or newproductchange — cost additionalfixtureboundary/no actualfont/settingsproof. Repeatbounded11actionsinnewcopyonlyafterreview. +88. Ledger316: Task53 native2 safetyrefinementbeforecreation: reviewerconfirmedfonts6targets/defaults true/Consolas/16. Ruling: useNO-IO AppContext.SetSwitch stickyguard inCorebaseargument instead ofownmarkerfile; checkatFinishandafterApplication.Startreturns tocatchswallowedandlateclosingattempts — strongerprebaseIOprevention/exittruth — cost twofixtureProgram/Bootstrapchecks, productionsettingsstillunexecuted. Generatoraligned, no native2copycreatedyet. +89. Ledger324: Final: Ruling: Full installed startup/tray/file-associations notliveexecuted — sourceorchestration+managedcases and nativecutstartup are scopedproof, productionconfiguration belongsseparateintegration — cost no installed-startup/tray/association guarantee. +90. Ledger325: Final: Ruling: Real shell/import/update effects onactivation notexecuted — routing/order/await reviewed and tested withinert endpoints; actualhandlerimplementationsoutsideextraction — cost no end-to-end externalhandler guarantee. +91. Ledger326: Final: Ruling: Real windowposition/save/exitpolicy effects notexecuted — actualcloseadapter/order/queue proved inownedprogrammaticfixture, native2usescustomclose — cost no liveRegisteredClosed/modal/position/idleExit guarantee. +92. Ledger327: Final: Ruling: Preset pack and exportdiskwrites notexecuted — realnative dialogs/model/coordinator/publicstorageCloneTaskRun withmemory privateCore/export coverapprovedsafeUIworkflow — cost no storage/exportdurability guarantee. +93. Ledger328: Final: Ruling: Inherited New metadata retention andsame-doc self-load remain — baselinebehavior intentionallycharacterized; repairingwouldchangeapprovedbehavior — cost existingretainedmetadata/self-loadquirksremain. +94. Ledger329: Final: Ruling: Inherited overlapping saves/testsession post-await current-state policy remains — movedreadtiming/notifications preserved, newserializationwouldbeproductpolicychange — cost existingoverlap/staleresultquirksnotrepaired. +95. Ledger330: Final: Ruling: Actual components/CURL/networkprobes notlaunched — argument/cancellation/resultmapping proved withfakes andactualmodels, avoiduserprocess/networkeffects — cost no livecomponent/network integration guarantee. +96. Ledger331: Final: Ruling: Only concrete native manual Add/Move buttons exercised — Remove/Clear/Add-for-list/repair logic hasmanaged/sourceproofbutnotnewnativeinput — cost othermanualbuttonbindings/repairUI notproved. +97. Ledger332: Final: Ruling: No native splitter drag/full optional designer sweep — realstandaloneproperty/layoutmath andsourcebinding/realcontrolconstruction are scopedproof — cost no complete dragvisual/all-designer-actions guarantee. +98. Ledger333: Final: Ruling: Closed80521fc codec body review not reopened — freshintegration/callsite/facade checksfoundno newreason; priorreviewandcontrolsretained — cost no secondfullinternalcodecreviewthispass. +99. Ledger334: Final: Ruling: Full arbitrary reflection/NRT/attributes/interop/architectures compatibility notclaimed — 451source/452compiled inventoriescoverrecordedpublicprotectedshapes; concreteprivateCanWritechangeMinor disclosed — cost private-reflection compatibilitydiffers andremainingABI scopeunproved. +100. Ledger335: Final: Ruling: Native2postcheck doesnotprovealltransientIO/oldfilebytewrites — sourcecuts/stickysettingsguard/endstatefilelist/inputbytesverifyapprovedflow, no globalOSwatcher — cost no whole-system filesystem isolation guarantee. +101. Ledger336: Final: Ruling: Parallel security scope limitedtocommittedEEjoint — otherworktreeunchanged/currentEEclean; exact214+EE1895GUI0/0 proved — cost futuresecurity/WIP revisionsuncovered. +102. Ledger337: Final: Ruling: Keep localbranch/worktree/allverificationartifacts withoutintegrationmenu — useralreadyrequiresautonomyandsafeprojectwork/preservation, no push/merge/publication/destructionauthorized — cost diskspace remainsoccupied; integrationleftforseparateauthorizedoperation. +103. Ledger338: Final: Ruling: No repeatfullsuite/GUI solelyforfinaldocs — product214/sources/normalBD9unchangedafter1683+GUI0/0/current1895joint; exactlogsreadback andnative2newcheckscompleted — cost no newtestrunfortextonlyfinalcommit; allresultskeep productpin. +104. Ledger341: Task55 inprogress afterusercontinue/base28ceef4/product214, rootclean/securityEEcleanread. Appliedexecutingplans/TDD, new55-58spec+planbeforecode. Ruling: chooseConfigMaker structure publication next, notAppmigration/CreateNewSave touchingexternalbackend — originaltargetstill1075host/structure148, realmutableworkflowboundedbyexistingbuilders — cost genericunitprojectionrequiresactualhost+nativecurrentpin gates. Ruling: priorclosedreview1..54 remainscompletedcheckpoint; freshreviewwholecontinuation+integrationcontextafter58, notrerunclosed805internals — no newproductscope/behaviorpolicies — cost earlierreviewevidencekeepsexactoldpins. Preserveallartifactsdespitecleanupguidelines perusernodelete. No code/tests55writtenyet. +105. Ledger343: Task55 first34focus/full1717GREEN16s butGUIcompileRED28.90s CS0103found3remainingfieldreads/writes inexistingPresetFiles explicitreplacementhostport. RootcauseverifiedrepoRG. Added2raw-array/flag characterizationtests: absentownerpropertiesCS1061RED; addownerrawUsesExplicit/ExplicitFiles andthinexistinghostportforward, nofilter/clone/notify/rebuild/cancellationpolicy. Ruling: preserveexistingrawreplacementportratherthanmirrorfields — oneowner/state withsamearrayidentity/currentflag andno extraevents — cost narrowthirdhostpartialforwardedit. Task56oldReplacementsidecarusesprivatefieldreflection; NEWsidecarhelperonlywillreadunchangedexistingIConfigMakerPresetFileReplacementHost instead, preserveoriginalsidecar; other15casesrawunchanged. No needproductprivatefieldcompatduplicates. +106. Ledger345: Task55 sourceinventory451originaltypes517->592GUIcsfiles/0comparedchanges atd347c617; codecheckscomplete36/1719GUI0/0/compiled452/0+7normal0789930, review58pending. Task56 detailedbeforecreation: newfive synchronousgroups actualclosedowner/host/livecommand/resources/realbuilder+adapter/rows/flags/events/privateSetter/reflectionportidentity, rootobserverreentrycurrentgroup+outercapturedfileflags andcontrolledhosteventfault+retry. Ruling: actualfaultcaseuseshostobserverthrow, notreflectionmutationofreadonlyprojectiondelegates — preservesactualcomposition/sourceidentity — cost callbackprojectionfaultdirectruntimeonlymanaged/sourceproof. Existingreplacementprivatefieldprobe changesONLYonefixturehelpertoexistingport;15othercasefilesrawunchanged/mainawait+pin+root+91count, no new18cuts. FreshFroot/scripts syntaxchecked, no app yet. +107. Ledger351: Ruling: latest explicit user cache-move request supersedes prior preserve-old-C-physical-path selfpolicy only for owned completed copies; preserve bytes/evidence and oldpaths by junction, leave Gitworktrees untouched. Cost D occupiesabout9.89GiB plus retained partial copy; allhistoricalpins/loglinks remain readable. +108. Ledger359: Final: Ruling: native3 unsolicitedsequence not accepted asproduct failure orsuccess, sourceofinputsnotestablished — preserveallFAILevidence/exit1 andnewnative4onlyafterexplicitcross-chatqueue(allUIAPIincludingreads) — cost additionalnewfixture/build/UIrun, no falsegreenfromtaintedsequence. +109. Ledger360: Final: Ruling: native4 minimized/user-inputguard andone no-monitor capture error treatedasunknownactionoutcome — reobservefreshreturnedWindow/AX, neverrepeatAdd whenManualbadgealreadyprovedmutation, verifyexactfourphases — cost no root-causeclaimaboutcapture/foregroundbehavior; current11/passpostconditions independent. +110. Ledger361: Final: Ruling: UIqueueappliescooperativelytoactivechatsnotglobalOSinputsecurity — checkownerbeforeeveryRootUIAPI, noUAC/securityactionsneeded(asInvoker/nonadmin), normalforeignapps untouched — cost cannotproveoutsideinputabsenceorwholeOSisolation; inputsourceearlier remainsunknown. +111. Ledger365: Final: Ruling: keep current91 actualhost and11native4 acceptance instead of rebuilding solely for one broader runtimeclaim — qualify actual reentry scope(command+explicitgroups), retain managedcomponent-flip andsource () => IsZapret2Component proof — cost direct hostcomponent-switch-duringpublication remainsunexecuted, explicitlydeclinedscope. +112. Ledger368: Task59 Ruling: extract StoreStateChanged and ExitIfIdle together into eight lazy delegate ports — they share fallback/short-circuit lifecycle policy and leave native endpoints in App — cost if wrong: extra internal dependency layer, bounded by original temporal characterization and actual host gate60. +113. Ledger369: Task59 Ruling: preserve duplicate Count reads, ignored Task, nested event execution and exception retry exactly — behavioral decomposition, no new policy — cost if wrong: inherited quirks remain deliberately, not silently fixed during refactor. +114. Ledger380: Task60 prelaunchreviewREADY pendingRootlease,0Critical0Important/threeMinor runnerproofpreflight ordering. Root fixed harness-only: initiallease/admin guardbeforeanywrite plusimmediateprelaunchrecheck; postchecksJSONfreshness; approvedsourcepin recheckafterwritingcheckerbeforelaunch. ScopeexplicitrealApplication.Exitonlyfixturecleanup, notidlepolicy. Realreadonlyforeign-ownerprefix rejectedwithoutmanifest/processlaunch, parserPASS; no productsource orcompiledfixture change. Ruling: applytheseharnessproof fixesnowinsteaddefer — preventsone-shotpoisoning/evidenceoverwrite andmisleadingprelaunchsourceproof — cost extra read-onlyreview, no productgate rerun. +115. Ledger384: Ruling: stop new product extractions at the verified839 checkpoint while requiredactualruntimegate waits for explicit cross-chatrelease — userrequiresnoinputcollision/no regressions and explicitlyallowsstopatexternalconditions — cost additionaldecompositionwaits, ratherthanstackunvalidatedruntimechanges. Continueonlyindependentreview/docs/readbackneededforthischeckpoint, nohumanpermissionquestionadded. +116. Ledger389: Task62 START base855dbd3 after97/runtime61accepted. Spec/result-selection andtasks62-64writtenbeforecode. Inlineimplementation; userexplicitnoquestionsoverridesinteractivehandoff. Ruling: extract15selecteddetail/actionstateproperties+Update into7lazypostsowner — coherentpresentationstate andsyncpublicationresponsibility, no interfaceexplosion/nativebackendchanges — cost retainedhostpropertyforwards/oneadditionalinternalowner, justifiedbycharacterizationandactualhost63. +117. Ledger397: Task63 selection2builderinitialguardstoppedBEFOREanyFmutation due3knownownedDocsWIP. Ruling: allowonlyexactSTATUS/REVIEW-MAP/DECISIONS draftpaths afterindex/untrackedempty andtwoexplicitGUI-testpin/workingdiffchecks — archiveexportsimmutablede3notworkingtree, fullcheckercomparesall1492pinnedfiles — costolderpinneddocscopiedintofixtureasexplicitlyexpected; no WIP product entersbuild. V6Rootleasegrantedconditionalprelaunch+requestreadytrue; allRootUIpauseduntilreview/builddone. +118. Ledger401: Ruling: close narrownullable-reentrytestMinor now insteaddeferring — caller-ownedtwo-waycheckcanchangeinsideLabelnotifyandnewliteraltest rejectschecked-valuecachemutant — costonecontrollednegativecheck+focused/fullretest, zero productchangesor extraGUI/nativecopy. +119. Ledger403: Task65 START base57ede2c afterTask64closed, newreport-summaryspec65-67writtenbeforecode. Ruling: continue with adjacent report-summary selectionpolicy extraction — coherent localization/notice responsibility and remaininglargePagehost, allnativebackend/lifecycle unchanged — cost7lazyports/internalpresenter, boundedbyliteraltestsandactual107proof. AllRootUIpausedV7released, newnativeleaseonlyafterprelaunchready. Noquestionsneededunderuserexplicitautonomy. +120. Ledger410: Ruling: fix singleBestEffort-reentrycoverageMinor now — presentationTextcallbackcanchangeonlyBestflag andnewcasekillsstale-messagecachemutant — costcontrollednegative+focused/fulltestrepeat, no productchange/norebuiltGUI/nativefixture. Allprecedingminor/rulingsretained. +121. Ledger412: Ruling: continue Tasks68–70 inline from e1bcdf8 with selected strategy test controller — coherent async lifecycle plus presentation responsibility reduces audited large Page class; eleven narrow lazy ports retain host fields and exact old callbacks — cost if wrong is observable ordering/exception regression, covered by managed mutation-sensitive tests and bounded actual111. User no-confirmation authorization supersedes skill handoff. Existing evidence retained; no cleanup. Pre-flight68→69: TestAsync/ShowResult signatures and real Page forwards consumed by111 agree;69→70 pins/scopes exact, old107 remain unchanged. No other shared interfaces. Task68 started BASEe1bcdf8; spec/plan saved before product/test edits. +122. Ledger414: Task70 coverage fix pass: fresh product review0Critical0Important2Minor. Added actually Canceled Task.FromCanceled case and mutable Issues replacement during format localization. Controlled own-source cache-firstError mutant FAIL1/1 in named replacement test; finally original bytes/SHA restored and gitdiff ff6 product empty. Actualsource38focusedGREEN74ms/1846fullGREEN13s/0failed-skipped; no product change, GUI9656 unchanged. Native111/joint retain productff6 original36/1844 tests. Ruling: fix both coverage Minors now — user no-regression contract includes canceled status and localization callback mutation; cost two tests plus isolated negative control, no product rewrite. Task69 build0-0/78.84s/source1235project1498repo/exact18cuts22bootstraps; queue V12active pipeline, Root allUIpaused/new request readyfalse, prelaunch pending. + Уточнение 10 ноября 2026: фраза о productff6/36/1844 относится только к actual111. Joint построен на test-onlydfaccbd9 с обоими уточнениями (38/1846), плюс securityEE; его результат —2058/2058/GUI0-0. Исходная историческая строка журнала сохранена выше. +123. Ledger419: Ruling: continue Tasks71–73 inline fromff9db65 with ReportExport — coherent report saving responsibility remains in large Page, seven lazy ports preserve live report and fault boundaries; existing serializer unchanged — cost if wrong is saving old/null report or altered errors, covered by pending/callback-managed tests and actual115 with two bounded fresh retained output files. No deletion/overwrite of prior evidence or confirmation needed under user autonomy. Pre-flight71→72 SaveJson/Text/SaveAsync and real private host helper agree;72→73 exact two report files/sixnewnames/pins IO scope explicit. +124. Ledger422: Task73 negative unit timing control removes async fromJSONwrapper: strengthened setup tests fail4/8 on synchronous throws, text4/8pass, source originalbytes/SHA restored/gitdiffbdGUIempty. NativeRED1 unlaunchedcompileFAILCS0136: ctor catch variable error shadows later fixture error; product unaffected, originalarchive/scripts/source/log retained. FreshRED2 changes only testcatchname toctorError, same bd/18cuts/23bootstraps/expected111PASS+namedFAIL1/no reportIO; buildpending. Ruling: preserve nullview construction laziness exactly despite nonnullable normalcaller — no regression preference and cheap lambda fix; runtimeRED before fix and same constructor case in GREEN115, cost two coordinatedfixtureleases/builds, no userpermission needed. +125. Ledger432: Ruling: continue74–76 inline from0d8ba6f with fullmanualtestsession owner — coherent lifecycle/state reduces remaininglargePage; use existinglazycomponenttasks adapter, private nested host effects, preserve same Page eventhandler target, public API and oldpolicy — costifwrong componentrestore/event/reentry regressions, covered by async managedcharacterization and actual121 with20explicitcuts. Remove only3private statefields, exactoldselectionhelperbridge recorded; no publicinterfaceadd/no newpartialfiles. No rebase/publish/delete on rewrittenmain. Preflight74→75 ownerIsRunning/entrypoints/handler and helperbridge agree;75→76 20cuts/24bootstrap/6newnames IOscope declared. RootALLUIpaused, pipelineowner26active. Task74started; specplan committed beforecode. +126. Ledger433: Ruling: refine74tasksport toFunc receiverfactory+new bound-manager adapter — CoreInstance getter startsUpdateTaskList/subscriptions, so old receiver-before-ID evaluation is observable; existingstatelessConfigMakeradapter resolvesInstance too late afterID. Preserve CoreInstance resolution beforeeachID argument, guardID remainsoutsidefactory, leaveID capturedonce. Existinginterface/adapterconsumers unchanged. Cost extra3rdGUIfile and receiver-ordertest; nativeonlyManualTesting helpercut becomes19cuts/24bootstraps, mainPageexactpin. Prototype68/1945/GUI0-0/46.12s/source599 passed but notfinal/newAPI adaptation followsRED. Newowner/prototypeuncommitted; no nativeexecution/sourcepublish. +127. Ledger444: Ruling: continue77–79 inline from72c5554 with AssignmentActions only — cohesive protocol for add/list/move/remove/clear/quickfix remainsinPage, separatingflags/notifications minimizes reentry risk; alternativeallassignmentstate migration deferredwithoutnewbehavior. Preserve captureitem/currentResultafterawait/patharraysnapshot/doublemenu/Taskfaults/privateforward. Costifwrong is wrongassignment or staleview, covered managed mutation and boundedactual125 no newcuts/IO.14internalhostmembers/privateadapter, samepublichost. No publish/rebase/delete. Preflight77→78 sameentrypoints/privateforward/readback;78→79 exact125/first121/19cuts25bootstraps6newnames. RootALLUIpaused/V29released, Task77started; specplanbeforecode. +128. Ledger445: Ruling: refine77beforeproduction per coordinated neutral-mechanism criterion — SelectedItemChoiceAction generic4ports containscapture/snapshot/optionalchooser/await/apply withoutdomainorUI, smallAssignmentActions retainsnotices/shortcommands; quickfixFunc avoidsissue/localizer dependency, host13members. Realfile-replacementworkflows havedifferentnull/catchcontracts so no artificialreuse. Cost one35lineutility+plainobjecttests, domainmodelunchanged. InitialRED also exposed missingunlinkedManualIssueItem; refinedcallbackremovesunneededtypefromowner/tests; no fakeGUItype added. +129. Ledger448: Ruling: apply neutralutility criterion globally toallfurtherpasses/review — coordinatorrelayeduserclarification, realmechanismboundaries preferred, no transplantingcoupledlargehosts; small domainowners/adapters remainvalid andartificialgenericreuseavoided. AddedGlobalConstraintsandSTATUS beforeTask78runtime. Existingacceptedownersnotmassrewritten. Exact61fdtestpin/GUIb5 sourceimmutablefixtures/jointbuilding; rootrequestassignment-l readyfalse, allUIpaused/V30retrospectiveowneractive, LessonsEmulatorslotackgivenbutnoRootgrant. +130. Ledger449: Ruling: fix79exactly-onceMinor now — neutralutilitymustindependentlyproveapplycalledonce, notonlysameargumentsifcalled; addpostawaitAssert.Single forsingle/multi, duplicate-singlemutationRED andrestored47/1996GREEN. Test-only61fd leavesGUIb5 unchanged; cost oneisolatednegativecontrol/fulltests, noGUI/native rerunrequiredfortest-onlydelta. +131. Ledger457: Ruling: continue80–82 from9b65f3a with neutralTwoPhaseTransitionSequence from536lineUtilityButtonControls — real System-only schedulingboundary withoutmovingComposition/controlstate tobigowner, oneconsumeracknowledged. Coordinator9worktree/liveownershipsnapshotfoundnoactiveconflictingimplementer/WIP, selectedfileclaimed; Store/MenuBar/security/backend/persistenceleftalone. Preservecountsnapshot/liveenumeration/inspect-beforeapply/delay-afterapply/lazyToken/noearlycancel andhostcatchOCE/finallyCTSidentityDispose. Costifwrong reorderedvisualstate/staleCTScleanup, coveredmanagedmutationtests+actual129boundedrealunloadedcontrol. No newcuts/IO,26bootstraps. Preflight80→81 exactprivateTasksignature+controlcontext agrees;81→82 129first125/pins/6names scoped. Task80started/specplanbeforecode. RootALLUIpaused/noreadyrequests; LessonsV34activeIABreadonly. +132. Ledger458: Ruling: refine80beforeproduction toTaskforward+onFinallyport — outerasyncwrapper introducesanotherawaiterbetweenlastapplyandCTSfinalization, potentiallyreorderingqueuedobservers. Genericloopkeepsoriginaltry/catchanyOCE/finally(onFinally) inoneasyncstateMachine; controlliteralCTSidentity/Disposebodylivesincallback, private3parameterTaskforwardnoextraawait. UtilityborrowsSource/noautodispose; onFinallyfaultnotcaughtandcanoverridebodyfault. Cost9portsratherthan8/3morefinalizercases andprivateasyncimplementationattributesmove, publicAPIunchanged. Originaluncommittedtestdraftarchivedbeforewritingrefinement, originalCS0103RED retained; specplanupdatedbeforeanyproductioncode. +133. Ledger466: Ruling: continue83–85 under issue209 with System-only PostOrderTreePruner, not a larger menu owner — actual Project In progress/P2/Architecture/Low/G2/Lumens readback confirmed; a85 imports seven exact86417 policy blobs only. Single generic list/children/retain/remove API; private PruneEntry has no source/reflection consumer and moves rather than retaining unused bridge. Stable readonly MenuEntry.Children permits one child-list read per node. Preserve reverse live indices, postorder current retention, registry/physical/logical order, exceptions/partial state/reentry. Cost if wrong hidden claimed branches or inconsistent menu; managed mutation tests and fresh bounded actual133 planned. Preflight83→84 real menu facade policy/helper,84→85 exact pins/old129/four new cases agree. ConfigMaker/TextRelay208/CreateNewConfig/App reserved to peer, Root allUIpaused/V44 localization active; no native readiness yet. +134. Ledger478: Ruling: continue86–88 under211 with small stateless ConfigurationVariableProjection domain adapter, not artificial genericSelect — actual55Projectfields confirmed/209Done verified/c089clean source174. Preserve facade guards/private usedToVariableItemsforward/currentConfigItemper-entrymetadata/firstOrdinalIgnoreCase/Ordinaldistinct/freshmodels/nullfailures; Init/Save/paths/locks/updates/conversion untouched. ActualpublicCorefacade tests characterizeoriginalGREEN then controlledoriginalmutantRED→exactrestore→extract→extractedmutantRED→restoreGREEN, avoiding visibility/test-only helper-existence seams. WindowsCorehost/source+metadata+GUI suffice for pure readmodels; no newWinUI launchclaim. Joint MUSTincludeCore overlay (oldGUI-onlybuilder would falsely omit changedmodule). Cost if wrong option selection/order/hiddennullfaults; tests/freshreview/fullsourcejoint guard it. Preflight86→87 models/signatures/pin match;87→88 fullCore source/typedhost evidence, not historical133. Peer212/208/Create/App reserved; allRootUIpaused/current56released. +135. Ledger481: Ruling: clarify134/211 dictionary-order contract as source dictionary enumeration order, not historical insertion order — reviewerMinor correctly notes removed slots can be reused; original/extracted foreach preserve whatever order the dictionary supplies. Correct spec/plan/issue wording with an additive explanation, no C# or test change needed. Cost if wrong an overstated API promise; live unsorted dictionary projection is covered and literal loops compared independently. Do not redesign dictionary state or rerun passing binaries for wording-only changes. +136. Ledger486: Ruling: continue89–91 under215 with small System-only genericDiagnosticHighlightingUpdater state owner (one currentconsumer/sevenports), keepWinUIbackground-light expression and literalUIsetter callback inControl.Editor; source828sum/Editor157. Actual69Projectfields+211Done prerequisite verified. Preserve2currentdiagnosticreads/fullerrorbeforewarning/Sourcepredicate-tokenrereads/rawsignaturecollisions/Ordinal/currentpostcollectioncache/preapplycommit/stickyfault/reentry/reset/perinstance. Freshreadonlydesignreview0Critical0Importantproduct; nativeisolationImportant requiressettlementbeforebuild. Costdelegates+helperstate, no publicAPI/framework/disposal/VMchanges. Preflight89→90 actualprivateApplyTheme/Background signatures+generichelperports match;90→91 bounded137/menu133prefix/21cuts/pins/IOlimits, notpeer137norcombinedvisual. +137. Ledger487: Ruling: resolve215nativeImportant with TWO explicit new fixture-only prefsboundaryfiles,21cuts total — currentSearch ctor readsSEARCHmatchCase/wholeWord andConsoleFontHelper staticinit/ctor/settersread-writePSEUDOCONSOLEevenwithoutLoaded; acceptedmenu133manifesthasneithercut. Addtypedfixed/inmemoryGetSetcallbacks onlyinSearchUserControl.xaml.cs andConsoleFontHelper.cs beforeanyactualCtor; keepUIlogic/changedEditor/helperreal; rejectremainingSettingsManagercalls/unknownkeys/types, no newIO/productsettingschanges. Needindependentexactprelaunchproofbeforebuild/launch; boundedold19cuts preserved,26oldcases/28bootstraps/4groups=137. No blindassumptionunloadedmeansnoprefs. Cost2narrowcutsandlimitedfont/searchpreferencecoverage, noactualpreferenceIOproof. +138. Ledger490: Ruling: document215fixture lifetime Minor explicitly rather than changing production lifecycle — independent prebuildreview reconstructed1531Git/21literalcuts/28scratchbootstraps/26rawoldcases and identified existingAnimatedSelectorBar ctor staticEnabledChanged subscription whose unsubscribe needsUnloaded. Fixture intentionallyneverloads/unloads; CancelBackgroundWork proves stoppedownedtimer, not objectGC/completeeventdetachment. Retained eventgraph endswithboundedownprocess exit; no newIO or globalhandlermutation, no product/XAMLedit. Cost memory retained until the one short host exits; no claimfullteardown/visual lifecycle coverage. Prebuildfinalverdictpending. +139. Ledger491: Ruling: correct215native prebuildImportant array assertions before compiling — reviewer read actualTextControlBox1.3.0 PE/XML metadata and found SyntaxHighlightLanguage.Highlights is SyntaxHighlights[], so three Countcomparisons are invalid. Preserve originalcase/manifest/diff in highlighting-prebuild-count-review-original; replace only3Count→Length in scratch+ownedUNBUILTfixture, recheckall1531/21cuts/28bootstrap/26oldbytesPASS. No product/test source or previously executed artifact changed; no nativebuild/launchattempt yet. Cost testfixturecorrection only; independent reread beforebuild required, no misleading failedbuild attribution. +140. Ledger495: Ruling: resolve215native attributionImportant with NEW r2 archive, preserving entire compiled/unlaunchedV1 — freshwholecontinuationreview confirmedproduct+joints0C/I/M but generatedxBind hooksLoading, so cumulative5reads2writes cannotproveFontinitbyunloadedControl and mightfalsefail. Newcase incrementalper-keySearchreadsaroundactualctor; explicitseparateConsoleFontHelper.Instance checks3fixedtypedvalues/readkeys and2boundedFontSizewrites, noLoading/noIO, keep21cuts. OriginalcaseAttributionV1+allcompiledfixture/scripts/pins preserved. Cost explicitfontboundary coverage separatefromcontrolbinding, noimplicitfontLoadingclaim. FirstR2archivecommandguardstoppedbeforecreationbecauseuntrackednewreport; committruthfulWIPdocscheckpointthenretryguardwithoutweakeningit, productliteraled390unchanged. +141. Ledger501: Final: Ruling: reviewerDeclinedtojudge installedproduct/fullvisual/combinedpeernative are outside215localcontract underopen14/15, acceptboundaryandkeepthoseissuesopen; final215runtime/docs are requiredandnotskipped, actual137nowcompletecurrentdocsawaitsamefreshreview. Cost boundedcompositiondoesnotproveinstalled/fullstartup/combined149runtime; no claimotherwise. + +## Deferred Minor + +1. Ledger150: Final: minor (deferred): ConfigMakerPresetResources.ReplaceFileInText and ConfigMakerPresetReferenceEditor.ReplaceFileInText duplicate file-kind mapping; reviewer confirmed runtime calls use editor. Preserve compatibility facade now; future shared delegation can prevent drift when kinds grow. No user-facing defect observed in current mapping. +2. Ledger187: Final: minor (deferred): managedunit test add-hook does not assert running alreadytrue inside firstremove/add, and Stopfireforgetunit usesCompletedTask so cannotcatchfuture synchronousjoin; codeiscurrentlycorrect. Task40plannedactualhostcomposition must assert realadapterprelude flag and Stopreturn withfaulted managedtask observedoutside, without reopening productreview or expanding unit39 polish. +3. Ledger198: Final: minor (deferred): Task40 observer attachesafterctor, eventcount0 notstandaloneproofnoctornotifications; source+ownerunit coversinitnoevent. Actualruntimeassertion scopedtozeroendpoint/viewactions, realinitialvalues/owner/adapter, no inflatedconstructor-notificationclaim. +4. Ledger199: Final: minor (deferred): actualhost staleA emittedafterBselection, not queuedAbeforeidchange; managedowner testcoverscross-changequeue. Reportactualaslateold-idignored andbackgroundqueue/hostsender/thread/order only. +5. Ledger200: Final: minor (deferred): unexpectedtrackedfault may shortcircuitCleanupAsync afterallgatesreleased butbeforeunsubscribe/staticclear; runnerfails/ownAppexits/no nextgroup/no realendpoint path. No safetyblockforoneownedlaunch, not reusable generalcleanupguarantee. +6. Ledger211: Final: minor (deferred): KnownLoad theory dictionaryequalsInlineData andcallbackcount isweakselfvalidating dispatchassert; expectedgood/spoof/no:no alreadycoveredneighboringtests. Keepnewunitpolishdeferred, no codebug/fixpass. +7. Ledger221: Final: minor (deferred): Spoof group onlyassertsnonempty modelpopulation, lacksunique-debugflag negativecontrol forwrongfactory; actualbackend directSpooffactory sourceverified, othermanagedtestscoverdispatch. RuntimeclaimlimitedtocurrentSpoofselection+population/currentEditor/unsupportedguard, notindependentfactoryidentityassertion. +8. Ledger231: Final: minor (deferred): Task43 editor-value theory uses fresh fixture per value, so alone would not detect caching after first eligible query; managed polish deferred, Task44 must query changing editor twice on same actual host. +9. Ledger243: Final: minor (deferred): Task45 known-variable unit test uses KNOWN and environment fallback couldmask empty snapshot on a runner with KNOWN set; sourceactualsamecollection verified, actual-host46 unique marker+presenceguard/mutateafterconstruction willcover integration. Managedpolishdeferred. +10. Ledger259: Final: minor (deferred): Task47 scalartests allsplitters12 and exacttrace onlyfileshidden, so literal12 replacingFilesSizerWidth couldpass; correctsourceverified, Task48 distinct11/17/23 plusvisiblefiles/max/cap calculations tocover actualadapterrisk. Managedpolishdeferred. +11. Ledger272: Final: minor (deferred): Task49 reentryfakeport discardswindowparams and countsoperations, so swappingouter/nestedreceiver couldescape; productionlocalwindowcorrectsourceverified, Task50twoactualWindowidentities in save/detach/release/forget traces willcoverintegration. Unitpolishdeferred. +12. Ledger290: Final: minor (deferred): unitcustomupdate assertsnormalizedrowandtokenbutnotrecordedWrite.Content; sourcepassesnormalizedcorrectly, Task52realNormalize->inertWriteassert exactdifferentcontent — unitpolishdeferred. +13. Ledger291: Final: minor (deferred): unitoverlap/loadguard waits have no deadline/finally release underhypotheticalserializedregression; currentcode passes/nonserialsourceverified, Task52 boundedWaitAsync3s+finallyreleasesallgates — cost futureunitregressioncouldhanguntiloutertimeout, optionaltesthardeningdeferred. +14. Ledger321: Final: minor (deferred): finalwholebranchreview1d76cbd: ConfigMaker IsHelpLoading/HasCommandModules/UsageText/CommandArgumentPlaceholder/CommandArgumentLabel/AdditionalDesignerArguments lost private setters, PropertyInfo.CanWrite true->false; public C# setters existedneitherbefore norafter, no dependentbinding/reflectionconsumerfound. Documentexplicitreflectionlimit; restoreonlyifactualconsumeridentified. +15. Ledger322: Final: minor (deferred): finalwholebranchreview1d76cbd: PreferRequestedActions(null!) nowadapterNone/fallbackwithoutprevious Cannot process redirected activation warning; normalWinRTnonnullflowunchanged, initialnullallowed. Preservecurrentcode; optionalfuturediagnosticguardmustbeinside redirectedtry only. +16. Ledger323: Final: minor (deferred): finalwholebranchreview1d76cbd: Tests README/md/ru Presentation tables listfirstgroupsonly and GUI-not-covered sentenceambiguous; xUnit source-link96GUIproductionfiles/30changedpresentationtestfiles current, WinUIappnotloadedbyunit. Currentmapclarifies; READMEtable/navigationpolishdeferred. +17. Ledger364: Final: minor (deferred): Task58 actual-host reentry toggles command and explicit groups, component is set Zapret2 before publication; mid-publication component flip proved managed+live production closure source only. Documentation qualified, no product defect. Additional actualhost component-switch case deferred; cost future accidental host component caching might escape current runtime group. +18. Ledger500: Final: minor (deferred): bounded215nativefixture intentionally never raisesLoaded/Unloaded; existingAnimatedSelectorBar staticEnabledChanged subscription retains graph until ownedprocess exit. Productunchanged; onlyownedtimerstop/unattachedstatecovered, noGC/eventdetachmentclaim. Documentedexplicitly, no lifecycle redesign in local highlighting scope. diff --git a/docs/DECOMPOSITION-REVIEW-MAP.ru.md b/docs/DECOMPOSITION-REVIEW-MAP.ru.md new file mode 100644 index 00000000..0a28259c --- /dev/null +++ b/docs/DECOMPOSITION-REVIEW-MAP.ru.md @@ -0,0 +1,434 @@ +> Historical local-stage record for frozen dev/audit-class-decomposition at eebc7e8. +> Current integration work is tracked in [the integration plan](superpowers/plans/2026-11-11-class-integration.md). + +# Карта приёмки декомпозиции + +Актуальная проверка: 11 ноября 2026 года. Текущийкодed390cd/issue215/продолжение89–91: +32focused/2108full/GUI0-0/source451(606)/compiled4520loss+7old; helper29/Editor149/control820. +ExactEEjoint2320/GUI0-0, correctedpeerf706+Root+EE2398/GUI0-0; source/XMLpostchecksPASS. +Native137/21cuts собран0-0/48.44s после3Count→Length+одногоusing исправлений в новом casefile; +первый failedbuild сохранён,23pins первой собранной копии проверены, но запуск запрещён из-за +ошибки атрибуции общих preference counters. Отдельная r2 собрана0-0/69.10s, independentREADY0C/I, +actual137PASS(first133)/COMPLETE/exit0/allpostchecks23pins/PID79052gone/explicit83→release84. +Final91ACCEPT0unresolvedCritical/Important/Minor наproducted390/docscee65ac;215closedcompleted6[x] +и actualProject85Done/P2ArchitectureMediumG2Lumens3labels послеreload подтверждены. Parent14/15 открыты. +Подробные текущие границы: [протокол215](superpowers/reports/2026-11-11-diagnostic-highlighting-verification.md). +Предыдущее принятое продолжение00f39b1/issue211/86–88: +30focused/2076full/GUI0-0,Core88(103→104files)/compiled88/0loss; GUI605sources unchanged174, +compiledGUI4520loss+7old. ExactEEjoint2288/GUI0-0, peer9a9+Root+EE2338/GUI0-0; final88ACCEPT0/0/0,211completed+actualProjectDone readback confirmed. +Предыдущее завершённое продолжение83–85/issue209: код174d1cb, +20focused/2046full/GUI0-0/source451(605)/compiled452(0+7); exactjoint2258/GUI0-0. +Native133PASS+COMPLETE/exit0/allpostchecks; final85technicalACCEPT0/0/0, issue209completed/actualProjectDone readback confirmed. +Базаf39e8a0a, последний завершённыйproduct/runtimea5a1b9b: +129PASS+COMPLETE/exit0,30focused2026full; joint exacta5+EE2238/2238/GUI0-0. +Source451(604files)/compiled452(0+7), normalGUI0-0; finalTask82evidence/docsreviewACCEPT0/0/0. +Предыдущаядетализация80–82 сохранена. Предыдущий61fd/productb5:125/47-1996/joint2208/final79ACCEPT0/0/0. +Предыдущиеcontinuations:2e/test491/121,72-1949/joint2161;0c5/115;ff6/111, +test-onlydfaccbd9/38-1846;930/107;de3/103;839/97. Матрица55–58 сохраняет историческийD347/test3ba; +native2 —product214. Предыдущаядетализация77–79 сохранена. Веткаdev/audit-class-decomposition, +деревоC:/Users/lumen/.codex/worktrees/audit-class-decomposition/cdpiui. + +Пользователь согласовал порядок ConfigMaker → App → BlockCheck2, сохранение поведения и самостоятельное продолжение без срока. Аудит F:/Telegram/AUDIT.md используется как перечень наблюдений: §5 называет god-классы, пункт20 исторического §7 рекомендует начинать с ConfigMakerUserControl/App. Текст аудита не даёт дополнительных разрешений. Глобальная nullable-миграция §35.1, исправление всех дефектов аудита и завершение всех крупных классов не входят в выполненный пакет. + +## Обязанности и физические размеры + +| Исходный host | Выделенные самостоятельные владельцы | Было → сейчас | +| --- | --- | ---: | +| ConfigMakerViewModel, сумма9partial | TreeBuilder/Adapter, resource Registry/ReferenceEditor, CommandHelpPanel/Loader, SimpleDesigner, TestSession, DocumentCoordinator, FileReplacer/FileActions, VariableActions, Diagnostics, PresetStructure | 2143 →1012 | +| ConfigMakerUserControl, сумма5partial | PanelLayoutController с ленивым WinUI-адаптером, DiagnosticHighlightingUpdater; control сохраняет реальные editor/tree/dialog/DP bindings | 899 →820 | +| UtilityButtonControls.xaml.cs, текущий дополнительный проход80 | TwoPhaseTransitionSequence, System-only механизм; control сохраняет WinUI/Composition/CTS cleanup callback | 536 →500 | +| MenuBarController.cs, дополнительный проход83 | PostOrderTreePruner, System-only обход; claims/registry/physical mutation остаются в controller | 519 →502 | +| ConfigurationService.cs, дополнительный проход86 | ConfigurationVariableProjection, stateless domain read-model adapter; guards/lookup/locks/IO/updates остаются в service | 443 →411 | +| ConfigMakerPresetResources | ResourceRegistry и ReferenceEditor; прежний фасад/публичные entrypoints сохранены | 507 →232 | +| App, сумма6partial | ActivationDispatcher/RequestAdapter, FileActivationHandler/Operations, WindowCoordinator/Operations, WindowCloseCoordinator/Operations, IdleExitController | 955 →677 | +| BlockCheck2ViewModel, сумма3partial | Options, Progress, RunResult, RunController, SiteListController/backend | 999 →426 | +| BlockCheck2ResultViewModel | ManualAssignmentEditor/IssueItem, ManualPresetState/Operations, ManualStrategyTestController/Operations | 565 →268 | +| CreateNewConfigViewModel, сумма6partial | ConditionDraft, TestSession, GraphicDesigner, ComponentSelection | 1037 →818 | +| BlockCheck2ResultPageViewModel, сумма4partial, срез855dbd3 | ResultSelection, ReportSummaryPresenter, SelectedStrategyTest, ReportExport, ManualTestSession, AssignmentActions с нейтральным SelectedItemChoiceAction | 874 →513 | + +Считаются физические строки вместе с using/комментариями. Уменьшение host не равно снижению общего количества строк. Новые объекты содержат перенесённые обязанности и явные зависимости; новых partial-частей для сокрытия объёма крупных классов не добавлено. В host остаются UI-адаптация и ранее согласованные соседние обязанности. Декомпозиция всех оставшихся крупных объектов не заявляется. + +## Историческая матрица55–58: требование → свидетельство → предел + +| Требование | Проверено | Предел | +| --- | --- | --- | +| Сохранить поведение при переносе | Целевые absent-owner RED→GREEN, characterization уведомлений/исключений/reentry/await/current-state, полный suite на текущем product1719/1719,0failed/skipped; повтор после test-only уточнения 11s | Тесты не доказывают отсутствие всех возможных регрессий | +| GUI продолжает собираться | Текущий normalGUI x64 Release, SDK8.0.427:0warnings/errors65.78s | x86/ARM/полный production startup не проверены | +| Исходный внешний контракт | Source:451исходный exported type/0потерь сравниваемых сигнатур,517→592GUI C#files | Синтаксическое сравнение, не полная semantic/attribute/API гарантия | +| Скомпилированный контракт |452исходных exported types/0потерь/изменений записанных shapes,7ранее добавленных internal interfaces; positive/negative controls анализатора | Нет полной гарантии NRT/всех attributes/inherited dependencies/interop/ABI/произвольной reflection; диагностические async stack/атрибуты могли переместиться | +| Проверить настоящее сочетание host/owner/adapter/model | Actual runtime наd347c617:91PASS+COMPLETE/exit0/postchecks | BackendIO и часть UI-targets заменены явно; отдельные дополнительные группы имеют свои pins | +| Проверить native manual editor Task15 | Native4 наd347:empty →Add split →Add disorder →Move split down, реальные кнопки/коллекции/identities/1-based order/flags/draft/action tokens/12events | Нет живого CURL/component test, Add for list, remove/clear UI, repair/report export | +| Проверить native document workflow Task16 | Native4 наd347:реальные editor/DP/model/document,readonly,Save cancel/success с вводом имени,Export coordination,New cancel/continue | Private storageCore/export/pickers/settings/task endpoints инертны; фактические файлы пресета/архив экспорта не записывались | +| Не принять частичный успех за завершение | Первыйnative PID52048:11UI PASS/COMPLETE/exit0,но общий FAIL из-за Settings.xml/bak. NEWnative2 PID36508:все11+postchecks PASS | Первый результат остаётся FAIL, даже после успешной новой копии | +| Не мешать security-сессии | Read-only committed `ee4771675956fe213634675f37579362efb7e0eb`; новый jointd347+EE:1931/1931,GUI0/0 | Её рабочее дерево/WIP не включались, последующие её изменения не проверялись | +| Сохранить проект и свидетельства | Локальные scoped commits, старые копии/входы/логи/архивы сохранены, нет reset/force-push/merge/publish/удаления исходников/веток | Ничего не отправлено на GitHub и не интегрировано в общую ветку | + +## Точные исторические артефакты55–58 + +Normal DLL исторического productd347 SHA256 `07899304940A75B7749A052271874CE3D1A3E141919856D4663EA805F0A5B423`. Это обычный бинарник того этапа, не DLL с заглушками стенда. До закрытия58 после d347 менялись только тест и документация; последующие product/runtime pins приведены в продолжениях ниже. + +Actual-host стенд: `F:/cdpiui-verify/cdpiui-struct2-d347c61-20261109`, GUI DLL `280A28248ECBA6CE51A545A7B3F92C12443FF4213F9E1FECCFE292A019B06EB6`, PID35892,91PASS/COMPLETE/exit0. Последний совместный срез: `F:/cdpiui-verify/cdpiui-joint-structure-ee47716-20261109`,1931/1931 иGUI0/0. + +Native2: `F:/cdpiui-verify/cdpiui-native2-214b4b3-20261109`, GUI DLL `86EC3A2759FFF4A83A578F621DFC540B7D6A05A10BB248976BCE5CE6CF510ED3`,19явных cuts/1482repo inputs/1230project inputs, XAMLсовпадает с product. Реальный public storage Clone+Task.Run сохраняется; private core возвращает контролируемый результат. ConsoleFont/Search preferences в памяти, SettingsManager guard срабатывает до XML base и проверяется также после Application.Start. Стенд не является полной OS/filesystem sandbox. + +PID36508:15:44:45.2758468Z→15:47:31.5834895Z;11PASS/COMPLETE/exit0,0FAIL/пустые stdout/stderr, sourcepostcheckPASS,процесс завершён. `Settings`, export иcustom output отсутствуют; только input+result log появились в bin, прежние имена сохранились. Input23bytes `native.example.invalid\n`, SHA256 `70CE5088BE2697D3D75728DEDE2F0DA5DF9FF27BCF9B8525650AC3C141E105F7`. Проверка имён не доказывает отсутствие transient IO/перезаписи старых bytes во всех местах системы. + +Локальные проверочные scripts/logs/AX/manifest/retainedJSON находятся в `.superpowers/sdd/2026-11-08-class-decomposition/`, исходные архивы новых копий — в `F:/cdpiui-verify/archives`. По новому запросу пользователя37 завершённых C:копий перенесены на D с SHA256 и junction; старые пути и содержимое сохранены. Git worktrees не переносились. Для этих копий запрещён слепой повторный запуск builder/runner: предусмотрены freshness guards. [Текущая подробная история](DECOMPOSITION-STATUS.ru.md), [план](superpowers/plans/2026-11-08-class-decomposition.md), [спецификация](superpowers/specs/2026-11-08-class-decomposition-design.md). + +## Оставшиеся границы + +Не выполнена глобальная переработка App migration/Win32/tray, всей ConfigMaker/CreateNewConfig UI-оболочки и всех storage/import/export/settings сервисов. Реальные backend операции и полный production startup/window close policy/drag resize потребуют отдельных проверок. Security/staging/Update/ZIP/settings persistence остаются за параллельной сессией. Ни «весь аудит закрыт», ни абсолютное «регрессий нет» не утверждается; выполненные проверки не обнаружили product-регрессий в своей области. + +Финальное независимое ревью всей ветки завершено после native Task53; его результат и отложенные замечания записаны ниже. Полный журнал принятых решений и отложенных Minor сохранён в [приложении](DECOMPOSITION-DECISIONS.ru.md). + +## Историческое итоговое ревью Task54 + +Свежий reviewer без контекста переписки принял весь диапазон f39e8a0a→1d76cbdb: **0Critical,0Important,3Minor**. Просмотрены153пути/68коммитов за несколько проходов, четыре кластера и все пять Review Focus;96Presentation source links наGUI существуют/без дубликатов Link,30файлов presentation tests изменены. Ревью сверяло исходники и сохранённые результаты; оно не запускало повторно сборки/тесты/приложение/manifest writers. На завершении Task54 обязательных product-исправлений не было; тот review относится к214b4b3. + +Три Minor после собственной сверки с baseline отложены: + +- Несколько ConfigMaker properties потеряли **private** setters: PropertyInfo.CanWrite изменился true→false для IsHelpLoading,HasCommandModules,UsageText,CommandArgumentPlaceholder,CommandArgumentLabel,AdditionalDesignerArguments. Публичных C# setters раньше не было; зависимого потребителя/привязки в репозитории не найдено. Произвольная reflection-совместимость не гарантируется этими API inventories. +- PreferRequestedActions(null!) теперь получает None от адаптера и делает fallback без прежнего warning. Для штатного непустого WinRT event расхождения не найдено. Если диагностику неверного вызова восстанавливать позже, guard нужен внутри redirected try; initial null допускается. +- CDPIUI.Tests README.md/README.ru.md описывают первые Presentation группы и двусмысленно исключают GUI. Сейчас unit tests компилируют выбранные productionGUI sources, WinUI application вxUnit не запускается. Обзор README и ссылка на эту карту остаются polish-задачей. + +Все13 сознательно исключённых reviewer областей получили отдельное решение с ценой ошибки в [полном приложении](DECOMPOSITION-DECISIONS.ru.md). Прежние13Minor также сохранены; некоторые их риски дополнительно проверены поздними actual-host группами, managed polish не выдаётся за исправленный. Нового source-кода после successful product проверок не было; для финальных текстовых изменений suite/GUI повторно не запускались. Локальная ветка и все материалы сохраняются, публикации/слияния/удаления не выполняются. + + +## Продолжение 55–58 + +Владелец состояния PresetStructure выделен наd347c617, 36 новых managed cases. Preliminary review всего +продолжения28ceef44→d347c617 принял product без Critical/Important. Единственный Minor усилен тестом +3ba7d388 и подтверждён повтором36/1719. Реальный host/owner/WinUI adapter прошёл91группу; точные три +входных файла проверены отдельно побайтовым сравнением. Нативный повтор11наблюдений наd347/native4 принят со всеми postchecks; Task57 закрыт. +Task58 принят итоговым независимым ревью с уточнением границы actual-host проверки. Предыдущие результаты сохраняют собственные pins. + + +Текущий native4: F:/cdpiui-verify/cdpiui-native4-d347c61-20261109, GUI SHA256 +`E82D1B44B5596044725335F92505249EF5FD33B7D10504BED6B0F50E381104BA`, bootstrap +`7EDB334D3B997083E001E6D5250421E67492F4B42C86A7583D34E231390342CC`, точный source-boundary manifest +`E95C8649CE8CDD4EBE38782E68232629CDE5808D0F20BD498510DD11B6910101`. PID50036,11PASS/COMPLETE/exit0, +0FAIL/пустые streams/1231+1486 post-source/manifest/input23bytes/Settings-export-custom absent/ +only2newbinfiles/processfinished подтверждены. Конструктор SettingsManager блокирует XML до base; +sticky switch проверен Finish и после Application.Start. Пределы native2 по реальным backend/IO/полному +OS наблюдению сохраняются. Native3 PID2228 остаётся FAIL/exit1: незапланированный ввод, причина не доказана. +Для native4 подтверждена исключительная очередь трёх чатов со всеми UI API; после завершения передана peer. + +Итог review28ceef44→3ba7d388+документы:0Critical/0Important/1Minor. Actual-host reentry изменяет команду +и явные группы; компонент задан заранее. Его смена во время публикации остаётся managed+source-only +proof, отдельный actual-host case отложен с ценой возможного пропуска будущего кэша компонента. +Документальное уточнение выполнено, product-исправлений не потребовалось. Все пять Review Focus +проверены,111Ruling и17deferredMinor сохранены в приложении. Продолжение55–58 завершено в указанной области. + +## Продолжение 59–61 + +Product839cc952: AppIdleExitController,39focused/1758full/GUI0warnings-errors52,94s, +source451/517→593/0comparedchanges, compiled452/0recordedchanges/7прежних interface adds. +Normal DLL `0DD76BD2DFC2E6101E2BB09CCB5FC094541EC2F547E821F3B65E5FB157F4BA1D`. +Joint exact839+ee47716:1970/1970 иGUI0/0. Fresh product review2400dee→839cc952:0Critical/Important/Minor, +все пять новых и пять исходных Review Focus, прежние App callers/Store subscription/close callback. + +Actual idle host:97PASS+COMPLETE/exit0, PID61180,05:09:45.0171515Z→05:09:49.2267677Z 10ноября2026UTC, +1232project/1489repo/18boundary files/19bootstraps; сборка0/0 за71,39s и prelaunchREADY0/0/0. +Реальны current list/migration/private host forward/owner/App-bound callback, инертны Store/Good/Create/ +Close/Exit/Warn; без настоящего Storeevent/PrepareWindow/idle-policy nativeExit/fullstartup. +Сам стенд вызывает реальный Application.Exit при завершении. GUI fixture SHA256 +`CD9389B6B9DE9F21807F3A3DCCF2AC4FE55A037BE4B7056A1B5D0DF1A33206E4`. +Postchecks PASS: пустые streams/noFAIL/source+approved hashes/три точных входа/Settings-export-markers +absent/4новых binnames/прежние имена сохранены/processfinished. Общая OS isolation не доказана. + +Явный handoffV4Root после peer process/windowfinished и lessonswithdrawn; Root noUIAPI, после97 +передалV5peer/native-governance и allUIpaused. Runtimegate60 иreview61 закрыты:0Critical/Important, +1Minor о формулировке входных файлов исправлен (16/16/15байт). Native4/d347:11интерактивных наблюдений остаются на прежнем product. Старый pendingcheckpoint +b848620 и неуспешные native-прогоны сохранены. Новых продуктовых исправлений после839 нет. + + +## Продолжение62–64 + +Page main432→380/sum874→822, owner179lines/15properties/7lazyports. Productde3d3821: +28focused/1786full/GUI0-0/source451(594files)/compiled4520+7; joint exactde3+EE1998/GUI0-0. +NormalSHA9EBC1DD5C23DBA121C27584CAC999197A104BC67DC9932D9E9FCFAF0E6990E16. +Productreview0Critical/Important/1Minortestcoverage закрытtest-onlyffa65fc9: nullablelabelobserver, +controlled-cachemutantRED→originalsource29focused/1787fullGREEN. Product/normalGUI unchanged. + +Actualselection2host103PASS+COMPLETE/exit0, PID45692,2026-11-10T05:39:53.4500889Z→05:39:57.3058215Z, +0FAIL/emptystreams/source1233project1492repo/exact18cuts20bootstraps/pins/3inputfiles16-16-15bytes/ +Settings-export-markersabsent/4newbinnames/priornames/processfinished/5actualbinarySHAprelaunch+postexit. +Build0-0/55,58s/prelaunchREADY0/0/0. Firstselectioncopyunlaunchedpreserved afterfalse-positivecase review; +selection2distinguisheschangedResult/listpredicateandmenuactionsorder. ActualrealPage/owner/currentResult/ +HasSession/localizer/evidence/listpredicate/hostsender+private-set, fakeviewSelected/Menuonly, no lifecycle/ +component/backend/native calls; managedlocalizer/format/culturefaults remainownscope. Old97unchanged; +nativevisual/startup/wholeOS/ABI notproved. XAMLunchanged. GUI fixtureACC8ECD1…/source-boundary host-fixture-manifest.txt36A52817…/ +runner798B3F99… exactfullhashesinSTATUS. V6Root→V7released afterpostchecks/allUIpaused. +Finalreview64ACCEPT0Critical/Important/Minor, test/doc уточнения закрыты. Все103unique/first97sameordertext, +оба журнала побайтно совпали,522→526bin files/currentdiskhashes matched,118Ruling17Minor exactledger. + + +## Продолжение65–67 + +Product93091a13 ReportSummaryPresenter,Page353/sum795.20focused/1807full/GUI0-0/API451(595)/452(0+7), +joint exact930+EE2019/2019/GUI0-0. NormalC4DCFA8E0BD20B07435276DB3912C0D82ABA8F11A89E2103E8DC643F717665F1. +Productreview0Critical/Important/1Minortestcoverageclosedby4d19d461: BestEffort-onlytitlecallback/repeatedread, +controlledcachedBestmutantRED→restoredsource21focused/1808fullGREEN; no product/GUIbinary change. + +Summaryfixture107PASS+COMPLETE/exit0,PID45484,2026-11-10T06:00:48.7342523Z→06:00:52.8956430Z, +build0-0/68,59s,prelaunchREADY,source1234project1495repo18cuts21bootstraps. AllpostchecksPASS: +noFAIL/emptystreams/source+5sourcepins/3inputfiles16-16-15bytes/forbiddenoutputsabsence/4newbinfiles/ +priornames/PIDgone/5actualbinarySHAprelaunch+postexit. Exacthashes/pathsSTATUS; source-boundarymanifest1A0C… +is distinct fromruntime-run-manifest. New4groupsrealPage/Result/report/Localizer/privateforward/hostdelegates, +inertShowStatusonly; otherviewcallsThrow, noUpdateView/lifecycle/component/native. Old103same scope, +managedTextreentry/localizerfaults notclaimedasnativeLocalizerinjection. No visual/startup/wholeOS/ABI proof. +V7released→explicitV8Rootafterallpaused+readyfalse/prelaunchREADY→V9released afterpostchecks/allUIpaused. +Finalruntime/docsreview67ACCEPT0Critical/Important/Minor;107unique/first103sameordertext/logsbyteequal, +5binary/5sourceSHA independentlychecked. No newproductsourceafter930; joint2019/native107retain930, +21/1808belongs4d19test-only. 120Ruling17Minor mirrorsretained; continuation65–67closed. + +## Продолжение68–70 + +Product ff6bc636: SelectedStrategyTest, одиннадцать ленивых портов; host сохраняет публичный Task, +private result forward, поле running/private progress setter и sender. Main353→300/sum795→742. +36focused/1844full/GUI0-0/54,40с; source451(596files)/compiled452(0+7), immutable ff6 и working/current +GUI inputs совпадают. Обычная DLL965649633BC6B14C034ECEF43E4FD908C2A7F5FF03855418D14280E9342B42E1. + +Product review: 0Critical/Important, два coverage Minor закрыты test-onlydfaccbd9: +реальный Canceled Task и замена Error issue при локализации формата. Cache-firstError mutant RED, +original source bytes/SHA restored;38focused/1846full GREEN, повторное review0/0/0. Runtime111 pinff6 +содержит первоначальные36/1844; joint exactdfaccbd9+EE2058/2058/GUI0-0 включает оба новых теста. + +Actual111: PID9112, UTC15:06:27.9269258→15:06:37.3261527 10ноября2026, build0-0/78,84с, +independent prelaunchREADY,1235project/1498repo/exact18cuts/22bootstraps. Реальные Page/Result/helper/ +Localizer/private forward/host flags/sender/finally, отрицательный current Result через замену session +на sessionless в progress observer и backend trap0calls. Status/menu/command view контролируются, +реальные backend/component lifecycle не вызываются; pending/cancel/callback mutation — managed scope. +111unique/first107sameordertext/COMPLETE/exit0/noFAIL/empty streams/logsbyteequal/5actualbinarySHA +доlaunch-послеexit/6sourcepins/3inputfiles16-16-15bytes/forbiddenoutputsabsent/522→526binfiles4newnames/ +allpriornames/PIDgone. Полные pins/paths в STATUS; source-boundarymanifest3BBDC5DF… не равен runtime manifest. +ЯвныйpipelineV15handoff→V16Root→V17released послеpostchecks/ALLRootUIpaused, pipeline уведомлён. +Старые107two-nonactivatedWindows/realExit teardown и прежние native pins сохраняют свой scope. +Full startup/interactive visual/native/whole OS/ABI proof не заявляется. Task70 закрыт final review0/0/0, +два тестовых Minor и историческая joint-фраза исправлены;122Ruling/17deferredMinor сохранены. + +## Продолжение71–73 + +ReportExport: семь ленивых портов, публичные JSON/text Task и private SaveAsync forwards сохранены, +current report читается после picker внутри catch; no-report/cancel/setup faults/pending/concurrent/ +reentry/realCanceledTask/success status fault/error identity покрыты31managedcases. Serializer/clipboard +не менялись. Page sum742→705/main300→305, export85→43. Product0c5ea124:31focused/1877full/GUI0-0 +18,46с/source451(597)/compiled452(0+7). Normal0A96C87463214289EA0B9FE6B04D1328C312ABA9F7AE45D417E7A8903946B3EF. +Joint exact0c5+EE2089/2089/0failed-skipped47с/GUI0-0/69,41с. + +Оба product review Minor закрыты: actualRED2111PASS+namedconstructorFAIL/innerNRE:55/exit1 наbd91343 +подтвердил eager `_view.PickSaveFile`; lazy lambda fix0c5 сохраняет null-view/no-report поведение. +Test-only62e усилил returnedTask fault timing; контролируемое удалениеasync дало4JSONFAIL/4textPASS, +sourcebytes/SHA restored;31/1877GREEN. Первоначальный115bd и compile-failed red1 сохраненыUNLAUNCHED; +RED2 —ожидаемоеFAILсвидетельство, его4newfiles/3reportpathsabsent/postchecks прошли, это не GREEN115. + +Исправленныйactual115 использует тот же B7AEBF2B casefile,23bootstraps/18cuts/1236project1501repo, +build0-0/69,96с/prelaunchREADY. PID71744 UTC15:52:46.0727531→15:52:50.1694270 10ноября2026, +115unique/first111sameordertext/oneCOMPLETE/exit0/noFAIL/empty streams/logsbyteequal/5actualbinarySHA +доlaunch-послеexit/7sourcepins/3inputs16-16-15/2realretainedownreportoutputs354-260bytes/6newnames/ +522→528/priornames/negativepathSettingsmarkersabsent/PIDgone. JSON/text прочитаны обратно и внешне +проверены literalcurrentmodelfields+SHA; только2freshdirectchildпути вownFbinaryroot, inertpicker/status. +Core Page/Result/Report/Localizer/serializer/privatehelper реальны, null-view ctor теперьPASS. +Backend/componentlifecycle/desktopdialogs/fullstartup/interactivevisual/wholeOS/ABIнепроверялись. +Exactpaths/полныеpinsSTATUS; sourceboundarymanifest9AEC93BC… distinct отruntime manifest, +runnerAB85F091… . Same18cuts и21oldcasepartials неизменны относительно111 (толькоownExePathвcut). +ЯвныеhandoffsV19→20→21RED иV23→24→25GREEN,RootALLUIpausedпослеpostchecks/ack/requestfalse, +pipelineуведомлён; noRootdesktopUI/nootherprocess/worktreeedits. Productreview0/0/0, +finalTask73evidence/docsreviewACCEPT0/0/0;124Ruling/17deferredMinor сохранены. Проверки закрыты на0c5. +Отдельная история main d72ad478→7ead95f7 имеет одинаковыйtree33323ba5 и нулевойdiff; ancestry сменился. +Root не интегрировал новую историю; точные localsource/runtime/joint pins не смешиваются сlivePRdiff. + +## Продолжение74–76 + +ManualTestSession product2e70779 владеет тремя прежними flags и всем lifecycle ручного теста. +Page сохраняет публичные Task/getter, private leave/event-handler forwards и исходный handler TargetPage. +Узкий internal host11members/private nested adapter передаёт эффекты; FuncTasks разрешает связанный +ComponentTasksManager receiver до каждого ID аргумента. GuardID читается отдельно, leave захватывает +одинID доtry. Существующие ConfigMaker adapter/consumers не меняются. Новых guards/locks/dedup нет. +Page705→572/main305→308/manual186→50; все четыре partial прежние, нового public interface нет. +Private поля перенесены: произвольная private reflection не обещается, единственный известный +selection fixture получил проверяемую замену только одной строки доступа к полю owner. + +Absent-ownerCS0246 и receiver-portCS1503 RED сохранены; unconditional-restore mutant дал2FAIL. +На фактическом продукте прошли1947full/GUI0-0 за39,26с. +После этих полных проверок ID-before-receiver mutant дал1FAIL; original bytes/SHA восстановлены, +Затем70focused прошли на восстановленном исходнике, после них source451(600)/compiled452(0+7). +Product review0Critical/Important/2Minor к тестам закрыты +test-only491692bc: отдельные gates одновременных запусков и false/null button running→одинStopped. +DroppedStop(true) mutant дал2FAIL, sourcebytes/SHA restored, GUI diff2e пуст;72focused60ms/1949full10с +безfailed/skipped. Повторное product reviewACCEPT0/0/0. Normal GUI SHA256 +`670A98479785F6083D76656EAA77EC2CE74243BE9D6A65C785319948D6C6953A`. +Joint exact491+securityee47716 —2161/2161/42с/GUI0-0/61,24с, security worktree read-only cleanEE. + +Actual121: `F:/cdpiui-verify/cdpiui-manualsession-491692b-20261110`, build0-0/79,64с, +1506repo/1239project/exact19cuts/24bootstraps+verifiedemptySecretstub, prelaunchREADY. +Новый cut только в ManualTesting helpers: receiver/currentID/logger; mainPage/owner/bound adapter +совпадают с product. Единственная разрешённая правка старого selection helper — private-state bridge, +все остальные assertions и21oldcasepartial прежние. Новые6групп проверяют реальную Page/Result/ +session/purewriter/Localizer/privatehost/originalhandler/dispatcher; tasks/confirm/status/menu/logger +инертны. Проверены captured row/current Result, pending confirm/run/stop, restore, один leave ID, +startup guard, две queued exits после stop, exception identity и setup/catch границы. +Boundmanageradapter проверен source/GUI compile, настоящий manager не вызывается. Backend/OSrestore/ +native dialogs/fullstartup/interactivevisual/wholeOS/ABI не проверялись, новых IO в6группах нет. + +PID69044 UTC17:46:43.3819843→17:46:47.3377306 10ноября2026:121unique/first115exactorder/oneCOMPLETE/ +exit0/noFAIL/empty streams/logsbyteequal/5actualbinarySHAprepost+8sourcepins/3exactinputs16-16-15/ +2realretainedreports354-260bytes+goldenSHA/currentliteralfields/6newnames522→528/priornames/ +negativepathSettingsmarkersabsent/PIDgone. Normal670A неизменён. SHA-pinned дополнительный readback +повторил unique/prefix/logs/13pins/reports/names/absence/normalDLL; runner проверил три input-файла. +Выбранные полные SHA/paths в STATUS, полный список13path+SHA в scratch `page-manual-host-approved-pins.json`; +fixtureDLLCBDCCDEB/sourceboundarymanifest0ED94928/runnerC09821A4/ +readback87A835C3; source-boundarymanifest отличается от runtime manifest. + +Явный pipelineV27grant Root после его UIfinished подтверждён координатором. V28 только нормализовала +filenamealias запроса уже действующего Root grant. После postchecks/ownedPIDgone RootALLUIpaused, +idleack/requestcompletedfalse/V29releasedowner:null, обе сессии уведомлены. Root desktop/CUA API не +использовал. Task75/76 закрыты, final evidence/docs reviewACCEPT0Critical/0Important/0Minor. +Хронологический документальный Minor исправлен:full1947+GUI→receiver mutant→restore→70focused→API, +затем49172/1949; полный13-entry locator уточнён. Независимо сверены1506fixtureinputs и1533jointfiles/ +166overlays/точная additive testcsproj;126Ruling/17deferredMinor сохранены. Новых product правок не было. + +## Продолжение77–79 + +Productb5cce888/test61fd0e7: нейтральный SelectedItemChoiceAction39строк/4порта/System-only и маленький +AssignmentActions80строк/13memberinternalhost/privateadapter. Один текущий потребитель, без обещания +существующего reuse; domain notices/команды отделены от capture/snapshot/optionalchoice/apply. +Прежние Page state/private setters/notification sender/preview/model policy сохранены; sum572→513, +Assignments171→110/main308→310. Sync/Task fault timing, captured row/current Result после await, +mutable snapshot identity, single runtime-null vs multiple-null cancellation, independent choices, +move/reentry/duplicate menus/quickfix прошли характеризацию. Global neutralutility criterion закреплён +в плане и STATUS для всех дальнейших проходов, без массового rewrite принятых владельцев. + +Absent-ownerRED, selected-reread-afterawait mutantFAIL1→byte/SHA restore;47focused/1996full/GUI0-0 +41,73с/source451(603)/compiled452(0+7). Product review0/0/1Minor о SingleChoice тесте закрыт +test61fd: пары+Assert.Single после await в single/multiple plain-object cases, duplicate-singleapply +mutantFAIL1→restore→47focused38ms/1996full10сGREEN; re-reviewACCEPT0/0/0. Product GUI неизменён. Нормальная DLL24797CCA…, +полныйSHASTATUS. Координатор отдельно выполнил14case standalone plainobject probe на utilitySHA44872BE0… +и13/14negativecontrol(single-nullguard), Root прочёлJSON; это boundedutilityproof, не productruntime. + +Exactjoint61fd+EE2208/2208/41с/GUI0-0/59,36с. Все603immutableGUIinputsсовпалисcurrentnormalizedLF. +Actual125 F:/cdpiui-verify/cdpiui-assignment-actions-61fd0e7-20261110:build0-0/71,78с, +1512repo1242project/exact19cuts25bootstraps/старые23casepartial прежние, no newIO/cuts. +Четыре realPage/Result/editor/localizer/formatter/privatehost группы описаныSTATUS: noitem/paths/add/ +duplicate/doublemenus/privateforward; pendingcapturedrow/currentResult/snapshot/single/cancel; move/ +reentry/reselect/remove/clear/guards/sender; quickfix/liveissuecollection/syncpartialfault/Tasksetupfault. +Chooser/selection/status/menu инертны, backend/components/native/visual/fullstartup/wholeOS/ABI не проверены. +RunnerB9BE0FBC/readbackBB7DAC29; выбранные полные SHA/пути вSTATUS, все14path+SHA —scratch +`assignment-actions-host-approved-pins.json`. +IndependentprelaunchREADY/0блокирующихзамечаний. Helper owncopy дискриминируется managed tests, +actual groups проверяют end-to-end array isolation (реальный editor сам возвращает новый массив). +Joint1538paths/1537Gitblobs+exactadditivecsproj109items/172overlaypaths независимо сверены. +Actual125 PID68696 UTC18:37:05.7871699→18:37:17.5133853 10ноября2026:125unique/first121exactorder/ +oneCOMPLETE/exit0/noFAIL/empty streams/logsbyteequal/5actualbinaryprepost+9sourcepins/3inputs16-16-15/ +2realreports354-260goldenSHA+literalcurrentfields/6newnames522→528/priornames/forbiddenabsence/PIDgone/ +normal24797unchanged. SHA-pinnedreadback дополнительно повторил unique/prefix/logs/14pins/reports/ +names/absence/normalDLL. После явного retrospectiveV31Rootgrant запуск выполнен один раз; +после postchecks/idleack/rootrequestfalse/RootALLUIpaused atomicV32active возвращён retrospective +ready-заявке, обе сессии уведомлены. NoRootdesktop/CUA API. Tasks78/79 закрыты, +final evidence/docsreviewACCEPT0Critical/0Important/0Minor. Два documentary locator Minor исправлены; +125/prefix/logs/14pins/inputsoutputs/528recursive names/absence/PID/queue/normalDLL и прежние source/ +joint границы независимо сверены. 130Ruling17DeferredMinor сохранены. Product source послеb5 неизменён. + +## Продолжение80–82 + +Producta5a1b9b, doc уточнение24bf329: TwoPhaseTransitionSequence50строк/9входов/двеliveгруппы, +System-only/безWinUI/Composition/доменов. Одинconsumer; UtilityButtonControls536→500, XAML/DP/ +навигация/анимации/создание-отменаCTS и literal cleanup callback прежние. Две Count reads до операций, +captured total только дляпауз, inspect-beforeapply, selector-afterapply, lazyToken даже при0duration, +нетearlycancel/snapshots/Concat. Directprivate3paramTaskforward не добавляетawait; helpercatchanyOCE +тела/finallyonFinally, исключение финализатора снаружи catch. Caller-owned callback refchecks/Dispose, +helper самCTSнеCancel/Dispose. Перемещение private async attributes/stackframes вAPIscopeнеобещается. + +AbsenthelperCS0103RED×2, inspect-afterapplymutantFAIL1→originalbytesSHA66FB2469…restored; +2026full11с/GUI0-0/52,89с/API451(604)0loss/compiled452(0+7)/focused30/51msGREEN. +Productreview82ACCEPT0Critical/Important/Minor; finalruntime/docreview82 такжеACCEPT0/0/0. Normal2F0BD022… полныйSHASTATUS. +Coordinatorstandalone12/12+expected11/12negativecontrol включаяqueuedSyncContext/cleanupbeforeobserver, +samehelper/raw66FB…; RootпрочёлTRANSITION-PROBE-RESULT.json, не подменяетactualcontrolproof. +Immutable604GUIsourcesmatchworkingnormalizedLF. Jointa5+EE2238/2238/44с/GUI0-0/85,38с, +independent1540paths/1539Gitblobs/175overlays/onlysharedcsproj+110exactGUIitems. + +Actual129 F:/cdpiui-verify/cdpiui-transition-sequence-a5a1b9b-20261110:build0-0/70,42с, +1515repo1243project/exact19cuts26bootstraps/24oldcasebyteequal/15actualpins, prelaunchREADY×2. +New4groupsrealunloadedcontrolconstructor/compiledXAML/Buttons/Visibility/Items/privateTask/Task.Delay; +readonlyUISettings, noLoaded/Composition/navigation/help/settings/backend/desktop/newIO/cuts. +Owned pendingTask state machine inspection on pinned.NET8 verifiesdirecthelper/controlpredicate/source/ +4literaldurations, no clocktiming/ABIguarantee. Normalphases/finalizer/preCancel/disposedempty-single/ +Tokenfaultpartialstate/newerCTSsentinel ownership/liveDPcallback проверяются. Sentinel не доказывает +две параллельные native последовательности; concurrency managed. Одинowncallback гарантирует trace +before reentry без предположения о порядке нескольких callbacks. Timeoutнеподавляетсяexpectedfault. + +SelectedfullSHA/pathsSTATUS, все15path+SHA вscratch `transition-control-host-approved-pins.json`. +Runner7D227A02…/readbackA122324B…проверяютсядоwrites/launchиpostrun. Prelaunch1515source/pins/PEasInvoker/ +uiAccessfalse/nonadmin/noreparse/522names/freshpaths/MSILstatefields/XBF/ownprocessnone PASS. +ПовторныйguardпротивV39released увиделужеV40retrospectiveactiveиостановилсядоleasewrites/launch; +это coordination gate, нерезультатactualFAIL. После explicitretrospectiveV41Rootgrant запуск один раз. +PID81460 UTC19:40:40.6399817→19:40:46.0595732 10ноября2026:129unique/first125exactorder/ +oneCOMPLETE/exit0/noFAIL/empty streams/logsbyteequal/15actualpins/5binaryprepost/3inputs16-16-15/ +2realreports354-260goldenSHA+literalfields/522→528recursive6newnames/priornames/forbiddenabsence/ +normal2F0Bunchanged/PIDgone. SHA-pinnedreadback повторилunique/prefix/logs/15pins/reports/names/absence/ +normalDLL. Послеpostchecks/Rootidleack/requestfalse/ALLUIpaused atomicV42releasedowner:null, +обе сессии уведомлены, noRootdesktop/CUA APIs. Tasks81/82COMPLETE, finalreviewACCEPT0Critical/ +0Important/0Minor; independent1515fixture/15pins/129prefix/IO/names/PID/queue/604GUI/joint1540paths/ +110XMLitems/175overlays проверены.132Ruling17Minor сохранены, product/source послеa5 неизменён, +no redundant runs for docs. + +## Матрица83–85: menu pruning, issue209 + +Spec: superpowers/specs/2026-11-10-menu-pruning-design.md; basea85/pin174d1cbf5699455d7768ae2398df4f8f241bddab. +Policy exact86417 imported as separatea85/7files; issue/Project actual In progress/P2/Architecture/Low/G2 +confirmed before code. Other executor208 owns ConfigMaker/TextRelay/CreateNewConfig/App, untouched here. + +| Контракт | Свидетельство | Граница | +| --- | --- | --- | +| Neutrality/postorder/live indices | PostOrderTreePruner23lines, one4port System-only API/oneconsumer; MenuBarController519→502;20tests | Menu claims and registry/physical removal remain in host | +| Child callback changes retention, reverse order/reentry/fault partial state | missing-fileRED→20GREEN; eager-retainmutant5FAIL→exactbyteSHA34B54E72restore→20focused/2046full | No transaction/index repair/null guards added | +| Normal GUI/contracts | GUI0-0/59.24s,BA70952D8A1598847C3CFB42856D2FE0F8AC2110B0CD29A5A09C2C0760E250AB; source451/605/0,meta452/0+7old | Recorded source/metadata shapes, not fullABI | +| Independent product review | Fresh reviewer ACCEPT0Critical/0Important/0Minor on174d1cb | Raw evidence read; reviewer did not rerun builds/tests/UI | +| ExactEE joint |2258/2258/1m25s,GUI0-0/90.99s;1542paths/1541blobs/178overlays/111additiveXMLitems | Isolated snapshot, no merge/security checkout change | +| Native fixture/runtime |133unique/first129/COMPLETE/exit0/allpostchecks;1525repo1244project/19oldcuts/27bootstraps/25oldcasebytes/18pins; build0-0/77.21s; prelaunchREADY | Explicit48Rootgrant; then49peer208handoff afterPIDgone/idleack/requestfalse | + +Fixture F:/cdpiui-verify/cdpiui-menu-pruning-174d1cb-20261110. Four actual MenuBar/Frame/controller +checks cover weak nested pruning, strong/weak descendants and protected outcomes, mergedclaims/prefix, +already detached physical root/ignored Remove false/idreuse. Actual object identity checked in logical +lists/physical collections/registry. No Loaded/navigation/activation/backend/desktop/newIO/cuts. +Failure callback/reentry ordering is managed/source evidence, not real WinUI notification execution. +RunnerE47818EA49B87459CC72BAD7CBFAF15F07452F34ECEE21D47B374A83048B60C1 and verifier +56A171078C4AF5AED040D3F4BA3C87F41FE1022BAA02480239340623D244AE83 enforce old129orderedprefix, +133unique/oneCOMPLETE/exit0/18pins/3inputs/2goldenreports/6newnames/absence/process. Full selected +hashes and scope in STATUS; everyactualpath/hash in menu-pruning-host-approved-pins.json. +Actual133 runtime PID68204 UTC20:50:11.5149509Z→20:50:20.9279135+00:00,133unique/first129/ +oneCOMPLETE/exit0/noFAIL/streams0/logsbyteequal/18actualpins/5binaryprepost/3inputs16-16-15/ +2goldenreports354-260/522→528recursive6newnames/allpriornames/absence/normalBA7095unchanged/PIDgone. +FixtureDLL49EB7BED5E791D9DB359F6CB299B4839BEC34A2B0F3124584CA397AED0A30539; manifest696D1EB3... +Root48explicitgrant→postchecks/idleack/requestfalse/allUIpaused→atomic49readyreviewedpeer208grant. +Earlierfree46guardstoppedonactual47historybeforewrites; prematuregrantmessagecorrectedimmediately. +Additional independent threewayb577+174+EE:2287/2287/GUI0-0/74.70s,1544exactpaths/1543Gitblobs/ +177GUIoverlays4Menudelta/112uniqueXMLadds/all14securityitems126total retained, onlycsproj overlap. +No jointnative137/merge/releaseclaim. Final85technicalACCEPT0/0/0; issue209closedcompleted+actualProjectDone/P2ArchitectureLowG2Lumens/3labels readback afterreload52 confirmed. +133Ruling17Minor retained. Physical controller count corrected519→502, prior501transcription +retained with additive ledger/issue correction; source/binaries unchanged. + +## Матрица86–88: ConfigurationVariableProjection, issue211 + +Basec089/source00f39b1a9be70cb97cebd7290b5f24dac6a5ab47, spec2026-11-11-configuration-variable-projection-design.md. +ActualProject55Inprogress/P2ArchitectureLowG2Lumens/2canonicalLabels доimplementation,209Doneverified. + +| Контракт | Свидетельство | Граница | +| --- | --- | --- | +| Two typed read-model loops, facade state stays | service443→411/helper45/internalstateless/usedprivateforward; guard/lookup/locks/IO/updates untouched | One consumer/domain adapter, no artificial generic framework | +| Model order/ownership/comparers/nulls |30actualpublicCoretests; original30→mutantFAIL3→exactrestore30; extractedmutantFAIL3→exactrestore30 | Current source dictionary enumeration order, no historical insertion promise | +| Full validation/contracts |2076/11s/0fail-skip;GUI0-0/70.77s; Core88source103→104/compiled88/0loss;605GUIfilesunchanged/GUI4520+7old | Metadata/syntax inventory, not complete ABI | +| ExactEE joint includesCore |2288/43s/GUI0-0/66.19s;1544paths/1543blobs/111XML/14securityitems | Onlycsproj overlap, emptygeneratedSecret onlyextra | +| Peer relay208+loader212+menu+Core+EE |2338/42s/GUI0-0/65.46s;1548paths/1547blobs/113dedupXML/14securityitems | Source/test/build composition, no merge/combined WinUI runtime/release claim | +| Independent review |Final source/joints/currentdocs ACCEPT0Critical0Important0Minor; orderMinor resolved/Ruling135 |211completed/6criteria[x]+actualProject64Done/P2ArchitectureLowG2Lumens/2labelsafterreload | + +Selected source/assembly hashes, exactFroots and fullproof paths in STATUS; allCore104input hashes +and bothjoint fullpaths+SHA maps in their retained JSONs. Original/helper mutation restoration exact, +testedCore candidate equals actualtestbin, initializer/lazy metadata/first-match/nullshortcircuit checked. +ActualCoreWindows facade execution is the relevant changed-code proof; no WinUI/binding/startup code +changed, previous133on174 retainedas historical. 135Ruling17oldDeferredMinor remain. Worktree/source +ownership of peer208/212/214 respected; source00 remains unchanged after documentation clarification. + +Task88localacceptancecomplete: source00f39/docsf573 finalreview0/0/0→accept6788006950→API211completed +→actualProject64Done/reload/finalmetadatarecord6788179295. RootreadfullsharedJSON+canonicalfields, +parents14/15LIVEopen. NoSource/testchangeafter00; finalclosurecheckpoint is docs-only. diff --git a/docs/DECOMPOSITION-STATUS.ru.md b/docs/DECOMPOSITION-STATUS.ru.md new file mode 100644 index 00000000..925c5c85 --- /dev/null +++ b/docs/DECOMPOSITION-STATUS.ru.md @@ -0,0 +1,1427 @@ +> Historical local-stage record for frozen dev/audit-class-decomposition at eebc7e8. +> Current integration work is tracked in [the integration plan](superpowers/plans/2026-11-11-class-integration.md). + +# Декомпозиция крупных классов + +Работа по наблюдениям о крупных классах из раздела 5 аудита и согласованному с пользователем порядку. Рекомендация начинать с ConfigMakerUserControl/App — пункт 20 исторического плана раздела 7; раздел 35.1 относится к отдельной, не выполненной глобальной nullable-миграции. База — `f39e8a0`; локальная ветка — `dev/audit-class-decomposition`. Отчёт обновляется по проверенным этапам, 8–11 ноября 2026 года. + +Работа продолжается по запросу пользователя **без временного ограничения**. Текущий код **ed390cd**, +продолжение89–91/[issue215](https://github.com/lumenpearson/cdpiui/issues/215): DiagnosticHighlightingUpdater, +Editor157→149/control828→820/helper29,32focused/2108full/GUI0-0/source451(606)/compiled452(0loss+7old). +Мутация порядка записи ключа вызвала4FAIL, точное восстановление→32GREEN. ExactEEjoint2320/GUI0-0; +correctedpeerf706+Root+EE2398/GUI0-0, оба source/XMLpostchecksPASS. История первой проверочной копии: +архив1531inputs/21точныйcut/28bootstrap/26неизменных прежних casefiles; независимое +ревью изоляции разрешило её сборку после исправления3Count→Length assertions; первая сборка +выявила пропущенный namespace import в новом тестовом файле, второй прогон —0warnings/errors48.44s. +Первая собранная копия сохранена без запуска: ревью выявило неверную атрибуцию общих счётчиков +настроек конструктору unloaded control. Отдельная r2-копия с поимёнными Search reads и явной проверкой +font singleton собрана0-0/69.10s; независимое prelaunchREADY0C/I, explicit83→137PASS(first133)/exit0/ +all23pins/1531Git21cuts28bootstrap26oldcases/3inputs2goldenreports/522→5286newnames/normal100Eunchanged/ +PID79052gone→idle/requestfalse→release84. Final91ACCEPT0unresolvedCritical/Important/Minor; +#215closedcompleted6criteria[x]/accept6789505833 и actualProject85Done после reload подтверждены: +P2/Architecture/Medium/G2/lumenpearson/3labels. Parent14/15 открыты; это локальная приёмка. +[Подробный протокол](superpowers/reports/2026-11-11-diagnostic-highlighting-verification.md). +Предыдущее принятое продолжение, код **00f39b1**, +продолжение86–88/[issue211](https://github.com/lumenpearson/cdpiui/issues/211): ConfigurationService +443→411/адаптер45строк,30focused/2076full/GUI0-0; Core88source/104files/compiled88/0recordedloss, +все605GUI C#files неизменны относительно174. ExactEEjoint2288/GUI0-0; peer9a9+Root+EE2338/GUI0-0. +Final88ACCEPT0Critical/0Important/0Minor;211closedcompleted+actualProjectDone readback confirmed. Новый WinUI runtime для чистых Core-проекций не заявляется. +Предыдущее завершённое продолжение83–85 +по [задаче209](https://github.com/lumenpearson/cdpiui/issues/209): код **174d1cb**, нейтральный +PostOrderTreePruner/MenuBarController,20focused/2046full/GUI0-0; native133PASS+COMPLETE/exit0. +Точный joint174d1cb+ee47716 прошёл2258/2258/GUI0-0, parallel relay+menu+EE2287/GUI0-0. Предыдущий принятый product/runtime: +**a5a1b9b**, TwoPhaseTransitionSequence/UtilityButtonControls, +**129PASS+COMPLETE/exit0**,30focused/2026full безfailed/skipped, GUI0warnings/errors, +source451/604C#files/0потерь и compiled452/0recordedchanges/+7прежних internal-interface shapes. +Exact jointa5a1b9b+ee47716 —2238/2238 иGUI0/0. Runtime129 сохраняет все125прежних групп, +добавляя четыре проверки realunloadedControl/XAML/Buttons.Visibility/privateTask/Task.Delay/CTS. +Новых IO/cuts в четырёх группах нет; два прежних report outputs сохранены в собственной F-копии. +Tasks81/82 закрыты, final evidence/docs reviewACCEPT0Critical/0Important/0Minor. + +Предыдущие runtime pins:61fd0e7/125(productb5,47/1996,joint2208),491692bc/121(product2e/manual session,72/1949,joint2161),0c5ea124/115, +ff6bc636/111,93091a13/107,de3d3821/103,839cc952/97; их тестовые уточнения сохраняют свои pins. +Manual121 с шестью lifecycle группами/настоящим dispatcher и инертными component ports также принят. + +Новый control536→500/helper50строк, directTaskforward с прежним CTS cleanup callback. Полный +scope нового129 и отдельные compiler/reflection/visual ограничения описаны в секции80–82. + +Общий критерий следующих проходов и ревью, переданный координирующей сессией по уточнению +пользователя: по возможности выделять небольшие утилитарные объекты с более нейтральным назначением, +когда архитектура проекта или модуля даёт такую границу. Нейтральный механизм отделяется от UI и +доменного orchestration; перенос того же сцепленного крупного host в новый большой класс недостаточен. +Искусственная универсальность, лишние интерфейсы и вымышленное повторное использование не нужны. +Небольшие доменные владельцы/WinUI adapters сохраняются там, где это удерживает состояние и контракты. + +Интерактивный native4 относится к **d347c617**, test-only3ba7d388:11PASS+COMPLETE/exit0 и всеpostchecks. +Результаты1719/1719, actual-host91 и joint1931/1931 относятся к историческомуd347c617. +Прежнийnative2 сохраняет product214b4b3. Весь аудит этим не закрыт. +[Приёмочная сводка первого временного окна](DECOMPOSITION-ACCEPTANCE.ru.md) сохраняет историческийe42срез. + +Текущие физические размеры относительно базы: ConfigMaker host **2143 → 1012**, App **955 → 677**, основной BlockCheck2ViewModel **999 → 426**, публичный BlockCheck2ResultViewModel **565 → 268**, ресурсный фасад **507 → 232**, исходный UI control **899 → 828**. Ниже сохранена история отдельных проходов и их точные границы проверки. + +Дополнительные ограниченные проходы по следующей крупной ViewModel: CreateNewConfigViewModel **1037 → 818** строк после condition draft, test session, designer state и component selection; остальные её обязанности пока остаются в host. + +BlockCheck2ResultPageViewModel после selection, summary, selected test, export, manual session и +текущего assignment-actions переноса: **874 → 513** строк в прежних четырёх partial-файлах. +ManualTesting **186 → 50**, Assignments **171 → 110** в последнем проходе; actual125 прошёл все postchecks. + +## Выполненный проход + +| Область | Изменение | +| --- | --- | +| ConfigMaker | Построение деревьев выделено в чистый builder, данные узлов и адаптер существующих WinUI-моделей. Регистрация ресурсов и переписывание ссылок вынесены из общего фасада. | +| App | Порядок первого и перенаправленного запуска выделен в dispatcher. WinRT-адаптер читает payload по запрошенному виду. Прежние обработчики и правила доступа остаются на своих местах. | +| BlockCheck2 | Состояние параметров, валидация, загрузка настроек и создание session request принадлежат отдельной OptionsViewModel. Основная ViewModel сохраняет API и отправителя уведомлений. | + +Это самостоятельные объекты с ограниченными зависимостями. Новых partial-частей крупных классов не добавлено. + +| Класс / исходные файлы | До | После первого прохода | +| --- | ---: | ---: | +| ConfigMakerViewModel, сумма partial-файлов | 2143 | 1957 | +| App, сумма partial-файлов | 955 | 874 | +| BlockCheck2ViewModel, сумма partial-файлов | 999 | 783 | +| ConfigMakerPresetResources | 507 | 232 | + +Указаны физические строки с using и комментариями; это не сложность методов и не процент покрытия. + +## Сохранение поведения + +Новые тесты проверяют дерево файлов и профилей, сортировку en-US/sv-SE, координаты перехода в редактор, ресурсы и все значения переменных, маркеры Lua и offset blob, варианты активации, параметры BlockCheck2 и последовательности уведомлений/записи настроек. + +Во время переноса найдены и устранены до завершения этапов: + +- Чтение команды до уведомления о добавлении ресурса давало устаревший текст. Восстановлено исходное позднее чтение; сценарий воспроизведён падающим тестом. +- Общий пустой массив подавлял PropertyChanged дерева и мог оставлять неверную видимость вкладки групп. Восстановлена новая коллекция при каждом построении; тест показал ошибку идентичности до исправления. +- Объединённый callback direct-команды изменял частичный результат при исключении GUI fallback. Восстановлено исходное промежуточное присваивание; тест упал с true вместо false и прошёл после исправления. +- Аргументы перенаправленного Launch читаются повторно после await миграции, как в исходнике; проверяется отдельным провайдером с меняющимся значением. + +## Проверки первого прохода + +- До изменений: 768/768 xUnit; GUI x64 Release — 0 warnings/errors. +- После изменений: 835/835 xUnit, 0 failed/skipped; GUI x64 Release — 0 warnings/errors. +- 67 новых presentation-сценариев используют реальные production-исходники, подключённые к xUnit без WinUI runtime. Работающие компоненты, системные настройки и tray не запускаются. +- ConfigMaker, App activation и BlockCheck2 прошли отдельные независимые read-only ревью. Обнаруженные замечания исправлены. +- В отдельной копии совместно проверены security `4b5a0ba2d165af7113aff7b70508034507b9bb50` и этот проход: 857/857 xUnit, 0 failed/skipped; GUI x64 Release — 0 warnings/errors. Первая GUI-сборка вложенной копии остановилась на PRI175/PRI252 для существующего XBF по пути длиной 260 символов. Те же исходники в коротком каталоге `C:/Users/lumen/Programming/cdpiui-joint-4b5a0ba-20261108` собраны успешно, без изменений product-кода. +- Smoke-проверка реальных адаптеров из `CDPIUI.dll` прошла: содержимое/тип файловых узлов, тип и четыре координаты option-узлов, разные пустые коллекции обоих entrypoints. Проверялись production-типы через reflection, без окон, App/tray/компонентов и пользовательских настроек. + +Использован SDK `C:/Users/lumen/.dotnet/dotnet.exe`, версия 8.0.427. Основные команды: + +```powershell +dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release +dotnet build CDPIUI/CDPIUI.csproj -c Release -p:Platform=x64 +git diff --check +``` + +## Границы и ограничения + +Security/staging/ZIP/updater/settings persistence принадлежат параллельной сессии. Её рабочее дерево и незакоммиченные файлы здесь не меняются. В общем тестовом проекте изменения аддитивны. + +Полный production startup и реальный запуск компонентов не выполнены. Живые WinUI-привязки проверены в изолированном стенде ниже. Успешные тесты, сборка и ревью не являются доказательством отсутствия любых регрессий. Сохраняемые форматы, ключи настроек, протокол pipe и URI allowlists не изменены. + +Крупные классы ещё требуют следующих проходов по оставшимся обязанностям ConfigMaker, lifecycle окон App и BlockCheck2. Этот отчёт не объявляет весь аудит закрытым; завершённые дополнительные проходы перечислены ниже. + +## Второй проход: панель справки ConfigMaker + +Каталог команд, фильтры модулей и поиска, выбранная команда и аргумент выделены в `ConfigMakerCommandHelpPanel`. Сохраняются экземпляры коллекций/опций, отправитель уведомлений host-модели, порядок выбора и обновления Copy/Insert. Async loading/cancellation и операции редактора остаются в host. + +Добавлено 17 сценариев, включая восстановление группы после reload и повторный вход из синхронного уведомления. Полный suite: 852/852, GUI x64 — 0 warnings/errors. Независимое ревью не нашло runtime-регрессий; замечание к nullable-параметру, уже поддерживающему null, устранено аннотацией `string?` без изменения поведения. + +Сумма исходных partial-файлов ConfigMakerViewModel после этого прохода — 1823 строки (до начала работы 2143). Следующий участок — жизненный цикл тестового запуска редактора. + +## Третий проход: тестовая сессия ConfigMaker + +`ConfigMakerTestSession` владеет состоянием теста, подпиской, остановкой и восстановлением прежнего запуска. Узкий адаптер вызывает те же перегрузки ComponentTasksManager; его singleton не инициализируется при создании ViewModel. Host сохраняет разрешение аргументов, локализованные сообщения и DispatcherQueue. + +Добавлено 16 сценариев без настоящих процессов: состояние и сообщения по порядку, отказ/ошибки, восстановление обычной конфигурации, игнорирование событий во время старта, отложенный выход и чтение ComponentId после await. Полный suite — 868/868, GUI x64 — 0 warnings/errors. Независимое ревью не обнаружило новых замечаний. Реальный запуск компонента и доставка в живом диспетчере не проверялись. + +Автономная работа продолжается до 14:00 9 ноября 2026 года по Москве. Проверенные этапы сохраняются локальными коммитами; публикация и необратимые действия не выполняются. + +## Четвёртый проход: простой дизайнер ConfigMaker + +`ConfigMakerSimpleDesigner` владеет моделями и синхронизацией между графическим дизайнером и текстом команды. Существующие фабрики и преобразование аргументов вызываются через ленивый backend; доступ к DatabaseHelper и локализатору не переносится в конструктор. Host сохраняет публичные свойства, экземпляры команд, отправителя уведомлений и сообщения. + +Добавлено 17 сценариев: повторное чтение редактора, изменения обычных и групповых параметров, выход из дизайнера, повторный вход из синхронных событий, ошибки загрузки/преобразования и сброс dirty-флага после записи текста. Полный suite — 885/885, GUI x64 — 0 warnings/errors. Независимое ревью не нашло runtime-регрессий; замечание к прямой проверке выхода из дизайнера закрыто дополнительным тестом. + +Сумма исходных partial-файлов ConfigMakerViewModel теперь 1581 строка против 2143 перед началом работы. Следующий участок — создание и повторное использование окон App; обработка WinUI-событий закрытия и modal/native операции требуют сохранения прежних границ. + +## Пятый проход: каталог и создание окон App + +`AppWindowCoordinator` управляет выбором живого окна, повторным использованием и заменой Safe-окон, поиском Unsafe-окна по template-id и снимками для закрытия. Он работает с прежним `OpenWindows`; WinUI-адаптер выполняет прежние операции создания, позиционирования, регистрации и активации. Обработчики закрытия, modal/native операции и migration/idle lifecycle остаются в App. + +Добавлен 21 сценарий: ожидание актуальной задачи локализации, изменение списка во время await/Close, живые/закрытые/дублирующиеся окна, сравнение id, порядок операций и исключения. Независимое ревью обнаружило отличие исключения для null-типа при пустом списке; тест воспроизвёл NullReferenceException вместо ArgumentNullException. Исходная отложенная лямбда восстановлена в обоих методах создания. + +Полный suite — 906/906, GUI x64 — 0 warnings/errors. Сумма partial-файлов App — 794 строки против 955 перед началом работы. Эти проверки не запускают настоящие окна или компоненты. + +Совместная проверка завершённых изменений на security `ada2a4ba982e09662e0edc37c54ccb4472d6dc4c` и GUI `ecc78287aff30d629d6e0c43c174d2431fe6ecf9`: 969/969 тестов, 0 failed/skipped; GUI x64 Release — 0 warnings/errors. Отдельная копия `C:/Users/lumen/Programming/cdpiui-joint-ada2a4b-20261108` сохраняет новые security-исходники и весь GUI-проход относительно первоначальной базы. Рабочие деревья обеих сессий не объединялись. + +## Шестой проход: отображаемый прогресс BlockCheck2 + +`BlockCheck2ProgressViewModel` владеет фазой, счётчиками, идентификаторами текущей цели/стратегии, форматированием текущей цели и оценками времени. Host сохраняет API и отправителя уведомлений. Оценщик реализует узкий интерфейс; его вычисления и Stopwatch не изменены. + +Добавлено 16 сценариев с реальным production-оценщиком и управляемыми результатами для проверки порядка: все поля до первого события, актуальные параметры, case-sensitive поиск цели, повторные и вложенные обновления, сброс, finally, завершение и исключения. Полный suite — 922/922, 0 failed/skipped; GUI x64 Release — 0 warnings/errors. Независимое ревью: 0 Critical/Important/Minor. CTS, процесс выполнения, история и сохранение отчёта остаются в прежнем владельце; final state устанавливается после SaveAsync. + +Текущее число физических строк исходных файлов крупных классов: + +| Класс | Перед работой | Последний checkpoint | +| --- | ---: | ---: | +| ConfigMakerViewModel, сумма partial-файлов | 2143 | 1525 | +| App, сумма partial-файлов | 955 | 794 | +| BlockCheck2ViewModel, сумма partial-файлов | 999 | 675 | +| ConfigMakerPresetResources | 507 | 232 | + +Счётчик включает using, комментарии и пустые строки. Это мера размера класса, а не оценка сложности или покрытия. Код выделен в самостоятельных владельцев ответственности с проверенными прежними контрактами. + +## Седьмой проход: загрузка справки ConfigMaker + +`ConfigMakerCommandHelpLoader` владеет текущим запросом, отменой и состоянием загрузки справки. Прежний сервис и панель передаются напрямую; parser/cache/Core/pipe не изменены. Host сохраняет API, локализованные статусы, отправителя уведомлений и порядок отмены перед остановкой таймера диагностики. + +Добавлено 17 сценариев: поздние ответы, перекрывающиеся запросы, смена компонента, forceRefresh, освобождение прежнего CTS, повторный вход, точный порядок сбросов коллекций и границы catch/finally. Полный suite — 939/939, 0 failed/skipped; GUI x64 Release — 0 warnings/errors. Независимое ревью не нашло runtime-дефектов; замечание к прямой проверке повторного сброса опций закрыто тестом наблюдаемых CollectionChanged-событий. ConfigMakerViewModel теперь 1525 строк против 2143 до начала работы. + +## Восьмой проход: живые привязки WinUI + +В отдельной копии `111b017dbacc7f50892320b2fac350c209799e39` проверены production-контролы через нативный интерфейс. Все выделенные владельцы и XAML совпадают с коммитом. Восемь явных границ стенда отключают single-instance/startup/tray/associations, подменяют help/tasks/output/catalog, запрещают реальный scan и fallback каталога данных в AppData. Проверка всех отслеживаемых GUI/Shared-файлов и независимое ревью подтвердили эти границы. Каталог данных обоих запусков находился внутри собственных бинарников. + +Наблюдалось в реальных элементах интерфейса: + +- ConfigMaker: текст команды и справка, выбор флага с обязательным аргументом, вставка `--dns-addr 8.8.8.8` отдельной строкой, фильтр `dns`, отключение/включение Insert и Replace при readonly, загрузка простого дизайнера и применение его переключателя. +- Тестовый сеанс: настоящий публичный `IsTesting` перешёл `false → true → false`; фиктивный task backend получил Run/Stop, событие завершения прошло через настоящий DispatcherQueue и обновило уведомление контроля. +- App: два вызова Safe-фабрики вернули один экземпляр вспомогательного окна; после закрытия окно исчезло и из каталога, и из нативного списка окон. +- BlockCheck2: production-страница показала `2 of 8 → 5 of 8`, progress bar `0.25 → 0.625`, URL, TLS/IPv6/порт, стратегию и счётчики. Значения взяты из самой страницы, отдельно от подписи тестового host. +- Advanced: штатные NumberBox приняли число запросов `5` и локализованный ввод задержки `1,25`; в XML стенда сохранены `RequestsPerDomain: int=5`, `StartupGraceSeconds: double=1.25`. Переключение протоколов дало настоящее предупреждение HTTP-only и сохранило типизированные bool-значения. + +Стенд собран без предупреждений и ошибок. Процессы обоих прогонов завершились с кодом 0; записи каждого запуска проверены отдельно, `FAIL` не зарегистрирован. Исходники, манифест и diff границ сохранены в `C:/Users/lumen/Programming/cdpiui-ui-smoke-111b017-20261109`. Полный production startup, tray/IPC, реальные компоненты/сканирование, восстановление компонента и настоящая отмена этим стендом не проверяются. Страницы Advanced/Progress открывались тестовым host; прохождение всего мастера не заявляется. + +Найден прежний дефект кодека: `--blacklist="path"` теряет закрывающую кавычку при переходе через дизайнер; после возврата настоящий редактор показал CFG003 — незавершённую цитату. `GraphicDesignerHelper` и formatter побайтно совпадают с версией до выделения дизайнера; старый и новый владельцы передают одинаковые аргументы. Исправление вынесено в следующий отдельный этап с тестом полного цикла. Предупреждение о `-p` в этом прогоне объяснялось сокращённой справкой стенда. + +## Кодек графического дизайнера и повторная UI-проверка + +Из `GraphicDesignerHelper` выделен чистый `GraphicDesignerCommandCodec`; публичный фасад, XML-фабрики и локализация сохранены. После 19 характеристических сценариев прежняя потеря кавычки воспроизведена падающим тестом и исправлена. Значения с `=` уже корректно разбирались по первому разделителю; отдельного изменения для них не потребовалось. + +Новые сценарии проверяют известные и неизвестные флаги, inline/separate значения, короткие и slash-флаги, полностью quoted аргументы, пробелы, пустые значения и динамическую фабрику. Для enum и proxy-полей сохраняются скалярные значения; неперсистентная группировка обеспечивает обратную сборку команды. Ручная очистка поля возвращает прежний bare flag, а присваивание того же parsed empty сохраняет явный пустой аргумент. + +Локальный кодовый коммит — `27bfa46`. Полный результат этого кода — **985/985 xUnit, 0 failed/skipped; GUI x64 Release — 0 warnings/errors**. Замечания независимого ревью воспроизведены RED-тестами, исправлены и повторно проверены; оставшихся actionable defects ревью не выявило. + +В новой изолированной копии `C:/Users/lumen/Programming/cdpiui-ui-codec-27bfa46-20261109` повторён нативный цикл: исходная команда с quoted blacklist path → Simple designer → изменение `-p` → Code. Поле дополнительных аргументов сохранило обе кавычки; после обратного преобразования закрывающая кавычка видна в редакторе, диагностика показывает **0 errors, 0 warnings**. Прежний CFG003 в этом сценарии устранён. + +Дополнительный стенд использует настоящий `ComponentSettingUserControl`: исходный `Very fast` отображался в ComboBox и давал `--mode="very fast"`; после ручного выбора `Fast` получен `--mode=fast`. Настоящий `TgWsProxyStartupArguments.Parse` прочитал quoted host/port/secret как скалярные значения, port разбирается как int 1443. Для этого отдельного enum-контрола стенд явно переносит TextValue в модель; связь через шаблон настоящего редактора здесь не проверялась. Границы стенда прошли независимое ревью и сверку всех 934 tracked GUI/Shared файлов: только восемь согласованных fixture-подмен, рабочие владельцы и XAML неизменны. Процесс завершился с кодом 0, в логе нет FAIL. Полный production startup, реальные компоненты и системные настройки по-прежнему вне этого стенда. + +Совместная копия `C:/Users/lumen/Programming/cdpiui-joint-d65477f-20261109` содержит GUI `27bfa46b1cdd829deec2786998561cb382292d53` и security `d65477f369ad0951189946248a7e76405771f80d`, с аддитивным объединением test project. Результат — **1069/1069 xUnit, 0 failed/skipped; GUI x64 Release — 0 warnings/errors**. Security-сессия отдельно сообщила об открытом filesystem gap в своём коммите; совместный прогон подтверждает совместимость и не закрывает этот дефект или весь аудит. Незавершённые изменения другой сессии не переносились. + +## Состояние результатов BlockCheck2 + +Из основной `BlockCheck2ViewModel` выделен `BlockCheck2RunResultViewModel`: ошибки, issues, результат, report/session, вычисляемые признаки и экспорт. Тонкий `BlockCheck2ReportOperations` использует прежние builder/serializer. Существующая публичная `BlockCheck2ResultViewModel`, которая обслуживает окно результатов и ручные назначения, совпадает с исходной базой. Основной host сохраняет публичный API и последовательность run/CTS/Cancel/history/cleanup; финальное состояние устанавливается после await истории. + +35 новых сценариев проверяют пустой и готовый отчёт, best-effort/HTTP-only, live-чтение параметров, ссылки session, частичное состояние при исключении, ленивую сериализацию, синхронные границы экспорта, path/token/task identity, повторные уведомления ошибок, совместный reset с реальным progress owner и повторный вход из PropertyChanged. Локальный кодовый коммит — `7188106`. Результат — **1020/1020 xUnit, 0 failed/skipped; GUI x64 Release — 0 warnings/errors**. Независимое повторное ревью не оставило Critical/Important замечаний. + +В отдельном стенде `C:/Users/lumen/Programming/cdpiui-ui-result-7188106-20261109` проверен настоящий host: для двух последовательных отчётов каждое из 11 событий пришло от основной ViewModel и уже видело актуальные result/session/report/targets/issues, флаги и аргументы. У отчётов различались catalog/host, поэтому JSON и text также проверены на актуальное содержимое. Внутренний сброс результата после заданного прогресса прошёл полную последовательность 29 событий; поля уже были очищены в момент уведомления, экспорт стал недоступен. + +В настоящем InfoBar страницы сначала наблюдалось сообщение `No config is needed for the tested connections` с уточнением о проверке только HTTP, затем — `Config selected successfully`. Это отображение fixture-результатов, а не результат реального сетевого сканирования. Сверка 937 tracked GUI/Shared файлов и независимое ревью стенда подтвердили восемь согласованных boundary-подмен и неизменность владельцев/XAML относительно коммита. Стенд собран без предупреждений/ошибок, процесс завершился с кодом 0, FAIL в логе нет. Запуск сканирования, реальная история, экспорт на диск, публичный Reset с cleanup и полное прохождение мастера этим прогоном не проверялись. + +Сумма partial-файлов основной BlockCheck2ViewModel уменьшилась с 675 до 607 физических строк (исходно в начале работы — 999). Дополнительная совместная копия после этого этапа ещё не запускалась; приведённые выше 1069 тестов относятся к точному GUI-коммиту 27bfa46. + +## Ручные назначения окна результатов: код проверен, нативная проверка продолжается + +Из публичной `BlockCheck2ResultViewModel` выделен `BlockCheck2ManualAssignmentEditor`: операции над назначениями, совместимые site-list targets/пути, автоматический seed, ключи и отметки выбора, индексы строк. Используется прежняя коллекция `Draft.Assignments`. Host сохраняет публичный API, построение manual preset, локализацию issues и manual test service. Тело `BlockCheck2ManualIssueItem` перенесено в собственный файл без изменений. Модель окна уменьшилась с **565 до 402 физических строк**, новый редактор — 229 строк. + +34 новых сценария используют настоящие production Draft/assignment/evidence/rules и проверяют guard/duplicate/scopes, primary/fallback order, path sorting en-US/sv-SE и вторичный full-path order, повторный вход из событий коллекции, live session/evidence, исключения formatter/rebuild/subscriber и частично опубликованное состояние. Полный suite — **1054/1054 xUnit, 0 failed/skipped; GUI x64 Release — 0 warnings/errors**. Независимый ревьюер сверил все 13 перенесённых методов и не выявил introduced defects; пять дополнительных случаев покрытия также проверены повторно. + +Прежние различия record equality/automatic keys, fallback anchor и сопоставления site по host сохранены в этом extraction; их отдельные риски не объявляются исправленными. Удаление и очистка назначений покрыты headless; реальные компоненты и тесты стратегий этим этапом не запускаются. + +Нативная проверка Add/Move пока не завершена. В первом варианте стенда настоящая `ResultPage` была помещена прямо во вкладку без требуемого `Frame + MenuBarHost`. Три запуска зависли до первого ручного редактирования; два диагностических запуска прошли все точки трассировки, включая завершение LoadSession. Для второго Windows зарегистрировала переполнение стека (`0xc00000fd`). Стек третьего запуска показал `AnimatedSelectorBarMenu.Subscription.ScheduleRetry`: без `MenuBarSession` он бесконечно планирует повтор. Код страницы и меню этим extraction не изменялся; независимый разбор подтвердил отсутствующий контракт окружения стенда. Успешное добавление/перестановка из этих запусков не заявляется. + +Исправлен только стенд: навигация через настоящий Frame, подключение MenuBarHost и проверка ненулевой MenuBarSession до размещения страницы. Он повторно собран с **0 warnings/errors**, исправление прошло независимое read-only ревью. Сверка tracked GUI/Shared/Core/AddOns подтверждает прежние десять явных fixture-границ; production-модель, редактор и XAML совпадают с `9211253`. Повторный интерактивный прогон ожидает освобождения общего desktop от отдельного UAC `ToolsSmokeTest.exe`; точный путь этого запроса не подтверждён, разрешение ему не выдавалось. Кодовый результат 1054/1054 и нативный Add/Move учитываются раздельно. + +## Операции документа ConfigMaker: код проверен + +`ConfigMakerDocumentCoordinator` управляет загрузкой документа и ConfigItem, созданием ConfigItem из редактора, сохранением в приложение, экспортом текста/пакета и созданием нового документа. Используются прежние документ и коллекции. Host оставляет UI, локализацию, перестроение дерева, файловую автокоррекцию и прикрепление ресурсов; существующий storage реализует узкий интерфейс с неизменными телами методов. Конвертер вызывает тот же унаследованный static parser непосредственно через объявляющий `LScriptCore`, без зависимости от WinUI-локализатора. + +Сохранены `Sync → Attach → Sync → dialog`, создание storage после ответа диалога, применение результата к актуальному документу после await, callback/event order, прежние границы catch и частично опубликованное состояние при отказах. Не добавлены snapshots, сериализация параллельных сохранений или повторная readonly-проверка после подтверждения New. Эти прежние особенности характеризуются тестами, а не объявляются исправленными. + +Добавлено **46 сценариев** с настоящими document/variable/resource/converter models: клонирование и идентичность коллекций, self-load, живые чтения после событий, импорт и legacy conditional conversion, отмена/overwrite, storage factory timing, сопоставление resources, отложенные/параллельные сохранения, частичные отказы подписчиков, New и экспорт. Итог — **1100/1100 xUnit, 0 failed/skipped**. GUI x64 Release — **0 warnings/errors**; после GUI менялись только дополнительные тесты и документация. Независимый ревьюер сверил восемь перенесённых тел и явные host-адаптеры, внесённых дефектов не обнаружил. + +`ConfigMakerViewModel.Document.cs` уменьшился с **242 до 113 физических строк**; сумма partial-файлов host — с **1525 до 1400** (исходно 2143). Координатор — 197 строк. Unit-тесты используют fake host для callback contract; дополнительная runtime-проверка настоящего host описана ниже. Новый интерактивный проход контролов этого этапа пока не подтверждён. Настоящие storage/export I/O и автокорректор не запускались. Предыдущие нативные результаты относятся к своим точным pinned-коммитам. + +## Runtime-проверка настоящего host операций документа + +В отдельной копии `C:/Users/lumen/Programming/cdpiui-host-f7e5454-20261109` настоящий `ConfigMakerViewModel` выполнен на UI-потоке WinUI Application DispatcherQueue с фиктивным `IConfigMakerView`. Полные host/coordinator/document/converter/structure-adapter и XAML совпадают с кодовым коммитом `f7e5454`. Семь явных подмен заменяют обычный startup, путь данных и каталожные lookup, help, storage и exporter. Каталог данных проверяется до создания модели и ограничен собственным каталогом бинарников; окна, desktop input, реальные компоненты и автокоррекция не вызываются. + +Прошли семь групп runtime-assertions: + +- Load: прежние document/collections, глубокие копии с исходными значениями, нормализованный текст view, вся последовательность восьми промежуточных/финальных состояний и настоящий sender событий. Проверены данные attached missing-file node, tooltip и реальные вызовы диагностики. +- SetComponent/help: настоящий loader и host callback к фиктивному output; диагностика показывает ноль ошибок и предупреждений. +- Save: диалог завершается до вызова backend; правка редактора во время await сохраняется. Проверены полные три состояния уведомлений, alias mapping ресурса, идентичность результата и настоящий статус Success с локализованным сообщением. +- Overwrite: выбран правильный inert backend, CANCELED не создаёт сообщения и сохраняет имя. +- Export: запрет text format при variables, ожидание backend, реальные Success/Error сообщения и отмена picker до синхронизации. Физический экспорт отсутствует. +- New: readonly и отмена не очищают документ; отложенное подтверждение сохраняет прежнюю однократную readonly-проверку. Проверены все четыре состояния очистки, сохранённая metadata, пустые node lists, base directory и undo callback. +- ConfigItem import/create: настоящий converter и base-directory adapter; Create самостоятельно читает новый текст view, который ещё не передан через OnEditorTextChanged. + +Стенд прошёл независимое ревью границ и assertions. Сверены **1190 tracked GUI/Shared/Core/AddOns файлов**: ровно семь boundary files; дополнительные C# — только bootstrap и проверенный пустой Secret stub. Сборка — **0 warnings/errors**. Процесс PID 27288 завершился с **кодом 0**, все семь PASS и COMPLETE присутствуют, FAIL нет; stdout/stderr пусты. Логи, source manifest и SHA-256 бинарника сохранены в scratch-папке этого плана. Root suite 1100/1100 относится к неизменному продуктовому коду f7e5454 и повторно ради harness/docs не запускался. + +Это runtime-проверка настоящего host с fake view/backend. Она дополняет unit-тесты, но не заменяет интерактивный Add/Move и проверку контролов, которые остаются открытыми. Уточнены также прежние числа файлов в этом отчёте: 1415/1419 были общими количествами во всём репозитории; фактические checker-области GUI/Shared для соответствующих коммитов содержат 934/937 файлов. Функциональные результаты тех прогонов от этого не меняются. + +## Замена отсутствующих файлов: код проверен + +`ConfigMakerPresetFileReplacer` объединяет замену из диалога и тихого импорта: выбор auto/manual/empty ветки, применение замены, explicit file entries, command/rebuild/event/status и обработку ошибок. `ConfigMakerPresetFileReplacementBackend` делегирует прежним filesystem/resource/autocorrect операциям. Автокорректор создаётся только после выбора AutoCorrect; прежний ConfigImportResult готовится синхронно, поиск остаётся в Task.Run. Открытие/add/remove/insert и сам Document partial не изменены. + +Сохранены важные различия: attached update не меняет команду/explicit array и не публикует событие; непустая неудачная suggestion не открывает manual fallback; silent replacement подавляет сообщения, сохраняя остальные действия. При reference replacement explicit array обновляется до команды, событие идёт после rebuild. Чтение актуального CommandText и создание EventArgs остаются внутри условного `PresetFileReplaced?.Invoke` в host, sender — сам host. Предыдущие мутации при поздней ошибке не откатываются. + +Добавлено **46 сценариев** без физических файловых/shell операций: guards, выбор и ожидание диалога/поиска, ленивый factory, нормализация пути, identity/path/kind matching, сохранение остальных полей, поздние чтения, форматирование, silent mode, частичные отказы и области catch. Полный suite — **1146/1146 xUnit, 0 failed/skipped**; GUI x64 Release — **0 warnings/errors**. Независимое ревью всех семи перенесённых методов, интерфейсов, backend и host/silent adapters не выявило внесённых дефектов. + +`ConfigMakerViewModel.PresetFiles.cs` уменьшился с **327 до 178 физических строк**; aggregate host — с **1400 до 1254**. Replacer — 194 строки. Linked-source tests используют fake ports; дополнительная runtime-проверка настоящего host и части backend с инертными I/O-границами описана ниже. Это не новый результат интерактивной проверки контролов. + +## Runtime-проверка замены файла в настоящем host + +В новой копии `C:/Users/lumen/Programming/cdpiui-replace-01163f0-20261109` проверен точный кодовый коммит `01163f0`. Host, replacer и registry/reference editor совпадают с pin. Конструктор lazy corrector и ShouldSuggestEmptyFile сохранены; в прежнем Task.Run подменён только target поиска. Восемь явных boundary files заменяют startup/data/catalog/help/storage/export, подготовку фиктивного autocorrect result и низкоуровневые FileExists/CreateEmpty/результат поиска. Все пути fixture ограничены собственным bin; физические файлы замены не создавались, оригинальный filesystem search не выполнялся. + +Пять новых групп actual-host assertions прошли вместе с семью документными группами на новом составе конструктора: + +- Manual reference replacement ожидает ответ диалога. Настоящие registry/reference editor переписывают command и variable values. Обработчик добавления ресурса и обработчик rebuild по очереди меняют команду; оба изменения сохраняются. Проверены explicit array, сохранение строки другого kind и настоящий sender/event args с актуальной командой после rebuild. +- Attached replacement сохраняет тот же resource и explicit array, публикует ровно два состояния path/built-in, не меняет команду и не вызывает PresetFileReplaced. +- Auto replacement готовит фиктивный result на UI-потоке до настоящего Task.Run. Worker получает тот же объект и прежний component, пока UI меняет текущие component/command. После освобождения worker замена использует актуальный текст и возвращает событие/статус на UI-поток. +- Empty ветка использует настоящий ShouldSuggestEmptyFile, инертный create marker и существующий guard при второй попытке; поиск, reference event и физическое создание отсутствуют. +- Два настоящих private forwarding helper вызваны с showStatus=false: reference event сохраняется, новые статусные сообщения подавлены. Полный public silent-autocorrect import с оригинальным поиском не запускался. + +До execution ревью выявило и помогло устранить два недостатка harness: ожидания CRLF/LF и пропуск bounded await worker при ранней ошибке. Product-код не менялся. Assertions отдельно учитывают прежние представления model/event и нормализованных document/view; cleanup в finally освобождает worker и ожидает завершение, сохраняя первичную ошибку. + +Финальная сборка стенда — **0 warnings/errors**. Независимо сверены все **1431 tracked файл** pinned-архива; внутри GUI/Shared/Core/AddOns — **1194**. Отличаются только восемь boundary files; дополнительные C# — два bootstrap и проверенный пустой Secret stub. Процесс PID 43396 завершился с **кодом 0**: все **12 PASS**, COMPLETE, ни одного FAIL; stdout/stderr пусты. Manifest, SHA-256 и отдельный свежий лог сохранены в scratch. Root unit suite остаётся **1146/1146**, продукты после его проверки не менялись. + +Стенд проверяет настоящий host с fake view/backend-границами на DispatcherQueue. Он не подтверждает настоящий editor/dialog/file picker, интерактивный Add/Move или production startup. Последняя проверка общего desktop по-прежнему видит отдельный UAC; разрешение ему не выдавалось и интерактивные gates остаются открытыми. + +## Остальные файловые действия ConfigMaker: код проверен + +`ConfigMakerPresetFileActions` владеет add/open/show/remove/insert и picker workflow. Новый production backend сохраняет прежние registry/filesystem/settings/shell операции и обращается к ним при вызове метода. Host сохраняет публичные сигнатуры, объект AddPresetFileCommand и private picker forward; replacement/document owner и silent callers не изменены. + +Зафиксированы исходные порядок и границы ошибок: Add передаёт тот же ленивый enumerable и показывает исходное число добавленных файлов; выбор text application ожидается и не вызывает shell после ответа. Remove запоминает объект до подтверждения и удаляет именно его из прежней коллекции после await. Insert проверяет readonly, сохраняет preset URI, нормализует путь перед регистрацией и читает alias после rebuild. Частичные мутации при ошибках остаются прежними. + +**47 новых сценариев**, полный suite **1193/1193, 0 failed/skipped**; GUI x64 Release **0 warnings/errors**, 47.43 секунды. Независимый read-only reviewer сверил все семь исходных методов, двенадцать backend mappings, host adapters и тесты; findings и отложенных оценок нет. Новый owner — **152 физических строки**, файловый partial — **178 → 79**, aggregate ConfigMaker host — **1254 → 1158** (исходно 2143). + +Unit-тесты используют реальные document/resource/observable collection models и фиктивные ports. Реальные settings/shell/физические файловые операции в них не выполнялись; production mappings проверены сборкой и ревью. Дополнительная actual-host runtime-проверка этого этапа ещё предстоит. Предыдущие результаты стендов сохраняют свои точные pinned-коммиты; интерактивные gates остаются открытыми. + +## Runtime-проверка остальных файловых действий + +Новая копия `C:/Users/lumen/Programming/cdpiui-actions-a87f27b-20261109` закреплена на `a87f27b`. Настоящие host, document/actions/replacer owners, registry/reference editor и XAML не изменены. К прежним восьми startup/data/catalog/help/storage/export/replacement boundaries добавлена девятая: запись policy/remember/shell вызовов вместо работы с настройками и внешними приложениями. Действительные path resolution, File.Exists и регистрация ресурсов сохранены. + +После проверки точного binary/data root и asInvoker стенд создал ровно три безвредных входа с FileMode.CreateNew в собственном каталоге бинарников. Они оставлены на месте; финальная проверка сравнила точные байты. Существующие файлы не перезаписывались и не удалялись. Пять новых runtime-групп проверили: + +- Add/picker: реальные фильтры существования и дубликатов, resource kinds/built-in, attached tree nodes, локализованное исходное число добавлений, identity коллекции и команды. +- Open/show: настоящее разрешение preset URI и проверка файла; ожидаемый true/false ответ диалога, remember только для true, порядок inert text/default/folder вызовов. +- Missing/null: Warning с разрешённым путём и отсутствие policy/dialog/shell вызовов. +- Remove: удаление без диалога для unreferenced; отмена; замена объекта с тем же alias во время await не меняет захваченный объект; локализованный диалог, один rebuild и запуск предварительно остановленного diagnostics timer. +- Insert: настоящий registry и мутация alias при rebuild, поздняя quoted reference, согласованность editor/document/model, command event до cursor write, readonly guard с ненулевым файлом. + +Все **17 групп** (12 прежних composition/replacement и 5 новых) прошли: PID **37800**, exit **0**, PASS/COMPLETE, без FAIL/stdout/stderr. Финальная сборка — **0 warnings/errors**, 41.13 секунды. Независимый reviewer сверил все **1436 tracked-файлов**, включая **1198** в четырёх product roots, ровно девять boundaries и три bootstrap/пустой Secret stub. До исполнения усилены три assertions: байты вместо текста, остановленный исходный timer и ненулевой readonly-вход. Product-код не менялся. DLL SHA256: `80A6485ADEFEDE1D24FDEBBAF2A39538DBC7D82222D90AEEA7FC19013AC1396B`. + +Это actual-host integration с fake view и внешними границами. Реальные shell/preferences, storage/export, original autocorrect search, component tests и интерактивные контролы не запускались. Полные catch/attach порядки дополнительно проверены unit suite и source review; runtime-набор не объявляется исчерпывающим. Интерактивные gates Task15/16 остаются открытыми. + +## Совместимость с security-веткой, обновлённый pin + +В новой отдельной копии `C:/Users/lumen/Programming/cdpiui-joint-5cf1e17-20261109` объединены только committed snapshots: GUI **`a87f27ba078f1d8041f005436f356ec302ae65c7`**, security **`5cf1e17e51f537195964466319a2a84993713634`**, общая база `f39e8a0`. Исходники обеих рабочих веток не менялись. Пересечений product-файлов не было; test csproj получил только дополнительные items нашей ветки с сохранением security project items. + +Совместный suite — **1328/1328, 0 failed/skipped**, 1 минута 9 секунд; GUI x64 Release — **0 warnings/errors**, 1 минута 31.78 секунды. Manifest и отдельные логи сохранены в scratch плана. Security pin имеет собственный документированный suite 903/903; его открытые durable transaction/recovery, serialization и cleanup задачи остаются ответственностью параллельной сессии. Новые непроверенные изменения той ветки не включались; старые совместные копии сохранены. + +## Проверка объявленного публичного API + +Отдельный scratch-инструмент на Roslyn из установленного SDK сравнил committed GUI-исходники базы `f39e8a0` и `00fb0ad` (код `a87f27b`). Прочитаны все **517 → 559 tracked C# файлов**, сопоставлен **451 исходный экспортируемый тип**. Среди сравниваемых объявлений публичных/protected методов, свойств и доступных accessor, событий, полей, конструкторов, generic constraints, значений enum и параметров по умолчанию удалений/изменений не найдено. + +Сам checker проверен двумя контролями: удаление async-модификатора реализации и недоступного private setter не меняет публичную сигнатуру; контроль с удалённым public setter, другим типом свойства и новым default-параметром обнаружил ровно три изменения и завершился ожидаемым отказом. Исходники, входные pinned blobs и логи сохранены в `api-compatibility` внутри scratch плана; product-код и зависимости не менялись. + +Это синтаксическая проверка объявлений. Она не сопоставляет семантически aliases, base/interface lists, унаследованные/синтезированные члены, attributes или binary ABI и не доказывает runtime-совместимость сама по себе. Результат дополняет общий suite, GUI-сборку, runtime-стенды и независимое source review. + +## Общий review и исправление повторного designer roundtrip + +Независимый reviewer прочитал весь диапазон `f39e8a0…00fb0ad`: 95 файлов (72 GUI, 20 тестового проекта, 3 документа), включая реальные вызывающие окна и границы новых owners. Critical findings нет; найдено одно Important замечание в уже исправляемом кодеке и одно Minor замечание по дублированию file-kind mapping. Других внесённых поведенческих дефектов ревью не выявило. + +Important воспроизведён тестами: неизвестный `--blacklist="/Program Files/lists/hosts.txt"` терял кавычки при следующем посещении дизайнера, а `--blacklist="--port=1443"` мог включить известную настройку port. То же исходно ломалось в базе, но препятствовало заявленному сохранению quoted values. Источник — нормализация inline `=` в пробел и принятие любого slash/dash-leading quoted токена за новую опцию. Реальный CreateNewConfigViewModel повторяет Parse/Build при переключении вкладок. + +Исправление сохраняет `=` у неизвестного inline аргумента, чьё значение само выглядит опцией, включая quoted, целиком quoted и bare inline формы. Пробелы до первого `=` внутри grouped quoted токена отличают путь от опции; пробелы после `=` сохраняют настоящую целиком quoted опцию. Неразрешимая без схемы неоднозначность отдельно записанного имени вида `"--port=1443"` остаётся прежней: для однозначного файла нужно inline `--blacklist="--port=1443"`. Старые unquoted separate boundaries и контроль `-p "--port=1443"` сохранены. + +Добавлен **21 сценарий** с тремя последовательными посещениями дизайнера. Первые 15 показали **11 RED / 4 PASS**; дополнительный контроль целиком quoted/bare inline ownership — **6 RED / 3 PASS** до завершения исправления. Весь codec suite теперь **67/67**, root **1214/1214**, GUI x64 Release **0 warnings/errors**, 11.67 секунды. Это одна fix pass по замечанию общего ревью; повторный reviewer для уже покрытого исправления не запускался. Новая runtime-проверка реального фасада и обновлённая совместная копия рассматриваются отдельно. + +Minor отложен: `ConfigMakerPresetResources.ReplaceFileInText` и `ConfigMakerPresetReferenceEditor.ReplaceFileInText` содержат одинаковое соответствие видов файла. Рабочий путь использует editor, текущее соответствие совпадает. Будущая общая реализация уменьшит риск расхождения при добавлении видов; сейчас дополнительная правка не нужна для устранения наблюдаемого дефекта. + +Решения по границам ревью: интерактивные Add/Move и controls остаются непроверенными; production startup/shell/settings/real backend/components подтверждены только в указанных выше пределах. Унаследованные self-load clearing, живой текущий документ после awaited Save и protocol/direct ordering сохранены согласно требованию parity; их возможные прежние последствия не объявляются исправленными. Security/staging/Update/ZIP/recovery остаются у параллельной сессии. Стоимость этих границ — соответствующие runtime и security риски остаются вне доказанного охвата. + +## Runtime фасада после codec fix и новая совместная копия + +В свежей копии `C:/Users/lumen/Programming/cdpiui-facade-80521fc-20261109` выполнен точный product pin `80521fcfd62ac393c05def42cfe7322a3a728250`. К прежним 17 host-группам добавлены четыре проверки настоящих GraphicDesignerHelper, GoodbyeDPI catalog, моделей и динамической proxy factory. Проверены три повторных Parse/Build посещения для slash/dash/equals путей, quoted/whole-quoted/bare inline ownership, настоящая quoted опция после `-p` и скаляры port/host/secret после реальной фабрики. Codec, фасад и модели совпадают с pin. + +Новые четыре группы не добавляют файловых, UI или внешних операций; используются прежние девять startup/data/catalog/help/storage/export/replacement/shell boundaries. Source checker сверил **1198 tracked файлов** четырёх product roots и разрешил только девять изменений, четыре bootstrap и пустой Secret stub. Новые call paths и сгенерированные root/pin/launch guards проверены исполнителем; это не повторное ревью исправленного product finding. Сборка — **0 warnings/errors**, 82.87 секунды. + +Процесс **39492** завершился с **exit 0**: все **21 PASS**, COMPLETE, без FAIL/stdout/stderr. Три прежних CreateNew входа сохранены побайтно. DLL SHA256: `9273C5C3D990566EFDFB7F622007E234191FCDAC4826637C0E537D5C7E2363C6`. Этот результат проверяет настоящий фасад и модели на UI-потоке; он не является новым интерактивным прогоном editor/ComboBox/dialogs и не закрывает gates15/16. + +Отдельная совместная копия `C:/Users/lumen/Programming/cdpiui-joint-38ec905-20261109` объединяет GUI **`80521fcfd62ac393c05def42cfe7322a3a728250`** с committed security **`38ec905051d9590ac6b36adc5dc4ce6cfdb9e324`**. Security pin имеет документированный suite911/911 и Update publish; текущие cleanup WIP-файлы не включены. Пересечений product-файлов нет, test csproj объединён только дополнительными items. Совместный suite — **1357/1357, 0 failed/skipped**, 49 секунд; GUI — **0 warnings/errors**, 81.08 секунды. Ветки и старые копии не изменены. Это совместимость данной пары, с сохранёнными ограничениями security по durable recovery/cleanup/final restart. + +## App: маршрутизация файлового запуска + +`AppFileActivationHandler` владеет прежним ProcessFiles и whitelist пяти расширений. `AppFileActivationOperations` сохраняет настоящие filesystem/predicate/window/import вызовы. В App остались private forward и store-only композиция; conditional importer, startup/redirect dispatcher, Program, migration lock, settings recovery и security/importer implementations не менялись. + +Сохранены удаление всех двойных кавычек без Trim, debug log до Path.Exists, case-insensitive whitelist, share → task → patch → store и возврат после первого подходящего файла. Массив читается без snapshot. Share ждёт создание окна, активирует его и ждёт SetFileAsync; patch задаёт путь перед активацией; store ждёт создание окна с прежним default activate и запускает SetPackFilePath без ожидания импорта. + +**45 новых сценариев:** 41 targeted и четыре проверки связки реальных handler/activation dispatcher. Проверены guards, приоритеты, null/fault/cancellation, ожидаемые route tasks, изменение следующего элемента массива при reentry, initial file/argv suppression, startup catch и redirected propagation/fallback. Полный suite — **1259/1259, 0 failed/skipped**. GUI x64 Release — **0 warnings/errors**, 45.93 секунды; после него менялись только дополнительные тесты и документация. + +Независимое source review нового диапазона относительно `906b218` не нашло Critical/Important/Minor дефектов. Сопоставлены исходный ProcessFiles, все семь production port методов, App composition, неизменённый conditional callback, dispatcher и реальные endpoint-методы окон. Дополнительные async task frames не меняют проверенные эффекты, контекст, faults/cancellation или fire-and-forget границу. + +App aggregate уменьшился **794 → 754** физических строки (исходно955), activation partial **259 → 215**. Новый handler — **55**, production adapter — **50** строк. Тесты не запускали App/окна/import/update; window ordering, Path.Exists и log source подтверждены компиляцией и независимым source comparison. Реальный production import и security policy не объявляются проверенными; дополнительный inert runtime seam учитывается отдельно. + +## App: runtime связывание и порядок адаптера с инертными целями + +Новая копия `C:/Users/lumen/Programming/cdpiui-appfiles-c16a18a-20261109` закреплена на `c16a18afe72255d9ef19c8b6d9fc815fde492100`. Конструктор настоящего App до InitializeComponent, handler, dispatcher, private ProcessFiles и conditional callback binding сохранены. После InitializeComponent действует прежний безопасный startup cut. Десятая boundary file заменяет лишь низкоуровневые log/exists/factory/activate/conditional invocation targets в AppFileActivationOperations; его await/create/set/activate/fire-and-forget оркестрация остаётся прежней. + +Пять новых групп runtime assertions подтвердили: + +- Настоящие instance/field/delegate bindings и отсутствие eager operations; empty/unsupported/missing paths не вызывают маршрут. +- Share ожидает unsafe inactive factory, затем activate, затем незавершённый SetFileAsync; следующий файл не читается. +- Update задаёт путь перед activate; store ожидает safe factory с прежним default activate=true и возвращается, пока pack import task ещё pending. +- Conditional target ожидается на UI-потоке; отдельно проверены target/method исходного сохранённого callback. Сам private importer не вызван. +- Настоящий private forward и redirected File dispatcher сохраняют fault identity/canceled task и не переходят к следующему файлу после ошибки. + +Window stubs — обычные объекты C#, без WinUI Window. Factory/work gates отменяются/освобождаются в finally, handler completion наблюдается с пределом3секунд даже после раннего assertion failure. Paths — прямые дочерние marker names собственного bin, физических входных пакетов нет. ConfigShare.IsSupported остаётся настоящим safe extension-предикатом; Path.Exists и Logger target в этом стенде подменены и не объявляются реально выполненными. + +Независимое safety/assertion review сверило **1201 tracked файл** четырёх product roots: ровно десять boundary files, пять bootstrap и проверенный пустой Secret stub. Обязательных исправлений не потребовалось. Сборка — **0 warnings/errors**, 65.73 секунды. PID **44836**, exit **0**, все **26 PASS**, COMPLETE, без FAIL/stdout/stderr; прежние три CreateNew входа сохранены побайтно. DLL SHA256: `57584342D4D1ED45EF73F3B9937565053D0630E80DDD28F87C5B79E82055FECC`. + +Это гибридное static/runtime подтверждение retained App composition и оркестрации с инертными целями. Настоящие factory/activation/modality, Path.Exists, полный startup и importer correctness этим не доказаны; native gates15/16 по-прежнему открыты. Совместная копия пока сохраняет более ранний GUI pin80521fc; свежая совместимость текущего App будет проверена на следующем стабильном code freeze. + +## BlockCheck2: состояние сборки ручного пресета + +`BlockCheck2ManualPresetState` владеет результатом manual build, Rebuild, описанием subjects и factory options. Он использует прежний Draft и список manual probe results. Production operations делегирует тому же BlockCheckManualPresetService. Host по-прежнему создаёт настоящий локализованный ManualIssueItem, фильтрует acknowledged keys и публикует прежние уведомления; BuildEvidence, assignment editing, QuickFix и live strategy testing не переносились. + +Сохранены разные порядки пустой/непустой веток, очистка result на прежнем месте Load, deferred overlay с исходными comparers, grouping и culture/path/subject rules. Result назначается до issue callbacks и читается заново после них при ApplyStructuredChange. Ранний session/result/list snapshot, rollback или catch не добавлены. Constructor/backend только сохраняют зависимости; прежние assignment callbacks и публичные коллекции остаются теми же. + +**39 новых сценариев** с реальными Draft/assignment/domain models: update flag/expert state, ordering, overlay/comparers, живые deferred коллекции/current session, options allocation/clamp, grouping/subjects/culture, reentry, partial errors, непустые Profiles в Draft.Groups и прежняя invalid site-list scope ошибка. Проверены сначала отсутствующий owner API RED, затем 36 PASS; после дополнительных coverage cases — **39/39**, полный suite **1298/1298, 0 failed/skipped**. GUI x64 Release — **0 warnings/errors**, 49.24 секунды; после GUI менялись только тесты и документация. + +Независимое source review диапазона от `2d4202d` не нашло внесённых дефектов. Проверены перенесённые тела, result/Load/constructor mappings, настоящий IssueItem с локализацией и acknowledged filter, production Build forward. Public result model — **402 → 319** физических строк (исходно565), новый state — **133**, backend — **18**. Полная связка реального public model/localizer/ack/filter/domain builder ещё не исполнялась на этом этапе; fake ports в unit tests её не заменяют. Следующий отдельный runtime-проход будет использовать настоящий localizer и чистый builder, без вызова live TestStrategyAsync или сети. + +## Runtime настоящей manual result model + +Новая копия C:/Users/lumen/Programming/cdpiui-manualstate-a29b1f1-20261109 закреплена на a29b1f19fe9f22167290106e039e74830c3a7028. Public BlockCheck2ResultViewModel, state, editor, IssueItem, localizer, preset service и writer совпадают с pin. К прежним 26 группам добавлены пять программных проверок на Application DispatcherQueue с настоящей локализацией и чистым builder; источники manual strategy/probe данных подготовлены заранее. + +- Load проверил report/evidence, отсутствие automatic assignments и прежние identities draft/collections/probe-list/service. +- Add/Add/Move/Clear проверены по независимым literal action tokens, stable row objects, indexes/evidence/draft groups и точной последовательности 12 host notifications на каждое редактирование. +- Site и site-list scopes дали настоящий localized MANUAL_SCOPE_OVERLAP с описанными subjects. QuickFix подавил issue key при Rebuild(false); перемещение туда и обратно восстановило исходный key и доказало сброс acknowledgement. +- Во время ManualIssues.Clear при Load(report) подписчик увидел прежний manual result; после него result очищен на прежнем месте. No-session Rebuild(false) сохранил automatic draft. +- Подготовленный completed failure ProbeResult добавлен только в существующий private список, без вызова live tester. Он заменил успешное scan evidence и дал настоящий localized MANUAL_STRATEGY_UNPROVEN; reload очистил тот же список и вернул исходное evidence. + +До исполнения уточнены два ожидания стенда: Move туда-обратно нужен для проверки того же key, а strategy id synthetic result должен быть каноническим для case-sensitive domain summary dictionary. Case-insensitive overlay самого state отдельно проверен unit-тестом. Это уточнения harness, product-код не менялся. + +Независимое safety/assertion review сверило **1205 tracked файлов** четырёх product roots, ровно прежние десять boundary files, шесть bootstrap и пустой Secret stub. Обязательных исправлений не найдено. Сборка — **0 warnings/errors**, 69.67 секунды. PID **35764**, exit **0**: все **31 PASS**, COMPLETE, без FAIL/stdout/stderr. Три прежних CreateNew входа сохранены побайтно; process завершился и post-run source check прошёл. DLL SHA256: D320B404D6DCCB1C85440F314AE88B14D613DDD2BCDE99D30EAD04D09CD1E1A6. + +Новыми manual cases не вызывались live TestStrategyAsync, strategy/probe runners, сеть, компоненты, persistence/history, окна или controls. Site-list path используется как metadata; единственный новый physical predicate проверяет собственный actions-sites.txt, созданный предыдущими группами. Это runtime моделей и domain composition, не интерактивный Add/Move; native gates15/16 остаются открытыми. + +## Совместимость актуального code freeze с security cleanup pin + +Новая копия C:/Users/lumen/Programming/cdpiui-joint-a99d0d0-20261109 объединяет GUI **a29b1f19fe9f22167290106e039e74830c3a7028** и security **a99d0d0c0c433f9878fdfc0b4af7fa4a79bb4c73**, общая база f39e8a0. Security pin имеет документированный suite926/926 и включает bounded no-follow cleanup. Его последующий promotion WIP не копировался. + +Скрипт требует clean worktree и отдельно проверяет отсутствие GUI/test source отличий между текущим docs-only HEAD и явным product pin. Product-пересечений нет; test csproj объединён только добавочными items. Совместный suite — **1456/1456, 0 failed/skipped**, 74 секунды; GUI x64 Release — **0 warnings/errors**, 62.24 секунды. Исходные рабочие ветки и старые snapshots сохранены. Проверка относится к этой паре; durable recovery, handoff, restart, MSI и другие ограничения security-сессии остаются открытыми. + +## Ручной strategy test controller + +Checkpoint 25e1db7042707d752cea35d4cdfb5317fe54eae2 выделяет подготовку аргументов и оркестрацию TestStrategyAsync из public ResultViewModel. Controller получает те же Draft, list и getter session, прежний rebuild callback; operations adapter хранит прежний service и напрямую делегирует прежние методы. Сохранены отсутствие sync session guard, fresh unavailable issue до чтения item, attempts/timeouts/token, ConfigureAwait(true), замена результатов по прежним comparers и чтение Draft.IsAutomatic после всех уведомлений item. + +Сначала тесты дали ожидаемый CS0246 из-за отсутствующего controller. После переноса прошли 32 целевых проверки и полный suite 1330; GUI x64 Release — **0 warnings/errors**, 41.01 секунды. Независимое read-only ревью приняло весь перенос и исходные 32 сценария без замечаний. Затем добавлены пять проверок для пустого, неуспешного, частично успешного и успешного probe, а также изменения списка из observer; финальный suite — **1335/1335, 0 failed/skipped**. Product-код после GUI/review не менялся. Public ResultViewModel: 319 → 268 строк, controller — 87, adapter — 26. + +Явные решения: поздний result после Load по-прежнему применяется к текущему списку и исходному item; отмена принадлежит backend; overlapping tests завершаются без сериализации; observer/rebuild exceptions сохраняют частичные изменения. Это унаследованные свойства и контракт переноса. Цена сохранения — controller не вводит новых гарантий отмены, отбрасывания устаревших результатов или rollback. Live strategy runners, сеть, восстановление компонентов и interactive controls не исполнялись; tests используют управляемые tasks и настоящие EvidenceItem/Draft. + +## Runtime ручного strategy test с инертным backend + +Отдельная копия C:/Users/lumen/Programming/cdpiui-manualtest-25e1db7-20261109 закреплена на 25e1db7042707d752cea35d4cdfb5317fe54eae2. Public model/controller/adapter/evidence/state/editor/IssueItem/localizer/preset builder/writer совпадают с pin. Независимое ревью безопасности и assertions проверило **1208 tracked файлов** четырёх product roots, ровно 11 файлов с подменёнными границами, семь bootstrap и пустой Secret stub, а также compilation inputs. Первые десять границ совпадают с предыдущим принятым стендом. Единственная новая граница — typed delegate вместо создания и запуска runners в service.TestWithCdpiuiAdaptersAsync; при отсутствии hook следует явное исключение. Конструктор и sync GetFullStrategyArguments настоящие. + +Пять новых групп дополнили прежнюю 31: реальные ctor/service/delegate identities и чистый writer; no-session guard до item/token/backend; pending reply с worker thread через настоящий public forward/controller/adapter с проверкой options/token, 11 evidence и 12 host events на DispatcherQueue, реального rebuild/localized unproven issue и буквального draft action; Load во время ожидания с прежними stale-item/current-list/current-session semantics; fault identity, canceled task и обратный порядок завершения двух тестов. Все зарегистрированные tasks/gates наблюдаются и освобождаются в finally с ограничением ожидания, hook сбрасывается. + +Сборка — **0 warnings/errors**, 79.92 секунды. PID **14584**, 08:50:40.3342330Z → 08:50:43.1441970Z, exit **0**: **36 PASS, COMPLETE**, без FAIL/stdout/stderr. Три собственных input сохранены побайтно, post-run source check прошёл, процесс завершился. DLL SHA256: 9A619EEA572D498CCD9B0ED5CF4FE7E69F39488C38D0F935139A344DC11A5371. Это настоящая композиция с управляемой целью backend; реальные service.TestAsync, strategy/probe runners, сеть, компоненты, окна и desktop input не вызывались. Native interactive gates 15/16 остаются открытыми. + +Инвентаризация API обновлена для f39e8a0 → 25e1db7 тем же Roslyn runner: **451 исходный exported type**, 517 → 569 tracked GUI C# файлов, **0 удалённых или изменённых сравниваемых сигнатур**. Положительный и отрицательный controls ранее проверили этот же алгоритм. Как и прежде, это syntax inventory с перечисленными выше исключениями, без доказательства ABI, inheritance или runtime совместимости. + +## Совместимость с security promotion/write/store pin + +Новая копия C:/Users/lumen/Programming/cdpiui-joint-80c17c1-20261109 объединяет GUI **25e1db7042707d752cea35d4cdfb5317fe54eae2** и security **80c17c11be80c708d5985533dee8683781ee8e7f**, база f39e8a0. Этот committed security pin имеет документированный suite 967/967 и включает batch rollback verified promotion, atomic file writes/copies и ограничения Store folder cleanup. Его более поздние незакоммиченные изменения не копировались. + +Полный совместный suite — **1534/1534, 0 failed/skipped**, 75 секунд. GUI x64 Release — **0 warnings/errors**, 68.84 секунды. Применены прежние guards clean worktree, явных pins, отсутствия пересечения product-файлов и только добавочного объединения test project items. Исходные рабочие деревья и предыдущие snapshots сохранены. Это проверка совместимости указанной пары: durable crash journal, общий installation mutex, Store directory promotion, runtime handoff/restart/MSI и остальные открытые границы security-сессии этим не закрываются. + +## Операции с переменными ConfigMaker + +Checkpoint c480fd3cc218526da792ac2c9b3a7b982ae8a584 выделяет создание, редактирование, удаление и вставку ссылки в ConfigMakerVariableActions. Owner получает тот же document и host; публичные Edit/Remove и CreateVariableCommand сохраняют прежний RunReportingErrorsAsync. Реальные editor/Attach/tree/diagnostics/view/localizer endpoints остаются прежними. Новые nullable annotations ограничены явными host adapters; исходный annotation context публичных forwards сохранён. + +После ожидаемого absent-owner CS0246 RED прошли **38 целевых проверок**, полный suite **1373/1373, 0 failed/skipped**, GUI x64 Release — **0 warnings/errors**, 45.29 секунды. Единственное независимое ревью проверило точный diff, новые исходники, фактические document events, callbacks, localized confirmation, error wrapper и XAML command bindings; Critical/Important/Minor замечаний нет. Variables partial сократился с 84 до 36 строк, общий host — с 1158 до 1112, owner — 85 строк. + +Сохранены решения исходного кода: Edit ищет original object после await, но index остаётся прежним при последующих reentrant document events; editor получает текущий текст после этих событий. Create использует текущую коллекцию после диалога, Remove — прежний объект и refresh даже при его отсутствии. Реальный dialog adapter по-прежнему формирует OriginalName после ожидания. Цена сохранения — старые reentry/late-dialog quirks и частичные изменения при исключении не получают нового rollback или cancellation policy. Tests проверяют реальные document/variable events с fake host; actual native dialogs, queued lifecycle, внешний editor/Attach IO, logger/status и визуальное поведение не исполнялись. Их mapping подтверждён исходниками и компиляцией. + +## Runtime операций с переменными через настоящий host + +Новая копия C:/Users/lumen/Programming/cdpiui-variables-c480fd3-20261109 закреплена на c480fd3cc218526da792ac2c9b3a7b982ae8a584. Независимое safety/assertion ревью сверило **1210 tracked файлов** всех четырёх product roots, ровно прежние 11 файлов с подменёнными границами, восемь bootstrap, пустой Secret и pinned build inputs. ConfigMaker host/owner/port/document/variable/command/localizer/tree/diagnostics совпадают с pin. Нового product boundary нет; bootstrap view получил только управляемые Edit и Show targets, которые бросают при отсутствии настройки. + +К прежним 36 группам добавлены пять: идентичность owner/document/collection и отказ от редактирования; pending rename с worker reply и настоящими editor/document events на DispatcherQueue; localized confirmation reject/accept с сохранённым текстом ссылки и настоящим localized CFG004; вставка через курсор/editor helper и read-only guard; настоящий CreateVariableCommand с running notifications, подавлением повторного вызова и Load во время ожидания. После Load результат добавляется тем же объектом в текущую коллекцию до Show callback. + +Pending dialogs освобождаются через null/false, все tasks наблюдаются с ограничением три секунды, actual diagnostics timer останавливается и subscribers снимаются. Первичная ошибка не заменяется cleanup-ошибкой. Callbacks фиксируют thread flags без assertions внутри public error wrapper. Native dialogs и намеренное исполнение logger/status error paths отсутствуют. При неожиданном workflow exception прежний logger остаётся достижимым; проверенные own-executable/data-root guards ограничивают штатный путь данным bin, без универсального обещания для произвольного executable. + +Сборка — **0 warnings/errors**, 63.59 секунды. PID **34304**, 09:20:48.8343188Z → 09:20:52.1280114Z, exit **0**: **41 PASS, COMPLETE**, без FAIL/stdout/stderr. DLL SHA256: 82089C1516BAEB1E5A4BB8E49CAA8908A208F96450D903EB4E8375D9274E4BE9. Post-sourcecheck прошёл, процесс завершился, три входных файла сохранены побайтно. Инвентаризация bin по времени создания показала только эти три input и result log. Это программная проверка настоящих models/commands/editor callbacks с инертным view; native dialogs/controls и gates 15/16 не объявляются проверенными. + +## Run lifecycle BlockCheck2 + +Checkpoint 26297fdf386f7c09f4d058486399d4ac7318937f выделяет StartAsync, Cancel, CTS и решение о final state в BlockCheck2RunController. Host сохраняет State/Targets, options/progress/results, preparation/runner/history endpoints и прежнюю cleanup-политику. Публичный API и отправитель уведомлений сохранены. Prelude остаётся вне try, CTS назначается до Running, final state вычисляется до ожидания history, finally освобождает local CTS и очищает current field только при совпадении. + +После absent-controller CS0246 RED прошли **44 целевые проверки**, полный suite **1417/1417, 0 failed/skipped**, GUI x64 Release — **0 warnings/errors**, 43.98 секунды. Независимое ревью приняло точный перенос, реальные adapters и оставленные host endpoints без Critical/Important/Minor. Общая ViewModel сократилась с 607 до 551 строки, controller — 98 строк. + +Явные унаследованные границы: prelude errors выходят без finally; подготовка и notifications применяются до проверки Success; token cancellation не заменяет backend result; Cancel/history не пересчитывают заранее выбранный final state; catches/finally могут оставлять прежние частичные изменения. Реальная ordinary history IO error по-прежнему поглощается host wrapper с HistorySaveError и Logger — fake-host endpoint fault не доказывает обратного. + +ReferenceEquals защищает CTS нового запуска при reentry из финального события. Старый finally при этом всё ещё завершает общий progress и вызывает cleanup по текущим report/root: он может затронуть estimator и generated root нового запуска. Это прежнее поведение сохранено; unit case доказывает только CTS lifetime, без обещания безопасности production cleanup при таком reentry. Backend, history, Logger, cleanup/deletion и actual-host run composition в unit/review не исполнялись; соответствующие эффекты не объявляются проверенными. + +## Runtime запуска и отмены через настоящий BlockCheck2 host + +Копия C:/Users/lumen/Programming/cdpiui-runlife-26297fd-20261109 закреплена на 26297fdf386f7c09f4d058486399d4ac7318937f. Независимое safety/assertion ревью сверило **1212 tracked файлов**, ровно 13 объявленных файлов с подменёнными границами, девять bootstrap, пустой Secret и build inputs. Прежние 11 границ сохранены. Новые подмены в главном host ограничены settings factory, Prepare/backend/history/Logger targets; SiteLists partial меняет только private cleanup target на recorder. Storage не менялся. Реальные ctor/controller/options/progress/results/state/report builder/serializer и тела history wrapper, CreateSessionRequest, Progress/options/preflight merge сохранены. + +Пять групп дополнили прежнюю 41: ctor/guard/invalid preparation и безопасная запись cleanup-вызова; pending backend, progress на DispatcherQueue, Cancel token и result/session/report; pending history с запретом нового запуска и удержанием CTS, затем сериализация и Completed; синтетический history fault через настоящий catch с HistorySaveError и инертным log target; backend fault/OCE с различными state/error/null и освобождением CTS. Настоящие Prepare, runners/network, settings persistence, history storage, Logger и удаление не вызывались. + +Первая сборка стенда выявила CS8752 в сокращённом new для params; исправлен только тип конструктора в одном bootstrap, исходный RED log сохранён. Исправленная сборка — **0 warnings/errors**, 43.16 секунды. PID **44184**, 09:40:59.7214656Z → 09:41:02.1449988Z, exit **0**: **46 PASS, COMPLETE**, без FAIL/stdout/stderr. DLL SHA256: C89BCAC4EC99452CC9FF82590C4D824BDE2C370E2FEF4C7CFA871824A28C2E95. Post-sourcecheck прошёл, процесс завершился, три входных файла сохранены побайтно. Source текущего product pin после предыдущих unit/GUI/review не менялся. + +Ограничения остаются явными: это composition с инертными targets, не доказательство реального history IO или безопасности generated-root cleanup при reentry. Повторный read-only просмотр Windows в 09:39 UTC показал прежнее UAC-окно ToolsSmokeTest.exe без подтверждённых path/args; inputs не выполнялись. Native gates 15/16 остаются открытыми. + +## Контракты скомпилированной DLL и public CLR flags + +Для дополнительной проверки отдельно собрана pristine база f39e8a0 в C:/Users/lumen/Programming/cdpiui-abi-f39-20261109. Все **1374 tracked файла** репозитория совпали с pin до и после сборки; единственный добавленный source — проверенный пустой Secret stub. SDK 8.0.427, Release x64, **0 warnings/errors**, 57.32 секунды. Приложение не запускалось. Анализатор на System.Reflection.Metadata/PEReader читает DLL как данные и не загружает WinUI. + +Первое сравнение с обычной product DLL 26297fd выявило **16 изменённых metadata shapes**: неявная реализация новых внутренних interfaces добавила Virtual/Final/NewSlot к прежним public getters и двум storage methods. Параметры и типы сохранились, sealed classes остались non-overridable; пользовательская runtime-регрессия этим не установлена. Для сохранения прежней metadata surface добавлены явные private interface forwards к тем же public endpoints. Storage forwards возвращают исходные Tasks непосредственно; getter/setter/cleanup вызываются один раз в прежний момент. + +После исправления 74659b7 прошли **1417/1417, 0 failed/skipped**, GUI — **0 warnings/errors**, 45.44 секунды. Сравнение **452 исходных exported types** показало **0 удалённых или изменённых записанных shapes** и семь добавленных direct internal-interface declarations. SHA256 обычной product DLL: DAB8100F612A9E26DB93BFDA207DBB6CD19BF32E61BE0EE05681A08F5383057B. Она отличается от модифицированной runtime fixture DLL; RED/GREEN snapshots и inventories сохранены. + +Controls проверили одинаковую DLL и положительный пример с прежними recorded shapes, но иным телом методов/временем завершения Task. Этот пример подтверждает именно shape comparison, а не эквивалентность поведения. Отрицательный compiled control дал ожидаемый exit2 и 16 changes; отдельные assertions потребовали обнаружения всех 11 категорий: base, virtual, default, setter, constant, enum, constraint, sealed, удалённый type, protected method и event. Независимое read-only ревью приняло пять продуктовых mapping-исправлений и анализатор без Critical/Important/Minor. + +Объём доказательства ограничен declared public/protected metadata members, прямыми base/interface identities, именованными типами, relevant flags, generic constraints, parameter names и Constant-table defaults/literals. Не сравниваются полный inherited/dependency surface, runtime MethodImpl maps, assembly versions, все attributes/NRT/params/caller-info, attribute-encoded decimal/DateTime defaults, interop layout или marshalling. Это сохранение записанной поверхности данной DLL, не полное доказательство managed/native ABI или отсутствия behavioral regressions. + +## Проверка freeze 74659b7 + +Свежая runtime-копия C:/Users/lumen/Programming/cdpiui-final-74659b7-20261109 сохранила прежние 13 границ, девять bootstrap и 46 групп. Независимое delta/safety review подтвердило 1212 tracked файлов и сохранение всех новых explicit forwards после fixture cuts. Сборка — **0 warnings/errors**, 63.63 секунды; PID 40860, 10:07:17.2076428Z → 10:07:19.5379863Z, exit0, **46 PASS/COMPLETE**, без FAIL/stdout/stderr, post-sourcecheck PASS и три input сохранены. Fixture DLL SHA256: BA46FE35A264C6077AA0DC927CAC2D7CFA598200969C800D944E114AC0D46116. + +Source API inventory f39 → 74659b7: **451 исходный exported type**, 517 → 573 файлов, ноль удалённых/изменённых сравниваемых сигнатур. Новая joint-копия C:/Users/lumen/Programming/cdpiui-joint-ee47716-20261109 объединила GUI74659b74e3d53a0e024bfe6075169901c554f2de и securityee4771675956fe213634675f37579362efb7e0eb с документированным suite980. Результат — **1629/1629, 0 failed/skipped**, 92 секунды; GUI — **0 warnings/errors**, 64.27 секунды. Источники и предыдущие copies не менялись, WIP другой сессии не применялся. + +## Condition draft следующей крупной ViewModel + +Checkpoint e42ac481ab230866bd65ea06ccb7496a52a75c9c выделяет четыре поля черновика условия, validation/preview, reset/add и уведомления из CreateNewConfigViewModel в самостоятельный CreateConfigConditionDraft. Host сохраняет публичные bindings и sender, те же коллекции, Remove/VariableChanged/Logger/Save/Import/Test. Constructor только сохраняет callbacks; реальные helpers/localizer вызываются лениво. + +После absent-owner RED прошли **24 целевые проверки**, полный suite **1441/1441, 0 failed/skipped**, GUI — **0 warnings/errors**, 42.20 секунды. Независимое source review проверило реальные helpers, XAML, forwarding и nullable context без замечаний. Compiled surface: **452 исходных exported types, 0 потерь/изменений, 7 добавленных interface declarations**; normal DLL SHA256 DAFB35EC6A4CCD6B728A4D05FB1712465C79420A3B38633B0F199628BA02552B. + +Сохранены исходные правила: ASCII validator, удаление только обычных пробелов из preview name, whitespace On/Off, raw Add без availability guard/trim/reset и частичные изменения при observer exception. Condition POCO остаётся настоящей моделью; annotations-only GUI context сохранён при подключении к tests. Размер host 1037 → 1001 строк, Variables partial 118 → 74, owner 84 строки. Unit/source checks не объявляют native constructor/flyout/rendering и весь класс завершёнными. + +## Финальные проверки e42ac48 + +Новая копия C:/Users/lumen/Programming/cdpiui-complete-e42ac48-20261109 добавляет пять actual CreateNew condition groups к прежним 46, без новых product boundary cuts. Проверены полный архив **1457 tracked repository files**, **1213 product-root files**, прежние **13 boundary files**, **10 bootstrap** и build inputs; независимое safety/assertion review принято до выполнения. Сборка стенда — **0 warnings/errors**, 59.36 секунды. PID **42532**, 10:26:59.2287230Z → 10:27:01.2864720Z, exit **0**, **51 PASS + COMPLETE**, без FAIL/stdout/stderr; post-sourcecheck PASS, процесс завершился, три входных файла сохранены побайтно. Fixture DLL SHA256: 814BB17DAF15F1B930C1FFCAFB472DD11C7F13325D92FFB4697EFD0AF1AE0733. + +В этом стенде реально проверены constructor CreateNew, condition owner, helpers/Core formatter, localizer, forwarding/host sender, reset/Add/reentry/observer exceptions. View только записывает SetExitAsk; остальные view методы запрещены. Native controls/flyout, Save/Import/Test/Logger и внешние endpoints не выполнялись. Все 51 группы сохраняют ранее оговорённые инертные границы. + +Source inventory f39 → e42: **451 исходный exported type**, **517 → 574 GUI C# files**, ноль удалённых/изменённых сравниваемых сигнатур. Compiled normal DLL e42 против pristine f39: **452 исходных exported types**, ноль удалённых/изменённых recorded shapes, **семь добавленных internal-interface declarations**. Методы сравнения имеют разные покрытия; ограничения metadata/ABI, перечисленные выше, сохраняются. + +Совместная копия C:/Users/lumen/Programming/cdpiui-joint-e42-ee47716-20261109 использует GUI **e42ac481ab230866bd65ea06ccb7496a52a75c9c** и committed security **ee4771675956fe213634675f37579362efb7e0eb**. Итог — **1653/1653, 0 failed/skipped**, 38 секунд; GUI — **0 warnings/errors**, 62.55 секунды. Незакоммиченная работа другой сессии не включена. Новый product-код после e42 не менялся; итоговая [приёмочная сводка](DECOMPOSITION-ACCEPTANCE.ru.md) содержит карту владельцев, принятые решения и оставшийся backlog. Native gates 15/16 и весь аудит остаются открытыми. + +## Возобновление без дедлайна: test session CreateNewConfig + +По новому прямому запросу пользователя продолжена безопасная автономная работа без прежнего временного ограничения. Историческая приёмочная сводка e42 не переписывается под новые результаты. + +Checkpoint96c2cfe выделяет running/current-id, button text/glyph, подписку и start/stop/queued state из CreateNewConfigViewModel.Testing в CreateConfigTestSession. Узкий CreateConfigComponentTestTasks сохраняет ленивые обращения к прежнему manager. Публичные host getters/private setters, XAML/leave-page вызовы и отправитель PropertyChanged сохранены. Начальный текст присваивается без события в прежней точке constructor. + +После absent-owner RED прошли33целевых теста, полный suite1474/1474 (0failed/skipped,9s), GUI x64 —0warnings/errors41.72s. Sourceinventory451originalexportedtypes/517->577files/0removedchanged; compiled452/0+7прежнихinterfaceadds, normalDLL E9407FAB802C6663440612F3814362708505172975838C53BFB7BE41598A8EEC. Независимый свежий reviewer не обнаружил Critical/Important. Два Minor относятся к узкому unit proof: флаг running не утверждается внутри первого subscription hook, а Stop с CompletedTask не отличает fire-and-forget от синхронного join. Они отложены в managed tests; следующий запланированный actual-host этап дополнит эти проверки на реальном adapter/host. + +Сохранены исходные after-await/current-id/argument-order правила, case-sensitive очередь, подписка после естественного выхода, пустой/null ID, частичные состояния при fault/reentry и отсутствие ожидания Run/leave-page Stop Tasks. Manager singleton стабилен и уже инициализирован первым unsubscribe; его последующее чтение внутри adapter не дало наблюдаемой разницы. Новые restore/locks/rollback/cancellation guards не вводились. Цена — прежние частичные и отложенные ошибки остаются. Host сократился1001->929 (база1037), Testing118->24, owner129строк. + +Actual constructor/command/dispatcher composition на новом pin, native15/16 и настоящие backend/DB/locale/fileeffects пока не доказаны этим этапом. Подготовка следующего безопасного стенда выявила реальные locale/DB/script пути даже при тестовом CreateConfig; они будут инертными границами стенда, без изменения production поведения. + +## Actual-host проверка test session на 96c2cfe + +Новая копия C:/Users/lumen/Programming/cdpiui-createtest-96c2cfe-20261109 сохранила прежние 51 группы и добавила пять. Подменены 15 файлов: прежние 13 границ, четыре low-level manager targets в новом adapter и два callback targets подготовки/форматирования в constructor. Реальные owner, adapter bodies, AsyncRelayCommand, публичные host forwards и DispatcherQueue сохранены; неподдерживаемые fixture IDs проходят исходный ранний выход designer conversion. Locale/DB/unsafe script endpoints не исполняются. + +Полная source/build-input сверка прошла для 1462 tracked repository files, включая 1216 файлов четырёх продуктовых проектов; 11 bootstrap и пустой Secret проверены отдельно. Сборка стенда — 0 warnings/errors, 69.69 секунды. До запуска независимый reviewer принял точные cuts, call paths, assertions и границы очистки. EXE asInvoker/uiAccess=false SHA256 E17175E97D82383FC1BCE40273E5FA8418B15410CBC792B5AD5ED762678085EF; fixture DLL E29FF54F35B2480BB92935733637699B0A8968EE0F6961882D651B5EEFC1375E, отдельно от normal product E9407F…. + +PID 5764, 12:59:28.7341308Z → 12:59:30.9999152Z, exit 0: 56 PASS + COMPLETE, без FAIL/stdout/stderr. Post-sourcecheck прошёл, процесс завершился. Три входных файла после всех групп побайтно совпали с исходными UTF-8 contents, hash snapshot сохранён. Новые группы проверили реальную команду/ожидание stop, running до первой remove/add, текущую подготовку после await, отсутствие ожидания run, host sender/поток/порядок уведомлений, background queue, late old-id/natural-exit/resubscribe, StopTestRun с отдельно наблюдаемым faulted Task и частичные состояния command fault/null config. + +Пределы нового runtime proof: отсутствие уведомления во время constructor подтверждается исходником/unit, observer runtime прикреплён после constructor. Переключение ID между enqueue и обработкой проверено managed owner test; actual-host группа проверяет late old-id, пришедший после смены ID. Непредусмотренная ошибка tracked task может прервать очистку после освобождения всех gates; в таком случае собственный процесс завершает проверку с ошибкой, следующие группы не стартуют. Это не общее доказательство cleanup на произвольной ошибке. Настоящие компоненты/IPC/БД/locale/formatter, native15/16 и production startup остаются непроверенными. + +Новая совместная копия C:/Users/lumen/Programming/cdpiui-joint-96-ee47716-20261109: GUI 96c2cfe782b329354b19a90e9129fa2b8d0bc852 + committed security ee4771675956fe213634675f37579362efb7e0eb. Итог — 1686/1686, 0 failed/skipped, 38 секунд; GUI — 0 warnings/errors, 57.16 секунды. Старые copies и логи сохранены, чужой WIP не включён. + +## Состояние graphic designer CreateNewConfig + +Checkpoint cdf3bdc выделяет loaded-component cache, additional settings, поиск/изменение model values, parse/build orchestration в CreateConfigGraphicDesigner. Тонкий backend вызывает прежние конкретные фабрики/NoDPI DB/XML/helper endpoints. Коллекции остаются теми же; host сохраняет tab/visibility/view sequence и точные чтения/присваивания EditorText. Public AdditionalSettings пересылает уведомления с прежним host sender. Конструкторы не вызывают backend. + +После absent-API RED прошли 34 целевых теста, полный suite 1508/1508 (0 failed/skipped, 10 s), GUI — 0 warnings/errors, 38.02 s. Source inventory: 451 original exported type, 517 → 580 файлов, ноль удалённых/изменённых сравниваемых сигнатур. Compiled inventory: 452 original exported types, ноль потерь/изменений, семь прежних interface additions. Normal DLL SHA256 D3E078495398F2C896D0F37AE9B72B07F74FFC949FF35C990404AC0B53E825B9. + +Независимый свежий review подтвердил фактические XAML/handler/model/helper mappings без Critical/Important. Отложен один Minor: KnownLoad theory сравнивает заданные самим тестом значения и число callbacks; точные dispatch calls уже проверяются соседними тестами. Сохранены case-sensitive GUID/ID, late mapped-id после callback, missing-annotation retry, first-match precedence, реальные grouping setters и прежние partial/reentrant/error/null policies. Codec и UI-политики не переписывались. Цена сохранения — старые quirks остаются; новые guards/rollback/dirty policy не введены. + +Host сократился 929 → 858 строк (первоначально 1037), GraphicDesigner partial 135 → 61, owner 109 строк. Actual-host/commands/view composition нового pin, настоящий NoDPI DB/XML, native15/16 и визуальное поведение TabView остаются отдельными gates. + +## Actual-host проверка designer state на cdf3bdc + +Новая копия C:/Users/lumen/Programming/cdpiui-designer-cdf3bdc-20261109 проверена по 1466 tracked файлам всего архива, включая 1219 файлов четырёх продуктовых проектов. Ровно 16 файлов с подменами: прежние 15 и три NoDPI target substitutions в новом backend. Двенадцать bootstrap/пустой Secret/входы сборки проверены отдельно, старые десять sidecar файлов побайтно сохранены. Сборка — 0 warnings/errors, 73.28 s; независимое safety/assertion review принято до первого запуска. EXE asInvoker/uiAccess=false, E17175E97D82383FC1BCE40273E5FA8418B15410CBC792B5AD5ED762678085EF; fixture DLL D32996BFF216FD32FFCC82A707FED143B21AA4431AB4A69E090F17C1DB96692A, отдельно от normal D3E078…. + +PID 33316, 13:25:40.5160465Z → 13:25:42.7032211Z, exit 0: 61 PASS + COMPLETE, без FAIL/stdout/stderr. Post-sourcecheck PASS, процесс завершился. После всей последовательности три входных файла отдельно сверены с исходными literal UTF-8 bytes; snapshot hashes сохранён. + +Пять новых групп исполнили реальный host/owner/backend/collections, AdditionalSettings forwarding и синхронные ошибки/reentry, Goodbye factory и -p/port parse-build, три RelayCommands и настоящие grouping/model setters, чтение текущего EditorText после callback записи, unsupported visibility/convert guards, NoDPI path/коллекции/retry/cache и частичное состояние при контролируемой ошибке loader. View задаёт состояние вкладки и записывает вызовы; настоящие TabView/native controls не исполняются. + +Один Minor оставлен как предел proof: Spoof группа проверяет непустые модели, текущий selected ID и live editor/guard; уникальный Spoof option не утверждается. Точный вызов Spoof factory проверен исходниками backend, другие managed tests фиксируют dispatch; runtime-группа отдельно не различает ошибочную подмену фабрики. Уведомления во время constructor покрыты source/unit, поскольку runtime observer подключается позже. NoDPI DB/filesystem/XML, реальный formatter/test manager, deployment и native15/16 остаются вне выполнения. Эти ограничения не превращены в зелёные gates. + +Совместная копия C:/Users/lumen/Programming/cdpiui-joint-cdf-ee47716-20261109 использует GUI cdf3bdc91c35d473128caba39fc1ae6672ef0152 и committed security ee4771675956fe213634675f37579362efb7e0eb. Итог — 1720/1720, 0 failed/skipped, 37 s; GUI — 0 warnings/errors, 56.35 s. Чужой WIP не включён, старые copies сохранены. + +## Выбор компонента и доступность команд CreateNewConfig + +Checkpoint cbd16ad выделяет SelectedComponent, DisplayName, три связанных visibility flags и прежнюю последовательность переключения view/dirty/audit в CreateConfigComponentSelection. Семь ленивых callbacks не исполняются при создании. Публичные типы, private setters, host sender и приватный CheckViewType для Navigation сохранены; поддержки computed-property notifications, новых guards/trim/ID validation или rollback не добавлено. + +Absent-owner/model-source REDCS0246, 34 целевых теста GREEN; полный suite 1542/1542 (0 failed/skipped, 9 s), GUI x64 Release 0 warnings/errors, 44.16 s. Source inventory: 451 original types, 517 → 581 GUI C# файлов, ноль потерь сравниваемых сигнатур. Compiled: 452 original exported types, ноль removed/changed recorded shapes, семь прежних additions. Normal DLL SHA256 3F38926DAF7C4EBB9220D7DE6C1CD218B618CED0049F092BAA28A1B90DC2D1D2. Host 858 → 818, main partial 299 → 259, owner 103 строки. + +Независимый fresh review — ACCEPT, Critical 0 / Important 0. Minor: теория editor values использует отдельный fixture на строку и сама не ловит кэширование после первого чтения; managed polish отложен, следующий actual-host gate проверит повторные запросы на одном экземпляре. Constructor observer подключается позже, поэтому отсутствие ctor notifications подтверждается исходником, а trace подтверждает ноль вызовов callbacks. Сохранены reference identity, null-name normalization, distinction null selected object/null ID, shortcircuit editor reads, whitespace, исходные reentry/частичные ошибки и Save-then-Test audit. Actual host/commands runtime нового pin, реальные контролы/IO и native15/16 пока остаются отдельными gates. + +## Actual-host проверка выбора компонента на cbd16ad + +Новая короткая копия C:/Users/lumen/Programming/cdpiui-select-cbd16ad-20261109: 1468 tracked repository files, из них 1220 файлов четырёх проектов, ровно 16 прежних boundary files, 13 bootstraps и проверенный пустой Secret. Все 11 прежних sidecar сценариев побайтно сохранены. Build 0 warnings/errors, 122.24 s. Независимый safety/assertion reviewer проверил архив, полный состав сборки, те же cuts, отсутствие reparse paths, asInvoker/uiAccess=false и текущий nonadmin token до первого запуска. EXE SHA E17175E97D82383FC1BCE40273E5FA8418B15410CBC792B5AD5ED762678085EF, fixture DLL 0ED58C4E2EA8B5083C009736DBA8A8A9E76DD5319C5863BBB68FB393F93D2C7E, отдельно от normal 3F38926D…. + +PID 47540, 13:55:16.6378597Z → 13:55:21.2333556Z, exit 0: 66 PASS + COMPLETE, без FAIL/stdout/stderr, post-sourcecheck PASS, процесс завершился. Внешняя проверка после всех групп подтвердила literal UTF-8 bytes трёх входных файлов; свежий hash snapshot сохранён. Новые группы исполнили реальный coordinator/host/две команды CanExecute, живое чтение редактора, shortcircuit/whitespace/null-ID/reentry, точный единый trace supported/unsupported/null, sender и частичные состояния при property/dirty/audit/editor faults. Commands не запускались, test session оставалась cold. + +Minor managed live-read theory остаётся отложенным как отдельный unit polish, но тот же риск покрыт actual-host многократным true→false→true запросом обеих команд на одном экземпляре. Reentry assertions фиксируют выбранные suffix/count/final-state, не весь вложенный trace. Constructor no-event, приватный Navigation route и настоящие native events/controls/IO остаются source-only либо вне runtime scope. Native15/16 этим не закрыты. + +Свежий совместный срез C:/Users/lumen/Programming/cdpiui-joint-cbd-ee47716-20261109: GUI cbd16ad67c61693e6f8e903dd6584bcb683b428b + committed security ee4771675956fe213634675f37579362efb7e0eb. 1754/1754, 0 failed/skipped, 1 m 41 s; GUI 0 warnings/errors, 88.39 s. Более долгие параллельные сборки затрагивали разные копии; source pin неизменён. Чужой WIP и старые copies сохранены. + +## Панель диагностики ConfigMaker + +Checkpoint 36b9e23 выделяет реальную валидацию и reference diagnostics, публикацию строк и локализованные счётчики в ConfigMakerDiagnostics. В host остаются прежняя ObservableCollection, factory с исходным Source→SeverityText→Description, таймер/debounce и приватные entrypoints. Generic type разрешает тестировать production owner с явной проекцией строки без WinUI stubs; настоящая модель с Brush не переписывается. + +37 новых целевых случаев после отсутствующего owner RED; полный suite 1579/1579, 0 failed/skipped, 15 s; GUI x64 Release 0 warnings/errors, 59.12 s. Source inventory 451 исходный type, 517→582 файлов, 0 removed/changed compared signatures; compiled 452/0+7 прежних additions. Normal DLL SHA256 AE0584134762DF2A9DFF9B08413B1BACF22D846ECDC0CA91A2DA6C648B408666. ConfigMaker host 1117→1075, Diagnostics partial 96→48, owner 90 строк; main увеличился на шесть строк constructor wiring. + +Независимый fresh review — ACCEPT, 0 Critical/Important. Minor: unit test KNOWN может зависеть от наличия одноимённой environment variable; managed polish отложен, actual-host следующий gate использует уникальный marker с проверкой только присутствия и последующим rename. Исходник подтверждает ту же коллекцию переменных. Все старые input/callback/notification order, reentry и partial exceptions сохранены; несколько listeners коллекции по-прежнему включают стандартный reentrancy guard. Внутренние setters owner нужны для прежних private setters host и не расширяют exported API. Actual host sender/real row/timer entrypoint нового pin проверяются отдельно; native visuals/Brush/automatic timer/external IO не доказаны этим unit/source/metadata этапом. + +## Actual-host проверка диагностики на 36b9e23 + +Новая копия C:/Users/lumen/Programming/cdpiui-diag-36b9e23-20261109 сверена по 1470 tracked repository files, включая 1221 файл четырёх проектов. Те же 16 boundary files, все 12 прежних sidecar файлов побайтно сохранены, 14 bootstraps и generated empty Secret проверены отдельно. Build 0 warnings/errors, 73.62 s; независимый safety review принят до запуска. EXE asInvoker/uiAccess=false/nonadmin, SHA E17175E97D82383FC1BCE40273E5FA8418B15410CBC792B5AD5ED762678085EF; fixture DLL E9618769A4E6A4939B818AE235B8023DB1D2D93A0BA5A55552008EDF64FCB9F3, отдельно от normal AE058413…. + +PID 38944, 14:07:50.0600669Z → 14:07:52.4322586Z, exit 0: 71 PASS + COMPLETE, без FAIL/stdout/stderr. Post-sourcecheck PASS, процесс завершился. Внешняя literal UTF-8 byte сверка трёх входных файлов после всех групп прошла; fresh hash snapshot сохранён. Пять новых групп проверили настоящий generic owner, host, UI row factory, validators/localizer, текущие inputs/collections, sender/order/equality/reentry/partial faults и прямой вход DiagnosticsTimer_Tick. После каждого fixture сняты подписки/обработчики, CancelBackgroundWork остановил его таймер. + +Уникальный marker отсутствовал в окружении по presence-only guard; добавление переменной после constructor и CFG004 после rename закрыли риск unit KNOWN на интеграционном уровне. Сам unit polish остаётся отложенным. Прямой вызов Tick не доказывает автоматическую доставку, event subscription или IsRunning после Stop; эти binding/Stoporder части проверены исходником. Nested reentry assertions фиксируют final states/counts, не весь trace. Реальные localized strings сравниваются через тот же localizer: проверяется wiring, не качество перевода. Constructor no-event, визуальная Brush/контролы/native15/16, реальное IO и production startup этим не закрыты. + +Новый совместный срез C:/Users/lumen/Programming/cdpiui-joint-diag-ee47716-20261109: GUI 36b9e23cc396de2bc1c15b2bc5408d587fbd58a5 + committed security ee4771675956fe213634675f37579362efb7e0eb. 1791/1791, 0 failed/skipped, 1 m 16 s; GUI 0 warnings/errors, 65.51 s. Чужие файлы и старые evidence/copies сохранены. + +## Расчёт размеров панелей ConfigMakerUserControl + +Checkpoint c0ed350 выделяет UpdateLayoutBounds, флаги initialization/updating и saved editor height в ConfigMakerPanelLayoutController. Отдельный ConfigMakerPanelLayoutView хранит девять ленивых getters к настоящим XAML elements/columns/row; owner создаётся до ViewModel/InitializeComponent без чтения controls. Host сохраняет show-hide/tab/event методы, точки capture/invalidate, публичные flags и приватный forward. Нового host partial/interface нет. Не введены восстановление ширины, NaN normalization, rollback или новые guards. + +39 целевых тестов после отсутствующего owner/port RED; полный suite 1618/1618, 0 failed/skipped, 13 s; GUI x64 Release 0 warnings/errors, 49.86 s. Source inventory 451 original type, 517→585 файлов, 0 removed/changed compared signatures; compiled 452/0+7 прежних additions. Normal DLL SHA256 F66DB84B5F89FFCD2488AD00FB9BA6A1767282851A6478248E7341C5E0075A99. UI control 899→828, Layout partial 233→158, main 240→244, owner95/port22/adapter41 строк. + +Fresh review — ACCEPT, 0 Critical/Important. Minor: unit fixtures задают всем разделителям12, поэтому не ловят замену FilesSizerWidth этим литералом; actual-adapter gate задаёт11/17/23 и проверяет все вклады при видимой панели. Managed polish отложен. Источник подтверждает fixed XAML targets без deferred/replacement path; будущая динамическая перепривязка field потребует отдельного review receiver timing. Fake setter after-store exception покрывает соответствующий callback stage, не все native DP validations. Actual adapter на standalone elements, полный control constructor/ранние XAML events, визуальное resize/native15/16 ещё отдельно. Старые quirks и частичные состояния сохранены намеренно. + +## Проверка layout adapter на настоящих standalone WinUI elements + +Новый стенд C:/Users/lumen/Programming/cdpiui-layout-c0ed350-20261109 использует точный product pin c0ed350943bb3d077c5fa85ab84a4e11ded5176d. Проверены 1474 tracked repository files, включая 1224 файла четырёх проектов, те же 16 cuts и 15 bootstraps с пустым Secret; все 13 старых case sidecars побайтно сохранены. Build 0 warnings/errors, 110.37 s. Независимый prelaunch review проверил source/archive/inputs/manifest/asInvoker/uiAccess=false/nonelevated/no reparse/fresh paths. EXE SHA E17175E97D82383FC1BCE40273E5FA8418B15410CBC792B5AD5ED762678085EF; fixture DLL 0E6F8B9DEDCEC38D1F3A793D4643B0CD1CE05A2B69C973262641203CA46145DE, отдельно от normal F66DB84B…. + +PID 41396, 14:20:08.1726222Z → 14:20:12.0142052Z, exit 0: 76 PASS + COMPLETE, без FAIL/stdout/stderr, post-sourcecheck PASS, процесс завершился. После всех групп три входных файла сверены с literal UTF-8 bytes, fresh hash snapshot сохранён. Standalone Grid получил положительные ActualWidth/ActualHeight после реальных Measure/Arrange/UpdateLayout; dimensions не подменялись. Пять новых групп исполнили production adapter/controller с настоящими Grid/ColumnDefinition/RowDefinition: девять lazy mappings, visibility, корректные width/height targets, splitters11/17/23, cap/clamp, saved/current height, callback-selected target, reentry и controlled getter fault перед Width с уже присвоенным MaxWidth/повторной инициализацией. + +Minor splitter-constant риска из unit tests закрыт интеграционно: при видимой files панели проверены max472/900 и editor width582/732. Managed polish остаётся отложенным. Runtime использовал допустимые UI property values; отказ native DP на invalid value не проверялся. Width floor360 покрыт managed tests, height floor180 — также actual adapter. Полный ConfigMakerUserControl/ранние XAML SizeChanged, перетаскивание, native15/16 и визуальное отображение остаются отдельными gates. + +Свежая совместная копия C:/Users/lumen/Programming/cdpiui-joint-lay-ee47716-20261109: GUI c0ed350 + committed security ee4771675956fe213634675f37579362efb7e0eb, без чужого WIP. 1830/1830, 0 failed/skipped, 1 m 31 s; GUI 0 warnings/errors, 111.25 s. Все старые copies/evidence сохранены. + +## Lifecycle закрытия окна App + +Checkpoint 73d92a6 выделяет cleanup и post-cleanup dispatch из Window_ClosedHandler в AppWindowCloseCoordinator. WinUI adapter сохраняет исходные backend calls, migration predicate, Low queue и callbacks текущего App. Host оставляет Window/e.Handled guards/private forward и event detach в прежнем порядке. Список OpenWindows тот же, private setter приложения после initialization не используется. Реальные position/modal/migration/store/Prepare/ExitIfIdle implementations не меняются. + +Absent owner/port RED, 33 целевых случая GREEN; полный suite 1651/1651, 0 failed/skipped, 15 s; GUI x64 Release 0 warnings/errors, 55.99 s. Source inventory 451 original type, 517→588 файлов, 0 removed/changed compared signatures; compiled 452/0+7 прежних additions. Normal DLL SHA256 0411722957B976B5F3D797BE918179C034D5EA405F47577C2D800C68C7437D19. App 754→702, Windows partial190→133/xaml172→177, coordinator61/adapter41/port21 строк. + +Fresh review — ACCEPT, 0 Critical/Important. Minor: управляемые fake operations теряют window argument, поэтому aggregate nested-close assertions не ловят перестановку outer/nested receiver; source проходит локальное правильное окно, следующий actual-composition gate запишет два разных window identities. Unit polish отложен. Enqueue wrapper меняет delegate identity/stack, но target остаётся тем же ExitIfIdle, сравнения/отписки по этой identity нет. Сохранены captured dispatcher/migration, live post-cleanup Count, shortcircuit Store, fire-and-forget Prepare и все прежние partial finally/logger failures. Actual Closed delivery, отписки/Low callback и реальные backend effects не исполнены unit tests; их scope в следующем gate будет явно ограничен инертными endpoints. + +## Actual composition закрытия окна App + +Свежая копия C:/Users/lumen/Programming/cdpiui-close-73d92a6-20261109 прошла полную сверку 1478 tracked files, включая 1227 файлов четырёх проектов. Ровно 17 cuts: прежние16, дополнительный lowlevel AppWindowCloseOperations и два расширения существующего App cut; 16 bootstraps/пустой Secret, 14 старых case sidecars побайтно сохранены. Build0 warnings/errors90.60s; независимый prelaunch review проверил все inputs/manifest/no reparse/medium nonadmin token/fresh outputs. EXE SHA E17175E97D82383FC1BCE40273E5FA8418B15410CBC792B5AD5ED762678085EF; fixture DLL B25A3AFB0E8F9E070907B39DAD47853D696ECCA7295DA8E771B333AE7C3E3943, отдельно от normal04117229…. + +PID49108, 14:37:40.6481697Z→14:37:43.9617754Z, exit0:81 PASS+COMPLETE, без FAIL/stdout/stderr, post-sourcecheck PASS, процесс завершился. После всех групп три входных файла совпали с literal UTF-8 bytes; fresh hash snapshot сохранён. Настоящий App ctor/owner/adapter/list/callback targets и две принадлежащие стенду неактивированные Window участвовали в точных window-specific nested traces, реальный DispatcherQueue получил source priorityLow и исполнил callbacks на UI-потоке. Проверены неправильный sender/private guard, basic predicate, controlled migration/rejection/Prepare tasks/Save logger/Forget exception. + +Unit Minor receiver identity закрыт интеграционно для save/detach/release/forget двух разных окон; managed polish отложен. Окна не регистрировались/активировались/закрывались вручную, ссылки держались до завершения собственного процесса. Настоящий Closed/e.Handled, эффективность отписки ранее подписанных handlers, Welcome-id true, position/settings/modal/migration/Prepare/ExitIfIdle policy остаются source-only либо вне исполнения: соответствующие endpoints инертны. Window origin labels callback относятся к instrumentation, не к нативному событию. Barriers/gates описывают normal cleanup, не глобальную native cleanup гарантию при неожиданном synchronous block; процесс вышел0, поэтому собственные ресурсы завершены. + +Joint C:/Users/lumen/Programming/cdpiui-joint-cls-ee47716-20261109: GUI73d92a6+committed securityee4771675956fe213634675f37579362efb7e0eb,1863/1863,0failed/skipped1m28s, GUI0warnings/errors92.84s. Чужие worktrees/WIP не затронуты. На C осталось около2.36GB; F проверен как локальный NTFS с54GB свободного места. Следующие новые проверочные копии будут на F, исторические копии/логи не перемещаются и не удаляются. + +## Site-list workflow BlockCheck2 + +Checkpoint 214b4b3 выделяет load/cache/error, обработку custom list, выбор и счётчики в BlockCheck2SiteListController. Production использует настоящий BlockCheck2SiteListItem через тонкий backend. Две исходные ObservableCollection, host sender/четыре notification names, generated root/preparation/cleanup/request остаются прежними. Item и Storage не изменены для подключения unit tests; explicit generic row projection позволяет проверить orchestration без WinUI/DB/файлов. + +После исправления синтаксиса нового test setup наблюдался целевой absent-owner/port REDCS0246, затем32focused GREEN. Полный suite1683/1683,0failed/skipped16s; GUI x64 Release0warnings/errors51.20s. Source inventory451 original type,517→591файл/0removedchanged; compiled452/0+7прежних additions. NormalDLL SHA256 BD9ABF77A3A24E95B532CF6754BBEA432ED2D5AE607369463F2F83EA565DAE76. Host555→426, SiteLists215→82/main231→235, owner133/backend26/port24строки. + +Fresh review ACCEPT0Critical/Important, два Minor отложены: unit Write.Content не утверждается напрямую; при гипотетической сериализации unit gate waits могут зависнуть до внешнего timeout. Следующий bounded actual-host стенд проверит точный нормализованный Write.Content и освобождает все собственные gates в finally с3s waits. Сохранены prelude outside try, lazy filter/sort после Clear на mutable definitions, case-sensitive exclude, текущий root, captured custom item/path/token before await, late collection/root, отсутствие дополнительной cancellation/reselection/serialization и прежние partial failures/self-clear/checked Sum. Async state-machine/stack переместились в owner, compiler attributes не входят в объявленный ABI scope; reflection consumers в исходниках не найдены. Реальные host/backend/model/task/UI proofs следующего pin, реальные IO/DB/cleanup и native15/16 остаются отдельными границами. + +## Actual site-list composition на F + +Стенд F:/cdpiui-verify/cdpiui-sites-214b4b3-20261109 сверяет1482tracked repository files, из них1230 четырёх проектов,18cuts/17bootstraps/empty Secret;15 прежних case sidecars побайтно сохранены. В новом backend заменены только Load/Legacy/CustomPath/Write. Factory/Normalize/localizer/model/currentroot остаются настоящими. Первый build0/0 108.87s сохранён вместе с DLL1DD65D4… и original sidecar; по prelaunch review три worker completions получили Track/3s/TrySetResult, а legacy sentinel стал существующим actions-insert.txt с ненулевым DomainCount и явным LegacyArguments assertion. Корректирующая сборка в той же новой копии0warnings/errors47.71s, без повторного archivebuilder. Product214b4b3 не менялся. + +Независимый final prelaunch ACCEPT проверил все inputs/исправления/PE/no reparse/локальный NTFS F/medium nonadmin/fresh markers. EXE SHA E17175E97D82383FC1BCE40273E5FA8418B15410CBC792B5AD5ED762678085EF; final fixture DLL C3FDB09704DE9B4E1FC6FC5728E4ADAC4AB2B20D0FCCB76A3D65BC38D4D479FE, отдельно от normal BD9ABF77…. + +PID34040,15:02:04.9067454Z→15:02:10.3901784Z,exit0:86PASS+COMPLETE, без FAIL/stdout/stderr, post-sourcecheck PASS, процесс завершился. Внешнее чтение после всего run подтвердило literal UTF-8 bytes трёх файлов и отсутствие missing/custom markers; fresh hash snapshot сохранён. Пять групп исполнили настоящий Main/closedgeneric/backend/Item: lazy identities; worker-to-UI load/guard/current mutable definitions/sv-SE/filter/cache; real own-file factory/count/options/four host events/selection; Normalize→точный Write.Content/token, controlled completed-canceled-token policy/current root/captured removed custom row; overlap completion order/current roots и error/retry. Все product и worker tasks ограничены3s, gates освобождены/задачи завершены до снятия handlers/context. + +Оба unit Minor риска закрыты отдельной интеграционной проверкой exact normalized write и bounded gate lifecycle; unit polish остаётся отложенным. Empty Text(key) localization branch здесь source-only. Source helper writes/DB/probes/cleanup/native15/16 и реальные cancellation IO effects не исполнялись; factory читала только собственные известные входы и собственный отсутствующий zero-marker, custom rows считались по памяти. Нет обещания глобальной cleanup при неизвестном constructor/synchronous block. + +Joint F:/cdpiui-verify/cdpiui-joint-sites-ee47716-20261109: GUI214b4b3+committed securityee4771675956fe213634675f37579362efb7e0eb,1895/1895,0failed/skipped1m26s,GUI0warnings/errors75.79s. Исторические C: копии/архивы не менялись и не перемещались; новые source archives созданы на F. Весь аудит и открытые native gates этим не закрыты. + +## Нативные проверки документа и ручных назначений — Task53 + +На product214b4b3 закрыты оставшиеся **ограниченные native gates15/16**. Исторические формулировки «native15/16 открыты» выше описывают соответствующий прежний срез. Текущий результат относится к перечисленным ниже действиям в реальных контролах с изолированными backend-операциями. + +В собственной WinUI-копии F:/cdpiui-verify/cdpiui-native2-214b4b3-20261109 через Sky выполнены11наблюдений: загрузка документа с переменной MODE/ресурсом sites; readonly/New no-op; реальный Save dialog cancel; тот же диалог с вводом Native saved fixture и успешным результатом; экспорт через настоящий coordinator в память; реальный New dialog cancel/continue; пустой manual draft; Add for site split; Add for site disorder; Move down split. Add/Move делались только штатными кнопками страницы. Сверены DP/model/document/editor text, исходные коллекции/клонированные rows, public storage Clone+Task.Run, metadata после save, форматная политика export, сохранение/очистка данных после диалогов, реальные assignment identities/order/draft/evidence/action tokens и12hostevents после каждого Add/Move. Видимые editor/list/dialogs подтверждены screenshot/AX-наблюдениями. + +Перед запуском независимое ревью сверило1482repo/1230project inputs,19явных boundary files, все XAML неизменны, один bootstrap+emptySecret. Startup/help/tasks/output/pickers/storageCore/exporter/settings/shell/scan backend инертны. SearchUserControl preferences и ConsoleFontHelper6settings calls также изолированы, сохранив реальные контролы и defaults true/Consolas/16. Неожиданный SettingsManager.Instance выставляет sticky AppContext switch и бросает исключение ДО XML base ctor; switch проверяется Finish и после Application.Start до returnexitcode. Обработчик ошибок ConfigMaker делает общий FAIL вместо реального logger. Это проверочный стенд, не изменение product behavior. + +Сборка75.21s,0warnings/errors. EXEE17175E97D82383FC1BCE40273E5FA8418B15410CBC792B5AD5ED762678085EF(asInvoker/uiAccessfalse), GUI DLL86EC3A2759FFF4A83A578F621DFC540B7D6A05A10BB248976BCE5CE6CF510ED3, Shared15CCF56EF5E7EC0972DAE8DACA755486497BF5B9588B88B684DCBDBBDC1D11BD, CoreE18B0918FE6BEF36347446C68390D6FBF26C148765ACEB87AFA598AD2481783C, AddOns05038F2AAD41F3CC82822A790BA8EE4315E8BEE75BD497CCF628F2027DA7D918. Все пять hashes закреплены в runner. Это fixture DLL, normal product DLL остаётся BD9ABF77…. + +PID36508,15:44:45.2758468Z→15:47:31.5834895Z: **11PASS+COMPLETE,exit0**,0FAIL,пустые stdout/stderr,sourcepostcheckPASS,процесс завершён. Внешнее чтение подтвердило23literalUTF8bytes `native.example.invalid\n`, SHA25670CE5088BE2697D3D75728DEDE2F0DA5DF9FF27BCF9B8525650AC3C141E105F7. Settings/export/custom отсутствуют; в bin появились только собственные input+result log, прежние имена файлов сохранились. Контроль списка не доказывает отсутствие transient IO/перезаписи всех старых bytes, глобальной OS-изоляции нет. AX/log/manifest/fresh retained JSON сохранены в ignored workspace, sourcearchive на F. + +Первый native17cut прогон PID52048 дал11UI PASS/COMPLETE/exit0, но **общий FAIL** по postSettingsabsence: ConsoleFontHelper.Instance из XAML x:Bind создал собственные Settings.xml/bak до UI. Этот результат сохранён как неуспешный; копия/входы/логи/DLL/AX не удалялись и не перезапускались. Следующая новая native2копия добавила font boundary и раннюю no-IO защиту SettingsManager. Две ошибки harness-компиляции, промежуточные сборки и обнаруженные до запуска Search/Logger gaps также сохранены. Ни один из этих helper changes не попал в product tree. + +Проверены собственное Window и реальные dialogs/Frame/Menu/контролы. Production App activation/tray/registration/close persistence, фактические storage/export/autocorrect/настройки/запуск компонентов, report file picker/clipboard/repair/optional designer actions, drag-resize и весь аудит не объявляются проверенными. Для завершённого ограниченного прохода native gates15/16 закрыты; реальные endpoints остаются отдельными интеграционными границами. + +## Итоговая проверка согласованного пакета + +Финальное независимое whole-branch ревью f39e8a0a→1d76cbdb: ACCEPT,0Critical,0Important,3Minor. Product214b4b3 остался без новых изменений. [Карта требований и свидетельств](DECOMPOSITION-REVIEW-MAP.ru.md) содержит физические размеры/owner map/точные pins и ограничения. [Полное приложение решений](DECOMPOSITION-DECISIONS.ru.md) сохраняет все Ruling строки и отложенные Minor, включая отдельные решения по13исключённым reviewer областям. + +Новые Minor: private setters ряда публичных ConfigMaker properties удалены(произвольная reflection CanWrite отличается); null-вызов redirected activation теряет прежний warning при сохранении fallback; Tests README отстаёт от новых Presentation groups/смешивает source-link и WinUI runtime. Публичных C# setters/зависимых privateSetter consumers не найдено, normal WinRT flow не изменился; замечания после проверки baseline отложены, обязательного product fixpass нет. Полной arbitrary reflection/NRT/attributes/interop/ABI гарантии анализаторы не дают. + +Согласованный пакет владельцев и ограниченные native15/16 gates завершены. Весь аудит/глобальная nullable-миграция/все оставшиеся крупные классы/реальные backend endpoints не объявлены завершёнными. Ветка, worktree, журналы и verification copies остаются локально; исходники/ветки не удалялись, force/reset/merge/push/publish не выполнялись. Пользовательский deadline отменён, безопасные технические решения принимались самостоятельно. + + +## Продолжение 55–58: состояние деревьев ConfigMaker + +`ConfigMakerPresetStructure` владеет явными файлами/группами, результатами построения и признаками +доступности. Шесть ленивых зависимостей сохраняют чтение текущей команды, компонента, вложений и реальных +builder/WinUI adapter в прежних точках. Публикация файлов предшествует вычислению групп; оба признака +обновляются до уведомления об узлах групп. Повторный вход и исключение наблюдателя сохраняют исходное +частичное состояние. Публичный host и существующий raw replacement port передают прежние объекты и sender. +Private setters обеих коллекций узлов сохранены. Форматы, настройки и XAML продукта не менялись. + +Добавлено 36 managed-сценариев с RED отсутствующего владельца и дополнительным RED для двух raw port +properties. После GUI-проверки устранены три оставшихся обращения к перенесённым полям. Итог: 36/36, +1719/1719, GUI 0/0; normal DLL SHA256 `07899304940A75B7749A052271874CE3D1A3E141919856D4663EA805F0A5B423`. +Source inventory: 517→592 GUI C# files, 451 исходный exported type; compiled: 452 исходных типа, 0 изменений +записанных shapes, 7 прежних internal-interface additions. PresetStructure partial 118→47 строк, +main 399→407, общий host 1075→1012; новый owner — 124 строки. + +Независимое ревью диапазона 28ceef44→d347c617: 0 Critical, 0 Important, 1 Minor к наблюдаемости unit-теста. +В тесте теперь задана явная структура: раннее уведомление видит false/false, уведомление групп — true/true. +Изменён только тест, checkpoint3ba7d388. Целевые 36/36 и полный suite1719/1719 прошли повторно. +Обычная песочница отклонила 12 прежних AddOns IO-тестов с UnauthorizedAccessException в AppData; +повтор того же набора вне песочницы прошёл 1719/1719, без product-исправлений. + +Actual-host fixture `F:/cdpiui-verify/cdpiui-struct2-d347c61-20261109`: 1231 project inputs/1486 repo files, +те же 18 явных границ изоляции, 18 bootstrap sources. Пять новых групп используют реальный host, owner, +resources, builder/adapter, узлы и UI dispatcher. Ошибочная подготовка одного сценария найдена до запуска; +первая struct-копия сохранена без выполнения. Исправленная struct2 собрана с 0/0, отдельно принята по пяти +SHA256. PID35892, 2026-11-09T21:00:37.1223567Z→21:00:43.3186221Z: 91 PASS/COMPLETE/exit0, пустые streams, +post-source check, завершение процесса и точные байты трёх retained inputs подтверждены. +Новый joint `F:/cdpiui-verify/cdpiui-joint-structure-ee47716-20261109`: 1931/1931 и GUI 0/0. + +Нативный gate57 пройден на новой копии native4/d347c617. Предыдущий native3 завершён exit1 после +незапланированной UI-последовательности до первого планового клика; источник ввода не установлен, +этот запуск остаётся FAIL. По прямому запросу пользователя введена общая исключительная очередь +CDPIUI/lessons для всех UI API, включая чтения и снимки. Оба соседних чата подтвердили паузу до native4. + + +По отдельному запросу пользователя об освобождении C: 37 завершённых проверочных копий перенесены +в `D:/CDPIUI-C-20261109` с SHA256-проверкой и сохранением старых C-путей через junction. Перенесено +10624161841 логических байт; финальное чтение через все37 исходных путей подтвердило контрольные хеши, +проверенных C-дубликатов не осталось. Кэши уже перенесены параллельной сессией в D:/UserCaches; +активные npm _npx оставлены на C. После ошибочной попытки junction для уже пустого старого pip его +физический default path восстановлен без удаления данных; рабочий D-кэш не менялся. На финальной +проверке C: свободно 14,75 GiB, D: 7,51 GiB. Архивы, partial copy и диагностический reparse сохранены; +Git worktrees, прежние NuGet/Gradle links на F и SDK8.0.427 не менялись. + + +Native4 `F:/cdpiui-verify/cdpiui-native4-d347c61-20261109`: тот же product,19 явных границ изоляции, +1231 project inputs/1486 repo files, неизменённые XAML и владельцы. Сборка0/0 за70,03s и отдельное +prelaunch review всех пяти бинарников, bootstrap и точного SHA манифеста. GUI DLL +`E82D1B44B5596044725335F92505249EF5FD33B7D10504BED6B0F50E381104BA`. +PID50036:2026-11-09T21:32:14.1121727Z→21:48:15.6098961Z,11PASS/COMPLETE/exit0/noFAIL, +пустые streams, post-source и pinned manifest checks, Settings/export/custom absence, +ровно два разрешённых новых bin-файла и точные23bytes входа SHA70CE5088… подтверждены. +Пройдены реальные Save/New dialogs, ввод имени и manual Add/Move; private storage core/export/pickers, +settings/startup/tasks остаются инертными. Восстановление снимка после свёрнутого окна/no-monitor +выполнено через свежие Window/AX; неопределённый Add не повторялся, его результат проверен отдельно. +После normal close окно отсутствует и процесс завершён; AX и журналы сохранены. + +UI-очередь передана соседнему CDPIUI-чату для одного файлового прогона; в этой сессии прекращены +все UI API до нового согласования. Продолжаются CLI/source/review. Закрытие продолжения58 подтверждается +отдельным итоговым ревью документов и результатов, без повторения green product checks ради текста. + +Итоговое независимое ревью продолжения28ceef44→3ba7d388 и четырёх документальных файлов принято: +0 Critical,0 Important,1 Minor к границе доказательства. В actual-host обработчике во время публикации +меняются команда и явные группы; компонент задан Zapret2 заранее. Смена компонента в этой точке +проверена managed-тестом и source wiring `() => IsZapret2Component`, но отдельного живого host-перехода +в этом прогоне нет. Дополнительный runtime-case отложен явно; потенциальная цена — будущий ошибочный +кэш компонента может не быть замечен этой actual-host группой. Дефект продукта не обнаружен. +Task58 закрыт после уточнения этой границы. Журнал решений зеркалит111 строк Ruling и17 отложенных Minor; +предыдущие пункты и неуспешные прогоны сохраняют исторические pins. + +## Продолжение 59–61: App idle exit + +После checkpoint2400dee выделен `AppIdleExitController` на product **839cc952**. Он сохраняет реакцию +StoreStateChanged и проверку ExitIfIdle, восемь ленивых портов и прежние private forwards App. Нативные +действия, Logger, список окон, migration flag и опрос фоновых задач остаются в App. Условие выхода, +порядок повторных чтений, игнорирование Task создания и границы warning/fallback не изменены. + +Проверены39новых managed cases (absent-owner CS0246 RED→GREEN), полный suite **1758/1758**, +0failed/skipped12s; normalGUI x64 Release **0warnings/errors52,94s**. Source451/517→593/0потерь +сравниваемых сигнатур, compiled452/0изменений записанных shapes/7прежних interface adds. Обычная DLL +SHA256 `0DD76BD2DFC2E6101E2BB09CCB5FC094541EC2F547E821F3B65E5FB157F4BA1D`. +Immutable source pin совпал с проанализированным precommit source, нормализованным к LF. +Joint exact839cc95+ee47716: **1970/1970** за82s, GUI **0/0** за71,36s; чужое дерево не менялось. + +Actual-host `F:/cdpiui-verify/cdpiui-idle-839cc95-20261110`: **97 PASS + COMPLETE/exit0**. +PID61180, UTC2026-11-10T05:09:45.0171515Z→05:09:49.2267677Z. Сборка0/0 за71,39s, +1232project/1489repo inputs, те же18изолированных source files и19bootstrap sources. Прежние91группа +сохранены, добавлены6групп настоящего App/owner: current-list replacement/real migration/App-bound +callback; working/pending/faulted Task; stopped/current state; warning+retry; sync reentry; exception identities. +Count/migration/private Store forward реальные, Store/GoodCheck/Create/Close/Exit/Warn действия инертны. +Настоящий Store event, PrepareWindow и idle-policy native Exit не запускались; завершение самого стенда +использует реальный Application.Exit. Это не полный production startup или OS/filesystem sandbox. + +Все postchecks PASS:97групп/COMPLETE/noFAIL, exit0/пустые streams, post-source и точные утверждённые +pins, побайтно проверены три входных файла (16,16 и15байт), Settings/export/custom/missing markers отсутствуют, ровно4новых bin-файла, +все прежние имена сохранены, процесс завершён. Проверка имён не доказывает неизменность любых прежних +байт или отсутствие transient IO вне этого ограниченного сценария. GUI fixture DLL SHA256 +`CD9389B6B9DE9F21807F3A3DCCF2AC4FE55A037BE4B7056A1B5D0DF1A33206E4`; source manifest +`124B5B9BD1A495A63C7320F0DFF063CB724CAF7CB1DE2D45D230ECBBAABD6EF7`; runner +`9AF91AFE7FE80920D25664197620B2B9925322FEBCFC8BC1A34A21DD9B37A520`. + +Независимое product/integration review2400dee→839cc952 принято: **0Critical/0Important/0Minor**. +Prelaunch review READY0/0/0 после трёх runner-only уточнений; продукт/бинарники от них не менялись. +После прежнего ожидания пользователь возобновил работу. Peer передал исключительную очередьV4Root, +lessons снял desktop-заявку и сохранил allUIpaused. Root выполнил программный прогон без UI API, +после точного process-finished передал очередьV5peer/native-governance, сам allUIpaused. +Итоговое независимое review60/61 принято:0Critical/0Important/1Minor к формулировке о входах. +Уточнено: это три файла16/16/15байт, а не три байта; продуктовых исправлений не потребовалось. +Первые91PASS совпали с прежними по тексту/порядку, все97уникальны. Task61 закрыт. Старыйb848620 +сохраняет исторический NOT RUN до передачи очереди. Native4/d347 остаётся своим pin. + + +## Продолжение 62–64: BlockCheck2 result selection + +Product `de3d3821e6b2d0f13f49e179af88175f53213476` выделяет состояние и публикацию выбранной стратегии +из BlockCheck2ResultPageViewModel. Пятнадцать свойств, nullable toggle, доступность действий и детали +принадлежат BlockCheck2ResultSelection; host сохраняет публичные entrypoints/private setters и sender. +Семь ленивых портов сохраняют повторные чтения running/manual, захваченный item, текущий Result, +локализацию, порядок CanAddForSiteList/menu/setters и partial state при ошибке. Lifecycle/компоненты не менялись. +Page main432→380строк; сумма4partials874→822, owner179строк. Новыхpartial/XAML/пакетов нет. + +Исходные28managed cases после absent-owner CS0246/CS0234 RED, full1786/1786 безfailed/skipped12s; +normalGUI x64Release0warnings/errors53,93s. Source451/517→594/0comparedchanges, +compiled452/0recordedchanges/7прежних internal-interface adds. Normal GUI DLL SHA256 +`9EBC1DD5C23DBA121C27584CAC999197A104BC67DC9932D9E9FCFAF0E6990E16`. +Immutablepin source совпал с проверенным precommit input, normalizedLF. Joint exactde3+securityEE: +1998/1998 за39s и GUI0/0 за57,54s. Security checkout сохранён чистым/не менялся. + +Свежий product review принял855dbd3→de3:0Critical/0Important/1Minor к тесту nullable reentry. +Test-only `ffa65fc947ce7aec3c1df8b0c2b532287b29713a` закрывает его: observer ManualTestLabel сбрасывает +IsManualTestChecked вnull; метка остаётсяStopTest, glyph перечитывает null и остаётсяE768. Контрольная +мутация с кешированием checkedBeforeLabel дала ожидаемый FAIL; оригинальные bytes source восстановлены +вfinally/SHAпроверены. Это отрицательный контроль теста, а не найденный продуктовый дефект. +После восстановления29focusedGREEN/1787fullGREEN,0failed/skipped11s. GUI/нативный binary не менялись, +повторная GUI-сборка не требовалась. Joint1998 и archive inputs относятся к exactde3 с первыми28тестами. + +Первый F:/cdpiui-verify/cdpiui-selection-de3d382-20261110 собран0/0, но сохранён UNLAUNCHED: +prelaunchreview выявил два недостаточно различающих host-case. В новом selection2 добавлены отрицательный +list-result переход из notification при активной session/runningfalse и проверка action/label внутри menu +с начальным IsTestStrategyEnabled=false. Runner отдельно сверяет все5бинарников передlaunch/послеexit, +четыре sourcepins до/послеchecker/послеrun и conditionalready/lease до первой записи/передlaunch. + +Принятый actual-host `F:/cdpiui-verify/cdpiui-selection2-de3d382-20261110`: **103 PASS + COMPLETE/exit0**, +PID45692, UTC2026-11-10T05:39:53.4500889Z→05:39:57.3058215Z. Сборка0/0 за55,58s, +1233project/1492repo/exact18cuts/20bootstrap sources,97старых+6новых групп. PrelaunchREADY0/0/0. +Реальны Page/owner/Result/session/evidence/listpredicate/Localizer/privateflags/hostsender и setter visibility; +fakeview разрешает SelectedStrategy/Menu, остальные endpoints бросают ошибку. Нет OnLoaded/Unloaded/ +Test/Stop/component/native действий в новых группах. CleanupApplication.Exit и два неактивированныхWindow +относятся к старым97группам. Managedпроверяеттакжеlocalizer/format/culture faults; runtimeневыдаётся +заnativevisual/startup/OSfilesystemproof. XAMLне менялся. + +Все postchecksPASS:103/COMPLETE/exit0/noFAIL/пустые streams/source+pins/три входных файла16/16/15байт/ +Settings-export-custom-missingmarkersabsent/ровно4newbinnames/priornames/processfinished и фактические +SHAвсех5бинарников до/после. GUI fixture SHA256 +`ACC8ECD1B391F8CE73E4B0D765B08BDD1DAB833F3BC1581D5AA10C3B8F652B9D`; source-boundary `host-fixture-manifest.txt` SHA256 +`36A528178CB8AEF98C1A97CBB6DE0AA3564312B7505A6A4501863DF7CAE70F4F`; runner +`798B3F99E45CE43E210E84290616704056BF3F1CEE1A71228DDF97F4D0C2C1BF`. +PeerявнопередалV6RootприобоихallUIpaused/lessonswithdrawn, после103RootallUIpaused иV7released/owner:null. +Finalruntime/docsreview64 принято:0Critical/0Important/0Minor после закрытия тестового и документального +уточнений. Все103PASSуникальны; первые97совпали с предыдущим стендом по порядку и тексту, оба журнала +побайтно совпали,522→526bin-файлов, фактические SHAдо/после/на диске совпали. Task64 закрыт. +Продуктовых изменений послеde3 нет, исторические pins и118Ruling/17deferredMinor сохранены. + + +## Продолжение65–67: сводка отчёта + +Product93091a13b533897015d8efe789a6aa3aad7ff066 выделяет выборseverity/title/message из PageViewModel +в internal BlockCheck2ReportSummaryPresenter. Пять lazybool state reads + host-bound Text/ShowActionMessage, +конструктор без вызовов портов, прежнийprivateShowReportSummary сохранён. Нет snapshot/catch/newrules; +повторные чтения между localization calls и reentry сохранены. Page main380→353/sum822→795. + +20focusedGREEN29ms послеabsent-ownerCS0246RED,full1807/1807 безfailed/skipped19s, +normalGUIx64Release0warnings/errors44,29s; source451/517→595/0comparedchanges и compiled452/0+7. +NormalDLL SHA256 `C4DCFA8E0BD20B07435276DB3912C0D82ABA8F11A89E2103E8DC643F717665F1`. +Immutable930 source совпал с precommit working input normalizedLF. Joint exact930+securityEE +прошёл2019/2019 за82s и GUI0/0 за67,24s. Чужое дерево read-only/cleanEE, без product overlap. + +Свежий productreview57ede2c→930 принят0Critical/0Important/1Minor к повторному BestEffort-чтению в тесте. +Test-only4d19d461b4038fbe965ffcfaf52fcae6075ad2c1 добавил изменение толькоBest=true внутриPartialTitleText: +ожидаютсяWarning/PartialTitle/BestEffortMessage и дваbest-чтения по разные стороны Text. Контрольная +мутация с кешированием первогоBest дала RED stalePartialMessage; оригинальныеbytes восстановлены +вfinally/SHAverified/gitdiffGUIagainst930empty. На исходнике21focusedGREEN29ms/full1808GREEN14s, +0failed/skipped. Это отрицательный контроль теста, не продуктовый дефект. NormalGUI/fixturebinary не +менялись, новая GUI/nativeсборка не требовалась. Runtime/joint архивы остаются наexact930с20summarycases. + +Actual-host F:/cdpiui-verify/cdpiui-summary-93091a1-20261110: **107PASS+COMPLETE/exit0**, +PID45484, UTC2026-11-10T06:00:48.7342523Z→06:00:52.8956430Z. Build0warnings/errors68,59s, +1234project/1495repo/exact18cuts/21bootstrap sources,old103+4summary. IndependentprelaunchREADY. +Реальны Page/Result/reportDTO/NoBypass issue/HTTP-only target/Localizer/privateforward и hostdelegate targets. +Fakeview разрешает толькоShowStatus; Selected/Menu/прочие endpoints бросаютошибку. Новые группы не +вызывают UpdateView/OnLoaded/Unloaded/Test/Stop/component/backend/native actions. Старые103 и cleanupExit +сохраняют прежнийscope; nativevisual/fullstartup/OSfilesystemproof не заявлен. Textcallback/faults —managedscope. + +Все postchecksPASS:107групп/COMPLETE/exit0/noFAIL/пустые streams/source+5sourcepins/три +входных файла16/16/15байт/Settings-export-custom-missingmarkersabsent/4newbinnames/priornames/finishedPID, +5фактическихbinarySHAдоlaunch/послеexit. GUI fixture SHA256 +`3972CB2D26A3C16373602ECE971E7ADF32E75118C0DBDEF8A888B44A5D61C245`; source-boundary +`host-fixture-manifest.txt` SHA256 `1A0C2610201D50919A1BC026D94B953C43CF7A4D0C60BB2C2F5653D57E3765C2`; +runner SHA256 `C6537BE6D601470390B1009EF73B6B3AA408BD6C12C7023CD33429815327438A`. +Под свежие peer/lessonsallUIpaused/readyfalse иV7released выполнен явныйV8Rootgrant/readytrueпослеreview. +После107/точногоPIDgone RootallUIpaused иV9released/owner:null, backup+ackсохранены; чужиепроцессы не менялись. +Finalevidence/docsreview67 принято:0Critical/0Important/0Minor после закрытия тестового и документального +уточнений. Все107PASSуникальны; первые103совпали с предыдущим прогоном по порядку и тексту, оба +журнала побайтно совпали, fivebinary/fivesourceSHA проверены. Task67 закрыт. Продуктовых исправлений +после930 нет, все прежниеpins и120Ruling/17deferredMinor сохранены. + +## Продолжение68–70: одиночная проверка выбранной стратегии + +Product `ff6bc636ddad9147012d1a8e1d4b183f2cf8ded5` выделяет выполнение одиночного теста и +представление результата в `BlockCheck2SelectedStrategyTest`. Сохранены одиннадцать ленивых портов, +поле `_strategyTestRunning`, private setter прогресса, публичный Task и приватный метод показа результата. +Выбранная строка захватывается до уведомлений; тестовый порт читает текущий `Result` после них. +Первые публикации остаются до `try`, порядок catch/finally и частичные состояния не меняются. +Сумма четырёх partial страницы уменьшилась **795 → 742**, основной файл — **353 → 300** строк. + +Absent-owner CS0246 RED, затем **36 целевых / 1844 общих** теста, без ошибок и пропусков. +GUI x64 Release: 0 предупреждений, 0 ошибок, 54,40 с. Source inventory сравнил 451 исходный тип +в 517 → 596 C# файлах, потерь сигнатур нет; metadata inventory — 452 типа, 0 потерь и 7 прежних +добавлений интерфейсов. Все 596 GUI-файлов immutable ff6 совпали с проверенным working input +после нормализации LF. Это ограниченные проверки сигнатур, без полной ABI/annotation/interop гарантии. +SHA256 обычной GUI DLL: `965649633BC6B14C034ECEF43E4FD908C2A7F5FF03855418D14280E9342B42E1`. + +Независимое product review не нашло дефектов переноса и предложило два Minor к покрытию. +Test-only `dfaccbd982d4a8f0b896e5369c72added756a1c1` добавил действительно отменённую задачу +`Task.FromCanceled` и замену первого Error issue из callback локализации формата. Контрольная мутация, +кеширующая первую ошибку до локализации, дала RED в новом тесте; исходные байты восстановлены +в finally, SHA и отсутствие GUI diff с ff6 проверены. Затем **38/38 целевых**, **1846/1846 общих** +тестов, 0 failed/skipped; повторное product review — 0 Critical/Important/Minor. Это усиление тестов, +продуктового исправления не было. Обычная GUI DLL не менялась, повторная сборка для test-only не нужна. + +Joint `F:/cdpiui-verify/cdpiui-joint-selectedtest-ee47716-20261110` объединяет exact dfaccbd9 с +security `ee4771675956fe213634675f37579362efb7e0eb`: **2058/2058**, 0 failed/skipped, 48 с; +GUI 0 предупреждений/ошибок, 92,08 с. Security worktree проверен read-only, clean EE, исходники +другой сессии не изменялись. Joint включает оба новых тестовых уточнения; runtime-архив остаётся на ff6. + +Actual host `F:/cdpiui-verify/cdpiui-selectedtest-ff6bc63-20261110`: **111PASS+COMPLETE/exit0**, +PID 9112, UTC `2026-11-10T15:06:27.9269258Z` → `2026-11-10T15:06:37.3261527Z`. +Build 0 warnings/errors, 78,84 с; независимое prelaunch READY. Сверены 1235 project / 1498 repo +tracked inputs, ровно 18 прежних boundary-файлов, 22 bootstrap-файла и пустой secret stub. +Прежние107 групп сохранены; новые4 проверяют реальную Page/Result/issue-helper/Localizer, private +forward, host-bound delegates, нулевые/частичные/успешные probes, первые issue/Error, reentry, +guards и границы исключений. Важный отрицательный сценарий: при уведомлении прогресса реальная +модель с сессией заменяется на sessionless модель; вызов текущего Result возвращает +MANUAL_SESSION_UNAVAILABLE, ловушка backend остаётся невызванной. Реальные flags/sender/finally/ +assignment formatting проверены; status/menu/command view контролируются. Setup fault до try сохраняет +состояние и идентичность исключения, ошибка status превращается в один error и затем выполняется cleanup. + +Все postchecks PASS: 111 уникальных PASS, один COMPLETE, первые107 совпадают по порядку и тексту, +0 FAIL, пустые stdout/stderr, retained log побайтно совпадает с binary-root log. Пять фактических +binary SHA сверены до запуска и после выхода, шесть source pins сохранены. Три входных файла +16/16/15 байт сохранены; Settings/export/custom/missing markers отсутствуют, только четыре новых +bin-файла, все прежние 522 имени сохранены (итого526), owned process отсутствует. +Fixture GUI SHA256: `4A54612E01DA34765AE4739269F009B0FD49C8C44E4A8F974D9A14C8CEADBA72`. +Source-boundary `host-fixture-manifest.txt` SHA256: +`3BBDC5DF1CEC50C327356FD0FF0AE0331E01D96A28956700D858D7E0E607A05D`. +Runner SHA256: `987234C3DC3B34A98C46056683F2F3062B814FFA17CCD7345F35F386E55819CD`. + +Очередь согласована с текущим pipeline owner: его явный V15 release/all UI paused, затем V16 Root +после READY и проверки остальных ready=false. После owned PID gone и postchecks Root all UI paused, +V17 released/owner:null, запрос completed/ready=false и отдельный idle ack. Pipeline уведомлён для +продолжения GitHub своим grant. Root не использовал desktop UI API; чужие окна/процессы не менялись. +Новые4 группы не вызывают manual component lifecycle/OnLoaded/Unloaded или настоящие backend actions. +Старые107 сохраняют прежние два nonactivated окна и Application.Exit teardown. Полный запуск продукта, +интерактивный visual/native сценарий и изоляция всего OS этим прогоном не доказаны. +Task70 закрыт: final runtime/docs review — 0 Critical, 0 Important, 0 Minor. Уточнение к исторической +записи122 разделяет actual111 на ff6 и joint на dfaccbd9+EE; оба прежних тестовых замечания закрыты. +Все хеши, журналы, входы, отсутствие процесса и точные границы прогона проверены независимо. +На момент закрытия Task70 продукт после ff6 не менялся; повторный прогон для документации не требовался. + +## Продолжение71–73: сохранение отчётов + +Из частичного класса страницы выделен `BlockCheck2ReportExport`: выбор пути, JSON/text save action, +await и сообщения завершения/ошибки. Семь ленивых портов, публичные SaveJsonReportAsync/ +SaveTextReportAsync и private SaveAsync(Func) сохранены. Clipboard и сам сериализатор не менялись. +Отчёт читается перед guard и снова внутри save action после picker; изменения текущего Result между +ними видны. Только null path отменяет операцию. Setup ошибки остаются вне catch, а save/await/ +success localization/status внутри catch. Независимые параллельные сохранения, reentry и отмена +сохранены. Сумма четырёх partial **742 → 705**, main **300 → 305**, export **85 → 43** строки. + +Первоначальный `bd913430` прошёл absent-owner RED →31focused/1877full, GUI0/0, source451/597 и +compiled452/0+7. При ревью найден крайний случай переноса: method-group `_view.PickSaveFile` стал +обращаться к null view в конструкторе, хотя раньше no-report exports могли завершиться без view. +Это замечание проверено отдельным настоящим RED, а не принято только по предположению. +Первый full115 архив `F:/cdpiui-verify/cdpiui-reportexport-bd91343-20261110` сохранён UNLAUNCHED. +Диагностический red1 сохранён UNLAUNCHED с CS0136 в тестовой переменной catch; red2 исправил только её имя. + +Actual RED2 `F:/cdpiui-verify/cdpiui-reportexport-red2-bd91343-20261110`, PID53604, +UTC15:37:43.1832730→15:37:47.5483859 10ноября2026:111 прежних PASS, один +NULL_VIEW_EAGER_PICKER_REGRESSION, inner NullReferenceException в настоящем Page ctor:55, +exit1/безCOMPLETE. Build0/0/66,19с, independent prelaunch READY именно для ожидаемого RED. +Все postchecks прошли: те же18cuts/23bootstraps/1236project1501repo,5binary7sourcepins, +три прежних входа16/16/15байт, только4newbinnames/все522прежних имени, все3reportpaths/Settings/ +markers отсутствуют, streams пусты, процесс завершён. Это свидетельство найденной регрессии, +не принятый успешный runtime. Runner SHA256 +`5D5EF79AFC140FFFD7BD1BB60EC5D586299DB8EAF8F2EE615B5B091C6AD8A5E1`. +Явный pipelineV19handoff→RootV20→послеpostchecksV21released/ALLRootUIpaused, затем pipeline продолжилV22. + +Test refinement `62e6839` отдельно усилил различие синхронного исключения и faulted returned Task: +вызов делается до Assert.ThrowsAsync. Контрольная мутация без async у JSON wrapper уронила все4JSON +setup cases, четыре text cases прошли. Исходные байты восстановлены вfinally/SHAverified. +На исходнике31focused/1877full прошли; этот же refinement включён в окончательный product. + +После фактического RED исправлен picker на lambda, которая обращается к полю только при вызове. +Текущий `0c5ea12483d39ff0e21b3dca4457bf5e4e1df8c5` прошёл31focused/1877full,0failed/skipped, +GUI0warnings/errors18,46с; source451/517→597/0потерь и metadata452/0потерь/+7прежних additions. +Все597immutableGUIфайлов совпали с проверенным working input normalizedLF. +Normal DLL SHA256 `0A96C87463214289EA0B9FE6B04D1328C312ABA9F7AE45D417E7A8903946B3EF`. +Повторное product review —0Critical/0Important/0Minor, оба замечания закрыты. +Joint exact0c5+securityEE `F:/cdpiui-verify/cdpiui-joint-reportexport2-ee47716-20261110`: +2089/2089/0failed-skipped47с, GUI0/0/69,41с. Security worktree read-only/cleanEE, без source overlap. + +Исправленный actual115 `F:/cdpiui-verify/cdpiui-reportexport2-0c5ea12-20261110` собран0/0/69,96с; +независимое prelaunch READY,1501repo/1236project/exact18cuts23bootstraps/5binary7sourcepins. +Новый сценарий идентичен RED2 по SHA256 B7AEBF2B…; прежние111 групп и21casepartial сохранены. +Расширение IO явно ограничено двумя fresh direct-child файлами owned-report-export.json/.txt в своём +binaryroot; третий путь должен остаться отсутствующим. Это реальные serializer writes/readback, +внешние postchecks проверяют current model fields/длины/SHA. Только6новых имён:3inputs+log+2reports. +Fakeview разрешает PickSaveFile/ShowStatus, остальные endpoints бросают; desktop picker, component +backend, full startup, interactive visual и whole-OS isolation не проверяются. Pending/concurrent и +локализационные ошибки относятся к managed/source scope. + +Actual115 выполнен: **115 уникальных PASS + один COMPLETE / exit0**, PID71744, +UTC `2026-11-10T15:52:46.0727531Z` → `2026-11-10T15:52:50.1694270Z`. +Первые111 совпали по тексту и порядку с принятым selected-test прогоном; обе копии журнала побайтно +совпали, 0FAIL, пустые stdout/stderr. Все5фактических binary SHA сверены непосредственно до запуска +и после выхода,7sourcepins сохранены. Тот же B7AEBF2B сценарий, который дал RED конструктора, +теперь прошёл создание null-view host и оба no-report экспорта. JSON/text содержат текущие отчёты +после замены Result из picker; все наблюдаемые status calls выполнялись в UI-потоке. JSON сохранён +354байта/SHA256 `5A1B4603F26F04A0C4459D80D4C521951932D697FB03109E0AD3CEA78ED8C198`, +text260байт/SHA256 `FB43AC90C034C29F072836089EA40E20982A64ED3C66265D79CBB8B05D204979`. +Третий report path, Settings/export/custom/missing markers остались отсутствующими; три input-файла +16/16/15байт сохранены, ровно6newbinnames,522→528файлов и все прежние имена, owned PID отсутствует. +Normal GUI hash0A96 неизменён; отдельный facts verifier повторил115unique/first111/logs/12pins/ +два real output contents+SHA/6names/absence/normalDLL. Ни один прошлый архив не запускался повторно. + +Fixture GUI SHA256 `4CECB365BFC1ACEAEE81A3F50BADB3BDCABE7631A1087BFD1FA1C8267FCF458C`. +Source-boundary `host-fixture-manifest.txt` SHA256 +`9AEC93BCE22224418F4DFCA108C137770ACF63EB9DCCFFBE26F8B00467AC0F63`. +Runner SHA256 `AB85F091171708646F7679B1CE0F4B500D43E140F7E64F8655C623EC05AFE5F9`. +Очередь: явный pipelineV23release/ALLUIpaused→RootV24grant после READY/остальныхready=false; +после postchecks/ownedPIDgone —RootALLUIpaused/idleack/requestcompletedfalse/V25released. +Pipeline и координирующая сессия уведомлены для продолжения своим grant. Root desktop UI API не +вызывал, чужие окна/процессы/рабочие деревья не изменял. Final Task73 evidence/docs review принят: +0Critical/0Important/0Minor, оба прежних замечания закрыты,124Ruling/17исторических deferredMinor +сохранены. Независимо сверены все12pins, входы и выходы,115/prefix/logs/528имён/absence/PID, +REDvsGREEN/samecase, exactjoint/normalDLL. После0c5 продукт не менялся, повтор для документации не нужен. + +Координационное примечание на10ноября2026: в общем Git сменился origin/main с +`d72ad478bc05c6ab9e53f46da1a2b6c58690b202` на `7ead95f7756057f67cd113671a7f84cf422e8d32`. +Read-only проверка подтвердила одинаковый tree `33323ba54f948dc7379061e805330bcb08fd610d`, +нулевой diff и отсутствие old-main ancestry в новой истории. В момент наблюдения Root dev HEAD был +0c5; продукт от этого события не изменился. Root не выполнял fetch, обновление refs main/origin/main, +rebase/merge/push. Это отдельная граница +последующей интеграции истории; текущие source/runtime/joint результаты привязаны к указанным точным +коммитам и не подменяются live-сравнением чужого PR. О смене refs сообщила соседняя сессия, +затем указанные локальные Git-объекты и tracking ref проверены независимо; автор изменения не установлен. + +## Продолжение74–76: жизненный цикл ручного теста + +Product `2e70779e0b69169241b2e5b3322601533f36acb1` выделяет всё управление ручным тестом из +ResultPageViewModel.ManualTesting в `BlockCheck2ManualTestSession`: три bool состояния, запуск, +обычную остановку, уход со страницы, восстановление компонента и обработку task-state событий. +Публичный getter/Task методы и private leave/state-handler forwards сохранены. Приватный вложенный +ManualTestHost проксирует Page эффекты; новый публичный интерфейс host не добавлен. Сумма четырёх +partial уменьшилась **705 → 572**, ManualTesting **186 → 50**, main **305 → 308** строк. + +Порядок receiver-before-ID сохранён отдельной фабрикой. Getter ComponentTasksManager.Instance +инициализирует задачи и подписки; прежний ConfigMaker adapter разрешал бы его после аргумента ID. +Поэтому существующий IConfigMakerTestTasks переиспользован через новый bound-manager adapter: +каждая операция сначала получает manager receiver, затем читает текущий ID. Guard ID остаётся +отдельным чтением; leave захватывает один ID до try. Новые locks/guards/dedup/cancellation не введены. +Состояние больше не находится в трёх private полях Page: единственный известный reflection consumer, +старый selection fixture, получил явно проверенный bridge к owner._isRunning. Это не обещание +сохранить произвольную private reflection; публичные API и observable поведение проверены отдельно. + +Absent-owner CS0246 RED, затем receiver-port CS1503 RED; unconditional-restore mutant дал2FAIL. +На фактическом продукте прошли1947full и GUI проверка ниже. После них functional ID-before-receiver +mutant дал FAIL в новом тесте; исходные байты восстановлены вfinally, SHA проверен, затем70focused +прошли на восстановленном исходнике, далее API inventories. Итоговые source/product проверки:70focused/1947full/0failed-skipped, +GUI x64 Release0warnings/errors39,26с; source451/517→600/0потерь и metadata452/0потерь/+7прежних +interface additions. Normal DLL SHA256 +`670A98479785F6083D76656EAA77EC2CE74243BE9D6A65C785319948D6C6953A`. + +Product review нашло0Critical/0Important и два Minor к тестам. Test-only +`491692bc4dcd6c84f477639e1e78428122b5f9c0` разделил gates конкурентных запусков: оба доходят до +ожидания, затем завершаются по очереди без гонки в списках/event fake. Добавлены false/null button +cases уже работающей сессии с ровно одним Stopped notice. Мутация Stop(true)→Stop() дала2FAIL; +source bytes/SHA восстановлены, GUI diff относительно2e пуст. Затем72focused60ms/1949full10с GREEN, +0failed/skipped. Повторное product review —0Critical/0Important/0Minor. GUI/normalDLL не менялись. + +Immutable491 содержит тот же GUI код, оба тестовых уточнения и все600GUIфайлов, совпавшие с working +input normalizedLF. Joint exact491+security `ee4771675956fe213634675f37579362efb7e0eb`: +`F:/cdpiui-verify/cdpiui-joint-page-manual-ee47716-20261110`,2161/2161/0failed-skipped42с, +GUI0/0/61,24с. Security worktree проверен read-only/cleanEE, пересечения production sources нет. + +Новая actual121 копия `F:/cdpiui-verify/cdpiui-manualsession-491692b-20261110` собрана0/0/79,64с. +Independent prelaunch READY:1506repo/1239project trackedinputs,19точныхcuts/24bootstraps+пустойstub, +5фактическихbinary/8sourcepins, embeddedasInvoker/nonadmin/no reparse,522исходных bin-имени, +все пути результатов свежие. Прежние18cuts совпали с115 с учётом ownExePath. Новый boundary только +в ManualTesting.cs: tasks receiver factory/currentID/logger. MainPage ctor/owner/bound adapter вF +совпадают с продуктом. В selection partial изменена только строка private-state bridge; все его +остальные assertions и115прежних PASS-текстов сохранены. Остальные21старыхcasepartial побайтно прежние. + +Шесть новых групп проверяют реальную Page/Result/session/pure writer/Localizer/private adapter, +исходный handler TargetPage, lazy static factories и настоящий dispatcher. Tasks/confirm/status/ +selection/logger контролируются; реальный ComponentTasksManager и процессы не запускаются, реальное +OS восстановление не проверяется. Группы включают pending confirm/run/stop, captured selected item, +current Result replacement→setup NRE, три live stop IDs против одного leave ID, startup-event guard, +две queued exit notices после явной остановки, original fault boundaries. Новых IO нет: прежние +3inputs/log/2reportoutputs=6newnames. Реальный bound-manager adapter проверен source/GUI compilation, +а не вызовом настоящего manager на стенде. Native dialogs/fullstartup/wholeOS/ABI proof не заявляются. + +Runner SHA256 `C09821A43B53B053FB97BB80A42F195DFB9BF6F7C02A790A5F4C371F490E03EC`. +Дополнительный readback SHA256 `87A835C3B8FCF07480BBC3EE60E44CDFADB15E0D2318784B1505B01338B9A5F4` +проверяется до launch и непосредственно перед исполнением. Он требует121unique/first115 exactorder, +побайтовое равенство журналов,13diskpins, exact354/260byte report outputs с прежними goldenSHA, +6newnames/522→528/forbiddenabsence/normalDLL. Три literalinput файла16/16/15 проверяет сам runner. +Runtime121 выполнен: **121 уникальный PASS + один COMPLETE / exit0**, PID69044, +UTC `2026-11-10T17:46:43.3819843Z` → `2026-11-10T17:46:47.3377306Z`. Первые115 совпали по тексту +и порядку с предыдущим принятым прогоном, журналы побайтно равны; 0FAIL, stdout/stderr пусты. +Все13 actual disk pins и исходные границы подтверждены, три input-файла16/16/15байт сохранены, +оба отчёта354/260байт совпали с прежними golden SHA и literal current JSON/text полями. +Сохранены522 прежних имени, итог528/ровно6новых, negative report path/Settings/markers отсутствуют. +Owned PID69044 завершился и отсутствует; normalGUI670A неизменён. Дополнительный readback повторил +121unique/first115/logs/13pins/reports/6names/absence/normalDLL после всех runner postchecks. + +Fixture GUI SHA256 `CBDCCDEBC1173FB60C4A90C9CD6392915B57DCB6FB9E00FE4CC236276E8F1B07`. +Source-boundary manifest SHA256 +`0ED94928FDE79373705857004694F9D67BC9AC9D77F1E06C259F48A1DD8FF1E0`. +Очередь: pipeline явно передала Root V27grant после завершения своего UI; координатор подтвердил. +Уже принадлежащая Root lease V28 нормализовала filename alias запроса в reviewed slug без смены +объёма разрешения. После postchecks/ownedPIDgone RootALLUIpaused, requestcompleted/ready=false, +idleack сохранён, V29released/owner:null. Обе сессии уведомлены, Root desktop/CUA API не вызывал. +Task75/76 закрыты: final evidence/docs reviewACCEPT0Critical/0Important/0Minor. Один документальный +Minor о порядке проверок исправлен: full1947+GUI до receiver mutant, restore→70focused→API inventories, +затем49172/1949. Независимо сверены1506fixtureinputs/13pins/runtime/queue и1533jointfiles/166overlaypaths/ +точная аддитивная testcsproj. 126Ruling/17исторических deferredMinor сохранены; продукт после2e и GUI +после обычной проверенной сборки не менялись. + +## Продолжение77–79: действия назначений и нейтральный механизм выбора + +Product `b5cce88838bc32acc20f4e5eb3ad2d03868456e4` отделяет небольшой общий механизм +`SelectedItemChoiceAction` от доменных команд `BlockCheck2AssignmentActions`. Первый —39строк, +четыре callback-порта, plain reference types и System/collections/Task; в нём нет Page/WinUI/BlockCheck2/ +локализации. Его самостоятельная обязанность — захват выбранного объекта, один снимок вариантов, +необязательное ожидание выбора и применение. Один текущий production-потребитель явно признан; +существующее повторное использование не выдумывается. Небольшой domain owner80строк хранит команды +и notice policy, не состояние всей Page. Internal host13members/private nested adapter читает current +Result при вызове, quickfix использует Func операции. Это реальная граница механизма и +orchestration; перенос того же крупного сцепленного объекта в новый класс целью не является. + +Page сохраняет прежние public методы/private ShowAssignmentResult, свойства/private setters, +UpdateAssignmentView/Buttons, sender и preview formatter. Сумма **572 → 513**, Assignments **171 → 110**, +main **308 → 310**. Новых partial-частей нет. Editor/model/preset policy и XAML не менялись. +Sync команды выбрасывают исключения непосредственно; async list возвращает Task даже при setup fault. +Item захватывается до await, paths.ToArray один раз, chooser получает этот же mutable snapshot; +после await current Result читается заново. Zero/one chooser пропускают, null отменяет только +multiple-choice chooser; runtime null в single-path массиве всё ещё доходит до apply. Empty/whitespace/ +outside-list результаты не получают новой validation. Move восстанавливает captured assignment после +view reentry; add result сохраняет двойной menu update, quickfix один; concurrent choices независимы. + +Absent-owner CS0246/CS0234 RED сохранён; контролируемое повторное чтение selected после await дало +FAIL в captured-row тесте, исходные bytes/SHA восстановлены finally. Source utility SHA256 +`44872BE09BB97551B906B1D7B285A77F51FFA14ECAA03AB9404714D9121352F2`. +Final47focused38ms/1996full10с,0failed/skipped; normalGUI x64 Release0warnings/errors41,73с. +Source451/517→603/0потерь, compiled452/0recordedchanges/+7прежних interface shapes. +Normal DLL SHA256 `24797CCABA986B0141D564002E96B819AB515AEF58F4AD3C923CD49CF3EF8FAF`. + +Product review0Critical/0Important/1Minor к neutral single-choice тесту: прежние Same assertions +внутри apply не доказывали сам вызов и его кратность. Test-only +`61fd0e7eb5f895c314e358d716a4a131a25da250` записывает пары и проверяет Single после await в обоих +plain-object сценариях. Duplicate-single-apply mutant дал1FAIL/Assert.Single; исходник/SHA восстановлен, +GUI diff относительноb5 пуст, затем47focused/1996full GREEN; повторное product/unit reviewACCEPT0/0/0. +Независимый координатор предоставил +standalone14/14 probe на том же SHA без WinUI/BlockCheck2/packages и negative control13/14 с единственным +single-runtime-null FAIL; Root прочёл его PROBE-RESULT.json. Это ограниченное свидетельство механизма, +не замена продуктовых/GUI/runtime проверок. + +Все603 immutable61fd GUI исходника совпали с working/current normalizedLF. Exact joint61fd+security +`ee4771675956fe213634675f37579362efb7e0eb`: +`F:/cdpiui-verify/cdpiui-joint-assignment-actions-ee47716-20261110`,2208/2208/0failed-skipped41с, +GUI0/0/59,36с. Security sources не меняются, joint строится отдельно из committed pins. +Независимое ревью сверило1538ожидаемых source paths:1537 Gitblobs совпали, testcsproj равен security +плюс109аддитивных GUI Include элементов; общий изменённый путь только testcsproj, overlay172пути. + +Новая actual125 копия `F:/cdpiui-verify/cdpiui-assignment-actions-61fd0e7-20261110` собрана0/0/71,78с: +1512repo/1242project trackedinputs, прежние19cuts,25bootstrap sources+verifiedemptySecretstub. +Четыре новые группы используют real Page/Result/editor/Localizer/private host/preview formatter и +общий choice механизм; selection/chooser/status/menu контролируются. Новых source boundaries и IO +нет; все прежние23casepartial сохраняются. Проверяются cold/noitem/zeropaths, add/duplicate/private +forward/two menus; pending choice с captured row/current Result replacement, isolated mutable array, +single/cancel; real move/reselect после preview reentry/remove/clear/empty guards/sender; real issue +quickfix и sync notice partial fault против returnedTask selection fault. Реальные backend/components/ +native dialogs/fullstartup/interactivevisual/wholeOS/ABI не проверяются. + +Runner SHA256 `B9BE0FBC5EACD0F5CFD3607803739AC2809A0B715A75D4DCB7ADF369B6FEB24B`, +readback SHA256 `BB7DAC29E969CAECDA178066343BF3D22FF94A32909BF71677E071307E9186BF`. +Полный список14actualpath+SHA —scratch `assignment-actions-host-approved-pins.json`. +Fixture DLL `FFE32FA95182B6B2DF0AFEE3266C675CC7E4728A218D51DCC59DC19D0FFFC1AD`, +source-boundary manifest `266D6F9967F7E734BC28A6988AA6E0AEC8604EBE1262F1FD193E43CA5F440FF0`. +Fresh independent prelaunch READY0блокирующихзамечаний: все1512Gitblobs/1242projectpaths,19cuts, +23oldcasebytes/14actualpins/embeddedasInvoker/nonadmin/noReparse/522names/freshness подтверждены. +Actual groups доказывают end-to-end изоляцию массива от модели; собственное копирование в helper +отдельно различают managed tests, поскольку сам реальный editor уже возвращает новый массив. +Actual125 выполнен: **125 уникальных PASS + один COMPLETE / exit0**, PID68696, +UTC `2026-11-10T18:37:05.7871699Z` → `2026-11-10T18:37:17.5133853Z`. Первые121совпали по тексту +и порядку с принятым manual-session прогоном; обе копии журналов побайтно равны,0FAIL/stdoutstderr0. +Все14actualpins и исходные границы подтверждены, пять binarySHA до/после запуска равны; +3literalinputs16/16/15байт и2realreports354/260байт с прежними goldenSHA/currentliteralfields сохранены. +В bin522→528имён, ровно6новых/все прежние сохранены; negative report path/Settings/markers отсутствуют. +Own PID68696 завершён и отсутствует, normalGUI24797CCA неизменён. Дополнительный SHA-pinnedreadback +повторил125unique/first121/logs/14pins/reports/names/absence/normalDLL после всех runner checks. + +UI очередь: владелец retrospective явно передал Root V31active/requestassignment-actions-20261110-l, +все остальные UI paused. После prelaunchREADY/проверки grant запуск состоялся один раз. После всех +postchecks RootALLUIpaused/idleack/requestcompletedfalse, затем atomicV32active возвращён готовой +retrospective заявке `issue-retrospective-project-final-readback`; обе сессии уведомлены. Root desktop/ +CUA API не вызывал, чужие окна/процессы/worktrees не менял. Lessons слот согласован Root после APKready, +его pending readiness не использовалась как grant. Tasks78/79 закрыты: final evidence/docs review +ACCEPT0Critical/0Important/0Minor. Оба documentary locator Minor исправлены: текущий раздел77–79, +полные14pathpins в отдельном approvedmanifest. Независимо сверены125/prefix/logs/14pins/3inputs/ +2outputs/528recursive names/absence/ownedPIDgone/queueV31→32, current normalDLL и точные joint/source +границы. 130Ruling/17DeferredMinor сохранены. Продукт послеb5 и GUI после normal сборки не менялись. + +Для следующих проходов остаются ConfigMaker host1012строк (синхронизация editor/document и смена +компонента), CreateNewConfig818 (navigation/save/сборка config), App677 (оставшаяся platform/startup +координация). Это перечень кандидатов, не объявление об их уже выполненном переносе. После текущего +прохода ResultPage513 в значительной части содержит properties/адаптацию; один порог числа строк +не требует дальнейшего разбиения коротких forwards. Следующая граница выбирается по самостоятельной +обязанности и нейтральному механизму, с сохранением current reads/уведомлений/ошибок. Core import/storage/ +configuration и security policy требуют сверки владения с соседней сессией перед изменением, чтобы +не пересекать её работу. Цифры из копии AUDIT исторические и отличаются от текущего дерева. + +## Продолжение80–82: общий механизм двух групп переходов + +Product `a5a1b9ba512073d75267943cafba9bc1eddb86b3` выделяет `TwoPhaseTransitionSequence` из +536строчного UtilityButtonControls. Координатор проверил9worktrees/активные сессии и отсутствие +конфликтующего WIP перед выбором файла. Store/MenuBar/security/backend/persistence не меняются. +Helper50строк,9входов/две группы, только System/collections/Task/CTS; нет Button/Visibility/WinUI/ +Composition/localizer. Один текущий consumer, повторное использование не заявляется. Control +**536 → 500** сохраняет создание/отмену CTS, literal finalizer callback, анимации, navigation, XAML/DP. + +Counts обеих групп читаются один раз до операций; captured total управляет паузами, не ограничивает +live foreach. Inspect до apply захватывает bool, duration selector выполняется после apply и только +перед промежуточной паузой; затем lazy Token и delay. Нулевая пауза не пропускает чтение Token. +Отменённый CTS не подавляет первое действие/одиночный переход; disposed empty/single не читает Token. +Новых snapshots/guards/locks/Concat/ConfigureAwait(false) нет. В helper сохранён catch(anyOCE) тела и +finally(onFinally), исключения финализатора не перехватываются и могут перекрыть body fault. +Прямой private3parameter Task forward не добавляет новый await между последним apply и очисткой. +Control callback обнуляет поле только для того же CTS и всегда освобождает переданный CTS; helper +сам не отменяет и не освобождает заимствованный источник. Private async attributes/stack frames +переместились; публичные API прежние. Первый вариант с outerasyncwrapper был пересмотрен до product edit. + +Absent-helper CS0103 RED на обоих вариантах API; прежний uncommitted test draft сохранён отдельно. +Контрольный inspect-after-apply mutant дал1FAIL; исходные bytes/SHA восстановлены finally: +`66FB24692285E24BFD758E6D7499C83CB784875818D51FE83BA27F922FA03D81`. +После восстановления полный suite2026/2026/0failed-skipped11с, GUI0warnings/errors52,89с, +API inventories и focused30/51ms GREEN. Source451/517→604/0потерь; compiled452/0recordedchanges/ +7прежних interface shapes. Normal DLL SHA256 +`2F0BD022AF1926228353C5E88CB9FA2EF3A94FB3F3AD7BC43F4164F1556E788D`. +Свежий product review82 —ACCEPT0Critical/0Important/0Minor. Координатор независимо предоставил12/12 +standalone cases того же helper, включая queued SynchronizationContext/cleanup до observer и +expected11/12 inspect-mutant; Root source/bin/obj не менялись, UI не использовался. Это bounded helper +proof, не визуальная проверка. Все604immutablea5GUI inputs совпали с working/current normalizedLF. + +Exact jointa5+security `ee4771675956fe213634675f37579362efb7e0eb`: +`F:/cdpiui-verify/cdpiui-joint-transition-control-ee47716-20261110`,2238/2238/0failed-skipped44с, +GUI0/0/85,38с. Независимо сверены1540ожидаемых paths:1539Gitblobs совпали, overlay175пути, +единственный shared path testcsproj равен security XML+110аддитивных GUI items без иных изменений. + +Actual129 copy `F:/cdpiui-verify/cdpiui-transition-sequence-a5a1b9b-20261110` собрана0/0/70,42с, +1515repo/1243project/exact19прежнихcuts/26bootstraps+emptySecretstub. Все24прежнихcasepartial +побайтно прежние; четыре новые группы создают реальный UtilityButtonControls/compiled XAML/Buttons/ +Items/Visibility и вызывают прежний private Task с реальным Task.Delay. UISettings только readonly +AnimationsEnabled; control не получает Loaded/Windowparent, Composition/navigation/help/settings/ +backend/desktopinput не вызываются. Новых source cuts/IO нет, старые3inputs/2reports/log=6newnames. + +Own pending Task state machine пинованного.NET8 читается reflection: прямой helper Task, control-bound +inspect и тот же borrowed source, четыре literal delay values160/310/130/160ms. Это проверка binding, +не замер wall-clock/визуального тайминга и не стабильный runtime API. Проверяются реальные две фазы/ +UI thread/final CTS cleanup; precancel firstapply/anyOCEbody; disposed empty/single vs actual Token +fault после первого apply; old cancellation не очищает newerCTS sentinel. Sentinel не обозначает +два одновременно работающих native цикла: concurrency проверена managed. Один owned DP callback +пишет trace до reentry; порядок нескольких WinUI callback registrations не предполагается. Teardown +ожидает/освобождает свои задачи/CTS/callbacks, timeout не скрывается ожидаемым fault. Loaded animation/ +полный startup/visual/wholeOS/backend proof не заявляются. + +Два независимых prelaunchREADY0блокирующихзамечаний:1515inputs/19cuts/24oldcasebytes/15actualpins/ +embeddedasInvoker/uiAccessfalse/nonadmin/noReparse/522priornames/freshoutputs/noownprocess, +MSIL fields для owned state-machine reflection и compiledXBF подтверждены. Полный15path+SHA список: +scratch `transition-control-host-approved-pins.json`. Runner SHA256 +`7D227A02C6AD1466C759DF107CCF4E1A237323C2F88258BFAE608BB5D917662C`, readback SHA256 +`A122324BD378C9038DE4AB180C5AFF09EFE465D146CBC55887A095E5FF9FCCB7`. +Fixture DLL SHA256 `4BAA8F03651F55BE3D368E3344CAFB75B9586E134BD70B194C15808040B4EF7E`, +source-boundary manifest `3E776B584E7C682B4220D1A3B6080CBFF27220695AD6D6935D7A930BDD19C676`. +Попытка оформления grant с ранее свободнойV39 остановлена повторной проверкой: фактическаяV40 уже +принадлежала retrospective finalpolicy UI. Owner/lease/fixture не изменены этой попыткой; это +coordination gate, не runtimeFAIL. Затем текущий владелец явно передал Root V41active/requestm, +все остальные UI paused. Утверждённый runner был запущен ровно один раз. + +Actual129: **129уникальныхPASS + один COMPLETE / exit0**, PID81460, +UTC `2026-11-10T19:40:40.6399817Z` → `2026-11-10T19:40:46.0595732Z`. Первые125совпали по тексту +и порядку, обе копии журнала побайтно равны;0FAIL/пустые stdoutstderr. Все15actualpins и5binarySHA +до/после запуска совпали;3literalinputs16/16/15байт и2retainedrealreports354/260байт с прежними +goldenSHA/currentliteralfields проверены. Bin522→528recursive names, ровно6новых/все прежние сохранены, +negativepath/Settings/custom/missingmarkers отсутствуют. PID81460 завершён и отсутствует, normalGUI2F0B +неизменён. Дополнительный SHA-pinned readback повторил129unique/first125/logs/15pins/reports/names/ +absence/normalDLL. Сценарии realCtor/XAML/privateTask/boundports/DPcallback/CTScleanup прошли. + +После postchecks/ownedPIDgone RootALLUIpaused/idleack/requestcompletedfalse, atomicV42released/ +owner:null; обе сессии уведомлены. Root desktop/CUA APIs не вызывал. Новых Root UI заявок нет. +Tasks81/82 закрыты: final evidence/docs reviewACCEPT0Critical/0Important/0Minor. Независимо сверены +1515fixtureinputs/19cuts/24oldcasebytes/26bootstraps/15pins/129prefix/logs/inputsoutputs/528names/ +absence/PIDgone/V41→42,604immutableGUIfiles и1540jointpaths/110XMLitems/175overlays. Все четыре +документа соответствуют этим scopes и ограничениям. 132Ruling/17DeferredMinor сохранены. Продукт +послеa5 и обычная DLL после normalGUI build не менялись; повторные тесты/сборки ради docs не нужны. + +## Продолжение83–85: postorder pruning меню + +Локальный контракт [issue209](https://github.com/lumenpearson/cdpiui/issues/209) и +[design](superpowers/specs/2026-11-10-menu-pruning-design.md), basea85efec4/product174d1cbf5699455d7768ae2398df4f8f241bddab. +Issue/Project до кода: In progress/P2/Architecture/Low/G2/lumenpearson, labels type:refactor, +area:architecture,area:native-qa; actual browser readback сохранён policy executor. Отдельныйa85 +импортирует семь exact86417 policy blobs без изменений продукта. ConfigMaker/TextRelay208, +CreateNewConfig и App зарезервированы за другой сессией; её worktree не менялся. + +MenuBarController519→502, нейтральный System-only PostOrderTreePruner23 строки, один потребитель. +Прежний private PruneEntry не имел сторонних source/reflection consumers; рекурсия перешла в utility. +Все три entrypoints сохраняют policy в controller: strong/weak/children retain после потомков; +registry перед physical Remove и logical RemoveAt после успешного callback. Reverse live indices, +повторный вход, ignored false от physical Remove, exception identity и частичное состояние сохранены. +Новых partial/пакетов/public API, snapshots/retries/repair/transactions не добавлено. + +Task83: CS2001 absent-helper RED;20focused GREEN, controlled eager-retain mutant FAIL5/15PASS; +source восстановлен exact bytes/SHA34B54E725993173BD65C1D56A4C95D469DA7810744DEA403BFBBFEDA75ADE183. +Затем20focused26ms/2046full15s,0failed/skipped. Обычная GUI0warnings/errors59.24s, +DLLBA70952D8A1598847C3CFB42856D2FE0F8AC2110B0CD29A5A09C2C0760E250AB. +Source451exported/605files/0loss; compiled452/0recordedchanges/+7прежних additions, не полный ABI. +Первый вызов source analyzer указал отсутствующий Debug output и завершился до анализа; +corrected Release result сохранён отдельно, исправления продукта не потребовалось. +Независимое code/test review83: ACCEPT0Critical/0Important/0Minor, без запуска тестов или UI reviewer. + +Joint174d1cb+securityee4771675956fe213634675f37579362efb7e0eb: +F:/cdpiui-verify/cdpiui-joint-menu-pruning-ee47716-20261110,2258/2258/1m25s/0failed-skipped, +GUI0/0/90.99s. Отдельная проверка состава:1542expectedpaths/1541Gitblobs(171literal1370LFnormalized), +178GUIoverlays,111точных additive csproj items, sole overlap testcsproj; только пустой generated Secret +вне Gitinputs. Security checkout не менялся, joint не является merged/exact-PRHEAD acceptance. + +Task84 immutable fixture F:/cdpiui-verify/cdpiui-menu-pruning-174d1cb-20261110: +build0warnings/errors77.21s,1525repo/1244project/19прежних cuts/27bootstraps; все25oldcasepartials +побайтно равны actual129. Новые четыре группы: actual weak nested tree; strong roots/descendants и +Protected/PartiallyRemoved; merged weak claims/prefix и Removed/NotFound; detached physical root, +ignored Remove false и identifier reuse. Реальные standalone MenuBar/Frame/controller/collections; +сверяется logical/physical/registry identity, нет Window activation/navigation/backend/desktop/newIO. +Fault/reentry callback sequencing — managed/source evidence, не WinUI notification runtime proof. +18actualpins(5binary13source), runnerE47818EA49B87459CC72BAD7CBFAF15F07452F34ECEE21D47B374A83048B60C1, +readback56A171078C4AF5AED040D3F4BA3C87F41FE1022BAA02480239340623D244AE83; parser0errors. +Independent prelaunchREADY0blocking; actual133 COMPLETE/exit0/PID68204gone, UTC +20:50:11.5149509Z→20:50:20.9279135+00:00 10ноября2026.133unique/first129exactorder/oneCOMPLETE/ +noFAIL/streams0/logsbyteequal/18actualpins/5binaryprepost/3inputs16-16-15/2reports354-260goldenSHA +и currentliteralfields/522→528recursive6newnames/allpriornames/forbiddenabsence/normalBA7095unchanged. +FixtureDLL49EB7BED5E791D9DB359F6CB299B4839BEC34A2B0F3124584CA397AED0A30539; +boundarymanifest696D1EB31CCB122C5C2084621BE63BC46FA0A7E258E4D940230EA03987C28752. +Все18actualpath+SHA в menu-pruning-host-approved-pins.json; readonlyverifier повторилPASS. +Ранний Root-coordinator guard ожидал свободныйV46, но увидел ужеV47history active и остановился +до queuewrites/UI. Ошибочное сообщение о Rootgrant немедленно исправлено live47readback; +реальный47 принадлежал history. Послеегоpostchecks получен explicitV48Rootgrant; запуск один раз. +После всехpostchecks/rootidleack/requestfalse/ALLRootUIpaused атомарноV49переданраннейreadyзаявке +peer208/text-relay-208-b577dfe, reviewedrunner40F509...сверенпередпередачей. NoRootdesktop/CUA APIs. +Native133 принят в пределах fixture; final85 technical ACCEPT0Critical/0Important/0Minor, прежний129 сохранён. +Issue209 closed/completed и actualProjectDone/P2/Architecture/Low/G2/lumenpearson подтверждены послеreload52. +Все6criteria[x], canonical3labels/assignee/milestone2 сохранены; metadata209finalcomment6779317178. +Proof: commonGit/task-policy-rollout-2026-11-10/issues208-209-project-closeout.json + issue209-done.jpg. +Task85 COMPLETE scopedlocalacceptance; integration14 и broadernative15 LIVEopen/не закрывались. +Raw evidence: .superpowers/sdd/2026-11-08-class-decomposition/task83-*, menu-pruning-host-*, +joint-menu-pruning-*, source/compiled inventory. Старые архивы и failed/mutant logs сохранены. + +Дополнительный parallel joint, подготовленный исполнителем208 и независимо перечитанный Rootreviewer: +F:/cdpiui-verify/cdpiui-joint-relay-menu-ee47716-20261110, pins b577dfeeaa9abd628be30f3fc0133bc85e051be9 ++174d1cbf5699455d7768ae2398df4f8f241bddab+ee4771675956fe213634675f37579362efb7e0eb. +2287/2287/1m16s/0failed-skipped,GUI0warnings-errors74.70s. Все1544expectedpaths/1543Gitblobs +(240literal1303LFnormalized) проверены с Git,177GUIoverlays+4Menu delta; only shared path csproj, +112unique additiveitems (111+111−110common), все14security Include items/126total сохранены. +Нет неожиданных source inputs/reparsepoints, только empty generated Secret. Три исходных worktree +не менялись verifier; это source/tests/build composition, не общий native137/merge/release acceptance. + +## Продолжение86–88: Core variable projection, issue211 + +Local contract [211](https://github.com/lumenpearson/cdpiui/issues/211), +[spec](superpowers/specs/2026-11-11-configuration-variable-projection-design.md), +basec0892652eb794a27a79612a2b38399ecd565fbcc, product00f39b1a9be70cb97cebd7290b5f24dac6a5ab47. +ActualProject55Inprogress/P2/Architecture/Low/G2/lumenpearson/type:refactor+area:architecture readback +получен до кода;209Done prerequisite выполнен. Исторический аудит называл ConfigurationService1166строк, +но до этого прохода он уже443строки; данный проход443→411, helper45. Root не приписывает себе прежние +извлечения. Peer212Navigation/LoadVars/named-loader,208relay и будущий214App.Modal/DispatcherTaskBridge +остаются другой сессии. Никаких чужих source/index/HEAD не изменялось. + +Internal stateless ConfigurationVariableProjection переносит два literal loop bodies и initializer +order. Facade сохраняет FindItem/instance-null guards и used private ToVariableItems forwarding; +static null failures, ordinal file/pack lookup, raw key spelling/values/comments, firstOrdinalIgnoreCase +metadata match/short-circuit, OrdinalDistinct и fresh result/model/options ownership сохранены. +Metadata читается с capturedConfigItem на прежней каждой итерации; CurrentValueIndex не меняется. +Init/Save/paths/locks/updates/expansion/converters/persistence/security не менялись. Новых publicAPI, +partial/interfaces/packages/visibility/testseams нет. Это малый domain adapter, не genericSelectframework. + +30тестов вызывают actualpublicCorefacade сowned ConfigItem/SetConfigItem, без Init/Save/IO/WinUI. +Original30GREEN25ms→first-to-last-match mutantFAIL3→original exactbytes/SHA +B6D3D6BDAF7372AE59F20E66A4359D594979AFB25EA3AB4F8B06CEBCA3A2A182 restore→30GREEN28ms; +послеextractтотжеконтрольчерезpublicfacadeFAIL3→helper exactbytes/SHA +47312139432BE2478A2E7900B90A01517B180A1ACCA93C00CFFE9630AEC331A9 restore→30GREEN23ms. +Full2076/2076/11s/0failed-skipped; normalGUI0warnings-errors70.77s, +DLLA7E00F36939811821A36AD1DEE1D31958847C93F4B03EFFA89A9779D165CC46C. +После host/tool resume старый exec handle недоступен; прочитан прежний complete GUI log и fresh104Core +source hashes совпали, повторная сборка без изменений не выполнялась. + +Core source syntax88exports/103→104C#files/0signature losses; compiled88→88/0changes/0adds. +Baseline actualpre-changeCoreA64370212868EC11CC9532A39AB60BB214367414FED88E34A7C5323575D5DAF6; +testedcandidate38F3DB60AC594A8D3A6E07527FE8E7BDDD6446769C3EE9548B44F5EF6E970F47 равен test-binCore. +Все605GUI C#files равны174; GUIcompiled452/0changes/+7старыхadditions. ПолныйABI/annotations/interop +не сертифицируются. WindowsCLR actualCoreexecution проверяет изменённые модели; новый WinUI launch +для этих read-only loops не нужен, GUIbindings/types/startup неизменны. Старый133 относится к174, +не является новым Core/visual/native-startup доказательством. + +Core-inclusive joint builder вscratch `build-config-projection-joint.py` принимает только committed +pins; includes CDPIUI+CDPIUI.Core+Tests, сохраняет Rootproject item order и добавляет peer-only nodes, +проверяет base project nodes/первичные14securityitems/unique keys/fullGitblobs/postbuild SHA/XML/extra +sources и emptySecretstub. Скрипт одноразовый, повторно запускать в принятых каталогах нельзя. + +- F:/cdpiui-verify/joint-cvar-00f39b1-security-a: exactEE4771675956fe213634675f37579362efb7e0eb, + 2288/2288/43s/0failed-skipped,GUI0warnings-errors66.19s;1544paths/1543Gitblobs(241literal1302LFnormalized), + 181Rootoverlays/111additiveXML/14securityitems/onlycsproj overlap/postSourceProofPASS. +- F:/cdpiui-verify/joint-cvar-00f39b1-peer-9a9f7cd-a: добавляет exactpeer9a9f7cd79a56cd1456e7e78d940fb11e185695ab + (relay208+named-loader212),2338/2338/42s/0failed-skipped,GUI0warnings-errors65.46s; + 1548paths/1547blobs(246literal1301LFnormalized),181Rootoverlays7peerdelta/113dedupXML/14securityitems/ + onlycsproj overlap/postSourceProofPASS. No combined WinUI runtime/merge/releaseclaim. + +Raw source-proof/manifest/test/gui/execution records: scratch joint-config-projection-security-* +и joint-config-projection-peer-9a9f7cd-*; full before/after metadata и source inputs вcompiled-contract +иcore-api-compatibility. Независимый reviewer реконструировал все Gitblobs/XML обоих joint послеbuild, +прочитал rawlogs, сверил104Core/605GUIinputs и actualtestedDLL, не запускалbuild/tests/UI/checker. +Implementation/joints0Critical0Important; Minor описания historical insertionorder исправлен: +сохраняется порядок, который выдаёт исходныйdictionaryenumerator; reusable removed slots не дают +обещания исторического insertionorder. Это Ruling135/spec/plan/issue clarification, C#/tests не менялись. +135Ruling17прежнихDeferredMinor сохранены. Final88currentdocs/source/joints ACCEPT0Critical/0Important/0Minor;211accepted/closedcompleted/6criteria[x], +actualProject64Done/P2ArchitectureLowG2Lumens/2labels послеreload подтверждён. Acceptance6788006950, +metadata finalrecord6788179295; proof commonGit/task-policy-rollout-2026-11-10/follow-211-212-20261111/ +project-closeout-211-212.json и issue211-done.jpg прочитаныRoot. Task88 COMPLETE scopedlocal; +Rootsource00/docsf573, finalcloseoutdocs не меняютC#/tests. Parent14/15LIVEopen, no integration/releaseclaim. +ВсеRootUIpaused:59Lessons→60peer137→61released→62Lessonsresume послеfreshreadiness/APKhash проверок; +currentUIowner не перехватывается по времени. Parent14/15 integration/broadernative остаются отдельно. diff --git a/docs/superpowers/plans/2026-11-08-class-decomposition.md b/docs/superpowers/plans/2026-11-08-class-decomposition.md new file mode 100644 index 00000000..b6db2f33 --- /dev/null +++ b/docs/superpowers/plans/2026-11-08-class-decomposition.md @@ -0,0 +1,1266 @@ +# ConfigMaker Decomposition Implementation Plan + +Возобновлён 9 ноября 2026 по прямому запросу пользователя без временного ограничения. Дедлайн и winddown ниже относятся к завершённому первому окну; новые этапы начинаются с Task39 на product e42 / docs63ce869. Остальные ограничения безопасной автономной работы сохраняются. + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox syntax for tracking. + +**Goal:** Extract tree construction and resource editing while retaining current editor behavior. +**Architecture:** Pure tree data and builder, a WinUI adapter, resource registry and reference editor; existing facade/ViewModel APIs stay compatible. +**Tech Stack:** C#, .NET 8, WinUI 3, xUnit; no additional packages. +**Spec:** ../specs/2026-11-08-class-decomposition-design.md + +## Global Constraints + +- Baseline f39e8a0; other session owns security/staging/Update/ZIP/settings. +- No changes to preset formats, localization, XAML bindings or UI behavior. +- Preserve aliases, direct variable paths, Lua markers, blob offsets, profile names and source spans. +- Add test source links without replacing existing project entries. +- User requires no regressions: verify tests and GUI build before completion. +- For all further passes, prefer small utility objects with a neutral purpose when the module's + architecture provides a real boundary. Separate reusable mechanisms from UI/domain orchestration; + do not merely move a coupled large host into another large specialized class. Do not invent generic + abstractions, extra interfaces or claimed reuse without a concrete need. Small domain owners and + WinUI adapters remain appropriate where they preserve coherent state and observable behavior. + +## Review Focus + +- File categories, current-culture sorting and missing/attached file tooltips. +- Empty or marker-only profile fallback and source spans. +- Remove a new resource if neither command nor variables actually change. +- Reuse existing resources for repeated case-insensitive paths. +- Direct paths and command snippets in Value/Values/OnValue/OffValue. + +### Task 1: Pure tree builder and UI adapter + +**Files:** helpers ConfigMakerPresetTreeBuilder.cs, ConfigMakerPresetTreeData.cs, ConfigMakerPresetTreeAdapter.cs; ViewModel.PresetStructure.cs; Presentation/ConfigMakerPresetTreeBuilderTests.cs; additive test source links. +**Interfaces:** BuildFiles(files) returns IReadOnlyList; BuildGroups(options, explicitGroups, isZapret2) returns IReadOnlyList. Constructor takes localize, resolvePath, fileExists and describeOption functions. Adapter returns existing ConfigMakerTreeNode objects. + +- [x] Write tests for categories/sorting/tooltips, empty input, common groups, multiple profiles, name precedence, fallback, descriptions and source spans. +- [x] Run tests against the absent API, then extract the existing algorithms and make tests green. +- [x] Wire builder/adapter while retaining ViewModel notification order; run GUI x64 build. + +### Task 2: Resource registry and reference editor + +**Files:** helpers ConfigMakerPresetResourceRegistry.cs, ConfigMakerPresetReferenceEditor.cs, ConfigMakerPresetResources.cs; Presentation resource/reference tests; additive source links. +**Interfaces:** Registry takes IList, resolvePath, isInsideComponent; exposes FindAttached, CreateUniqueAlias, AddFiles, GetOrCreate overloads, TryUpdateAttachedResource, Remove. ReferenceEditor takes variables, registry, extractFiles, extractDirectFile; exposes AttachExistingFiles(command) and ReplaceReferences(command,file,replacementPath). + +- [x] Test case-insensitive reuse/aliases, Cyrillic, built-in flags, missing files, all variable values, direct/inline paths, blob/Lua and no-op rollback. +- [x] Run tests before classes exist; extract the original algorithms without changing policy; retain the facade API. +- [x] Run targeted tests, full xUnit suite and GUI x64 build. + +### Task 3: Independent review and evidence + +- [x] Compare old/new algorithms and notification order with a fresh reviewer. +- [x] Reproduce any actionable defect in a failing test before fixing. +- [x] Final full xUnit suite, GUI build and git diff --check; record class sizes and limitations. +- [x] Report the isolated diff and next classes without claiming the audit complete. + +## Execution + +User approved autonomous continuation. Execute inline with one final reviewer, without per-task approvals. +User additionally authorized safe local checkpoints and autonomous acceptance until 14:00 MSK on 2026-11-09 (supersedes 02:00). Use deadline-guarded checkpoint.ps1; no deletion/publish/push/merge/reset. Scratch progress: .superpowers/sdd/2026-11-08-class-decomposition. + +### Task 4: App activation dispatcher + +**Files:** Helper/Basic/AppActivationRequest.cs, AppActivationDispatcher.cs, AppActivationRequestAdapter.cs; App.xaml.cs and App.Activation.cs; Presentation/AppActivationDispatcherTests.cs; additive linked test sources. +**Interfaces:** ProcessStartupAsync(string[] arguments, Func getInitialActivation) and ProcessRedirectedAsync(AppActivationRequest). Constructor takes migration-argv, migration-launch, files, protocol, direct, splitter and startup-error callbacks. + +- [x] Write sequence/fallback/partial-failure/await/payload tests before extracting. +- [x] Move orchestration only, preserving callback timing, exceptions and inherited precedence. +- [x] Run targeted/full tests and GUI build; review independently before completion. + +### Task 5: BlockCheck2 options ownership + +**Files:** ViewModels/BlockCheck2OptionsViewModel.cs, IBlockCheck2OptionsSettings.cs, BlockCheck2OptionsSettings.cs; existing BlockCheck2ViewModel partials; Presentation/BlockCheck2OptionsTests.cs and source links. +**Interfaces:** Options constructor accepts typed settings, Func isRunning and Func selectedSiteListCount; properties retain names/types; CreateSessionRequest(Func>) retains evaluation order. + +- [x] Write behavioral tests for defaults, corrupted values, derived validity, recommendations, notifications/save order and request snapshots. +- [x] Transfer state/options logic; forward host properties/events and keep process execution unchanged. +- [x] Targeted/full tests, GUI build and independent read-only comparison with baseline. + +### Task 6: ConfigMaker command-help panel + +**Files:** Helper/CreateConfigHelper/ConfigMakerCommandHelpPanel.cs; ConfigMakerViewModel.CommandHelp.cs/.cs/.Diagnostics.cs; Presentation/ConfigMakerCommandHelpPanelTests.cs and additive production source links. +**Interfaces:** Panel constructor Func localize, Func isEditorReadOnly; Document and stable CommandOptions/CommandModules; existing selection/search/argument properties; SelectCommand, RebuildCommandModules, RebuildCommandOptions, BuildSelectedCommand. INotifyPropertyChanged is forwarded by host; async loading/status/clipboard/editor remain outside. + +- [x] Test module/query/reload/selection/argument/notification/reentrancy contracts against absent panel API. +- [x] Extract existing state and algorithms, retain public host proxies and command notification order. +- [x] Full tests, GUI and actual adapter smoke; independent review vs bdc9170; fix any regression before local checkpoint. + +### Task 7: ConfigMaker test-session lifecycle + +**Files:** helpers ConfigMakerTestSession.cs, IConfigMakerTestTasks.cs, ConfigMakerComponentTestTasks.cs; ConfigMakerViewModel.Testing.cs/.cs; Presentation/ConfigMakerTestSessionTests.cs and source links. +**Interfaces:** Session constructor: tasks, Func currentComponent, Func> confirm, Func installed, Action notice, Func refresh, Action> enqueue; StartAsync(arguments), StopAsync(showCompletionMessage=false), IsTesting, TestComponentId, StateChanged. + +- [x] Test observable process/notice/state order and both failure boundaries before implementing. +- [x] Extract lifecycle; preserve all host APIs, actual process manager methods and live-read timing. +- [x] Full test/GUI run, independent comparison with pre-task checkpoint, local commit after checks. + +### Task 8: ConfigMaker simple-designer ownership + +**Files:** helpers ConfigMakerSimpleDesigner.cs, IConfigMakerSimpleDesignerBackend.cs, ConfigMakerSimpleDesignerBackend.cs; existing SimpleDesigner partial/.cs; Presentation/ConfigMakerSimpleDesignerTests.cs; pure model/base/formatter source links. +**Interfaces:** backend IsSupported, TryLoad, Parse, Build; owner constructor backend/currentComponent/editor getter/setter/three ICommand/notice callback. Owner keeps named collections/properties, MarkDirty, UpdateAvailability, OnEditorViewChanged, OnAdditionalDesignerArgumentsChanged, three change handlers. + +- [x] Test loading/selection/editing/reentrancy/dirty/error contracts before implementation. +- [x] Transfer existing state and algorithms; retain exact production backend and host command identity. +- [x] Full tests, GUI, independent review vs70b4295 and safe local checkpoint. + +### Task 9: App window lookup and creation ownership + +**Files:** Helper/WindowHelper/AppWindowCoordinator.cs, IAppWindowOperations.cs, AppWindowOperations.cs; App.xaml.cs/App.Windows.cs; Presentation/AppWindowCoordinatorTests.cs and additive source links. +**Interfaces:** coordinator receives existing List, Func readiness and operations backend; GetCurrent(Type), CloseAll(Type), CloseTemplate(Type,id), CreateSafeAsync(Type,activate), CreateUnsafeAsync(Type,activate,id). Backend retains actual WinUI APIs and host RegisterWindow. + +- [x] Write tests for readiness/snapshots, reuse/duplicate/dead windows, id matching, close ordering and failure propagation before implementation. +- [x] Transfer rules, preserve public App API/list and event lifecycle boundaries. +- [x] Full suite, GUI, independent review vs b4593ee; safe local checkpoint. + + +### Task 10: BlockCheck2 displayed progress ownership + +**Files:** ViewModels/BlockCheck2ProgressViewModel.cs, IBlockCheck2ProgressEstimator.cs; existing estimator and BlockCheck2ViewModel.cs; Presentation/BlockCheck2ProgressTests.cs and source links. +**Interfaces:** owner receives live targets/validation-attempts/startup-grace providers plus optional existing estimator implementation; Update, StartRun, FinishRun, Reset(beforeNotifications), CompleteDisplayedProgress. Host forwards properties/events and retains result/state/cancellation/history lifecycle. + +- [x] Test displayed progress/target formatting, estimator arguments and sequencing, update/reset/finally notifications and repeated/reentrant reads before implementation. +- [x] Transfer fields and presentation algorithms without changing estimator math, report/state/cancellation ordering or source-of-truth list. +- [x] Full suite and GUI, independent review vs ecc7828, then reversible local checkpoint. + +### Task 11: ConfigMaker help-loading lifecycle + +**Files:** Helper/CreateConfigHelper/ConfigMakerCommandHelpLoader.cs; host CommandHelp.cs/.cs; Presentation/ConfigMakerCommandHelpLoaderTests.cs and source link. +**Interfaces:** loader receives existing panel, live component/localizer functions, production LoadAsync delegate and structure/diagnostics/status callbacks; LoadAsync(componentId,forceRefresh), Cancel, IsHelpLoading/IsCommandListEnabled/UsageText with host event forwarding. + +- [x] Test concurrent/canceled/stale results, notification/callback order and exception/reentrancy boundaries before implementation. +- [x] Move lifecycle unchanged; keep production service/parser/cache, host public APIs and cancel-then-timer order. +- [x] Full tests and GUI, independent comparison with b12d857, safe local checkpoint. + +### Task 12: Fixture-backed live WinUI verification + +**Artifacts:** ignored scratch harness/patch scripts, a pinned short verification source copy; no harness source enters product directories in the task worktree. + +- [x] Create explicit startup/help/process/output/catalog test boundaries in copy and validate data isolation. +- [x] Build and inspect harness boundaries; exercise real controls/window ownership through native UI. +- [x] Record observed behavior/failures and scope limits; reproduce any production regression before fixing. + + +### Task 13: Graphic designer command codec and quoted-value defect + +**Files:** Helper/CreateConfigHelper/GraphicDesignerCommandCodec.cs; existing GraphicDesignerHelper facade; Views/CreateConfigHelper/GraphicDesignerSettingItemModel.cs; Presentation/GraphicDesignerCommandCodecTests.cs and source link. + +- [x] Read and characterize current parse/build semantics and source call sites; write absent-API characterization tests. +- [x] Extract pure model/command conversion unchanged, retain original facade and configuration factories. +- [x] Reproduce quoted unknown-flag roundtrip loss with a real failing test, then fix quote handling; investigate values containing equals before deciding any additional change. +- [x] Full tests/GUI/independent review; repeat relevant live roundtrip and next joint check with the latest completed security commit. + +Code checkpoint 27bfa46: 985/985 tests and GUI x64 Release with zero warnings/errors; independent follow-up review found no remaining actionable defects. Native post-fix editor/designer roundtrip retained the closing quote and showed zero errors/warnings; real enum selection and proxy scalar reads also passed. Joint compatibility with security d65477f passed 1069/1069 tests and GUI with zero warnings/errors. Values containing equals were already preserved by the original first-separator split and required no additional fix. Security d65477f still has its separately reported open filesystem gap; this joint result establishes compatibility only. + +### Task 14: BlockCheck2 result and report ownership + +**Files:** create ViewModels/BlockCheck2RunResultViewModel.cs, IBlockCheck2ReportOperations.cs and BlockCheck2ReportOperations.cs; modify existing BlockCheck2ViewModel.cs/.SiteLists.cs and additive test source links; create Presentation/BlockCheck2ResultTests.cs. The existing public BlockCheck2ResultViewModel remains the window/manual-assignment model. +**Interfaces:** owner constructor (IBlockCheck2ReportOperations, BlockCheck2OptionsViewModel); SetPreparedIssues(IReadOnlyList) is quiet; ApplyRunResult(BlockCheckSessionPreparationResult,BlockCheckRunResult), SetOperationError(string), SetHistorySaveError(string), Reset(Action resetProgress); existing result/report properties and three Save*Async methods. Report operations exposes Build(catalog,preset,targets,result), SerializeJson/Text(report), SaveJson/Text/PresetArgumentsAsync(path,report,token). Actual adapter retains existing service instances. + +- [x] Write characterization tests for empty/failed/best-effort/HTTP-only reports, exact issue matching, session identity/live option timing, partial failure state, lazy serialization and repeated reads, synchronous missing-report export, path/token/task forwarding, exception propagation, repeated error notifications and reset order with the real progress owner. +- [x] Run tests against absent API and retain RED evidence. Extract state/algorithms; preserve host event forwarding and async history/CTS ordering. +- [x] Run targeted and full tests, GUI x64 Release and diff checks. Independently review against aeeba14; reproduce actionable findings before fixing. +- [x] Verify actual host PropertyChanged sender/order and completion notices in an isolated fixture-backed WinUI run; do not launch a real scan or export dialog. +- [x] Record aggregate class reduction, limitations and verified local checkpoint; leave the overall timed goal active. + +Code checkpoint 7188106: 35 targeted cases (including two reentrant scenarios), full 1020/1020 and GUI zero warnings/errors. Review-found name collision and a residual field reference in SiteLists were confirmed by GUI compiler errors and fixed; the pre-existing public model matches the baseline blob exactly. Native isolated host verification passed all 11 result events and all 29 reset events, correct sender/current snapshot/serialization/export flags, and both real completion InfoBars. Fixture process exited zero; real scans/history/disk exports/public Reset were not invoked. Host aggregate 675 to 607 physical lines. + +### Task 15: Manual assignment editor of the BlockCheck2 result window + +**Files:** create ViewModels/BlockCheck2ManualAssignmentEditor.cs and BlockCheck2ManualIssueItem.cs; modify existing BlockCheck2ResultViewModel.cs and BlockCheck2ManualResultViewModels.cs; source-link existing Draft/manual models/rules plus new editor into test project; create Presentation/BlockCheck2ManualAssignmentEditorTests.cs. Preserve the original nullable annotation context for linked legacy sources. +**Interfaces:** editor constructor (BlockCheck2PresetDraft draft, Func session, Func> evidence, Action clearAcknowledgedIssues, Action rebuildPreset, Func? formatActions=null). Items aliases Draft.Assignments. Methods AddForSite/List, RemoveAssignment, MoveAssignment, ClearManualAssignments, GetSiteListPaths, CanAddForSiteList, SeedAutomaticAssignments(session), ClearAutomaticKeys, RefreshEvidenceSelections, RefreshAssignmentIndexes retain host signatures/behavior. Host methods delegate; rebuilding/issue localization/manual tests stay in host. + +- [x] Write characterization tests for collection identity, guard/duplicate/missing definitions, scope compatibility/ignored targets/path sorting, move/remove/clear callbacks, automatic seed primary/fallback/scope/de-duplication, selected/automatic flags, Draft timing, exception/partial state and reentrant collection notifications. +- [x] Observe absent-API RED, move localized issue model intact and extract assignment ownership without altering rules or service calls. +- [x] Run targeted/full tests, GUI and source/API comparison; independent read-only review vs 59a5e8f, reproduce and fix actionable defects. +- [x] Verify relevant real model/collection/UI behavior in a pinned isolated fixture; record evidence, scope limits and class reduction before finalizing the task. + +Code verification: 34 targeted cases, full 1054/1054, GUI zero warnings/errors; independent review and follow-up found no introduced defects. All 13 extracted bodies compare equal after dependency/name substitutions. Public result window model 565 to 402 physical lines; new editor 229. Native Add/Move remains pending. Existing comparer/provenance/scope/reentrancy semantics are characterized and preserved, without claiming their separate baseline risks fixed. + +Native verification investigation: the initial direct-TabView fixture omitted the production Frame/MenuBarHost contract. Three fixture runs did not reach an Add/Move observation; run2 Windows error c00000fd and run3 actual managed UI-thread stack identify AnimatedSelectorBarMenu.ScheduleRetry with a permanently null MenuBarSession. The corrected fixture navigates through a real Frame with MenuBarHost attached, asserts a non-null session before mounting, builds with zero warnings/errors, and passed independent read-only review. All tracked GUI/Shared/Core/AddOns files still differ only at the ten explicit external boundaries. Native repetition is pending while a separate ToolsSmokeTest.exe UAC occupies the common desktop; the exact requested path is unverified and no elevation consent was granted. Keep the last checkbox open until actual Add/Move observations pass. + +### Task 16: ConfigMaker document workflow coordinator + +**Files:** create Helper/CreateConfigHelper/ConfigMakerDocumentCoordinator.cs, IConfigMakerDocumentHost.cs, IConfigMakerDocumentStorage.cs and Tests/Presentation/ConfigMakerDocumentCoordinatorTests.cs. Modify host ConfigMakerViewModel.cs/.Document.cs, existing ConfigMakerPresetStorageService interface declaration only, PresetDocumentConverter's inherited static qualification, and additive test source links for coordinator/interfaces/actual document+converter/save-result/request. +**Interfaces:** coordinator constructor (ConfigMakerPresetDocument document, IConfigMakerDocumentHost host, Func createStorage, Func export). Methods retain host names/signatures for LoadPresetDocument, LoadConfigItem, CreateConfigItem, SaveToApplicationAsync, NewDocumentAsync, SaveTextAsync, SyncDocumentFromEditor. Storage SaveAsync(string,ConfigMakerPresetDocument)/OverwriteAsync(ConfigMakerPresetDocument) return Task. Host supplies ComponentId get/set, EditorText, IsEditorReadOnly, SetEditorText, SetBaseDirectory, RebuildPresetStructure, UpdateSimpleDesignerAvailability, NotifyDocumentStateChanged, AttachExistingPresetFiles, ApplyAutoCorrectorSilentlyAsync(ConfigItem), GetConfigItemBaseDirectory(ConfigItem), AskSavePresetAsync(name,overwriteEnabled), ConfirmNewDocumentAsync(), ChooseExportPath(bool), ClearPresetStructure, ClearEditorUndoHistory, Text(key), ShowDocumentMessage(message,isError). Explicit host implementations forward to existing UI/helpers without changing public API. + +- [x] Write characterization tests using actual document/variable/resource/converter models for load clone/identity/self-load/event timing, config import callback/await order, create current text, sync-attach-sync, dialog cancellation/overwrite, storage factory timing, result identity/live metadata, first alias handling, ordinal cancellation, exceptions/partial state, overlapping saves, New readonly/content/confirmation/clear order and retained metadata, export format permission/cancellation/catch boundaries. Add exact legacy conditional conversion coverage. +- [x] Run absent-owner API RED; preserve it. Implement coordinator by moving the existing workflow, retain private filesystem/autocorrect methods in host. Replace converter's inherited static qualifier with the declaring LScriptCore and link actual models; no test-only model stubs. +- [x] Run targeted/full tests and GUI x64 Release, compare public API/source scopes and run diff checks. Independent read-only review against a260690; reproduce/fix actionable regressions before checkpoint. +- [x] Record class aggregate and verification limits, create scoped local code checkpoint. +- [x] Add fixture-backed native workflow observations when the common desktop is available; fake storage/export in the copy, never invoke actual saves or file deletion for this verification. + +Code verification: 46 new cases, full 1100/1100 and GUI zero warnings/errors; independent read-only review found no introduced defects after comparing all eight moved bodies and explicit host adapters. Document partial 242 to 113 physical lines, aggregate ConfigMaker host 1525 to 1400, coordinator 197. GUI inputs unchanged after its successful build; final tests include seven additional characterization cases. Native host integration remains pending; actual storage/export/autocorrect effects are unchanged and were not executed. + +### Task 17: Actual ConfigMaker document host integration on the UI thread + +**Artifacts:** ignored DocumentHostSmokeBootstrap.cs, prepare-document-host.py, check-document-host-boundaries.py and build-document-host.ps1; new pinned source copy C:/Users/lumen/Programming/cdpiui-host-f7e5454-20261109. No harness enters product source tree. +**Scope:** instantiate the actual ConfigMakerViewModel on Application's DispatcherQueue thread with an inert IConfigMakerView. Keep the complete host, coordinator, document, converter, structure adapter and XAML assets unchanged. Explicit fixture boundaries: Program/Main and App startup; own-bin-only DataDirectory; resource facade catalog path lookups; ComponentCommandHelpService.LoadAsync; storage SaveAsync/OverwriteAsync and exporter ExportAsync entrypoints. No actual storage, exporter, auto-correct, component test, scan, history, shell, window navigation or desktop input. + +- [x] Create fresh pinned copy, preserve all older copies, and verify every tracked GUI/Shared/Core/AddOns source/asset against f7e5454; require exactly seven changed boundary files plus one explicit bootstrap. +- [x] Independently review boundaries and assertions before execution; build with zero warnings/errors. The executable manifest remains asInvoker; fixture asserts portable own binary data root and UI-thread affinity. +- [x] Exercise real host Load, help, deferred Save, exporter success/failure/cancel, readonly/cancel/deferred-confirm New, ConfigItem creation/load. Assert document/collection identities, command/editor/diagnostics state, actual event sender and partial-state order, resource updates and status severity/message. Export/storage are inert and no physical config is saved. +- [x] Confirm process exit zero and exact PASS groups/no FAIL; record logs/pin/hash and scope limits. This closes real-host adapter runtime coverage only. Keep interactive Task15 Add/Move and Task16 control UI gates open until real observations pass. + +Verified actual-host integration: exact product f7e54545ba27fee6622e79bc2f95f65c3df88aad; 1190 tracked GUI/Shared/Core/AddOns files, seven explicit boundaries plus bootstrap/verified empty Secret stub. All seven assertion groups passed; PID27288 exited zero, no FAIL, no stdout/stderr. Full literal document state sequences8/3/4 and independent current-editor read were strengthened after review before execution. Build zero warnings/errors; main product inputs unchanged. DLL SHA25627607C62EFF27363E30F491D5D5C5FE5B8B6D11CEE103F77B1639DDC631714F9. Interactive control gates remain open. + +### Task 18: Missing preset file replacement workflow + +**Files:** create Helper/CreateConfigHelper/ConfigMakerPresetFileReplacer.cs, IConfigMakerPresetFileReplacementHost.cs, IConfigMakerPresetFileReplacementBackend.cs (including auto-corrector contract), ConfigMakerPresetFileReplacementBackend.cs and Tests/Presentation/ConfigMakerPresetFileReplacerTests.cs. Modify host main/PresetFiles partials and additive test source links for owner/contracts/existing choice enum. Keep Document partial's silent wrappers compatible; do not change actual resource/autocorrect implementations. +**Interfaces:** replacer constructor(host,backend); ReplacePresetFileAsync(ConfigMakerPresetFileInfo?), TryCreateEmptyPresetFile(string,bool=true), TryApplyPresetFileReplacement(ConfigMakerPresetFileInfo,string,bool). Host exposes RunReportingErrorsAsync(Func), AskPresetFileReplacementAsync(path), ChooseReplacementFile(path), Text(key), ShowPresetFileMessage(message,severity), RebuildPresetStructure(), UsesExplicitPresetStructure, ConfigMakerPresetFileInfo[] ExplicitPresetFiles get/set, SetCommandText(string), NotifyPresetFileReplaced(originalPath,replacementPath). Backend exposes TryResolvePath, FileExists, CreateEmptyFile, TryUpdateAttachedResource, ReplaceReferences and CreateAutoCorrector; corrector ShouldSuggestEmptyFile(string)/Task FindReplacementAsync(string). Backend constructor only stores the existing facade. Notice severity is Success/Warning/Error and maps explicitly to WinUI in host. + +- [x] Write tests for null/invalid/existing/cancel/manual/auto paths and asynchronous timing, lazy corrector factory, empty-file/suggestion/manual fallback rules, attached-vs-reference branch, normalized path checks, explicit array identity/matching/retained fields, conditional formatted command assignment, post-rebuild event timing, silent status, partial mutations and all catch/exception propagation boundaries. Use no real filesystem/shell operations. +- [x] Observe absent-owner API RED and preserve output. Extract workflow and add thin production adapters, retaining public signatures, silent Document callers, conditional event construction/sender and actual algorithms. +- [x] Run targeted/full tests, GUI x64 Release, source/diff checks; independent read-only comparison with8039f8a. Reproduce and fix introduced defects before checkpoint. +- [x] Record aggregate reduction, limitations and scoped local code checkpoint. +- [x] Add actual-host fixture verification without filesystem effects if possible. Keep prior interactive gates separate. + +Code verification: 46 new targeted cases, full1146/1146 and GUI zero warnings/errors. Read-only independent review found no introduced defects in all seven moved methods, host/backend mappings and silent callers. File partial327 to178 physical lines, aggregate host1400 to1254; replacer194. No actual filesystem/shell operations executed in the new tests. Actual-host event/backend runtime check remains separate; conditional event sender/read and synchronous snapshot-before-Task.Run are statically verified so far. + +### Task 19: Actual missing-file replacement host integration + +**Artifacts:** new ignored ReplacementHostSmokeBootstrap.cs, ReplacementHostCases.cs and make/prepare/check/build-replacement-host scripts; fresh pinned copy C:/Users/lumen/Programming/cdpiui-replace-01163f0-20261109. Preserve all older copies. Product pin01163f080d96139111d06970ad384825cbe467f6. +**Scope:** actual host/replacer/document/registry/reference editor and Task.Run wrapper. Eight boundary files: same seven startup/data/catalog/help/storage/export boundaries as Task17, resource snapshot creation inert, plus low-level replacement backend FileExists/CreateEmpty/FindReplacement target. Do not call original autocorrect search, physical file creation, public silent-autocorrect import, component testing, shell, history or desktop input. Test silent private helper forwards directly on the UI thread. Keep document regression groups at the new constructor/host composition pin; do not count them as new unit tests. + +- [x] Create and source-check the fresh copy: all tracked GUI/Shared/Core/AddOns sources/assets compared to pin, exactly eight boundary files and only two bootstraps/empty Secret stub added. Actual host/replacer/registry/reference editor remain unchanged. +- [x] Build zero warnings/errors and independently review safety/assertions before execution. Require own binary data root/asInvoker and thread affinity; bounded worker wait always released in finally. +- [x] Verify manual reference replacement with resource-event reentry and post-rebuild command change, explicit array and variable updates, real event sender/args/status; attached branch preserves command/array/event absence; auto snapshot is prepared on UI thread before worker and uses old component while live editor/component change; empty branch and direct silent helpers have expected event/status behavior with no physical files. +- [x] Run all twelve assertion groups (seven document composition, five replacement groups), require process exit zero/no FAIL, record logs/hash/pin and exact scope. Keep interactive control gates distinct. + +Verified actual replacement host integration: PID43396, exact01163f080d96139111d06970ad384825cbe467f6; twelve groups passed, exit0, noFAIL/stdout/stderr. Build0warnings/errors; independent1431-file archive comparison,1194 within the four product roots; eight boundaries/two bootstraps/empty stub. Manual/attached/auto/empty/silent helper paths covered with actual host/registry/reference editor, UI snapshot and worker/return affinity. Full silent-autocorrect import, physical IO/search and interactive controls not executed. DLL SHA25610A8E8BD2B5238461F8D6DB9FD44C5CFF361F6AA06E40101EA744E7C975B04EE. Root1146/1146 unchanged. + +### Task 20: Remaining preset file tree actions + +**Files:** create ConfigMakerPresetFileActions.cs, IConfigMakerPresetFileActionsHost.cs, IConfigMakerPresetFileActionsBackend.cs, ConfigMakerPresetFileActionsBackend.cs under Helper/CreateConfigHelper and Presentation/ConfigMakerPresetFileActionsTests.cs. Modify host main/PresetFiles and additive test source links. Reuse existing file-notice enum and real document/resource/file models; no new package. +**Interfaces:** constructor(IList,host,backend), AddPresetFiles(IEnumerable), AddPresetFilesFromPicker(), OpenPresetFileAsync(FileInfo?), ShowPresetFileInFolder(FileInfo?), RemovePresetFileAsync(FileInfo?), InsertPresetFileReference(FileInfo?). Host: RunReportingErrorsAsync, ChoosePresetFilesToAdd, AttachExistingPresetFiles, RebuildPresetStructure, SetPresetFilesPanelVisible, Text/ShowPresetFileMessage, AskTextFileApplicationAsync, ConfirmRemoveReferencedFileAsync, ScheduleDiagnostics, IsEditorReadOnly, InsertAtCursor. Backend: AddFiles, ResolvePath, TryResolvePath, FileExists, GetOrCreate(fullPath,kind,out bool), FindAttached, IsReferenced, ShouldAskForTextApplication, RememberTextFileDialogShown, OpenTextFile, OpenFileInDefaultApp, ShowFileInFolder. + +- [x] Characterize original enumerable/count/picker/add order, text/nontext open and dialog await/preferences/shell routing, missing/show sync exceptions, null/unattached/referenced removal, resource identity across confirmation/reentrant subscriber failures, readonly/preset URI/direct path insert, full-path timing and late resource alias after rebuild. No real filesystem/shell/preferences execution. +- [x] Observe absent-owner API RED, then move unchanged workflow into owner and add thin production adapters. Preserve private picker method and command identity, original catch scopes and all public signatures. +- [x] Run targeted/full tests, GUI x64 Release and diff/source checks; independent read-only comparison with29b05a8, reproduce/fix introduced defects before checkpoint. +- [x] Record aggregate/class reduction and scope limits; create scoped local code checkpoint. +- [x] Add actual-host fixture coverage when feasible while preserving existing pinned copies and interactive gates. + +Code gate: 47 targeted cases, full1193/1193 with no failed/skipped; GUI x64 Release0warnings/errors47.43s. Independent read-only review accepted all seven transferred methods, twelve backend forwards and host composition; no findings or declined-to-judge items. PresetFiles178 to79 physical lines, aggregate1254 to1158, new owner152. Real settings/shell/filesystem and interactive controls not executed by the unit suite. + +### Task 21: Actual file-actions host integration + +**Artifacts:** fresh pinned copy C:/Users/lumen/Programming/cdpiui-actions-a87f27b-20261109; FileActionsHostSmokeBootstrap.cs, FileActionsHostCases.cs and make/prepare/check/build scripts in ignored plan scratch. Product pina87f27ba078f1d8041f005436f356ec302ae65c7. Keep all older copies intact. +**Scope:** actual ConfigMaker host, file actions/replacer/document owners and registry/reference editor. Same eight startup/data/catalog/help/storage/export/replacement boundaries asTask19, plus actions backend preference and shell calls recorded instead of executed. Real action File.Exists/path/registry operations retained. After exact own-bin/asInvoker/data-root guards create exactly three harmless new input files using FileMode.CreateNew, preserve their bytes and leave them in the fixture. Never overwrite/delete them or execute shell/settings, original autocorrect search, real storage/export/component tests or desktop input. + +- [x] Source-check pinned four product roots, exactly nine boundary files and three bootstraps/empty Secret stub. Build zero warnings/errors; independent safety/assertion review before execution. +- [x] Verify actual add/picker filters, kinds/metadata/tree/counts/command identity; text open dialog await true/false and inert shell routes with real file resolution; missing/null warning guards; remove original object after pending localized confirmation and actual rebuild/timer; insert real registry with alias mutation during rebuild and real editor/cursor/event order. +- [x] Run all seventeen assertion groups, require exit0/noFAIL and unchanged input bytes; record hash/log/pin and exact runtime limits. Keep interactive gates15/16 open. + +Runtime gate: PID37800, exit0, all17PASS/COMPLETE, noFAIL/stdout/stderr. Final reviewed fixture build0warnings/errors41.13s; independent all1436tracked-file comparison including1198 in product roots, nine boundaries and three bootstraps/empty stub. Before execution fixed byte-comparison, timer-precondition and nonnull-readonly assertion gaps; product unchanged. DLL80A6485ADEFEDE1D24FDEBBAF2A39538DBC7D82222D90AEEA7FC19013AC1396B. Three CreateNew input files retained with exact bytes; real shell/preferences/storage/export/search/components and interactive controls not executed. Full attach ordering/exceptions characterized by Task20 unit tests and static review rather than exhaustively by this runtime suite. + +### Task 22: Caller-visible source API inventory + +**Artifacts:** ignored api-compatibility project/input/controls/logs in plan scratch. Uses Roslyn bundled with the existing SDK8.0.427; no product dependency or source changes. Pins f39e8a0 to00fb0ad (producta87f27b). + +- [x] Read all tracked GUI C# source blobs from both pins, parse without executing product initializers, compare existing exported type declarations and explicitly declared public/protected method/property/accessor/event/field/constructor signatures, generic constraints, parameter defaults and enum member values. +- [x] Treat async implementation modifier and inaccessible private/internal accessors as implementation details. Validate a positive control for async/private-setter changes and a negative control that independently removes a public setter, changes a property type and changes a parameter default. +- [x] Record exact syntax-only scope and evidence; keep runtime/binary/API-synthesis claims separate. + +Result:451original exported types across517baseline/559final GUI C# files, zero removed/changed compared signatures. Positive control exit0; negative control exit2 with exactly3expected changes. No product change, full suite1193/1193 and GUI0/0 remain tied to the unchanged product checkpoint. This inventory does not resolve aliases/base/interface lists, inherited/synthesized members, attributes or binary ABI, and does not replace runtime/source review. + +### Task 23: Whole-branch review and one fix pass + +**Range:** f39e8a0 to00fb0ad; fresh whole_branch_review using review package/ledger/spec, all95files. No Critical, one Important incomplete quoted codec repair, one Minor duplicate mapping. Root accepts Important by actual effect despite inherited baseline defect; it belongs to the already authorizedTask13 quoted-value repair. No second reviewer after the fix. + +- [x] Regrade findings and record all declined scopes/rulings; defer Minor duplicate facade/editor file-kind mapping. +- [x] Reproduce repeated quoted root-relative/dash-leading path loss and literal known-option filename activation with RED tests. Keep true whole-quoted options after bare flags and unquoted separate legacy boundaries. +- [x] Preserve explicit inline ownership for unknown values resembling options; distinguish whitespace before/after first equals in whole quoted tokens. Validate three repeated visits, known/unknown and inline/separate paths, whole quoted/bare inline forms. +- [x] Run all codec tests67/67 and full suite1214/1214 nofailed/skipped; GUI x64Release0warnings/errors11.67s. Scope checkpoint; no arbitrary minor fixes or second review. + +RED evidence: final-codec-red.log11fail/4pass; extra same-root-cause inline control final-codec-inline-ownership-red.log6fail/3pass. Final GREEN final-codec-complete-green.log67/67; final-codec-fix-tests/gui logs.21new cases. Update exact-pin facade runtime and joint compatibility separately; older17groups and1328joint results retain earlier pins. + +### Task 24: Final codec facade integration and refreshed compatibility + +**Artifacts:** new pinned C:/Users/lumen/Programming/cdpiui-facade-80521fc-20261109, CodecFacadeCases.cs plus cloned own-root guarded bootstraps/scripts. Product80521fcfd62ac393c05def42cfe7322a3a728250. Prior fixtures unchanged. No new external boundary beyond the same nine accepted inTask21; only one additional pure in-process codec test file and Run call. No added windows/desktop input or component/settings/shell/filesystem operation. Three prior CreateNew inputs remain part of the reused seventeen host groups. + +- [x] Source-check all tracked four-root files against pin: exactly prior nine boundary files, four bootstrap files/emptySecret. Inspect new codec call paths and generated root/pin/build/run guards before execution; build0warnings/errors. +- [x] Verify actual GraphicDesignerHelper catalog/facade/models and dynamic factory on DispatcherQueue: three repeated path/ownership visits, genuine whole quoted options, decoded proxy scalars. Retain prior seventeen host assertion groups at the final constructor/codec pin; require21PASS, COMPLETE, exit0/noFAIL/stdout/stderr. +- [x] Refresh joint compatibility of80521fc with documented committed security38ec905 (owner911/911). Never include security cleanup WIP; preserve older snapshots. Record exact pins/hash/logs and unverified native control limits. + +Facade fixture sourcechecker1198tracked productroot files, nine boundaries/four bootstraps/emptySecret. Build0warnings/errors82.87s. PID39492, exit0,21PASS+COMPLETE/noFAIL/stdout/stderr; three inputs byte-identical and retained. DLL9273C5C3D990566EFDFB7F622007E234191FCDAC4826637C0E537D5C7E2363C6. Four new groups use actual facade/catalog/models/dynamicfactory, no controls or external operations. Root inspected added pure call paths and unchanged accepted boundaries; no second product review. Joint80521fc+38ec905 suite1357/1357 nofailed/skipped49s; GUI0warnings/errors81.08s. Security cleanup WIP excluded. + +### Task 25: App file activation routing + +**Base:**906b218d807ebfa73c79d583f1b0e970ceee85dc; previous whole-branch review/fix remains complete. This new App extraction gets its own review of the new range, not re-review of the fixed codec. **Files:** new Helper/Basic/AppFileActivationHandler.cs, IAppFileActivationOperations.cs, AppFileActivationOperations.cs, Presentation/AppFileActivationHandlerTests.cs; App main/Activation and additive test links only. All four new paths verified absent. +**Interfaces:** handler(operations).ProcessFiles(string[])->Task. Operations: LogFile(string), PathExists(string), IsConfigShareSupported(string), OpenConfigShareAsync(string), OpenConditionalTaskAsync(string), OpenUpdateFileAsync(string), OpenStorePackAsync(string). Production constructor(App,Func conditional callback), store-only. Source algorithms/importers/security/Program/migration/dispatcher contracts unchanged. + +- [x] Write characterization and observe absent-owner API RED: guards, whitelist/case/all-quotes/no-trim, order/precedence/first-file, faults/cancellation, await all route tasks and reentrant live array. +- [x] Transfer ProcessFiles and static whitelist; keep private App forward and store-only composition. Move exact share/patch/store window actions into thin production port; conditional method unchanged and invoked through original callback. Preserve fire-and-forget pack import and debug log source. +- [x] Targeted/full tests and GUI x64Release, independent read-only review of all new range/mappings vs906b218, resolve introduced defects with RED/GREEN before checkpoint. No real files/windows/import/update actions. +- [x] Record reduction, exact scope and local checkpoint. Consider source-boundary runtime integration if useful; do not duplicate unchanged older gates or claim full startup/import execution. + +Verification: absent-ownerCS0246 RED;41targeted PASS, initialfull1255/1255+GUI0warnings/errors45.93s. Added4real AppActivationDispatcher+handler composition cases (initial file/argv suppression, startup error catch, redirected error propagation, redirected launch fallback); finalfull1259/1259 nofailed/skipped. After GUI only tests/docs changed. Independent review accepted routing and all7production port methods/composition/endpoints, no findings; real startup/windows/import/security execution excluded. App aggregate794->754, activationpartial259->215, owner55/backend50. Additional async adapter task frames noted but effect/order/context/fault/cancel semantics retained by source comparison. Optional actual-App private-forward/adapter-order fixture considered separately, with inert fake window/import targets only; no runtime import claim. + +### Task 26: Actual App file routing composition with inert window targets + +**Decision by executor under delegated autonomy:** close the new production adapter order/composition gap using a fresh pinned copy, not real imports or windows. Product c16a18afe72255d9ef19c8b6d9fc815fde492100. Derive from Task24 facade harness into a NEW short path; never rewrite an older copy. Keep prior21groups. Added AppFileActivationCases.cs is scratch/bootstrap only. Exactly one new boundary file (AppFileActivationOperations.cs), total10; five bootstraps/emptySecret. App ctor before InitializeComponent, handler and activation dispatcher remain actual source; preserve the prior safe startup cut after it. + +**Boundary details:** production operations LogFile/PathExists targets record/consult own-bin fake markers. IsConfigShareSupported remains actual safe extension predicate. Replace only share/update/store factory targets with bounded plain-object fake window factories, and ActivateWindow targets with recorder; keep original await/create/set/activate and fire-and-forget method bodies. Fake object SetFileAsync waits a controlled task, SetUpdateFilePath records synchronously, SetPackFilePath returns an intentionally incomplete task. Replace conditional invocation target with inert task; reflection independently asserts the stored original callback target/method and App instance identity before tests. Do not call real callback. All marker paths exact direct children of guarded bin. No actual WinUI window instance, real file/package load, update, settings, shell, pipe, tray, driver or component operation is allowed. + +- [x] Prepare five new runtime assertion groups: actual App/handler/operations/dispatcher field identities and empty/unsupported/missing guards; share awaits factory then activates before awaited SetFile; patch set-before-activate and store awaits factory with default activate=true but does not await pack import; conditional captured callback identity plus awaited inert target; actual private forward/redirected File dispatcher preserve result/fault/cancel and first-file behavior. Thread affinity for every recorded operation. Retain26total groups. +- [x] Make all pending factory/import tasks bounded, release/cancel them in finally and observe completion even on early assertion failure. Source checker all four-root files against pin, exactly10boundary files and five bootstraps/emptySecret; additionally inspect all new call paths and constructor retention. Build0warnings/errors, independent safety/assertion review before execution. +- [x] Run asInvoker own-bin/no-window fixture only after review; require26PASS, COMPLETE, exit0/noFAIL/stdout/stderr. Preserve three prior CreateNew input files and byte checks. Record exact scope/pin/hash/logs, source comparison and process exit; do not count fake windows as native UI or full production startup/import. Keep prior interactive15/16 gates open. No need to repeat unrelated source checks until a new concern justifies them. + +Runtime targets are deliberately substituted; success would prove App private forward and the retained production adapter orchestration with inert targets, not actual WinUI window factory/activation or importer correctness. Do not claim actual Path.Exists execution in this fixture (unit/static comparison already establishes original mapping); markers replace it. Joint compatibility can be refreshed at a later stable code freeze rather than for every docs/harness step. + +Verified: independent safety/assertion review accepted1201tracked productroot files, exactly10boundaries/fivebootstraps/emptySecret; App ctor before InitializeComponent exactpin. Build0warnings/errors65.73s. PID44836 started07:55:20.1981878Z, exit0at07:55:22.3576511Z;26PASS/COMPLETE/noFAIL/stdout/stderr. DLL57584342D4D1ED45EF73F3B9937565053D0630E80DDD28F87C5B79E82055FECC. No mandatory fixture fixes. ActualApp bindings/handler/adapter sequence/dispatcher proven with inert targets; actualwindows/imports/Path.Exists/startup unexecuted. Three input files retained exactbytes; postrun sourcecheckPASS. + +### Task 27: BlockCheck2 manual preset state + +**Base:**2d4202dd6f4c406c7484ead6612703f758b318c2. **Files:** create ViewModels/BlockCheck2ManualPresetState.cs, IBlockCheck2ManualPresetHost.cs, IBlockCheck2ManualPresetOperations.cs, BlockCheck2ManualPresetOperations.cs and Presentation/BlockCheck2ManualPresetStateTests.cs; modify public BlockCheck2ResultViewModel and additive test links only. All5new paths verified absent; never overwrite public existing result class. Owner(Draft,IReadOnlyList,host,operations), Rebuild(bool), ClearResult(), Arguments, static OptionsFor(session). Host Session getter/ClearIssues/AddIssueGroup(severity,code,message,count,IEnumerablesubjects)/RefreshAssignmentIndexes/RefreshEvidenceSelections/NotifyManualState. Build port takes catalog, targets, assignments, evidence, options and returns existing result. + +- [x] Write behavior tests with real Draft/assignment/domain types and fake host/Build; absent-owner API RED. Cover empty/populated ordering, update flag/expert state, deferred overlay/comparers/targets/current session, options/grouping/subjects, live callbacks and partial failures. +- [x] Move result/rebuild/subject/options logic, preserving private host forward, exact Load clear position, localized issue/ack adapter and same domain service. No direct network/testing/assignment editing policy changes; no UI localizer stubs. +- [x] Run targeted/full tests and GUI x64Release; independent new-range read-only review vs2d4202d including real host/IssueItem/service callbacks. Resolve introduced defects with RED/GREEN before local checkpoint. +- [x] Record physical reduction/exact scope, tests/review/risks and checkpoint. Assess separate real public-model runtime using initialized localizer and pure manual build; never call live TestStrategyAsync. + +Verified: absent-ownerCS0246RED, initial36targeted/full1295+GUI0warnings/errors49.24s. Independent review accepted all transferred logic, host/state/service bindings/localizedIssueItem/ack mapping with no findings. Added3cases for populated Profiles reaching real Draft.Groups and invalid site-list scope failure/blank laziness, final39targeted and full1298/1298 nofailed/skipped. After GUI only tests/docs changed. Public result402->319physical lines, state133/backend18; no public API/collection/sender/network/domain builder change. Real public model/localizer/ack filtering/production Build runtime remains separate; do not count fake host tests as it. + +### Task 28: Actual manual preset public-model integration + +**Executor decision under delegated autonomy:** verify actual public model/localizer/ack/domain-Build composition with the initialized Application DispatcherQueue and pure fixture data. Product a29b1f19fe9f22167290106e039e74830c3a7028. Derive NEW C:/Users/lumen/Programming/cdpiui-manualstate-a29b1f1-20261109 from Task26 App harness. Keep prior26groups, add ManualPresetHostCases.cs as sixth bootstrap and five groups (31total). Same10boundary files: no changes to public model/state/editor/IssueItem/preset service/writer. Never run live TestStrategyAsync, probes/components, persistence/history, windows or UI controls. Inspect ctor/call paths before execution. + +**Fixture data:** reuse only the pure two-strategy/one-target/catalog/report pattern from ignored ManualSmokeBootstrap.cs around290-310, never its window/page setup. fixture-split(multisplit,pos1), fixture-disorder(multidisorder,pos2), three successful attempts each, TLS12/IPv4 example.test. Actual ReportBuilder/preset builder. For site-list scope use existing own-bin actions-sites.txt from prior groups and explicit Target.HostListPaths; no new file/user path. + +- [x] Five groups: Load/session/report/evidence and stable identities; programmatic Add(split),Add(disorder),Move(split,1),Clear with independent action arrays and12hostnotifications per edit; overlapping site+site-list scopes yield localized MANUAL_SCOPE_OVERLAP/subjects, QuickFix acknowledges exact key and private Rebuild(false) stays suppressed until editing clears ack; Load(report) observes previous result during ManualIssues.Clear then clears at original point, same collections; an already-completed manual failure ProbeResult injected only into existing private list affects actual builder overlay (no live test), and reload clears that same list. Check nonempty Draft.Groups. +- [x] Literal actions from previous fixture: split --lua-desync=multisplit:pos=1; two same-site assignments --lua-desync=circular:fails=3:maxseq=32768:inseq=4096, --lua-desync=multisplit:pos=1:strategy=1, --lua-desync=multidisorder:pos=2:strategy=2:final; moving swaps action order/indices. Inspect unchanged builder for precise failure issue expectations, never compute expected output by re-running the implementation under test. +- [x] Fresh paths guard; sourcechecker all4roots exactpin, same10boundaries/sixbootstraps/emptySecret. Inspect new pure ctor/Build/localizer/assignment call paths; build0warnings/errors; independent safety/assertion review before first execution. +- [x] Require31PASS/COMPLETE/exit0/noFAIL/stdout/stderr, process finished, prior3inputs byte-identical retained. Record pin/hash/scope; no native-control/live-test claim. Keep gates15/16 open and corrected native921 fixture preserved/unlaunched. + +After this freeze refresh joint compatibility at a documented committed security pin (latest read a99d0d0, owner926/926). Do not include promotion WIP/edit other worktree. Preserve all previous copies/logs; no routine unchanged root-test reruns for harness/docs. + +Verified:1205tracked productroot files, same10boundaries/sixbootstraps/emptySecret; independent safety/assertion reviewACCEPT, no mandatory fixes. Build0warnings/errors69.67s. PID35764 start08:26:29.9213722Z, exit0at08:26:32.3312406Z:31PASS/COMPLETE/noFAIL/stdout/stderr. DLLD320B404D6DCCB1C85440F314AE88B14D613DDD2BCDE99D30EAD04D09CD1E1A6. Manual models/state/editor/IssueItem/localizer/service/writer unchanged froma29; actualactions/events/ack/reset/overlay passed, no live testing/controls. Beforeexecution root refined assertion to move-back originalkey and canonical domain strategyid; no productchange. Threepriorinputs exactbytes retained, processgone. +Joint a29b1f19fe9f22167290106e039e74830c3a7028+a99d0d0c0c433f9878fdfc0b4af7fa4a79bb4c73:1456/1456 nofailed/skipped74s, GUI0warnings/errors62.24s. Explicit productpin allowed docs-only HEAD via source-diff guard, clean working tree at snapshot, no product overlap, additive testitems only. Promotion WIP excluded; old snapshots preserved. + +### Task 29: Manual strategy test controller + +Base83a44cf, producta29b1f1. Executor accepts the above bounded extraction under delegated autonomy. Keep service/list initialization, public methods and actual domain behavior. No live TestWithCdpiuiAdaptersAsync execution in checks. + +- [x] Write actual EvidenceItem/Draft tests with fake operations; absent-controller API RED. Cover no-session and sync argument failures, fresh options/identity/timeouts/token, pending/fault/cancel, completion order, current draft/session/list reentry, overlay comparers, partial exceptions and captured SynchronizationContext. +- [x] Mechanically transfer bodies into controller; thin same-service adapter and host forwards. Preserve ConfigureAwait(true), sync GetFull argument order and no-session-before-item async guard. +- [x] Targeted/full tests, GUI x64Release, independent new-range read-only review vs83a44cf. Fix introduced defects with RED/GREEN. Do not reopen completed codec review. +- [x] Record physical reduction, exact checks, inherited behavior rulings and remaining native/live-backend limitations; scoped local checkpoint. + +Verified: CS0246 absent-controller RED;32targeted/full1330, GUI0warnings/errors41.01s. Independent manual_strategy_test_review ACCEPT, no findings, real service/host/item/state callbacks inspected. Added5coveragecases for empty/failed/partial/success actual evidence projection and returned-pair replacement/live list edits by observer; finalfull1335/1335 nofailed/skipped9s. These five test-only cases added after reviewed snapshot; product unchanged after GUI/review. PublicResult319->268physical lines, controller87/adapter26. Scope rulings: preserve inherited sync no-session failure, stale-item/current-list application after Load, backend-owned cancellation, completion order and partial mutations without rollback. Cost: no stronger cancellation/lateness guarantee; live runner/network/component recovery and interactive controls remain unexecuted. No second codec review. + +### Task 30: Actual manual strategy test composition with inert backend + +Product25e1db7042707d752cea35d4cdfb5317fe54eae2. Derive NEW cdpiui-manualtest-25e1db7-20261109 from Task28 harness; preserve prior31groups and add5runtime groups (36total). Keep public model/controller/operations/evidence/state/preset-builder/localizer exactpin. Add eleventh explicit boundary ONLY in AddOns BlockCheckManualStrategyTestService: fixture-only static typed delegate and replace TestWithCdpiuiAdaptersAsync runner creation/execution target with delegate invocation (throw if absent). Pure GetFullStrategyArguments remains actual writer call. Never invoke service.TestAsync/real strategy/probe runners/network/components. All prior10boundaries unchanged after root/pin substitution. + +- [x] Five groups: actual ctor identity/callback binding and pure full arguments; unavailable result before item/backend; controlled pending result through public forward->samecontroller->sameadapter->servicehook, verify options/token, UI thread notifications and actual state rebuild/localized issue; Load while pending applies to same list/stale item/current session; fault/cancel/overlap order with bounded task release and cleanup. Literal output/actions/issue codes independent of implementation calls used as oracle. +- [x] Add seventh bootstrap ManualStrategyTestHostCases.cs. Sourcechecker exact4roots/pin/11boundaryfiles/7bootstraps/emptySecret; preserve alloldcopies. Fresh-path/root/asInvoker/process/deadline guards retained. +- [x] Build0warnings/errors; independent safety/assertion review before first execution. Runtime requires36PASS/COMPLETE/exit0/noFAIL/stdout/stderr, postsourcecheck, finishedprocess and unchanged prior3input bytes. No native-control/live-backend claim. + +Verified: independent safety/assertion ACCEPT1208files/exact11boundaries/sevenbootstraps+emptySecret, additional buildinputs exactpin. Build0warnings/errors79.92s. PID14584 start08:50:40.3342330Z, exit0end08:50:43.1441970Z:36PASS/COMPLETE/noFAIL/stdout/stderr. DLL9A619EEA572D498CCD9B0ED5CF4FE7E69F39488C38D0F935139A344DC11A5371. Samecontroller/adapter/model/state/localizer/service-writer composition confirmed on actual DispatcherQueue; external service target inert, real TestAsync/runners nevercalled. Threeownbininputs byteidentical retained, postsourcecheckPASS, processfinished. No productchange. Preserve native15/16 gates and allpreviouscopies. + +API syntax inventory refreshed f39e8a0->25e1db7 using same Roslyn runner/previouslyvalidatedcontrols:451originalexportedtypes,517->569GUIC#files,0removed/changed compared signatures. Only source syntax; no ABI/inheritance/semanticattribute/runtime guarantee. + +Updated joint freeze: GUI25e1db7042707d752cea35d4cdfb5317fe54eae2 + committed security80c17c11be80c708d5985533dee8683781ee8e7f vsf39, fresh cdpiui-joint-80c17c1-20261109. Securityowner967/967 documented, laterWIPexcluded.1534/1534 nofailed/skipped75s; GUI0warnings/errors68.84s. Sameclean/pin/source-no-overlap/additive-test-items guards. Originalworktrees and allpreviouscopies preserved. Durablejournal/globalmutex/handoff/restart/MSI/Storepromotion remainseparate. + +### Task 31: ConfigMaker variable actions + +Base2295bbd, product25e1db7. Executor accepts this bounded extraction under delegated autonomy. Preserve all variable/document formats and actual host callbacks; do not run real dialogs/files/components/network. + +- [x] Characterization with real document/variable/collection/content events and fake host. Absent-owner API RED; cover null/cancel/pending, reference equality/current membership, ordinal rename/replacement/reentry index timing, current command reads, removal confirmation/live object, insertion evaluation order, partial exceptions. +- [x] Transfer four workflows into ConfigMakerVariableActions + host port. Modify original Variables partial, keep RunReportingErrorsAsync/CreateVariableCommand/private forward and exact localized confirmation. +- [x] Targeted/full tests, GUI x64 Release and independent new-range read-only review vs2295bbd. Fix introduced Critical/Important with RED/GREEN, log deferred minors and inherited rulings. +- [x] Record reduction/checks/limitations and scoped local checkpoint. Assess actual host runtime proof separately; no routine refresh of unchanged joint/API snapshots. + +Verified: absent-owner CS0246 RED, 38targeted PASS, full1373/1373 nofailed/skipped14s, GUI0warnings/errors45.29s. Independent variable_actions_review ACCEPT: exact transferred bodies, actual document/editor/Attach/tree/diagnostics/dialog/localizer/errorwrapper/XAML command bindings, no Critical/Important/Minor. Nullable enableannotations begins only below public forwards, preserving their original annotation context. Variables partial84->36, ConfigMaker aggregate1158->1112, owner85. + +Executor rulings on every set-aside line: preserve inherited pre-event index despite reentrant move/clear (cost: same wrong-row/partial failure possible for such observers); preserve late-dialog Edit membership/Create current collection/Remove original-object behavior (cost: no new stale-operation cancellation); preserve real adapter late OriginalName evaluation (cost: outside name changes while dialog awaits may affect replacement as before); preserve partial callback changes and outer logger/status wrapper (cost: no rollback). Actual native dialogs/queued lifecycle/editor or Attach external IO/logger/status/visual result unexecuted; source wiring and compile are evidence for mapping, not runtime proof. No mandatory review fixes or deferred new minors. + +### Task 32: Actual ConfigMaker variable host composition + +Product c480fd3cc218526da792ac2c9b3a7b982ae8a584. NEW cdpiui-variables-c480fd3-20261109 derived from Task30 harness, previous36+five groups=41. Same11product boundary files, eighth bootstrap VariableHostCases.cs. Actual ConfigMaker host/owner/port/document/variable/command/localizer/tree/diagnostics unchanged from pin. Only bootstrap View gains typed Edit reply hook and Show tool action, both THROW if unset so previous unexpected-call guards remain. No new product boundary. + +- [x] Five groups: ctor/same document/collection/host bindings plus canceled edit; real pending rename/dialog identity/editor/reference/document events; referenced removal canceled/accepted with exact localized confirmation and retained command plus actual CFG004 localization; insertion through real cursor/editor and read-only guard; actual CreateVariableCommand pending/CanExecute events/repeated execution suppression and Load while waiting adds same result to current document. Fresh unique variable names, environment-presence precheck only for expected diagnostic, no reading/output of other env values. +- [x] New cases use plain variables/string values and same document-host fixture component, no files/resources; previous three own-bin inputs retained. Track pending tasks/gates, finally bounded release/observe and CancelBackgroundWork to stop actual diagnostics timer; preserve primary failure. Do not exercise error wrapper failures because production logger/status external targets remain real. +- [x] Fresh sourcechecker all4roots/pin/exact11boundaries/eightbootstraps/emptySecret/buildinputs; build0warnings/errors, independent safety/assertion review before first execution. Require41PASS/COMPLETE/exit0/noFAIL/stdout/stderr, postsourcecheck/finishedprocess/byteidentical3inputs. No native-dialog/visual proof claim; native15/16 stayopen. + +Verified: independent safety/assertion ACCEPT1210trackedfiles/exact11priorboundaries/eightbootstraps/emptySecret/pinnedbuildinputs. No mandatory fixes. Build0warnings/errors63.59s. PID34304 start09:20:48.8343188Z exit0end09:20:52.1280114Z:41PASS/COMPLETE/noFAIL/stdout/stderr. DLL82089C1516BAEB1E5A4BB8E49CAA8908A208F96450D903EB4E8375D9274E4BE9. PostsourcecheckPASS/processfinished/3inputbytesretained; runtime-createdbinentries only3inputs+resultlog. Real variable model/commands/editor/diagnostic/localizer composition passed, controlledviewtargets, no new productchange. Review rulings: first scratchrunlog absent despite notseparatelylistedguard, allotherfreshpathsblockrerun; no change needed for first reviewed execution. Logger reachable on unexpectederrors but exactexe/data-root guard boundsnormaldata effects to ownbin; not runtimeproof of logger/error/nativepaths or arbitraryexe isolation. Native15/16 open. Preserve everypreviouscopy and evidence. + +### Task 33: BlockCheck2 run lifecycle controller + +Base e890887, product c480fd3. Executor accepts bounded extraction described above. Move only orchestration/CTS/final-state decision; backend/history/cleanup and state/display remain host. Do not alter SiteLists/Storage or run actual deletion/network/history in tests. + +- [x] Write real-domain/fake-host behavior tests, absent-controller API RED. Cover ordering/identities, CanStart/Cancel guards, prelude outside try, invalid/final-state mapping, faults/OCE, pending run/history/report/final-state capture, CTS disposal and new-run reentry, callback/finally failures, original SynchronizationContext. +- [x] Move bodies and CTS into owner, preserve public API and exact host steps via explicit narrow adapter. Keep RunPrepared/SaveHistory/State/Notify/progress/result implementations unchanged, only corrected ownership comment if necessary. +- [x] Focused/full suite and GUI x64 Release; independent read-only new-range review vs e890887, resolve introduced defects with RED/GREEN, record inherited/deferred rulings. +- [x] Scoped local checkpoint and clear runtime limitations; assess separate actual-host proof before code freeze. Winddown10:45UTC and deadline11UTC unchanged. + +Verified: absent-controller CS0246 RED,44focused PASS, full1417/1417 nofailed/skipped14s, GUI0warnings/errors43.98s. Independent run_lifecycle_review ACCEPT: exact orchestration/CTS/final-state/adapters/options/progress/results/service/history/cleanup source composition, no Critical/Important/Minor. No product changes after GUI/review. BlockCheck aggregate607->551physical lines; owner98. + +Executor rulings on all eight inherited/set-aside items: preserve prelude outside try/no-finally on guard/reset/start failure; prepared Targets/Issues/events before Success and partial callbacks; CTS before Running and result-owned cancellation outcome; captured final state/current report before awaited history and blocked normal new run; actual history wrapper swallows ordinary service IO errors (HistorySaveError+Logger), unlike fake endpoint fault; ReferenceEquals protects only new CTS on final-state reentry while old Finish/shared progress and cleanup/current root still run (cost: existing new-estimator/root interference possible); catch/finally failures retain original partial mutations/resource boundaries; synchronous Cancel uses current field after state callbacks with no new synchronization. Costs explicitly retained, no claim of new rollback/lateness/cancellation/cleanup guarantees. Native/backend/history/logger/cleanup/deletion execution and actual-host integration remain unproven by unit/source checks. No mandatory fixes/deferred new minors or reopened closed reviews. + +### Task 34: Actual BlockCheck2 run host composition + +Product26297fdf386f7c09f4d058486399d4ac7318937f. NEW cdpiui-runlife-26297fd-20261109 derived from Task32, old41+fivegroups=46, ninth bootstrap BlockCheckRunHostCases.cs. Same11priorboundaries plus TWO narrowly patched product files: BlockCheck2ViewModel.cs changes only low-level options-settings factory, Prepare call target (retains actual CreateSessionRequest), RunWith backend target (retains actual Progress/options/preflight merge), History Save target and Logger target; SiteLists partial changes only private CleanupGeneratedSiteLists target to recorder. No Storage changes/deletion or real network/history/database/settings. Actual ctor/owner/port/options/progress/results/state/report builder/serializer and history wrapper bodies retained except listed targets. + +- [x] Fivegroups: actual ctor/controller/host/options bindings and guard/invalid preparation with recorded cleanup; pending backend progress on DispatcherQueue and Cancel -> canceled result/report with no deletion; pending history keeps CanStart false/CTS alive until final, actual preflight merge/result/session/report/serialization; synthetic history IO fault reaches actual HistorySaveError+inert Logger and still final Completed; synthetic backend fault/OCE reach real OperationError/Failed vs Canceled/null and recorded cleanup. Use pure ManualHostSession data and memory-only settings provider. +- [x] All callbacks record data/threadflags without throwing assertions inside controlled workflow; assert outside tasks. Track backend/history gates/tasks and release with WasCanceled result / memory history reply, bounded observe in finally, stop progress; remove subscribers/reset hooks. No actual RunWith/Prepare/Save/Logger/cleanup IO fallback allowed. +- [x] Sourcechecker all4roots/pin/exact13boundaries/ninebootstraps/emptySecret/buildinputs, build0warnings/errors, independent safety/assertion review before firstexecution. Require46PASS/COMPLETE/exit0/noFAIL/stdout/stderr/postsourcecheck/processfinished/retained3inputs. Real production endpoints, reentrant generated-root safety, native controls remain unproved. + +Verified: initialfixtureCS8752 params targettypednew RED29.86s preserved, onebootstrap typename correctedexplicitly, no productchange. Corrected existingcopybuild0/0 43.16s, independent safety/assertion ACCEPT1212files/exact13boundaries/ninebootstraps+emptySecret/buildinputs. PID44184 Start09:40:59.7214656Z Exit0End09:41:02.1449988Z:46PASS/COMPLETE/noFAIL/stdout/stderr/postsourcecheckPASS/processfinished/3inputsretained. DLLC89BCAC4EC99452CC9FF82590C4D824BDE2C370E2FEF4C7CFA871824A28C2E95. Actualhistorywrapper policy and progress/result/controller composition verified with inert endpoints, no real network/storage/settings/logger/deletion/reentrantroot/nativeclaim. Reviewlimits adopted, first-run pathscheckedabsent including scratchcopy, do notrerunarchivebuilder/prepare/runner. Native09:39read confirmedunchangedconsent3803510 ToolsSmokeTestunknownpublisher/UIAonly0, no inputs,15/16open. + +### Task 35: Compiled public contract verification + +Executor accepts additional regression evidence for original exported GUI surface, without modifying product. Build pristine f39e8a0a7267e4fcd4a02eef186a3ee08df8dcd9 in NEW short cdpiui-abi-f39-20261109, only exact generated empty Secret allowed; sourcecheck all4roots/buildinputs. No application execution. Compare compiled baseline CDPIUI.dll to product26297fd GUI DLL from verified root build using standalone net8 System.Reflection.Metadata/PEReader tool (BCL only, no new package). + +Evidence-driven scope adjustment: first compiled comparison at26297fd returned16changed shapes, all from public methods/getters implicitly implementing new internal interfaces and receiving virtual/final/newslot flags. Types/parameters remain unchanged and sealed types remain non-overridable, but prior public metadata transparency is stricter. Preserve RED artifact. Add explicit private interface forwards to original public members in five files (storage service, ConfigMaker Document/Files/Variables, BlockCheck main), no method-body/format/policy change. Verify full/GUI and compiled GREEN plus independent new-range review before checkpoint; this bounded product correction replaces the initial no-product-change assumption. + +- [x] Fresh scratch analyzer/inputs/logs and guarded archive/build; verify rootpin/sourceunchanged/currentDLL identity and same SDK/config/platform. Preserve all prior copies/evidence. +- [x] Canonical metadata signatures for exported types and externally accessible public/protected members: base/interface retention, visibility/type/static/virtual/abstract/sealed relevant flags, method/field/property/event types, generic constraints, parameter names/defaults, literal/enum constants. Decode type signatures by names, not unstable metadata tokens; permit additions. Record exact limitations: no complete annotations/attributes/interop/behavioral/native-ABI guarantee, compiler implementation attributes excluded. +- [x] Positive identical-assembly control and compiled synthetic negative controls independently exercise signature/default/setter/constant/base/constraint/flag removal detection. Meaningful expected failing exit, then product comparison. Independent read-only analyzer/assertion review before reporting proof. +- [x] Refresh source inventory and latest committed-security joint compatibility once code freezes; then requirement-by-requirement audit/status/rulings before10:45UTC winddown and11UTC deadline. Do not declare native15/16 or real external endpoints complete. + +Verified: pristinef39 baseline1374trackedrepositoryfiles exactLF before/afterbuild, onlyemptySecret, GUI0/0 57.32s. SameSDK8.0.427/Release/x64. Initial normal262DLL8148ECB5... RED16shapes; explicitforwards correction full1417/1417 nofailed/skipped15s+GUI0/0 45.44s. CandidateDAB8100F612A9E26DB93BFDA207DBB6CD19BF32E61BE0EE05681A08F5383057B:452originalexportedtypes/452after,0removedchangedshapes,7addedinternal-interface declarations. Identical/recorded-shape-positive controls0; negativeexit2/16changes andstrict11categoryassertions. Independent compiled_contract_review ACCEPT noCritical/Important/Minor, compared identical baselineinventories andonlyexpected16restored publicflags; productendpoints/taskidentity preserved. + +Rulings: keep strictvirtual/final/newslot ratherthannormalize away; positivecontrol deliberately changes output/timing and proves SHAPEequivalenceonly; defaults/constants onlyConstanttable, attrencodeddecimal/DateTime/params/callerinfo/NRTetc excluded; comparedeclaredmembers/directbase/interfaces, notdependency/inheritedclosure/MethodImplmaps, assemblyversionsignored; no completeABI/interoplayout/marshalling/attributes/behavioral/no-regressionguarantee. No further polish/productcorrection requested. Preserve allRED/GREEN binaries/json/logs; normalproductDLL distinctfromruntimefixtureC89. Final46actualhostcomposition atnewpin and source/joint refresh remain next. + +### Task 36: Final freeze verification and completion audit + +Product74659b74e3d53a0e024bfe6075169901c554f2de, normalDLLDAB8100F612A9E26DB93BFDA207DBB6CD19BF32E61BE0EE05681A08F5383057B. No new features planned. Repeat actual46groups in NEW cdpiui-final-74659b7-20261109 using same13fixture boundaries/ninebootstraps, allowing only newpin/root/log substitutions; explicit privateport mappings remainexactpin. Previous262fixture preserved. Narrow independent delta/safety review before firstexecution; no reopening closed body decisions. + +- [x] Newfixture allsource/buildinputs checks, build0warnings/errors, independent delta/safety ACCEPT,46PASS/COMPLETE/exit0/noFAIL/stdout/stderr/processfinished/postsourcecheck/inputbytesretained. Record actualport mappings exercised and realexternal/native limits. +- [x] Refresh originalsource syntax inventory f39->74659, preserve oldcontrols/evidence, and normalDLL/compiledcontract snapshot pin/hash guards. +- [x] Latest documented committed-security joint pin (currentread ee47716, owner980/980) in freshcopy, clean/source-no-overlap/additive-testitems guards, fullsuite+GUI. Do notincludeWIP/editparallelworktree. +- [x] Audit original user scope, audit recommendations asdata, approved order, every plan gate/invariant/artifact and all review rulings against current authoritative evidence. Distinguish completed bounded passes from unhandled large classes/global NRT/security/native gates. Record exact latestpins/results/remainingrisks, architectureownership/map if useful, final cleanbranch/localcommits/no publish/no destructive source actions. +- [x] Begin winddown at10:45UTC; no further product changes or new refactoring stages. Preserve current evidence and prepare final self-contained Russian report. Completion requires bounded user objective audit; native15/16 remainopen. +- [x] At11UTC stop the timed run and deliver the report, recording the actual remaining native blocker rather than declaring full completion. No new work past the deadline. Delivered in chat at14:00MSK; native15/16 remainedopen. Later explicit user request resumes work without that deadline. + +Freeze746 evidence: actualfinal46PASS/COMPLETE/exit0 atPID40860,10:07:17.2076428Z->10:07:19.5379863Z, source1212/13boundaries/ninebootstraps/emptySecret, build0/0 63.63s, independentdelta/safetyACCEPT,3inputsretained. Source451types517->573files0changedsignature; jointGUI746+securityee4771675956fe213634675f37579362efb7e0eb owner980:1629/1629 nofailed/skipped92s, GUI0/0 64.27s. Allhistoricalevidencepreserved. Completionaudit identified approved nextlargeVM CreateNew1037, one bounded pure draft extraction below before winddown, then refresh latestchecks; no new feature/policy. + +### Task 37: CreateNewConfig condition draft ownership + +Baseb1eb2ca, product74659. Exact bounded owner described in spec; otherlargeVMs remain backlog and Welcome migration stays outside parallel ownership. No save/import/testing/Logger mutation. Source-link real ConditionVariableModel, preserve annotations-only context. + +- [x] Real-model/collection/spies behavior tests before owner (absent API RED): setters/equality/null/notification order, validation/preview current reads/shortcircuit/localization, reset redundant Preview/order, Add invalid/raw/exit-before-read/reentry/identity/partial errors, real Core formatter. +- [x] Move draft state/logic into store-only owner, plain host public forwards and same sender, lazy production callbacks. Keep original collections and unrelated methods. Full/GUI, compiled and source contract retention, independent new-range read-only review. +- [x] Checkpoint then finalsource/compiled contract+joint/runtime delta only as justified; no new code after10:45UTC. Record inherited rulings and untouched scopes. Native15/16 remainopen. + +Verified: absent API CS0246 RED,24focused/full1441/1441 nofailed/skipped13s, GUI0warnings/errors42.20s. CompiledcandidateDAFB35EC6A4CCD6B728A4D05FB1712465C79420A3B38633B0F199628BA02552B vsf39:452types0removedchanged7addedinterfaces. Independent condition_draft_review ACCEPT allbodies/actualhelpermapping/XAMLhostsender/modelcontext, noCriticalImportantMinor. One expected formatter literal corrected from source beforeGREEN; no productalgorithm repair. CreateNew1037->1001physical lines,Variables118->74, owner84. No productchangesafterGUI/review. + +Rulings adopted: retainASCIIvalidator/space-onlypreview normalization/whitespaceOnOff; rawinvalidduplicateAdd/noreset remainsbaseline; Remove/VariableChanged/Logger/Save/Import/Test unchangedandnotnewexecutionproof; actualWinUIctor/localizer/render/flyout/native notprovedbyunit/source; inheritedlargeclass/globalNRT/security scopesopen. Existingmodelannotations-onlycontext preservedbydirectives, no UIstubs. Next actualCreateNewhost group canuse realconstructor (onlycommands,HardcodedItemIds pure dictionary,localizerstrings) with fakeICreateNewConfigView.SetExitAskAvailable, everyotheractionthrows, no newproductboundary. + +### Task 38: Last validation of condition host and final artifact audit + +Producte42ac481ab230866bd65ea06ccb7496a52a75c9c, normalDLLDAFB35EC6A4CCD6B728A4D05FB1712465C79420A3B38633B0F199628BA02552B. NEW cdpiui-complete-e42ac48-20261109 fromTask36, same13boundaries plus tenthbootstrap CreateConditionHostCases.cs, old46+5groups=51. NO newproductboundary: actualCreateNewctor/host/owner/model/helpers/localizer exactpin. Constructorcalls onlyRelayCommands/HardcodedItemIds dictionary/localizedstrings, fields/defaultcollections; noOpen/Select/Save/Test methods. FakeICreateNewConfigView onlySetExitAsk records, everyotheroperationthrows. + +- [x] Fivegroups: actualCtor/sameowner/collection/noViewcalls; realvalidation/Corepreview/hostsender/order/invalidlocalizedfallback; reset order/redundantpreview/noexit; Addexit-first currentrawvalues/freshmodel/invalidallowed/sharedcollection; hostreentry and synchronousobserverfailure withassignedfield/no derivedevents. No nativecontrols/flyout/externalIO/logging. +- [x] Build/sourcecheck1213tracked/13boundaries/10bootstraps/emptySecret/buildinputs; independent delta/safety review before firstexecution;51PASS/COMPLETE/exit0/noFAIL/stdout/stderr/postcheck/processfinished/3inputsretained. Source/compiledcontracts atnewpin and latest tested-security ee47716 joint freshcopy/full+GUI. +- [x] Complete Task35/36/37 verification/audit checkboxes according to actualscope, keep native15/16open; audit/map/reviewrulings/backlog/source-vs-audit citations accurate. No furtherproductchanges; winddown begun10:45UTC, deadline/report gate remains explicit underTask36. + +Verified e42: NEW complete-e42 fixture build0warnings/errors59.36s, independent safety/assertion ACCEPT1213product-root files/1457fullarchive/13boundaries/10bootstraps/emptySecret. PID42532 10:26:59.2287230Z->10:27:01.2864720Z exit0,51PASS+COMPLETE/noFAIL/stdout/stderr, postsourcecheckPASS/processfinished/3inputbytesretained. RuntimeDLL814BB17DAF15F1B930C1FFCAFB472DD11C7F13325D92FFB4697EFD0AF1AE0733; normalDLLDAFB35... retained separately. Source451types517->574files0removedchanged; compiled452types0removedchanged7addedinterfaces. Fresh joint e42ac481ab230866bd65ea06ccb7496a52a75c9c+ee4771675956fe213634675f37579362efb7e0eb1653/1653 nofailed/skipped38s GUI0/0 62.55s. Evidence paths, ownership map, inherited rulings, audit references and remaining scopes consolidated in docs/DECOMPOSITION-ACCEPTANCE.ru.md; no product change after reviewed e42. + +### Task 39: CreateNewConfig test session ownership + +Base63ce869, producte42. Spec section «Возобновление: test session CreateNewConfig». New ViewModels/CreateConfig/CreateConfigTestSession.cs; Helper/CreateConfigHelper/ICreateConfigTestTasks.cs and CreateConfigComponentTestTasks.cs; modify existing main constructor and Testing partial; Presentation/CreateConfigTestSessionTests.cs + additive source links. No new host partial files. + +Interfaces: ICreateConfigTestTasks event Action> StateUpdated, Task StopAsync(string), Task RunAsync(string,string). Session constructor takes tasks, Func<(bool HasComponent,string ComponentId)> selection (distinguishes no selection from null/empty id), Action convertDesigner, Func createConfig, Func startupArguments, Func localize, Action enqueue. Exposes ToggleAsync, Stop, InitializeText(no event), button forwarding properties and readonly state for focused assertions. Host sender preserved; adapter lazy. + +- [x] Write real-owner/ConfigItem managed tests first: store-only init, start/stop/subscription/order, missing/null/empty selection, pending stop/current reads, queued events/case/current-id, natural exit/resubscribe, fault/partial-state/fire-and-forget, reentry/localizer/observer failures. Run absent API RED; expected CS0246 only for new types. +- [x] Extract exact lifecycle with narrow callbacks and lazy adapter; preserve original host signatures/private setters/command and queue behavior. Focused tests GREEN; full suite and GUI0warnings/errors with SDK8.0.427, git diffcheck. +- [x] Compare normal DLL compiled surface and source signatures as justified; independent review once for new range only, rule on every finding, RED/GREEN mandatory corrections. Checkpoint scoped files, record counts/pins/logs/rulings and remaining host/native gaps. + +Verified96c2cfe782b329354b19a90e9129fa2b8d0bc852: absentAPIREDCS0246,33focused/full1474/1474 nofailed/skipped9s, GUI0/0 41.72s; source451/517->577/0, compiled452/0+7 unchangedinterfaceadds. NormalDLL E9407FAB802C6663440612F3814362708505172975838C53BFB7BE41598A8EEC. IndependentfreshreviewACCEPT noCritical/Important, twoMinor managedunitproofgaps deferred (prelude running assertion inside subscription hook; Stopfireforget vs completedTask). Task40 actualhost plannedprelude snapshots/returnedfaultedTask observation will supply additional integration proof, no productcorrection/re-review. Reviewrulings/costs inledger. Host1001->929, Testing118->24, owner129; public/privateaccessors/XAML/leavepage hook preserved. No realmanager/IO/native execution. + +### Task 40: Actual CreateNewConfig test host composition + +At96c2cfe prepare NEW cdpiui-createtest-96c2cfe-20261109 from existing51group fixture, retaining priorcopies. Same13priorboundaryfiles plus TWO narrowly cut files: CreateConfigComponentTestTasks.cs replaces four manager.Instance targets with configured inert tasks endpoint; CreateNewConfigViewModel.cs replaces only CreateConfig callback and startupformatter callback targets with memory-only functions. Actual owner/adapter/constructor/commands/queue/property forwards retained. Rationale: actual CreateConfigConditionBuilder resolves/creates/reads locale even saveLocalization=false, CreateConfigPageHelper uses DatabaseHelper, formatter invokes LScriptCore unsafe engine; do not execute them merely to test session composition. Actual ConvertDesigner remains, with only unsupported fixture component IDs so existing guard returns before editing/IO. No live manager/process/pipe/settings/DB/locale/Logger/native operations. Total15boundaries, eleventhbootstrap CreateTestHostCases.cs,51+fivegroups=56. Sourcecheck all productroots/fullarchive/buildinputs and exactcuts; build/safety review before first execution. Native15/16 remain separate. + +Five groups: constructor owner/realadapter/commands/initialtext/noendpointcalls; actual AsyncRelayCommand awaits controlledStop with prelude flag recorded on firstremove/add and current configuration read afterawait, RunTasknotawaited; actual DispatcherQueue receives background state with hostsender/thread/order/case/lateid/naturalexit/resubscribe; actual StopTestRun resets/doubleunsubscribes and returns normally with faulted returnedTask observed independently; commandfault/nullconfig preserve ownerpartialstate plus commandfinally and no unsafe error endpoints. + +Every pending stop/run/queue task bounded and released/observed in finally; stop each model before changing configured endpoint, detach host observers and drain queue before clearing hooks. No assertions thrown inside controlled backend callbacks; record and assert afterward. Existing51groups preserved unchanged except newpin/root/log and one call/count. Initial run only after independent safety/assertion ACCEPT, then56PASS/COMPLETE/exit0/noFAIL/stdout/stderr/postsourcecheck/processfinished/threeinputsbyte-identicalretained. + +- [x] Specify new boundary delta and five meaningful actual-host groups, including host sender, initialization and queued callbacks/command awaits with controlled tasks; safety/cleanup proof before run. +- [x] Build/review/execute once, preserve earlier fixtures and logs; update status/acceptance with current pin and no inflated native/production claims. + +Verified: freshfixture1216productroot/1462fullrepo/15cuts/11bootstraps+emptySecret/noextrabuildinputs; build0/0 69.69s; independent safety/assertion ACCEPT beforelaunch, EXEasInvoker/uiAccessfalse E17175E... andfixtureDLL E29FF54F... matched. PID5764 12:59:28.7341308Z->12:59:30.9999152Z exit0;56PASS+COMPLETE/noFAIL/stdout/stderr/postsourcecheckPASS/processfinished/3inputbytesretained andfreshhashJSON. Constructor event observer attachesafterctor, so runtimeprooflimitedtoinitialvalues/lazyendpoint/view; queuedcross-ID-change coveredmanagedonly, runtimechecksbackgrounddelivery/lateoldid. Unexpectedtrackedfault canshortcircuit cleanup afterallgatesreleased; ownappfails/exits/no realendpoint/no nextgroup, notgeneralcleanupguarantee. Allreviewlimits/rulings recorded. Fresh joint96+EE1686/1686 nofailed/skipped38s GUI0/0 57.16s; oldfixtures/evidence preserved. + +### Task 41: CreateNewConfig graphic designer state + +Basec4cd534, product96c2cfe. Spec section «Возобновление: состояние graphic designer CreateNewConfig». New ViewModels/CreateConfig/CreateConfigGraphicDesigner.cs, Helper/CreateConfigHelper/ICreateConfigGraphicDesignerBackend.cs and CreateConfigGraphicDesignerBackend.cs; modify existing main constructor/AdditionalSettings and GraphicDesigner partial only; new Presentation/CreateConfigGraphicDesignerTests.cs + additive source links. No codec/model/Core/DB/security implementations change. + +Interfaces: backend LoadGoodbye(items,groups), LoadSpoof(items,groups), bool TryLoadNoDpi(string id,items,groups), string Parse(items,groups,string), string Build(items,groups,string), all existing ObservableCollection model types. Owner receives same collections, backend, Func live component-id getter. Owns AdditionalSettings, LoadedComponentId, Load(string), ChangeText(Tuple), ToggleBool(Tuple), SelectGuid(Tuple), Parse(string), Build(). Host forwards original handlers/properties and same sender; UI branch/order/editor normalization unchanged. + +- [x] Write real production model/collection behavior tests before absent owner/port: store-only constructor, AdditionalSettings/equality/null/events, known/cache/reload/case/missing annotation/current id/reentrant/throw load, first-match text/bool/group GUID edits and grouping/partial errors, parse/build live callbacks/argument capture. Run expected absent API RED. +- [x] Extract exact state/algorithms into owner and thin lazy backend; keep UI policies and public/private host surface. Focused GREEN, full suite, GUI0warnings/errors with SDK8.0.427, compiled/public source retention and diffcheck. +- [x] Independent review new Task41 range once; rule inherited policies, defer minors, fix mandatory defects via RED/GREEN. Scoped checkpoint/counts/status/evidence, no claim real NoDPI IO or native controls. + +Verifiedcdf3bdc91c35d473128caba39fc1ae6672ef0152: absentAPIREDCS0246,34focused/full1508/1508 nofailed/skipped10s GUI0/0 38.02s; source451/517->580/0, compiled452/0+7oldinterfaceadds. NormalDLL D3E078495398F2C896D0F37AE9B72B07F74FFC949FF35C990404AC0B53E825B9. IndependentfreshreviewACCEPT noCriticalImportant; oneMinor tabletheoryself-validation weakness deferred, othercasesalreadycoverdispatch. Allreviewrulings/costs recorded. Host929->858; GraphicDesignerpartial135->61, owner109. No productchangeafterchecks. + +### Task 42: Actual CreateNewConfig designer composition + +After Task41, NEW pinned copy from56group fixture, same15boundaries plus narrow new designer-backend NoDPI DB/exists/XML targets only. Actual owner/host/collections/commands/AdditionalSettings/real safe factories+codec and tab sequence retained; new five groups =>61 and twelfth bootstrap. Define exact source cuts/assertions/cleanup before editing. No real DB/XML/component/native/shell/save calls; no changes in prior cases beyond pin/root/log/call/count. + +- [x] Specify/build/sourcecheck allarchive/buildinputs and independent safety/assertion review before first execution; five groups prove actual wiring/current models/view sequence/commands/cache/real safe parse-build and NoDPI retry on inert endpoints. +- [x] One bounded own asInvoker run with61PASS/COMPLETE/exit0/noFAIL/stdout/stderr/postcheck/inputbytesretained; current-pin joint/security compatibility once, preserve all previous copies. Record exact scope, counts, limits/rulings. + +Verified: freshfixturecdf3bdc1219productroot/1466fullrepo/16exactcuts/12bootstraps+emptySecret/noextrabuildinputs, build0/0 73.28s, independent safety/assertion ACCEPT beforelaunch. EXEasInvoker/uiAccessfalseE17175E...; fixtureDLLD32996BFF216FD32FFCC82A707FED143B21AA4431AB4A69E090F17C1DB96692A matched. PID33316 13:25:40.5160465Z->13:25:42.7032211Z exit0;61PASS+COMPLETE/noFAIL/stdout/stderr/postsourcecheckPASS/processfinished. Finalexternalbytecheck3inputsPASS/hashJSONretained. Spooffactoryidentity sourceprovedonly, runtimegroup population/liveRead/guard; no ctor-eventabsence/nativecontrols/realNoDPIIO claims. Freshjointcdf3+EE1720/1720 nofailed/skipped37s GUI0/0 56.35s. Alloldcopies/evidencepreserved; reviewrulings/minors explicitinledger/status. + +Task42 refinement before fixture editing: productcdf3bdc, NEW cdpiui-designer-cdf3bdc-20261109 (short path to retain WinUI/PRI path margin). Same15previouscuts plus one new file CreateConfigGraphicDesignerBackend.cs, exactly three NoDPI targets: directory lookup, File.Exists, XML_LoadDesignerConfig -> memory-only guarded recorders (no actual file). Keep real Goodbye/Spoof/Parse/Build helper calls. Same11previousbootstraps/case sources unchanged; add CreateDesignerHostCases.cs as twelfth, main onecall/count61/root/pin/log substitutions only. Total16boundaryfiles. Actual application remains asInvoker/no native windows/input. + +Five groups: actual constructor/owner/backend/collection identities and AdditionalSettings host sender/equality/reentry/observer fault; actual Goodbye factory + selected/tab/view order/cache + known -p/port parse/build; actual three RelayCommands against real mutable models/grouping/first-match/reentrant values; real Spoof factory and host current EditorText read after controlled normalization-write reentry plus unsupported-component visibility/convert guard; NoDPI missing/retry/success/cache and propagated controlled loader fault via inert directory/exists/XML endpoints. Constructor notification absence remains source/unit proof (observer attaches later); fake view is not real TabView/native UI. No actualSave/CreateVariables/test-run/DB/script/shell paths, prior56tests retainTask40cuts. All callbacks record rather than assert; controlled expected fault caught in scenario, observers detached/hookscleared in finally. Safety/assertion review after build and before firstexecution;61PASS/COMPLETE/exit0/noFAIL/stdout/stderr/postcheck/processfinished/final3inputbytes check. Freshjointcdf3+committedEE once, no WIP. + +### Task 43: CreateNewConfig component selection coordinator + +Base9985e52, productcdf3bdc. Spec section «Возобновление: component selection CreateNewConfig». New ViewModels/CreateConfig/CreateConfigComponentSelection.cs; modify existing main forwards/constructor/private CheckViewType/IsSaveAvailable and ConfigComponentOption.cs annotations-context only; new Presentation/CreateConfigComponentSelectionTests.cs + source links. No new host partial, navigation/Save/other-owner/backend/codec implementation changes. + +Constructor: Func supported, Action selectDesigner, Action selectText, Action handleSelection, Action dirty, Action audit, Func editorText. Owns SelectedComponent(ConfigComponentOption?), DisplayName, IsAdditionalSettingsVisible=false, IsNotReadyErrorVisible=true, IsTabBarVisible=true; derived IsDesignerSupported/IsSaveAvailable; CheckViewType(). Same null/default identity and source order. Host proxy uses original declarations/private setters; no implicit interface port flags. + +- [x] Real-model/delegate/spies behavior tests before absent owner: constructor/defaults, identity/equality/null/display normalization, exact supported/unsupported/null callback+event order, live capability/shortcircuit/whitespace/nullID, reentrant selection/flags/view effects and partial exception paths. Expected absent API RED (including source-link input as necessary), no GUI stubs. +- [x] Extract exact coordinator with store-only callbacks; preserve host private entrypoints/publicmetadata/notifications/queue interactions. Focused/full GREEN, GUI0warnings/errors SDK8.0.427, normal compiled/source contract retention, diffcheck. +- [x] Independent fresh new-range review once, mandatory fixes viaRED/GREEN only, minors/rulings explicit. Scoped code checkpoint/counts/status, no actual control/persistence claims. + +Verified: absent API/source input REDCS0246,34focused/full1542/1542 nofailed/skipped9s GUI0/0 44.16s; compiled452/0+7 unchanged prior declarations. NormalDLL3F38926D...; independent fresh review ACCEPT0Critical/Important, one managed live-read coverage minor deferred to actual-host repeated query. Host858->818/main299->259/owner103. Source inventory451/517->581/0 at cbd16ad; Task44 runtime/joint pending. + +### Task 44: Actual component selection and capability composition + +NEW pinned copy afterTask43 from61group fixture, same16boundaries (Main two inert test-prep targets unchanged) and oldcase sidecars unchanged. Add thirteenthbootstrap fivegroups=>66. No new cuts/real services/native controls. Existingactual host/private CheckViewType Navigation caller/commands/view interaction retained; controlled view/observers only. Define exactfivegroups/cleanup before editing, review source/buildinputs/allarchive/safety before firstexecution. + +- [x] Prepare/build/review five actual groups for cold owner/host forwarding, live CanExecute/query shortcircuit, supported/unsupported/null order and reentry/observer partial-state; same16sourcecuts/no hidden new endpoints. +- [x] Single own asInvoker66PASS/COMPLETE/exit0/noFAIL/stdoutstderr/postcheck/processfinished/final3bytesretained; currentpinjoint+committedEE once; report scoped proof and leave native15/16 open. + +Task44 refinement before fixture editing: use one new short pinned copy, same16cutfiles and unchanged prior61case sources; add CreateSelectionHostCases.cs only as thirteenth sidecar. No command Execute, Save, test start/stop or new endpoint substitutions. Five actual-host groups: (1) same concrete coordinator/public defaults/cold command state and constructor lazy-view behavior (observer attaches later, so no runtime absence-of-constructor-notification claim); (2) both real commands query current editor, shortcircuit missing object/name, whitespace and null-ID distinction, no extra computed notifications, editor-read reentry retains earlier guards; (3) unified host-property/view/Save-then-Test audit trace for unsupported/supported/null selection, object identity and equal-value suppression; (4) observer/tab reentry with original outer continuation and partial flags; (5) controlled property observer, exit-ask, command-audit and editor-read faults preserve assigned/partial state and stop subsequent callbacks. Private CheckViewType stays source-verified for Navigation; direct supported/unsupported switching exercises its same owner target without navigation IO. + +Controlled view records facts rather than asserts inside callbacks; optional hooks invoke only owned model changes/IOException. UI-thread and host/command sender checks; detach all model and command handlers, clear hooks in finally, verify test session and commands stayed cold. Unsupported markers avoid factory/DB IO; supported Goodbye uses the already-reviewed real safe factory/codec. NoDPI endpoints remain the same old inert cuts. Fresh archive/input checks, build, independent safety review, exact asInvoker hashes before launch; all66groups then process exit, post-sourcecheck and external literal-byte check for three own direct-child inputs. Old evidence/copies preserved, no native/deployment/real backend claims. + +Verified: productcbd16ad/1220roots1468fullarchive/16cuts/13bootstraps/build0/0 122.24s; independent safetyACCEPTbeforelaunch. PID47540 13:55:16.6378597Z->13:55:21.2333556Z exit0/66PASS+COMPLETE/noFAIL/stdoutstderr/postcheck/final3literalbytes. NewjointCBD+EE1754/1754 nofailed/skipped1m41s GUI0/0 88.39s. All scope/rulings/status preserved, no productchange. + +### Task 45: ConfigMaker diagnostics panel + +After Task44 checkpoint. Spec section «Следующий проход ConfigMaker: diagnostics panel». New Helper/CreateConfigHelper/ConfigMakerDiagnostics.cs (internal generic owner), new Presentation/ConfigMakerDiagnosticsTests.cs; modify existing ConfigMakerViewModel.cs constructor and Diagnostics partial only, additive test links for owner/actual validation/reference-validator source. ComponentCommandValidationService.cs annotations-only context if needed; no service algorithm/UI row/formatter/resource/security changes. + +Interfaces: constructor ObservableCollection, Func editor, Func> options, IEnumerable variables, Func resource, Func factory, Func text, Action refresh. Rebuild(), ErrorCountText/WarningCountText internal owner setters and private host forwards, GetSeverityText(ComponentCommandDiagnostic), GetDescription(ComponentCommandDiagnostic). Host factory keeps original initializer order and calls owner text methods; same collection and property names. Timer Stop/Start/Tick, Cancel and existing private RebuildDiagnostics callers unchanged. + +- [x] Actual-model tests before owner: lazy constructor/defaults, current editor/options order, Validate/reference ordering and results/order, all kinds/severities/token formatting/current culture, counts/equality, collection/factory/counter/localizer/highlight reentry and partial exceptions; no UI stubs/real IO. Run absent-owner RED. +- [x] Extract exact code, focused/full GREEN and GUI x64 SDK8.0.427 0warnings/errors; source/compiled retention, diffcheck. Preserve original public annotations/metadata/context. +- [x] Independent fresh new-range review; mandatory fixes one RED/GREEN pass, defer minors/rule scope. Record exact pin/counts/proof; actual-host next task, native15/16 remainopen. + +Verified: missinggenericownerCS0246RED,37focusedGREEN/full1579/1579 nofailed/skipped15s GUI0/0 59.12s; compiled452/0+7normalDLLAE058413...; independentfreshreviewACCEPT0Critical/Important. Minor variabletestenvfallbackweakness deferred, actual-host distinct guarded marker planned. ConfigMaker1117->1075/Diagnostics96->48/owner90. Source inventory451/517->582/0 at36b9e23, actualhost/timer/runtime nextgate. + +### Task 46: Actual ConfigMaker diagnostics composition + +After Task45, use NEW short pinned copy from66group fixture, same16cuts/oldsidecars unchanged and no new backend targets; actual host/generic owner/real validators/UI row/localizer/timer entrypoint retained. Define exact extra five groups/assertions/cleanup before creation; diagnostics brushes only through actual WinUI controls if separately proven, fakeview highlighting records no native windows. Safety review before first app execution. Fullarchive/input checks/build0/0, own bounded asInvoker71PASS/COMPLETE/exit0/noFAIL/stdoutstderr/postcheck/processfinished/final3bytes and fresh committed security joint once. No deletion/real DB/network/shell/history/storage and no native15/16 closure by programmatic fakeview. + +Task46 refinement before fixture editing: product36b9e23, NEW short cdpiui-diag-36b9e23-20261109, same16cuts and all prior66case sidecars byte-identical. Fourteenth new sidecar DiagnosticsHostCases.cs; main onecall/count71/root/pin/log only. Five groups: (1) actual closed generic owner/real UI rows samecollection/variables and cold/lazy constructor, real timer300ms nonrepeating and direct private Tick entrypoint Stop->Rebuild; no auto-timer delivery claim; (2) exact real validator/reference order, actual UI row Source/SeverityText/Description/localizer, counts/hostsender/unified trace/equality and refresh; Brush/native visual not evaluated; (3) live current editor-before-options, unique environment-presence-guarded variable marker added after ctor then renamed to force CFG004, attached resource lookup changes, same collections/no snapshot; (4) single-collection-listener and property-observer reentry preserving original outer results/count continuation; (5) controlled editor/collectionReset/counterObserver/highlight exceptions through private host method retain partial state, no logger/errorwrapper endpoint. No rows factory substitution. + +Controlled DiagnosticsView implements only EditorText and RefreshEditorHighlighting, records calls/thread and optional owned hook, all other action endpoints throw; IsViewLoaded=false. Private Invoke helper unwraps reflection inner exception for owned synchronous fault assertions only. Every fixture detaches model/collection handlers, clears hooks and calls real CancelBackgroundWork to stop its timer; no help/test/command execution. No env writes or values printed; marker presence-only guard fails own app if unexpectedly set. Source/runtime limits constructor notifications/automatic timer/native/real IO remain explicit. Independent safety/assertion review after fresh allarchive/buildinput check and build before firstlaunch; same71/COMPLETE/process/postcheck/final3literalbytes gate and fresh exactpinjoint+committedsecurity. + +Verified Task46: product36b9e23/1221roots1470fullarchive/16cuts/14bootstraps/build0/0 73.62s, independent prelaunchACCEPT. PID38944 14:07:50.0600669Z->14:07:52.4322586Z exit0/71PASS+COMPLETE/noFAIL/stdoutstderr/postcheck/final3literalbytes. Newjoint36+EE1791/1791 nofailed/skipped1m16s GUI0/0 65.51s. All source/runtime/native limits and rulings explicit, no productchange. + +### Task 47: ConfigMakerUserControl resizable panel layout + +Basecd13231, product36b9e23. Spec section «Следующий проход исходного God-control: resizable panel layout». New Helper/CreateConfigHelper/{ConfigMakerPanelLayoutController.cs,IConfigMakerPanelLayoutView.cs,ConfigMakerPanelLayoutView.cs}; modify existing control constructor and Layout partial only; new Presentation/ConfigMakerPanelLayoutTests.cs and additive two pure links. No new host partial/interface/UI mode or settings/backend changes. + +Pure port: RootWidth/RootHeight; FilesVisible/CommandsVisible/BottomVisible; FilesMinWidth; FilesMaxWidth/FilesWidth get/set; FilesSizerWidth/CommandSizerWidth/BottomSizerHeight; EditorMaxWidth/EditorWidth/EditorMaxHeight set; EditorHeight get/set. Controller constructor store port; IsUpdating, Invalidate(), RememberEditorHeight(double), Update(). Adapter constructor six Func, two Func, one Func, store only. Host private forward and exact capture/invalidate order retained. Public host flags not used as implicit interface implementations, recorded flags unchanged. + +- [x] Write absent-owner RED tests with actual double math and pure port: cold ctor, all visibility/dimension branches, invalid roots/shortcircuit, files min/cap/clamp, initialized/current/saved bottom height, reset/reentry/repeated getter reads and partial exception/finally semantics. No product adapter executed in unit tests. +- [x] Extract exact algorithm and lazy real adapter; focus/full GREEN, GUI SDK8x64 0warnings/errors, compiled/source public contract0removedchanged, diffcheck and physical counts. +- [x] Independent fresh new-range review, one mandatory RED/GREEN fixpass only/minorsdeferred/rulings explicit; commit/status. No claim native resizing or actualcontrol construction. + +Verified: owner+portabsentCS0246RED,39focused/full1618/1618 nofailed/skipped13s GUI0/0 49.86s, compiled452/0+7normalF66DB84B...; freshreviewACCEPT0Critical/Important, splitter-constant testminor deferredtoactual48distinct11/17/23. Control899->828/Layout233->158/main240->244/owner95/port22/adapter41. Sourceinventory451/517->585/0 atc0ed350; no actualUI/fullControl/nativeproofclaim. + +### Task 48: Actual WinUI layout adapter mapping + +After Task47 NEW short pinned copy from71group fixture, same16external cuts/oldsidecars unchanged plus fifteenth bootstrap five groups=>76. Define concrete standalone WinUI elements/scenarios and cleanup after inspecting actual adapter, before creation; preserve live numeric property access and real WinUI property validation, no full control/Window activation/desktop input/settings. Source review confirms constructor/XAML host wiring, programmatic adapter proof stays distinct from native15/16. Safety/assertion review and allarchive/input check/build before firstexecution; one own asInvoker76/COMPLETE/exit0/noFAIL/stdoutstderr/postcheck/processfinished/final3literalbytes; fresh exactproduct+committedsecurity joint. If standalone Arrange does not produce positive ActualWidth/Height, record actual scope and pursue source/managed proof without faking native UI state or claiming gate green. + +Task48 refinement before fixture editing: same16cuts and all prior71sidecar sources unchanged, fifteenth new LayoutAdapterHostCases.cs, fivegroups=>76. Actual standalone Grid/FrameworkElement/ColumnDefinition/RowDefinition on owned WinUI UIthread, no full ConfigMakerUserControl/Window/activation/desktop input. All9callbacks record current target/thread and can perform owned controlled callback only; port/owner constructors store-only. Cases: (1) lazy adapter/owner zero callbacks and zero-sized actual root shortcircuit; (2) arrange standalone root, all real getter/setter mappings/visibility with distinct files11/command17/bottom23 lengths and distinct workspace-width/editor-height targets; (3) real controller visible files at1200 and2000 width yields max472/900, widths250/900 and editor582/732, checking cap/clamp and eachsplitter contribution; (4) saved/current/invalidated height, hide/show and smaller root with realpropertyvalues; (5) live replacement of callback-selected standalone element, nestedUpdate guard and owned getter exception beforewidth assignment preserving priorMaxWidth/finally/retry. Hooks record ratherthanassert insideportcallbacks; allownedobjects no externalIO. + +Root helper sets own Grid Width/Height then Measure/Arrange/UpdateLayout and requires positive ActualWidth/Height before positivebranch assertions; if frameworkcannotarrangeunparentedroot, fail/preserveevidence, never fakeactualdimensions or labelnativegate green. Fakeport tests cover numeric behavior, actualruntime coversadapter/nativeproperties onstandaloneelements only; originalcontrolwiring/earlyXAML remain sourceproved. Runtime ownprocess lifetime ownsobjects; callbacks nulled in finally, ownerIsUpdatingfalse/threadfactschecked. Safetyreview after fullarchive/inputcheck/build; same76process/postcheck/threebytes plusfreshjoint. Native15/16 remainopen. + +Verified Task48: productc0ed350/1224roots1474fullarchive/16cuts/15bootstraps/build0/0 110.37s; independent prelaunchACCEPT. PID41396 14:20:08.1726222Z->14:20:12.0142052Z exit0/76PASS+COMPLETE/noFAIL/stdoutstderr/postcheck/final3literalbytes. Real standalone Arrange positive; sameadapter/owner realUIproperties/callbacks/splitters covered, no fullControl/invalidDP/nativeclaims. Newjointc0+EE1830/1830 nofailed/skipped1m31s GUI0/0 111.25s. + +### Task 49: App window close lifecycle coordinator + +Base7dc341f, productc0ed350. Spec section «Следующий проход App: window close lifecycle». New Helper/Basic/{AppWindowCloseCoordinator.cs,IAppWindowCloseOperations.cs,AppWindowCloseOperations.cs}; modify existing App.xaml.cs constructor/field and App.Windows.cs handler only. New Presentation/AppWindowCloseCoordinatorTests.cs/additive two pure links. No migration/security/modal/position/window factory implementation changes or new host interface/partial. + +Port: Func CaptureExitEnqueue(TWindow); bool IsMigrationWindow(TWindow); SavePosition/Detach/ReleaseModal/ForgetOwner(TWindow); Warn(Exception), CompleteMigration(), bool IsStoreWorking(), Task CreatePrepareAsync(), ExitIfIdle(). Owner stores List/port, HandleClosed(TWindow). Adapter constructor ModalWindowCoordinator, Actiondetach, FunccreatePrepare, Actionexit. Captures dispatcher at original point then returns Low queue closure (no earlyenqueue); original backend policies preserved. + +- [x] Absent-owner/port RED tests realList/fake managedoperations: exact allbranches/order/currentCount/captured migration/enqueue, missing/duplicate windows, save/logger/detach/modal/remove/complete/forget/post-dispatch faults and partial state, reentry during cleanup, unawaited returnedTask/pending gate with bounded worker cleanup. No WinUI/real IO/process execution. +- [x] Extract exact workflow/thin realadapter, hostguards/forward; focused/full GREEN, GUI SDK8x64 0warnings/errors, source/compiled publicretention, diffcheck/counts. +- [x] Independent fresh newrange review, mandatoryRED/GREENfixes only/minorsdeferred/rulings explicit; scopedcommit/status. No claim actualClosed event/backend/native15/16. + +Verified: CS0246missingownerportRED,33focused/full1651/1651 nofailed/skipped15s GUI0/0 55.99s; compiled452/0+7 normal04117229...; freshreviewACCEPT0Critical/Important, one managedwindowidentitycoverage minor deferred. App754->702/Windows190->133/xaml172->177/coordinator61/adapter41/port21. Sourceinventory451/517->588/0 at73d92a6; native/backend/Closed event notclaimed. + +### Task 50: Actual App close coordinator/adapter composition + +AfterTask49 NEW short pinned copy from76group fixture, preserve oldcases/16cuts and define new adapter lowlevel targets precisely beforecreation. Actual App constructor/owner/adapter/currentList/dispatcher callback should remain; real logger/window-position/modal/Prepare/migration/ExitIfIdle effects inert. Nonactivated owned Window objects permitted only after safety review of exact source/manifest; no full user-window registration/closure/startup/desktop input or actualClosed-policy claim without direct evidence. Define fivegroups/cleanup and need for17th boundary, sourcecheckallarchive/buildinputs, independent safety review before firstlaunch,81/COMPLETE/exit0/noFAIL/stdoutstderr/postcheck/processfinished/threebytes, fresh committedsecurityjoint. No native15/16/deployment/security closure by programmatic fake endpoints. + +Task50 refinement before fixture editing: NEW short pin copy after49 from76groups, same16oldcutfiles plus seventeenth AppWindowCloseOperations.cs only; existing App.xaml.cs cut extended in two places: detachcallback recorder before original Closed/SizeChanged removals, and ExitIfIdle body -> context recorder (original exitpolicy source/unit outsidethisgate). New WindowCloseHostCases.cs sixteenthbootstrap; main oneawait/count81/root/pin/log only; all old14case sidecars unchanged. + +Adapter lowlevel substitutions: SavePosition/ReleaseModal(true)/Logger target/CompleteMigration/ForgetOwner/IsStoreWorking/CreatePrepare delegate endpoint -> guarded memoryrecorders; IsMigrationWindow wrapper default executes original Welcome predicate, optionalperownedwindowoverride for truebranch without Welcome ctor; CaptureExitEnqueue retains real window.DispatcherQueue and sourceLow argument but TryEnqueue target wrapper records window/priority, default calls actual queue with same priority/action and canreject viacontrolledflag. Detach callback/actualeventremovals retained, _exit callback stillboundtoApp.ExitIfIdle, _createPrepare passedtohookforidentitybutnotexecuted. No realposition/settings/modalWin32/migration/Prepare/logger/exitpolicy. + +Fivegroups: (1) actual App constructor/owner/adapter/sameList/modal/delegate targets/noeagercalls plus private wrongsender guard; (2) two nonactivated owned basic Window objects created only here, actualdefaultpredicate false, cleanuporder/membership and real Low callback deliveredonUI; (3) reentrant A/B close with perWindowmigrationoverride and exact window-specific save/detach/release/forget traces, two queuecallbacks; (4) controlledqueue rejection synchronous Appforward and unawaited pending/faulted Preparetask with same actual callbacktarget recorded; (5) ownedSave+logger and Forget exceptions retain sourcepartialstates/queue boundary with observed tasks. No nativeClosed event/fullhandlerfalsebranch/handledargs/createPrepare callbackbody claims. Nonactivated windows never Register/Activate/Close; normal ownedprocess exit reclaims nativeobjects, programmatic internalownercallonly. No desktopinput. + +Perfixture app.OpenWindows must initiallyempty; mutate/remove only the two known references, neverunknownwindows; observers/hooks defaultthrow withoutcontext, flags/threadfacts recorded. All pending gatesreleased and queuedexits awaitedwith3s bound/cleanup barrierbeforecontextclear, original list emptiness and nativeprocessExit checked. Assertions outsidehooks; no full nativecleanup/leakguarantee beyondownprocess. Source/build/allarchive exact17cuts/16bootstraps, prelaunch independent safety review beforefirstnewWindow/applicationexecution;81/COMPLETE/exit0/stdoutstderr/postsource/processfinished/external3bytes/freshjoint exactcommittedsecurity. Native15/16 remainopen. + +Verified Task50: product73d92a6/1227roots1478fullarchive/17cuts/16bootstraps/build0/0 90.60s, independent prelaunchACCEPT. PID49108 14:37:40.6481697Z->14:37:43.9617754Z exit0/81PASS+COMPLETE/noFAIL/stdoutstderr/postcheck/final3literalbytes. Two ownnonactivatedWindow identities/actualqueue/sourceLow/callbackstub covered, no realClosed/backend/exitpolicyclaims. Newjoint73+EE1863/1863 nofailed/skipped1m28s GUI0/0 92.84s. Futurefreshcopies onlocalNTFSFspace, historicalCcopiespreserved. + +### Task 51: BlockCheck2 site-list workflow controller + +Basea1576c3, product73d92a6. New ViewModels/{BlockCheck2SiteListController.cs,IBlockCheck2SiteListBackend.cs,BlockCheck2SiteListBackend.cs}; modify existing Main constructor/field and SiteLists partial only; new Presentation/BlockCheck2SiteListControllerTests.cs + additive two pure links. Real SiteListElement comes from referenced AddOns. SiteListItem/Storage/preview/cleanup/options/Core/security implementations unchanged. + +Controller constructor same Available/Selected ObservableCollection, backend, FunccurrentGeneratedRoot, ActionselectionChanged. IsSiteListLoading/SiteListLoadError and counts; LoadAsync(), AddCustom(string filePath,string sourceName), UpdateCustomAsync(content,displayName,sourceName,token), Select(item),Remove(item),SetSelected(IEnumerable). Backend LoadAvailableAsync=>Task>, IsLegacyGenerated(path), Create(displayName,sourceName,path,boolcustom,string?editableContent,stringroot), Normalize(content), CreateCustomPath(), WriteAsync(path,normalized,token),Text(key),GetFilePath/GetDisplayName/GetDomainCount/IsCustom(TItem),UpdateCustom(TItem,string). Factory receives explicit false/null for original noncustom calls, original true/normalized for custom. Host public declarations plain forwards, no implicit interface flags. + +- [x] Absentowner+port RED tests with real ObservableCollections/SiteListElement and explicitrowbackend: cold ctor/counts, load guard/event/culture/order/currentdefinitions/legacy/case filters/rootgetter/retry/cache, prelude/catch/finally faults and partialreentry; custom path/dedup/no-add, normalized empty/token/current-afterawait/captureditem/removal/overlap/update errors; selection/null/self-source/distinct/notify/count overflow. No actual file/DB/Storage/Window/cleanup. +- [x] Exact extraction and thin productionbackend; focus/full GREEN, GUI SDK8x64 0warnings/errors, compiled/source retention/diffcheck/physicalcounts. +- [x] Independent fresh review newrange, mandatoryRED/GREENonly/minorsdeferred/rulings; scopedcommit/status. Actualclosedgeneric/model/host/backend/task/thread nextgate, no native15/16 claims. + +Verified: initialtestsyntaxcorrectedbeforeeligibleRED; CS0246missingownerportRED,32focus/full1683/1683 nofailed/skipped16s GUI0/0 51.20s; compiled452/0+7 normalBD9ABF77...; freshreviewACCEPT0Critical/Important, Write-content/unbounded-unit-gates minorsdeferred, actual52strongchecksplanned. Host555->426/SiteLists215->82/main231->235/owner133/backend26/port24. Sourceinventory451/517->591/0 at214b4b3; Item/Storageunchanged. + +### Task 52: Actual BlockCheck2 site-list composition on F + +After51 NEW short fixture and joint roots under F:/cdpiui-verify (verified localNTFS/free54GB). Old C: copies/archives untouched, future new archives also F. New paths/folders fresh/no-reparse check, exactsourcepin/old81sidecars unchanged, same17cuts plus narrow new SiteListBackend lowlevel IO targets only. Real factory/Item/model counts/host notifications/current roots/normalization retained. Define fivegroups=>86 and seventeenthbootstrap beforecreation; no Storage implementation edits. Only reads of knownown three input files permitted through real noncustom row constructor; customWrite/path/load/legacy endpoints inert and content-backed rows avoid File.ReadLines. Same86/COMPLETE/exit0/stdoutstderr/postsource/processfinished/final3bytes; independent safety review beforefirstexecution; fresh currentpin+committedsecurity joint. ExactFroot replacements must cover forward/backslash/doubleescaped strings in prepare/DirectoriesManager/main/root guards; task code root staysC. No tempcleanup/deletion/realDB/history/network/userfile writes. + +Task52 refinement before fixture editing: F:/cdpiui-verify/cdpiui-sites-PIN-20261109 and new source archive under F:/cdpiui-verify/archives; taskroot/logs/scripts remainC, no oldmoves/deletions. Same17cutfiles+newBlockCheck2SiteListBackend only (18), allold81sidecars unchanged; seventeenth bootstrap SiteListHostCases.cs, mainoneawait/count86/root/pin/log only. Newbackend IO substitutions LoadAvailable/IsLegacy/CreateCustomPath/Write only; retain real Normalize/Text/modelpropertyread/update/factory. Noncustomfactory reads only own existing actions-sites/actions-insert inputs or an explicit own missing marker (modelCountDomains catchesIO); legacy marker filteredbeforefactory. Custommemorycontent avoidsfile reads; allfakewrite paths own sites-custom-N-M.txt remain absent, no actualWrite/DB/delete. + +Fivegroups: (1) realMain/closedgeneric/collections/backend/coldstate/lazyroot and no backendload/runner endpoints; (2) pendingload/guard/UIcontinuation and exact same mutable SiteListElement/sv-SE ordering/blank+legacy/zero-missing/caseexclude/realrowDomainCount/cache/root, separatefailure/retry asneeded; (3) actual AddCustom ownedfile/no-add, select/pathdedup/removeidentity/SetDistinct/selfclear and four hostnotification names/current counts/CanStart; (4) actual normalized raw multiline->exactWrite.Content/token plusrealcustomrow/count and lateRoot afterawait, existing captured row updatedafterremoval/no rootrefresh, nocancelrecheck whenfakewritecompletes; (5) two pendingcustomtasks completionorder/currentroot plus boundedloadfault/retry/hostsender/UI and no realrunners/history/cleanup. Allqueries useactualModels; readonlybygetter collections stayidentity, no privatefields/Storage fakecompilechange. + +Every async task tracked, all awaits bounded3s, owned load/write gates released in finally and tasks awaitedbeforeunsub/contextclear. No SourceFixture.Start/Prepare/cleanup called; original settings fake remains memory and newmethods mustnotalterRunCalls/History/Cleanup counts. Markers absent before and externalafterentire86run; literal3inputbytesafterexit required. Field/root/readSourceWindow old81scope remainsdistinct. ParentFmkdir guardedresolved/no-reparse/localNTFScapacity; generatedcode substitutions cover '/', single/double/quad-backslash full oldabsolute fixturepath, not taskCroot. Verify staleCfixtureabsolute absent fromnew prepare/main/check/builder/runner and expectedFDirectoriesManager beforebuild/review. Safetyreview afterallarchive/buildinputs/build beforelaunch; actualSDKDLL/exe asInvoker/nonadmin andF no-reparse; exactnewFjointcurrentGUI+committedEE once. Native15/16stayopen. + +Task52 prelaunch refinement from independent safety preflight, before first application execution: three Task.Run completion workers now tracked and bounded3s with TrySetResult; first original sidecar/build log and first DLL snapshot preserved, corrected sidecar rebuilt in existing fresh Fcopy with NEW log, archivebuilder never rerun. Legacy sentinel now existing actions-insert.txt (knownDomainCount1 if incorrectly admitted), backend LegacyArguments asserted; absent zero marker remains sites-absent-item.txt. This makes runtime legacy exclusion distinguishable, normalized write and owner flow unchanged; all18cuts/oldsidecars/sourcepin unchanged. External final3bytes and custom/missing markers stillrequired. + +Verified Task52: product214b4b3/Ffixture1230roots1482fullarchive/18cuts/17bootstraps, firstbuild0/0 108.87s originalDLL+sidecarpreserved, correctedbuild0/0 47.71s, independent finalprelaunchACCEPT. PID34040 15:02:04.9067454Z->15:02:10.3901784Z exit0/86PASS+COMPLETE/noFAIL/stdoutstderr/postcheck/processfinished/externalfinal3literalbytes+markersPASS. NewFjoint214+EE1895/1895 nofailed/skipped1m26s GUI0/0 75.79s. UnitpolishdeferredbutruntimeexactWrite/boundedgatescovered; source-onlyemptyText/native/IO limits explicit. + +### Task 53: Native Task15/16 gates on214b4b3 + +NEW F:/cdpiui-verify/cdpiui-native2-214b4b3-20261109, archiveF:/cdpiui-verify/archives/native2-214b4b3-source.tar. New NativeGates2Bootstrap.cs based on only corrected Frame/manual-load+check bodies from old ManualSmokeBootstrap; no old deadline helper/nativecopy rerun. Two tabs: actual ConfigMaker and actual Frame-hosted ResultPage. No Main/progress/codec/window-reuse helper scopes. UI buttons for check loaded/readonly, real saveDialog, inert export, real New confirmation, load/check manual and Finish. Sticky flags11PASS+COMPLETE; known own Window.Closed exits process, asInvoker/no elevation; same own dataRoot/explicitprocesspath guard. All dialogs actual except filepickers; actual Add/Move only throughSky. + +Planned19boundaryfiles: Program,App.xaml,DirectoriesManager,ComponentCommandHelpService,ConfigMakerViewModel main (fake manager/installed predicate/editor settings/handlerfailuretrap),ConfigMakerUserControl main (output2targets),SearchUserControl(read2preferences/refuse2writes),ConfigMakerPresetResources(component/base-dir DBtargets),ConfigMakerPresetStorageService(private SaveCore only),ConfigMakerPresetExporter,ConfigMakerFileDialogs(3pickers inert),BlockCheck2ViewModel(main optionssettings),BlockCheck2SiteListBackend(load/path/write inert),BlockCheck2MainPageViewModel(refuse scan),BlockCheck2ResultPageViewModel.ManualTesting(refuse Start),BlockCheck2ResultPageViewModel(real strategytesttargetrefuse),ConfigMakerPresetFileActionsBackend(preferences/shelltargets inert). Additional ConsoleFontHelper6preferences memory(defaulttrue/Consolas/16), Core.SettingsManager ctorbaseargumentRefuseNativeSettings throws beforeXMLbase andsetsstickyAppContextswitch; require switchfalse atFinish AND afterApplication.Start returns(beforeexitcode). Actual controlXAML/layout/diagnostics/doccoordinator/realmodel/codec/manualeditor/FrameMenu remainpin exact. No App.WindowClose backend changes because windowunregistered/customeventonly. One bootstrap +verifiedemptySecret asonlyC#extras. Allrepo/sourceinputs compared to214, expectedpatchset exactly19; no native app start until independent fresh safety/assertion approval+hashes. + +- [x] Design/source/build/check full pinned new F fixture and review guard/ownedinput/log/timeout/manifest and all native paths before launch. +- [x] Launch exactasInvoker ownexe; use freshSky target snapshots/inputs for all11observations; record screenshot/AX/log evidence, no coordinate guessing/shortcut permissions. +- [x] RequireCOMPLETE/noFAIL/exit0/stdoutstderrempty/processfinished/postsource/inputbytes/noexport; markTask15/16nativeboxes only for actualobserved phases. Preserve alloldcopies and scope gaps (productionbackend/startup stillunproved). + +First native17cut copy preserved: PID52048/11PASS+COMPLETE/exit0 but mandatorypostSettingsabsence FAIL (ConsoleFontHelper x:Bind initialized Settings.xml/bak beforeUI). Overallgate notgreen; newnative2only after19cutreview, repeat11actions. No oldcopyrerun. + +Verified final native2: exact214/19cuts/1230roots1482fullrepo/build0warnings/errors75.21s/independentprelaunchAPPROVED; GUI86EC3A27…/EXEE17175E…/CoreE18B0918…/Shared15CCF56E…/AddOns05038F2A…. PID36508,15:44:45.2758468Z→15:47:31.5834895Z,11PASS+COMPLETE/exit0/noFAIL/stdoutstderr/postsourcecheck/processfinished/Settingsabsent/only2allowednewbinfiles/literal23inputbytesretainedSHA70CE5088… PASS. ActualSkyobservationsseven document cases/four manual phases, own AX retained. Native15/16boundedgatescomplete; productionbackend/startup/actualexport/autocorrect/settings/fullwindowlifecycle notclaimed. First17cutrunfailure remainsFAIL. + +### Task 54: Final requirement and evidence map + +After53, refresh selectedaudit scope/owner map/physicalcounts/pins and exactchecks; historical first-window acceptance unchanged. Inspect root/status/source/normalDLL preservation/latestjointpin/securityownership/no uncommittedforeignchanges/no activeownedprocess. Independent final integration/requirements review per executing-plans skill, with closedcodec body review not reopened without new integration evidence; mandatoryfindingsoneRED/GREENpass, minor/rulingsreported. No redundantgreenruns fordocs-only, no force/reset/delete/publish/merge. Current branch remainslocal/reviewable, all remaining native/fullbackend/wholeaudit limits explicit. + +Verified Task54: freshwholebranchACCEPT f39e8a0a→1d76cbdb,153paths/68commits/all4clusters/96validGUIlinks/30changedpresentationtestfiles;0CriticalImportant,3Minor deferred afterrootbaselinecheck. Every13declinedjudgment ledgeredwithcost, exhaustiveappendixupdated. No mandatorycodefix/rereview/redundantgreenrunsforfinaldocsonly; product214/root1683GUI0/0/source451/compiled452/0+7/joint1895/native2eleven+allpostchecks remainexact. Keepbranch/worktree/evidence peruserauthorization; no integrationmenu needed foralreadyselected safe local-preservation scope. + +### Task 55: ConfigMaker preset structure state and publication + +Base28ceef44c0e438885ecb229a70c41cc1d9aeaa91, previousproduct214b4b3. Extract new Helper/CreateConfigHelper/ConfigMakerPresetStructure.cs, generic internal sealed ConfigMakerPresetStructure: ObservableObject. Existing PresetStructure partial delegates; existing private node setters retained. No new host interface/partial/XAML/backend/schema/settings changes. CurrentTreeBuilder/Adapter remain real and supplied through closures; owner takes six live funcs (command, zapret2, extractFiles(command), attachedFiles, projectFiles(files), projectGroups(options,explicitGroups,zapret2)). Constructor stores only. Owner owns explicit arrays/use flag/two node lists/two flags, same public property names, Set/Clear/Rebuild and AvailabilityChanged. Host forwards owner PropertyChanged with host sender and availability with EventArgs.Empty. + +Exact temporal contract: guards files then groups beforeenumeration; file filter nonblank/dedup kind+OrdinalIgnoreCase beforeToArray, assign files beforegroup enumeration, set explicitflag afterboth arrays. Rebuild extract currentcommand ->ToArray, enrich explicit missingoption only first matchingkind/path, attachedToArray, basefirstconcat/dedup; fileprojection then fieldassign+propertyevent BEFORE reading currentcommand/groupstate/zapret2 for group projection. Compute availability aftergroupbuild against current fields, assignbothflags BEFORE groupnodepropertyevent, then unconditional3derivedevents, availabilityevent onlybooldelta. No reentryguard/atomic snapshot/rollback. Clear resets explicitflag/arrays then Rebuild. Cold HasPresetGroups/IsVisible true; actual projection allocates empty collections as before. + +- [x] Write realmodel/Core/parser/comparer + genericmanagedprojection tests: defaults/noeagercalls, explicit filtering/firstdedup/enrichment/precedence/attached live, option/source coords and livecomponent/command reads, collectionidentity/equality/eventsequence/flagtiming, Set guards/partial enumeration, allcallback/eventthrow partialstates, Clear/reentry/nested publication/currentfield timing; no filesystem/localizer/WinUI fakes masquerading as actual controls. Observe eligible absent-owner RED before source. +- [x] Extract exact state/algorithm and wire production closures. Focus/full GREEN +GUIx64 0warnings/errors, source+compiled recorded API including retainedprivate node setters, physicalcounts/diffcheck; scopedcommit. New range stillsubjecttofinalreview58. + +### Task 56: Actual preset structure composition + +New pinnedFfixture from previous86group currentownerhost harness: same18external boundary files/old17bootstrap sources unchanged, new eighteenth PresetStructureHostCases (five groups =>91). Real host/genericowner/resources/builder/WinUIadapter/nodecontent/current delegates/eventsender/UIthread; no extra backend effects. Cases: lazy/default/actualowner wiring; detected/explicit/enrichment/attached realmodels/treecontent; exact empty/nonempty hostevents/availabilityflags/newemptyarray/private-set compatibility; hostobserver command/component/explicitstate reentry and currentgroup reads; controlled projection/read fault partialstate+retry. All callbacks/hooks restored, no unboundedTasks/no new file IO/nativeWindow activation/cleanup. Sourcecheckallarchive/buildinputs/newpin+exact18cuts/18bootstraps, independent prelaunch safety approval before app.91PASS/COMPLETE/exit0/noFAIL/stdoutstderr/postsource/3literalinputbytes/processfinished. New source/publiccontract and exact committedsecurity joint forcurrentpin. Old copies/logs preserved. + +### Task 57: Current native document/manual regression gate + +Because55 changes realcontrol tree publication, repeat exactly the approved11native observations in a NEW currentpinFcopy derivedfromnative2. Firstnative3 failed afterunsolicitedUIsequenceandispreserved; acceptedfreshnative4 usesexclusivecross-chatUIqueue. Same19explicitcuts, pureSettingsguard+Finish/postApplication.Start probes, oldnative2copyneverrerun; allrealXAML/realcontrols/owners remainpinexact. Same independentfreshprelaunch safety, allarchive/buildinputs/hashpins/ownpath/asInvoker/nonadmin/freshoutputs/no reparse. Only named11Sky actions, actualSave/Newdialogs plusAdd/Move; all11+COMPLETE/exit0/noFAIL/stdoutstderr/postsource/Settingsabsent/only2newbinfiles/literalinputbytes/processfinished required. No fullstartup/actualbackend/resize/otherbuttons claims. + +### Task 58: Continued-batch review and close + +Fresh-context final review of the entire continuation28ceef4..current with whole-branch integration context, priorclosed1..54 review notblindlyrepeated. All original5ReviewFocus items andnewstate/publication/reentry/adapter ordering checked deliberately. Regrade byusereffect; mandatoryONE RED/GREENfixpass+fullchecks, Minor deferred/rulings foreachdeclinedline. Refresh map/status/decisions/currentpins; local scopedcommits, no deletes/reset/force/push/merge/publish. User explicitly resumed; previous completion describespriorcheckpoint only. + +Task55 refinement fromGUI RED: existing PresetFiles explicit IConfigMakerPresetFileReplacementHost.UsesExplicitPresetStructure/ExplicitPresetFiles forward to rawownerproperties, preservingarrayidentity/no extraevents/rebuild. TwoextraCS1061RED tests beforefix. Task56 one copied ReplacementHostCases helper uses that existingport instead ofremovedprivatefield; preserveoriginalsource andallother15casefilesraw, record exactone-helperdelta inchecker/review. + + +Verified Task55/56: productd347c617, test-only3ba7d388. 36focused/1719full/GUI0warnings-errors65.78s, +source451/517→592/0comparedchanges, compiled452/0recordedchanges/7retainedinterfaceadds; normal0789930. +Actualstruct2 currentpin exact18cuts/18bootstraps/1231project1486repo, build0/0 and independentprelaunchACCEPT; +PID35892 91PASS+COMPLETE/exit0/noFAIL/empty streams/postsource/threeexactretainedinputs/processfinished. +Initialstructfixturebadtestsetup caughtbeforeexecution, preservedunlaunched. Jointd347+EE1931/1931GUI0/0. +Continuationreview0Critical/0Important/1Minormanagedflag-observability; test3ba7d388 strengthensexplicitmode, +36/1719repassed; sandbox12AddOnsIO failuresdiagnosedUnauthorizedAccess thenunrestricted1719GREEN. +Task57 currentnative4 eleven observations and allpostchecks complete; Task58 finaldocumentation/review pending. Native2 retains oldpin. + + +Task57 verified on NEWnative4 after native3 unsolicitedsequenceFAIL/exit1 retained. Same19cuts/d347/XAML, +build0/0 70.03s/sevenartifact+manifest pins/independentprelaunchAPPROVED. Explicituserauthorizedqueue: +CDPIUI peer+lessons pausedALLUIAPI, activeRootcheckedbeforeeachSkycall, no concurrentUIreads/input. +PID50036 21:32:14.1121727Z→21:48:15.6098961Z,11PASS+COMPLETE/exit0/noFAIL/empty streams/postsource1231+ +1486/exactmanifest/Settings-export-customabsent/only2newbinfiles/exact23inputbytesSHA70CE5088/processfinished. +AfterlastfreshUIinventory RootreleasedALLUIAPI toCDPInativefilesowner; no furtherGUIinthischatwithoutlease. +Native3 neverrerun, inputsourceunknown; minimized/no-monitor captures recoveredfreshstatewithnorepeatedAdd. + +Task56 verified-scope qualification: actual host callback changes command and explicit groups during file +publication; component is set Zapret2 beforehand. Mid-publication component flip is managed+production +live-closure source proof, not actual-host runtime proof. Direct projection fault remains managed/source-only +as previously ruled. Additional live component-switch case deferred explicitly, no product defect claimed. + +Task58 complete: fresh final review28ceef44→3ba7d388+fourdocs ACCEPT0Critical/0Important/1Minor(scope +qualification above). No mandatoryproductfix; existing1719/GUI0-0/451+452API/actual91/joint1931/native4 +eleven+allpostchecks retained exactpins; no redundantgreenrunsfortext. Decisionsappendix111Ruling17Minor. + +### Continuation59–61: App idle exit + +Spec: [App idle exit](../specs/2026-11-10-app-idle-exit-design.md). Execute inline per executing-plans; +user explicitly selected autonomous continuation, so no interactive plan handoff. Base2400dee. +Global constraints above remain; no settings/backend/migration/startup/security changes or UI use without lease. + +Review Focus for this continuation (also retain original five): (1) live Count/migration short circuit; +(2) close changes state before idle decision; (3) warning/fallback exceptions keep their original boundary; +(4) unawaited/pending/faulted creation and nested events; (5) real App-bound callbacks and lazy host wiring. + +### Task 59: App idle exit controller and characterization + +Files: create `CDPIUI/Helper/Basic/AppIdleExitController.cs`, +`CDPIUI.Tests/Presentation/AppIdleExitControllerTests.cs`; modify `CDPIUI/App.xaml.cs` and test csproj. +Produces internal constructor `(Func windowCount, Func migrationPending, Func storeWorking, +Func goodCheckRunning, Func createPrepare, Action closePrepare, Action exit, Action warn)`; +`void HandleStoreStateChanged(bool isWorking)` and `void ExitIfIdle()`. Host private signatures unchanged. + +- [x] Write literal call-trace tests for all four exit guards, repeated live count, working guard/Create, + stopped close-before-current-read, each throwing port, warn/fallback throws, reentry and ignored pending/faulted Task. + Constructor calls nothing; each test states the behavior mutation it detects. Observe absent-owner CS0246 RED. +- [x] Extract unchanged policy and wire eight lazy production ports. Host warning keeps original category/message; + close coordinator retains host method group. Focus/full GREEN, normal GUI x64 Release0warnings/errors, + source451/compiled452 recorded shapes, physical counts, diffcheck; commit only owned paths. + +### Task 60: Actual App idle composition gate + +Create new pinned F verification copy from struct2, preserve old91groups. Use existing external-cut App.xaml +to provide controlled create/close/exit/Store/GoodCheck endpoints while exercising real private App forwards, +real owner, live App.OpenWindows and real migration flag. Inactive new context preserves old close-group +Exit recorder. No activated PrepareWindow, full startup, backend or persistent settings. Add grouped assertions +for live window-list replacement/migration, Store state/close current reads, throw/fallback/reentry and callback +identity. Optional actual component-flip scope extension only if independently specified and reviewed. + +- [x] Record exact source cuts/inputs/bootstrap/artifact pins; independent prelaunch safety review. +- [x] Run bounded nonactivated programmatic host only after peer coordination; all expected PASS/COMPLETE, + exit0/noFAIL/empty streams/source/input/absence/process checks. Refresh exact committed security joint. + +### Task 61: Integration review and checkpoint + +- [x] Fresh-context review2400dee..current plus docs with original five and continuation five Review Focus. + Mandatory defects get one RED/GREEN fix pass and appropriate checks; Minor explicitly adjudicated. +- [x] Refresh status/map/decisions pins/scopes; scoped local commits. Preserve all evidence/worktrees and + continue the user-authorized project work; no reset/delete/force/push/merge/publish. + + +Task59 verified839cc952:39focused/1758full/normalGUI0-0/451source593files/452compiled0+7, +App702→677physical lines. Independent product review2400dee→839cc952 ACCEPT0CriticalImportantMinor. +Joint exact839+ee477161970/1970 andGUI0-0. Task60 newFidlefixture built0-0/71.39s, +1232project1489repo/exact18boundaryfiles19bootstraps, old91+6App=97, prelaunchREADY0/0/0. +Runner-only threeMinors fixed/read-onlyrechecked; all5binaries+3sourcepins unchanged. +Runtime97 NOT RUN: sharedownerV3peer-nativefiles remainsactive/waitingOnApproval; explicitrelease +notreceived, lessonsnextready/allUIpaused. Root allUIpaused/no newWinUIprocess, nolease stealing or +foreignapprovalconfirmation. Task60runtime andTask61finalclose remain OPEN untilexternalqueuehandoff. +LastclosedruntimeD347/native4 eleven+allpostchecks remainsacceptedwithownpin. Product review isaccepted, +not an assertionofruntimecompletion. Preserveone-shotfixtureandreviewedrunnerSHA9AF91AFE… forresume. + + +Task60 COMPLETE afterexplicitpeerhandoffV4Root/lessonswithdrawn:97PASS+COMPLETE/exit0/noFAIL/empty +streams, PID61180 2026-11-10T05:09:45.0171515Z→05:09:49.2267677Z,1232project1489repo/exact18cuts19 +bootstraps/sourcepins/threeexactinputs/settings-export-markersabsent/only4newbinfiles/priornames/processfinished. +Reviewedrunner9AF91AFE unchanged. NoRootUIAPI; afterpostchecksRootallUIpaused andqueueV5handedpeer. +Product839/normal0DD unchanged, prior39/1758/GUI/API/joint1970 preserved; finalruntime/docsreview61next. + +Task61 COMPLETE finalruntime/evidencereview0Critical0Important1Minordocwordingfixed:threeinputfiles +16/16/15bytes,notthreebytes. No productfix/rerunrequired, all97uniquePASS/first91sameordertext/hashpins +confirmed. Prior115Ruling17Minorhistoricalappendixretained. Continue userauthorizeddecompositionnext. + +### Continuation62–64: BlockCheck2 result selection + +Spec: [result selection](../specs/2026-11-10-result-selection-design.md). Base855dbd3. Inline executing-plans, +preserve original global constraints and autonomous execution. Review Focus5: captured item despite menu +reentry; live running/manual reads between notifications; list predicate before running guard; localization/ +formatting faults leave exact partial state; host sender/private setters/two-way nullable check retained. + +### Task62: Selection state and publication owner + +Create `CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultSelection.cs` and +`CDPIUI.Tests/Presentation/BlockCheck2ResultSelectionTests.cs`; modify existing PageViewModel.cs/testcsproj. +Constructor consumes Func, three Func (session/running/manual), +Func list predicate, Func text, Action menu. +Produces15same-named state properties with get/set, defaults preserved, and `void Update()`. + +- [x] Write literal branch/state/event/port-order tests, reentry/captured item/live flags, repeated equality, + nullable setter, localizer/format/menu/observer failures. Observe absent-owner CS0246 RED before owner. +- [x] Move exact algorithm/state, preserve host private/public setters and sender. Focus/full GREEN, normal + GUIx64 0warnings/errors, source451/compiled452 recorded-shape checks, physicalcounts/diffcheck; scopedcommit. + +### Task63: Actual selection composition + +- [x] Fresh F copy of newpin from idle97: same18boundary files/old19bootstrap sources, add actual Page + selection cases using current real Result/HasSession/evidence/localizer/owner/private-set/public nullable + ports. Fakeview onlySelectedStrategy/NotifyMenu; other methods throw, no lifecycle/backend endpoints. + Literal details, flags, hostsender/events, menu reentry/current Result/running and partial faults. Specify + group count and exact hashes before launch; independent read-only prelaunch review, allinputs/cuts. +- [x] Under new explicit Root lease run expectedPASS/COMPLETE/exit0/noFAIL/empty streams/source/pins/input/ + absent outputs/prior names/owned process gates; new exact committed-security joint and normalDLL unchanged. + +### Task64: Final continuation review + +- [x] Fresh review855dbd3..current with originalfive/newfive Review Focus; adjudicate every finding, + mandatory one RED/GREEN fix pass; Minor explicitly ledgered. Refresh map/status/decisions/scopedcommits. + No publication/merge/reset/delete or another session's work. Continue after coherent checked checkpoint. + + +Task62/63verified: productde3/normal9EBC,28/1786GUI0-0/source451(594)compiled4520+7/joint1998GUI0-0. +Productreview0CriticalImportant1Minortestcoveragefixed ffa65fc9: controlled-cachemutantRED, restoredsource +29focused/1787fullGREEN, no productchange/GUIrerun. Firstselectioncopyunlaunchedretained; freshselection2 +negativecurrentResult/listcase+throwingmenuorder strengthened, build0-0/55.58s/prelaunch0-0-0. +V6Rootlease+readytrue, PID45692 UTC2026-11-10T05:39:53.4500889Z→05:39:57.3058215Z,103PASS/COMPLETE/ +exit0/emptystreams/source1233project1492repo/18cuts20bootstraps/sourcepins/inputfiles16-16-15bytes/ +Settings-export-markersabsent/4newbinfiles/priornames/processfinished/5actualbinarySHAprelaunch+postexitPASS. +RootnoUIAPI, RootallUIpaused/V7releasedafterprocessabsence; Task64finalreviewnext. No productchangesafterde3. + +Task64 COMPLETE finalfreshreview0Critical0Important0Minor aftertest/doc refinements. All103unique, +first97sameordertext, retainedlogsbyteequal,5binary+4sourcehashespre/post/currentmatch,inputfiles16-16-15, +522→526files4newnames/no forbiddenoutputs/PIDgone/V7released. Product unchanged, source/API/UIevidence +retainsDE3pin,test-onlyFFAretest29/1787. Historical118Ruling17DeferredMinor preserved; docs-onlyclose. + +### Continuation65–67: report summary presentation + +Spec: [report summary](../specs/2026-11-10-report-summary-design.md), base57ede2c. Inline, originalglobal +constraints retained. Review Focus: live result reads between localization calls; precedence NoBypass vs +Success/BestEffort; HTTP-only short circuit; exception before Show produces no notice; real private host +forward/current Result + host-bound delegates. Originalfive paths remain integration-review inputs. + +### Task65: Report summary presenter + +Create `CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReportSummaryPresenter.cs`, +`CDPIUI.Tests/Presentation/BlockCheck2ReportSummaryPresenterTests.cs`; modify PageViewModel.cs/testcsproj. +Consumes five Func, Func, Action in exact +HasReport/NoBypass/Success/BestEffort/HttpOnly/text/show order. Produces `void Show()`; ctor stores only. + +- [x] Literal key/severity/trace/precedence/short-circuit/reentry/fault cases; absent-owner RED. +- [x] Extract unchanged algorithm, lazy current Result ports/private forward; focused/full GREEN, + normalGUI/API/physical counts/diffcheck, scopedcommit. No lifecycle/backend changes. + +### Task66: Actual summary composition + +- [x] New pinned F copy from accepted103, preserve20oldbootstraps/18cuts, add4realPage/Result/report/ + localizer/private-forward/inertShowStatus groups=107. Empty/success/best/partial/NoBypass/http-only, + current Result replacement, reentry/error boundary; other view calls throw. No UpdateView/lifecycle/native. +- [x] Independentprelaunch exactsource/artifacts, explicitRootlease,107PASS/COMPLETE/exit0/allpostchecks + incl5actualbinarySHApre/post. New committedsecurityjoint/normalbinarypreservation; release queue. + +### Task67: Final review and checkpoint + +- [x] Fresh review57ede2c..current with originalfive/newfive focus, mandatoryoneRED/GREENpass, + explicitminor/ruling adjudication; refresh reports/pins/scope/scoped local commits. Preserve evidence. + + +Task65/66verified:930product/normalC4DC,20focused/1807full/GUI0-0/API451(595)4520+7/joint2019/GUI0-0. +Productreview0CriticalImportant1Minortestcoveragefixed4d19d461: titlecallbackchangesonlyBestEffort, +cachedBestmutantRED→originalsource21focused/1808fullGREEN, sourceBYTESrestored/noGUIchange. +107PASS+COMPLETE/exit0/PID45484 UTC2026-11-10T06:00:48.7342523Z→06:00:52.8956430Z/noFAIL/empty +streams/source1234project1495repo/exact18cuts21bootstraps/5sourcepins/3inputs16-16-15/forbiddenabsences/ +4newbinfiles/priornames/PIDgone/5actualbinarySHAprelaunch-postexit. V8Rootafterexplicitreleasedqueue+all +paused+readiesfalse+prelaunchREADY/ownreadytrue; after107V9releasedallUIpaused. Finalreview67next. + +Task67 COMPLETE finalreviewACCEPT0Critical0Important0Minor aftertest-onlyBestEffortreentrycase+headerdoc +correction. Actual107unique/first103sameordertext/logsbyteequal/5binary5sourceSHA/exact3files16-16-15/ +empty streams/exit0/noFAIL/PIDgone/V9released independentlychecked;20/1807original930+test-only21/1808 +andjoint2019/GUI0-0/source451(595)compiled4520+7 distinctpinsretained. No newproductfix or redundantGUI/ +native rerunfordocs. Historical120Ruling17DeferredMinor preserved, localreviewablecheckpoint. + +### Continuation68–70: selected strategy test + +Spec: [selected strategy test](../specs/2026-11-10-selected-strategy-test-design.md), basee1bcdf8. +Inline executing-plans; user explicitly authorizes autonomous selection/execution without confirmations. +Original global constraints/five review inputs remain. New Review Focus: pre-try failures leave flags; +captured item but current Result after notifications; pending/reentry guard; catch/finally exception +precedence; first issue/Error, formatting before Error, zero attempts and culture-dependent display. + +### Task 68: Selected strategy test controller and characterization + +Files: create `CDPIUI/ViewModels/BlockCheck2/BlockCheck2SelectedStrategyTest.cs` and +`CDPIUI.Tests/Presentation/BlockCheck2SelectedStrategyTestTests.cs`; modify PageViewModel.cs/testcsproj. +Constructor consumes Func selected, Func running, Action setRunning, +Action progress, Action selection, Func> test, Action assignments, +Func text, Func issueText, Action error, +Action show. Produces Task TestAsync(), void ShowResult(manualResult). + +- [x] Write guard/literal traces/pending/captured item/reentry/fault-boundary and presentation tests + specified above; run focused filter and observe absent-owner CS0246 RED. +- [x] Extract unchanged algorithms and lazy host wiring; focused/full GREEN, GUIx64 0warnings/errors, + source451/compiled452 recorded shapes, physical counts/diffcheck; scoped local checkpoint. + +### Task 69: Actual selected test composition + +- [x] New immutable pinned F copy from accepted107, preserve21old bootstrap sources/18boundary files; + add4groups=111 using real Page/Result/localizer/private forward and narrow inert view. One inert model + session is loaded then replaced with a sessionless model; no external component/backend operations or + new source cuts. Independent prelaunch review of exact inputs/pins. +- [x] Explicit coordinated Root UI lease,111uniquePASS+COMPLETE/exit0/noFAIL/empty streams/source+binary + pre/post pins/retained inputs/forbidden absences/prior names/process finished; release queue. + Exact committed-security joint full tests/GUI and normal GUI binary preservation. + +### Task 70: Final review and checkpoint + +- [x] Fresh review e1bcdf8..current plus original whole-branch integration context, original/newfive focus. + Mandatory one RED/GREEN defect fix pass, explicit Minor/rulings. Refresh status/map/decisions/pins, + scoped local commits. Preserve evidence and other sessions' ownership; no publication/deletion. + +Task68/69 verified: productff6bc636/36focused1844full/GUI0-0/54.40s/source451(596)compiled4520+7. +Test-onlydfaccbd9 closes2coverageMinors: trueCanceledTask and liveIssues replacement during format; +cache-firstError mutantRED→restoredsource38focused74ms/1846full13sGREEN/productreview0/0/0. +Actual111unique/first107sameordertext/COMPLETE/exit0/PID9112gone/empty streams/logsbyteequal/allpostchecks, +UTC2026-11-10T15:06:27.9269258Z→15:06:37.3261527Z, build0-0/78.84s/prelaunchREADY, +1235project1498repo/exact18cuts22bootstraps/5binary6sourcepins/3inputfiles16-16-15/forbiddenabsences/ +4newbinfiles/priornames. ExplicitpipelineV15handoff→RootV16→V17released/RootallUIpaused; pipeline +notified to resume. Joint exactdfaccbd9+EE2058/2058/GUI0-0/92.08s. Normal96564963 unchanged. +Task70 COMPLETE finalreview0Critical0Important0Minor; no product changes afterff6, historical122Ruling17Minor retained. +FinaldocMinor corrected immediately below historicalruling122: actual111ff6 vsjointdf+EE2058. No productfix +or redundanttest/GUI/native rerun; evidence/5binary6sourceSHA/111uniquefirst107/logs/input/PID independentlyverified. + +### Continuation71–73: report export + +Spec: [report export](../specs/2026-11-10-report-export-design.md), baseff9db65. Inline executing-plans, +autonomous user authorization and original constraints retained. Review Focus: live current report after +picker/localization; setup faults outside catch; success-localizer/status faults inside catch; independent +concurrent paths/tasks; exact real serializer binding and report IO restricted to two fresh own files. + +### Task 71: Report export controller and characterization + +Files: create `CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReportExport.cs`, +`CDPIUI.Tests/Presentation/BlockCheck2ReportExportTests.cs`; modify PageViewModel.cs/.Export.cs/testcsproj. +Consumes Func, Func picker, two Func save ports, +Func text, Action show, Action error. Produces +Task SaveJsonAsync(), Task SaveTextAsync(), Task SaveAsync(Func); no ownership of files/components. + +- [x] Literal branch/trace/live-report/pending/concurrent/reentry/cancellation/fault tests before owner, + absent-owner CS0246 RED; then original algorithm extraction and lazy host wiring, focused/full GREEN. +- [x] Normal GUIx64 Release0-0/source451/compiled452 recorded shapes/current physical counts/diffcheck; + scoped local commit with exact immutable source/API pins. No clipboard or serializer changes. + +### Task 72: Actual report export composition + +- [x] Before fix, isolated expected-RED on bd91343 proves eager null-view picker binding with real host: + old111 PASS then named constructor FAIL/exit1, no new report IO. Preserve unlaunched first115 and + compile-failed red1; fresh red2 only repairs test catch-name collision. After RED lazy lambda fix, + same null-view constructor case must pass in a new immutable GREEN115 copy. +- [x] Fresh pinned F copy from111, preserve22oldbootstraps/18cuts, add4groups=115. Real Page/Result/report/ + Localizer/serializer/private save helper, inert picker/status only. Two direct-child report outputs + json/text written/read back/retained, third marker must remain absent; exact6newbinnames, no other IO. + Independent prelaunch READY covering scope change and full pins/archives/nonadmin/freshness. +- [x] Coordinate explicit UI handoff/grant;115unique/first111/COMPLETE/exit0/empty streams/allsource+binary + pre/post pins/input+output contents/forbiddenabsences/priornames/owned process gone; release queue. + Exact committed-security joint full tests/GUI; preserve normal binary and other sessions' work. + +### Task 73: Final integration review + +- [x] Fresh review ff9db65..current with original+new five focus and previous closed branch context; + mandatory RED/GREEN defect fix pass, explicit rulings/Minor, accurate API/runtime/IO limits. + Refresh docs/pins/local commits; no destructive actions/publication or evidence cleanup. + +Task71/72 verified: initialbd91343 31/1877/GUI0-0/API597/4520+7; productreview2Minor fixed viaactual +RED2bd111oldPASS+namedCtorFAIL/innerNREline55/exit1/noCOMPLETE (PID53604/allpostchecks), thenlazy +pickerfix0c5ea124. Tasktiming62e source mutation4JSONFAIL/4textPASS→restore→31/1877GREEN included. +Current0c5 31focused40ms/1877full14s/GUI0-0/18.46s/source451(597)compiled4520+7/normal0A96, +joint exact0c5+EE2089/47s/GUI0-0/69.41s. Original115bdunlaunched/red1compilefailedunlaunched retained. +GREEN115 new0c5 copy/69.96sbuild/prelaunchREADY, sameB7AEBFcase asRED; PID71744 UTC15:52:46.0727531→ +15:52:50.1694270/exit0/115unique-first111/COMPLETE/logsbyteequal/empty streams/noFAIL/1236project1501repo/ +18cuts23bootstraps/5binary7sourcepins/3inputs16-16-15/2realoutputs354-260bytes/currentfields+SHA/ +6newnames522→528/priornames/negativepathSettingsmarkersabsent/PIDgone. V23pipelinehandoff→24Root→ +25released/RootALLUIpaused+ack/requestfalse; pipeline notified, no moreRootUIinpackage. +Task73 COMPLETE finalruntime/docsreviewACCEPT0Critical0Important0Minor;124Ruling17DeferredMinor retained, +no newproductsourceafter0c5. Independentfull12pins/3inputs2outputs/115uniquefirst111/logs/528names/ +absences/PID/REDvsGREEN/samecase/jointexactpins/normal0A96 checked; no rerunforfinaldocs. + +### Continuation74–76: manual component test session + +Spec: [manual test session](../specs/2026-11-10-manual-test-session-design.md), base0d8ba6f. Inline +executing-plans, autonomous authorization and original global constraints. Review Focus: live repeated ID +vs single captured leave ID; setup/catch/leave fault boundaries; captured item/current Result after menu; +pending Run and concurrent Stop/Start without new locks; exact host subscription/dispatcher callback timing. + +### Task 74: Manual test session owner and characterization + +Create `CDPIUI/ViewModels/BlockCheck2/BlockCheck2ManualTestSession.cs`, +`CDPIUI/ViewModels/BlockCheck2/IBlockCheck2ManualTestHost.cs`, +`CDPIUI/ViewModels/BlockCheck2/BlockCheck2ManualComponentTestTasks.cs`, +`CDPIUI.Tests/Presentation/BlockCheck2ManualTestSessionTests.cs`; modify Page.cs/.ManualTesting.cs/testcsproj. +Consumes host interface11members, Func resolveTasks, Func componentId, +Action> host handler. Produces IsRunning, Task ToggleFromButtonAsync()/ToggleAsync()/ +StartAsync()/StopAsync(bool=false)/StopOnLeaveAsync(), void HandleStateUpdated(Tuple). +Private nested ManualTestHost handles real Page effects; public host keeps old entrypoints/getter. + +- [x] Tests for all spec branch/trace/async/reentry/fault/ID/restore/queue contracts; absent-owner CS0246 RED. +- [x] Extract original policy/state, cold constructor and lazy adapters; focused/full GREEN, GUI0-0, + source451/compiled452 no losses/+7 prior shapes, physical counts/diffcheck; scoped local commit. + +### Task 75: Actual manual test composition + +- [x] New immutable F copy from115; preserve23oldbootstraps with one exact old selection-helper bridge, + add6groups=121. New19cuts/24bootstraps: controlledtasks receiver/currentID/logger only in + ManualTesting; Page ctor itself remains exactpin, real private handler TargetPage/subscription, + real dispatcher, captured/current inputs, + pending/restore/leave/exit queue and partial faults; no real components/processes/native dialogs. +- [x] Independent prelaunch full inputs/cuts/bridge/artifact pins; explicit current-owner UI handoff/grant, + 121unique/first115/COMPLETE/exit0/noFAIL/empty streams/5binary+sources/source/input/output/6newnames/ + absence/priornames/process checks; release. Exact committed-security joint full suite/GUI. + +### Task 76: Final integration review + +- [x] Fresh review0d8ba6f..current plus original/newfive focus and closed branch context; mandatory + RED/GREEN fix pass, explicit rulings/Minors; accurate state/private-reflection/adapter/IO boundaries. + Refresh docs/pins/physical counts, local checkpoint, preserve archives and all other worktrees. + +Task74 product2e70779:70focused/1947full/GUI0-0/39.26s/source451(600)compiled4520+7/normal670A, +host705→572(main305→308,manual186→50). Actor owns3flags, nestedhosteffects/currentResult, samePage +handler, FuncTasks receiver-before-ID withboundmanageradapter; originalpolicypreserved. +Test-only491692bc closes2reviewMinors:separateconcurrentgates+false/nullrunningbuttonStoppedtoast; +buttonmutant2FAIL→restoredsource72focused60ms/1949full10sGREEN, productreviewACCEPT0/0/0. +Native121 copy491built0-0/79.64s,1506repo1239project19cuts24bootstraps/oneexactoldselectionbridge/ +5binary8sourcepins/asInvoker/noReparse/522priornames. PrelaunchREADYincludingextraSHA-pinnedreadback +runnerC09821A4/readback87A835C3/unique121-first115/golden354-260reports/6newnames/absence/normal670A. +Joint exact491+EE2161/2161/42s/GUI0-0/61.24s. Runtime121PASS+COMPLETE/exit0,PID69044 +UTC17:46:43.3819843→17:46:47.3377306/121unique-first115/logsbyteequal/13actualpins/3inputs16-16-15/ +2retainedreports354-260goldenSHA+literalcurrentfields/6newnames522→528/priornames/forbiddenabsence/ +normal670Aunchanged/ownedPIDgone. ExplicitpipelineV27grant→V28canonicalrequestalias(sameRootowner) +→postchecks/RootALLUIpaused/idleack/requestcompletedfalse/V29releasedowner:null; peers notified. +Task75/76COMPLETE, final evidence/docsreviewACCEPT0Critical0Important0Minor. One documentary chronology +Minor corrected:1947full+GUI before receiver mutant, restore→70focused→source/metadata inventories; +later49172/1949. Independent1533jointfiles/166overlays/additivecsproj/pins/runtime/queue verified. +No Rootdesktop/CUA APIs/no redundant GUI rerun;126Ruling/17DeferredMinor retained. + +### Continuation77–79: assignment actions + +Spec: [assignment actions](../specs/2026-11-10-assignment-actions-design.md), base72c5554. +Inline executing-plans, autonomous authorization and prior global constraints retained. Review Focus: +captured selected row versus current Result after chooser; paths snapshot/identity and cancellation; +restore selected assignment after update reentry; exact duplicate menu updates; sync vs Task faults. + +### Task 77: Assignment action owner and characterization + +Create `CDPIUI/ViewModels/BlockCheck2/BlockCheck2AssignmentActions.cs`, +`CDPIUI/ViewModels/BlockCheck2/IBlockCheck2AssignmentActionsHost.cs`, +`CDPIUI/Helper/UserExperience/SelectedItemChoiceAction.cs`, +`CDPIUI.Tests/Presentation/BlockCheck2AssignmentActionsTests.cs`, +`CDPIUI.Tests/Presentation/SelectedItemChoiceActionTests.cs`. +Modify Page.cs/.Assignments.cs and testcsproj. Consumes internal host13members in spec. Produces +void AddSelectedStrategyForSite(), Task AddSelectedStrategyForListAsync(), void ShowResult(bool), +void MoveSelectedAssignment(int), RemoveSelectedAssignment(), ClearAssignments(), +ApplyManualIssueQuickFix(Func). Page entrypoints/private ShowAssignmentResult retained. +Neutral SelectedItemChoiceAction.ExecuteAsync(Func selected, +Func> choices, Func,Task> choose, +Action apply) where both types:class; no BlockCheck2/WinUI dependency. + +- [x] Characterization before owner: guards/traces/paths identity/pending/current Result/reentry/ + concurrent/cancel/fault timing/partial failures, absent-owner RED then original extraction GREEN. +- [x] Controlled selected-reread mutant RED→byte/SHA restoration→focused/full GREEN; normal GUI0-0, + source/metadata contracts and sizes; scoped local checkpoint. + +### Task 78: Actual assignment composition + +- [x] Fresh immutable copy from121, preserve all24bootstraps/19cuts, add4groups=125/25bootstraps; + real Page/Result/editor/localizer/privateadapter/preview, controlled chooser/view only, no new IO. +- [x] Fresh independent prelaunch READY including every oldcase byte/pin/source/binary/IO gate; + coordinate explicit allUI lease;125unique/first121/COMPLETE/exit0/allpostchecks and release queue. + Exact committed-security joint full suite/GUI, preserve previous source/binary/IO evidence. + +### Task 79: Final integration review + +- [x] Fresh review72c5554..current with original and new five Review Focus; fix evidenced defects via + RED/GREEN, ledger rulings/Minors, current docs/API/runtime/scopes/pins; scoped local checkpoint. + +Task77 productb5cce888/source61fd0e7(test-only): neutralhelper39lines4ports/domainowner80lines13hostmembers, +Page572→513/Assignments171→110/main308→310.47focused/1996full/GUI0-0/41.73s/source451(603)0loss/ +compiled4520loss+7oldadds/normal24797CCA. Exactly-oncecoverageMinor fixedin61fd, duplicate-singleapply +mutantFAIL1→bytesSHArestore→47focused38ms/1996full10sGREEN/productre-reviewACCEPT0/0/0. +Joint61fd+EE2208/2208/41s/GUI0-0/59.36s; independent1538paths/172overlays/109additivecsprojitems exact. +Task78copy61fd0-0/71.78s/1512repo1242project/exact19cuts25bootstraps/23oldcasebytes/14actualpins, +prelaunchREADY. PID68696 UTC18:37:05.7871699→18:37:17.5133853:125unique/first121/COMPLETE/exit0/ +noFAIL/empty streams/logsbyteequal/14pins/3inputs16-16-15/2reports354-260goldenSHA+literalfields/ +522→528sixnewnames/priornames/absence/normal24797unchanged/PIDgone. ExplicitV31Rootgrant from +retrospective→postchecks+idleack/requestfalse/RootALLUIpaused→V32returnactivegrantretrospective; +bothpeersnotified/noRootdesktopCUA APIs. Tasks78/79COMPLETE, final evidence/docsreviewACCEPT0/0/0; +two documentarylocatorMinors closed. Independent125prefix/logs/14pins/3inputs2outputs/528recursive +names/absence/PID/queue/normalDLL/currentjointsource boundaries confirmed;130Ruling17Minor preserved. + +### Continuation80–82: neutral two-phase transitions + +Spec: [transition sequence](../specs/2026-11-10-transition-sequence-design.md), base9b65f3a. +Inline executing-plans/autonomous authorization/globalneutralcriterion. Ownership coordinator verified +no conflicting WIP/implementer in9worktrees; selected UtilityButtonControls only, not Store/backend. +Review Focus: inspect before apply vs delay after; token-read only if an actual delay is needed; +captured total vs live lists/inspect across await; old/new CTS identity cleanup; any-OCE swallowing +from body but not finalizer, no extra async wrapper between last apply and finalization. + +### Task 80: Neutral transition mechanism and host forwarding + +Create `CDPIUI/Helper/UserExperience/TwoPhaseTransitionSequence.cs`, +`CDPIUI.Tests/Presentation/TwoPhaseTransitionSequenceTests.cs`; modify +`CDPIUI/Controls/Universal/UtilityButtonControls.xaml.cs` and testcsproj. +Produces static Task RunAsync with two list inputs, inspect/apply/two delay selectors/ +delay/borrowed CTS/onFinally exactspecports. Existing private3parameter Task method/Max/HasVisible kept; +Task forward avoids extra await; literal CTS finalizer callback stays in control, catch/finally execute +in the same generic async sequence. Implementation async attributes/stack frames are not public API. + +- [x] Characterization and absent-helper RED before source; exact effects and async/fault/lazy-token/ + live-list/independent-call/borrowed-lifetime tests; original algorithm extraction, focused GREEN. +- [x] Mutation negativecontrol→byte/SHA restore→focused/full GREEN; normalGUI0-0/source/metadata + inventory/physical counts/diff, scoped local checkpoint for immutable native/joint verification. + +### Task 81: Actual UtilityButtonControls composition + +- [x] New immutable Fcopy from125, preserve25oldbootstraps/19cuts andall24oldcasebytes, add4groups=129/ + 26bootstraps. Realunloadedcontrol constructor/XAML/Buttons/Visibility/privateasync/Task.Delay; + no Composition/navigation/settings/help/backend/desktop or new IO. UISettings readonly noted. +- [x] Independent prelaunch READY fullsource/pins/asInvoker/freshness/IOlimits; coordinate explicit UI + grant,129unique/first125/COMPLETE/exit0/empty streams/allpostchecks/processgone/queue release. + Exact committed-security joint fulltests/GUI, preserve all previous evidence and normal binary. + +### Task 82: Final integration review + +- [x] Fresh review9b65f3a..current with original and new five focuses; RED/GREEN fix pass, explicit + rulings/Minors, exact source/API/runtime/joint/neutrality/visual limits; current docs/local checkpoint. + +Task80 producta5a1b9b/helper50lines/control536→500/directTaskforward/noextraasyncboundary; +30focused51ms/2026full11s/GUI0-0/52.89s/source451(604)0loss/compiled4520loss+7oldadds/normal2F0B. +CS0103RED×2/inspect-afterapplymutantFAIL1→originalbytesSHA66FBrestored, productreview82ACCEPT0/0/0. +Coordinatorstandalone12+expected11negative/context-observerproof; exactjointA5+EE2238/2238/44s/ +GUI0-0/85.38s,1540expectedpaths/1539Gitblobs/175overlay/110additivecsprojitems independentlyverified. +Task81 actual129Fcopy0-0/70.42s/1515repo1243project/exact19cuts26bootstraps/24oldcasebytes/ +15actualpins/2prelaunchREADY. PriorV39→40coordinationguard stoppedbeforeeffects; thenexplicitV41Rootgrant, +PID81460 UTC19:40:40.6399817→19:40:46.0595732/129unique-first125/COMPLETE/exit0/noFAIL/streams0/ +logsbyteequal/15pins/3inputs16-16-15/2reports354-260goldenSHA+literalfields/522→528recursive6newnames/ +priornames/absence/normal2F0Bunchanged/PIDgone. Rootpostchecks/idleack/requestfalse/ALLUIpaused→ +atomicV42releasedowner:null/bothpeersnotified/noRootdesktopCUA APIs. Tasks81/82COMPLETE, +finalevidence/docsreviewACCEPT0Critical0Important0Minor;1515fixture/15pins/129prefix/IO/528names/PID/ +queue/604GUI/joint1540paths110XMLitems175overlays independentlyverified.132Ruling17Minor retained; +allpreviousarchivespreserved/no rerun/deletion, product/source unchangedafterA5. + +### Continuation83–85: neutral postorder menu pruning + +Issue209; spec [menu pruning](../specs/2026-11-10-menu-pruning-design.md). Basea85efec4, +productA5. Issue/Project actual fields confirmed before implementation. Other executor owns208 +ConfigMaker/TextChangeRelay/CreateNewConfig/App; Root owns MenuBarController and new helper only. +Review Focus: reverse live index traversal; retention after descendants; registry then physical +then logical mutation; exception identity/partial effects; reentry without snapshot or repair. + +### Task 83: Neutral pruning mechanism and host policy + +Create Helper/UserExperience/PostOrderTreePruner.cs and Presentation/PostOrderTreePrunerTests.cs; +modify Controls/MenuBar/MenuBarController.cs and additive testcsproj. One System-only generic +Prune(IList, children, retain, remove) entry point as specified; no new partial/domain owner. + +- [x] Characterization first, absent-helper RED; extract exact algorithm and host removal policy. + Expected focused GREEN with observable ordering, mutation and failure contracts. +- [x] Controlled eager-retention mutant fails; exact byte/SHA restoration; focused and full tests, + normal Release/x64 GUI build0-0, source/metadata inventory and source checkpoint. No native claim yet. + +### Task 84: Actual menu composition and security joint + +- [x] Fresh immutable copy from129 with four new groups=133/27bootstraps, same19cuts and25old + case partials byte-identical; standalone unactivated actual menu/controller only, no newIO. + Expected independent prelaunch READY with source/binary/asInvoker/freshness/IO gates. +- [x] Explicit allUI grant, one-shot133unique/first129/COMPLETE/exit0/allpostchecks/processgone, + idleack and queue handoff. Exact committed-security joint fulltests and GUI0-0, source composition. + +### Task 85: Independent review and local acceptance + +- [x] Fresh final review83–85 with original and new five focuses; verified corrective pass if needed, + accurate current docs/rulings/limits/checkpoint. Expected no unaddressed Critical/Important findings. +- [x] All209 local criteria evidenced; acceptance comment, immediate completed+ProjectDone and actual + metadata readback. Integration14/installed15 remain open; continue only into an unowned next task. + +Task83–85 COMPLETE: product174d1cb/docs-evidencee7436d0;20focused/2046full/GUI0-0/source4516050/meta4520+7; +actual133first129/exit0/allpostchecks/18pins/PID68204gone/explicit48→idle-requestfalse→49peer208; +exactEEjoint2258/GUI0-0/1542paths111XMLadds; parallelb577+174+EE2287/GUI0-0/1544paths112dedupadds. +FreshfinalreviewACCEPT0Critical0Important0Minor,133Ruling17Minor preserved. Sourcecontroller519→502 +correctedfrom501transcriptionwithoutsourcechange.209acceptcomment6779106275→APIclosedcompleted/6criteria[x] +→Project52Done/readbackafterreload/finalcomment6779317178; exact3labels/Lumens/G2/Low/P2Architecture. +Parents14/15LIVEopen, no push/merge/releaseclaim. Next211iscreatedbutimplementationgatedonactualProjectintake. + +### Continuation86–88: Core variable read-model projection + +Issue211; spec [configuration projection](../specs/2026-11-11-configuration-variable-projection-design.md). +Basec089265/source174. Actual55ProjectInprogress/P2/Architecture/Low/G2/Lumens confirmed; +209completed+Done prerequisite satisfied. Root owns ConfigurationService/new helper/tests only; +peer212 Navigation/LoadVars/named-loader and ConfigMaker/Create/App stay reserved. +Review Focus: source dictionary enumeration order/stored spelling and fresh ownership; first OrdinalIgnoreCase metadata match; +Ordinal stable distinct options; lazy null/first-match faults and current metadata per entry; +joint snapshots include the changed Core source rather than earlier GUI-only overlays. + +### Task 86: Characterize the facade and extract the model adapter + +Create Core Configuration/Helpers/ConfigurationVariableProjection.cs and +CDPIUI.Tests/ConfigurationVariableProjectionTests.cs; modify only ConfigurationService.cs. +Produces internal static ToVariableItems(Dictionary) and ToCommaVariableItems(ConfigItem) +with existing models. No testcsproj source link, visibility widening, helper-existence test or new API. + +- [x] Actual public static/instance facade characterization on owned models first. Expected original + GREEN, then original first-match mutant RED; restore exact bytes/SHA and confirm focused GREEN. +- [x] Extract original loops/used private forward/host guards; extracted-helper mutant must cause RED + through actual facade, then exact byte restoration and final focused GREEN. No IO/native UI involved. + +### Task 87: Core contracts and parallel regression evidence + +- [x] Capture original Core assembly/source; focused/full tests GREEN, normal GUI0-0; before/after Core + source/compiled contracts0loss and unchanged605GUI sources/GUI metadata. Source checkpoint for joint. +- [x] Fresh exact committed-Security joint with Core-inclusive overlay, then committed peer composition + when available; tests/GUI0-0 and full Git/blob/XML/extra-input proof. Preserve old snapshots/logs. + +### Task 88: Independent review and local acceptance + +- [x] Fresh independent review86–88 with original/newfocuses, verified corrective pass if needed; + current evidence/docs/limits, no unaddressed Critical/Important findings and local checkpoint. +- [x] All211criteria evidenced; acceptance record, immediatecompleted+ProjectDone and actualmetadata + readback. Parents14/15 remain open; actualCoreWindows facade proof is separate from old WinUI133. + +Task86–88 COMPLETE: source00f39b1a9be70cb97cebd7290b5f24dac6a5ab47/docsf573f4f; +30actualCorefacade/2076full/GUI0-0(70.77s),Core88source103→104/compiled88/0changes; +605GUIsourcesunchanged174/GUIcompiled4520loss+7old. CoreinclusiveEE2288/GUI0-0/1544paths111XML; +peer9a9+Root+EE2338/GUI0-0/1548paths113XML. Bothbefore/afterproofs independentlyreconstructed. +Original/helpermutants3FAILeach→exactrestoreGREEN, typedSourcepublicAPI/noWinUInewruntimeclaim. +DocorderMinorcorrectedviaRuling135;135Ruling17oldDeferredMinor. Finalreview0CriticalImportantMinor, +accept6788006950→API211closedcompleted6criteria[x]→Project64actualDone/P2ArchitectureLowG2Lumens2labels +readbackafterreload/final6788179295. Parent14/15LIVEopen, no push/merge/release. + +### Continuation89–91: Diagnostic highlighting updates + +Issue215; [design](../specs/2026-11-11-diagnostic-highlighting-design.md), base80c1ec2/source00f39. +Actual69ProjectInprogress/P2ArchitectureMediumG2Lumens/3labels readback beforeimplementation; +211Done64 prerequisite verified. Root onlyControl.Editor/newSystemupdater/tests; peerVM/Create/Appreserved. +Review Focus: separate live passes/Source reads; raw-key collisions and current post-collection comparison; +commit before callback/sticky faults/reentry; literal UI receiver/constructor/Design order; transitive +Search/ConsoleFont preference isolation before actualControl construction. + +### Task 89: System-only highlighting update state and host delegation + +Create Helper/UserExperience/DiagnosticHighlightingUpdater.cs and Presentation/DiagnosticHighlightingUpdaterTests.cs; +modify onlyControl.Editor.cs and additive testcsproj. One signature field/Reset/sevenport Update exactspec. + +- [x] Characterize with plain nodes/traces before helper, missing-helper RED then original extraction GREEN. + Expected two current reads/error-first/lazy tokens/raw data/collection-reentry and exact fault boundaries. +- [x] Controlled commit-after-callback mutant RED with bounded reentry, exact byte/SHA restoration; + focused/full GREEN, normal GUI0-0/source+compiled contracts, source checkpoint. No publicAPI/VM changes. + +### Task 90: Actual control composition and parallel joints + +- [x] Fresh archive from new committed source and accepted menu133casebase, four new groups=137/28bootstraps/ + 26oldcasebytes. Old19cuts plus exactly Search/ConsoleFont preference endpoints=21, typedinmemorycallbacks/ + fixedvalues, no product preference changes or newIO. Expected fullsource/pin/asInvoker/freshness proof. +- [x] Independent prelaunch READY/exclusive explicit grant;137unique/first133/COMPLETE/exit0/streams0/ + allpins/3inputs2goldenreports/6newnames/absence/processgone, idle/handoff. Exact committed-Security and + corrected availablepeer joint tests/GUI/source+XML proof, preserve original and rejected artifacts. + +### Task 91: Independent review and local acceptance + +- [x] Fresh review89–91 incl all original/new focuses; verified corrective pass if needed, current docs/ + rulings/limits/localcheckpoint, no unaddressed Critical/Important findings. +- [x] All215criteria evidenced, acceptance record/immediatecompleted+ProjectDone/actualreadback; + parent14/15 remain open, real visuals/startup/installed integration not inferred from bounded137. + +Task89–91 COMPLETE local: producted390cd416b58ea404f04286f7eace5a66e4320a/docstechnicalcee65ac; +32focused/2108full/GUI0-0/source4516060loss/compiled4520loss+7old, helpermutant4RED→exactrestoreGREEN. +ExactEEjoint2320 and correctedpeerf706+EE2398/GUI0-0/fullsource+XML independentlyverified. +R2actual137unique/first133/COMPLETE/exit0/all23pins/1531Git21cuts28bootstrap26oldbytes/IO/PID79052gone/ +explicit83→idle/requestfalse→84release. OriginalcompiledV1preservedunlaunched; Count/import/attribution +corrections+fonttiming/statusdocMinors retained. FinalfreshACCEPT0unresolvedC/I/M;141Ruling18DeferredMinor. +215accept6789505833→APIclosedcompleted6[x]→actualProject85Done/P2ArchitectureMediumG2Lumens3labels +readbackafterreload/86released. Parents14/15open; no push/merge/releaseorunionnativeclaim. diff --git a/docs/superpowers/plans/2026-11-11-class-integration.md b/docs/superpowers/plans/2026-11-11-class-integration.md new file mode 100644 index 00000000..dcaa61f9 --- /dev/null +++ b/docs/superpowers/plans/2026-11-11-class-integration.md @@ -0,0 +1,73 @@ +# Class decomposition integration implementation plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Keep implementation inline and obtain one fresh final whole-change review. + +**Goal:** Compose the accepted Root and peer decomposition on current default, qualify the actual +combined revision and publish a reviewable draft integration PR under issue14. + +**Architecture:** Preserve current default except the exact reviewed decomposition delta. Resolve +App through a three-way merge and test source links through additive XML composition. No new rule +implementation or interface framework is introduced. + +**Tech Stack:** C#/WinUI3/.NET8.0.427/xUnit, Git blob provenance, PowerShell7/Python fixture tooling. + +**Spec:** [integration design](../specs/2026-11-11-class-integration-design.md). + +## Global constraints + +- Preserve source pins/default6c00/Rooted390/frozenRooteebc/peerf706 and prior artifacts. +- Existing issue14/intake87 is the owner; keep14/15 open until their original acceptance passes. +- Existing isolated worktree; new dev/audit-class-integration, no shared-main rewrite or deletion. +- Preserve upstream security/localization/workflows and exact default test project nonadditive XML. +- No real preferences/backend/privilege/desktop actions in bounded native tests; exclusive UI queue. +- Fresh source/runtime/CI evidence applies only to the named new SHA; prior2320/2398/137/141 is history. +- Current-default API0loss is distinct from the pre-existing historical Root/G1 GUI1/Core3 drift; + keep13/14/15 and the draft boundary visible, no G1 takeover or main merge. + +## Review Focus + +- Root window creation reads the current default StartupInitialization.Ready; early startup/faults + retain readiness and emergency behavior rather than reverting to an older completed task. +- Source transplant keeps every upstream non-owned path and deliberate test-link removal; XML + deduplication does not drop Security, recovery or dispatcher regression tests. +- Live collection/Source reads, notification order, exception identity, sync dispatcher callbacks, + callback mutation and same/different-key reentry retain both owners' accepted contracts. +- Union native cases share logger/context/static-event state without invalidating either prior corpus; + font reads are explicit and Loading remains unexecuted. +- Current source/resources/binary pins, owned IO/process cleanup and new explicit UI grant match + the exact integration SHA; no installed/full-startup result is inferred from bounded149. + +### Task 1: Establish default and compose exact accepted source + +Interfaces: current default + reviewed Root/peer blobs → composed source/provenance manifest. + +- [x] Record default API SHA and actual Project87 fields, preserve frozen Root/peer refs and oldnormal100E + artifact, then create new integration branch in the already isolated worktree. +- [x] Run fresh default tests/GUI and preserve source/compiled baselines. ExpectedGREEN; on failure + investigate rather than attributing a pre-existing problem to the transplant. +- [ ] Compose scoped Root/peer Git blobs, clean App three-way merge and additive current-default XML; + preserve all upstream non-owned paths and relevant owned documentation, record full provenance. +- [ ] Focused/full GREEN, normal GUI0-0 and API0unintendedloss; verify exact complete input/tree/XML + proof and source checkpoint. Commit only the named source and reviewable documentation. + +### Task 2: Qualify the actual native union + +Interfaces: composed source pin → immutable149 fixture/source/build/pins/runtime proof. + +- [ ] Preflight Root137+peer12 exact source/case labels/private probes/context/logger/readiness/resource + inputs; prepare a fresh archive, exact boundaries/counts/31bootstraps, independent pre-build review. +- [ ] Compile0-0, pin actual binaries/resources/source/runner/verifier and actual fresh filename count; + independent prelaunchREADY plus new explicit exclusive UI grant. +- [ ] One149unique/Root137prefix/peer141projection/COMPLETE/exit0 run, then all source/IO/hash/streams/ + owned-process checks, idle/requestfalse/release. Preserve any failed/rejected attempt intact. + +### Task 3: Final review and publish the qualified revision + +Interfaces: all source/contract/runtime proofs → independently reviewed exact PR HEAD/checks. + +- [ ] Update current docs/provenance/limits; fresh strongest-model independent whole-change review, + resolve actionable findings with the appropriate verification and final source checkpoint. +- [ ] Refresh current default, preserve any newer change, prepare exact PR body/metadata and publish + isolated branch/PR with Refs#14; verify required checks on final HEAD and read actual metadata. +- [ ] Record actual achieved acceptance and any remaining14/15 criteria. Close only if all issue14 + criteria pass; otherwise leave it in the accurate working state with explicit next evidence. diff --git a/docs/superpowers/reports/2026-11-11-class-integration-provenance.json b/docs/superpowers/reports/2026-11-11-class-integration-provenance.json new file mode 100644 index 00000000..68449752 --- /dev/null +++ b/docs/superpowers/reports/2026-11-11-class-integration-provenance.json @@ -0,0 +1,980 @@ +{ + "main": "6c00c789ee2b37238af30f14cfdaf0f55a278274", + "root": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "peer": "f706f16934695bcb122de63d0442c4ab20f42869", + "rootDocumentation": "eebc7e8621b85fa08ee015ea3b7eab1e72c78c5f", + "rootScopedPaths": 184, + "peerScopedPaths": 10, + "bothChanged": [ + "CDPIUI.Tests/CDPIUI.Tests.csproj", + "CDPIUI.Tests/README.md", + "CDPIUI.Tests/README.ru.md", + "CDPIUI/App.xaml.cs" + ], + "additiveItems": 115, + "defaultItems": 14, + "changedProductInputs": { + "CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "44953430ede3f53f8c3907415403a1ae82cc2459", + "sha256": "6888415433219AAFE8C1824997CBB1246CC33AB860ED084CF07C527944930066" + }, + "CDPIUI.Core/ComponentServices/Helpers/Configuration/Helpers/ConfigurationVariableProjection.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "dc02ededba0f8ec14505e05fa01199d59db4b0d0", + "sha256": "47312139432BE2478A2E7900B90A01517B180A1ACCA93C00CFFE9630AEC331A9" + }, + "CDPIUI.Tests/CDPIUI.Tests.csproj": { + "source": "default plus deduplicated additive Root/peer items", + "defaultItems": 14, + "addedItems": 115, + "deliberatelyRemovedDefaultItems": [ + [ + "Compile", + "../cdpiui.trayicon/helper/basic/directoryaclguard.cs" + ] + ], + "sha256": "329C4F2D6ADFED45C46CD6258EAFBBA7DF93DBB535283FA16A577B1E4EC3F6C7" + }, + "CDPIUI.Tests/ConfigurationVariableProjectionTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "8f5decd3c7d35c03991b8e161c624a979c71c830", + "sha256": "CC67903FA7A11ABEC2478B0F7C4D4AE26BB7154D6AB538423C9A33C4BF347F09" + }, + "CDPIUI.Tests/Presentation/AppActivationDispatcherTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "076d78efba963cf28dbb133ee7547f2adfb1614f", + "sha256": "73F8396B4315006546209DC7D58B28622F7954779ED8FA764E154B27A53DB8F2" + }, + "CDPIUI.Tests/Presentation/AppFileActivationHandlerTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "169061992c9b9a24a0ec29459c0f9ae079d1c304", + "sha256": "11EA2FBD84A6E095544C364CCF2DF92B1535925960A654916096BECB3886209F" + }, + "CDPIUI.Tests/Presentation/AppIdleExitControllerTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "0214b82f42749c66f67ae5dc73f74a1beab61eb1", + "sha256": "FED1B2FAB4AA9682F60331839B7308CE86A1177B7D4E07FE7128489DEC21CE70" + }, + "CDPIUI.Tests/Presentation/AppWindowCloseCoordinatorTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "a54a752028393515c8d6de954e0461451a9afe55", + "sha256": "CE22BF8557D002330DEE73D90982BC5D798A15FE7037EF96AF0009993E6293D3" + }, + "CDPIUI.Tests/Presentation/AppWindowCoordinatorTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "5cfec9f7adaf800661c0bd2109798e04faf253b3", + "sha256": "BDA2163DF9E82BE81CADFCFC93352AACFCA346858C8C4CA1B98DE7CF4A70EBB9" + }, + "CDPIUI.Tests/Presentation/BlockCheck2AssignmentActionsTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "c0ce8e2d8d21215a37a5c478be180d64f008d024", + "sha256": "E7E052865FF2FAB8F71C5EEAA38A10A20EA36E5BDBBC7F6C20DA35E2C3C334FB" + }, + "CDPIUI.Tests/Presentation/BlockCheck2ManualAssignmentEditorTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "facf3aa88aabaaedd9a69635e8fe607763b6ca6b", + "sha256": "B43CF7392D392B0B55DF943CBEB554D1779F3B59444DE241EAD009B071B139C7" + }, + "CDPIUI.Tests/Presentation/BlockCheck2ManualPresetStateTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "36ba7220a512f85bc28e64a04d2e1afae1bbdd67", + "sha256": "B365C2BE551E6993E04B04FC1246766C75DA940CCEC03A5351C47583AFB413CF" + }, + "CDPIUI.Tests/Presentation/BlockCheck2ManualStrategyTestControllerTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "9edb81da240a41312adafb9b3eeb292e5067f15b", + "sha256": "994195037AB08BBD6F0AD3A0A5B9B53F5502D5A51C06F2294BB2D153E6D155EF" + }, + "CDPIUI.Tests/Presentation/BlockCheck2ManualTestSessionTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "d6da9dd4d6a8fa9b2196c56dcb2110ec38dd8201", + "sha256": "D62735B094A8877A941B700DE7761A785AC62AF65DD6F142501BC02AA5B5E6F6" + }, + "CDPIUI.Tests/Presentation/BlockCheck2OptionsTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "10ea214cfa0e80b7d9fe34a8609c2946be4a4194", + "sha256": "3FA4620E81EFBB7786010E520F3F47E8A32B6354D78318B8D717FE7B4320164D" + }, + "CDPIUI.Tests/Presentation/BlockCheck2ProgressTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "b5ceef2c53f4f713708a0889cdf8c7b1fecbf9ff", + "sha256": "1187BC15A8C549C870FDDDF625DFCF75517E8C68C0C2D5C4640A873130FE2BFF" + }, + "CDPIUI.Tests/Presentation/BlockCheck2ReportExportTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "384a7134d4117971ac6bf82c3d52cb31781fc22e", + "sha256": "D7D7B07817ADDC22AD26F2B0D810E1251C04324E6FF040BC2C325E0E7D0158DA" + }, + "CDPIUI.Tests/Presentation/BlockCheck2ReportSummaryPresenterTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "f158e8e893fad88a1e5a9d6d8fe23d886c3bca64", + "sha256": "AA605CFDD163C94E87F25B82245630E6D80EE6DC42292D6D8B78D778CF12FD55" + }, + "CDPIUI.Tests/Presentation/BlockCheck2ResultSelectionTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "edc0ab240977ab9487a69b40d829a4dd215be38b", + "sha256": "7F19A360B42F7C5EEEC29F4227838FDCB411C0AAD8DE8045AADCA125F761A4C3" + }, + "CDPIUI.Tests/Presentation/BlockCheck2ResultTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "3a2e47a51f20f13f49b2927c9ca9f9e86645b380", + "sha256": "1E89BEF2484EC5D60EDF5AA12A84FCD7F3661368D36AB4BC947D5117DC401E5C" + }, + "CDPIUI.Tests/Presentation/BlockCheck2RunControllerTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "994f4f8185412c929e5b68a518e90565ef20e88f", + "sha256": "BA03BAEE7F969CD271C85B7822A21B10A5281E726707D0C61801BFE0EEC1A02F" + }, + "CDPIUI.Tests/Presentation/BlockCheck2SelectedStrategyTestTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "3ef5f78765569079750d6f83c6a9be0b560769b6", + "sha256": "003FB932CD8A549A995A518B02C73A073B1F4B7D4199584F9BFFF513E24D3DC8" + }, + "CDPIUI.Tests/Presentation/BlockCheck2SiteListControllerTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "f2cb1a0b2f8decf01649735785c971dbf312a0a2", + "sha256": "3AC171F4A6EC257673935FCAABAF46BECAC6CFCBBA456BA31C2642744362DB61" + }, + "CDPIUI.Tests/Presentation/ConfigMakerCommandHelpLoaderTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "18957448340d76e159506cee308f7629714f01d1", + "sha256": "DD6E1322AFE8D4B0A83C3B075391BDF0F173A83B496E37601A1659034B278F47" + }, + "CDPIUI.Tests/Presentation/ConfigMakerCommandHelpPanelTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "8f05c0c1108e8ff39d8a468a242cd85bd195cc14", + "sha256": "281920ACFC0845572A09D22C21D40793057D0D3D20AECCA12C0454F3731BC4BA" + }, + "CDPIUI.Tests/Presentation/ConfigMakerDiagnosticsTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "f7ad95f4734ffc19d81031d91ee27c271cc3ef8c", + "sha256": "367E0684EA4FA7D01074D8FD47A4F2246CD1D57899394413792170C05E8BD780" + }, + "CDPIUI.Tests/Presentation/ConfigMakerDocumentCoordinatorTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "096ec2b86a36c12f867d6adbbb49100f41741bf8", + "sha256": "D70D5AFE62E2CD3457EAA91E7C8A6B22A8E2B9CFAE86370879E959E935506858" + }, + "CDPIUI.Tests/Presentation/ConfigMakerPanelLayoutTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "8a6285a1d056641534571a4f24017123f3aedc61", + "sha256": "9435928BE44AF94C4F9FBB06E65286BCD11FF118D96F377B95E9E44A552BDBB0" + }, + "CDPIUI.Tests/Presentation/ConfigMakerPresetFileActionsTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "5dd9429a8ddad236fd607d9aeb297488deb2d5ed", + "sha256": "E979CAC086ED2E4895D2A55E016C32EF896136F9E016CEA51EA9BF9FB6EB93D9" + }, + "CDPIUI.Tests/Presentation/ConfigMakerPresetFileReplacerTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "bcdc0340b284b92c9a4e8097f46a0efbf3705244", + "sha256": "CB3CBF18B1EBB1F5B4C45B32C801669E315250D6682282DECE8075B758D0B626" + }, + "CDPIUI.Tests/Presentation/ConfigMakerPresetReferenceEditorTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "f665b0f0913b5a4e275fb02a9c83184000761138", + "sha256": "4313553BB0D17CBE8C412AC968E62254D63681DDC17829ACB3ADC091B019036B" + }, + "CDPIUI.Tests/Presentation/ConfigMakerPresetResourceTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "d7214c4cebc62e81ab57089a6134e564b74e4aba", + "sha256": "1A6086D615DE6364956B35505D2CA5E33E6309D964357A7D12360C4538F8758A" + }, + "CDPIUI.Tests/Presentation/ConfigMakerPresetStructureTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "a8bfa4978eb715b035ffccca5db1f2be84b171bd", + "sha256": "EAED3D7ECAA29EDCD135B2E896DDE78C8CB4515D0B05D99BF415D864E4032EDB" + }, + "CDPIUI.Tests/Presentation/ConfigMakerPresetTreeBuilderTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "d3858da183fedc879f33f60c8d34b7b19f84d602", + "sha256": "EE63AC684DDA7510156A66B6429898D5683D7190B96EC81CA2CE2CD3BA9CB7EB" + }, + "CDPIUI.Tests/Presentation/ConfigMakerSimpleDesignerTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "0ef22d5a38ea51972a468f7c41f0b070d7663bb9", + "sha256": "41B7BEB3E325896FE8C2F6B20DE3ACDFE39E334DF491C62D7397927B3A65572B" + }, + "CDPIUI.Tests/Presentation/ConfigMakerTestSessionTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "9ba3f847fd766d471c0ecc91339138573a867cf6", + "sha256": "6160D85B249195C8D60B8D549695EB533AFED4812599FFA4CAA57C11978143F4" + }, + "CDPIUI.Tests/Presentation/ConfigMakerVariableActionsTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "c0d8d3eddcf765dc6e4d81d35183eca6fe4082e5", + "sha256": "8261798124246AF5C63FFF41EEC7F4F6BD716F05CA9628D5AE7BB6DC965F683F" + }, + "CDPIUI.Tests/Presentation/CreateConfigComponentSelectionTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "fa9e96e632d7cb8c757d5dcf5ebef71d383d6b49", + "sha256": "CE66AC6D3CDBABF3341F02EE43A3EACDFB02DDE8866BE33209C4E5ED00B65DB6" + }, + "CDPIUI.Tests/Presentation/CreateConfigConditionDraftTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "f5febcf1e8e7e930adcb4258e55f6d8df71aadf2", + "sha256": "39D7B95FDF6669937573D8C95CEB0AC9EC6F16A59584AFFD2A923AE9B565B35D" + }, + "CDPIUI.Tests/Presentation/CreateConfigGraphicDesignerTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "0d44bf8f329e1d0ac2ab96d871869de589de56e8", + "sha256": "675E34B34CA5D8A67CFC106394EEB1C2462CB686E3DC7C951AAA2A2508897AE7" + }, + "CDPIUI.Tests/Presentation/CreateConfigTestSessionTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "4b2daca79ef396dc1ba4245f69f4c68867955e47", + "sha256": "CA15D1AFBAEF26368FE9702772D1DB36AF119D2F7F9D766AD6847619641F0559" + }, + "CDPIUI.Tests/Presentation/DiagnosticHighlightingUpdaterTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "8674e4b657e0504ad01088ed220e0e1a07e0fe69", + "sha256": "61A6675FBE16380064ED5C33BF0E6D68004F76DB0D0580589FDB525012D1ABB9" + }, + "CDPIUI.Tests/Presentation/DispatcherTaskBridgeTests.cs": { + "source": "f706f16934695bcb122de63d0442c4ab20f42869", + "blob": "547b75f781aa9bf8cb05a95fb3cbaf5fe2699e50", + "sha256": "783207E45C64C83786E94C2DA2C3E4092522924F583413E40517B94A4091819D" + }, + "CDPIUI.Tests/Presentation/GraphicDesignerCommandCodecTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "8d2de6cc600ccc4528d12714bc064aabadbb11bf", + "sha256": "C797D5608A7759D212B112DB923E41516F03EACB62C86D25772084130C834A46" + }, + "CDPIUI.Tests/Presentation/NamedValueCollectionLoaderTests.cs": { + "source": "f706f16934695bcb122de63d0442c4ab20f42869", + "blob": "02bcb9633eb491720ca30d1301550acbe5b222e0", + "sha256": "630FC5EFF40160216A88E3A3BC58B73E796BDDE21A1DCB6F30525337A0D76CD1" + }, + "CDPIUI.Tests/Presentation/PostOrderTreePrunerTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "f12bcef5388d267cd0df87957f7a2aa3cbb6c212", + "sha256": "1DACFF41D99AF6FDEA0FC756BEBB10A58CE4E22458A316C6A553694861A6E8EC" + }, + "CDPIUI.Tests/Presentation/SelectedItemChoiceActionTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "8555d9fba87d69d7e6a79a0c0a15edd632b29332", + "sha256": "C1E75EDDE8820530F6946C673E6B0B43E189B7613F06A12E2E48C103074945CB" + }, + "CDPIUI.Tests/Presentation/TextChangeRelayTests.cs": { + "source": "f706f16934695bcb122de63d0442c4ab20f42869", + "blob": "07e75a02b686feef932097a6587425d5fe9db63c", + "sha256": "2ED9AB16D045ECDD743F2C3D84AC6919D7400F82FBD342D9FB893657CF44A5EB" + }, + "CDPIUI.Tests/Presentation/TwoPhaseTransitionSequenceTests.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "a8c4e6162d2ce9037c64c64542a1fb8def7a152f", + "sha256": "3CF5E659DB92514E6AC5D8F57A51479B45FD8F06FF0A749CFE0DE3694501D166" + }, + "CDPIUI/App.Activation.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "a1ee7e4273a8e7caac6f52bae06e8dda0850f5de", + "sha256": "B71977E7C391A69B2FA4414DCC831421B056F5221EB56AAF00A2F9FDD72B81B6" + }, + "CDPIUI/App.Modal.cs": { + "source": "f706f16934695bcb122de63d0442c4ab20f42869", + "blob": "057c831cc6f6e5aa7df04e94581edffdffa189a1", + "sha256": "0899562436E761C806CA70E4C9CCF3549190988BC15856879C4256D5AB8047C1" + }, + "CDPIUI/App.Windows.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "e69d3c9b6f9e1167e09678772fa8ab2c23e2f4e8", + "sha256": "C8DA2BFD54E9F0127D62267C7C43EC5F62C4B38466B1443099C08E8DAB2FB9D1" + }, + "CDPIUI/App.xaml.cs": { + "source": "three-way(default,f39,Root)", + "inputs": [ + "6c00c789ee2b37238af30f14cfdaf0f55a278274", + "f39e8a0a7267e4fcd4a02eef186a3ee08df8dcd9", + "ed390cd416b58ea404f04286f7eace5a66e4320a" + ], + "sha256": "F65F5DCD6441A8D562E109CD25E40098D59A92BBEB6BCC8419032306A2006B66" + }, + "CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.Editor.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "a95d25517f0b3ae4363215e7b64b965901e90265", + "sha256": "07208EB0EFB45ACBDD4D263532A495A79F16AA9C7381D3A51D8EA208D1F50966" + }, + "CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.Layout.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "5144255f0e51ce6fc9d5f4acef6952b46611e30b", + "sha256": "935B730CEAF510BA80DF0F4F86C6F3C5B28EB13F013EFAFAB77EE2099D9DA90D" + }, + "CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.xaml.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "921893c6879285995858592ff1a13876282aab05", + "sha256": "A8EC574704E1EA29F906D52FEBC3E12B8D157BE44A6F111C782F2049FF68501F" + }, + "CDPIUI/Controls/CreateConfigHelper/EnumModel.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "e3f581edbfc21ac0c58ab35b979c323474ef09d0", + "sha256": "0B6B1F80151218AE82E24FBE1037EDD3B861D6AE9730B7233B7E183EE3D168F4" + }, + "CDPIUI/Controls/MenuBar/MenuBarController.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "9d1d2389fef113ab7a98d4d76f266d8c1a53302d", + "sha256": "59CEA4B8BEAC39FC007E5A8C5790E5671CE411B5C830C28E887528D533FA367D" + }, + "CDPIUI/Controls/Universal/UtilityButtonControls.xaml.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "f678d4b40cfb2c81ec1a39ce7b7d6bbc0946316e", + "sha256": "93A9064F5AD0B16F73CE4CE264BCDF6130D8FC8305F30217B54FFFD27DE266D4" + }, + "CDPIUI/Helper/Basic/AppActivationDispatcher.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "0b4444dfe8381917815c73e76635d5ed04dd9f3a", + "sha256": "88108374255B1B909A79A2FBD16D91FF85FDFC6D8BB80028DCE0FB10861AF6AA" + }, + "CDPIUI/Helper/Basic/AppActivationRequest.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "72f2a88cd3a980a936d263acc78591b6441293dd", + "sha256": "8A6F13974DE8B34DDCC7F53A838572967C26F06B90665EF53ECE2792046DB65F" + }, + "CDPIUI/Helper/Basic/AppActivationRequestAdapter.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "487151949a516cf42f2acf63239a5fdf8ba1b1b5", + "sha256": "6C1CC16927AB80CE1408FEA456002F3312AB7CB9901F22AD03DA1321B2900A4B" + }, + "CDPIUI/Helper/Basic/AppFileActivationHandler.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "2743d39fadfef4be6d4450fb581e8293d477a921", + "sha256": "5B07572F7C332D7477B34D2D0AA50C1ADA8D0299214EAFFC9FF1C5541DAEE719" + }, + "CDPIUI/Helper/Basic/AppFileActivationOperations.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "e3a7c27050c40041ba24f4d2b07c86010930e627", + "sha256": "5F9C7F048B844BB71A7C5031A109094DAFBC1F0EB14D1133624DA2DEDF8369BE" + }, + "CDPIUI/Helper/Basic/AppIdleExitController.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "72eac4aa17713ddfd0634a4ba93fe27fdde1cb9d", + "sha256": "01CC79ADB10194062CE1BBCFDDB899EE4BEC9415F3BAB4FD2217728AA7471400" + }, + "CDPIUI/Helper/Basic/AppWindowCloseCoordinator.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "945aa25a3ad3c7601ec3322f5bb329f2511d1469", + "sha256": "B0F2AB05857549742CCD34FC65D459C97698A57779C97363D006DBB3B76115C1" + }, + "CDPIUI/Helper/Basic/AppWindowCloseOperations.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "4390ce2a43b7bf0f077dcf68b5ab2bba7620536b", + "sha256": "C684E83C67B8BB794AA44D33E947E62800CAE4B0236754F9F1182EF50FD07414" + }, + "CDPIUI/Helper/Basic/IAppFileActivationOperations.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "e4d29ac31832dd35a31a27f54c32c25835849572", + "sha256": "C18B222895525B4BBE879570A3FC567C7E9E818B912465D668DD6688BB04B2D8" + }, + "CDPIUI/Helper/Basic/IAppWindowCloseOperations.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "d744181e38f25c0f74688edf88ca2f7438b02019", + "sha256": "0867DB36C1E44AF1ED06DCE56562194893762858D7ED7EF43C0957C0446F40DF" + }, + "CDPIUI/Helper/CreateConfigHelper/ComponentCommandValidationService.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "fb11c5bcba03320a3790eeb3c974b58f8933ac46", + "sha256": "A8EE0A344DF9051E0E835F4275E5BA2916F01C58446EE8AF5DC3F15D28C0AAC5" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandHelpLoader.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "f4915a3d0ba1649326935a735a933205b31166ac", + "sha256": "F744FF9E7D2DE559AB5DECEA8AF3621E11C9DBEF413A4B32523D68309683E717" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandHelpPanel.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "0dc6c6fe77781390a8e31b947e2267485346f8db", + "sha256": "E0E17F1820E333D1628200DFA7F47E07181EE65A4D5FAB5166F0B9590C8A4E10" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerCommandText.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "2b6ee991101ee1ed4800d4ffdc5e57075524dda1", + "sha256": "B54C60AFC21643747287A4397E5D775C7045BD7F6C3C2AB00DE3E94896A69A5B" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerComponentTestTasks.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "a9e66c9d3d6b117dc420fb603277318c8f8c5e41", + "sha256": "C115C66803D25B257511CF09D516196D2E898988A6AEB8BF5B68E13EB1F37BBC" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerDiagnostics.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "b10c9a473143de8bb5e43f6f174047b1eba918b3", + "sha256": "676D952B94ADEF8AE4E1AB6B6A5D90852FF827BE40B4865AA3A83AA78437D5D8" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerDocumentCoordinator.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "5043a909ad458649524dd15fbe0fff7d46279b27", + "sha256": "D6BBA48CFF435B01FC70413C4B06748F4B47872AB306C98EE1DDE1CF58DCB598" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPanelLayoutController.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "e69298c26610b3bc4f9ccfedd5f8572f0241d721", + "sha256": "9B4C719FB8DD4CFFC67471DF53637FED4C6D0E542B8A5A8FA0E45003CA9E7851" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPanelLayoutView.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "eb276460f8cc0481d510dbd4bd6bcd049213a1e8", + "sha256": "91D9106CD6C944597485D6A3C9B18BEBEEE33A77142539D648A2CBE7DF8B8638" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileActions.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "1bb1144651cc2e20775c9fb1f3112a48ddbd6643", + "sha256": "26BEDEC67E3F4A5CC3136CE2082BCA628F7166F63F5480632947C9FEE17B4915" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileActionsBackend.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "7e32b3dbbbe6fb50de5d4dc5e248f6d206b6e9f9", + "sha256": "4BA47479DD187B08B79110E3288625E3C87A8E5817126951EEF1129D7C1CF530" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileKinds.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "e8da73358ed9e143d9d766f561a0fd3bf528ef1b", + "sha256": "38CE68FC3DCBC8FBF68EDC2BD5989B50DC6DA4069FBB905D293724A9D03F042B" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileReplacementBackend.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "878d0946903132f98096e6e7c487f959d43d9d8f", + "sha256": "0E48CDD2A7AC3A3408D30C3C8C50245CC2C5FF5D486A6616B2030D72DF8E0684" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetFileReplacer.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "baebb02c0b43cd883738b4a267d0610357d6ee12", + "sha256": "C7C848C08CF2C69DB6BAF751812BB48A05AA6627826B4BD9FD6F2F44B627D740" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetOptionGroups.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "4ba6637cd8434723fca4c3aac1a839b08d8e5e5f", + "sha256": "7C82088E6FA57793EFD298A3CDDBA80BFE7DDC79CB3AD18FBF55A141E8DBBB98" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetReferenceEditor.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "f568d63070b37f4a5d020b49551ae64a76460f95", + "sha256": "829B0680E8F5E0408DFE1B1D55B0B6DF143095CD8478BCEF9565EE3308474E76" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetResourceRegistry.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "d52c10e02fa8c1c13bdda5b871bd95c76156e70d", + "sha256": "CCB9F567632D6A5C28F1B822739F046C2F38A0F4995FEDBAD6DCBE6C825BA015" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetResources.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "5f2989b1ad89df633c08b03f1bef2011976222bf", + "sha256": "CA4138E0F40FC372FE0139D230FE97C5113B4B64FF59B675F76478A05DF1444C" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetStorageService.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "7ffb7be070045a6f8314ae517c5a38ff4230179a", + "sha256": "9F1F2EDEA3E29EBDA32B61D005BF764C1CE031A87060204B10CF38A42BDCEB8C" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetStructure.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "e33185898764a4a8ddc82c8e5ae34324188bb993", + "sha256": "D9184CA4E5F2AA43BCD5BC2DD9CF0E0A6F9AB2B2ED54F1E2E28E38708671599B" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeAdapter.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "54573dde08d0d99a504d2c04a201106e1fce325d", + "sha256": "C4D1CEC74AECF8F0F4F233DE3815801C02F92851BE9CCD1963857619EF38E675" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeBuilder.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "6bdf8fcfd63964882389c126d6045a86f11b3509", + "sha256": "E26D4ACA527E8D719DD4E8096C4052CC48564D3A17129C1D1F0F27F7BC9510A7" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeData.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "aad8866a41b7636afa3bb022f26ec732dfc5afc3", + "sha256": "FC4EA0EAA2B9A4A1877DBF4B2936CA39272D24AB89D0ADDADDC1709CCAEA50B0" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerPresetTreeProjection.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "9e94ab8465039aa793057d301f4055ac7c8648f3", + "sha256": "DE7185CC643C11C88CC859EAB772C2A0C79A0379A8DDE2995C3254B28FAA68B0" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerSimpleDesigner.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "cd776923d780b5b0148f01819d77c2f13e33464b", + "sha256": "E2DC7FDA89919C50432076C5677B957890A391A6E21D55E4E2EFC78BD4160078" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerSimpleDesignerBackend.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "445454c2bbfef433131fa4600a77177c86f5f7a9", + "sha256": "BBCE136A8AE3415E9462BEE229C1D39982BDBDC3DEACE9FFD4FF3A892ACC43AB" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerTestSession.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "8815b647a1c3ace6b2be4fba1ddaee1b2d918c06", + "sha256": "41C70686D945E4A6D6CB2978CA8E2A27989BC23F175E8FA32B9D655D0D2B53B1" + }, + "CDPIUI/Helper/CreateConfigHelper/ConfigMakerVariableActions.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "1fe879f1dbaa8401e508d3e96a4c4ac6cf5f1867", + "sha256": "1CE459772F714B66C747BB8AD5B980F4E4C7E1424ED0F9F8896F4B4BC6BB62FC" + }, + "CDPIUI/Helper/CreateConfigHelper/CreateConfigComponentTestTasks.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "401860900983036818fe66ce74ffd16125a2464b", + "sha256": "5D00CD282E9854E4BEFFDBBABF1752B98A806266E12AC5011A92ED8EB9B13739" + }, + "CDPIUI/Helper/CreateConfigHelper/CreateConfigGraphicDesignerBackend.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "5be1282a8def919222b815621ea1af8a96d818a5", + "sha256": "A1EC6666B5148E6CB9738A031203512218213DD3FBFB0D95E3A557F843F775A8" + }, + "CDPIUI/Helper/CreateConfigHelper/GraphicDesignerCommandCodec.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "a11fac5b3c28729b58caaf3f76b4ec2825ac5cc9", + "sha256": "3296EA9D6F82ADC979DA34B5A1BDDD1D2143AFCD72A3F3BDBA408C19E924C59C" + }, + "CDPIUI/Helper/CreateConfigHelper/GraphicDesignerHelper.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "7afc5c55d6e02f5815d8a92d05942a2faebda8db", + "sha256": "2D083D00355EB0958CCD79FD7B81AC865305F7FBA51956CDAC1BC2F30A87E622" + }, + "CDPIUI/Helper/CreateConfigHelper/IConfigMakerDocumentHost.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "741aaf92df4a6c6e4369dcaf29b29cbadaeeee91", + "sha256": "762E3569AB5D3B0BDB56458D719D7B41741D0404EDFFF1FAC4EF2B94880059C4" + }, + "CDPIUI/Helper/CreateConfigHelper/IConfigMakerDocumentStorage.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "b54922e47323e5803df36662f4cd427cc8cd8e73", + "sha256": "ABB73C49CDB15F49AF0C684D3799F1075FDEE2C2C7A7EB5D4D6A42C56F8822D3" + }, + "CDPIUI/Helper/CreateConfigHelper/IConfigMakerPanelLayoutView.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "98a4220cdf26b22ba533bd2c52f816dc4fe9f4d1", + "sha256": "A1609FE693625487ECACA953D85EB087D54E69848E18BB9032C5C548A16A9F98" + }, + "CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileActionsBackend.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "f9b6d2760ed785e9d52694973bb48ad7489cf4ed", + "sha256": "41E9B6E0214DF5AF3F4F0C259F2D033CF8FBC1E92D678C2FEF43F78122989DC5" + }, + "CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileActionsHost.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "fbea2ecfc770e24a38d12d0b6b5a7e7da07d9523", + "sha256": "342239D0F5602DCCCB860E0FE2D388CD8DD81BC397C500415F56ECB0E4CB3BD4" + }, + "CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileReplacementBackend.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "a91f2a29fb35d09d35ba6a8be6265aa06fd7ea99", + "sha256": "5782490B91FAC1E2DA4F273BDBFF377BE249FD216C7254ACE7AAE9BD52F50D9A" + }, + "CDPIUI/Helper/CreateConfigHelper/IConfigMakerPresetFileReplacementHost.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "05bea81782ed35c328a8290bce2a8af778023e58", + "sha256": "D609E7A6E130F5C9F87CD4B8ADE8ED3F97D1B7D7AD54E4FF7675BBA04471743D" + }, + "CDPIUI/Helper/CreateConfigHelper/IConfigMakerSimpleDesignerBackend.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "ba6494f0402fd8f41e86ebfca57cabb3ad9d3365", + "sha256": "FE689FF4D9817E05B59FA872373AEA6A86003439C13A6B071300352F13668E1F" + }, + "CDPIUI/Helper/CreateConfigHelper/IConfigMakerTestTasks.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "051120a22fee4e7ff9d6f9efabd517736a3a0445", + "sha256": "15105B922E291CC5F98EC7D2ADECC0CC8F6DC1D4E0F7727E1B4346D895206C3E" + }, + "CDPIUI/Helper/CreateConfigHelper/IConfigMakerVariableActionsHost.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "0c2759f710cf49ca3afd030d54be1abe3428d4ed", + "sha256": "78A37C4EBC761E12F2BC56B670249FF36D5577423337D789AF80448025CCBA5A" + }, + "CDPIUI/Helper/CreateConfigHelper/ICreateConfigGraphicDesignerBackend.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "e1703f105d24ec065e036ad7c5231f689f142767", + "sha256": "67B5D1C3A67B54500FE6AA958EE84FBD718911031A8A49207CA93F3D341E11CA" + }, + "CDPIUI/Helper/CreateConfigHelper/ICreateConfigTestTasks.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "4b138e59efca955fbd827be3e77c2236aecdf38b", + "sha256": "D13FE04B3E08606C00F84597A2609BE0C06260D22AE93578867C626244B149F9" + }, + "CDPIUI/Helper/UserExperience/DiagnosticHighlightingUpdater.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "9c7ec6dc50b6557519b7b2cf52ecb840cde77eb7", + "sha256": "88721943DD1D7520EAE6846A236AEC2CC60575ACEF74B2AE2DFBD040A9C6CA5F" + }, + "CDPIUI/Helper/UserExperience/DispatcherTaskBridge.cs": { + "source": "f706f16934695bcb122de63d0442c4ab20f42869", + "blob": "e84b1afd686429ad7c12c26ed58aba41f800c9a4", + "sha256": "4173D8AAB9EF6DCFFD8A1D249D9B7D18D6653A43F19A9615B2A7EF49CABB7CF7" + }, + "CDPIUI/Helper/UserExperience/NamedValueCollectionLoader.cs": { + "source": "f706f16934695bcb122de63d0442c4ab20f42869", + "blob": "3d7449498e3f9638de9daaa05b0b7c2b3387e907", + "sha256": "7DBE0571C5399327CCF955F580FABCAB5E76F64CE23684E9A01CADC99A6D1269" + }, + "CDPIUI/Helper/UserExperience/PostOrderTreePruner.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "592ff557a98c4bee548be7d8f879148b2386da9c", + "sha256": "34B54E725993173BD65C1D56A4C95D469DA7810744DEA403BFBBFEDA75ADE183" + }, + "CDPIUI/Helper/UserExperience/SelectedItemChoiceAction.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "85d613fcfb937588b3bca614dce19ec325a14443", + "sha256": "44872BE09BB97551B906B1D7B285A77F51FFA14ECAA03AB9404714D9121352F2" + }, + "CDPIUI/Helper/UserExperience/TextChangeRelay.cs": { + "source": "f706f16934695bcb122de63d0442c4ab20f42869", + "blob": "3c6e1c5e0fda8460eb2bcb4d5a89a4536f31e47e", + "sha256": "00322BF11EAC6E95F9323B70A3D3275E550A928703BD45CF46211F77BC875BB3" + }, + "CDPIUI/Helper/UserExperience/TwoPhaseTransitionSequence.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "640882ec6ee1018eb6c3e3bb11cee0358460ce75", + "sha256": "66FB24692285E24BFD758E6D7499C83CB784875818D51FE83BA27F922FA03D81" + }, + "CDPIUI/Helper/WindowHelper/AppWindowCoordinator.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "a73f83b87527f46e61d6391b77e9f4633e6abac2", + "sha256": "0081A83A0D4B38DDB44A6289456F2A4D562681C699A1FE47015AF769B23DA50F" + }, + "CDPIUI/Helper/WindowHelper/AppWindowOperations.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "1e68aaa4f92bfd8e8342e1b53d52eb743f211752", + "sha256": "7BC433AEA266034FE349201839F5603DD3E12483A772876A3B8A7FF13093BD75" + }, + "CDPIUI/Helper/WindowHelper/IAppWindowOperations.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "3b6e00b7ec40a92ebdcf72b6f288668628f5bdf4", + "sha256": "7FC3422432BD2DAEBA82EFF0DDA6B34DA3E4D89363638F7BE3093D2E9744BB28" + }, + "CDPIUI/ViewModels/BlockCheck2/BlockCheck2AssignmentActions.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "2e8d3a6be9318ae5a122bd123b3a41f4b57edef8", + "sha256": "C6D277BDA47066205E09B7B424BC22A2EB4BC97BBE91CB3E9395622A79EA6C47" + }, + "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ManualComponentTestTasks.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "063eb62cb6b0632b85b5e5e14b79f13d5e22e9f4", + "sha256": "27BE0E03225F6B1060B76F895C90B33D550BB0FF5D3F074867CDD8F45B4F7F3C" + }, + "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ManualTestSession.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "01e1be7ac908c119cdae6a94e3f4cf01fe406606", + "sha256": "AFA23639306305F04B7FB40976C0F4EE246EDC8089F06F932E5853365358A700" + }, + "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReportExport.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "5f9c153ca8538fd2f104ee34e28f7e56d149e647", + "sha256": "40CB2A3C5AE184B79016C42BA7528952D0AF92C8D79FB141781C8CB74081AB89" + }, + "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReportSummaryPresenter.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "dae76bc2a593d99526049954a9cf5d5b69883e03", + "sha256": "AEB2AFDC37EFE0718D4AD151AC3C25FE451E9BB3DB7330E36EA2C098155A0269" + }, + "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.Assignments.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "ce64c3533ef5bd95d5b999823cb989419875b064", + "sha256": "A39762190E07A986CDBB84727A81AECC63E192149D56C07ABE5DFD3EB6F9B2C4" + }, + "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.Export.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "dc2487dc0d5bdc0bdd2c6325a24a1b9737365aa8", + "sha256": "77ED78EBF44C81CC895FED3FA444C09C08A6DF1A12B76A8D7406248F12635E96" + }, + "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.ManualTesting.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "47174a32357e3a68c7751ea2fb08014a3d2e97c9", + "sha256": "7B4D95F64AD9D05E2DCF243DACD0A0328FEF18F93870B33584C71A4071059E9A" + }, + "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultPageViewModel.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "2b30f6b285bc9383e56d762857c52792c267c6e9", + "sha256": "E3C9BF2FCF574A30C31CCEE99F6C53FD16DA4902DBD7D16B911F436F0FABA3E0" + }, + "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ResultSelection.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "f17f6f8d2f49ac99e37ffc62cf044ba259d5931f", + "sha256": "888EFED70EEBE2EE41CDF2CCB44D53A3F115E9BEAEEBD087EC9C8FCD9921A407" + }, + "CDPIUI/ViewModels/BlockCheck2/BlockCheck2SelectedStrategyTest.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "b513617e626a4631bda33eece009a83dd6372a6b", + "sha256": "411D180C02B7963442232AAAE02BA206B4B04F4F8C729D096C877B1CA904E74F" + }, + "CDPIUI/ViewModels/BlockCheck2/IBlockCheck2AssignmentActionsHost.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "5a50cb51e3e0a83d9bacde43859968c38d192f0e", + "sha256": "A904EE5BFB22A4EE466BF869FAD236AD497F6A76DCE6090980BA4C88F6240927" + }, + "CDPIUI/ViewModels/BlockCheck2/IBlockCheck2ManualTestHost.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "89d0116289e37e90a182e494db5c70f49755be5c", + "sha256": "F291A0E2AC9754322010E8D0C61E714DD09210976690CA1520E8DAAC2A4FFA3C" + }, + "CDPIUI/ViewModels/BlockCheck2ManualAssignmentEditor.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "b7ad20fde6eb3c16f44de709b529a7c3b01513c0", + "sha256": "5DF6F603DD4BD760D96FE9F96F2FA7CFB425A69FF4142A787E650A8C76A83116" + }, + "CDPIUI/ViewModels/BlockCheck2ManualAssignmentRules.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "87ba799925220708f6f01932a16f89c9b2bb2d76", + "sha256": "C24737DBAF55DE4A7947A3B4B924C76D95BC3E98926BA84DCF1D29CDB3463E98" + }, + "CDPIUI/ViewModels/BlockCheck2ManualIssueItem.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "df29aa266cdba0ea5ff6a35dce7d193f91cbce47", + "sha256": "C14B4BC8F127B6F6B456D1192E36E014AAAC778D1CFDA4CAA1F78D9D42CF1817" + }, + "CDPIUI/ViewModels/BlockCheck2ManualPresetOperations.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "7cd51794048d10bc3474a7b43bd91931b7808bff", + "sha256": "B15336AB695CFF660FC36BA5040FB687B0710104ACD297AD723657F1E3D07DCB" + }, + "CDPIUI/ViewModels/BlockCheck2ManualPresetState.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "83cc336184e3d2f5753c03c9423e0d0999e2b9b8", + "sha256": "9C787277A5F592D6ED2E2ECFED82AF3677BB9B996A029C23BF32DEE7F8D365F8" + }, + "CDPIUI/ViewModels/BlockCheck2ManualResultViewModels.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "9d4690571a8471bd1d5478dd951aa2fa5e708991", + "sha256": "ABECBC5EE7CF02CEDF9FF670402DE221FDCB30E3DC8B5704937F3D675D6008C4" + }, + "CDPIUI/ViewModels/BlockCheck2ManualStrategyTestController.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "7ed7eca71b999e7642d2cf29ca2911fed96fe8b4", + "sha256": "2934AA14109E8C7B5868ACECCA5708A8BB797E1A001CD5B39A1207D71BAA8737" + }, + "CDPIUI/ViewModels/BlockCheck2ManualStrategyTestOperations.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "fd9d557792281511b18e28d6fff527198a19dedd", + "sha256": "420FB4163826B489978E0A933564D7552ADF8D0A4DB5F3A95596AF885A659532" + }, + "CDPIUI/ViewModels/BlockCheck2OptionsSettings.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "a7ca9b762641e09ada31f8eeb2606fa4a7f578ab", + "sha256": "B624C5B74086BD6466D6CB7118ACDD248DFE3F0BC3B0D4A88DAAAD80EFBED61D" + }, + "CDPIUI/ViewModels/BlockCheck2OptionsViewModel.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "74245f2f00be039ced4aeceb1a88aae2d1e99d7c", + "sha256": "AE78D253F8DEB6B3FA8A3517C5C419EDD9355F6191D84DB6A351A0347A717C68" + }, + "CDPIUI/ViewModels/BlockCheck2PresetDraft.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "903d5748cc1940cbd95ce4e958b724fde0c2c7c6", + "sha256": "763BD46A8BDB2378699404F9F838B57C537D9D4235E33E7AB382D0D9600278C3" + }, + "CDPIUI/ViewModels/BlockCheck2ProgressEstimator.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "40bca971e6a6080d58e5cbb3a9293fc42eda1b79", + "sha256": "4D885619A0B4EA82CF047811132353956001B8BE23F07AB871D150B2149D940C" + }, + "CDPIUI/ViewModels/BlockCheck2ProgressViewModel.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "ff4ecdbc3dca51821d61d79c9307d3ebc77b0a62", + "sha256": "921E5FC6F5A2D3EA41DA185EF9CF8D063C006436E08AB86E768193805C6C4B6E" + }, + "CDPIUI/ViewModels/BlockCheck2ReportOperations.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "f0df8e73107aa3c309c28cb970656d924f37977f", + "sha256": "4BAEDDCB9968F2746A73331955013B01C09B3B272F4362D5309E2F4C46B2B32E" + }, + "CDPIUI/ViewModels/BlockCheck2ResultViewModel.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "78cdb7c5c6f8b29702361df8aa2daee0d5956667", + "sha256": "EBF5BD6D60ABBEF0F34CB7AEAE0159602F9D99EA9310A9EDBCE80A363358A0CE" + }, + "CDPIUI/ViewModels/BlockCheck2RunController.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "9c995c600a9fabc6addbf4fd19139a13e0e5f14e", + "sha256": "829A3119FF142C0464EE7F2CAF0B8B4AA26F7C051B209D49DBF92C1CEBE7ADA6" + }, + "CDPIUI/ViewModels/BlockCheck2RunResultViewModel.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "83fcda62b81d6dc40e63f8e9f90914f69a9cf3ae", + "sha256": "A688AA2FEF721AB37DA1937FC7563DD694F6EF28A5C77988A85735399282D5A2" + }, + "CDPIUI/ViewModels/BlockCheck2SiteListBackend.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "f1a575f11c22f916c56949b3618c7e1ecbd019b1", + "sha256": "3D2CB6011F3F654C201CB91245F749EC19E061F8B4C52D27D4B09D5EE86FF9F9" + }, + "CDPIUI/ViewModels/BlockCheck2SiteListController.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "19d7037dfc08683fac8422f49987094982ff1dad", + "sha256": "2FA508B156DC00E92D07BAED45970309C712E56A64246BA268DDC404D42CA4D2" + }, + "CDPIUI/ViewModels/BlockCheck2ViewModel.Options.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "a216f8ec0f8938385b659bdcd8632c9deee6991e", + "sha256": "3C49DC23E5E7133010FBB8DF3BFC7D4D5CE31094ABB1F2AEFC6155D2B38BEEEA" + }, + "CDPIUI/ViewModels/BlockCheck2ViewModel.SiteLists.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "5fefcf3246c7a9acbe76ccc5345d73a605d0a7f8", + "sha256": "87805A038673CE6AF2D7946985018BFB532CEA800CCAB528D116C3A263AFDF62" + }, + "CDPIUI/ViewModels/BlockCheck2ViewModel.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "2584e5462e8aa7c9667acbb5f47d309852a01091", + "sha256": "A1D34773974DB30145B321EACB0FD1D3C458FCC70071BBC53B90B58AB3314D9B" + }, + "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.CommandHelp.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "8716f8d27bc29ee741f40f8f56b12ad18d53b9a5", + "sha256": "97E0525B01FA524E76BE5A24A9AD4D6C13E20988F0694665B02CED022BFE09F3" + }, + "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Diagnostics.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "1986c7ffe428203d6ef7dd543bf26729c4e60c1f", + "sha256": "852033202AC2CFF959BC92CA2510B018FB3860B556D9F922A7DFB24465576931" + }, + "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Document.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "62825d9ee56ebe097144d26a79c5abbac060f72d", + "sha256": "44951408501F31462E1BB4DE35B8BC62765E62CC7EF03BF1A69B888B39376648" + }, + "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.PresetFiles.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "c00d9c7f8ad14895c27438a99e85a2f9c2f2ccb2", + "sha256": "933A7203A6A6DCC8FD2E4C64B6F3D9F0CA61909CFF10BB4F85F71CB2EF8D7844" + }, + "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.PresetStructure.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "8c362fe3ebe60e5c51df913f022b86f23ede697a", + "sha256": "0946E038FE88055ADBBCC467BF5772166BD0B8FB2458A0AD758598522DBDF96C" + }, + "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.SimpleDesigner.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "ca63191d07b8000306c9d82fb3e97cb70167cd3d", + "sha256": "B9B7057225DFD9277D352F2E5069FB3FE516533ABD6BA0F043155CCC02F8A1C7" + }, + "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Testing.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "b91e2f21c3d3e35143f8dd86b5c8d2a13db40143", + "sha256": "52D675DB25E8B9CE64CCAD25C71C9D534C57911F1600958FC746A91335C1CF21" + }, + "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.Variables.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "e78297703595c6caf795200d0d64cf7e87ae04c1", + "sha256": "87B4126FAAD488FA7D671135AAEEC51992045843AD7010948E22CD97134EBE63" + }, + "CDPIUI/ViewModels/ConfigMaker/ConfigMakerViewModel.cs": { + "source": "f706f16934695bcb122de63d0442c4ab20f42869", + "blob": "0108eec56d94ab050b979195ab0989f0926054de", + "sha256": "73E537621F77FA9FA5BA90E004CC9D38CF309BC630D22530402644CF3168EBA1" + }, + "CDPIUI/ViewModels/ConfigMakerPresetDocumentConverter.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "f2d585d3e8fdfcc8161493773af09a2f56fb23e2", + "sha256": "532059CFA1F6298ECD319651FAB55E42989E24E557B5CE8F9886BC4C067DAAB9" + }, + "CDPIUI/ViewModels/CreateConfig/ConfigComponentOption.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "b1e6998430e9d489e08555c80e5b3a8cb9931ec7", + "sha256": "FD6734229E0FC0A918449F9DB5993E733DADC279DDA556AB7CB608FD75D2BD0A" + }, + "CDPIUI/ViewModels/CreateConfig/CreateConfigComponentSelection.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "0b8af6faf663ad14a30b7492a3dea48209991de7", + "sha256": "9CB4C6E284A11A99069544A789CF3261ACD962A9116F548CF40F5A81C0EB0F1D" + }, + "CDPIUI/ViewModels/CreateConfig/CreateConfigConditionDraft.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "b16f3948647fa1a4c4626164e1bef54161959980", + "sha256": "829743F3D7F9EA95BE3EC3EFC3F2B7CFA826624DA5BDE702E164D35F993B4DB5" + }, + "CDPIUI/ViewModels/CreateConfig/CreateConfigGraphicDesigner.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "7decf8ff730fb271c3f211de54ac885665360ae0", + "sha256": "09998F4691C5B3134FCA2D5F1FD919C3EB8309A24231019C044CDF41C8E28944" + }, + "CDPIUI/ViewModels/CreateConfig/CreateConfigTestSession.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "5d2697cc686e0933164942a3073c52ca2254ec44", + "sha256": "7497CA3B9793ABD2626FD25088EEC980D6D587534BF2CDF47D5E842670371EF2" + }, + "CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.GraphicDesigner.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "149ac35f28ddd8599f65f1514c5c4e8d28d37bdb", + "sha256": "AA93CA87B32ED34894499E361015282B71183893BF2BD5618484A7098049F468" + }, + "CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Navigation.cs": { + "source": "f706f16934695bcb122de63d0442c4ab20f42869", + "blob": "ab6e7004fef852acb7d34755705b69c2ac688b3e", + "sha256": "6E8E6D9EAD8A5D3D8A65BBCCFA7FF30C88B258E88B9F3BCE2C3818529A9BE229" + }, + "CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Testing.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "ded71700451eb8ab7c67a6bdc07d10d36be0aaca", + "sha256": "C809F8CB42D12E420789358FE23AA8F2A826E9F7000E457E3688DDA60D4B53C7" + }, + "CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.Variables.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "6bf0dc53c8f57b78799ae1a7648086842b300321", + "sha256": "962B0B2EA52D04AE37CC9DD7C90FC38056D79E2300BD817191F5A11AF3096284" + }, + "CDPIUI/ViewModels/CreateConfig/CreateNewConfigViewModel.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "59fc766bbd17bd71c3add95bc287457ddf63c699", + "sha256": "9D68A2E2F0A7F60F43175F431530C3F588008A34244128A18AE5BACB340B0AB4" + }, + "CDPIUI/ViewModels/IBlockCheck2ManualPresetHost.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "19cd8c6a76df5d47e27d160aa4dc6803d46a03db", + "sha256": "E5D9EA6EE61AD9598BEBFD864B674E7AE95D83CAD95609C2FCA07020F88F8C76" + }, + "CDPIUI/ViewModels/IBlockCheck2ManualPresetOperations.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "5cc2ee1811c681ef9a38a42e597badbb67020ae3", + "sha256": "694926BB23409E90D02F5CCF311A4A445D61BB651C450DA67C56E6B306C989EA" + }, + "CDPIUI/ViewModels/IBlockCheck2ManualStrategyTestOperations.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "63fd366c328539f723f547f8aecf2df45b791132", + "sha256": "1809F18F7EA9A8623769E89324D8D3ADF70117C557D4517FA35E641501E1A403" + }, + "CDPIUI/ViewModels/IBlockCheck2OptionsSettings.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "3893682963d1a684974c1d3de13917bec7a85e95", + "sha256": "3E5CFFE461E2FD187DC4214BA305E9C4C42214BA28B354681710BE0C0581FDC2" + }, + "CDPIUI/ViewModels/IBlockCheck2ProgressEstimator.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "942f1716f92e9a2b769324160ece81a91b9c75be", + "sha256": "DCE4A34A4B5344655B53E79F5322A59192168F14FCB7B9579FA911956DC25CDC" + }, + "CDPIUI/ViewModels/IBlockCheck2ReportOperations.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "5a9e831b063c6e2d6bd761d7739e2c7234458aad", + "sha256": "D37CA5367701F1A1BB63335DC06FE521156D4B9BB9CF3756CB4DE9E854AF2619" + }, + "CDPIUI/ViewModels/IBlockCheck2RunHost.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "c481e91ddefe4656e77585f053ac0a8741a8017f", + "sha256": "6FA0D3BD65E385784FC3F9B5E96F500396B4F4F0DF69D6E78F649A85F47D9C6C" + }, + "CDPIUI/ViewModels/IBlockCheck2SiteListBackend.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "1ee004e8c0da900a1111677b256a9dcd9d9443f1", + "sha256": "5122A3C7C87DA1B8D0E9FD761DA4130F9B6F43619069522416E46AACAFE72C70" + }, + "CDPIUI/ViewModels/ObservableObject.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "4ce8e24382ab03f68ffed931d26ae7538ea72787", + "sha256": "7F118CC37A77FC6DF1C0844EE08E0D7ABAED008C2D54D2063E85A11BAC6385D4" + }, + "CDPIUI/Views/CreateConfigHelper/ConditionVariableModel.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "9c9b940a305d329263aeeb41170813b759e3f648", + "sha256": "4D1C225A18E6EF41AC94ED4639681FFCD2C0599BB2339995F815914AA8D9B47D" + }, + "CDPIUI/Views/CreateConfigHelper/GraphicDesignerExclusiveSettingItemModel.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "41e0d255d5fdf6d5c0b5189258157a3abf66798b", + "sha256": "83A10F94DCB5DE8C7EFCB8615D0A68CCF39A2E47C4B007D2D9904696F49FFFAA" + }, + "CDPIUI/Views/CreateConfigHelper/GraphicDesignerSettingItemModel.cs": { + "source": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "blob": "44be23f74c991232ebbb56a62746b283873b5c4c", + "sha256": "53F2854E28490EC1AFF53BE06098EB4CAF9E7B21192EF5F834C27F1818C74C77" + } + }, + "scope": "Current-default G2 composition only; historical G1 API drift and issue13 remain unaccepted. No native149 or publication claim." +} \ No newline at end of file diff --git a/docs/superpowers/reports/2026-11-11-class-integration-source.md b/docs/superpowers/reports/2026-11-11-class-integration-source.md new file mode 100644 index 00000000..c63dc4e5 --- /dev/null +++ b/docs/superpowers/reports/2026-11-11-class-integration-source.md @@ -0,0 +1,74 @@ +# Class integration source checkpoint + +Owner: [issue14](https://github.com/lumenpearson/cdpiui/issues/14), Root, +`dev/audit-class-integration`, existing isolated checkout +`C:/Users/lumen/.codex/worktrees/audit-class-decomposition/cdpiui`. +Actual Project87 intake: In progress/P2/Architecture/Medium/G2/lumenpearson, type:refactor and +area:architecture. No broad integration acceptance or main merge is recorded. + +## Source provenance + +The current default is `6c00c789ee2b37238af30f14cfdaf0f55a278274`, verified through GitHub and +local origin/main. The scoped transplant consumes reviewed Root product +`ed390cd416b58ea404f04286f7eace5a66e4320a`, frozen Root documentation/branch +`eebc7e8621b85fa08ee015ea3b7eab1e72c78c5f`, and the complete corrected peer product +`f706f16934695bcb122de63d0442c4ab20f42869` (peer final docs249bba). Both frozen branches and +their prior accepted/rejected artifacts remain intact. + +Root184 and peer10 scoped paths are composed over current default. Only App.xaml.cs, the test +project and two README files changed on both sides. A clean App three-way merge keeps default +emergency/readiness behavior and Root owner construction. Default README text is retained. Current +test XML retains all14 declared default items and its deliberate DirectoryAclGuard link removal; +115 deduplicated additive items include the accepted Unidecode.NET reference at unchanged central +2.1.0. No default property/package version or unowned security/localization/workflow file is replaced. + +The full pre-checkpoint provenance covers1572 expected repository paths, including current plan/spec +and the imported historical decomposition documents. Two new evidence documents are added with +this checkpoint. The companion JSON lists every changed product input with its source and hash; +raw complete provenance, XML and all-input hashes remain in +`.superpowers/sdd/2026-11-11-class-integration/`. The only extra compile input is the exact generated +empty Secret stub; no unexpected C#/XAML/project file was found. + +## Fresh checks + +- Current-main baseline:745 tests passed,0 failed/skipped,9s; GUI0 warnings/errors,71.19s. +- Composed focused state-owner/recovery suite:169 passed,0 failed/skipped,32ms. +- Composed full suite:2163 passed,0 failed/skipped,10s. +- Composed Release/x64 GUI:0 warnings/errors,63.10s. +- Normal GUI SHA256: `D1B46BAF7C68B7436201EB28C477F1D70C748AD2132E64C108DC1D7F1BD00C52`. +- Current-main source API: GUI451 original exported types,520→612 C# inputs,0 loss; + Core88 types,102→103 inputs,0 loss. +- Current-main compiled API: GUI452 types,0 removed/changed shapes,+7 previously accepted Root + additions; Core88 types,0 removed/changed shapes,0 additions. Inventories are not full native ABI proof. +- Roslyn token/body checks preserve default readiness field/getter/two complete methods/theme + statement, all seven Root owner fields and all other constructor statements/order. A controlled + loss of startup readiness was rejected by this guard; no product file was mutated for that probe. +- Complete source/XML and extra-build-input checks passed after execution. + +An initial focused compile used stale assets with `--no-restore` after adding the already-declared +Root package item and reported missing Unidecode. The source/project already contained the correct +reference. A normal restore resolved it without a product or dependency-declaration fix. The first +failed log and restored focused/full/GUI logs are retained separately. Source preparation also +stopped safely on an overbroad upstream-deletion guard and a shell parser error before product writes; +both tooling errors were corrected and their actual resolutions are in the new ledger. + +## Historical API and G1 boundary + +The separate Root/G1 surface differs from current main at one GUI optional-default constructor and +three MSI/pipe signatures carrying expectedSha256. Independent Root→main and Root→composed source +analyses produce exactly the same differences: this transplant adds none. Zero loss is claimed +against current default and the owned decomposition contracts, not the full older security snapshot. + +[Issue13](https://github.com/lumenpearson/cdpiui/issues/13)/draftPR10 still own G1 and rewritten +ancestry reconciliation. The historical audit-defects implementation chat is archived; no active G1 +execution owner was confirmed. Its EE checkout/ref is preserved. This stage does not resume that +chat, change MSI/security/pipe code, waive G1 acceptance, or merge PR10. The G2 PR must remain draft +with the dependency visible; issues13/14/15 stay open while their criteria remain incomplete. + +## Remaining qualification + +A new named committed source pin, immutable union149 native fixture, independent source/prelaunch +and final reviews, and exact-head PR CI are the next gates. Proposed149 preserves Root137 prefix +and the peer141 label projection; prior137/141 are separate historical corpora. No union native build +or execution is claimed here. All Root UI calls are paused until a new explicit grant. Full startup, +visual/installed-product and broader acceptance remain separate from the bounded fixture. diff --git a/docs/superpowers/reports/2026-11-11-diagnostic-highlighting-verification.md b/docs/superpowers/reports/2026-11-11-diagnostic-highlighting-verification.md new file mode 100644 index 00000000..421e2cf2 --- /dev/null +++ b/docs/superpowers/reports/2026-11-11-diagnostic-highlighting-verification.md @@ -0,0 +1,170 @@ +# Diagnostic highlighting update verification + +Issue: [#215](https://github.com/lumenpearson/cdpiui/issues/215). +Execution owner: Root, `dev/audit-class-decomposition`, +`C:/Users/lumen/.codex/worktrees/audit-class-decomposition/cdpiui`. +Product checkpoint: `ed390cd416b58ea404f04286f7eace5a66e4320a`. +This is a local implementation stage. Integration remains in #14 and broader native acceptance in #15. +The local stage is accepted: final independent review passed, issue215 is closed as completed with +all six criteria checked, and actual Project Status Done was verified after reload under queue85. + +## Behavior and scope + +`ConfigMakerUserControl.Editor.cs` delegates its one highlighting signature and reset operation to +the internal System-only `DiagnosticHighlightingUpdater`. The editor file changes from 157 to 149 +lines; the five control partials change from 828 to 820. The helper contains 29 lines. +The control retains its background/light calculation and literal highlighter/Design setter order. + +The extraction preserves two current diagnostic reads, the complete error pass before the warning +pass, separate predicate/token Source reads, raw token order/duplicates/case/null values, literal +comma/pipe signature collisions and Ordinal comparison. Collection completes before the current +key is compared. The requested key is committed before apply. A failed apply keeps that key. +Reentrant callbacks and collection-time reset/reentry retain their original state effects. +No view model, XAML, preference implementation, parser or persisted format is changed. + +## Managed checks and contracts + +Windows, .NET SDK 8.0.427 at `C:/Users/lumen/.dotnet/dotnet.exe`: + +- Missing-helper RED: CS2001 before the helper was created. +- Focused tests: 32 passed. A controlled commit-after-callback mutation caused 4 failures; the + original bytes were restored in `finally`, then all 32 passed again in 23 ms. +- Restored helper SHA256: `88721943DD1D7520EAE6846A236AEC2CC60575ACEF74B2AE2DFBD040A9C6CA5F`. +- `dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release --no-restore`: 2108 passed, + 0 failed/skipped, 10 seconds. +- `dotnet build CDPIUI/CDPIUI.csproj -c Release -p:Platform=x64 --no-restore`: 0 warnings/errors, + 42.76 seconds. +- GUI source inventory: 451 original exported types across 517 baseline to 606 current C# files, + 0 removed/changed original signatures. All 606 current source inputs match the committed pin. +- GUI compiled inventory: 452 original exported types, 0 removed/changed shapes, 7 previously + recorded additions. Source and metadata inventories do not establish full native ABI compatibility. +- Core source is unchanged from accepted `00f39b1a9be70cb97cebd7290b5f24dac6a5ab47`. + +Normal GUI DLL SHA256: `100E51E7FBD990AAB9D41755769796CC6C4EA7B75F79BCFF8C7894C5F96FA3EC`. +Raw evidence remains under `.superpowers/sdd/2026-11-08-class-decomposition/`, including +`task89-*`, `api-compatibility/*highlighting*` and `compiled-contract/highlighting-GUI-*`. + +## Committed source composition + +The Core-inclusive builder creates fresh copies from exact committed blobs, preserves the security +test items and verifies all repository inputs plus the additive test-project XML before and after +execution. It does not modify another session's worktree or Git references. + +Security composition with `ee4771675956fe213634675f37579362efb7e0eb`: +`F:/cdpiui-verify/joint-highlighting-ed390cd-security-a`. +2320 tests passed, 0 failed/skipped; GUI 0 warnings/errors, 59.09 seconds. +The proof covers 1546 expected paths, 1545 Git blobs, 184 Root overlays, 112 additive project items +and all 14 security items. Only the test project overlaps. The generated empty secret stub is the +only extra source input. Post-build source proof passed. + +The corrected peer composition with `f706f16934695bcb122de63d0442c4ab20f42869` passed: +`F:/cdpiui-verify/joint-highlighting-ed390cd-peer-f706f16-a`, 2398 tests, 0 failed/skipped; +GUI 0 warnings/errors, 58.74 seconds. All 1552 expected paths and 1551 Git blobs are covered, +with 184 Root overlays, 10 peer delta paths, 115 deduplicated additive items and all 14 security +items retained. The post-build source proof passed. That peer pin includes the complete dispatcher +bridge correction; rejected `9e63b55` is not accepted. The fresh independent reviewer reconstructed +both complete trees and XML from committed blobs and hashed the disk contents, without joint +findings. These results do not establish a combined native runtime pass. + +## Native fixture status and limits + +The first independent preparation review found an Important error in three new fixture assertions: +the pinned library exposes `SyntaxHighlightLanguage.Highlights` as `SyntaxHighlights[]`, so the +assertions must use `Length`. The original case/manifest/diff are retained in +`highlighting-prebuild-count-review-original`. Only the three `Count`→`Length` assertions were +corrected in scratch and the unbuilt fixture; full source-boundary checks passed again. This was +found by reading library metadata before any fixture build. Independent correction readback confirmed +exactly those three changes and returned READY for BUILD, with 0 Critical/Important findings. + +The first compilation then failed with CS0246 because the new fixture partial lacked the +`CDPIUI.ViewModels.ConfigMaker` import for `IConfigMakerView`; the XAML target reported the same +compiler failure. The original case/manifest/diff and `highlighting-host-build.log` are retained. +Only that import was added in scratch and the fixture; all source-boundary checks passed again. +The second compilation passed with 0 warnings/errors in 48.44 seconds, retained separately in +`highlighting-host-build2.log`. These fixture-only corrections do not alter the product checkpoint. + +The fixture archive is `F:/cdpiui-verify/cdpiui-highlighting-ed390cd-20261111`. +The source checker compared all 1531 repository inputs and 1246 GUI/Shared/Core/AddOns inputs. +It found exactly 21 boundary files and 28 bootstrap files, with all 26 previous case partials byte +identical to accepted Root menu133. These are preparation results, not an executed native test. +The binary directory has 522 files. Five actual binaries and 18 source inputs are pinned (23 total). +The fixture DLL SHA256 is `4B8F56E35BD74C441E53D3D3534699C2FD8856AE74CAF1DF4BBAC10009E36D83`. +The runner SHA256 is `FE83083A54CE84B55BD9922C0DD34A9FA514EEFF7B9F8E747FB01000CC430A22`; +the readback verifier SHA256 is `FBC16112E73BAC5E0D6C881AF5D84863E4739A1B21DF4B273BB8D23642A5F08F`. +These pins belong to the first compiled attempt, which must remain unlaunched. Independent product +review found one Important fixture attribution error: cumulative preference reads/writes cannot +prove that this unloaded control initialized the font singleton. Generated x:Bind waits for Loading. +The first attempt remains intact at its original path, with its sources, binaries, pins and logs. + +A fresh `-r2` archive uses incremental per-key Search reads around actual control construction, +plus a separate explicit `ConsoleFontHelper.Instance` check of the three fixed typed font values +and two bounded FontSize setter writes in memory. It will not attribute font access to delayed +control bindings. Both preference cuts remain. Its first archive-preparation command stopped on +the clean-worktree guard before it created the archive: current documentation was untracked. +Documentation checkpoint `5805c8334c76d95d9bd301ed423b7cb7844b02ae` resolved that guard without +weakening it; product inputs remain the literal `ed390cd`. Independent r2 source review returned +READY for BUILD after reconstructing all 1531 inputs, 21 cuts, 28 bootstraps and 26 old case files. +The r2 build passed with 0 warnings/errors in 69.10 seconds. A separate independent post-build +review verified all 23 pins, actual embedded asInvoker/uiAccess=false manifest, fresh 522 binary +filenames, non-admin execution, local NTFS/no reparse points, exact source and uncut Editor/updater, +and the runtime gates. It returned READY with 0 Critical/Important findings. + +The r2 fixture is `F:/cdpiui-verify/cdpiui-highlighting-ed390cd-20261111-r2`. +DLL SHA256: `A03599B0A1F5C3F05F0930BAB381DB1E0A9C84CC435BDE04F0387EA6C2ADB70F`. +Runner2 SHA256: `83B1319277F3C6448A0500C7A86D7CB482F415E5EA8F11DCC9CC9259A676DED9`. +Verifier2 SHA256: `912D39C1279C84C7CF3751DF8699FBC281CB7C1D19B09C19698631AD2FC3655C`. + +The canonical request was atomically updated to r2 READY, then an explicit guarded free82→Root83 +grant was read back, with every other UI participant paused. One hidden owned process ran from +2026-11-11T07:00:36.6419523Z to 07:00:42.8313907+00:00, PID79052, exit0. All 137 unique groups +passed with the accepted133 prefix in exact order, one COMPLETE, no FAIL, and empty stdout/stderr. +Postchecks verified all 23 actual pins, five binary hashes before/after execution, full source, +three retained literal inputs of 16/16/15 bytes, two real serializer outputs of 354/260 bytes with +their exact golden hashes and model fields, 522→528 filenames with only the six approved additions, +all prior names retained, forbidden outputs absent, unchanged normal GUI and termination of the +owned process. The idle receipt/requestfalse/all-UI-paused state preceded guarded release83→84, +owner null. No CUA, desktop input or foreign window action occurred. All V1 pins remain unchanged. + +Runtime evidence: `highlighting-host2-execution.log`, `highlighting-host2-run.log`, +`highlighting-host2-run-manifest.txt`, `highlighting-host2-{inputs,outputs}-retained.json`, +`highlighting-host2-postchecks.json`, `highlighting-host2-approved-pins.json`, +`highlighting-host2-explicit-grant-v83.json` and `highlighting-host2-owner-released-v84.json`. + +The old 19 boundary files remain. Two explicit fixture-only additions replace only preference +endpoints in `SearchUserControl.xaml.cs` and `ConsoleFontHelper.cs` with typed in-memory values. +They reject unknown keys/types; neither patched file retains a SettingsManager call. The actual +constructors, setters, XAML, editor and new updater remain. No product preference code is changed. +The Search constructor reads preferences immediately. The generated control binding defers font +access to Loading, so this unloaded control does not prove that it initializes the font singleton. +The fixture exercises that singleton and its setters explicitly as a separate isolated boundary. + +Four new executed groups extend Root menu133 to Root137: constructor/unchanged identity plus the +separate explicit font boundary, current +diagnostic Source/severity, actual background reset, and independent caches in two owned controls. +Root137 differs from the peer named-value137 and the peer dispatcher141. Counts do not establish +combined runtime acceptance. All owned controls stay unloaded/unattached; owned timers are stopped. +This does not establish full event detachment or garbage collection: the existing +`AnimatedSelectorBar` subscribes to a static item event in its constructor and unsubscribes on +Unloaded. This fixture deliberately does not raise Unloaded, so that subscription retains its +objects until the owned bounded process exits. No global handler is changed by the test. +No desktop input, activation, navigation, focus, backend or preference IO is permitted. Managed tests +cover fault/reentry ordering; this bounded native fixture does not prove full visual/startup or +installed-product behavior. Source/prelaunch reviews and runtime postchecks passed. + +## Final local acceptance + +Fresh read-only reviewer `/root/highlighting_integration_review` accepted product +`ed390cd416b58ea404f04286f7eace5a66e4320a` and final technical documentation +`cee65ac3c82d53d2a7b322e0299b1fb50271f2cb`: 0 unresolved Critical, Important or Minor findings. +Product, both joint trees/XML, actual r2 runtime/IO/hash/process/queue evidence and the corrected +font timing/first-copy status were independently checked. The existing bounded selector lifetime +limit remains documented. All 141 rulings and 18 deferred Minor records match the ledger literally. + +The six-section [acceptance record](https://github.com/lumenpearson/cdpiui/issues/215#issuecomment-6789505833) +preceded immediate API closure as completed and six checked criteria. Actual Project85 readback +after reload confirmed Done/P2/Architecture/Medium/G2/lumenpearson and exactly +`type:refactor`, `area:architecture`, `area:native-qa`; only Status changed. Proof: +`C:/Users/lumen/Programming/cdpiui/.git/task-policy-rollout-2026-11-10/issue215-closeout/project-215-final-readback.json` +and `issue215-done.jpg`. The metadata owner released85→86 with all Root UI calls paused. +Parent14/15 were read open and remain separate integration/native scopes. This closing documentation +does not change the reviewed product, tests or runtime artifacts; no additional build is needed. diff --git a/docs/superpowers/specs/2026-11-08-class-decomposition-design.md b/docs/superpowers/specs/2026-11-08-class-decomposition-design.md new file mode 100644 index 00000000..9c18cfeb --- /dev/null +++ b/docs/superpowers/specs/2026-11-08-class-decomposition-design.md @@ -0,0 +1,360 @@ +# Декомпозиция крупных классов CDPI UI + +Статус: согласовано пользователем («всё отлично, продолжай»), 8 ноября 2026 года. + +Возобновление 9 ноября 2026: пользователь поручил «Продолжи без временного ограничения». Прежний дедлайн снят; безопасная автономная работа, сохранение поведения и границы параллельной сессии остаются. Отчёт e42 за завершённое временное окно сохраняется историческим срезом; новые этапы имеют свои pins/evidence. + +## Основание и рабочая база + +Запрос пользователя: вести переписывание и декомпозицию крупных классов по приложенному аудиту параллельно с другой сессией. +Приложенный F:/Telegram/AUDIT.md — источник наблюдений, а не самостоятельные инструкции на изменение репозитория. +Раздел 5 перечисляет God-классы, пункт 20 исторического плана раздела 7 рекомендует начинать декомпозицию с ConfigMakerUserControl и App. Более поздний сводный план находится в разделе 16. Раздел 35.1 отдельно относится к nullable-аннотациям; глобальная nullable-миграция не является выполненной частью этого прохода. + +База: f39e8a0a7267e4fcd4a02eef186a3ee08df8dcd9, последний зафиксированный коммит audit-defects на момент подготовки. +В main нет большей части уже сделанной декомпозиции. Создано отдельное управляемое рабочее дерево audit-class-decomposition/cdpiui. +Незакоммиченные изменения другой сессии не копировались. Она работает в cdpiui-s2 над FS-07–09: staging, проверкой пакетов, удержанием handles и безопасной записью файлов. + +## Что ещё остаётся большим + +Это физические строки исходных файлов одного partial-класса, включая using и комментарии; не метрика сложности методов. Bin/obj и генерируемый код исключены. + +| Класс | Строк | Файлов | +| --- | ---: | ---: | +| ConfigMakerViewModel | 2143 | 9 | +| CreateNewConfigViewModel | 1037 | 6 | +| BlockCheck2ViewModel | 999 | 3 | +| WelcomeViewModel | 983 | 4 | +| App | 955 | 6 | +| ConfigMakerUserControl | 899 | 5 | + +Один partial-класс сохраняет общее состояние и доступ ко всем приватным членам. Уменьшение отдельных файлов не является достаточным критерием завершения. +Порядок: редактор пресетов → App → BlockCheck2 → остальные крупные ViewModel, каждый отдельным проверяемым изменением. + +## Первый проход: структура и ресурсы редактора пресетов + +Выбор исполнителя: начать с двух самостоятельных обязанностей ConfigMaker, которые можно проверить без запуска GUI и без вмешательства в текущие security fixes. +Сохранить C#, .NET 8, WinUI, форматы пресетов и локализацию. Новые библиотеки и миграция DI/MVVM не требуются. + +### Построение деревьев структуры + +Вынести преобразование файлов и аргументов в узлы дерева из ConfigMakerViewModel.PresetStructure.cs в отдельный ConfigMakerPresetTreeBuilder. +Builder получает файлы, группы, parsed options и функции локализации, описания опции, разрешения пути и проверки существования файла. +Он не обращается к ViewModel, DispatcherQueue, DatabaseHelper, Localizer.Get() или процессам. +Контракт с WinUI (решение исполнителя после builder check): builder возвращает новые чистые production-descriptors файловых и групповых узлов, без Brush, FontFamily, Visibility и ConsoleFontHelper. Тонкий ConfigMakerPresetTreeAdapter преобразует descriptors в существующие ConfigMakerTreeNode/ConfigMakerPresetFileTreeItem/ConfigMakerPresetTreeItemViewModel; его не подключать в обычный xUnit. Внешние XAML bindings и типы содержимого дерева остаются прежними. +В ViewModel оставить выбор явной/вычисляемой структуры, вызов builder/adapter, публикацию PresetFileNodes/PresetGroupNodes и уведомления о доступности. +Сохранить сортировку, порядок категорий, объединение файлов без дублей, приоритет явных названий, fallback-группы и позиции SourceIndex/SourceLength/SourceLine/SourceColumn. +Весь класс ViewModel должен реально уменьшиться; добавление новых partial-файлов не считается выполнением. + +### Работа с файловыми ссылками и ресурсами + +Разделить ConfigMakerPresetResources (507 строк) на небольшие объекты с явными зависимостями: + +- ConfigMakerPresetResourceRegistry: поиск/добавление attached resources, уникальные aliases, повторное использование одного файла, признак built-in. Разрешение пути и проверка принадлежности компоненту приходят функциями. +- ConfigMakerPresetReferenceEditor: замена и прикрепление ссылок в команде и во всех значениях переменных. Использует существующий ConfigFileReferences и registry; не управляет UI и не читает глобальную базу. +- Существующий ConfigMakerPresetResources: совместимый фасад для разрешения путей, snapshots, формирования auto-correct result и делегирования двум объектам. Его методы для остального GUI сохраняются. + +Не менять storage copier, правила файловой безопасности, ZIP, updater, staging, ACL или запуск процессов. +Сохранить preset://, правила alias collision, кириллические имена, --blob с offset, маркеры Lua и прямые файловые значения переменных. +Не оставлять новый ресурс, если переписывание не изменило ни команду, ни переменные. Повторное прикрепление должно быть идемпотентным. + +### Проверки + +Сначала зафиксировать существующее поведение характеристическими тестами, затем извлекать объекты и запускать те же сценарии. +Тесты не запускают tray, установщик, компоненты или системные настройки. +Чистые GUI-модели и извлечённые классы подключить как linked source по существующему примеру launcher/DirectoryAclGuard; не ссылаться на весь WinUI-проект из xUnit. +Если linked-source набор становится большим, допустим отдельный тестовый проект чистой presentation-логики. Не копировать реализации и не подменять production-модели тестовыми заглушками. + +Обязательные сценарии: + +1. Дерево файлов: категории, сортировка, отсутствующий и attached-файл, пустой набор. +2. Группы: common filters/options, несколько profiles, явное имя перед parsed-именем, fallback при пустой команде, source spans. +3. Ресурсы: повторный файл, коллизия alias без учёта регистра, кириллица, built-in и внешний файл. +4. Переменные: Value, Values, OnValue и OffValue; прямой путь и путь внутри команды. +5. Повторное прикрепление, отсутствующий файл и отсутствие замен: нет лишних ресурсов или изменений команды. +6. Blob/Lua: имя blob, offset и маркер файла сохраняются при замене. + +В конце: релевантные тесты, полный существующий xUnit suite, сборка GUI x64 и git diff --check. +Если окружение не позволяет выполнить проверку, указать конкретную причину; не объявлять её пройденной. + +## Границы параллельной работы + +Изменять только ConfigMaker GUI helpers/ViewModels, их чистые тесты, минимальное подключение тестовых исходников и документацию изменения. +Не редактировать cdpiui-s2, его ветку и журнал docs/AUDIT-STATUS.ru.md. Не переносить незавершённые security changes. +Публикация, push, merge и сообщения другой сессии не входят в этот проход. +Результат — отдельный diff поверх указанной базы; перед последующим объединением проверить пересечения с актуальной audit-defects. + +## Критерии завершения первого прохода + +- Отдельные builder, registry и reference editor с ограниченными зависимостями. +- В ConfigMakerViewModel меньше логики построения деревьев, а не больше partial-частей. +- ConfigMakerPresetResources стал фасадом, извлечённые обязанности тестируются без WinUI runtime. +- Поведение редактора и сохранённые форматы совместимы; тесты и доступные сборки подтверждают это. +- Отчёт содержит команды, результаты и следующие классы; закрытие всего аудита не заявляется. + +## Проверка проекта и исходной базы + +Builder check выявил зависимость существующих tree item models от WinUI. Выбраны чистые production-descriptors и UI adapter; это решение исполнителя, не новое требование пользователя. +Исходный xUnit suite на f39e8a0: 768 passed, 0 failed, 0 skipped; использован C:/Users/lumen/.dotnet/dotnet.exe (SDK 8.0.427), Release. +Первый проход реализован; актуальные результаты и ограничения — в docs/DECOMPOSITION-STATUS.ru.md. Исходная GUI x64 сборка прошла без ошибок и предупреждений. + +## Следующий согласованный этап: App activation + +После ConfigMaker выделить AppActivationDispatcher и чистый AppActivationRequest. Dispatcher управляет только порядком вызовов; существующие обработчики migration/files/protocol/direct, WinRT adapter и завершение/открытие окон остаются в GUI. +Сохранить разные последовательности первого и перенаправленного запуска, fallback, short-circuit, повторное чтение initial activation после await, обработку ошибок и частично успешный результат. +Не исправлять одновременно унаследованные особенности: initial direct-команда может заменить ранее полученный результат protocol; redirected migration всё ещё вызывает splitter до проверки результата. +Program, URI allowlists, pipe, file imports, migration window locking и settings recovery не менять. +Проверки: порядок, пропуск fallback после успеха, оба источника migration, исключения после частичного успеха, асинхронное ожидание, регистр префиксов и неизменная передача payload обработчику. + +## Следующий согласованный этап: BlockCheck2 options + +Выделить BlockCheck2OptionsViewModel: существующее состояние выбора целей, протоколов/IP, preset и advanced options, загрузка/валидация сохранённых значений, создание session request. +Доступ к settings передать через типизированный IBlockCheck2OptionsSettings; production adapter вызывает прежний BlockCheck2SettingsStore с прежними int/bool/double generic types. Изменений файла настроек и ключей нет. +Текущий BlockCheck2ViewModel сохраняет API, проксирует свойства и пересылает PropertyChanged от своего имени, в прежнем порядке относительно записи настроек. IsRunning и число выбранных списков читаются через функции, а не сохранённый снимок. +Сканирование, cancellation, progress, report/history, site-list I/O и запуск компонентов не переносить. +Тесты: defaults/corrupt persisted values, timeout coupling, finite/nonfinite значения, attempts, preset recommendations, порядок notify/save и отсутствие лишних событий, динамический CanStart, состав и момент чтения session request. + +## Следующий проход ConfigMaker: состояние панели справки + +Выделить ConfigMakerCommandHelpPanel: живой документ справки, коллекции модулей/опций, фильтр/поиск, выбор команды и поля аргумента. Только чистые модели; локализация и IsEditorReadOnly приходят функциями. +Сохранить существующие коллекции и их типы, порядок Clear/Add/PropertyChanged, reentrancy SelectedCommandModule при изменении ComboBox, сортировку OrdinalIgnoreCase, восстановление выбранной группы без учёта регистра и fallback All. +В ConfigMakerViewModel оставить async loading/cancellation, UsageText/loading/status, команды copy/insert и обновление деревьев/диагностики после загрузки. Все прежние публичные свойства проксируются; sender уведомлений остаётся прежним host. +Отдельно сохранить особенности: выбор null не очищает старые поля аргумента; повторная установка текста поиска всё равно перестраивает коллекцию; изменение документа само не вызывает rebuild. +Проверки: группы/поиск/description fallback, прежний модуль после reload, required/optional argument, динамический readonly, точный порядок событий выбора, collection resets и повторный вход через синхронные уведомления. + +## Следующий проход ConfigMaker: тестовая сессия + +Выделить ConfigMakerTestSession: флаги тестового запуска, текущий тестируемый компонент, подписка на его состояние, stop/restore и обработка завершения. Работа с ComponentTasksManager — через узкий GUI adapter IConfigMakerTestTasks; сами Core/pipe/process реализации не меняются. +Host оставляет проверку выбранного компонента, разрешение аргументов из документа, локализованные сообщения и реальный DispatcherQueue. Session получает явные функции текущего ComponentId, подтверждения замены, установленности, сообщений, refresh output и enqueue. +Сохранить моменты повторного чтения ComponentId вокруг await, порядок IsTesting/подписки/уведомлений/проверки installed/run, игнорирование TaskStateUpdated во время старта, отличие запуска с тестовыми аргументами от восстановления обычной конфигурации и исходные границы catch. +Тесты не запускают процессы и не останавливают установленные компоненты. Проверяются успешный старт, отказ/ошибки, отсутствие компонента, восстановление, отложенные события, повторные start/stop и смена выбранного компонента во время ожидания. + +## Следующий проход ConfigMaker: графический дизайнер + +Выделить ConfigMakerSimpleDesigner: стабильные коллекции моделей, дополнительные аргументы, dirty/updating guards, обработка изменений и переходов между редактором/дизайнером. Публичные host-свойства и ICommand остаются совместимыми; уведомления пересылаются от имени host. +Существующие GraphicDesignerHelper и правила преобразования не менять. Ленивый backend сохраняет выбор GoodbyeDPI/SpoofDPI/NoDPI, DB lookup и проверку annotation-файла только при загрузке моделей. +Сохранить два чтения EditorText при загрузке, порядок Additional/Clear/Load/Attach/Parse, retry после отсутствующей аннотации/ошибки, границы catch и finally, case-sensitive идентификаторы моделей и сброс dirty после SetEditorText. +При подключении legacy-моделей и ObservableObject к headless-тестам явно сохранить текущий GUI-контекст Nullable=annotations, не менять runtime defaults и не отключать проверки нового класса. + +## Следующий проход App: каталог и создание окон + +Выделить AppWindowCoordinator над прежним экземпляром List окон: выбор живого окна по типу, Safe reuse/replacement, Unsafe reuse по непустому template-id, закрытие снимка окон и первого template по id. Общие типы не зависят от WinUI; backend выполняет прежние create/position/register/activate/close операции. +Host сохраняет все публичные сигнатуры, OpenWindows и прямой ShowWindow.Activate без BringToFront. Readiness читается через функцию при каждом вызове и ожидается до построения снимка; snapshot/reuse/close/remove/create/position/register/activate порядок и исключения сохраняются. +WinUI Closed/SizeChanged, modal coordinator, Program migration и idle/exit остаются в App. Тесты используют реальные алгоритмы координатора и управляемые окна без запуска приложения или изменения пользовательских настроек. + + +## Следующий проход BlockCheck2: отображаемый прогресс + +Выделить BlockCheck2ProgressViewModel: фаза/счётчики/идентификаторы/оставшееся время и зависимые display-свойства текущей цели. Список целей и параметры оценки приходят живыми функциями, уведомления host пересылает от своего имени. +Существующий BlockCheck2ProgressEstimator получает узкий интерфейс для тестирования последовательностей; его вычисления и Stopwatch не менять. Сохранить момент вызовов StartRun/StopRun/ResetObservations/Update и порядок всех уведомлений, включая значения полей до первого уведомления. +Reset принимает callback уведомлений результата после сброса полей прогресса, чтобы сохранить общий порядок OperationError/HistorySaveError/result перед progress-notifications. Остановка в finally очищает только обе оценки времени; CompleteDisplayedProgress изменяет только отображаемое число и ratio. +State, CTS, подготовка/запуск компонентов, сохранение отчёта, история и site-list I/O остаются в основной модели. Существующее исправление final-state только после SaveAsync не затрагивать. + +## Следующий проход ConfigMaker: жизненный цикл загрузки справки + +Выделить ConfigMakerCommandHelpLoader: текущий CTS, IsHelpLoading/IsCommandListEnabled/UsageText и последовательность загрузки. Service остаётся прежним production-объектом, передаётся его LoadAsync; Core/pipe/cache/parser не меняются. Панель передаётся как существующий объект, локализация и ComponentId — живыми функциями, UI-последствия — callback-ами. +Сохранить Cancel/Dispose/new CTS и получение токена до уведомлений; IsHelpLoading и локализацию loading-текста вне try; stale/canceled guard только после await; затем Document/Usage/modules/options/structure/diagnostics/status. Catch только OperationCanceledException, finally сбрасывает loading лишь для неотменённого токена. CancelBackgroundWork сначала отменяет loader, затем останавливает timer; отмена сама не сбрасывает loading и не dispose-ит источник. +Проверить конкурирующие запросы, позднее завершение отменённого запроса, смену компонента, forceRefresh, исключения до/внутри try, повторный вход из уведомлений и действительную загрузку коллекций панели без запуска компонентов. + +## Проверка привязок в живом WinUI + +После выделения владельцев проверить реальные XAML-контролы в отдельной копии pinned commit. Startup/single-instance/associations/tray и внешние help/process/catalog источники заменить явными тестовыми границами только в копии; production ветку и рабочие настройки не менять. До инициализации моделей убедиться, что DataDirectory находится в собственном каталоге бинарников. +Проверить редактор/справку/дизайнер/readonly/тестовые уведомления ConfigMaker, параметры и progress-привязки BlockCheck2, реальное повторное использование окон App. Результат на заглушках указывать как fixture-backed UI smoke, отдельно от реального запуска компонентов или полного production startup. Управление окнами — штатным Computer Use, только по наблюдаемому состоянию. + + +## Отдельный этап после UI-прогона: кодек графического дизайнера + +Нативный прогон подтвердил прежнюю потерю закрывающей кавычки у неизвестного флага с quoted path (CFG003). Выделить чистое преобразование GraphicDesignerCommandCodec из GraphicDesignerHelper, оставив фабрики/локализацию/XML-loading и совместимые facade-методы прежними. +Сначала перенести прежний алгоритм под characterization-тесты; затем отдельным RED-тестом полного цикла подтвердить потерю кавычки и исправить именно её. Сохранить порядок моделей/групп, GUID matching, defaults, формат и обработку известных/неизвестных флагов за пределами зафиксированного дефекта. Сценарии значений с equals проверить на существующем коде перед выбором исправления. +Это отдельный bugfix/decomposition этап после завершённого behavior-preserving переноса, разрешённый общей задачей по аудиту и автономным принятием безопасных правок. Core tokenizers, cache, pipe и процессная часть остаются вне изменения. + +Кодек сохраняет синтаксические кавычки неизвестных аргументов. Для enum и динамической фабрики (в том числе Telegram proxy) он передаёт скалярное значение без внешних кавычек: иначе выбор enum и чтение port/host/secret меняют смысл. Неперсистентный признак группировки в модели позволяет собрать обратно пробелы и явный пустой аргумент. Он устанавливается вместе с разобранным значением до PropertyChanged и сбрасывается при фактическом ручном изменении; присваивание того же значения не уничтожает группировку. Фабрика завершает инициализацию до добавления в observable collection. Обычный inline quoted value сохраняет прежнее представление поля. + +Ревью выявило и тесты воспроизвели отдельные пограничные случаи: полностью quoted следующая опция после флага, скалярный port в динамической фабрике, enum lookup и очистка поля после quoted parse. Исправления прошли повторное независимое ревью и 985 тестов; нативная проверка и совместная сборка учитываются отдельно. + +Общий review всего диапазона дополнительно выявил неполноту этого исправления при повторных переходах text/designer. В этом fix pass сохранить группировку quoted root-relative `/Program Files/...` и dash-leading `-team lists/...` путей с раздельным и inline аргументом. Пробелы до первого `=` внутри quoted токена означают grouped value, а пробелы после `=` не мешают распознаванию настоящей целиком quoted опции. У неизвестного inline аргумента сохранить `=`, если значение само похоже на опцию: иначе `--blacklist="--port=1443"`, целиком quoted `"--blacklist=--port=1443"` или bare inline вариант при следующем parse могут включить известную настройку port. Явная inline принадлежность важнее прежней нормализации её в пробел. Раздельно записанные quoted значения, похожие на опции и не содержащие пробелов до первого =, остаются лексически неоднозначными; не вводить schema/arity inference или новый общий parser. Прежние unquoted separate dash/slash boundaries и `-p "--port=1443"` сохранить. Верифицировать не менее трёх последовательных Parse/Build посещений. Это уточнение уже согласованного исправления потери quoted values, не новый формат пресетов. + +## Следующий этап: результаты и отчёты BlockCheck2 + +Выделить из BlockCheck2ViewModel самостоятельный BlockCheck2RunResultViewModel: OperationError, HistorySaveError, Issues, LastResult/LastReport/LastSession, вычисляемые признаки отчёта, lazy text/JSON и экспорт. Существующие BlockCheckReportBuilder и BlockCheckReportSerializer вызываются через IBlockCheck2ReportOperations и тонкий production-адаптер. Публичный конструктор и свойства основной ViewModel не меняются; sender уведомлений остаётся основная ViewModel. + +ApplyRunResult сохраняет исходный порядок: сначала LastResult, затем Build с актуальным SelectedRunPreset, затем LastReport и session с актуальными timeout/grace, затем Issues и прежняя последовательность уведомлений. Не превращать это в атомарную транзакцию и не делать ранний snapshot параметров. Prepared Issues назначаются без уведомления, чтобы host по-прежнему уведомлял Targets → TargetCount → Issues. NoBypassRequired читает именно Issues отчёта с ordinal-сравнением кода; HTTP-only требует непустой набор targets, только Http. + +Reset принимает callback существующего progress.Reset: сначала очищает все поля результата/ошибок, затем progress сбрасывает поля, после этого идут OperationError → HistorySaveError → результат → уведомления прогресса. Одинаковые ошибки и повторный пустой Reset продолжают уведомлять. Отсутствующий отчёт при экспорте бросает то же синхронное InvalidOperationException до вызова serializer; путь, token, task identity и ошибки backend не меняются. + +Host сохраняет orchestration StartAsync/Cancel, CTS, историю/логирование, generated-site-list cleanup, выбор финального состояния и установку финального состояния только после await истории. Файловые форматы, report builder/serializer, AddOns/Core и границы другой сессии не изменяются. Проверить pure owner и production-адаптер linked source, полный suite, GUI и независимое сравнение с aeeba14. + +## Редактор ручных назначений окна результатов BlockCheck2 + +Вынести из существующей публичной BlockCheck2ResultViewModel (565 строк) редактор BlockCheck2ManualAssignmentEditor: добавление/удаление/перемещение/очистку назначений, совместимые site-list targets и пути, seed автоматических назначений, ключи автоматического выбора, порядок строк и отметки выбора evidence. Он использует существующий Draft.Assignments, live-провайдеры session/evidence и callbacks очистки acknowledged issues и RebuildManualPreset. Форматирование действий остаётся прежним Zapret2ConfigWriter; тесты могут подставить функцию, чтобы проверить исключения и порядок. + +Сохранить различия ordinal/ignore-case в duplicate matching и ключах, фильтрацию ignored targets, текущую культуру сортировки имён файлов, исходный порядок primary/fallback/scope, пропуск отсутствующих strategy/target и последовательности коллекций/callbacks/Draft.LoadAutomatic. При повторном входе читать актуальные session/evidence там же, где host читал поля; не делать ранние snapshots. ClearAutomaticKeys отдельно вызывается при Load(report) на прежнем месте, чтобы не менять collection-event timing. + +Публичная модель и её constructor/method/property signatures сохраняются; она продолжает строить manual preset, группировать/локализовать issues, запускать manual tests и публиковать прежние PropertyChanged. Существующий BlockCheck2ManualIssueItem переносится целиком в собственный файл без изменений конструктора/локализации; остальные модели общего файла остаются чистыми production-моделями для linked-source тестов. Новые файлы создавать только после проверки отсутствия пути; существующие классы не заменять. + +Проверки: absent-API RED, реальные модели Draft/assignments/evidence/rules, mutation/order/seed/failure/reentrancy/path/culture scenarios, полный suite, GUI x64, независимое ревью против 59a5e8f и релевантный нативный проход в изолированном стенде. Процессные сервисы, AddOns algorithms, форматы и security-код не менять. + +## Координатор операций документа ConfigMaker + +Вынести из ConfigMakerViewModel.Document.cs порядок LoadPresetDocument, LoadConfigItem, CreateConfigItem, SaveToApplicationAsync, NewDocumentAsync, SaveTextAsync и синхронизацию документа/сохранённых ресурсов в ConfigMakerDocumentCoordinator. Существующий экземпляр ConfigMakerPresetDocument и обе observable collections сохраняются. Host предоставляет узкий IConfigMakerDocumentHost для актуальных свойств редактора, UI/callback-ов и прежних методов attach/autocorrect; сам coordinator не зависит от WinUI, базы данных или файловой системы. + +Сохранить последовательность metadata/clone/ComponentId/editor/structure/designer/event при загрузке, включая self-load и повторный вход из событий; два Sync вокруг AttachExistingPresetFiles перед диалогом; создание нового storage service только после ненулевого ответа диалога. IConfigMakerDocumentStorage повторяет SaveAsync(name,document)/OverwriteAsync(document); существующий сервис реализует этот интерфейс без изменения тел. ExportAsync передаётся прежним статическим методом. Не добавлять snapshot, блокировку параллельных сохранений или rollback: backend продолжает сам делать прежний clone, а host применяет результат к актуальному документу после await. + +NewDocument проверяет readonly только до await, подтверждает только текст/variables/resources, сохраняет прочую metadata и очищает editor/base/name/collections/structure/undo в прежнем порядке. SaveText ловит исключения chooser/sync/export/успешного уведомления; SaveToApplication по-прежнему их не перехватывает. CANCELED сравнивается ordinal; сохранённые resources сопоставляются по первому alias ignore-case, пустой path не обновляется. Сообщения и локализация остаются вызваны в прежних точках; DocumentStateChanged публикуется от host. + +Для linked-source тестов подключить настоящие PresetDocument/Converter/SaveResult/Request. Единственный вызов унаследованного static GetNameOnOffValuesFromConditionString в converter квалифицировать непосредственно объявляющим LScriptCore, чтобы убрать зависимость чистой конверсии от WinUI-локализатора; само тело метода и алгоритмы converter не менять. Проверить legacy conditional-конверсию реальным тестом. Автокорректор, storage/export I/O, форматы, Core/AddOns и security WIP остаются прежними. + +## Замена отсутствующих файлов пресета + +Выделить ConfigMakerPresetFileReplacer из наиболее сложной части ConfigMakerViewModel.PresetFiles.cs: ReplacePresetFileAsync, auto/manual выбор, TryCreateEmptyPresetFile и TryApplyPresetFileReplacement, включая три сообщения результата. Это общий workflow диалога и тихого импорта. Открытие/add/remove/insert остаются в host для отдельного следующего прохода; переносить весь блок в новый столь же смешанный класс не требуется. + +Replacer зависит от IConfigMakerPresetFileReplacementHost (прежний RunReportingErrorsAsync, выбор файла, localization/status, structure и explicit file array, setter CommandText, событие) и IConfigMakerPresetFileReplacementBackend (TryResolvePath, FileExists, CreateEmptyFile, TryUpdateAttachedResource, ReplaceReferences, CreateAutoCorrector). AutoCorrector предоставляет ShouldSuggestEmptyFile и FindReplacementAsync; production wrapper создаёт прежний ConfigImportResult синхронно, затем вызывает тот же FindReplacement на Task.Run. Создавать wrapper/ConfigImportAutoCorrector только после выбора AutoCorrect, как исходный код. + +Сохранить null/blank/exists guards, неизвестное значение выбора как отмену, отсутствие manual fallback после ненулевой неудачной suggestion, CreateNew semantics, точки catch и silent showStatus=false. Attached update не меняет command/explicit array и не публикует PresetFileReplaced. При переписывании ссылок сначала обновить актуальный explicit array через ReferenceEquals или kind+PathsEqual, затем при CommandChanged отформатировать и назначить CommandText, перестроить структуру и вызвать прежнее событие от host с актуальной командой. Чтение CommandText и new EventArgs остаются внутри условного PresetFileReplaced?.Invoke в host, чтобы сохранить точку чтения и отсутствие чтения при отсутствии подписчика. + +Новые интерфейсы не добавляют файловую политику, snapshots, транзакции или rollback. Настоящие filesystem/resource-registry/autocorrect/shell алгоритмы не менять; backend только делегирует прежним операциям. Проверки выполняют ветки и порядок на фиктивных внешних операциях с настоящими FileInfo/Replacement/Core path/formatter типами; не открывают приложения и не создают/удаляют физические файлы. + +## Остальные действия дерева файлов пресета + +Выделить ConfigMakerPresetFileActions для AddPresetFiles, OpenPresetFileAsync, ShowPresetFileInFolder, RemovePresetFileAsync, InsertPresetFileReference, picker и missing notice. Он получает прежнюю стабильную document.Resources как IList, узкий UI-host и ленивый backend для facade/File.Exists, text-file preferences и shell. Backend constructor только сохраняет facade; существующие filesystem/settings/shell реализации не меняются. Host сохраняет публичные методы, AddPresetFileCommand и private picker forward, замену файлов и её уже проверенные adapters. + +Add передаёт исходный IEnumerable без раннего перечисления/snapshot, использует исходный added count и порядок attach/rebuild/panel/status только при count>0. Open сохраняет site-list-or-txt правило, ожидание application dialog, RememberDialogShown только при true и отсутствие shell-вызова после любого результата диалога. Show-in-folder остаётся синхронным и не добавляет reporting catch. + +Remove находит resource один раз до await, подтверждает только referenced, после await удаляет именно прежний объект из той же коллекции и затем rebuild/schedule даже при неуспешном Remove. Это удаление metadata из памяти, не физического файла. Insert сохраняет readonly/null short-circuit, прежний trim и preset:// bypass, порядок exists/full-path/GetOrCreate; resource.Reference читается после rebuild при resourceAdded, чтобы сохранить alias, изменённый обработчиком события. Не добавлять readonly guards к остальным операциям, rollback или новые проверки путей. + +Проверки используют настоящие document/resource/file модели и реальные BCL collections/path operations, но фиктивные filesystem/shell/preferences. Сохранить области synchronous exception propagation и RunReportingErrorsAsync; отдельно проверить mutation/await/reentry и ошибки collection subscribers. Actual-host интеграцию с fake внешними границами учитывать отдельно от интерактивных контролов. + +## Следующий проход App: файловая маршрутизация активации + +Первый App dispatcher оставил file imports на месте. Теперь выделить только ProcessFiles и список пяти поддерживаемых extensions в AppFileActivationHandler, с узким IAppFileActivationOperations и production AppFileActivationOperations. Это выбор маршрута и прежний порядок окон; реальные ConfigShare/conditional/store/update importer implementations, форматы, security/path/trust checks, Program, URI allowlists, migration lock и settings recovery не меняются. + +Handler получает исходный string[] и последовательно читает его без snapshot: для каждого элемента Replace всех двойных кавычек на пустую строку (не Trim), затем исходный debug log, Path.Exists и extension whitelist OrdinalIgnoreCase. Path.Exists остаётся Path.Exists, не File.Exists. До существования/whitelist нельзя вызывать ConfigShare.IsSupported. Сначала ConfigShare, затем cdpitask, затем cdpipatch, иначе store pack. Обрабатывается только первый подходящий файл; следующий не читается, пока ожидается его маршрут, и после успеха больше не читается. Null array/element и backend failures остаются faulted async task без нового catch/fallback. + +Production operations constructor только сохраняет App и прежний private conditional callback. Share: await UnsafeCreate(activate:false), Activate, await SetFileAsync. Patch: await SafeCreate(activate:false), SetUpdateFilePath, Activate. Store: await SafeCreate() с прежним activate default и fire-and-forget SetPackFilePath; не ждать completion самого импорта. Conditional delegate сохраняет исходный private метод целиком. Log source остаётся nameof(App). В App остаётся ProcessFiles forward для прежнего activation dispatcher; новый owner/backend создаются до InitializeComponent без обращения к settings/windows/importers. + +Characterization проверяет whitelist/case/quote normalization, guard/order/first-file, route precedence, async task and exception/cancellation propagation, ожидание всех четырёх route tasks и живое чтение массива после reentry. Тесты используют fake operations и не создают окон/файлов, не импортируют пакеты, не запускают updater. WinUI adapter проверяется компиляцией и отдельным source comparison, без утверждения реального production import. Глубина этого прохода — перенос оркестрации, не изменение политики импорта. + +## Следующий проход BlockCheck2: ручной preset state + +Выделить BlockCheck2ManualPresetState из публичного BlockCheck2ResultViewModel: RebuildManualPreset, DescribeManualIssueSubject, current manual preset result/Arguments и factory ManualOptions. Owner получает тот же Draft, ту же stable IReadOnlyList ручных ProbeResult, narrow host и Build operations. Production operations лишь делегирует прежнему экземпляру BlockCheckManualPresetService. BuildEvidence/strategy testing, ручной список probe results, acknowledged issue keys и локализованный ManualIssueItem остаются host; сетевые/component callbacks не переносить. + +Host сохраняет коллекции и публичный API, private rebuild forward, порядок Load и result clear. ClearResult вызывается ровно на месте прежнего `_manualPreset = null` после ManualIssues.Clear; никакой объединённый reset не переставляет события. В constructor owner/backend только сохраняют зависимости; assignment editor callbacks остаются прежними host callbacks. ManualPresetArguments читает owner.Arguments без новых уведомлений. ManualOptions в host становится forward к одной чистой factory OptionsFor, сохраняя fresh allocation, Math.Max(1,MinimumAttempts) и неизменённый MinimumSuccessRate. + +Rebuild начинает с host.ClearIssues, затем читает актуальный session и assignments. Пустая ветка очищает result, refresh indexes, опционально ApplyStructuredChange(empty), refresh evidence, NotifyManualState. Непустая ветка формирует deferred probe overlay (StrategyId OrdinalIgnoreCase, TargetId Ordinal), append ручных результатов, вызывает Build, назначает result ДО issue callbacks, группирует issue по точным Severity/Code/Message в исходном порядке. Host.AddIssueGroup создаёт прежний локализованный item и проверяет тот же ordinal acknowledged key до добавления. Describe subjects остаётся deferred до вызова конструктора item: scope match раньше strategy match, затем slash-список и исходный fallback; существующие culture/path правила не менять. + +Непустая ветка опционально применяет current owner result к draft ПОСЛЕ issue callbacks, затем indexes/evidence/notify. Не сохранять ранний snapshot session, assignment list или current result: reentrant callback может изменить их в прежний момент. Deferred targets predicate читает актуальный session ignored ids, а source targets/probes и options вычисляются как в исходном вызове. Исключения выходят синхронно, ранее выполненные мутации не откатываются. Assignment edit/selection, QuickFix/ack semantics, test result replacement, IssueItem/localization и domain builder не менять. + +Unit-тесты используют настоящие Draft/assignment/domain types и fake host/build ports; real IssueItem и WinUI localizer не подменять ради компиляции. Проверить обе разные последовательности веток, updateDraft true/false, expert/automatic state, overlay/comparers/live deferred enumeration, options/grouping/subjects, reentry и partial exceptions. GUI build и independent source review подтверждают host adapters; actual public-model runtime с настоящим localizer/pure builder рассматривается отдельным этапом, без live strategy tests или сети. + +## Следующий проход BlockCheck2: ручной strategy test controller + +Выделить GetFullStrategyArguments и TestStrategyAsync в BlockCheck2ManualStrategyTestController. Передать тот же Draft, ту же List, getter текущего session, исходный RebuildManualPreset callback и узкий operations port. Production adapter только хранит прежний BlockCheckManualStrategyTestService и напрямую делегирует его sync GetFullStrategyArguments / TestWithCdpiuiAdaptersAsync. Конструкторы не обращаются к зависимостям. Public model signatures и исходная service initialization остаются прежними. + +Синхронный GetFullStrategyArguments по-прежнему без session guard: сначала item.Evidence.Strategy/Target, затем текущий session.Scan.AttemptsPerTarget с Math.Max(1,...), fresh options. Async Test сначала проверяет session, при отсутствии возвращает fresh result/issues с исходным MANUAL_SESSION_UNAVAILABLE, даже для null item или canceled token. Затем исходный порядок item/options/session timeouts/grace/token, await ConfigureAwait(true). Никаких Task.Run, locks, validation, catch, snapshot, дополнительной проверки отмены или смены session. + +Если результат содержит ProbeResult: RemoveAll по StrategyId OrdinalIgnoreCase и TargetId Ordinal, Add того же probe, item.ApplyTestResult, затем чтение текущего Draft.IsAutomatic и вызов rebuild(!IsAutomatic). Все уведомления item идут до rebuild; observer может изменить draft/session/list. Pending Load и перекрывающиеся тесты сохраняют прежнее поведение применения по порядку завершения, включая stale item и current host session. Ошибки/отмена/частичные мутации выходят без rollback. Probe-null result не меняет состояния. + +Characterization использует настоящие EvidenceItem/Draft/domain, fake operations и управляемые tasks, без real backend execution/network/components. Проверить sync/async failure boundaries, identity/options/evaluation order, cancellation ownership, current-context continuation, overlay comparers/order, live draft/session/list changes и partial callback failures. Compile реального production adapter и source review подтверждают прежний service call; фактический запуск стратегии остаётся вне проверок. + +## Следующий проход ConfigMaker: операции с переменными + +Выделить ConfigMakerVariableActions с тем же ConfigMakerPresetDocument и узким IConfigMakerVariableActionsHost. Owner содержит Edit/Remove/Create/Insert; host сохраняет public signatures, RunReportingErrorsAsync вокруг Edit/Remove и CreateVariableCommand, private Create forward и исходный error logger/status. Конструктор owner только сохраняет зависимости. Реальные document/variable models и коллекции не меняются. Host adapter делегирует прежние view/localizer/editor/attach/tree/diagnostics callbacks, не переносит их побочные эффекты в owner. + +Edit: null guard, await view.Edit(document,originalVariable), null result guard, IndexOf исходного объекта ПОСЛЕ await, missing guard. Затем ordinal сравнение result.OriginalName с result.Variable.Name, ReplaceVariableReference в том же документе, SetEditorText с текущим document.CommandText ПОСЛЕ document events, присваивание по ранее вычисленному index, Attach, Rebuild, Schedule. Не клонировать result, не искать повторно index после reentry, не валидировать имена/дубликаты сверх прежнего UI. + +Remove: null guard, host.CommandText.Contains(variable.Reference, OrdinalIgnoreCase) до await; только при referenced ждать исходное localized confirmation. После согласия/отсутствия ссылки Remove исходного объекта, Rebuild, Schedule, даже если Remove вернул false. Ссылки из command не удалять. Create: await view.Edit(document,null), null guard, Add того же result.Variable, Attach, ShowVariablesTool, Rebuild, Schedule. Insert: IsEditorReadOnly читается раньше null guard, затем текущий Reference и прежний InsertAtCursor. + +Никаких snapshots, новых guards, locks, rollback или catch в owner. Документ может перезагрузиться/измениться во время await; collection/content observers могут изменить коллекцию после вычисления edit index. Сохранить исходную частичную мутацию и порядок исключений. Unit characterization использует настоящие document/variable events, fake host и managed tasks без dialogs/files/network. GUI compile и независимое source review подтверждают реальные adapter/localizer/error wrapper/command bindings. + +## Следующий проход BlockCheck2: run lifecycle controller + +Выделить StartAsync, Cancel, CTS field и private GetFinalState в BlockCheck2RunController. Host сохраняет State, Targets, options/progress/results и все backend/history/generated-root/cleanup endpoints. IBlockCheck2RunHost предоставляет только исходные шаги workflow и текущие CanStart/CanCancel/LastReport; constructor controller только сохраняет host, создаётся в конце исходного host constructor. Публичные StartAsync/Cancel становятся forwards, sender и порядок всех host notifications прежние. + +Start сначала читает CanStart и при false возвращает null без finally. При прежнем LastReport обновляет generated root, затем ResetResultState и progress.StartRun ВНЕ try. В try Prepare с исходным CreateSessionRequest; ApplyPrepared adapter содержит прежние assignments Targets/Issues и три Notify в исходном порядке. При invalid — InputInvalid/null. Иначе локальный CTS назначается в owner field ДО State.Running, await прежнего RunPrepared endpoint, ApplyRunResult, CompleteDisplayedProgress, вычисление final state ДО await SaveHistory текущего LastReport, затем SetState(final) и возврат того же result. Пока history pending, прежний running state блокирует новый запуск. + +Catch OCE назначает Canceled/null; catch Exception — прежний SetOperationError(message), Failed/null. Никаких новых catch/validation/rollback/locks/cancellation checks. Finally: FinishRun, dispose локального CTS, field clear ТОЛЬКО по ReferenceEquals текущего field и local, CleanupIfUnviewable, NotifyActionState. Сохранить порядок даже при исключениях callbacks и reentry нового запуска на final-state event; finally старого запуска не очищает CTS нового. Cancel читает CanCancel до null field guard, устанавливает Canceling, затем вызывает текущий field.Cancel, сохраняя reentry и synchronous callback exceptions. + +Unit characterization использует реальные Prepared/RunResult/Report types, fake host и управляемые tasks. Покрыть prelude вне try, invalid/success/final-state precedence, pending history и captured final state/current report, exception/cancellation boundaries, reentry/CTS lifetime, cancel before backend и cancel callback exceptions, partial finally и captured SynchronizationContext. Реальные Prepare/runner/network/history/logger/cleanup/deletion не исполнять. Source review и GUI compile подтверждают host adapters; optional actual-host runtime требует отдельного безопасного fixture design. + +## Следующая крупная ViewModel: CreateNewConfig condition draft + +Выделить из CreateNewConfigViewModel.Variables.cs четыре condition draft fields/properties, ConditionPreview, IsConditionSaveAvailable, ResetConditionDraft, AddCondition и draft notifications в CreateConfigConditionDraft. Получить ту же ObservableCollection, lazy callbacks исходных validation/CreateCondition/localizer и SetExitAskAvailable(true). Constructor только сохраняет зависимости. Host сохраняет public API/collections, forward property notifications с прежним sender, RemoveCondition/RemoveVariable/VariableChanged и все save/import/test workflows. + +Сеттеры нормализуют null в пустую строку, публикуют собственное имя при изменении, затем Preview/IsSave для Name/On/Off; Description только своё имя. Preview сначала текущий IsSave, затем вновь читает текущие Name без пробелов/On/Off для formatter; invalid branch lazily localizes NothingToPreview. Не добавлять guards/snapshots/caching. Reset вызывает четыре setters в прежнем порядке Name/Description/On/Off, затем безусловный Preview. Add сначала exit-ask callback, затем создаёт fresh model из текущих RAW полей и добавляет в ту же collection, без IsSave guard/reset/trim; callback может изменить draft до чтения. + +Новый owner strict nullable; исходная POCO model сохраняет annotations-only GUI context при source-link в tests. Unit tests используют настоящую collection/model, spies для validation/format/localizer и один настоящий Core formatter; без WinUI stubs, dialogs, storage, Logger или component execution. Public getters/setters остаются plain forwards без implicit interfaces, чтобы сохранить CLR flags. + +## Возобновление: test session CreateNewConfig + +Выбор исполнителя: следующим отдельным владельцем станет CreateConfigTestSession из CreateNewConfigViewModel.Testing.cs. Он владеет running/current-id, button text/glyph, подпиской и start/stop/process-state orchestration. Конструктор хранит callbacks; начальный текст присваивается без уведомления в прежней точке host constructor. Host сохраняет публичные getters/private setters и sender, AsyncRelayCommand, SelectedComponent, конвертацию designer/CreateConfig, startup argument formatter, localizer и DispatcherQueue через ленивые callbacks. Реальные ComponentTasksManager endpoints остаются в узком adapter с event/StopAsync/RunAsync, без инициализации singleton при создании adapter. + +Сохранить прежний порядок и quirks: unsubscribe перед guard StopTestRun и повторный unsubscribe при reset; локальный runId для fire-and-forget stop; start устанавливает running до remove/add подписки и читает selection после них; существование selection отдельно от null/empty Id. Await Stop перед conversion/create, аргумент runId читается до formatter; возвращённый Run Task не ожидается. State tuple ставится в очередь без раннего guard, сравнивается с текущим id при исполнении case-sensitive; glyph затем localized text затем running. Reset glyph/text до flags/unsubscribe/id-clear. Никаких новых try/finally, locks, cancellation, rollback, restore или guards; прежние частичные состояния при fault/reentry остаются. Никаких изменений Save/Import/GraphicDesigner/service implementations. + +Проверка: linked pure production owner/port с настоящим Core ConfigItem; managed fake service и controlled tasks/queue без WinUI, IO или процессов. RED до owner, focused/full suite, GUI x64, metadata comparison на normal DLL, независимый review нового диапазона. Actual host/adapter runtime proof — отдельный следующий gate с inert service boundary; native15/16 и настоящий backend этим не закрываются. + +## Возобновление: состояние graphic designer CreateNewConfig + +Следующий выбор исполнителя — CreateConfigGraphicDesigner, самостоятельный владелец loaded component id, additional settings и изменений двух существующих коллекций моделей. Host сохраняет коллекции/bindings, всю последовательность переключения вкладок/visibility/view calls и точные чтения/присваивания EditorText. Load получает прежний captured selected id; живой getter HardcodedItemIds передаётся функцией, чтобы позднее чтение id после factory/collection callbacks не превратилось в snapshot. AdditionalSettings продолжает null->empty, equality suppression и host sender. Constructor владельца и backend только сохраняют зависимости. + +В отдельном CreateConfigGraphicDesignerBackend оставить прежние конкретные Goodbye/Spoof factories, NoDPI DB directory + Path.Combine(edannotationfile.xml) + File.Exists + XML(nodpi), Parse/Build через неизменённый GraphicDesignerHelper. Не использовать case-insensitive TryLoad от ConfigMaker: у CreateNew исходные сравнения case-sensitive, конкретный порядок branch/cache и иное поведение при неподдерживаемом id. Это тонкие adapters к общему helper, не новая реализация codec. + +Сохранить строки алгоритмов: при отсутствии NoDPI annotation cache не обновляется и попытка повторяется; cache после successful callback читает текущий mapped id; exception/reentry не получает rollback. Text/bool выбирают первый standalone либо первый matching child первого matching exclusive group; GUID case-sensitive, group selection без дополнительной validation/check state; прежние null/unknown/partial-model эффекты сохраняются. Parse возвращённое additional значение присваивается после model callbacks; Build получает additional до backend callback. Никаких новых dirty/readonly/normalization/guards. Реальные модели + fake backend тестируют contract без WinUI/DB/XML, код adapter компилируется и проверяется review; следующий actual-host gate использует реальные safe factories/codec и инертные NoDPI IO targets. + +## Возобновление: component selection CreateNewConfig + +Выбор исполнителя: CreateConfigComponentSelection владеет SelectedComponent, DisplayName, тремя связанными visibility flags (additional/not-ready/tabbar), вычислением IsDesignerSupported/IsSaveAvailable и порядком CheckViewType/dirty/audit. Другие visibility, folder buttons, title/mode/navigation/save/IO остаются в host. Семь ленивых callbacks: supported-id predicate, select designer/text tab, HandleSelectionChange(bool), mark exit ask, audit commands, read current EditorText. Это coordinator выбора компонента, не общий property bag. Конструктор не вызывает view/predicate/command callbacks. + +Host сохраняет прежние public types/private setters, bindings и sender через plain forwards. Приватный CheckViewType остаётся forward для Navigation. Дополнительные уведомления computed properties не добавляются. Сохранить equality по identity, null->empty только DisplayName, пустой/null selected ID отдельно от отсутствующего объекта; CanSave проверяет наличие объекта/name/editor без trim/ID validation и читает editor только после shortcircuit. Selected setter сначала notify, затем CheckViewType, dirty, audit. Check сначала null guard, затем additional/notready, затем текущий supported predicate; supported выбирает tab до tabbar=true и Handle(false), unsupported вызывает Handle(true) до selectText и tabbar=false. Callback/reentry/observer exception сохраняют прежние частичные состояния и продолжение внешнего setter без нового rollback/revalidation. + +Linked tests используют настоящий ConfigComponentOption; его annotations-only GUI context явно сохраняется при source link, без изменения модели/nullable policy проекта. Нового интерфейса на public host не вводить (public CLR flags сохраняются). Реальный view и методы designer остаются ленивыми host targets; actual-host следующий gate использует текущие16inert boundaries без новых backend/service cuts. + +## Следующий проход ConfigMaker: diagnostics panel + +Выделить сбор и обновление Diagnostics, error/warning counts и локализованное представление диагностик в ConfigMakerDiagnostics. Generic internal owner сохраняет ту же ObservableCollection; actual host закрывает TItem настоящим ConfigMakerDiagnosticViewModel с WinUI Brush. Unit tests используют производственные diagnostic/help/variable/validator types и явную factory projection, без WinUI stubs или изменения модели UI. Конструктор только хранит collection, lazy EditorText/options getters, ту же Variables collection, resource predicate, item factory, localizer и highlighting callback. Timer/debounce, private RebuildDiagnostics entrypoint/callers и GUI adapter остаются в host. + +Rebuild читает EditorText один раз, затем текущие options; Validate(...).ToList, затем AddDiagnostics с текущими variables/resource resolver, всё ДО Clear. После Clear создаёт и добавляет по одному item в прежнем порядке. Host item factory сохраняет object initializer Source, SeverityText, Description; локализация severity/description принадлежит owner, host лишь присваивает результаты. Для неизвестного severity используется warning label; для неизвестного kind прежняя unterminated-quote строка. Все прежние форматные строки/параметры и культура String.Format сохраняются. После collection callbacks вычислить error count по Severity.Error, warning=results.Count-error (включая неизвестный severity), локализовать/присвоить ErrorCountText, затем WarningCountText, затем RefreshEditorHighlighting. Никаких новых notifications/equality policy/sort/cache/catch/rollback/guards/snapshots. + +Synchronous collection/property/localizer/view callbacks могут reenter Rebuild или изменить текущие model inputs. Сохранить локальный outer results и частичные mutation/exception paths; при Validate/reference failure предыдущие collection/counts остаются, при factory/Add/localizer/counter/highlight failures присвоенное сохраняется. Counter notifications пересылаются синхронно с прежним host sender, private setters plain forwards сохраняют CLR shape. Аннотационный контекст существующего pure validation source при source-link сохраняется явно; глобальная nullable migration не входит. Actual view/Timer/native callback/runtime integration доказываются отдельным gate, новые реальные IO/DB/logger endpoints не исполняются. + +## Следующий проход исходного God-control: resizable panel layout + +Выделить из ConfigMakerUserControl.Layout.cs алгоритм UpdateLayoutBounds и состояния layoutInitialized/updatingLayoutBounds/savedEditorHeight в ConfigMakerPanelLayoutController. Чистый IConfigMakerPanelLayoutView передаёт только bool/double properties, причём все чтения/присваивания остаются в прежней последовательности, без входного snapshot или предварительного расчёта всех выходов. Отдельный WinUI ConfigMakerPanelLayoutView хранит девять lazy getters для Root/files/command/bottom/workspace/editor FrameworkElement и двух ColumnDefinition/одной RowDefinition; constructor только сохраняет callbacks. В control owner и adapter создаются первой строкой constructor ДО ViewModel/InitializeComponent, чтобы ранние XAML callbacks видели тот же default state. Реальные controls через callbacks читаются только при обращении. Host сохраняет public flags/панельные show-hide/tab/events, ShowPanel, dead savedEditorWidth assignment и private UpdateLayoutBounds forward, без нового host interface/partial. + +Controller guard сохраняет shortcircuit updating || rootWidth<=0 || rootHeight<=0, затем флаг true и прежний try/finally. Константы360/340/180/110, files max=Math.Max(150, rootWidth-editorMin-(commands?commandMin+sizer:0)-filesSizer), cap45%, clamp/current min/max, затем available main width/editor MaxWidth→Width и height MaxHeight→Height точно как раньше. Command-panel width остаётся прежним max-width, dead savedEditorWidth не начинает влиять на поведение. Bottom height выбирает текущую Height только после initialized, иначе min(saved420,max); CompletePanelChange invalidate перед Update и event. Hide bottom запоминает ActualHeight в прежней точке. SizeChanged guard использует owner.IsUpdating, finally сбрасывает его даже при property/callback exception; initialized=true только после всех assignments. Не добавлять нормализацию NaN/inf, min/max guards, rollback или catch. + +Unit characterization использует pure scalar port/spies/reentrant controlled callbacks без WinUI stubs или view IO: all branches/minimums/caps/clamps/initial-vs-current height/hidden panels/repeated live reads/order/shortcircuit/exception-recovery/reentry. Реальные UI property validation и Window visual delivery этим не заменяются. Normal GUI compile/metadata/source plus fresh review проверяют mapping к исходным XAML elements. Actual adapter with standalone WinUI elements в следующем безопасном gate, full control/native15/16/visual resize remain separate. + +## Следующий проход App: window close lifecycle + +Выделить workflow Window_ClosedHandler в AppWindowCloseCoordinator с той же List и узким IAppWindowCloseOperations. Host оставляет sender is Window/e.Handled guards и приватный forward, Window_SizeChanged/Register/Activate/modal implementation/migration policy не меняются. Separate AppWindowCloseOperations для настоящего Window хранит modal coordinator, detach callback, createPrepare callback и ExitIfIdle callback; constructor только сохраняет зависимости и создаётся в App до InitializeComponent, без обращений к Window/IO. + +HandleClosed сначала захватывает enqueue closure с текущим window.DispatcherQueue, затем вычисляет bool migrationWindowClosed через прежний WelcomeWindow/Id OrdinalIgnoreCase. Try SavePosition, catch warning, finally: detach Closed→SizeChanged в одной последовательной host callback; try ReleaseModal(isClosing:true)/catch warning; try sameList.Remove(window)/catch warning; if captured migration bool CompleteMigration; затем ForgetOwner. Сохранять частичные finally и исключения самого logger/cleanup. После finally captured migration: попытка Low enqueue ExitIfIdle, при false sync ExitIfIdle, return. Иначе при текущем list.Count==0 && current StoreWorking fire-and-forget original SafeCreateNewWindow(activate:false); иначе тот же enqueue/fallback. Никаких новых guards/await/locks/catch/snapshot/rollback и актуализации captured migration/dispatcher после callbacks. + +Pure owner не знает WinUI, Window handles, settings или TaskMonitor. Real adapter вызывает прежние WinUI/event/modal/position/logger/Program/backend methods; исходный ExitIfIdle policy остаётся App. Сама List фиксирована readonly currentApp constructor и уже передаётся WindowCoordinator; private OpenWindows setter в приложении после initial assignment не используется. UI event args/handler guard и реальные backend effects проверяются отдельно, не через unit stubs. Unit tests используют настоящую List, managed tasks/objects/closures с ожидаемыми fault/reentry boundaries. New public host interface не вводится, CLR flags не меняются. + +## Следующий проход BlockCheck2: site-list workflow + +Выделить loading/loaded/error, две существующие коллекции и Load/AddCustom/UpdateCustom/Select/Remove/SetSelected и computed counts из SiteLists partial в BlockCheck2SiteListController. Generic owner работает с настоящими ObservableCollection и реальным SiteListElement из AddOns, через IBlockCheck2SiteListBackend выполняет legacy/factory/normalization/path/write/localizer и чтение свойств TItem. Production closed TItem=BlockCheck2SiteListItem; новый тонкий backend вызывает те же SiteListHelper/BlockCheck2SiteListStorage/real item методы. Не менять SiteListItem/Storage ради compile unit tests; тесты явно проецируют fake row port, без WinUI stubs. Generated root, preparation preview/run/cleanup/CreateSessionRequest остаются host; generated-root getter читается лениво на каждой factory call. + +Load guard loaded||loading. Вне try назначить loading=true/error=null и безусловно Notify IsSiteListLoading затем SiteListLoadError. В try await LoadAvailable, Clear, затем ленивые Where nonblank Directory/!legacy и OrderBy PackName/ThenBy Name CurrentCultureIgnoreCase над теми же mutable SiteListElement. Не создавать DTO snapshots и не сортировать раньше Clear. Factory получает текущий Name??Path.GetFileName(Directory)??fallback/PackName??empty/Directory/generated root; затем DomainCount>0 && !DisplayName.Contains("exclude") case-sensitive before Add. loaded=true после всех rows; catch Exception (включая cancellation) error=Message/Notify; finally loading=false/Notify. Partial/reentrant/notification exceptions сохраняются, включая prelude outside try. + +AddCustom сначала Path.GetFullPath, поиск Available.Concat(Selected) OrdinalIgnoreCase по текущим paths; existing возвращается по reference. Иначе new factory item из filename/source/fullpath/current generated root, без добавления в коллекции. Update нормализует, empty→тот же localized InvalidDataException; находит первый текущий IsCustom ДО await, captured path либо CreateCustomPath, await Write с исходным token. Затем если item absent создать real new custom row с normalized content/current root и Insert(0), иначе UpdateCustomContent исходного captured item (даже если он удалён за время await); затем прежний selection notify, return sameitem. Никаких locks/snapshots/reselection/cancellation-rechecks/rollback. + +Select/Remove сохраняют ThrowIfNull(item), case-insensitive path dedup, Notify только после фактической mutation; SetSelected Clear перед ленивым DistinctBy, включая same-source self-clear/null input partial effect. Selected counts живые Count/Sum(DomainCount). Selection callback остаётся исходным host NotifySiteListSelectionChanged (четыре имена/порядок), loading/error notifications пересылаются с host sender. Backend/owner constructor store-only, same collections; нового host interface/partial нет. Реальные IO/DB/cleanup remain source-only до отдельного безопасного runtime gate. + +## Оставшиеся native gates на текущем pin + +Свежий Sky list_windows после Task52 показывает5targetable windows, без consent/CDPIUI/Smoke candidates; прежний UAC blocker больше не наблюдается. Перенести corrected921 native-сценарии в НОВУЮ копию текущего214b4b3 на F, старую не запускать/не менять. Standalone SmokeWindow создаётся вручную, с собственным Closed→App.Exit и записью в собственный App.OpenWindows, без App.Register/position/modal lifecycle. Все actual production controls/pages/owners остаются. Program/App startup/DirectoriesManager/help/task manager/output/settings/DB-relative resources/catalog/scan/manual tests/storage/export/filepicker/shell границы ниже инертны, без userdata/backend/actions. Root data ровно own executable bin, без fallback. Real Frame+MenuBarHost.SetFrame и nonnull MenuBarSession обязательны ДО mounting ResultPage (исправление известного harness-only stackoverflow). + +Native Task15: LoadSession controlled two-strategy TLS12/IPv4 report, сохранить actual collection aliases и references. Четыре observation phases: empty; click реального Add for site split; click Add disorder; click реального Move down для split. Проверить order/1-based indexes/same objects/Draft origin/evidence flags/CanUseConfig/canonical serialized actions/порядок host notifications. Helper лишь загружает и проверяет; assignments меняются исключительно production UI actions через Sky. + +Native Task16: реальный ConfigMakerUserControl и document coordinator, actual dependency-property/editor binding, коллекции/variables/resource tree. Controlled preset содержит одну variable MODE и attached sites resource, command на собственный fixture file. Реальная SavePreset ContentDialog: cancel без persistence и success с отредактированным именем; public real storage SaveAsync/OverwriteAsync+Clone/Task.Run остаются, только private SaveCore backend memory result. Export path fakeown .cdpiconfig и exporter memory recorder, no zip/text write; validate allowText=false/current document. Реальная New confirmation cancel/continue, readonly no-op и cleared text/name/variables/resources с сохранением collection identity/остальной metadata. Один initial CreateNew own input file и append-only own log допустимы; input retained byte-identical/no physical export. No user settings/real databases/shell/components/probes. + +Native UI inputs только через Sky в точном observed own window; сначала snapshot/focus, потом один ввод/клик+refresh. Не взаимодействовать с чужими UAC/auth/security windows. Ошибки sticky, Finish возможен только после всех11distinctPASS и noFAIL, затем COMPLETE/native process exit0. Own30minute watchdog exits2/failure on abandoned fixture, не общее временное ограничение задачи; watcher checks in<=1s intervals. Full source/build input/manifest/ownroot/fresh files independently reviewed beforefirstlaunch. Native warnings/bugs must distinguish harness/baseline/product via evidence, no automatic green from programmatic86. + +Предпусковое ревью добавило семнадцатую явную границу: вложенный SearchUserControl создаётся из реального XAML и читает SEARCH settings в ctor даже при Collapsed. Два чтения заменены false, два persistence Click target отказом; XAML и сам search control сохранены, реальный SettingsManager не запускается. Первые16cut manifest/DLL сохранены, до исправления ни одного запуска. + +Первый17cut native run дал11UI PASS/COMPLETE/exit0, но postgate обнаружил собственный Settings.xml/bak из ConsoleFontHelper x:Bind. Общий gate не принят. В НОВОЙ native2копии добавляются18ConsoleFontHelper6settings-targets(defaulttrue/Consolas/16) и19Core.SettingsManager failfast baseargument доXMLbase. Он выставляет process-local AppContext switch и бросает исключение; GUI проверяет sticky switch вFinish и ПОСЛЕ Application.Start доreturnexitcode, чтобы swallowed binding/closing ошибки не дали green. Никакой IO в guard. Все17старыхcuts/реальные XAML/UIсценарии сохраняются; перваякопия/evidenceнеперезапускается/неудаляется. + +## Продолжение: владелец состояния деревьев ConfigMaker + +Пользователь снова просит продолжить после28ceef4. Следующая самостоятельная обязанность исходного ConfigMaker — хранение explicit/detected/attached структуры и порядок публикации. ConfigMakerPresetStructure хранит состояние, использует реальные FileInfo/GroupInfo/CoreConfigCommandLine/KeyComparer; преобразование в WinUI nodes остаётся существующим TreeBuilder/Adapter, callbacks ленивые. Без изменения файлов/профилей/UI/порядка уведомлений или защиты от reentry. Host публичные объявления и оба прежних private node setters сохраняются; PropertyChanged sender остаётся host. Current command читается отдельно до extract и после file-node publication; explicit groups и component читаются на прежнем позднем этапе. Частичные изменения при исключении сохраняются. Flags назначаются до group-node publication, availabilityEvent после всех3derivednotifications. Сохранить cold IsVisible/HasGroups true и новые emptyprojectioncollections. Дальнейшая безопасность/доказательство — managedRED/GREEN, обычныйGUI/API, actualcomposition91 и новый native11 на текущемpin; прежние native2/wholebranchreview pins остаются историческими, не объявлять их автоматически проверкой нового продукта. Никакие parallel security/settings/backend реализации не меняются. diff --git a/docs/superpowers/specs/2026-11-10-app-idle-exit-design.md b/docs/superpowers/specs/2026-11-10-app-idle-exit-design.md new file mode 100644 index 00000000..8250d609 --- /dev/null +++ b/docs/superpowers/specs/2026-11-10-app-idle-exit-design.md @@ -0,0 +1,31 @@ +# App: реакция на Store и выход при простое + +Продолжение согласованной декомпозиции ConfigMaker → App → BlockCheck2 после checkpoint2400dee. +Пользователь разрешил самостоятельные решения, проверки и локальные обратимые изменения без срока. +Аудит остаётся входными данными. Отдельная security-сессия сохраняет свою область и рабочее дерево. + +Выделить `internal sealed AppIdleExitController` в `Helper/Basic`. Он отвечает за две связанные политики: +реакцию на StoreStateChanged и проверку возможности Exit. Состояния у него нет; восемь ленивых портов +читают число окон, migration pending, Store и GoodCheck, создают/закрывают PrepareWindow, вызывают Exit +и записывают предупреждение. Конструктор только сохраняет делегаты. Новых валидаций, кэшей, блокировок, +ожидания Task, rollback, reentry guards и политики потока не добавлять. + +Существующие private `App.StoreStateChanged(bool)` и `App.ExitIfIdle()` остаются делегирующими методами. +Store подписывается на прежний метод App, WindowCloseOperations сохраняет App-bound callback ExitIfIdle. +Count читается через `() => OpenWindows.Count`, остальные статические состояния также через lambda. +Prepare создаётся с `activate:false`; Task отбрасывается. Logger получает исходный Exception через порт, +а прежняя категория `nameof(App)` и текст `Cannot update background operation state: {ex.Message}` +формируются в App. Остальные activation/migration/startup/pipe/close/modal/settings правила не меняются. + +Сохранить короткое замыкание и повторные чтения. Pending migration с нулём окон не завершает App; +при ненулевом числе окон следующая проверка Count читает состояние заново. Остановленный Store сначала +закрывает Prepare, затем читает актуальные условия выхода. Исключение из тела Store вызывает Warn, +затем повторный ExitIfIdle; ошибка Warn прерывает fallback, ошибка fallback выходит наружу. Прямой +ExitIfIdle исключения не перехватывает. Синхронные вложенные события выполняются без ограничения. + +Доказательства: linked-source managed characterization порядка, актуальных чтений, ошибок, reentry +и необжидаемого Task; полный suite; обычная GUI x64 Release; source/compiled recorded API. Затем новый +actual-host стенд с настоящими App/owner и инертными конечными действиями, отдельным source manifest, +prelaunch review и postchecks. Нативный ввод допускается только после явной передачи общей UI-очереди. +Сейчас очередь у другого чата; код и CLI-проверки независимы от неё. Проверки не являются доказательством +отсутствия всех регрессий или полной OS isolation. Все старые неуспешные стенды сохраняются. diff --git a/docs/superpowers/specs/2026-11-10-assignment-actions-design.md b/docs/superpowers/specs/2026-11-10-assignment-actions-design.md new file mode 100644 index 00000000..a8df7d28 --- /dev/null +++ b/docs/superpowers/specs/2026-11-10-assignment-actions-design.md @@ -0,0 +1,70 @@ +# BlockCheck2: действия ручных назначений + +Продолжение принятого72c5554. Пользователь поручил продолжать декомпозицию самостоятельно, +без регрессий и подтверждений. Агент выбирает самостоятельный internal BlockCheck2AssignmentActions +для операций Page над назначениями: add site/list, move, remove, clear, quick fix, result notice. +Оставшиеся presentation flags, private setters, UpdateAssignmentView/Buttons и форматирование preview +сохраняются в Page. Работа не меняет model/editor/preset policy, XAML, тексты и форматы. + +Альтернативы: оставить методы в Page сохраняет смешение действий и состояния; перенести одновременно +все assignment properties/notifications расширяет риск reentry и объём. Выбран перенос только +протокола действий, с отдельным узким internal host и private nested Page adapter. Это решение агента, +не новый запрос пользователя. Новых partial частей и public интерфейсов host не будет. + +Перед product edit граница уточнена по переданному координирующей сессией критерию: извлекать +нейтральные небольшие механизмы там, где граница действительно существует. Новый +`Helper/UserExperience/SelectedItemChoiceAction` — static generic механизм с четырьмя портами +selected/choices/chooser/apply; TItem/TChoice reference types. Он ничего не знает о Page, BlockCheck2, +WinUI, notices, Result и пресетах. В нём живут capture/snapshot/optional await/null cancel/apply. +AssignmentActions остаётся небольшим доменным orchestration для notices и коротких команд, а не +новым крупным владельцем всей Page. Иные file-replacement workflows не используют этот механизм: +их whitespace/catch/backend контракты отличаются, общее применение потребовало бы смены поведения. + +Owner constructor только сохраняет IBlockCheck2AssignmentActionsHost. Интерфейс содержит13members: +SelectedStrategy; GetSiteListPaths(item); ChooseSiteListAsync(paths); AddForSite(item); +AddForSiteList(item,path); SelectedAssignment get/set; MoveAssignment(item,offset); +RemoveAssignment(item); ClearAssignments(); UpdateAssignmentView(); +UpdateActionButtons(); Text(key); ShowMessage(severity,title,message). +Все model обращения в adapter читают текущий Page.Result при вызове. Constructor не читает view, +даже null, не запускает manager/component/backend. Public Page методы и private ShowAssignmentResult +сохраняются как forwards. Async list entrypoint возвращает faulted Task для setup faults как прежде. + +Add site: один captured SelectedStrategy, null возвращает; AddForSite на current Result, затем +ShowResult(bool). Add list: captured item, current GetSiteListPaths(item).ToArray() до await; +zero paths возвращает, one path без chooser; multiple paths передаются как тот же snapshot array. +Отказ только path==null, whitespace/empty/path вне списка не валидируются заново. После await +AddForSiteList использует captured item и выбранный путь, но текущий Result. Массив для chooser +остаётся изменяемым, первый путь для single path берётся до chooser. Runtime null в single-path +массиве передаётся apply как прежде: null guard находится только внутри multiple-choice ветки. +Текущий потребитель нейтрального механизма один; существующее повторное использование не заявляется. +Никаких locks/guards/dedup/ +cancellation/catch/ConfigureAwait(false) не добавляется. Одновременные вызовы независимы. + +ShowResult: bool выбирает Success/AssignmentAddedTitle/AssignmentAddedMessage либо +Warning/AssignmentNotAddedTitle/AssignmentDuplicateMessage. Text title читается до message; +ShowMessage вызывается после обоих; UpdateAssignmentView, затем отдельный UpdateActionButtons. +Существующий UpdateAssignmentView уже вызывает UpdateActionButtons: двойной menu update сохраняется. +Исключения локализации/notice/view распространяются прежним экземпляром и обрывают последующие эффекты. + +Move: captured SelectedAssignment; при nonnull и MoveAssignment(current Result,selected,offset)==true +сначала UpdateAssignmentView, затем SelectedAssignment=тот же captured object. Изменение selection +или Result из update callback не меняет объект восстановления. Любой offset передаётся без нормализации. +Remove: null guard; RemoveAssignment, затем UpdateAssignmentView даже если model ничего не удалил. +Clear: ClearAssignments, затем UpdateAssignmentView даже на пустой модели. QuickFix принимает Func +операции: Page closure читает current Result и передаёт captured issue. False возвращает +без UI; true показывает Success/ManualIssueQuickFixCompletedTitle/ManualScopeOverlapAcceptedMessage, +затем UpdateAssignmentView без отдельного UpdateActionButtons. Все live ports/reentry/fault границы прежние. + +Проверки нейтрального механизма используют plain object/string вне BlockCheck2. Domain проверки: +absent-owner RED, literal traces/guards, paths snapshot identity, pending selection/model +changes, independent concurrent choices, cancellation/faulted Task timing, observer/localizer reentry, +exception identity/partial effects. Контрольная мутация повторного чтения selected после await должна +упасть. Full suite, normal GUIx64 Release, source451/compiled452 no losses/+7 prior adds, sizes/diff. +Новый bounded actual125=121прежних+4assignment groups: реальная Page/Result/editor/localizer/preview +formatter/private nested adapter; controlled selection/chooser/status/menu. Новых source cuts и IO нет: +19cuts/25bootstrap sources, прежние3inputs/log/2reports=6newbinfiles. Проверяются live model после chooser, +реальные memory assignments/move/remove/clear/quickfix, original private forward и частичные faults. +Independent prelaunch READY, явная согласованная UI lease, exact committed-security joint, final review. +Full startup/настоящие dialogs/component/backend/visual/wholeOS/ABI не объявляются проверенными. + +Прежние evidence/копии и чужие worktrees сохраняются. Нет deletion/reset/rebase/merge/push/publication. diff --git a/docs/superpowers/specs/2026-11-10-manual-test-session-design.md b/docs/superpowers/specs/2026-11-10-manual-test-session-design.md new file mode 100644 index 00000000..c022b673 --- /dev/null +++ b/docs/superpowers/specs/2026-11-10-manual-test-session-design.md @@ -0,0 +1,69 @@ +# BlockCheck2: жизненный цикл ручного теста + +Продолжение аудита крупных классов после принятого0d8ba6f. Агент самостоятельно выбирает перенос +всего ручного теста из ResultPageViewModel.ManualTesting.cs в internal BlockCheck2ManualTestSession. +Пользователь прямо разрешил автономное продолжение без подтверждений. Форматы, XAML и политика +запуска/остановки не меняются; новая синхронизация, validation, cancellation или исправление старых +гонок не добавляются. Работа остаётся в dev/audit-class-decomposition, без интеграции переписанного main. + +Owner хранит три прежних bool состояния (_isRunning/_isStartingTest/_restoreComponentAfterTest), +без новых PropertyChanged/StateChanged. IsRunning обслуживает прежний public IsManualTestRunning +и lazy selection port. Host сохраняет все public Task методы, private StopTestOnLeaveAsync и +ComponentTasksManager_TaskStateUpdated. Подписан тот же private host method group: Target=Page, +Method=ComponentTasksManager_TaskStateUpdated. Три прежних private host поля удаляются как внутреннее +устройство; публичный API не меняется. Единственный известный потребитель поля _isManualTestRunning — +старый actual selection helper — получает явно проверенный bridge к owner._isRunning. Старый helper +и архивы сохраняются, все его остальные проверки и тексты115PASS остаются прежними. + +Конструктор owner только сохраняет четыре порта: IBlockCheck2ManualTestHost, +Func resolveTasks, Func currentComponentId и hostStateHandler. +Каждая операция сначала вызывает resolveTasks, затем вычисляет ID и вызывает метод уже полученного +receiver. ComponentTasksManager.Instance имеет инициализацию с побочными эффектами; прежний порядок +receiver-before-ID обязателен. Новый BlockCheck2ManualComponentTestTasks хранит переданный manager, +переиспользуя существующий IConfigMakerTestTasks. Существующий ConfigMakerComponentTestTasks не подходит: +он разрешает Instance внутри метода, после получения ID. Его код/потребители не меняются. +Интерфейс host описывает SelectedStrategy, +IsStrategyTestRunning, IsManualTestChecked, GetFullStrategyArguments(item), ConfirmReplacementAsync, +UpdateSelectedStrategy, UpdateAssignmentView, Text, ShowMessage, Warn(Exception), Enqueue(Func). +Приватный вложенный ManualTestHost только проксирует поля/методы Page; публичный класс не реализует +новый интерфейс. Constructor host не обращается к view/manager/ID, в том числе при null view. + +ToggleFromButton: nullable checked==true вызывает Start, остальные значения Stop(true). Toggle +выбирает по _isRunning. Start захватывает item, затем guards null/running/strategy по старому short +circuit. UpdateSelection предшествует GetFullArguments текущего Result с captured item. Guard +!Success/IsNullOrEmpty сохраняет Warning/ManualTesting и ErrorCode либо EmptyArguments. Whitespace +аргументы не нормализуются. Stop(false) вызывается до IsTaskRunning(id); confirm только если running, +отказ возвращает без нового Stop. Restore snapshot=componentWasRunning; Stop(id), flags true/true, +subscribe host handler, UpdateSelection и Started notice остаются ДО try. Try охватывает только +Run(id, captured result.Result) и сброс starting. Catch сбрасывает starting, показывает Error с +string.Format(Text(StartFailed),exception.Message), затем Stop(false). Ошибки notice/format/cleanup +выходят из прежних границ. Pending/конкурентные start/stop не сериализуются и не подавляются заново. + +Stop всегда начинает с UpdateSelection, даже когда уже stopped. Если running: capture restore, +flags running/starting=false, unsubscribe, whitespace guard с первым чтением ID, затем Stop(вновьID), +Restore(вновьID) при captured restore. После этого restore=false, optional Stopped notice, selection, +assignments. Все ID чтения живые, исключения до final updates сохраняют частичное состояние. +Leave при stopped ничего не делает; при running capture restore и сразу сбрасывает ВСЕ три flags, +unsubscribe, один раз читает ID вне try, whitespace возвращает. Только Stop/Restore внутри try, +при ошибке Warn(exception). Ни notice, ни selection/assignments тут не добавляются. Logger host +сохраняет LogSource/строку/receiver-before-exception-formatting и прежний uncaught warning fault. + +StateUpdated short-circuit: running, !starting, OrdinalIgnoreCase currentID, state.Item2==false. +При совпадении очередь принимает async callback: Exited warning, затем Stop(false). Guard только +при постановке, не при доставке; нет dedup/captured component ID. Host Enqueue адаптирует Func +в прежний dispatcher async-void callback с игнорируемым TryEnqueue результатом. Public/private +forwards возвращают owner Task без раннего вызова пользовательских портов; Task fault timing сохраняется. + +Проверки: absent-owner RED, literal traces/guards/partial failures/pending/concurrent/reentry/live IDs/ +restore vs leave difference/captured item/current arguments/real canceled tasks/subscription identity/ +queued callback faults and delivery-time state. TCS ожидания ограничены и освобождаются finally. +Full managed suite, GUIx64 Release, source451/compiled452 shapes без потерь, прежние+7 additions. +Новый bounded actual121=115старых+6manual, realPage/Result/session/localizer/privateforwards/dispatcher, +контролируемые tasks/confirm/status/selection и logger. Один новый boundary файл ManualTesting.cs +заменяет только resolveTasks/currentID и logger; всего19cuts,24bootstrap sources. Один старый +selection helper меняется только на bridge к новому state owner, без ослабления старых asserts. +Новых IO нет: старые3inputs/log/2reportoutputs=6newbinfiles, все прежние source/binary/input/output/ +absence/process checks. Independent prelaunch READY, явный UI handoff, exact security joint и finalreview. +Это composition/lifecycle proof с inert component tasks, не настоящий запуск winws/restore/OS isolation. + +Никаких удалений/reset/rebase/push/merge/publication; чужие worktrees и прежние evidence сохраняются. diff --git a/docs/superpowers/specs/2026-11-10-menu-pruning-design.md b/docs/superpowers/specs/2026-11-10-menu-pruning-design.md new file mode 100644 index 00000000..46372d9c --- /dev/null +++ b/docs/superpowers/specs/2026-11-10-menu-pruning-design.md @@ -0,0 +1,52 @@ +# Postorder pruning for the menu controller + +Issue: https://github.com/lumenpearson/cdpiui/issues/209. Local stage only; integration and +installed-product acceptance remain with #14 and #15. Execution owner is thread01a1bc96 on +dev/audit-class-decomposition. Base a85efec4 contains the exact86417 task policy; product/tests +are still A5. Actual Project fields were read back: In progress/P2/Architecture/Low, G2, +lumenpearson. ConfigMaker/CreateNewConfig/App and TextChangeRelay belong to the other executor. + +Extract only recursive pruning from the519-line MenuBarController. A small System-only +PostOrderTreePruner has one entry point: + +`Prune(IList nodes, Func> children, +Func retain, Action remove)`. + +For each list, capture its starting last index and visit indices backwards. Read the current +node at that index, obtain its child list once, and recursively prune it. Then evaluate the +current retain predicate. If false, invoke remove before RemoveAt(index) on the same list. +Do not copy lists, precompute retention, enumerate forward, retry, catch faults, repair indices, +add cancellation, transactions, cycle guards or null guards. Reentry and list mutation retain +the original algorithm's partial effects and index failures. Null callbacks need not be read +for an empty list. Child-list identity is stable in MenuEntry (readonly get-only List). + +The host keeps strong/weak/retained-child policy in its predicate. The host removal callback +keeps registry removal before physical WinUI removal, including the ignored physical Remove +return value. RemoveAt follows only a successful callback. Other scope, integration, ordering, +identifier, navigation, session and lifetime code remains unchanged. The old private recursive +PruneEntry implementation moves to the utility; no recorded public API uses that private method, +and a source search found no fixture or production reflection binding to it. Do not add an +unused private forwarding method. There is one current consumer, with no invented reuse claim. + +Managed characterization covers reverse roots/children, postorder retention, strong/weak claims, +retained descendants, parent state changed from a child callback, collection identity, failure +order and exception identity, partial removal, live insertion and reentry. A controlled mutation +that evaluates retention before pruning children must fail; restore original source bytes in a +finally block and verify SHA before final focused/full tests. Build normal GUI and compare the +existing source and compiled contract inventories; these are bounded checks, not complete ABI proof. + +Native continuation fixes four new groups,133 total, based on accepted actual129. Use standalone +unactivated real MenuBar/Frame/controller/attached lifetime and identifier properties. Verify weak +scope removal, strong or claimed descendants, branch outcomes and actual physical/logical/registry +composition. No Window activation, navigation, backend, desktop input or new IO is authorized by +this fixture. Existing19 cuts and26 bootstraps stay; one bootstrap adds menu cases (27 total). +All25 previous case partials stay byte-identical. Preserve old129 ordered PASS texts and all +binary/source/input/output/absence/process gates. A separate fresh prelaunch review and explicit +exclusive UI grant are prerequisites to launching. Existing accepted129 is historical baseline, +not new133 evidence. Retain failures and archives; never rerun a one-shot output location. + +Verify an isolated joint source with exact committed securityEE. Obtain fresh independent final +review of this local continuation, update status/map/decision evidence, and add case-specific issue +acceptance. Close #209 completed plus Project Done only after every local criterion is satisfied, +with actual readback. Do not close the broad integration/release parents or claim visual/full +startup/installed behavior from the bounded menu fixture. diff --git a/docs/superpowers/specs/2026-11-10-report-export-design.md b/docs/superpowers/specs/2026-11-10-report-export-design.md new file mode 100644 index 00000000..f54f9797 --- /dev/null +++ b/docs/superpowers/specs/2026-11-10-report-export-design.md @@ -0,0 +1,42 @@ +# BlockCheck2: сохранение отчётов + +Продолжить аудит больших классов после принятого ff9db65, выделив сохранение JSON/text из +BlockCheck2ResultPageViewModel.Export.cs в internal BlockCheck2ReportExport. Это выбор агента в рамках +разрешённого автономного продолжения; поведение, форматы и backend не меняются. + +Конструктор сохраняет семь портов без вызовов: текущий report, picker(title/defaultName/filter), +saveJson(path,report), saveText(path,report), text, show notice и error. Host сохраняет serializer, +публичные SaveJsonReportAsync/SaveTextReportAsync и private SaveAsync(Func) как forwards. +Копирование в clipboard и все соседние обязанности остаются на месте. +Прежний конструктор host допускает null view, пока операции не требуют view. Сохранить эту +отложенность: picker lambda читает поле только при выборе файла; null report exports с null view безопасны. + +SaveJsonAsync/SaveTextAsync повторяют исходные алгоритмы. Null report прекращает работу до любого UI +порта. Затем Text(title), Text(filter), PickSaveFile с точными прежними именами и ключами. Только null +filename означает отмену; empty/whitespace не нормализуются. Guard, локализация picker и сам picker +находятся вне try сохранения. Исключения здесь возвращаются в Task без error notice. Отчёт читается +заново внутри save action после picker; изменения Result/report во время локализации/выбора сохраняются. + +SaveAsync catch охватывает saveAction, await, обе success-локализации и ShowActionMessage. Success +сначала локализует BlockCheck2ActionCompletedTitle, затем BlockCheck2FileSavedMessage. Любая ошибка +этой области передаёт exception.Message в ShowActionError. Ошибка error callback выходит наружу с той +же идентичностью; отмена задачи обрабатывается как error. Не добавлять retry, loading guard, +сериализацию параллельных сохранений, новые catch/cancellation или ConfigureAwait. Pending задачи +и повторные входы сохраняют исходный порядок; каждый вызов использует свой выбранный путь. + +Проверки: absent-owner RED; literal ключи/порядок, cancel/null/empty filename, live report после picker, +изменения report между text callbacks, pending/concurrent/reentry, setup vs save failure boundaries, +real Canceled task, ошибка success notice и exception identity. В тестах setup faults сам вызов до +Assert.ThrowsAsync должен вернуть Task, а не бросить синхронно. Full managed suite, GUI, прежние +source/metadata inventories. Новый bounded actual115 сохраняет старые111 и добавляет4 группы реальной +Page/Report/Localizer/serializer: guard/cancel/порты, JSON текущего Result, text текущего Result, private +SaveAsync/error boundaries и null report после picker. Настоящий picker не открывается; два новых +report-файла пишутся реальным serializer строго в корень binary directory новой F-копии, сохраняются +и читаются обратно. Третий отрицательный путь должен остаться отсутствующим. Других IO, backend, +manual component lifecycle или desktop UI нет. В postchecks разрешены ровно6 новых имён вместо4: +прежние3inputs+log и2report outputs. Нужны independent prelaunch review, pins всех артефактов/исходников, +эксклюзивная очередь, все postchecks и exact security joint. Старые native/actual копии не запускать. + +Не менять настройки, XAML, формат сериализации или security worktree. Все evidence сохраняются; +коммиты локальные, без удаления/reset/push/merge/publish. Проверка композиции с ограниченным report IO +не доказывает full startup, интерактивный picker, visual/XAML поведение или изоляцию всего OS. diff --git a/docs/superpowers/specs/2026-11-10-report-summary-design.md b/docs/superpowers/specs/2026-11-10-report-summary-design.md new file mode 100644 index 00000000..f4346aee --- /dev/null +++ b/docs/superpowers/specs/2026-11-10-report-summary-design.md @@ -0,0 +1,24 @@ +# BlockCheck2: сводка отчёта + +После принятого selection103/docs57ede2c выделить ещё одну самостоятельную обязанность большой +BlockCheck2ResultPageViewModel: выбор severity/title/message для статуса отчёта. Internal sealed +BlockCheck2ReportSummaryPresenter в том же каталоге принимает пять ленивых bool-портов HasReport, +NoBypassRequired, Success, IsBestEffort, IsHttpOnly, Func text и Action +show. Конструктор только сохраняет их; Show повторяет старый ShowReportSummary без новых правил. + +Пустой отчёт читает только HasReport, локализует EmptyTitle затем EmptyMessage и показывает Error. +Иначе severity выбирает NoBypass→Informational, Success→Success, остальноеWarning. Заголовок читает +NoBypass/Success/BestEffort заново, затем message ещё раз; HTTP-only читается только внутри NoBypass. +Text может изменить данные между title/message, Show может повторно войти. Это не атомарный snapshot: +все старые чтения и короткое замыкание сохраняются, исключения идут наружу без частичного показа. + +Host сохраняет private ShowReportSummary и все остальные методы/свойства/XAML/lifecycle. Порты через +lambda читают текущий Result, Text/ShowActionMessage остаются host-bound. Нет новых model/schema/API, +настроек, настоящих компонентов или UI workflows. Работа inline, пользователь уже разрешил выбор +границ/продолжение без подтверждений; security и чужие worktrees остаются отдельными. + +Проверки: absent-owner RED, literal branch keys/precedence/port sequence/reentry/faults; fullsuite/GUI/API. +Новый actual-host107=103старых+4summary groups, realPage/Result/report/Localizer/private forward, +view разрешает только ShowStatus. Новые группы не вызывают UpdateView/OnLoaded/Test/component calls. +Предзапусковое ревью, отдельная UI-очередь, точные артефакты и postchecks, exactsecurityjoint и finalreview. +Сохранять все прошлые pins/копии и их пределы; nativevisual/fullstartup/OS isolation не доказываются. diff --git a/docs/superpowers/specs/2026-11-10-result-selection-design.md b/docs/superpowers/specs/2026-11-10-result-selection-design.md new file mode 100644 index 00000000..50243e59 --- /dev/null +++ b/docs/superpowers/specs/2026-11-10-result-selection-design.md @@ -0,0 +1,31 @@ +# BlockCheck2: состояние выбранной стратегии + +Продолжение после закрытого actual-host97 на product839cc952, docs855dbd3. Пользователь поручил +продолжать декомпозицию самостоятельно без подтверждений и без регрессий. Реальные компоненты, +настройки, security/staging/Update и чужие рабочие деревья не менять. + +Выделить internal sealed `BlockCheck2ResultSelection : ObservableObject` в существующем каталоге +ViewModels/BlockCheck2. Он владеет пятнадцатью свойствами доступности/деталей выбранной стратегии и +алгоритмом UpdateSelectedStrategy. Host оставляет публичные свойства и точные setter accessibility, +перенаправляет их владельцу и пересылает PropertyChanged с host sender. Нового partial или XAML нет. + +Семь ленивых портов: выбранный real BlockCheck2StrategyEvidenceItem; текущий HasSession; +strategyTestRunning; manualTestRunning; CanAddForSiteList(item); Text(key); NotifyMenuStateChanged. +Конструктор только сохраняет порты и исходные default values. Сохраняются все повторные чтения +running/manual, короткое замыкание, захваченный в начале item, порядок setter/локализации/menu и +string.Format с текущей культурой. Null item пропускает HasSession, сбрасывает семь деталей и +локализует выбор; nonnull без session всё равно показывает детали. CanAddForSiteList вызывается до +последнего running guard. Уведомление menu происходит до деталей и может синхронно менять host. +Никакого snapshot, reentry guard, rollback, catch, дедупликации уведомлений или новых валидаций. + +Host сохраняет текущие Result/view/поле strategyTestRunning/поле manualTestRunning, все тестовые, +component lifecycle и assignment workflows. Никаких реальных стратегий/компонентов/сети не запускать. +Прежняя native4/d347 проверка сохраняет свой pin; не выдавать её за проверку нового host wiring. + +Доказательства: managed linked-source real evidence/model/formatter + controlled side-effect ports; +literal notifications/traces/defaults/flags/culture/reentry/partial exception states. Полный suite, +обычный GUI x64 Release, source/compiled recorded API. Затем новый pinned actual-host стенд со старым97 +и real PageViewModel/owner/localizer/session + inert IBlockCheck2ResultPageView; обращаться только к +UpdateSelectedStrategy и свойствам, без OnLoaded/OnUnloaded/Test/Stop/backend. Независимое prelaunch, +эксклюзивная очередь для программного WinUI прогона, postchecks и joint committed security. Финальное +fresh review всего продолжения. Сохранять старые артефакты; результаты имеют ограниченные scopes. diff --git a/docs/superpowers/specs/2026-11-10-selected-strategy-test-design.md b/docs/superpowers/specs/2026-11-10-selected-strategy-test-design.md new file mode 100644 index 00000000..51d40a2d --- /dev/null +++ b/docs/superpowers/specs/2026-11-10-selected-strategy-test-design.md @@ -0,0 +1,41 @@ +# BlockCheck2: одиночная проверка выбранной стратегии + +Продолжение принятого checkpoint e1bcdf8, в рамках аудита больших UI-классов. Выделить из +BlockCheck2ResultPageViewModel выполнение TestSelectedStrategyAsync и представление +ShowStrategyTestResult в internal sealed BlockCheck2SelectedStrategyTest. Решение о границе принято +агентом по прямому разрешению пользователя продолжать самостоятельно; новые функции не добавляются. + +Host сохраняет публичный Task TestSelectedStrategyAsync(), private ShowStrategyTestResult(result), +поле _strategyTestRunning, private setter IsStrategyTestProgressVisible, Text/ShowActionError/ +ShowActionMessage и все остальные методы. Новый объект не владеет компонентами или процессами. +Его конструктор только сохраняет одиннадцать портов: selected item, running getter/setter, progress +setter, update selection, test(item), update assignments, text, issue text, error, show notice. +Тестовый порт lambda обращается к текущему Result во время вызова, а не захватывает модель конструктора. + +TestAsync читает выбранную строку один раз; null прекращает работу без чтения running. Затем guard +running; captured item используется даже при изменении выбора из уведомления. Установка running, +progress и первый UpdateSelectedStrategy остаются ДО try. Исключение здесь не запускает cleanup. +Внутри try await Test(item), повторный UpdateSelectedStrategy и ShowResult. Catch преобразует любое +исключение этой области в ShowActionError(exception.Message). Finally сбрасывает running, progress, +обновляет selection, assignments именно в таком порядке. Исключения catch/finally сохраняют обычную +семантику C#; новые catch/retry/ConfigureAwait/cancellation/сериализация не добавляются. Pending task +держит running, повторный вызов подавляется, cleanup не происходит до завершения. + +ShowResult: без ProbeResult берётся первое issue независимо от severity, иначе fallback failure key. +С ProbeResult сначала вычисляется реальный ProbeSummary и локализуется/форматируется результат, +даже если позднее найден Error issue. Первый Error передаётся issue-localizer/error; без Error +severity Success когда successes == attempts (включая 0 == 0), иначе Warning. Заголовок локализуется +после format и после поиска Error. Используется текущая культура string.Format, issue/localization/ +show callbacks могут бросать и повторно входить. Не применять result.Success вместо старого условия. + +Проверки: literal traces/state, captured row/current ports, pending/faulted/cancelled tasks, pre-try +faults, catch/finally interruption/exception identity, real ProbeSummary/first issue/first Error/empty +attempts/culture/format failure/reentry. Затем full managed suite, GUI x64 Release, существующие +source/metadata inventory checks. Новый bounded actual host сохраняет прежние107 групп и добавляет4: +реальный host/private forward/порты/empty issues; probe/issue presentation matrix; настоящая +sessionless Result.TestStrategyAsync с guards/finally; pre-try и show fault publication. Реальный +backend не вызывается, новые native cuts не нужны. Перед запуском независимое prelaunch review, +эксклюзивная очередь всех UI API, pins и полные postchecks. Это проверка композиции, не visual/full startup. + +Не менять XAML, настройки, форматы, manual component testing, security ветку или чужие worktrees. +Сохранить все старые evidence copies. Коммиты локальные; без удаления/reset/push/merge/publish. diff --git a/docs/superpowers/specs/2026-11-10-transition-sequence-design.md b/docs/superpowers/specs/2026-11-10-transition-sequence-design.md new file mode 100644 index 00000000..ef0f2241 --- /dev/null +++ b/docs/superpowers/specs/2026-11-10-transition-sequence-design.md @@ -0,0 +1,70 @@ +# Последовательность двух групп переходов + +Продолжение принятого9b65f3a по standing authorization пользователя без подтверждений. Координатор +сверил9worktrees/live sessions: другого активного implementer или tracked-WIP UtilityButtonControls +не найдено. Агент выбирает этот536строчный control вместо вмешательства в Store install/backend +или создания нового большого владельца всех анимаций. Security/persistence policy не меняется. + +Самостоятельный нейтральный `Helper/UserExperience/TwoPhaseTransitionSequence` содержит только +механизм двух последовательных групп действий с паузами. System/collections/Task/CancellationToken, +без Button/Visibility/Composition/WinUI/локализатора. Один текущий потребитель, повторное использование +не заявляется. В control остаются составление групп, callbacks/анимации/навигация, настройки, отмена +предыдущей последовательности и тело финализации текущего CTS. Новых partial частей/публичных API нет. + +API: static Task RunAsync(IReadOnlyList<(TItem Item,TState State)> first, +IReadOnlyList<(TItem Item,TState State)> second, Func inspect, +Action apply, Func firstDelay, Func secondDelay, +Func delay, CancellationTokenSource cancellation, Action onFinally). +Конструкторов/состояния нет. Source CTS заимствован: utility не отменяет и не освобождает его. + +Обязательная последовательность: first.Count, затем second.Count читаются по одному разу до любых +действий, transitionCount фиксируется. Первый foreach завершает все first, затем foreach second. +Перечисляются сами переданные списки, без ToArray/Concat/new guards. Для каждого элемента inspect +выполняется до apply, bool захватывается; apply предшествует увеличению индекса. Только если index +меньше исходного transitionCount, вызывается соответствующий delay-selector, затем читается +cancellation.Token, затем delay, затем await в текущем контексте. Последний элемент всё ещё вызывает +inspect/apply, но не delay-selector/token/delay. После await модели/списки/inspect остаются live. +Повторный подсчёт count, cache inspect/вычисление delay до apply или снимок списков — изменение поведения. + +Никакой ранней проверки отмены: уже canceled CTS не подавляет первое действие и одиночный переход. +Даже disposed CTS допустим для empty/single без Token-read, но faulted Task при реальном ожидании. +Setup/inspect/apply/delay failures возвращаются через Task с прежним исключением. Utility сохраняет +прежний catch(any OperationCanceledException) и finally с вызовом onFinally; никаких новых catch и +ConfigureAwait(false) нет. Non-OCE распространяются, OCE из тела подавляются как прежде; исключение +самого onFinally не перехватывается и может перекрыть прежнюю ошибку, как исходный finally. +Host private RunVisibilitySequenceAsync с прежними тремя параметрами становится прямым Task forward, +без дополнительного await/state machine. OnFinally callback содержит прежнее literal тело: освобождает +переданный CTS всегда, обнуляет поле только при ReferenceEquals текущему CTS; старый завершившийся +запуск не очищает более новый. Cleanup выполняется до завершения того же Task, без нового перехода +между контекстами. Это уточнение агента до product edit: внешний async wrapper мог изменить порядок +queued observers относительно финализации. Fire-and-forget вызов/SetButtonVisibilities не меняются. + +Host ports: HasVisibleButtonToTheLeft, Button.Visibility setter; first delay выбирает Reposition или +Hide плюс gap, second — Max(Show,Reposition/2) либо Show плюс gap. Сами selector-выражения выполняются +после apply и только перед нужной паузой. Реальные Task.Delay и lazy CTS.Token остаются прежними. +Max/HasVisible/private forward сохраняют сигнатуры; UISettings и Composition code не переносятся. + +TDD: absent-helper RED; plain object/string states, exact trace/count/order/timing/durations, +no-final-delay, mutable-list/current inspect после await, captured count, independent calls, +pre-canceled/disposed CTS, setup and callback fault identity/Task status, borrowed lifetime и onFinally +ровно один раз/до завершения/ошибка поверх прежней. Контрольная +мутация inspect-after-apply или early cancellation должна упасть; исходные bytes/SHA восстановить. +Полный suite/normal GUIx64 Release/source451/compiled452 no losses и7прежних добавлений, размеры/diff. + +Actual129=125прежних+4bounded utility-control groups, новая immutable F-копия/25oldbootstraps+1, +прежние19cuts без добавления. Реальные UtilityButtonControls constructor/compiled XAML/standalone +Buttons/Visibility/Items/HasVisible/private forward/Task.Delay. UISettings только readonly +AnimationsEnabled; control не добавляется в окно и не получает Loaded, Composition animations и +навигация не запускаются, help/settings/backend не вызываются. Никаких desktop snapshots/input. +Проверить два этапа/применение/финальныйCTS null+Dispose; canceled и старый/new CTS identity cleanup; +single/empty и отсутствие новых IO. Один собственный pending Task проверяется reflection по +StateMachine пинованного.NET8: это доказывает прямой forward, настоящий control predicate/source и +четыре literal duration значения bound selectors без измерения wall-clock. Это fixture-only зависимость +от compiler/runtime implementation, не стабильный API контракт. Newer CTS в identity case — sentinel +замены без запуска второй новой последовательности; независимые concurrent циклы проверены managed. +Один owned DP callback записывает событие до reentry, порядок нескольких WinUI registrations не +предполагается. При teardown timeout не подавляется как ожидаемая task fault. +Visual appearance/full production startup/loaded animations/ +wholeOS/realbackend не заявляются. Все старые125тексты/pins/3inputs/2reports/6newnames/absence/process +gates сохраняются; independent prelaunch READY и явная UI lease перед запуском. Exact security joint, +финальное read-only review с текущими limits. Никаких удалений/rebase/merge/push/чужих worktree правок. diff --git a/docs/superpowers/specs/2026-11-11-class-integration-design.md b/docs/superpowers/specs/2026-11-11-class-integration-design.md new file mode 100644 index 00000000..eecf4d94 --- /dev/null +++ b/docs/superpowers/specs/2026-11-11-class-integration-design.md @@ -0,0 +1,111 @@ +# Accepted class decomposition integration + +Owner: Root under [issue14](https://github.com/lumenpearson/cdpiui/issues/14). Existing Project87 +intake readback confirms In progress/P2/Architecture/Medium/G2/lumenpearson, type:refactor and +area:architecture before implementation. The original issue criteria remain open. + +## Sources and delivery boundary + +Preserve frozen `dev/audit-class-decomposition` at `eebc7e8621b85fa08ee015ea3b7eab1e72c78c5f`, +product `ed390cd416b58ea404f04286f7eace5a66e4320a`, and the peer branch/worktree at final docs +`249bba0143f5929ce5cb75fc09a4ef778aede731`, product `f706f16934695bcb122de63d0442c4ab20f42869`. +Root local209/211/215 and peer208/212/214 are accepted separately. Do not treat rejected9e63b55 +as an accepted dispatcher implementation; consume the complete corrected final peer blobs. + +The GitHub API and local origin/main agree on current default +`6c00c789ee2b37238af30f14cfdaf0f55a278274`. Start new `dev/audit-class-integration` from this +default in the existing isolated Root worktree. Keep all earlier refs and archives. No shared-main +rewrite, deletion, forced push or automatic merge to main is part of this plan. Publication of a +reviewable PR and exact-head CI are within issue14; acceptance remains open if any original criterion +is unverified. Full installed/visual and broader native acceptance remain under issue15. + +SecurityEE `ee4771675956fe213634675f37579362efb7e0eb` is not an ancestor of current main. Its +2320/2398 source compositions are historical compatibility evidence. Do not transplant that entire +branch over current upstream security/localization code. A read-only whole-branch merge-tree probe +found179 conflicts, mostly unrelated security, process and documentation paths. + +The new composition preserves the CURRENT default API, not the unreconciled G1 branch API. +Compared with the separate Root/G1 snapshot, current main already has one GUI optional-argument +change (localized emergency-window defaults) and three Core MSI/pipe signatures without the +expectedSha256 parameter. Source comparison proves exactly the same differences before and after +this composition; none is introduced by the decomposition. Do not claim zero drift against the full +historical Root/G1 surface. Issue13/PR10 remains open and draft for G1/ancestry reconciliation; the +historical audit-defects checkout/EE ref remain intact, with no confirmed active G1 execution chat. +Do not take over those security files. Publish this G2 change as a draft with the dependency visible; +do not mark14 accepted or merge to main while its required reconciliation/acceptance remains open. + +## Scoped source composition + +Derive Root's exact changed paths from base `f39e8a0a7267e4fcd4a02eef186a3ee08df8dcd9` to +producted390, restricted to CDPIUI/CDPIUI.Core/CDPIUI.Tests. The184 paths overlap current default +changes at only App.xaml.cs, the test project, and its two README files. Preserve current default +outside the declared decomposition delta, including all security, localization and workflow files. + +For uncontested paths, copy the exact reviewed Root blob. For App.xaml.cs use a recorded three-way +merge (default / f39 / Root); the read-only probe is clean and retains both default emergency/theme +recovery and StartupInitialization plus all Root owner construction. Verify semantic method bodies, +not only required substrings. Keep default README prose and append current test guidance if needed. + +Start test XML from current default, which intentionally removes the old DirectoryAclGuard source +link and adds EmergencyRecovery/StartupInitialization. Append only Root's additive item delta from +f39, then the peer additions. Deduplicate by item kind+Include; reject conflicting metadata, +package-version or property edits. The accepted additive delta includes the existing Unidecode.NET +test reference at the unchanged central2.1.0 version, needed by the linked registry; restore assets +after composition. Keep every default item, deliberate removal and nonadditive property unchanged. +Never restore a removed default link merely because it existed in the older Root baseline. + +Then apply the peer's10-path scoped delta from common +`a5a1b9ba512073d75267943cafba9bc1eddb86b3` to finalf706. It owns App.Modal, ConfigMaker main, +CreateNewConfig.Navigation, three new System helpers and their three test classes, plus additive +project links. Each existing host must still equal its expected common/Root content before replacing +it. Preserve the sync Action and async Func dispatcher paths and rejecting-context tests. +No new product behavior or rule framework is proposed. Do not create tests that merely mirror a merge; +run the accepted behavior suites on the newly composed source. + +Record every repository path's source pin, byte hash, merged XML and the precise exceptions. Import +owned decomposition documentation without overwriting newer upstream governance/localization docs. +Retain source provenance and prior contributor history through explicit source references and frozen +branches; this scoped transplant is a new integration commit, not a claim that prior branches merged. + +## Verification and native union + +Run fresh current-default tests/GUI first and preserve its compiled API inventories. Then qualify the +new composed SHA with focused state-owner tests, full suite, Release/x64 GUI and source/compiled +public contract comparisons against current default and the accepted Root surface. All current default +source outside declared inputs must remain exact. Investigate a failure before editing its cause. + +The proposed union corpus is149: Root137 exact prefix, then relay4, named-loader4 and dispatcher4. +Project its labels onto the accepted peer141 corpus and require the same order. Keep old case bytes +where private probes still apply; any necessary private bridge adaptation must be explicit and preserve +all assertions, with exact original/delta evidence. Never infer a union pass from prior137/141. +Expected31bootstraps: Root27 case partials + peer3 + one main; verify actual filenames and duplicates. + +Prepare a fresh immutable archive only after source checkpoint. Derive exact source cuts before build; +the initial proposal retains the21 existing cuts, including only the two preference endpoint files. +Current default publishes pending StartupInitialization.Ready before real startup. The fixture replaces +real startup, so complete this actual owner with Start(() => Task.CompletedTask) inside its existing +App constructor cut; do not remove or replace the production readiness helper. This is fixture setup, +not proof of real startup. Localizer setup reads only owned packaged Strings using the current builder; +do not call the real settings-reading application initializer. Verify generated JSON/resource packaging. + +Keep typed in-memory Search/font endpoints, separate Search constructor and explicit font evidence, +owned logger restoration before dispatcher groups, and synchronization-context restoration in finally. +Review all constructor transitive paths and current resource inputs. No real backend/preferences, +desktop input, activation of foreign windows, privilege request or real component execution. +Measure the actual fresh binary filename count; preserve all prior filenames and allow only the same +six owned input/log/report additions. Pin sources/resources/binaries/runner/verifier before launch. +Require independent pre-build source and post-build prelaunch reviews and a new exclusive UI grant. +Run once, retain all149 results/streams/IO/hash/process proofs, then idle/requestfalse/release. + +Existing unloaded selector graphs may remain event-rooted until the bounded process exits. Timer +stop/unattached state is a narrower claim than full lifecycle or GC detachment. Native corpus coverage +does not establish full startup/visual/installed behavior. Preserve all prior and rejected artifacts. + +## Review and publication + +Fresh independent review must inspect default readiness/emergency behavior, all accepted state-owner +contracts, exact source/XML provenance and runtime proof. Resolve actionable findings with meaningful +verification. Refresh the default branch before publication and handle any new overlap explicitly. +Prepare the PR description and required metadata, publish the isolated branch, and verify checks on +the exact final PR HEAD. Record integration only when actually performed; no broad issue14 closure +from a local commit, larger test count or successful bounded fixture alone. diff --git a/docs/superpowers/specs/2026-11-11-configuration-variable-projection-design.md b/docs/superpowers/specs/2026-11-11-configuration-variable-projection-design.md new file mode 100644 index 00000000..35203f00 --- /dev/null +++ b/docs/superpowers/specs/2026-11-11-configuration-variable-projection-design.md @@ -0,0 +1,62 @@ +# Configuration variable read-model projection + +Local issue211, basec089265/source174d1cb. The historical audit lists ConfigurationService among +large classes; it is443lines at this source. This pass extracts only its boolean/choice read-model +loops. Actual Project intake55 was read after reload: In progress/P2/Architecture/Low/G2/lumenpearson, +type:refactor+area:architecture. Dependency209 is closedcompleted/actualDone. Root owns this Core +service/new helper/tests; peer212 owns CreateNewConfig.Navigation/LoadVars and its named loader, +peer208 owns its accepted relay; ConfigMaker/Create/App remain outside this implementation. + +Add a small internal stateless ConfigurationVariableProjection under Configuration/Helpers: +`List ToVariableItems(Dictionary jparams)` and +`List ToCommaVariableItems(ConfigItem configItem)`. +This is a coherent adapter to existing domain models, not a generic Select framework or a new +large service. It uses no WinUI/backend/settings/DB/filesystem, state, interfaces or new packages. +No public API is added. Preserve private ToVariableItems as a used forwarding method for both +public GetVariables overloads; GetCommaVariables keeps its original FindItem and null guard. + +Boolean projection enumerates the original dictionary, in the order supplied by the source dictionary and with stored spelling; +each call allocates a new list and new models, setting name then value, leaving variable_name null. +Static GetVariables(null) and a null jparams still throw as before; instance missing item/dictionary +still returns a fresh empty list. FindItem's ordinal file/pack lookup, locks and all mutation methods +remain unchanged. Returned model mutations do not update the underlying dictionary. + +Comma projection receives the captured ConfigItem itself. The dictionary expression is evaluated +at the original foreach point; metadata is read from its current availableCommaVarsValues at each +iteration. Do not pass an earlier metadata snapshot, build a lookup, cache results or normalize keys. +FirstOrDefault uses OrdinalIgnoreCase on VarName; duplicate matches keep the first metadata row. +Options use Distinct(StringComparer.Ordinal).ToList(), preserving first occurrence/case variants, +then initializer order name/comment/value/values. Keep the raw current value even if absent from +options, null or empty. Missing metadata has a null comment/empty list; null Values also gives a +fresh empty list. Each returned options list is independent even when two keys share metadata. +Runtime-null metadata entries retain lazy first-match failure/short-circuit boundaries. Empty +dictionaries never inspect malformed metadata. Do not catch/repair errors or change source models +(including CurrentValueIndex). The helper's null-forgiving annotation adds no runtime guard. + +Tests invoke the actual public Core facade with owned ConfigItem/AvailableVarValues and SetConfigItem, +without Init/Save or private reflection. Keep service guards and observable result ownership/order/ +comparers/nulls. Characterization is expected GREEN on the original implementation. A deliberate +original first-match mutation must fail before extraction; restore exact bytes/SHA, then extract. +Repeat the mutation against the extracted helper: a RED proves the facade actually executes it, +then restore exact bytes and run focused/full GREEN. No helper-existence test, public test seam, +InternalsVisibleTo or duplicate source-linked Core helper is needed. + +Capture pre-change Core source and actual assembly before extraction. Compare after Core source and +compiled public shapes with the existing bounded analyzers; do not claim complete ABI compatibility. +All605 GUI sources must remain equal to174. Build normal Release/x64 GUI, retain normal binaries and +compare its recorded public metadata. Native WinUI launch is not relevant to these pure Core loops: +actual public facade execution on Windows tests the changed behavior and assembly composition; +UI types/bindings/startup are untouched. Historical133 belongs to174, not new-Core execution proof. +Any later scope change into UI/native requires a revised contract and exclusive grant. + +Joint snapshots MUST overlay CDPIUI.Core as well as CDPIUI and CDPIUI.Tests. Earlier GUI-only +snapshot builders would omit this change and could pass behavior tests against the old implementation. +Use exact committed SecurityEE and committed peer relay/navigation when available, full source/blob/ +XML reconstruction, no deletions or WIP, one-shot fresh F directories. Verify every expected file and +only the empty generated Secret extra outside build outputs. Keep original failed attempts and archives. + +Obtain fresh independent review of this continuation and current evidence, update plan/status/map and +decision ledger. This accepts a LOCAL source/test/build result only. Publish/merge, final-PR-HEAD CI, +installed product and broad native acceptance remain with14/15. After scoped acceptance, immediately +record issue211completed plus actualProjectDone/readback in the same working turn. No user confirmation +is needed under the continuing authorization; all Root UI calls remain paused. diff --git a/docs/superpowers/specs/2026-11-11-diagnostic-highlighting-design.md b/docs/superpowers/specs/2026-11-11-diagnostic-highlighting-design.md new file mode 100644 index 00000000..39801270 --- /dev/null +++ b/docs/superpowers/specs/2026-11-11-diagnostic-highlighting-design.md @@ -0,0 +1,81 @@ +# Diagnostic highlighting update state + +Local issue215, base80c1ec2/source00f39. ActualProject69 read after reload: In progress/P2/Architecture/ +Medium/G2/lumenpearson, type:refactor+area:architecture+area:native-qa. Prerequisite211completed/Done64 +is verified. Root owns only ConfigMakerUserControl.Editor.cs (157lines of828 across five partials), +new Helper/UserExperience/DiagnosticHighlightingUpdater.cs, tests/source link and evidence/docs. +Peer owns ConfigMakerViewModel208, CreateNavigation212 and App.Modal/DispatcherTaskBridge214. +No XAML, other control partial, VM, Core, preferences, persistence or format changes. + +The helper is a small System-only state owner, one current consumer, not a framework or a large +transplanted host. State is one last-requested signature initialized to string.Empty; Reset sets it +to string.Empty without replacing the helper. API: + +`void Update(string background, bool isLight, Func> diagnostics, +Func isError, Func isWarning, Func token, +Action apply)`. + +Run diagnostics().Where(isError).Select(token).ToArray() completely before obtaining diagnostics() +again for Where(isWarning).Select(token).ToArray(). Do not fuse passes, cache the enumerable or +preproject Source: ConfigMakerDiagnosticViewModel.Source is mutable. Host predicates and selector +must read item.Source separately, exactly as before. Preserve ordering, duplicates, runtime nulls, +fault identity/timing, and current reads during collection. Reentry/reset during collection must +compare against the current signature after collection, not a signature captured on entry. + +Build exactly $"{background}|{isLight}|{string.Join(',', errorTokens)}|{string.Join(',', warningTokens)}". +Compare current stored key with StringComparison.Ordinal. Unchanged keys still collect both arrays. +For a new key, store it immediately BEFORE apply(isLight,errorTokens,warningTokens). No catch/restore, +retry, queue, lock, cancellation or token normalization. A callback failure is sticky; collection +faults do not commit. Same-key callback reentry skips application; different-key inner state survives +the outer return. Preserve null/empty and comma/pipe signature collisions as existing behavior. + +The host keeps its literal captured background and short-circuit forced-dark/ActualTheme/App.CurrentTheme +expression. The callback keeps CommandEditor.SyntaxHighlighting assignment, including its receiver/RHS +evaluation and highlighter constructors, BEFORE reading/assigning TextControlBoxDesigns to Design. +Do not eagerly capture CommandEditor, build a highlighter or read designs before collection. Replace +only the old signature field with a readonly helper instance and its three usages. Reset remains +after EditorPanel.Background assignment succeeds and before ApplyEditorTheme. No disposal/constructor +forwarding/new public API is needed. Per-call delegates are a bounded allocation cost, not a reason +to cache current callbacks or sources. + +TDD uses plain objects/strings and traces, no fake WinUI. Cover two reads/passes, mutable Source and +collection reset/reentry, repeated-key collection, raw keys/collisions, exception identity and sticky +commit, same/different-key callback reentry, reset identity and per-instance independence. Watch +missing-helper RED and a controlled commit-after-callback mutant fail with bounded nested reentry; +restore exact bytes/SHA in finally, then focused/full GREEN. Build normal GUI and compare bounded +source/compiled contracts. Source/metadata inventories do not certify full ABI or visual behavior. + +Native design fixes four new groups=137 based on accepted menu133 (a different case set from peer +named-loader137). Keep all26old case partials byte-identical and add one new partial=28bootstraps. +Use real unactivated ConfigMakerUserControl/compiledXAML/TextControlBox/VM diagnostics, assert unchanged +refresh highlighter identity, replacement after reset/token changes and independent control state. +No Loaded, navigation, focus, desktop input, renderer/frame timing or real preferences/backend. +Selector/UI callback faults and synthetic reentry remain managed/source proof, not native notification +claims. Own VM diagnostics timers/background cancellation are stopped on teardown. + +IMPORTANT prelaunch isolation ruling: accepted menu133 has19cuts and does NOT cut SearchUserControl +or ConsoleFontHelper. InitializeComponent constructs SearchUserControl (two immediate SEARCH reads). +Generated x:Bind registers its ConsoleFontHelper.Instance update on Loading; constructing the +unloaded control does not prove that this singleton is initialized. The fixture explicitly accesses +the isolated font singleton separately, verifies its fixed typed values/covered read keys and two +bounded FontSize setter writes, then restores size12. Constructor Search reads use fresh per-key +baselines and must each increase once. Before native build, add +exactly two fixture-only preference boundary files: Controls/Universal/SearchUserControl.xaml.cs and +Helper/UserExperience/ConsoleFontHelper.cs. Replace ONLY their SettingsManager Get/Set endpoints with +typed owned literal/in-memory callbacks; keep UI constructors, setters, events and highlighting source +unaltered. Explicit new total21cuts, no new IO. Pin all replacements; require no remaining SettingsManager +endpoint in those patched files and reject unknown preference keys/types. Never run the real control +before this source-boundary proof. Retain the old19 boundaries/IO gates and independently review the +exact new prelaunch scope, source pins and asInvoker/freshness/process gates before any launch. +Do not modify product preferences or accepted old fixtures to obtain this isolation. + +Four intended groups: real constructor/unchanged-refresh cache; real diagnostic changes and resulting +highlighter identity; real ApplyEditorBackground reset and brush/highlighter update; independent cache +state across two owned controls. If precise assertions need refinement, settle and ledger them before +building. No full visual/startup/installed acceptance is inferred from this bounded composition. + +Use fresh committed-Security and available accepted peer source joint, complete Git/blob/XML proof, +full tests/GUI and independent final review. Peer214old9e is rejected after an Important sync-context +finding; only corrected/verified pins can be accepted. Keep all failures/archives/oldpins, no destructive +operations or time-based UI takeover. After all local215criteria pass, record acceptance and immediately +closecompleted+actualProjectDone/readback. Parent14/15 integration/broadernative remain open. From 5bc845919c6f233874e9f7eaa74aec37769878e0 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:05:40 +0300 Subject: [PATCH 02/31] Record the qualified native class integration corpus The union fixture executed all 149 groups under the exclusive UI grant. It preserved the Root prefix, peer projection, source and binary inputs, packaged translations and owned IO boundaries. The process exited and the queue was released after all postchecks. Current documentation distinguishes Project 7 from its UI grant version. The independent final review and exact PR HEAD checks remain pending, and the G1 reconciliation remains separate. Refs #14. Changed files: - "docs/superpowers/plans/2026-11-11-class-integration.md" (+6/-6 lines). - "docs/superpowers/reports/2026-11-11-class-integration-source.md" (+42/-7 lines). - "docs/superpowers/specs/2026-11-11-class-integration-design.md" (+2/-2 lines). The file counts compare the staged tree with its first parent. Staged-Tree: 08236f09ba9c74210019a488f01a1c3710a1f075 --- .../plans/2026-11-11-class-integration.md | 12 ++--- .../2026-11-11-class-integration-source.md | 49 ++++++++++++++++--- .../2026-11-11-class-integration-design.md | 4 +- 3 files changed, 50 insertions(+), 15 deletions(-) diff --git a/docs/superpowers/plans/2026-11-11-class-integration.md b/docs/superpowers/plans/2026-11-11-class-integration.md index dcaa61f9..9e91dc80 100644 --- a/docs/superpowers/plans/2026-11-11-class-integration.md +++ b/docs/superpowers/plans/2026-11-11-class-integration.md @@ -41,24 +41,24 @@ implementation or interface framework is introduced. Interfaces: current default + reviewed Root/peer blobs → composed source/provenance manifest. -- [x] Record default API SHA and actual Project87 fields, preserve frozen Root/peer refs and oldnormal100E +- [x] Record default API SHA and actual Project 7 fields under UI grant v87, preserve frozen Root/peer refs and oldnormal100E artifact, then create new integration branch in the already isolated worktree. - [x] Run fresh default tests/GUI and preserve source/compiled baselines. ExpectedGREEN; on failure investigate rather than attributing a pre-existing problem to the transplant. -- [ ] Compose scoped Root/peer Git blobs, clean App three-way merge and additive current-default XML; +- [x] Compose scoped Root/peer Git blobs, clean App three-way merge and additive current-default XML; preserve all upstream non-owned paths and relevant owned documentation, record full provenance. -- [ ] Focused/full GREEN, normal GUI0-0 and API0unintendedloss; verify exact complete input/tree/XML +- [x] Focused/full GREEN, normal GUI0-0 and API0unintendedloss; verify exact complete input/tree/XML proof and source checkpoint. Commit only the named source and reviewable documentation. ### Task 2: Qualify the actual native union Interfaces: composed source pin → immutable149 fixture/source/build/pins/runtime proof. -- [ ] Preflight Root137+peer12 exact source/case labels/private probes/context/logger/readiness/resource +- [x] Preflight Root137+peer12 exact source/case labels/private probes/context/logger/readiness/resource inputs; prepare a fresh archive, exact boundaries/counts/31bootstraps, independent pre-build review. -- [ ] Compile0-0, pin actual binaries/resources/source/runner/verifier and actual fresh filename count; +- [x] Compile0-0, pin actual binaries/resources/source/runner/verifier and actual fresh filename count; independent prelaunchREADY plus new explicit exclusive UI grant. -- [ ] One149unique/Root137prefix/peer141projection/COMPLETE/exit0 run, then all source/IO/hash/streams/ +- [x] One149unique/Root137prefix/peer141projection/COMPLETE/exit0 run, then all source/IO/hash/streams/ owned-process checks, idle/requestfalse/release. Preserve any failed/rejected attempt intact. ### Task 3: Final review and publish the qualified revision diff --git a/docs/superpowers/reports/2026-11-11-class-integration-source.md b/docs/superpowers/reports/2026-11-11-class-integration-source.md index c63dc4e5..be268d9f 100644 --- a/docs/superpowers/reports/2026-11-11-class-integration-source.md +++ b/docs/superpowers/reports/2026-11-11-class-integration-source.md @@ -3,7 +3,7 @@ Owner: [issue14](https://github.com/lumenpearson/cdpiui/issues/14), Root, `dev/audit-class-integration`, existing isolated checkout `C:/Users/lumen/.codex/worktrees/audit-class-decomposition/cdpiui`. -Actual Project87 intake: In progress/P2/Architecture/Medium/G2/lumenpearson, type:refactor and +Actual Project 7 intake, verified under UI grant v87: In progress/P2/Architecture/Medium/G2/lumenpearson, type:refactor and area:architecture. No broad integration acceptance or main merge is recorded. ## Source provenance @@ -65,10 +65,45 @@ execution owner was confirmed. Its EE checkout/ref is preserved. This stage does chat, change MSI/security/pipe code, waive G1 acceptance, or merge PR10. The G2 PR must remain draft with the dependency visible; issues13/14/15 stay open while their criteria remain incomplete. -## Remaining qualification +## Actual union149 qualification -A new named committed source pin, immutable union149 native fixture, independent source/prelaunch -and final reviews, and exact-head PR CI are the next gates. Proposed149 preserves Root137 prefix -and the peer141 label projection; prior137/141 are separate historical corpora. No union native build -or execution is claimed here. All Root UI calls are paused until a new explicit grant. Full startup, -visual/installed-product and broader acceptance remain separate from the bounded fixture. +Source checkpoint: `b41b724c7d930a1fa9209c75c88ffce5c4775213`,212 owned changed paths including +190 product inputs with their provenance hashes. The normal commit hook refused automatic prose +generation for this large diff. A complete manually validated detailed message passed the same hook; +its exact file inventory was retained. No hook was bypassed and no history was rewritten. + +Immutable fixture: `F:/cdpiui-verify/cdpiui-class-integration-b41b724-20261111`. +Independent pre-build source review reconstructed1574 inputs,21 literal cut files,1553 unchanged, +31 bootstraps with27 Root and3 corrected peer case partials byte-identical,35 allowed extras, +no reparse points and the exact empty Secret template. No helper or App.Modal was cut. The existing +App cut completes the actual StartupInitialization owner with a no-op, replacing fixture startup +only; real application startup and settings initialization remain unexecuted. + +Build:0 warnings/errors,78.82s. Independent post-build review verified54 pins (5 own binaries, +20 packaged resources and29 source/evidence inputs), all522 prior binary filenames/hashes, embedded +asInvoker/uiAccess=false, non-admin execution and fresh paths. All20 packaged resources match their +generated copies, with5206 entries equal to the current JSON dictionaries. +Fixture DLL SHA256: `EB1A6C7ADD132324467D2FC72DD3D1A7100D72A5C974C64B4C216F5F04463B11`. +Runner SHA256: `7685AC057F2B176DCFF9D97D62BFE7D7D35CC9A04AFB843D787A32E3A565F3D1`. +Verifier SHA256: `72EB07EBD6350E42CAAAD0C0E519161271625186C76F3D20EE84E5FD50655613`. + +After independent READY0Critical/Important, the canonical request was atomically marked ready and +an explicit free88→Root89 grant was read back with every other participant paused. One hidden owned +process ran UTC2026-11-11T09:01:29.6351047Z→09:01:35.2378129+00:00, PID78128, exit0. +All149 unique groups match the declared sequence, preserving exact Root137 prefix and the complete +ordered peer141 projection. One COMPLETE,0 FAIL and empty stdout/stderr were recorded. + +All54 pins, every522 prior binary hash and all packaged resources remained unchanged. Source and +boundary proofs passed after execution. Three literal inputs16/16/15 bytes and two real serializer +golden reports354/260 bytes with exact fields/hashes were retained. Only six declared filenames +were added (522→528); forbidden outputs were absent. Normal GUI D1B46B remained unchanged. +The owned process is gone. Idle receipt/requestfalse/all-UI-paused state preceded guarded89→90 +release, owner null. No CUA, desktop input, foreign window, privilege or real backend/MSI action occurred. + +Raw evidence in the new workspace includes `native-execution.log`, `class-integration-host-*`, +`native-approved-pins.json`, `native-build-baseline.json`, `native-accepted-corpora.json`, +`native-explicit-grant-v89.json` and `native-owner-released-v90.json`. +The existing intentionally unloaded selector graph may remain event-rooted until this bounded +process exits; only timer stop/unattached state is proved. Full visual/installed/startup and G1 +acceptance are separate. Final whole-change evidence/documentation review and exact-head draft-PR +CI remain pending; issues13/14/15 stay open and no main integration is claimed. diff --git a/docs/superpowers/specs/2026-11-11-class-integration-design.md b/docs/superpowers/specs/2026-11-11-class-integration-design.md index eecf4d94..b27856ec 100644 --- a/docs/superpowers/specs/2026-11-11-class-integration-design.md +++ b/docs/superpowers/specs/2026-11-11-class-integration-design.md @@ -1,7 +1,7 @@ # Accepted class decomposition integration -Owner: Root under [issue14](https://github.com/lumenpearson/cdpiui/issues/14). Existing Project87 -intake readback confirms In progress/P2/Architecture/Medium/G2/lumenpearson, type:refactor and +Owner: Root under [issue14](https://github.com/lumenpearson/cdpiui/issues/14). Existing Project 7 +intake, verified under UI grant v87, confirms In progress/P2/Architecture/Medium/G2/lumenpearson, type:refactor and area:architecture before implementation. The original issue criteria remain open. ## Sources and delivery boundary From bc5cdf74d119b9ef4fcc27f058e8f597f82d5e82 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:07:24 +0300 Subject: [PATCH 03/31] Clarify the native integration source boundaries The source report now names the behavior owners that remain uncut in the native fixture. The original broad statement could also include the external-operation adapters that are deliberately isolated. The corrected text distinguishes App.Modal, StartupInitialization and the final peer case helpers from the documented 21 boundaries. The existing resource, source and binary evidence is unchanged. The runtime result still has 149 groups and the same exact source checkpoint. Refs #14. Changed files: - "docs/superpowers/reports/2026-11-11-class-integration-source.md" (+4/-2 lines). The file counts compare the staged tree with its first parent. Staged-Tree: 482a97b81adc5a0722df3b19c670165ba1b3cafd --- .../reports/2026-11-11-class-integration-source.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/superpowers/reports/2026-11-11-class-integration-source.md b/docs/superpowers/reports/2026-11-11-class-integration-source.md index be268d9f..2f4463ba 100644 --- a/docs/superpowers/reports/2026-11-11-class-integration-source.md +++ b/docs/superpowers/reports/2026-11-11-class-integration-source.md @@ -75,8 +75,10 @@ its exact file inventory was retained. No hook was bypassed and no history was r Immutable fixture: `F:/cdpiui-verify/cdpiui-class-integration-b41b724-20261111`. Independent pre-build source review reconstructed1574 inputs,21 literal cut files,1553 unchanged, 31 bootstraps with27 Root and3 corrected peer case partials byte-identical,35 allowed extras, -no reparse points and the exact empty Secret template. No helper or App.Modal was cut. The existing -App cut completes the actual StartupInitialization owner with a no-op, replacing fixture startup +no reparse points and the exact empty Secret template. App.Modal, StartupInitialization and the +behavior helpers exercised by the final12 peer groups remain uncut. The documented21 cuts include +ConsoleFontHelper and external-operation adapters. The existing App cut completes the actual +StartupInitialization owner with a no-op, replacing fixture startup only; real application startup and settings initialization remain unexecuted. Build:0 warnings/errors,78.82s. Independent post-build review verified54 pins (5 own binaries, From 72dc16799c4fc12ae7196577e754c76d08489f6c Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:10:06 +0300 Subject: [PATCH 04/31] Record independent review of bounded class integration The plan marks the independent whole-change review and documentation update as complete. The publication, exact-head draft pull request, and required check tasks remain pending. The report records reviewer acceptance for product revision `b41b724c7d930a1fa9209c75c88ffce5c4775213` and documentation revision `bc5cdf74d119b9ef4fcc27f058e8f597f82d5e82`. The recorded review found no unresolved Critical, Important, or Minor findings against the stated default revision. The reviewer reproduced product hashes, fixture inputs, pins, baseline hashes, runtime evidence, and queue receipts. The report also records corrections to Project 7 wording and the helper-cut statement. The documented verdict remains limited to the bounded integration evidence. The report excludes real startup, loading, interactive picker, installed-product, garbage-collection detachment, and full historical G1 compatibility. The report keeps publication and exact-head draft pull request checks as subsequent gates. The related issues remain open, and the document claims neither a main merge nor broad issue acceptance. Changed files: - "docs/superpowers/plans/2026-11-11-class-integration.md" (+1/-1 lines). - "docs/superpowers/reports/2026-11-11-class-integration-source.md" (+15/-2 lines). The file counts compare the staged tree with its first parent. Staged-Tree: 5819cf9e749ef16d96ae02a421f344b28b4f6c5d --- .../plans/2026-11-11-class-integration.md | 2 +- .../2026-11-11-class-integration-source.md | 17 +++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/docs/superpowers/plans/2026-11-11-class-integration.md b/docs/superpowers/plans/2026-11-11-class-integration.md index 9e91dc80..783771fa 100644 --- a/docs/superpowers/plans/2026-11-11-class-integration.md +++ b/docs/superpowers/plans/2026-11-11-class-integration.md @@ -65,7 +65,7 @@ Interfaces: composed source pin → immutable149 fixture/source/build/pins/runti Interfaces: all source/contract/runtime proofs → independently reviewed exact PR HEAD/checks. -- [ ] Update current docs/provenance/limits; fresh strongest-model independent whole-change review, +- [x] Update current docs/provenance/limits; fresh strongest-model independent whole-change review, resolve actionable findings with the appropriate verification and final source checkpoint. - [ ] Refresh current default, preserve any newer change, prepare exact PR body/metadata and publish isolated branch/PR with Refs#14; verify required checks on final HEAD and read actual metadata. diff --git a/docs/superpowers/reports/2026-11-11-class-integration-source.md b/docs/superpowers/reports/2026-11-11-class-integration-source.md index 2f4463ba..e4d3a5d2 100644 --- a/docs/superpowers/reports/2026-11-11-class-integration-source.md +++ b/docs/superpowers/reports/2026-11-11-class-integration-source.md @@ -107,5 +107,18 @@ Raw evidence in the new workspace includes `native-execution.log`, `class-integr `native-explicit-grant-v89.json` and `native-owner-released-v90.json`. The existing intentionally unloaded selector graph may remain event-rooted until this bounded process exits; only timer stop/unattached state is proved. Full visual/installed/startup and G1 -acceptance are separate. Final whole-change evidence/documentation review and exact-head draft-PR -CI remain pending; issues13/14/15 stay open and no main integration is claimed. +acceptance are separate. + +## Independent review and publication gate + +Fresh read-only reviewer `/root/class_integration_review` accepted the bounded integration at +product `b41b724c7d930a1fa9209c75c88ffce5c4775213` and reviewed documentation +`bc5cdf74d119b9ef4fcc27f058e8f597f82d5e82`, against default6c00:0 unresolved Critical, +Important or Minor findings. The reviewer independently reproduced all190 product hashes +(179 exact Root,9 exact peer,2 composed inputs), current XML and App merge, all1574 fixture inputs, +54 pins,522 baseline hashes, actual149 labels/logs/streams/IO/process and89→90 queue receipts. +The Project 7/UI grant wording and overly broad helper-cut statement were corrected and read back. + +Real startup/Loading/interactive picker/installed-product/GC-detachment and full historical G1 +compatibility remain outside this bounded verdict. Publication and exact-head draft-PR CI are the +next gates. Issues13/14/15 remain open and no main merge or broad issue14 acceptance is claimed. From 36235846fb116acad49b328b29120afa92714712 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:33:29 +0300 Subject: [PATCH 05/31] Record class integration CI corrections Current CI needs inventory records for the imported class decomposition documents while each original author and introduction remains traceable. The added records preserve existing entries and identify Russian design prose from its actual content rather than its filename. An exact historical prose exception keeps the secret scan active and continues to detect different values, paths and synthetic credentials. Local governance and redacted file scans pass after the rejected report quotation was removed from the current documentation. The product source and accepted native artifacts remain unchanged, and the draft still depends on separate G1 and native acceptance. Changed files: - ".gitleaks.toml" (+8/-0 lines). - "docs/governance/document-inventory.json" (+210/-0 lines). - "docs/superpowers/plans/2026-11-11-class-integration.md" (+4/-0 lines). - "docs/superpowers/reports/2026-11-11-class-integration-source.md" (+41/-0 lines). The file counts compare the staged tree with its first parent. Refs: #14 Staged-Tree: 46d8a08287e7957c2f3cbdd1562173ec09187e77 --- .gitleaks.toml | 8 + docs/governance/document-inventory.json | 210 ++++++++++++++++++ .../plans/2026-11-11-class-integration.md | 4 + .../2026-11-11-class-integration-source.md | 41 ++++ 4 files changed, 263 insertions(+) diff --git a/.gitleaks.toml b/.gitleaks.toml index 5854ad8d..b380bfc4 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -21,3 +21,11 @@ condition = "AND" paths = ['''(^|/)docs/audit/findings\.json$'''] regexTarget = "line" regexes = ['''^\s*"key": "4-pipe-framing-failure",\s*$'''] + +[[allowlists]] +description = "Historical class-decomposition test count is not an API credential" +targetRules = ["generic-api-key"] +condition = "AND" +paths = ['''(^|/)docs/superpowers/specs/2026-11-08-class-decomposition-design\.md$'''] +regexTarget = "match" +regexes = ['''^API, actualcomposition91 $'''] diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index d73bdb6b..551fe9b6 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1215,6 +1215,216 @@ "policy": "ASD-STE100 principles for English", "language": "en", "changes": "Record JSON localization implementation, exception recovery requirements, and open delivery acceptance boundaries." + }, + { + "path": "docs/DECOMPOSITION-ACCEPTANCE.ru.md", + "firstIntroduction": "f75c5a4a638898ea4240e7efbdcab59cb6871ffc\tleather147\tdocs: record final decomposition evidence and open gates", + "first_commit": "f75c5a4a638898ea4240e7efbdcab59cb6871ffc", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "ru", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/DECOMPOSITION-DECISIONS.ru.md", + "firstIntroduction": "1d76cbdb099140e0f3ca5eaad546021a3239ef6f\tleather147\tdocs: map decomposition requirements and recorded decisions", + "first_commit": "1d76cbdb099140e0f3ca5eaad546021a3239ef6f", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "ru", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/DECOMPOSITION-REVIEW-MAP.ru.md", + "firstIntroduction": "1d76cbdb099140e0f3ca5eaad546021a3239ef6f\tleather147\tdocs: map decomposition requirements and recorded decisions", + "first_commit": "1d76cbdb099140e0f3ca5eaad546021a3239ef6f", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "ru", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/DECOMPOSITION-STATUS.ru.md", + "firstIntroduction": "bdc9170c5d3370ad0554a140a3841596bfc59cb6\tleather147\trefactor(gui): extract preset, activation and BlockCheck options responsibilities", + "first_commit": "bdc9170c5d3370ad0554a140a3841596bfc59cb6", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "ru", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/plans/2026-11-08-class-decomposition.md", + "firstIntroduction": "bdc9170c5d3370ad0554a140a3841596bfc59cb6\tleather147\trefactor(gui): extract preset, activation and BlockCheck options responsibilities", + "first_commit": "bdc9170c5d3370ad0554a140a3841596bfc59cb6", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "en", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/plans/2026-11-11-class-integration.md", + "firstIntroduction": "b41b724c7d930a1fa9209c75c88ffce5c4775213\tleather147\tApply accepted class owners to current main", + "first_commit": "b41b724c7d930a1fa9209c75c88ffce5c4775213", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "en", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/reports/2026-11-11-class-integration-source.md", + "firstIntroduction": "b41b724c7d930a1fa9209c75c88ffce5c4775213\tleather147\tApply accepted class owners to current main", + "first_commit": "b41b724c7d930a1fa9209c75c88ffce5c4775213", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "en", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/reports/2026-11-11-diagnostic-highlighting-verification.md", + "firstIntroduction": "5805c8334c76d95d9bd301ed423b7cb7844b02ae\tleather147\tRecord highlighting verification and pending native fixture work", + "first_commit": "5805c8334c76d95d9bd301ed423b7cb7844b02ae", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "en", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/specs/2026-11-08-class-decomposition-design.md", + "firstIntroduction": "bdc9170c5d3370ad0554a140a3841596bfc59cb6\tleather147\trefactor(gui): extract preset, activation and BlockCheck options responsibilities", + "first_commit": "bdc9170c5d3370ad0554a140a3841596bfc59cb6", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "ru", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/specs/2026-11-10-app-idle-exit-design.md", + "firstIntroduction": "839cc952b5439548e036a83c6eea78a61d642b61\tleather147\trefactor: extract App idle exit and store state policy", + "first_commit": "839cc952b5439548e036a83c6eea78a61d642b61", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "ru", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/specs/2026-11-10-assignment-actions-design.md", + "firstIntroduction": "a0d031ec49e00bd2b70169af9a1dc53372e33b28\tleather147\tDocument assignment action decomposition and behavior boundaries", + "first_commit": "a0d031ec49e00bd2b70169af9a1dc53372e33b28", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "ru", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/specs/2026-11-10-manual-test-session-design.md", + "firstIntroduction": "3cdadef542e4c5686cad974018bdd8927b7470e0\tleather147\tdocs: plan manual test lifecycle decomposition", + "first_commit": "3cdadef542e4c5686cad974018bdd8927b7470e0", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "ru", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/specs/2026-11-10-menu-pruning-design.md", + "firstIntroduction": "174d1cbf5699455d7768ae2398df4f8f241bddab\tleather147\tExtract live postorder menu pruning into a generic helper", + "first_commit": "174d1cbf5699455d7768ae2398df4f8f241bddab", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "en", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/specs/2026-11-10-report-export-design.md", + "firstIntroduction": "81c419c1330fb85e47e76692266e0132f27bc1e7\tleather147\tdocs: plan report export responsibility extraction", + "first_commit": "81c419c1330fb85e47e76692266e0132f27bc1e7", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "ru", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/specs/2026-11-10-report-summary-design.md", + "firstIntroduction": "93091a13b533897015d8efe789a6aa3aad7ff066\tleather147\trefactor: extract BlockCheck2 report summary presentation", + "first_commit": "93091a13b533897015d8efe789a6aa3aad7ff066", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "ru", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/specs/2026-11-10-result-selection-design.md", + "firstIntroduction": "de3d3821e6b2d0f13f49e179af88175f53213476\tleather147\trefactor: extract BlockCheck2 selected strategy presentation", + "first_commit": "de3d3821e6b2d0f13f49e179af88175f53213476", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "ru", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/specs/2026-11-10-selected-strategy-test-design.md", + "firstIntroduction": "1be51e495c1805b089722a4a074f7edf7ad17c84\tleather147\tdocs: plan selected strategy test decomposition", + "first_commit": "1be51e495c1805b089722a4a074f7edf7ad17c84", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "ru", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/specs/2026-11-10-transition-sequence-design.md", + "firstIntroduction": "93cba4cdf94c14405da28678371aa1bca033ada1\tleather147\tRecord neutral two-phase transition sequence design", + "first_commit": "93cba4cdf94c14405da28678371aa1bca033ada1", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "ru", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/specs/2026-11-11-class-integration-design.md", + "firstIntroduction": "b41b724c7d930a1fa9209c75c88ffce5c4775213\tleather147\tApply accepted class owners to current main", + "first_commit": "b41b724c7d930a1fa9209c75c88ffce5c4775213", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "en", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/specs/2026-11-11-configuration-variable-projection-design.md", + "firstIntroduction": "00f39b1a9be70cb97cebd7290b5f24dac6a5ab47\tleather147\tExtract configuration variable read-model projection", + "first_commit": "00f39b1a9be70cb97cebd7290b5f24dac6a5ab47", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "en", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/specs/2026-11-11-diagnostic-highlighting-design.md", + "firstIntroduction": "ed390cd416b58ea404f04286f7eace5a66e4320a\tleather147\tExtract diagnostic highlighting state into a reusable updater", + "first_commit": "ed390cd416b58ea404f04286f7eace5a66e4320a", + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", + "language": "en", + "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." } ], "current_history_base": "7ead95f7756057f67cd113671a7f84cf422e8d32", diff --git a/docs/superpowers/plans/2026-11-11-class-integration.md b/docs/superpowers/plans/2026-11-11-class-integration.md index 783771fa..0585a23e 100644 --- a/docs/superpowers/plans/2026-11-11-class-integration.md +++ b/docs/superpowers/plans/2026-11-11-class-integration.md @@ -69,5 +69,9 @@ Interfaces: all source/contract/runtime proofs → independently reviewed exact resolve actionable findings with the appropriate verification and final source checkpoint. - [ ] Refresh current default, preserve any newer change, prepare exact PR body/metadata and publish isolated branch/PR with Refs#14; verify required checks on final HEAD and read actual metadata. +- Draft PR216 is published from72dc with API labels/assignee/G2/head/base read back. Its first + GUI/MSI/libraries/tools/CodeQL/metadata checks passed. Governance inventory and one exact prose + false positive required additive CI corrections; their local checks pass. The current PR record + owns final-head CI and actual Project 7 receipts. No merge or broader acceptance follows from publication. - [ ] Record actual achieved acceptance and any remaining14/15 criteria. Close only if all issue14 criteria pass; otherwise leave it in the accurate working state with explicit next evidence. diff --git a/docs/superpowers/reports/2026-11-11-class-integration-source.md b/docs/superpowers/reports/2026-11-11-class-integration-source.md index e4d3a5d2..e12e6a3a 100644 --- a/docs/superpowers/reports/2026-11-11-class-integration-source.md +++ b/docs/superpowers/reports/2026-11-11-class-integration-source.md @@ -122,3 +122,44 @@ The Project 7/UI grant wording and overly broad helper-cut statement were correc Real startup/Loading/interactive picker/installed-product/GC-detachment and full historical G1 compatibility remain outside this bounded verdict. Publication and exact-head draft-PR CI are the next gates. Issues13/14/15 remain open and no main merge or broad issue14 acceptance is claimed. + +## Draft publication and first CI correction + +[Draft PR216](https://github.com/lumenpearson/cdpiui/pull/216) was published with HEAD +`72dc16799c4fc12ae7196577e754c76d08489f6c`, based on current main6c00. API readback confirmed +the draft, exact head/base, type:refactor and area:architecture labels, lumenpearson assignee, +G2 milestone and a mergeable source tree. Project 7 intake uses its own exclusive UI grant; +its actual receipt and the final-head CI result belong to the PR record. + +The [first CI run](https://github.com/lumenpearson/cdpiui/actions/runs/42993863256) passed GUI, +portable layout, installer file-list/MSI, libraries, managed tests, package audit and tools. +[CodeQL](https://github.com/lumenpearson/cdpiui/actions/runs/42993863296) and Contribution metadata +also passed. Two checks failed and were reproduced locally before correction: + +- [Governance](https://github.com/lumenpearson/cdpiui/actions/runs/42993863221) found21 missing + document-inventory entries. The additive correction retains all129 existing records and all + top-level metadata. Each new entry uses the actual first-introduction commit/author from the + frozen historical Root or current integration history, rather than attributing the import as authorship. +- Gitleaks8.30.1 interpreted the historical design's API/test-count prose as a credential. + An exact generic-api-key match exception is limited to that phrase and that document path suffix. + No detector or general path scan is disabled. Both the original72dc file archive and its four + added commits scan clean with the corrected configuration. Three negative controls still detect + a changed count, the same phrase in another file and a synthetic key in the same document. + +The first control sentinel contained `notARealCredential` and was already excluded by the original +default rules; it could not prove key detection. That rejected control and its reports remain intact. +A fresh control uses an inert high-entropy value and passes all three detection assertions. +The tool archive matches the published Windows x64 SHA256 +`D29144DEFF3A68AA93CED33DDDF84B7FDC26070ADD4AA0F4513094C8332AFC4E`. +Local governance now checks150 Markdown files with0 errors; all32 validator unit tests pass. +The first scan extraction also stopped on a PowerShell `tar` alias; explicit `tar.exe` extracted the +still-empty destination without replacing an existing fixture. No product, test, native fixture, +dependency version or accepted binary changed. New-head CI remains a separate required readback. +The first correction report quoted the triggering phrase at another path and correctly failed a +fresh file scan. The report now describes it without repeating that literal; the narrow exception +was not extended. The rejected report scan remains available with the earlier evidence. +Independent review also corrected eight historical design entries from English to Russian after +reading their actual prose; filenames alone did not identify their content language. +The path expression permits a normal scan-root prefix and would also match a nested copy with +the same suffix. That deferred narrowness improvement does not exempt another value or rule; +the exact non-credential literal remains mandatory. No existing repository file has that nested path. From 9262400ec10f6c18c6e23bcfece2586957adb759 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:49:24 +0300 Subject: [PATCH 06/31] Record BlockCheck2 completion presentation design Current completion presentation depends on repeated session reads and callback order that the extraction must retain. The design keeps navigation and result publication in the existing host while a small presenter owns only notice policy. The plan defines focused regression controls, public contract comparison and a fresh source-pinned native qualification before local acceptance. An independent builder found no important design gap and clarified that inert ports prevent backend operations while collaborator construction remains intact. Existing integration and security branches remain frozen, and their broader acceptance issues stay open. Changed files: - "docs/governance/document-inventory.json" (+20/-0 lines). - "docs/superpowers/plans/2026-11-11-blockcheck-completion.md" (+72/-0 lines). - "docs/superpowers/specs/2026-11-11-blockcheck-completion-design.md" (+97/-0 lines). The file counts compare the staged tree with its first parent. Refs: #217 Staged-Tree: 5e39e8abdc28387b09cd2714acfd0e4c559e9dfb --- docs/governance/document-inventory.json | 20 ++++ .../plans/2026-11-11-blockcheck-completion.md | 72 ++++++++++++++ ...2026-11-11-blockcheck-completion-design.md | 97 +++++++++++++++++++ 3 files changed, 189 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-11-blockcheck-completion.md create mode 100644 docs/superpowers/specs/2026-11-11-blockcheck-completion-design.md diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index 551fe9b6..7f428596 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1425,6 +1425,26 @@ "policy": "ASD-STE100 principles for English; preserve historical evidence and original authorship", "language": "en", "changes": "Record class decomposition design, verification and bounded integration evidence under issue14; retain historical revision limits." + }, + { + "path": "docs/superpowers/plans/2026-11-11-blockcheck-completion.md", + "firstIntroduction": "Local BlockCheck2 completion presentation contract under issue217; base36235846fb116acad49b328b29120afa92714712", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Define bounded completion notice extraction, original live-read/notification contracts and named verification; no integrated acceptance." + }, + { + "path": "docs/superpowers/specs/2026-11-11-blockcheck-completion-design.md", + "firstIntroduction": "Local BlockCheck2 completion presentation contract under issue217; base36235846fb116acad49b328b29120afa92714712", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Define bounded completion notice extraction, original live-read/notification contracts and named verification; no integrated acceptance." } ], "current_history_base": "7ead95f7756057f67cd113671a7f84cf422e8d32", diff --git a/docs/superpowers/plans/2026-11-11-blockcheck-completion.md b/docs/superpowers/plans/2026-11-11-blockcheck-completion.md new file mode 100644 index 00000000..e98c4a92 --- /dev/null +++ b/docs/superpowers/plans/2026-11-11-blockcheck-completion.md @@ -0,0 +1,72 @@ +# BlockCheck2 Completion Presentation Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan inline, task-by-task. Obtain a fresh final independent review. + +**Goal:** Extract completion notice policy from the MainPage host without changing observable behavior. + +**Architecture:** A small internal pure presenter reads lazy ports at the original branch points. +The host retains navigation, notice-open and severity/title/message publication. No rule duplication. + +**Tech Stack:** C#/.NET8.0.427, xUnit linked source, WinUI3, Git/blob/API and immutable native evidence. + +**Spec:** [completion design](../specs/2026-11-11-blockcheck-completion-design.md). + +## Global constraints + +- Issue217 actual intake99 is verified; root owns only the named new stage on its isolated branch. +- Preserve frozen PR2163623584, RootEebc/peer249 refs and all historical source/runtime evidence. +- Preserve all public signatures/setters, localization keys, lazy reads, notification sender/order, + nullable raw values, exception identity and reentry. No new package, framework or behavior. +- No real settings/backend/history/network/scan/installation; native work requires reviewed cuts + and a new explicit exclusive UI grant including snapshots/reads. Keep other chats paused. +- Retain evidence/workspaces despite skill cleanup defaults: the user forbids destructive deletion. +- Do not merge main or claim G1/full-native/integrated acceptance;13/14/15 stay separate. + +## Review Focus + +- View navigation and IsResultNoticeOpen callbacks can change state before completion policy starts. +- Repeated State/OperationError/HistorySaveError reads can differ; caches change existing semantics. +- Localization callbacks can change HTTP-only/error/history data before the next original read. +- Publication callbacks can throw or reenter; preserve partial state, sender and outer continuation. +- New native cases must exercise actual MainPage wiring, with old149 cases/cuts correctly attributed. + +### Task 1: Extract and qualify the completion policy + +**Files:** new ViewModels/BlockCheck2/BlockCheck2RunCompletionPresenter.cs; MainPageViewModel.cs; +MainPageViewModel.Progress.cs; Tests/Presentation/BlockCheck2RunCompletionPresenterTests.cs; +Tests.csproj; this plan/design and additive docs/governance/document-inventory.json. + +**Interfaces:** consumes the eight lazy ports specified in the design; produces Show():void, +with one notice publisher call and no mutable invocation state. Host forwards through its original +private HandleRunCompleted and three setters. + +- [ ] Read the design/issue and actual metadata; preserve clean branch/base and API/normal GUI baseline. + Check design with a fresh builder reviewer before implementation. +- [ ] Write focused tests first for state/read/key/short-circuit/null/reentry/exception contracts. + Observe the expected missing component or behavior RED before implementing it. +- [ ] Implement the original policy in the presenter. Keep host lifecycle statements in place and + add constructor wiring without invoking ports. Run focused tests and inspect actual output. +- [ ] Prove a controlled cache/read mutation fails behavior assertions, preserve output, restore + exact bytes/hash and run focused/full GREEN plus normal Release/x64 GUI0warnings/errors. +- [ ] Verify source and compiled public API preservation, exact product footprint and current + governance/secret scans. Record failures/resolution and commit the owned product checkpoint. + +### Task 2: Qualify actual MainPage composition and accept the local stage + +**Files:** new source-pinned F:/cdpiui-verify fixture and retained ignored stage workspace; +dedicated verification report and additive document inventory. Product stays at Task1 checkpoint. + +**Interfaces:** consumes Task1 SHA and accepted union149 source/cases; produces a reviewed fresh +native corpus, actual build/pins and execution/postcheck receipt for this source only. + +- [ ] Read Task1 evidence; derive full Git source inventory, literal cuts, unchanged case partials, + new actual-host cases and exact sequence/count. Preserve fresh paths and all prior fixtures. +- [ ] Independently review isolation/new cases before build, compile0-0, then pin real binaries, + resources, source, runner/verifier and all preexisting output names/hashes. Obtain READY. +- [ ] Coordinate a new explicit exclusive lease, run the owned bounded process once, validate + exact pass labels/COMPLETE/exit0/streams/IO/hash/resource/source/absence/process checks, then + publish idle/requestfalse and guarded release. Preserve and diagnose failed attempts. +- [ ] Update evidence/docs; obtain fresh whole-change independent review, fix Critical/Important + with observed RED→GREEN and ledger any rulings/deferred minors. +- [ ] Check all six local issue criteria against named current evidence, post six-section acceptance, + close completed+actual ProjectDone immediately and read back full metadata. Leave13/14/15 open. diff --git a/docs/superpowers/specs/2026-11-11-blockcheck-completion-design.md b/docs/superpowers/specs/2026-11-11-blockcheck-completion-design.md new file mode 100644 index 00000000..d1fbfd3e --- /dev/null +++ b/docs/superpowers/specs/2026-11-11-blockcheck-completion-design.md @@ -0,0 +1,97 @@ +# BlockCheck2 run completion presentation + +## Intent and ownership + +[Issue217](https://github.com/lumenpearson/cdpiui/issues/217) accepts a local behavior-preserving +decomposition of the completion notice in BlockCheck2MainPageViewModel. The user authorized +autonomous continuation without confirmation. The implementation owner chooses this boundary; +it is not a new behavior request from the user. + +Baseline:36235846fb116acad49b328b29120afa92714712, frozen draft PR216. Use +dev/blockcheck-completion-presentation in the existing isolated Root worktree. Peer source families +are released and its frozen refs/artifacts remain intact. Actual Project7 intake under grant99 +confirmed In progress/P2/Architecture/Medium/G2/lumenpearson/two canonical labels after reload. +PR216 remains draft; issues13/14/15 retain their wider acceptance. + +## Chosen boundary + +Extract the contiguous severity/title/message/history-warning policy after IsResultNoticeOpen=true +and before UpdateNavigationButtons in HandleRunCompleted. Keep InputInvalid handling, both step +transitions, the notice-open setter and navigation updates in that private host method. +Keep the three result setters together in a callback supplied by the host. + +Use a small internal BlockCheck2RunCompletionPresenter in the existing BlockCheck2 presentation +folder. It has no WinUI, storage, settings, network, timers or mutable per-call state. Its eight +ports are current state, no-bypass, HTTP-only, operation error, history error, text lookup, issue +formatting and notice publication. The constructor stores them without reading or invoking them. +Show computes with locals and invokes the publisher once. Do not add validation, error recovery, +memoization, a DTO snapshot or a reentry guard. + +This is a domain policy because the existing session states and literal resource keys define it. +A generic notification framework would add abstraction without another matching consumer. +The result-page report summary remains separate: it has different branch rules and keys. + +## Observable contract + +- The original host tests InputInvalid first. Its navigation callback can change current state; + later reads still come from the actual Session. The invalid branch formats issues, updates + navigation and returns without opening or publishing a result notice. +- The other branch navigates to WorkComplete, opens the result notice, then evaluates policy. + PropertyChanged and view callbacks can reenter or change session data before policy reads. +- Test current state at each original if/else-if point. NoBypass is read only when that current + state is Completed. No state read is cached across another callback or branch test. +- The no-bypass branch chooses Informational, localizes its title, then reads HTTP-only to choose + the message key. Other branches preserve Completed, CompletedWithWarnings, Canceled and the + default Error fallback. The chosen branch is not restarted after title localization. +- Failure localizes its title before checking operation error. Preserve separate guard/value + reads; a value can change between them, including to null. Issue formatting is lazy and used + only for a null/empty/whitespace guard result. It can throw with its original exception identity. +- History error is tested after the branch message. When nonblank, concatenate the current + message, Environment.NewLine, localized warning, one space and a fresh history-error read. + Localization can replace the later value. Keep raw whitespace and nullable value behavior. +- Publish severity, title and message in that order through the host's existing SetProperty + setters. Sender identity stays the host. Reentry has independent locals and no guard. + The outer call continues its original publications after an inner call returns. +- Preserve exceptions and already-observed partial effects. A failing text getter or setter + does not get a new catch, rollback or final navigation update. + +## Interfaces and files + +BlockCheck2RunCompletionPresenter constructor: + +```csharp +BlockCheck2RunCompletionPresenter( + Func state, Func noBypass, Func httpOnly, + Func operationError, Func historyError, + Func text, Func formatIssues, + Action publish) +``` + +Show():void is internal behavior through the existing private HandleRunCompleted entrypoint. +The MainPage constructor adds a readonly presenter after the existing CancelCommand assignment. +The host publisher performs the three original property assignments, without snapshots or extra work. +Only the new source file, MainPage constructor and Progress partial change in product code. +The test project adds one linked source item; existing severity/model references are reused. + +## Verification and acceptance limits + +Write focused xUnit tests before host edits. Cover every enum state, exact keys/read order, +short-circuiting, nullable values, localization mutation, nested Show calls and thrown delegates. +Observe at least one meaningful controlled read/cache mutant fail, restore exact bytes/hash and +run focused/full tests. Build the normal GUI and compare baseline source/compiled public APIs. +The current baseline2163/native149 results remain historical until the named new source runs. + +Prepare a NEW immutable source-pinned native fixture from the accepted union149 recipe. Preserve +all prior case partials byte-for-byte; derive counts and pins from actual files. Add narrow actual +MainPage composition cases for invalid early return, navigation/open/publication order, callback +mutation and publication reentry/exception behavior. Existing inert settings/run ports prevent +real settings access and backend/history operations; the Session still constructs its normal +collaborator objects. Do not call OnLoaded or execute a scan. Review all cuts and the new +cases before build/launch; pin actual output/resources/runner/verifier and preexisting filenames. +Acquire a new explicit exclusive UI grant only after READY; prove pass labels, IO/hashes/resources, +streams, owned process exit and idle release. No inferred grant or broad native acceptance. + +One fresh final independent review gates local acceptance. Keep rejected attempts and original +branches/fixtures. No deletion, reset, main merge, installation or G1 ownership change is required. +The local issue can close only with its six verified criteria and actual Project Done readback. +Integration/release acceptance stays with13/14/15 and later draft qualification. From 08678c28f73dfe5c1c154ea112173ef55baa77a1 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:00:13 +0300 Subject: [PATCH 07/31] Extract BlockCheck2 completion notice presentation Current completion notices use a dedicated presenter while the MainPage host retains navigation and ordered result publication. The policy preserves repeated session reads, localization order, nullable error values and callback reentry through eight lazy ports. Focused tests pass after a controlled history cache mutation fails two assertions and the exact original helper bytes are restored. The full managed suite passes all 2201 tests and the normal GUI build has no warnings or errors. Source and compiled public contract inventories show no lost or changed shapes, while native composition remains a separate pending gate. Changed files: - "CDPIUI.Tests/CDPIUI.Tests.csproj" (+1/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2RunCompletionPresenterTests.cs" (+261/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Progress.cs" (+1/-52 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs" (+10/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2RunCompletionPresenter.cs" (+85/-0 lines). - "docs/governance/document-inventory.json" (+14/-4 lines). - "docs/superpowers/plans/2026-11-11-blockcheck-completion.md" (+4/-4 lines). - "docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md" (+76/-0 lines). The file counts compare the staged tree with its first parent. Refs: #217 Staged-Tree: ccedf053d62dfeaaf024dbe69030dba1168feda5 --- CDPIUI.Tests/CDPIUI.Tests.csproj | 1 + .../BlockCheck2RunCompletionPresenterTests.cs | 261 ++++++++++++++++++ .../BlockCheck2MainPageViewModel.Progress.cs | 53 +--- .../BlockCheck2MainPageViewModel.cs | 10 + .../BlockCheck2RunCompletionPresenter.cs | 85 ++++++ docs/governance/document-inventory.json | 18 +- .../plans/2026-11-11-blockcheck-completion.md | 8 +- ...1-11-blockcheck-completion-verification.md | 76 +++++ 8 files changed, 452 insertions(+), 60 deletions(-) create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2RunCompletionPresenterTests.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/BlockCheck2RunCompletionPresenter.cs create mode 100644 docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md diff --git a/CDPIUI.Tests/CDPIUI.Tests.csproj b/CDPIUI.Tests/CDPIUI.Tests.csproj index 70cb49fc..c3eb3f87 100644 --- a/CDPIUI.Tests/CDPIUI.Tests.csproj +++ b/CDPIUI.Tests/CDPIUI.Tests.csproj @@ -52,6 +52,7 @@ + diff --git a/CDPIUI.Tests/Presentation/BlockCheck2RunCompletionPresenterTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2RunCompletionPresenterTests.cs new file mode 100644 index 00000000..a561ce05 --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2RunCompletionPresenterTests.cs @@ -0,0 +1,261 @@ +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.ViewModels.BlockCheck2; + +namespace CDPIUI.Tests.Presentation; + +public class BlockCheck2RunCompletionPresenterTests +{ + [Fact] + public void ConstructorDoesNotReadLocalizeFormatOrPublish() + { + var f = new Fixture(); + Assert.Empty(f.Trace); + Assert.Empty(f.Notices); + } + + [Theory] + [InlineData(BlockCheckSessionState.Idle, BlockCheck2NoticeSeverity.Error, "BlockCheck2FailedTitle", "issues", 4)] + [InlineData(BlockCheckSessionState.InputInvalid, BlockCheck2NoticeSeverity.Error, "BlockCheck2FailedTitle", "issues", 4)] + [InlineData(BlockCheckSessionState.Running, BlockCheck2NoticeSeverity.Error, "BlockCheck2FailedTitle", "issues", 4)] + [InlineData(BlockCheckSessionState.Canceling, BlockCheck2NoticeSeverity.Error, "BlockCheck2FailedTitle", "issues", 4)] + [InlineData(BlockCheckSessionState.Completed, BlockCheck2NoticeSeverity.Success, "BlockCheck2CompletedTitle", "t:BlockCheck2CompletedMessage", 2)] + [InlineData(BlockCheckSessionState.CompletedWithWarnings, BlockCheck2NoticeSeverity.Warning, "BlockCheck2BestEffortCompletedTitle", "t:BlockCheck2BestEffortCompletedMessage", 3)] + [InlineData(BlockCheckSessionState.Failed, BlockCheck2NoticeSeverity.Error, "BlockCheck2FailedTitle", "issues", 4)] + [InlineData(BlockCheckSessionState.Canceled, BlockCheck2NoticeSeverity.Informational, "BlockCheck2CanceledTitle", "t:BlockCheck2CanceledMessage", 4)] + public void EveryStateRetainsSeverityKeysAndRepeatedStateReads(BlockCheckSessionState state, + BlockCheck2NoticeSeverity severity, string title, string message, int stateReads) + { + var f = new Fixture { State = state }; + f.Owner.Show(); + Assert.Equal((severity, "t:" + title, message), Assert.Single(f.Notices)); + Assert.Equal(stateReads, f.Trace.Count(s => s == "state")); + Assert.Equal(state == BlockCheckSessionState.Completed ? 1 : 0, f.Trace.Count(s => s == "no-bypass")); + Assert.DoesNotContain("http", f.Trace); + } + + [Theory] + [InlineData(false, "BlockCheck2NoBypassRequiredMessage")] + [InlineData(true, "BlockCheck2HttpOnlyNoBypassRequiredMessage")] + public void CompletedNoBypassHasPriorityAndReadsHttpAfterTitle(bool httpOnly, string key) + { + var f = new Fixture { State = BlockCheckSessionState.Completed, NoBypass = true, HttpOnly = httpOnly }; + f.Owner.Show(); + Assert.Equal((BlockCheck2NoticeSeverity.Informational, "t:BlockCheck2NoBypassRequiredTitle", "t:" + key), Assert.Single(f.Notices)); + Assert.Equal(["state", "no-bypass", "text:BlockCheck2NoBypassRequiredTitle", "http", "text:" + key, + "history-error", "publish"], f.Trace); + } + + [Fact] + public void CompletedReadOrderDoesNotTouchFailureOrHttpPorts() + { + var f = new Fixture { State = BlockCheckSessionState.Completed }; + f.Owner.Show(); + Assert.Equal(["state", "no-bypass", "state", "text:BlockCheck2CompletedTitle", + "text:BlockCheck2CompletedMessage", "history-error", "publish"], f.Trace); + } + + [Fact] + public void AStateChangeBetweenChecksUsesTheLaterStateWithoutBacktracking() + { + var f = new Fixture { NoBypass = true }; + var states = new Queue([BlockCheckSessionState.Running, BlockCheckSessionState.Completed]); + f.ReadState = states.Dequeue; + f.Owner.Show(); + Assert.Equal(BlockCheck2NoticeSeverity.Success, Assert.Single(f.Notices).Severity); + Assert.DoesNotContain("no-bypass", f.Trace); + Assert.Empty(states); + } + + [Fact] + public void TheThirdStateReadCanSelectWarningsAfterCompletedNoBypassWasFalse() + { + var f = new Fixture(); + var states = new Queue([BlockCheckSessionState.Completed, + BlockCheckSessionState.Running, BlockCheckSessionState.CompletedWithWarnings]); + f.ReadState = states.Dequeue; + f.Owner.Show(); + Assert.Equal(BlockCheck2NoticeSeverity.Warning, Assert.Single(f.Notices).Severity); + Assert.Equal(3, f.Trace.Count(s => s == "state")); + Assert.Equal(1, f.Trace.Count(s => s == "no-bypass")); + } + + [Fact] + public void NoBypassTitleLocalizationCanChangeTheHttpMessage() + { + var f = new Fixture { State = BlockCheckSessionState.Completed, NoBypass = true }; + f.OnStep = step => { if (step == "text:BlockCheck2NoBypassRequiredTitle") f.HttpOnly = true; }; + f.Owner.Show(); + Assert.Equal("t:BlockCheck2HttpOnlyNoBypassRequiredMessage", Assert.Single(f.Notices).Message); + } + + [Fact] + public void TitleMutationDoesNotRestartAnAlreadySelectedCompletedBranch() + { + var f = new Fixture { State = BlockCheckSessionState.Completed }; + f.OnStep = step => { if (step == "text:BlockCheck2CompletedTitle") f.State = BlockCheckSessionState.Failed; }; + f.Owner.Show(); + Assert.Equal((BlockCheck2NoticeSeverity.Success, "t:BlockCheck2CompletedTitle", "t:BlockCheck2CompletedMessage"), Assert.Single(f.Notices)); + Assert.DoesNotContain("operation-error", f.Trace); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" \t\r\n")] + public void BlankOperationErrorUsesLazyIssuesExactlyOnce(string? operationError) + { + var f = new Fixture { OperationError = operationError }; + f.Owner.Show(); + Assert.Equal("issues", Assert.Single(f.Notices).Message); + Assert.Equal(1, f.Trace.Count(s => s == "operation-error")); + Assert.Equal(1, f.Trace.Count(s => s == "issues")); + } + + [Fact] + public void FailureTitleLocalizationPrecedesTheOperationErrorGuard() + { + var f = new Fixture(); + f.OnStep = step => { if (step == "text:BlockCheck2FailedTitle") f.OperationError = " changed error "; }; + f.Owner.Show(); + Assert.Equal(" changed error ", Assert.Single(f.Notices).Message); + Assert.Equal(2, f.Trace.Count(s => s == "operation-error")); + Assert.DoesNotContain("issues", f.Trace); + } + + [Fact] + public void NonblankOperationErrorIsReadAgainAndCanBecomeNull() + { + var f = new Fixture { OperationError = "first" }; + f.OnStep = step => + { + if (step == "operation-error" && f.Trace.Count(s => s == step) == 2) f.OperationError = null; + }; + f.Owner.Show(); + Assert.Null(Assert.Single(f.Notices).Message); + Assert.DoesNotContain("issues", f.Trace); + } + + [Fact] + public void IssueFormattingDoesNotRetryTheOperationErrorAfterMutation() + { + var f = new Fixture(); + f.OnStep = step => { if (step == "issues") f.OperationError = "late"; }; + f.Owner.Show(); + Assert.Equal("issues", Assert.Single(f.Notices).Message); + Assert.Equal(1, f.Trace.Count(s => s == "operation-error")); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" \t\r\n")] + public void BlankHistoryErrorDoesNotLocalizeOrReadItsValueAgain(string? historyError) + { + var f = new Fixture { State = BlockCheckSessionState.Completed, HistoryError = historyError }; + f.Owner.Show(); + Assert.Equal("t:BlockCheck2CompletedMessage", Assert.Single(f.Notices).Message); + Assert.Equal(1, f.Trace.Count(s => s == "history-error")); + Assert.DoesNotContain("text:BlockCheck2HistorySaveFailedMessage", f.Trace); + } + + [Fact] + public void HistoryWarningReadsItsRawCurrentValueAfterLocalization() + { + var f = new Fixture { State = BlockCheckSessionState.Completed, HistoryError = "first" }; + f.OnStep = step => { if (step == "text:BlockCheck2HistorySaveFailedMessage") f.HistoryError = " second "; }; + f.Owner.Show(); + Assert.Equal("t:BlockCheck2CompletedMessage" + Environment.NewLine + + "t:BlockCheck2HistorySaveFailedMessage second ", Assert.Single(f.Notices).Message); + Assert.Equal(2, f.Trace.Count(s => s == "history-error")); + } + + [Fact] + public void HistoryValueCanBecomeNullAfterItsNonblankGuard() + { + var f = new Fixture { HistoryError = "first" }; + f.OnStep = step => { if (step == "text:BlockCheck2HistorySaveFailedMessage") f.HistoryError = null; }; + f.Owner.Show(); + Assert.Equal("issues" + Environment.NewLine + "t:BlockCheck2HistorySaveFailedMessage ", Assert.Single(f.Notices).Message); + Assert.Equal(2, f.Trace.Count(s => s == "history-error")); + } + + [Fact] + public void PublicationCanReenterAndOuterLocalsContinueAfterInnerPublication() + { + var f = new Fixture { State = BlockCheckSessionState.Completed }; + bool nested = false; + f.OnStep = step => + { + if (step != "publish" || nested) return; + nested = true; + f.State = BlockCheckSessionState.Canceled; + f.Owner.Show(); + }; + f.Owner.Show(); + Assert.Equal([BlockCheck2NoticeSeverity.Informational, BlockCheck2NoticeSeverity.Success], f.Notices.Select(n => n.Severity)); + Assert.Equal("t:BlockCheck2CompletedMessage", f.Notices[1].Message); + Assert.Equal(2, f.Trace.Count(s => s == "publish")); + } + + [Theory] + [InlineData("state")] + [InlineData("no-bypass")] + [InlineData("http")] + [InlineData("text:BlockCheck2NoBypassRequiredTitle")] + [InlineData("text:BlockCheck2FailedTitle")] + [InlineData("operation-error")] + [InlineData("issues")] + [InlineData("history-error")] + [InlineData("text:BlockCheck2HistorySaveFailedMessage")] + [InlineData("publish")] + public void DelegateFailurePropagatesTheSameExceptionWithoutStickyState(string point) + { + var f = new Fixture { State = point is "state" or "no-bypass" or "http" or "text:BlockCheck2NoBypassRequiredTitle" + ? BlockCheckSessionState.Completed : BlockCheckSessionState.Failed, NoBypass = true, HistoryError = "history" }; + var error = new SentinelException(); + f.OnStep = step => { if (step == point) throw error; }; + Assert.Same(error, Assert.Throws(f.Owner.Show)); + Assert.Empty(f.Notices); + f.OnStep = null; + f.Owner.Show(); + Assert.Single(f.Notices); + } + + private sealed class SentinelException : Exception; + + private sealed class Fixture + { + public BlockCheckSessionState State = BlockCheckSessionState.Failed; + public bool NoBypass, HttpOnly; + public string? OperationError, HistoryError; + public Func? ReadState; + public Action? OnStep; + public List Trace { get; } = []; + public List<(BlockCheck2NoticeSeverity Severity, string Title, string? Message)> Notices { get; } = []; + public BlockCheck2RunCompletionPresenter Owner { get; } + + public Fixture() + { + Owner = new( + () => Read("state", () => ReadState?.Invoke() ?? State), + () => Read("no-bypass", () => NoBypass), + () => Read("http", () => HttpOnly), + () => Read("operation-error", () => OperationError), + () => Read("history-error", () => HistoryError), + key => Read("text:" + key, () => "t:" + key), + () => Read("issues", () => "issues"), + (severity, title, message) => + { + _ = Read("publish", () => true); + Notices.Add((severity, title, message)); + }); + } + + private T Read(string point, Func value) + { + Trace.Add(point); + OnStep?.Invoke(point); + return value(); + } + } +} diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Progress.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Progress.cs index b8adc042..85a91334 100644 --- a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Progress.cs +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Progress.cs @@ -1,4 +1,3 @@ -using System; using CDPIUI.AddOns.BlockCheck2.Models; using CDPIUI.AddOns.BlockCheck2.Presentation; @@ -117,57 +116,7 @@ private void HandleRunCompleted() GoToStep(BlockCheck2WizardStep.WorkComplete); IsResultNoticeOpen = true; - BlockCheck2NoticeSeverity severity; - string title; - string message; - if (Session.State == BlockCheckSessionState.Completed && Session.NoBypassRequired) - { - severity = BlockCheck2NoticeSeverity.Informational; - title = Text("BlockCheck2NoBypassRequiredTitle"); - message = Text(Session.LastReportIsHttpOnly - ? "BlockCheck2HttpOnlyNoBypassRequiredMessage" - : "BlockCheck2NoBypassRequiredMessage"); - } - else if (Session.State == BlockCheckSessionState.Completed) - { - severity = BlockCheck2NoticeSeverity.Success; - title = Text("BlockCheck2CompletedTitle"); - message = Text("BlockCheck2CompletedMessage"); - } - else if (Session.State == BlockCheckSessionState.CompletedWithWarnings) - { - severity = BlockCheck2NoticeSeverity.Warning; - title = Text("BlockCheck2BestEffortCompletedTitle"); - message = Text("BlockCheck2BestEffortCompletedMessage"); - } - else if (Session.State == BlockCheckSessionState.Canceled) - { - severity = BlockCheck2NoticeSeverity.Informational; - title = Text("BlockCheck2CanceledTitle"); - message = Text("BlockCheck2CanceledMessage"); - } - else - { - severity = BlockCheck2NoticeSeverity.Error; - title = Text("BlockCheck2FailedTitle"); - message = string.IsNullOrWhiteSpace(Session.OperationError) - ? FormatIssues() - : Session.OperationError; - } - - if (!string.IsNullOrWhiteSpace(Session.HistorySaveError)) - { - message = string.Concat( - message, - Environment.NewLine, - Text("BlockCheck2HistorySaveFailedMessage"), - " ", - Session.HistorySaveError); - } - - ResultNoticeSeverity = severity; - ResultNoticeTitle = title; - ResultNoticeMessage = message; + _completionPresenter.Show(); UpdateNavigationButtons(); } diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs index 8481d06d..a2dfa5c4 100644 --- a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs @@ -19,6 +19,7 @@ public sealed partial class BlockCheck2MainPageViewModel : ObservableObject { private readonly ILocalizer _localizer = Localizer.Get(); private readonly BlockCheck2DurationText _durationText; + private readonly BlockCheck2RunCompletionPresenter _completionPresenter; private readonly IBlockCheck2MainPageView _view; private bool _handlersConnected; private BlockCheck2PreparationPreview? _preparationPreview; @@ -42,6 +43,15 @@ public BlockCheck2MainPageViewModel(IBlockCheck2MainPageView view) _view = view; _durationText = new BlockCheck2DurationText(_localizer); CancelCommand = new RelayCommand(CancelFromButton, () => _isCancelEnabled); + _completionPresenter = new BlockCheck2RunCompletionPresenter( + () => Session.State, () => Session.NoBypassRequired, () => Session.LastReportIsHttpOnly, + () => Session.OperationError, () => Session.HistorySaveError, Text, FormatIssues, + (severity, title, message) => + { + ResultNoticeSeverity = severity; + ResultNoticeTitle = title; + ResultNoticeMessage = message; + }); } public BlockCheck2ViewModel Session { get; } = new(); diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2RunCompletionPresenter.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2RunCompletionPresenter.cs new file mode 100644 index 00000000..daa76535 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2RunCompletionPresenter.cs @@ -0,0 +1,85 @@ +#nullable enable + +using System; +using CDPIUI.AddOns.BlockCheck2.Presentation; + +namespace CDPIUI.ViewModels.BlockCheck2; + +// Selects the final notice with the original live reads and localization order. +internal sealed class BlockCheck2RunCompletionPresenter +{ + private readonly Func _state; + private readonly Func _noBypass, _httpOnly; + private readonly Func _operationError, _historyError; + private readonly Func _text; + private readonly Func _formatIssues; + private readonly Action _publish; + + public BlockCheck2RunCompletionPresenter(Func state, Func noBypass, + Func httpOnly, Func operationError, Func historyError, + Func text, Func formatIssues, + Action publish) + { + _state = state; + _noBypass = noBypass; + _httpOnly = httpOnly; + _operationError = operationError; + _historyError = historyError; + _text = text; + _formatIssues = formatIssues; + _publish = publish; + } + + public void Show() + { + BlockCheck2NoticeSeverity severity; + string title; + string? message; + if (_state() == BlockCheckSessionState.Completed && _noBypass()) + { + severity = BlockCheck2NoticeSeverity.Informational; + title = _text("BlockCheck2NoBypassRequiredTitle"); + message = _text(_httpOnly() + ? "BlockCheck2HttpOnlyNoBypassRequiredMessage" + : "BlockCheck2NoBypassRequiredMessage"); + } + else if (_state() == BlockCheckSessionState.Completed) + { + severity = BlockCheck2NoticeSeverity.Success; + title = _text("BlockCheck2CompletedTitle"); + message = _text("BlockCheck2CompletedMessage"); + } + else if (_state() == BlockCheckSessionState.CompletedWithWarnings) + { + severity = BlockCheck2NoticeSeverity.Warning; + title = _text("BlockCheck2BestEffortCompletedTitle"); + message = _text("BlockCheck2BestEffortCompletedMessage"); + } + else if (_state() == BlockCheckSessionState.Canceled) + { + severity = BlockCheck2NoticeSeverity.Informational; + title = _text("BlockCheck2CanceledTitle"); + message = _text("BlockCheck2CanceledMessage"); + } + else + { + severity = BlockCheck2NoticeSeverity.Error; + title = _text("BlockCheck2FailedTitle"); + message = string.IsNullOrWhiteSpace(_operationError()) + ? _formatIssues() + : _operationError(); + } + + if (!string.IsNullOrWhiteSpace(_historyError())) + { + message = string.Concat( + message, + Environment.NewLine, + _text("BlockCheck2HistorySaveFailedMessage"), + " ", + _historyError()); + } + + _publish(severity, title, message); + } +} diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index 7f428596..050f8f5a 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1428,8 +1428,8 @@ }, { "path": "docs/superpowers/plans/2026-11-11-blockcheck-completion.md", - "firstIntroduction": "Local BlockCheck2 completion presentation contract under issue217; base36235846fb116acad49b328b29120afa92714712", - "first_commit": null, + "firstIntroduction": "9262400ec10f6c18c6e23bcfece2586957adb759\tleather147\tRecord BlockCheck2 completion presentation design", + "first_commit": "9262400ec10f6c18c6e23bcfece2586957adb759", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", @@ -1438,13 +1438,23 @@ }, { "path": "docs/superpowers/specs/2026-11-11-blockcheck-completion-design.md", - "firstIntroduction": "Local BlockCheck2 completion presentation contract under issue217; base36235846fb116acad49b328b29120afa92714712", - "first_commit": null, + "firstIntroduction": "9262400ec10f6c18c6e23bcfece2586957adb759\tleather147\tRecord BlockCheck2 completion presentation design", + "first_commit": "9262400ec10f6c18c6e23bcfece2586957adb759", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", "language": "en", "changes": "Define bounded completion notice extraction, original live-read/notification contracts and named verification; no integrated acceptance." + }, + { + "path": "docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md", + "firstIntroduction": "Local issue217 completion policy verification; source checkpoint pending commit", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Record managed tests, mutation rejection, GUI and contract evidence; actual native/final acceptance remains pending." } ], "current_history_base": "7ead95f7756057f67cd113671a7f84cf422e8d32", diff --git a/docs/superpowers/plans/2026-11-11-blockcheck-completion.md b/docs/superpowers/plans/2026-11-11-blockcheck-completion.md index e98c4a92..e7a8c8ae 100644 --- a/docs/superpowers/plans/2026-11-11-blockcheck-completion.md +++ b/docs/superpowers/plans/2026-11-11-blockcheck-completion.md @@ -40,13 +40,13 @@ Tests.csproj; this plan/design and additive docs/governance/document-inventory.j with one notice publisher call and no mutable invocation state. Host forwards through its original private HandleRunCompleted and three setters. -- [ ] Read the design/issue and actual metadata; preserve clean branch/base and API/normal GUI baseline. +- [x] Read the design/issue and actual metadata; preserve clean branch/base and API/normal GUI baseline. Check design with a fresh builder reviewer before implementation. -- [ ] Write focused tests first for state/read/key/short-circuit/null/reentry/exception contracts. +- [x] Write focused tests first for state/read/key/short-circuit/null/reentry/exception contracts. Observe the expected missing component or behavior RED before implementing it. -- [ ] Implement the original policy in the presenter. Keep host lifecycle statements in place and +- [x] Implement the original policy in the presenter. Keep host lifecycle statements in place and add constructor wiring without invoking ports. Run focused tests and inspect actual output. -- [ ] Prove a controlled cache/read mutation fails behavior assertions, preserve output, restore +- [x] Prove a controlled cache/read mutation fails behavior assertions, preserve output, restore exact bytes/hash and run focused/full GREEN plus normal Release/x64 GUI0warnings/errors. - [ ] Verify source and compiled public API preservation, exact product footprint and current governance/secret scans. Record failures/resolution and commit the owned product checkpoint. diff --git a/docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md b/docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md new file mode 100644 index 00000000..95943417 --- /dev/null +++ b/docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md @@ -0,0 +1,76 @@ +# BlockCheck2 completion presentation verification + +## Source and acceptance boundary + +[Issue217](https://github.com/lumenpearson/cdpiui/issues/217) owns this LOCAL stage on +dev/blockcheck-completion-presentation, based on frozen draft PR216 at +36235846fb116acad49b328b29120afa92714712. The user authorized autonomous safe decomposition. +The [design](../specs/2026-11-11-blockcheck-completion-design.md) and +[plan](../plans/2026-11-11-blockcheck-completion.md) were introduced in +9262400ec10f6c18c6e23bcfece2586957adb759 after independent builder acceptance0Critical/Important. +The builder clarified that Session still constructs collaborators; inert ports prevent real +settings access and backend/history operations. No OnLoaded or real scan is needed for this stage. + +Actual [Project7 intake](https://github.com/lumenpearson/cdpiui/issues/217#issuecomment-6792498881) +was reloaded under exclusive grant99: In progress/P2/Architecture/Medium/G2/lumenpearson, +type:refactor and area:architecture. The existing card was reused and grant100 was released. +The product checkpoint is recorded by the issue evidence after the source commit. This report's +first section records Task1; new actual-host acceptance remains pending below. + +## Task1 managed policy and host extraction + +The new internal BlockCheck2RunCompletionPresenter contains only the final notice policy. +HandleRunCompleted retains its InputInvalid early return, step callbacks, notice-open publication +and final navigation update. Constructor wiring stores eight lazy ports after CancelCommand; +the host callback keeps severity/title/message setters together and in their original order. +No public signature, resource, storage/scan policy, package or dependency version changes. + +Windows/.NET SDK8.0.427 commands: + +```text +dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release --no-restore --filter FullyQualifiedName~BlockCheck2RunCompletionPresenterTests +dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release --no-restore +dotnet build CDPIUI/CDPIUI.csproj -c Release -p:Platform=x64 --no-restore +``` + +The first focused run failedCS0246 for the intentionally absent presenter, before implementation. +After the pure policy was added,38/38 focused tests passed. The tests cover every enum state, +exact localization keys/read points, no-bypass short circuit, HTTP-only after title, separate +operation/history guard/value reads, raw whitespace/null values, exception identity and reentry. + +A controlled history-cache mutant failed2 behavior assertions: localization could no longer +replace the later history value or change it to null. The original file was restored byte-for-byte. +Restored source SHA256:1B991D88EB76FE797A18D8FE9BF464B16696A738F5126A3C6037FF051E5793C9. +The restored focused run passed38/38/23ms. Full suite passed2201/2201/10s,0 failed/skipped. +The normal GUI build passed0 warnings/errors in58.84s. +Normal artifact SHA256:185FED074A7B53AFCCB66D121CFE30AF29FEEED1BF9A2B7D0B19733A7D98E593. + +The source guard compares the original policy tokens under the eight declared port mappings, +including the significant single-space warning separator. All remaining Progress code and all +prior MainPage constructor/host bytes match the baseline after removing the exact new wiring. +Its first attempt incorrectly expected a closing brace outside the selected verification slice; +only the tool expectation changed, then the complete guard passed. No product repair was needed. + +Source inventory:451 retained exported GUI types across612→613 tracked C# files,0 lost/changed +signatures. Compiled inventory:452 GUI and88 Core retained exported types,0 lost/changed/added +retained shapes. The exact product footprint is two changed MainPage files and one new presenter; +Core/AddOns/Shared source is unchanged. These inventories have their recorded syntax/metadata +limits and do not prove every attribute, native ABI or behavioral scenario. + +The baseline GUI artifact is the previously accepted product binary with D1B46B hash; the new +build legitimately replaces the normal output. Historical fixture postchecks must not be rerun +against the new normal output as though an old artifact path were immutable forever. + +Raw local evidence is retained in .superpowers/sdd/2026-11-11-blockcheck-completion: focused and +full logs, rejected mutant output, exact restoration file/hash, normal GUI log, source-policy guard, +source input/footprint and compiled inventories. Old integration and native evidence remain intact. + +## Task2 native composition and final review + +Pending. The accepted149 fixture belongs to b41b724 and does not qualify the new MainPage wiring. +Prepare a fresh named source snapshot, preserve all prior case partials and documented cuts, +add actual-host completion cases, obtain independent isolation/READY review and a new explicit +UI grant. Pin actual outputs/resources/source/runner/verifier and preexisting files before launch. +No new native process, desktop action, backend operation, installation or successful result is +claimed at this Task1 checkpoint. Final independent review and all local issue criteria remain open. +Issues13/14/15 and draft PR216 retain their separate integration, G1 and wider native boundaries. From 11957046a38f9db56b9b37cc6d79082766c062af Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:29:45 +0300 Subject: [PATCH 08/31] Record actual BlockCheck2 completion host verification Current native evidence qualifies the completion presenter through the actual MainPage view model and retained prior fixture corpus. The fresh process passes all 154 unique groups with one completion record, an unchanged prior prefix and an exit code of zero. Source, resource, binary, input, report, filename and process checks pass before the guarded UI queue release. The report records isolation boundaries, rejected verification attempts and the corrected prelaunch scope while preserving the original source checkpoint. Final independent review and exact-head checks remain required before the separate local acceptance and project closeout. Changed files: - "docs/governance/document-inventory.json" (+3/-3 lines). - "docs/superpowers/plans/2026-11-11-blockcheck-completion.md" (+7/-4 lines). - "docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md" (+69/-10 lines). The file counts compare the staged tree with its first parent. Refs: #217 Staged-Tree: db89db48b9d3dbb88f2ec37783ed755721f027b1 --- docs/governance/document-inventory.json | 6 +- .../plans/2026-11-11-blockcheck-completion.md | 11 ++- ...1-11-blockcheck-completion-verification.md | 79 ++++++++++++++++--- 3 files changed, 79 insertions(+), 17 deletions(-) diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index 050f8f5a..47ca727c 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1448,13 +1448,13 @@ }, { "path": "docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md", - "firstIntroduction": "Local issue217 completion policy verification; source checkpoint pending commit", - "first_commit": null, + "firstIntroduction": "08678c28f73dfe5c1c154ea112173ef55baa77a1\tleather147\tExtract BlockCheck2 completion notice presentation", + "first_commit": "08678c28f73dfe5c1c154ea112173ef55baa77a1", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", "language": "en", - "changes": "Record managed tests, mutation rejection, GUI and contract evidence; actual native/final acceptance remains pending." + "changes": "Record managed and actual native154 completion presentation evidence, source pins, rejected attempts, limits and local acceptance gates." } ], "current_history_base": "7ead95f7756057f67cd113671a7f84cf422e8d32", diff --git a/docs/superpowers/plans/2026-11-11-blockcheck-completion.md b/docs/superpowers/plans/2026-11-11-blockcheck-completion.md index e7a8c8ae..bf4f61c3 100644 --- a/docs/superpowers/plans/2026-11-11-blockcheck-completion.md +++ b/docs/superpowers/plans/2026-11-11-blockcheck-completion.md @@ -48,7 +48,7 @@ private HandleRunCompleted and three setters. add constructor wiring without invoking ports. Run focused tests and inspect actual output. - [x] Prove a controlled cache/read mutation fails behavior assertions, preserve output, restore exact bytes/hash and run focused/full GREEN plus normal Release/x64 GUI0warnings/errors. -- [ ] Verify source and compiled public API preservation, exact product footprint and current +- [x] Verify source and compiled public API preservation, exact product footprint and current governance/secret scans. Record failures/resolution and commit the owned product checkpoint. ### Task 2: Qualify actual MainPage composition and accept the local stage @@ -59,14 +59,17 @@ dedicated verification report and additive document inventory. Product stays at **Interfaces:** consumes Task1 SHA and accepted union149 source/cases; produces a reviewed fresh native corpus, actual build/pins and execution/postcheck receipt for this source only. -- [ ] Read Task1 evidence; derive full Git source inventory, literal cuts, unchanged case partials, +- [x] Read Task1 evidence; derive full Git source inventory, literal cuts, unchanged case partials, new actual-host cases and exact sequence/count. Preserve fresh paths and all prior fixtures. -- [ ] Independently review isolation/new cases before build, compile0-0, then pin real binaries, +- [x] Independently review isolation/new cases before build, compile0-0, then pin real binaries, resources, source, runner/verifier and all preexisting output names/hashes. Obtain READY. -- [ ] Coordinate a new explicit exclusive lease, run the owned bounded process once, validate +- [x] Coordinate a new explicit exclusive lease, run the owned bounded process once, validate exact pass labels/COMPLETE/exit0/streams/IO/hash/resource/source/absence/process checks, then publish idle/requestfalse and guarded release. Preserve and diagnose failed attempts. - [ ] Update evidence/docs; obtain fresh whole-change independent review, fix Critical/Important with observed RED→GREEN and ledger any rulings/deferred minors. +- [ ] Publish only this stage as a stacked draft PR against frozen dev/audit-class-integration; + verify all required checks on its exact final HEAD and actual PR metadata/Project fields. + Refs14 and217 keep integration ownership explicit; no automatic closure, parent draft or main merge. - [ ] Check all six local issue criteria against named current evidence, post six-section acceptance, close completed+actual ProjectDone immediately and read back full metadata. Leave13/14/15 open. diff --git a/docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md b/docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md index 95943417..15713d04 100644 --- a/docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md +++ b/docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md @@ -14,8 +14,9 @@ settings access and backend/history operations. No OnLoaded or real scan is need Actual [Project7 intake](https://github.com/lumenpearson/cdpiui/issues/217#issuecomment-6792498881) was reloaded under exclusive grant99: In progress/P2/Architecture/Medium/G2/lumenpearson, type:refactor and area:architecture. The existing card was reused and grant100 was released. -The product checkpoint is recorded by the issue evidence after the source commit. This report's -first section records Task1; new actual-host acceptance remains pending below. +Product checkpoint:08678c28f73dfe5c1c154ea112173ef55baa77a1. Later report changes contain evidence +only; the actual native fixture is pinned to this product source. The full local acceptance still +requires fresh whole-change review and final metadata below. ## Task1 managed policy and host extraction @@ -24,6 +25,7 @@ HandleRunCompleted retains its InputInvalid early return, step callbacks, notice and final navigation update. Constructor wiring stores eight lazy ports after CancelCommand; the host callback keeps severity/title/message setters together and in their original order. No public signature, resource, storage/scan policy, package or dependency version changes. +The MainPage partial sum is826→785 physical lines, Progress174→123 and presenter85. Windows/.NET SDK8.0.427 commands: @@ -65,12 +67,69 @@ Raw local evidence is retained in .superpowers/sdd/2026-11-11-blockcheck-complet full logs, rejected mutant output, exact restoration file/hash, normal GUI log, source-policy guard, source input/footprint and compiled inventories. Old integration and native evidence remain intact. -## Task2 native composition and final review +## Task2 actual native composition -Pending. The accepted149 fixture belongs to b41b724 and does not qualify the new MainPage wiring. -Prepare a fresh named source snapshot, preserve all prior case partials and documented cuts, -add actual-host completion cases, obtain independent isolation/READY review and a new explicit -UI grant. Pin actual outputs/resources/source/runner/verifier and preexisting files before launch. -No new native process, desktop action, backend operation, installation or successful result is -claimed at this Task1 checkpoint. Final independent review and all local issue criteria remain open. -Issues13/14/15 and draft PR216 retain their separate integration, G1 and wider native boundaries. +Fresh fixture:F:/cdpiui-verify/cdpiui-blockcheck-completion-08678c2-20261111, source08678c2. +Independent pre-build and post-build/prelaunch review each returned0Critical/Important/Minor. +The reviewer reconstructed all1579 Git inputs, exactly21 retained boundary files,32 bootstraps, +36 source extras, full manifest/patch diff and30 byte-identical prior case partials. The main +bootstrap changes only its fixture path/pin/result name, one call and COMPLETE count. No new +product cut was added; the presenter and both changed MainPage files remain real and uncut. + +The154 unique expected labels retain the entire accepted149 prefix, including Root137 prefix +and ordered peer141 projection, then add five actual MainPage ViewModel groups: + +- InputInvalid still returns through the input-notice path after its step callback changes state. +- Completed/history and no-bypass/HTTP notices use actual localized values and host setter order. +- Navigation and notice-open callbacks replace current state/error before the real policy reads. +- Reentry from the severity notification keeps the inner severity while the outer title/message + continue, including the original equality suppression and host sender identity. +- A title-notification exception retains identity and already-published fields, skips the remaining + message/navigation work, then permits retry after that observer is detached. + +These cases bind the actual private HandleRunCompleted as an Action on the Application dispatcher. +Session, result state, localizer, presenter and setters are uncut. A narrow two-method fake view +records GoToStep and ShowNavigationButtons; no actual Page visual or XAML Loading is exercised. +Existing inert settings ports cover constructor reads. Normal collaborators are still constructed, +but preparation/scan/history/backend/cleanup/settings-write counters remain unchanged. All added +property subscriptions and view callbacks detach in finally. The existing unloaded selector graph +has the prior process-lifetime limit; no new garbage-collection or full-startup claim is added. + +Native build:0 warnings/errors,85.25s. The actual58 pins contain5 own binaries,20 packaged resources +and33 source/evidence files. Every522 preexisting binary filename/hash was captured before launch. +All20 packaged resources equal generated bytes, all5206 entries equal committed JSON, and all10 +completion keys used by the native cases contain nonempty English text. Embedded PE manifest: +x64/asInvoker/uiAccess=false; the executing account is not elevated. + +Native DLL SHA256:F890879CC2160F06C64BD42A0F1178114F6899024E8CB3BF8EC39E276DA3D960. +Runner SHA256:26925C43D24FCEBCA17793E0119FFC934FE150843E199F7C1BF7C0CDDBD19ED1. +Verifier SHA256:BB410DD93F571DD866C4775B8C846FEC4B4014FFC8B40132846FB19FED8185A5. + +After READY, fresh queue100 was released/all six participants paused with no other ready request. +The canonical readiness and explicit Root grant101 were guarded, written and read back. A stale +preparation-only sentence in the scope was detected and corrected in the owned request/lease +before any launch; both original and corrected receipts remain. The actual readiness/pin/owner/hash +fields did not change during this wording repair. The reviewed runner checked the active lease +and matching ready request before evidence writes and again immediately before launch. + +One hidden owned process, PID78236, ran UTC2026-11-11T10:22:47.1555762Z→10:22:52.4878259+00:00. +Actual result:154 unique PASS in the exact expected order, one COMPLETE,0FAIL, exit0 and empty +stdout/stderr. All58 pins and all522 prior hashes remained unchanged. Source/cut/case proofs and +post-run resource comparisons passed. Three literal inputs16/16/15 bytes and two golden serializer +reports354/260 bytes retain their exact bytes/hashes/fields. Exactly six new names produced522→528 +files; forbidden outputs remain absent. Normal GUI185FED remains unchanged. PID78236 and the exact +fixture executable are absent. Idle/requestfalse/completed/allUIpaused preceded guarded101→102 +release; owner:null/released was read back and the canonical request records the release acknowledgement. + +No CUA, desktop input, foreign window, elevation, installation, real preferences or backend/history +operation occurred. The native boundary proves ViewModel composition and the retained old corpus; +it does not accept interactive dialogs, real scans, XAML Loading, installed behavior or G1. +Raw evidence includes native-build.log, native-approved-pins.json, native-build-baseline.json, +native-accepted-corpora.json, native-execution.log, blockcheck-completion-host-* files, source manifest, +resource post-proof and explicit corrected101/released102 receipts in the dedicated stage workspace. + +## Final review and acceptance + +Fresh whole-change review and the case-specific acceptance/actual ProjectDone readback remain +pending at this evidence checkpoint. Issues13/14/15 and draft PR216 retain their separate +integration, G1 and wider native boundaries; no main merge or release decision is implied. From 3da11cb098d3e1241b2a86cd86ee0c14d80b1942 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:36:47 +0300 Subject: [PATCH 09/31] Record independent completion presentation review Current independent review accepts the completion notice decomposition and its bounded native evidence with no critical or important findings. The reviewer separately reconstructed the source contracts, artifact hashes, retained case corpus, localization entries and process queue receipts. The report now attributes equality suppression to the unchanged source because the new reentry case does not count that notification separately. The optional runtime counter remains a deferred minor and introduces no product, fixture or binary revision. Draft publication, final-head checks and actual delivery metadata remain separate acceptance gates for the execution owner. Changed files: - "docs/superpowers/plans/2026-11-11-blockcheck-completion.md" (+1/-1 lines). - "docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md" (+16/-4 lines). The file counts compare the staged tree with its first parent. Refs: #217 Staged-Tree: 4064a4bf676331e8090017c54862b68721196640 --- .../plans/2026-11-11-blockcheck-completion.md | 2 +- ...1-11-blockcheck-completion-verification.md | 20 +++++++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/docs/superpowers/plans/2026-11-11-blockcheck-completion.md b/docs/superpowers/plans/2026-11-11-blockcheck-completion.md index bf4f61c3..bdead836 100644 --- a/docs/superpowers/plans/2026-11-11-blockcheck-completion.md +++ b/docs/superpowers/plans/2026-11-11-blockcheck-completion.md @@ -66,7 +66,7 @@ native corpus, actual build/pins and execution/postcheck receipt for this source - [x] Coordinate a new explicit exclusive lease, run the owned bounded process once, validate exact pass labels/COMPLETE/exit0/streams/IO/hash/resource/source/absence/process checks, then publish idle/requestfalse and guarded release. Preserve and diagnose failed attempts. -- [ ] Update evidence/docs; obtain fresh whole-change independent review, fix Critical/Important +- [x] Update evidence/docs; obtain fresh whole-change independent review, fix Critical/Important with observed RED→GREEN and ledger any rulings/deferred minors. - [ ] Publish only this stage as a stacked draft PR against frozen dev/audit-class-integration; verify all required checks on its exact final HEAD and actual PR metadata/Project fields. diff --git a/docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md b/docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md index 15713d04..a477f2ff 100644 --- a/docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md +++ b/docs/superpowers/reports/2026-11-11-blockcheck-completion-verification.md @@ -83,7 +83,9 @@ and ordered peer141 projection, then add five actual MainPage ViewModel groups: - Completed/history and no-bypass/HTTP notices use actual localized values and host setter order. - Navigation and notice-open callbacks replace current state/error before the real policy reads. - Reentry from the severity notification keeps the inner severity while the outer title/message - continue, including the original equality suppression and host sender identity. + continue, with host sender identity and two navigation updates. Equality suppression remains + confirmed by the unchanged SetProperty source; the new case does not count the repeated + IsResultNoticeOpen=true assignment separately. - A title-notification exception retains identity and already-published fields, skips the remaining message/navigation work, then permits retry after that observer is detached. @@ -130,6 +132,16 @@ resource post-proof and explicit corrected101/released102 receipts in the dedica ## Final review and acceptance -Fresh whole-change review and the case-specific acceptance/actual ProjectDone readback remain -pending at this evidence checkpoint. Issues13/14/15 and draft PR216 retain their separate -integration, G1 and wider native boundaries; no main merge or release decision is implied. +Fresh independent reviewer /root/completion_integration_review accepted the whole change +3623584..11957046a38f9db56b9b37cc6d79082766c062af:0Critical,0Important,1Minor. +The reviewer independently reconstructed the source/read/order/nullable/exception contract, all +58 pins and522 prior hashes,154 labels and149/137/141 corpora,30 previous case bytes,21 cuts, +resource5206 entries, document origins and grant/idle/exit receipts. Build/tests/apps were not rerun. +The Minor identifies the uncounted repeated notice-open notification in the reentry case. This +report now attributes equality suppression to unchanged source, and the additional runtime counter +remains deferred. No product, case, fixture, binary or evidence change was needed. + +Stacked draft publication, exact final-head CI, actual PR Project fields and the case-specific +acceptance/ProjectDone readback remain pending at this evidence checkpoint. Issues13/14/15 and +draft PR216 retain their separate integration, G1 and wider native boundaries; no main merge or +release decision is implied. Their tracker receipts hold subsequent publication/acceptance state. From 9de4d0d87bdd5feaa49451b3885e892c32c353cf Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:13:32 +0300 Subject: [PATCH 10/31] Record MainPage progress presentation design Current MainPage progress display fields remain separate from the accepted numeric estimator and completion notice owners. The design gives six existing values and their synchronous update policy to one internal observable object with eight lazy ports. A single model-owned bridge preserves host sender identity, field visibility, equality suppression and exception propagation without changing loaded or unloaded subscriptions. The plan requires focused mutation controls, public contract comparison and a fresh native corpus before the separate local acceptance. Independent builder review found no design gap, while all prior branch references and qualified artifacts remain intact. Changed files: - "docs/governance/document-inventory.json" (+20/-0 lines). - "docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md" (+74/-0 lines). - "docs/superpowers/specs/2026-11-11-blockcheck-progress-presentation-design.md" (+102/-0 lines). The file counts compare the staged tree with its first parent. Refs: #219 Staged-Tree: c226d6b3d32fd09f168fb2f287d0a7512288e6b9 --- docs/governance/document-inventory.json | 20 ++++ ...-11-11-blockcheck-progress-presentation.md | 74 +++++++++++++ ...blockcheck-progress-presentation-design.md | 102 ++++++++++++++++++ 3 files changed, 196 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md create mode 100644 docs/superpowers/specs/2026-11-11-blockcheck-progress-presentation-design.md diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index 47ca727c..0040256d 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1455,6 +1455,26 @@ "policy": "ASD-STE100 principles for English", "language": "en", "changes": "Record managed and actual native154 completion presentation evidence, source pins, rejected attempts, limits and local acceptance gates." + }, + { + "path": "docs/superpowers/specs/2026-11-11-blockcheck-progress-presentation-design.md", + "firstIntroduction": "Local MainPage progress presentation state contract under issue219; base3da11cb098d3e1241b2a86cd86ee0c14d80b1942", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Define six-value progress state ownership, live-read and host notification contracts with isolated verification; no integrated acceptance." + }, + { + "path": "docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md", + "firstIntroduction": "Local MainPage progress presentation state contract under issue219; base3da11cb098d3e1241b2a86cd86ee0c14d80b1942", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Define six-value progress state ownership, live-read and host notification contracts with isolated verification; no integrated acceptance." } ], "current_history_base": "7ead95f7756057f67cd113671a7f84cf422e8d32", diff --git a/docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md b/docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md new file mode 100644 index 00000000..fc9152fa --- /dev/null +++ b/docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md @@ -0,0 +1,74 @@ +# MainPage Progress Presentation Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan inline, task-by-task, with a fresh final independent reviewer. + +**Goal:** Move six progress display values and their update policy into one focused state owner. + +**Architecture:** An internal observable owner stores the same fields and lazy read ports. Public +host properties/private entrypoints forward to it; one synchronous bridge retains host notifications. + +**Tech Stack:** C#/.NET8.0.427, xUnit linked source, WinUI3, API/blob and immutable native evidence. + +**Spec:** [progress presentation design](../specs/2026-11-11-blockcheck-progress-presentation-design.md). + +## Global constraints + +- Issue219 actual intake107 is verified before implementation; Root owns the isolated branch. +- Base/frozen PR2183da11cb and parent2163623584, peer249/f706 and RootEebc remain intact. +- Preserve all six cold values, public getters/private setters and five host method entrypoints. +- Read lazy ports and publish synchronously in the original order; no snapshots/guards/catches. +- Numeric progress/estimator167, duration formatter, lifecycle, completion217, resources and all + backend/security/storage/package versions remain unchanged. +- No real preferences/backend/history/scan or OnLoaded; native testing needs independent READY + and a NEW explicit exclusive UI lease, including all snapshots/reads. +- Retain source/evidence/workspaces; no deletion, reset, shared-main rewrite or unqualified merge. + +## Review Focus + +- Phase publication can change counts and terminal state before later displays read them. +- Stage publication can change running/phase/overall estimate; overall must read current values. +- Repeated equal updates still evaluate ports but suppress notifications under existing SetProperty. +- Nested disclosure callbacks change visibility before the outer localization and may throw. +- Host/owner event bridge must be synchronous, attached once and retain sender/partial state without + adding loaded/unloaded or static lifetime behavior. + +### Task 1: Extract the progress display owner + +**Files:** new CDPIUI/ViewModels/BlockCheck2/BlockCheck2ProgressPresentation.cs; MainPageViewModel.cs; +MainPageViewModel.Progress.cs; CDPIUI.Tests/Presentation/BlockCheck2ProgressPresentationTests.cs; +test project link, this design/plan and additive document inventory. + +**Interfaces:** consumes the eight lazy ports specified in the spec; produces six observable +properties and Toggle/Update/Format methods with the old names. MainPage preserves its public and +private forwarding entrypoints and one PropertyChanged bridge. + +- [ ] Read the issue/design and actual fields; preserve parent and current source/compiled/normal + artifact baselines. Have a fresh builder check the design before code. +- [ ] Write focused tests first and observe the expected missing-component/behavior RED. +- [ ] Implement cold owner state, exact original policy and host facade/bridge, without touching + lifecycle/estimator/duration/navigation/completion. Run focused tests and inspect real results. +- [ ] Apply a meaningful controlled early-read/cache mutation, observe behavior assertions fail, + restore exact bytes/hash and run focused/full GREEN plus normal Release/x64 GUI0-0. +- [ ] Verify source/compiled public preservation, exact product footprint, source/bridge/read-order + guards, governance and redacted secret scans. Record failures and commit the product checkpoint. + +### Task 2: Qualify actual host composition and accept locally + +**Files:** fresh F:/cdpiui-verify source-pinned fixture and retained ignored stage artifacts; +dedicated verification report and additive inventory. + +**Interfaces:** consumes Task1 source pin and accepted154 source/cases/cuts; produces an independently +reviewed new actual-host corpus, pins/runtime/postchecks and local delivery record. + +- [ ] Read Task1 evidence; preserve154 prior labels/case bytes, derive all source inputs/cuts/extras + and new actual host cases before compiling a fresh path. +- [ ] Obtain independent pre-build review, build0-0, derive actual artifacts/resources/source/runner/ + verifier pins and all prior output hashes, then independent prelaunch READY. +- [ ] Coordinate a new explicit lease, execute one owned process and prove labels/COMPLETE/exit0, + streams/IO/source/resources/hashes/absence/process cleanup; idle/requestfalse/guarded release. +- [ ] Update evidence/docs; obtain fresh whole-change review, resolve Critical/Important with + observed RED→GREEN and ledger rulings/deferred minors. Preserve original artifacts. +- [ ] Publish a stacked draft against frozen dev/blockcheck-completion-presentation with Refs14/219; + verify exact final-head checks and actual PR/Project fields, no parent or main merge. +- [ ] Verify all six local issue criteria, post the six-section acceptance record, immediately + close completed/set actual ProjectDone and read back closure/classification/owner/fields. diff --git a/docs/superpowers/specs/2026-11-11-blockcheck-progress-presentation-design.md b/docs/superpowers/specs/2026-11-11-blockcheck-progress-presentation-design.md new file mode 100644 index 00000000..b659fba0 --- /dev/null +++ b/docs/superpowers/specs/2026-11-11-blockcheck-progress-presentation-design.md @@ -0,0 +1,102 @@ +# MainPage progress presentation state + +## Intent and execution boundary + +[Issue219](https://github.com/lumenpearson/cdpiui/issues/219) owns a LOCAL continuation of the +audit decomposition. Baseline3da11cb098d3e1241b2a86cd86ee0c14d80b1942 is frozen draft PR218; +its local issue217 is completed with all6 criteria and actual ProjectDone105/final receipt. +Use dev/blockcheck-progress-presentation in the existing isolated Root worktree. Actual issue219 +Project7 intake107 confirmed In progress/P2/Architecture/Medium/G2/lumenpearson/two canonical labels +after reload, then released108. Do not change parent branches, other checkouts or G1 services. + +The implementation owner selects this boundary under the user's explicit autonomous authorization. +No new user behavior is proposed. Historical issue167 owns numeric progress and the estimator; +this stage owns only the six MainPage display values that remain in its Progress partial. + +## Architecture + +Add internal sealed BlockCheck2ProgressPresentation:ObservableObject. It owns exactly these +existing fields/properties, with the same names, values and SetProperty semantics: + +| Property | Initial value | +| --- | --- | +| ProgressPhaseText | string.Empty | +| ProgressCounterText | string.Empty | +| StageRemainingTimeText | string.Empty | +| OverallRemainingTimeText | string.Empty | +| IsAdditionalProgressInfoVisible | false | +| ProgressViewMoreText | null | + +Keep all six public host getters and private setters as direct owner forwards. The owner is +internal; its writable properties do not introduce an exported API. The host constructor creates +it after the existing completion-presenter wiring and attaches exactly one model-owned synchronous +PropertyChanged bridge to host.OnPropertyChanged. No bridge is added by OnLoaded/OnUnloaded. +It lives with the host, has no static/global event root and needs no separate disposal mechanism. +External observers continue to receive the host as sender and read its current owner values. + +Keep host ToggleAdditionalProgressInfo, UpdateProgressViewMoreText, UpdateProgressText, +FormatRemainingTime and FormatOverallRemainingTime entrypoints as forwards. Move their literal +policy into the owner; do not duplicate it. Keep UpdateLocalizedText, Session_PropertyChanged and +the loaded/unloaded subscription logic unchanged. Numeric Session progress and the existing +BlockCheck2DurationText implementation remain unchanged. + +Use eight lazy ports, stored without invocation by the owner constructor: + +```csharp +BlockCheck2ProgressPresentation( + Func phase, Func running, + Func current, Func total, + Func stageEstimate, Func overallEstimate, + Func text, Func formatRemaining) +``` + +The host passes its current Session properties, Text and the existing duration formatter. +No input DTO, snapshot, queued/batched event bridge, extra validation, catch, guard or new package +is needed. This is a coherent progress display owner; a generic presentation framework adds no value. + +## Observable contract + +- Construction preserves all cold values and invokes no phase/state/count/estimate/text/formatter + port. Existing prior constructor statements remain in their order. +- UpdateProgressText publishes phase, counter, stage remaining and overall remaining in that order. + Each later expression reads the current ports after any preceding property notification. +- Phase selection retains all six named enum branches and Preparing fallback for null or another + enum value. Localization occurs before publishing the selected phase. +- Counter formatting calls Text first, then reads current and total; string.Format uses the ambient + current culture at the original call point. Do not preformat numbers or capture culture earlier. +- Each remaining-time calculation reads running separately. When not running, read nullable phase; + if it has a value, return the literal em dash without reading an estimate or calling the formatter. + A null phase still formats. No read is shared between stage and overall. +- Stage formatting reads its current estimate and the same RemainingTimeCalculating key. Overall + reads its current estimate before re-reading phase to choose Baseline's OverallTimeCalculating + versus RemainingTimeCalculating. Keep that argument evaluation order. +- SetProperty equality suppression and field-before-notification behavior remain. Equal output + still evaluates its right-hand-side ports; only notification is suppressed. The synchronous + bridge retains host sender identity and preserves exception identity/partial effects. +- Toggle reads current visibility, publishes its inverse, then re-reads visibility for ViewLess or + ViewMore localization. A callback may toggle again; the outer update must use the resulting value. + Keep null/string behavior and no new reentry or error-recovery state. +- Every host instance owns independent display fields and bridge. Loaded/unloaded behavior and + original private setters remain compatible; no user settings, storage or scan operation is added. + +## Verification and limits + +Write focused linked-source xUnit tests first, using the existing ObservableObject link. Cover cold +ports, all phase/null/unknown branches, exact reads/keys/culture, repeated equal updates, per-property +callback mutation, terminal short circuits, nested disclosure toggles, instance isolation and all +relevant delegate/observer exceptions. A controlled early count/estimate snapshot must fail an +observable test before exact source/hash restoration. Run focused/full suites and normal GUI; +compare source/compiled public contracts and the exact two-host-files/new-owner footprint. + +Create a NEW source-pinned native fixture from accepted154. Preserve all old case partial bytes, +the existing21 cuts and old sequence; derive new counts, extras, resource/binary/source pins and +all preexisting filenames/hashes. Add actual MainPage owner/facade/bridge cases for current values, +ordered notifications with mutations, nested disclosure and partial exceptions on the dispatcher. +Retain inert settings/operation ports; do not call OnLoaded or real scans/backend/history/settings. +Review isolation before build and actual pins before launch, then acquire a new explicit lease. +Prove exact runtime labels/COMPLETE/exit/streams/source/resources/IO/hash/process/idle release. + +Fresh final review, stacked draft exact-head checks and actual delivery fields precede local +acceptance/closure/ProjectDone. Parent13/14/15 and drafts216/218 keep their separate boundaries. +No full Page visual, XAML Loading, installed, G1, new GC or release result is inferred. Preserve all +workspaces/refs/accepted/rejected artifacts; no destructive cleanup is authorized. From 41585746c9171aac7827760332c8f79f919f6f48 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:27:59 +0300 Subject: [PATCH 11/31] Extract MainPage progress presentation state The MainPage model keeps progress display state beside navigation and run control. The new internal owner stores six existing values and uses eight lazy ports. Existing public properties and private entrypoints forward to the owner through one synchronous notification bridge. This preserves current reads after callbacks, sender identity, equal value suppression, exception identity and partial effects. Focused tests first failed because the owner did not exist. An early count cache then failed eleven behavioral cases before exact source restoration. All 2243 managed tests and the normal WinUI build now pass. Source and compiled comparisons preserve original public contracts, while native qualification remains the next local acceptance step. Changed files: - "CDPIUI.Tests/CDPIUI.Tests.csproj" (+1/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2ProgressPresentationTests.cs" (+306/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Progress.cs" (+17/-69 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs" (+7/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ProgressPresentation.cs" (+126/-0 lines). - "docs/governance/document-inventory.json" (+14/-4 lines). - "docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md" (+77/-0 lines). The file counts compare the staged tree with its first parent. Refs: #219 Staged-Tree: 129c133704e7300eb7bde33df72f9de41e12ce0f --- CDPIUI.Tests/CDPIUI.Tests.csproj | 1 + .../BlockCheck2ProgressPresentationTests.cs | 306 ++++++++++++++++++ .../BlockCheck2MainPageViewModel.Progress.cs | 86 +---- .../BlockCheck2MainPageViewModel.cs | 7 + .../BlockCheck2ProgressPresentation.cs | 126 ++++++++ docs/governance/document-inventory.json | 18 +- ...heck-progress-presentation-verification.md | 77 +++++ 7 files changed, 548 insertions(+), 73 deletions(-) create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2ProgressPresentationTests.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/BlockCheck2ProgressPresentation.cs create mode 100644 docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md diff --git a/CDPIUI.Tests/CDPIUI.Tests.csproj b/CDPIUI.Tests/CDPIUI.Tests.csproj index c3eb3f87..30e86078 100644 --- a/CDPIUI.Tests/CDPIUI.Tests.csproj +++ b/CDPIUI.Tests/CDPIUI.Tests.csproj @@ -53,6 +53,7 @@ + diff --git a/CDPIUI.Tests/Presentation/BlockCheck2ProgressPresentationTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2ProgressPresentationTests.cs new file mode 100644 index 00000000..40fa8cc8 --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2ProgressPresentationTests.cs @@ -0,0 +1,306 @@ +using System.Globalization; +using CDPIUI.AddOns.BlockCheck2.Models; +using CDPIUI.ViewModels.BlockCheck2; + +namespace CDPIUI.Tests.Presentation; + +public class BlockCheck2ProgressPresentationTests +{ + [Fact] + public void ConstructorKeepsSixColdValuesWithoutReadingAnyPort() + { + var f = new Fixture(); + Assert.Equal(string.Empty, f.Owner.ProgressPhaseText); + Assert.Equal(string.Empty, f.Owner.ProgressCounterText); + Assert.Equal(string.Empty, f.Owner.StageRemainingTimeText); + Assert.Equal(string.Empty, f.Owner.OverallRemainingTimeText); + Assert.False(f.Owner.IsAdditionalProgressInfoVisible); + Assert.Null(f.Owner.ProgressViewMoreText); + Assert.Empty(f.Trace); + } + + [Theory] + [InlineData(BlockCheckScanPhase.BaselineProbing, "BlockCheck2PhaseBaseline")] + [InlineData(BlockCheckScanPhase.StartingStrategy, "BlockCheck2PhaseStartingStrategy")] + [InlineData(BlockCheckScanPhase.Probing, "BlockCheck2PhaseProbing")] + [InlineData(BlockCheckScanPhase.StrategyCompleted, "BlockCheck2PhaseStrategyCompleted")] + [InlineData(BlockCheckScanPhase.ValidatingPreset, "BlockCheck2PhaseValidatingConfig")] + [InlineData(BlockCheckScanPhase.RepairingPreset, "BlockCheck2PhaseRepairingConfig")] + [InlineData(null, "BlockCheck2PhasePreparing")] + [InlineData((BlockCheckScanPhase)999, "BlockCheck2PhasePreparing")] + public void EveryPhaseAndFallbackUsesTheOriginalKey(BlockCheckScanPhase? phase, string key) + { + var f = new Fixture { Phase = phase }; + f.Owner.UpdateProgressText(); + Assert.Equal("t:" + key, f.Owner.ProgressPhaseText); + Assert.Equal(2, f.Trace.Count(s => s == "phase")); + Assert.Equal("phase", f.Trace[0]); + Assert.Equal("text:" + key, f.Trace[1]); + } + + [Fact] + public void RunningUpdateRetainsPortAndPublicationOrder() + { + var f = new Fixture(); + f.Owner.UpdateProgressText(); + Assert.Equal(["phase", "text:BlockCheck2PhaseBaseline", "changed:ProgressPhaseText", + "text:BlockCheck2ProgressCounterFormat", "current", "total", "changed:ProgressCounterText", + "running", "stage-estimate", "format:BlockCheck2RemainingTimeCalculating", "changed:StageRemainingTimeText", + "running", "overall-estimate", "phase", "format:BlockCheck2OverallTimeCalculating", "changed:OverallRemainingTimeText"], f.Trace); + } + + [Fact] + public void PhasePublicationCanReplaceCountsBeforeTheCounterReadsThem() + { + var f = new Fixture(); + f.OnStep = point => + { + if (point == "changed:ProgressPhaseText") { f.Current = 7; f.Total = 9; } + }; + f.Owner.UpdateProgressText(); + Assert.Equal("7/9", f.Owner.ProgressCounterText); + Assert.True(f.Trace.IndexOf("changed:ProgressPhaseText") < f.Trace.IndexOf("current")); + } + + [Fact] + public void CounterLocalizationRunsBeforeBothNumberReads() + { + var f = new Fixture(); + f.OnStep = point => + { + if (point == "text:BlockCheck2ProgressCounterFormat") { f.Current = 12; f.Total = 20; } + }; + f.Owner.UpdateProgressText(); + Assert.Equal("12/20", f.Owner.ProgressCounterText); + } + + [Fact] + public void StringFormatUsesCultureAfterBothNumberGettersHaveRun() + { + var original = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); + var f = new Fixture { Current = 1234, Total = 5678, CounterFormat = "{0:N0}|{1:N0}" }; + f.OnStep = point => { if (point == "total") CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); }; + f.Owner.UpdateProgressText(); + Assert.Equal("1.234|5.678", f.Owner.ProgressCounterText); + } + finally { CultureInfo.CurrentCulture = original; } + } + + [Theory] + [InlineData(null)] + [InlineData("{0")] + public void InvalidCounterFormatStillReadsBothNumbersBeforeThrowing(string? format) + { + var f = new Fixture { CounterFormat = format }; + if (format is null) Assert.Throws(f.Owner.UpdateProgressText); + else Assert.Throws(f.Owner.UpdateProgressText); + Assert.Contains("current", f.Trace); + Assert.Contains("total", f.Trace); + Assert.NotEqual(string.Empty, f.Owner.ProgressPhaseText); + Assert.Equal(string.Empty, f.Owner.ProgressCounterText); + Assert.Equal(string.Empty, f.Owner.StageRemainingTimeText); + Assert.DoesNotContain("running", f.Trace); + } + + [Fact] + public void StagePublicationCanChangeTerminalStateBeforeOverallFormatting() + { + var f = new Fixture(); + f.OnStep = point => + { + if (point == "changed:StageRemainingTimeText") + { + f.Running = false; f.Phase = BlockCheckScanPhase.Probing; f.OverallEstimate = TimeSpan.FromHours(1); + } + }; + f.Owner.UpdateProgressText(); + Assert.Equal("BlockCheck2RemainingTimeCalculating:null", f.Owner.StageRemainingTimeText); + Assert.Equal("—", f.Owner.OverallRemainingTimeText); + Assert.DoesNotContain("overall-estimate", f.Trace); + } + + [Fact] + public void OverallEstimateIsReadBeforeThePhaseWhichChoosesItsKey() + { + var f = new Fixture(); + f.OnStep = point => { if (point == "overall-estimate") f.Phase = BlockCheckScanPhase.Probing; }; + Assert.Equal("BlockCheck2RemainingTimeCalculating:null", f.Owner.FormatOverallRemainingTime()); + Assert.Equal(["running", "overall-estimate", "phase", "format:BlockCheck2RemainingTimeCalculating"], f.Trace); + } + + [Fact] + public void StoppedWithNullPhaseFormatsOverallAfterTwoIndependentPhaseReads() + { + var f = new Fixture { Running = false, Phase = null }; + Assert.Equal("BlockCheck2RemainingTimeCalculating:null", f.Owner.FormatOverallRemainingTime()); + Assert.Equal(["running", "phase", "overall-estimate", "phase", "format:BlockCheck2RemainingTimeCalculating"], f.Trace); + } + + [Fact] + public void StoppedWithNullPhaseStillReadsAndFormatsStageEstimate() + { + var f = new Fixture { Running = false, Phase = null, StageEstimate = TimeSpan.FromSeconds(2) }; + Assert.Equal("BlockCheck2RemainingTimeCalculating:20000000", f.Owner.FormatRemainingTime()); + Assert.Equal(["running", "phase", "stage-estimate", "format:BlockCheck2RemainingTimeCalculating"], f.Trace); + } + + [Theory] + [InlineData(BlockCheckScanPhase.BaselineProbing)] + [InlineData(BlockCheckScanPhase.Probing)] + [InlineData((BlockCheckScanPhase)999)] + public void StoppedWithAnyPhaseReturnsEmDashWithoutReadingEstimates(BlockCheckScanPhase phase) + { + var f = new Fixture { Running = false, Phase = phase }; + Assert.Equal("—", f.Owner.FormatRemainingTime()); + Assert.Equal("—", f.Owner.FormatOverallRemainingTime()); + Assert.Equal(["running", "phase", "running", "phase"], f.Trace); + } + + [Fact] + public void RepeatedEqualUpdateStillEvaluatesEveryExpressionButSuppressesChanges() + { + var f = new Fixture(); + f.Owner.UpdateProgressText(); f.Trace.Clear(); + f.Owner.UpdateProgressText(); + Assert.DoesNotContain(f.Trace, s => s.StartsWith("changed:", StringComparison.Ordinal)); + Assert.Equal(2, f.Trace.Count(s => s == "phase")); + Assert.Equal(2, f.Trace.Count(s => s == "running")); + Assert.Contains("current", f.Trace); Assert.Contains("total", f.Trace); + Assert.Contains("stage-estimate", f.Trace); Assert.Contains("overall-estimate", f.Trace); + } + + [Fact] + public void SixWritableValuesRetainSenderAndPerPropertyEquality() + { + var f = new Fixture(); + void Assign() + { + f.Owner.ProgressPhaseText = "phase"; f.Owner.ProgressCounterText = "counter"; + f.Owner.StageRemainingTimeText = "stage"; f.Owner.OverallRemainingTimeText = "overall"; + f.Owner.IsAdditionalProgressInfoVisible = true; f.Owner.ProgressViewMoreText = "more"; + } + Assign(); + Assert.Equal(["changed:ProgressPhaseText", "changed:ProgressCounterText", "changed:StageRemainingTimeText", + "changed:OverallRemainingTimeText", "changed:IsAdditionalProgressInfoVisible", "changed:ProgressViewMoreText"], f.Trace); + f.Trace.Clear(); Assign(); Assert.Empty(f.Trace); + } + + [Fact] + public void DisclosureTogglePublishesVisibilityBeforeCurrentViewLessText() + { + var f = new Fixture(); f.Owner.ToggleAdditionalProgressInfo(); + Assert.True(f.Owner.IsAdditionalProgressInfoVisible); + Assert.Equal("t:ViewLess", f.Owner.ProgressViewMoreText); + Assert.Equal(["changed:IsAdditionalProgressInfoVisible", "text:ViewLess", "changed:ProgressViewMoreText"], f.Trace); + } + + [Fact] + public void NestedDisclosureToggleMakesOuterLocalizationReadTheFinalVisibility() + { + var f = new Fixture(); bool nested = false; + f.OnStep = point => + { + if (point != "changed:IsAdditionalProgressInfoVisible" || nested) return; + nested = true; f.Owner.ToggleAdditionalProgressInfo(); + }; + f.Owner.ToggleAdditionalProgressInfo(); + Assert.False(f.Owner.IsAdditionalProgressInfoVisible); + Assert.Equal("t:ViewMore", f.Owner.ProgressViewMoreText); + Assert.Equal(2, f.Trace.Count(s => s == "changed:IsAdditionalProgressInfoVisible")); + Assert.Equal(2, f.Trace.Count(s => s == "text:ViewMore")); + Assert.Equal(1, f.Trace.Count(s => s == "changed:ProgressViewMoreText")); + Assert.DoesNotContain("text:ViewLess", f.Trace); + } + + [Fact] + public void DisclosureObserverFailureKeepsChangedVisibilityAndUnreachedText() + { + var f = new Fixture(); var error = new Sentinel(); + f.OnStep = point => { if (point == "changed:IsAdditionalProgressInfoVisible") throw error; }; + Assert.Same(error, Assert.Throws(f.Owner.ToggleAdditionalProgressInfo)); + Assert.True(f.Owner.IsAdditionalProgressInfoVisible); Assert.Null(f.Owner.ProgressViewMoreText); + Assert.DoesNotContain("text:ViewLess", f.Trace); + f.OnStep = null; f.Owner.ToggleAdditionalProgressInfo(); + Assert.False(f.Owner.IsAdditionalProgressInfoVisible); Assert.Equal("t:ViewMore", f.Owner.ProgressViewMoreText); + } + + [Fact] + public void InstancesOwnDistinctDisplayState() + { + var first = new Fixture(); var second = new Fixture(); + first.Owner.UpdateProgressText(); first.Owner.ToggleAdditionalProgressInfo(); + Assert.Equal(string.Empty, second.Owner.ProgressPhaseText); + Assert.Null(second.Owner.ProgressViewMoreText); Assert.Empty(second.Trace); + } + + [Theory] + [InlineData("phase")] + [InlineData("text:BlockCheck2PhaseBaseline")] + [InlineData("text:BlockCheck2ProgressCounterFormat")] + [InlineData("current")] + [InlineData("total")] + [InlineData("running")] + [InlineData("stage-estimate")] + [InlineData("format:BlockCheck2RemainingTimeCalculating")] + [InlineData("overall-estimate")] + [InlineData("format:BlockCheck2OverallTimeCalculating")] + public void PortFailuresRetainIdentityWithoutAStickyGuard(string point) + { + var f = new Fixture(); var error = new Sentinel(); + f.OnStep = step => { if (step == point) throw error; }; + Assert.Same(error, Assert.Throws(f.Owner.UpdateProgressText)); + f.OnStep = null; f.Owner.UpdateProgressText(); + Assert.NotEqual(string.Empty, f.Owner.OverallRemainingTimeText); + } + + [Theory] + [InlineData("ProgressPhaseText", 1)] + [InlineData("ProgressCounterText", 2)] + [InlineData("StageRemainingTimeText", 3)] + [InlineData("OverallRemainingTimeText", 4)] + public void ObserverFailureRetainsPublishedFieldsAndStopsLaterExpressions(string property, int published) + { + var f = new Fixture(); var error = new Sentinel(); + f.OnStep = point => { if (point == "changed:" + property) throw error; }; + Assert.Same(error, Assert.Throws(f.Owner.UpdateProgressText)); + string[] values = [f.Owner.ProgressPhaseText, f.Owner.ProgressCounterText, f.Owner.StageRemainingTimeText, f.Owner.OverallRemainingTimeText]; + Assert.All(values.Take(published), value => Assert.NotEqual(string.Empty, value)); + Assert.All(values.Skip(published), value => Assert.Equal(string.Empty, value)); + f.OnStep = null; f.Owner.UpdateProgressText(); + Assert.NotEqual(string.Empty, f.Owner.OverallRemainingTimeText); + } + + private sealed class Sentinel : Exception; + + private sealed class Fixture + { + public BlockCheckScanPhase? Phase = BlockCheckScanPhase.BaselineProbing; + public bool Running = true; + public int Current, Total; + public TimeSpan? StageEstimate, OverallEstimate; + public string? CounterFormat = "{0}/{1}"; + public Action? OnStep; + public List Trace { get; } = []; + public BlockCheck2ProgressPresentation Owner { get; } + + public Fixture() + { + Owner = new(() => Read("phase", () => Phase), () => Read("running", () => Running), + () => Read("current", () => Current), () => Read("total", () => Total), + () => Read("stage-estimate", () => StageEstimate), () => Read("overall-estimate", () => OverallEstimate), + key => Read("text:" + key, () => key == "BlockCheck2ProgressCounterFormat" ? CounterFormat! : "t:" + key), + (value, key) => Read("format:" + key, () => key + ":" + (value?.Ticks.ToString(CultureInfo.InvariantCulture) ?? "null"))); + Owner.PropertyChanged += (sender, args) => + { + Assert.Same(Owner, sender); + Step("changed:" + args.PropertyName); + }; + } + + private void Step(string point) { Trace.Add(point); OnStep?.Invoke(point); } + private T Read(string point, Func value) { Step(point); return value(); } + } +} diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Progress.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Progress.cs index 85a91334..030c5e65 100644 --- a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Progress.cs +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Progress.cs @@ -1,107 +1,55 @@ -using CDPIUI.AddOns.BlockCheck2.Models; using CDPIUI.AddOns.BlockCheck2.Presentation; namespace CDPIUI.ViewModels.BlockCheck2; public sealed partial class BlockCheck2MainPageViewModel { - private string _progressPhaseText = string.Empty; - private string _progressCounterText = string.Empty; - private string _stageRemainingTimeText = string.Empty; - private string _overallRemainingTimeText = string.Empty; - private bool _isAdditionalProgressInfoVisible; - private string? _progressViewMoreText; - public string ProgressPhaseText { - get => _progressPhaseText; - private set => SetProperty(ref _progressPhaseText, value); + get => _progressPresentation.ProgressPhaseText; + private set => _progressPresentation.ProgressPhaseText = value; } public string ProgressCounterText { - get => _progressCounterText; - private set => SetProperty(ref _progressCounterText, value); + get => _progressPresentation.ProgressCounterText; + private set => _progressPresentation.ProgressCounterText = value; } public string StageRemainingTimeText { - get => _stageRemainingTimeText; - private set => SetProperty(ref _stageRemainingTimeText, value); + get => _progressPresentation.StageRemainingTimeText; + private set => _progressPresentation.StageRemainingTimeText = value; } public string OverallRemainingTimeText { - get => _overallRemainingTimeText; - private set => SetProperty(ref _overallRemainingTimeText, value); + get => _progressPresentation.OverallRemainingTimeText; + private set => _progressPresentation.OverallRemainingTimeText = value; } public bool IsAdditionalProgressInfoVisible { - get => _isAdditionalProgressInfoVisible; - private set => SetProperty(ref _isAdditionalProgressInfoVisible, value); + get => _progressPresentation.IsAdditionalProgressInfoVisible; + private set => _progressPresentation.IsAdditionalProgressInfoVisible = value; } public string? ProgressViewMoreText { - get => _progressViewMoreText; - private set => SetProperty(ref _progressViewMoreText, value); + get => _progressPresentation.ProgressViewMoreText; + private set => _progressPresentation.ProgressViewMoreText = value; } - public void ToggleAdditionalProgressInfo() - { - IsAdditionalProgressInfoVisible = !IsAdditionalProgressInfoVisible; - UpdateProgressViewMoreText(); - } + public void ToggleAdditionalProgressInfo() => _progressPresentation.ToggleAdditionalProgressInfo(); private void UpdateProgressViewMoreText() => - ProgressViewMoreText = Text(IsAdditionalProgressInfoVisible ? "ViewLess" : "ViewMore"); - - private void UpdateProgressText() - { - ProgressPhaseText = Session.CurrentPhase switch - { - BlockCheckScanPhase.BaselineProbing => Text("BlockCheck2PhaseBaseline"), - BlockCheckScanPhase.StartingStrategy => Text("BlockCheck2PhaseStartingStrategy"), - BlockCheckScanPhase.Probing => Text("BlockCheck2PhaseProbing"), - BlockCheckScanPhase.StrategyCompleted => Text("BlockCheck2PhaseStrategyCompleted"), - BlockCheckScanPhase.ValidatingPreset => Text("BlockCheck2PhaseValidatingConfig"), - BlockCheckScanPhase.RepairingPreset => Text("BlockCheck2PhaseRepairingConfig"), - _ => Text("BlockCheck2PhasePreparing"), - }; - ProgressCounterText = string.Format( - Text("BlockCheck2ProgressCounterFormat"), - Session.ProgressCurrent, - Session.ProgressTotal); - StageRemainingTimeText = FormatRemainingTime(); - OverallRemainingTimeText = FormatOverallRemainingTime(); - } - - private string FormatRemainingTime() - { - if (!Session.IsRunning && Session.CurrentPhase.HasValue) - { - return "—"; - } + _progressPresentation.UpdateProgressViewMoreText(); - return _durationText.FormatRemaining( - Session.EstimatedRemainingTime, - "BlockCheck2RemainingTimeCalculating"); - } + private void UpdateProgressText() => _progressPresentation.UpdateProgressText(); - private string FormatOverallRemainingTime() - { - if (!Session.IsRunning && Session.CurrentPhase.HasValue) - { - return "—"; - } + private string FormatRemainingTime() => _progressPresentation.FormatRemainingTime(); - return _durationText.FormatRemaining( - Session.EstimatedOverallRemainingTime, - Session.CurrentPhase == BlockCheckScanPhase.BaselineProbing - ? "BlockCheck2OverallTimeCalculating" - : "BlockCheck2RemainingTimeCalculating"); - } + private string FormatOverallRemainingTime() => _progressPresentation.FormatOverallRemainingTime(); private void HandleRunCompleted() { diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs index a2dfa5c4..9162851f 100644 --- a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs @@ -20,6 +20,7 @@ public sealed partial class BlockCheck2MainPageViewModel : ObservableObject private readonly ILocalizer _localizer = Localizer.Get(); private readonly BlockCheck2DurationText _durationText; private readonly BlockCheck2RunCompletionPresenter _completionPresenter; + private readonly BlockCheck2ProgressPresentation _progressPresentation; private readonly IBlockCheck2MainPageView _view; private bool _handlersConnected; private BlockCheck2PreparationPreview? _preparationPreview; @@ -52,6 +53,12 @@ public BlockCheck2MainPageViewModel(IBlockCheck2MainPageView view) ResultNoticeTitle = title; ResultNoticeMessage = message; }); + _progressPresentation = new BlockCheck2ProgressPresentation( + () => Session.CurrentPhase, () => Session.IsRunning, + () => Session.ProgressCurrent, () => Session.ProgressTotal, + () => Session.EstimatedRemainingTime, () => Session.EstimatedOverallRemainingTime, + Text, _durationText.FormatRemaining); + _progressPresentation.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); } public BlockCheck2ViewModel Session { get; } = new(); diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ProgressPresentation.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ProgressPresentation.cs new file mode 100644 index 00000000..e17f16eb --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ProgressPresentation.cs @@ -0,0 +1,126 @@ +#nullable enable + +using System; +using CDPIUI.AddOns.BlockCheck2.Models; + +namespace CDPIUI.ViewModels.BlockCheck2; + +// Owns progress display values; numeric progress and run lifecycle stay with Session. +internal sealed class BlockCheck2ProgressPresentation : ObservableObject +{ + private readonly Func _phase; + private readonly Func _running; + private readonly Func _current, _total; + private readonly Func _stageEstimate, _overallEstimate; + private readonly Func _text; + private readonly Func _formatRemaining; + private string _progressPhaseText = string.Empty; + private string _progressCounterText = string.Empty; + private string _stageRemainingTimeText = string.Empty; + private string _overallRemainingTimeText = string.Empty; + private bool _isAdditionalProgressInfoVisible; + private string? _progressViewMoreText; + + public BlockCheck2ProgressPresentation(Func phase, Func running, + Func current, Func total, Func stageEstimate, Func overallEstimate, + Func text, Func formatRemaining) + { + _phase = phase; + _running = running; + _current = current; + _total = total; + _stageEstimate = stageEstimate; + _overallEstimate = overallEstimate; + _text = text; + _formatRemaining = formatRemaining; + } + + public string ProgressPhaseText + { + get => _progressPhaseText; + set => SetProperty(ref _progressPhaseText, value); + } + + public string ProgressCounterText + { + get => _progressCounterText; + set => SetProperty(ref _progressCounterText, value); + } + + public string StageRemainingTimeText + { + get => _stageRemainingTimeText; + set => SetProperty(ref _stageRemainingTimeText, value); + } + + public string OverallRemainingTimeText + { + get => _overallRemainingTimeText; + set => SetProperty(ref _overallRemainingTimeText, value); + } + + public bool IsAdditionalProgressInfoVisible + { + get => _isAdditionalProgressInfoVisible; + set => SetProperty(ref _isAdditionalProgressInfoVisible, value); + } + + public string? ProgressViewMoreText + { + get => _progressViewMoreText; + set => SetProperty(ref _progressViewMoreText, value); + } + + public void ToggleAdditionalProgressInfo() + { + IsAdditionalProgressInfoVisible = !IsAdditionalProgressInfoVisible; + UpdateProgressViewMoreText(); + } + + public void UpdateProgressViewMoreText() => + ProgressViewMoreText = _text(IsAdditionalProgressInfoVisible ? "ViewLess" : "ViewMore"); + + public void UpdateProgressText() + { + ProgressPhaseText = _phase() switch + { + BlockCheckScanPhase.BaselineProbing => _text("BlockCheck2PhaseBaseline"), + BlockCheckScanPhase.StartingStrategy => _text("BlockCheck2PhaseStartingStrategy"), + BlockCheckScanPhase.Probing => _text("BlockCheck2PhaseProbing"), + BlockCheckScanPhase.StrategyCompleted => _text("BlockCheck2PhaseStrategyCompleted"), + BlockCheckScanPhase.ValidatingPreset => _text("BlockCheck2PhaseValidatingConfig"), + BlockCheckScanPhase.RepairingPreset => _text("BlockCheck2PhaseRepairingConfig"), + _ => _text("BlockCheck2PhasePreparing"), + }; + ProgressCounterText = string.Format( + _text("BlockCheck2ProgressCounterFormat"), + _current(), + _total()); + StageRemainingTimeText = FormatRemainingTime(); + OverallRemainingTimeText = FormatOverallRemainingTime(); + } + + public string FormatRemainingTime() + { + if (!_running() && _phase().HasValue) + { + return "—"; + } + + return _formatRemaining(_stageEstimate(), "BlockCheck2RemainingTimeCalculating"); + } + + public string FormatOverallRemainingTime() + { + if (!_running() && _phase().HasValue) + { + return "—"; + } + + return _formatRemaining( + _overallEstimate(), + _phase() == BlockCheckScanPhase.BaselineProbing + ? "BlockCheck2OverallTimeCalculating" + : "BlockCheck2RemainingTimeCalculating"); + } +} diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index 0040256d..c69f57ab 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1458,8 +1458,8 @@ }, { "path": "docs/superpowers/specs/2026-11-11-blockcheck-progress-presentation-design.md", - "firstIntroduction": "Local MainPage progress presentation state contract under issue219; base3da11cb098d3e1241b2a86cd86ee0c14d80b1942", - "first_commit": null, + "firstIntroduction": "9de4d0d87bdd5feaa49451b3885e892c32c353cf\tleather147\tRecord MainPage progress presentation design", + "first_commit": "9de4d0d87bdd5feaa49451b3885e892c32c353cf", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", @@ -1468,13 +1468,23 @@ }, { "path": "docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md", - "firstIntroduction": "Local MainPage progress presentation state contract under issue219; base3da11cb098d3e1241b2a86cd86ee0c14d80b1942", - "first_commit": null, + "firstIntroduction": "9de4d0d87bdd5feaa49451b3885e892c32c353cf\tleather147\tRecord MainPage progress presentation design", + "first_commit": "9de4d0d87bdd5feaa49451b3885e892c32c353cf", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", "language": "en", "changes": "Define six-value progress state ownership, live-read and host notification contracts with isolated verification; no integrated acceptance." + }, + { + "path": "docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md", + "firstIntroduction": "Local progress presentation verification under issue219; product introduction is recorded after the checkpoint commit.", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Record focused mutation and full suite evidence, compatibility checks, native qualification and local delivery limits." } ], "current_history_base": "7ead95f7756057f67cd113671a7f84cf422e8d32", diff --git a/docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md b/docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md new file mode 100644 index 00000000..22204f83 --- /dev/null +++ b/docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md @@ -0,0 +1,77 @@ +# MainPage progress presentation verification + +## Scope and source + +[Issue219](https://github.com/lumenpearson/cdpiui/issues/219) accepts a local extraction of six +MainPage display values. The baseline is frozen PR218 at +`3da11cb098d3e1241b2a86cd86ee0c14d80b1942`. The isolated branch is +`dev/blockcheck-progress-presentation`, owned by Codex chat +`01a1bc96-ea11-73a1-a4a1-5cd6db1617fa`. Parent issues13/14/15 remain open; +draft PR216 and218 retain their separate integration boundaries. + +The new internal BlockCheck2ProgressPresentation owns four formatted strings, disclosure visibility +and the ViewMore/ViewLess text. It stores eight lazy ports. The six public host getters and private +setters forward to that owner. Five existing method entrypoints also forward. One synchronous +PropertyChanged bridge keeps the host sender and current value visible to observers. + +Only MainPageViewModel.cs and its Progress partial change in existing product source. The owner is +one new file. Core, AddOns, Shared, numeric progress167, duration formatting, lifecycle, navigation, +completion217, resources, package versions and loaded/unloaded subscriptions are unchanged. + +## Managed behavior checks + +Windows and .NET SDK8.0.427 were used. New tests were written before the owner existed. The first +focused run failed with the expected CS0246 missing BlockCheck2ProgressPresentation. After the +implementation, all42 focused cases passed. The tests cover the six cold values, all phase branches, +null and unknown phases, read/publication order, ambient formatting culture, localization mutation, +terminal short circuits, repeated equal output, all setters, instance isolation and partial failures. + +A controlled mutant read current and total before phase publication. It failed11 cases and passed31. +The failures included stale counter values after phase notifications and counter localization. +The exact original bytes were restored, with SHA256 +`2797C9B7346C6BDA436CAC6CF0A042EAE5837D5E3A065CC48C410D30E179C7E8`. +The restored focused run passed42/42 in20ms. The full suite then passed2243/2243 in9s, +with zero failures and skips. + +```text +C:/Users/lumen/.dotnet/dotnet.exe test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release --no-restore --filter FullyQualifiedName~BlockCheck2ProgressPresentationTests +C:/Users/lumen/.dotnet/dotnet.exe test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release --no-restore +C:/Users/lumen/.dotnet/dotnet.exe build CDPIUI/CDPIUI.csproj -c Release -p:Platform=x64 --no-restore +``` + +The normal WinUI build passed with zero warnings/errors in42.52s. Its previous accepted DLL was +copied before this build. Historical217 runtime checks retain their historical normal-output hash; +they must not be executed against a newly rebuilt output and presented as current evidence. + +## Contract and footprint checks + +The source inventory compared613 baseline GUI C# files with614 current files. All451 original +exported source type signatures remain. The compiled comparison preserved452 GUI and88 Core +exported type shapes, with zero removed/changed shapes and zero additions on retained types. +These checks do not certify every annotation, attribute, native ABI or runtime behavior. + +A source guard compares literal policy tokens under the eight declared lazy-port substitutions. +It also checks all six cold fields, host private setters, five forwards, the exact constructor +wiring, one synchronous bridge, unchanged completion body and every previous constructor statement. +The first guard attempt incorrectly replaced the Text suffix inside method names. A word-boundary +replacement corrected the verification script; product source did not change for this tool failure. +The corrected guard passed. + +## Native and delivery status + +Native qualification and final delivery are pending at this product checkpoint. The next step is a +fresh source-pinned fixture that retains all154 accepted groups and their case bytes, with the same21 +inert boundary cuts. New actual-host cases must verify the facade and synchronous bridge, including +equal values, sender identity, callback mutation, nested disclosure and exception partial effects. +Independent review and a new explicit UI lease are required before launch. No actual native result, +full Page visual result, XAML Loading, installed-product acceptance, G1 acceptance, merge or release +is claimed here. + +The actual Project7 intake was read after reload under exclusive grant107: In progress, P2, +Architecture, Medium, G2, lumenpearson and exactly two canonical labels. The queue released108. +The [intake receipt](https://github.com/lumenpearson/cdpiui/issues/219#issuecomment-6794116445) +records that private Project result. CI metadata does not verify private Project fields. + +All accepted and rejected artifacts remain in the ignored workspace for this plan. No prior fixture, +worktree, branch or evidence directory is deleted. Local acceptance requires the later final review, +stacked draft checks, six-section acceptance record, completed issue and actual ProjectDone readback. From 1ea41fb3beaeb3bd790b9e4970f687c21bdb0f13 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:42:31 +0300 Subject: [PATCH 12/31] Record MainPage progress native qualification The progress presentation extraction now has actual host evidence on its product checkpoint. The fresh fixture preserves every prior case and boundary cut while adding six focused host groups. Independent checks verified the source inputs, executable manifest, resources, complete output baseline and exact launch pins before execution. One leased process passed all 160 groups with no failures and retained every expected file hash after exit. The report distinguishes source and managed checks from direct native assertions. It records the remaining positive overall estimate and ViewLess coverage limits. Parent integration and release acceptance remain open, and the shared interface queue was released after process cleanup. These documentation changes preserve the tested product and immutable fixture bytes. Changed files: - "docs/governance/document-inventory.json" (+2/-2 lines). - "docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md" (+8/-8 lines). - "docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md" (+56/-9 lines). The file counts compare the staged tree with its first parent. Refs: #219 Staged-Tree: bdb1c221bf7ade7a3d4196e10c00953fc0948f4a --- docs/governance/document-inventory.json | 4 +- ...-11-11-blockcheck-progress-presentation.md | 16 ++--- ...heck-progress-presentation-verification.md | 65 ++++++++++++++++--- 3 files changed, 66 insertions(+), 19 deletions(-) diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index c69f57ab..a2b26236 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1478,8 +1478,8 @@ }, { "path": "docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md", - "firstIntroduction": "Local progress presentation verification under issue219; product introduction is recorded after the checkpoint commit.", - "first_commit": null, + "firstIntroduction": "41585746c9171aac7827760332c8f79f919f6f48\tleather147\tExtract MainPage progress presentation state", + "first_commit": "41585746c9171aac7827760332c8f79f919f6f48", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", diff --git a/docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md b/docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md index fc9152fa..4ef0c731 100644 --- a/docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md +++ b/docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md @@ -42,14 +42,14 @@ test project link, this design/plan and additive document inventory. properties and Toggle/Update/Format methods with the old names. MainPage preserves its public and private forwarding entrypoints and one PropertyChanged bridge. -- [ ] Read the issue/design and actual fields; preserve parent and current source/compiled/normal +- [x] Read the issue/design and actual fields; preserve parent and current source/compiled/normal artifact baselines. Have a fresh builder check the design before code. -- [ ] Write focused tests first and observe the expected missing-component/behavior RED. -- [ ] Implement cold owner state, exact original policy and host facade/bridge, without touching +- [x] Write focused tests first and observe the expected missing-component/behavior RED. +- [x] Implement cold owner state, exact original policy and host facade/bridge, without touching lifecycle/estimator/duration/navigation/completion. Run focused tests and inspect real results. -- [ ] Apply a meaningful controlled early-read/cache mutation, observe behavior assertions fail, +- [x] Apply a meaningful controlled early-read/cache mutation, observe behavior assertions fail, restore exact bytes/hash and run focused/full GREEN plus normal Release/x64 GUI0-0. -- [ ] Verify source/compiled public preservation, exact product footprint, source/bridge/read-order +- [x] Verify source/compiled public preservation, exact product footprint, source/bridge/read-order guards, governance and redacted secret scans. Record failures and commit the product checkpoint. ### Task 2: Qualify actual host composition and accept locally @@ -60,11 +60,11 @@ dedicated verification report and additive inventory. **Interfaces:** consumes Task1 source pin and accepted154 source/cases/cuts; produces an independently reviewed new actual-host corpus, pins/runtime/postchecks and local delivery record. -- [ ] Read Task1 evidence; preserve154 prior labels/case bytes, derive all source inputs/cuts/extras +- [x] Read Task1 evidence; preserve154 prior labels/case bytes, derive all source inputs/cuts/extras and new actual host cases before compiling a fresh path. -- [ ] Obtain independent pre-build review, build0-0, derive actual artifacts/resources/source/runner/ +- [x] Obtain independent pre-build review, build0-0, derive actual artifacts/resources/source/runner/ verifier pins and all prior output hashes, then independent prelaunch READY. -- [ ] Coordinate a new explicit lease, execute one owned process and prove labels/COMPLETE/exit0, +- [x] Coordinate a new explicit lease, execute one owned process and prove labels/COMPLETE/exit0, streams/IO/source/resources/hashes/absence/process cleanup; idle/requestfalse/guarded release. - [ ] Update evidence/docs; obtain fresh whole-change review, resolve Critical/Important with observed RED→GREEN and ledger rulings/deferred minors. Preserve original artifacts. diff --git a/docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md b/docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md index 22204f83..f2e90f10 100644 --- a/docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md +++ b/docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md @@ -17,6 +17,8 @@ PropertyChanged bridge keeps the host sender and current value visible to observ Only MainPageViewModel.cs and its Progress partial change in existing product source. The owner is one new file. Core, AddOns, Shared, numeric progress167, duration formatting, lifecycle, navigation, completion217, resources, package versions and loaded/unloaded subscriptions are unchanged. +Product checkpoint: `41585746c9171aac7827760332c8f79f919f6f48`. The four MainPage partials +decreased from785 to740 lines; the Progress partial decreased from123 to71 lines. ## Managed behavior checks @@ -57,15 +59,60 @@ The first guard attempt incorrectly replaced the Text suffix inside method names replacement corrected the verification script; product source did not change for this tool failure. The corrected guard passed. -## Native and delivery status - -Native qualification and final delivery are pending at this product checkpoint. The next step is a -fresh source-pinned fixture that retains all154 accepted groups and their case bytes, with the same21 -inert boundary cuts. New actual-host cases must verify the facade and synchronous bridge, including -equal values, sender identity, callback mutation, nested disclosure and exception partial effects. -Independent review and a new explicit UI lease are required before launch. No actual native result, -full Page visual result, XAML Loading, installed-product acceptance, G1 acceptance, merge or release -is claimed here. +## Actual native qualification + +The new fixture is `F:/cdpiui-verify/cdpiui-blockcheck-progress-4158574-20261111`, archived from +the full product pin above. It contains1584 Git inputs, exactly21 retained boundary cuts and37 +allowed extras. All31 prior case partials retain their bytes. There are33 bootstrap files: the main +bootstrap,31 prior partials and the new ProgressPresentation partial. The owner and MainPage remain +uncut. The six new groups use actual Session/progress fields, private delegates, duration formatting, +localization and the synchronous bridge on the real dispatcher. The two-method fake view proves +composition. It does not load the actual Page or establish visual/XAML behavior. + +An independent read-only review found zero Critical/Important isolation defects before build. The +native build then passed0 warnings/0 errors in60.27s. A second independent check read the actual +AMD64 PE32+ manifest: asInvoker and uiAccess=false. The current token was non-admin and the exact +executable was absent. The reviewer reconstructed all1584 inputs/cuts/extras and rehashed all522 +binary-output files and all60 approved inputs. Root independently rehashed these before the lease. + +The60 pins comprise5 owned binaries,20 resources and35 source/evidence files. All20 resources match +generated bytes and5206 source-JSON entries. All24 relevant English keys are nonempty. Selected pins: + +| Artifact | SHA256 | +| --- | --- | +| Native GUI DLL | `6D9C0EA87245C1FE3DBB1643705418742E57E1C8ADF41F858164981B259EAF19` | +| Runner | `58F00954477C97EEBAAF1B7E2937ED2328E24F913D969BEC64F1AD4218BB8EBC` | +| Runtime verifier | `27E154518F7BCAF014262D07BB504D5946B1C2FAE05CCF7B089A7181D12268C9` | +| Complete output baseline | `C9CD5B1882AE57AF8A2EEB2AE31C2C74353815D017F6E808D87FDE20F6C46939` | +| Accepted corpus | `B903AFB4F22ED8FAA2B5D59EA18568CCEDADE648986F0A2C41547DD5E2775DE0` | +| New case partial | `BFFA558CDD39C8FD9FA28097C735075127EDD2AA1786908F871EE8F0FDD57F6C` | + +Fresh queue112 was released with all six participants paused. A guarded transfer granted Root113 +only for this process. One actual process, PID88728, passed160 unique groups with the exact154 +prefix, one COMPLETE, zero FAIL lines, exit0 and empty stdout/stderr. The retained Root137 prefix +and Peer141 projection also match. All source/resource/artifact pins and all522 prior filenames and +hashes passed after exit. Exactly six new names increased the output count to528. The three literal +inputs retain lengths16/16/15. The two real serializer reports retain exact354/260-byte golden data, +hashes and current model fields. Settings, custom-site and forbidden export markers remain absent. +The normal GUI DLL remains `1E4FEF4A5FB5FE62543F345FA9D8DB38ABFEF61867F46BF85FF0BE38A55B2205`. + +Root separately verified PID88728 and the exact executable absent, wrote idle113/requestfalse and +released the queue to114 with owner:null and all six participants paused. There was no desktop input, +elevation, OnLoaded, scan, backend/history/cleanup operation, settings write or deletion. Existing +inert settings constructor reads and normal collaborator construction remain part of the fixture. + +The six new groups directly cover cold values, all private setters, host sender, equality, phase and +duration entrypoints, ordered callback mutation, independent instances, nested disclosure and observer +exception identity/partial effects/retry. A distinct positive overall estimate and a settled ordinary +ViewLess toggle have source and managed-test evidence only. This Minor native coverage limit is +retained explicitly; it is not attributed to the native assertions. + +## Delivery status and limits + +Final review, stacked draft final-head checks and local acceptance are pending at this evidence +checkpoint. No full Page visual, XAML Loading, installed-product, G1, merge or release acceptance is +claimed. Raw recipes, pins, logs, manifests, baseline and postchecks remain in this plan's ignored +workspace `.superpowers/sdd/2026-11-11-blockcheck-progress-presentation/`. The actual Project7 intake was read after reload under exclusive grant107: In progress, P2, Architecture, Medium, G2, lumenpearson and exactly two canonical labels. The queue released108. From 3c7f8961477dbff0b4b021493b629ba1a1a0fa05 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:47:52 +0300 Subject: [PATCH 13/31] Record MainPage progress review outcome The fresh reviewer accepted the complete progress presentation change with no critical or important finding. One minor finding identified an inaccurate attribution of positive overall estimate coverage. The report now states that this positive value reaching the formatter has source evidence only. Managed tests prove the read order and terminal paths, and they directly assert the ordinary ViewLess value. The review record distinguishes independent read and hash comparisons from the recorded owner executions. Product files, tests, native case bytes and launch pins remain unchanged. The plan records the finished review while remote checks and actual delivery metadata remain pending. This correction preserves the bounded local acceptance contract and keeps broader integration and release work separate. Changed files: - "docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md" (+1/-1 lines). - "docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md" (+30/-6 lines). The file counts compare the staged tree with its first parent. Refs: #219 Staged-Tree: 0cb8d40e77cc05866fccb4e4b516f44363fdc18c --- ...-11-11-blockcheck-progress-presentation.md | 2 +- ...heck-progress-presentation-verification.md | 36 +++++++++++++++---- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md b/docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md index 4ef0c731..dda83be1 100644 --- a/docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md +++ b/docs/superpowers/plans/2026-11-11-blockcheck-progress-presentation.md @@ -66,7 +66,7 @@ reviewed new actual-host corpus, pins/runtime/postchecks and local delivery reco verifier pins and all prior output hashes, then independent prelaunch READY. - [x] Coordinate a new explicit lease, execute one owned process and prove labels/COMPLETE/exit0, streams/IO/source/resources/hashes/absence/process cleanup; idle/requestfalse/guarded release. -- [ ] Update evidence/docs; obtain fresh whole-change review, resolve Critical/Important with +- [x] Update evidence/docs; obtain fresh whole-change review, resolve Critical/Important with observed RED→GREEN and ledger rulings/deferred minors. Preserve original artifacts. - [ ] Publish a stacked draft against frozen dev/blockcheck-completion-presentation with Refs14/219; verify exact final-head checks and actual PR/Project fields, no parent or main merge. diff --git a/docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md b/docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md index f2e90f10..69385ff4 100644 --- a/docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md +++ b/docs/superpowers/reports/2026-11-11-blockcheck-progress-presentation-verification.md @@ -89,7 +89,8 @@ generated bytes and5206 source-JSON entries. All24 relevant English keys are non Fresh queue112 was released with all six participants paused. A guarded transfer granted Root113 only for this process. One actual process, PID88728, passed160 unique groups with the exact154 -prefix, one COMPLETE, zero FAIL lines, exit0 and empty stdout/stderr. The retained Root137 prefix +prefix, one COMPLETE, zero FAIL lines, exit0 and empty stdout/stderr. The process ran from +2026-11-11T11:40:39.3366236Z to2026-11-11T11:40:41.9606548+00:00. The retained Root137 prefix and Peer141 projection also match. All source/resource/artifact pins and all522 prior filenames and hashes passed after exit. Exactly six new names increased the output count to528. The three literal inputs retain lengths16/16/15. The two real serializer reports retain exact354/260-byte golden data, @@ -103,14 +104,37 @@ inert settings constructor reads and normal collaborator construction remain par The six new groups directly cover cold values, all private setters, host sender, equality, phase and duration entrypoints, ordered callback mutation, independent instances, nested disclosure and observer -exception identity/partial effects/retry. A distinct positive overall estimate and a settled ordinary -ViewLess toggle have source and managed-test evidence only. This Minor native coverage limit is -retained explicitly; it is not attributed to the native assertions. +exception identity/partial effects/retry. Passing a distinct positive overall estimate to the +formatter is supported by source inspection only. Managed tests cover overall read order, null +formatting and terminal short circuits; the positive value assigned in the terminal test is not read. +An ordinary settled ViewLess value has a direct managed assertion. Neither positive overall +formatting nor settled ViewLess is directly asserted by the native cases. These coverage limits +remain explicit and are not attributed to executed assertions that do not exist. + +## Independent final review + +Fresh reviewer progress_presentation_final_review examined the complete nine-file range +`3da11cb098d3e1241b2a86cd86ee0c14d80b1942` through +`1ea41fb3beaeb3bd790b9e4970f687c21bdb0f13`: zero Critical, zero Important and one Minor. +The Minor identified the coverage-attribution wording above. This report now distinguishes the +source-only positive overall value from the managed ViewLess assertion. Product, tests and native +case/pin bytes remain unchanged; the positive overall execution gap remains deferred. + +The reviewer traced all lazy reads, culture selection, setters, bridge, nested disclosure and partial +effects. Independent hashing checked all60 approved pins, all522 prior outputs, inputs, golden +reports, restored owner, native case and normal GUI. The reviewer also compared the raw160 corpus +and streams. Build/test/process execution remains the owner's recorded evidence; the reviewer used +read-only comparisons. The verdict supports the stacked draft and this bounded local result. + +Full Page rendering/focus/activation, independent qualification of unchanged operating components, +GC collection, installed-product behavior and broad G1/release acceptance remain separate. Source +supports instance ownership and no new static root, without a new collection experiment. Final +remote checks and actual private Project readbacks must precede local closure. ## Delivery status and limits -Final review, stacked draft final-head checks and local acceptance are pending at this evidence -checkpoint. No full Page visual, XAML Loading, installed-product, G1, merge or release acceptance is +Stacked draft final-head checks and local acceptance are pending at this evidence checkpoint. +No full Page visual, XAML Loading, installed-product, G1, merge or release acceptance is claimed. Raw recipes, pins, logs, manifests, baseline and postchecks remain in this plan's ignored workspace `.superpowers/sdd/2026-11-11-blockcheck-progress-presentation/`. From 330458e623ead885a632c5ff0abd5e7fd9bbb739 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:13:28 +0300 Subject: [PATCH 14/31] Record MainPage review presentation design The MainPage model still stores six review strings beside navigation and notices. This design gives their policy a focused observable owner and a live read only source. A direct Session adapter preserves fifteen current getters without copying values. Existing host setters and the supplied preview entrypoint remain synchronous forwards with the original sender and exception behavior. The plan requires focused tests before implementation and a controlled cache mutation before exact restoration. It also requires public contract comparisons and a fresh native fixture that retains all 160 prior groups. The builder check found nothing important left before planning. Product implementation has not started, and broader integration and release acceptance remain separate. Changed files: - "docs/governance/document-inventory.json" (+20/-0 lines). - "docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md" (+76/-0 lines). - "docs/superpowers/specs/2026-11-11-blockcheck-review-presentation-design.md" (+139/-0 lines). The file counts compare the staged tree with its first parent. Refs: #221 Staged-Tree: f9f28d58588947d2a3fbc6ba8c04d645a422333f --- docs/governance/document-inventory.json | 20 +++ ...26-11-11-blockcheck-review-presentation.md | 76 ++++++++++ ...1-blockcheck-review-presentation-design.md | 139 ++++++++++++++++++ 3 files changed, 235 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md create mode 100644 docs/superpowers/specs/2026-11-11-blockcheck-review-presentation-design.md diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index a2b26236..cdb204c5 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1485,6 +1485,26 @@ "policy": "ASD-STE100 principles for English", "language": "en", "changes": "Record focused mutation and full suite evidence, compatibility checks, native qualification and local delivery limits." + }, + { + "path": "docs/superpowers/specs/2026-11-11-blockcheck-review-presentation-design.md", + "firstIntroduction": "Local MainPage review summary contract under issue221; baseline3c7f8961477dbff0b4b021493b629ba1a1a0fa05.", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Define six-value review state ownership, a direct live Session source, callback/read-order contracts and bounded local qualification." + }, + { + "path": "docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md", + "firstIntroduction": "Local MainPage review summary contract under issue221; baseline3c7f8961477dbff0b4b021493b629ba1a1a0fa05.", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Define six-value review state ownership, a direct live Session source, callback/read-order contracts and bounded local qualification." } ], "current_history_base": "7ead95f7756057f67cd113671a7f84cf422e8d32", diff --git a/docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md b/docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md new file mode 100644 index 00000000..3fd1cbb1 --- /dev/null +++ b/docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md @@ -0,0 +1,76 @@ +# MainPage Review Presentation Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan inline, task-by-task, with a fresh final independent reviewer. + +**Goal:** Move six review strings and their original formatting policy into a focused state owner. + +**Architecture:** An internal owner reads a15-property live source through a direct Session adapter. +Six host properties and one private method forward to it, with one synchronous host-sender bridge. + +**Tech Stack:** C#/.NET8.0.427, xUnit linked source, WinUI3, API/blob and immutable native evidence. + +**Spec:** [review presentation design](../specs/2026-11-11-blockcheck-review-presentation-design.md). + +## Global constraints + +- Issue221 actual intake119 is verified before implementation. Root owns the isolated named branch. +- Base PR2203c7f896 and parent2183da11cb/2163623584 remain frozen and unmerged. +- Preserve six empty values, public getters/private setters and private UpdateReviewSummary(preview). +- All15 source getters remain current direct reads, with exact types, order and repeated calls. +- Preserve preview identity, conditional localization, ambient culture, strings and synchronous events. +- Do not change preview/estimate models, duration implementation, Session/options/site-list behavior, + progress/completion owners, navigation/lifecycle/subscriptions, resources, packages or operating code. +- No real OnLoaded/settings/scan/backend/history/cleanup. Native launch requires independent READY + and a NEW explicit exclusive lease, including all snapshots and read-only UI calls. +- Retain every worktree/ref/archive/accepted and rejected artifact; no deletion, reset or parent merge. + +## Review Focus + +- Source and connections notifications can change every later source value before its original read. +- TLS automatic-name localization can change later protocol/IP flags; connection formatting comes later. +- Mode-name localization can change preset before the second read; TestAllStrategies must short circuit. +- Duration formatting can change later preview observations; nested calls retain each frame's preview. +- Current-field/host-sender/equality/exception semantics depend on one synchronous bridge, with no + new static root, loaded subscription or cached snapshot. + +### Task 1: Extract the review presentation owner and live source + +**Files:** create IBlockCheck2ReviewSource.cs, BlockCheck2ReviewSource.cs and +BlockCheck2ReviewPresentation.cs beside MainPage; modify MainPageViewModel.cs/Review.cs only in +existing product; add CDPIUI.Tests/Presentation/BlockCheck2ReviewPresentationTests.cs and source +links for owner/interface/existing preview; design/plan/report and additive inventory. + +**Interfaces:** consumes15 current Session values through the internal read-only source, Text and +existing FormatDuration. Produces six observable strings and UpdateReviewSummary(preview). Host +preserves six private setters, supplied-preview method and one constructor-owned synchronous bridge. + +- [ ] Read issue/spec/actual intake; preserve source/compiled/normal-output baselines and frozen refs. + Obtain a fresh design-builder verdict before product code. +- [ ] Write focused tests first for the named contract and observe expected missing-component RED. +- [ ] Implement the interface, exact direct adapter, cold owner and original policy; wire host forwards + and one bridge without touching lifecycle or existing owners. Run focused GREEN. +- [ ] Apply a controlled early preset cache and observe behavior assertions fail; restore exact bytes/ + hash and run focused/full GREEN and normal GUI Release/x64 with0 warnings/errors. +- [ ] Verify source/compiled public preservation, exact footprint, literal policy, all15 mappings, + host setters/bridge/remainder, governance and redacted scans. Record failures and commit checkpoint. + +### Task 2: Qualify actual composition and accept locally + +**Files:** fresh F:/cdpiui-verify immutable fixture plus retained ignored recipes, pins, logs and +postchecks; dedicated report and additive inventory. + +**Interfaces:** consumes Task1 source pin and accepted160 recipe/corpus. Produces reviewed actual +host/source/preview cases and explicit local delivery evidence without accepting parent integration. + +- [ ] Read Task1 evidence and brief; preserve all160 labels/old case bytes/21cuts. Derive fresh inputs, + extras/corpus and positive actual-host assertions before build, with no new IO or cuts. +- [ ] Obtain independent pre-build review; build0-0, derive actual binary/resource/source/runner/ + verifier pins and all prior output hashes, then obtain independent prelaunch READY. +- [ ] Coordinate a new explicit lease; execute one owned process, prove exact labels/COMPLETE/exit0, + streams/hash/resource/source/IO/absence/process cleanup; idle/requestfalse and guarded release. +- [ ] Update evidence and obtain fresh whole-branch review; resolve Critical/Important through observed + RED→GREEN, record all rulings/deferred minors and preserve original artifacts. +- [ ] Publish a draft stacked on dev/blockcheck-progress-presentation with Refs14/221; verify exact + final-head checks and actual PR labels/owner/G2/Project fields, without merging a parent or main. +- [ ] Verify all six local criteria, post the six-section acceptance record, immediately close completed/ + set actual ProjectDone and read back closure, criteria, classification and fields. diff --git a/docs/superpowers/specs/2026-11-11-blockcheck-review-presentation-design.md b/docs/superpowers/specs/2026-11-11-blockcheck-review-presentation-design.md new file mode 100644 index 00000000..23ae267a --- /dev/null +++ b/docs/superpowers/specs/2026-11-11-blockcheck-review-presentation-design.md @@ -0,0 +1,139 @@ +# MainPage review summary presentation + +## Intent and accepted boundary + +[Issue #221](https://github.com/lumenpearson/cdpiui/issues/221) owns the next LOCAL audit +decomposition. The baseline is frozen draft PR #220 at +`3c7f8961477dbff0b4b021493b629ba1a1a0fa05`. Its local child #219 is completed with all six +criteria, actual Project Done under grant117, and [final readback](https://github.com/lumenpearson/cdpiui/issues/219#issuecomment-6795215194). +This does not accept the broad integration, G1, installed-product or release boundaries. + +Use `dev/blockcheck-review-presentation` in the existing isolated Root worktree. Actual issue221 +Project intake119 was reloaded and read back before this design and implementation: In progress, +P2, Architecture, Medium, G2, lumenpearson and two canonical labels. The +[intake receipt](https://github.com/lumenpearson/cdpiui/issues/221#issuecomment-6795366566) records +that evidence. The queue released120 with all six participants paused. + +The four MainPage partials total740 lines. Their Review partial still holds six strings and the +policy that formats the preparation summary. Give this responsibility one internal state owner. +The interface and adapter below are the executor's design choice under the user's instruction to +continue independently. A fresh builder must inspect this design before product code changes. + +## Structure and dependencies + +Create three focused files beside the existing MainPage owners: + +| File | Responsibility | +| --- | --- | +| IBlockCheck2ReviewSource.cs | Read-only contract for the15 current Session values used by this policy. | +| BlockCheck2ReviewSource.cs | Direct adapter over one actual BlockCheck2ViewModel, with no copies or policy. | +| BlockCheck2ReviewPresentation.cs | Six observable strings and the literal summary update policy. | + +The owner derives from the existing ObservableObject and receives: + +```csharp +BlockCheck2ReviewPresentation( + IBlockCheck2ReviewSource source, + Func text, + Func formatDuration) +``` + +Store dependencies without invoking them. The source adapter stores the same Session instance +without reading a property during construction. These three constructor dependencies replace a +long list of scalar callbacks; the source remains a live view of Session, never a snapshot DTO. +This contract is internal to this display responsibility. Do not make a generic presentation layer. + +The source contract has exactly these property names and types: + +| Type | Properties | +| --- | --- | +| int | SelectedSiteListCount, SelectedDomainCount | +| bool | IncludeHttp, IncludeTls12, IncludeTls13, IncludeTlsAuto, IncludeQuic | +| bool | IncludeIpv4, IncludeIpv6, TestAllStrategies | +| BlockCheckRunPreset | SelectedRunPreset | +| double | RequestsPerDomain, ConnectTimeoutSeconds, RequestTimeoutSeconds, StartupGraceSeconds | + +Every adapter getter must directly return the corresponding Session property. Keep repeated getter +calls repeated. Do not implement the interface on Session or change its public API, options, +selection controller or settings. Unit tests use a traced mutable source fake; native composition +uses this real adapter and Session. The existing preparation-preview record can be linked into the +test project without modifying it or its estimate model. + +The new owner holds ReviewSourcesText, ReviewConnectionsText, ReviewModeText, ReviewRequestsText, +ReviewTimeoutsText and ReviewMaximumTimeText, each initially string.Empty. Writable owner +properties use the existing SetProperty. The host keeps all six public getters and private setters +as direct forwards. The private host UpdateReviewSummary(BlockCheck2PreparationPreview preview) +forwards the same reference to owner.UpdateReviewSummary(preview). + +Add one readonly owner field. Construct the adapter/owner after existing progress wiring, then +attach one synchronous owner.PropertyChanged bridge to host.OnPropertyChanged(args.PropertyName). +Use no second host SetProperty, queued/batched forwarding, loaded/unloaded registration or static +event. The object graph shares the host lifetime. Preserve every prior constructor statement. + +## Observable policy + +Move the original policy literally, substituting Session accesses with source accesses, Text with +the text delegate and the existing FormatDuration call with its delegate. Preserve the following: + +1. Publish sources, connections, mode, requests, timeouts and maximum duration in that order. Each + later expression observes current inputs after preceding property callbacks. Equal outputs still + evaluate their right-hand side; only notifications are suppressed. +2. Sources localizes its format before reading selected-list count, selected-domain count and the + supplied preview.TargetCount. Do not read preview earlier or introduce a null guard. An invalid + null preview retains the original evaluation order and exception boundary. +3. Construct the protocol array in HTTP, TLS1.2, TLS1.3, localized automatic TLS, QUIC/HTTP3 order. + Keep every literal string, space, conditional localization and OfType filter. Read IPv4 + and IPv6 after that array, then localize the connections format and join both arrays with `, `. +4. Read SelectedRunPreset for the mode name. Quick and Exhaustive retain their keys; every other + value uses Balanced. Localize the name before reading TestAllStrategies. The second preset read + occurs only when TestAllStrategies is false. Keep the original period/space and interpolation + when appending the all-strategies text. Do not cache preset across these operations. +5. Requests and timeouts localize their formats before their numeric getters. Keep numeric types, + argument evaluation order and string.Format's ambient culture after all argument reads. Do not + preformat numbers or capture a culture earlier. +6. Use the same supplied preview for maximum duration. Read MaximumDuration for the null branch; + the positive branch then localizes its format, reads Duration for FormatDuration, and re-reads + MaximumDuration for EstimatedStrategyJobs and EstimatedRequests after that callback. Preserve + these repeated reads and any resulting partial effects or exceptions. +7. Assign each field before its synchronous notification, retaining the host sender. Nested calls + may update the same owner with another preview; the outer frame then continues with its original + preview and current source. Propagate delegate/observer exceptions unchanged, without sticky + recovery state, catches or a reentry guard. + +## Verification + +Write focused linked-source tests before implementation and observe the missing-component RED. +Cover cold dependencies, all15 source properties, literal protocol/IP combinations and order, +conditional TLS localization, preset fallback and second-read short circuit, sources/preview identity, +numeric culture, null and positive maximum estimates, per-publication changes, repeated equality, +nested updates and partial observer/port failures. Explicitly assert a positive maximum estimate +reaches the duration formatter with distinct job/request values. Test null-preview evaluation order. + +A controlled early preset cache must fail an observable mutation assertion. Restore exact bytes and +hash, then pass focused/full suites and normal Release/x64 GUI. Compare source/compiled public +contracts and exact two-host-files/three-internal-files footprint. A source guard must compare policy +tokens, significant strings, all15 direct adapter mappings, six private setters, one bridge and the +unchanged host remainder. Record every failed tool attempt and correction truthfully. + +Build a NEW immutable native fixture from the accepted160 recipe. Preserve all prior case bytes, +labels and21 cuts. The new owner/adapter/MainPage remain uncut. Use actual Session/options and +controlled values, real preview/localizer/duration/dispatcher, and a narrow view with the existing +inert operating ports. Exercise positive maximum formatting, live callback mutations, private +setters/sender/equality, nested previews and exceptions. Seed list-item content explicitly when +needed, so constructors do not read real files. Do not invoke OnLoaded or real scan/settings/history/ +backend/cleanup operations, and add no operating cuts or IO. + +Derive source/extras/corpus/pin counts from the prepared fixture. Obtain independent pre-build and +prelaunch READY, inspect actual non-admin/asInvoker/uiAccessfalse PE and all hashes, then acquire a +new explicit exclusive lease. Prove all prior output hashes, exact labels/COMPLETE/exit/streams, +resource/source/IO/absence/process checks and idle/requestfalse/release. State source-only coverage +separately from executed assertions. No full Page, XAML Loading or GC collection result is inferred. + +## Delivery and exclusions + +Complete fresh final whole-branch review and any required Critical/Important RED→GREEN fixes. +Publish a stacked draft on frozen PR220, verify exact final-head checks and actual PR Project fields, +then post six-section LOCAL acceptance and immediately close completed/set actual Done/read back. +Parent issues13/14/15 and drafts216/218/220 retain their separate integration and release boundaries. +No shared-main change, installation, dependency update, security takeover or destructive operation +is authorized by this stage. Retain all workspaces, refs and accepted/rejected evidence. From 1c2d44336fe4bb97bc100a5102fc7a7667d65068 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:25:36 +0300 Subject: [PATCH 15/31] Extract MainPage review summary presentation The review summary still mixed mutable display fields with the wizard host. The new internal owner keeps six values and reads current Session data through a direct adapter. Public getters, private setters and the original preview entrypoint remain synchronous forwards. This preserves argument order, culture, notification sender, reentry and partial exceptions without changing Session policy or operating boundaries. Focused tests were written before implementation and detected the missing owner. An early preset cache then failed twelve cases before exact source restoration. All 2430 managed tests and the normal WinUI build pass with the restored policy. Public contract comparisons and exact source guards also pass, while fresh native qualification remains the next local acceptance step. Changed files: - "CDPIUI.Tests/CDPIUI.Tests.csproj" (+3/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2ReviewPresentationTests.cs" (+491/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Review.cs" (+14/-81 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs" (+4/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReviewPresentation.cs" (+123/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReviewSource.cs" (+27/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/IBlockCheck2ReviewSource.cs" (+22/-0 lines). - "docs/governance/document-inventory.json" (+14/-4 lines). - "docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md" (+87/-0 lines). The file counts compare the staged tree with its first parent. Refs: #221 Staged-Tree: 59b1311aa3e29f9cedd0c4fd5502a26ebdccc6a5 --- CDPIUI.Tests/CDPIUI.Tests.csproj | 3 + .../BlockCheck2ReviewPresentationTests.cs | 491 ++++++++++++++++++ .../BlockCheck2MainPageViewModel.Review.cs | 95 +--- .../BlockCheck2MainPageViewModel.cs | 4 + .../BlockCheck2ReviewPresentation.cs | 123 +++++ .../BlockCheck2/BlockCheck2ReviewSource.cs | 27 + .../BlockCheck2/IBlockCheck2ReviewSource.cs | 22 + docs/governance/document-inventory.json | 18 +- ...kcheck-review-presentation-verification.md | 87 ++++ 9 files changed, 785 insertions(+), 85 deletions(-) create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2ReviewPresentationTests.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReviewPresentation.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReviewSource.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/IBlockCheck2ReviewSource.cs create mode 100644 docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md diff --git a/CDPIUI.Tests/CDPIUI.Tests.csproj b/CDPIUI.Tests/CDPIUI.Tests.csproj index 30e86078..48d496aa 100644 --- a/CDPIUI.Tests/CDPIUI.Tests.csproj +++ b/CDPIUI.Tests/CDPIUI.Tests.csproj @@ -54,6 +54,9 @@ + + + diff --git a/CDPIUI.Tests/Presentation/BlockCheck2ReviewPresentationTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2ReviewPresentationTests.cs new file mode 100644 index 00000000..80af8f82 --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2ReviewPresentationTests.cs @@ -0,0 +1,491 @@ +using System.Globalization; +using CDPIUI.AddOns.BlockCheck2.Presentation; +using CDPIUI.ViewModels; +using CDPIUI.ViewModels.BlockCheck2; + +namespace CDPIUI.Tests.Presentation; + +public class BlockCheck2ReviewPresentationTests +{ + [Fact] + public void ConstructorKeepsSixEmptyValuesWithoutReadingDependencies() + { + var owner = new BlockCheck2ReviewPresentation(null!, + _ => throw new InvalidOperationException("Early text read"), + _ => throw new InvalidOperationException("Early duration format")); + + Assert.Equal(string.Empty, owner.ReviewSourcesText); + Assert.Equal(string.Empty, owner.ReviewConnectionsText); + Assert.Equal(string.Empty, owner.ReviewModeText); + Assert.Equal(string.Empty, owner.ReviewRequestsText); + Assert.Equal(string.Empty, owner.ReviewTimeoutsText); + Assert.Equal(string.Empty, owner.ReviewMaximumTimeText); + } + + [Theory] + [InlineData(0, "C:|")] + [InlineData(1, "C:HTTP|")] + [InlineData(2, "C:TLS 1.2|")] + [InlineData(3, "C:HTTP, TLS 1.2|")] + [InlineData(4, "C:TLS 1.3|")] + [InlineData(5, "C:HTTP, TLS 1.3|")] + [InlineData(6, "C:TLS 1.2, TLS 1.3|")] + [InlineData(7, "C:HTTP, TLS 1.2, TLS 1.3|")] + [InlineData(8, "C:auto|")] + [InlineData(9, "C:HTTP, auto|")] + [InlineData(10, "C:TLS 1.2, auto|")] + [InlineData(11, "C:HTTP, TLS 1.2, auto|")] + [InlineData(12, "C:TLS 1.3, auto|")] + [InlineData(13, "C:HTTP, TLS 1.3, auto|")] + [InlineData(14, "C:TLS 1.2, TLS 1.3, auto|")] + [InlineData(15, "C:HTTP, TLS 1.2, TLS 1.3, auto|")] + [InlineData(16, "C:QUIC / HTTP/3|")] + [InlineData(17, "C:HTTP, QUIC / HTTP/3|")] + [InlineData(18, "C:TLS 1.2, QUIC / HTTP/3|")] + [InlineData(19, "C:HTTP, TLS 1.2, QUIC / HTTP/3|")] + [InlineData(20, "C:TLS 1.3, QUIC / HTTP/3|")] + [InlineData(21, "C:HTTP, TLS 1.3, QUIC / HTTP/3|")] + [InlineData(22, "C:TLS 1.2, TLS 1.3, QUIC / HTTP/3|")] + [InlineData(23, "C:HTTP, TLS 1.2, TLS 1.3, QUIC / HTTP/3|")] + [InlineData(24, "C:auto, QUIC / HTTP/3|")] + [InlineData(25, "C:HTTP, auto, QUIC / HTTP/3|")] + [InlineData(26, "C:TLS 1.2, auto, QUIC / HTTP/3|")] + [InlineData(27, "C:HTTP, TLS 1.2, auto, QUIC / HTTP/3|")] + [InlineData(28, "C:TLS 1.3, auto, QUIC / HTTP/3|")] + [InlineData(29, "C:HTTP, TLS 1.3, auto, QUIC / HTTP/3|")] + [InlineData(30, "C:TLS 1.2, TLS 1.3, auto, QUIC / HTTP/3|")] + [InlineData(31, "C:HTTP, TLS 1.2, TLS 1.3, auto, QUIC / HTTP/3|")] + [InlineData(32, "C:|IPv4")] + [InlineData(33, "C:HTTP|IPv4")] + [InlineData(34, "C:TLS 1.2|IPv4")] + [InlineData(35, "C:HTTP, TLS 1.2|IPv4")] + [InlineData(36, "C:TLS 1.3|IPv4")] + [InlineData(37, "C:HTTP, TLS 1.3|IPv4")] + [InlineData(38, "C:TLS 1.2, TLS 1.3|IPv4")] + [InlineData(39, "C:HTTP, TLS 1.2, TLS 1.3|IPv4")] + [InlineData(40, "C:auto|IPv4")] + [InlineData(41, "C:HTTP, auto|IPv4")] + [InlineData(42, "C:TLS 1.2, auto|IPv4")] + [InlineData(43, "C:HTTP, TLS 1.2, auto|IPv4")] + [InlineData(44, "C:TLS 1.3, auto|IPv4")] + [InlineData(45, "C:HTTP, TLS 1.3, auto|IPv4")] + [InlineData(46, "C:TLS 1.2, TLS 1.3, auto|IPv4")] + [InlineData(47, "C:HTTP, TLS 1.2, TLS 1.3, auto|IPv4")] + [InlineData(48, "C:QUIC / HTTP/3|IPv4")] + [InlineData(49, "C:HTTP, QUIC / HTTP/3|IPv4")] + [InlineData(50, "C:TLS 1.2, QUIC / HTTP/3|IPv4")] + [InlineData(51, "C:HTTP, TLS 1.2, QUIC / HTTP/3|IPv4")] + [InlineData(52, "C:TLS 1.3, QUIC / HTTP/3|IPv4")] + [InlineData(53, "C:HTTP, TLS 1.3, QUIC / HTTP/3|IPv4")] + [InlineData(54, "C:TLS 1.2, TLS 1.3, QUIC / HTTP/3|IPv4")] + [InlineData(55, "C:HTTP, TLS 1.2, TLS 1.3, QUIC / HTTP/3|IPv4")] + [InlineData(56, "C:auto, QUIC / HTTP/3|IPv4")] + [InlineData(57, "C:HTTP, auto, QUIC / HTTP/3|IPv4")] + [InlineData(58, "C:TLS 1.2, auto, QUIC / HTTP/3|IPv4")] + [InlineData(59, "C:HTTP, TLS 1.2, auto, QUIC / HTTP/3|IPv4")] + [InlineData(60, "C:TLS 1.3, auto, QUIC / HTTP/3|IPv4")] + [InlineData(61, "C:HTTP, TLS 1.3, auto, QUIC / HTTP/3|IPv4")] + [InlineData(62, "C:TLS 1.2, TLS 1.3, auto, QUIC / HTTP/3|IPv4")] + [InlineData(63, "C:HTTP, TLS 1.2, TLS 1.3, auto, QUIC / HTTP/3|IPv4")] + [InlineData(64, "C:|IPv6")] + [InlineData(65, "C:HTTP|IPv6")] + [InlineData(66, "C:TLS 1.2|IPv6")] + [InlineData(67, "C:HTTP, TLS 1.2|IPv6")] + [InlineData(68, "C:TLS 1.3|IPv6")] + [InlineData(69, "C:HTTP, TLS 1.3|IPv6")] + [InlineData(70, "C:TLS 1.2, TLS 1.3|IPv6")] + [InlineData(71, "C:HTTP, TLS 1.2, TLS 1.3|IPv6")] + [InlineData(72, "C:auto|IPv6")] + [InlineData(73, "C:HTTP, auto|IPv6")] + [InlineData(74, "C:TLS 1.2, auto|IPv6")] + [InlineData(75, "C:HTTP, TLS 1.2, auto|IPv6")] + [InlineData(76, "C:TLS 1.3, auto|IPv6")] + [InlineData(77, "C:HTTP, TLS 1.3, auto|IPv6")] + [InlineData(78, "C:TLS 1.2, TLS 1.3, auto|IPv6")] + [InlineData(79, "C:HTTP, TLS 1.2, TLS 1.3, auto|IPv6")] + [InlineData(80, "C:QUIC / HTTP/3|IPv6")] + [InlineData(81, "C:HTTP, QUIC / HTTP/3|IPv6")] + [InlineData(82, "C:TLS 1.2, QUIC / HTTP/3|IPv6")] + [InlineData(83, "C:HTTP, TLS 1.2, QUIC / HTTP/3|IPv6")] + [InlineData(84, "C:TLS 1.3, QUIC / HTTP/3|IPv6")] + [InlineData(85, "C:HTTP, TLS 1.3, QUIC / HTTP/3|IPv6")] + [InlineData(86, "C:TLS 1.2, TLS 1.3, QUIC / HTTP/3|IPv6")] + [InlineData(87, "C:HTTP, TLS 1.2, TLS 1.3, QUIC / HTTP/3|IPv6")] + [InlineData(88, "C:auto, QUIC / HTTP/3|IPv6")] + [InlineData(89, "C:HTTP, auto, QUIC / HTTP/3|IPv6")] + [InlineData(90, "C:TLS 1.2, auto, QUIC / HTTP/3|IPv6")] + [InlineData(91, "C:HTTP, TLS 1.2, auto, QUIC / HTTP/3|IPv6")] + [InlineData(92, "C:TLS 1.3, auto, QUIC / HTTP/3|IPv6")] + [InlineData(93, "C:HTTP, TLS 1.3, auto, QUIC / HTTP/3|IPv6")] + [InlineData(94, "C:TLS 1.2, TLS 1.3, auto, QUIC / HTTP/3|IPv6")] + [InlineData(95, "C:HTTP, TLS 1.2, TLS 1.3, auto, QUIC / HTTP/3|IPv6")] + [InlineData(96, "C:|IPv4, IPv6")] + [InlineData(97, "C:HTTP|IPv4, IPv6")] + [InlineData(98, "C:TLS 1.2|IPv4, IPv6")] + [InlineData(99, "C:HTTP, TLS 1.2|IPv4, IPv6")] + [InlineData(100, "C:TLS 1.3|IPv4, IPv6")] + [InlineData(101, "C:HTTP, TLS 1.3|IPv4, IPv6")] + [InlineData(102, "C:TLS 1.2, TLS 1.3|IPv4, IPv6")] + [InlineData(103, "C:HTTP, TLS 1.2, TLS 1.3|IPv4, IPv6")] + [InlineData(104, "C:auto|IPv4, IPv6")] + [InlineData(105, "C:HTTP, auto|IPv4, IPv6")] + [InlineData(106, "C:TLS 1.2, auto|IPv4, IPv6")] + [InlineData(107, "C:HTTP, TLS 1.2, auto|IPv4, IPv6")] + [InlineData(108, "C:TLS 1.3, auto|IPv4, IPv6")] + [InlineData(109, "C:HTTP, TLS 1.3, auto|IPv4, IPv6")] + [InlineData(110, "C:TLS 1.2, TLS 1.3, auto|IPv4, IPv6")] + [InlineData(111, "C:HTTP, TLS 1.2, TLS 1.3, auto|IPv4, IPv6")] + [InlineData(112, "C:QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(113, "C:HTTP, QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(114, "C:TLS 1.2, QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(115, "C:HTTP, TLS 1.2, QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(116, "C:TLS 1.3, QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(117, "C:HTTP, TLS 1.3, QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(118, "C:TLS 1.2, TLS 1.3, QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(119, "C:HTTP, TLS 1.2, TLS 1.3, QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(120, "C:auto, QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(121, "C:HTTP, auto, QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(122, "C:TLS 1.2, auto, QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(123, "C:HTTP, TLS 1.2, auto, QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(124, "C:TLS 1.3, auto, QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(125, "C:HTTP, TLS 1.3, auto, QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(126, "C:TLS 1.2, TLS 1.3, auto, QUIC / HTTP/3|IPv4, IPv6")] + [InlineData(127, "C:HTTP, TLS 1.2, TLS 1.3, auto, QUIC / HTTP/3|IPv4, IPv6")] + public void ProtocolAndIpTruthTableRetainsLiteralOrderAndSeparators(int mask, string expected) + { + using var f = new Fixture(); f.Source.Mask = mask; + f.Update(); + Assert.Equal(expected, f.Owner.ReviewConnectionsText); + Assert.Equal((mask & 8) != 0, f.Trace.Contains("text:BlockCheck2TlsAutoShortName")); + } + + [Fact] + public void UpdateReadsAndPublishesInTheOriginalOrder() + { + using var f = new Fixture(); f.Update(); + Assert.Equal(["text:BlockCheck2ReviewSourcesFormat", "lists", "domains", "changed:ReviewSourcesText", + "http", "tls12", "tls13", "tlsauto", "quic", "ipv4", "ipv6", "text:BlockCheck2ReviewConnectionsFormat", + "changed:ReviewConnectionsText", "preset", "text:BlockCheck2QuickModeName", "all", "preset", "changed:ReviewModeText", + "text:BlockCheck2ReviewRequestsFormat", "requests", "changed:ReviewRequestsText", + "text:BlockCheck2ReviewTimeoutsFormat", "connect", "request", "grace", "changed:ReviewTimeoutsText", + "text:BlockCheck2ReviewMaximumTimeUnavailable", "changed:ReviewMaximumTimeText"], f.Trace); + Assert.Equal(["S:2/5/11", "C:HTTP|IPv4", "quick", "R:2.5", "T:1.25|3.5|0.75", "none"], f.Values); + } + + [Theory] + [InlineData(BlockCheckRunPreset.Quick, "quick")] + [InlineData(BlockCheckRunPreset.Balanced, "balanced")] + [InlineData(BlockCheckRunPreset.Exhaustive, "exhaustive. all")] + [InlineData((BlockCheckRunPreset)999, "balanced")] + public void PresetBranchesAndUnknownFallbackRemainStable(BlockCheckRunPreset preset, string expected) + { + using var f = new Fixture(); f.Source.Preset = preset; f.Update(); + Assert.Equal(expected, f.Owner.ReviewModeText); + Assert.Equal(2, f.Trace.Count(p => p == "preset")); + } + + [Fact] + public void AllStrategiesShortCircuitsTheSecondPresetRead() + { + using var f = new Fixture(); f.Source.All = true; + f.OnStep = point => { if (point == "preset" && f.Trace.Count(p => p == point) > 1) throw new Sentinel(); }; + f.Update(); + Assert.Equal("quick. all", f.Owner.ReviewModeText); + Assert.Equal(1, f.Trace.Count(p => p == "preset")); + } + + [Fact] + public void ModeLocalizationCanReplacePresetBeforeTheSecondRead() + { + using var f = new Fixture(); + f.OnStep = point => { if (point == "text:BlockCheck2QuickModeName") f.Source.Preset = BlockCheckRunPreset.Exhaustive; }; + f.Update(); + Assert.Equal("quick. all", f.Owner.ReviewModeText); + } + + [Fact] + public void EarlierPublicationsChangeLaterInputsWithoutAnEarlySnapshot() + { + using var f = new Fixture(); + f.OnStep = point => + { + if (point == "changed:ReviewSourcesText") f.Source.Mask = 16 | 64; + if (point == "changed:ReviewConnectionsText") f.Source.Preset = BlockCheckRunPreset.Exhaustive; + if (point == "changed:ReviewModeText") f.Source.Requests = 7.5; + if (point == "changed:ReviewRequestsText") f.Source.Connect = 19.25; + }; + f.Update(); + Assert.Equal("C:QUIC / HTTP/3|IPv6", f.Owner.ReviewConnectionsText); + Assert.Equal("exhaustive. all", f.Owner.ReviewModeText); + Assert.Equal("R:7.5", f.Owner.ReviewRequestsText); + Assert.Equal("T:19.25|3.5|0.75", f.Owner.ReviewTimeoutsText); + } + + [Fact] + public void SourceLocalizationPrecedesCountReads() + { + using var f = new Fixture(); + f.OnStep = point => { if (point == "text:BlockCheck2ReviewSourcesFormat") { f.Source.Lists = 7; f.Source.Domains = 19; } }; + f.Update(); + Assert.Equal("S:7/19/11", f.Owner.ReviewSourcesText); + } + + [Fact] + public void AutomaticTlsLocalizationCanChangeLaterProtocolAndIpReads() + { + using var f = new Fixture(); f.Source.Mask = 8; + f.OnStep = point => { if (point == "text:BlockCheck2TlsAutoShortName") f.Source.Mask |= 16 | 64; }; + f.Update(); + Assert.Equal("C:auto, QUIC / HTTP/3|IPv6", f.Owner.ReviewConnectionsText); + Assert.True(f.Trace.IndexOf("text:BlockCheck2TlsAutoShortName") < f.Trace.IndexOf("quic")); + Assert.True(f.Trace.IndexOf("ipv6") < f.Trace.IndexOf("text:BlockCheck2ReviewConnectionsFormat")); + } + + [Theory] + [InlineData(null, "C:QUIC / HTTP/3|")] + [InlineData("", "C:, QUIC / HTTP/3|")] + [InlineData("automatic", "C:automatic, QUIC / HTTP/3|")] + public void AutomaticTlsRetainsNullFilteringAndEmptyStringJoining(string? name, string expected) + { + using var f = new Fixture(); f.Source.Mask = 8 | 16; f.AutoName = name; f.Update(); + Assert.Equal(expected, f.Owner.ReviewConnectionsText); + } + + [Theory] + [InlineData(null)] [InlineData("{")] [InlineData("{9}")] + public void InvalidSourcesFormatStillReadsCountsBeforeFormattingThrows(string? format) + { + using var f = new Fixture(); f.SourcesFormat = format; + var error = Record.Exception(() => f.Update()); + if (format is null) Assert.IsType(error); else Assert.IsType(error); + Assert.Equal(["text:BlockCheck2ReviewSourcesFormat", "lists", "domains"], f.Trace); + Assert.All(f.Values, value => Assert.Equal(string.Empty, value)); + } + + [Fact] + public void FormatCultureIsReadAfterTheNumericGetters() + { + using var f = new Fixture(); + f.OnStep = point => { if (point == "grace") CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); }; + f.Update(); + Assert.Equal("R:2.5", f.Owner.ReviewRequestsText); + Assert.Equal("T:1,25|3,5|0,75", f.Owner.ReviewTimeoutsText); + } + + [Fact] + public void PositiveMaximumPassesDurationAndDistinctCountsToTheFormatter() + { + using var f = new Fixture(); var duration = TimeSpan.FromMinutes(61); + f.Update(Preview(23, new() { Duration = duration, EstimatedStrategyJobs = 17, EstimatedRequests = 199 })); + Assert.Equal("S:2/5/23", f.Owner.ReviewSourcesText); + Assert.Equal($"M:D:{duration.Ticks}|17|199", f.Owner.ReviewMaximumTimeText); + Assert.Contains("duration:" + duration.Ticks, f.Trace); + } + + [Fact] + public void DurationCallbackCanReplaceTheEstimateBeforeLaterCountReads() + { + using var f = new Fixture(); var original = TimeSpan.FromMinutes(3); + var preview = Preview(11, new() { Duration = original, EstimatedStrategyJobs = 1, EstimatedRequests = 2 }); + f.OnStep = point => + { + if (point.StartsWith("duration:", StringComparison.Ordinal)) + typeof(BlockCheck2PreparationPreview).GetProperty(nameof(BlockCheck2PreparationPreview.MaximumDuration))! + .SetValue(preview, new BlockCheckMaximumDurationEstimate { Duration = TimeSpan.FromDays(2), EstimatedStrategyJobs = 29, EstimatedRequests = 307 }); + }; + f.Update(preview); + Assert.Equal($"M:D:{original.Ticks}|29|307", f.Owner.ReviewMaximumTimeText); + } + + [Fact] + public void MaximumLocalizationCanRemoveTheEstimateBeforeDurationIsRead() + { + using var f = new Fixture(); var preview = Preview(11, new() { Duration = TimeSpan.FromMinutes(3) }); + f.OnStep = point => + { + if (point == "text:BlockCheck2ReviewMaximumTimeFormat") + typeof(BlockCheck2PreparationPreview).GetProperty(nameof(BlockCheck2PreparationPreview.MaximumDuration))!.SetValue(preview, null); + }; + Assert.Throws(() => f.Update(preview)); + Assert.All(f.Values.Take(5), value => Assert.NotEqual(string.Empty, value)); + Assert.Equal(string.Empty, f.Owner.ReviewMaximumTimeText); + Assert.DoesNotContain(f.Trace, p => p.StartsWith("duration:", StringComparison.Ordinal)); + } + + [Fact] + public void NestedUpdatesRetainEachFramesPreviewAndCurrentSource() + { + using var f = new Fixture(); bool nested = false; + var outer = Preview(11, new() { Duration = TimeSpan.FromMinutes(3), EstimatedStrategyJobs = 17, EstimatedRequests = 199 }); + var inner = Preview(37, new() { Duration = TimeSpan.FromMinutes(5), EstimatedStrategyJobs = 41, EstimatedRequests = 503 }); + f.OnStep = point => + { + if (point == "changed:ReviewConnectionsText" && !nested) + { nested = true; f.Source.Requests = 99; f.Update(inner); } + }; + f.Update(outer); + Assert.Equal("S:2/5/37", f.Owner.ReviewSourcesText); + Assert.Equal("R:99", f.Owner.ReviewRequestsText); + Assert.Equal($"M:D:{outer.MaximumDuration!.Duration.Ticks}|17|199", f.Owner.ReviewMaximumTimeText); + Assert.Equal(2, f.Trace.Count(p => p == "changed:ReviewMaximumTimeText")); + } + + [Fact] + public void NullPreviewRetainsLocalizationAndCountReadsBeforeItsOriginalFailure() + { + using var f = new Fixture(); + Assert.Throws(() => f.Owner.UpdateReviewSummary(null!)); + Assert.Equal(["text:BlockCheck2ReviewSourcesFormat", "lists", "domains"], f.Trace); + Assert.All(f.Values, value => Assert.Equal(string.Empty, value)); + } + + [Fact] + public void EqualUpdatesStillReadInputsAndLocalizeButSuppressEvents() + { + using var f = new Fixture(); f.Update(); + var first = f.Trace.Where(p => !p.StartsWith("changed:", StringComparison.Ordinal)).ToArray(); + f.Trace.Clear(); f.Update(); + Assert.Equal(first, f.Trace); + } + + [Theory] + [InlineData("ReviewSourcesText")] + [InlineData("ReviewConnectionsText")] + [InlineData("ReviewModeText")] + [InlineData("ReviewRequestsText")] + [InlineData("ReviewTimeoutsText")] + [InlineData("ReviewMaximumTimeText")] + public void EachSetterPreservesEqualityAndCurrentFieldBeforeNotification(string name) + { + using var f = new Fixture(); var property = typeof(BlockCheck2ReviewPresentation).GetProperty(name)!; + f.OnStep = point => { if (point == "changed:" + name) Assert.Equal("value", property.GetValue(f.Owner)); }; + property.SetValue(f.Owner, "value"); property.SetValue(f.Owner, "value"); + Assert.Equal(["changed:" + name], f.Trace); + } + + [Theory] + [InlineData("text:BlockCheck2ReviewSourcesFormat", 0)] + [InlineData("text:BlockCheck2ReviewConnectionsFormat", 1)] + [InlineData("text:BlockCheck2QuickModeName", 2)] + [InlineData("text:BlockCheck2ReviewRequestsFormat", 3)] + [InlineData("text:BlockCheck2ReviewTimeoutsFormat", 4)] + [InlineData("text:BlockCheck2ReviewMaximumTimeUnavailable", 5)] + public void LocalizationFailuresRetainExceptionIdentityAndOnlyEarlierPublications(string point, int published) + { + using var f = new Fixture(); var failure = new Sentinel(); f.OnStep = p => { if (p == point) throw failure; }; + Assert.Same(failure, Assert.Throws(() => f.Update())); + Assert.Equal(published, f.Trace.Count(p => p.StartsWith("changed:", StringComparison.Ordinal))); + Assert.All(f.Values.Take(published), value => Assert.NotEqual(string.Empty, value)); + Assert.All(f.Values.Skip(published), value => Assert.Equal(string.Empty, value)); + } + + [Theory] + [InlineData("lists", 0)] [InlineData("domains", 0)] + [InlineData("http", 1)] [InlineData("tls12", 1)] [InlineData("tls13", 1)] + [InlineData("tlsauto", 1)] [InlineData("quic", 1)] [InlineData("ipv4", 1)] [InlineData("ipv6", 1)] + [InlineData("preset", 2)] [InlineData("all", 2)] [InlineData("requests", 3)] + [InlineData("connect", 4)] [InlineData("request", 4)] [InlineData("grace", 4)] + public void EverySourceGetterCanFailAtItsOriginalPoint(string point, int published) + { + using var f = new Fixture(); var failure = new Sentinel(); f.OnStep = p => { if (p == point) throw failure; }; + Assert.Same(failure, Assert.Throws(() => f.Update())); + Assert.Equal(published, f.Trace.Count(p => p.StartsWith("changed:", StringComparison.Ordinal))); + Assert.All(f.Values.Skip(published), value => Assert.Equal(string.Empty, value)); + } + + [Theory] + [InlineData("ReviewSourcesText", 1)] [InlineData("ReviewConnectionsText", 2)] + [InlineData("ReviewModeText", 3)] [InlineData("ReviewRequestsText", 4)] + [InlineData("ReviewTimeoutsText", 5)] [InlineData("ReviewMaximumTimeText", 6)] + public void ObserverFailureRetainsAssignedFieldAndCanRetry(string property, int assigned) + { + using var f = new Fixture(); var failure = new Sentinel(); + f.OnStep = p => { if (p == "changed:" + property) throw failure; }; + Assert.Same(failure, Assert.Throws(() => f.Update())); + Assert.All(f.Values.Take(assigned), value => Assert.NotEqual(string.Empty, value)); + Assert.All(f.Values.Skip(assigned), value => Assert.Equal(string.Empty, value)); + f.OnStep = null; f.Update(); Assert.All(f.Values, value => Assert.NotEqual(string.Empty, value)); + } + + [Fact] + public void DurationFailureLeavesMaximumUnassignedWithoutWrappingTheException() + { + using var f = new Fixture(); var failure = new Sentinel(); + f.OnStep = point => { if (point.StartsWith("duration:", StringComparison.Ordinal)) throw failure; }; + Assert.Same(failure, Assert.Throws(() => f.Update(Preview(11, new() { Duration = TimeSpan.FromMinutes(3) })))); + Assert.All(f.Values.Take(5), value => Assert.NotEqual(string.Empty, value)); + Assert.Equal(string.Empty, f.Owner.ReviewMaximumTimeText); + } + + [Fact] + public void OwnersHaveIndependentValuesAndSourceReads() + { + using var first = new Fixture(); using var second = new Fixture(); first.Update(); + Assert.Empty(second.Trace); Assert.All(second.Values, value => Assert.Equal(string.Empty, value)); + } + + private static BlockCheck2PreparationPreview Preview(int count = 11, BlockCheckMaximumDurationEstimate? estimate = null) => + new(count, estimate, []); + private sealed class Sentinel : Exception; + + private sealed class Fixture : IDisposable + { + private readonly CultureInfo _culture = CultureInfo.CurrentCulture; + internal readonly List Trace = []; + internal Action? OnStep; + internal string? AutoName = "auto", SourcesFormat = "S:{0}/{1}/{2}"; + internal readonly Source Source; + internal readonly BlockCheck2ReviewPresentation Owner; + internal Fixture() + { + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; + Source = new Source(this); Owner = new BlockCheck2ReviewPresentation(Source, Text, Duration); + Owner.PropertyChanged += (sender, e) => { Assert.Same(Owner, sender); Step("changed:" + e.PropertyName); }; + } + internal string[] Values => [Owner.ReviewSourcesText, Owner.ReviewConnectionsText, Owner.ReviewModeText, + Owner.ReviewRequestsText, Owner.ReviewTimeoutsText, Owner.ReviewMaximumTimeText]; + internal void Update(BlockCheck2PreparationPreview? preview = null) => Owner.UpdateReviewSummary(preview ?? Preview()); + internal void Step(string point) { Trace.Add(point); OnStep?.Invoke(point); } + internal T Read(string point, Func value) { Step(point); return value(); } + private string Text(string key) + { + Step("text:" + key); + return key switch + { + "BlockCheck2ReviewSourcesFormat" => SourcesFormat!, + "BlockCheck2ReviewConnectionsFormat" => "C:{0}|{1}", + "BlockCheck2TlsAutoShortName" => AutoName!, + "BlockCheck2QuickModeName" => "quick", "BlockCheck2BalancedModeName" => "balanced", + "BlockCheck2ExhaustiveModeName" => "exhaustive", "BlockCheck2ReviewAllStrategies" => "all", + "BlockCheck2ReviewRequestsFormat" => "R:{0}", "BlockCheck2ReviewTimeoutsFormat" => "T:{0}|{1}|{2}", + "BlockCheck2ReviewMaximumTimeUnavailable" => "none", "BlockCheck2ReviewMaximumTimeFormat" => "M:{0}|{1}|{2}", + _ => throw new InvalidOperationException("Unexpected review key: " + key), + }; + } + private string Duration(TimeSpan duration) { Step("duration:" + duration.Ticks); return "D:" + duration.Ticks; } + public void Dispose() => CultureInfo.CurrentCulture = _culture; + } + + private sealed class Source(Fixture f) : IBlockCheck2ReviewSource + { + internal int Lists = 2, Domains = 5, Mask = 1 | 32; + internal BlockCheckRunPreset Preset = BlockCheckRunPreset.Quick; + internal bool All; + internal double Requests = 2.5, Connect = 1.25, Request = 3.5, Grace = 0.75; + public int SelectedSiteListCount => f.Read("lists", () => Lists); + public int SelectedDomainCount => f.Read("domains", () => Domains); + public bool IncludeHttp => f.Read("http", () => (Mask & 1) != 0); + public bool IncludeTls12 => f.Read("tls12", () => (Mask & 2) != 0); + public bool IncludeTls13 => f.Read("tls13", () => (Mask & 4) != 0); + public bool IncludeTlsAuto => f.Read("tlsauto", () => (Mask & 8) != 0); + public bool IncludeQuic => f.Read("quic", () => (Mask & 16) != 0); + public bool IncludeIpv4 => f.Read("ipv4", () => (Mask & 32) != 0); + public bool IncludeIpv6 => f.Read("ipv6", () => (Mask & 64) != 0); + public BlockCheckRunPreset SelectedRunPreset => f.Read("preset", () => Preset); + public bool TestAllStrategies => f.Read("all", () => All); + public double RequestsPerDomain => f.Read("requests", () => Requests); + public double ConnectTimeoutSeconds => f.Read("connect", () => Connect); + public double RequestTimeoutSeconds => f.Read("request", () => Request); + public double StartupGraceSeconds => f.Read("grace", () => Grace); + } +} diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Review.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Review.cs index ecd51664..f330e408 100644 --- a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Review.cs +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.Review.cs @@ -1,110 +1,43 @@ -using System.Linq; -using CDPIUI.AddOns.BlockCheck2.Models; -using CDPIUI.AddOns.BlockCheck2.Presentation; - namespace CDPIUI.ViewModels.BlockCheck2; public sealed partial class BlockCheck2MainPageViewModel { - private string _reviewSourcesText = string.Empty; - private string _reviewConnectionsText = string.Empty; - private string _reviewModeText = string.Empty; - private string _reviewRequestsText = string.Empty; - private string _reviewTimeoutsText = string.Empty; - private string _reviewMaximumTimeText = string.Empty; - public string ReviewSourcesText { - get => _reviewSourcesText; - private set => SetProperty(ref _reviewSourcesText, value); + get => _reviewPresentation.ReviewSourcesText; + private set => _reviewPresentation.ReviewSourcesText = value; } public string ReviewConnectionsText { - get => _reviewConnectionsText; - private set => SetProperty(ref _reviewConnectionsText, value); + get => _reviewPresentation.ReviewConnectionsText; + private set => _reviewPresentation.ReviewConnectionsText = value; } public string ReviewModeText { - get => _reviewModeText; - private set => SetProperty(ref _reviewModeText, value); + get => _reviewPresentation.ReviewModeText; + private set => _reviewPresentation.ReviewModeText = value; } public string ReviewRequestsText { - get => _reviewRequestsText; - private set => SetProperty(ref _reviewRequestsText, value); + get => _reviewPresentation.ReviewRequestsText; + private set => _reviewPresentation.ReviewRequestsText = value; } public string ReviewTimeoutsText { - get => _reviewTimeoutsText; - private set => SetProperty(ref _reviewTimeoutsText, value); + get => _reviewPresentation.ReviewTimeoutsText; + private set => _reviewPresentation.ReviewTimeoutsText = value; } public string ReviewMaximumTimeText { - get => _reviewMaximumTimeText; - private set => SetProperty(ref _reviewMaximumTimeText, value); + get => _reviewPresentation.ReviewMaximumTimeText; + private set => _reviewPresentation.ReviewMaximumTimeText = value; } - private void UpdateReviewSummary(BlockCheck2PreparationPreview preview) - { - ReviewSourcesText = string.Format( - Text("BlockCheck2ReviewSourcesFormat"), - Session.SelectedSiteListCount, - Session.SelectedDomainCount, - preview.TargetCount); - - string[] protocols = - [ - .. new[] - { - Session.IncludeHttp ? "HTTP" : null, - Session.IncludeTls12 ? "TLS 1.2" : null, - Session.IncludeTls13 ? "TLS 1.3" : null, - Session.IncludeTlsAuto ? Text("BlockCheck2TlsAutoShortName") : null, - Session.IncludeQuic ? "QUIC / HTTP/3" : null, - }.OfType(), - ]; - string[] ipVersions = - [ - .. new[] - { - Session.IncludeIpv4 ? "IPv4" : null, - Session.IncludeIpv6 ? "IPv6" : null, - }.OfType(), - ]; - ReviewConnectionsText = string.Format( - Text("BlockCheck2ReviewConnectionsFormat"), - string.Join(", ", protocols), - string.Join(", ", ipVersions)); - string modeName = Session.SelectedRunPreset switch - { - BlockCheckRunPreset.Quick => Text("BlockCheck2QuickModeName"), - BlockCheckRunPreset.Exhaustive => Text("BlockCheck2ExhaustiveModeName"), - _ => Text("BlockCheck2BalancedModeName"), - }; - bool testsAllStrategies = Session.TestAllStrategies || - Session.SelectedRunPreset == BlockCheckRunPreset.Exhaustive; - ReviewModeText = testsAllStrategies - ? $"{modeName}. {Text("BlockCheck2ReviewAllStrategies")}" - : modeName; - ReviewRequestsText = string.Format( - Text("BlockCheck2ReviewRequestsFormat"), - Session.RequestsPerDomain); - ReviewTimeoutsText = string.Format( - Text("BlockCheck2ReviewTimeoutsFormat"), - Session.ConnectTimeoutSeconds, - Session.RequestTimeoutSeconds, - Session.StartupGraceSeconds); - ReviewMaximumTimeText = preview.MaximumDuration == null - ? Text("BlockCheck2ReviewMaximumTimeUnavailable") - : string.Format( - Text("BlockCheck2ReviewMaximumTimeFormat"), - _durationText.FormatDuration(preview.MaximumDuration.Duration), - preview.MaximumDuration.EstimatedStrategyJobs, - preview.MaximumDuration.EstimatedRequests); - } + private void UpdateReviewSummary(BlockCheck2PreparationPreview preview) => + _reviewPresentation.UpdateReviewSummary(preview); } diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs index 9162851f..4501945f 100644 --- a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs @@ -21,6 +21,7 @@ public sealed partial class BlockCheck2MainPageViewModel : ObservableObject private readonly BlockCheck2DurationText _durationText; private readonly BlockCheck2RunCompletionPresenter _completionPresenter; private readonly BlockCheck2ProgressPresentation _progressPresentation; + private readonly BlockCheck2ReviewPresentation _reviewPresentation; private readonly IBlockCheck2MainPageView _view; private bool _handlersConnected; private BlockCheck2PreparationPreview? _preparationPreview; @@ -59,6 +60,9 @@ public BlockCheck2MainPageViewModel(IBlockCheck2MainPageView view) () => Session.EstimatedRemainingTime, () => Session.EstimatedOverallRemainingTime, Text, _durationText.FormatRemaining); _progressPresentation.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); + _reviewPresentation = new BlockCheck2ReviewPresentation( + new BlockCheck2ReviewSource(Session), Text, _durationText.FormatDuration); + _reviewPresentation.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); } public BlockCheck2ViewModel Session { get; } = new(); diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReviewPresentation.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReviewPresentation.cs new file mode 100644 index 00000000..eae9c763 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReviewPresentation.cs @@ -0,0 +1,123 @@ +#nullable enable + +using System; +using System.Linq; +using CDPIUI.AddOns.BlockCheck2.Presentation; + +namespace CDPIUI.ViewModels.BlockCheck2; + +internal sealed class BlockCheck2ReviewPresentation : ObservableObject +{ + private readonly IBlockCheck2ReviewSource _source; + private readonly Func _text; + private readonly Func _formatDuration; + private string _reviewSourcesText = string.Empty; + private string _reviewConnectionsText = string.Empty; + private string _reviewModeText = string.Empty; + private string _reviewRequestsText = string.Empty; + private string _reviewTimeoutsText = string.Empty; + private string _reviewMaximumTimeText = string.Empty; + + public BlockCheck2ReviewPresentation(IBlockCheck2ReviewSource source, + Func text, Func formatDuration) + { + _source = source; + _text = text; + _formatDuration = formatDuration; + } + + public string ReviewSourcesText + { + get => _reviewSourcesText; + set => SetProperty(ref _reviewSourcesText, value); + } + + public string ReviewConnectionsText + { + get => _reviewConnectionsText; + set => SetProperty(ref _reviewConnectionsText, value); + } + + public string ReviewModeText + { + get => _reviewModeText; + set => SetProperty(ref _reviewModeText, value); + } + + public string ReviewRequestsText + { + get => _reviewRequestsText; + set => SetProperty(ref _reviewRequestsText, value); + } + + public string ReviewTimeoutsText + { + get => _reviewTimeoutsText; + set => SetProperty(ref _reviewTimeoutsText, value); + } + + public string ReviewMaximumTimeText + { + get => _reviewMaximumTimeText; + set => SetProperty(ref _reviewMaximumTimeText, value); + } + + public void UpdateReviewSummary(BlockCheck2PreparationPreview preview) + { + ReviewSourcesText = string.Format( + _text("BlockCheck2ReviewSourcesFormat"), + _source.SelectedSiteListCount, + _source.SelectedDomainCount, + preview.TargetCount); + + string[] protocols = + [ + .. new[] + { + _source.IncludeHttp ? "HTTP" : null, + _source.IncludeTls12 ? "TLS 1.2" : null, + _source.IncludeTls13 ? "TLS 1.3" : null, + _source.IncludeTlsAuto ? _text("BlockCheck2TlsAutoShortName") : null, + _source.IncludeQuic ? "QUIC / HTTP/3" : null, + }.OfType(), + ]; + string[] ipVersions = + [ + .. new[] + { + _source.IncludeIpv4 ? "IPv4" : null, + _source.IncludeIpv6 ? "IPv6" : null, + }.OfType(), + ]; + ReviewConnectionsText = string.Format( + _text("BlockCheck2ReviewConnectionsFormat"), + string.Join(", ", protocols), + string.Join(", ", ipVersions)); + string modeName = _source.SelectedRunPreset switch + { + BlockCheckRunPreset.Quick => _text("BlockCheck2QuickModeName"), + BlockCheckRunPreset.Exhaustive => _text("BlockCheck2ExhaustiveModeName"), + _ => _text("BlockCheck2BalancedModeName"), + }; + bool testsAllStrategies = _source.TestAllStrategies || + _source.SelectedRunPreset == BlockCheckRunPreset.Exhaustive; + ReviewModeText = testsAllStrategies + ? $"{modeName}. {_text("BlockCheck2ReviewAllStrategies")}" + : modeName; + ReviewRequestsText = string.Format( + _text("BlockCheck2ReviewRequestsFormat"), + _source.RequestsPerDomain); + ReviewTimeoutsText = string.Format( + _text("BlockCheck2ReviewTimeoutsFormat"), + _source.ConnectTimeoutSeconds, + _source.RequestTimeoutSeconds, + _source.StartupGraceSeconds); + ReviewMaximumTimeText = preview.MaximumDuration == null + ? _text("BlockCheck2ReviewMaximumTimeUnavailable") + : string.Format( + _text("BlockCheck2ReviewMaximumTimeFormat"), + _formatDuration(preview.MaximumDuration.Duration), + preview.MaximumDuration.EstimatedStrategyJobs, + preview.MaximumDuration.EstimatedRequests); + } +} diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReviewSource.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReviewSource.cs new file mode 100644 index 00000000..db59aaf4 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2ReviewSource.cs @@ -0,0 +1,27 @@ +using CDPIUI.AddOns.BlockCheck2.Presentation; + +namespace CDPIUI.ViewModels.BlockCheck2; + +// A live view of Session. No option value is copied when this adapter is created. +internal sealed class BlockCheck2ReviewSource : IBlockCheck2ReviewSource +{ + private readonly BlockCheck2ViewModel _session; + + public BlockCheck2ReviewSource(BlockCheck2ViewModel session) => _session = session; + + public int SelectedSiteListCount => _session.SelectedSiteListCount; + public int SelectedDomainCount => _session.SelectedDomainCount; + public bool IncludeHttp => _session.IncludeHttp; + public bool IncludeTls12 => _session.IncludeTls12; + public bool IncludeTls13 => _session.IncludeTls13; + public bool IncludeTlsAuto => _session.IncludeTlsAuto; + public bool IncludeQuic => _session.IncludeQuic; + public bool IncludeIpv4 => _session.IncludeIpv4; + public bool IncludeIpv6 => _session.IncludeIpv6; + public BlockCheckRunPreset SelectedRunPreset => _session.SelectedRunPreset; + public bool TestAllStrategies => _session.TestAllStrategies; + public double RequestsPerDomain => _session.RequestsPerDomain; + public double ConnectTimeoutSeconds => _session.ConnectTimeoutSeconds; + public double RequestTimeoutSeconds => _session.RequestTimeoutSeconds; + public double StartupGraceSeconds => _session.StartupGraceSeconds; +} diff --git a/CDPIUI/ViewModels/BlockCheck2/IBlockCheck2ReviewSource.cs b/CDPIUI/ViewModels/BlockCheck2/IBlockCheck2ReviewSource.cs new file mode 100644 index 00000000..6e894836 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/IBlockCheck2ReviewSource.cs @@ -0,0 +1,22 @@ +using CDPIUI.AddOns.BlockCheck2.Presentation; + +namespace CDPIUI.ViewModels.BlockCheck2; + +internal interface IBlockCheck2ReviewSource +{ + int SelectedSiteListCount { get; } + int SelectedDomainCount { get; } + bool IncludeHttp { get; } + bool IncludeTls12 { get; } + bool IncludeTls13 { get; } + bool IncludeTlsAuto { get; } + bool IncludeQuic { get; } + bool IncludeIpv4 { get; } + bool IncludeIpv6 { get; } + BlockCheckRunPreset SelectedRunPreset { get; } + bool TestAllStrategies { get; } + double RequestsPerDomain { get; } + double ConnectTimeoutSeconds { get; } + double RequestTimeoutSeconds { get; } + double StartupGraceSeconds { get; } +} diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index cdb204c5..c0de8e68 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1488,8 +1488,8 @@ }, { "path": "docs/superpowers/specs/2026-11-11-blockcheck-review-presentation-design.md", - "firstIntroduction": "Local MainPage review summary contract under issue221; baseline3c7f8961477dbff0b4b021493b629ba1a1a0fa05.", - "first_commit": null, + "firstIntroduction": "330458e623ead885a632c5ff0abd5e7fd9bbb739\tleather147\tRecord MainPage review presentation design", + "first_commit": "330458e623ead885a632c5ff0abd5e7fd9bbb739", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", @@ -1498,13 +1498,23 @@ }, { "path": "docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md", - "firstIntroduction": "Local MainPage review summary contract under issue221; baseline3c7f8961477dbff0b4b021493b629ba1a1a0fa05.", - "first_commit": null, + "firstIntroduction": "330458e623ead885a632c5ff0abd5e7fd9bbb739\tleather147\tRecord MainPage review presentation design", + "first_commit": "330458e623ead885a632c5ff0abd5e7fd9bbb739", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", "language": "en", "changes": "Define six-value review state ownership, a direct live Session source, callback/read-order contracts and bounded local qualification." + }, + { + "path": "docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md", + "firstIntroduction": "Local MainPage review presentation verification under issue221; product introduction recorded after checkpoint commit.", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Record focused mutation/full managed evidence, exact source and public contract checks, bounded actual-host qualification and local delivery limits." } ], "current_history_base": "7ead95f7756057f67cd113671a7f84cf422e8d32", diff --git a/docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md b/docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md new file mode 100644 index 00000000..c7cb4805 --- /dev/null +++ b/docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md @@ -0,0 +1,87 @@ +# MainPage review presentation verification + +## Scope and source checkpoint + +[Issue #221](https://github.com/lumenpearson/cdpiui/issues/221) owns this LOCAL review-summary +extraction. Frozen baseline: `3c7f8961477dbff0b4b021493b629ba1a1a0fa05`, draft PR220. +Design commit: `330458e623ead885a632c5ff0abd5e7fd9bbb739`. The isolated branch is +`dev/blockcheck-review-presentation` in the Root worktree. Actual Project intake119 was verified +before implementation, then released120 with all six participants paused. The +[intake receipt](https://github.com/lumenpearson/cdpiui/issues/221#issuecomment-6795366566) records +In progress/P2/Architecture/Medium/G2/lumenpearson and two canonical labels after reload. + +An internal six-string owner now formats the same summary through a15-property read-only source, +a direct Session adapter, localized Text and the existing duration formatter. The six public host +getters/private setters and private supplied-preview method remain forwards. One constructor-owned +synchronous bridge retains the host sender and current-field semantics. The four MainPage partials +decreased from740 to677 lines; the Review partial decreased from110 to43. + +The existing product footprint is exactly MainPageViewModel.cs and Review.cs. Three internal files +are added: the source interface, its direct Session adapter and the presentation owner. Session, +options/site lists, numeric/progress/completion owners, duration and preview models, lifecycle, +navigation, resources, packages, Core/AddOns/Shared and operating code remain unchanged. + +## Design and managed evidence + +A fresh design-builder inspected the policy, constructor, notification base and inherited160 fixture +boundaries, and reported "nothing important left" before implementation. The source contract uses +the original getter types; SelectedRunPreset is non-nullable. The intake verification wording was +corrected to distinguish an unknown preset from null preview/estimate cases. + +The first constructor test was written before any interface/adapter/owner implementation. Its +focused run observed the expected CS0246 missing BlockCheck2ReviewPresentation. All subsequent +behavior tests were also written before the implementation. The first owner run passed187/187 +in38ms. These tests include128 literal protocol/IP input-output rows and discriminating checks for +localization, lazy reads, culture, current values after callbacks, partial failures and preview identity. + +A controlled mutant cached SelectedRunPreset before the first display update. It failed12 cases and +passed175, including stale mode state and early read-order assertions. Exact original bytes were +restored in a finally block and verified with SHA256 +`9F5A14E3FA90599EBDF8B74FA1701AB78A7CAD1EB5CEB9DBFF7890287C13BC36`. +The restored focused run passed187/187 in33ms. With host wiring present, the full suite passed +2430/2430 in9s, with zero failures/skips. The normal WinUI build passed0 warnings/errors in39.32s. + +```text +C:/Users/lumen/.dotnet/dotnet.exe test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release --no-restore --filter FullyQualifiedName~BlockCheck2ReviewPresentationTests +C:/Users/lumen/.dotnet/dotnet.exe test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release --no-restore +C:/Users/lumen/.dotnet/dotnet.exe build CDPIUI/CDPIUI.csproj -c Release -p:Platform=x64 --no-restore +``` + +The focused assertions cover all protocol/IP selections, null/empty automatic TLS names, explicit +preset branches and unknown fallback, the short-circuited second preset read, localization mutation, +publication mutation, culture after numeric getters, null preview and invalid formats, positive +maximum-duration formatting with distinct counts, repeated estimate reads after a duration callback, +nested updates with different previews, six setters/equality/current values, all15 getter failures, +observer and formatter exception identity, partial effects, retry and independent owners. + +## Compatibility and exact-source guards + +The source inventory compared614 baseline GUI files with617 current C# files. All451 original +exported source signatures remain. Compiled comparisons preserve452 GUI and88 Core exported type +shapes, with zero removals/changes and zero additions on retained types. These bounded inventories +do not certify all annotations, attributes, native ABI or runtime behavior. + +The policy guard compares original tokens under the declared source/Text/FormatDuration mappings, +including significant strings and repeated preview reads. It verifies all15 exact typed source +getters, cold constructors/fields, six owner and host setters, the private preview forward, one bridge, +all prior constructor bytes and the three additive test links. The adapter does not copy values or +read properties during construction. The guard passed without a product correction. + +The accepted previous normal GUI DLL was saved before rebuilding. The current normal GUI SHA256 is +`A0D830364F9A25B7ACD755E71DC1B704CE47DEA261C11A68B7589F3C8FCF5753`. +Earlier160 runtime evidence retains its historical normal-output hash. Do not run its frozen +verifier against this new normal output and describe that result as a regression of the old fixture. + +## Native and delivery status + +Native qualification is pending at this product checkpoint. The next stage must create a NEW source +archive, preserve all160 accepted labels/old case bytes/21 cuts, and add actual MainPage/source/ +preview/bridge cases. Positive maximum formatting, callbacks, private setters, equality, sender, +reentry and partial exceptions need direct assertions. Derive fresh counts/pins/outputs from that +fixture, obtain independent pre-build/prelaunch READY, then acquire a new explicit exclusive lease. +Root currently has no ready native request or pending UI call. + +Final whole-change review, stacked draft final-head checks, actual PR Project readback and immediate +completed/Done acceptance remain pending. Parent13/14/15 and drafts216/218/220 stay separate and +unmerged. No full Page rendering, XAML Loading, installed product, GC collection, G1 or release +result is inferred. Keep all accepted and rejected evidence, branches, workspaces and source archives. From b679c6c10cde31ce728fb233f505450f57adeaa7 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:47:42 +0300 Subject: [PATCH 16/31] Record MainPage review native qualification The review presentation extraction now has actual composition evidence on its product checkpoint. The fresh fixture keeps all previous cases and boundary cuts while adding six focused host groups. Independent review verified source inputs, execution level, resources, launch pins and the full output baseline before the process started. One leased process passed all 166 groups and every resource, file, hash and process check after exit. The new groups prove direct adapter values, positive duration formatting, current callbacks, nested previews and exception recovery. They also preserve host sender identity and equal value suppression through the real model bridge. The report distinguishes these results from full Page and installed product acceptance. Shared interface ownership was released, and broader integration and release work remain open. Changed files: - "docs/governance/document-inventory.json" (+2/-2 lines). - "docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md" (+8/-8 lines). - "docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md" (+71/-11 lines). The file counts compare the staged tree with its first parent. Refs: #221 Staged-Tree: 4f67eaecab685ec5752abc4bc3587ce817dc865c --- docs/governance/document-inventory.json | 4 +- ...26-11-11-blockcheck-review-presentation.md | 16 ++-- ...kcheck-review-presentation-verification.md | 82 ++++++++++++++++--- 3 files changed, 81 insertions(+), 21 deletions(-) diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index c0de8e68..806e9898 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1508,8 +1508,8 @@ }, { "path": "docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md", - "firstIntroduction": "Local MainPage review presentation verification under issue221; product introduction recorded after checkpoint commit.", - "first_commit": null, + "firstIntroduction": "1c2d44336fe4bb97bc100a5102fc7a7667d65068\tleather147\tExtract MainPage review summary presentation", + "first_commit": "1c2d44336fe4bb97bc100a5102fc7a7667d65068", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", diff --git a/docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md b/docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md index 3fd1cbb1..28e2f802 100644 --- a/docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md +++ b/docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md @@ -44,14 +44,14 @@ links for owner/interface/existing preview; design/plan/report and additive inve existing FormatDuration. Produces six observable strings and UpdateReviewSummary(preview). Host preserves six private setters, supplied-preview method and one constructor-owned synchronous bridge. -- [ ] Read issue/spec/actual intake; preserve source/compiled/normal-output baselines and frozen refs. +- [x] Read issue/spec/actual intake; preserve source/compiled/normal-output baselines and frozen refs. Obtain a fresh design-builder verdict before product code. -- [ ] Write focused tests first for the named contract and observe expected missing-component RED. -- [ ] Implement the interface, exact direct adapter, cold owner and original policy; wire host forwards +- [x] Write focused tests first for the named contract and observe expected missing-component RED. +- [x] Implement the interface, exact direct adapter, cold owner and original policy; wire host forwards and one bridge without touching lifecycle or existing owners. Run focused GREEN. -- [ ] Apply a controlled early preset cache and observe behavior assertions fail; restore exact bytes/ +- [x] Apply a controlled early preset cache and observe behavior assertions fail; restore exact bytes/ hash and run focused/full GREEN and normal GUI Release/x64 with0 warnings/errors. -- [ ] Verify source/compiled public preservation, exact footprint, literal policy, all15 mappings, +- [x] Verify source/compiled public preservation, exact footprint, literal policy, all15 mappings, host setters/bridge/remainder, governance and redacted scans. Record failures and commit checkpoint. ### Task 2: Qualify actual composition and accept locally @@ -62,11 +62,11 @@ postchecks; dedicated report and additive inventory. **Interfaces:** consumes Task1 source pin and accepted160 recipe/corpus. Produces reviewed actual host/source/preview cases and explicit local delivery evidence without accepting parent integration. -- [ ] Read Task1 evidence and brief; preserve all160 labels/old case bytes/21cuts. Derive fresh inputs, +- [x] Read Task1 evidence and brief; preserve all160 labels/old case bytes/21cuts. Derive fresh inputs, extras/corpus and positive actual-host assertions before build, with no new IO or cuts. -- [ ] Obtain independent pre-build review; build0-0, derive actual binary/resource/source/runner/ +- [x] Obtain independent pre-build review; build0-0, derive actual binary/resource/source/runner/ verifier pins and all prior output hashes, then obtain independent prelaunch READY. -- [ ] Coordinate a new explicit lease; execute one owned process, prove exact labels/COMPLETE/exit0, +- [x] Coordinate a new explicit lease; execute one owned process, prove exact labels/COMPLETE/exit0, streams/hash/resource/source/IO/absence/process cleanup; idle/requestfalse and guarded release. - [ ] Update evidence and obtain fresh whole-branch review; resolve Critical/Important through observed RED→GREEN, record all rulings/deferred minors and preserve original artifacts. diff --git a/docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md b/docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md index c7cb4805..c77131e1 100644 --- a/docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md +++ b/docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md @@ -20,6 +20,8 @@ The existing product footprint is exactly MainPageViewModel.cs and Review.cs. Th are added: the source interface, its direct Session adapter and the presentation owner. Session, options/site lists, numeric/progress/completion owners, duration and preview models, lifecycle, navigation, resources, packages, Core/AddOns/Shared and operating code remain unchanged. +Product checkpoint: `1c2d44336fe4bb97bc100a5102fc7a7667d65068`. Later evidence commits do not +change the qualified product or native case bytes. ## Design and managed evidence @@ -72,16 +74,74 @@ The accepted previous normal GUI DLL was saved before rebuilding. The current no Earlier160 runtime evidence retains its historical normal-output hash. Do not run its frozen verifier against this new normal output and describe that result as a regression of the old fixture. -## Native and delivery status - -Native qualification is pending at this product checkpoint. The next stage must create a NEW source -archive, preserve all160 accepted labels/old case bytes/21 cuts, and add actual MainPage/source/ -preview/bridge cases. Positive maximum formatting, callbacks, private setters, equality, sender, -reentry and partial exceptions need direct assertions. Derive fresh counts/pins/outputs from that -fixture, obtain independent pre-build/prelaunch READY, then acquire a new explicit exclusive lease. -Root currently has no ready native request or pending UI call. +## Actual native qualification + +The fresh fixture is `F:/cdpiui-verify/cdpiui-blockcheck-review-1c2d443-20261111`, archived from +the product checkpoint. It contains1591 tracked Git inputs, exactly21 inherited cuts,34 bootstrap +files and38 allowed extras, with no reparse entries. All32 prior case partials retain their bytes. +The main bootstrap adds the last review call and COMPLETE166 count, apart from path/pin names. +The exact160-label prefix is retained and six distinct review groups are appended. + +Before the initial review verdict, the adapter group gained explicit Quick/TestAllStrategies true +and false assertions with all protocol flags false, plus the unknown-preset Balanced fallback. The +seven-line assertion delta changed no label, product, operating endpoint or cut. Original draft +case bytes were retained. The final case SHA is recorded below. The independent pre-build reviewer +reconstructed the complete fixture and approved those final bytes with0 Critical/Important/Minor. + +The native build passed0 warnings/errors in75.27s. Independent prelaunch review rehashed all65 +approved inputs and all522 output paths/digests, reconstructed source/manifest/corpus evidence and +verified all32 prior partials again. The actual executable is PE32+ AMD64, with an embedded +asInvoker/uiAccess=false manifest. The token was non-admin and the exact executable was absent. +PowerShell parsing had0 errors; the runtime verifier and pin tables were consistent. All7 forbidden +paths,13 fresh run/evidence paths and custom markers were absent. No pending hash value remained. + +The65 approved inputs are5 owned binaries,20 resources and40 source/evidence files. All20 resources +are generated-byte identical, their5206 entries equal source JSON, and38 required English keys are +nonempty. Selected actual hash anchors: + +| Artifact | SHA256 | +| --- | --- | +| Native GUI DLL | `AFBD9A8DAEEF9B4F386F8FB0CFD6267C1AB6A064F8DC05A1963F530AB6095F15` | +| Runner | `90DDD4A03497353A89058C7999717DBDBA19818099BA2B838723398420BB7F9A` | +| Runtime verifier | `CB412BD26DF46368A4B8F035B9F0519B2E0E73B43F0E105E58C643BBCD07D478` | +| Complete output baseline | `9585290814A1CD60E09E02B03642FF5A6CEE7E1E70CB3250B842580E98B8D8E8` | +| Accepted corpus | `7BDB3893F3D0E3F179365AD24EF3941E74DD4E1A4C4C15A2E45F518130E0C81A` | +| Final review case | `09B6F291DF5D2A93EF0C97AE81FCEBAA40CC549CBFD7583E87E8AE31A75479BB` | + +Root independently rehashed the65 pins and522 baseline files immediately before guarded queue +transfer120→121. Only this native process owned that lease. PID6720 ran from +2026-11-11T12:44:37.6688885Z to2026-11-11T12:44:40.2506392+00:00. All166 unique groups passed +with the exact160/154/149/137 prefixes, peer141 projection, one COMPLETE, zero FAIL, exit0 and +empty stdout/stderr. All65 pins/all522 prior filenames and hashes passed after exit. Exactly six +new output names made528 total. The three literal inputs retain16/16/15 bytes. Both serializer +reports retain exact354/260-byte golden contents, hashes and current model fields. All7 forbidden +paths remain absent, including both non-file list paths. The normal GUI remains at the SHA above. + +The six new groups directly assert cold values, all private setters/host sender/equality, individual +protocol/IP mappings and full order,2 selected lists/5 domains/23 preview targets, distinct request/ +timeout values and positive61-minute duration with17 jobs/199 requests. They assert both explicit +all-strategies states, unknown preset fallback, callbacks changing later source/preview reads, +repeated equality/current adapter values/separate owners, nested preview identity and observer +exception identity/partial effects/retry. They use actual MainPage, source adapter, Session, preview, +localizer, duration formatter and dispatcher with a two-method view substitute that is never called. + +Both list items receive nonempty literal content, so their constructors use the in-memory domain +count branch. Reflection seeds option fields and avoids persisted setters. All externally attached +new handlers detach in finally. Operating counters/settings writes remain unchanged; existing +inert settings constructor reads remain part of composition. No OnLoaded, real scan/preparation/ +backend/history/cleanup operation, settings write, additional operating file IO, desktop input or deletion +was introduced. External absence checks cover the two non-file paths. + +Root separately verified PID6720 and the exact executable absent, wrote idle121/requestfalse with +no pending call, and guarded release122/readback confirmed owner:null and all six participants paused. +Raw recipes, logs, pins, baseline, source/resource evidence and postchecks remain in this plan's +ignored workspace `.superpowers/sdd/2026-11-11-blockcheck-review-presentation/`. + +## Delivery status and limits Final whole-change review, stacked draft final-head checks, actual PR Project readback and immediate -completed/Done acceptance remain pending. Parent13/14/15 and drafts216/218/220 stay separate and -unmerged. No full Page rendering, XAML Loading, installed product, GC collection, G1 or release -result is inferred. Keep all accepted and rejected evidence, branches, workspaces and source archives. +completed/Done acceptance remain pending at this evidence checkpoint. Parent13/14/15 and drafts +216/218/220 stay separate and unmerged. The two-method view establishes model composition, without +full Page rendering/XAML Loading/focus/activation, installed-product, GC collection, G1 or release +acceptance. Independent qualification of unchanged components remains with their owning stages. +Keep all accepted and rejected evidence, branches, workspaces and source archives. From b627a0f62dace8dde20ca2574a9d28646f71b421 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:58:49 +0300 Subject: [PATCH 17/31] Record MainPage review findings and evidence limits The fresh whole branch review found no critical or important issue in the extracted presentation. Two minor findings concerned evidence wording and document readability. The retained record now distinguishes the 21 inherited cut paths from the 20 complete files that remain byte identical. The remaining file changes only its pinned expected executable path for the fresh fixture. The documents now separate ordinary words, counts and issue references for clear English instructions. The report records independent hash comparisons separately from the original test and process executions. Product files, tests, native cases, launch pins and outputs remain unchanged. Final remote checks and actual delivery field readbacks remain required before local acceptance, while parent integration and release boundaries stay open. Changed files: - "docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md" (+12/-12 lines). - "docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md" (+60/-39 lines). - "docs/superpowers/specs/2026-11-11-blockcheck-review-presentation-design.md" (+12/-12 lines). The file counts compare the staged tree with its first parent. Refs: #221 Staged-Tree: 9aa61eadb1daf709591a61122159ce30ae43843e --- ...26-11-11-blockcheck-review-presentation.md | 24 ++--- ...kcheck-review-presentation-verification.md | 99 +++++++++++-------- ...1-blockcheck-review-presentation-design.md | 24 ++--- 3 files changed, 84 insertions(+), 63 deletions(-) diff --git a/docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md b/docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md index 28e2f802..7219e263 100644 --- a/docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md +++ b/docs/superpowers/plans/2026-11-11-blockcheck-review-presentation.md @@ -4,19 +4,19 @@ **Goal:** Move six review strings and their original formatting policy into a focused state owner. -**Architecture:** An internal owner reads a15-property live source through a direct Session adapter. +**Architecture:** An internal owner reads a 15-property live source through a direct Session adapter. Six host properties and one private method forward to it, with one synchronous host-sender bridge. -**Tech Stack:** C#/.NET8.0.427, xUnit linked source, WinUI3, API/blob and immutable native evidence. +**Tech Stack:** C#/.NET 8.0.427, xUnit linked source, WinUI3, API/blob and immutable native evidence. **Spec:** [review presentation design](../specs/2026-11-11-blockcheck-review-presentation-design.md). ## Global constraints -- Issue221 actual intake119 is verified before implementation. Root owns the isolated named branch. -- Base PR2203c7f896 and parent2183da11cb/2163623584 remain frozen and unmerged. +- Issue #221 actual intake under grant 119 is verified before implementation. Root owns the isolated named branch. +- Base PR #220 at `3c7f896` and parents #218 at `3da11cb` and #216 at `3623584` remain frozen and unmerged. - Preserve six empty values, public getters/private setters and private UpdateReviewSummary(preview). -- All15 source getters remain current direct reads, with exact types, order and repeated calls. +- All 15 source getters remain current direct reads, with exact types, order and repeated calls. - Preserve preview identity, conditional localization, ambient culture, strings and synchronous events. - Do not change preview/estimate models, duration implementation, Session/options/site-list behavior, progress/completion owners, navigation/lifecycle/subscriptions, resources, packages or operating code. @@ -50,8 +50,8 @@ preserves six private setters, supplied-preview method and one constructor-owned - [x] Implement the interface, exact direct adapter, cold owner and original policy; wire host forwards and one bridge without touching lifecycle or existing owners. Run focused GREEN. - [x] Apply a controlled early preset cache and observe behavior assertions fail; restore exact bytes/ - hash and run focused/full GREEN and normal GUI Release/x64 with0 warnings/errors. -- [x] Verify source/compiled public preservation, exact footprint, literal policy, all15 mappings, + hash and run focused/full GREEN and normal GUI Release/x64 with 0 warnings/errors. +- [x] Verify source/compiled public preservation, exact footprint, literal policy, all 15 mappings, host setters/bridge/remainder, governance and redacted scans. Record failures and commit checkpoint. ### Task 2: Qualify actual composition and accept locally @@ -59,18 +59,18 @@ preserves six private setters, supplied-preview method and one constructor-owned **Files:** fresh F:/cdpiui-verify immutable fixture plus retained ignored recipes, pins, logs and postchecks; dedicated report and additive inventory. -**Interfaces:** consumes Task1 source pin and accepted160 recipe/corpus. Produces reviewed actual +**Interfaces:** consumes Task 1 source pin and accepted160 recipe/corpus. Produces reviewed actual host/source/preview cases and explicit local delivery evidence without accepting parent integration. -- [x] Read Task1 evidence and brief; preserve all160 labels/old case bytes/21cuts. Derive fresh inputs, +- [x] Read Task 1 evidence and brief; preserve all 160 labels/old case bytes/21 cuts. Derive fresh inputs, extras/corpus and positive actual-host assertions before build, with no new IO or cuts. - [x] Obtain independent pre-build review; build0-0, derive actual binary/resource/source/runner/ verifier pins and all prior output hashes, then obtain independent prelaunch READY. - [x] Coordinate a new explicit lease; execute one owned process, prove exact labels/COMPLETE/exit0, streams/hash/resource/source/IO/absence/process cleanup; idle/requestfalse and guarded release. -- [ ] Update evidence and obtain fresh whole-branch review; resolve Critical/Important through observed - RED→GREEN, record all rulings/deferred minors and preserve original artifacts. -- [ ] Publish a draft stacked on dev/blockcheck-progress-presentation with Refs14/221; verify exact +- [x] Update evidence and obtain fresh whole-branch review; resolve Critical/Important through observed + REDв†’GREEN, record all rulings/deferred minors and preserve original artifacts. +- [ ] Publish a draft stacked on dev/blockcheck-progress-presentation with Refs #14 and Refs #221; verify exact final-head checks and actual PR labels/owner/G2/Project fields, without merging a parent or main. - [ ] Verify all six local criteria, post the six-section acceptance record, immediately close completed/ set actual ProjectDone and read back closure, criteria, classification and fields. diff --git a/docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md b/docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md index c77131e1..cae69371 100644 --- a/docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md +++ b/docs/superpowers/reports/2026-11-11-blockcheck-review-presentation-verification.md @@ -3,18 +3,18 @@ ## Scope and source checkpoint [Issue #221](https://github.com/lumenpearson/cdpiui/issues/221) owns this LOCAL review-summary -extraction. Frozen baseline: `3c7f8961477dbff0b4b021493b629ba1a1a0fa05`, draft PR220. +extraction. Frozen baseline: `3c7f8961477dbff0b4b021493b629ba1a1a0fa05`, draft PR #220. Design commit: `330458e623ead885a632c5ff0abd5e7fd9bbb739`. The isolated branch is -`dev/blockcheck-review-presentation` in the Root worktree. Actual Project intake119 was verified -before implementation, then released120 with all six participants paused. The +`dev/blockcheck-review-presentation` in the Root worktree. Actual Project intake under grant 119 was verified +before implementation, then released 120 with all six participants paused. The [intake receipt](https://github.com/lumenpearson/cdpiui/issues/221#issuecomment-6795366566) records In progress/P2/Architecture/Medium/G2/lumenpearson and two canonical labels after reload. -An internal six-string owner now formats the same summary through a15-property read-only source, +An internal six-string owner now formats the same summary through a 15-property read-only source, a direct Session adapter, localized Text and the existing duration formatter. The six public host getters/private setters and private supplied-preview method remain forwards. One constructor-owned synchronous bridge retains the host sender and current-field semantics. The four MainPage partials -decreased from740 to677 lines; the Review partial decreased from110 to43. +decreased from 740 to 677 lines; the Review partial decreased from 110 to 43. The existing product footprint is exactly MainPageViewModel.cs and Review.cs. Three internal files are added: the source interface, its direct Session adapter and the presentation owner. Session, @@ -32,16 +32,16 @@ corrected to distinguish an unknown preset from null preview/estimate cases. The first constructor test was written before any interface/adapter/owner implementation. Its focused run observed the expected CS0246 missing BlockCheck2ReviewPresentation. All subsequent -behavior tests were also written before the implementation. The first owner run passed187/187 -in38ms. These tests include128 literal protocol/IP input-output rows and discriminating checks for +behavior tests were also written before the implementation. The first owner run passed 187/187 +in 38 ms. These tests include 128 literal protocol/IP input-output rows and discriminating checks for localization, lazy reads, culture, current values after callbacks, partial failures and preview identity. -A controlled mutant cached SelectedRunPreset before the first display update. It failed12 cases and -passed175, including stale mode state and early read-order assertions. Exact original bytes were +A controlled mutant cached SelectedRunPreset before the first display update. It failed 12 cases and +passed 175, including stale mode state and early read-order assertions. Exact original bytes were restored in a finally block and verified with SHA256 `9F5A14E3FA90599EBDF8B74FA1701AB78A7CAD1EB5CEB9DBFF7890287C13BC36`. -The restored focused run passed187/187 in33ms. With host wiring present, the full suite passed -2430/2430 in9s, with zero failures/skips. The normal WinUI build passed0 warnings/errors in39.32s. +The restored focused run passed 187/187 in 33 ms. With host wiring present, the full suite passed +2430/2430 in 9 s, with zero failures/skips. The normal WinUI build passed 0 warnings/errors in 39.32 s. ```text C:/Users/lumen/.dotnet/dotnet.exe test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release --no-restore --filter FullyQualifiedName~BlockCheck2ReviewPresentationTests @@ -53,18 +53,18 @@ The focused assertions cover all protocol/IP selections, null/empty automatic TL preset branches and unknown fallback, the short-circuited second preset read, localization mutation, publication mutation, culture after numeric getters, null preview and invalid formats, positive maximum-duration formatting with distinct counts, repeated estimate reads after a duration callback, -nested updates with different previews, six setters/equality/current values, all15 getter failures, +nested updates with different previews, six setters/equality/current values, all 15 getter failures, observer and formatter exception identity, partial effects, retry and independent owners. ## Compatibility and exact-source guards -The source inventory compared614 baseline GUI files with617 current C# files. All451 original -exported source signatures remain. Compiled comparisons preserve452 GUI and88 Core exported type +The source inventory compared 614 baseline GUI files with 617 current C# files. All 451 original +exported source signatures remain. Compiled comparisons preserve 452 GUI and 88 Core exported type shapes, with zero removals/changes and zero additions on retained types. These bounded inventories do not certify all annotations, attributes, native ABI or runtime behavior. The policy guard compares original tokens under the declared source/Text/FormatDuration mappings, -including significant strings and repeated preview reads. It verifies all15 exact typed source +including significant strings and repeated preview reads. It verifies all 15 exact typed source getters, cold constructors/fields, six owner and host setters, the private preview forward, one bridge, all prior constructor bytes and the three additive test links. The adapter does not copy values or read properties during construction. The guard passed without a product correction. @@ -77,26 +77,26 @@ verifier against this new normal output and describe that result as a regression ## Actual native qualification The fresh fixture is `F:/cdpiui-verify/cdpiui-blockcheck-review-1c2d443-20261111`, archived from -the product checkpoint. It contains1591 tracked Git inputs, exactly21 inherited cuts,34 bootstrap -files and38 allowed extras, with no reparse entries. All32 prior case partials retain their bytes. +the product checkpoint. It contains 1591 tracked Git inputs, exactly 21 inherited cuts, 34 bootstrap +files and 38 allowed extras, with no reparse entries. All 32 prior case partials retain their bytes. The main bootstrap adds the last review call and COMPLETE166 count, apart from path/pin names. -The exact160-label prefix is retained and six distinct review groups are appended. +The exact 160-label prefix is retained and six distinct review groups are appended. Before the initial review verdict, the adapter group gained explicit Quick/TestAllStrategies true and false assertions with all protocol flags false, plus the unknown-preset Balanced fallback. The seven-line assertion delta changed no label, product, operating endpoint or cut. Original draft case bytes were retained. The final case SHA is recorded below. The independent pre-build reviewer -reconstructed the complete fixture and approved those final bytes with0 Critical/Important/Minor. +reconstructed the complete fixture and approved those final bytes with 0 Critical/Important/Minor. -The native build passed0 warnings/errors in75.27s. Independent prelaunch review rehashed all65 -approved inputs and all522 output paths/digests, reconstructed source/manifest/corpus evidence and -verified all32 prior partials again. The actual executable is PE32+ AMD64, with an embedded +The native build passed 0 warnings/errors in 75.27 s. Independent prelaunch review rehashed all 65 +approved inputs and all 522 output paths/digests, reconstructed source/manifest/corpus evidence and +verified all 32 prior partials again. The actual executable is PE32+ AMD64, with an embedded asInvoker/uiAccess=false manifest. The token was non-admin and the exact executable was absent. -PowerShell parsing had0 errors; the runtime verifier and pin tables were consistent. All7 forbidden -paths,13 fresh run/evidence paths and custom markers were absent. No pending hash value remained. +PowerShell parsing had 0 errors; the runtime verifier and pin tables were consistent. All 7 forbidden +paths, 13 fresh run/evidence paths and custom markers were absent. No pending hash value remained. -The65 approved inputs are5 owned binaries,20 resources and40 source/evidence files. All20 resources -are generated-byte identical, their5206 entries equal source JSON, and38 required English keys are +The 65 approved inputs are 5 owned binaries, 20 resources and 40 source/evidence files. All 20 resources +are generated-byte identical, their 5206 entries equal source JSON, and 38 required English keys are nonempty. Selected actual hash anchors: | Artifact | SHA256 | @@ -108,18 +108,18 @@ nonempty. Selected actual hash anchors: | Accepted corpus | `7BDB3893F3D0E3F179365AD24EF3941E74DD4E1A4C4C15A2E45F518130E0C81A` | | Final review case | `09B6F291DF5D2A93EF0C97AE81FCEBAA40CC549CBFD7583E87E8AE31A75479BB` | -Root independently rehashed the65 pins and522 baseline files immediately before guarded queue -transfer120→121. Only this native process owned that lease. PID6720 ran from -2026-11-11T12:44:37.6688885Z to2026-11-11T12:44:40.2506392+00:00. All166 unique groups passed -with the exact160/154/149/137 prefixes, peer141 projection, one COMPLETE, zero FAIL, exit0 and -empty stdout/stderr. All65 pins/all522 prior filenames and hashes passed after exit. Exactly six +Root independently rehashed the 65 pins and 522 baseline files immediately before guarded queue +transfer 120в†’121. Only this native process owned that lease. PID 6720 ran from +2026-11-11T12:44:37.6688885Z to 2026-11-11T12:44:40.2506392+00:00. All 166 unique groups passed +with the exact 160/154/149/137 prefixes, peer141 projection, one COMPLETE, zero FAIL, exit0 and +empty stdout/stderr. All 65 pins/all 522 prior filenames and hashes passed after exit. Exactly six new output names made528 total. The three literal inputs retain16/16/15 bytes. Both serializer -reports retain exact354/260-byte golden contents, hashes and current model fields. All7 forbidden +reports retain exact 354/260-byte golden contents, hashes and current model fields. All 7 forbidden paths remain absent, including both non-file list paths. The normal GUI remains at the SHA above. The six new groups directly assert cold values, all private setters/host sender/equality, individual -protocol/IP mappings and full order,2 selected lists/5 domains/23 preview targets, distinct request/ -timeout values and positive61-minute duration with17 jobs/199 requests. They assert both explicit +protocol/IP mappings and full order, 2 selected lists/5 domains/23 preview targets, distinct request/ +timeout values and positive 61-minute duration with 17 jobs/199 requests. They assert both explicit all-strategies states, unknown preset fallback, callbacks changing later source/preview reads, repeated equality/current adapter values/separate owners, nested preview identity and observer exception identity/partial effects/retry. They use actual MainPage, source adapter, Session, preview, @@ -132,16 +132,37 @@ inert settings constructor reads remain part of composition. No OnLoaded, real s backend/history/cleanup operation, settings write, additional operating file IO, desktop input or deletion was introduced. External absence checks cover the two non-file paths. -Root separately verified PID6720 and the exact executable absent, wrote idle121/requestfalse with -no pending call, and guarded release122/readback confirmed owner:null and all six participants paused. +Root separately verified PID 6720 and the exact executable absent, wrote idle 121/requestfalse with +no pending call, and guarded release 122/readback confirmed owner:null and all six participants paused. Raw recipes, logs, pins, baseline, source/resource evidence and postchecks remain in this plan's ignored workspace `.superpowers/sdd/2026-11-11-blockcheck-review-presentation/`. +## Independent final review + +Fresh reviewer review_presentation_final_review examined the complete range +`3c7f8961477dbff0b4b021493b629ba1a1a0fa05` through +`b679c6c10cde31ce728fb233f505450f57adeaa7`: zero Critical, zero Important and two Minor. +The product policy, direct adapter and synchronous bridge preserve the original behavior. Independent +read-only checks rehashed all 65 pins and 522 prior outputs, matched six new names, inputs and reports, +and reconstructed the exact 166-label corpus. Owner logs remain the executed build/test/process +evidence; the reviewer did not rerun those commands. + +Both findings concerned records. The retained ledger now qualifies its earlier shorthand: all 21 +cut paths match, 20 complete files are byte-identical, and DirectoriesManager changes only the new +expected fixture EXE path. Replacing that literal reproduces the whole file. All 32 old case partials +are byte-identical without substitution. The three new documents also separate ordinary words, +counts and issue references, including explicit Refs #14 and Refs #221. Product, tests, native case, +pins and outputs are unchanged. Static document checks apply to these corrections. + +The reviewer supports the stacked draft and qualified local result. Full Page/installed behavior, +runtime GC collection and real operating routes remain outside the bounded fixture. Final remote +checks and actual private Project readbacks remain executor gates before local closure. + ## Delivery status and limits -Final whole-change review, stacked draft final-head checks, actual PR Project readback and immediate -completed/Done acceptance remain pending at this evidence checkpoint. Parent13/14/15 and drafts -216/218/220 stay separate and unmerged. The two-method view establishes model composition, without +Stacked draft final-head checks, actual PR Project readback and immediate +completed/Done acceptance remain pending at this evidence checkpoint. Parent issues #13/#14/#15 and draft PRs +#216/#218/#220 stay separate and unmerged. The two-method view establishes model composition, without full Page rendering/XAML Loading/focus/activation, installed-product, GC collection, G1 or release acceptance. Independent qualification of unchanged components remains with their owning stages. Keep all accepted and rejected evidence, branches, workspaces and source archives. diff --git a/docs/superpowers/specs/2026-11-11-blockcheck-review-presentation-design.md b/docs/superpowers/specs/2026-11-11-blockcheck-review-presentation-design.md index 23ae267a..25b8db85 100644 --- a/docs/superpowers/specs/2026-11-11-blockcheck-review-presentation-design.md +++ b/docs/superpowers/specs/2026-11-11-blockcheck-review-presentation-design.md @@ -5,16 +5,16 @@ [Issue #221](https://github.com/lumenpearson/cdpiui/issues/221) owns the next LOCAL audit decomposition. The baseline is frozen draft PR #220 at `3c7f8961477dbff0b4b021493b629ba1a1a0fa05`. Its local child #219 is completed with all six -criteria, actual Project Done under grant117, and [final readback](https://github.com/lumenpearson/cdpiui/issues/219#issuecomment-6795215194). +criteria, actual Project Done under grant 117, and [final readback](https://github.com/lumenpearson/cdpiui/issues/219#issuecomment-6795215194). This does not accept the broad integration, G1, installed-product or release boundaries. -Use `dev/blockcheck-review-presentation` in the existing isolated Root worktree. Actual issue221 -Project intake119 was reloaded and read back before this design and implementation: In progress, +Use `dev/blockcheck-review-presentation` in the existing isolated Root worktree. Actual issue #221 +Project intake under grant 119 was reloaded and read back before this design and implementation: In progress, P2, Architecture, Medium, G2, lumenpearson and two canonical labels. The [intake receipt](https://github.com/lumenpearson/cdpiui/issues/221#issuecomment-6795366566) records -that evidence. The queue released120 with all six participants paused. +that evidence. The queue released 120 with all six participants paused. -The four MainPage partials total740 lines. Their Review partial still holds six strings and the +The four MainPage partials total 740 lines. Their Review partial still holds six strings and the policy that formats the preparation summary. Give this responsibility one internal state owner. The interface and adapter below are the executor's design choice under the user's instruction to continue independently. A fresh builder must inspect this design before product code changes. @@ -25,7 +25,7 @@ Create three focused files beside the existing MainPage owners: | File | Responsibility | | --- | --- | -| IBlockCheck2ReviewSource.cs | Read-only contract for the15 current Session values used by this policy. | +| IBlockCheck2ReviewSource.cs | Read-only contract for the 15 current Session values used by this policy. | | BlockCheck2ReviewSource.cs | Direct adapter over one actual BlockCheck2ViewModel, with no copies or policy. | | BlockCheck2ReviewPresentation.cs | Six observable strings and the literal summary update policy. | @@ -103,7 +103,7 @@ the text delegate and the existing FormatDuration call with its delegate. Preser ## Verification Write focused linked-source tests before implementation and observe the missing-component RED. -Cover cold dependencies, all15 source properties, literal protocol/IP combinations and order, +Cover cold dependencies, all 15 source properties, literal protocol/IP combinations and order, conditional TLS localization, preset fallback and second-read short circuit, sources/preview identity, numeric culture, null and positive maximum estimates, per-publication changes, repeated equality, nested updates and partial observer/port failures. Explicitly assert a positive maximum estimate @@ -112,11 +112,11 @@ reaches the duration formatter with distinct job/request values. Test null-previ A controlled early preset cache must fail an observable mutation assertion. Restore exact bytes and hash, then pass focused/full suites and normal Release/x64 GUI. Compare source/compiled public contracts and exact two-host-files/three-internal-files footprint. A source guard must compare policy -tokens, significant strings, all15 direct adapter mappings, six private setters, one bridge and the +tokens, significant strings, all 15 direct adapter mappings, six private setters, one bridge and the unchanged host remainder. Record every failed tool attempt and correction truthfully. Build a NEW immutable native fixture from the accepted160 recipe. Preserve all prior case bytes, -labels and21 cuts. The new owner/adapter/MainPage remain uncut. Use actual Session/options and +labels and 21 cuts. The new owner/adapter/MainPage remain uncut. Use actual Session/options and controlled values, real preview/localizer/duration/dispatcher, and a narrow view with the existing inert operating ports. Exercise positive maximum formatting, live callback mutations, private setters/sender/equality, nested previews and exceptions. Seed list-item content explicitly when @@ -131,9 +131,9 @@ separately from executed assertions. No full Page, XAML Loading or GC collection ## Delivery and exclusions -Complete fresh final whole-branch review and any required Critical/Important RED→GREEN fixes. -Publish a stacked draft on frozen PR220, verify exact final-head checks and actual PR Project fields, +Complete fresh final whole-branch review and any required Critical/Important REDв†’GREEN fixes. +Publish a stacked draft on frozen PR #220, verify exact final-head checks and actual PR Project fields, then post six-section LOCAL acceptance and immediately close completed/set actual Done/read back. -Parent issues13/14/15 and drafts216/218/220 retain their separate integration and release boundaries. +Parent issues #13/#14/#15 and draft PRs #216/#218/#220 retain their separate integration and release boundaries. No shared-main change, installation, dependency update, security takeover or destructive operation is authorized by this stage. Retain all workspaces, refs and accepted/rejected evidence. From f7338ef123b490fb1f7919a633b4dad421433730 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:35:57 +0300 Subject: [PATCH 18/31] Record MainPage wizard navigation design The wizard host still combines current step and button state with asynchronous workflow. The design assigns that navigation state to a focused owner and a direct live source. View publication keeps its original step observations, while later availability reads remain current after callbacks. The existing command retains its identity and receives every cancellation notification, including repeated equal values. The owner is created before command construction and stores its callbacks without invoking them. The builder check found nothing important left after tracing the existing constructor and navigation policy. The plan requires tests before code, a cache mutation control, public contract checks and fresh native qualification. Product implementation has not started, and parent integration and release acceptance remain separate. Changed files: - "docs/governance/document-inventory.json" (+20/-0 lines). - "docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md" (+80/-0 lines). - "docs/superpowers/specs/2026-11-11-blockcheck-wizard-navigation-design.md" (+142/-0 lines). The file counts compare the staged tree with its first parent. Refs: #223 Staged-Tree: 2ae9b84181000c86d83228621ddcdc086f80341b --- docs/governance/document-inventory.json | 20 +++ ...2026-11-11-blockcheck-wizard-navigation.md | 80 ++++++++++ ...-11-blockcheck-wizard-navigation-design.md | 142 ++++++++++++++++++ 3 files changed, 242 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md create mode 100644 docs/superpowers/specs/2026-11-11-blockcheck-wizard-navigation-design.md diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index 806e9898..f3791828 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1515,6 +1515,26 @@ "policy": "ASD-STE100 principles for English", "language": "en", "changes": "Record focused mutation/full managed evidence, exact source and public contract checks, bounded actual-host qualification and local delivery limits." + }, + { + "path": "docs/superpowers/specs/2026-11-11-blockcheck-wizard-navigation-design.md", + "firstIntroduction": "Local MainPage wizard navigation contract under issue223; baseline b627a0f62dace8dde20ca2574a9d28646f71b421.", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Define current step and button ownership, direct live navigation source, unconditional command notifications and bounded local qualification." + }, + { + "path": "docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md", + "firstIntroduction": "Local MainPage wizard navigation contract under issue223; baseline b627a0f62dace8dde20ca2574a9d28646f71b421.", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Define current step and button ownership, direct live navigation source, unconditional command notifications and bounded local qualification." } ], "current_history_base": "7ead95f7756057f67cd113671a7f84cf422e8d32", diff --git a/docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md b/docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md new file mode 100644 index 00000000..29bdbace --- /dev/null +++ b/docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md @@ -0,0 +1,80 @@ +# MainPage Wizard Navigation Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan inline, task-by-task, with a fresh final independent reviewer. + +**Goal:** Move wizard step, Next state and Cancel availability into one focused navigation owner. + +**Architecture:** An internal observable owner reads a live source with seven bool properties, +calls the existing view and uses one command-notification action. The host keeps its bound API and +private forwarding entrypoints, with one synchronous property bridge. + +**Tech Stack:** C#/.NET 8.0.427, xUnit linked source, WinUI3, exact API/source and immutable native evidence. + +**Spec:** [wizard navigation design](../specs/2026-11-11-blockcheck-wizard-navigation-design.md). + +## Global constraints + +- Issue #223 actual Project intake under grant 127 is verified before implementation. +- Use isolated dev/blockcheck-wizard-navigation from frozen PR #222/b627a0f; preserve all parent refs. +- Preserve SiteLists/true/null/true defaults, two public Next properties/private setters, one command + instance, and private GoToStep/SetCancelEnabled/UpdateNavigationButtons forwards. +- Preserve running/step observations before the view, current source reads after it and every original + short circuit. SetCancelEnabled always assigns and notifies, including equal values. +- Construct the cold owner before CancelCommand; no source/view/text/command callback runs early. +- Change only the main existing MainPage file, plus mechanical step reads. Keep all other owners, + async workflow bodies, models/interfaces, Session/options, resources, packages and operating code. +- No OnLoaded or command Execute in native cases; no new operating IO/cuts. Native launch needs + independent READY and a NEW explicit exclusive lease, including read-only UI APIs. +- Retain every worktree/ref/archive/accepted and rejected artifact; no deletion, reset or parent merge. + +## Review Focus + +- View callbacks can change Session/current step after visibility and step flags are computed. +- Equal Cancel values still notify the same command; its observer reads the assigned value and can fail. +- Advanced uses validity then CanContinue, without a HasTargetSources guard; Mode and other steps + retain their own short circuits, even when the Next button is hidden during running. +- Nested view/command/property/text calls preserve each frame's earlier flags and later current inputs. +- Constructor callback capture and one synchronous bridge retain coldness, sender and lifetime without + a new static root, loaded subscription or notification for plain step/cancel state. + +### Task 1: Extract navigation state and the direct live source + +**Files:** create IBlockCheck2NavigationSource.cs, BlockCheck2NavigationSource.cs and +BlockCheck2WizardNavigation.cs beside MainPage; modify only MainPageViewModel.cs in existing product; +add CDPIUI.Tests/Presentation/BlockCheck2WizardNavigationTests.cs and links for owner/interface/ +existing view/enum/record; design/plan/report and additive inventory. + +**Interfaces:** consumes seven current source bools, existing two-method view, Text and unconditional +command notification. Produces current step/Cancel getters, two observable Next properties and the +three existing private host entrypoints through direct forwards. + +- [ ] Read issue/spec/intake and retain source/compiled/normal baselines. Obtain a fresh builder verdict + before product code. Verify no old native case depends on moved private fields. +- [ ] Write focused cold/state/ordering tests first and observe expected missing-component RED. +- [ ] Implement the exact source and owner policy, host forwards/current-step reads and one bridge; + preserve prior constructor statement order. Run focused GREEN and inspect real assertions. +- [ ] Apply a controlled CanCancel cache before the view callback; observe behavior failures, restore + exact bytes/hash and pass focused/full GREEN plus normal GUI with zero warnings/errors. +- [ ] Verify source/compiled public preservation, exact footprint, original policy/read points/seven + mappings/host fields/constructor/command wiring, governance and redacted scans; commit checkpoint. + +### Task 2: Qualify actual host/command composition and accept locally + +**Files:** fresh immutable F:/cdpiui-verify fixture and ignored recipes/pins/logs/postchecks; +dedicated report and additive inventory. + +**Interfaces:** consumes Task 1 source pin and accepted 166 corpus/case bytes/cut paths. Produces +actual host/source/view/command evidence and local delivery without accepting parent integration. + +- [ ] Read Task 1 evidence/brief; preserve all 166 labels and old case bytes/cuts, derive fresh input, + corpus/pin/extra counts and discriminating command/current-step callback cases before build. +- [ ] Obtain independent pre-build review, build zero warnings/errors, derive actual artifacts/resources/ + source/runner/verifier pins and full output baseline, then independent prelaunch READY. +- [ ] Acquire a new explicit exclusive lease; run one process and prove labels/COMPLETE/exit/streams, + source/resources/hashes/IO/absence/process cleanup, idle/requestfalse and guarded release. +- [ ] Update evidence and obtain fresh whole-branch review; resolve Critical/Important through observed + RED→GREEN, ledger all rulings/deferred minors and retain original artifacts. +- [ ] Publish a draft stacked on dev/blockcheck-review-presentation with Refs #14 and Refs #223; + verify exact final-head checks and actual PR metadata/Project fields, without parent/main merge. +- [ ] Verify all six criteria, post six-section LOCAL acceptance, immediately close completed/set actual + Project Done and read back closure, criteria, labels, owner, milestone and fields. diff --git a/docs/superpowers/specs/2026-11-11-blockcheck-wizard-navigation-design.md b/docs/superpowers/specs/2026-11-11-blockcheck-wizard-navigation-design.md new file mode 100644 index 00000000..e7124772 --- /dev/null +++ b/docs/superpowers/specs/2026-11-11-blockcheck-wizard-navigation-design.md @@ -0,0 +1,142 @@ +# MainPage wizard navigation ownership + +## Intent and execution boundary + +[Issue #223](https://github.com/lumenpearson/cdpiui/issues/223) owns this LOCAL continuation of +the audit decomposition. Frozen baseline: draft PR #222 at +`b627a0f62dace8dde20ca2574a9d28646f71b421`. Its local stage #221 is completed with all six +criteria, actual Project Done under grant 125 and +[final readback](https://github.com/lumenpearson/cdpiui/issues/221#issuecomment-6796855871). +The four MainPage partials total 677 lines. This stage extracts its remaining navigation state +and projection without changing asynchronous workflow or operating behavior. + +Root owns `dev/blockcheck-wizard-navigation` in the existing isolated worktree. Actual issue #223 +Project intake under grant 127 was verified after reload: In progress/P2/Architecture/Medium/G2, +lumenpearson and exactly two canonical labels. The +[receipt](https://github.com/lumenpearson/cdpiui/issues/223#issuecomment-6797095818) records it. +Queue 128 is released with all six participants paused. No lease is inferred from that state. + +These design choices are the executor's under the user's explicit autonomous authorization. +A fresh builder checks them before implementation. Keep parent issues #13/#14/#15 and draft PRs +#216/#218/#220/#222 open and separate; no main integration or release is accepted here. + +## Structure and state + +Create three internal files beside the existing MainPage owners: + +| File | Responsibility | +| --- | --- | +| IBlockCheck2NavigationSource.cs | Seven read-only Session observations used by navigation. | +| BlockCheck2NavigationSource.cs | Direct live Session adapter, with no copied values or policy. | +| BlockCheck2WizardNavigation.cs | Current step, Next state, Cancel availability and original projection policy. | + +The owner derives from ObservableObject. Keep these cold values: + +| Value | Initial state | Notification rule | +| --- | --- | --- | +| CurrentStep | BlockCheck2WizardStep.SiteLists | Plain state; no PropertyChanged. | +| IsNextEnabled | true | Existing SetProperty equality and field-before-event semantics. | +| NextButtonText | null | Existing SetProperty equality and field-before-event semantics. | +| IsCancelEnabled | true | Plain state; command notification on every setter call. | + +Expose CurrentStep and IsCancelEnabled as getters on the internal owner. IsNextEnabled and +NextButtonText are writable there so host private setters can forward without a second SetProperty. +Keep the host's public property signatures and the existing CancelCommand object. + +Constructor dependencies are: + +```csharp +BlockCheck2WizardNavigation( + IBlockCheck2NavigationSource source, + IBlockCheck2MainPageView view, + Func text, + Action notifyCancelChanged) +``` + +All four dependencies are stored without invocation. Reuse the existing two-method view interface, +WizardStep enum and NavigationButtons record. The source has seven bool getters: IsRunning, +CanCancel, HasTargetSources, AdvancedOptionsValid, CanContinueFromTargets, CanStart and HasReport. +The first six directly return same-named Session properties; HasReport returns Session.LastReport +!= null at the original conditional read point. Its constructor stores Session without reading data. +Do not implement a new interface on Session or change existing model/view definitions. + +In the host, add one readonly navigation owner and create it after the existing view/duration setup, +before CancelCommand construction. Supply a stored closure that calls the eventual existing +CancelCommand.NotifyCanExecuteChanged. Constructor coldness is essential: this closure must not run +before the command is assigned. The RelayCommand constructor itself only stores callbacks. +Its CanExecute closure reads navigation.IsCancelEnabled. Keep all prior constructor statements in +their relative order, and use the stored host view when creating the owner. + +Attach one synchronous owner.PropertyChanged bridge to host.OnPropertyChanged(args.PropertyName). +It forwards only the two bound Next properties because plain step/cancel state raises no event. +No bridge is added by OnLoaded/OnUnloaded and no new static event or lifetime mechanism is needed. +The object graph belongs to the host and shares its lifetime; no GC collection claim is implied. + +Remove the four old backing fields. Every remaining host step read becomes navigation.CurrentStep +at its original point. Keep private GoToStep(step), SetCancelEnabled(value) and +UpdateNavigationButtons as direct forwards. Async Next/Back/Cancel methods otherwise stay intact. +Keep notices, progress/review/completion owners, localization, Session/options/site lists, resources, +packages and operating code unchanged. Only the existing main MainPage file changes in product. + +## Original sequencing contract + +GoToStep always assigns the new step before calling view.GoToStep(step), including repeated or +unknown enum values. A view callback may call GoToStep again; the inner step remains current after +the outer view call returns. A thrown view exception retains the already assigned step. Add no +validation, equality guard, catch or automatic navigation refresh. + +SetCancelEnabled always assigns its argument, then calls notifyCancelChanged, even for equal values. +Do not use SetProperty or notify a model property. The command event keeps the existing command as +sender, and CanExecute must observe the new value inside that event. An observer exception leaves +the assigned availability and stops the caller at the same point. There is no notification deduplication. + +Move UpdateNavigationButtons literally with these declared source/Text substitutions: + +1. Read source.IsRunning, then derive all six local step flags from the current stored step. +2. Construct the same NavigationButtons record and call view.ShowNavigationButtons. Exit follows + WorkComplete; Back is !running; Cancel is running; Next is !running && !onProgress && !onComplete. + ViewResult reads HasReport only when !running && onComplete. All these values precede the view + callback and retain their original observations. +3. After that callback, read current source.CanCancel and call SetCancelEnabled unconditionally. + Its command observer can change later inputs before Next evaluation. +4. Set IsNextEnabled using the original local step flags and lazy current source reads: SiteLists + reads HasTargetSources; Advanced reads AdvancedOptionsValid then CanContinueFromTargets only + when valid; Mode is true; Review reads CanStart; other steps are false. Do not add !running or + HasTargetSources checks. In particular, CanContinueFromTargets is independent of HasTargetSources. +5. Localize StartButton for the original onReview flag, otherwise NextButton, after IsNextEnabled + publication. Do not recompute the step flags after view, command, property or text callbacks. + +Preserve original partial effects, exception identity and nested calls. Equal bound outputs still +evaluate their right-hand sides; the view, command notification and localization still occur on +repeated updates. The mix of earlier local observations and later live reads is intentional preservation. + +## Verification and limits + +Write tests first and observe missing-component RED. Linked-source tests use a traced mutable +source, the existing view contract and a command-notification action; no WinUI or settings class +is needed. Cover all steps/unknown values, running/report combinations, lazy report/Next branches, +constructor coldness, repeated GoToStep calls, state-before-view callbacks, command notification on +every assignment, no step/cancel PropertyChanged, sender/current values, snapshots before view and +live CanCancel/Next reads after it, nested calls, localization mutation, exceptions/partial state/retry. +Do not assume running directly disables IsNextEnabled: the visibility record and bound value have +different original rules. A controlled early CanCancel cache before the view callback must fail. + +Restore exact bytes/hash and pass focused/full suites, normal Release/x64 GUI, source/compiled API, +exact footprint/policy/adapter/constructor/host-read guards, governance and redacted scans. Link the +new owner/interface and existing view/enum/record files into tests; keep the real adapter for native +composition. Preserve normal output baselines before rebuilding. + +Extend accepted 166 into a NEW immutable native fixture with all old labels/case bytes and the same +21 cut paths. The one fixture-specific expected EXE literal changes; other cut bodies remain intact. +The new owner/source/MainPage/view/RelayCommand stay real and uncut, with a controlled two-method +view and inherited inert operating ports. Check actual command identity/sender/CanExecute state and +repeated notifications without Execute, private entrypoints through delegates, current step changes, +view snapshots/later Session reads, nested callbacks and partial exceptions. Add no operating IO, +cut, lifecycle call or user setting write. Derive counts/pins, independently review before build and +launch, inspect actual PE/non-admin status/resources/full hashes, acquire a NEW explicit UI lease, +then verify exact runtime corpus/COMPLETE/exit/streams/IO/hash/absence/process cleanup and release. + +Fresh final review, exact final-head stacked draft checks, actual PR Project readback and immediate +completed/Done acceptance finish only this local contract. Full Page/XAML/focus/activation, installed +product, real operating routes, GC collection, G1, broad integration and release remain separate. +Retain all refs/worktrees/archives/accepted and rejected evidence; no destructive cleanup is authorized. From 31ab5c2f16dbbf11c5c1fab4f5a0e90214be7f05 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:51:27 +0300 Subject: [PATCH 19/31] Extract MainPage wizard navigation state The wizard host mixed current step and button state with the workflow. The new internal owner holds these values and reads current Session properties through a direct source adapter. Existing host properties and private entrypoints remain synchronous forwards. The original command keeps its identity and notifies on every Cancel assignment, including equal values. Focused tests observed the missing owner before implementation and detected an early Cancel cache before exact source restoration. All 2505 managed tests and the normal WinUI build pass with the restored source. Exact policy guards and source and compiled contract comparisons also pass. Fresh native qualification remains the next local acceptance step. Changed files: - "CDPIUI.Tests/CDPIUI.Tests.csproj" (+5/-0 lines). - "CDPIUI.Tests/Presentation/BlockCheck2WizardNavigationTests.cs" (+339/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs" (+25/-56 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2NavigationSource.cs" (+17/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/BlockCheck2WizardNavigation.cs" (+80/-0 lines). - "CDPIUI/ViewModels/BlockCheck2/IBlockCheck2NavigationSource.cs" (+12/-0 lines). - "docs/governance/document-inventory.json" (+14/-4 lines). - "docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md" (+75/-0 lines). The file counts compare the staged tree with its first parent. Refs: #223 Staged-Tree: afd920f501dd121d253d10808dfbd07720a90ee0 --- CDPIUI.Tests/CDPIUI.Tests.csproj | 5 + .../BlockCheck2WizardNavigationTests.cs | 339 ++++++++++++++++++ .../BlockCheck2MainPageViewModel.cs | 81 ++--- .../BlockCheck2NavigationSource.cs | 17 + .../BlockCheck2WizardNavigation.cs | 80 +++++ .../IBlockCheck2NavigationSource.cs | 12 + docs/governance/document-inventory.json | 18 +- ...ockcheck-wizard-navigation-verification.md | 75 ++++ 8 files changed, 567 insertions(+), 60 deletions(-) create mode 100644 CDPIUI.Tests/Presentation/BlockCheck2WizardNavigationTests.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/BlockCheck2NavigationSource.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/BlockCheck2WizardNavigation.cs create mode 100644 CDPIUI/ViewModels/BlockCheck2/IBlockCheck2NavigationSource.cs create mode 100644 docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md diff --git a/CDPIUI.Tests/CDPIUI.Tests.csproj b/CDPIUI.Tests/CDPIUI.Tests.csproj index 48d496aa..5b028f3d 100644 --- a/CDPIUI.Tests/CDPIUI.Tests.csproj +++ b/CDPIUI.Tests/CDPIUI.Tests.csproj @@ -56,6 +56,11 @@ + + + + + diff --git a/CDPIUI.Tests/Presentation/BlockCheck2WizardNavigationTests.cs b/CDPIUI.Tests/Presentation/BlockCheck2WizardNavigationTests.cs new file mode 100644 index 00000000..36c2bab0 --- /dev/null +++ b/CDPIUI.Tests/Presentation/BlockCheck2WizardNavigationTests.cs @@ -0,0 +1,339 @@ +using CDPIUI.ViewModels.BlockCheck2; + +namespace CDPIUI.Tests.Presentation; + +public class BlockCheck2WizardNavigationTests +{ + [Fact] + public void ConstructorKeepsFourColdValuesWithoutInvokingDependencies() + { + var owner = new BlockCheck2WizardNavigation(null!, null!, + _ => throw new InvalidOperationException("Early text read"), + () => throw new InvalidOperationException("Early command notification")); + + Assert.Equal(0, (int)owner.CurrentStep); + Assert.True(owner.IsNextEnabled); + Assert.Null(owner.NextButtonText); + Assert.True(owner.IsCancelEnabled); + } + + [Theory] + [InlineData(0, false, false, false, true, false, false, true, true, "next")] + [InlineData(0, false, true, false, true, false, false, true, true, "next")] + [InlineData(0, true, false, false, false, true, false, false, true, "next")] + [InlineData(0, true, true, false, false, true, false, false, true, "next")] + [InlineData(1, false, false, false, true, false, false, true, true, "next")] + [InlineData(1, false, true, false, true, false, false, true, true, "next")] + [InlineData(1, true, false, false, false, true, false, false, true, "next")] + [InlineData(1, true, true, false, false, true, false, false, true, "next")] + [InlineData(2, false, false, false, true, false, false, true, true, "next")] + [InlineData(2, false, true, false, true, false, false, true, true, "next")] + [InlineData(2, true, false, false, false, true, false, false, true, "next")] + [InlineData(2, true, true, false, false, true, false, false, true, "next")] + [InlineData(3, false, false, false, true, false, false, true, true, "start")] + [InlineData(3, false, true, false, true, false, false, true, true, "start")] + [InlineData(3, true, false, false, false, true, false, false, true, "start")] + [InlineData(3, true, true, false, false, true, false, false, true, "start")] + [InlineData(4, false, false, false, true, false, false, false, false, "next")] + [InlineData(4, false, true, false, true, false, false, false, false, "next")] + [InlineData(4, true, false, false, false, true, false, false, false, "next")] + [InlineData(4, true, true, false, false, true, false, false, false, "next")] + [InlineData(5, false, false, true, true, false, false, false, false, "next")] + [InlineData(5, false, true, true, true, false, true, false, false, "next")] + [InlineData(5, true, false, true, false, true, false, false, false, "next")] + [InlineData(5, true, true, true, false, true, false, false, false, "next")] + [InlineData(999, false, false, false, true, false, false, true, false, "next")] + [InlineData(999, false, true, false, true, false, false, true, false, "next")] + [InlineData(999, true, false, false, false, true, false, false, false, "next")] + [InlineData(999, true, true, false, false, true, false, false, false, "next")] + public void VisibilityAndEnabledValuesRetainTheOriginalTable(int step, bool running, bool report, + bool exit, bool back, bool cancel, bool result, bool next, bool enabled, string text) + { + var f = new Fixture(); f.Owner.GoToStep((BlockCheck2WizardStep)step); f.ClearTrace(); + f.Source.Running = running; f.Source.Report = report; f.Owner.UpdateNavigationButtons(); + Assert.Equal(new BlockCheck2NavigationButtons(exit, back, cancel, result, next), Assert.Single(f.Buttons)); + Assert.Equal(enabled, f.Owner.IsNextEnabled); Assert.Equal(text, f.Owner.NextButtonText); + Assert.False(f.Owner.IsCancelEnabled); Assert.Equal(1, f.Notifications); + } + + [Theory] + [InlineData(0)] [InlineData(3)] [InlineData(5)] [InlineData(999)] + public void EveryGoAssignsBeforeTheViewEvenForRepeatedOrUnknownSteps(int value) + { + var f = new Fixture(); var step = (BlockCheck2WizardStep)value; + f.OnStep = point => { if (point.StartsWith("view-step:", StringComparison.Ordinal)) Assert.Equal(step, f.Owner.CurrentStep); }; + f.Owner.GoToStep(step); f.Owner.GoToStep(step); + Assert.Equal([step, step], f.Steps); + Assert.DoesNotContain(f.Trace, p => p.StartsWith("changed:", StringComparison.Ordinal)); + } + + [Fact] + public void NestedGoKeepsTheInnerStepAfterTheOuterViewReturns() + { + var f = new Fixture(); bool nested = false; + f.OnStep = point => { if (point == "view-step:Review" && !nested) { nested = true; f.Owner.GoToStep(BlockCheck2WizardStep.Advanced); } }; + f.Owner.GoToStep(BlockCheck2WizardStep.Review); + Assert.Equal(BlockCheck2WizardStep.Advanced, f.Owner.CurrentStep); + Assert.Equal([BlockCheck2WizardStep.Review, BlockCheck2WizardStep.Advanced], f.Steps); + } + + [Fact] + public void GoFailureRetainsAssignedStepAndExceptionIdentity() + { + var f = new Fixture(); var failure = new Sentinel(); + f.OnStep = p => { if (p.StartsWith("view-step:", StringComparison.Ordinal)) throw failure; }; + Assert.Same(failure, Assert.Throws(() => f.Owner.GoToStep((BlockCheck2WizardStep)999))); + Assert.Equal((BlockCheck2WizardStep)999, f.Owner.CurrentStep); + f.OnStep = null; f.Owner.GoToStep(BlockCheck2WizardStep.Mode); + Assert.Equal(BlockCheck2WizardStep.Mode, f.Owner.CurrentStep); + } + + [Theory] + [InlineData(false)] [InlineData(true)] + public void CancelAlwaysAssignsAndNotifiesIncludingEqualValuesWithoutPropertyEvents(bool value) + { + var f = new Fixture(); + f.OnStep = p => { if (p.StartsWith("command:", StringComparison.Ordinal)) Assert.Equal(value, f.Owner.IsCancelEnabled); }; + f.Owner.SetCancelEnabled(value); f.Owner.SetCancelEnabled(value); + Assert.Equal([value, value], f.CommandValues); + Assert.Equal(2, f.Notifications); + Assert.DoesNotContain(f.Trace, p => p.StartsWith("changed:", StringComparison.Ordinal)); + } + + [Fact] + public void UpdatePublishesViewThenCurrentCancelThenNextAndLocalizedText() + { + var f = new Fixture(); f.Owner.GoToStep(BlockCheck2WizardStep.Review); f.ClearTrace(); f.Source.Start = false; + f.Owner.UpdateNavigationButtons(); + Assert.Equal(["running", "view-buttons", "can-cancel", "command:False", "can-start", + "changed:IsNextEnabled", "text:BlockCheck2StartButton", "changed:NextButtonText"], f.Trace); + } + + [Fact] + public void ViewCallbackKeepsEarlierVisibilityAndStepFlagsButLaterCancelIsCurrent() + { + var f = new Fixture(); f.Owner.GoToStep(BlockCheck2WizardStep.Review); f.ClearTrace(); + f.OnStep = p => + { + if (p == "view-buttons") + { + f.Owner.GoToStep(BlockCheck2WizardStep.WorkComplete); f.Source.Running = true; + f.Source.Cancel = true; f.Source.Start = false; + } + }; + f.Owner.UpdateNavigationButtons(); + Assert.Equal(new BlockCheck2NavigationButtons(false, true, false, false, true), Assert.Single(f.Buttons)); + Assert.Equal(BlockCheck2WizardStep.WorkComplete, f.Owner.CurrentStep); + Assert.True(f.Owner.IsCancelEnabled); Assert.False(f.Owner.IsNextEnabled); Assert.Equal("start", f.Owner.NextButtonText); + Assert.Contains("can-start", f.Trace); + Assert.True(f.Trace.IndexOf("view-buttons") < f.Trace.IndexOf("can-cancel")); + } + + [Fact] + public void StepFlagsAreObservedAfterTheRunningGetter() + { + var f = new Fixture(); f.Source.Report = true; + f.OnStep = p => { if (p == "running") f.Owner.GoToStep(BlockCheck2WizardStep.WorkComplete); }; + f.Owner.UpdateNavigationButtons(); + Assert.Equal(new BlockCheck2NavigationButtons(true, true, false, true, false), Assert.Single(f.Buttons)); + Assert.Equal(["running", "view-step:WorkComplete", "report"], f.Trace.Take(3)); + } + + [Fact] + public void CommandCallbackChangesLaterInputsButDoesNotRecomputeAdvancedStepFlags() + { + var f = new Fixture(); f.Owner.GoToStep(BlockCheck2WizardStep.Advanced); f.ClearTrace(); f.Source.Valid = false; + f.OnStep = p => + { + if (p == "command:False") + { f.Source.Valid = true; f.Source.Continue = true; f.Owner.GoToStep(BlockCheck2WizardStep.Review); f.Source.Start = false; } + }; + f.Owner.UpdateNavigationButtons(); + Assert.True(f.Owner.IsNextEnabled); Assert.Equal("next", f.Owner.NextButtonText); + Assert.Equal(BlockCheck2WizardStep.Review, f.Owner.CurrentStep); + Assert.Contains("valid", f.Trace); Assert.Contains("continue", f.Trace); Assert.DoesNotContain("can-start", f.Trace); + } + + [Fact] + public void NextPropertyCallbackDoesNotChangeTheEarlierReviewTextDecision() + { + var f = new Fixture(); f.Owner.GoToStep(BlockCheck2WizardStep.Review); f.ClearTrace(); f.Source.Start = false; + f.OnStep = p => { if (p == "changed:IsNextEnabled") f.Owner.GoToStep(BlockCheck2WizardStep.Mode); }; + f.Owner.UpdateNavigationButtons(); + Assert.Equal(BlockCheck2WizardStep.Mode, f.Owner.CurrentStep); + Assert.False(f.Owner.IsNextEnabled); Assert.Equal("start", f.Owner.NextButtonText); + } + + [Fact] + public void NestedLocalizationRetainsInnerEnabledValueAndOuterText() + { + var f = new Fixture(); f.Owner.GoToStep(BlockCheck2WizardStep.Review); f.ClearTrace(); bool nested = false; + f.OnStep = p => + { + if (p == "text:BlockCheck2StartButton" && !nested) + { + nested = true; f.Owner.GoToStep(BlockCheck2WizardStep.SiteLists); f.Source.Targets = false; + f.Owner.UpdateNavigationButtons(); + } + }; + f.Owner.UpdateNavigationButtons(); + Assert.Equal(BlockCheck2WizardStep.SiteLists, f.Owner.CurrentStep); + Assert.False(f.Owner.IsNextEnabled); Assert.Equal("start", f.Owner.NextButtonText); + Assert.Equal(2, f.Notifications); Assert.Equal(2, f.Buttons.Count); + Assert.Equal(2, f.Trace.Count(p => p == "changed:NextButtonText")); + } + + [Fact] + public void NestedViewRetainsTheOuterSitesDecisionAfterInnerReview() + { + var f = new Fixture(); f.Source.Targets = false; bool nested = false; + f.OnStep = p => + { + if (p == "view-buttons" && !nested) + { nested = true; f.Owner.GoToStep(BlockCheck2WizardStep.Review); f.Owner.UpdateNavigationButtons(); } + }; + f.Owner.UpdateNavigationButtons(); + Assert.Equal(BlockCheck2WizardStep.Review, f.Owner.CurrentStep); + Assert.False(f.Owner.IsNextEnabled); Assert.Equal("next", f.Owner.NextButtonText); + Assert.Equal(2, f.Notifications); Assert.Equal(2, f.Buttons.Count); + } + + [Fact] + public void EqualUpdatesStillCallViewCommandSourceAndTextButSuppressBoundPropertyEvents() + { + var f = new Fixture(); f.Source.Targets = false; f.Owner.UpdateNavigationButtons(); f.ClearTrace(); + f.Owner.UpdateNavigationButtons(); + Assert.Equal(["running", "view-buttons", "can-cancel", "command:False", "targets", "text:BlockCheck2NextButton"], f.Trace); + Assert.Equal(1, f.Notifications); + } + + [Theory] + [InlineData(0, false)] [InlineData(1, false)] [InlineData(2, false)] [InlineData(3, false)] + [InlineData(4, false)] [InlineData(5, true)] [InlineData(999, false)] + public void ReportGetterStaysLazyWhenVisibilityDoesNotNeedIt(int step, bool running) + { + var f = new Fixture(); f.Owner.GoToStep((BlockCheck2WizardStep)step); f.Source.Running = running; + f.OnStep = p => { if (p == "report") throw new Sentinel(); }; + f.Owner.UpdateNavigationButtons(); Assert.DoesNotContain("report", f.Trace); + } + + [Theory] + [InlineData(0, false, "targets")] + [InlineData(1, false, "")] + [InlineData(2, false, "valid")] + [InlineData(2, true, "valid,continue")] + [InlineData(3, false, "can-start")] + [InlineData(4, false, "")] + [InlineData(5, false, "")] + [InlineData(999, false, "")] + public void NextBranchesReadOnlyTheirOriginalInputs(int step, bool valid, string expected) + { + var f = new Fixture(); f.Owner.GoToStep((BlockCheck2WizardStep)step); f.ClearTrace(); f.Source.Valid = valid; + f.Owner.UpdateNavigationButtons(); + string[] ports = ["targets", "valid", "continue", "can-start"]; + Assert.Equal(expected.Split(',', StringSplitOptions.RemoveEmptyEntries), f.Trace.Where(ports.Contains)); + } + + [Fact] + public void AdvancedDoesNotAddATargetSourceGuardAndRunningDoesNotDirectlyDisableNextValue() + { + var f = new Fixture(); f.Owner.GoToStep(BlockCheck2WizardStep.Advanced); f.Source.Targets = false; f.Source.Running = true; + f.Owner.UpdateNavigationButtons(); + Assert.True(f.Owner.IsNextEnabled); Assert.False(Assert.Single(f.Buttons).Next); + Assert.DoesNotContain("targets", f.Trace); + } + + [Fact] + public void BoundSettersKeepCurrentFieldAndEqualityIncludingNullText() + { + var f = new Fixture(); f.Owner.NextButtonText = null; Assert.Empty(f.Trace); + f.OnStep = p => + { + if (p == "changed:IsNextEnabled") Assert.False(f.Owner.IsNextEnabled); + if (p == "changed:NextButtonText") Assert.Equal("label", f.Owner.NextButtonText); + }; + f.Owner.IsNextEnabled = false; f.Owner.IsNextEnabled = false; + f.Owner.NextButtonText = "label"; f.Owner.NextButtonText = "label"; + Assert.Equal(["changed:IsNextEnabled", "changed:NextButtonText"], f.Trace); + } + + [Theory] + [InlineData("running", 0, 0, 0, true, true, null)] + [InlineData("report", 5, 0, 0, true, true, null)] + [InlineData("view-buttons", 0, 1, 0, true, true, null)] + [InlineData("can-cancel", 0, 1, 0, true, true, null)] + [InlineData("command:False", 0, 1, 1, false, true, null)] + [InlineData("targets", 0, 1, 1, false, true, null)] + [InlineData("valid", 2, 1, 1, false, true, null)] + [InlineData("continue", 2, 1, 1, false, true, null)] + [InlineData("can-start", 3, 1, 1, false, true, null)] + [InlineData("changed:IsNextEnabled", 0, 1, 1, false, false, null)] + [InlineData("text:BlockCheck2NextButton", 0, 1, 1, false, false, null)] + [InlineData("changed:NextButtonText", 0, 1, 1, false, false, "next")] + public void FailuresPreserveExceptionIdentityAndOriginalPartialEffects(string point, int step, + int views, int notifications, bool cancel, bool next, string? text) + { + var f = new Fixture(); f.Owner.GoToStep((BlockCheck2WizardStep)step); f.ClearTrace(); + f.Source.Targets = false; f.Source.Start = false; var failure = new Sentinel(); + f.OnStep = p => { if (p == point) throw failure; }; + Assert.Same(failure, Assert.Throws(() => f.Owner.UpdateNavigationButtons())); + Assert.Equal(views, f.Buttons.Count); Assert.Equal(notifications, f.Notifications); + Assert.Equal(cancel, f.Owner.IsCancelEnabled); Assert.Equal(next, f.Owner.IsNextEnabled); + Assert.Equal(text, f.Owner.NextButtonText); + f.OnStep = null; f.Owner.UpdateNavigationButtons(); Assert.NotNull(f.Owner.NextButtonText); + } + + [Fact] + public void OwnersHaveIndependentStateAndCallbacks() + { + var first = new Fixture(); var second = new Fixture(); first.Owner.GoToStep(BlockCheck2WizardStep.Review); + first.Owner.SetCancelEnabled(false); first.Owner.IsNextEnabled = false; first.Owner.NextButtonText = "first"; + Assert.Equal(BlockCheck2WizardStep.SiteLists, second.Owner.CurrentStep); + Assert.True(second.Owner.IsCancelEnabled); Assert.True(second.Owner.IsNextEnabled); Assert.Null(second.Owner.NextButtonText); + Assert.Empty(second.Trace); + } + + private sealed class Sentinel : Exception; + private sealed class Fixture + { + internal readonly List Trace = []; + internal readonly List Steps = []; + internal readonly List Buttons = []; + internal readonly List CommandValues = []; + internal Action? OnStep; + internal int Notifications; + internal readonly Source Source; + internal readonly BlockCheck2WizardNavigation Owner; + internal Fixture() + { + Source = new Source(this); Owner = new BlockCheck2WizardNavigation(Source, new View(this), Text, Notify); + Owner.PropertyChanged += (sender, args) => { Assert.Same(Owner, sender); Step("changed:" + args.PropertyName); }; + } + internal void Step(string point) { Trace.Add(point); OnStep?.Invoke(point); } + internal bool Read(string name, Func value) { Step(name); return value(); } + internal void ClearTrace() { Trace.Clear(); Steps.Clear(); Buttons.Clear(); CommandValues.Clear(); Notifications = 0; } + private string Text(string key) + { + Step("text:" + key); + return key switch { "BlockCheck2StartButton" => "start", "BlockCheck2NextButton" => "next", _ => throw new InvalidOperationException("Unexpected navigation key: " + key) }; + } + private void Notify() { Notifications++; CommandValues.Add(Owner.IsCancelEnabled); Step("command:" + Owner.IsCancelEnabled); } + } + private sealed class Source(Fixture f) : IBlockCheck2NavigationSource + { + internal bool Running, Cancel, Report; + internal bool Targets = true, Valid = true, Continue = true, Start = true; + public bool IsRunning => f.Read("running", () => Running); + public bool CanCancel => f.Read("can-cancel", () => Cancel); + public bool HasReport => f.Read("report", () => Report); + public bool HasTargetSources => f.Read("targets", () => Targets); + public bool AdvancedOptionsValid => f.Read("valid", () => Valid); + public bool CanContinueFromTargets => f.Read("continue", () => Continue); + public bool CanStart => f.Read("can-start", () => Start); + } + private sealed class View(Fixture f) : IBlockCheck2MainPageView + { + public void GoToStep(BlockCheck2WizardStep step) { f.Steps.Add(step); f.Step("view-step:" + step); } + public void ShowNavigationButtons(BlockCheck2NavigationButtons buttons) { f.Buttons.Add(buttons); f.Step("view-buttons"); } + } +} diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs index 4501945f..a4bd2514 100644 --- a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2MainPageViewModel.cs @@ -23,13 +23,10 @@ public sealed partial class BlockCheck2MainPageViewModel : ObservableObject private readonly BlockCheck2ProgressPresentation _progressPresentation; private readonly BlockCheck2ReviewPresentation _reviewPresentation; private readonly IBlockCheck2MainPageView _view; + private readonly BlockCheck2WizardNavigation _navigation; private bool _handlersConnected; private BlockCheck2PreparationPreview? _preparationPreview; - private BlockCheck2WizardStep _currentStep = BlockCheck2WizardStep.SiteLists; - private bool _isNextEnabled = true; - private string? _nextButtonText; - private bool _isCancelEnabled = true; private bool _isInputNoticeOpen; private string _inputNoticeTitle = string.Empty; @@ -44,7 +41,10 @@ public BlockCheck2MainPageViewModel(IBlockCheck2MainPageView view) { _view = view; _durationText = new BlockCheck2DurationText(_localizer); - CancelCommand = new RelayCommand(CancelFromButton, () => _isCancelEnabled); + _navigation = new BlockCheck2WizardNavigation( + new BlockCheck2NavigationSource(Session), _view, Text, () => CancelCommand.NotifyCanExecuteChanged()); + _navigation.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); + CancelCommand = new RelayCommand(CancelFromButton, () => _navigation.IsCancelEnabled); _completionPresenter = new BlockCheck2RunCompletionPresenter( () => Session.State, () => Session.NoBypassRequired, () => Session.LastReportIsHttpOnly, () => Session.OperationError, () => Session.HistorySaveError, Text, FormatIssues, @@ -89,14 +89,14 @@ public bool? IsExhaustiveModeSelected public bool IsNextEnabled { - get => _isNextEnabled; - private set => SetProperty(ref _isNextEnabled, value); + get => _navigation.IsNextEnabled; + private set => _navigation.IsNextEnabled = value; } public string? NextButtonText { - get => _nextButtonText; - private set => SetProperty(ref _nextButtonText, value); + get => _navigation.NextButtonText; + private set => _navigation.NextButtonText = value; } /// Two-way: the user can close the notice. @@ -217,7 +217,7 @@ private void UpdateLocalizedText() UpdateProgressViewMoreText(); UpdateNavigationButtons(); UpdateProgressText(); - if (_currentStep == BlockCheck2WizardStep.Review && _preparationPreview != null) + if (_navigation.CurrentStep == BlockCheck2WizardStep.Review && _preparationPreview != null) { UpdateReviewSummary(_preparationPreview); } @@ -232,34 +232,31 @@ private void SelectRunPreset(bool? isChecked, BlockCheckRunPreset preset) } } - private void GoToStep(BlockCheck2WizardStep step) - { - _currentStep = step; - _view.GoToStep(step); - } + private void GoToStep(BlockCheck2WizardStep step) => + _navigation.GoToStep(step); public async Task NextAsync() { - if (_currentStep == BlockCheck2WizardStep.SiteLists) + if (_navigation.CurrentStep == BlockCheck2WizardStep.SiteLists) { await ContinueFromSiteListsAsync(); return; } - if (_currentStep == BlockCheck2WizardStep.Mode) + if (_navigation.CurrentStep == BlockCheck2WizardStep.Mode) { GoToStep(BlockCheck2WizardStep.Advanced); UpdateNavigationButtons(); return; } - if (_currentStep == BlockCheck2WizardStep.Advanced) + if (_navigation.CurrentStep == BlockCheck2WizardStep.Advanced) { await ContinueFromAdvancedAsync(); return; } - if (_currentStep != BlockCheck2WizardStep.Review || !Session.CanStart) + if (_navigation.CurrentStep != BlockCheck2WizardStep.Review || !Session.CanStart) { return; } @@ -324,23 +321,23 @@ public bool GoBack() return false; } - if (_currentStep == BlockCheck2WizardStep.SiteLists) + if (_navigation.CurrentStep == BlockCheck2WizardStep.SiteLists) { return true; } - else if (_currentStep == BlockCheck2WizardStep.Mode) + else if (_navigation.CurrentStep == BlockCheck2WizardStep.Mode) { GoToStep(BlockCheck2WizardStep.SiteLists); } - else if (_currentStep == BlockCheck2WizardStep.Advanced) + else if (_navigation.CurrentStep == BlockCheck2WizardStep.Advanced) { GoToStep(BlockCheck2WizardStep.Mode); } - else if (_currentStep == BlockCheck2WizardStep.Review) + else if (_navigation.CurrentStep == BlockCheck2WizardStep.Review) { GoToStep(BlockCheck2WizardStep.Advanced); } - else if (_currentStep is BlockCheck2WizardStep.Progress or BlockCheck2WizardStep.WorkComplete) + else if (_navigation.CurrentStep is BlockCheck2WizardStep.Progress or BlockCheck2WizardStep.WorkComplete) { Session.Reset(); IsResultNoticeOpen = false; @@ -363,11 +360,8 @@ private void CancelFromButton() SetCancelEnabled(false); } - private void SetCancelEnabled(bool value) - { - _isCancelEnabled = value; - CancelCommand.NotifyCanExecuteChanged(); - } + private void SetCancelEnabled(bool value) => + _navigation.SetCancelEnabled(value); private void ShowInputIssue(string message) => ShowInputNotice(Text("BlockCheck2InputIssueTitle"), message); @@ -394,33 +388,8 @@ private string FormatIssues(IEnumerable sourceIssues) : string.Join(Environment.NewLine, messages); } - private void UpdateNavigationButtons() - { - bool running = Session.IsRunning; - bool onSiteLists = _currentStep == BlockCheck2WizardStep.SiteLists; - bool onMode = _currentStep == BlockCheck2WizardStep.Mode; - bool onAdvanced = _currentStep == BlockCheck2WizardStep.Advanced; - bool onReview = _currentStep == BlockCheck2WizardStep.Review; - bool onProgress = _currentStep == BlockCheck2WizardStep.Progress; - bool onComplete = _currentStep == BlockCheck2WizardStep.WorkComplete; - - _view.ShowNavigationButtons(new BlockCheck2NavigationButtons( - Exit: onComplete, - Back: !running, - Cancel: running, - ViewResult: !running && onComplete && Session.LastReport != null, - Next: !running && !onProgress && !onComplete)); - - SetCancelEnabled(Session.CanCancel); - IsNextEnabled = onSiteLists - ? Session.HasTargetSources - : onAdvanced - ? Session.AdvancedOptionsValid && Session.CanContinueFromTargets - : onMode || (onReview && Session.CanStart); - NextButtonText = onReview - ? Text("BlockCheck2StartButton") - : Text("BlockCheck2NextButton"); - } + private void UpdateNavigationButtons() => + _navigation.UpdateNavigationButtons(); private string Text(string key) => _localizer.GetLocalizedString(key); } diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2NavigationSource.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2NavigationSource.cs new file mode 100644 index 00000000..0e08751e --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2NavigationSource.cs @@ -0,0 +1,17 @@ +namespace CDPIUI.ViewModels.BlockCheck2; + +// A live navigation view of the same Session; construction reads no values. +internal sealed class BlockCheck2NavigationSource : IBlockCheck2NavigationSource +{ + private readonly BlockCheck2ViewModel _session; + + public BlockCheck2NavigationSource(BlockCheck2ViewModel session) => _session = session; + + public bool IsRunning => _session.IsRunning; + public bool CanCancel => _session.CanCancel; + public bool HasTargetSources => _session.HasTargetSources; + public bool AdvancedOptionsValid => _session.AdvancedOptionsValid; + public bool CanContinueFromTargets => _session.CanContinueFromTargets; + public bool CanStart => _session.CanStart; + public bool HasReport => _session.LastReport != null; +} diff --git a/CDPIUI/ViewModels/BlockCheck2/BlockCheck2WizardNavigation.cs b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2WizardNavigation.cs new file mode 100644 index 00000000..90f8f9b2 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/BlockCheck2WizardNavigation.cs @@ -0,0 +1,80 @@ +#nullable enable + +using System; + +namespace CDPIUI.ViewModels.BlockCheck2; + +internal sealed class BlockCheck2WizardNavigation : ObservableObject +{ + private readonly IBlockCheck2NavigationSource _source; + private readonly IBlockCheck2MainPageView _view; + private readonly Func _text; + private readonly Action _notifyCancelChanged; + private BlockCheck2WizardStep _currentStep = BlockCheck2WizardStep.SiteLists; + private bool _isNextEnabled = true; + private string? _nextButtonText; + private bool _isCancelEnabled = true; + + public BlockCheck2WizardNavigation(IBlockCheck2NavigationSource source, + IBlockCheck2MainPageView view, Func text, Action notifyCancelChanged) + { + _source = source; + _view = view; + _text = text; + _notifyCancelChanged = notifyCancelChanged; + } + + public BlockCheck2WizardStep CurrentStep => _currentStep; + public bool IsCancelEnabled => _isCancelEnabled; + public bool IsNextEnabled + { + get => _isNextEnabled; + set => SetProperty(ref _isNextEnabled, value); + } + + public string? NextButtonText + { + get => _nextButtonText; + set => SetProperty(ref _nextButtonText, value); + } + + public void GoToStep(BlockCheck2WizardStep step) + { + _currentStep = step; + _view.GoToStep(step); + } + + public void SetCancelEnabled(bool value) + { + _isCancelEnabled = value; + _notifyCancelChanged(); + } + + public void UpdateNavigationButtons() + { + bool running = _source.IsRunning; + bool onSiteLists = _currentStep == BlockCheck2WizardStep.SiteLists; + bool onMode = _currentStep == BlockCheck2WizardStep.Mode; + bool onAdvanced = _currentStep == BlockCheck2WizardStep.Advanced; + bool onReview = _currentStep == BlockCheck2WizardStep.Review; + bool onProgress = _currentStep == BlockCheck2WizardStep.Progress; + bool onComplete = _currentStep == BlockCheck2WizardStep.WorkComplete; + + _view.ShowNavigationButtons(new BlockCheck2NavigationButtons( + Exit: onComplete, + Back: !running, + Cancel: running, + ViewResult: !running && onComplete && _source.HasReport, + Next: !running && !onProgress && !onComplete)); + + SetCancelEnabled(_source.CanCancel); + IsNextEnabled = onSiteLists + ? _source.HasTargetSources + : onAdvanced + ? _source.AdvancedOptionsValid && _source.CanContinueFromTargets + : onMode || (onReview && _source.CanStart); + NextButtonText = onReview + ? _text("BlockCheck2StartButton") + : _text("BlockCheck2NextButton"); + } +} diff --git a/CDPIUI/ViewModels/BlockCheck2/IBlockCheck2NavigationSource.cs b/CDPIUI/ViewModels/BlockCheck2/IBlockCheck2NavigationSource.cs new file mode 100644 index 00000000..795347a2 --- /dev/null +++ b/CDPIUI/ViewModels/BlockCheck2/IBlockCheck2NavigationSource.cs @@ -0,0 +1,12 @@ +namespace CDPIUI.ViewModels.BlockCheck2; + +internal interface IBlockCheck2NavigationSource +{ + bool IsRunning { get; } + bool CanCancel { get; } + bool HasTargetSources { get; } + bool AdvancedOptionsValid { get; } + bool CanContinueFromTargets { get; } + bool CanStart { get; } + bool HasReport { get; } +} diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index f3791828..0ef9aec5 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1518,8 +1518,8 @@ }, { "path": "docs/superpowers/specs/2026-11-11-blockcheck-wizard-navigation-design.md", - "firstIntroduction": "Local MainPage wizard navigation contract under issue223; baseline b627a0f62dace8dde20ca2574a9d28646f71b421.", - "first_commit": null, + "firstIntroduction": "f7338ef123b490fb1f7919a633b4dad421433730\tleather147\tRecord MainPage wizard navigation design", + "first_commit": "f7338ef123b490fb1f7919a633b4dad421433730", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", @@ -1528,13 +1528,23 @@ }, { "path": "docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md", - "firstIntroduction": "Local MainPage wizard navigation contract under issue223; baseline b627a0f62dace8dde20ca2574a9d28646f71b421.", - "first_commit": null, + "firstIntroduction": "f7338ef123b490fb1f7919a633b4dad421433730\tleather147\tRecord MainPage wizard navigation design", + "first_commit": "f7338ef123b490fb1f7919a633b4dad421433730", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", "language": "en", "changes": "Define current step and button ownership, direct live navigation source, unconditional command notifications and bounded local qualification." + }, + { + "path": "docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md", + "firstIntroduction": "Local wizard navigation evidence under issue223.", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Record managed mutation evidence, exact policy and public contract guards, bounded native qualification and local delivery limits." } ], "current_history_base": "7ead95f7756057f67cd113671a7f84cf422e8d32", diff --git a/docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md b/docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md new file mode 100644 index 00000000..8633677f --- /dev/null +++ b/docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md @@ -0,0 +1,75 @@ +# MainPage wizard navigation verification + +## Scope and source checkpoint + +[Issue #223](https://github.com/lumenpearson/cdpiui/issues/223) accepts this LOCAL navigation +extraction from frozen baseline `b627a0f62dace8dde20ca2574a9d28646f71b421`, draft PR #222. +The branch is `dev/blockcheck-wizard-navigation` in the existing isolated Root worktree. +Actual Project intake under grant 127 was verified before implementation: In progress, P2, +Architecture, Medium, G2, lumenpearson and two canonical labels after reload. The +[intake receipt](https://github.com/lumenpearson/cdpiui/issues/223#issuecomment-6797095818) +records those values. Queue 128 was released with all six participants paused. + +An internal owner now holds the current step, Next enabled state, Next text and Cancel availability. +It reads seven current boolean properties through a direct Session adapter. The existing view, +localizer and command notification remain synchronous dependencies. The public Next properties, +private setters and three private host entrypoints remain forwards. The same CancelCommand reads +the owner's current value; its notification is unconditional, including repeated equal assignments. +One constructor-owned synchronous property bridge preserves the host sender. + +Only the main existing MainPage source changes, with three new internal source files and focused +tests. Other MainPage partials, Session, options, resources, packages and Core/AddOns/Shared remain +unchanged. The constructor stores all dependencies without reading or calling them. Its placement +before command creation preserves all prior constructor statements and the initial true predicate. + +## Managed verification and mutation control + +The fresh design check reported "nothing important left" before implementation. The first cold +constructor test observed CS0246 for the missing owner. All behavioral tests were then written +before implementation. The pure owner passed 75/75 in 28 ms before host wiring. + +The focused tests include 28 literal visibility rows, equal and unknown steps, nested view calls, +unconditional Cancel notifications, current source reads after callbacks, lazy branches, earlier +step flags, text and property reentry, exception identity, partial effects, retry and instance isolation. +Advanced retains validity then CanContinueFromTargets without a HasTargetSources guard. Next +enabled state remains independent of the separate button visibility during running. + +A controlled mutant read CanCancel before the view callback. Five tests failed and 70 passed. +Exact original bytes were restored in finally and verified with SHA256 +`0ADBA2B7EF6FDA312B7323B48064A49E0BF3A64CFDDF61D7BAF5B16A92BECCC2`. +The restored focused run passed 75/75 in 25 ms. With host wiring present, the full suite passed +2505/2505 in 9 s, zero failures or skips. The normal WinUI build passed with zero warnings and +errors in 40.39 s. + +```text +C:/Users/lumen/.dotnet/dotnet.exe test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release --no-restore --filter FullyQualifiedName~BlockCheck2WizardNavigationTests +C:/Users/lumen/.dotnet/dotnet.exe test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release --no-restore +C:/Users/lumen/.dotnet/dotnet.exe build CDPIUI/CDPIUI.csproj -c Release -p:Platform=x64 --no-restore +``` + +## Compatibility and source guards + +The source inventory compares 617 baseline GUI files with 620 current files. All 451 original +exported signatures remain. Compiled comparisons preserve 452 GUI and 88 Core exported type +shapes, with zero removals or changes and zero additions on retained types. These bounded checks +do not certify every attribute, annotation, native ABI or runtime behavior. + +The policy guard compares all three moved method bodies with the original tokens under declared +source, view and command substitutions. It reconstructs the complete original host under only the +allowed changes. It verifies seven direct typed mappings, four cold values, two observable setters, +plain step and Cancel values, three forwards, step reads, the same command, one bridge, cold +construction, all prior constructor statements and five additive test links. The guard passed. + +## Native and delivery boundaries + +Fresh native qualification, independent whole-branch review, exact final-head hosted checks, +actual PR Project readback and immediate local acceptance remain pending at this checkpoint. +The next fixture must preserve all accepted 166 labels, 33 old case partials and 21 cut paths. +It must obtain independent pre-build and prelaunch review and a new explicit exclusive UI lease. +No OnLoaded, command Execute, real scan, settings write, backend, history or cleanup is required. + +Refs #14 and Refs #223. Parent #13/#14/#15 and draft PRs #216/#218/#220/#222 remain separate and +unmerged. Model composition does not establish full Page rendering, XAML Loading, focus, +activation, installed-product, GC collection, G1 or release acceptance. Retain all source archives, +refs, workspaces and accepted or rejected evidence. Raw evidence belongs to the ignored workspace +`.superpowers/sdd/2026-11-11-blockcheck-wizard-navigation/`. From 18aafc26e5fb8f532e8011ca38089f66f9e30065 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:15:02 +0300 Subject: [PATCH 20/31] Record MainPage navigation native qualification The first native attempt exposed an invalid fixture input while the product correctly rejected those options. Its complete source, binary and failure records remain available. A fresh copy uses valid startup grace and asserts its input preconditions before the matrix. Independent reviews verified the corrected source, real option limits and all new artifact boundaries. The corrected process passed all 172 groups under a new exclusive lease. Exact source, resources, prior output hashes, retained inputs and reports, process exit and queue release checks passed. This record preserves the failed attempt and distinguishes bounded host composition from visual, installed product and release acceptance. Product and managed test bytes remain unchanged. Changed files: - "docs/governance/document-inventory.json" (+2/-2 lines). - "docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md" (+9/-9 lines). - "docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md" (+93/-6 lines). The file counts compare the staged tree with its first parent. Refs: #223 Staged-Tree: 6c8628eb3798655d5ca77fbafee9662def643c51 --- docs/governance/document-inventory.json | 4 +- ...2026-11-11-blockcheck-wizard-navigation.md | 18 ++-- ...ockcheck-wizard-navigation-verification.md | 99 +++++++++++++++++-- 3 files changed, 104 insertions(+), 17 deletions(-) diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index 0ef9aec5..c16f4a18 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1538,8 +1538,8 @@ }, { "path": "docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md", - "firstIntroduction": "Local wizard navigation evidence under issue223.", - "first_commit": null, + "firstIntroduction": "31ab5c2f16dbbf11c5c1fab4f5a0e90214be7f05\tleather147\tExtract MainPage wizard navigation state", + "first_commit": "31ab5c2f16dbbf11c5c1fab4f5a0e90214be7f05", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", diff --git a/docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md b/docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md index 29bdbace..2cdb26ff 100644 --- a/docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md +++ b/docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md @@ -48,14 +48,14 @@ existing view/enum/record; design/plan/report and additive inventory. command notification. Produces current step/Cancel getters, two observable Next properties and the three existing private host entrypoints through direct forwards. -- [ ] Read issue/spec/intake and retain source/compiled/normal baselines. Obtain a fresh builder verdict +- [x] Read issue/spec/intake and retain source/compiled/normal baselines. Obtain a fresh builder verdict before product code. Verify no old native case depends on moved private fields. -- [ ] Write focused cold/state/ordering tests first and observe expected missing-component RED. -- [ ] Implement the exact source and owner policy, host forwards/current-step reads and one bridge; +- [x] Write focused cold/state/ordering tests first and observe expected missing-component RED. +- [x] Implement the exact source and owner policy, host forwards/current-step reads and one bridge; preserve prior constructor statement order. Run focused GREEN and inspect real assertions. -- [ ] Apply a controlled CanCancel cache before the view callback; observe behavior failures, restore +- [x] Apply a controlled CanCancel cache before the view callback; observe behavior failures, restore exact bytes/hash and pass focused/full GREEN plus normal GUI with zero warnings/errors. -- [ ] Verify source/compiled public preservation, exact footprint, original policy/read points/seven +- [x] Verify source/compiled public preservation, exact footprint, original policy/read points/seven mappings/host fields/constructor/command wiring, governance and redacted scans; commit checkpoint. ### Task 2: Qualify actual host/command composition and accept locally @@ -66,14 +66,14 @@ dedicated report and additive inventory. **Interfaces:** consumes Task 1 source pin and accepted 166 corpus/case bytes/cut paths. Produces actual host/source/view/command evidence and local delivery without accepting parent integration. -- [ ] Read Task 1 evidence/brief; preserve all 166 labels and old case bytes/cuts, derive fresh input, +- [x] Read Task 1 evidence/brief; preserve all 166 labels and old case bytes/cuts, derive fresh input, corpus/pin/extra counts and discriminating command/current-step callback cases before build. -- [ ] Obtain independent pre-build review, build zero warnings/errors, derive actual artifacts/resources/ +- [x] Obtain independent pre-build review, build zero warnings/errors, derive actual artifacts/resources/ source/runner/verifier pins and full output baseline, then independent prelaunch READY. -- [ ] Acquire a new explicit exclusive lease; run one process and prove labels/COMPLETE/exit/streams, +- [x] Acquire a new explicit exclusive lease; run one process and prove labels/COMPLETE/exit/streams, source/resources/hashes/IO/absence/process cleanup, idle/requestfalse and guarded release. - [ ] Update evidence and obtain fresh whole-branch review; resolve Critical/Important through observed - RED→GREEN, ledger all rulings/deferred minors and retain original artifacts. + REDв†’GREEN, ledger all rulings/deferred minors and retain original artifacts. - [ ] Publish a draft stacked on dev/blockcheck-review-presentation with Refs #14 and Refs #223; verify exact final-head checks and actual PR metadata/Project fields, without parent/main merge. - [ ] Verify all six criteria, post six-section LOCAL acceptance, immediately close completed/set actual diff --git a/docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md b/docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md index 8633677f..04c55f2f 100644 --- a/docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md +++ b/docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md @@ -15,7 +15,8 @@ It reads seven current boolean properties through a direct Session adapter. The localizer and command notification remain synchronous dependencies. The public Next properties, private setters and three private host entrypoints remain forwards. The same CancelCommand reads the owner's current value; its notification is unconditional, including repeated equal assignments. -One constructor-owned synchronous property bridge preserves the host sender. +One constructor-owned synchronous property bridge preserves the host sender. The main file decreases +from 426 to 395 lines; the four-part MainPage total decreases from 677 to 646. Only the main existing MainPage source changes, with three new internal source files and focused tests. Other MainPage partials, Session, options, resources, packages and Core/AddOns/Shared remain @@ -60,13 +61,99 @@ allowed changes. It verifies seven direct typed mappings, four cold values, two plain step and Cancel values, three forwards, step reads, the same command, one bridge, cold construction, all prior constructor statements and five additive test links. The guard passed. +The product checkpoint is `31ab5c2f16dbbf11c5c1fab4f5a0e90214be7f05`. The normal GUI SHA256 is +`F1DC9407FF2B5D60F37B682BE9456A04970498F68E0F362F6AE79B8DC8E6644A`. Earlier native evidence +keeps its historical normal-output hash; do not rerun an old verifier against the changed output. + ## Native and delivery boundaries -Fresh native qualification, independent whole-branch review, exact final-head hosted checks, -actual PR Project readback and immediate local acceptance remain pending at this checkpoint. -The next fixture must preserve all accepted 166 labels, 33 old case partials and 21 cut paths. -It must obtain independent pre-build and prelaunch review and a new explicit exclusive UI lease. -No OnLoaded, command Execute, real scan, settings write, backend, history or cleanup is required. +The fresh source fixture is `F:/cdpiui-verify/cdpiui-blockcheck-navigation-31ab5c2-20261111`, +archived from the product pin. Independent pre-build reconstruction verified 1598 Git inputs, +21 inherited cut paths, 35 bootstrap files and 39 allowed extras, with no reparse entries. All 33 +prior case partials are equal in raw bytes. Twenty whole cut files are equal; DirectoriesManager +is equal after the exact fixture EXE literal substitution. The accepted 166-label prefix remains, +and six unique navigation groups produce the expected 172-label corpus. + +The initial pre-build review found a missing Reporting import in the new scenario. This was a +source-inspected expected compile blocker; no compiler failure was executed. The sole correction +adds that import in the recipe and fixture. Original bytes/hash were preserved. The reviewer +independently verified the exact one-import delta and final case bytes, then returned READY with +zero active Critical, Important or Minor findings. Product, assertions, labels and cuts are unchanged. + +The native build passed with zero warnings/errors in 71.55 s. There are 69 approved inputs: +5 owned binaries, 20 generated resources and 44 source/evidence files. All 522 prior output +filenames and hashes form the launch baseline. The 20 packaged resources equal generated bytes; +5206 entries equal the source JSON and all 40 relevant English keys are nonempty. Native GUI DLL +SHA256: `257F9BBF72E47DE7D356CAA5E37AEDF876B635B8CCFF883AF7478A8837271F1E`. +The runner SHA256 is `A1399B0404C63E7064E01BE59FD364575A9BE1C9AA3FFBC7A0CE9CBEA2457F0B`; +the runtime verifier SHA256 is `C653F737B68D91432E8120CCC4E0404F7A8657463BA16150001C22318C702D32`. + +### Retained failed native attempt + +The first reviewed fixture ran once under explicit grant 129. PID 62736 ran from +2026-11-11T14:04:44.6202465Z to 2026-11-11T14:04:47.2235145+00:00. It passed the prior 166 groups +and the first new group, then failed Completed/Advanced: 167 PASS, one FAIL, no COMPLETE, exit1. +The case had seeded startup grace 0 while expecting valid options. The unchanged product requires +at least 0.25 and correctly returned false. This is a scenario input defect, not accepted runtime +qualification. Independent static reviews had missed that invalid numeric precondition. + +All failed fixture/source/archive/case/binary/pin/log bytes remain retained. The failure-specific +readback verified all 69 pins, all 522 prior output hashes, full 1598-input source/cut checks, +exact six new output names, three literal inputs, two golden reports, all seven forbidden paths, +custom-marker absence, normal GUI hash, and owned PID/exact EXE absence. Idle 129 recorded failure, +requestfalse was set, and guarded release 130 retained previousVersion 129 with all six paused. +The initial generic completion verifier was not used to manufacture a successful result. + +A fresh `-r2` fixture and `native-r2/` evidence directory retain the same product pin, corpus, +old case bytes and cuts. Only the new case seed changes from 0 to 0.75; an explicit assertion checks +valid options, no targets and the intended CanContinue/CanStart inputs before matrix execution. +Rebuild, independent checks and a new lease apply to that new copy. No rejected fixture is rerun. + +### Corrected native build + +The R2 build passed with zero warnings/errors in 56.44 s. Fresh R2 pinning again produced +69 inputs, a 522-file baseline and 20 resources with 5206 entries and 40 relevant English keys. +The corrected case SHA256 is `95625539D509B9D2FC603B2A66FA995A55B7F699567D45157309AE5C87B2B70C`. +R2 native GUI SHA256: `A3AE4EDD88451F7C87DF923AA0222F18896BAF8E755A55B6FE04C5CE9D2FB523`. +R2 runner SHA256: `B5BAA80B03C8F3AE1DA2E27B8D59F83A52F8248E1CE169F682F32D738577F35E`. +R2 verifier SHA256: `5182AE4EF0276B8343F7C4F526A1245CEF3F62A734760AE0BD2831509F422189`. +Independent R2 pre-build review checked all numeric limits and all matrix expectations against +the actual options and Session predicates. It returned READY with no active findings. + +### Accepted R2 runtime evidence + +Independent R2 prelaunch review returned READY with zero Critical, Important or Minor findings. +It rehashed all 69 pins and 522 prior outputs, reconstructed source/corpus evidence and parsed +the actual PE resource tree: AMD64 PE32+, one embedded asInvoker/uiAccess=false manifest. +The current token was non-admin; the exact process and fresh outputs were absent. PowerShell +parsing had zero errors. This static review did not replace the subsequent runtime assertions. + +After Root's own immediate hash/readiness checks, explicit grant 131 permitted one R2 process. +PID 89288 ran from 2026-11-11T14:14:02.1120838Z to 2026-11-11T14:14:04.6887812+00:00. All 172 unique groups passed, +with the exact 166/160/154/149/137 prefixes and peer 141 projection, one COMPLETE, zero FAIL, +exit0 and empty streams. All 69 pins, 522 prior filenames/hashes, full source boundaries and +resources passed afterward. Exactly six new names made 528 total files. The three input files +retain their literal 16/16/15 bytes. Both serializer reports retain exact 354/260-byte golden +contents and current model fields. All seven forbidden paths and custom markers remain absent. +The normal GUI DLL retains the recorded F1DC9407 hash. + +The six groups assert cold fields and both private setters, host sender/equality, command identity +and unconditional equal-value notifications, all step/running/Canceling visibility and availability, +invalid advanced options and missing connection/target/report branches, view mutation before +current CanCancel, command mutation before later source reads, retained earlier step flags, +nested command frames, separate owners, equal/unknown/nested steps, view exception identity, +command-observer partial state and retry. Actual MainPage, Session, source, owner, command, +localizer and dispatcher are exercised. New view endpoints are controlled callbacks; settings +constructor reads use the existing inert port. No OnLoaded, Execute, settings write, scan, +backend, history, cleanup, additional operating IO or source cut is introduced. + +Root independently checked PID 89288 and exact EXE absence, wrote idle 131/requestfalse with +no pending call, and read back guarded release 132 with previousVersion 131, owner null and +all six participants paused. R2 evidence is in this plan's `native-r2/` subdirectory. The initial +failed fixture and all original review/build/runtime records remain retained separately. + +Fresh whole-branch review, exact final-head hosted checks, actual PR Project readback and +immediate LOCAL acceptance remain pending at this evidence checkpoint. Refs #14 and Refs #223. Parent #13/#14/#15 and draft PRs #216/#218/#220/#222 remain separate and unmerged. Model composition does not establish full Page rendering, XAML Loading, focus, From 12ef689e0968bd7ff4b27cee0fe7af02091286da Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:23:43 +0300 Subject: [PATCH 21/31] Record navigation review and correct evidence wording The independent whole branch review found no product defect or blocking verification gap. Two minor findings concerned damaged plan text and the wording of a source contract count. The plan now uses plain text for the verification sequence. The report correctly counts exported types whose signatures were compared and preserves the failed native attempt alongside the corrected result. This change records the reviewed range, evidence boundaries and remaining delivery gates. Product source, managed tests and both native fixtures remain unchanged. Static documentation checks apply to this commit while the recorded full suite and native results retain their exact product identities. Final hosted checks and actual Project readback remain required before local acceptance. Changed files: - "docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md" (+2/-2 lines). - "docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md" (+26/-4 lines). The file counts compare the staged tree with its first parent. Refs: #223 Staged-Tree: e1bcdd4c975ffbae10d5e32188ee50cea169a0e8 --- ...2026-11-11-blockcheck-wizard-navigation.md | 4 +-- ...ockcheck-wizard-navigation-verification.md | 30 ++++++++++++++++--- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md b/docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md index 2cdb26ff..a7e1547d 100644 --- a/docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md +++ b/docs/superpowers/plans/2026-11-11-blockcheck-wizard-navigation.md @@ -72,8 +72,8 @@ actual host/source/view/command evidence and local delivery without accepting pa source/runner/verifier pins and full output baseline, then independent prelaunch READY. - [x] Acquire a new explicit exclusive lease; run one process and prove labels/COMPLETE/exit/streams, source/resources/hashes/IO/absence/process cleanup, idle/requestfalse and guarded release. -- [ ] Update evidence and obtain fresh whole-branch review; resolve Critical/Important through observed - REDв†’GREEN, ledger all rulings/deferred minors and retain original artifacts. +- [x] Update evidence and obtain fresh whole-branch review; resolve Critical/Important through observed + RED to GREEN, ledger all rulings/deferred minors and retain original artifacts. - [ ] Publish a draft stacked on dev/blockcheck-review-presentation with Refs #14 and Refs #223; verify exact final-head checks and actual PR metadata/Project fields, without parent/main merge. - [ ] Verify all six criteria, post six-section LOCAL acceptance, immediately close completed/set actual diff --git a/docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md b/docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md index 04c55f2f..ead4b04c 100644 --- a/docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md +++ b/docs/superpowers/reports/2026-11-11-blockcheck-wizard-navigation-verification.md @@ -50,8 +50,8 @@ C:/Users/lumen/.dotnet/dotnet.exe build CDPIUI/CDPIUI.csproj -c Release -p:Platf ## Compatibility and source guards -The source inventory compares 617 baseline GUI files with 620 current files. All 451 original -exported signatures remain. Compiled comparisons preserve 452 GUI and 88 Core exported type +The source inventory compares 617 baseline GUI files with 620 current files. The source comparison +covered 451 baseline exported types. It found no removed or changed signatures on those types. Compiled comparisons preserve 452 GUI and 88 Core exported type shapes, with zero removals or changes and zero additions on retained types. These bounded checks do not certify every attribute, annotation, native ABI or runtime behavior. @@ -152,8 +152,30 @@ no pending call, and read back guarded release 132 with previousVersion 131, own all six participants paused. R2 evidence is in this plan's `native-r2/` subdirectory. The initial failed fixture and all original review/build/runtime records remain retained separately. -Fresh whole-branch review, exact final-head hosted checks, actual PR Project readback and -immediate LOCAL acceptance remain pending at this evidence checkpoint. +## Independent whole-branch review + +Fresh reviewer wizard_navigation_final_review inspected the complete range +`b627a0f62dace8dde20ca2574a9d28646f71b421` through +`18aafc26e5fb8f532e8011ca38089f66f9e30065`: zero Critical, zero Important and two Minor findings. +It reconstructed the original complete host under the declared substitutions, compared all three +policy bodies and seven direct mappings, and verified that product and tests are unchanged after +the product pin. Read-only checks independently reconstructed both native attempts, all 69 pins, +522 prior outputs, exact six new names, resources, inputs, golden reports, corpus and queue records. +Owner logs remain the executed test/build/process evidence; the reviewer did not repeat those runs. + +The two Minor findings concern documentation. The plan now uses plain ASCII `RED to GREEN` +instead of a committed damaged character sequence. The source API count now names 451 exported +types whose signatures were compared. No product, test, native case, pin or output changed for +these corrections. Static documentation checks apply; no product rerun is attributed to this commit. + +The executor retains original hidden-button/Next and Advanced-without-target behavior, repeated +command notifications, unknown steps, earlier outer-frame flags and partial exception effects. +Changing those policies, adding constructor guards or thread synchronization would exceed this +preserving refactor. The reference graph introduces no new external root; actual GC collection +remains unmeasured. Full Page/XAML/focus/activation and unchanged operating routes remain separate. + +Exact final-head hosted checks, actual PR Project readback and immediate LOCAL acceptance remain +pending at this evidence checkpoint. The issue's later acceptance record is authoritative for delivery. Refs #14 and Refs #223. Parent #13/#14/#15 and draft PRs #216/#218/#220/#222 remain separate and unmerged. Model composition does not establish full Page rendering, XAML Loading, focus, From a1a79fba42b7db3622ec43da315744465b67496c Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:51:05 +0300 Subject: [PATCH 22/31] Record Store download presentation ownership design The design assigns eleven observable download values and the plain `ErrorHappens` latch to an internal `ItemDownloadPresentation` owner. The host retains public property access, private method forwards, and a synchronous property-change bridge. The documented behavior preserves unconditional `StatusTip` notifications and equality checks for the other observable properties. The specification defines ordered publications, callback-visible partial state, nested error behavior, and late latch assignment. The operating boundary leaves queue delivery, Store actions, database access, installation, deletion, and existing late reads outside the extraction. The document also preserves localization timing, culture-sensitive formatting, raw nullable values, and exception effects. The implementation plan separates focused state extraction from native host qualification. The listed checks remain pending and include tests, source comparisons, build evidence, fixture pinning, lease control, and final review. The governance inventory records both documents with their baseline, author, language policy, and local introduction status. Changed files: - "docs/governance/document-inventory.json" (+20/-0 lines). - "docs/superpowers/plans/2026-11-11-store-download-presentation.md" (+79/-0 lines). - "docs/superpowers/specs/2026-11-11-store-download-presentation-design.md" (+135/-0 lines). The file counts compare the staged tree with its first parent. Refs: #225 Staged-Tree: 48a2ce8bb212518dbdcd9310574ab2b413affb15 --- docs/governance/document-inventory.json | 20 +++ .../2026-11-11-store-download-presentation.md | 79 ++++++++++ ...1-11-store-download-presentation-design.md | 135 ++++++++++++++++++ 3 files changed, 234 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-11-store-download-presentation.md create mode 100644 docs/superpowers/specs/2026-11-11-store-download-presentation-design.md diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index c16f4a18..c1e87978 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1545,6 +1545,26 @@ "policy": "ASD-STE100 principles for English", "language": "en", "changes": "Record managed mutation evidence, exact policy and public contract guards, bounded native qualification and local delivery limits." + }, + { + "path": "docs/superpowers/specs/2026-11-11-store-download-presentation-design.md", + "firstIntroduction": "Local Store download presentation contract under issue225; baseline12ef689e0968bd7ff4b27cee0fe7af02091286da.", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Define download display state ownership, unconditional tip events, late error latch and bounded local qualification." + }, + { + "path": "docs/superpowers/plans/2026-11-11-store-download-presentation.md", + "firstIntroduction": "Local Store download presentation contract under issue225; baseline12ef689e0968bd7ff4b27cee0fe7af02091286da.", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Define download display state ownership, unconditional tip events, late error latch and bounded local qualification." } ], "current_history_base": "7ead95f7756057f67cd113671a7f84cf422e8d32", diff --git a/docs/superpowers/plans/2026-11-11-store-download-presentation.md b/docs/superpowers/plans/2026-11-11-store-download-presentation.md new file mode 100644 index 00000000..98fc9ef8 --- /dev/null +++ b/docs/superpowers/plans/2026-11-11-store-download-presentation.md @@ -0,0 +1,79 @@ +# Store Item Download Presentation Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan inline, task-by-task, with a fresh final independent reviewer. + +**Goal:** Give the eleven download values, plain error latch and seven display methods one focused owner. + +**Architecture:** Internal ItemDownloadPresentation stores Text without invocation and preserves +original field/event/localization order. The host keeps public/private forwards and one synchronous +sender bridge. Queue and operating workflows retain their original current reads. + +**Tech Stack:** C#/.NET 8.0.427, xUnit linked source, WinUI3, exact source/public inventories, +immutable native corpus and explicit exclusive UI queue. + +**Spec:** [download presentation design](../specs/2026-11-11-store-download-presentation-design.md). + +## Global constraints + +- Issue #225 actual Project intake 137/release 138 is verified before implementation. +- Use dev/store-download-presentation from frozen PR #224/12ef689; retain all prior refs/workspaces. +- Preserve eleven defaults/setters, plain error latch, seven private forwards and one host bridge. +- StatusTip always notifies even equal/null. Other properties use SetProperty equality. +- Error latch is checked once at guarded entry and written LAST after four error publications. +- Keep all stage/text/threshold/culture/partial exception/reentry behavior; no snapshots or new guards. +- Existing product changes are restricted to main ItemViewPageViewModel. Keep Queue.cs byte-identical, + including speed formatting before the guard, operation identity, subscriptions and dispatcher. +- Keep two late CheckCurrentStatus reads, completion current-ID/error reads and all operating routes. +- No Load, Execute, queue delivery, StoreHelper, DB, install/delete, new operating cuts/IO or deletion. +- Every native launch and UI API needs a fresh explicit lease, independent READY and full postchecks. + +## Review Focus + +- StatusTip's unconditional assignment/notification differs from the other ten observable setters. +- ShowDownloadState and OnInstallingError have ordered publications with callback-visible partial state. +- A nested error may change the latch after a guarded entry; the outer call does not recheck it. + Later outer error notifications see that current nested latch, including before a later outer failure. +- ApplyStage keeps its earlier header across callbacks and preserves branch-specific values it does not write. +- Time formatting observes culture after localization and preserves the earlier TimeSpan argument. +- New owner construction stays cold; prior host initialization and commands retain relative order. +- Bounded constructor/private-model evidence is distinct from Page loading, image visuals and queue delivery. + +### Task 1: Extract the focused state and literal policy + +**Files:** create CDPIUI/ViewModels/Store/ItemDownloadPresentation.cs; modify only the existing +main ItemViewPageViewModel.cs in product; add Presentation/ItemDownloadPresentationTests.cs and +one linked-source entry; focused design/plan/report and additive document inventory. + +**Interfaces:** consumes a stored Text function and original method arguments. Produces eleven +current observable values, plain ErrorHappens and seven methods through host property/private forwards. + +- [ ] Read issue/spec/intake, preserve normal/source/compiled baselines, and obtain a fresh builder + verdict before product code. Inspect accepted 172 cases for moved-field dependencies. +- [ ] Write cold/ordering/gate/stage/culture/reentry/failure tests first and observe expected missing-owner RED. +- [ ] Implement owner, eleven host forwards, seven method forwards, two remaining latch accesses and + one cold constructor bridge; preserve prior statements. Run focused GREEN and inspect assertions. +- [ ] Apply a controlled early error latch before error publications, observe behavioral failures, + restore exact source/hash in finally, then focused/full GREEN and normal GUI with zero warnings/errors. +- [ ] Verify source/compiled public preservation, exact existing footprint, whole-host/policy/property/ + constructor/bridge/latch/Queue guards, line bounds, governance and redacted scans; commit checkpoint. + +### Task 2: Qualify actual host composition and accept locally + +**Files:** fresh immutable F:/cdpiui-verify fixture, ignored source/build/pin/run/postcheck evidence, +dedicated report and additive inventory. + +**Interfaces:** consumes Task 1 product pin and accepted 172 corpus, 34 old case partials and 21 cut +paths. Produces bounded real Store host/private setter/forward evidence and local draft acceptance. + +- [ ] Read Task 1 evidence/brief; preserve all accepted labels/case bytes/cuts and derive fresh counts. + Add discriminating actual host/setter/guard/latch/reentry/failure cases before build. +- [ ] Obtain independent pre-build review; build zero warnings/errors, pin all actual artifacts/resources/ + sources/runner/verifier and baseline filenames/hashes, then independent prelaunch READY. +- [ ] Obtain a NEW explicit exclusive lease, run one exact owned process, and verify corpus/COMPLETE/ + exit/streams/source/resources/hash/IO/absence/process cleanup; idle/requestfalse and guarded release. +- [ ] Update evidence and obtain fresh whole-branch review. Resolve Critical/Important through observed + RED to GREEN, retain failures, and ledger all rulings/deferred Minor findings and their costs. +- [ ] Publish a draft stacked on dev/blockcheck-wizard-navigation with Refs #14 and Refs #225; verify + exact final-head checks and actual PR metadata/Project fields, without parent/main merge. +- [ ] Verify six criteria, post six-section LOCAL acceptance, immediately close completed/set actual + Project Done and read back criteria, closure reason, labels, owner, milestone and fields. diff --git a/docs/superpowers/specs/2026-11-11-store-download-presentation-design.md b/docs/superpowers/specs/2026-11-11-store-download-presentation-design.md new file mode 100644 index 00000000..a922cf13 --- /dev/null +++ b/docs/superpowers/specs/2026-11-11-store-download-presentation-design.md @@ -0,0 +1,135 @@ +# Store item download presentation ownership + +## Intent and delivery boundary + +[Issue #225](https://github.com/lumenpearson/cdpiui/issues/225) owns this LOCAL continuation of +the audit decomposition. Frozen baseline: draft PR #224 at +`12ef689e0968bd7ff4b27cee0fe7af02091286da`. Its local stage #223 is completed with six verified +criteria, actual Project Done under grant 135 and +[final readback](https://github.com/lumenpearson/cdpiui/issues/223#issuecomment-6798650935). +The main ItemViewPageViewModel source has 562 lines; Queue.cs has 122, total 684. + +Root owns `dev/store-download-presentation` in the existing isolated worktree. Actual issue +Project intake 137 persisted In progress/P2/Architecture/Medium/G2/lumenpearson and two canonical +labels after reload. Its [receipt](https://github.com/lumenpearson/cdpiui/issues/225#issuecomment-6798817588) +and guarded release 138 precede implementation. The parallel utility owner confirmed no overlap. +No parent/main merge, operating Store action, installation or deletion belongs to this stage. + +## Chosen owner + +Create one internal `ItemDownloadPresentation : ObservableObject` in the Store view-model folder. +It owns eleven existing display values and the plain error latch. One stored `Func` +performs localization lazily. Its constructor only stores that function; it invokes no callback. +No source interface or general framework is needed because policy reads only its own current state. + +| Property | Cold value | Notification rule | +| --- | --- | --- | +| IsActionVisible | true | SetProperty equality | +| IsDownloadStatusVisible | false | SetProperty equality | +| IsErrorStatusVisible | false | SetProperty equality | +| IsStopEnabled | true | SetProperty equality | +| StatusText | string.Empty | SetProperty equality | +| IsSpeedVisible | false | SetProperty equality | +| SpeedText | string.Empty | SetProperty equality | +| StatusTip | null | Assign and notify on every call, including equal/null | +| IsProgressIndeterminate | true | SetProperty equality | +| ProgressValue | 0d | SetProperty equality, including double NaN semantics | +| ErrorName | ERR_FLASHLIGHT_BISY | SetProperty equality; preserve this exact identifier | +| ErrorHappens | false | Plain assignment, no model property event | + +The eleven observable properties are writable on the internal owner. Keep their public host getters +and private setters as forwards. ErrorHappens has a plain getter/setter on the internal owner so +the original Install reset and completion-route read occur at the same points, without a new event. + +The host adds one readonly field. After the original view and dispatcher assignments, construct +the cold owner with `key => _localizer.GetLocalizedString(key)`, then attach one synchronous bridge +to `OnPropertyChanged(args.PropertyName)`. Keep all prior constructor statements in relative order, +including the three RelayCommand objects. Do not move the packaged BitmapImage initializer, +localizer initialization or AdditionalInfo collection. + +The aggregate reference graph belongs to the host. Add no static event, loaded subscription, +disposal requirement, thread guard or reentry lock. Source inspection can show ownership; actual +GC collection remains outside this qualification. + +## Seven policy methods and observable sequence + +Keep all seven private host methods as direct forwards with their existing argument types: +ShowDownloadState, ApplyStage, OnStageChanged, OnProgressChanged, OnTimeRemainingChanged, +OnSpeedChanged and OnInstallingError. The owner holds their original bodies, with only localization +and owned field/property references changed. Preserve raw nullable strings and double values. + +ShowDownloadState writes Stop enabled, indeterminate, Error hidden, Action hidden and Download +visible in that order. Each publication can invoke a callback before the next value is evaluated. + +ApplyStage maps null to QueueWaiting and keeps a local header string. GETR, END, Extracting, +Completed and CANC localize the original key, then set indeterminate. Downloading localizes, +sets determinate and then shows speed. ErrorHappens only selects its header; it does not change +indeterminate, speed or the error latch. ConnectingToService localizes its header, localizes and +publishes StatusTip, then sets indeterminate. Unknown and empty stage strings are localization keys +verbatim. Every branch publishes the stored header to StatusText last. No other state is reset. + +OnStageChanged reads ErrorHappens once and returns if true. Otherwise it calls ShowDownloadState, +hides speed and calls ApplyStage, without checking the latch again after callbacks. OnProgressChanged +also checks once, then sets determinate before the raw progress value. OnSpeedChanged checks once +before assigning the raw speed string. + +OnTimeRemainingChanged checks the latch once. At one minute or more, localize LeftMinutes before +formatting the truncated integer minute count. Current culture is observed by string.Format after +localization. Below the threshold, localize LeftSmall. Assign StatusTip through its unconditional +setter. Keep the earlier TimeSpan argument across callbacks and preserve formatting failures. + +OnInstallingError has no early guard. This invocation shows Error, hides Action, hides Download +and assigns ErrorName before its own final latch assignment. Notifications observe the current +latch, including changes made by nested calls. A nested error can set it true before the outer +ErrorName notification; later guarded calls respect that current value. An exception prevents the +remaining outer statements and preserves all effects already performed by either frame. Retry +follows ordinary equality behavior; do not snapshot or roll back the latch. + +Preserve exception identity, nested outer/inner frames, field-before-event behavior and partial +effects. An early latch, equality optimization for StatusTip, new validation or a late recheck would +change behavior and needs a separate requirement. + +## Host and operating boundaries + +Only the existing main ItemViewPageViewModel source changes. Queue.cs remains byte-identical, +including operation-ID lookup, handler versions, dispatcher checks, callback identity and speed +formatting with its literal comma-space before OnSpeedChanged's error gate. + +CheckCurrentStatus keeps two separate Store queue-record reads; Progress is read after ApplyStage +callbacks. ShowItemAfterInstallActions keeps its initial ID gate, ordered resets and later current +ID/error checks. Load, Install, Delete, support checks, StoreHelper, DB, licenses and all other +operating actions remain in the host. Only remaining plain latch accesses become owner accesses. +Do not capture item, ID, queue record, error or supported state at a new point. + +Keep public/compiled signatures, XAML, resources, packages, Core/AddOns/Shared/security and other +sessions' worktrees unchanged. Target the main source below 500 lines and the focused owner below +300; these counts supplement the responsibility boundary and do not justify unrelated extraction. + +## Verification and recovery + +Write focused tests before implementation and observe a missing-owner RED. Cover all cold values, +eleven setters, unconditional StatusTip, error gates, every stage, threshold/culture, raw null/NaN, +callback mutation, nested frames, exception identity, partial effects, retry and instance isolation. +An early ErrorHappens assignment must fail real assertions. Restore exact source in finally, verify +its hash and pass focused/full tests and the normal GUI build. Add a discriminating nested-error test: +from the first outer error notification, invoke an inner error once. The later outer ErrorName +notification must observe latch true, its final value must use the outer argument, and a new guarded +call must respect the nested latch. Also retain nested effects if a later outer observer throws. + +Compare the complete old host under declared substitutions and all seven literal policy bodies, +eleven property forwards, constructor order, cold dependencies, bridge and plain latch. Preserve +Queue.cs and all other existing product bytes. Compare source signatures for the 451 baseline +exported types and compiled 452 GUI/88 Core type shapes, with explicit inventory limits. + +Create a fresh immutable source-pinned fixture from accepted native 172. Retain all 34 case partials, +labels and 21 cut paths. Add actual cold ItemViewPageViewModel/private-forward/setter cases with +the current dispatcher and a four-method view substitute that throws on every operating endpoint. +The existing constructor's BitmapImage evidence is limited to its owned packaged URI. Do not call +Load, Execute, queue delivery, StoreHelper, install/delete/DB or add operating cuts/IO. Require +independent pre-build and prelaunch checks, fresh pins, an explicit new exclusive lease and complete +source/resource/corpus/output/hash/process/idle-release postchecks. Derive every count from inputs. + +Full Page/XAML, image decoding/visuals, real queue delivery, unchanged operating routes, installed +product, runtime GC collection, G1, integration and release remain separate. Keep both navigation +native attempts and all new accepted or rejected artifacts. Recover through an additive corrective +commit. Refs #14 and Refs #225. From ca1b6b0882babd907d1557c785f542dcba1d30bd Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:08:45 +0300 Subject: [PATCH 23/31] Extract Store item download presentation state The Store item host mixed eleven display values and an error latch with operating actions. The new internal owner keeps those values and seven original presentation methods. Public getters, private setters and private entrypoints remain synchronous forwards with the host as event sender. Unconditional tip notifications and current nested error effects retain their original order. Focused tests preceded implementation and detected the absent owner. An early latch mutation failed eight cases before exact source restoration. All 2588 managed tests and the normal WinUI build pass with the restored source. Exact policy and public contract guards also pass. Fresh bounded native qualification remains the next local delivery step. Changed files: - "CDPIUI.Tests/CDPIUI.Tests.csproj" (+1/-0 lines). - "CDPIUI.Tests/Presentation/ItemDownloadPresentationTests.cs" (+400/-0 lines). - "CDPIUI/ViewModels/Store/ItemDownloadPresentation.cs" (+209/-0 lines). - "CDPIUI/ViewModels/Store/ItemViewPageViewModel.cs" (+41/-139 lines). - "docs/governance/document-inventory.json" (+14/-4 lines). - "docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md" (+97/-0 lines). The file counts compare the staged tree with its first parent. Refs: #225 Staged-Tree: 88cdac987fd917d989603fe7f0b68643d19f2faf --- CDPIUI.Tests/CDPIUI.Tests.csproj | 1 + .../ItemDownloadPresentationTests.cs | 400 ++++++++++++++++++ .../Store/ItemDownloadPresentation.cs | 209 +++++++++ .../ViewModels/Store/ItemViewPageViewModel.cs | 180 ++------ docs/governance/document-inventory.json | 18 +- ...tore-download-presentation-verification.md | 97 +++++ 6 files changed, 762 insertions(+), 143 deletions(-) create mode 100644 CDPIUI.Tests/Presentation/ItemDownloadPresentationTests.cs create mode 100644 CDPIUI/ViewModels/Store/ItemDownloadPresentation.cs create mode 100644 docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md diff --git a/CDPIUI.Tests/CDPIUI.Tests.csproj b/CDPIUI.Tests/CDPIUI.Tests.csproj index 5b028f3d..e578a2e8 100644 --- a/CDPIUI.Tests/CDPIUI.Tests.csproj +++ b/CDPIUI.Tests/CDPIUI.Tests.csproj @@ -58,6 +58,7 @@ + diff --git a/CDPIUI.Tests/Presentation/ItemDownloadPresentationTests.cs b/CDPIUI.Tests/Presentation/ItemDownloadPresentationTests.cs new file mode 100644 index 00000000..09675fc6 --- /dev/null +++ b/CDPIUI.Tests/Presentation/ItemDownloadPresentationTests.cs @@ -0,0 +1,400 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Globalization; +using System.Linq; +using CDPIUI.ViewModels.Store; +using Xunit; + +namespace CDPIUI.Tests.Presentation; + +public sealed class ItemDownloadPresentationTests +{ + private sealed class Sentinel : Exception; + private static ItemDownloadPresentation New(Func? text = null) => new(text ?? (key => "loc:" + key)); + private static List Observe(ItemDownloadPresentation subject) + { + var events = new List(); + subject.PropertyChanged += (sender, args) => { Assert.Same(subject, sender); events.Add(args.PropertyName!); }; + return events; + } + private static object?[] Values(ItemDownloadPresentation s) => [s.IsActionVisible, s.IsDownloadStatusVisible, + s.IsErrorStatusVisible, s.IsStopEnabled, s.StatusText, s.IsSpeedVisible, s.SpeedText, s.StatusTip, + s.IsProgressIndeterminate, s.ProgressValue, s.ErrorName, s.ErrorHappens]; + private static void DirtyDownload(ItemDownloadPresentation s) + { + s.IsStopEnabled = false; s.IsProgressIndeterminate = false; s.IsErrorStatusVisible = true; + s.IsActionVisible = true; s.IsDownloadStatusVisible = false; + } + [Fact] + public void Constructor_keeps_cold_values_without_localizing() + { + var subject = new ItemDownloadPresentation(_ => throw new InvalidOperationException("Cold constructor localized.")); + Assert.True(subject.IsActionVisible); + Assert.False(subject.IsDownloadStatusVisible); + Assert.False(subject.IsErrorStatusVisible); + Assert.True(subject.IsStopEnabled); + Assert.Equal(string.Empty, subject.StatusText); + Assert.False(subject.IsSpeedVisible); + Assert.Equal(string.Empty, subject.SpeedText); + Assert.Null(subject.StatusTip); + Assert.True(subject.IsProgressIndeterminate); + Assert.Equal(0d, subject.ProgressValue); + Assert.Equal("ERR_FLASHLIGHT_BISY", subject.ErrorName); + Assert.False(subject.ErrorHappens); + } + + public static IEnumerable Setters() + { + yield return ["IsActionVisible", false]; yield return ["IsDownloadStatusVisible", true]; + yield return ["IsErrorStatusVisible", true]; yield return ["IsStopEnabled", false]; + yield return ["StatusText", "status"]; yield return ["IsSpeedVisible", true]; + yield return ["SpeedText", "speed"]; yield return ["StatusTip", "tip"]; + yield return ["IsProgressIndeterminate", false]; yield return ["ProgressValue", 13.5d]; + yield return ["ErrorName", "error"]; + } + [Theory, MemberData(nameof(Setters))] + public void Setter_assigns_before_event_and_preserves_its_equality_rule(string name, object value) + { + var s = New(_ => throw new Sentinel()); var property = typeof(ItemDownloadPresentation).GetProperty(name)!; + int count = 0; + s.PropertyChanged += (sender, args) => + { + Assert.Same(s, sender); Assert.Equal(name, args.PropertyName); + Assert.Equal(value, property.GetValue(s)); count++; + }; + property.SetValue(s, value); property.SetValue(s, value); + Assert.Equal(name == "StatusTip" ? 2 : 1, count); + } + + [Theory] + [InlineData("StatusText"), InlineData("SpeedText"), InlineData("StatusTip"), InlineData("ErrorName")] + public void String_setters_retain_raw_null_and_tip_always_notifies(string name) + { + var s = New(); var property = typeof(ItemDownloadPresentation).GetProperty(name)!; var events = Observe(s); + property.SetValue(s, null); property.SetValue(s, null); + Assert.Null(property.GetValue(s)); Assert.Equal(name == "StatusTip" ? 2 : 1, events.Count); + Assert.All(events, e => Assert.Equal(name, e)); + } + + [Fact] + public void Error_latch_is_plain_state_with_no_property_event_or_dependency_call() + { + var s = New(_ => throw new Sentinel()); var events = Observe(s); + s.ErrorHappens = true; s.ErrorHappens = true; s.ErrorHappens = false; s.ErrorHappens = false; + Assert.False(s.ErrorHappens); Assert.Empty(events); + } + + [Fact] + public void ShowDownloadState_preserves_five_ordered_partial_publications_and_equality() + { + var s = New(_ => throw new Sentinel()); DirtyDownload(s); + var trace = new List<(string?, bool, bool, bool, bool, bool)>(); + s.PropertyChanged += (_, e) => trace.Add((e.PropertyName, s.IsStopEnabled, s.IsProgressIndeterminate, + s.IsErrorStatusVisible, s.IsActionVisible, s.IsDownloadStatusVisible)); + s.ShowDownloadState(); s.ShowDownloadState(); + Assert.Equal(new (string?, bool, bool, bool, bool, bool)[] { + ("IsStopEnabled", true,false,true,true,false), ("IsProgressIndeterminate",true,true,true,true,false), + ("IsErrorStatusVisible",true,true,false,true,false), ("IsActionVisible",true,true,false,false,false), + ("IsDownloadStatusVisible",true,true,false,false,true) }, trace); + } + + public static IEnumerable Stages() + { + foreach (bool initial in new[] { false, true }) + { + yield return ["GETR", "GettingReady", true, false, initial]; + yield return ["END", "Finishing", true, false, initial]; + yield return ["Downloading", "Downloading", false, true, initial]; + yield return ["Extracting", "Installing", true, false, initial]; + yield return ["ErrorHappens", "ErrorHappens", null, false, initial]; + yield return ["Completed", "Finishing", true, false, initial]; + yield return ["CANC", "Cancel", true, false, initial]; + yield return ["ConnectingToService", "ConnectingToService", true, false, initial]; + yield return [null, "QueueWaiting", true, false, initial]; + yield return ["", "", true, false, initial]; + yield return ["unknown.raw", "unknown.raw", true, false, initial]; + } + } + [Theory, MemberData(nameof(Stages))] + public void Stage_matrix_preserves_keys_order_and_values_it_does_not_assign(string? stage, string key, + bool? indeterminate, bool showSpeed, bool initial) + { + var trace = new List(); var s = New(k => { trace.Add("text:" + k); return "loc:" + k; }); + s.IsProgressIndeterminate = initial; s.IsSpeedVisible = initial; s.StatusTip = "old-tip"; s.StatusText = "old-header"; + s.PropertyChanged += (_, e) => trace.Add(e.PropertyName!); s.ApplyStage(stage); + var expected = new List { "text:" + key }; + if (key == "ConnectingToService") { expected.Add("text:ConnectingToServiceTip"); expected.Add("StatusTip"); } + if (indeterminate.HasValue && initial != indeterminate.Value) expected.Add("IsProgressIndeterminate"); + if (showSpeed && !initial) expected.Add("IsSpeedVisible"); expected.Add("StatusText"); + Assert.Equal(expected, trace); Assert.Equal(indeterminate ?? initial, s.IsProgressIndeterminate); + Assert.Equal(showSpeed || initial, s.IsSpeedVisible); + Assert.Equal(key == "ConnectingToService" ? "loc:ConnectingToServiceTip" : "old-tip", s.StatusTip); + Assert.Equal("loc:" + key, s.StatusText); Assert.False(s.ErrorHappens); + } + + [Fact] + public void Repeated_connecting_stage_localizes_again_and_always_publishes_equal_tip() + { + var calls = new List(); var s = New(k => { calls.Add(k); return k; }); var events = Observe(s); + s.ApplyStage("ConnectingToService"); s.ApplyStage("ConnectingToService"); + Assert.Equal(new[] { "ConnectingToService", "ConnectingToServiceTip", "ConnectingToService", "ConnectingToServiceTip" }, calls); + Assert.Equal(new[] { "StatusTip", "StatusText", "StatusTip" }, events); + } + + [Fact] + public void OnStageChanged_preserves_show_reset_localize_and_final_header_order() + { + var trace = new List(); var s = New(k => { trace.Add("text:" + k); return k; }); + DirtyDownload(s); s.IsSpeedVisible = true; s.PropertyChanged += (_, e) => trace.Add(e.PropertyName!); + s.OnStageChanged("Downloading"); + Assert.Equal(new[] { "IsStopEnabled", "IsProgressIndeterminate", "IsErrorStatusVisible", "IsActionVisible", + "IsDownloadStatusVisible", "IsSpeedVisible", "text:Downloading", "IsProgressIndeterminate", "IsSpeedVisible", "StatusText" }, trace); + } + + [Theory] + [InlineData("stage"), InlineData("progress"), InlineData("time"), InlineData("speed")] + public void Error_gate_returns_before_all_writes_and_localization(string operation) + { + var s = New(_ => throw new Sentinel()); s.ErrorHappens = true; var before = Values(s); var events = Observe(s); + switch (operation) + { + case "stage": s.OnStageChanged("Downloading"); break; + case "progress": s.OnProgressChanged(45); break; + case "time": s.OnTimeRemainingChanged(TimeSpan.FromMinutes(2)); break; + case "speed": s.OnSpeedChanged("ignored"); break; + } + Assert.Equal(before, Values(s)); Assert.Empty(events); + } + + [Fact] + public void Stage_entry_does_not_recheck_error_after_show_callback_sets_it() + { + var s = New(); DirtyDownload(s); bool nested = false; + s.PropertyChanged += (_, e) => + { + if (e.PropertyName == "IsStopEnabled" && !nested) { nested = true; s.OnInstallingError("nested"); } + }; + s.OnStageChanged("Downloading"); + Assert.True(s.ErrorHappens); Assert.Equal("nested", s.ErrorName); Assert.False(s.IsErrorStatusVisible); + Assert.False(s.IsActionVisible); Assert.True(s.IsDownloadStatusVisible); Assert.True(s.IsSpeedVisible); + Assert.False(s.IsProgressIndeterminate); Assert.Equal("loc:Downloading", s.StatusText); + s.OnProgressChanged(99); Assert.Equal(0d, s.ProgressValue); + } + + [Fact] + public void Progress_entry_finishes_value_after_an_indeterminate_observer_sets_error() + { + var s = New(); s.PropertyChanged += (_, e) => + { if (e.PropertyName == "IsProgressIndeterminate") s.OnInstallingError("nested"); }; + s.OnProgressChanged(13.5); + Assert.True(s.ErrorHappens); Assert.False(s.IsProgressIndeterminate); Assert.Equal(13.5, s.ProgressValue); + } + + [Theory] + [InlineData(double.NaN), InlineData(double.PositiveInfinity), InlineData(double.NegativeInfinity)] + [InlineData(-1d), InlineData(0d), InlineData(101d), InlineData(123.5d)] + public void Progress_preserves_raw_values_and_repeated_double_equality(double value) + { + var s = New(_ => throw new Sentinel()); var events = Observe(s); s.OnProgressChanged(value); + if (double.IsNaN(value)) Assert.True(double.IsNaN(s.ProgressValue)); else Assert.Equal(value, s.ProgressValue); + Assert.False(s.IsProgressIndeterminate); + Assert.Equal(value == 0d ? new[] { "IsProgressIndeterminate" } : new[] { "IsProgressIndeterminate", "ProgressValue" }, events); + int count = events.Count; s.OnProgressChanged(value); Assert.Equal(count, events.Count); + } + + [Theory] + [InlineData(-60d, "soon"), InlineData(0d, "soon"), InlineData(59.999d, "soon")] + [InlineData(60d, "left 1"), InlineData(119.999d, "left 1"), InlineData(120d, "left 2"), InlineData(3601d, "left 60")] + public void Time_threshold_and_truncated_minutes_keep_unconditional_tip_events(double seconds, string expected) + { + var keys = new List(); var s = New(k => { keys.Add(k); return k == "/UIHelper/LeftMinutes" ? "left {0}" : "soon"; }); + var events = Observe(s); s.OnTimeRemainingChanged(TimeSpan.FromSeconds(seconds)); s.OnTimeRemainingChanged(TimeSpan.FromSeconds(seconds)); + Assert.Equal(expected, s.StatusTip); Assert.Equal(new[] { "StatusTip", "StatusTip" }, events); + Assert.Equal(new[] { seconds >= 60 ? "/UIHelper/LeftMinutes" : "/UIHelper/LeftSmall", seconds >= 60 ? "/UIHelper/LeftMinutes" : "/UIHelper/LeftSmall" }, keys); + } + + [Fact] + public void Time_format_uses_culture_after_localization() + { + var original = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); + var s = New(_ => { CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); return "{0:N1}"; }); + s.OnTimeRemainingChanged(TimeSpan.FromMinutes(1234.75)); Assert.Equal("1.234,0", s.StatusTip); + } + finally { CultureInfo.CurrentCulture = original; } + } + + [Fact] + public void Time_localization_reentry_keeps_outer_time_and_observes_current_latch_without_recheck() + { + ItemDownloadPresentation? s = null; bool nested = false; + s = New(_ => + { + if (!nested) { nested = true; s!.OnInstallingError("nested"); } + return "left {0}"; + }); + s.OnTimeRemainingChanged(TimeSpan.FromMinutes(7.9)); + Assert.True(s.ErrorHappens); Assert.Equal("left 7", s.StatusTip); + } + + [Fact] + public void Speed_retains_raw_null_and_equal_value_suppression() + { + var s = New(_ => throw new Sentinel()); var events = Observe(s); + s.OnSpeedChanged(null); s.OnSpeedChanged(null); s.OnSpeedChanged(" 2 MB/s, "); s.OnSpeedChanged(" 2 MB/s, "); + Assert.Equal(" 2 MB/s, ", s.SpeedText); Assert.Equal(new[] { "SpeedText", "SpeedText" }, events); + } + + [Fact] + public void Error_assigns_four_display_values_before_its_own_terminal_latch() + { + var s = New(_ => throw new Sentinel()); s.IsDownloadStatusVisible = true; + var events = new List(); + s.PropertyChanged += (_, e) => { events.Add(e.PropertyName!); Assert.False(s.ErrorHappens); }; + s.OnInstallingError("outer"); + Assert.Equal(new[] { "IsErrorStatusVisible", "IsActionVisible", "IsDownloadStatusVisible", "ErrorName" }, events); + Assert.True(s.ErrorHappens); Assert.Equal("outer", s.ErrorName); + } + + [Fact] + public void Error_has_no_entry_guard_and_can_publish_raw_null_while_already_latched() + { + var s = New(); s.ErrorHappens = true; s.IsDownloadStatusVisible = true; var events = Observe(s); + s.OnInstallingError(null); + Assert.Equal(new[] { "IsErrorStatusVisible", "IsActionVisible", "IsDownloadStatusVisible", "ErrorName" }, events); + Assert.Null(s.ErrorName); Assert.True(s.ErrorHappens); + } + + [Fact] + public void Error_observer_can_run_guarded_calls_before_the_outer_terminal_assignment() + { + var s = New(); s.PropertyChanged += (_, e) => + { if (e.PropertyName == "IsErrorStatusVisible") { Assert.False(s.ErrorHappens); s.OnProgressChanged(71); s.OnSpeedChanged("inner-speed"); } }; + s.OnInstallingError("outer"); + Assert.Equal(71d, s.ProgressValue); Assert.Equal("inner-speed", s.SpeedText); Assert.True(s.ErrorHappens); + } + + [Theory] + [InlineData(false), InlineData(true)] + public void Nested_error_changes_current_latch_before_later_outer_header_and_survives_outer_failure(bool throwOuter) + { + var s = New(); s.IsDownloadStatusVisible = true; bool nested = false; var error = new Sentinel(); + var names = new List<(string?, bool)>(); + s.PropertyChanged += (_, e) => + { + if (e.PropertyName == "IsErrorStatusVisible" && !nested) { nested = true; s.OnInstallingError("inner"); } + if (e.PropertyName == "ErrorName") + { + names.Add((s.ErrorName, s.ErrorHappens)); + if (s.ErrorName == "outer") + { + Assert.True(s.ErrorHappens); s.OnSpeedChanged("blocked"); + if (throwOuter) throw error; + } + } + }; + if (throwOuter) Assert.Same(error, Assert.Throws(() => s.OnInstallingError("outer"))); + else s.OnInstallingError("outer"); + Assert.Equal(new (string?, bool)[] { ("inner", false), ("outer", true) }, names); + Assert.Equal("outer", s.ErrorName); Assert.True(s.ErrorHappens); Assert.Equal(string.Empty, s.SpeedText); + } + + [Theory] + [InlineData(0), InlineData(1), InlineData(2), InlineData(3)] + public void Error_observer_failure_keeps_partial_fields_and_unwritten_latch_then_retries(int fault) + { + var s = New(); s.IsDownloadStatusVisible = true; var events = Observe(s); var error = new Sentinel(); + string[] names = ["IsErrorStatusVisible", "IsActionVisible", "IsDownloadStatusVisible", "ErrorName"]; + PropertyChangedEventHandler fail = (_, e) => { if (e.PropertyName == names[fault]) throw error; }; + s.PropertyChanged += fail; Assert.Same(error, Assert.Throws(() => s.OnInstallingError("new"))); + Assert.True(s.IsErrorStatusVisible); Assert.Equal(fault < 1, s.IsActionVisible); Assert.Equal(fault < 2, s.IsDownloadStatusVisible); + Assert.Equal(fault == 3 ? "new" : "ERR_FLASHLIGHT_BISY", s.ErrorName); Assert.False(s.ErrorHappens); + Assert.Equal(names.Take(fault + 1), events); s.PropertyChanged -= fail; s.OnInstallingError("new"); + Assert.Equal(names, events); Assert.True(s.ErrorHappens); + } + + [Fact] + public void Nested_stage_keeps_outer_local_header_and_inner_unassigned_state() + { + var s = New(); bool nested = false; + s.PropertyChanged += (_, e) => { if (e.PropertyName == "IsProgressIndeterminate" && !nested) { nested = true; s.ApplyStage("ErrorHappens"); } }; + var events = Observe(s); s.ApplyStage("Downloading"); + Assert.Equal("loc:Downloading", s.StatusText); Assert.False(s.IsProgressIndeterminate); Assert.True(s.IsSpeedVisible); + Assert.Equal(new[] { "StatusText", "IsProgressIndeterminate", "IsSpeedVisible", "StatusText" }, events); + } + + [Fact] + public void Connecting_second_localization_failure_leaves_tip_indeterminate_and_header_untouched() + { + var error = new Sentinel(); var calls = new List(); + var s = New(k => { calls.Add(k); if (k == "ConnectingToServiceTip") throw error; return k; }); + s.IsProgressIndeterminate = false; s.StatusTip = "old-tip"; s.StatusText = "old-header"; var events = Observe(s); + Assert.Same(error, Assert.Throws(() => s.ApplyStage("ConnectingToService"))); + Assert.Equal(new[] { "ConnectingToService", "ConnectingToServiceTip" }, calls); + Assert.Empty(events); Assert.False(s.IsProgressIndeterminate); Assert.Equal("old-tip", s.StatusTip); Assert.Equal("old-header", s.StatusText); + } + + [Fact] + public void Connecting_tip_observer_failure_retains_assignment_and_equal_tip_notifies_on_retry() + { + var s = New(); s.IsProgressIndeterminate = false; s.StatusText = "old"; var events = Observe(s); var error = new Sentinel(); + PropertyChangedEventHandler fail = (_, e) => { if (e.PropertyName == "StatusTip") throw error; }; + s.PropertyChanged += fail; Assert.Same(error, Assert.Throws(() => s.ApplyStage("ConnectingToService"))); + Assert.Equal("loc:ConnectingToServiceTip", s.StatusTip); Assert.False(s.IsProgressIndeterminate); Assert.Equal("old", s.StatusText); + s.PropertyChanged -= fail; s.ApplyStage("ConnectingToService"); + Assert.Equal(new[] { "StatusTip", "StatusTip", "IsProgressIndeterminate", "StatusText" }, events); + } + + [Fact] + public void Download_indeterminate_observer_failure_stops_speed_and_header_then_retries() + { + var s = New(); var events = Observe(s); var error = new Sentinel(); + PropertyChangedEventHandler fail = (_, e) => { if (e.PropertyName == "IsProgressIndeterminate") throw error; }; + s.PropertyChanged += fail; Assert.Same(error, Assert.Throws(() => s.ApplyStage("Downloading"))); + Assert.False(s.IsProgressIndeterminate); Assert.False(s.IsSpeedVisible); Assert.Equal(string.Empty, s.StatusText); + s.PropertyChanged -= fail; s.ApplyStage("Downloading"); + Assert.Equal(new[] { "IsProgressIndeterminate", "IsSpeedVisible", "StatusText" }, events); + } + + [Fact] + public void Stage_show_observer_failure_prevents_reset_and_localization() + { + var s = New(_ => throw new InvalidOperationException("Text should be later.")); DirtyDownload(s); s.IsSpeedVisible = true; + var error = new Sentinel(); s.PropertyChanged += (_, _) => throw error; + Assert.Same(error, Assert.Throws(() => s.OnStageChanged("Downloading"))); + Assert.True(s.IsStopEnabled); Assert.False(s.IsProgressIndeterminate); Assert.True(s.IsErrorStatusVisible); + Assert.True(s.IsActionVisible); Assert.False(s.IsDownloadStatusVisible); Assert.True(s.IsSpeedVisible); + } + + [Fact] + public void Progress_observer_failure_keeps_old_value_then_retries_after_equality_suppression() + { + var s = New(); s.ProgressValue = 5; var events = Observe(s); var error = new Sentinel(); + PropertyChangedEventHandler fail = (_, e) => { if (e.PropertyName == "IsProgressIndeterminate") throw error; }; + s.PropertyChanged += fail; Assert.Same(error, Assert.Throws(() => s.OnProgressChanged(7.5))); + Assert.False(s.IsProgressIndeterminate); Assert.Equal(5d, s.ProgressValue); s.PropertyChanged -= fail; s.OnProgressChanged(7.5); + Assert.Equal(new[] { "IsProgressIndeterminate", "ProgressValue" }, events); Assert.Equal(7.5, s.ProgressValue); + } + + [Theory] + [InlineData(true), InlineData(false)] + public void Time_dependency_failure_does_not_publish_tip(bool localizationFailure) + { + var error = new Sentinel(); var s = New(_ => localizationFailure ? throw error : "{1}"); s.StatusTip = "old"; var events = Observe(s); + if (localizationFailure) Assert.Same(error, Assert.Throws(() => s.OnTimeRemainingChanged(TimeSpan.FromMinutes(2)))); + else Assert.Throws(() => s.OnTimeRemainingChanged(TimeSpan.FromMinutes(2))); + Assert.Equal("old", s.StatusTip); Assert.Empty(events); + } + + [Fact] + public void Independent_owners_do_not_share_values_events_or_latch() + { + var first = New(); var second = New(); var events = Observe(second); + first.OnInstallingError("first"); first.StatusTip = "tip"; first.ProgressValue = 77; + Assert.False(second.ErrorHappens); Assert.Equal("ERR_FLASHLIGHT_BISY", second.ErrorName); + Assert.Null(second.StatusTip); Assert.Equal(0d, second.ProgressValue); Assert.Empty(events); + } +} diff --git a/CDPIUI/ViewModels/Store/ItemDownloadPresentation.cs b/CDPIUI/ViewModels/Store/ItemDownloadPresentation.cs new file mode 100644 index 00000000..1e64850d --- /dev/null +++ b/CDPIUI/ViewModels/Store/ItemDownloadPresentation.cs @@ -0,0 +1,209 @@ +#nullable enable + +using System; + +namespace CDPIUI.ViewModels.Store; + +internal sealed class ItemDownloadPresentation : ObservableObject +{ + private readonly Func _text; + private bool _errorHappens; + private bool _isActionVisible = true; + private bool _isDownloadStatusVisible; + private bool _isErrorStatusVisible; + private bool _isStopEnabled = true; + private string? _statusText = string.Empty; + private bool _isSpeedVisible; + private string? _speedText = ""; + private string? _statusTip; + private bool _isProgressIndeterminate = true; + private double _progressValue; + private string? _errorName = "ERR_FLASHLIGHT_BISY"; + + public ItemDownloadPresentation(Func text) + { + _text = text; + } + + public bool ErrorHappens + { + get => _errorHappens; + set => _errorHappens = value; + } + + public bool IsActionVisible + { + get => _isActionVisible; + set => SetProperty(ref _isActionVisible, value); + } + + public bool IsDownloadStatusVisible + { + get => _isDownloadStatusVisible; + set => SetProperty(ref _isDownloadStatusVisible, value); + } + + public bool IsErrorStatusVisible + { + get => _isErrorStatusVisible; + set => SetProperty(ref _isErrorStatusVisible, value); + } + + public bool IsStopEnabled + { + get => _isStopEnabled; + set => SetProperty(ref _isStopEnabled, value); + } + + public string? StatusText + { + get => _statusText; + set => SetProperty(ref _statusText, value); + } + + public bool IsSpeedVisible + { + get => _isSpeedVisible; + set => SetProperty(ref _isSpeedVisible, value); + } + + public string? SpeedText + { + get => _speedText; + set => SetProperty(ref _speedText, value); + } + + public string? StatusTip + { + get => _statusTip; + set + { + _statusTip = value; + OnPropertyChanged(); + } + } + + public bool IsProgressIndeterminate + { + get => _isProgressIndeterminate; + set => SetProperty(ref _isProgressIndeterminate, value); + } + + public double ProgressValue + { + get => _progressValue; + set => SetProperty(ref _progressValue, value); + } + + public string? ErrorName + { + get => _errorName; + set => SetProperty(ref _errorName, value); + } + + public void ShowDownloadState() + { + IsStopEnabled = true; + IsProgressIndeterminate = true; + IsErrorStatusVisible = false; + IsActionVisible = false; + IsDownloadStatusVisible = true; + } + + public void ApplyStage(string? state) + { + state ??= "QueueWaiting"; + string stageHeaderText = string.Empty; + switch (state) + { + case "GETR": + stageHeaderText = _text("GettingReady"); + IsProgressIndeterminate = true; + break; + case "END": + stageHeaderText = _text("Finishing"); + IsProgressIndeterminate = true; + break; + case "Downloading": + stageHeaderText = _text("Downloading"); + IsProgressIndeterminate = false; + IsSpeedVisible = true; + break; + case "Extracting": + stageHeaderText = _text("Installing"); + IsProgressIndeterminate = true; + break; + case "ErrorHappens": + stageHeaderText = _text("ErrorHappens"); + break; + case "Completed": + stageHeaderText = _text("Finishing"); + IsProgressIndeterminate = true; + break; + case "CANC": + stageHeaderText = _text("Cancel"); + IsProgressIndeterminate = true; + break; + case "ConnectingToService": + stageHeaderText = _text("ConnectingToService"); + StatusTip = _text("ConnectingToServiceTip"); + IsProgressIndeterminate = true; + break; + default: + stageHeaderText = _text(state); + IsProgressIndeterminate = true; + break; + } + StatusText = stageHeaderText; + } + + public void OnStageChanged(string? stage) + { + if (_errorHappens) + return; + + ShowDownloadState(); + + IsSpeedVisible = false; + + ApplyStage(stage); + } + + public void OnProgressChanged(double progress) + { + if (_errorHappens) + return; + + IsProgressIndeterminate = false; + ProgressValue = progress; + } + + public void OnTimeRemainingChanged(TimeSpan time) + { + if (_errorHappens) + return; + + if (time.TotalMinutes >= 1) + StatusTip = string.Format(_text("/UIHelper/LeftMinutes"), (int)time.TotalMinutes); + else + StatusTip = _text("/UIHelper/LeftSmall"); + } + + public void OnSpeedChanged(string? speedText) + { + if (_errorHappens) + return; + + SpeedText = speedText; + } + + public void OnInstallingError(string? errorCode) + { + IsErrorStatusVisible = true; + IsActionVisible = false; + IsDownloadStatusVisible = false; + + ErrorName = errorCode; + _errorHappens = true; + } +} diff --git a/CDPIUI/ViewModels/Store/ItemViewPageViewModel.cs b/CDPIUI/ViewModels/Store/ItemViewPageViewModel.cs index 21deb333..c211b24e 100644 --- a/CDPIUI/ViewModels/Store/ItemViewPageViewModel.cs +++ b/CDPIUI/ViewModels/Store/ItemViewPageViewModel.cs @@ -30,10 +30,10 @@ public sealed partial class ItemViewPageViewModel : ObservableObject private readonly IItemViewPageView _view; private readonly ILocalizer _localizer = Localizer.Get(); private readonly DispatcherQueue _dispatcherQueue; + private readonly ItemDownloadPresentation _downloadPresentation; private string _storeId; private RepoItemModel _item; - private bool _errorHappens; private bool _loaded; private string _itemName = string.Empty; @@ -46,26 +46,17 @@ public sealed partial class ItemViewPageViewModel : ObservableObject private bool _isWarningVisible = true; private string _warningText = ""; private bool _isActionEnabled = true; - private bool _isActionVisible = true; private string _actionText = string.Empty; private bool _isMoreVisible; private bool _isUnsupportedWarningVisible; private bool _isLinksVisible = true; - private bool _isDownloadStatusVisible; - private bool _isErrorStatusVisible; - private bool _isStopEnabled = true; - private string _statusText = string.Empty; - private bool _isSpeedVisible; - private string _speedText = ""; - private string _statusTip; - private bool _isProgressIndeterminate = true; - private double _progressValue; - private string _errorName = "ERR_FLASHLIGHT_BISY"; public ItemViewPageViewModel(IItemViewPageView view, DispatcherQueue dispatcherQueue) { _view = view; _dispatcherQueue = dispatcherQueue; + _downloadPresentation = new ItemDownloadPresentation(key => _localizer.GetLocalizedString(key)); + _downloadPresentation.PropertyChanged += (_, args) => OnPropertyChanged(args.PropertyName); DeleteCommand = new RelayCommand(Delete); ShowFolderCommand = new RelayCommand(ShowFolder); LaunchUnsupportedHelpCommand = new RelayCommand(LaunchUnsupportedHelp); @@ -146,8 +137,8 @@ public bool IsActionEnabled public bool IsActionVisible { - get => _isActionVisible; - private set => SetProperty(ref _isActionVisible, value); + get => _downloadPresentation.IsActionVisible; + private set => _downloadPresentation.IsActionVisible = value; } public string ActionText @@ -176,38 +167,38 @@ public bool IsLinksVisible public bool IsDownloadStatusVisible { - get => _isDownloadStatusVisible; - private set => SetProperty(ref _isDownloadStatusVisible, value); + get => _downloadPresentation.IsDownloadStatusVisible; + private set => _downloadPresentation.IsDownloadStatusVisible = value; } public bool IsErrorStatusVisible { - get => _isErrorStatusVisible; - private set => SetProperty(ref _isErrorStatusVisible, value); + get => _downloadPresentation.IsErrorStatusVisible; + private set => _downloadPresentation.IsErrorStatusVisible = value; } public bool IsStopEnabled { - get => _isStopEnabled; - private set => SetProperty(ref _isStopEnabled, value); + get => _downloadPresentation.IsStopEnabled; + private set => _downloadPresentation.IsStopEnabled = value; } public string StatusText { - get => _statusText; - private set => SetProperty(ref _statusText, value); + get => _downloadPresentation.StatusText; + private set => _downloadPresentation.StatusText = value; } public bool IsSpeedVisible { - get => _isSpeedVisible; - private set => SetProperty(ref _isSpeedVisible, value); + get => _downloadPresentation.IsSpeedVisible; + private set => _downloadPresentation.IsSpeedVisible = value; } public string SpeedText { - get => _speedText; - private set => SetProperty(ref _speedText, value); + get => _downloadPresentation.SpeedText; + private set => _downloadPresentation.SpeedText = value; } /// @@ -216,30 +207,26 @@ public string SpeedText /// public string StatusTip { - get => _statusTip; - private set - { - _statusTip = value; - OnPropertyChanged(); - } + get => _downloadPresentation.StatusTip; + private set => _downloadPresentation.StatusTip = value; } public bool IsProgressIndeterminate { - get => _isProgressIndeterminate; - private set => SetProperty(ref _isProgressIndeterminate, value); + get => _downloadPresentation.IsProgressIndeterminate; + private set => _downloadPresentation.IsProgressIndeterminate = value; } public double ProgressValue { - get => _progressValue; - private set => SetProperty(ref _progressValue, value); + get => _downloadPresentation.ProgressValue; + private set => _downloadPresentation.ProgressValue = value; } public string ErrorName { - get => _errorName; - private set => SetProperty(ref _errorName, value); + get => _downloadPresentation.ErrorName; + private set => _downloadPresentation.ErrorName = value; } /// Shows the item; called when the page is opened with an item id. @@ -394,7 +381,7 @@ private async Task InstallAsync() if (!await AskLicenseAsync()) return; ConnectHandlers(); - _errorHappens = false; + _downloadPresentation.ErrorHappens = false; ShowDownloadState(); @@ -412,14 +399,8 @@ private async Task AskLicenseAsync() return await _view.AcceptLicensesAsync(_item.license); } - private void ShowDownloadState() - { - IsStopEnabled = true; - IsProgressIndeterminate = true; - IsErrorStatusVisible = false; - IsActionVisible = false; - IsDownloadStatusVisible = true; - } + private void ShowDownloadState() => + _downloadPresentation.ShowDownloadState(); private void CheckCurrentStatus() { @@ -434,102 +415,23 @@ private void CheckCurrentStatus() } } - private void ApplyStage(string state) - { - state ??= "QueueWaiting"; - string stageHeaderText = string.Empty; - switch (state) - { - case "GETR": - stageHeaderText = _localizer.GetLocalizedString("GettingReady"); - IsProgressIndeterminate = true; - break; - case "END": - stageHeaderText = _localizer.GetLocalizedString("Finishing"); - IsProgressIndeterminate = true; - break; - case "Downloading": - stageHeaderText = _localizer.GetLocalizedString("Downloading"); - IsProgressIndeterminate = false; - IsSpeedVisible = true; - break; - case "Extracting": - stageHeaderText = _localizer.GetLocalizedString("Installing"); - IsProgressIndeterminate = true; - break; - case "ErrorHappens": - stageHeaderText = _localizer.GetLocalizedString("ErrorHappens"); - break; - case "Completed": - stageHeaderText = _localizer.GetLocalizedString("Finishing"); - IsProgressIndeterminate = true; - break; - case "CANC": - stageHeaderText = _localizer.GetLocalizedString("Cancel"); - IsProgressIndeterminate = true; - break; - case "ConnectingToService": - stageHeaderText = _localizer.GetLocalizedString("ConnectingToService"); - StatusTip = _localizer.GetLocalizedString("ConnectingToServiceTip"); - IsProgressIndeterminate = true; - break; - default: - stageHeaderText = _localizer.GetLocalizedString(state); - IsProgressIndeterminate = true; - break; - } - StatusText = stageHeaderText; - } + private void ApplyStage(string state) => + _downloadPresentation.ApplyStage(state); - private void OnStageChanged(string stage) - { - if (_errorHappens) - return; + private void OnStageChanged(string stage) => + _downloadPresentation.OnStageChanged(stage); - ShowDownloadState(); + private void OnProgressChanged(double progress) => + _downloadPresentation.OnProgressChanged(progress); - IsSpeedVisible = false; + private void OnTimeRemainingChanged(TimeSpan time) => + _downloadPresentation.OnTimeRemainingChanged(time); - ApplyStage(stage); - } + private void OnSpeedChanged(string speedText) => + _downloadPresentation.OnSpeedChanged(speedText); - private void OnProgressChanged(double progress) - { - if (_errorHappens) - return; - - IsProgressIndeterminate = false; - ProgressValue = progress; - } - - private void OnTimeRemainingChanged(TimeSpan time) - { - if (_errorHappens) - return; - - if (time.TotalMinutes >= 1) - StatusTip = string.Format(_localizer.GetLocalizedString("/UIHelper/LeftMinutes"), (int)time.TotalMinutes); - else - StatusTip = _localizer.GetLocalizedString("/UIHelper/LeftSmall"); - } - - private void OnSpeedChanged(string speedText) - { - if (_errorHappens) - return; - - SpeedText = speedText; - } - - private void OnInstallingError(string errorCode) - { - IsErrorStatusVisible = true; - IsActionVisible = false; - IsDownloadStatusVisible = false; - - ErrorName = errorCode; - _errorHappens = true; - } + private void OnInstallingError(string errorCode) => + _downloadPresentation.OnInstallingError(errorCode); private void ShowItemAfterInstallActions(string id) { @@ -542,7 +444,7 @@ private void ShowItemAfterInstallActions(string id) SpeedText = ""; StatusTip = _localizer.GetLocalizedString("WorkingOnIt"); - if (id == _storeId && !_errorHappens) + if (id == _storeId && !_downloadPresentation.ErrorHappens) { IsActionEnabled = IsItemSupported(); ActionText = _localizer.GetLocalizedString("Install"); diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index c1e87978..167cc7d5 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1548,8 +1548,8 @@ }, { "path": "docs/superpowers/specs/2026-11-11-store-download-presentation-design.md", - "firstIntroduction": "Local Store download presentation contract under issue225; baseline12ef689e0968bd7ff4b27cee0fe7af02091286da.", - "first_commit": null, + "firstIntroduction": "a1a79fba42b7db3622ec43da315744465b67496c\tleather147\tRecord Store download presentation ownership design", + "first_commit": "a1a79fba42b7db3622ec43da315744465b67496c", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", @@ -1558,13 +1558,23 @@ }, { "path": "docs/superpowers/plans/2026-11-11-store-download-presentation.md", - "firstIntroduction": "Local Store download presentation contract under issue225; baseline12ef689e0968bd7ff4b27cee0fe7af02091286da.", - "first_commit": null, + "firstIntroduction": "a1a79fba42b7db3622ec43da315744465b67496c\tleather147\tRecord Store download presentation ownership design", + "first_commit": "a1a79fba42b7db3622ec43da315744465b67496c", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", "language": "en", "changes": "Define download display state ownership, unconditional tip events, late error latch and bounded local qualification." + }, + { + "path": "docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md", + "firstIntroduction": "Local Store download presentation verification under issue225.", + "first_commit": null, + "first_author": "leather147", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Record nested-latch clarification, observed TDD/mutation/full managed evidence, exact compatibility guards and bounded native delivery gates." } ], "current_history_base": "7ead95f7756057f67cd113671a7f84cf422e8d32", diff --git a/docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md b/docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md new file mode 100644 index 00000000..e1f1c384 --- /dev/null +++ b/docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md @@ -0,0 +1,97 @@ +# Store item download presentation verification + +## Scope and source checkpoint + +[Issue #225](https://github.com/lumenpearson/cdpiui/issues/225) owns this LOCAL GUI presentation +extraction from frozen PR #224 at `12ef689e0968bd7ff4b27cee0fe7af02091286da`. +Root owns `dev/store-download-presentation` in the existing isolated worktree. Actual Project +intake 137 persisted In progress/P2/Architecture/Medium/G2/lumenpearson and two canonical labels +after reload. The [receipt](https://github.com/lumenpearson/cdpiui/issues/225#issuecomment-6798817588) +and guarded release 138 precede implementation. No other session owns this source family. + +One internal ItemDownloadPresentation owns eleven display values and the plain error latch. +Its only dependency is a lazy Text function, stored without invocation. Eleven public host +getters/private setters and seven private methods remain forwards, with one synchronous +host-sender bridge. StatusTip assigns and notifies on every call, including equal/null values. +The other ten properties retain SetProperty equality. ErrorHappens has no property event. + +The main source decreases from 562 to 464 lines. Queue.cs remains 122 lines, so the partial sum +decreases from 684 to 586. The new owner has 209 lines. Existing product changes are restricted +to the main source, with two mechanical remaining error-latch accesses at their original points. +CheckCurrentStatus's two late queue reads, Queue.cs formatting/subscriptions/dispatcher/version +checks, completion-route current reads and operating actions remain in the host. + +## Design clarification and TDD evidence + +Design commit: `a1a79fba42b7db3622ec43da315744465b67496c`. Before product code, the fresh +builder found one important overstatement: each error invocation writes its own latch last, +but a nested error can set the current latch before later outer notifications. The specification, +plan and issue were corrected before TDD. The builder confirmed that clarification resolved and +found nothing else important. Tests explicitly preserve the nested latch and both frames' effects +when a later outer observer throws. No entry snapshot or outer recheck is introduced. + +The first cold test was written before the owner or link existed and observed the expected +CS0246 for ItemDownloadPresentation. All 83 focused cases were then written before implementation. +The first pure run passed 83/83 in 39 ms, with two test-only CS8620 nullable-tuple warnings. +Explicit nullable expected-tuple types corrected those annotations without changing assertions. +A clean pure run passed 83/83 in 31 ms before host wiring. + +Coverage includes twelve cold values, eleven setters, raw null strings, unconditional tip events, +plain latch, ordered partial states, 22 literal stage/carryover rows, repeated localization, +single entry guards, callbacks changing the latch, NaN/infinities/raw progress, minute thresholds, +culture after localization, nested errors/stages, failure identity, partial effects, retry and +independent owners. The nested-error cases distinguish current shared state from an entry snapshot. + +The first controlled-mutant preparation stopped before any mutation or test because its LF +anchor did not match raw CRLF bytes. The finally block restored and verified the original hash; +the original helper was preserved. Only the harness newline selection was corrected. +The actual early-latch mutant then failed eight cases and passed 75, total 83 in 40 ms. +Those are behavioral assertion failures, with no compilation error. Exact original owner bytes +were restored in finally and verified with SHA256 +`5FD7E26EF1BE4D5C3D8851761565B9F1B11971D9281FC53925951B5CCB6E053C`. +The restored focused run passed 83/83 in 28 ms. + +With host wiring present, the complete suite passed 2588/2588 in 9 s, zero failures/skips. +The normal WinUI build passed with zero warnings/errors in 47.92 s. + +```text +C:/Users/lumen/.dotnet/dotnet.exe test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release --no-restore --filter FullyQualifiedName~ItemDownloadPresentationTests +C:/Users/lumen/.dotnet/dotnet.exe test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release --no-restore +C:/Users/lumen/.dotnet/dotnet.exe build CDPIUI/CDPIUI.csproj -c Release -p:Platform=x64 --no-restore +``` + +## Compatibility and exact-source guards + +The source comparison covers 451 baseline exported types across 620 baseline and 621 current +GUI files. No original signature was removed or changed. Compiled comparisons preserve 452 GUI +and 88 Core exported type shapes, with zero removals/changes and no additions on retained types. +These bounded inventories do not certify every attribute, annotation, inferred source type or +native ABI. Core/AddOns/Shared source remains unchanged. + +The policy guard compares all seven literal bodies under declared visibility, nullable annotation +and Text substitutions. It reconstructs the complete original host under only the allowed field, +property, method, constructor and two latch substitutions. It checks the entire owner's declared +shape, twelve defaults, eleven setter rules, plain current latch, cold constructor, one bridge, +all prior constructor statement order, unchanged Queue.cs and one additive test link. It passes +without a product correction. The old accepted native cases contain no moved Store-field reference. + +The current normal GUI SHA256 is +`78D188F6BE63B731F92EBC8006160894A632389FABDE97140F5F77D77B6CD61C`. Accepted navigation evidence keeps its historical F1DC9407 output hash, +which was saved before this rebuild. Do not rerun its frozen verifier against the new normal output. + +## Pending native and delivery gates + +Fresh immutable native qualification will retain the accepted 172-label corpus, all 34 old case +partials and 21 inherited cut paths. Actual Store host constructor/private-forward/setter evidence +uses its current dispatcher and a four-method view substitute that throws on operating endpoints. +The packaged BitmapImage check is limited to its owned URI, without visual decoding/loading. +No Load, Execute, queue delivery, StoreHelper, DB, installation, deletion, new operating cut or IO +belongs to this stage. Independent pre-build/prelaunch READY and a new explicit lease are required. + +Native, fresh whole-branch review, stacked draft/exact final-head checks, actual PR Project fields +and immediate six-criterion local acceptance remain pending at this evidence checkpoint. +Refs #14 and Refs #225. Parent #13/#14/#15 and draft #216/#218/#220/#222/#224 remain open/unmerged. +Full Page/XAML, image visuals, queue delivery, real operating routes, runtime GC collection, +installed product, G1, integration and release remain separate. Retain every ref, workspace, +archive and accepted or rejected artifact, including both preceding navigation attempts. +Raw evidence is in `.superpowers/sdd/2026-11-11-store-download-presentation/`. From 604c6a763fe8db8fa25a6436c738e5d2f76ed156 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:45:44 +0300 Subject: [PATCH 24/31] Record Store download native qualification The first fixture build exposed a local declaration conflict in its new scenario. Its source, archive and failed build evidence remain available. A fresh copy changes only the conflicting local variable name. Independent checks verified that correction, the complete retained corpus and all operating boundaries before a new build and launch. The corrected fixture built without warnings or errors and passed all 178 groups under a new exclusive lease. Source, resource, artifact, prior output, retained input and report checks passed after exit. Process absence and guarded queue release were verified separately. This record accepts bounded host composition while leaving visual, queue delivery, installed product and release qualification separate. Product and managed test bytes remain unchanged. Changed files: - "docs/governance/document-inventory.json" (+2/-2 lines). - "docs/superpowers/plans/2026-11-11-store-download-presentation.md" (+8/-8 lines). - "docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md" (+79/-10 lines). The file counts compare the staged tree with its first parent. Refs: #225 Staged-Tree: 3a8516c470c7de2708246dd206449447f20d0457 --- docs/governance/document-inventory.json | 4 +- .../2026-11-11-store-download-presentation.md | 16 ++-- ...tore-download-presentation-verification.md | 89 ++++++++++++++++--- 3 files changed, 89 insertions(+), 20 deletions(-) diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index 167cc7d5..5fdd07a6 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1568,8 +1568,8 @@ }, { "path": "docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md", - "firstIntroduction": "Local Store download presentation verification under issue225.", - "first_commit": null, + "firstIntroduction": "ca1b6b0882babd907d1557c785f542dcba1d30bd\tleather147\tExtract Store item download presentation state", + "first_commit": "ca1b6b0882babd907d1557c785f542dcba1d30bd", "first_author": "leather147", "upstream_path_present": false, "policy": "ASD-STE100 principles for English", diff --git a/docs/superpowers/plans/2026-11-11-store-download-presentation.md b/docs/superpowers/plans/2026-11-11-store-download-presentation.md index 98fc9ef8..d1c80647 100644 --- a/docs/superpowers/plans/2026-11-11-store-download-presentation.md +++ b/docs/superpowers/plans/2026-11-11-store-download-presentation.md @@ -47,14 +47,14 @@ one linked-source entry; focused design/plan/report and additive document invent **Interfaces:** consumes a stored Text function and original method arguments. Produces eleven current observable values, plain ErrorHappens and seven methods through host property/private forwards. -- [ ] Read issue/spec/intake, preserve normal/source/compiled baselines, and obtain a fresh builder +- [x] Read issue/spec/intake, preserve normal/source/compiled baselines, and obtain a fresh builder verdict before product code. Inspect accepted 172 cases for moved-field dependencies. -- [ ] Write cold/ordering/gate/stage/culture/reentry/failure tests first and observe expected missing-owner RED. -- [ ] Implement owner, eleven host forwards, seven method forwards, two remaining latch accesses and +- [x] Write cold/ordering/gate/stage/culture/reentry/failure tests first and observe expected missing-owner RED. +- [x] Implement owner, eleven host forwards, seven method forwards, two remaining latch accesses and one cold constructor bridge; preserve prior statements. Run focused GREEN and inspect assertions. -- [ ] Apply a controlled early error latch before error publications, observe behavioral failures, +- [x] Apply a controlled early error latch before error publications, observe behavioral failures, restore exact source/hash in finally, then focused/full GREEN and normal GUI with zero warnings/errors. -- [ ] Verify source/compiled public preservation, exact existing footprint, whole-host/policy/property/ +- [x] Verify source/compiled public preservation, exact existing footprint, whole-host/policy/property/ constructor/bridge/latch/Queue guards, line bounds, governance and redacted scans; commit checkpoint. ### Task 2: Qualify actual host composition and accept locally @@ -65,11 +65,11 @@ dedicated report and additive inventory. **Interfaces:** consumes Task 1 product pin and accepted 172 corpus, 34 old case partials and 21 cut paths. Produces bounded real Store host/private setter/forward evidence and local draft acceptance. -- [ ] Read Task 1 evidence/brief; preserve all accepted labels/case bytes/cuts and derive fresh counts. +- [x] Read Task 1 evidence/brief; preserve all accepted labels/case bytes/cuts and derive fresh counts. Add discriminating actual host/setter/guard/latch/reentry/failure cases before build. -- [ ] Obtain independent pre-build review; build zero warnings/errors, pin all actual artifacts/resources/ +- [x] Obtain independent pre-build review; build zero warnings/errors, pin all actual artifacts/resources/ sources/runner/verifier and baseline filenames/hashes, then independent prelaunch READY. -- [ ] Obtain a NEW explicit exclusive lease, run one exact owned process, and verify corpus/COMPLETE/ +- [x] Obtain a NEW explicit exclusive lease, run one exact owned process, and verify corpus/COMPLETE/ exit/streams/source/resources/hash/IO/absence/process cleanup; idle/requestfalse and guarded release. - [ ] Update evidence and obtain fresh whole-branch review. Resolve Critical/Important through observed RED to GREEN, retain failures, and ledger all rulings/deferred Minor findings and their costs. diff --git a/docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md b/docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md index e1f1c384..2b3fbd86 100644 --- a/docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md +++ b/docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md @@ -79,16 +79,85 @@ The current normal GUI SHA256 is `78D188F6BE63B731F92EBC8006160894A632389FABDE97140F5F77D77B6CD61C`. Accepted navigation evidence keeps its historical F1DC9407 output hash, which was saved before this rebuild. Do not rerun its frozen verifier against the new normal output. -## Pending native and delivery gates - -Fresh immutable native qualification will retain the accepted 172-label corpus, all 34 old case -partials and 21 inherited cut paths. Actual Store host constructor/private-forward/setter evidence -uses its current dispatcher and a four-method view substitute that throws on operating endpoints. -The packaged BitmapImage check is limited to its owned URI, without visual decoding/loading. -No Load, Execute, queue delivery, StoreHelper, DB, installation, deletion, new operating cut or IO -belongs to this stage. Independent pre-build/prelaunch READY and a new explicit lease are required. - -Native, fresh whole-branch review, stacked draft/exact final-head checks, actual PR Project fields +Product checkpoint: `ca1b6b0882babd907d1557c785f542dcba1d30bd`. Later evidence updates do not +change product or managed test bytes. + +## Native preparation and retained failed build + +The first fresh fixture is `F:/cdpiui-verify/cdpiui-store-download-ca1b6b0-20261111`. +Independent pre-build reconstruction verified 1603 tracked inputs, exactly 21 inherited cut paths, +36 bootstrap files, 40 extras and no reparse entries. All 34 accepted navigation R2 partials are +raw-byte identical. Twenty whole cut files are raw-byte identical; DirectoriesManager differs +only in the exact new EXE literal. The 172-label prefix and six new labels form 178 unique groups. + +The initial review found stale navigation scope and reviewer text in the copied queue helper. +That metadata and the preparer were corrected before any request; original bytes were retained. +The review found no other unresolved issue and permitted build, without claiming compilation. +The build then failed: zero warnings, primary CS0136 for a conflicting local count declaration, +secondary MSB3073, 50.73 s. The initial source review had missed the declaration-space conflict. +No application, readiness request, lease, runtime pin set or successful runtime result existed. +The failed source/archive/case/recipes/build artifacts and log remain unchanged. + +A NEW `-r2` fixture and `native-r2/` evidence workspace use the same product pin. Its case changes +only two identifier occurrences: the later count declaration and use become guardedEventCount. +Assertions, labels, endpoints and flow are unchanged. A fresh independent reconstruction verified +all inputs/cuts/cases/corpus and the exact rename. Read-only Roslyn 4.8 AST inspection found 33 local +declarations, one ancestor-scope conflict in R1 and zero in R2; lambda/catch/deconstruction scopes +were also checked. This was not compilation. R2 pre-build READY has no unresolved findings. +The corrected case SHA256 is +`2DD2B0ECFFB99CD93D30798CF5A9739D5A01CB0CFB94C4EA70403CA339779FCF`. + +## Accepted R2 native qualification + +The fresh R2 fixture is `F:/cdpiui-verify/cdpiui-store-download-ca1b6b0-20261111-r2`. +Its build passed with zero warnings/errors in 59.33 s. Pinning produced 73 actual inputs: +5 own binaries, 20 resources and 48 source/evidence files, including unchanged Queue.cs. +The full 522-file output baseline is hashed. All 20 packaged resources equal generated bytes, +5206 entries equal source JSON, and 51 English keys satisfy the declared rules. Ordinary labels +can legitimately equal their keys; all eleven actual Store values have explicit native assertions. + +The same independent reviewer rehashed all 73 pins and 522 baseline paths/digests, reconstructed +all source/corpus evidence and parsed the actual EXE: AMD64 PE32+, Windows GUI, one embedded +asInvoker/uiAccess=false manifest. The current token was non-admin; the exact process, future +outputs and markers were absent. PowerShell parsing had zero errors and no pending pin remained. +Prelaunch verdict: READY, zero unresolved Critical, Important or Minor findings. + +| Artifact | SHA256 | +| --- | --- | +| Native GUI DLL | `8DBC45E583E65C29E964C09F244C78855032BE5F04EA91A8B890FAAA1B5095B3` | +| Runner | `A8C9B035C59458010F049896147D8843DC11C6AA540922D6F93D5176450F35BD` | +| Runtime verifier | `7F7DCE1162D2B5896C65B88039B40B1F7180841587CB85EC6DD4A89F15B8C3C4` | +| Full output baseline | `F587E846019E311B8FDCACE32CBF36CC54FF216D9082D1954D5E4519EAE760A7` | +| Corpus | `C6361DC856CB14A5EB852C576F849CF55AC4CBC7B3E693BD29052FAEF5A7E479` | +| Corrected Store case | `2DD2B0ECFFB99CD93D30798CF5A9739D5A01CB0CFB94C4EA70403CA339779FCF` | + +Root independently repeated the immediate hash/readiness checks before explicit grant 139. +One PID 79748 ran from 2026-11-11T15:41:49.4721170Z to 2026-11-11T15:41:52.0697273+00:00. +All 178 unique groups passed with the exact 172/166/160/154/149/137 prefixes and peer 141 +projection, one COMPLETE, zero FAIL, exit0 and empty stdout/stderr. All 73 pins, 522 prior +filenames/hashes, full source boundaries and resources passed afterward. Exactly six new names +made 528 total files. Three literal inputs retain 16/16/15 bytes; both serializer reports retain +exact 354/260-byte golden contents and current model fields. All seven forbidden paths and +custom markers remain absent. The normal GUI retains the recorded 78D188F6 hash. + +The six Store groups exercise actual constructor/dispatcher/packaged URI, eleven private setters, +host sender/equality/plain latch, stage/carryover and five-publication order, guarded entry with +later outer effects, current nested latch before outer ErrorName and after outer failure, all four +error-observer boundaries/partial state/retry, raw NaN and null speed, ordinary time thresholds, +unconditional repeated tip and independent models. Actual Store host/owner/localizer are uncut. +The view throws on all four endpoints. IsLoaded, StoreId, AdditionalInfo, handler connection/version +and inherited operating counters remain cold. All external handlers detach in finally. + +Root separately checked PID 79748 and the exact EXE absent, wrote idle 139/requestfalse with +no pending call, and read back guarded release 140 with previousVersion 139, owner null and +all six participants paused. R2 evidence is retained in `native-r2/`; R1 remains the failed build. +Bitmap evidence is URI-only. No Load, Execute, queue delivery, StoreHelper, DB, installation, +deletion, new operating cut or operating IO was introduced. These checks do not establish +image decoding, full Page/XAML, real queue delivery or unchanged operating actions. + +## Pending delivery gates + +Fresh whole-branch review, stacked draft/exact final-head checks, actual PR Project fields and immediate six-criterion local acceptance remain pending at this evidence checkpoint. Refs #14 and Refs #225. Parent #13/#14/#15 and draft #216/#218/#220/#222/#224 remain open/unmerged. Full Page/XAML, image visuals, queue delivery, real operating routes, runtime GC collection, From 3afa82e3f4947ce4bef38b14d86c642c93ddbe90 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:44:15 +0300 Subject: [PATCH 25/31] Record independent Store presentation review The independent whole branch review found no actionable defect in product code, tests or evidence. It reconstructed the original host and policy and verified all retained native inputs and outputs. An earlier unavailable model produced no verdict and was replaced with a fresh available reviewer. The execution records remain distinct from that read only assessment. This commit records the completed review and its broader acceptance limits. Product source, managed tests and both native fixture attempts remain unchanged. The published head still needs required hosted checks and actual Project readback before local acceptance. Parent integration, installed product and release work retain their separate boundaries. Changed files: - "docs/superpowers/plans/2026-11-11-store-download-presentation.md" (+1/-1 lines). - "docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md" (+18/-2 lines). The file counts compare the staged tree with its first parent. Refs: #225 Staged-Tree: 5f10ed56c8a25301af827c04eb0ca502d1ee6d18 --- .../2026-11-11-store-download-presentation.md | 2 +- ...tore-download-presentation-verification.md | 20 +++++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/docs/superpowers/plans/2026-11-11-store-download-presentation.md b/docs/superpowers/plans/2026-11-11-store-download-presentation.md index d1c80647..be5f1411 100644 --- a/docs/superpowers/plans/2026-11-11-store-download-presentation.md +++ b/docs/superpowers/plans/2026-11-11-store-download-presentation.md @@ -71,7 +71,7 @@ paths. Produces bounded real Store host/private setter/forward evidence and loca sources/runner/verifier and baseline filenames/hashes, then independent prelaunch READY. - [x] Obtain a NEW explicit exclusive lease, run one exact owned process, and verify corpus/COMPLETE/ exit/streams/source/resources/hash/IO/absence/process cleanup; idle/requestfalse and guarded release. -- [ ] Update evidence and obtain fresh whole-branch review. Resolve Critical/Important through observed +- [x] Update evidence and obtain fresh whole-branch review. Resolve Critical/Important through observed RED to GREEN, retain failures, and ledger all rulings/deferred Minor findings and their costs. - [ ] Publish a draft stacked on dev/blockcheck-wizard-navigation with Refs #14 and Refs #225; verify exact final-head checks and actual PR metadata/Project fields, without parent/main merge. diff --git a/docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md b/docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md index 2b3fbd86..ef75e1e9 100644 --- a/docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md +++ b/docs/superpowers/reports/2026-11-11-store-download-presentation-verification.md @@ -155,10 +155,26 @@ Bitmap evidence is URI-only. No Load, Execute, queue delivery, StoreHelper, DB, deletion, new operating cut or operating IO was introduced. These checks do not establish image decoding, full Page/XAML, real queue delivery or unchanged operating actions. +## Independent final review + +Fresh reviewer store_download_final_review_available examined the complete range +`12ef689e0968bd7ff4b27cee0fe7af02091286da` through +`604c6a763fe8db8fa25a6436c738e5d2f76ed156`: zero Critical, zero Important and zero Minor findings. +The earlier Astra review attempt stopped on a usage limit without a verdict; it supplies no +acceptance evidence. The replacement used the available explicit gpt-6.1-sol model with a fresh +context. It independently reconstructed the full host, seven policies, eleven setters and native +inputs/corpus, rehashed all 73 pins and 522 prior outputs, and checked resources, IO and queue records. +It inspected the owner logs without rerunning tests, builds, product processes or UI. + +The reviewer found no actionable defect and supports the stacked draft and qualified local result. +Every broader qualification it set aside is recorded with an executor ruling and cost in the ledger. +No product, managed test, fixture case, pin or runtime output changed after that review. + ## Pending delivery gates -Fresh whole-branch review, stacked draft/exact final-head checks, actual PR Project fields -and immediate six-criterion local acceptance remain pending at this evidence checkpoint. +Stacked draft/exact final-head checks, actual PR Project fields and immediate six-criterion local +acceptance remain pending at this evidence checkpoint. The issue's later acceptance record is +authoritative for delivery. Refs #14 and Refs #225. Parent #13/#14/#15 and draft #216/#218/#220/#222/#224 remain open/unmerged. Full Page/XAML, image visuals, queue delivery, real operating routes, runtime GC collection, installed product, G1, integration and release remain separate. Retain every ref, workspace, From 9c24c8a393ce91799a377dc96f7a3020aca8ed52 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:46:09 +0300 Subject: [PATCH 26/31] Record the stack-through-227 integration plan for issue 14 The new plan defines an aggregate integration path from current main through the frozen PR 227 ancestry. The document preserves published branch heads, later pull request bases, foreign worktrees, and existing product behavior. The plan separates candidate creation, source qualification, native boundary checks, publication, review, integration, and issue acceptance. The verification scope includes managed tests, GUI compilation, contract comparisons, governance checks, and independently reviewed runtime evidence. The document assigns broader G1 reconciliation and integrated native coverage to their existing issues. The completed checklist item records the documented Project fields and ownership readback. The remaining checklist items stay pending, so the plan does not report candidate testing, publication, integration, or acceptance as complete. The governance inventory now identifies the plan as an English ASD-STE100 document. The inventory entry states that current-main behavior and published ancestry require preservation while the original issue 14 criteria receive fresh verification. Changed files: - "docs/governance/document-inventory.json" (+10/-0 lines). - "docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md" (+64/-0 lines). The file counts compare the staged tree with its first parent. Refs: #14 Staged-Tree: 4eca912e49372b0f71640200920537d4bca6d171 --- docs/governance/document-inventory.json | 10 +++ ...1-12-class-stack-through227-integration.md | 64 +++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index d73bdb6b..2d5fb561 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1215,6 +1215,16 @@ "policy": "ASD-STE100 principles for English", "language": "en", "changes": "Record JSON localization implementation, exception recovery requirements, and open delivery acceptance boundaries." + }, + { + "path": "docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md", + "firstIntroduction": "Current stack-through227 integration plan; issue14", + "first_commit": null, + "first_author": "lumenpearson", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Preserve published ancestry and current-main behavior; verify original issue14 criteria before integration and acceptance." } ], "current_history_base": "7ead95f7756057f67cd113671a7f84cf422e8d32", diff --git a/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md b/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md new file mode 100644 index 00000000..79b82a14 --- /dev/null +++ b/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md @@ -0,0 +1,64 @@ +# Stack through PR 227 integration implementation plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Execute in the owning session and obtain fresh independent review before integration. + +**Goal:** Integrate the accepted decomposition ancestry through PR 227 into current main, preserve upstream changes and foreign work, and accept issue 14 only when every original criterion has current evidence. + +**Architecture:** Create dev/class-stack-integration in the existing clean owner-controlled future-task-issues worktree from current main. Use a normal merge of the frozen PR 227 tip; its five parent PR heads remain ancestors and all published branch refs stay fixed. Publish one aggregate integration PR. Keep original issue criteria and G1/G3 boundaries intact. + +**Tech Stack:** Git, C#/WinUI 3/.NET 8, xUnit, Python, PowerShell 7, GitHub REST and authenticated Project 7 browser. + +**Spec:** Issue 14, including its preserved original five acceptance criteria and the additive execution contract https://github.com/lumenpearson/cdpiui/issues/14#issuecomment-6806632312; docs/task-lifecycle.md and docs/delivery-gates.md. + +## Global constraints + +- Execution owner: chat 01a1c5f4-bad8-7310-bafb-1bcf792172a9; only its existing future-task-issues checkout may change. +- Freeze initial main 21555a29ce9fba98c678c445d04ee9f6ce3c85ba and stack tip 3afa82e3f4947ce4bef38b14d86c642c93ddbe90. Re-read remote state before publication and merge. +- Preserve all six published stack heads, later PR 230/231 bases, foreign worktrees, source, index, output, and evidence. No rebase, force push, deletion or automatic retarget. +- Preserve all main changes including PR 229 language captions. No new product feature or dependency version is part of this integration. +- Respect exclusive UI ownership for browser reads, native launches and snapshots. Coordinate heavy builds separately. +- Issue 13 keeps historical G1 reconciliation. Issue 15 keeps the broader integrated native matrix. A bounded hidden fixture does not prove real picker, full startup, installed-product or release acceptance. +- Historical results apply only to their named pins. Final-head checks, independent review and integrated revision require fresh readback. + +## Review focus + +- A clean Git merge can still omit main test links or duplicate Compile items; compare XML items and execute localization plus decomposition tests together. +- Old decomposition App ownership must preserve main startup readiness, security, localization, persisted and pipe contracts; compare current-main source and compiled public shapes. +- Synchronous observers, live collection reads, duplicate assignment, identity and cancellation must retain order and reentry behavior; execute the existing focused tests and complete suite on the candidate. +- Reusing a fixture can silently reuse old binaries or verdicts; use a new candidate archive/output, complete source/cut manifest, resource and binary hashes, and new reviewed runtime evidence. +- Original PR state is separate from commit reachability; inspect actual GitHub merged fields and Project state after aggregate integration, without advancing frozen base refs. + +### Task 1: Establish a reviewable candidate + +Files: create this plan under docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md; update docs/governance/document-inventory.json; merge existing product/test/document paths without unrelated edits. + +Interfaces: frozen main and PR 227 ancestry -> candidate tree and unchanged published-ref inventory. + +- [x] Read back actual issue 14 Project fields and ownership before source work. Grant169 fresh reload: In progress/P2/Architecture/Medium/G2/lumenpearson; canonical labels match. +- [ ] Recheck own clean branch/HEAD and published refs; create dev/class-stack-integration from current main without moving the old branch. +- [ ] Save this plan and its inventory entry, then merge frozen 227 with a detailed exact-inventory commit message and Refs #14. +- [ ] Verify all six heads are ancestors, all newer main paths are preserved, no deleted upstream input or duplicate test Compile item exists, and policy remains current. + +### Task 2: Qualify current source and native boundaries + +Files: owner-controlled evidence directory; create docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md plus inventory entry when fresh results exist. Existing tests: CDPIUI.Tests, especially UI/LanguageSelectModelTests.cs and Presentation cases. + +Interfaces: candidate SHA -> current managed/API/native evidence, with original issue criterion mapping. + +- [ ] Run baseline/current source and compiled contract comparison against current main. Preserve prior G1 limitations rather than relabel them as new integration loss. +- [ ] Restore and run Release focused presentation/localization tests and the complete suite serially. Build the normal Release/x64 GUI with the documented empty Secret stub. Record exact results and named SHA. +- [ ] Run policy/governance and appropriate secret/security checks. Attribute CI-only packaging checks to exact PR HEAD. +- [ ] Prepare a new archive and output for the bounded 178-case union, inspect every fixture modification and resource, obtain independent prelaunch review and an explicit UI grant, execute once and retain source/binary/IO/process proof. +- [ ] Map all five original issue criteria to actual evidence. Execute additional changed native dialog cancellation/file identity/shutdown scenarios where needed; never infer them from source inspection or inert adapters. Leave issue 14 open if any required boundary remains unverified. + +### Task 3: Publish, review, integrate and accept + +Files: report/inventory and GitHub issue/PR/Project metadata. + +Interfaces: complete candidate evidence -> independently reviewed final PR HEAD, actual main integration and honest issue state. + +- [ ] Publish one aggregate draft PR against current main with Refs #14 and full metadata. Attach it to this chat and read actual Project fields. +- [ ] Obtain fresh independent whole-change review, resolve findings and rerun affected checks; keep source and documentation pins explicit. +- [ ] Verify all required checks on final HEAD and current main compatibility. Merge normally only after scoped review and native gates pass; preserve all original refs. +- [ ] Read back integrated SHA, ancestry, original PR states and post-integration checks. Record pending acceptance boundaries if any. +- [ ] If all original issue criteria pass, post the six-section case-specific acceptance record, mark verified items, close completed and set actual Project Done in the same turn, then read back both. Otherwise retain the accurate working state and concrete remaining checks. From bcafcfb93ee28da9a0e1cf0cb5177189b48dc372 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 12 Nov 2026 01:21:01 +0300 Subject: [PATCH 27/31] Record current verification of the stack integration candidate The current report records the named source revision, managed test results, normal GUI compilation and bounded public contract comparisons. Actual Project fields and their exclusive browser grants are recorded separately from CI metadata. The original baseline preparation failure and its documented resolution remain visible. The historical composition records now point to the current integration plan. Their original evidence and limits remain intact. The new delivery decision preserves the separate G1 and broader native acceptance work. Current source review found no material product issue, while native execution and main integration remain outstanding. The report describes two prepared native fixtures and their reviewed source corrections, build results and blocked launch state. This documentation commit changes no product or test source. Required checks must be read on its final HEAD before any acceptance claim. Changed files: - "docs/DECOMPOSITION-ACCEPTANCE.ru.md" (+2/-1 lines). - "docs/DECOMPOSITION-DECISIONS.ru.md" (+2/-1 lines). - "docs/DECOMPOSITION-REVIEW-MAP.ru.md" (+2/-1 lines). - "docs/DECOMPOSITION-STATUS.ru.md" (+2/-1 lines). - "docs/governance/document-inventory.json" (+10/-0 lines). - "docs/superpowers/plans/2026-11-11-class-integration.md" (+3/-0 lines). - "docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md" (+8/-6 lines). - "docs/superpowers/reports/2026-11-11-class-integration-source.md" (+3/-0 lines). - "docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md" (+94/-0 lines). - "docs/superpowers/specs/2026-11-11-class-integration-design.md" (+3/-0 lines). The file counts compare the staged tree with its first parent. Refs: #14 Staged-Tree: 8f72bc64dbf80c208f1faedea70c93903413f21b --- docs/DECOMPOSITION-ACCEPTANCE.ru.md | 3 +- docs/DECOMPOSITION-DECISIONS.ru.md | 3 +- docs/DECOMPOSITION-REVIEW-MAP.ru.md | 3 +- docs/DECOMPOSITION-STATUS.ru.md | 3 +- docs/governance/document-inventory.json | 10 ++ .../plans/2026-11-11-class-integration.md | 3 + ...1-12-class-stack-through227-integration.md | 14 +-- .../2026-11-11-class-integration-source.md | 3 + ...1-12-class-stack-through227-integration.md | 94 +++++++++++++++++++ .../2026-11-11-class-integration-design.md | 3 + 10 files changed, 129 insertions(+), 10 deletions(-) create mode 100644 docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md diff --git a/docs/DECOMPOSITION-ACCEPTANCE.ru.md b/docs/DECOMPOSITION-ACCEPTANCE.ru.md index e7354561..31ea516f 100644 --- a/docs/DECOMPOSITION-ACCEPTANCE.ru.md +++ b/docs/DECOMPOSITION-ACCEPTANCE.ru.md @@ -1,5 +1,6 @@ > Historical local-stage record for frozen dev/audit-class-decomposition at eebc7e8. -> Current integration work is tracked in [the integration plan](superpowers/plans/2026-11-11-class-integration.md). +> The previous local composition is tracked in [its historical plan](superpowers/plans/2026-11-11-class-integration.md). +> Current stack-through227 integration and its original acceptance gates are tracked in [the current plan](superpowers/plans/2026-11-12-class-stack-through227-integration.md). # Приёмочная сводка декомпозиции, 9 ноября 2026 diff --git a/docs/DECOMPOSITION-DECISIONS.ru.md b/docs/DECOMPOSITION-DECISIONS.ru.md index 9ea424da..825b5456 100644 --- a/docs/DECOMPOSITION-DECISIONS.ru.md +++ b/docs/DECOMPOSITION-DECISIONS.ru.md @@ -1,5 +1,6 @@ > Historical local-stage record for frozen dev/audit-class-decomposition at eebc7e8. -> Current integration work is tracked in [the integration plan](superpowers/plans/2026-11-11-class-integration.md). +> The previous local composition is tracked in [its historical plan](superpowers/plans/2026-11-11-class-integration.md). +> Current stack-through227 integration and its original acceptance gates are tracked in [the current plan](superpowers/plans/2026-11-12-class-stack-through227-integration.md). # Решения и отложенные замечания декомпозиции diff --git a/docs/DECOMPOSITION-REVIEW-MAP.ru.md b/docs/DECOMPOSITION-REVIEW-MAP.ru.md index 0a28259c..3919bcef 100644 --- a/docs/DECOMPOSITION-REVIEW-MAP.ru.md +++ b/docs/DECOMPOSITION-REVIEW-MAP.ru.md @@ -1,5 +1,6 @@ > Historical local-stage record for frozen dev/audit-class-decomposition at eebc7e8. -> Current integration work is tracked in [the integration plan](superpowers/plans/2026-11-11-class-integration.md). +> The previous local composition is tracked in [its historical plan](superpowers/plans/2026-11-11-class-integration.md). +> Current stack-through227 integration and its original acceptance gates are tracked in [the current plan](superpowers/plans/2026-11-12-class-stack-through227-integration.md). # Карта приёмки декомпозиции diff --git a/docs/DECOMPOSITION-STATUS.ru.md b/docs/DECOMPOSITION-STATUS.ru.md index 925c5c85..ec18221c 100644 --- a/docs/DECOMPOSITION-STATUS.ru.md +++ b/docs/DECOMPOSITION-STATUS.ru.md @@ -1,5 +1,6 @@ > Historical local-stage record for frozen dev/audit-class-decomposition at eebc7e8. -> Current integration work is tracked in [the integration plan](superpowers/plans/2026-11-11-class-integration.md). +> The previous local composition is tracked in [its historical plan](superpowers/plans/2026-11-11-class-integration.md). +> Current stack-through227 integration and its original acceptance gates are tracked in [the current plan](superpowers/plans/2026-11-12-class-stack-through227-integration.md). # Декомпозиция крупных классов diff --git a/docs/governance/document-inventory.json b/docs/governance/document-inventory.json index cc84dda7..c993e09a 100644 --- a/docs/governance/document-inventory.json +++ b/docs/governance/document-inventory.json @@ -1585,6 +1585,16 @@ "policy": "ASD-STE100 principles for English", "language": "en", "changes": "Preserve published ancestry and current-main behavior; verify original issue14 criteria before integration and acceptance." + }, + { + "path": "docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md", + "firstIntroduction": "Current stack-through227 verification; issue14 and PR233", + "first_commit": null, + "first_author": "lumenpearson", + "upstream_path_present": false, + "policy": "ASD-STE100 principles for English", + "language": "en", + "changes": "Current source/managed/API/Project evidence, historical-stage framing and remaining native/integration acceptance." } ], "current_history_base": "7ead95f7756057f67cd113671a7f84cf422e8d32", diff --git a/docs/superpowers/plans/2026-11-11-class-integration.md b/docs/superpowers/plans/2026-11-11-class-integration.md index 0585a23e..38d0579b 100644 --- a/docs/superpowers/plans/2026-11-11-class-integration.md +++ b/docs/superpowers/plans/2026-11-11-class-integration.md @@ -1,3 +1,6 @@ +> Historical local-composition record. The maintainer's later integration request supersedes this stage's local/draft-only delivery boundary. +> The [current integration plan](2026-11-12-class-stack-through227-integration.md) preserves the original issue14 criteria and separate G1/G3 acceptance. Original pins, results and limits below remain historical. + # Class decomposition integration implementation plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Keep implementation inline and obtain one fresh final whole-change review. diff --git a/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md b/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md index 79b82a14..268dd4ea 100644 --- a/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md +++ b/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md @@ -10,6 +10,8 @@ **Spec:** Issue 14, including its preserved original five acceptance criteria and the additive execution contract https://github.com/lumenpearson/cdpiui/issues/14#issuecomment-6806632312; docs/task-lifecycle.md and docs/delivery-gates.md. +Current verification: [integration report](../reports/2026-11-12-class-stack-through227-integration.md). This supersedes only the earlier executor-defined local/draft-only delivery boundary; issue13 and all original issue14 criteria remain intact. + ## Global constraints - Execution owner: chat 01a1c5f4-bad8-7310-bafb-1bcf792172a9; only its existing future-task-issues checkout may change. @@ -35,9 +37,9 @@ Files: create this plan under docs/superpowers/plans/2026-11-12-class-stack-thro Interfaces: frozen main and PR 227 ancestry -> candidate tree and unchanged published-ref inventory. - [x] Read back actual issue 14 Project fields and ownership before source work. Grant169 fresh reload: In progress/P2/Architecture/Medium/G2/lumenpearson; canonical labels match. -- [ ] Recheck own clean branch/HEAD and published refs; create dev/class-stack-integration from current main without moving the old branch. -- [ ] Save this plan and its inventory entry, then merge frozen 227 with a detailed exact-inventory commit message and Refs #14. -- [ ] Verify all six heads are ancestors, all newer main paths are preserved, no deleted upstream input or duplicate test Compile item exists, and policy remains current. +- [x] Recheck own clean branch/HEAD and published refs; create dev/class-stack-integration from current main without moving the old branch. +- [x] Save this plan and its inventory entry, then merge frozen 227 with a detailed exact-inventory commit message and Refs #14. +- [x] Verify all six heads are ancestors, all newer main paths are preserved, no deleted upstream input or duplicate test Compile item exists, and policy remains current. ### Task 2: Qualify current source and native boundaries @@ -45,8 +47,8 @@ Files: owner-controlled evidence directory; create docs/superpowers/reports/2026 Interfaces: candidate SHA -> current managed/API/native evidence, with original issue criterion mapping. -- [ ] Run baseline/current source and compiled contract comparison against current main. Preserve prior G1 limitations rather than relabel them as new integration loss. -- [ ] Restore and run Release focused presentation/localization tests and the complete suite serially. Build the normal Release/x64 GUI with the documented empty Secret stub. Record exact results and named SHA. +- [x] Run baseline/current source and compiled contract comparison against current main. Preserve prior G1 limitations rather than relabel them as new integration loss. +- [x] Restore and run Release focused presentation/localization tests and the complete suite serially. Build the normal Release/x64 GUI with the documented empty Secret stub. Record exact results and named SHA. - [ ] Run policy/governance and appropriate secret/security checks. Attribute CI-only packaging checks to exact PR HEAD. - [ ] Prepare a new archive and output for the bounded 178-case union, inspect every fixture modification and resource, obtain independent prelaunch review and an explicit UI grant, execute once and retain source/binary/IO/process proof. - [ ] Map all five original issue criteria to actual evidence. Execute additional changed native dialog cancellation/file identity/shutdown scenarios where needed; never infer them from source inspection or inert adapters. Leave issue 14 open if any required boundary remains unverified. @@ -57,7 +59,7 @@ Files: report/inventory and GitHub issue/PR/Project metadata. Interfaces: complete candidate evidence -> independently reviewed final PR HEAD, actual main integration and honest issue state. -- [ ] Publish one aggregate draft PR against current main with Refs #14 and full metadata. Attach it to this chat and read actual Project fields. +- [x] Publish one aggregate draft PR against current main with Refs #14 and full metadata. Attach it to this chat and read actual Project fields. - [ ] Obtain fresh independent whole-change review, resolve findings and rerun affected checks; keep source and documentation pins explicit. - [ ] Verify all required checks on final HEAD and current main compatibility. Merge normally only after scoped review and native gates pass; preserve all original refs. - [ ] Read back integrated SHA, ancestry, original PR states and post-integration checks. Record pending acceptance boundaries if any. diff --git a/docs/superpowers/reports/2026-11-11-class-integration-source.md b/docs/superpowers/reports/2026-11-11-class-integration-source.md index e12e6a3a..8cd47eec 100644 --- a/docs/superpowers/reports/2026-11-11-class-integration-source.md +++ b/docs/superpowers/reports/2026-11-11-class-integration-source.md @@ -1,3 +1,6 @@ +> Historical local-composition record. The maintainer's later integration request supersedes this stage's local/draft-only delivery boundary. +> The [current integration plan](../plans/2026-11-12-class-stack-through227-integration.md) preserves the original issue14 criteria and separate G1/G3 acceptance. Original pins, results and limits below remain historical. + # Class integration source checkpoint Owner: [issue14](https://github.com/lumenpearson/cdpiui/issues/14), Root, diff --git a/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md b/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md new file mode 100644 index 00000000..0b5817cf --- /dev/null +++ b/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md @@ -0,0 +1,94 @@ +# Stack through PR 227: current integration verification + +Owner: chat `01a1c5f4-bad8-7310-bafb-1bcf792172a9`, issue [14](https://github.com/lumenpearson/cdpiui/issues/14), branch `dev/class-stack-integration`, isolated `C:/Users/lumen/.codex/worktrees/future-task-issues/cdpiui`. + +[Draft PR 233](https://github.com/lumenpearson/cdpiui/pull/233) is the current integration vehicle. **Issue 14 remains open; native acceptance and actual main integration are incomplete.** This report records current source, managed, compiled-contract and preparation evidence. It does not accept the whole issue. + +## Delivery decision and preserved history + +The maintainer explicitly requested integration of the stack through PR 227. This supersedes the prior executor-defined local/draft-only publication boundary in the historical 2026-11-11 class-integration plan, design and source report. Those records retain their original pins, results and limits. [The additive issue decision and independent boundary review](https://github.com/lumenpearson/cdpiui/issues/14#issuecomment-6806815231) explain the current boundary. + +Issue 13 and PR 10 retain historical G1 reconciliation. The one older GUI optional-default difference and three Core expected-hash signature differences predate this integration. Current-main preservation is required; it is not G1 acceptance or adoption of that older branch. The delivery gates permit G2 alongside G1. Issue 15 retains broader integrated native/real-picker/startup scenarios and does not close with this source stage. + +## Candidate and provenance + +- Current main: `21555a29ce9fba98c678c445d04ee9f6ce3c85ba`. +- Plan-only first parent: `9c24c8a393ce91799a377dc96f7a3020aca8ed52`. +- Normal merge/product candidate: `e417d4efef05c47393bde549c301cb519577d9bc`. +- Stack tip: `3afa82e3f4947ce4bef38b14d86c642c93ddbe90`. + +All six published heads are retained as ancestors: PR 216 `36235846fb116acad49b328b29120afa92714712`, PR 218 `3da11cb098d3e1241b2a86cd86ee0c14d80b1942`, PR 220 `3c7f8961477dbff0b4b021493b629ba1a1a0fa05`, PR 222 `b627a0f62dace8dde20ca2574a9d28646f71b421`, PR 224 `12ef689e0968bd7ff4b27cee0fe7af02091286da` and PR 227 at the tip above. Their published refs were preserved. Later PR 230/231 work and foreign checkouts were not merged, retargeted or modified. + +The product/test tree matches the clean read-only merge probe `525418989453cf9ce76edd030102a76972a5fd79`. Its only initial differences were the new plan and inventory entry. The inventory append was the only conflict; all 129 main and 165 stack records remain, with the one new plan record. No product correction was needed. All 16 main test-project items remain; all 130 explicit Compile includes exist without duplicates. All five nonproject PR 229 blobs remain exact. Tray, elevated launcher, Shared, installer, Update, EditHostFile, dependency versions, package sources and workflows remain current-main content. + +The state-owner map is in the historical decomposition decisions, accepted per-owner reports and the current source. The aggregate retains the focused editor/document/resource owners, App activation/window/modal/close/idle composition, BlockCheck2 state/result/manual-test/presentation/navigation owners, CreateConfig owners, stateless Core projection and Store download presentation owner. Review checked live reads, collection identity, notification order, cancellation ownership, callback/await sequencing, reentry and partial-failure behavior; no new duplicate domain rule was found. + +## Fresh commands and results + +Environment: Windows x64, .NET SDK 8.0.427. The managed runs and GUI build use separate platform outputs. Their Core DLL hashes must not be treated as identical. + +| Command or check | Current result | +|---|---| +| Pristine main archive: `dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release -m:1` | 747/747 actual tests passed; zero failed/skipped; 10 seconds test duration | +| Pristine main: `dotnet build CDPIUI/CDPIUI.csproj -c Release -p:Platform=x64 -m:1` | 0 warnings/errors; 69.85 seconds | +| Candidate focused command below | 1845/1845 passed; zero failed/skipped; 416 ms test duration | +| Candidate full: `dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release --no-restore -m:1` | 2590/2590 passed; zero failed/skipped; 10 seconds test duration | +| Candidate normal GUI: `dotnet build CDPIUI/CDPIUI.csproj -c Release -p:Platform=x64 -m:1` | 0 warnings/errors; 65.83 seconds | +| `python .github/scripts/check_governance.py` on e417 | 166 Markdown documents; 0 errors | +| `python -m unittest discover -s .github/scripts/tests -v` | 32/32 passed | + +The focused command was: + +```text +dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release -m:1 --filter "FullyQualifiedName~CDPIUI.Tests.Presentation|FullyQualifiedName~LanguageSelectModelTests|FullyQualifiedName~ConfigurationVariableProjectionTests" +``` + +Every baseline test display name remains in the full candidate results. Every focused name is also present in that full run. Unique TRX directories preserve each scope separately. + +Source syntax inventory retains all 451 original GUI exported types across 520 to 621 Git C# inputs, and all 88 Core types across 102 to 103 inputs. No compared original signature was removed or changed. The prospective-tree API inputs were independently matched to Git blobs; the candidate product tree is identical to that probe. + +Fresh compiled comparison against the pristine main binaries retains all 452 GUI and 88 Core exported types with zero lost recorded shapes. Seven added GUI shapes are the already reviewed internal interface declarations on retained facades/storage; Core has no added shape. This metadata surface excludes full annotation, attribute, forwarding and native ABI guarantees. Tests execute the Release/AnyCPU Core output; GUI/API comparison uses Release/x64. + +Normal candidate GUI SHA256: `677497652039bf69a93e600b10d1de23b914d335631334e2a3271fe2a21c55d3`. Normal GUI Core SHA256: `c54b8c8d8195ce602e58ec300c9da58124675a82279ea9bc2e25fe61f0a734f0`. The proof records the four separate baseline/candidate binaries and analyzer hash. + +The initial baseline attempt in the new checkout failed before tests with CS0234 because the documented empty Secret template had not been generated. The standard script created it; exact comparison with its empty template passed. The first failed log remains. No credential, product fix or staged secret was introduced. The successful pristine archive baseline is the separate result above. + +## Independent review and CI + +Fresh read-only reviewer `/root/class_stack_integration_review` examined base21555 to e417, the substantive product families and high-risk tests, source/metadata inputs, binary hashes and all three TRX result sets. Verdict: **0 Critical, 0 Important, 0 Minor product findings** at e417. The reviewer did not rerun tests or launch software. The verdict is not merge readiness: final documentation, native and integration gates remain open. + +Required checks on e417 were read as successful: CodeQL, Contribution metadata, Analyze csharp, Analyze python, governance, gui, libraries, secrets and tools. Both push/PR executions may appear on that SHA. An initial metadata event before complete PR metadata failed; later events after labels/owner/G2 passed. New documentation commits require their own final-head readback. CI packaging/build results are not installed-product acceptance. + +## Actual Project metadata and UI ownership + +Issue 14 was opened and reloaded under grant169: In progress / P2 / Architecture / Medium / G2 / lumenpearson, with type:refactor and area:architecture. No field correction was necessary. A pre-UI participant-mapping guard stopped before navigation; the sole coordinator corrected the mapping and retained both records before the successful readback. + +The auto-added PR 233 card initially had Inbox and empty Priority/Area/Risk. Under fresh grant175, only that card was set to In progress / P2 / Architecture / Medium. Reload/AX/cell readback confirmed G2, lumenpearson and both canonical labels. JSON and JPG receipts were saved. Only the owner-created temporary tabs were closed. Requests were marked complete/idle; this owner never wrote owner.json. The coordinator controls grants and releases. Private Project fields are not inferred from Actions metadata checks. + +## Prepared native checks: no current execution + +Two fresh archives of e417 contain 1606 tracked inputs each. Host has 38 declared extras, shutdown 39. Each has exactly 21 reviewed boundary files. All original cut-file inputs match the historical accepted source. The 36 accepted bootstrap files are retained; the main has exactly three declared identity changes: own root, current PIN and log basename. + +The fresh host preserves the canonical 178 groups. The shutdown fixture uses two plain no-content owned Window types, actual App registration and CloseWindow/Closed delivery, uncut close-handler/coordinator/cleanup/Low dispatcher/idle forwarding, and an observational wrapper that records state before calling real Application.Exit. It requires a first-close Low FIFO barrier, retained sentinel identity, final empty original registry and exactly one validated real-exit marker. It has no successful unconditional exit fallback. Theme/titlebar behavior and active modal restoration are outside this tail. + +The source review caught two Important fixture issues before compilation: old root/PIN literals and a no-longer-isolated theme/logger path caused by Grid content. Both were corrected; previous source/manifests are retained. A preparation-script quoting error stopped before file writes and was corrected. These are fixture preparation records, not product regressions. + +Builds: host had 0 warnings/errors in 74.59 seconds; shutdown had 0 warnings/errors in 59.45 seconds. Post-build source hashes and input sets match. Each artifact baseline has 522 files, embedded asInvoker/uiAccess=false, 20 packaged resource dictionaries matching generated bytes and 5206 values matching source JSON. Five offline tail-parser negative controls reject missing, duplicate or premature exit evidence, incomplete cleanup and failure mixed with success. The positive control passes. Optimized Python is rejected. + +The native helper requires a fresh direct human native-resume record, a matching new coordinator grant, all other UI participants paused and the reviewed bundle hash. It writes no queue-owner file. The native user hold is still blocked. A run-mode negative control was rejected before preflight or launch. Read-only preflight passes for both packages. **Native application launches in this case: zero.** Final prelaunch review remains pending. + +Exact unchanged ConfigMaker/BlockCheck/CreateConfig picker endpoints and view interfaces, combined with controlled-response host tests, justify G2 source-preservation coverage of unchanged picker implementations. They do not prove real picker Cancel. Issue 15 retains real picker, second selection, missing-resource replacement and full integrated scenarios. + +## Original acceptance and next evidence + +| Original issue 14 criterion | Current assessment | +|---|---| +| Document state/collection/subscription/cancellation/lifecycle ownership | Supported by current source and ownership records; this report needs final delta review | +| Preserve public/stored/pipe/order/identity/reentry contracts | Supported within source, tests and bounded metadata checks; no full ABI claim | +| One implementation; focused/full tests pass | Verified on e417 within the reviewed scope | +| Changed native, cancellation, file identity and orderly shutdown | Incomplete: fresh178 and real close-tail execution/postchecks required | +| Reviewed publication, final-head CI and actual integration | Draft published; e417 source/CI verified; final docs/native/main integration remain | + +No issue checklist is declared fully accepted by this report. After approved native execution, record all results and limits, review the final report delta and final PR HEAD checks, integrate normally, and read back the resulting main revision and original PR dispositions. Close issue14 completed and set actual Done immediately only when every original criterion passes. Keep13/15 and later local-stage goals separate. + +Raw artifacts are retained in the owner-controlled common Git evidence directory `task-policy-rollout-2026-11-10/issue14-stack-through227/`: original/current API snapshots, source/tree/XML proofs, unique logs/TRX, compiled inventories/hashes, Project169/175 JSON/JPG, native source/build/resource/pin manifests, R1 correction snapshots, offline controls and the blocked prelaunch package. Evidence was not copied into another session's outputs. diff --git a/docs/superpowers/specs/2026-11-11-class-integration-design.md b/docs/superpowers/specs/2026-11-11-class-integration-design.md index b27856ec..58a399bb 100644 --- a/docs/superpowers/specs/2026-11-11-class-integration-design.md +++ b/docs/superpowers/specs/2026-11-11-class-integration-design.md @@ -1,3 +1,6 @@ +> Historical local-composition record. The maintainer's later integration request supersedes this stage's local/draft-only delivery boundary. +> The [current integration plan](../plans/2026-11-12-class-stack-through227-integration.md) preserves the original issue14 criteria and separate G1/G3 acceptance. Original pins, results and limits below remain historical. + # Accepted class decomposition integration Owner: Root under [issue14](https://github.com/lumenpearson/cdpiui/issues/14). Existing Project 7 From 44f6cab4f9a247aa8066ad3650f13235dfcfc114 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 12 Nov 2026 01:21:49 +0300 Subject: [PATCH 28/31] Record independent readiness of the bounded native verification package The verification report now records the independent source and artifact review of both prepared native fixtures. The reviewer checked their complete source manifests, actual binaries, embedded privilege declarations, localization resources and guarded launcher. The recorded verdict is conditional technical readiness for one exact bundle hash. The native hold remains blocked because the current user permission covers Project browser work. A new direct native resume and matching coordinator grant are still required. No runtime result or issue acceptance follows from this review. The report also preserves the rule that a failed host run prevents the shutdown tail and any automatic retry. This commit changes only verification documentation. Product source, tests, the compiled candidate and the reviewed native package remain unchanged. The final documentation delta and required checks need their own current HEAD readback before integration. Changed files: - "docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md" (+1/-1 lines). The file counts compare the staged tree with its first parent. Refs: #14 Staged-Tree: fff1d92f0b4a4006fa7915cb389829c8fe08c60c --- .../reports/2026-11-12-class-stack-through227-integration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md b/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md index 0b5817cf..124a4f8f 100644 --- a/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md +++ b/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md @@ -75,7 +75,7 @@ The source review caught two Important fixture issues before compilation: old ro Builds: host had 0 warnings/errors in 74.59 seconds; shutdown had 0 warnings/errors in 59.45 seconds. Post-build source hashes and input sets match. Each artifact baseline has 522 files, embedded asInvoker/uiAccess=false, 20 packaged resource dictionaries matching generated bytes and 5206 values matching source JSON. Five offline tail-parser negative controls reject missing, duplicate or premature exit evidence, incomplete cleanup and failure mixed with success. The positive control passes. Optimized Python is rejected. -The native helper requires a fresh direct human native-resume record, a matching new coordinator grant, all other UI participants paused and the reviewed bundle hash. It writes no queue-owner file. The native user hold is still blocked. A run-mode negative control was rejected before preflight or launch. Read-only preflight passes for both packages. **Native application launches in this case: zero.** Final prelaunch review remains pending. +The native helper requires a fresh direct human native-resume record, a matching new coordinator grant, all other UI participants paused and the reviewed bundle hash. It writes no queue-owner file. The native user hold is still blocked. A run-mode negative control was rejected before preflight or launch. Read-only preflight passes for both packages. **Native application launches in this case: zero.** Independent reviewer `/root/issue14_acceptance_boundary_review` completed the source correction review and final artifact/runner review: **conditional technical PRELAUNCH READY, 0 Critical / 0 Important / 0 Minor**, for bundle `9519CAB19265829F0D1568B14C99C4789B7EF6A8F8C29F28AF730A151C26CF48`. The reviewer independently recomputed helper/manifest/binary hashes, parsed both embedded privilege manifests and compared all resource entries. This is not permission or runtime acceptance. A new direct human native-resume instruction and fresh matching coordinator grant are still required. If the host fails, the shutdown tail must not start; no automatic retry is allowed. Exact unchanged ConfigMaker/BlockCheck/CreateConfig picker endpoints and view interfaces, combined with controlled-response host tests, justify G2 source-preservation coverage of unchanged picker implementations. They do not prove real picker Cancel. Issue 15 retains real picker, second selection, missing-resource replacement and full integrated scenarios. From 6f59b2f0a2e2ec5a9471f13f823b838b26f7ec48 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:13:26 +0300 Subject: [PATCH 29/31] Record the stopped issue 14 native qualification The first approved host process returned exit code one under exclusive grant 189. The runner created three action inputs before launch. The unchanged fixture then opened the same filenames with FileMode.CreateNew and failed on the first collision after twelve partial assertion groups. The shutdown fixture did not run, and the batch had no retries. The report preserves the failure, the reviewed package identity and the successful read-only preservation checks. The plan retains the native and integration gates as incomplete. Both independent reviewers confirmed the failed checkpoint, and the documentation review has no unresolved findings. Governance validation checked 167 Markdown files with zero errors. No product, fixture or helper correction is included. Refs #14 Changed files: - "docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md" (+6/-0 lines). - "docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md" (+23/-5 lines). The file counts compare the staged tree with its first parent. Staged-Tree: 0a50e07aaeab1b4d53e2a8fe43edd1d65b53fa07 --- ...1-12-class-stack-through227-integration.md | 6 ++++ ...1-12-class-stack-through227-integration.md | 28 +++++++++++++++---- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md b/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md index 268dd4ea..42d8788d 100644 --- a/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md +++ b/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md @@ -64,3 +64,9 @@ Interfaces: complete candidate evidence -> independently reviewed final PR HEAD, - [ ] Verify all required checks on final HEAD and current main compatibility. Merge normally only after scoped review and native gates pass; preserve all original refs. - [ ] Read back integrated SHA, ancestry, original PR states and post-integration checks. Record pending acceptance boundaries if any. - [ ] If all original issue criteria pass, post the six-section case-specific acceptance record, mark verified items, close completed and set actual Project Done in the same turn, then read back both. Otherwise retain the accurate working state and concrete remaining checks. + +## Stopped native batch: grant189 + +The human approved the two prepared runs with stop-on-first-failure and no retries. The one host launch at product e417 failed: PID85016, exit1, 12 partial PASS groups, then IOException because the runner precreated the three inputs that the host opens with FileMode.CreateNew. The shutdown tail was not launched. No correction, cleanup of evidence or retry occurred. Source/binary/process postchecks and idle189 are retained in the current report. + +Issue14 and draftPR233 remain unaccepted. Native and main integration items stay unchecked. The native hold is blocked again. Any later correction and execution require a fresh explicit human instruction, independent review and a new queue grant; preserve the failed package and foreign work. diff --git a/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md b/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md index 124a4f8f..62deebba 100644 --- a/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md +++ b/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md @@ -2,7 +2,7 @@ Owner: chat `01a1c5f4-bad8-7310-bafb-1bcf792172a9`, issue [14](https://github.com/lumenpearson/cdpiui/issues/14), branch `dev/class-stack-integration`, isolated `C:/Users/lumen/.codex/worktrees/future-task-issues/cdpiui`. -[Draft PR 233](https://github.com/lumenpearson/cdpiui/pull/233) is the current integration vehicle. **Issue 14 remains open; native acceptance and actual main integration are incomplete.** This report records current source, managed, compiled-contract and preparation evidence. It does not accept the whole issue. +[Draft PR 233](https://github.com/lumenpearson/cdpiui/pull/233) is the current integration vehicle. **Issue 14 remains open and blocked: the only approved host run failed under grant189; the shutdown tail was not launched. Native acceptance and actual main integration are incomplete.** This report records current source, managed, compiled-contract and preparation evidence. It does not accept the whole issue. ## Delivery decision and preserved history @@ -65,7 +65,7 @@ Issue 14 was opened and reloaded under grant169: In progress / P2 / Architecture The auto-added PR 233 card initially had Inbox and empty Priority/Area/Risk. Under fresh grant175, only that card was set to In progress / P2 / Architecture / Medium. Reload/AX/cell readback confirmed G2, lumenpearson and both canonical labels. JSON and JPG receipts were saved. Only the owner-created temporary tabs were closed. Requests were marked complete/idle; this owner never wrote owner.json. The coordinator controls grants and releases. Private Project fields are not inferred from Actions metadata checks. -## Prepared native checks: no current execution +## Native preparation and failed first execution Two fresh archives of e417 contain 1606 tracked inputs each. Host has 38 declared extras, shutdown 39. Each has exactly 21 reviewed boundary files. All original cut-file inputs match the historical accepted source. The 36 accepted bootstrap files are retained; the main has exactly three declared identity changes: own root, current PIN and log basename. @@ -75,10 +75,28 @@ The source review caught two Important fixture issues before compilation: old ro Builds: host had 0 warnings/errors in 74.59 seconds; shutdown had 0 warnings/errors in 59.45 seconds. Post-build source hashes and input sets match. Each artifact baseline has 522 files, embedded asInvoker/uiAccess=false, 20 packaged resource dictionaries matching generated bytes and 5206 values matching source JSON. Five offline tail-parser negative controls reject missing, duplicate or premature exit evidence, incomplete cleanup and failure mixed with success. The positive control passes. Optimized Python is rejected. -The native helper requires a fresh direct human native-resume record, a matching new coordinator grant, all other UI participants paused and the reviewed bundle hash. It writes no queue-owner file. The native user hold is still blocked. A run-mode negative control was rejected before preflight or launch. Read-only preflight passes for both packages. **Native application launches in this case: zero.** Independent reviewer `/root/issue14_acceptance_boundary_review` completed the source correction review and final artifact/runner review: **conditional technical PRELAUNCH READY, 0 Critical / 0 Important / 0 Minor**, for bundle `9519CAB19265829F0D1568B14C99C4789B7EF6A8F8C29F28AF730A151C26CF48`. The reviewer independently recomputed helper/manifest/binary hashes, parsed both embedded privilege manifests and compared all resource entries. This is not permission or runtime acceptance. A new direct human native-resume instruction and fresh matching coordinator grant are still required. If the host fails, the shutdown tail must not start; no automatic retry is allowed. +The native helper requires a fresh direct human native-resume record, a matching new coordinator grant, all other UI participants paused and the reviewed bundle hash. It writes no queue-owner file. At the earlier prelaunch checkpoint, the native user hold was blocked. A run-mode negative control was rejected before preflight or launch. Read-only preflight passed for both packages. No native application had launched at that checkpoint. Independent reviewer `/root/issue14_acceptance_boundary_review` completed the source correction review and final artifact/runner review: **conditional technical PRELAUNCH READY, 0 Critical / 0 Important / 0 Minor**, for bundle `9519CAB19265829F0D1568B14C99C4789B7EF6A8F8C29F28AF730A151C26CF48`. The reviewer independently recomputed helper/manifest/binary hashes, parsed both embedded privilege manifests and compared all resource entries. This is not permission or runtime acceptance. The execution rule required a new direct human native-resume instruction and fresh matching coordinator grant. If the host fails, the shutdown tail must not start; no automatic retry is allowed. Exact unchanged ConfigMaker/BlockCheck/CreateConfig picker endpoints and view interfaces, combined with controlled-response host tests, justify G2 source-preservation coverage of unchanged picker implementations. They do not prove real picker Cancel. Issue 15 retains real picker, second selection, missing-resource replacement and full integrated scenarios. +## Failed native attempt under grant189 + +The maintainer explicitly approved the two prepared fixtures in direct user message `01a1ce26-0ab5-7b81-9a54-0bf04e27036a`. Both fresh read-only preflights passed, main and PR HEAD remained unchanged, and the sole coordinator issued matching exclusive grant189. The owner read the live grant, scope, request and paused-participant guards before invoking: + +```text +python native_runner.py --run host +``` + +This was exactly one launch of the owned host executable, PID **85016**. It exited **1** after approximately **0.85 seconds**, with `accepted=false`. The log contains **12 PASS groups**, followed by `System.IO.IOException`: `actions-sites.txt` already exists. These partial groups do not count as a 178-group PASS. + +The runner precreated all three action inputs before process creation. The retained, unchanged `HostSmokeBootstrap.Actions.cs` then called `CreateActionInput`, which opens these same filenames with `FileMode.CreateNew`. The duplicate creation caused the first collision at the sites input. This is a runner/fixture preparation defect missed by prelaunch qualification. The subsequent read-only audit by `/root/issue14_acceptance_boundary_review` independently confirmed this Important orchestration finding and stated that the earlier conditional PRELAUNCH READY verdict was incorrect for host orchestration. The audit independently rehashed both binary sets, all manifest-listed source files, the bundle and normal GUI; it did not rerun anything. This failure does not establish a product regression. No product or fixture correction was made after the failed attempt. + +The batch stopped immediately, as the human required. **No retry and no shutdown-tail launch occurred.** No file was removed or overwritten. The three inputs, FAIL log, empty stdout/stderr and runtime receipt remain intact. Read-only failure postchecks confirmed the exact owned executable has no process, all 522 baseline host files remain unchanged, the unlaunched shutdown directory still exactly matches its 522-file manifest, both 1606-input source/cut manifests match, and the normal GUI binary hash is unchanged. The host output directory gained only the three runner-created inputs and the result log; no golden report outputs were produced. + +Receipts: `native-host-runtime.json`, `native-failure-postcheck189.json`, `human-native-resume-20261112.json`, and queue `issue14-native-idle189.json`. The canonical request is not ready, all owner UI is paused, no call is pending, and the native hold is blocked again. The owner never wrote the queue-owner file. The coordinator alone releases grant189. Foreign worktrees and processes were not touched. + +Unblock condition: the maintainer must explicitly authorize any later correction and new execution after this stop. A later proposal must resolve input-creation ownership in a fresh package, preserve this failed package, obtain independent review and a new exclusive grant. No automatic resume, repaired-package run, main integration, issue closure or Done transition is authorized by the failed attempt. The prior successful source/managed/CI results retain their named revisions; native criterion4 and integration criterion5 remain incomplete. + ## Original acceptance and next evidence | Original issue 14 criterion | Current assessment | @@ -86,8 +104,8 @@ Exact unchanged ConfigMaker/BlockCheck/CreateConfig picker endpoints and view in | Document state/collection/subscription/cancellation/lifecycle ownership | Supported by current source and ownership records; this report needs final delta review | | Preserve public/stored/pipe/order/identity/reentry contracts | Supported within source, tests and bounded metadata checks; no full ABI claim | | One implementation; focused/full tests pass | Verified on e417 within the reviewed scope | -| Changed native, cancellation, file identity and orderly shutdown | Incomplete: fresh178 and real close-tail execution/postchecks required | -| Reviewed publication, final-head CI and actual integration | Draft published; e417 source/CI verified; final docs/native/main integration remain | +| Changed native, cancellation, file identity and orderly shutdown | Incomplete: host failed after12 groups; no retry or real close-tail execution; fresh approved qualification is required | +| Reviewed publication, final-head CI and actual integration | Draft PR233 remains unmerged; source/CI evidence retained; native failure blocks acceptance and main integration | No issue checklist is declared fully accepted by this report. After approved native execution, record all results and limits, review the final report delta and final PR HEAD checks, integrate normally, and read back the resulting main revision and original PR dispositions. Close issue14 completed and set actual Done immediately only when every original criterion passes. Keep13/15 and later local-stage goals separate. From c30d827a52f772bb4c7687d35b684539eb5c302f Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:17:18 +0300 Subject: [PATCH 30/31] Record the accepted R2 native integration evidence The separately authorized R2 batch completed the full host corpus and the actual close sequence on the unchanged product candidate. The host recorded 178 canonical groups and the shutdown trace recorded six ordered events with one actual exit. Both processes exited successfully and retained all pinned inputs, baseline artifacts and allowed output boundaries. The original failed batch remains preserved as a distinct failed result. The report attributes execution to the coordinator and records independent runtime acceptance, hashes, process checks and the actual Project Verification readback. The plan records the completed native qualification while retaining final review, current HEAD checks and integration as delivery gates. Governance validation checked 167 Markdown documents with zero errors. This commit changes no product, test, fixture or operational helper. Refs #14 Changed files: - "docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md" (+9/-3 lines). - "docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md" (+34/-13 lines). The file counts compare the staged tree with its first parent. Staged-Tree: 91f425e44e19db3d9e602232e5ff78624eb0f669 --- ...1-12-class-stack-through227-integration.md | 12 +++-- ...1-12-class-stack-through227-integration.md | 47 ++++++++++++++----- 2 files changed, 43 insertions(+), 16 deletions(-) diff --git a/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md b/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md index 42d8788d..330bff69 100644 --- a/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md +++ b/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md @@ -49,9 +49,9 @@ Interfaces: candidate SHA -> current managed/API/native evidence, with original - [x] Run baseline/current source and compiled contract comparison against current main. Preserve prior G1 limitations rather than relabel them as new integration loss. - [x] Restore and run Release focused presentation/localization tests and the complete suite serially. Build the normal Release/x64 GUI with the documented empty Secret stub. Record exact results and named SHA. -- [ ] Run policy/governance and appropriate secret/security checks. Attribute CI-only packaging checks to exact PR HEAD. -- [ ] Prepare a new archive and output for the bounded 178-case union, inspect every fixture modification and resource, obtain independent prelaunch review and an explicit UI grant, execute once and retain source/binary/IO/process proof. -- [ ] Map all five original issue criteria to actual evidence. Execute additional changed native dialog cancellation/file identity/shutdown scenarios where needed; never infer them from source inspection or inert adapters. Leave issue 14 open if any required boundary remains unverified. +- [x] Run policy/governance and appropriate secret/security checks. Attribute CI-only packaging checks to exact PR HEAD. +- [x] Prepare a new archive and output for the bounded 178-case union, inspect every fixture modification and resource, obtain independent prelaunch review and an explicit UI grant, execute once and retain source/binary/IO/process proof. +- [x] Map all five original issue criteria to actual evidence. Execute additional changed native dialog cancellation/file identity/shutdown scenarios where needed; never infer them from source inspection or inert adapters. Leave issue 14 open if any required boundary remains unverified. ### Task 3: Publish, review, integrate and accept @@ -70,3 +70,9 @@ Interfaces: complete candidate evidence -> independently reviewed final PR HEAD, The human approved the two prepared runs with stop-on-first-failure and no retries. The one host launch at product e417 failed: PID85016, exit1, 12 partial PASS groups, then IOException because the runner precreated the three inputs that the host opens with FileMode.CreateNew. The shutdown tail was not launched. No correction, cleanup of evidence or retry occurred. Source/binary/process postchecks and idle189 are retained in the current report. Issue14 and draftPR233 remain unaccepted. Native and main integration items stay unchecked. The native hold is blocked again. Any later correction and execution require a fresh explicit human instruction, independent review and a new queue grant; preserve the failed package and foreign work. + +## Separately authorized Root R2 checkpoint + +The failed189 series remains frozen. The coordinator prepared a new R2 with fixture-owned input creation, actual-method RED2/7 then GREEN7/7 controls, new source/build/pin roots and independent review. Direct human message01a1ce58-a45a-7f80-8ad3-e9464a7bb6e1 approved the concrete new R2 batch. Grant193 executed one host178 PID96600 and, only after its accepted result, one actual-close tail PID92580; both exited0 and retained all source/binary/IO/process checks, with no retries. Slot released194. The current report records exact hashes, independent attribution and limits. + +This plan is the frozen pre-merge checklist. Final report review, final-HEAD checks, integration and issue/Project acceptance are recorded in issue14 during the same delivery turn. They must not be inferred from this prepared checkpoint. diff --git a/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md b/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md index 62deebba..759a6f69 100644 --- a/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md +++ b/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md @@ -2,7 +2,7 @@ Owner: chat `01a1c5f4-bad8-7310-bafb-1bcf792172a9`, issue [14](https://github.com/lumenpearson/cdpiui/issues/14), branch `dev/class-stack-integration`, isolated `C:/Users/lumen/.codex/worktrees/future-task-issues/cdpiui`. -[Draft PR 233](https://github.com/lumenpearson/cdpiui/pull/233) is the current integration vehicle. **Issue 14 remains open and blocked: the only approved host run failed under grant189; the shutdown tail was not launched. Native acceptance and actual main integration are incomplete.** This report records current source, managed, compiled-contract and preparation evidence. It does not accept the whole issue. +[Draft PR 233](https://github.com/lumenpearson/cdpiui/pull/233) is the current integration vehicle. **This is the frozen pre-merge verification record.** The failed batch189 is preserved below. A separately authorized Root-owned R2 subsequently passed host178 and actual-close shutdown checks under grant193. Final review, final-HEAD CI and actual main integration remain delivery gates; the issue acceptance comment records their later disposition. ## Delivery decision and preserved history @@ -65,6 +65,8 @@ Issue 14 was opened and reloaded under grant169: In progress / P2 / Architecture The auto-added PR 233 card initially had Inbox and empty Priority/Area/Risk. Under fresh grant175, only that card was set to In progress / P2 / Architecture / Medium. Reload/AX/cell readback confirmed G2, lumenpearson and both canonical labels. JSON and JPG receipts were saved. Only the owner-created temporary tabs were closed. Requests were marked complete/idle; this owner never wrote owner.json. The coordinator controls grants and releases. Private Project fields are not inferred from Actions metadata checks. +After the failed189 batch, browser-only grant191 changed both cards to Blocked. After the separately accepted R2, browser-only grant195 restored both to **Verification / P2 / Architecture / Medium / G2 / lumenpearson**, with both canonical labels retained. Each page was reloaded; actual cell values and PNG receipts were saved. Only own tabs28/29 were closed. This is a real private Project readback, not a CI inference. Final Done remains dependent on actual integration and issue acceptance. + ## Native preparation and failed first execution Two fresh archives of e417 contain 1606 tracked inputs each. Host has 38 declared extras, shutdown 39. Each has exactly 21 reviewed boundary files. All original cut-file inputs match the historical accepted source. The 36 accepted bootstrap files are retained; the main has exactly three declared identity changes: own root, current PIN and log basename. @@ -79,7 +81,7 @@ The native helper requires a fresh direct human native-resume record, a matching Exact unchanged ConfigMaker/BlockCheck/CreateConfig picker endpoints and view interfaces, combined with controlled-response host tests, justify G2 source-preservation coverage of unchanged picker implementations. They do not prove real picker Cancel. Issue 15 retains real picker, second selection, missing-resource replacement and full integrated scenarios. -## Failed native attempt under grant189 +## Historical failed native attempt under grant189 The maintainer explicitly approved the two prepared fixtures in direct user message `01a1ce26-0ab5-7b81-9a54-0bf04e27036a`. Both fresh read-only preflights passed, main and PR HEAD remained unchanged, and the sole coordinator issued matching exclusive grant189. The owner read the live grant, scope, request and paused-participant guards before invoking: @@ -89,24 +91,43 @@ python native_runner.py --run host This was exactly one launch of the owned host executable, PID **85016**. It exited **1** after approximately **0.85 seconds**, with `accepted=false`. The log contains **12 PASS groups**, followed by `System.IO.IOException`: `actions-sites.txt` already exists. These partial groups do not count as a 178-group PASS. -The runner precreated all three action inputs before process creation. The retained, unchanged `HostSmokeBootstrap.Actions.cs` then called `CreateActionInput`, which opens these same filenames with `FileMode.CreateNew`. The duplicate creation caused the first collision at the sites input. This is a runner/fixture preparation defect missed by prelaunch qualification. The subsequent read-only audit by `/root/issue14_acceptance_boundary_review` independently confirmed this Important orchestration finding and stated that the earlier conditional PRELAUNCH READY verdict was incorrect for host orchestration. The audit independently rehashed both binary sets, all manifest-listed source files, the bundle and normal GUI; it did not rerun anything. This failure does not establish a product regression. No product or fixture correction was made after the failed attempt. +The runner precreated all three action inputs before process creation. The retained, unchanged `HostSmokeBootstrap.Actions.cs` then called `CreateActionInput`, which opens these same filenames with `FileMode.CreateNew`. The duplicate creation caused the first collision at the sites input. This is a runner/fixture preparation defect missed by prelaunch qualification. The subsequent read-only audit by `/root/issue14_acceptance_boundary_review` independently confirmed this Important orchestration finding and stated that the earlier conditional PRELAUNCH READY verdict was incorrect for host orchestration. The audit independently rehashed both binary sets, all manifest-listed source files, the bundle and normal GUI; it did not rerun anything. This failure does not establish a product regression. No product or fixture correction was made within that stopped batch. The later R2 is a separately owned, reviewed and authorized package. The batch stopped immediately, as the human required. **No retry and no shutdown-tail launch occurred.** No file was removed or overwritten. The three inputs, FAIL log, empty stdout/stderr and runtime receipt remain intact. Read-only failure postchecks confirmed the exact owned executable has no process, all 522 baseline host files remain unchanged, the unlaunched shutdown directory still exactly matches its 522-file manifest, both 1606-input source/cut manifests match, and the normal GUI binary hash is unchanged. The host output directory gained only the three runner-created inputs and the result log; no golden report outputs were produced. -Receipts: `native-host-runtime.json`, `native-failure-postcheck189.json`, `human-native-resume-20261112.json`, and queue `issue14-native-idle189.json`. The canonical request is not ready, all owner UI is paused, no call is pending, and the native hold is blocked again. The owner never wrote the queue-owner file. The coordinator alone releases grant189. Foreign worktrees and processes were not touched. +Receipts: `native-host-runtime.json`, `native-failure-postcheck189.json`, `human-native-resume-20261112.json`, and queue `issue14-native-idle189.json`. The canonical request is not ready, all owner UI is paused, no call is pending, and the native hold is blocked again. The owner never wrote the queue-owner file. The coordinator alone released grant189 as190. Foreign worktrees and processes were not touched. + +The recorded unblock condition required the maintainer to explicitly authorize any later correction and new execution after this stop. A later proposal must resolve input-creation ownership in a fresh package, preserve this failed package, obtain independent review and a new exclusive grant. No automatic resume, repaired-package run, main integration, issue closure or Done transition is authorized by the failed attempt. The prior successful source/managed/CI results retain their named revisions; native criterion4 and integration criterion5 were incomplete at that stopped checkpoint. + +## Separately authorized corrected R2 and runtime results + +Execution owner for R2: coordinator chat `01a1bc96-ea11-73a1-a4a1-5cd6db1617fa`. R2 uses new `F:/cdpiui-verify/class-stack-e417d4e-20261112-root-r2-host` and `-shutdown` roots. Product source remains e417. The failed189 package, its three inputs, FAIL log, helpers and manifests remain immutable. The corrected runner checks that the three inputs are absent and lets the unchanged host create them. A portable managed control uses the actual two C# helper methods and three literal calls: old preparation has2 failing controls out of7; corrected preparation passes7/7. These controls did not run WinUI. + +The R2 host build passed with0 warnings/errors in83.51seconds; shutdown passed with0 warnings/errors in59.03seconds. Each has522 pinned baseline artifacts,1606 tracked inputs,21 declared boundary paths and38/39 extras. Both embedded manifests are asInvoker/uiAccess=false;20 packaged dictionaries and5206 values match generated and source resources. The immutable technical packet has bundle SHA256 `33D32B10E1BFD53EDFDD3EADDD11773062619434DCA956E503E014CCC3F74A58`; its36-input compiled review index is `0F07F238A6FF4E375273AF7DBCF9F8603BD4A5B1C12A9F6EB603A4B8CC09CB3F`. Independent reviewer chat `01a1c049-c090-70c1-bcfe-d38e1e2704fe` qualified that unexecuted packet and then the exact authorized operational-copy delta. + +A new direct human answer, actual message `01a1ce58-a45a-7f80-8ad3-e9464a7bb6e1`, approved the concrete two-run R2 question. The issue owner independently read the actual question/answer context and receipt. This approval is distinct from the stopped189 authorization. After fresh peer pauses and preflights, the coordinator issued native-only grant193. + +| Actual R2 run | Retained result | +|---|---| +| `python native_runner.py --run host` | One launch, PID96600, exit0,178 canonical unique PASS groups in order, COMPLETE, zero FAIL, accepted=true; runtime5.376586seconds | +| `python native_runner.py --run shutdown` | One later launch, PID92580, exit0,6 ordered events and exactly1 actual-exit marker, accepted=true; runtime3.204804seconds | + +The host result includes three exact input byte sequences and two golden export outputs. Its522 baseline file hashes remain unchanged and only the six allowed files were added. The shutdown result has exactly `START → CLOSED_FIRST → FIRST_LOW_BARRIER → CLOSED_LAST → ACTUAL_EXIT → COMPLETE`. It proves original-registry identity, retained first-close sentinel, Low-priority survival barrier, final empty registry and one actual idle-controller exit. Its522 baseline hashes remain unchanged and only its result log was added. Both streams are empty, both owned images are absent, and no retry occurred. The normal GUI, both source manifests, immutable technical inputs and oldfailed189 inputs remain unchanged. The coordinator released the slot as194; all UI remained paused during the CLI-native window. + +Runtime artifacts are retained in the Root-owned `.superpowers/sdd/issue14-native-r2-authorized-01a1ce58` directory, outside the issue owner's checkout. Runtime index SHA256: `5B77093817C9881135901F64F8476500AF6C54618A300E71D611793A2B1D6537`. Post-native proof SHA256: `7EEDFF0AAD0FD0D7B70827D0B4D40A3BF7AD961E5E0878990A3F544823B05B78`. This issue owner independently rehashed all16 indexed artifacts and both522-file baselines, checked exact allowed output sets and read both actual PID-bound logs/receipts. That was read-only inspection of the coordinator's execution, not another native run. Independent full-runtime review was subsequently recorded in [issue14](https://github.com/lumenpearson/cdpiui/issues/14#issuecomment-6816245548): `/root/issue14_acceptance_boundary_review` independently verified all16runtime/36technical/23failed/17operational pins and gives PASS with0Critical/Important/Minor for original criterion4. [The separate peer review](https://github.com/lumenpearson/cdpiui/issues/14#issuecomment-6816247958) also accepts the complete bounded batch with0blocking findings. -Unblock condition: the maintainer must explicitly authorize any later correction and new execution after this stop. A later proposal must resolve input-creation ownership in a fresh package, preserve this failed package, obtain independent review and a new exclusive grant. No automatic resume, repaired-package run, main integration, issue closure or Done transition is authorized by the failed attempt. The prior successful source/managed/CI results retain their named revisions; native criterion4 and integration criterion5 remain incomplete. +This qualifies the stated bounded G2 host and real-close composition. It does not prove real picker interaction, full visual startup, active-modal restoration, installed-product, G1 reconciliation or a release. Exact unchanged picker endpoints plus controlled-response actual-host checks justify source-preservation coverage within G2; issue15 retains the broader real-picker matrix. -## Original acceptance and next evidence +## Original acceptance mapping and delivery boundary -| Original issue 14 criterion | Current assessment | +| Original issue14 criterion | Pre-merge evidence | |---|---| -| Document state/collection/subscription/cancellation/lifecycle ownership | Supported by current source and ownership records; this report needs final delta review | -| Preserve public/stored/pipe/order/identity/reentry contracts | Supported within source, tests and bounded metadata checks; no full ABI claim | -| One implementation; focused/full tests pass | Verified on e417 within the reviewed scope | -| Changed native, cancellation, file identity and orderly shutdown | Incomplete: host failed after12 groups; no retry or real close-tail execution; fresh approved qualification is required | -| Reviewed publication, final-head CI and actual integration | Draft PR233 remains unmerged; source/CI evidence retained; native failure blocks acceptance and main integration | +| Document state/collection/subscription/cancellation/lifecycle ownership | Current owner records and source composition; whole-change review and current report | +| Preserve public/stored/pipe/order/identity/reentry contracts | Current-main source and compiled comparison, preserved paths, focused/full managed tests and bounded native owner checks; no full ABI claim | +| One implementation; focused/full tests pass | Whole-source review0 findings at e417;1845 focused/2590 full, all747 baseline test names retained | +| Changed native, cancellation, file identity and orderly shutdown | Separately authorized R2 host178 plus actual-close6-event tail; source-only justification for unchanged real picker endpoints; larger integrated matrix remains issue15 | +| Reviewed publication, final-head CI and actual integration | Aggregate PR233; final report review and exact final-HEAD check readback required immediately before merge; integrated SHA and original PR dispositions belong to the issue's subsequent acceptance record | -No issue checklist is declared fully accepted by this report. After approved native execution, record all results and limits, review the final report delta and final PR HEAD checks, integrate normally, and read back the resulting main revision and original PR dispositions. Close issue14 completed and set actual Done immediately only when every original criterion passes. Keep13/15 and later local-stage goals separate. +This report does not close the issue or imply a merge. After final independent review and successful required checks on the final PR HEAD, recheck unchanged main compatibility and integrate normally. Read back main reachability, original PR states and post-integration checks. The six original branch refs and later230/232 bases stay fixed; an original PR whose base was not advanced may retain an unmerged state even when its head is contained in main. Do not label a closed unmerged PR as delivered. Issue14 closes completed and actual Project7 becomes Done only when the six-section acceptance record verifies every original criterion. Original checklist copies describe the same five obligations. Issues13/15 and later work retain their own contracts. Raw artifacts are retained in the owner-controlled common Git evidence directory `task-policy-rollout-2026-11-10/issue14-stack-through227/`: original/current API snapshots, source/tree/XML proofs, unique logs/TRX, compiled inventories/hashes, Project169/175 JSON/JPG, native source/build/resource/pin manifests, R1 correction snapshots, offline controls and the blocked prelaunch package. Evidence was not copied into another session's outputs. From 08f6de285617cfb5eaac58f91eda31d336280063 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:26:22 +0300 Subject: [PATCH 31/31] Correct the later pull request references The integration plan and report identified a later preserved branch as pull request 231. That number belongs to its owning issue. The actual Welcome migration pull request is 232, whose base remains the status presentation branch from pull request 230. The two references now use the correct pull request numbers and preserve the same integration boundary. The correction changes two documentation lines only. Product source, tests, native packages, runtime evidence and published branch refs remain unchanged. Governance validation checked 167 Markdown documents with zero errors, and whitespace validation passed. The successful checks on the preceding c30d827 commit retain their original attribution. The final commit requires its own independent delta review and exact HEAD checks before integration. Refs #14 Changed files: - "docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md" (+1/-1 lines). - "docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md" (+1/-1 lines). The file counts compare the staged tree with its first parent. Staged-Tree: 60924f1fd493c329bdd4d0af2a63d68e5c1db04c --- .../plans/2026-11-12-class-stack-through227-integration.md | 2 +- .../reports/2026-11-12-class-stack-through227-integration.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md b/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md index 330bff69..f12d6006 100644 --- a/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md +++ b/docs/superpowers/plans/2026-11-12-class-stack-through227-integration.md @@ -16,7 +16,7 @@ Current verification: [integration report](../reports/2026-11-12-class-stack-thr - Execution owner: chat 01a1c5f4-bad8-7310-bafb-1bcf792172a9; only its existing future-task-issues checkout may change. - Freeze initial main 21555a29ce9fba98c678c445d04ee9f6ce3c85ba and stack tip 3afa82e3f4947ce4bef38b14d86c642c93ddbe90. Re-read remote state before publication and merge. -- Preserve all six published stack heads, later PR 230/231 bases, foreign worktrees, source, index, output, and evidence. No rebase, force push, deletion or automatic retarget. +- Preserve all six published stack heads, later PR 230/232 bases, foreign worktrees, source, index, output, and evidence. No rebase, force push, deletion or automatic retarget. - Preserve all main changes including PR 229 language captions. No new product feature or dependency version is part of this integration. - Respect exclusive UI ownership for browser reads, native launches and snapshots. Coordinate heavy builds separately. - Issue 13 keeps historical G1 reconciliation. Issue 15 keeps the broader integrated native matrix. A bounded hidden fixture does not prove real picker, full startup, installed-product or release acceptance. diff --git a/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md b/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md index 759a6f69..a7fd6be9 100644 --- a/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md +++ b/docs/superpowers/reports/2026-11-12-class-stack-through227-integration.md @@ -17,7 +17,7 @@ Issue 13 and PR 10 retain historical G1 reconciliation. The one older GUI option - Normal merge/product candidate: `e417d4efef05c47393bde549c301cb519577d9bc`. - Stack tip: `3afa82e3f4947ce4bef38b14d86c642c93ddbe90`. -All six published heads are retained as ancestors: PR 216 `36235846fb116acad49b328b29120afa92714712`, PR 218 `3da11cb098d3e1241b2a86cd86ee0c14d80b1942`, PR 220 `3c7f8961477dbff0b4b021493b629ba1a1a0fa05`, PR 222 `b627a0f62dace8dde20ca2574a9d28646f71b421`, PR 224 `12ef689e0968bd7ff4b27cee0fe7af02091286da` and PR 227 at the tip above. Their published refs were preserved. Later PR 230/231 work and foreign checkouts were not merged, retargeted or modified. +All six published heads are retained as ancestors: PR 216 `36235846fb116acad49b328b29120afa92714712`, PR 218 `3da11cb098d3e1241b2a86cd86ee0c14d80b1942`, PR 220 `3c7f8961477dbff0b4b021493b629ba1a1a0fa05`, PR 222 `b627a0f62dace8dde20ca2574a9d28646f71b421`, PR 224 `12ef689e0968bd7ff4b27cee0fe7af02091286da` and PR 227 at the tip above. Their published refs were preserved. Later PR 230/232 work and foreign checkouts were not merged, retargeted or modified. The product/test tree matches the clean read-only merge probe `525418989453cf9ce76edd030102a76972a5fd79`. Its only initial differences were the new plan and inventory entry. The inventory append was the only conflict; all 129 main and 165 stack records remain, with the one new plan record. No product correction was needed. All 16 main test-project items remain; all 130 explicit Compile includes exist without duplicates. All five nonproject PR 229 blobs remain exact. Tray, elevated launcher, Shared, installer, Update, EditHostFile, dependency versions, package sources and workflows remain current-main content.