diff --git a/README.md b/README.md
index 5d2a69e..3d57afb 100644
--- a/README.md
+++ b/README.md
@@ -57,7 +57,7 @@ pwsh -File tools/Publish-Avalonia.ps1
`--import-recipes 原数据根目录` 可以导入已有配方,`--check-standalone` / `--check-runtime` 检查本地手部模型和使用模拟 AI 的步骤门控,`--check-gpu` 额外要求手部推理使用 GPU;这些本地诊断不代表真实 D3 接口联调成功。
-主界面每个步骤显示正常次数和异常次数:正常完成计入正常,异常跳过计入异常;按配方累计本次运行的结果,复位、停止或重新应用配方不会清零,重启软件后重新统计。
+主界面每个步骤显示正常次数和异常次数:正常完成计入正常,异常跳过计入异常;按配方保存在 `workspace/step-counts.json`,复位、停止、重新应用配方或重启软件均保留;仅点击“重置步骤”后的“重置计数”按钮,才会清零当前已应用配方的计数,不影响步骤进度及其他配方。
## 验证
diff --git a/src/SopHelper.Avalonia/Models/StepCountsStore.cs b/src/SopHelper.Avalonia/Models/StepCountsStore.cs
new file mode 100644
index 0000000..61f170a
--- /dev/null
+++ b/src/SopHelper.Avalonia/Models/StepCountsStore.cs
@@ -0,0 +1,51 @@
+using System.IO;
+using System.Text.Json;
+using SopHelper.Engine.Sop;
+using SopHelper.Presentation;
+
+namespace SopHelper.Models;
+
+/// 按配方持久保存步骤累计结果,独立于运行参数和配方编辑。
+public sealed class StepCountsStore(string root) : IStepCountStore
+{
+ private static readonly object FileGate = new();
+ public static StepCountsStore Current => new(DesktopPlatform.WorkspaceRoot);
+ public string FilePath => Path.Combine(root, "workspace", "step-counts.json");
+
+ private Dictionary> Read()
+ {
+ if (!File.Exists(FilePath)) return new(StringComparer.OrdinalIgnoreCase);
+ var all = JsonSerializer.Deserialize>>(File.ReadAllText(FilePath))
+ ?? throw new InvalidDataException("累计次数文件内容为空");
+ if (all.Values.Any(steps => steps is null || steps.Any(pair => pair.Key <= 0
+ || pair.Value.NormalCount < 0 || pair.Value.AbnormalCount < 0)))
+ throw new InvalidDataException("累计次数文件包含无效步骤或负数");
+ return new(all, StringComparer.OrdinalIgnoreCase);
+ }
+
+ public IReadOnlyDictionary Load(string recipeName)
+ {
+ lock (FileGate) return Read().GetValueOrDefault(recipeName) ?? [];
+ }
+
+ public void Save(string recipeName, IReadOnlyDictionary counts)
+ {
+ lock (FileGate)
+ {
+ var all = Read();
+ all[recipeName] = new(counts);
+ Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
+ var temporary = FilePath + ".tmp";
+ try
+ {
+ using (var stream = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None))
+ {
+ JsonSerializer.Serialize(stream, all, new JsonSerializerOptions { WriteIndented = true });
+ stream.Flush(flushToDisk: true);
+ }
+ File.Move(temporary, FilePath, overwrite: true);
+ }
+ finally { if (File.Exists(temporary)) File.Delete(temporary); }
+ }
+ }
+}
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml b/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml
index c3a2adc..627bfc2 100644
--- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml
@@ -94,6 +94,7 @@
+
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
index 1e8ceef..b486403 100644
--- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
@@ -102,6 +102,7 @@ public class SopPageViewModel : ViewModelBase
_camera = camera;
_pipeline = pipeline;
_engine = engine;
+ _engine.StepCountStore ??= SopHelper.Models.StepCountsStore.Current;
_engine.VisionDecisionClient ??= new ConfiguredVisionDecisionClient(VisionHttp);
_pipeline.ShouldDetectHands = () => _engine.RequiresHandDetection;
_dialogs = dialogs;
@@ -138,6 +139,7 @@ public class SopPageViewModel : ViewModelBase
StartStopCommand = new DelegateCommand(async () => await StartStopAsync(), CanStart);
TogglePauseCommand = new DelegateCommand(_engine.TogglePause, () => IsRunning);
ResetCommand = new DelegateCommand(_engine.Reset, () => IsRunning);
+ ResetCountsCommand = new DelegateCommand(ResetCounts, () => StepCards.Count > 0);
ApplyRecipeCommand = new DelegateCommand(ApplyRecipe, () => CanSelectCamera && !string.IsNullOrWhiteSpace(SelectedRecipe));
SnapshotCommand = new DelegateCommand(Snapshot, () => _lastFrame is not null);
EditRecipeCommand = new DelegateCommand(EditRecipe, CanEditRecipe);
@@ -348,6 +350,7 @@ public class SopPageViewModel : ViewModelBase
/// 复位
public DelegateCommand ResetCommand { get; private set; } = null!;
+ public DelegateCommand ResetCountsCommand { get; private set; } = null!;
public DelegateCommand DeleteRecipeCommand { get; private set; } = null!;
/// 应用配方
@@ -402,6 +405,7 @@ public class SopPageViewModel : ViewModelBase
StartStopCommand?.RaiseCanExecuteChanged();
TogglePauseCommand?.RaiseCanExecuteChanged();
ResetCommand?.RaiseCanExecuteChanged();
+ ResetCountsCommand?.RaiseCanExecuteChanged();
ApplyRecipeCommand?.RaiseCanExecuteChanged();
SnapshotCommand?.RaiseCanExecuteChanged();
EditRecipeCommand?.RaiseCanExecuteChanged();
@@ -592,6 +596,7 @@ public class SopPageViewModel : ViewModelBase
_engine.Load(new SopConfig());
ClearProcessImages();
StepCards.Clear(); Rois.Clear(); HandResult = null; _lastFrame = null;
+ ResetCountsCommand?.RaiseCanExecuteChanged();
ActiveRecipe = "未应用配方";
RaisePropertyChanged(nameof(InferenceBackendText));
RaiseCommands();
@@ -852,6 +857,8 @@ public class SopPageViewModel : ViewModelBase
StepCards.Add(card);
}
+ ResetCountsCommand.RaiseCanExecuteChanged();
+
foreach (var (name, def) in config.Sop.Regions)
Rois.Add(new RoiItem { Name = name, X = def.X1, Y = def.Y1, W = def.X2 - def.X1, H = def.Y2 - def.Y1, ColorHex = def.Color });
@@ -999,6 +1006,22 @@ public class SopPageViewModel : ViewModelBase
}
}
+ private void ResetCounts()
+ {
+ if (StepCards.Count == 0) return;
+ try
+ {
+ _engine.ResetStepCounts();
+ foreach (var card in StepCards) UpdateStepCounts(card, _engine.Statistics);
+ Log("info", "已重置当前配方的累计次数:" + ActiveRecipe);
+ }
+ catch (Exception error)
+ {
+ StatusText = "重置计数失败,累计次数已保留";
+ Log("warn", "重置计数失败:" + error.Message);
+ }
+ }
+
private static void UpdateStepCounts(StepCard card, SopRunStatistics statistics)
{
var counts = statistics.GetStepCounts(card.StepId);
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
index 6385694..8435867 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
@@ -79,15 +79,33 @@ public partial class SopEngine
public event Action? RoundFinished;
private readonly Dictionary _statistics = new(StringComparer.OrdinalIgnoreCase);
public SopRunStatistics Statistics { get; private set; } = new();
+ public IStepCountStore? StepCountStore { get; set; }
public SopRunStatistics GetStatistics(string recipeName)
{
lock (_statistics)
{
if (!_statistics.TryGetValue(recipeName, out var statistics))
- _statistics[recipeName] = statistics = new SopRunStatistics();
+ {
+ statistics = new SopRunStatistics();
+ if (StepCountStore is { } store)
+ {
+ statistics.RestoreStepCounts(store.Load(recipeName));
+ statistics.StepCountsChanged += counts =>
+ {
+ try { store.Save(recipeName, counts); }
+ catch (Exception error) { Log("warn", "累计次数保存失败:" + error.Message); }
+ };
+ }
+ _statistics[recipeName] = statistics;
+ }
return statistics;
}
}
+ /// 仅手动清零当前配方的步骤计数;先保存成功,再更新内存。
+ public void ResetStepCounts()
+ {
+ Statistics.ResetStepCounts(() => StepCountStore?.Save(_config.Sop.Name, new Dictionary()));
+ }
private DateTime _stepEnteredAt = DateTime.Now;
/// 当前运行状态
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopRunStatistics.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopRunStatistics.cs
index d11e013..752ff87 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopRunStatistics.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopRunStatistics.cs
@@ -2,6 +2,12 @@ namespace SopHelper.Engine.Sop;
public readonly record struct StepRunCounts(long NormalCount, long AbnormalCount);
+public interface IStepCountStore
+{
+ IReadOnlyDictionary Load(string recipeName);
+ void Save(string recipeName, IReadOnlyDictionary counts);
+}
+
/// Session statistics for one recipe; elapsed times exclude pauses.
public sealed class SopRunStatistics(TimeProvider? timeProvider = null)
{
@@ -21,6 +27,23 @@ public sealed class SopRunStatistics(TimeProvider? timeProvider = null)
{
lock (_gate) return _stepCounts.GetValueOrDefault(stepId);
}
+ internal event Action>? StepCountsChanged;
+ internal void RestoreStepCounts(IReadOnlyDictionary counts)
+ {
+ lock (_gate)
+ {
+ _stepCounts.Clear();
+ foreach (var (id, value) in counts) _stepCounts[id] = value;
+ }
+ }
+ internal void ResetStepCounts(Action persistReset)
+ {
+ lock (_gate)
+ {
+ persistReset();
+ _stepCounts.Clear();
+ }
+ }
internal void RecordStepResult(int stepId, bool normal)
{
lock (_gate)
@@ -28,6 +51,7 @@ public sealed class SopRunStatistics(TimeProvider? timeProvider = null)
var counts = _stepCounts.GetValueOrDefault(stepId);
_stepCounts[stepId] = normal ? counts with { NormalCount = counts.NormalCount + 1 }
: counts with { AbnormalCount = counts.AbnormalCount + 1 };
+ StepCountsChanged?.Invoke(new Dictionary(_stepCounts));
}
}
private TimeSpan RunningElapsed => _running ? _clock.GetElapsedTime(_since) : TimeSpan.Zero;
diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs
index 70ac7e4..e835fda 100644
--- a/tests/Avalonia.Smoke/Program.cs
+++ b/tests/Avalonia.Smoke/Program.cs
@@ -711,6 +711,18 @@ internal static class Smoke
decision.Result.SetResult(new(true,.99,"确认完成"));
for(var i=0;i<10&&engine.State!=SopHelper.Engine.Sop.EngineState.Completed;i++)await Emit();
Counts(2,0,0,2,"Later rounds accumulate each final step result exactly once");
+ var countStore=new StepCountsStore(store.Root);
+ var savedCounts=countStore.Load(name);
+ Check(savedCounts[1].NormalCount==2&&savedCounts[2].AbnormalCount==2,"Each final result is persisted before application exit");
+ void AfterRestart(Action check)
+ {
+ using var camera=new FakeCamera{Devices=[]};
+ using var pipeline=new SopHelper.Engine.Pipeline.DetectionPipeline(camera);
+ var fresh=new SopPageViewModel(camera,pipeline,new SopHelper.Engine.Sop.SopEngine(),app.Container.Resolve());
+ try{check(fresh);}finally{fresh.Destroy();}
+ }
+ AfterRestart(fresh=>Check(fresh.ActiveRecipe==name+".yaml"&&fresh.StepCards[0].NormalCount==2&&fresh.StepCards[1].AbnormalCount==2,
+ "A fresh engine and view model restore persisted counts at startup"));
var view=window.GetVisualDescendants().OfType().Single();
var texts=view.GetVisualDescendants().OfType().Select(t=>t.Text).ToArray();
Check(!texts.Contains("违规 Top3")&&!texts.Contains("完成次数")&&!texts.Contains("平均用时"),"Removed summary and violation panels are absent");
@@ -720,6 +732,33 @@ internal static class Smoke
var screenshots=Path.GetFullPath(Path.Combine("..","scratch","screenshots"));Directory.CreateDirectory(screenshots);
using(var rendered=new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width,(int)window.Bounds.Height)))
{rendered.Render(window);rendered.Save(Path.Combine(screenshots,"step-result-counts.png"));}
+ var resetButton=view.FindControl