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(); StepTestDecisionChecks.Run(); CheckRuntimeSettings(root); StepTransferChecks.Run(root); 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() { 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.FrameStride = 2; options.AutoResetOnComplete = true; options.ResetDelaySec = 6; 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, "重启及切换配方沿用独立运行设置,不被旧配方覆盖"); } 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); 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("StepVideoViewport")!; var parameters = view.FindControl("StepParameters")!; Check(!view.GetVisualDescendants().OfType().Any(t => t.Header?.ToString() == "区域"), "Region editing is integrated into the step tab"); Check(!view.GetVisualDescendants().OfType().Any(t => t.Header?.ToString() == "全局设置"), "配方编辑不再包含全局设置页"); var regionNavigation = view.FindControl("StepRegionNavigation")!; var regionParameters = view.FindControl("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("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