228 lines
16 KiB
C#
228 lines
16 KiB
C#
using Avalonia.Controls;
|
||
using Avalonia.Threading;
|
||
using OpenCvSharp;
|
||
using SopHelper.Engine.Sop;
|
||
using SopHelper.Engine.SopAgent;
|
||
using SopHelper.VVMs.RecipeEditor;
|
||
|
||
internal static class OptimizeStepsChecks
|
||
{
|
||
public static void Run()
|
||
{
|
||
CheckRewriteProtocolAsync().GetAwaiter().GetResult();
|
||
// 独立运行优化测试时,在临时工作区建立有权设置模型的账号。
|
||
var access = SopHelper.Models.UserAccess.Current;
|
||
if (access.NeedsSetup) access.Setup("optimization-smoke-admin", "OptimizationSmokePassword123");
|
||
var model = new RecipeEditorViewModel { AgentEndpoint = "http://127.0.0.1:1/v1", AgentModel = "test" };
|
||
model.OptimizeStepsCommand.Execute();
|
||
Check(model.AgentStatus.Contains("没有"), "空配方不优化");
|
||
var first = model.Recipe.AddStep(); first.Description = "零件安装到位";
|
||
model.OptimizeStepsCommand.Execute();
|
||
Check(model.AgentStatus.Contains("关键帧"), "缺关键帧不优化");
|
||
using var image = new Mat(48, 64, MatType.CV_8UC3, new Scalar(30, 40, 230));
|
||
first.KeyFrameBase64 = Convert.ToBase64String(image.ToBytes(".png")); first.KeyFrameSeconds = 2.5;
|
||
// 模拟缩放帧,配方区域的右下角在原图边缘,直接套用坐标会越界。
|
||
first.KeyFrameSourceSize = new() { Width = 128, Height = 96 };
|
||
var inspect = model.Recipe.AddRegion("inspect");
|
||
inspect.X1 = 65; inspect.Y1 = 49; inspect.X2 = 128; inspect.Y2 = 96;
|
||
first.AiImageMode = VisionImageMode.FixedRegion; first.AiImageRegion = "inspect";
|
||
var second = model.Recipe.AddStep(); second.Description = "盖子关闭"; second.KeyFrameBase64 = first.KeyFrameBase64;
|
||
var original = first.Description;
|
||
var descriptions = new Descriptions(); model.DescriptionClient = descriptions;
|
||
var decisions = new Decisions(); model.StepTestDecisionClient = decisions;
|
||
var view = new RecipeEditor { DataContext = model };
|
||
Check(view.FindControl<Button>("OptimizeAgentStepsButton")?.Command == model.OptimizeStepsCommand, "优化按钮绑定");
|
||
var scopeBox = view.FindControl<ComboBox>("OptimizationScopeBox")!;
|
||
var stepBox = view.FindControl<ComboBox>("OptimizationStepBox")!;
|
||
Dispatcher.UIThread.RunJobs();
|
||
Check(scopeBox.SelectedIndex == 0 && !stepBox.IsVisible, "默认优化全部步骤");
|
||
model.OptimizeStepsCommand.Execute();
|
||
Check(model.IsAgentBusy && !model.OptimizeStepsCommand.CanExecute() && !model.TestStepDecisionCommand.CanExecute(), "优化期间禁用重复任务和手动判定");
|
||
Until(() => !model.IsAgentBusy);
|
||
Check(decisions.Requests.Count == 20 && descriptions.Calls == 2, "每步原文加9条改写恰好测试10次");
|
||
Check(first.Description == original + "改写4" && second.Description == "盖子关闭改写4", "选最高有效置信度,排除超时与NaN");
|
||
Check(decisions.Requests.Take(10).Select(r => r.Criteria).Distinct().Count() == 10
|
||
&& decisions.Requests.All(r => r.ImageCount == 1 && r.Description == r.Criteria && r.TimeoutMs == 300)
|
||
&& decisions.Requests.Take(10).All(r => r.SourceSeconds == 2.5 && r.Jpeg.SequenceEqual(decisions.Requests[0].Jpeg)), "复用整张关键帧和全局超时");
|
||
Check(model.StepDecisionLog.Contains("优化 10/10") && model.AgentStatus.Contains("保存"), "显示判定记录与保存提示");
|
||
Check(view.FindControl<ItemsControl>("OptimizationReportsList")?.ItemsSource == model.OptimizationReports
|
||
&& model.OptimizationReports.Count == 2, "界面绑定逐步优化明细");
|
||
for (var stepIndex = 0; stepIndex < 2; stepIndex++)
|
||
{
|
||
var report = model.OptimizationReports[stepIndex];
|
||
for (var candidateIndex = 0; candidateIndex < 10; candidateIndex++)
|
||
Check(report.Text.Contains($"{candidateIndex + 1:00} ·")
|
||
&& report.Text.Contains(decisions.Requests[stepIndex * 10 + candidateIndex].Criteria), "明细完整列出10种实际送检描述");
|
||
Check(report.Text.Contains("05 · 同义改写 · ★ 最高分选中") && report.Text.Contains("返回值:0.98")
|
||
&& report.Text.Contains("超时") && report.Text.Contains("NaN") && report.Text.Contains("不参与择优")
|
||
&& report.Outcome.Contains("保存"), "公开最高分、原始分数、超时及无效分数");
|
||
Check(report.EvidenceImage.PixelWidth == (stepIndex == 0 ? 32 : 64) && report.EvidenceImage.PixelHeight == (stepIndex == 0 ? 24 : 48)
|
||
&& descriptions.Images[stepIndex].SequenceEqual(decisions.Requests[stepIndex * 10].Jpeg), "Agent与djev接收完全相同的关键帧且界面显示该图片");
|
||
}
|
||
Check(model.OptimizationReports[0].EvidenceLabel.Contains("inspect [65,49,128,96] · 关键帧裁剪 [32,24,64,48]"),
|
||
"优化公开原区域和实际裁剪坐标");
|
||
using (var decoded = Cv2.ImDecode(Convert.FromBase64String(first.KeyFrameBase64), ImreadModes.Color))
|
||
Check(VisionDecisionImage.Encode(decoded, new() { X1 = 32, Y1 = 24, X2 = 64, Y2 = 48 }).SequenceEqual(decisions.Requests[0].Jpeg),
|
||
"优化按换算后的固定区域裁剪,Agent 与 djev 共用结果");
|
||
Check(model.AgentChatMessages.Count(m => m.Text.Contains("10 · 同义改写")) == 2, "对话保留每步全部候选及分数");
|
||
|
||
decisions = new Decisions { Invalid = true }; model.StepTestDecisionClient = decisions;
|
||
var retained = first.Description;
|
||
model.OptimizeStepsCommand.Execute(); Until(() => !model.IsAgentBusy);
|
||
// 两轮判定返回不同原因,检查第二轮只展示自己的日志和候选。
|
||
Check(model.StepDecisionLog.Contains("异常") && !model.StepDecisionLog.Contains("测试结果")
|
||
&& model.AgentChatMessages.Count(m => m.Text.Contains("10 · 同义改写")) == 2, "重新优化清空上一轮的判定日志和对话记录");
|
||
Check(first.Description == retained && decisions.Requests.Count == 20, "所有测试无效保留原说明");
|
||
Check(model.OptimizationReports.Count == 2 && model.OptimizationReports.All(r => r.Text.Contains("无有效分数")
|
||
&& !r.Text.Contains("★")), "异常结果公开且不标记为选中");
|
||
|
||
// 从界面选择单步。其他步骤缺关键帧时仍可运行,开始后切换选中项也不改变本次目标。
|
||
scopeBox.SelectedIndex = 1;
|
||
stepBox.SelectedItem = null;
|
||
Dispatcher.UIThread.RunJobs();
|
||
Check(stepBox.IsVisible && model.Recipe.SelectedStep is null, "单步模式显示步骤列表并同步选中项");
|
||
model.OptimizeStepsCommand.Execute();
|
||
Check(!model.IsAgentBusy && model.AgentStatus.Contains("请选择"), "单步模式未选步骤时提示选择");
|
||
stepBox.SelectedItem = second;
|
||
var firstFrame = first.KeyFrameBase64;
|
||
first.KeyFrameBase64 = "";
|
||
var secondOriginal = second.Description;
|
||
decisions = new Decisions(); model.StepTestDecisionClient = decisions;
|
||
var callsBeforeSingle = descriptions.Calls;
|
||
descriptions.Pending = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
model.OptimizeStepsCommand.Execute(); Until(() => descriptions.Calls == callsBeforeSingle + 1);
|
||
Check(!scopeBox.IsEffectivelyEnabled && !stepBox.IsEffectivelyEnabled, "任务运行时锁定范围和步骤选择器");
|
||
model.Recipe.SelectedStep = first;
|
||
descriptions.Pending.SetResult(Enumerable.Range(1, 9).Select(i => secondOriginal + "改写" + i).ToArray());
|
||
Until(() => !model.IsAgentBusy);
|
||
Check(decisions.Requests.Count == 10 && decisions.Requests.All(r => r.StepId == second.Id)
|
||
&& model.OptimizationReports.Count == 1 && model.AgentStatus.Contains("已优化 1 步"), "指定步骤只生成一份报告并判定10次");
|
||
Check(first.Description == retained && second.Description == secondOriginal + "改写4", "只回写启动时选中的步骤");
|
||
descriptions.Pending = null;
|
||
first.KeyFrameBase64 = firstFrame;
|
||
scopeBox.SelectedIndex = 0;
|
||
|
||
var callsBefore = descriptions.Calls;
|
||
foreach (var mode in new[] { VisionImageMode.Hand, VisionImageMode.FixedRegion })
|
||
{
|
||
first.AiImageMode = mode; first.AiImageRegion = "missing";
|
||
model.OptimizeStepsCommand.Execute(); Until(() => !model.IsAgentBusy);
|
||
Check(descriptions.Calls == callsBefore && first.Description == retained && model.AgentStatus.Contains("未应用"),
|
||
"无跟踪上下文或区域缺失时不向Agent发送错误图片,且配方不修改");
|
||
}
|
||
first.AiImageMode = VisionImageMode.FixedRegion; first.AiImageRegion = "inspect";
|
||
|
||
descriptions.Pending = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
model.OptimizeStepsCommand.Execute(); Until(() => model.IsAgentBusy);
|
||
model.CancelAgentCommand.Execute(); Until(() => !model.IsAgentBusy);
|
||
Check(first.Description == retained && model.AgentStatus.Contains("取消"), "取消后不修改配方");
|
||
|
||
descriptions.Pending = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
model.OptimizeStepsCommand.Execute(); Until(() => model.IsAgentBusy);
|
||
first.Description = "用户修改";
|
||
descriptions.Pending.SetResult(Enumerable.Range(1, 9).Select(i => retained + "改写" + i).ToArray());
|
||
Until(() => !model.IsAgentBusy);
|
||
Check(first.Description == "用户修改" && model.AgentStatus.Contains("未应用"), "优化期间编辑说明不能被覆盖");
|
||
|
||
descriptions.Pending = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
model.OptimizeStepsCommand.Execute(); Until(() => model.IsAgentBusy);
|
||
inspect.X2 = 126;
|
||
descriptions.Pending.SetResult(Enumerable.Range(1, 9).Select(i => "用户修改" + "改写" + i).ToArray());
|
||
Until(() => !model.IsAgentBusy);
|
||
Check(first.Description == "用户修改" && model.AgentStatus.Contains("送检规则"), "优化中改变区域配置时不应用旧范围的分数");
|
||
|
||
descriptions.Pending = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
model.OptimizeStepsCommand.Execute(); Until(() => model.IsAgentBusy);
|
||
var shutdown = model.ShutdownAsync(); Until(() => shutdown.IsCompleted); shutdown.GetAwaiter().GetResult();
|
||
Check(!model.IsAgentBusy && !model.OptimizeStepsCommand.CanExecute(), "关闭取消优化并等待清理");
|
||
Console.WriteLine("PASS: Agent全部与指定步骤优化、10次判定、最高分选择、异常保留、取消和并发修改保护");
|
||
}
|
||
|
||
private static async Task CheckRewriteProtocolAsync()
|
||
{
|
||
using var handler = new RewriteHandler();
|
||
using var http = new HttpClient(handler);
|
||
var client = new SopDescriptionClient(http);
|
||
var connection = new SopAgentConnection("http://localhost/v1", "test", "test-key", EnableThinking: false);
|
||
var candidates = await client.RewriteAsync("安装", "零件安装到位", new byte[] { 1, 2, 3 }, connection, CancellationToken.None);
|
||
Check(candidates.Count == 9 && handler.Body.Contains("零件安装到位") && handler.Body.Contains("不得增删要求"), "发送原始说明和保留工艺约束");
|
||
using var payload = System.Text.Json.JsonDocument.Parse(handler.Body);
|
||
var userContent = payload.RootElement.GetProperty("messages")[1].GetProperty("content");
|
||
Check(userContent[0].GetProperty("type").GetString() == "text"
|
||
&& userContent[1].GetProperty("type").GetString() == "image_url"
|
||
&& userContent[1].GetProperty("image_url").GetProperty("url").GetString() == "data:image/jpeg;base64,AQID"
|
||
&& handler.Body.Contains("必须查看附带的步骤关键帧") && handler.Body.Contains("禁止编造")
|
||
&& handler.Body.Contains("图片与原说明明显矛盾"), "真实HTTP请求发送图片并约束与图片及原说明一致");
|
||
Check(handler.Endpoint == "http://localhost/v1/chat/completions" && handler.Authorization == "Bearer test-key"
|
||
&& !payload.RootElement.GetProperty("chat_template_kwargs").GetProperty("enable_thinking").GetBoolean(), "复用Agent连接与思考参数");
|
||
handler.Duplicate = true;
|
||
try { await client.RewriteAsync("安装", "零件安装到位", new byte[] { 1, 2, 3 }, connection, CancellationToken.None); throw new Exception("重复候选应拒绝"); }
|
||
catch (FormatException) { }
|
||
handler.Duplicate = false; handler.Truncated = true;
|
||
try { await client.RewriteAsync("安装", "零件安装到位", new byte[] { 1, 2, 3 }, connection, CancellationToken.None); throw new Exception("截断候选应拒绝"); }
|
||
catch (FormatException) { }
|
||
}
|
||
|
||
private sealed class RewriteHandler : HttpMessageHandler
|
||
{
|
||
public string Body = "", Endpoint = "", Authorization = "";
|
||
public bool Duplicate, Truncated;
|
||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||
{
|
||
Body = await request.Content!.ReadAsStringAsync(cancellationToken);
|
||
// JSON默认转义中文,解码后用于检查原文及约束。
|
||
using var payload = System.Text.Json.JsonDocument.Parse(Body);
|
||
Body = System.Text.Json.JsonSerializer.Serialize(payload.RootElement, new System.Text.Json.JsonSerializerOptions
|
||
{ Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
|
||
Endpoint = request.RequestUri!.ToString(); Authorization = request.Headers.Authorization!.ToString();
|
||
var content = System.Text.Json.JsonSerializer.Serialize(new { descriptions = Enumerable.Range(1, 9).Select(i => Duplicate ? "重复" : "候选" + i) });
|
||
return new(System.Net.HttpStatusCode.OK)
|
||
{
|
||
Content = new StringContent(System.Text.Json.JsonSerializer.Serialize(new
|
||
{
|
||
choices = new[] { new { finish_reason = Truncated ? "length" : "stop", message = new { content } } }
|
||
}))
|
||
};
|
||
}
|
||
}
|
||
|
||
private static void Check(bool condition, string message) { if (!condition) throw new Exception(message); }
|
||
private static void Until(Func<bool> ready)
|
||
{
|
||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||
while (!ready() && watch.Elapsed < TimeSpan.FromSeconds(15))
|
||
{
|
||
using var cancellation = new CancellationTokenSource(5);
|
||
Dispatcher.UIThread.MainLoop(cancellation.Token);
|
||
}
|
||
if (!ready()) throw new TimeoutException("优化测试超时");
|
||
Dispatcher.UIThread.RunJobs();
|
||
}
|
||
private sealed class Descriptions : ISopDescriptionClient
|
||
{
|
||
public int Calls;
|
||
public List<byte[]> Images { get; } = [];
|
||
public TaskCompletionSource<IReadOnlyList<string>>? Pending;
|
||
public Task<IReadOnlyList<string>> RewriteAsync(string name, string description, byte[] jpeg, SopAgentConnection connection, CancellationToken token)
|
||
{
|
||
Calls++; Images.Add(jpeg);
|
||
return Pending?.Task.WaitAsync(token) ?? Task.FromResult<IReadOnlyList<string>>(Enumerable.Range(1, 9).Select(i => description + "改写" + i).ToArray());
|
||
}
|
||
}
|
||
private sealed class Decisions : IVisionDecisionClient
|
||
{
|
||
public bool HandlesRequestTimeout => true;
|
||
public List<VisionDecisionRequest> Requests { get; } = [];
|
||
public bool Invalid;
|
||
public Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request, CancellationToken token)
|
||
{
|
||
Requests.Add(request);
|
||
var index = (Requests.Count - 1) % 10;
|
||
return Task.FromResult(Invalid ? new(false, 1, "异常", VisionDecisionStatus.Insufficient)
|
||
: index == 8 ? new(true, 1, "迟到", ElapsedMs: 2000)
|
||
: index == 9 ? new(true, double.NaN, "无效概率")
|
||
: new VisionDecisionResult(true, index == 4 ? .98 : .6, "测试结果"));
|
||
}
|
||
}
|
||
}
|