diff --git a/src/SopHelper.Avalonia/Training/SopDraftVideoVerifier.cs b/src/SopHelper.Avalonia/Training/SopDraftVideoVerifier.cs index 73c45c1..cf8fd77 100644 --- a/src/SopHelper.Avalonia/Training/SopDraftVideoVerifier.cs +++ b/src/SopHelper.Avalonia/Training/SopDraftVideoVerifier.cs @@ -29,6 +29,7 @@ public sealed class SopDraftVideoVerifier : ISopDraftVideoVerifier using var budget = CancellationTokenSource.CreateLinkedTokenSource(token); budget.CancelAfter(TimeSpan.FromSeconds(video.DurationSeconds + 210)); var images = new System.Collections.Concurrent.ConcurrentDictionary(); + var budgetHints = new System.Collections.Concurrent.ConcurrentDictionary(); var playback = new RecordedVideoPlayback(); using var test = new SopVideoFlowTest(config); var diagnostics = new SopTriggerDiagnosticsCollector(config, draft, video.DurationSeconds); @@ -56,6 +57,14 @@ public sealed class SopDraftVideoVerifier : ISopDraftVideoVerifier images[request.StepId] = image with { FrameId = request.FrameId, Seconds = request.SourceSeconds ?? (fps > 0 ? request.FrameId / fps : 0), Jpeg = request.Jpeg, Confidence = decision.Confidence, Accepted = accepted, Reason = decision.Reason }; if (decision.Reason.Contains("接口请求失败") || decision.Reason.Contains("超时或已取消")) infrastructureFailure = true; + var options = config.Sop.Steps[request.StepId - 1].AiConfirmation; + if (!accepted && decision.Reason.Contains("超时或已取消") && options is { EvidenceMode: VisionEvidenceMode.Sequence, CheckWindowMs: > 0 } + && options.CheckWindowMs < options.TimeoutSeconds * 1000L) + { + var requestMs = (int)Math.Min(int.MaxValue, options.TimeoutSeconds * 1000L); + var suggested = (int)Math.Min(60000, requestMs + (long)Math.Max(options.CheckSettleMs, options.ObservationMinMs) + 500); + if (suggested > options.CheckWindowMs) budgetHints[request.StepId] = new(request.StepId, options.CheckWindowMs, requestMs, suggested); + } }; string? lastProgress = null; test.Changed += (status, _) => @@ -94,7 +103,8 @@ public sealed class SopDraftVideoVerifier : ISopDraftVideoVerifier ? "标准视频参考复核服务未返回有效判定,尚未完成验收;不应据此放宽工艺要求" : "标准视频回放期间视觉服务未返回有效判定,尚未完成验收;不应据此放宽工艺要求"; return new(test.IsCompleted && !contradictory && !infrastructureFailure, summary, test.StepResults, - images.Values.OrderBy(i => i.StepId).ToArray(), fingerprint, infrastructureFailure, diagnostics.Build(), references, test.IsCompleted); + images.Values.OrderBy(i => i.StepId).ToArray(), fingerprint, infrastructureFailure, diagnostics.Build(), references, test.IsCompleted, + images.Values.Any(i => i.Accepted == true) ? budgetHints.Values.OrderBy(h => h.StepId).ToArray() : null); } catch (OperationCanceledException) when (!token.IsCancellationRequested) { diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs index ac63178..7f94b85 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs @@ -431,7 +431,7 @@ public partial class RecipeEditorViewModel var ai = step.AiConfirmation!; return new SopAgentImageScope(index + 1, VisionImageMode.Resolve(ai), ai.ImageRegion, ai.HandPadding, ai.HandMinSize, ai.HandMemoryMs, ai.EvidenceMode, ai.CheckWindowMs, ai.MaxChecks, ai.CheckSettleMs, - ai.ObservationMaxMs, ai.ObservationMaxFrames, ai.ObservationRequestMaxFrames); + ai.ObservationMaxMs, ai.ObservationMaxFrames, ai.ObservationRequestMaxFrames, ai.TimeoutSeconds); }).ToArray(); } diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopDraftVerification.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopDraftVerification.cs index 5d8a608..17814c9 100644 --- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopDraftVerification.cs +++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopDraftVerification.cs @@ -6,6 +6,7 @@ using SopHelper.Engine.Sop; namespace SopHelper.Engine.SopAgent; public sealed record SopDraftVerificationStep(int Id, string Name, bool Completed, string Message, bool Skipped = false); +public sealed record SopDraftBudgetHint(int StepId, int CheckWindowMs, int RequestTimeoutMs, int SuggestedWindowMs); public sealed record SopDraftVerificationImage(int StepId, long FrameId, double Seconds, string Scope, double? Confidence, bool? Accepted, string Reason, [property: JsonIgnore] byte[] Jpeg, string EvidenceMode = VisionEvidenceMode.SingleFrame, @@ -21,7 +22,8 @@ public sealed record SopDraftReferenceCheck(int StepId, int EvidenceFrame, doubl } public sealed record SopDraftVerification(bool Passed, string Summary, IReadOnlyList Steps, [property: JsonIgnore] IReadOnlyList Images, string Fingerprint = "", bool InfrastructureFailure = false, - SopTriggerDiagnostics? TriggerDiagnostics = null, IReadOnlyList? ReferenceChecks = null, bool? RuntimePassed = null); + SopTriggerDiagnostics? TriggerDiagnostics = null, IReadOnlyList? ReferenceChecks = null, bool? RuntimePassed = null, + IReadOnlyList? BudgetHints = null); /// 回测和应用草稿共用同一映射,模型只能调整可观察规则,不能调低 AI 放行门槛。 public static class SopDraftConfigBuilder @@ -40,7 +42,7 @@ public static class SopDraftConfigBuilder { var previous = config.Sop.Steps.ElementAtOrDefault(index); SopVideoDraftClient.ValidateInspection(step.Inspection); - var ai = previous?.AiConfirmation ?? new() { CheckWindowMs = step.Inspection?.EvidenceMode == VisionEvidenceMode.Sequence ? 20000 : 10000 }; + var ai = previous?.AiConfirmation ?? new() { CheckWindowMs = step.Inspection?.EvidenceMode == VisionEvidenceMode.Sequence ? 40000 : 10000 }; step.Inspection?.Apply(ai); if (!VisionEvidenceMode.IsValid(ai) || !VisionEvidenceMode.IsCheckPolicyValid(ai)) throw new FormatException("检查策略与现有设置不兼容,请重新校验窗口及过程取证预算"); diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopStepDesignPrompt.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopStepDesignPrompt.cs index f6046a9..bda732f 100644 --- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopStepDesignPrompt.cs +++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopStepDesignPrompt.cs @@ -12,7 +12,7 @@ public static class SopStepDesignPrompt 检查策略 inspection(可省略字段沿用原值): - evidence_mode=single_frame/sequence;check_window_ms=500–60000;max_checks=1–20;check_settle_ms=100–3000且小于窗口;observation_min_ms=200–30000;observation_max_ms>=min且<=60000;observation_max_frames和observation_request_max_frames各3–32。 - - 新步骤默认单帧10秒/时序20秒窗口、最多3次、停稳350ms、过程最短2400/最长10000ms、缓存24帧/每次12帧。引擎按视觉差异压缩重复图片并保留瞬态及首尾;缓存与送检预算独立。按证据和服务耗时调整,窗口含模型等待,留重试余量;禁止修改完成阈值。 + - 新步骤默认单帧10秒/时序40秒窗口、最多3次、停稳350ms、过程最短2400/最长10000ms、缓存24帧/每次12帧。引擎按视觉差异压缩重复图片并保留瞬态及首尾;缓存与送检预算独立。按证据和服务耗时调整,窗口含模型等待,须覆盖单次服务请求预算并留重试余量,不按动作短暂程度压缩服务预算;step_image_context.TimeoutSeconds 为单次检查请求预算,须一并考虑;新步骤默认单请求30秒。禁止修改完成阈值。 - 人的动作连续,不能要求停下来等模型。手部事件仅开启检查窗口;前序等待时继续缓存后续动作。窗口内有限次复查,到期未确认跳过且整轮不计合格,跳过不等于完成。服务未答不等于视觉未通过,不能为超时改工艺。 触发及范围: diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs index 1cacb36..5382bc4 100644 --- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs +++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs @@ -43,6 +43,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient var knownReferenceFailures = new HashSet(); var protectedControls = request.VerifyDraft is null ? null : request.CurrentDraft; SopVideoDraft? queuedReferenceDraft = null; + string? queuedReplayReason = null; var maxTurns = request.CheckReference is null ? 12 : 20; var pendingCompression = ""; List? verificationBase = null; @@ -186,13 +187,13 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient // 直接将当前快照送入下方统一校验和回测路径;不伪造模型请求/响应日志。 finish = "stop"; var localDraft = queuedReferenceDraft ?? request.CurrentDraft!; - var fromReference = queuedReferenceDraft is not null; + var localReason = queuedReplayReason; queuedReferenceDraft = null; + queuedReplayReason = null; assistant = JsonSerializer.SerializeToElement(new { content = chatting ? SopAgentJson.Serialize(new { reply = "已按当前草稿执行标准视频回测。", draft = localDraft }) : SopAgentJson.Serialize(localDraft) }); - request.Progress?.Report(fromReference ? "参考对照已通过,直接回放候选草稿;不等待模型重复确认…" - : "直接回测当前草稿,失败后再请求 Agent 修订…"); + request.Progress?.Report(localReason ?? "直接回测当前草稿,失败后再请求 Agent 修订…"); } else { @@ -292,10 +293,31 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient knownReferenceFailures.UnionWith((report.ReferenceChecks ?? []).Where(c => c.Contradicts).Select(c => c.StepId)); request.Trace?.Invoke(new("verification_result", turn + 1, SopAgentJson.Serialize(new { - report.Passed, report.RuntimePassed, report.Summary, report.Steps, report.InfrastructureFailure, report.TriggerDiagnostics, report.ReferenceChecks, + report.Passed, report.RuntimePassed, report.Summary, report.Steps, report.InfrastructureFailure, report.BudgetHints, report.TriggerDiagnostics, report.ReferenceChecks, decisions = report.Images.Select(i => new { i.StepId, i.FrameId, i.Seconds, i.Scope, i.Confidence, i.Accepted, i.Reason }) }), report.Images.Select(i => new SopAgentTraceImage($"步骤{i.StepId} 视频帧{i.FrameId} {i.Seconds:F3}s {i.Scope}", i.Jpeg)) .Concat((report.ReferenceChecks ?? []).Where(c => c.Jpeg.Length > 0).Select(c => new SopAgentTraceImage($"参考步骤{c.StepId} evidence_frame={c.EvidenceFrame} {c.Scope}", c.Jpeg))).ToArray())); + if (!report.Passed && report.InfrastructureFailure && report.BudgetHints is { Count: > 0 } hints + && verificationAttempts < 3 && turn < maxTurns - 1) + { + var candidate = JsonSerializer.Deserialize(SopAgentJson.Serialize(draft))!; + var changed = false; + foreach (var hint in hints.Where(h => h.StepId > 0 && h.StepId <= candidate.Steps.Count + && h.SuggestedWindowMs > h.CheckWindowMs && h.SuggestedWindowMs <= 60000)) + { + var policy = candidate.Steps[hint.StepId - 1].Inspection ??= new(); + if (policy.CheckWindowMs >= hint.SuggestedWindowMs) continue; + policy.CheckWindowMs = hint.SuggestedWindowMs; + SopVideoDraftClient.ValidateInspection(policy); + changed = true; + } + if (changed) + { + queuedReferenceDraft = candidate; + queuedReplayReason = "检查窗口早于单次请求预算到期;仅扩大候选检查窗口并重新回放,判据、阈值和对照不变…"; + continue; + } + } if (!report.Passed && !report.InfrastructureFailure && verificationAttempts < 3 && turn < maxTurns - 1) { var failedIds = SopVerificationContext.FailedStepIds(report); @@ -465,6 +487,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient && checks.Where(c => c.Kind == "previous_state").All(c => c.Accepted == false); queuedReferenceDraft = request.AutoReplayAfterReference && referenceReady && knownReferenceFailures.Count == 0 ? candidate : null; + queuedReplayReason = queuedReferenceDraft is null ? null : "参考对照已通过,直接回放候选草稿;不等待模型重复确认…"; result = SopAgentJson.Serialize(new { reference_checks = checks, remaining_reference_checks = Math.Max(0, 6 - referenceAttempts), next_reference_step = knownReferenceFailures.Count > 0 ? knownReferenceFailures.Min() : referenceBlockingId == candidate.Steps.Count && confirmedReferences.TryGetValue(referenceBlockingId, out var finalReference) diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs index 54e48c9..6f138a8 100644 --- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs +++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs @@ -21,7 +21,7 @@ public sealed record SopVideoAnalysisRequest(string Recipe, string Instructions, public sealed record SopAgentPrompt(int Round, long EstimatedTokens, int ContextLength, string Compression, string Text); public sealed record SopAgentTrace(string Kind, int Round, string Text, IReadOnlyList? Images = null); public sealed record SopAgentTraceImage(string Name, byte[] Jpeg); -public sealed record SopAgentImageScope(int StepIndex, string Mode, string Region, int HandPadding, int HandMinSize, int HandMemoryMs, string EvidenceMode = VisionEvidenceMode.SingleFrame, int CheckWindowMs = 0, int MaxChecks = 3, int CheckSettleMs = 350, int ObservationMaxMs = 10000, int ObservationMaxFrames = 24, int ObservationRequestMaxFrames = 12); +public sealed record SopAgentImageScope(int StepIndex, string Mode, string Region, int HandPadding, int HandMinSize, int HandMemoryMs, string EvidenceMode = VisionEvidenceMode.SingleFrame, int CheckWindowMs = 0, int MaxChecks = 3, int CheckSettleMs = 350, int ObservationMaxMs = 10000, int ObservationMaxFrames = 24, int ObservationRequestMaxFrames = 12, int TimeoutSeconds = 30); public sealed record SopAgentChatTurn(string Role, string Text); public sealed record SopAgentChatResult(string Reply, SopVideoDraft? Draft, IReadOnlyList ObservedFrames); public sealed class SopVideoDraft diff --git a/tests/SopVideoAgent.Smoke/DirectDraftVerificationChecks.cs b/tests/SopVideoAgent.Smoke/DirectDraftVerificationChecks.cs index ec91fd4..24fe481 100644 --- a/tests/SopVideoAgent.Smoke/DirectDraftVerificationChecks.cs +++ b/tests/SopVideoAgent.Smoke/DirectDraftVerificationChecks.cs @@ -47,7 +47,29 @@ internal static class DirectDraftVerificationChecks "首个真正的模型请求就必须包含实际失败反馈"); } } - Console.WriteLine("PASS: 直接回测手改草稿、通过零模型请求、失败后修订、三轮上限、基础设施故障与取消保护"); + var budgetFrames = SopVideoSampler.ReadFrames(video, [0, 1], 0, default); + var budgetDraft = new SopVideoDraft { Steps = [new() { Name = "预算校准", Description = "主体完整达到目标状态", + StartSeconds = 0, EndSeconds = 4, EvidenceFrame = 1, IncompleteEvidenceFrame = 0, Region = "work", ImageMode = "full_frame", + Inspection = new() { EvidenceMode = "sequence", CheckWindowMs = 12000 } }] }; + using (var handler = new DraftHttp(budgetDraft)) + using (var http = new HttpClient(handler)) + { + var attempts = 0; + var result = await new SopVideoAgentClient(http).ChatAsync(new("预算测试", "保留判据和对照", video with { Frames = budgetFrames }, ["work"], + UserMessage: "回测并修订", CurrentDraft: budgetDraft, VerifyCurrentDraftFirst: true, SequenceAvailable: true, + VerifyDraft: (current, _, _) => + { + attempts++; + Check(current.Steps[0].Description == budgetDraft.Steps[0].Description && current.Steps[0].IncompleteEvidenceFrame == 0, + "预算校准不能改变工艺判据或未完成对照"); + if (attempts == 2) Check(current.Steps[0].Inspection!.CheckWindowMs == 32900, "候选窗口须覆盖真实单请求预算及采集余量"); + return Task.FromResult(new SopDraftVerification(attempts == 2, "实际服务预算反馈", [new(1, "预算校准", attempts == 2, "结果")], [], + InfrastructureFailure: attempts == 1, BudgetHints: attempts == 1 ? [new(1, 12000, 30000, 32900)] : null)); + }), new("https://budget.invalid/v1", "model", "", ContextLength: 32768, MaxTokens: 2048), default); + Check(attempts == 2 && result.Draft?.Verification?.Passed == true && handler.Bodies.Count == 0, + "窗口提前截断请求时仅调整预算并真实复测,无须模型改写判据或产生伪请求日志"); + } + Console.WriteLine("PASS: 直接回测手改草稿、通过零模型请求、预算不匹配无语义重写复测、三轮上限、基础设施故障与取消保护"); } private static void Check(bool value, string message) { if (!value) throw new Exception(message); } private sealed class DraftHttp(SopVideoDraft draft) : HttpMessageHandler diff --git a/tests/SopVideoAgent.Smoke/InspectionPolicyChecks.cs b/tests/SopVideoAgent.Smoke/InspectionPolicyChecks.cs index 83b5c72..87c8950 100644 --- a/tests/SopVideoAgent.Smoke/InspectionPolicyChecks.cs +++ b/tests/SopVideoAgent.Smoke/InspectionPolicyChecks.cs @@ -29,7 +29,7 @@ internal static class InspectionPolicyChecks template.Sop.Steps = []; draft.Steps[0].Inspection = new() { EvidenceMode = "sequence" }; Check(SopDraftConfigBuilder.Build(template, draft).Sop.Steps[0].AiConfirmation is - { CheckWindowMs: 20000, ObservationMaxFrames: 24, ObservationRequestMaxFrames: 12 }, "新时序步骤使用有界默认预算"); + { CheckWindowMs: 40000, ObservationMaxFrames: 24, ObservationRequestMaxFrames: 12 }, "新时序步骤使用有界默认预算"); draft.Steps[0].Inspection = null; Check(SopDraftConfigBuilder.Build(template, draft).Sop.Steps[0].AiConfirmation is { EvidenceMode: "single_frame", CheckWindowMs: 10000 }, "旧草稿兼容默认单帧策略");