Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ public Result ResolveConflict(bool keepLocal)
return Result.Fail("No pending PLC recipe to resolve.");
}

return _session.LoadAsCurrent(pending);
return ApplyRecipeFromPlc(pending);
}

private void OnConnectionStateChanged(PlcConnectionState state)
Expand Down
22 changes: 6 additions & 16 deletions SemiStep/SemiStep.Core/Recipes/RecipeSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@ public sealed class RecipeSession(
? Snapshot.Value.Recipe
: Recipe.Empty;

public Recipe LastValidRecipe { get; private set; } = Recipe.Empty;

public bool IsDirty { get; private set; }

public bool IsValid =>
Expand Down Expand Up @@ -131,18 +129,12 @@ public void MarkSaved()
}

/// <summary>
/// Replaces the current recipe with <paramref name="recipe"/> as a fresh editing session.
/// Differs from <see cref="Apply"/>: clears undo history (does not push the previous state)
/// because the new recipe represents a load (from CSV file or PLC), not an incremental edit.
/// Differs from <see cref="Reset"/>: loads a specific recipe instead of <see cref="Recipe.Empty"/>.
/// Loads a recipe that already passed <see cref="LoadAsCurrentValidated"/> as a fresh editing session
/// with cleared undo history; a recipe that fails analysis changes nothing.
/// </summary>
public Result LoadAsCurrent(Recipe recipe)
{
_history.Clear();
var snapshot = _analyzer.Analyze(recipe);
UpdateSnapshot(snapshot);
NotifySyncIfEnabled();

if (snapshot.IsFailed)
{
_logger.LogWarning(
Expand All @@ -152,6 +144,10 @@ public Result LoadAsCurrent(Recipe recipe)
return snapshot.ToResult();
}

_history.Clear();
UpdateSnapshot(snapshot);
NotifySyncIfEnabled();

_logger.LogInformation("Recipe loaded as current: {StepCount} steps", recipe.StepCount);

return Result.Ok().WithReasons(snapshot.Reasons);
Expand Down Expand Up @@ -452,17 +448,11 @@ private void UpdateSnapshot(Result<RecipeSnapshot> snapshot, bool markDirty)
{
IsDirty = true;
}

if (snapshot.IsSuccess)
{
LastValidRecipe = snapshot.Value.Recipe;
}
}

private void ResetSnapshotToEmpty()
{
Snapshot = RecipeSnapshot.Empty;
LastValidRecipe = Recipe.Empty;
IsDirty = false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,16 @@ public void RejectedMutation_LeavesRecipeAndValidStateUnchanged()
driver.IsValid.Should().BeFalse("unclosed For loops block validity");

var stepCountBeforeRejection = fixture.Session.Current.StepCount;
var lastValidStepCountBeforeRejection = fixture.Session.LastValidRecipe.StepCount;

var result = fixture.Session.AppendStep(RecipeTestDriver.EndForLoopActionId);

result.IsFailed.Should().BeTrue("closing a 4th nested loop exceeds the maximum nesting depth");
driver.IsValid.Should().BeFalse("mutation was rejected, state still has unclosed For loops");
fixture.Session.Current.StepCount.Should().Be(stepCountBeforeRejection, "rejected mutation must not change the recipe");
fixture.Session.LastValidRecipe.StepCount.Should().Be(lastValidStepCountBeforeRejection, "last valid recipe must not change when mutation is rejected");
}

[Fact]
public void LastValidRecipe_UpdatesAfterFix()
public void ClosingTheLoop_MakesTheRecipeValid()
{
fixture.Session.Reset();
var driver = new RecipeTestDriver(fixture.Session);
Expand All @@ -45,6 +43,6 @@ public void LastValidRecipe_UpdatesAfterFix()
driver.AddEndFor();
driver.IsValid.Should().BeTrue("adding EndFor closes the loop");

fixture.Session.LastValidRecipe.StepCount.Should().Be(3);
fixture.Session.Current.StepCount.Should().Be(3);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -815,15 +815,16 @@ public async Task LoadAsCurrent_Success_NotifiesSyncOnceWithPostChangeState()
}

[Fact]
public async Task LoadAsCurrent_FailedAnalysis_NotifiesSyncOnceWithPostChangeState()
public async Task LoadAsCurrent_FailedAnalysis_DoesNotNotifySync()
{
var harness = await BuildHarnessAsync();
AppendWait(harness, 5f);
var failingRecipe = BuildRecipeFailingAnalysis(harness);
var sync = EnableSync(harness);

harness.Session.LoadAsCurrent(failingRecipe).IsFailed.Should().BeTrue();

ShouldHaveSingleNotificationOfCurrentState(harness, sync);
sync.NotifyRecipeChangedCalls.Should().BeEmpty();
}

[Fact]
Expand Down Expand Up @@ -950,23 +951,23 @@ public async Task LoadAsCurrent_Success_SetsDirty()
}

