移除助手的djev回测入口及逻辑并保留步骤生成

This commit is contained in:
tfarcraw 2026-11-19 23:17:34 +08:00
parent cf0400b7fa
commit 74898e27d3
6 changed files with 68 additions and 232 deletions

View File

@ -482,21 +482,13 @@
<TextBlock Text="每次最大抽帧" VerticalAlignment="Center" Margin="0,0,8,0" />
<NumericUpDown Value="{Binding AgentMaxFrames, Mode=TwoWay}" Minimum="2" Maximum="60" Increment="1" Width="100" IsEnabled="{Binding AgentIsIdle}" />
<Button x:Name="GenerateAgentStepsButton" Content="生成步骤" Command="{Binding GenerateStepsCommand}" Margin="12,0,0,0" />
<Button x:Name="VerifyAgentStepsButton" Content="djev回测" Command="{Binding VerifyAgentDraftCommand}" Margin="8,0,0,0" />
<Button Content="取消分析" Command="{Binding CancelAgentCommand}" Margin="8,0,0,0" />
<Button Content="{Binding AgentApplyLabel}" Command="{Binding ApplyAgentDraftCommand}" Margin="8,0,0,0" />
</WrapPanel>
<TextBlock Text="先生成步骤草稿,可直接编辑或添加到配方;需要检查效果时,再单独点击“djev回测”。生成和普通对话不会自动回测。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
<TextBlock Text="生成步骤草稿后,可直接编辑或添加到配方,也可通过对话修订。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
<ProgressBar IsIndeterminate="True" IsVisible="{Binding IsAgentBusy}" Height="4" />
<TextBlock x:Name="AgentStatusText" Text="{Binding AgentStatus}" TextWrapping="Wrap" Foreground="{StaticResource Accent}" />
<Expander Header="标准视频回测与区域校正" IsExpanded="True">
<ScrollViewer MaxHeight="160" VerticalScrollBarVisibility="Auto">
<StackPanel Spacing="6">
<TextBlock Text="{Binding AgentVerificationSummary}" TextWrapping="Wrap" />
<TextBlock Text="{Binding AgentRegionAdjustmentsSummary}" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" />
</StackPanel>
</ScrollViewer>
</Expander>
<TextBlock Text="{Binding AgentRegionAdjustmentsSummary}" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" />
</StackPanel>
<ItemsControl Grid.Row="3" ItemsSource="{Binding AgentDraftSteps}" IsEnabled="{Binding AgentCanEditDraft}">
<ItemsControl.ItemTemplate>

View File

