aisop/tests/VideoFlowTest.Smoke/AgentDraftVerificationChecks.cs
tfarcraw df044f6c59 自动保存Agent分析全过程日志并显示具体失败原因
每次分析创建独立JSONL日志,实时记录模型请求与原始响应、工具调用、视频时间点、上下文压缩、回测结果及异常;实际读取和送检截图独立落盘。聊天显示日志位置,鉴权密钥与内联图片数据脱敏。取消和失败保留完整已写日志,额外错误快照关联会话日志。

修复tool_calls为空时的响应兼容问题,检查空choices及服务返回错误,避免吞掉具体解析异常。

验证:SopVideoAgent.Smoke、VideoFlowTest.Smoke通过,涵盖日志实时写入、图片证据、脱敏、异常与取消。真实接口独立分析完成三轮回测,未复现通用异常,草稿实际停在第二步;报告见scratch/agent-failure-live。额外Avalonia.Smoke的旧侧栏数量断言在进入Agent检查前失败,本次未涉及侧栏。
2026-11-18 14:07:30 +08:00

152 lines
12 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 = "人工要求" }];
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";
model.AgentAutoVerify = true;
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");
Check(verifier.Calls == 1 && model.AgentDraftSteps.Count == 1 && model.ApplyAgentDraftCommand.CanExecute(), $"Generated draft passes local verification before it becomes applicable: calls={verifier.Calls}, rows={model.AgentDraftSteps.Count}, status={model.AgentStatus}");
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_end") && logText.Contains("session_end"), "Every analysis saves its lifecycle and model events automatically");
Check(Directory.GetFiles(Path.ChangeExtension(savedLog, null) + "-images", "*.jpg").Length == 1,
"Actual model image evidence is saved beside the analysis 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;
model.GenerateStepsCommand.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.GenerateStepsCommand.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 async Task<SopVideoDraft> AnalyzeAsync(SopVideoAnalysisRequest request, SopAgentConnection connection, CancellationToken token)
{
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("已回测", 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));
}
}
}