[Fact]
public async Task LoadAsCurrent_FailedAnalysis_ClearsHistoryEmptiesCurrentAndKeepsLastValid()
public async Task LoadAsCurrent_FailedAnalysis_LeavesRecipeHistoryAndDirtyFlagUnchanged()
{
var harness = await BuildHarnessAsync();
var failingRecipe = BuildRecipeFailingAnalysis(harness);
AppendWait(harness, 1f);
AppendWait(harness, 2f);
harness.Session.Undo().IsSuccess.Should().BeTrue();
var lastValidBefore = harness.Session.LastValidRecipe;
harness.Session.MarkSaved();
var snapshotBefore = harness.Session.Snapshot;

harness.Session.LoadAsCurrent(failingRecipe).IsFailed.Should().BeTrue();
var result = harness.Session.LoadAsCurrent(failingRecipe);

harness.Session.Snapshot.IsFailed.Should().BeTrue();
harness.Session.Current.StepCount.Should().Be(0);
harness.Session.LastValidRecipe.Should().BeSameAs(lastValidBefore);
harness.Session.CanUndo.Should().BeFalse();
harness.Session.CanRedo.Should().BeFalse();
harness.Session.IsDirty.Should().BeTrue();
result.HasError<MaxLoopNestingDepthExceededError>().Should().BeTrue();
harness.Session.Snapshot.Should().BeSameAs(snapshotBefore);
harness.Session.CanUndo.Should().BeTrue();
harness.Session.CanRedo.Should().BeTrue();
harness.Session.IsDirty.Should().BeFalse();
}

#endregion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using SemiStep.Core.Plc.Sync.Ownership;
using SemiStep.Core.Recipes;
using SemiStep.Core.Recipes.Clipboard;
using SemiStep.Core.Recipes.Errors;
using SemiStep.Core.Recipes.Import;
using SemiStep.Tests.Core.Helpers;
using SemiStep.Tests.Helpers;
Expand All @@ -30,6 +31,7 @@ public sealed class PlcLifecycleManagerReconnectTests
private const int WaitActionId = 10;
private const int RieEtchActionId = 300;
private const string CommentKey = "comment";
private const float DurationAboveTimeMaximum = 100_000f;

private static async Task<(
PlcLifecycleManager Plc,
Expand Down Expand Up @@ -538,4 +540,55 @@ public async Task StateChanged_Connected_WhenPlcHoldsValueInKeyLocalOmits_FiresC

conflictFired.Should().BeTrue("a missing local key matches only the type default, not a value the PLC holds");
}

[Fact]
public async Task ResolveConflict_TakePlcRecipeFailingAnalysis_LeavesSessionUnchanged()
{
var (plc, session, s7Service, syncService, _, _) = await BuildAsync();

var result = await TakeConflictingPlcRecipeAsync(
plc, session, s7Service, syncService, RecipeStubs.LoopsNestedDeeperThanLimit());

result.HasError<MaxLoopNestingDepthExceededError>().Should().BeTrue();
}

[Fact]
public async Task ResolveConflict_TakePlcRecipeFailingImportCheck_LeavesSessionUnchanged()
{
var (plc, session, s7Service, syncService, _, _) = await BuildAsync();
var plcRecipe = Recipe.Empty.AppendStep(
new Step(WaitActionId, []).WithProperty(
RecipeTestDriver.StepDurationColumn, PropertyValue.FromFloat(DurationAboveTimeMaximum)));

var result = await TakeConflictingPlcRecipeAsync(plc, session, s7Service, syncService, plcRecipe);

result.HasError<AtStepError>(error => error.StepNumber == 1).Should().BeTrue();
}

