aisop/tests/VideoFlowTest.Smoke/AgentDraftVerificationChecks.cs

169 lines
14 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Avalonia.Controls;
using Avalonia.Threading;
using Avalonia.VisualTree;
using OpenCvSharp;
using Prism.Dialogs;
using SopHelper.Engine.Sop;
using SopHelper.Engine.SopAgent;
using SopHelper.Engine.Training;
using SopHelper.Training;
using SopHelper.VVMs.RecipeEditor;
using Window = Avalonia.Controls.Window;
internal static class AgentDraftVerificationChecks
{
public static void Run(string root)
{
var store = new RecipeWorkspace(root);
Directory.CreateDirectory(root);
var video = Path.Combine(root, "agent-verification.avi");
using (var writer = new VideoWriter(video, FourCC.MJPG, 10, new OpenCvSharp.Size(64, 48)))
{
Check(writer.IsOpened(), "Agent verification test video opens");
for (var i = 0; i < 20; i++) { using var image = new Mat(48, 64, MatType.CV_8UC3, new Scalar(20, 50, 100)); writer.Write(image); }
}
var config = new SopConfig(); config.Sop.Name = "代理草稿验证"; config.Sop.Parts = [];
config.Sop.Regions["work"] = new() { X2 = 64, Y2 = 48 };
config.Sop.Steps = [new() { Id = 1, Name = "保留人工步骤", Description = "人工要求" }];
Directory.CreateDirectory(Path.Combine(root,"workspace"));
File.WriteAllText(Path.Combine(root,"workspace","sop-agent.json"),"{\"endpoint\":\"http://127.0.0.1:1/v1\",\"model\":\"unit-test\",\"autoVerify\":true}");
var model = new RecipeEditorViewModel();
var verifier = new ProbeVerifier(); var client = new ProbeClient(); model.DraftVerifier = verifier; model.AgentClient = client;
model.OnDialogOpened(new DialogParameters { { "directory", store.RecipesDirectory }, { "config", config }, { "new", true } });
model.SaveCommand.Execute();
var path = store.ConfigPath(config.Sop.Name); var before = File.ReadAllBytes(path);
model.AgentVideoPath = video; model.AgentEndpoint = "http://127.0.0.1:1/v1"; model.AgentModel = "unit-test";
var view = new RecipeEditor { DataContext = model };
var window = new Window { Width = 1040, Height = 900, Content = view }; window.Show(); window.UpdateLayout();
var tabs = view.GetVisualDescendants().OfType<TabControl>().Single();
tabs.SelectedItem = tabs.Items.OfType<TabItem>().Single(t => t.Header?.ToString() == "Agent助手"); window.UpdateLayout();
Check(view.GetVisualDescendants().OfType<Button>().Count(b => ReferenceEquals(b.Command, model.VerifyAgentDraftCommand)) == 1,
"Agent page exposes one explicit reverify-and-repair button");
model.GenerateStepsCommand.Execute(); Until(() => !model.IsAgentBusy);
Check(model.AgentChatMessages.Any(m => m.IsPrompt && m.Text.Contains("实际系统提示词")), "Generation retains sent prompts in the chat after replacing the draft");
window.UpdateLayout();
Check(view.GetVisualDescendants().OfType<Expander>().Any(e => e.Header?.ToString()?.Contains("展开实际提示词") == true), "Chat exposes collapsible actual prompt details");
var preview=Path.GetFullPath("artifacts/agent-split-preview.png");Directory.CreateDirectory(Path.GetDirectoryName(preview)!);
using(var bitmap=new Avalonia.Media.Imaging.RenderTargetBitmap(new Avalonia.PixelSize((int)window.Bounds.Width,(int)window.Bounds.Height)))
{ bitmap.Render(window);bitmap.Save(preview); }
Check(verifier.Calls == 0 && model.AgentDraftSteps.Count == 1 && model.ApplyAgentDraftCommand.CanExecute(), $"Generation finishes without verification even with legacy autoVerify enabled: calls={verifier.Calls}, rows={model.AgentDraftSteps.Count}, status={model.AgentStatus}");
Check(!view.GetVisualDescendants().OfType<CheckBox>().Any(c=>c.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text?.Contains("生成后自动") == true)),
"Generation and verification are separate actions without an automatic chaining checkbox");
Check(model.Recipe.Regions.Count == 1 && model.Recipe.Steps.Count == 1 && File.ReadAllBytes(path).SequenceEqual(before), "Generating and verifying region proposals never edits or saves the recipe");
Check(model.AgentRegionAdjustmentsSummary.Contains("trigger"), "Region corrections are visible as draft proposals");
var logsFolder = Path.Combine(root, "workspace", "agent-logs");
var savedLog = Directory.GetFiles(logsFolder, "analysis-*.jsonl").Single();
var logText = File.ReadAllText(savedLog);
Check(logText.Contains("session_start") && logText.Contains("video_info") && logText.Contains("model_response")
&& !logText.Contains("verification_start") && logText.Contains("session_end"), "Generation logs finish without starting local verification");
Check(Directory.GetFiles(Path.ChangeExtension(savedLog, null) + "-images", "*.jpg").Length == 1,
"Actual model image evidence is saved beside the analysis log");
model.AgentChatInput="保留当前工艺要求,润色说明";model.SendAgentChatCommand.Execute();Until(()=>!model.IsAgentBusy);
Check(verifier.Calls==0&&client.SawCurrentDraft&&!client.SawDirectVerification&&model.ApplyAgentDraftCommand.CanExecute(),"Ordinary chat edits the current draft without running verification");
model.VerifyAgentDraftCommand.Execute();Until(()=>!model.IsAgentBusy);
Check(verifier.Calls==1&&client.SawVerification&&client.SawCurrentDraft&&client.SawDirectVerification&&model.ApplyAgentDraftCommand.CanExecute(),"Explicit verification reuses the generated draft and directly replays it before requesting model revision");
Check(Directory.GetFiles(logsFolder,"analysis-*.jsonl").Select(File.ReadAllText).Any(text=>text.Contains("verify_and_revise")&&text.Contains("verification_end")),
"Verification and revision use their own complete session log");
model.AgentApiKey = "never-show-secret";
client.Failure = new System.Net.Http.HttpRequestException("连接重置 Bearer never-show-secret data:image/jpeg;base64,AAAA");
model.GenerateStepsCommand.Execute(); Until(() => !model.IsAgentBusy);
Check(model.AgentStatus.Contains("模型接口连接失败") && model.AgentStatus.Contains("连接重置")
&& !model.AgentStatus.Contains("never-show-secret") && !model.AgentStatus.Contains("AAAA"), "Actual network cause is visible while credentials and image bytes are hidden");
var diagnostics = Directory.GetFiles(Path.Combine(root, "workspace", "agent-diagnostics"), "error-*.json").Select(File.ReadAllText).ToArray();
Check(diagnostics.Any(d => d.Contains("HttpRequestException") && d.Contains("Stage"))
&& diagnostics.All(d => !d.Contains("never-show-secret") && !d.Contains("AAAA")), "Agent failures persist a redacted exception and stage for diagnosis");
var errorLogs = Directory.GetFiles(logsFolder, "analysis-*.jsonl").Select(File.ReadAllText).ToArray();
Check(errorLogs.Any(l => l.Contains("exception") && l.Contains("HttpRequestException"))
&& errorLogs.All(l => !l.Contains("never-show-secret") && !l.Contains("AAAA")), "Session logs include the exception and hide credentials and inline image bytes");
Check(model.AgentDraftSteps.Count == 1 && File.ReadAllBytes(path).SequenceEqual(before), "Network failure preserves existing draft and recipe");
client.Failure = new InvalidOperationException("模型响应 choices 类型错误");
model.GenerateStepsCommand.Execute(); Until(() => !model.IsAgentBusy);
Check(model.AgentStatus.Contains("choices 类型错误") && model.AgentChatMessages.Any(m => m.Speaker == "错误详情"), "Previously hidden parsing errors now appear in chat with diagnostic location");
client.Failure = null;
model.AgentDraftSteps[0].Description = "人工补充的静态结果";
Check(!model.ApplyAgentDraftCommand.CanExecute() && model.AgentVerificationSummary.Contains("修改"), "Manual draft edits invalidate the verification result");
model.VerifyAgentDraftCommand.Execute(); Until(() => !model.IsAgentBusy);
Check(model.ApplyAgentDraftCommand.CanExecute(), "Reverification restores eligibility after an edited draft passes");
model.Recipe.Regions[0].X2 = 60;
model.ApplyAgentDraftCommand.Execute();
Check(model.Recipe.Steps.Count == 1 && !model.ApplyAgentDraftCommand.CanExecute(), "Changed calibration cannot apply a stale verified draft");
model.VerifyAgentDraftCommand.Execute(); Until(() => !model.IsAgentBusy);
model.ApplyAgentDraftCommand.Execute();
Check(model.Recipe.Steps.Count == 2 && model.Recipe.Steps[0].Name == "保留人工步骤"
&& model.Recipe.Regions.Any(r => r.Key == "trigger" && r.X1 == 8 && r.X2 == 28)
&& model.Recipe.Steps[1].Detection is { StableFrames: 8, Region: "trigger" }
&& model.Recipe.Steps[1].AiImageRegion == "work" && model.Recipe.Steps[1].AiMinConfidence == .85,
"Explicit application uses the exact tested trigger, crop and debounce while preserving existing steps and AI threshold");
Check(File.ReadAllBytes(path).SequenceEqual(before), "Applying verified draft still requires explicit recipe save");
verifier.Passed = false;
var previousCalls=verifier.Calls;
model.GenerateStepsCommand.Execute(); Until(() => !model.IsAgentBusy);
Check(verifier.Calls==previousCalls&&model.ApplyAgentDraftCommand.CanExecute(),"Regeneration remains independent from a prior verified workflow");
model.VerifyAgentDraftCommand.Execute();Until(()=>!model.IsAgentBusy);
Check(!model.ApplyAgentDraftCommand.CanExecute() && model.AgentVerificationSummary.Contains("未通过") && model.Recipe.Steps.Count == 2,
"Failed verification leaves the draft visible but blocks automatic application");
verifier.Hold = true;
var completedLogs = Directory.GetFiles(logsFolder, "analysis-*.jsonl");
model.VerifyAgentDraftCommand.Execute(); Until(() => verifier.Entered);
var runningLog = Directory.GetFiles(logsFolder, "analysis-*.jsonl").Except(completedLogs).Single();
using (var stream = new FileStream(runningLog, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader(stream))
{
var runningText = reader.ReadToEnd();
Check(runningText.Contains("verification_start") && !runningText.Contains("session_end"),
"Analysis events are flushed to disk while the operation is still running");
}
model.CancelAgentCommand.Execute(); Until(() => !model.IsAgentBusy);
Check(File.ReadAllText(runningLog).Contains("cancelled_or_timeout") && File.ReadAllText(runningLog).Contains("session_end"),
"Cancellation finishes the persistent log without losing earlier events");
Check(model.Recipe.Steps.Count == 2 && File.ReadAllBytes(path).SequenceEqual(before), "Cancelling verification leaves the recipe untouched");
Pump(model.ShutdownAsync()); window.Close(); model.OnDialogClosed();
}
private static void Pump(Task task) { Until(() => task.IsCompleted); task.GetAwaiter().GetResult(); }
private static void Until(Func<bool> ready)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
while (!ready() && watch.Elapsed < TimeSpan.FromSeconds(10)) { using var cancellation = new CancellationTokenSource(10); Dispatcher.UIThread.MainLoop(cancellation.Token); }
Check(ready(), "Agent verification operation completes"); Dispatcher.UIThread.RunJobs();
}
private static void Check(bool value, string message) { if (!value) throw new Exception(message); Console.WriteLine("PASS: " + message); }
private sealed class ProbeClient : ISopVideoDraftClient
{
public Exception? Failure;
public bool SawVerification, SawCurrentDraft, SawDirectVerification;
public async Task<SopVideoDraft> AnalyzeAsync(SopVideoAnalysisRequest request, SopAgentConnection connection, CancellationToken token)
{
SawVerification=request.VerifyDraft is not null;SawCurrentDraft=request.CurrentDraft is not null;SawDirectVerification=request.VerifyCurrentDraftFirst;
if (Failure is { } error) throw error;
request.PromptSent?.Report(new(1, 1234, connection.ContextLength, "", "实际系统提示词和当前用户要求"));
var frames = SopVideoSampler.ReadFrames(request.Video, [.5, 1.5], 0, token);
request.Trace?.Invoke(new("model_request", 1, "实际提示词"));
request.Trace?.Invoke(new("model_response", 1, "HTTP 200:模型返回草稿", [new("frame_index=0 time=0.5s", frames[0].Jpeg)]));
var draft = request.CurrentDraft ?? new SopVideoDraft
{
Summary = "生成草稿", RegionAdjustments = [new() { Key = "trigger", X1 = 8, Y1 = 8, X2 = 28, Y2 = 28, EvidenceFrame = 0, Note = "标准画面可见" }],
Steps = [new() { Name = "放入", Description = "盒内可见零件", Region = "trigger", ImageRegion = "work", StableFrames = 8, EndSeconds = 2, EvidenceFrame = 0 }]
};
draft.ObservedFrames = frames;
if (request.VerifyDraft is { } verify) draft.Verification = await verify(draft, request.Video with { Frames = frames }, token);
return draft;
}
public async Task<SopAgentChatResult> ChatAsync(SopVideoAnalysisRequest request, SopAgentConnection connection, CancellationToken token)
{ var draft = await AnalyzeAsync(request, connection, token); return new(request.VerifyDraft is null ? "已更新草稿" : "已回测", draft, draft.ObservedFrames); }
}
private sealed class ProbeVerifier : ISopDraftVideoVerifier
{
public bool Passed = true, Hold, Entered;
public int Calls;
public async Task<SopDraftVerification> VerifyAsync(SopVideoDraft draft, SopVideoSample video, SopConfig template, IProgress<string>? progress, CancellationToken token)
{
Calls++; Entered = Hold;
if (Hold) await Task.Delay(Timeout.Infinite, token);
return new(Passed, Passed ? "回测通过" : "回测未通过", [new(1, draft.Steps[0].Name, Passed, "本地判定")], [],
SopDraftConfigBuilder.Fingerprint(SopDraftConfigBuilder.Build(template, draft), video));
}
}
}