using Avalonia; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Headless; using Avalonia.Media.Imaging; using Avalonia.Media; using Avalonia.Threading; using Prism.Ioc; using Prism.Dialogs; using SopHelper; using SopHelper.Engine.Camera; using SopHelper.Engine.Training; using SopHelper.Models; using SopHelper.Training; using SopHelper.VVMs.SopPage; using SopHelper.VVMs.RecipeEditor; using System.Text.Json; using Avalonia.VisualTree; using OpenCvSharp; using SopHelper.Engine.SopAgent; using SopHelper.Engine.Sop; using Window = Avalonia.Controls.Window; using Point = Avalonia.Point; using Size = Avalonia.Size; using Avalonia.Input; internal static class Smoke { private static int _exit=1; private static bool _visionOnly; private static bool _processImagesOnly; private static bool _recipeSelectionOnly; private static string? _agentSettingsFile; private static readonly FakeCamera Camera=new(); [STAThread] public static int Main(string[] args) { _visionOnly=args.Contains("--vision-only"); _processImagesOnly=args.Contains("--process-images-only"); _recipeSelectionOnly=args.Contains("--recipe-selection-only"); var agentSettingsIndex=Array.IndexOf(args,"--agent-settings-file"); if(agentSettingsIndex>=0) { if(agentSettingsIndex+1>=args.Length)throw new ArgumentException("--agent-settings-file 后需提供设置文件路径"); _agentSettingsFile=Path.GetFullPath(args[agentSettingsIndex+1]); } var previousRoot=Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT"); var dataRoot=Path.Combine(Path.GetTempPath(),"sophelper-layout-smoke-"+Guid.NewGuid().ToString("N")); Directory.CreateDirectory(dataRoot); var djevSettingsOnly = args.Contains("--djev-settings-only"); var djevEnvironment = new[] { "SOPHELPER_D3_ROOT", "SOPHELPER_VISION_ENDPOINT", "SOPHELPER_VISION_PROVIDER" } .ToDictionary(name => name, Environment.GetEnvironmentVariable); if (djevSettingsOnly) { // 假安装与服务提供方隔离保证界面测试不加载模型、不更改真实服务配置。 foreach (var tier in new[] { "lite", "nano" }) { var modelPath = Path.Combine(dataRoot, tier == "lite" ? "D3Lite" : "D3Nano", "model"); Directory.CreateDirectory(modelPath); File.WriteAllText(Path.Combine(modelPath, "MODEL_MANIFEST.json"), JsonSerializer.Serialize(new { model_name = "d3-" + tier })); File.WriteAllText(Path.Combine(modelPath, "decision_config.json"), "{}"); } Environment.SetEnvironmentVariable("SOPHELPER_D3_ROOT", Path.Combine(dataRoot, "D3Lite")); Environment.SetEnvironmentVariable("SOPHELPER_VISION_ENDPOINT", "http://127.0.0.1:8766/v1/systemone"); Environment.SetEnvironmentVariable("SOPHELPER_VISION_PROVIDER", "test"); } if(_agentSettingsFile is not null) { Directory.CreateDirectory(Path.Combine(dataRoot,"workspace")); File.Copy(_agentSettingsFile,Path.Combine(dataRoot,"workspace","sop-agent.json")); } Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT",dataRoot); var settingsPath=Path.Combine(dataRoot,"workspace","settings.json"); var settingsBefore=File.Exists(settingsPath)?File.ReadAllBytes(settingsPath):null; System.Diagnostics.Trace.Listeners.Add(new System.Diagnostics.ConsoleTraceListener()); Environment.SetEnvironmentVariable("SOPHELPER_CPU_THREADS","4"); try { AppBuilder.Configure(()=>new App(Camera)).UseSkia() .UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing=false }) .LogToTrace(Avalonia.Logging.LogEventLevel.Warning) .AfterSetup(_=> { var lifetime=(IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!; lifetime.Startup+=(_,_)=>Dispatcher.UIThread.Post(async()=>await Run(lifetime)); }).StartWithClassicDesktopLifetime([],ShutdownMode.OnExplicitShutdown); if(args.Contains("--camera-lifecycle-only")&&_exit==0) Check(!Camera.IsConnected&&Camera.DisposeCount>0,"Application exit releases the retained camera connection"); } finally { if(settingsBefore is not null)File.WriteAllBytes(settingsPath,settingsBefore); else if(File.Exists(settingsPath))File.Delete(settingsPath); Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT",previousRoot); if (djevSettingsOnly) foreach (var item in djevEnvironment) Environment.SetEnvironmentVariable(item.Key, item.Value); if(!Path.GetFullPath(dataRoot).StartsWith(Path.GetFullPath(Path.GetTempPath())))throw new Exception("Unexpected test data root"); Directory.Delete(dataRoot,true); } return _exit; } private static async Task Run(IClassicDesktopStyleApplicationLifetime lifetime) { try { var userCameraPath=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"SopHelper","last-camera.json"); var userCameraBefore=File.Exists(userCameraPath)?File.ReadAllBytes(userCameraPath):null; await Task.Delay(150); var app=(App)Application.Current!;var window=lifetime.MainWindow!; if(Environment.GetCommandLineArgs().Contains("--djev-shutdown-only")) { // 注入尚未完成的启动任务,验证关闭必须先取消并等待,且重复点击不会提前销毁窗口。 var startup=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var fields=System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.NonPublic; var options=new D3StartupOptions(new("http://127.0.0.1:8766/v1/systemone"), Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!,"unused","unused","unused", TimeSpan.FromSeconds(2),TimeSpan.FromMilliseconds(20)); // 用当前进程的错误启动时间模拟过期记录,不接触真实模型,也不能结束测试宿主。 File.WriteAllText(options.MarkerPath,JsonSerializer.Serialize(new D3ProcessMarker(Environment.ProcessId,DateTime.UnixEpoch))); typeof(App).GetField("_d3Options",fields)!.SetValue(app,options); typeof(App).GetField("_d3Startup",fields)!.SetValue(app,startup.Task); var cancellation=(CancellationTokenSource)typeof(App).GetField("_d3StartupCancellation",fields)!.GetValue(app)!; window.Close();window.Close(); Check(cancellation.IsCancellationRequested&&window.IsVisible&&Camera.DisposeCount==0,"退出先取消模型启动,等待期间重复关闭不提前释放资源"); startup.SetResult(); for(var retry=0;window.IsVisible&&retry<100;retry++)await Task.Delay(20); Check(!window.IsVisible&&!File.Exists(options.MarkerPath)&&Camera.DisposeCount>0,"启动任务完成后清理模型记录、关闭窗口并释放相机"); _exit=0;return; } if (Environment.GetCommandLineArgs().Contains("--djev-settings-only")) { var model = app.Container.Resolve(); var view = new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(model); var dialog = new Window { Content = view, Width = 900, Height = 900 }; dialog.Show(); await Task.Delay(60); try { var tier = view.FindControl("DjevTierInput")!; var save = view.FindControl