aisop/tests/VisionDecision.Smoke/Program.cs
2026-12-06 18:29:59 +08:00

189 lines
11 KiB
C#

using System.Net;
using System.Text;
using System.Text.Json;
using SopHelper.Engine.Common;
using SopHelper.Engine.Sop;
if (args.Contains("--dlite-audit")) { await DliteAudit.RunAsync(args); return; }
SettingsMigrationChecks.Run();
static void Check(bool value, string message) { if (!value) throw new Exception(message); }
var retired = SopConfigLoader.Parse("""
sop:
name: 旧物体规则
model: { path: old.onnx, classes: [盒子] }
steps:
- id: 1
description: 把盒子放好
detection: { method: object_present, target_object: 盒子 }
""");
Check(!SopConfigLoader.ToYaml(retired).Contains("model:") && retired.Warnings.Any(w=>w.Contains("已移除或不支持")), "旧模型绑定必须忽略,旧物体规则提示改用手部规则");
var sample = SopConfigLoader.Load(Path.Combine("configs", "sop", "hand-ai.yaml"));
Check(sample.Warnings.Count == 0 && sample.Sop.Steps.All(s => s.AiConfirmation is not null), "示例配方必须有效且不依赖 YOLO");
var d3Sample = SopConfigLoader.Load(Path.Combine("configs", "sop", "d3-workflow.yaml"));
Check(d3Sample.Warnings.Count == 0 && d3Sample.Sop.Steps.All(s => s.AiConfirmation?.ImageRegion == "work"), "D3 示例必须有效、使用区域取图且不依赖 YOLO");
var config = SopConfigLoader.Parse("""
sop:
name: 手部 AI 测试
settings:
auto_reset_on_complete: false
regions:
work: { x1: 0, y1: 0, x2: 100, y2: 100 }
steps:
- id: 1
name: 装配
description: 把零件安装到位
detection: { method: hand_in_region, region: work, stable_frames: 2, tolerance: 1 }
ai_confirmation: { criteria: 旧条件不能覆盖步骤说明, retry_delay_ms: 0, timeout_seconds: 1 }
""");
Check(config.Warnings.Count == 0, "有效的纯手部 AI 配方不应要求 YOLO");
// 旧配方迁移后给说明和判据各保留一份,可独立修改并保存。
Check(config.Sop.Steps[0].CompletionCriteria == "把零件安装到位", "旧步骤沿用原说明作为初始完成条件");
config.Sop.Steps[0].CompletionCriteria = "安装槽内可见零件";
var savedStep = SopConfigLoader.Parse(SopConfigLoader.ToYaml(config)).Sop.Steps[0];
Check(savedStep.Description == "把零件安装到位" && savedStep.CompletionCriteria == "安装槽内可见零件", "步骤说明与完成条件分别保存");
// 旧配方缺字段、显式 null 和空判据都不能退回“规则即完成”。
var legacy = SopConfigLoader.Parse("""
sop:
name: 旧配方
settings: { auto_reset_on_complete: false }
regions: { work: { x1: 0, y1: 0, x2: 100, y2: 100 } }
steps:
- id: 1
name: 放置盒子
detection: { method: hand_in_region, region: work, stable_frames: 1 }
""");
Check(legacy.Sop.Steps[0].AiConfirmation is not null && legacy.Warnings.Any(w=>w.Contains("请填写 AI 完成条件")), "旧配方必须默认 AI 确认并提示补充步骤说明");
foreach (var missing in new AiConfirmation?[] { null, new() })
{
legacy.Sop.Steps[0].AiConfirmation = missing;
var guarded = new SopEngine(); guarded.Load(legacy); guarded.Start();
string? message = null;
guarded.StepSnapshotChanged += s => message = s.Message;
for (int i = 0; i < 10; i++) guarded.ProcessFrame(new() { Hands = [new() { Rect = new(20,20,10,10) }] }, () => throw new Exception("空判据不应取图"));
Check(guarded.State == EngineState.Running && guarded.CurrentStep?.Id == 1 && message!.Contains("填写 AI 完成条件"), "步骤说明缺失不得仅凭手部规则推进");
guarded.Stop();
}
var fake = new FakeDecision();
var engine = new SopEngine { VisionDecisionClient = fake };
engine.Load(config); engine.Start();
var frame = new FrameResult { FrameId = 42, Timestamp = DateTime.Now, Hands = [new() { Rect = new(20, 20, 10, 10) }] };
var image = new byte[] { 1, 2, 3 };
var captures = 0;
byte[] Capture() { captures++; return image; }
engine.ProcessFrame(frame, Capture);
Check(captures == 0, "稳定帧未满足不能取图");
engine.ProcessFrame(frame, Capture);
await fake.Called.Task.WaitAsync(TimeSpan.FromSeconds(5));
Check(captures == 1 && fake.Request?.FrameId == 42, "应提交动作触发的准确帧");
Check(fake.Request?.Criteria == "安装槽内可见零件", "发给模型的判据使用独立完成条件");
for (int i = 0; i < 10; i++) engine.ProcessFrame(frame, Capture);
Check(captures == 1 && engine.State == EngineState.Running, "AI 等待期间不得重复请求或推进");
byte[]? evidence = null;
engine.StepSnapshotChanged += s => { if (s.IsMet) evidence = s.EvidenceJpeg; };
fake.Result.SetResult(new(true, 0.95, "已安装"));
for (int i = 0; i < 100 && engine.State != EngineState.Completed; i++) { await Task.Delay(10); engine.ProcessFrame(frame, Capture); }
Check(engine.State == EngineState.Completed && ReferenceEquals(evidence, image), "仅 AI 确认可完成,且必须保留原判定图");
// 复位、暂停、停止都应使旧请求失效,即使服务忽略取消。
foreach (var action in new Action<SopEngine>[] { e => e.Reset(), e => { e.TogglePause(); e.TogglePause(); }, e => { e.Stop(); e.Start(); } })
{
fake = new(); engine.VisionDecisionClient = fake; engine.Reset();
engine.ProcessFrame(frame, Capture); engine.ProcessFrame(frame, Capture);
await fake.Called.Task.WaitAsync(TimeSpan.FromSeconds(5));
action(engine);
fake.Result.SetResult(new(true, 1, "旧结果"));
engine.VisionDecisionClient = null;
await Task.Delay(20);
engine.ProcessFrame(frame, Capture); engine.ProcessFrame(frame, Capture);
Check(engine.State == EngineState.Running, "旧结果不能推进新状态");
}
foreach (var decision in new[] { new VisionDecisionResult(false, .99, "未完成"), new(true, .5, "不确定") })
{
fake = new(); engine.VisionDecisionClient = fake; engine.Reset();
engine.ProcessFrame(frame, Capture); engine.ProcessFrame(frame, Capture);
await fake.Called.Task.WaitAsync(TimeSpan.FromSeconds(5));
fake.Result.SetResult(decision);
await Task.Delay(30); engine.ProcessFrame(frame, Capture);
Check(engine.State == EngineState.Running, "拒绝或低置信度不得完成");
var before = captures; engine.ProcessFrame(frame, Capture);
Check(captures == before, "拒绝后必须限流");
}
fake = new(); engine.VisionDecisionClient = fake; engine.Reset();
engine.ProcessFrame(frame, Capture); engine.ProcessFrame(frame, Capture);
await fake.Called.Task.WaitAsync(TimeSpan.FromSeconds(5));
await Task.Delay(1100); engine.ProcessFrame(frame, Capture);
Check(engine.State == EngineState.Running, "超时不能完成");
engine.Stop();
// HTTP 适配器:校验真实出站消息和严格响应解析,不进行外部网络调用。
var names = new[] { "SOPHELPER_VISION_ENDPOINT", "SOPHELPER_VISION_MODEL", "SOPHELPER_VISION_API_KEY" };
var previous = names.Select(Environment.GetEnvironmentVariable).ToArray();
try
{
Environment.SetEnvironmentVariable(names[0], "https://vision.invalid/v1/chat/completions");
Environment.SetEnvironmentVariable(names[1], "test-vision");
Environment.SetEnvironmentVariable(names[2], "test-key");
using var handler = new FakeHttp(); using var http = new HttpClient(handler);
var client = new ChatCompletionsVisionClient(http);
var request = new VisionDecisionRequest("配方", 1, "装配", "说明", "已安装", 42, DateTime.Now, image);
var result = await client.DecideAsync(request, default);
Check(result.Completed && result.Confidence == .95, "应解析兼容接口响应");
using var body = JsonDocument.Parse(handler.Body!);
Check(body.RootElement.GetProperty("model").GetString() == "test-vision", "应发送配置模型");
Check(body.RootElement.GetProperty("messages")[1].GetProperty("content")[1].GetProperty("image_url").GetProperty("url").GetString() == "data:image/jpeg;base64,AQID", "应发送准确取图");
Check(handler.Authorization == "Bearer test-key", "应使用配置密钥");
foreach (var malformed in new[] { "{\"completed\":true}", "{\"completed\":true,\"confidence\":2,\"reason\":\"错误\"}", "不是 JSON" })
{
handler.Content = malformed;
var rejected = false;
try { await client.DecideAsync(request, default); } catch (Exception) { rejected = true; }
Check(rejected, "畸形响应必须拒绝");
}
handler.Content = "{\"completed\":true,\"confidence\":0.95,\"reason\":\"已安装\"}";
handler.FinishReason = "length";
var truncatedRejected = false;
try { await client.DecideAsync(request, default); } catch (FormatException) { truncatedRejected = true; }
Check(truncatedRejected, "截断响应必须拒绝");
handler.Status = HttpStatusCode.Unauthorized;
var httpRejected = false;
try { await client.DecideAsync(request, default); } catch (InvalidOperationException) { httpRejected = true; }
Check(httpRejected, "HTTP 失败不得完成");
}
finally { for (int i = 0; i < names.Length; i++) Environment.SetEnvironmentVariable(names[i], previous[i]); }
await LayaChecks.RunAsync(args);
await D3Checks.RunAsync(args);
await RealtimeDeadlineChecks.RunAsync();
await BufferedEvidenceChecks.RunAsync();
await ObservationWindowChecks.RunAsync();
await ContinuousCheckTests.RunAsync();
await SequenceProtocolTests.RunAsync();
VisualEvidenceTests.Run();
HandContactChecks.Run();
await TriggerImageChecks.RunAsync();
await DynamicRegionChecks.RunAsync();
Console.WriteLine("PASS: 手部触发、单请求、AI 门控、证据帧、限流、超时、旧结果失效、配方往返、兼容 HTTP 消息及错误响应、Laya 原生适配与复核语义");
sealed class FakeDecision : IVisionDecisionClient
{
public TaskCompletionSource Called { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource<VisionDecisionResult> Result { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public VisionDecisionRequest? Request;
public Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request, CancellationToken cancellationToken)
{ Request = request; Called.TrySetResult(); return Result.Task; }
}
sealed class FakeHttp : HttpMessageHandler
{
public string? Body, Authorization;
public string FinishReason = "stop";
public HttpStatusCode Status = HttpStatusCode.OK;
public string Content = "{\"completed\":true,\"confidence\":0.95,\"reason\":\"已安装\"}";
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Body = await request.Content!.ReadAsStringAsync(cancellationToken);
Authorization = request.Headers.Authorization?.ToString();
return new(Status) { Content = new StringContent(JsonSerializer.Serialize(new { choices = new[] { new { finish_reason = FinishReason, message = new { content = Content } } } }), Encoding.UTF8, "application/json") };
}
}