From c0250d4ee21268d1b8f3b07aba33538c9fa83f03 Mon Sep 17 00:00:00 2001 From: Oleg <18466855+EvaTheSalmon@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:29:28 +0300 Subject: [PATCH] fix(ui): save recipes that have warnings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RecipeCoordinator.SaveRecipeAsync rejected every recipe whose session IsValid was false, and IsValid is false on any warning. A half-built loop, a loop start without its end or an end without a start, blocked Save, so the exit, New and Open prompts in practice offered only "Не сохранять". Save no longer checks validity. Since a failed load leaves the session unchanged, the session always holds an analyzed recipe, so warnings save and the file opens again with the same warnings. Writes to the PLC keep their own gate on IsValid. The hard-coded English rejection text goes with the old gate. The exit, New, Open and Save failure tests used an unclosed loop to make the save fail; they now fail on a real file system error. Co-Authored-By: Claude Opus 5.5 --- .../UI/MainWindow/MainWindowExitFlowTests.cs | 10 +- .../UI/RecipeCoordinatorSaveGateTests.cs | 139 +++++++++++++++--- .../RecipeFileUnsavedChangesTests.cs | 16 +- .../RecipeFileViewModelLoadResultTests.cs | 8 +- .../RecipeFileViewModelSaveResultTests.cs | 22 +-- .../Coordinator/RecipeCoordinator.cs | 11 -- docs/readme.md | 2 + 7 files changed, 148 insertions(+), 60 deletions(-) diff --git a/SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowExitFlowTests.cs b/SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowExitFlowTests.cs index 5b7adc2..d58b205 100644 --- a/SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowExitFlowTests.cs +++ b/SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowExitFlowTests.cs @@ -83,15 +83,15 @@ public async Task HandleExitChoice_Save_SuccessfulSave_ClosesWindow() [AvaloniaFact] public async Task HandleExitChoice_Save_FailedCoordinatorSave_KeepsWindowOpen() { - var driver = new RecipeTestDriver(_fixture.Session); - driver.AddFor(3).AddWait(1f); - _fixture.Session.IsValid.Should().BeFalse("the recipe has an unclosed For loop"); - _viewModel.RecipeFile.SaveFileInteraction.RegisterHandler(context => context.SetOutput(_tempFilePath)); + await File.WriteAllTextAsync(_tempFilePath, "blocker"); + var unwritablePath = Path.Combine(_tempFilePath, "recipe.csv"); + _viewModel.RecipeFile.SaveFileInteraction.RegisterHandler(context => context.SetOutput(unwritablePath)); await _window.HandleExitChoiceAsync(UnsavedChangesChoice.Save); _window.IsVisible.Should().BeTrue("a failed save must not discard the recipe by closing the window"); - File.Exists(_tempFilePath).Should().BeFalse(); + File.Exists(unwritablePath).Should().BeFalse(); + _fixture.MessagePanel.Entries.Count(e => e.IsError).Should().Be(1, "the failed save is reported once"); } [AvaloniaFact] diff --git a/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorSaveGateTests.cs b/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorSaveGateTests.cs index 6362eec..536c190 100644 --- a/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorSaveGateTests.cs +++ b/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorSaveGateTests.cs @@ -10,6 +10,7 @@ using SemiStep.Core.Plc; using SemiStep.Core.Plc.Sync.Ownership; using SemiStep.Core.Recipes; +using SemiStep.Core.Recipes.Analysis.Warnings; using SemiStep.Core.Recipes.Clipboard; using SemiStep.Core.Recipes.Import; using SemiStep.Tests.Core.Helpers; @@ -30,39 +31,112 @@ public sealed class RecipeCoordinatorSaveGateTests private const string TempFilePrefix = "SemiStep.CoordinatorSaveGate"; [AvaloniaFact] - public async Task Save_OnDefectiveRecipe_FailsAndWritesNoFile() + public async Task Save_RecipeWithUnclosedLoop_SavesAndReopensWithSameWarnings() { - var (coordinator, panel, session) = await BuildCoordinatorAsync(); - var tempFilePath = Path.Combine(Path.GetTempPath(), $"{TempFilePrefix}.{Guid.NewGuid():N}.csv"); + var warnings = await SaveAndReopenAsync(driver => driver.AddWait(1f).AddFor(3).AddWait(1f)); + + warnings.Should().Equal((typeof(UnclosedForLoopWarning), 2)); + } + + [AvaloniaFact] + public async Task Save_RecipeWithUnmatchedLoopEnd_SavesAndReopensWithSameWarnings() + { + var warnings = await SaveAndReopenAsync(driver => driver.AddWait(1f).AddEndFor()); + + warnings.Should().Equal((typeof(UnmatchedEndForWarning), 2)); + } + + [AvaloniaFact] + public async Task Open_SavedRecipeWithWarnings_NotifiesSyncServiceAsInvalid() + { + var tempFilePath = NewTempFilePath(); + var saving = await BuildCoordinatorAsync(); + var reopening = await BuildCoordinatorAsync(); try { - var driver = new RecipeTestDriver(session); - driver.AddFor(3).AddWait(1f); + new RecipeTestDriver(saving.Session).AddFor(3).AddWait(1f); + (await saving.Coordinator.SaveRecipeAsync(tempFilePath)).EnsureSuccess("Saving the defective recipe"); + + reopening.SyncService.SetSyncEnabled(true); + (await reopening.Coordinator.LoadRecipeAsync(tempFilePath)).EnsureSuccess("Opening the saved recipe"); + + reopening.SyncService.NotifyRecipeChangedCalls.Should().NotBeEmpty( + "opening a recipe with sync on hands it to the PLC sync service"); + var lastNotification = reopening.SyncService.NotifyRecipeChangedCalls[^1]; + lastNotification.Recipe.StepCount.Should().Be(2); + lastNotification.IsValid.Should().BeFalse( + "a recipe with warnings saves to a file but must not be written to the PLC"); + } + finally + { + saving.Dispose(); + reopening.Dispose(); + DeleteIfExists(tempFilePath); + } + } + + private static async Task> SaveAndReopenAsync( + Action buildDefectiveRecipe) + { + var tempFilePath = NewTempFilePath(); + var saving = await BuildCoordinatorAsync(); + var reopening = await BuildCoordinatorAsync(); + + try + { + buildDefectiveRecipe(new RecipeTestDriver(saving.Session)); + saving.Session.IsValid.Should().BeFalse("the fixture recipe carries a loop warning"); + var savedWarnings = LoopWarnings(saving.Session); + + var saveResult = await saving.Coordinator.SaveRecipeAsync(tempFilePath); - session.IsValid.Should().BeFalse("the recipe has an unclosed For loop"); + saveResult.IsSuccess.Should().BeTrue("a recipe with warnings must save"); + File.Exists(tempFilePath).Should().BeTrue(); + saving.Session.IsDirty.Should().BeFalse("a successful save marks the recipe saved"); - var result = await coordinator.SaveRecipeAsync(tempFilePath); + var loadResult = await reopening.Coordinator.LoadRecipeAsync(tempFilePath); - result.IsFailed.Should().BeTrue("Save must reject a recipe with structural defects"); - File.Exists(tempFilePath).Should().BeFalse("the file must not be written when Save is rejected"); - panel.Entries.Should().ContainSingle( - e => e.IsWarning, - "the underlying analyzer warning must still surface in the message panel after the rejected Save"); + loadResult.IsSuccess.Should().BeTrue("the saved file must open again"); + reopening.Session.Current.StepCount.Should().Be(saving.Session.Current.StepCount); + reopening.Panel.WarningCount.Should().Be(1, "the reopened recipe shows its one loop warning"); + var reopenedWarnings = LoopWarnings(reopening.Session); + reopenedWarnings.Should().Equal(savedWarnings); + + return reopenedWarnings; } finally { - coordinator.Dispose(); - panel.Dispose(); - if (File.Exists(tempFilePath)) - { - File.Delete(tempFilePath); - } + saving.Dispose(); + reopening.Dispose(); + DeleteIfExists(tempFilePath); + } + } + + private static List<(Type Type, int StepNumber)> LoopWarnings(RecipeSession session) + { + var unclosed = session.Snapshot.Reasons.OfType() + .Select(warning => (warning.GetType(), warning.StepNumber)); + var unmatched = session.Snapshot.Reasons.OfType() + .Select(warning => (warning.GetType(), warning.StepNumber)); + + return [.. unclosed, .. unmatched]; + } + + private static string NewTempFilePath() + { + return Path.Combine(Path.GetTempPath(), $"{TempFilePrefix}.{Guid.NewGuid():N}.csv"); + } + + private static void DeleteIfExists(string path) + { + if (File.Exists(path)) + { + File.Delete(path); } } - private static async Task<(RecipeCoordinator Coordinator, MessagePanelViewModel Panel, RecipeSession Session)> - BuildCoordinatorAsync() + private static async Task BuildCoordinatorAsync() { var configDir = TestConfigLocator.GetConfigDirectory("WithGroups"); var configLoadResult = await ConfigFacade.LoadAndValidateAsync(configDir); @@ -78,7 +152,8 @@ public async Task Save_OnDefectiveRecipe_FailsAndWritesNoFile() .AddSingleton(sp => sp.GetRequiredService()) .AddSingleton(sp => sp.GetRequiredService()) .AddSingleton(sp => sp.GetRequiredService()) - .AddSingleton() + .AddSingleton() + .AddSingleton(sp => sp.GetRequiredService()) .AddSingleton() .BuildServiceProvider(); @@ -101,6 +176,26 @@ public async Task Save_OnDefectiveRecipe_FailsAndWritesNoFile() NullLogger.Instance); coordinator.Initialize(); - return (coordinator, panel, session); + return new CoordinatorFixture( + coordinator, + panel, + session, + services.GetRequiredService(), + services); + } + + private sealed record CoordinatorFixture( + RecipeCoordinator Coordinator, + MessagePanelViewModel Panel, + RecipeSession Session, + StubPlcSyncService SyncService, + ServiceProvider Services) : IDisposable + { + public void Dispose() + { + Coordinator.Dispose(); + Panel.Dispose(); + Services.Dispose(); + } } } diff --git a/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileUnsavedChangesTests.cs b/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileUnsavedChangesTests.cs index f97a25a..981c6c6 100644 --- a/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileUnsavedChangesTests.cs +++ b/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileUnsavedChangesTests.cs @@ -145,15 +145,13 @@ public async Task New_Dirty_SaveAsCancelled_KeepsRecipe() [AvaloniaFact] public async Task New_Dirty_SaveFails_KeepsRecipe() { - new RecipeTestDriver(_fixture.Session).AddFor(3); - _fixture.Session.IsValid.Should().BeFalse("the recipe has an unclosed For loop"); var stepCountBefore = StepCount; _answer = UnsavedChangesChoice.Save; - _saveAsAnswer = _savePath; + _saveAsAnswer = UnwritableSavePath; await _recipeFile.NewRecipeCommand.Execute(); - File.Exists(_savePath).Should().BeFalse(); + File.Exists(UnwritableSavePath).Should().BeFalse(); StepCount.Should().Be(stepCountBefore, "a failed save aborts the new recipe"); _fixture.MessagePanel.Entries.Count(e => e.IsError).Should().Be(1, "the failed save is reported once"); } @@ -241,17 +239,16 @@ public async Task Open_Dirty_SaveAsCancelled_KeepsRecipeWithoutPicker() [AvaloniaFact] public async Task Open_Dirty_SaveFails_KeepsRecipeWithoutPicker() { - new RecipeTestDriver(_fixture.Session).AddFor(3); - _fixture.Session.IsValid.Should().BeFalse("the recipe has an unclosed For loop"); var stepCountBefore = StepCount; _answer = UnsavedChangesChoice.Save; - _saveAsAnswer = _savePath; + _saveAsAnswer = UnwritableSavePath; await _recipeFile.LoadRecipeCommand.Execute(); - File.Exists(_savePath).Should().BeFalse(); + File.Exists(UnwritableSavePath).Should().BeFalse(); _openPickerCount.Should().Be(0, "a failed save aborts the open"); StepCount.Should().Be(stepCountBefore); + _fixture.MessagePanel.Entries.Count(e => e.IsError).Should().Be(1, "the failed save is reported once"); } [AvaloniaFact] @@ -310,6 +307,9 @@ public async Task Open_Clean_OpensPickedFileWithoutPrompt() private int StepCount => _fixture.Coordinator.CurrentRecipe.StepCount; + /// A path below an existing file, so the file system rejects the write. + private string UnwritableSavePath => Path.Combine(_openPath, "recipe.csv"); + private async Task SavedStepCountAsync(string path) { File.Exists(path).Should().BeTrue(); diff --git a/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileViewModelLoadResultTests.cs b/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileViewModelLoadResultTests.cs index a251952..079fadb 100644 --- a/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileViewModelLoadResultTests.cs +++ b/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileViewModelLoadResultTests.cs @@ -79,10 +79,10 @@ public async Task LoadRecipe_CleanFile_SurfacesSuccessEntryWithoutWarning() [AvaloniaFact] public async Task LoadRecipe_StructurallyWarnedRecipeFromCleanFile_KeepsLoadedSuccessInOperationSlot() { - // A structurally-warned recipe (an unclosed For) is saved DIRECTLY through the CSV service, - // bypassing the coordinator save gate that rejects invalid recipes. The file itself is clean - // (correct ROWS header), so the load produces no integrity warning: the operation slot must - // still show the "Loaded" success, with the structural warning confined to the validation list. + // A structurally-warned recipe (an unclosed For) is saved directly through the CSV service. + // The file itself is clean (correct ROWS header), so the load produces no integrity warning: + // the operation slot must still show the "Loaded" success, with the structural warning + // confined to the validation list. var driver = new RecipeTestDriver(_fixture.Session); driver.AddFor(3); _fixture.Session.IsValid.Should().BeFalse("an unclosed For loop is a structural defect"); diff --git a/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileViewModelSaveResultTests.cs b/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileViewModelSaveResultTests.cs index 218b895..6e069ad 100644 --- a/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileViewModelSaveResultTests.cs +++ b/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileViewModelSaveResultTests.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Logging.Abstractions; -using SemiStep.Tests.Core.Helpers; using SemiStep.Tests.UI.Helpers; using SemiStep.UI.Localization; @@ -45,6 +44,11 @@ public async ValueTask DisposeAsync() { File.Delete(_tempFilePath); } + + if (Directory.Exists(_tempFilePath)) + { + Directory.Delete(_tempFilePath, recursive: true); + } } [AvaloniaFact] @@ -62,16 +66,15 @@ public async Task SaveRecipe_Success_EmitsTrueAndSetsCurrentFilePath() [AvaloniaFact] public async Task SaveRecipe_FailedCoordinatorSave_EmitsFalseAndKeepsCurrentFilePathUnset() { - var driver = new RecipeTestDriver(_fixture.Session); - driver.AddFor(3).AddWait(1f); - _fixture.Session.IsValid.Should().BeFalse("the recipe has an unclosed For loop"); - _recipeFile.SaveFileInteraction.RegisterHandler(context => context.SetOutput(_tempFilePath)); + await File.WriteAllTextAsync(_tempFilePath, "blocker"); + var unwritablePath = Path.Combine(_tempFilePath, "recipe.csv"); + _recipeFile.SaveFileInteraction.RegisterHandler(context => context.SetOutput(unwritablePath)); var saved = await _recipeFile.SaveRecipeCommand.Execute(); - saved.Should().BeFalse("the coordinator rejects saving a structurally defective recipe"); + saved.Should().BeFalse("the file system rejects a path below an existing file"); _recipeFile.CurrentFilePath.Should().BeNull("a failed save must not adopt the target path"); - File.Exists(_tempFilePath).Should().BeFalse(); + File.Exists(unwritablePath).Should().BeFalse(); } [AvaloniaFact] @@ -140,9 +143,8 @@ public async Task SaveRecipe_WithCurrentFilePath_FailedCoordinatorSave_EmitsFals context.SetOutput(_tempFilePath); }); (await _recipeFile.SaveRecipeCommand.Execute()).Should().BeTrue("the arrange save establishes the file path"); - var driver = new RecipeTestDriver(_fixture.Session); - driver.AddFor(3).AddWait(1f); - _fixture.Session.IsValid.Should().BeFalse("the recipe has an unclosed For loop"); + File.Delete(_tempFilePath); + Directory.CreateDirectory(_tempFilePath); var saved = await _recipeFile.SaveRecipeCommand.Execute(); diff --git a/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs b/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs index 875ff62..010fd7f 100644 --- a/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs +++ b/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs @@ -369,17 +369,6 @@ public async Task SaveRecipeAsync(string filePath) filePath, _session.Current.StepCount); - if (!_session.IsValid) - { - const string SaveRejectionMessage = "Cannot save recipe with structural defects (see warnings in the message panel)."; - _logger.LogWarning( - "Save rejected: recipe is not valid. StepCount={StepCount}", - _session.Current.StepCount); - var rejection = Result.Fail(SaveRejectionMessage).WithReasons(_session.Snapshot.Reasons); - RebuildMessagePanel(); - return rejection; - } - var result = await _csvService.SaveAsync(_session.Current, filePath); if (result.IsFailed) diff --git a/docs/readme.md b/docs/readme.md index ea33df5..2085ccc 100644 --- a/docs/readme.md +++ b/docs/readme.md @@ -384,6 +384,8 @@ _Окно установки RIE в транспонированном пред - отображается понятное сообщение; - запрещается сохранение/отправка рецепта в ПЛК до исправления ошибок. +Рецепт с предупреждениями о циклах (цикл без конца или конец цикла без начала) сохраняется в файл и открывается снова с теми же предупреждениями. В ПЛК такой рецепт не записывается, пока предупреждения не устранены. + --- ### 3.6. Импорт CSV