aisop/tests/VideoFlowTest.Smoke/Program.cs

489 lines
34 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Markup.Xaml.Styling;
using Avalonia.Themes.Fluent;
using Avalonia.Threading;
using Avalonia.VisualTree;
using OpenCvSharp;
using Prism.Dialogs;
using SopHelper.Engine.Common;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Training;
using SopHelper.Training;
using SopHelper.VVMs.RecipeEditor;
using SopHelper.VVMs.SopPage;
using Window = Avalonia.Controls.Window;
internal static class Program
{
private static string? _overlayPreviewPath;
[STAThread]
public static void Main(string[] args)
{
var previewIndex = Array.IndexOf(args, "--overlay-preview");
if (previewIndex >= 0 && previewIndex + 1 < args.Length) _overlayPreviewPath = args[previewIndex + 1];
var root = Path.Combine(Path.GetTempPath(), "video-flow-test-" + Guid.NewGuid().ToString("N"));
var previousRoot = Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT");
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT", root);
try
{
AppBuilder.Configure<Application>().UseSkia().UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }).SetupWithoutStarting();
Application.Current!.Styles.Add(new FluentTheme());
Application.Current.Styles.Add(new StyleInclude(new Uri("avares://SopHelper.Avalonia/")) { Source = new Uri("avares://SopHelper.Avalonia/Themes/Styles.axaml") });
if (args.Contains("--live")) { LiveVideoFlowChecks.Run(args); return; }
if (args.Contains("--agent-generation-only")) { AgentDraftGenerationChecks.Run(root); return; }
CheckAiFlow();
CheckSequenceEditor();
StepTestDecisionChecks.Run();
RecipeCloseChecks.Run(root);
CheckRuntimeSettings(root);
StepTransferChecks.Run(root);
AgentDraftGenerationChecks.Run(root);
StandardVideoImportChecks.Run(root);
CheckVideoPage(root);
}
finally
{
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT", previousRoot);
if (Directory.Exists(root)) Directory.Delete(root, true);
}
}
private static void CheckSequenceEditor()
{
Check(new StepNode().AiCheckWindowMs == 10000,
"新建步骤默认使用10秒限时复检");
var config = new SopConfig();
config.Sop.Steps.Add(new() { Id = 1, Description = "状态变化", AiConfirmation = new()
{ EvidenceMode = VisionEvidenceMode.Sequence, ObservationMinMs = 1800, ObservationMaxFrames = 13, ObservationRequestMaxFrames = 7, ObservationSampleMs = 300,
CheckWindowMs = 7000 } });
var editor = RecipeNode.From(config, "试验.yaml", false);
Check(editor.Steps[0].UsesSequenceEvidence, "编辑器须识别过程时序模式");
var restored = SopConfigLoader.Parse(SopConfigLoader.ToYaml(editor.ToConfig())).Sop.Steps[0].AiConfirmation!;
Check(restored.EvidenceMode == VisionEvidenceMode.Sequence && restored.ObservationMinMs == 1800
&& restored.ObservationMaxFrames == 13 && restored.ObservationRequestMaxFrames == 7 && restored.ObservationSampleMs == 300,
"编辑保存不得丢失时序模式、缓存容量与单次请求预算");
Check(editor.Steps[0].AiContinueAfterWindow && restored.CheckWindowMs == 7000, "编辑保存须保留连续操作限时复检参数");
editor.Steps[0].AiContinueAfterWindow = false;
Check(editor.ToConfig().Sop.Steps[0].AiConfirmation!.CheckWindowMs == 0, "关闭限时复检须恢复原等待策略");
Console.WriteLine("PASS: 编辑器过程时序模式及观察参数往返保留");
}
private static void CheckRuntimeSettings(string root)
{
var store = new SopHelper.Models.RuntimeSettingsStore(Path.Combine(root, "runtime-migration"));
var legacy = SopConfigLoader.Parse("sop: {settings: {frame_stride: 3, auto_reset_on_complete: false, reset_delay_sec: 4}}");
var options = store.LoadOrMigrate(legacy);
Check(options.FrameStride == 3 && !options.AutoResetOnComplete && options.ResetDelaySec == 4 && options.DjevTimeoutSeconds == 1, "首次使用旧配方时迁移运行设置,djev超时使用独立默认值");
options.FrameStride = 2; options.AutoResetOnComplete = true; options.ResetDelaySec = 6; options.DjevTimeoutSeconds = 3;
store.Save(options);
var other = SopConfigLoader.Parse("sop: {settings: {frame_stride: 9, auto_reset_on_complete: false, reset_delay_sec: 30}}");
var loaded = new SopHelper.Models.RuntimeSettingsStore(Path.Combine(root, "runtime-migration")).LoadOrMigrate(other);
loaded.Apply(other);
Check(other.Sop.Settings.FrameStride == 2 && other.Sop.Settings.AutoResetOnComplete && other.Sop.Settings.ResetDelaySec == 6 && other.Sop.Settings.DjevTimeoutSeconds == 3,
"重启及切换配方沿用独立运行设置,不被旧配方覆盖");
}
private static void CheckAiFlow()
{
var config = SopConfigLoader.Parse("""
sop:
name: 流程测试
settings: { auto_reset_on_complete: true }
regions: { work: { x1: 0, y1: 0, x2: 64, y2: 48 } }
steps:
- id: 1
name: 装配
description: 零件安装到位
detection: { method: hand_in_region, region: work, stable_frames: 1, tolerance: 1 }
ai_confirmation: { image_mode: fixed_region, image_region: work, timeout_seconds: 2 }
""");
var fake = new FakeDecision();
using var test = new SopVideoFlowTest(config, fake);
test.Start();
byte[]? sentImage = null;
test.DecisionImageCaptured += (jpeg, frameId) => { sentImage = jpeg; Check(frameId == 12, "Diagnostic image identifies the actual submitted video frame"); };
using var image = new Mat(48, 64, MatType.CV_8UC3, new Scalar(30, 60, 90));
var frame = new FrameResult { FrameId = 12, Timestamp = DateTime.Now, Size = (64, 48), Hands = [new Hand { Rect = new(20, 20, 10, 10) }] };
test.ProcessResult(frame, image);
Until(() => fake.Request is not null);
Check(!test.IsCompleted && fake.Request!.FrameId == 12 && fake.Request.Jpeg.Length > 0, "Hand trigger submits the exact video frame to AI without completing early");
Check(ReferenceEquals(sentImage, fake.Request!.Jpeg), "Diagnostic image is exactly the image sent to AI");
var drain = test.FinishPendingDecisionAsync();
Check(!drain.IsCompleted, "End of video waits for the outstanding AI decision");
fake.Result.SetResult(new(true, .99, "已安装"));
Pump(drain);
Check(test.IsCompleted && test.Finish("播放结束").Contains("检测通过") && test.Details.Contains("✓ 1 装配"), "Final AI confirmation completes the flow and preserves the completed step result");
Check(config.Sop.Settings.AutoResetOnComplete, "Test run preserves the editor configuration");
using var cancelled = new SopVideoFlowTest(config, new FakeDecision());
cancelled.Start();
cancelled.ProcessResult(frame, image);
var cancelledDrain = cancelled.FinishPendingDecisionAsync();
cancelled.Dispose(); Pump(cancelledDrain);
Check(!cancelled.IsCompleted, "Stopping a test cancels pending AI without reporting success");
var rejectedClient = new FakeDecision();
using var rejected = new SopVideoFlowTest(config, rejectedClient); rejected.Start();
rejected.ProcessResult(frame, image);
rejectedClient.Result.SetResult(new(false, .15, "裁剪图没有纸盒"));
Pump(rejected.FinishPendingDecisionAsync());
rejected.ProcessResult(new FrameResult { FrameId = 13, Size = (64, 48) }, image);
Check(rejected.Details.Contains("裁剪图没有纸盒") && rejected.Details.Contains("未检出手"), "A later hand message preserves the last AI rejection reason");
}
private static void CheckVideoPage(string root)
{
var store = new RecipeWorkspace(root);
var config = new SopConfig(); config.Sop.Name = "视频测试界面"; config.Sop.Parts = [];
var vm = new RecipeEditorViewModel();
vm.OnDialogOpened(new DialogParameters { { "directory", store.RecipesDirectory }, { "config", config }, { "new", true } });
vm.SaveCommand.Execute();
var model = vm.SopRecording!;
Check(!model.TestFlowCommand.CanExecute(), "Test flow is disabled without a saved standard video");
Directory.CreateDirectory(Path.GetDirectoryName(model.StandardVideoPath)!);
using (var writer = new VideoWriter(model.StandardVideoPath, FourCC.MJPG, 10, new OpenCvSharp.Size(64, 48)))
{
Check(writer.IsOpened(), "Standard test video opens");
for (var i = 0; i < 10; i++)
{
using var image = new Mat(48, 64, MatType.CV_8UC3, new Scalar(30, 60, 90)); writer.Write(image);
}
}
var runtimeStore = SopHelper.Models.RuntimeSettingsStore.Current;
var runtime = runtimeStore.Read() ?? new();
var originalTimeout = runtime.DjevTimeoutSeconds;
runtime.DjevTimeoutSeconds = 5; runtimeStore.Save(runtime);
try { CheckRealtimePlayback(model.StandardVideoPath); CheckContinuousPlayback(model.StandardVideoPath); }
finally { runtime.DjevTimeoutSeconds = originalTimeout; runtimeStore.Save(runtime); }
vm.Recipe.AddStepCommand.Execute();
var selected = vm.Recipe.SelectedStep!;
vm.CaptureStepKeyFrameCommand.Execute();
Check(selected.KeyFrameBase64.Length == 0, "Cannot capture a keyframe without a displayed video frame");
model.ToggleVideoPlaybackCommand.Execute(); Until(() => !model.IsBusy && model.Playback.IsPlaying);
Check(model.ToggleVideoPlaybackCommand.CanExecute() && model.PlayVideoButtonText == "暂停播放", "Combined playback button switches to pause while playing");
model.ToggleVideoPlaybackCommand.Execute(); Until(() => !model.IsBusy && !model.Playback.IsPlaying);
Check(model.ToggleVideoPlaybackCommand.CanExecute() && model.PlayVideoButtonText == "继续播放", "Combined playback button pauses and remains available to resume");
Pump(model.Playback.SeekAsync(50));
var displayed = Convert.ToBase64String(model.Playback.Frame!.ToPngBytes());
vm.CaptureStepKeyFrameCommand.Execute();
Check(selected.KeyFrameBase64 == displayed && selected.KeyFrameSeconds == model.Playback.DisplayedSeconds,
"Capture stores the exact displayed frame and timestamp after paused seeking");
vm.Recipe.AddStepCommand.Execute();
Check(vm.Recipe.SelectedStep!.KeyFrameBase64.Length == 0 && selected.KeyFrameBase64 == displayed,
"Keyframes belong to the selected step and do not leak across selection changes");
var transferred = SopStepTransfer.Read(SopStepTransfer.Export(vm.Recipe.ToConfig()));
Check(transferred.Sop.Steps[0].KeyFrameBase64 == displayed,
"Keyframe image and timestamp survive step export and import");
vm.SaveCommand.Execute();
var savedKeyFrames = RecipeNode.From(SopConfigLoader.Load(store.ConfigPath(config.Sop.Name)), "test.yaml", false);
Check(savedKeyFrames.Steps[0].KeyFrameBase64 == displayed && savedKeyFrames.Steps[0].KeyFrameSeconds == selected.KeyFrameSeconds,
"Saving and reopening the recipe preserves the selected step keyframe");
Pump(model.Playback.StopAsync());
// Unsupported condition exercises playback and incomplete results without hardware/models/API.
config.Sop.Steps = [new StepDef { Id = 1, Name = "待配置步骤", Description = "验证当前编辑配置", Detection = new() { Method = "unsupported" } }];
config.Sop.Regions["标定区"] = new() { X1 = 10, Y1 = 5, X2 = 50, Y2 = 40, Name = "标定区", Color = "#FF00FF" };
model.FlowTestConfigProvider = () => config;
var view = new RecipeEditor { DataContext = vm };
var window = new Window { Content = view, Width = 1040, Height = 760 }; window.Show(); window.UpdateLayout();
var stepVideo = view.FindControl<Border>("StepVideoViewport")!;
var parameters = view.FindControl<ScrollViewer>("StepParameters")!;
Check(!view.GetVisualDescendants().OfType<TabItem>().Any(t => t.Header?.ToString() == "区域"),
"Region editing is integrated into the step tab");
Check(!view.GetVisualDescendants().OfType<TabItem>().Any(t => t.Header?.ToString() == "全局设置"), "配方编辑不再包含全局设置页");
var regionNavigation = view.FindControl<ListBox>("StepRegionNavigation")!;
var regionParameters = view.FindControl<ScrollViewer>("RegionParameters")!;
Check(regionNavigation.TranslatePoint(default, window)!.Value.Y >= stepVideo.TranslatePoint(default, window)!.Value.Y + stepVideo.Bounds.Height
&& regionParameters.TranslatePoint(default, window)!.Value.Y >= stepVideo.TranslatePoint(default, window)!.Value.Y + stepVideo.Bounds.Height,
"Region navigation and parameters sit below the step video player");
Pump(model.Playback.SeekAsync(50)); window.UpdateLayout(); Dispatcher.UIThread.RunJobs();
var regionCanvas = view.FindControl<RegionCanvas>("StepVideoRegions")!;
Check(ReferenceEquals(regionCanvas.Image, model.Playback.Frame) && ReferenceEquals(regionCanvas.Regions, vm.Recipe.Regions),
"Integrated region canvas receives actual playback pixels and all recipe regions");
vm.Recipe.AddRegionCommand.Execute(); window.UpdateLayout(); Dispatcher.UIThread.RunJobs();
Check(ReferenceEquals(regionCanvas.SelectedRegion, vm.Recipe.SelectedRegion)
&& ReferenceEquals(regionNavigation.SelectedItem, vm.Recipe.SelectedRegion),
"Region navigation, parameters and canvas share the selected editable region");
var playbackButtons = ((Panel)view.FindControl<Button>("StepPlayPauseButton")!.Parent!).Children.OfType<Button>().ToArray();
Check(playbackButtons.Length == 3 && playbackButtons[1].Content?.ToString() == "停止" && playbackButtons[2].Content?.ToString() == "获取关键帧",
"Combined play/pause, stop and capture-keyframe buttons appear in order");
Pump(model.Playback.StopAsync());
vm.Recipe.SelectedStep = selected;
Dispatcher.UIThread.RunJobs(); window.UpdateLayout();
var keyFrame = view.FindControl<Image>("StepKeyFrameImage")!;
Check(ReferenceEquals(view.FindControl<Button>("TestStepDecisionButton")!.Command, vm.TestStepDecisionCommand),
"步骤关键帧测试按钮绑定编辑器测试判定命令");
var navigationAndLog = view.FindControl<Grid>("StepNavigationAndLog")!;
var navigationPanel = view.FindControl<DockPanel>("StepNavigationPanel")!;
var logPanel = view.FindControl<Grid>("StepDecisionLogPanel")!;
Check(Math.Abs(logPanel.Bounds.Height - navigationPanel.Bounds.Height) < 1
&& logPanel.Bounds.Y >= navigationAndLog.Bounds.Height / 2
&& view.FindControl<SelectableTextBlock>("StepDecisionLogText")!.Text == vm.StepDecisionLog,
"左侧上下等分步骤导航和可选择复制的判定日志,并绑定日志内容");
var keyFrameRegions = view.FindControl<KeyFrameRegionOverlay>("StepKeyFrameRegions")!;
Check(keyFrame.Source is Avalonia.Media.Imaging.Bitmap && ReferenceEquals(keyFrame.Source, selected.KeyFrameImage)
&& ReferenceEquals(keyFrameRegions.Image, selected.KeyFrameImage)
&& ReferenceEquals(keyFrameRegions.Regions, vm.Recipe.Regions),
"Saved native keyframe bitmap binds to both the original image and all-region overlay");
Check(((Grid)keyFrame.Parent!).Bounds.Height == 360 && !parameters.IsVisualAncestorOf(keyFrame),
"Double-height keyframe remains outside the scrolling parameters");
using (var rendered = new Avalonia.Media.Imaging.RenderTargetBitmap(new PixelSize(320, 360)))
{
rendered.Render(keyFrame);
using var png = new MemoryStream(); rendered.Save(png);
using var pixels = Cv2.ImDecode(png.ToArray(), ImreadModes.Color);
Check(Cv2.Mean(pixels).Val1 > 10, "Keyframe control actually renders saved image pixels");
}
var keyFramePosition = keyFrame.TranslatePoint(default, window);
parameters.Offset = new Vector(0, 400);
window.UpdateLayout(); Dispatcher.UIThread.RunJobs();
Check(keyFrame.TranslatePoint(default, window) == keyFramePosition,
"Scrolling step parameters does not move the keyframe");
parameters.Offset = default;
CheckStepParameterLayout(vm, view, window);
if (_overlayPreviewPath is not null)
{
using var rendered = new Avalonia.Media.Imaging.RenderTargetBitmap(new PixelSize((int)window.Bounds.Width, (int)window.Bounds.Height));
rendered.Render(window);
rendered.Save(Path.Combine(Path.GetDirectoryName(_overlayPreviewPath)!, "step-editor.png"));
parameters.Offset = new Vector(0, parameters.Extent.Height);
window.UpdateLayout(); Dispatcher.UIThread.RunJobs();
using var details = new Avalonia.Media.Imaging.RenderTargetBitmap(new PixelSize((int)window.Bounds.Width, (int)window.Bounds.Height));
details.Render(window);
details.Save(Path.Combine(Path.GetDirectoryName(_overlayPreviewPath)!, "step-parameters.png"));
parameters.Offset = default;
}
Check(parameters.Bounds.Width > window.Bounds.Width * .30 && parameters.Bounds.Width < window.Bounds.Width * .37
&& parameters.Extent.Width <= parameters.Viewport.Width + 1,
"Parameters occupy 35 percent and fit without horizontal scrolling");
Check(stepVideo.Bounds.Width >= window.Bounds.Width * .44 && stepVideo.Bounds.Width <= window.Bounds.Width * .53,
"Step video occupies half the available editor width");
var tabs = view.GetVisualDescendants().OfType<TabControl>().Single();
tabs.SelectedItem = tabs.Items.OfType<TabItem>().Single(t => t.Header?.ToString() == "SOP流程视频");
window.UpdateLayout(); Dispatcher.UIThread.RunJobs();
var button = view.GetVisualDescendants().OfType<Button>().Single(b => ReferenceEquals(b.Command, model.TestFlowCommand));
Check(button.Content?.ToString() == "测试流程" && button.IsEffectivelyVisible && model.TestFlowCommand.CanExecute(), "SOP video page exposes the enabled test flow button");
var importButton = view.GetVisualDescendants().OfType<Button>().Single(b => ReferenceEquals(b.Command, model.ImportVideoCommand));
Check(importButton.Content?.ToString() == "导入视频" && importButton.IsEffectivelyVisible && importButton.IsEnabled, "SOP video page exposes the enabled import button");
model.TestFlowCommand.Execute(); Until(() => !model.IsBusy);
Check(model.IsTestingFlow && model.Playback.IsPlaying && model.DisplayImage is { PixelWidth: 64, PixelHeight: 48 }, "Test button plays and displays the standard video without a camera");
Check(!model.TestFlowCommand.CanExecute() && !model.PlayVideoCommand.CanExecute() && !model.PreviewCommand.CanExecute() && !model.CanSeekVideo, "Test run prevents restart, playback switching, camera switching, and seeking");
Check(!view.FindControl<Slider>("VideoSeekSlider")!.IsEnabled, "Actual seek slider is disabled during flow testing");
var regionsOverlay = view.FindControl<FlowTestRegionOverlay>("FlowTestRegionsOverlay")!;
var handsOverlay = view.FindControl<HandOverlay>("FlowTestHandsOverlay")!;
Check(regionsOverlay.IsEffectivelyVisible && regionsOverlay.Regions!.ContainsKey("标定区")
&& handsOverlay.IsEffectivelyVisible && handsOverlay.ShowBounds && !handsOverlay.IsHitTestVisible,
"Video test displays the recipe region layer and hand skeleton/contact bounds without intercepting input");
var analyze = model.Playback.FrameAnalyzer!;
model.Playback.FrameAnalyzer = (image, id, seconds) =>
{
var result = analyze(image, id, seconds)!;
result.Hands = id % 2 == 0 ? [new Hand { HandType = HandType.Left, Rect = new(20, 10, 20, 25),
Keypoints = Enumerable.Range(0, 21).Select(i => new HandPoint { Index = i, X = 20 + i % 5 * 3, Y = 10 + i / 5 * 5, Confidence = 1 }).ToList() }] : [];
return result;
};
Until(() => model.Playback.Analysis is { FrameId: >= 2, Hands.Count: 1 });
Check(ReferenceEquals(handsOverlay.Result, model.Playback.Analysis) && handsOverlay.Result!.Size == (64, 48),
"Hand overlay receives the analysis published with the displayed video frame");
if (_overlayPreviewPath is not null)
{
window.UpdateLayout();
using var rendered = new Avalonia.Media.Imaging.RenderTargetBitmap(new PixelSize((int)window.Bounds.Width, (int)window.Bounds.Height));
rendered.Render(window); rendered.Save(_overlayPreviewPath);
}
void CheckAlignment()
{
window.UpdateLayout();
var host = (Grid)regionsOverlay.Parent!;
var videoImage = host.Children.OfType<Image>().Single();
var start = videoImage.TranslatePoint(new Avalonia.Point(), window)!.Value;
var end = videoImage.TranslatePoint(new Avalonia.Point(videoImage.Bounds.Width, videoImage.Bounds.Height), window)!.Value;
foreach (var overlay in new Control[] { regionsOverlay, handsOverlay })
{
var overlayStart = overlay.TranslatePoint(new Avalonia.Point(), window)!.Value;
var overlayEnd = overlay.TranslatePoint(new Avalonia.Point(overlay.Bounds.Width, overlay.Bounds.Height), window)!.Value;
Check(Math.Abs(start.X - overlayStart.X) < .01 && Math.Abs(start.Y - overlayStart.Y) < .01
&& Math.Abs(end.X - overlayEnd.X) < .01 && Math.Abs(end.Y - overlayEnd.Y) < .01,
"Region and hand layers exactly follow the image bounds through uniform scaling and letterboxing");
}
Check(Math.Abs((end.X - start.X) / (end.Y - start.Y) - 64d / 48) < .001, "Overlay host preserves the original video aspect ratio");
}
CheckAlignment();
window.Width = 840; window.Height = 900; CheckAlignment();
window.Width = 1040; window.Height = 760;
Until(() => model.Playback.Analysis is { FrameId: >= 3, Hands.Count: 0 });
Check(handsOverlay.Result!.Hands.Count == 0, "A frame with no hands clears the previous skeleton instead of retaining old detections");
Until(() => !model.IsTestingFlow);
Check(model.Playback.IsAtEnd && model.FlowTestStatus.Contains("流程未完成") && model.FlowTestDetails.Contains("待配置步骤"), "Video EOF reports incomplete flow and shows the step reason");
model.TestFlowCommand.Execute(); Until(() => !model.IsBusy);
Check(model.Playback.Progress < 50, "Each test restarts the video from its beginning");
model.StopVideoCommand.Execute(); Until(() => !model.IsBusy);
Check(!model.IsTestingFlow && !model.Playback.IsLoaded && model.FlowTestStatus.Contains("测试已停止"), "Stop playback also stops detection and preserves the test summary");
Check(model.Playback.Analysis is null && !model.ShowFlowTestOverlay, "Stopping playback clears the hand analysis and hides test overlays");
model.TestFlowCommand.Execute(); Until(() => !model.IsBusy);
Pump(vm.ShutdownAsync());
Check(!model.IsTestingFlow && !model.Playback.IsLoaded && model.Playback.FrameProcessor is null && model.Playback.FrameAnalyzer is null, "Closing the editor releases playback and flow detection");
using (var exclusive = new FileStream(model.StandardVideoPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
Check(exclusive.Length > 0, "Closing flow test unlocks the video file");
vm.ConfirmCloseAsync = () => Task.FromResult(RecipeCloseChoice.Discard);
window.Close(); Until(() => !window.IsVisible); vm.OnDialogClosed();
}
private static void CheckRealtimePlayback(string path)
{
var playback = new RecordedVideoPlayback();
var ids = new System.Collections.Concurrent.ConcurrentQueue<long>();
var config = SopConfigLoader.Parse("""
sop:
name: 连续播放
regions: { work: { x1: 0, y1: 0, x2: 64, y2: 48 } }
steps:
- id: 1
name: 装配
description: 盒内可见零件
detection: { method: hand_in_region, region: work, stable_frames: 1 }
ai_confirmation: { timeout_seconds: 5 }
""");
var fake = new FakeDecision();
using var test = new SopVideoFlowTest(config, fake); test.Start();
playback.FrameProcessor = (image, id, _) =>
{
ids.Enqueue(id);
test.ProcessResult(new FrameResult { FrameId = id, Timestamp = DateTime.Now, Size = (64, 48), Hands = [new Hand { Rect = new(20, 20, 10, 10) }] }, image);
};
Pump(playback.PlayAsync(path));
using (var wait = new CancellationTokenSource(350)) Dispatcher.UIThread.MainLoop(wait.Token);
Check(fake.Request is not null && !fake.Result.Task.IsCompleted && ids.Count > 1 && playback.IsPlaying && playback.Progress > 0,
"Video and frame detection continue while AI is still pending");
Until(() => playback.IsAtEnd);
Check(!fake.Result.Task.IsCompleted && !test.IsCompleted && ids.Last() > ids.First(), "Video reaches EOF without waiting for AI or reporting premature success");
// EOF可能发生在首次送检后仍未到期,明确等待配置期限后再模拟迟到结果。
var remainingDeadline = fake.Request!.TimeoutMs - RealtimeDecisionPolicy.Elapsed(fake.Request.StartedTimestamp);
if (remainingDeadline > 0)
{
using var deadlineWait = new CancellationTokenSource(TimeSpan.FromMilliseconds(remainingDeadline + 30));
Dispatcher.UIThread.MainLoop(deadlineWait.Token);
}
fake.Result.SetResult(new(true, .99, "盒内可见零件"));
Pump(test.FinishPendingDecisionAsync());
Check(!test.IsCompleted, "Late background result after EOF cannot bypass the configured deadline");
Pump(playback.StopAsync());
ids.Clear();
playback.FrameProcessor = (_, id, _) => { Thread.Sleep(140); ids.Enqueue(id); };
Pump(playback.PlayAsync(path));
Until(() => playback.IsAtEnd);
Check(ids.Count < 10 && ids.SequenceEqual(ids.OrderBy(id => id)), "Slow inference catches up with the video clock instead of slowing playback to process every frame");
Pump(playback.StopAsync());
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 firstRequest = fake.Calls.First().Request;
var remainingDeadline = firstRequest.TimeoutMs - RealtimeDecisionPolicy.Elapsed(firstRequest.StartedTimestamp);
if (remainingDeadline > 0) Pump(Task.Delay(TimeSpan.FromMilliseconds(remainingDeadline + 50)));
var drain = test.FinishPendingDecisionAsync();
fake.Calls.First().Result.TrySetResult(new(true, .99, "迟到的通过"));
Pump(drain);
Check(!test.IsCompleted && fake.Calls.Count == 1,
"Expired buffered video actions cannot generate late real-time passes or queue old model requests");
Pump(playback.StopAsync());
}
private static void CheckStepParameterLayout(RecipeEditorViewModel model, RecipeEditor view, Window window)
{
var step = model.Recipe.SelectedStep!;
var condition = step.Detection!;
var original = condition.Method;
var windowMs = step.AiCheckWindowMs;
var timing = step.StandardDurationMs = 1234;
var notifications = new HashSet<string?>();
System.ComponentModel.PropertyChangedEventHandler changed = (_, e) => notifications.Add(e.PropertyName);
condition.PropertyChanged += changed;
bool Visible(string name) => view.FindControl<Control>(name)!.IsVisible;
void Method(string method) { condition.Method = method; Dispatcher.UIThread.RunJobs(); window.UpdateLayout(); }
try
{
Method(ConditionMethod.HandInRegion);
Check(view.FindControl<NumericUpDown>("AiTimeoutSecondsInput") is null,
"配方步骤没有djev超时入口,超时由独立运行设置统一控制");
Check(Visible("TriggerRegionRow") && Visible("TriggerStableField") && !Visible("TriggerMoveRows") && !Visible("TriggerDurationRow"),
"区域触发仅显示操作区域和稳定帧,不显示移动或计时参数");
Method(ConditionMethod.HandMove);
Check(Visible("TriggerMoveRows") && !Visible("TriggerRegionRow") && !Visible("TriggerStableField") && !Visible("TriggerDurationRow"),
"移动触发显示起终点并隐藏不生效的稳定帧和计时参数");
Method(ConditionMethod.TimeElapsed);
Check(Visible("TriggerDurationRow") && !Visible("TriggerMoveRows") && !Visible("TriggerRegionRow") && !condition.UsesHandTrigger,
"计时触发仅显示持续时间,不显示手部区域参数");
Check(notifications.Contains(nameof(ConditionNode.UsesTriggerRegion)) && notifications.Contains(nameof(ConditionNode.IsTimedTrigger)),
"切换触发方式通知界面刷新相关参数");
Check(!view.FindControl<Expander>("StepAdditionalSettings")!.IsExpanded
&& !view.FindControl<ScrollViewer>("StepParameters")!.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text == "节拍毫秒")
&& model.Recipe.ToConfig().Sop.Steps.First(s => s.Id == step.Id).StandardDurationMs == timing,
"低频设置折叠,移除无运行用途的节拍输入并保留原配方数据");
step.AiContinueAfterWindow = false; Dispatcher.UIThread.RunJobs(); window.UpdateLayout();
Check(step.AiCheckWindowMs == 0 && !step.AiContinueAfterWindow, "紧凑复检控件不会把关闭的窗口强制重新开启");
}
finally
{
condition.PropertyChanged -= changed;
condition.Method = original; step.AiCheckWindowMs = windowMs;
Dispatcher.UIThread.RunJobs(); window.UpdateLayout();
}
}
private static void Until(Func<bool> ready)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
while (!ready() && watch.Elapsed < TimeSpan.FromSeconds(10))
{
using var cancellation = new CancellationTokenSource(10);
Dispatcher.UIThread.MainLoop(cancellation.Token);
}
if (!ready()) throw new TimeoutException("Smoke test timed out");
Dispatcher.UIThread.RunJobs();
}
private static void Pump(Task task) { Until(() => task.IsCompleted); task.GetAwaiter().GetResult(); }
private static void Check(bool value, string message) { if (!value) throw new Exception(message); Console.WriteLine("PASS: " + message); }
private sealed class FakeDecision : IVisionDecisionClient
{
public VisionDecisionRequest? Request;
public TaskCompletionSource<VisionDecisionResult> Result { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task<VisionDecisionResult> 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<VisionDecisionResult> Result)> Calls { get; } = new();
public Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request, CancellationToken cancellationToken)
{
var result = new TaskCompletionSource<VisionDecisionResult>(TaskCreationOptions.RunContinuationsAsynchronously);
Calls.Enqueue((request, result)); return result.Task.WaitAsync(cancellationToken);
}
}
}