141 lines
8.8 KiB
C#
141 lines
8.8 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 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;
|
||
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, "优化按钮绑定");
|
||
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("保存"), "显示判定记录与保存提示");
|
||
|
||
decisions = new Decisions { Invalid = true }; model.StepTestDecisionClient = decisions;
|
||
var retained = first.Description;
|
||
model.OptimizeStepsCommand.Execute(); Until(() => !model.IsAgentBusy);
|
||
Check(first.Description == retained && decisions.Requests.Count == 20, "所有测试无效保留原说明");
|
||
|
||
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);
|
||
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("安装", "零件安装到位", connection, CancellationToken.None);
|
||
Check(candidates.Count == 9 && handler.Body.Contains("零件安装到位") && handler.Body.Contains("不得增删要求"), "发送原始说明和保留工艺约束");
|
||
using var payload = System.Text.Json.JsonDocument.Parse(handler.Body);
|
||
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("安装", "零件安装到位", connection, CancellationToken.None); throw new Exception("重复候选应拒绝"); }
|
||
catch (FormatException) { }
|
||
handler.Duplicate = false; handler.Truncated = true;
|
||
try { await client.RewriteAsync("安装", "零件安装到位", 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 TaskCompletionSource<IReadOnlyList<string>>? Pending;
|
||
public Task<IReadOnlyList<string>> RewriteAsync(string name, string description, SopAgentConnection connection, CancellationToken token)
|
||
{
|
||
Calls++;
|
||
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, "测试结果"));
|
||
}
|
||
}
|
||
}
|