@ -1,116 +0,0 @@
using System.ComponentModel;
using System.Text.Json;
using SopHelper.Presentation;
using Prism.Commands;
using SopHelper.Engine.Sop;
using SopHelper.Engine.SopAgent;
using SopHelper.Training;
namespace SopHelper.VVMs.RecipeEditor;
public partial class RecipeEditorViewModel
{
public ISopDraftVideoVerifier DraftVerifier { get; set; } = new SopDraftVideoVerifier();
private bool _agentVerificationRequired;
private string? _agentVerifiedFingerprint;
private Task<SopDraftVerification>? _agentVerificationTask;
private readonly List<SopDraftRegion> _agentRegionAdjustments = [];
private string _agentVerificationSummary = "";
public string AgentVerificationSummary { get => _agentVerificationSummary; private set => SetProperty(ref _agentVerificationSummary, value); }
public string AgentRegionAdjustmentsSummary => string.Join("\n", _agentRegionAdjustments.Select(r =>
$"区域校正草稿:{r.Key} [{r.X1},{r.Y1}]–[{r.X2},{r.Y2}] · {r.Note}"));
public DelegateCommand VerifyAgentDraftCommand { get; private set; } = null!;
private async Task ReplayDraftWithDliteAsync()
{
if (IsAgentBusy || IsCapturing || _agentSample is null || AgentDraftSteps.Count == 0) return;
var draft = CreateAgentDraftSnapshot()!;
var video = _agentSample;
_agentCancellation = new CancellationTokenSource();
var token = _agentCancellation.Token;
IsAgentBusy = true;
_agentVerificationRequired = true;
AgentStatus = "正在由djev单图回测,每次判定500ms硬截止…";
using var runLog = new SopAgentRunLog(DesktopPlatform.WorkspaceRoot, "");
runLog.Write(new("session_start", 0, "djev_replay: single_frame; deadline_ms=500; agent_calls=0"));
runLog.Write(new("verification_start", 0, JsonSerializer.Serialize(draft)));
try
{
var progress = new Progress<string>(value => AgentStatus = value);
draft.Verification = await VerifyAgentDraftAsync(draft, video, CreateAgentVerificationTemplate(), progress, token);
token.ThrowIfCancellationRequested();
runLog.Write(new("verification_end", 0, JsonSerializer.Serialize(new { report = draft.Verification, decisions = draft.Verification.Images })));
foreach (var row in AgentDraftSteps) { row.PropertyChanged -= DraftRowChanged; row.Dispose(); }
AgentDraftSteps.Clear();
for (var i = 0; i < draft.Steps.Count; i++)
{
var step = draft.Steps[i];
var row = new AgentDraftRow(step, video.Frames[step.EvidenceFrame], draft.Verification.Images.LastOrDefault(v => v.StepId == i + 1));
row.PropertyChanged += DraftRowChanged; AgentDraftSteps.Add(row);
}
_agentRegionAdjustments.Clear();
PresentVerification(draft);
AgentStatus = draft.Verification.Passed ? "djev回测通过,未调用Agent或修改判据。"
: "djev回测未通过,未自动修改步骤;可根据失败证据编辑草稿后再回测。";
AgentChatMessages.Add(new("djev回测", AgentVerificationSummary));
}
catch (OperationCanceledException) { runLog.Write(new("cancelled_or_timeout", 0, "cancelled")); AgentStatus = "djev回测已取消。"; }
catch (Exception error) { AgentStatus = "djev回测失败:" + error.Message; }
finally
{
runLog.Write(new("session_end", 0, AgentStatus));
await WaitForAgentVerificationCleanupAsync();
_agentCancellation.Dispose(); _agentCancellation = null; IsAgentBusy = false;
}
}
private bool CanApplyAgentDraft() => !IsAgentBusy && !_draftApplied && AgentDraftSteps.Count > 0
&& (!_agentVerificationRequired || _agentVerifiedFingerprint is not null);
private async Task<SopDraftVerification> VerifyAgentDraftAsync(SopVideoDraft draft, SopVideoSample video, SopConfig template,
IProgress<string> progress, CancellationToken token)
{
token.ThrowIfCancellationRequested();
var operation = DraftVerifier.VerifyAsync(draft, video, template, progress, token);
Interlocked.Exchange(ref _agentVerificationTask, operation);
try { return await operation.ConfigureAwait(false); }
finally { Interlocked.CompareExchange(ref _agentVerificationTask, null, operation); }
}
private async Task WaitForAgentVerificationCleanupAsync()
{
var verification = Volatile.Read(ref _agentVerificationTask);
if (verification is null) return;
try { await verification; } catch { /* 已取消分析;仍等待本地解码/模型资源释放。 */ }
}
private SopConfig CreateAgentVerificationTemplate()
{
var template = Recipe.ToConfig();
var definitions = template.Sop.Steps;
template.Sop.Steps = _agentAppliedNodes.Where(Recipe.Steps.Contains)
.Select(node => definitions.First(s => s.Id == node.Id)).ToList();
return template;
}
private void DraftRowChanged(object? sender, PropertyChangedEventArgs e)
{
if (_agentVerifiedFingerprint is not null)
{
_agentVerifiedFingerprint = null;
AgentVerificationSummary = "草稿已修改,请点击“djev回测”后再应用。";
ApplyAgentDraftCommand.RaiseCanExecuteChanged();
}
}
private void PresentVerification(SopVideoDraft draft)
{
_agentRegionAdjustments.AddRange(draft.RegionAdjustments);
RaisePropertyChanged(nameof(AgentRegionAdjustmentsSummary));
_agentVerifiedFingerprint = draft.Verification?.Passed == true && !string.IsNullOrWhiteSpace(draft.Verification.Fingerprint)
? draft.Verification.Fingerprint : null;
AgentVerificationSummary = draft.Verification is { } report ? report.Summary + "\n"
+ string.Join("\n", report.Steps.Select(s => $"{(s.Completed ? "✓" : "○")} {s.Id} {s.Name}:{s.Message}"))
: "尚未进行标准视频回测。";
VerifyAgentDraftCommand.RaiseCanExecuteChanged();
ApplyAgentDraftCommand.RaiseCanExecuteChanged();
}
}

