diff --git a/src/SopHelper.Avalonia/Training/CameraFlowTest.cs b/src/SopHelper.Avalonia/Training/CameraFlowTest.cs index c2fddf8..a85b477 100644 --- a/src/SopHelper.Avalonia/Training/CameraFlowTest.cs +++ b/src/SopHelper.Avalonia/Training/CameraFlowTest.cs @@ -89,7 +89,7 @@ public sealed partial class CameraViewModel { var test = _flowTest; if (test is null) return; - FlowTestStatus = "标准视频播放结束,正在收取最后的 AI 判定…"; + FlowTestStatus = "标准视频播放结束,正在确认已缓存的连续操作证据…"; await test.FinishPendingDecisionAsync(); if (ReferenceEquals(_flowTest, test)) EndFlowTest("标准视频播放结束"); } diff --git a/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs b/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs index 2927106..6033c63 100644 --- a/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs +++ b/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs @@ -39,6 +39,7 @@ public sealed class SopVideoFlowTest : IDisposable snapshot.Sop.Model = null; _stride = Math.Max(1, snapshot.Sop.Settings.FrameStride); _engine.VisionDecisionClient = visionClient ?? new ConfiguredVisionDecisionClient(VisionHttp); + _engine.DecisionSubmitted += request => DecisionImageCaptured?.Invoke(request.Jpeg, request.FrameId); _engine.StepSnapshotChanged += step => { if (_steps.TryGetValue(step.StepId, out var previous) && previous.IsMet && !step.IsMet) return; @@ -78,7 +79,6 @@ public sealed class SopVideoFlowTest : IDisposable _engine.ProcessFrame(result, captureDecisionImage: region => { var jpeg = VisionDecisionImage.Encode(image, region); - DecisionImageCaptured?.Invoke(jpeg, result.FrameId); return jpeg; }); } diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.BufferedEvidence.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.BufferedEvidence.cs new file mode 100644 index 0000000..49ef03c --- /dev/null +++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.BufferedEvidence.cs @@ -0,0 +1,187 @@ +using SopHelper.Engine.Common; + +namespace SopHelper.Engine.Sop; + +public partial class SopEngine +{ + // 每个后续步骤只持有一份触发时的压缩图;AI 按工艺顺序消费,最多一个在途请求。 + private readonly Dictionary _bufferedSteps = []; + private int _nextCaptureIndex; + private long _observationSequence, _lastCaptureSequence; + private CaptureGate? _followingGate; + private sealed record CapturedDecision(VisionDecisionRequest Request, string Area) + { + public CaptureGate? Gate { get; init; } + } + private sealed record CaptureGate(ConditionEvaluator Evaluator, HandImageRegionTracker HandRegion) + { + public bool RequireRelease { get; set; } + } + + /// 实际发往 AI 的请求;排队取图不会提前触发这个事件。 + public event Action? DecisionSubmitted; + + private void ClearBufferedEvidence() + { + _bufferedSteps.Clear(); + _followingGate = null; + _nextCaptureIndex = _index; + _observationSequence = _lastCaptureSequence = 0; + } + + private static string? GetDecisionError(StepDef step) + { + if (string.IsNullOrWhiteSpace(step.Description)) return "请先填写步骤说明,AI 将按说明判断是否完成"; + if (!ConditionMethod.SupportsAiTrigger(step.Detection?.Method)) return "AI 确认需要手进入、离开区域或区域间移动触发"; + var options = step.AiConfirmation ?? new(); + if (!VisionImageMode.IsValid(options) || !double.IsFinite(options.MinConfidence) || options.MinConfidence is < 0 or > 1 + || options.RetryDelayMs < 0 || options.TimeoutSeconds <= 0) return "AI 确认配置无效"; + return null; + } + + private ConditionResult EvaluateAiStep(StepDef step, FrameResult frame, Func? captureJpeg, + Func? captureDecisionImage, out byte[]? evidence) + { + evidence = null; + if (GetDecisionError(step) is { } error) return new() { Message = error }; + var options = step.AiConfirmation ?? new(); + _handImageRegion.Observe(step, frame, _regions); + if (_pendingDecision is { } pending) + { + if (!pending.Task.IsCompleted) return new() { Message = "手部动作已触发取图,等待 AI 确认(后续动作继续取图)…" }; + _pendingDecision = null; + pending.Cancellation.Dispose(); + var decision = pending.Task.GetAwaiter().GetResult(); + _nextDecisionAt = Environment.TickCount64 + Math.Max(500, options.RetryDelayMs); + var met = decision.Completed && double.IsFinite(decision.Confidence) && decision.Confidence >= options.MinConfidence && decision.Confidence <= 1; + if (met) evidence = pending.Jpeg; + Log(met ? "info" : "warn", $"AI 步骤 {step.Id}:{decision.Reason}(置信度 {decision.Confidence:F2})"); + return new() { IsMet = met, Message = $"AI {(met ? "确认完成" : "未确认完成")}:{decision.Reason}" }; + } + if (VisionDecisionClient is not { } client) return new() { Message = "AI 接口或取图回调未配置" }; + + var buffered = _bufferedSteps.TryGetValue(_index, out var captured); + if (!buffered) + { + // EOF 收取结果时没有取图回调,不能拿结束画面伪造新触发。 + if (captureJpeg is null && captureDecisionImage is null) return new() { Message = "AI 接口或取图回调未配置" }; + ConditionResult trigger; + if (_nextCaptureIndex == _index && _followingGate is { } gate) + { + trigger = EvaluateCaptureGate(step, frame, gate); + _evaluator = gate.Evaluator; _handImageRegion = gate.HandRegion; + } + else trigger = _evaluator.EvaluateStep(step, frame); + if (!trigger.IsMet) return trigger; + if (Environment.TickCount64 < _nextDecisionAt) return new() { Message = "等待 AI 重试间隔,手部条件满足后重新取图" }; + _nextDecisionAt = Environment.TickCount64 + Math.Max(500, options.RetryDelayMs); + captured = CaptureDecision(step, frame, _handImageRegion, captureJpeg, captureDecisionImage, out error); + if (captured is null) return new() { Message = error! }; + } + var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(options.TimeoutSeconds)); + _pendingDecision = new(RunDecisionAsync(client, captured!.Request, cancellation.Token), captured.Request.Jpeg, cancellation); + if (buffered) + { + _bufferedSteps.Remove(_index); + if (captured.Gate is { } gate) { _evaluator = gate.Evaluator; _handImageRegion = gate.HandRegion; } + } + else if (_nextCaptureIndex <= _index) ArmFollowingStep(frame, step); + Log("info", $"步骤 {step.Id} 提交 AI 判定(原始帧 {captured.Request.FrameId},区域:{captured.Area}{(buffered ? ",使用连续操作缓存" : "")})"); + DecisionSubmitted?.Invoke(captured.Request); + return new() { Message = "手部动作已触发取图,等待 AI 确认(后续动作继续取图)…" }; + } + + private CapturedDecision? CaptureDecision(StepDef step, FrameResult frame, HandImageRegionTracker tracker, + Func? captureJpeg, Func? captureDecisionImage, out string? error) + { + error = null; + try + { + var options = step.AiConfirmation ?? new(); + var mode = VisionImageMode.Resolve(options); + RegionDef? region = null; + if (mode == VisionImageMode.FixedRegion) + { + region = _config.Sop.Regions.FirstOrDefault(p => p.Key.Equals(options.ImageRegion, StringComparison.OrdinalIgnoreCase)).Value; + if (region is null || captureDecisionImage is null) { error = "AI 取图区域不存在或未配置区域取图,未发送图片"; return null; } + } + else if (mode == VisionImageMode.Hand) + { + region = tracker.Resolve(options, frame); + if (region is null) { error = "未找到近期有效手部位置,等待手部重新触发取图"; return null; } + if (captureDecisionImage is null) { error = "未配置手部区域取图,未发送图片"; return null; } + } + var jpeg = captureDecisionImage is not null ? captureDecisionImage(region) : captureJpeg!(); + if (jpeg.Length == 0) { error = "AI 判定取图失败"; return null; } + var request = new VisionDecisionRequest(_config.Sop.Name, step.Id, step.Name, step.Description, + step.Description, frame.FrameId, frame.Timestamp, jpeg); + var area = region is null ? "整帧" : $"{(mode == VisionImageMode.Hand ? "手部附近" : options.ImageRegion)} [{region.X1},{region.Y1},{region.X2},{region.Y2}]"; + return new(request, area); + } + catch (Exception) { error = "AI 判定取图失败,请检查区域坐标与相机尺寸,等待重试"; return null; } + } + + private void ArmFollowingStep(FrameResult frame, StepDef predecessor) + { + _nextCaptureIndex = Math.Max(_nextCaptureIndex, _index) + 1; + _lastCaptureSequence = _observationSequence; + var next = StepAt(_nextCaptureIndex); + if (next is null) { _followingGate = null; return; } + var evaluator = new ConditionEvaluator(_config.Sop.Settings, _regions); + evaluator.NoteStepEntered(next.Id, frame.Timestamp); + var tracker = new HandImageRegionTracker(); + tracker.Observe(next, frame, _regions); + var repeatedEntry = predecessor.Detection is { } previous && next.Detection is { } condition + && previous.Method.Equals(ConditionMethod.HandInRegion, StringComparison.OrdinalIgnoreCase) + && condition.Method.Equals(previous.Method, StringComparison.OrdinalIgnoreCase) + && condition.Region.Equals(previous.Region, StringComparison.OrdinalIgnoreCase) + && condition.Hand.Equals(previous.Hand, StringComparison.OrdinalIgnoreCase); + _followingGate = new(evaluator, tracker) { RequireRelease = repeatedEntry }; + if (!repeatedEntry && next.Detection is not null) evaluator.EvaluateStep(next, frame); // 只登记轨迹,禁止同帧连过。 + } + + private bool IsHandInside(StepDef step, FrameResult frame) + { + var condition = step.Detection!; + if (!_regions.TryGetValue(condition.Region, out var region)) return false; + var hand = condition.Hand.ToLowerInvariant() switch + { + "left" or "左手" => frame.Hands.FirstOrDefault(h => h.HandType == HandType.Left), + "right" or "右手" => frame.Hands.FirstOrDefault(h => h.HandType == HandType.Right), + _ => frame.Hands.FirstOrDefault(h => h.HandType == HandType.Right) ?? frame.Hands.FirstOrDefault(), + }; + if (hand is null) return false; + var (x, y) = hand.Center; + return region.Contains(x, y, condition.Tolerance > 0 ? condition.Tolerance : _config.Sop.Settings.PositionTolerance); + } + + private void CaptureFollowingStep(FrameResult frame, Func? captureJpeg, Func? captureDecisionImage) + { + if (_nextCaptureIndex <= _index || _observationSequence <= _lastCaptureSequence + || _followingGate is not { } gate || StepAt(_nextCaptureIndex) is not { } step + || captureJpeg is null && captureDecisionImage is null || GetDecisionError(step) is not null) return; + var trigger = EvaluateCaptureGate(step, frame, gate); + if (!trigger.IsMet) return; + var captured = CaptureDecision(step, frame, gate.HandRegion, captureJpeg, captureDecisionImage, out var error); + if (captured is null) + { + Log("warn", $"步骤 {step.Id} 连续动作取图失败:{error}"); + return; + } + _bufferedSteps[_nextCaptureIndex] = captured with { Gate = gate }; + Log("info", $"步骤 {step.Id} 已缓存连续操作证据(原始帧 {frame.FrameId},区域:{captured.Area}),等待前序确认"); + StepSnapshotChanged?.Invoke(new() { StepId = step.Id, Name = step.Name, Message = $"动作已取图(帧 {frame.FrameId}),等待前序 AI 确认" }); + ArmFollowingStep(frame, step); + } + + private ConditionResult EvaluateCaptureGate(StepDef step, FrameResult frame, CaptureGate gate) + { + gate.HandRegion.Observe(step, frame, _regions); + if (gate.RequireRelease) + { + if (IsHandInside(step, frame)) return new() { Message = "等待手离开后再次进入,不能把同一次停留算作下一步" }; + gate.RequireRelease = false; gate.Evaluator.Reset(); + } + return gate.Evaluator.EvaluateStep(step, frame); + } +} diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs index f05423f..8984126 100644 --- a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs +++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs @@ -39,7 +39,7 @@ public enum EngineState /// SOP 状态机:加载配方 → 逐步判定 → 违规 → 日志。 /// 判定和日志都在这一层,UI 只订阅事件(引擎层不引用任何 WPF 类型)。 /// -public class SopEngine +public partial class SopEngine { private SopConfig _config = new(); private ConditionEvaluator _evaluator = null!; @@ -49,14 +49,14 @@ public class SopEngine private List _ordered = []; public IVisionDecisionClient? VisionDecisionClient { get; set; } - /// 视频输入结束后,允许消费已发送的最后一次 AI 判定。 - public bool HasPendingDecision => _pendingDecision is not null; + /// 包括在途 AI 请求和当前步骤已缓存、尚未送检的证据。 + public bool HasPendingDecision => _pendingDecision is not null || _bufferedSteps.ContainsKey(_index); private PendingDecision? _pendingDecision; private long _nextDecisionAt; - private readonly HandImageRegionTracker _handImageRegion = new(); + private HandImageRegionTracker _handImageRegion = new(); private sealed record PendingDecision(Task Task, byte[] Jpeg, CancellationTokenSource Cancellation); - private void InvalidateDecision() + private void InvalidateDecision(bool discardBuffered = true) { var pending = _pendingDecision; _pendingDecision = null; @@ -64,6 +64,7 @@ public class SopEngine pending?.Cancellation.Dispose(); _nextDecisionAt = 0; _handImageRegion.Reset(); + if (discardBuffered) ClearBufferedEvidence(); } private int _index; @@ -87,9 +88,10 @@ public class SopEngine /// 当前步骤(未完成的那一步) public StepDef? CurrentStep => State is EngineState.Idle or EngineState.Completed ? null : StepAt(_index); - /// 仅运行中的当前步骤需要手部条件时启用手部推理。 + /// 当前判定步骤或连续取图步骤需要手部条件时启用推理。 public bool RequiresHandDetection => State == EngineState.Running - && ConditionMethod.RequiresHandDetection(CurrentStep?.Detection?.Method); + && (ConditionMethod.RequiresHandDetection(CurrentStep?.Detection?.Method) + || ConditionMethod.RequiresHandDetection(StepAt(_nextCaptureIndex)?.Detection?.Method)); /// 配方(UI 显示步骤卡用) public SopConfig Config => _config; @@ -151,6 +153,7 @@ public class SopEngine _violations.Reset(); _index = 0; + _nextCaptureIndex = 0; _stepEnteredAt = DateTime.Now; _evaluator.NoteStepEntered(_ordered[0].Id, _stepEnteredAt); @@ -174,6 +177,7 @@ public class SopEngine _violations.Reset(); _index = 0; + _nextCaptureIndex = 0; _stepEnteredAt = DateTime.Now; if (StepAt(0) is StepDef first) _evaluator.NoteStepEntered(first.Id, _stepEnteredAt); @@ -221,12 +225,14 @@ public class SopEngine { if (State != EngineState.Running) return; + _observationSequence++; var step = StepAt(_index); if (step is null) return; // 1. 判定完成条件(稳定帧门控在 evaluator 里) byte[]? evidence = null; var result = EvaluateAiStep(step, frame, captureJpeg, captureDecisionImage, out evidence); + CaptureFollowingStep(frame, captureJpeg, captureDecisionImage); // 2. 违规:超时 / 必留物被拿走 var violation = _violations.CheckTimeout(step, _stepEnteredAt); @@ -257,7 +263,7 @@ public class SopEngine // 3. 推进 _index++; - InvalidateDecision(); // 重试间隔和跟手位置只属于刚完成的步骤。 + InvalidateDecision(discardBuffered: false); // 保留连续操作期间取得的后续步骤证据。 if (_index >= _ordered.Count) { @@ -284,69 +290,6 @@ public class SopEngine NotifyCurrent(); } - private ConditionResult EvaluateAiStep(StepDef step, FrameResult frame, Func? captureJpeg, Func? captureDecisionImage, out byte[]? evidence) - { - evidence = null; - if (string.IsNullOrWhiteSpace(step.Description)) - return new() { Message = "请先填写步骤说明,AI 将按说明判断是否完成" }; - var options = step.AiConfirmation ?? new AiConfirmation(); - if (!ConditionMethod.SupportsAiTrigger(step.Detection?.Method)) - return new() { Message = "AI 确认需要手进入、离开区域或区域间移动触发" }; - if (!VisionImageMode.IsValid(options) || !double.IsFinite(options.MinConfidence) || options.MinConfidence is < 0 or > 1 - || options.RetryDelayMs < 0 || options.TimeoutSeconds <= 0) - return new() { Message = "AI 确认配置无效" }; - _handImageRegion.Observe(step, frame, _regions); - if (_pendingDecision is { } pending) - { - if (!pending.Task.IsCompleted) return new() { Message = "手部动作已触发取图,等待 AI 确认…" }; - _pendingDecision = null; - pending.Cancellation.Dispose(); - var decision = pending.Task.GetAwaiter().GetResult(); - _nextDecisionAt = Environment.TickCount64 + Math.Max(500, options.RetryDelayMs); - var met = decision.Completed && double.IsFinite(decision.Confidence) && decision.Confidence >= options.MinConfidence && decision.Confidence <= 1; - if (met) evidence = pending.Jpeg; - Log(met ? "info" : "warn", $"AI 步骤 {step.Id}:{decision.Reason}(置信度 {decision.Confidence:F2})"); - return new() { IsMet = met, Message = $"AI {(met ? "确认完成" : "未确认完成")}:{decision.Reason}" }; - } - var trigger = _evaluator.EvaluateStep(step, frame); - if (!trigger.IsMet) return trigger; - if (Environment.TickCount64 < _nextDecisionAt) return new() { Message = "等待 AI 重试间隔,手部条件满足后重新取图" }; - // 配置缺失不能绕过 AI;限流,避免逐帧刷日志。 - _nextDecisionAt = Environment.TickCount64 + Math.Max(500, options.RetryDelayMs); - if (VisionDecisionClient is not { } client || captureJpeg is null && captureDecisionImage is null) - return new() { Message = "AI 接口或取图回调未配置" }; - try - { - RegionDef? region = null; - var mode = VisionImageMode.Resolve(options); - if (mode == VisionImageMode.FixedRegion) - { - region = _config.Sop.Regions.FirstOrDefault(p => p.Key.Equals(options.ImageRegion, StringComparison.OrdinalIgnoreCase)).Value; - if (region is null || captureDecisionImage is null) - return new() { Message = "AI 取图区域不存在或未配置区域取图,未发送图片" }; - } - else if (mode == VisionImageMode.Hand) - { - region = _handImageRegion.Resolve(options, frame); - if (region is null) return new() { Message = "未找到近期有效手部位置,等待手部重新触发取图" }; - if (captureDecisionImage is null) return new() { Message = "未配置手部区域取图,未发送图片" }; - } - var jpeg = captureDecisionImage is not null ? captureDecisionImage(region) : captureJpeg!(); - if (jpeg.Length == 0) return new() { Message = "AI 判定取图失败" }; - var request = new VisionDecisionRequest(_config.Sop.Name, step.Id, step.Name, step.Description, - step.Description, frame.FrameId, frame.Timestamp, jpeg); - var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(options.TimeoutSeconds)); - _pendingDecision = new(RunDecisionAsync(client, request, cancellation.Token), jpeg, cancellation); - var area = region is null ? "整帧" : $"{(mode == VisionImageMode.Hand ? "手部附近" : options.ImageRegion)} [{region.X1},{region.Y1},{region.X2},{region.Y2}]"; - Log("info", $"步骤 {step.Id} 手部触发取图,提交 AI 判定(帧 {frame.FrameId},区域:{area})"); - } - catch (Exception) - { - return new() { Message = "AI 判定取图失败,请检查区域坐标与相机尺寸,等待重试" }; - } - return new() { Message = "手部动作已触发取图,等待 AI 确认…" }; - } - private static Task RunDecisionAsync(IVisionDecisionClient client, VisionDecisionRequest request, CancellationToken token) => Task.Run(async () => { diff --git a/tests/VideoFlowTest.Smoke/Program.cs b/tests/VideoFlowTest.Smoke/Program.cs index f0aae5e..db39cdd 100644 --- a/tests/VideoFlowTest.Smoke/Program.cs +++ b/tests/VideoFlowTest.Smoke/Program.cs @@ -102,6 +102,7 @@ internal static class Program } } CheckRealtimePlayback(model.StandardVideoPath); + CheckContinuousPlayback(model.StandardVideoPath); // Unsupported condition exercises playback and incomplete results without hardware/models/API. config.Sop.Steps = [new StepDef { Id = 1, Name = "待配置步骤", Description = "验证当前编辑配置", Detection = new() { Method = "unsupported" } }]; model.FlowTestConfigProvider = () => config; @@ -171,6 +172,45 @@ internal static class Program Check(!playback.IsLoaded, "Stopping realtime playback releases the video reader"); } + private static void CheckContinuousPlayback(string path) + { + var config = new SopConfig(); config.Sop.Name = "AI延迟跨三步"; + for (var i = 0; i < 3; i++) + { + var key = "r" + i; + config.Sop.Regions[key] = new() { X1 = i * 20, Y1 = 0, X2 = i * 20 + 18, Y2 = 40 }; + config.Sop.Steps.Add(new() { Id = i + 1, Name = "连续操作" + (i + 1), Description = "区域内可见操作结果", + Detection = new() { Method = ConditionMethod.HandInRegion, Region = key, Hand = "right", StableFrames = 1, Tolerance = 1 }, + AiConfirmation = new() { ImageMode = VisionImageMode.FixedRegion, ImageRegion = key, TimeoutSeconds = 5 } }); + } + var fake = new MultiDecision(); + using var test = new SopVideoFlowTest(config, fake); test.Start(); + var playback = new RecordedVideoPlayback(); + playback.FrameProcessor = (image, id, _) => + { + var region = id < 3 ? 0 : id < 6 ? 1 : 2; + test.ProcessResult(new() { FrameId = id, Timestamp = DateTime.Now, Size = (64, 48), + Hands = [new Hand { HandType = HandType.Right, Rect = new(region * 20 + 4, 10, 6, 6) }] }, image); + }; + Pump(playback.PlayAsync(path)); + Until(() => playback.IsAtEnd); + Check(fake.Calls.Count == 1 && !test.IsCompleted && test.Details.Contains("动作已取图"), + "Continuous video captures later steps even when the first AI request lasts until EOF"); + var drain = test.FinishPendingDecisionAsync(); + for (var i = 0; i < 3; i++) + { + Until(() => fake.Calls.Count == i + 1); + var call = fake.Calls.ElementAt(i); + Check(call.Request.StepId == i + 1 && call.Request.FrameId / 3 == i, + "After EOF each AI request uses its own original action frame in process order"); + call.Result.SetResult(new(true, .99, "可见本步结果")); + } + Pump(drain); + Check(test.IsCompleted && test.Details.Split('✓').Length == 4, + "Buffered video actions complete all three steps without pausing playback or repeating actions"); + Pump(playback.StopAsync()); + } + private static void Until(Func ready) { var watch = System.Diagnostics.Stopwatch.StartNew(); @@ -191,4 +231,13 @@ internal static class Program public Task DecideAsync(VisionDecisionRequest request, CancellationToken cancellationToken) { Request = request; return Result.Task.WaitAsync(cancellationToken); } } + private sealed class MultiDecision : IVisionDecisionClient + { + public System.Collections.Concurrent.ConcurrentQueue<(VisionDecisionRequest Request, TaskCompletionSource Result)> Calls { get; } = new(); + public Task DecideAsync(VisionDecisionRequest request, CancellationToken cancellationToken) + { + var result = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Calls.Enqueue((request, result)); return result.Task.WaitAsync(cancellationToken); + } + } } diff --git a/tests/VisionDecision.Smoke/BufferedEvidenceChecks.cs b/tests/VisionDecision.Smoke/BufferedEvidenceChecks.cs new file mode 100644 index 0000000..8d33ed1 --- /dev/null +++ b/tests/VisionDecision.Smoke/BufferedEvidenceChecks.cs @@ -0,0 +1,195 @@ +using System.Collections.Concurrent; +using SopHelper.Engine.Common; +using SopHelper.Engine.Sop; + +internal static class BufferedEvidenceChecks +{ + public static async Task RunAsync() + { + await ContinuousSteps(); + await RejectionDoesNotSkip(); + await RepeatedEntryNeedsNewAction(); + await LeaveAndMoveEvidence(); + await LifecycleInvalidatesQueue(); + Console.WriteLine("PASS: 连续操作跨多步缓存、原始帧与裁剪、按序AI确认、拒绝不跳步、同区重新进入、离开/移动轨迹、暂停复位停止清空缓存"); + } + + private static SopConfig Config(int count = 3) + { + var config = new SopConfig(); config.Sop.Name = "连续操作"; + config.Sop.Settings.AutoResetOnComplete = false; + for (var i = 0; i < count; i++) + { + var key = "r" + i; + config.Sop.Regions[key] = new() { X1 = i * 60, Y1 = 0, X2 = i * 60 + 50, Y2 = 50 }; + config.Sop.Steps.Add(new() { Id = i + 1, Name = "操作" + (i + 1), Description = "区域内可见本步结果", + Detection = new() { Method = ConditionMethod.HandInRegion, Region = key, Hand = "right", StableFrames = 1, Tolerance = 1 }, + AiConfirmation = new() { ImageMode = VisionImageMode.FixedRegion, ImageRegion = key, RetryDelayMs = 0, TimeoutSeconds = 5 } }); + } + return config; + } + private static FrameResult Frame(long id, int? region) => new() + { + FrameId = id, Timestamp = new DateTime(2026, 11, 18).AddMilliseconds(id * 100), Size = (240, 80), + Hands = region is { } i ? [new Hand { HandType = HandType.Right, Rect = new(i * 60 + 10, 10, 10, 10) }] : [] + }; + private static SopEngine Engine(SopConfig config, DelayedClient client) + { + var engine = new SopEngine { VisionDecisionClient = client }; engine.Load(config); engine.Start(); return engine; + } + private static async Task Until(Func ready) + { + var watch = System.Diagnostics.Stopwatch.StartNew(); + while (!ready() && watch.Elapsed < TimeSpan.FromSeconds(3)) await Task.Delay(5); + Check(ready(), "异步判定未按预期完成"); + } + private static void Check(bool value, string message) { if (!value) throw new Exception(message); } + + private static async Task ContinuousSteps() + { + var client = new DelayedClient(); var engine = Engine(Config(), client); + var captured = new List<(long Frame, int Region, byte[] Jpeg)>(); + var completed = new List<(int Step, byte[]? Jpeg)>(); + engine.StepSnapshotChanged += s => { if (s.IsMet) completed.Add((s.StepId, s.EvidenceJpeg)); }; + for (var i = 0; i < 3; i++) + { + var frame = Frame(61 + i, i); + engine.ProcessFrame(frame, captureDecisionImage: region => + { + var jpeg = new byte[] { (byte)frame.FrameId, (byte)region!.X1 }; + captured.Add((frame.FrameId, region.X1, jpeg)); return jpeg; + }); + } + await Until(() => client.Calls.Count == 1); + Check(captured.Count == 3 && completed.Count == 0 && engine.CurrentStep!.Id == 1, + "第一步AI尚未返回时,后面两步必须完成独立取图且不能提前放行"); + for (var i = 0; i < 3; i++) + { + await Until(() => client.Calls.Count == i + 1); + var call = client.Calls.ElementAt(i); + Check(call.Request.StepId == i + 1 && call.Request.FrameId == 61 + i + && call.Request.CapturedAt == Frame(61 + i, i).Timestamp + && captured[i].Region == i * 60 && ReferenceEquals(call.Request.Jpeg, captured[i].Jpeg), + "后续AI必须使用该步骤操作发生时的原帧、时间和裁剪,不能换成当前结束画面"); + call.Result.SetResult(new(true, .99, "已完成")); + await Until(() => call.Result.Task.IsCompleted); + // EOF 之后只轮询缓存和判定,不再提供相机画面。 + await Until(() => { engine.ProcessFrame(Frame(999, null)); return completed.Count == i + 1; }); + if (i < 2) engine.ProcessFrame(Frame(999, null)); + } + Check(engine.State == EngineState.Completed && engine.Statistics.CompletedCount == 1 + && completed.Select(s => s.Step).SequenceEqual(new[] { 1, 2, 3 }) + && captured.Count == 3 && !engine.HasPendingDecision, + "连续三步必须按序确认、保留各自证据且只计一轮,不得要求重做动作"); + engine.Stop(); + } + + private static async Task RejectionDoesNotSkip() + { + var client = new DelayedClient(); var engine = Engine(Config(2), client); + engine.ProcessFrame(Frame(1, 0), captureDecisionImage: _ => [1]); + engine.ProcessFrame(Frame(2, 1), captureDecisionImage: _ => [2]); + await Until(() => client.Calls.Count == 1); + client.Calls.First().Result.SetResult(new(false, .99, "第一步不合格")); + await Until(() => { engine.ProcessFrame(Frame(3, null)); return !engine.HasPendingDecision; }); + Check(engine.CurrentStep!.Id == 1 && client.Calls.Count == 1, "第一步被拒绝时不能用后续动作或缓存跳过失败步骤"); + await Task.Delay(550); + engine.ProcessFrame(Frame(4, 0), captureDecisionImage: _ => [4]); + await Until(() => client.Calls.Count == 2); + client.Calls.Last().Result.SetResult(new(true, .99, "返工合格")); + await Until(() => { engine.ProcessFrame(Frame(5, null)); return engine.CurrentStep?.Id == 2; }); + engine.ProcessFrame(Frame(6, null)); + await Until(() => client.Calls.Count == 3); + Check(client.Calls.Last().Request is { StepId: 2, FrameId: 2 }, "前序返工确认后仍应保留后续原始动作证据"); + engine.Stop(); + } + + private static async Task RepeatedEntryNeedsNewAction() + { + foreach (var confirmEarly in new[] { false, true }) + { + var config = Config(2); config.Sop.Steps[1].Detection!.Region = "r0"; + var client = new DelayedClient(); var engine = Engine(config, client); + var captured = 0; + byte[] Capture() { captured++; return [(byte)captured]; } + for (var i = 1; i <= 4; i++) engine.ProcessFrame(Frame(i, 0), captureDecisionImage: _ => Capture()); + Check(captured == 1, "手在同一区域停留不能提前缓存后续同区进入步骤"); + await Until(() => client.Calls.Count == 1); + if (confirmEarly) + { + client.Calls.First().Result.SetResult(new(true, .99, "已完成")); + await Until(() => { engine.ProcessFrame(Frame(4, 0), captureDecisionImage: _ => Capture()); return engine.CurrentStep?.Id == 2; }); + engine.ProcessFrame(Frame(4, 0), captureDecisionImage: _ => Capture()); + Check(captured == 1, "前序AI提前确认后仍不能用同一次停留直接触发下一步"); + } + engine.ProcessFrame(Frame(5, null), captureDecisionImage: _ => Capture()); + engine.ProcessFrame(Frame(6, 0), captureDecisionImage: _ => Capture()); + Check(captured == 2, "重新离开并进入后必须捕获下一次操作,不能等待前序AI"); + engine.Stop(); + } + } + + private static async Task LeaveAndMoveEvidence() + { + foreach (var method in new[] { ConditionMethod.HandLeaveRegion, ConditionMethod.HandMove }) + { + var config = Config(2); var condition = config.Sop.Steps[1].Detection!; + condition.Method = method; + if (method == ConditionMethod.HandMove) + { + condition.FromRegion = "r1"; condition.ToRegion = "r2"; + config.Sop.Regions["r2"] = new() { X1 = 120, Y1 = 0, X2 = 170, Y2 = 50 }; + } + else config.Sop.Steps[1].AiConfirmation = new() { ImageMode = VisionImageMode.Hand, HandPadding = 5, HandMinSize = 32 }; + var client = new DelayedClient(); var engine = Engine(config, client); + engine.ProcessFrame(Frame(10, 0), captureDecisionImage: _ => [10]); + var frame = Frame(11, 1); + engine.ProcessFrame(frame, captureDecisionImage: _ => [11]); + var count = 0; + frame = Frame(12, method == ConditionMethod.HandMove ? 2 : null); + engine.ProcessFrame(frame, captureDecisionImage: region => + { + if (method == ConditionMethod.HandLeaveRegion) Check(region is { X1: > 50, X2: < 100 }, "后续离开步骤必须使用自己的离开前手部位置裁剪离开后的新帧"); + count++; return [12]; + }); + Check(count == 1, "前序AI未返回时不能漏掉后续手离开或跨区域移动"); + await Until(() => client.Calls.Count == 1); + client.Calls.First().Result.SetResult(new(true, .99, "完成")); + await Until(() => { engine.ProcessFrame(Frame(100, null)); return engine.CurrentStep?.Id == 2; }); + engine.ProcessFrame(Frame(101, null)); + await Until(() => client.Calls.Count == 2); + Check(client.Calls.Last().Request.FrameId == 12, "轨迹步骤在手已离开后仍应提交当时取得的画面"); + engine.Stop(); + } + } + + private static async Task LifecycleInvalidatesQueue() + { + foreach (var action in new Action[] { e => e.Reset(), e => { e.TogglePause(); e.TogglePause(); }, e => { e.Stop(); e.Start(); } }) + { + var client = new DelayedClient(); var engine = Engine(Config(2), client); + engine.ProcessFrame(Frame(1, 0), captureDecisionImage: _ => [1]); engine.ProcessFrame(Frame(2, 1), captureDecisionImage: _ => [2]); + await Until(() => client.Calls.Count == 1); + action(engine); + client.Calls.First().Result.SetResult(new(true, .99, "旧轮次结果")); + await Task.Delay(20); engine.ProcessFrame(Frame(100, null)); + Check(engine.CurrentStep?.Id == 1 && !engine.HasPendingDecision && client.Calls.Count == 1, + "暂停、复位、停止必须同时失效在途请求和全部后续缓存,不能跨轮次放行"); + engine.Stop(); + } + } + + private sealed class DelayedClient : IVisionDecisionClient + { + public ConcurrentQueue Calls { get; } = new(); + public Task DecideAsync(VisionDecisionRequest request, CancellationToken cancellationToken) + { + var call = new Call(request); Calls.Enqueue(call); return call.Result.Task.WaitAsync(cancellationToken); + } + } + private sealed class Call(VisionDecisionRequest request) + { + public VisionDecisionRequest Request { get; } = request; + public TaskCompletionSource Result { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + } +} diff --git a/tests/VisionDecision.Smoke/Program.cs b/tests/VisionDecision.Smoke/Program.cs index 7db268e..8eb75d9 100644 --- a/tests/VisionDecision.Smoke/Program.cs +++ b/tests/VisionDecision.Smoke/Program.cs @@ -148,6 +148,7 @@ try finally { for (int i = 0; i < names.Length; i++) Environment.SetEnvironmentVariable(names[i], previous[i]); } await LayaChecks.RunAsync(args); await D3Checks.RunAsync(args); +await BufferedEvidenceChecks.RunAsync(); await TriggerImageChecks.RunAsync(); await DynamicRegionChecks.RunAsync(); Console.WriteLine("PASS: 手部触发、单请求、AI 门控、证据帧、限流、超时、旧结果失效、配方往返、兼容 HTTP 消息及错误响应、Laya 原生适配与复核语义");