/// <summary>Raises a conflict over a saved local recipe with undo history, then takes the PLC recipe.</summary>
private static async Task<Result> TakeConflictingPlcRecipeAsync(
PlcLifecycleManager plc,
RecipeSession session,
StubS7Service s7Service,
StubPlcSyncService syncService,
Recipe plcRecipe)
{
session.AppendStep(WaitActionId).IsSuccess.Should().BeTrue();
session.AppendStep(WaitActionId).IsSuccess.Should().BeTrue();
session.MarkSaved();
var snapshotBefore = session.Snapshot;
var conflictFired = await ReconcileAndReportConflictAsync(plc, s7Service, syncService, plcRecipe);
conflictFired.Should().BeTrue();
var notificationsBefore = syncService.NotifyRecipeChangedCallCount;

var result = plc.ResolveConflict(keepLocal: false);

result.IsFailed.Should().BeTrue();
session.Snapshot.Should().BeSameAs(snapshotBefore);
session.CanUndo.Should().BeTrue();
session.IsDirty.Should().BeFalse();
syncService.NotifyRecipeChangedCallCount.Should().Be(notificationsBefore);

return result;
}
}
8 changes: 8 additions & 0 deletions SemiStep/SemiStep.Tests/Helpers/RecipeStubs.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Collections.Immutable;

using SemiStep.Core.Recipes;
using SemiStep.Tests.Core.Helpers;

namespace SemiStep.Tests.Helpers;

Expand All @@ -17,6 +18,13 @@ public static Recipe WithSteps(int actionKey, int stepCount)
return new Recipe([.. steps]);
}

/// <summary>Four nested loops closed at the innermost one: passes the import check, fails analysis on depth.</summary>
public static Recipe LoopsNestedDeeperThanLimit()
{
return WithSteps(RecipeTestDriver.ForLoopActionId, 4)
.AppendStep(new Step(RecipeTestDriver.EndForLoopActionId, []));
}

/// <summary>
/// A copy carrying the same content in fresh instances, so an equality check compares content
/// rather than references.
Expand Down
84 changes: 84 additions & 0 deletions SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowFailedOpenTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using System.Reactive.Linq;

using Avalonia.Headless.XUnit;

using AwesomeAssertions;

using SemiStep.Core.Recipes.Errors;
using SemiStep.Tests.Core.Helpers;
using SemiStep.Tests.Helpers;
using SemiStep.Tests.UI.Helpers;

using SemiStep.UI.MainWindow;
using SemiStep.UI.MessageService;

using Xunit;

namespace SemiStep.Tests.UI.MainWindow;