View File

@ -79,7 +79,6 @@ public partial class RecipeEditorViewModel
SaveCommand.RaiseCanExecuteChanged();
SendAgentChatCommand.RaiseCanExecuteChanged();
ClearAgentChatCommand.RaiseCanExecuteChanged();
VerifyAgentDraftCommand?.RaiseCanExecuteChanged();
}
}
public DelegateCommand GenerateStepsCommand { get; private set; } = null!;
@ -100,8 +99,6 @@ public partial class RecipeEditorViewModel
FetchAgentModelsCommand = new DelegateCommand(() => ScheduleModelDiscovery(immediate: true));
CancelAgentCommand = new DelegateCommand(() => _agentCancellation?.Cancel(), () => IsAgentBusy);
ApplyAgentDraftCommand = new DelegateCommand(ApplyAgentDraft, CanApplyAgentDraft);
VerifyAgentDraftCommand = new DelegateCommand(() => _agentTask = ReplayDraftWithDliteAsync(),
() => !IsAgentBusy && !IsCapturing && AgentDraftSteps.Count > 0);
BrowseAgentVideoCommand = new DelegateCommand(async () =>
{
var dialog = new OpenFileDialog { Title = "选择标准 SOP 视频", Filter = "视频|*.avi;*.mp4;*.mov;*.mkv;*.webm|所有文件|*.*" };
@ -219,7 +216,7 @@ public partial class RecipeEditorViewModel
if (string.IsNullOrWhiteSpace(AgentVideoPath) && SopRecording is not null) AgentVideoPath = SopRecording.StandardVideoPath;
}
private async Task AnalyzeVideoAsync(string? userMessage = null, bool verifyDraft = false)
private async Task AnalyzeVideoAsync(string? userMessage = null)
{
if (IsAgentBusy || IsCapturing) return;
if (SopRecording?.IsRecording == true) { AgentStatus = "请先停止并保存 SOP 录像,再开始分析。"; return; }
@ -236,7 +233,7 @@ public partial class RecipeEditorViewModel
var regionDefinitions = Recipe.ToConfig().Sop.Regions;
var regions = regionDefinitions.Keys.ToArray();
var recipeName = Recipe.Name; var instructions = AgentInstructions;
_agentCancellation = new CancellationTokenSource(); // 每次模型请求和每轮回测分别限时,支持整段视频多轮验证。
_agentCancellation = new CancellationTokenSource();
var token = _agentCancellation.Token;
IsAgentBusy = true;
AgentStatus = "正在读取标准 SOP 视频…";
@ -251,25 +248,15 @@ public partial class RecipeEditorViewModel
+ (string.IsNullOrWhiteSpace(prompt.Compression) ? "" : "\n" + prompt.Compression)));
});
var progress = new Progress<string>(value => { if (IsAgentBusy && ReferenceEquals(_agentCancellation, activeAnalysis)) AgentStatus = value; });
var verificationRequired = verifyDraft || userMessage is not null && _agentVerificationRequired;
var verificationTemplate = verifyDraft ? CreateAgentVerificationTemplate() : null;
Func<SopVideoDraft, SopVideoSample, CancellationToken, Task<SopDraftVerification>>? verify = verifyDraft
? async (draft, video, cancellation) =>
{
runLog?.Write(new("verification_start", 0, JsonSerializer.Serialize(draft)));
var result = await VerifyAgentDraftAsync(draft, video, verificationTemplate!, progress, cancellation);
runLog?.Write(new("verification_end", 0, JsonSerializer.Serialize(result)));
return result;
} : null;
try
{
runLog = new SopAgentRunLog(DesktopPlatform.WorkspaceRoot, connection.ApiKey);
runLog.Write(new("session_start", 0, JsonSerializer.Serialize(new
{
Recipe = recipeName, Video = path, Mode = verifyDraft ? "verify_and_revise" : userMessage is null ? "generate" : "chat",
Recipe = recipeName, Video = path, Mode = userMessage is null ? "generate" : "chat",
instructions, userMessage, Endpoint = new UriBuilder(endpoint) { UserName = "", Password = "", Query = "", Fragment = "" }.Uri.ToString(),
connection.Model, connection.ContextLength, connection.MaxTokens,
connection.Temperature, connection.TopP, connection.TimeoutSeconds, MaxFrames = maxFrames, VerifyDraft = verifyDraft
connection.Temperature, connection.TopP, connection.TimeoutSeconds, MaxFrames = maxFrames
})));
AgentChatMessages.Add(new("分析日志", "本次分析过程自动保存:" + runLog.Path));
var sample = await Task.Run(() => SopVideoSampler.ReadInfo(path, token), token);
@ -285,10 +272,7 @@ public partial class RecipeEditorViewModel
AgentChatMessages.Add(new("我", userMessage));
var result = await AgentClient.ChatAsync(new(recipeName, instructions, sample, regions, maxFrames, progress,
userMessage, _agentConversation.ToArray(), CreateAgentDraftSnapshot(), regionDefinitions,
CreateAgentImageScopes(), VerifyDraft: verify, PromptSent: promptLog, Trace: runLog.Write,
VerifyCurrentDraftFirst: verifyDraft,
CheckReference: verifyDraft ? (candidate, video, id, cancellation) => new SopDraftReferenceVerifier().CheckAsync(
SopDraftConfigBuilder.Build(verificationTemplate!, candidate), candidate, video, id, cancellation) : null,
CreateAgentImageScopes(), PromptSent: promptLog, Trace: runLog.Write,
SequenceAvailable: false), connection, token).WaitAsync(token);
token.ThrowIfCancellationRequested();
draft = result.Draft; reply = result.Reply;
@ -300,7 +284,7 @@ public partial class RecipeEditorViewModel
else
{
draft = await AgentClient.AnalyzeAsync(new(recipeName, instructions, sample, regions, maxFrames, progress,
RegionDefinitions: regionDefinitions, VerifyDraft: verify, PromptSent: promptLog, Trace: runLog.Write,
RegionDefinitions: regionDefinitions, PromptSent: promptLog, Trace: runLog.Write,
SequenceAvailable: false), connection, token).WaitAsync(token);
sample = sample with { Frames = draft.ObservedFrames };
reply = string.IsNullOrWhiteSpace(draft.Summary) ? $"已生成 {draft.Steps.Count} 步。" : draft.Summary;
@ -309,25 +293,18 @@ public partial class RecipeEditorViewModel
if (draft is not null)
{
SopVideoDraftClient.Validate(draft, sample, regions, regionDefinitions);
if (verify is not null && draft.Verification is null) draft.Verification = await verify(draft, sample, token);
token.ThrowIfCancellationRequested();
token.ThrowIfCancellationRequested();
ClearAgentDraft(clearConversation: false, forgetApplied: userMessage is null);
_agentVerificationRequired = verificationRequired;
_agentRegionAdjustments.AddRange(draft.RegionAdjustments);
RaisePropertyChanged(nameof(AgentRegionAdjustmentsSummary));
for (var i = 0; i < draft.Steps.Count; i++)
{
var step = draft.Steps[i];
var actual = draft.Verification?.Images.LastOrDefault(image => image.StepId == i + 1);
var row = new AgentDraftRow(step, sample.Frames[step.EvidenceFrame], actual);
row.PropertyChanged += DraftRowChanged;
var row = new AgentDraftRow(step, sample.Frames[step.EvidenceFrame]);
AgentDraftSteps.Add(row);
}
PresentVerification(draft);
AgentSummary = draft.Summary + (draft.Warnings.Count == 0 ? "" : "\n需核对:" + string.Join(";", draft.Warnings));
AgentStatus = draft.Verification is { Passed: false } ? "草稿回测未通过,未修改配方。可继续对话修订。"
: draft.Verification?.Passed == true ? $"已更新 {draft.Steps.Count} 步草稿,标准视频回测通过。"
: _agentVerificationRequired ? $"已更新 {draft.Steps.Count} 步草稿,请单独点击“djev回测”后更新配方。"
: $"已更新 {draft.Steps.Count} 步草稿。可先编辑或添加到配方,再按需点击“djev回测”。";
AgentStatus = $"已更新 {draft.Steps.Count} 步草稿,可编辑或添加到配方。";
}
else AgentStatus = "";
_agentSample = sample;
@ -336,8 +313,7 @@ public partial class RecipeEditorViewModel
}
catch (OperationCanceledException error)
{
await WaitForAgentVerificationCleanupAsync();
AgentStatus = token.IsCancellationRequested ? "分析已取消,当前配方未修改。" : "模型请求或本地回测超时,当前配方未修改。";
AgentStatus = token.IsCancellationRequested ? "分析已取消,当前配方未修改。" : "模型请求超时,当前配方未修改。";
AgentChatMessages.Add(new("系统", AgentStatus));
try { runLog?.Write(new("cancelled_or_timeout", 0, error.ToString())); }
catch (Exception logError) when (logError is IOException or UnauthorizedAccessException) { }
@ -363,16 +339,10 @@ public partial class RecipeEditorViewModel
var definitions = Recipe.ToConfig().Sop.Regions;
try { SopVideoDraftClient.Validate(draft, _agentSample, definitions.Keys.ToArray(), definitions); }
catch (FormatException error) { AgentStatus = "草稿未添加:" + error.Message; return; }
var resolved = SopDraftConfigBuilder.Build(CreateAgentVerificationTemplate(), draft);
if (_agentVerificationRequired && (_agentVerifiedFingerprint is null || _agentVerifiedFingerprint != SopDraftConfigBuilder.Fingerprint(resolved, _agentSample)))
{
_agentVerifiedFingerprint = null;
AgentVerificationSummary = "草稿、配方设置或区域已变化,请重新回测后应用。";
ApplyAgentDraftCommand.RaiseCanExecuteChanged(); return;
}
var resolved = SopDraftConfigBuilder.Build(CreateAgentDraftTemplate(), draft);
var currentVideo = new FileInfo(_agentSample.Path);
if (!currentVideo.Exists || _agentSample.SourceLength > 0 && (currentVideo.Length != _agentSample.SourceLength || currentVideo.LastWriteTimeUtc != _agentSample.SourceModifiedUtc))
{ AgentStatus = "标准视频已变化,请重新生成并回测。"; return; }
{ AgentStatus = "标准视频已变化,请重新生成。"; return; }
foreach (var adjusted in _agentRegionAdjustments)
{
var source = resolved.Sop.Regions[adjusted.Key];
@ -398,8 +368,7 @@ public partial class RecipeEditorViewModel
RaisePropertyChanged(nameof(AgentCanEditDraft));
ApplyAgentDraftCommand.RaiseCanExecuteChanged();
RefreshWarnings();
AgentStatus = $"已写入 {AgentDraftSteps.Count} 步,待保存。"
+ (_agentVerificationRequired && Recipe.Steps.Count > applied.Count ? "已验证草稿步骤;完整配方请到“SOP流程视频”测试。" : "");
AgentStatus = $"已写入 {AgentDraftSteps.Count} 步,待保存。";
}
private SopVideoDraft? CreateAgentDraftSnapshot()
@ -428,7 +397,7 @@ public partial class RecipeEditorViewModel
private IReadOnlyList<SopAgentImageScope> CreateAgentImageScopes()
{
if (CreateAgentDraftSnapshot() is not { } draft) return [];
var resolved = SopDraftConfigBuilder.Build(CreateAgentVerificationTemplate(), draft);
var resolved = SopDraftConfigBuilder.Build(CreateAgentDraftTemplate(), draft);
return resolved.Sop.Steps.Select((step, index) =>
{
var ai = step.AiConfirmation!;
@ -438,15 +407,27 @@ public partial class RecipeEditorViewModel
}).ToArray();
}
private readonly List<SopDraftRegion> _agentRegionAdjustments = [];
public string AgentRegionAdjustmentsSummary => string.Join("\n", _agentRegionAdjustments.Select(r =>
$"区域建议草稿:{r.Key} [{r.X1},{r.Y1}]–[{r.X2},{r.Y2}] · {r.Note}"));
private bool CanApplyAgentDraft() => !IsAgentBusy && !_draftApplied && AgentDraftSteps.Count > 0;
private SopConfig CreateAgentDraftTemplate()
{
var template = Recipe.ToConfig();
var definitions = template.Sop.Steps;
template.Sop.Steps = _agentAppliedNodes.Where(Recipe.Steps.Contains)
.Select(node => definitions.First(s => s.Id == node.Id)).ToList();
return template;
}
private void ClearAgentConversation() { _agentPromptSession = null; _agentConversation.Clear(); AgentChatMessages.Clear(); }
private void ClearAgentDraft(bool clearConversation = true, bool forgetApplied = true)
{
foreach (var row in AgentDraftSteps) { row.PropertyChanged -= DraftRowChanged; row.Dispose(); }
_agentVerifiedFingerprint = null;
_agentVerificationRequired = false;
foreach (var row in AgentDraftSteps) row.Dispose();
_agentRegionAdjustments.Clear();
AgentVerificationSummary = "";
RaisePropertyChanged(nameof(AgentRegionAdjustmentsSummary));
AgentDraftSteps.Clear(); _agentSample = null; _draftApplied = false; AgentSummary = "";
if (clearConversation) ClearAgentConversation();
@ -454,7 +435,6 @@ public partial class RecipeEditorViewModel
RaisePropertyChanged(nameof(AgentApplyLabel));
RaisePropertyChanged(nameof(AgentCanEditDraft));
ApplyAgentDraftCommand?.RaiseCanExecuteChanged();
VerifyAgentDraftCommand?.RaiseCanExecuteChanged();
}
}
@ -482,10 +462,10 @@ public sealed class AgentDraftRow : BindableBase, IDisposable
+ $";判定:{Step.Inspection?.EvidenceMode ?? "沿用/单帧"};检查窗口:{Step.Inspection?.CheckWindowMs?.ToString() ?? "默认"}ms"
+ (string.IsNullOrWhiteSpace(Region) ? " 触发区域未设置。" : "");
public BitmapSource EvidenceImage { get; }
public AgentDraftRow(SopDraftStep step, SopVideoFrame frame, SopDraftVerificationImage? actual = null)
public AgentDraftRow(SopDraftStep step, SopVideoFrame frame)
{
Step = step; EvidenceLabel = actual is null ? $"参考画面 {frame.Seconds:F1}s" : $"回测送检 {actual.Seconds:F1}s · {actual.Confidence:P1}";
using var image = Cv2.ImDecode(actual?.Jpeg ?? frame.Jpeg, ImreadModes.Color);
Step = step; EvidenceLabel = $"参考画面 {frame.Seconds:F1}s";
using var image = Cv2.ImDecode(frame.Jpeg, ImreadModes.Color);
EvidenceImage = BitmapSource.Create(image.Width, image.Height, 96, 96, PixelFormats.Bgr24, null,
image.Data, checked((int)(image.Step() * image.Height)), checked((int)image.Step()));
}

View File

@ -30,7 +30,7 @@ internal static class AgentBenchmarkChecks
Number("contextLength", 131702), Number("maxTokens", 8192), Decimal("temperature", .2), Decimal("topP", .9), Number("timeoutSeconds", 300),
disableThinking ? false : root.TryGetProperty("enableThinking", out var agentThinking) && agentThinking.ValueKind != JsonValueKind.Null ? agentThinking.GetBoolean() : null);
var template = SopConfigLoader.Load(configPath);
// 与界面未应用草稿的 CreateAgentVerificationTemplate 一致,不能继承不相关旧步骤的送检区。
// 与界面未应用草稿的 CreateAgentDraftTemplate 一致,不能继承不相关旧步骤的送检区。
template.Sop.Steps = [];
var original = File.ReadAllBytes(configPath);
var video = SopVideoSampler.ReadInfo(videoPath, default);

