聊天按轮次展示系统规则、输入、工具结果和真实回测反馈,隐藏图片Base64及鉴权信息。接近预算时释放历史图片并替换已过期草稿,长对话分批摘要并保留最近原文、当前草稿及最新要求,取消最近40条的静默截断。摘要失败、截断和取消时停止请求并保留原记录。 验证:SopVideoAgent.Smoke通过,覆盖上下文压缩、摘要成功/失败/取消、日志脱敏及原有生成回测闭环;VideoFlowTest.Smoke通过,覆盖提示词折叠显示和生成后日志保留。使用隔离构建目录,未重启用户程序。
114 lines
8.2 KiB
C#
114 lines
8.2 KiB
C#
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(); model.DraftVerifier = verifier; model.AgentClient = new ProbeClient();
|
|
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");
|
|
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;
|
|
model.GenerateStepsCommand.Execute(); Until(() => verifier.Entered);
|
|
model.CancelAgentCommand.Execute(); Until(() => !model.IsAgentBusy);
|
|
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 async Task<SopVideoDraft> AnalyzeAsync(SopVideoAnalysisRequest request, SopAgentConnection connection, CancellationToken token)
|
|
{
|
|
request.PromptSent?.Report(new(1, 1234, connection.ContextLength, "", "实际系统提示词和当前用户要求"));
|
|
var frames = SopVideoSampler.ReadFrames(request.Video, [.5, 1.5], 0, token);
|
|
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));
|
|
}
|
|
}
|
|
}
|