[Trait("Component", "UI")]
[Trait("Area", "RecipeFile")]
[Trait("Category", "Integration")]
public sealed class MainWindowFailedOpenTests : IAsyncLifetime
{
private readonly UIFixture _fixture = new();
private readonly string _openedFilePath =
Path.Combine(Path.GetTempPath(), $"failed-open-opened-{Guid.NewGuid():N}.csv");
private readonly string _failingFilePath =
Path.Combine(Path.GetTempPath(), $"failed-open-failing-{Guid.NewGuid():N}.csv");
private string _pathToOpen = string.Empty;
private MainWindowViewModel _viewModel = null!;

public async ValueTask InitializeAsync()
{
await _fixture.InitializeAsync();
_fixture.SeedRecipe(2);
(await _fixture.CsvService.SaveAsync(_fixture.Coordinator.CurrentRecipe, _openedFilePath))
.IsSuccess.Should().BeTrue();
(await _fixture.CsvService.SaveAsync(RecipeStubs.LoopsNestedDeeperThanLimit(), _failingFilePath))
.IsSuccess.Should().BeTrue();
_fixture.Coordinator.NewRecipe();
_viewModel = _fixture.CreateMainWindowViewModel();
_viewModel.RecipeFile.OpenFileInteraction.RegisterHandler(context => context.SetOutput(_pathToOpen));
}

public async ValueTask DisposeAsync()
{
_viewModel.Dispose();
await _fixture.DisposeAsync();
File.Delete(_openedFilePath);
File.Delete(_failingFilePath);
}

[AvaloniaFact]
public async Task Open_CsvFailingAnalysis_LeavesRecipeGridHistoryAndTitleUnchanged()
{
await OpenEditAndSaveAsync();
var recipeBefore = _fixture.Coordinator.CurrentRecipe;
var titleBefore = _viewModel.WindowTitle;
_viewModel.RecipeGrid.StepCount.Should().Be(recipeBefore.StepCount);

_pathToOpen = _failingFilePath;
await _viewModel.RecipeFile.LoadRecipeCommand.Execute();

_fixture.Coordinator.CurrentRecipe.Should().BeSameAs(recipeBefore);
_viewModel.RecipeGrid.StepCount.Should().Be(recipeBefore.StepCount);
_fixture.Coordinator.CanUndo.Should().BeTrue();
_fixture.Coordinator.IsDirty.Should().BeFalse();
_viewModel.RecipeFile.CurrentFilePath.Should().Be(_openedFilePath);
_viewModel.WindowTitle.Should().Be(titleBefore);
_fixture.MessagePanel.Entries.Should().Contain(entry => entry.Severity == MessageSeverity.Error);
(await _fixture.Coordinator.LoadRecipeAsync(_failingFilePath))
.HasError<MaxLoopNestingDepthExceededError>().Should().BeTrue(
"the file passes the file check, so the failure comes from analysis");
}

private async Task OpenEditAndSaveAsync()
{
_pathToOpen = _openedFilePath;
await _viewModel.RecipeFile.LoadRecipeCommand.Execute();
_fixture.Coordinator.AppendStep(RecipeTestDriver.WaitActionId).IsSuccess.Should().BeTrue();
(await _viewModel.RecipeFile.SaveRecipeCommand.Execute()).Should().BeTrue();
_fixture.Coordinator.CurrentRecipe.StepCount.Should().Be(3);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ public async Task LoadRecipeAsync_AnalyzerFailure_DoesNotPopulateValidationPanel
{
// A recipe whose loop nesting exceeds RecipeAnalyzer.MaxLoopDepth (3) passes
// ImportedRecipeValidator (which only checks per-step property validity, not loop
// structure) but FAILS RecipeAnalyzer.Analyze. Such a load stores a FAILED snapshot
// as the current one, whose IError reasons must NOT leak into the validation panel.
// structure) but FAILS RecipeAnalyzer.Analyze. Such a load leaves the session
// unchanged, and its IError reasons must NOT leak into the validation panel.
var deeplyNestedRecipe = BuildRecipeWithLoopNesting(4);
(await csvService.SaveAsync(deeplyNestedRecipe, tempFilePath))
.EnsureSuccess("Writing the deeply-nested CSV fixture");
Expand Down
28 changes: 28 additions & 0 deletions SemiStep/SemiStep.Tests/UI/RecipeCoordinatorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using SemiStep.Core.Plc.State;
using SemiStep.Core.Plc.Sync;
using SemiStep.Core.Recipes;
using SemiStep.Core.Recipes.Errors;
using SemiStep.Tests.Core.Helpers;
using SemiStep.Tests.Helpers;
using SemiStep.Tests.UI.Helpers;
Expand Down Expand Up @@ -489,4 +490,31 @@ public void RejectedMutation_KeepsPriorOperationError()
"a rejected mutation never reaches RaiseMutatedSafely, so the operation error survives")
.Which.Severity.Should().Be(MessageSeverity.Error);
}

[AvaloniaFact]
public async Task ResolveConflict_TakePlcRecipeFailingAnalysis_EmitsNoSignalAndLeavesSessionUnchanged()
{
_fixture.SeedRecipe(2);
var recipeBefore = _fixture.Coordinator.CurrentRecipe;
var conflictFired = false;
_fixture.Plc.PlcRecipeConflictDetected += (_, _) => conflictFired = true;
var plcRecipe = RecipeStubs.LoopsNestedDeeperThanLimit();
_fixture.S7Service.ManagingAreaToReturn =
new PlcManagingAreaState(Committed: true, RecipeLines: plcRecipe.StepCount);
_fixture.S7Service.RecipeToReturn = plcRecipe;
(await _fixture.Coordinator.EnableSync()).IsSuccess.Should().BeTrue();
_fixture.S7Service.RaiseStateChanged(PlcConnectionState.Connected);
await TestHelpers.WaitUntilAsync(
() => conflictFired,
cancellationToken: TestContext.Current.CancellationToken);
var sink = new RecordingRecipeSink();
_fixture.Coordinator.Mutated += sink.OnMutation;

var result = _fixture.Coordinator.ResolveConflict(keepLocal: false);

result.HasError<MaxLoopNestingDepthExceededError>().Should().BeTrue();
sink.Signals.Should().BeEmpty();
_fixture.Coordinator.CurrentRecipe.Should().BeSameAs(recipeBefore);
_fixture.Coordinator.CanUndo.Should().BeTrue();
}
}
6 changes: 5 additions & 1 deletion SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,11 @@ public Result ResolveConflict(bool keepLocal)

var result = _plc.ResolveConflict(keepLocal);

if (!keepLocal && result.IsSuccess)
if (result.IsFailed)
{
_logger.LogWarning("PLC recipe conflict resolution failed: {Errors}", result.FormatErrors());
}
else if (!keepLocal)
{
DispatchMutation(new MutationSignal.RecipeReplaced());
}
Expand Down
Loading