View File

@ -10,26 +10,26 @@ using SopHelper.Training;
using SopHelper.VVMs.RecipeEditor;
using Window = Avalonia.Controls.Window;
internal static class AgentDraftVerificationChecks
internal static class AgentDraftGenerationChecks
{
public static void Run(string root)
{
var store = new RecipeWorkspace(root);
Directory.CreateDirectory(root);
var video = Path.Combine(root, "agent-verification.avi");
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 verification test video opens");
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 = [];
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 verifier = new ProbeVerifier(); var client = new ProbeClient(); model.DraftVerifier = verifier; model.AgentClient = client;
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);
@ -42,19 +42,23 @@ internal static class AgentDraftVerificationChecks
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");
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("artifacts/agent-split-preview.png");Directory.CreateDirectory(Path.GetDirectoryName(preview)!);
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(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(!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)),
"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");
"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();
@ -64,12 +68,7 @@ internal static class AgentDraftVerificationChecks
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");
var agentCalls = client.Calls;
model.VerifyAgentDraftCommand.Execute();Until(()=>!model.IsAgentBusy);
Check(verifier.Calls==1 && client.Calls==agentCalls && !client.SawVerification && !client.SawDirectVerification && model.ApplyAgentDraftCommand.CanExecute(),"Explicit dlite verification must not call Agent or revise criteria");
Check(Directory.GetFiles(logsFolder,"analysis-*.jsonl").Select(File.ReadAllText).Any(text=>text.Contains("djev_replay")&&text.Contains("verification_end")),
"Verification and revision use their own complete session log");
Check(!client.SawVerification&&client.SawCurrentDraft&&!client.SawDirectVerification&&model.ApplyAgentDraftCommand.CanExecute(),"Ordinary chat edits the current draft without running verification");
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);
@ -87,44 +86,34 @@ internal static class AgentDraftVerificationChecks
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");
Check(model.ApplyAgentDraftCommand.CanExecute(), "Manual draft edits remain applicable without replay");
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
&& model.Recipe.Steps[1].AiCheckWindowMs == 14000
&& model.Recipe.Steps[1].AiObservationRequestMaxFrames == 6,
"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;
"Explicit application uses the generated trigger, crop and debounce while preserving existing steps and AI threshold");
Check(File.ReadAllBytes(path).SequenceEqual(before), "Applying generated draft still requires explicit recipe save");
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;
Check(!client.SawVerification&&model.ApplyAgentDraftCommand.CanExecute(),"Regenerated draft is directly applicable");
client.Hold = true;
var completedLogs = Directory.GetFiles(logsFolder, "analysis-*.jsonl");
model.VerifyAgentDraftCommand.Execute(); Until(() => verifier.Entered);
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("verification_start") && !runningText.Contains("session_end"),
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 verification leaves the recipe untouched");
Check(model.Recipe.Steps.Count == 2 && File.ReadAllBytes(path).SequenceEqual(before), "Cancelling generation leaves the recipe untouched");
model.ConfirmCloseAsync = () => Task.FromResult(RecipeCloseChoice.Discard);
Pump(model.ShutdownAsync()); window.Close(); Until(() => !window.IsVisible); model.OnDialogClosed();
}
@ -134,7 +123,7 @@ internal static class AgentDraftVerificationChecks
{
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();
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); }
@ -142,12 +131,15 @@ internal static class AgentDraftVerificationChecks
{
public Exception? Failure;
public int Calls;
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, "实际提示词"));
@ -159,23 +151,10 @@ internal static class AgentDraftVerificationChecks
Inspection = new() { EvidenceMode = "single_frame", CheckWindowMs = 14000, ObservationRequestMaxFrames = 6 } }]
};
draft.ObservedFrames = frames;
if (request.VerifyDraft is { } verify) draft.Verification = await verify(draft, request.Video with { Frames = frames }, token);
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); }
}
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 (Calls == 1) Check(template.Sop.Steps.Count == 0, "Unapplied drafts do not inherit unrelated recipe step image settings");
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));
}
}
}

View File

@ -32,13 +32,14 @@ internal static class Program
Application.Current!.Styles.Add(new FluentTheme());
Application.Current.Styles.Add(new StyleInclude(new Uri("avares://SopHelper.Avalonia/")) { Source = new Uri("avares://SopHelper.Avalonia/Themes/Styles.axaml") });
if (args.Contains("--live")) { LiveVideoFlowChecks.Run(args); return; }
if (args.Contains("--agent-generation-only")) { AgentDraftGenerationChecks.Run(root); return; }
CheckAiFlow();
CheckSequenceEditor();
StepTestDecisionChecks.Run();
RecipeCloseChecks.Run(root);
CheckRuntimeSettings(root);
StepTransferChecks.Run(root);
AgentDraftVerificationChecks.Run(root);
AgentDraftGenerationChecks.Run(root);
StandardVideoImportChecks.Run(root);
CheckVideoPage(root);
}