aisop/tests/VideoFlowTest.Smoke/AgentDraftGenerationChecks.cs

185 lines
15 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.Recipes;
using SopHelper.SopVideo;
using SopHelper.VVMs.RecipeEditor;
using Window = Avalonia.Controls.Window;
internal static class AgentDraftGenerationChecks
{
public static void Run(string root)
{
var store = new RecipeWorkspace(root);
Directory.CreateDirectory(root);
// 测试使用临时工作区的管理员账号验证模型设置写入。
var access = SopHelper.Models.UserAccess.Current;
if (!access.IsAdministrator) access.Setup("agent-smoke-admin", "AgentSmokePassword123");
var video = Path.Combine(root, "agent-generation.avi");
using (var writer = new VideoWriter(video, FourCC.MJPG, 10, new OpenCvSharp.Size(64, 48)))
{
Check(writer.IsOpened(), "Agent generation 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 = [];
ReferenceEvidenceChecks.Run(video);
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 client = new ProbeClient(); 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.AgentSequenceEnableThinking = false;
model.AgentEnableThinking = false;
using (var saved = System.Text.Json.JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "workspace", "sop-agent.json"))))
Check(!saved.RootElement.GetProperty("sequenceEnableThinking").GetBoolean() && !saved.RootElement.GetProperty("enableThinking").GetBoolean(), "Agent与时序思考设置须可持久化,便于复现实测参数");
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.FindControl<Button>("VerifyAgentStepsButton") is null
&& !view.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString()?.Contains("回测") == true),
"Agent page has no replay button");
Check(view.FindControl<Button>("GenerateAgentStepsButton") is not null
&& !view.GetVisualDescendants().OfType<Expander>().Any(e => e.Header?.ToString()?.Contains("回测") == true),
"Agent page retains generation without replay results");
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(Path.Combine("..","scratch","screenshots","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(!client.SawVerification && !client.SawDirectVerification && model.AgentDraftSteps.Count == 1 && model.ApplyAgentDraftCommand.CanExecute(), $"Generation finishes without verification even with legacy autoVerify enabled: rows={model.AgentDraftSteps.Count}, status={model.AgentStatus}");
Check(!view.GetVisualDescendants().OfType<CheckBox>().Any(c=>c.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text?.Contains("生成后自动") == true)),
"Agent page has no automatic replay checkbox");
Check(model.Recipe.Regions.Count == 1 && model.Recipe.Steps.Count == 1 && File.ReadAllBytes(path).SequenceEqual(before), "Generating 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.Recipe.SelectedStep = model.Recipe.Steps.Single();
model.TestStepDecisionCommand.Execute();
var previousDecisionLog = model.StepDecisionLog;
model.AgentChatInput="保留当前工艺要求,润色说明";model.SendAgentChatCommand.Execute();Until(()=>!model.IsAgentBusy);
Check(!client.SawVerification&&client.SawCurrentDraft&&!client.SawDirectVerification&&model.ApplyAgentDraftCommand.CanExecute(),"Ordinary chat edits the current draft without running verification");
Check(previousDecisionLog.Length > 0 && model.StepDecisionLog == previousDecisionLog
&& model.AgentChatMessages.Any(m => m.Text.Contains(savedLog)), "继续聊天保留本轮对话及判定日志");
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.StepDecisionLog.Length == 0 && model.AgentChatMessages.All(m => m.Speaker != "我" && !m.Text.Contains(savedLog))
&& model.AgentChatMessages.Count(m => m.Speaker == "分析日志") == 1, "重新生成从空日志和空对话开始,保留本次诊断");
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(), "Manual draft edits remain applicable without replay");
model.Recipe.Regions[0].X2 = 60;
model.ChooseAgentApplyAsync = () => Task.FromResult(AgentRecipeApplyChoice.Append);
model.ShowAgentApplyCompletedAsync = _ => Task.CompletedTask;
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
&& model.Recipe.Steps[1].AiCheckWindowMs == 14000
&& model.Recipe.Steps[1].AiObservationRequestMaxFrames == 6,
"Explicit application uses the generated trigger, crop and debounce while preserving existing steps and AI threshold");
// 比对实际采样的 JPEG 和时间,确保步骤沿用草稿的参考画面。
var evidence = client.Evidence!;
var keyFrame = Convert.ToBase64String(evidence.Jpeg);
Check(model.Recipe.Steps[1].KeyFrameBase64 == keyFrame && model.Recipe.Steps[1].KeyFrameSeconds == evidence.Seconds,
"应用草稿时将参考图及视频时间写入步骤关键帧");
Check(File.ReadAllBytes(path).SequenceEqual(before), "Applying generated draft still requires explicit recipe save");
model.GenerateStepsCommand.Execute(); Until(() => !model.IsAgentBusy);
Check(!client.SawVerification&&model.ApplyAgentDraftCommand.CanExecute(),"Regenerated draft is directly applicable");
client.Hold = true;
var completedLogs = Directory.GetFiles(logsFolder, "analysis-*.jsonl");
model.GenerateStepsCommand.Execute(); Until(() => client.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("model_request") && !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 generation leaves the recipe untouched");
model.SaveCommand.Execute();
var savedStep = SopConfigLoader.Load(path).Sop.Steps[1];
Check(savedStep.KeyFrameBase64 == keyFrame && savedStep.KeyFrameSeconds == evidence.Seconds,
"保存并重新读取配方后保留草稿关键帧及视频时间");
model.ConfirmCloseAsync = () => Task.FromResult(RecipeCloseChoice.Discard);
Pump(model.ShutdownAsync()); window.Close(); Until(() => !window.IsVisible); 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 generation 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 int Calls;
public SopVideoFrame? Evidence { get; private set; }
public bool Hold, Entered;
public bool SawVerification, SawCurrentDraft, SawDirectVerification;
public async Task<SopVideoDraft> AnalyzeAsync(SopVideoAnalysisRequest request, SopAgentConnection connection, CancellationToken token)
{
Calls++;
SawVerification=request.VerifyDraft is not null;SawCurrentDraft=request.CurrentDraft is not null;SawDirectVerification=request.VerifyCurrentDraftFirst;
if (Failure is { } error) throw error;
request.Trace?.Invoke(new("model_request", 1, "开始生成"));
if (Hold) { Entered = true; await Task.Delay(Timeout.Infinite, token); }
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,
Inspection = new() { EvidenceMode = "single_frame", CheckWindowMs = 14000, ObservationRequestMaxFrames = 6 } }]
};
draft.ObservedFrames = frames;
Evidence = frames[draft.Steps[0].EvidenceFrame];
Check(request.VerifyDraft is null && request.CheckReference is null && !request.VerifyCurrentDraftFirst, "Generation and chat never supply replay callbacks");
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); }
}
}