diff --git a/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs b/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs
index 67d1451..75ee64f 100644
--- a/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs
+++ b/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs
@@ -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)
diff --git a/SemiStep/SemiStep.Core/Recipes/RecipeSession.cs b/SemiStep/SemiStep.Core/Recipes/RecipeSession.cs
index f6b5b9c..9ef9607 100644
--- a/SemiStep/SemiStep.Core/Recipes/RecipeSession.cs
+++ b/SemiStep/SemiStep.Core/Recipes/RecipeSession.cs
@@ -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 =>
@@ -131,18 +129,12 @@ public void MarkSaved()
}
///
- /// Replaces the current recipe with as a fresh editing session.
- /// Differs from : 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 : loads a specific recipe instead of .
+ /// Loads a recipe that already passed as a fresh editing session
+ /// with cleared undo history; a recipe that fails analysis changes nothing.
///
public Result LoadAsCurrent(Recipe recipe)
{
- _history.Clear();
var snapshot = _analyzer.Analyze(recipe);
- UpdateSnapshot(snapshot);
- NotifySyncIfEnabled();
-
if (snapshot.IsFailed)
{
_logger.LogWarning(
@@ -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);
@@ -452,17 +448,11 @@ private void UpdateSnapshot(Result snapshot, bool markDirty)
{
IsDirty = true;
}
-
- if (snapshot.IsSuccess)
- {
- LastValidRecipe = snapshot.Value.Recipe;
- }
}
private void ResetSnapshotToEmpty()
{
Snapshot = RecipeSnapshot.Empty;
- LastValidRecipe = Recipe.Empty;
IsDirty = false;
}
diff --git a/SemiStep/SemiStep.Tests/Core/Integration/Snapshot/CoreSnapshotStateTests.cs b/SemiStep/SemiStep.Tests/Core/Integration/Snapshot/CoreSnapshotStateTests.cs
index 0838fce..30e4789 100644
--- a/SemiStep/SemiStep.Tests/Core/Integration/Snapshot/CoreSnapshotStateTests.cs
+++ b/SemiStep/SemiStep.Tests/Core/Integration/Snapshot/CoreSnapshotStateTests.cs
@@ -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);
@@ -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);
}
}
diff --git a/SemiStep/SemiStep.Tests/Core/RecipeSessionBehaviourCharacterizationTests.cs b/SemiStep/SemiStep.Tests/Core/RecipeSessionBehaviourCharacterizationTests.cs
index 497b0af..a6e652e 100644
--- a/SemiStep/SemiStep.Tests/Core/RecipeSessionBehaviourCharacterizationTests.cs
+++ b/SemiStep/SemiStep.Tests/Core/RecipeSessionBehaviourCharacterizationTests.cs
@@ -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]
@@ -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().Should().BeTrue();
+ harness.Session.Snapshot.Should().BeSameAs(snapshotBefore);
+ harness.Session.CanUndo.Should().BeTrue();
+ harness.Session.CanRedo.Should().BeTrue();
+ harness.Session.IsDirty.Should().BeFalse();
}
#endregion
diff --git a/SemiStep/SemiStep.Tests/Domain/PlcLifecycleManagerReconnectTests.cs b/SemiStep/SemiStep.Tests/Domain/PlcLifecycleManagerReconnectTests.cs
index 78f8fdc..8890e44 100644
--- a/SemiStep/SemiStep.Tests/Domain/PlcLifecycleManagerReconnectTests.cs
+++ b/SemiStep/SemiStep.Tests/Domain/PlcLifecycleManagerReconnectTests.cs
@@ -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;
@@ -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,
@@ -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().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(error => error.StepNumber == 1).Should().BeTrue();
+ }
+
+ /// Raises a conflict over a saved local recipe with undo history, then takes the PLC recipe.
+ private static async Task 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;
+ }
}
diff --git a/SemiStep/SemiStep.Tests/Helpers/RecipeStubs.cs b/SemiStep/SemiStep.Tests/Helpers/RecipeStubs.cs
index 74dc689..4deab85 100644
--- a/SemiStep/SemiStep.Tests/Helpers/RecipeStubs.cs
+++ b/SemiStep/SemiStep.Tests/Helpers/RecipeStubs.cs
@@ -1,6 +1,7 @@
using System.Collections.Immutable;
using SemiStep.Core.Recipes;
+using SemiStep.Tests.Core.Helpers;
namespace SemiStep.Tests.Helpers;
@@ -17,6 +18,13 @@ public static Recipe WithSteps(int actionKey, int stepCount)
return new Recipe([.. steps]);
}
+ /// Four nested loops closed at the innermost one: passes the import check, fails analysis on depth.
+ public static Recipe LoopsNestedDeeperThanLimit()
+ {
+ return WithSteps(RecipeTestDriver.ForLoopActionId, 4)
+ .AppendStep(new Step(RecipeTestDriver.EndForLoopActionId, []));
+ }
+
///
/// A copy carrying the same content in fresh instances, so an equality check compares content
/// rather than references.
diff --git a/SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowFailedOpenTests.cs b/SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowFailedOpenTests.cs
new file mode 100644
index 0000000..8980a5d
--- /dev/null
+++ b/SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowFailedOpenTests.cs
@@ -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().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);
+ }
+}
diff --git a/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorLoadRecipeTests.cs b/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorLoadRecipeTests.cs
index addda7d..ee66dd9 100644
--- a/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorLoadRecipeTests.cs
+++ b/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorLoadRecipeTests.cs
@@ -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");
diff --git a/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorTests.cs b/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorTests.cs
index 8d8a2fa..2464eb8 100644
--- a/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorTests.cs
+++ b/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorTests.cs
@@ -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;
@@ -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().Should().BeTrue();
+ sink.Signals.Should().BeEmpty();
+ _fixture.Coordinator.CurrentRecipe.Should().BeSameAs(recipeBefore);
+ _fixture.Coordinator.CanUndo.Should().BeTrue();
+ }
}
diff --git a/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs b/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs
index 71dc982..875ff62 100644
--- a/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs
+++ b/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs
@@ -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());
}
diff --git a/docs/plans/20261130-recipe-replace-save-exit-safety-ui.md b/docs/plans/20261130-recipe-replace-save-exit-safety-ui.md
new file mode 100644
index 0000000..945b9ea
--- /dev/null
+++ b/docs/plans/20261130-recipe-replace-save-exit-safety-ui.md
@@ -0,0 +1,198 @@
+# Save safety: UI spec
+
+This spec covers the plan `docs/plans/20261130-recipe-replace-save-exit-safety.md`, section "UI design". The implementer builds it as written. Existing values are cited as file:line.
+
+## 1. Link slot states
+
+### Fit rule
+
+- The slot is 270 px wide (`AppStatusBar.axaml:52`, `:56`). It holds a 12 px dot column and a text column (`:61`), so the text gets 258 px.
+- `LinkText` has no trimming (`AppStatusBar.axaml:71-74`). Every string must fit at its worst case.
+- The worst case includes the override suffix ", ", which `PlcLinkView.cs:43-46` appends to every kind except NoLink.
+- Text is Segoe UI 12 px (`grid_style.yaml:51`). Today's widest string is "ПЛК: ошибка синхронизации, a 15-character host such as 203.0.113.200" at 249 px.
+
+### New kinds
+
+The kinds are added to `PlcLinkKind` (`PlcLinkView.cs:7-15`). The texts follow the "ПЛК: " prefix pattern of `LinkConnecting`, `LinkConnected` and `LinkSyncError` (`Resources.ru.resx:526-539`).
+
+| Kind | ru text | en text | Dot | Width ru / with suffix |
+|---|---|---|---|---|
+| `Comparing` | `ПЛК: сравнение рецептов…` | `PLC: comparing recipes…` | hollow, `SecondaryForegroundBrush` stroke, as Connecting (`AppStatusBar.axaml:67-69`, `PlcLinkView.cs:24`) | 151 / 238 |
+| `Conflict` | `ПЛК: конфликт рецептов` | `PLC: recipe conflict` | filled, `DisconnectedBrush` (`AppStatusBar.axaml:65`, `#DB3B4B` at `grid_style.yaml:65`) | 136 / 223 |
+| `NotWritten` | `ПЛК: рецепт не записан` | `PLC: recipe not written` | filled, `SecondaryForegroundBrush` (`#6C707E`, `grid_style.yaml:70`) | 131 / 218 |
+| `ExitSending` | `ПЛК: запись рецепта…` | `PLC: writing recipe…` | hollow, as Comparing | 123 / 210 |
+| `TakeReading` | `ПЛК: чтение рецепта…` | `PLC: reading recipe…` | hollow, as Comparing | about 125 / 212 |
+
+New resx keys go in both `Resources.resx` and `Resources.ru.resx`: `LinkComparing`, `LinkConflict`, `LinkNotWritten`, `LinkExitSending` and `LinkTakeReading`.
+
+### Dot colours
+
+- **Comparing** is a short step in progress. It reuses the hollow grey dot of "подключение…" and "отключение…", the established look for "the app is working, wait". It is never green: D2 says the slot never shows connected during a pause.
+- **Conflict** is red. Writes stop, and the PLC holds another recipe until the operator chooses. That is the class of `SyncError`, which is red (`PlcLinkView.cs:22`) under D1b, "red: no link or error" (`decisions.md:21`). Orange is not allowed: D1 keeps orange for reset cells only, "Not 'not synced'" (`decisions.md:6`).
+- **NotWritten** gets a filled grey dot.
+ - It is a stable state, so the hollow "wait" dot does not fit.
+ - It is not a fault in two of its causes: a write parked until run end is expected, and a recipe with warnings is the operator's to fix. Red would overstate it.
+ - It is not green, because green would claim the PLC follows the screen.
+ - Filled grey differs from hollow grey (transient) and from no dot (sync off) by shape, so the state is not carried by colour alone.
+- **ExitSending** lasts at most 5 s, and the window waits for it. It gets the hollow dot.
+
+### Causes of NotWritten
+
+NotWritten means sync is on, the link is up, no pause holds, and the PLC does not hold the current screen recipe. Today these cases show green "ПЛК: подключено" (`PlcLinkViewModel.cs:82-85`). `PlcLinkViewModelTests.cs:185-187` pins Connected for `OutOfSync`, and that test changes.
+
+| Cause | Source today | Slot |
+|---|---|---|
+| The recipe has warnings, so it is not written | `PlcSyncStatus.OutOfSync` (`PlcSyncCoordinator.cs:99-105`) | NotWritten |
+| A write is parked until the run ends | parked write (`PlcSyncCoordinator.cs:479-509`) | NotWritten |
+| The last write failed | `PlcSyncStatus.Failed`, latched (`PlcLinkViewModel.cs:63-71`) | stays `SyncError`, red, as decided in D6a (`decisions.md:73`) |
+
+A failed write keeps `SyncError` because D6a already decided its text, colour and clear rule. A second kind for the same fault would break one term per concept. NotWritten reads a Core predicate that is true only for the two causes above. A normal write in its 1 s debounce or in flight is not a cause: the slot stays green, so it does not flash grey after every edit (plan, row D2). The broader "in sync" query, which a debounce does clear, is for exit only.
+
+### Tooltips
+
+Each kind keeps the two existing lines: the address (`LinkAddressFormat`) and `Последний обмен: {0}` (`PlcLinkView.cs:48-50`). Three kinds add a third line:
+
+| Kind | Third line ru | en |
+|---|---|---|
+| Comparing | `Запись в ПЛК ждёт конца сравнения.` | `Writing to the PLC waits for the comparison to end.` |
+| Conflict | `Запись в ПЛК ждёт выбора в окне конфликта рецептов.` | `Writing to the PLC waits for a choice in the recipe conflict window.` |
+| NotWritten | `Причина: {0}.`, where {0} is a reason from the closed set in section 2 | `Reason: {0}.` |
+
+NotWritten names its cause in the tooltip, not in the bar. One fixed text in the bar keeps the slot from changing width. NotWritten uses two reasons from section 2: "в рецепте есть предупреждения" and "идёт выполнение рецепта".
+
+### Click
+
+The click does not change. The slot opens the notification log (`MessagePanel.ShowCommand`, `AppStatusBar.axaml:59`).
+
+A click cannot bring a waiting conflict dialog forward. The conflict waits only during an app flow (plan, Terms), and every dialog in a flow is modal to the main window: `ShowDialog(this)` at `MainWindow.axaml.cs:179`, `:225`, `:232`, and owner-bound file pickers at `:189` and `:206`. While one is open, the status bar takes no pointer input. Plan row G1 brings the flow's window forward instead.
+
+### Resolve order
+
+This order replaces `PlcLinkViewModel.cs:77-86`. The first matching row wins.
+
+1. `ExitSending`: the exit send runs. `TakeReading`: the take of the PLC recipe runs (section 3). Both are UI flags in `MainWindowViewModel`, and they cannot hold together, because each runs inside an app flow.
+2. `Disconnecting`: the toggle is disabling and the link is not down. Same as today.
+3. `SyncOff`: sync is off. A comparison or conflict result after sync off is ignored (D10), so nothing below can hold.
+4. `Connecting`: the toggle is enabling **and the link is not up yet**.
+5. `NoLink`: the link is down. A link drop ends a conflict (plan row A10), so NoLink outranks it.
+6. `Conflict`: a conflict dialog is open or waiting.
+7. `Comparing`: a write pause holds and the link is up. This row also covers the gap between connect and the comparison start, and any pause without a conflict flag.
+8. `SyncError`: the error latch is set, as today.
+9. `NotWritten`: the recipe has warnings, or a write is parked until run end.
+10. `Connected`.
+
+Two rows differ from today and from the coordinator's draft:
+
+- Row 4 adds "link not up yet". Today `Enabling` alone gives Connecting (`:81`). If `EnableSync` awaits the comparison, the toggle stays in `Enabling` through it, and "сравнение" would never show. A headless test checks it, because on localhost it is too short to see.
+- Conflict is above Comparing. A conflict starts only after its comparison ends, and both carry one comparison ID (plan row A13), so the two cannot hold together. The order only guards against a stale flag. If both flags are ever set, the conflict is the newer fact.
+
+### Flashing
+
+A comparison takes under a second, so the slot reads "подключение…" or "нет связи", then "сравнение рецептов…", then the result. The fixed width keeps the bar still. There is no minimum display time: the slot shows the truth, and hiding a state would show "connected" during a pause. On a flaky link the slot repeats "нет связи" and "сравнение рецептов…", which is accurate.
+
+## 2. Exit dialog when the PLC did not get the current recipe
+
+### Window
+
+The new window is `PlcExitDialog` in `SemiStep.UI/ShutdownService/`, beside `ExitConfirmationDialog`. It has its own result enum, `PlcExitChoice { Cancel, CloseWithoutWrite }`. `Cancel` is value 0, so X, Alt+F4 and a dismissed dialog yield Cancel, as `UnsavedChangesChoice` does (`UnsavedChangesChoice.cs:7`, Cancel first). G6 relies on this.
+
+| Property | Value | Source |
+|---|---|---|
+| Width | 400 | reused, `ExitConfirmationDialog.axaml:9` |
+| Height | `SizeToContent="Height"`, not the fixed 150 | see below |
+| `WindowStartupLocation` | `CenterOwner` | reused, `:11` |
+| `CanResize` | False | reused, `:12` |
+| `ShowInTaskbar` | False | reused, `:13` |
+| Outer margin | 16 | desktop-ui scale; replaces 20 at `:15` |
+| Message lines | `StackPanel Spacing="8"` | desktop-ui scale |
+| Button row | 16 above, `Spacing="8"`, right-aligned | replaces `Margin="0,20,0,0"` and `Spacing="10"` at `:29-30` |
+| Message text | `TextWrapping="Wrap"` | reused, `:23` |
+
+The height comes from the content. A fixed 150 px with a 20 px margin leaves about 58 px for text, and the longest reason wraps to two lines (estimate below). Two lines plus the question line need about 65 px. The reason is set before the dialog opens, so the height never changes while the dialog is open.
+
+The 16 and 8 replace 20 and 10. The desktop-ui rule says: do not copy off-scale values into a new window. The cost is a 4 px difference in margin when the unsaved-changes prompt (G2) is followed by this dialog. Bringing `ExitConfirmationDialog` to 16 and 8 is a separate decision for the operator, because the plan does not touch that window.
+
+### Text
+
+| Part | ru | en |
+|---|---|---|
+| Title | `Рецепт не записан в ПЛК` | `Recipe not written to PLC` |
+| Line 1 | `ПЛК не получил текущий рецепт: {0}.` | `The PLC did not receive the current recipe: {0}.` |
+| Line 2 | `Закрыть программу без записи в ПЛК?` | `Close the program without writing to the PLC?` |
+| Button 1 | `Закрыть без записи` | `Close without writing` |
+| Button 2 | `Отмена`, reusing `DialogCancel` (`Resources.ru.resx:184-185`) | `Cancel` |
+
+The wording follows the existing prompt: a statement, then a question (`Имеются несохранённые изменения. Сохранить их?`, `Resources.ru.resx:175-176`). The title names the state, like `Несохранённые изменения` (`:172-173`). Line 2 names what the first button does, so the button text needs no explanation. Line 1 keeps the plan's wording. "Запись" is the one term for sending to the PLC in the title, line 2, the button and the slot text "запись рецепта…".
+
+New keys: `PlcExitTitle`, `PlcExitMessageFormat`, `PlcExitQuestion`, `PlcExitCloseWithoutWrite`, plus one `PlcNotWrittenReason*` key per reason below. Line 1 gets one reason from the closed set, by reason kind. It never carries Core's error text. Write details go to the log.
+
+### Reasons, in precedence order
+
+When several reasons hold, the first one in this table wins. A reason the operator can act on comes before a reason that is only a consequence.
+
+| # | Reason kind | ru {0} | en {0} | Line 1 width at 14 px |
+|---|---|---|---|---|
+| 1 | No link | `нет связи с ПЛК` | `no link to the PLC` | 320, one line |
+| 2 | Conflict open or waiting | `не решён конфликт рецептов` | `the recipe conflict is not resolved` | 408, two lines |
+| 3 | Comparison running | `идёт сравнение рецептов` | `the recipes are being compared` | 382, two lines |
+| 4 | Recipe has warnings | `в рецепте есть предупреждения` | `the recipe has warnings` | 425, two lines |
+| 5 | Run active, write parked | `идёт выполнение рецепта` | `a recipe is running` | 386, two lines |
+| 6 | Send timed out | `ПЛК не ответил за 5 с` | `the PLC did not answer within 5 s` | 358, one line |
+| 7 | Send failed, any other error | `ошибка записи` | `write error` | 316, one line |
+
+When the exit send started and did not finish, the dialog adds one line above the question: `Рецепт в ПЛК может быть неполным.` / `The recipe in the PLC may be incomplete.` A write marks the PLC recipe uncommitted before it writes the steps, so an interrupted send can leave it incomplete (plan, row G5). The line follows the send's outcome, not the reason shown. It shows after reasons 6 and 7, and also after reason 1 when the link dropped during the send, because reason 1 then wins the precedence. It never shows when no send started. Key: `PlcExitIncompleteWarning`, about 240 px at 14 px, one line. The height still comes from the content.
+
+- Reason 1 matches acceptance smoke step 5 ("нет связи с ПЛК").
+- Reason 5 matches the H3 notification "Идёт выполнение рецепта". `ErrorRecipeActive` (`Resources.ru.resx:238-239`, "Рецепт выполняется на ПЛК") is a full sentence and does not fit after a colon.
+- Reason 2 uses the dialog's own term, `Конфликт рецептов` (`PlcConflictTitle`, `:187-188`).
+- Reason 3 uses the slot's term "сравнение рецептов".
+- Reasons 4 and 5 double as the NotWritten tooltip causes in section 1.
+
+### Buttons and keys
+
+- Order, left to right: `Закрыть без записи`, `Отмена`. Windows puts the commit action first and Cancel last. The existing dialog follows the same order (`ExitConfirmationDialog.axaml:31-40`).
+- `Отмена` has `IsDefault="True"` and `IsCancel="True"`, so Enter and Esc both cancel. It gets the dialog's one `Classes="primary"`. D1 gives the accent to the one primary button only (`decisions.md:4`), and here the primary button is the safe default.
+- `Закрыть без записи` gets `Classes="secondary"`. It is not styled as destructive: the local recipe is already saved or discarded at G2, and nothing local is lost.
+- `Отмена` takes focus at open.
+- The `primary` and `secondary` classes are copied from `ExitConfirmationDialog.axaml:32,35`. No app style defines them, so Semi owns their look. Their effect was not checked in a running app.
+- Button widths at 14 px: "Закрыть без записи" 125, "Отмена" 49. With Semi button padding, both fit the 368 px content width on one line.
+
+## 3. Busy look during the exit send (G4, up to 5 s)
+
+The app has no window-level busy pattern: no overlay, no wait cursor, no progress control (grep of `SemiStep.UI`). The busy pattern that exists is the sync toggle's wait of up to 5 s:
+
+- The switch is disabled with a grey track (`RecipeToolBar.axaml:16`) and a grey caption (`:77-79`).
+- The link slot shows "ПЛК: отключение…" with a hollow dot (`PlcLinkView.cs:24`, `:35`).
+
+The take of the PLC recipe (plan row A2) reuses the overlay and key blocking below. During the take the link slot shows `TakeReading`, "ПЛК: чтение рецепта…" / "PLC: reading recipe…", with a hollow dot, as `ExitSending`. The read can last up to 10 s (plan row A5). A red "конфликт рецептов" with a wait cursor for that long would say the conflict is still open, while the operator has already chosen. Key: `LinkTakeReading`, about 125 px, 212 px with the override suffix. When the take ends, the slot follows the resolve order again.
+
+The exit send reuses the link slot part of that pattern and adds input blocking:
+
+- The link slot shows `ExitSending`, "ПЛК: запись рецепта…" with a hollow dot (section 1).
+- A transparent overlay `Panel` spans all rows of the `MainWindow.axaml:19` grid, with `Background="Transparent"` and `Cursor="Wait"`. It is visible only while the send runs. It takes pointer input, and the wait cursor shows over the whole window.
+- A tunnel `KeyDown` handler on the window marks every key handled while the send runs, so no grid key or menu gesture runs.
+- A close request during the send is refused, because the send runs inside the exit flow's app flow scope (plan, Terms and row G1). That scope replaces `_exitChoiceInProgress` (`MainWindow.axaml.cs:121-126`), which today covers only the unsaved path.
+- Controls are not greyed. Setting `IsEnabled=false` would switch every control and grid cell to its disabled look (`DataGridStyles.axaml:88`) for a send that usually takes well under a second, and the whole window would flash.
+- On success the window closes. On failure the overlay and the slot state clear before the exit dialog opens.
+- Test: a headless test sends a click and a key during a held send and asserts that neither changes the recipe or opens a menu.
+
+## 4. Window title
+
+The title "SemiStep - Рецепт из ПЛК *" is confirmed.
+
+- New key `WindowTitlePlcRecipe`: ru `Рецепт из ПЛК`, en `Recipe from PLC`. It sits next to `WindowTitleNewRecipe` (`Resources.ru.resx:214-215`).
+- `BuildWindowTitle` (`MainWindowViewModel.cs:302-311`) takes a third name source. A file path gives the file name. Untitled from the PLC gives `WindowTitlePlcRecipe`. Untitled otherwise gives `WindowTitleNewRecipe` (`:304-306`). The separator stays " - " (`:310`).
+- With a run: "SemiStep - Рецепт из ПЛК * [выполняется]", using `WindowTitleRunningSuffix` (`Resources.ru.resx:583-584`).
+- The name "Рецепт из ПЛК" ends when "Сохранить как" succeeds (file name), when New runs ("Новый рецепт") or when Open succeeds (file name). A cancelled or failed save keeps it (A4, E1).
+- The unsaved mark is always present right after a take, because the take marks the recipe unsaved (A2).
+
+## Esc on the conflict dialog
+
+`PlcConflictDialog` has no `IsCancel` button and no key handler (`PlcConflictDialog.axaml:41-46`, `PlcConflictDialog.axaml.cs`). Avalonia does not close a window on Esc by itself, so plan row A8 needs an Esc handler that closes the dialog without a choice. This is not verified in a running app.
+
+## Method
+
+- Widths are Pillow 12.2 measurements of `segoeui.ttf` and `SegUIVar.ttf`. Status bar text is measured at 12 px. Dialog text is measured at 14 px, which is assumed to be Semi's default body size; the app's dialog font size was not read from Semi. The app renders through HarfBuzz, so expect differences of about 1 to 3 px. Every width is an estimate.
+- The worst-case suffix host is `a 15-character host such as 203.0.113.200`.
+- Palette values come from `ConfigFiles/MBE/ui/grid_style.yaml:45-73`, installed by `CellPaletteInstaller.cs:56-73`.
+- Nothing was run in the app. Every behaviour claim about Avalonia (Esc, modal owners, the tunnel key handler) comes from reading code and needs the plan's tests.
diff --git a/docs/plans/20261130-recipe-replace-save-exit-safety.md b/docs/plans/20261130-recipe-replace-save-exit-safety.md
new file mode 100644
index 0000000..8499e43
--- /dev/null
+++ b/docs/plans/20261130-recipe-replace-save-exit-safety.md
@@ -0,0 +1,348 @@
+# Recipe replace, save and exit safety
+
+## Behavior
+
+Today several paths replace, save or drop the operator's recipe without asking, or let the screen
+and the PLC disagree without saying so:
+
+- Taking the PLC recipe keeps the old file name, so Ctrl+S overwrites that CSV (#234).
+- Taking the PLC recipe drops unsaved edits without a prompt, and the undo history is cleared.
+- Closing the conflict dialog without a choice leaves sync on, and the next edit overwrites the PLC recipe.
+- A write can reach the PLC after the app found a conflict and before the operator answered it.
+- Sync can write the local recipe before the reconnect comparison reads the PLC one (#181). A failed read also writes the local recipe.
+- The link slot shows green "ПЛК: подключено" while the PLC holds another recipe: after a reconnect, with a recipe that has warnings, or with a write parked until a run ends.
+- A CSV that passes the file check but fails analysis empties the session while the grid still shows the old steps.
+- A recipe with any warning cannot be saved.
+- Exit closes silently while the PLC holds something other than the screen recipe.
+
+After this work, one rule holds everywhere: while sync is on, the PLC gets only the screen recipe,
+and only after the operator could see any difference. The link slot never claims the PLC matches
+when it does not. When the app cannot keep this true, it turns sync off and says why in the
+notification panel, which keeps the message until the operator dismisses it. A dialog appears only
+when the operator has a choice to make. A local file changes only when the operator saves.
+
+Scope guard:
+- The conflict dialog keeps its two choices and its texts ("Оставить локальный", "Загрузить из ПЛК").
+- The unsaved-changes prompt keeps its three choices and its look.
+- New and Open with sync on still write the new recipe to the PLC, unless a write pause holds.
+- A recipe with warnings is still not written to the PLC.
+- A write refused during a run is still parked and written at run end.
+- A failed write still shows red "ПЛК: ошибка синхронизации".
+- Turning sync on still reports a failed connect or version read through the switch, and sync stays off, as today.
+- Windows shutdown and logoff still close without prompts. The recovery copy is #242.
+
+## Terms
+
+- **Prompt**: the existing "Сохранить изменения?" dialog with "Сохранить", "Не сохранять" and "Отмена".
+- **Untitled**: no file name. The title reads "SemiStep - Рецепт из ПЛК *", and Ctrl+S opens "Сохранить как".
+- **Write pause**: a period when the app sends nothing to the PLC. Edits stay on screen. When the pause ends with a write, the latest screen recipe is sent.
+- **Comparison**: the reconnect step that reads the protocol version and the PLC recipe and compares the recipe with the screen recipe. One comparison runs at a time.
+- **Comparison ID**: a number the app gives each comparison. A link drop, a new comparison or sync off makes every older ID stale. Anything carrying a stale ID is ignored: a result, a failed read, a conflict.
+- **In sync**: the PLC confirmed the current screen recipe, or the screen recipe was just taken from the PLC. A link drop, a comparison start, a conflict and any edit end it until the PLC confirms again.
+- **App flow**: the span from the start of an operator command that can open a dialog to the end of that command, gaps between chained dialogs included. Commands: New, Open, Save and Save As (Save opens a picker on an untitled recipe), the style settings window, the conflict dialog with its take, the exit flow with its send. Teardown runs after the window closes, in `Program.DisposeServices` with its existing 10 s bound, and is not part of any flow. A native file picker inside a command is part of its flow. The app counts flows with a scope that ends in `finally`, so an exception cannot leave one open. The exit flow uses the same scope; no second flag guards close.
+- **Transport deadline**: every single request to the PLC ends within 5 s: one connect attempt, one block read, one block write. A whole recipe write is many requests, and each gets its own deadline. Passing the deadline closes the client and declares link loss, as the keep-alive probe does. A write cut off this way counts as a failed write.
+- **Busy look**: the window takes no pointer or key input, shows a wait cursor, and greys nothing. Used during the exit send and the take.
+- **Link slot**: the status bar field that shows the PLC link state. Its texts and order are in the UI design.
+
+## Flow branches
+
+### Write pause, comparison and link slot (#181)
+
+| # | Situation | The app does | Decided by | Checked by |
+|---|---|---|---|---|
+| D1 | Sync turns on, or the link drops | A write pause starts. A write already in flight finishes or fails as today | operator (#181); agent: start at link loss, because a reconnect inside the 1 s debounce would write first | D1 tests |
+| D2 | The link slot while sync is on | Follows the UI design order: "нет связи", "ПЛК: чтение рецепта…" (during the take), "ПЛК: конфликт рецептов", "ПЛК: сравнение рецептов…", red "ошибка синхронизации", "ПЛК: рецепт не записан" (warnings, or a write parked until run end), green "подключено". A normal write in its 1 s debounce or in flight shows green, because it is being delivered | operator: status for waiting states, dialog for decisions; agent: no grey flash after every edit | D2 tests |
+| D3 | Comparison: identical, PLC empty, or PLC has no committed recipe | The pause ends, and the latest screen recipe is written | agent | D3 test |
+| D4 | Comparison: recipes differ | A conflict starts. The pause holds until the conflict ends (A rows) | operator | D4 test |
+| D5 | Comparison: screen recipe empty, no unsaved changes, PLC recipe not empty | Takes the PLC recipe without a dialog (B rows). The pause ends with nothing to write | existing, now untitled | B tests |
+| D6 | A read fails during the comparison, the version read included, or a read passes the transport deadline | The app closes the connection and declares link loss, as the keep-alive probe does. The reconnect loop connects again, and a new comparison runs. Sync stays on | agent: only the keep-alive probe and the execution monitor declare link loss today | D6 tests |
+| D6a | Any PLC request passes the transport deadline: a connect attempt, a request of the take read, the exit send, a normal write, or the keep-alive probe | The client closes, and link loss is declared. The link slot shows "нет связи". No busy look or flow waits longer than the deadline | agent: a hung transaction blocks the keep-alive probe behind the transport gate, so no other path would notice | D6a tests, one per transaction kind |
+| D7 | Three comparisons in a row fail within one sync-on period | Sync turns off. Notification: "Не удалось прочитать рецепт из ПЛК. Синхронизация выключена." | operator: no write after a failed read; agent: the cap ends an endless retry on a PLC-side fault | D7 test |
+| D8 | The PLC reports a different protocol version on reconnect | Sync turns off with the existing version message. Today it only logs. The comparison that runs on the first connect of a sync-on starts only after turning sync on has read the version, and skips its own version read. A mismatch there makes that comparison stale (D10), so it never writes to a mismatched PLC. D6 and D7 apply to its recipe reads | agent: one version report per failure | D8 tests |
+| D9 | The comparison throws | Counts as a failed read (D6, D7) | agent | D9 test |
+| D10 | Anything with a stale comparison ID arrives: a result, a failed read, a conflict, or a conflict answer clicked before a link drop | Ignored. A stale failed read neither closes the connection nor counts toward D7. A stale "Оставить локальный" writes nothing | agent | D10 tests |
+| D11 | New or Open during a pause | The new recipe shows and is not written. The comparison treats it like any screen recipe. An empty recipe from New is replaced by a non-empty PLC recipe (D5), because it holds nothing to lose | agent | D11 test |
+| D12 | The app turns sync off (D7, D8, A7, A8, A9, B4) while the operator presses the sync switch | Sync on and off run one at a time. The switch remembers the direction at the press and acts after the app's turn-off ends. A press to turn off finds sync already off and does nothing. The app never turns sync off from inside the comparison or the reconnect loop; it posts the turn-off | agent: a turn-off overlapping a new turn-on would kill the new session | D12 tests |
+
+### Conflict dialog
+
+| # | Situation | The app does | Decided by | Checked by |
+|---|---|---|---|---|
+| A1 | "Оставить локальный" | The pause ends, and the screen recipe is written. With warnings it is not written, and the link slot shows "ПЛК: рецепт не записан" | existing | A1 tests |
+| A2 | "Загрузить из ПЛК", no unsaved changes | The window gets the busy look. The app reads the PLC recipe again, checks it, checks once more that the screen has no unsaved changes (if it now has, A3 applies), and loads it untitled and marked unsaved. Undo and redo history are cleared. Nothing is written back. The link slot shows "подключено", and the pause ends | operator; agent: read again because the dialog may have waited, and block input so no edit lands during the read | A2 tests |
+| A3 | "Загрузить из ПЛК", unsaved changes | Prompt first. "Сохранить" saves to the file, or opens "Сохранить как" when untitled, then takes as in A2. "Не сохранять" takes. "Отмена" or X returns to the conflict dialog. The link slot shows the conflict until the take starts reading | operator | A3 tests |
+| A4 | The save in A3 fails, or "Сохранить как" is cancelled | Nothing is taken, and the conflict dialog returns | agent: same rule as New and Open | A4 test |
+| A5 | The read again in A2 fails, or the whole read passes 10 s | Nothing changes. The busy look ends. Notification: "Не удалось прочитать рецепт из ПЛК." The conflict ends, and D6 applies | agent: the transport deadline bounds each request, not the whole read; designer: the failure must not be silent | A5 tests |
+| A6 | The read again returns a recipe identical to the screen, or an empty or uncommitted one | Identical: the conflict ends, and the status is in sync. Empty or uncommitted: the conflict ends as D3, and the notification panel says "Рецепт в ПЛК отсутствует. Записан рецепт с экрана." | agent: the PLC recipe the operator chose no longer exists | A6 tests |
+| A7 | The PLC recipe fails the check on take, for example loops nested deeper than 3 | Nothing changes. Sync turns off. Notification: "Рецепт из ПЛК не загружен: <причина>. Синхронизация выключена." | agent | A7 test |
+| A8 | The conflict dialog closes with X, Esc or Alt+F4 | Sync turns off, and nothing is written or replaced. Notification: "Синхронизация выключена: конфликт рецептов не решён." Turning sync on compares again. Esc gets a handler, because the dialog has none today | operator | A8 tests |
+| A9 | The conflict dialog cannot be shown | Same as A8, plus the existing error | agent | A9 test |
+| A10 | The link drops while the conflict dialog is open | The dialog closes with its own "link lost" result, which is not A8, and sync stays on. The pause holds, the link slot shows "нет связи", and the next connect compares again | agent: the PLC recipe in the dialog may be outdated, and a flapping link must not turn sync off | A10 test |
+| A11 | The link drops while the A3 prompt or "Сохранить как" is open | The save still runs if chosen. Then the take is abandoned, and the conflict dialog does not return. The next connect compares again | agent: the app cannot close a native file picker | A11 test |
+| A12 | A conflict starts during an app flow | The conflict waits, and the link slot shows "ПЛК: конфликт рецептов". When the flow ends, a new comparison runs against the current screen recipe: it may end the conflict (D3, D5) or open the dialog with current step counts. Example: Open picks a file behind a waiting conflict, the file shows and is not written, then the comparison runs against it | operator | A12 tests |
+| A13 | A second conflict while one is open or waiting | Cannot happen: one comparison runs at a time, each new comparison makes the older ID stale (D10), and a link drop ends the current conflict (A10, A11). At most one conflict dialog exists | agent | invariant test |
+| A14 | A run starts on the PLC while the dialog is open | "Загрузить из ПЛК" works as A2 or A3. "Оставить локальный" parks the write until the run ends, and the link slot shows "ПЛК: рецепт не записан" | existing decision 35 | A14 test |
+
+### Taking the PLC recipe on reconnect without a dialog
+
+| # | Situation | The app does | Decided by | Checked by |
+|---|---|---|---|---|
+| B1 | The D5 case | Just before the take, the app checks again on the UI thread: screen recipe empty, no unsaved changes, no app flow. Then it takes untitled, as A2 without the read again | operator: untitled rule; agent: the first check runs off the UI thread | B1 tests |
+| B2 | The B1 check fails: the screen recipe has steps or unsaved changes, for example every step deleted | A conflict starts instead (A rows) | agent: an empty recipe can still be unsaved work | B2 test |
+| B3 | The B1 check fails because an app flow runs | A conflict waits (A12) | agent: a take behind an open dialog would hide | B3 test |
+| B4 | The B1 take fails the check | Same as A7 | agent | B4 test |
+
+### Load and save
+
+| # | Situation | The app does | Decided by | Checked by |
+|---|---|---|---|---|
+| E1 | Open of a CSV that passes the file check but fails analysis | Nothing changes: recipe, grid, undo, unsaved mark, file name and title. The error goes to the notification panel | operator | E1 test |
+| F1 | Save of a recipe with warnings, for example a loop without an end | Saves. The file opens again with the same warnings | operator | F1 round-trip test |
+
+### Exit
+
+| # | Situation | The app does | Decided by | Checked by |
+|---|---|---|---|---|
+| G1 | A close request during an app flow, from the taskbar or the title bar | While a dialog or picker is open, or the busy look shows: ignored, and the app activates its topmost open window, which brings a native picker forward with its owner. In a flow phase without either, for example the file write of a save: the close request is kept and runs the normal exit checks when the command ends | agent: one flow at a time; close is ignored only while something visible and bounded is in front | G1 tests, smoke step 4 |
+| G2 | Unsaved changes | The prompt first, as today. "Отмена" or X stops the exit before anything is written | existing | existing test |
+| G3 | Sync off, or in sync | Closes | existing | existing test |
+| G4 | Sync on, not in sync, and a write is allowed: link up, no pause, no conflict, no warnings, no run | The window gets the busy look, and the link slot shows "ПЛК: запись рецепта…". The app sends the current screen recipe now. The send runs through the one write path: it waits for a write already in flight and then writes the current recipe if that write held an older one, or it replaces the waiting one, so two writes never mix. Success means the PLC confirmed the current screen recipe. The UI stops waiting after 5 s whether or not the send honors cancellation, and the busy look ends in every case. On success the window closes | operator; agent: a send that ignores cancellation must not freeze the window | G4 tests |
+| G5 | The G4 send fails or times out, or a write is not allowed | The window stays. Exit dialog "Рецепт не записан в ПЛК" with the reason, "Закрыть без записи" and "Отмена". After a failed, timed-out or link-cut send the dialog says the PLC recipe may be incomplete, because a write marks the PLC recipe uncommitted before it writes the steps. "Закрыть без записи" closes the window at once. Teardown then runs after the window is gone, with its existing 10 s bound | operator | G5 tests |
+| G6 | Exit dialog, "Отмена" or X | The window stays, and sync continues. A later close runs the same checks again from G2 | agent: X means "Отмена", as in the prompt | G6 test |
+| G7 | A conflict starts during the exit flow | It waits like any conflict during an app flow (A12). If the window closes, the conflict ends with it. If the operator cancels the exit, a new comparison runs and may open the conflict dialog | agent | G7 tests |
+| G8 | Windows shutdown or logoff | Closes with no prompt and no write, as today (#242) | existing | none |
+
+### Minor
+
+| # | Situation | The app does | Decided by | Checked by |
+|---|---|---|---|---|
+| H1 | Undo or redo back to the saved state | The unsaved mark clears, and returns on the next step away | agent | H1 test |
+| H2 | An edit while a save is writing | The edit keeps its unsaved mark | agent | H2 test |
+| H3 | A run starts while the New or Open prompt or picker is open | Notification: "Идёт выполнение рецепта: открыть или создать рецепт нельзя." Today it does nothing silently | agent | H3 test |
+| H4 | The unused `LoadRecipeFromPlcAsync` path | Deleted. The test that calls it uses the production take path instead | agent: no production caller | build, H4 test |
+| H5 | The save temporary file | Flushed to disk before it replaces the target | agent | review |
+
+## Decisions
+
+- A dialog appears only for a choice. Waiting states show in the link slot: a comparison takes under a second on a healthy link and would flash a dialog on every reconnect, and a second modal on top of an open one is unsafe. rejected: a modal for waiting states.
+- Any state where the PLC cannot follow the screen ends with sync off and a notification, or with a dialog the operator answers. Every pause and every stuck not-written state shows in the link slot. rejected: holding writes after the conflict dialog closes without a choice.
+- The write pause during a conflict lasts until the conflict ends, also while the conflict waits for an app flow. rejected: turning sync off whenever a conflict meets an open dialog.
+- The write pause starts at link loss, not at reconnect.
+- A failed comparison read counts as a link drop, and three failures in a row turn sync off. A version mismatch on reconnect turns sync off at once. rejected: telling link errors from PLC-side errors by error type. The driver reports most socket faults as a generic command failure.
+- A waiting conflict compares again when the app flow ends, and "Загрузить из ПЛК" reads again before it takes. rejected: acting on a recipe read before a long wait.
+- "Waiting for the operator" is tracked per command flow, not per open window. A native picker is not an app window, and the gap between a prompt and its picker would otherwise read as idle.
+- A taken PLC recipe is untitled and marked unsaved, and the take writes nothing back. rejected: keeping the old file name.
+- "Отмена" in the take prompt returns to the conflict dialog. rejected: treating it as closing the conflict dialog, which turns sync off on a misclick.
+- A close request during an app flow is ignored and brings the flow's window forward. rejected: treating a close during the conflict dialog as closing the dialog, which turned sync off as a side effect of exit.
+- Exit asks whenever the PLC is not in sync, not only when a write is waiting. A failed write is dropped by `PlcSyncCoordinator.ApplyFailure`, so "a write is waiting" misses it.
+- The exit send lives in `PlcSyncCoordinator`, so it shares the one write path. rejected: a separate send that could interleave with the debounced write.
+- The link slot shows green during a normal write's debounce. rejected: a grey "не записан" flash after every edit.
+- The new exit dialog uses margins 16 and spacing 8 from the designer's scale. The existing prompt keeps 20 and 10, per the scope guard.
+- Hard to reverse: none. No file or PLC format changes.
+
+## UI design
+
+The designer's spec is `docs/plans/20261130-recipe-replace-save-exit-safety-ui.md`. The implementing
+agent builds it as written:
+
+- link slot kinds `Comparing` "ПЛК: сравнение рецептов…", `Conflict` "ПЛК: конфликт рецептов", `NotWritten` "ПЛК: рецепт не записан", `ExitSending` "ПЛК: запись рецепта…", their dots, tooltips and the resolve order
+- the exit dialog `PlcExitDialog`: title "Рецепт не записан в ПЛК", line "ПЛК не получил текущий рецепт: <причина>.", question "Закрыть программу без записи в ПЛК?", buttons "Закрыть без записи" and "Отмена", the reasons in precedence order
+- the busy look: transparent overlay with a wait cursor, keys blocked, controls not greyed. The take (A2) reuses it, with the link slot kind `Reading` "ПЛК: чтение рецепта…"
+- the "Рецепт в ПЛК может быть неполным." line shows whenever a send started and did not finish, whatever reason wins
+- the title "SemiStep - Рецепт из ПЛК *"
+
+## Caveats
+
+- The conflict dialog is modal, so the main window takes no input while it is open. `PlcConflictDialog` has no Esc handling (`SemiStep.UI/Plc/PlcConflictDialog.axaml:41-46`).
+- File pickers are `StorageProvider` calls, not app windows (`SemiStep.UI/MainWindow/MainWindow.axaml.cs:189`, `:206`). The app flow scope covers them.
+- ASSUMPTION: a close request from the taskbar reaches the main window's closing handler while a modal dialog or picker is open, and activating the main window brings its picker forward; fallback: G1 still holds, because the handler cancels; checked by: smoke step 4.
+- ASSUMPTION: Avalonia 12 lets the app close an open modal dialog from code (A10); fallback: the dialog's view model completes its result as "closed by link loss"; checked by: A10 test.
+- A native file picker cannot be closed by the app. A11 therefore acts after the picker returns.
+- Link loss is declared by the keep-alive probe (`SemiStep.Core/Plc/S7/S7Service.cs:256-278`) and the execution monitor (`SemiStep.Core/Plc/S7/S7Di.cs:44-47`). The keep-alive probe queues behind the transport gate, so a hung transaction also stops it. No transaction has a deadline today: `ReadRecipeFromPlcAsync` takes no token (`SemiStep.Core/Plc/PlcLifecycleManager.cs:233-236`), and the driver sets no timeout (`S7Driver.cs:27-35`). A read that fails returns `PlcCommandFailedError` (`PlcTransactionExecutor.cs:199-203`) and leaves the link state as is. `S7Service.DisconnectAsync` turns auto-reconnect off (`S7Service.cs:94-100`), so D6 must use the link-loss path, not disconnect.
+- `OnConnectionLost` does not close the transport, and `S7Driver.ConnectAsync` replaces its client without closing the old one (`S7Driver.cs:27-35`). Task 3 closes the old client in `ConnectAsync`, which covers D6 and keep-alive loss alike.
+- `HandleConnectionLost` changes the sync status only from `Syncing` (`SemiStep.Core/Plc/Sync/PlcSyncCoordinator.cs:147-157`), so `Synced` survives a link drop today. `PlcSyncStatus` also stays `Synced` during the debounce (`:97-121`). "In sync" is therefore a new Core query.
+- The existing write runs on its own token and does not stop on the caller's cancel (`PlcSyncCoordinator.cs:354-357`). G4 bounds the wait in the UI for this reason.
+- A write first marks the PLC recipe uncommitted with zero lines, then writes the steps (`PlcTransactionExecutor.cs:269-293`). An interrupted write leaves the PLC recipe incomplete. G5 says so.
+- No UI code reads `PlcSyncStatus.OutOfSync`. `PlcLinkViewModel.Resolve` falls to `Connected` (`SemiStep.UI/Plc/PlcLinkViewModel.cs:82-85`), and `PlcLinkViewModelTests.cs:185-187` pins that. The test changes.
+- `ValidateProtocolVersionAsync` fails both on a read error and on a mismatch (`PlcLifecycleManager.cs:160-169`). On reconnect, D6 takes the read error and D8 the mismatch. On first enable, both stay with the switch, as today (`:138-143`). The first connect raises `Connected` inside `EnableSync`'s connect (`S7Service.cs:208`, `PlcLifecycleManager.cs:301-316`), so the comparison would read the version a second time; D8 removes that read.
+- `RecipeSession.LoadAsCurrent` clears history and replaces the snapshot before it checks the analysis result (`SemiStep.Core/Recipes/RecipeSession.cs:139-146`), and it notifies sync (`:144`). E1 and A7 depend on reversing the order, and A2 on suppressing the notify.
+- `PlcLifecycleManager.EnableSync` turns sync on before it connects (`SemiStep.Core/Plc/PlcLifecycleManager.cs:135-136`), and `DisableSync` does not cancel a running comparison (`:186-204`). `MainWindowViewModel.ExecuteToggleSyncAsync` reads the direction when it runs, not at the press (`SemiStep.UI/MainWindow/MainWindowViewModel.cs:203`).
+- Reconnect writes the local recipe on a failed read (`PlcLifecycleManager.cs:361`, `:387`). A version failure on reconnect only rolls back without the disable path (`:341-351`).
+- "Local empty" is read on a pool thread (`PlcLifecycleManager.cs:395`, `:409`).
+- A failed write is consumed and not re-queued (`PlcSyncCoordinator.cs:424-459`). Only a parked write retries (`:479-509`).
+- Teardown disposes `PlcSyncCoordinator`, which cancels the debounce (`PlcSyncCoordinator.cs:182`). The G4 send runs before teardown. Teardown runs after `App.Run` returns, bounded at 10 s (`SemiStep.UI/Program.cs:79-93`, `docs/architecture/exit-flow.md`), and stays there.
+- The reconnect loop's connect takes no token (`S7Driver.cs:35`), and `S7Service.DisconnectAsync` waits for that loop (`S7Service.cs:103-111`). The transport deadline on a connect attempt bounds both.
+- ASSUMPTION: the S7 driver client returns from a hung connect, read or write when its token is cancelled, its own timeout passes, or the client is closed from another thread, and the transport gate is released afterwards; fallback: the deadline abandons the hung call, replaces the client, and releases the gate itself; checked by: the probe at the start of Task 3a, against a TCP listener that accepts and never answers. The result goes here as `probed:`.
+- The conflict signal fires without checking for other dialogs (`MainWindowViewModel.cs:113-117`), and the dialog shows step counts captured at detection (`:234-235`).
+- A null file path renders "Новый рецепт" (`MainWindowViewModel.cs:304-306`). `CurrentFilePath` has a private setter (`SemiStep.UI/RecipeFile/RecipeFileViewModel.cs:74-78`) that the reconnect take path (`SemiStep.UI/Coordinator/RecipeCoordinator.cs:400`) cannot reach.
+- Sync is never on at startup; the sync switch is its only trigger (`MainWindowViewModel.cs:213`). A fresh PLC emulator holds no recipe, shows the last write in a message line in its window, and loses its memory when it closes (`SemiStep.Tools.PlcEmulator/README.md`).
+
+## Constraints and non-goals
+
+- One owner per decision. Taking the PLC recipe runs through one path used by A2, A3 and B1. The write pause, the comparison ID, the sync on/off serialization, "in sync" and the exit send have one owner in Core. App flows have one counter in the UI.
+- Every app-initiated turn-off uses the existing disable path, posted outside the comparison and the reconnect loop.
+- No softlock: from every dialog in these flows, one action always leads out without writing anything. These are closing the conflict dialog (A8), "Отмена" in the prompt (back to the conflict dialog, then A8), and "Закрыть без записи" (G5). The busy look always ends: within 5 s for the exit send and 10 s for the take read, both bounded in the UI whatever the PLC does. The sync switch always works once an app turn-off has finished (D12).
+- No invisible pause: every pause and every stuck not-written state shows in the link slot. Every pause ends at a comparison result, a conflict end, a link drop followed by a new comparison, or sync off.
+- Out of scope: the recovery copy (#242), noticing external changes to the open file, multiple windows, a "drop link" control in the emulator, an interrupted write outside exit, and restyling the existing prompt.
+- Tests check states and error types, not wording. See `docs/architecture/error-reporting.md`.
+
+## Gates
+
+- none
+
+## Acceptance
+
+- `dotnet build SemiStep.slnx` → 0 warnings, 0 errors
+- `dotnet test SemiStep/SemiStep.Tests/SemiStep.Tests.csproj` → 0 failed
+- `dotnet format SemiStep.slnx --verify-no-changes` → exit 0
+- each new test named in the tables fails on the commit before its task and passes after it; the PR body lists them
+- manual smoke against the PLC emulator (`SemiStep.Tools.PlcEmulator`, launch profile in its README):
+ 1. Start the emulator and the app with the emulator config. Turn sync on, open an MBE sample, and wait until the emulator's message line reports the written recipe. Turn sync off, edit a cell, turn sync on → the conflict dialog appears. Choose "Загрузить из ПЛК" → the prompt appears. After "Не сохранять" the title reads "SemiStep - Рецепт из ПЛК *", and the link slot shows "подключено"
+ 2. Turn sync off, edit a cell, turn sync on, then press Esc on the conflict dialog → sync is off, and the notification panel holds the conflict message
+ 3. Turn sync on, which brings the conflict dialog back. Choose "Оставить локальный" → the emulator holds the edited cell, and the link slot shows "подключено"
+ 4. Turn sync off, edit a cell, turn sync on. With the conflict dialog open, close the app from the taskbar → the conflict dialog comes to the front, and the app stays open. Choose "Оставить локальный"
+ 5. Close the emulator and wait until the link slot shows "нет связи". In the app, edit a cell, save with "Сохранить как" to a scratch file, then close the app → the exit dialog appears with "нет связи с ПЛК", and "Закрыть без записи" closes the app
+- covered by headless tests only: "ПЛК: сравнение рецептов…" (too short to see on localhost), a link drop while the conflict dialog is open, a conflict behind the Open picker, the three-failure cap, a send that ignores cancellation
+
+---
+
+## Context
+
+- Write pause, comparison ID, sync on/off: `PlcLifecycleManager` (`EnableSync`, `DisableSync`, `OnConnectionStateChanged`, `RunReconciliationAsync`, `ResolveRecipeDifferenceAsync`) and `PlcSyncCoordinator` (debounce, write attempt, park until run end, `NotifyRecipeChanged`, status).
+- Link loss: `S7Service.OnConnectionLost`, the reconnect loop, `S7Driver.ConnectAsync`.
+- Link slot: `PlcLinkViewModel.Resolve`, `PlcLinkView`, `PlcLinkKind`, `AppStatusBar.axaml`.
+- Conflict UI: `MainWindowViewModel.HandleConflictAsync` and the subscription in its constructor, `PlcConflictDialog`.
+- Sync switch: `MainWindowViewModel.ExecuteToggleSyncAsync`.
+- Load: `RecipeSession.LoadAsCurrent` and `LoadAsCurrentValidated`, `RecipeCoordinator.LoadRecipeAsync` and the reconnect apply callback.
+- Save and prompt: `RecipeFileViewModel`, `RecipeCoordinator.SaveRecipeAsync`, `CsvFileIo`.
+- Exit: `MainWindow.OnWindowClosing`, `HandleExitChoiceAsync`, `SemiStep.UI/ShutdownService/ExitConfirmationDialog`, `docs/architecture/exit-flow.md`. Teardown order: `S7Di`.
+- Dialogs and interaction handlers: `docs/architecture/dialogs-and-interactions.md`, `MainWindow.axaml.cs` handlers.
+
+## Boundaries
+
+- Task 3 adds, in Core: the write pause with calls to end it with a write or without one, the comparison ID, serialized sync on/off, and the transport deadline.
+- Task 4 adds the Core predicate the link slot uses for "не записан".
+- Task 5 adds one take-PLC path that returns whether the recipe was replaced. The conflict answers and the reconnect take call it, and nothing else replaces the session recipe from the PLC.
+- Task 6 adds the app flow counter. A12, B3 and G1 read it.
+- Task 7 adds the "in sync" query and the send-now call in `PlcSyncCoordinator`. Send-now writes the current screen recipe through the one write path and returns the failure reason.
+
+## Tasks
+
+Delivery: each of tasks 1 to 8 ships as its own PR, in this order, and Task 3 ships as two: 3a (the transport deadline, `S7Driver` closing the old client, and the probe) and then 3b (the rest). Each PR leaves the app consistent on its own and carries its own doc updates. Task 10 is a final consistency pass over the docs.
+
+### Task 1: A failed load changes nothing
+
+**Goal:** E1 and the load part of A7
+**Entry:** `RecipeSession.LoadAsCurrent`
+**Likely touches:** `RecipeSession.cs`, `RecipeCoordinator.cs`, `PlcLifecycleManager.ResolveConflict`
+
+- [ ] analyze first, and change the snapshot, history, unsaved mark and file name only on success
+- [ ] the conflict take checks the PLC recipe like reconnect does
+- [ ] tests: E1, and a failed PLC take leaves the session unchanged
+- [ ] run tests - must pass before the next task
+
+### Task 2: Save recipes with warnings
+
+**Goal:** F1
+**Entry:** `RecipeCoordinator.SaveRecipeAsync`
+
+- [ ] the save gate allows warnings. Writes to the PLC keep their own validity gate
+- [ ] remove the save rejection text that becomes unreachable
+- [ ] tests: F1 round trip through Open with the same warnings
+- [ ] run tests - must pass before the next task
+
+### Task 3: Write pause and comparison (#181)
+
+**Goal:** D1, D3 to D12, and A1 (except its link slot text, Task 4), A7, A8, A9 on the existing conflict dialog
+**Entry:** `PlcLifecycleManager.EnableSync`, `OnConnectionStateChanged`, `RunReconciliationAsync`
+
+- [ ] the write pause starts at sync on and at link loss. Each comparison result ends or keeps it as the tables say, the existing reconnect take included (ends without a write; a failed take turns sync off)
+- [ ] the existing conflict answers carry the comparison ID and end the pause: "Оставить локальный" with a write, "Загрузить из ПЛК" without one, a failed take check with sync off. Closing the dialog without a choice, Esc included, and a dialog that cannot be shown turn sync off with the notification
+- [ ] 3a: probe the S7 driver against a TCP listener that accepts and never answers (connect, read, write: token, timeout, close from another thread, gate release), record it in Caveats, then add the transport deadline and make `S7Driver.ConnectAsync` close the old client
+- [ ] 3b: the comparison ID. A failed comparison read or a passed deadline declares link loss. Three failures in a row, and a version mismatch on reconnect, turn sync off. The first-connect comparison skips the version read
+- [ ] serialized sync on/off, the switch direction taken at the press, and app turn-offs posted outside the comparison and reconnect loop
+- [ ] tests: every row in the goal, D6a, an edit during the connect, a reconnect inside the debounce
+- [ ] run tests - must pass before the next task
+
+### Task 4: Link slot states
+
+**Goal:** D2
+**Entry:** `PlcLinkViewModel.Resolve`
+
+- [ ] the "не записан" predicate in Core: warnings, or a write parked until run end
+- [ ] the kinds `Comparing`, `Conflict` and `NotWritten`, with texts, dots, tooltips and resolve order from the UI design
+- [ ] update `PlcLinkViewModelTests` for the `OutOfSync` case
+- [ ] tests: D2, one per kind, one per order conflict, green during the debounce, and the link slot parts of A1 and A14
+- [ ] run tests - must pass before the next task
+
+### Task 5: Taking the PLC recipe (#234)
+
+**Goal:** A2 to A6, B1, B2, B4, and A7 through the new take path
+**Entry:** `PlcLifecycleManager.ResolveConflict`, `RecipeCoordinator` reconnect apply callback
+
+- [ ] one take-PLC path: prompt when there are unsaved changes, busy look, read again, check, check unsaved once more, load untitled and marked unsaved, no write back
+- [ ] after the take, one Core call sets the sync status to `Synced`. This clears the error latch, so the link slot shows "подключено" even when a write failed at the link drop before the conflict
+- [ ] the untitled-from-PLC state in the file view model and the title pipeline
+- [ ] the reconnect take checks "empty, no unsaved changes" on the UI thread, and starts a conflict otherwise
+- [ ] the take read has a 10 s overall bound in the UI, the link slot shows the `Reading` kind, and the busy look ends in `finally`
+- [ ] tests: A2 to A7, B1, B2, B4, a key during the take changes nothing, a take read that never returns, and a take after a failed write shows "подключено"
+- [ ] run tests - must pass before the next task
+
+### Task 6: Conflict dialog and app flows
+
+**Goal:** A10 to A14, B3, G1
+**Entry:** `MainWindowViewModel.HandleConflictAsync`, the interaction handlers in `MainWindow.axaml.cs`
+
+- [ ] the app flow counter, scoped per command with `finally`, pickers and gaps between chained dialogs included
+- [ ] a conflict waits for the counter to reach zero, then a new comparison runs. A reconnect take waits as a conflict while a flow runs
+- [ ] a link loss closes the conflict dialog, or abandons a pending take after the picker returns
+- [ ] at most one conflict dialog. A close request during a flow activates the app's topmost window
+- [ ] a close request during a flow phase without a dialog or busy look is kept and runs when the command ends
+- [ ] tests: A10 to A14, B3, G1 (both cases), the gap between a prompt and its picker
+- [ ] run tests - must pass before the next task
+
+### Task 7: Exit when the PLC is not in sync
+
+**Goal:** G2 to G7
+**Entry:** `MainWindow.OnWindowClosing`
+
+- [ ] the "in sync" query and the send-now call in `PlcSyncCoordinator`. Success means the PLC confirmed the current screen recipe
+- [ ] after the prompt, check "in sync". When a write is allowed, send now with the busy look and the `ExitSending` slot state. The UI stops waiting after 5 s, and the busy look ends in `finally`
+- [ ] otherwise, or on failure, show `PlcExitDialog` with the reason. X means "Отмена"
+- [ ] a conflict that starts during exit waits, and a new comparison runs if the exit is cancelled
+- [ ] tests: G4 to G7, a send that ignores cancellation, a pending debounce at close, an edit queued behind a write in flight at close, and a click and a key during a held send change nothing
+- [ ] run tests - must pass before the next task
+
+### Task 8: Minor fixes
+
+**Goal:** H1 to H5
+**Entry:** `RecipeSession` history and `MarkSaved`, `RecipeFileViewModel`, `CsvFileIo`
+
+- [ ] the unsaved mark follows the saved point in undo history
+- [ ] an edit during a save keeps its mark
+- [ ] New and Open report a run that started during their dialog
+- [ ] delete `LoadRecipeFromPlcAsync`, move its test to the production path, and flush the temporary file before the move
+- [ ] tests: H1 to H4
+- [ ] run tests - must pass before the next task
+
+### Task 9: Verify acceptance
+
+**Goal:** every Behavior line, Flow branch and Acceptance item holds on master after the last PR
+**Entry:** the plan's `## Acceptance` section
+
+- [ ] every Behavior line and Flow branch is implemented
+- [ ] every Acceptance command passes with its expected result
+- [ ] full test suite: `dotnet test SemiStep/SemiStep.Tests/SemiStep.Tests.csproj`
+
+### Task 10: Update documentation
+
+**Goal:** docs describe the new behavior
+**Entry:** `docs/readme.md` (user guide, Russian), `docs/architecture/exit-flow.md`, `docs/architecture/dialogs-and-interactions.md`
+
+- [ ] user guide: taking the PLC recipe, the new link slot states, sync turning off with a reason, and exit when the PLC is not in sync
+- [ ] architecture: the mirror rule, the write pause, the comparison ID, the take-PLC path, and the app flow rule
+
+## Post-Completion
+
+- the operator's manual test: the Acceptance smoke steps
+- #181 and #234 close with their PRs