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().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; } CheckAiFlow(); CheckSequenceEditor(); AgentDraftVerificationChecks.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() { var config = new SopConfig(); config.Sop.Steps.Add(new() { Id = 1, Description = "状态变化", AiConfirmation = new() { EvidenceMode = VisionEvidenceMode.Sequence, ObservationMinMs = 1800, ObservationMaxFrames = 13, ObservationSampleMs = 300, CheckWindowMs = 7000, MaxChecks = 4, CheckSettleMs = 450 } }); 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.ObservationSampleMs == 300, "编辑保存不得丢失时序模式与窗口参数"); Check(editor.Steps[0].AiContinueAfterWindow && restored.CheckWindowMs == 7000 && restored.MaxChecks == 4 && restored.CheckSettleMs == 450, "编辑保存须保留连续操作限时复检参数"); editor.Steps[0].AiContinueAfterWindow = false; Check(editor.ToConfig().Sop.Steps[0].AiConfirmation!.CheckWindowMs == 0, "关闭限时复检须恢复原等待策略"); Console.WriteLine("PASS: 编辑器过程时序模式及观察参数往返保留"); } 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); } } 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" } }]; 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 tabs = view.GetVisualDescendants().OfType().Single(); tabs.SelectedItem = tabs.Items.OfType().Single(t => t.Header?.ToString() == "SOP流程视频"); window.UpdateLayout(); Dispatcher.UIThread.RunJobs(); var button = view.GetVisualDescendants().OfType