diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs
index 06dd21a..3ba7384 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs
@@ -45,7 +45,8 @@ public partial class RecipeEditorViewModel
// 开始时固定目标;只检查目标步骤的说明和关键帧,后续切换选中项不会改变回写对象。
var selectedStep = recipe.SelectedStep;
- var targetSteps = OptimizeSelectedStepOnly
+ var selectedOnly = OptimizeSelectedStepOnly;
+ var targetSteps = selectedOnly
? recipeSteps.Where(node => ReferenceEquals(node, selectedStep))
: recipeSteps.AsEnumerable();
var steps = targetSteps.Select(node => new
@@ -54,7 +55,7 @@ public partial class RecipeEditorViewModel
}).ToArray();
if (steps.Length == 0) { AgentStatus = "请选择要优化的步骤。"; return; }
var missing = steps.FirstOrDefault(step => string.IsNullOrWhiteSpace(step.Description) || string.IsNullOrWhiteSpace(step.KeyFrameBase64));
- if (missing is not null) { AgentStatus = $"请先为步骤 {missing.Id}「{missing.Name}」填写完成说明并获取关键帧。"; return; }
+ if (selectedOnly && missing is not null) { AgentStatus = $"请先为步骤 {missing.Id}「{missing.Name}」填写完成说明并获取关键帧。"; return; }
var recipeName = recipe.Name;
var config = recipe.ToConfig();
@@ -77,61 +78,85 @@ public partial class RecipeEditorViewModel
var results = new List<(StepNode Node, string Description)>();
var unchanged = 0;
var retried = 0;
- var currentLabel = "";
+ var skipped = 0;
try
{
var timeout = (SopHelper.Models.RuntimeSettingsStore.Current.Read() ?? new()).DjevTimeoutMs;
- foreach (var step in steps)
+ for (var stepIndex = 0; stepIndex < steps.Length; stepIndex++)
{
+ token.ThrowIfCancellationRequested();
+ var step = steps[stepIndex];
var label = $"步骤 {step.Id}「{step.Name}」";
- currentLabel = label;
- AgentStatus = $"{label}:正在查看关键帧并生成9条同义完成说明…";
- var definition = config.Sop.Steps.First(s => s.Id == step.Id);
- var prepared = await Task.Run(() => PrepareStepDecisionImage(definition, config.Sop.Regions, videoPaths, token), token);
- var jpeg = prepared.Jpeg;
- AppendStepDecisionLog($"{label} · 优化实际送检:{prepared.Scope}");
- var report = new StepOptimizationReport(label, jpeg, step.KeyFrameSeconds, prepared.Scope);
- OptimizationReports.Add(report);
- string? best = null;
- VisionDecisionResult? bestResult = null;
- // 每轮使用相同原说明、送检图和达标阈值;首轮没有达标候选时重新生成一次。
- for (var round = 1; round <= 2 && best is null; round++)
+ StepOptimizationReport? report = null;
+ try
{
- token.ThrowIfCancellationRequested();
- if (round == 2) retried++;
- AgentStatus = $"{label}:第 {round} 轮生成9条同义完成说明…";
- var rewrites = await DescriptionClient.RewriteAsync(step.Name, step.Description, jpeg, connection, token).WaitAsync(token);
- // 对注入的客户端同样检查,保证每轮恰好10个不同候选。
- var candidates = new[] { step.Description }.Concat(rewrites).ToArray();
- if (candidates.Length != 10 || candidates.Any(string.IsNullOrWhiteSpace)
- || candidates.Distinct(StringComparer.Ordinal).Count() != 10)
- throw new FormatException("Agent未返回9条有效且不同的同义完成说明");
- for (var i = 0; i < candidates.Length; i++)
+ if (string.IsNullOrWhiteSpace(step.Description) || string.IsNullOrWhiteSpace(step.KeyFrameBase64))
+ throw new ArgumentException("请填写完成说明并获取关键帧。");
+ AgentStatus = $"{label}:正在查看关键帧并生成9条同义完成说明…";
+ var definition = config.Sop.Steps.First(s => s.Id == step.Id);
+ var prepared = await Task.Run(() => PrepareStepDecisionImage(definition, config.Sop.Regions, videoPaths, token), token);
+ var jpeg = prepared.Jpeg;
+ AppendStepDecisionLog($"{label} · 优化实际送检:{prepared.Scope}");
+ report = new StepOptimizationReport(label, jpeg, step.KeyFrameSeconds, prepared.Scope);
+ OptimizationReports.Add(report);
+ string? best = null;
+ VisionDecisionResult? bestResult = null;
+ // 每轮使用相同原说明、送检图和达标阈值;首轮没有达标候选时重新生成一次。
+ for (var round = 1; round <= 2 && best is null; round++)
{
token.ThrowIfCancellationRequested();
- var testLabel = $"{label} · 第 {round} 轮优化 {i + 1}/10";
- AgentStatus = $"{testLabel}(当前第 {results.Count + 1}/{steps.Length} 步)…";
- var description = candidates[i];
- var request = new VisionDecisionRequest(recipeName, step.Id, step.Name, description, description, 0, DateTime.Now, jpeg,
- SourceSeconds: step.KeyFrameSeconds, TimeoutMs: timeout);
- var result = await RunStepDecisionAsync(testLabel, request, token);
- token.ThrowIfCancellationRequested();
- AppendStepDecisionLog($"{testLabel}:{result.EffectiveStatus};置信度 {result.Confidence:P1};{result.Reason}");
- // 与单步测试判定使用同一放行条件;分数相同时保留原文或先测试的候选。
- if (result.EffectiveStatus == VisionDecisionStatus.Completed && result.Completed
- && double.IsFinite(result.Confidence) && result.Confidence >= step.AiMinConfidence
- && result.Confidence is >= 0 and <= 1
- && (bestResult is null || result.Confidence > bestResult.Confidence))
+ if (round == 2) retried++;
+ AgentStatus = $"{label}:第 {round} 轮生成9条同义完成说明…";
+ var rewrites = await DescriptionClient.RewriteAsync(step.Name, step.Description, jpeg, connection, token).WaitAsync(token);
+ // 对注入的客户端同样检查,保证每轮恰好10个不同候选。
+ var candidates = new[] { step.Description }.Concat(rewrites).ToArray();
+ if (candidates.Length != 10 || candidates.Any(string.IsNullOrWhiteSpace)
+ || candidates.Distinct(StringComparer.Ordinal).Count() != 10)
+ throw new FormatException("Agent未返回9条有效且不同的同义完成说明");
+ for (var i = 0; i < candidates.Length; i++)
{
- best = description;
- bestResult = result;
+ token.ThrowIfCancellationRequested();
+ var testLabel = $"{label} · 第 {round} 轮优化 {i + 1}/10";
+ AgentStatus = $"{testLabel}(当前第 {stepIndex + 1}/{steps.Length} 步)…";
+ var description = candidates[i];
+ var request = new VisionDecisionRequest(recipeName, step.Id, step.Name, description, description, 0, DateTime.Now, jpeg,
+ SourceSeconds: step.KeyFrameSeconds, TimeoutMs: timeout);
+ var result = await RunStepDecisionAsync(testLabel, request, token);
+ token.ThrowIfCancellationRequested();
+ AppendStepDecisionLog($"{testLabel}:{result.EffectiveStatus};置信度 {result.Confidence:P1};{result.Reason}");
+ // 与单步测试判定使用同一放行条件;分数相同时保留原文或先测试的候选。
+ if (result.EffectiveStatus == VisionDecisionStatus.Completed && result.Completed
+ && double.IsFinite(result.Confidence) && result.Confidence >= step.AiMinConfidence
+ && result.Confidence is >= 0 and <= 1
+ && (bestResult is null || result.Confidence > bestResult.Confidence))
+ {
+ best = description;
+ bestResult = result;
+ }
}
}
+ report.ShowResult(best, bestResult, step.AiMinConfidence);
+ results.Add((step.Node, best ?? step.Description));
+ if (best is null) unchanged++;
+ AgentChatMessages.Add(new("优化步骤", $"{label}\n{report.Text}"));
+ }
+ // 输入或候选无效时保留该步原说明。取消和服务故障由外层处理,避免应用中断批次的结果。
+ catch (Exception error) when (error is ArgumentException or FormatException or System.Text.Json.JsonException)
+ {
+ token.ThrowIfCancellationRequested();
+ var reason = $"{label} · {error.Message}";
+ report?.ShowSkipped(error.Message);
+ if (selectedOnly)
+ {
+ AgentStatus = $"步骤优化未应用:{reason}";
+ AgentChatMessages.Add(new("系统", AgentStatus));
+ return;
+ }
+
+ skipped++;
+ AppendStepDecisionLog($"已跳过:{reason}");
+ AgentChatMessages.Add(new("系统", $"已跳过:{reason}"));
}
- report.ShowResult(best, bestResult, step.AiMinConfidence);
- results.Add((step.Node, best ?? step.Description));
- if (best is null) unchanged++;
- AgentChatMessages.Add(new("优化步骤", $"{label}\n{report.Text}"));
}
token.ThrowIfCancellationRequested();
// 单步优化也保留整份配方的并发检查,避免用旧送检配置或已被替换的节点回写。
@@ -141,21 +166,17 @@ public partial class RecipeEditorViewModel
|| steps.Any(s => s.Node.Description != s.Description || s.Node.Name != s.Name || s.Node.Id != s.Id
|| s.Node.KeyFrameBase64 != s.KeyFrameBase64 || s.Node.KeyFrameSeconds != s.KeyFrameSeconds || s.Node.AiMinConfidence != s.AiMinConfidence))
{ AgentStatus = "优化期间配方、送检规则或关键帧已变化,结果未应用,请重新优化。"; return; }
+ if (results.Count == 0)
+ {
+ AgentStatus = $"已跳过 {skipped} 步,配方未修改。请查看逐步提示。";
+ return;
+ }
+
foreach (var result in results) result.Node.Description = result.Description;
RefreshWarnings();
- AgentStatus = $"已优化 {steps.Length} 步,{retried} 步重试一次;{unchanged} 步未达标,保留原说明。请点击“保存”写入配方文件。";
+ AgentStatus = $"已优化 {results.Count} 步,跳过 {skipped} 步,{retried} 步重试一次;{unchanged} 步未达标,保留原说明。请点击“保存”写入配方文件。";
}
catch (OperationCanceledException) { AgentStatus = "步骤优化已取消或请求超时,当前配方未修改。"; }
- catch (ArgumentException error)
- {
- AgentStatus = $"步骤优化未应用:{currentLabel} · {error.Message}";
- AgentChatMessages.Add(new("系统", AgentStatus));
- }
- catch (FormatException error)
- {
- AgentStatus = $"步骤优化未应用:{currentLabel} · {error.Message}。请核对原说明与关键帧。";
- AgentChatMessages.Add(new("系统", AgentStatus));
- }
catch (Exception error)
{
AgentStatus = "步骤优化失败,当前配方未修改。请检查Agent设置、关键帧和djev服务。";
@@ -196,5 +217,8 @@ public sealed class StepOptimizationReport : BindableBase, IDisposable
: $"选中说明:{description}\n置信度 {result.Confidence:P1}(阈值 {threshold:P1})\n{result.Reason}";
}
+ /// 已生成送检图但未完成候选测试时,保留图片并显示跳过原因。
+ public void ShowSkipped(string reason) => Text = $"保留原说明。原因:{reason}";
+
public void Dispose() => EvidenceImage.Dispose();
}
diff --git a/tests/VideoFlowTest.Smoke/OptimizeStepsChecks.cs b/tests/VideoFlowTest.Smoke/OptimizeStepsChecks.cs
index fccc970..e2d7f85 100644
--- a/tests/VideoFlowTest.Smoke/OptimizeStepsChecks.cs
+++ b/tests/VideoFlowTest.Smoke/OptimizeStepsChecks.cs
@@ -74,6 +74,20 @@ internal static class OptimizeStepsChecks
Check(model.OptimizationReports.Count == 2 && model.OptimizationReports.All(r => r.Text.Contains("两轮均未达标")
&& !r.Text.Contains("选中说明")), "未达标时没有入选说明");
+ // 首步候选无效时,保留原说明并记录原因,后续步骤仍完成测试和回写。
+ descriptions.InvalidDescription = retained;
+ decisions = new Decisions(); model.StepTestDecisionClient = decisions;
+ var secondBeforeSkip = second.Description;
+ model.OptimizeStepsCommand.Execute(); Until(() => !model.IsAgentBusy);
+ Check(first.Description == retained && second.Description == secondBeforeSkip + "改写4"
+ && decisions.Requests.Count == 10 && decisions.Requests.All(r => r.StepId == second.Id),
+ "首步候选无效时跳过并继续优化后续步骤");
+ Check(model.AgentStatus.Contains("已优化 1 步") && model.AgentStatus.Contains("跳过 1 步")
+ && model.OptimizationReports[0].Text.Contains("候选无效")
+ && model.AgentChatMessages.Any(m => m.Text.Contains("已跳过") && m.Text.Contains("候选无效")),
+ "汇总和逐步提示记录跳过原因");
+ descriptions.InvalidDescription = null;
+
// 从界面选择单步。其他步骤缺关键帧时仍可运行,开始后切换选中项也不改变本次目标。
scopeBox.SelectedIndex = 1;
stepBox.SelectedItem = null;
@@ -111,6 +125,9 @@ internal static class OptimizeStepsChecks
first.KeyFrameBase64 = firstFrame;
scopeBox.SelectedIndex = 0;
+ // 单步送检配置无效时提示未应用,且不会发送错误图像。
+ scopeBox.SelectedIndex = 1;
+ stepBox.SelectedItem = first;
var callsBefore = descriptions.Calls;
foreach (var mode in new[] { VisionImageMode.Hand, VisionImageMode.FixedRegion })
{
@@ -120,6 +137,7 @@ internal static class OptimizeStepsChecks
"无跟踪上下文或区域缺失时不向Agent发送错误图片,且配方不修改");
}
first.AiImageMode = VisionImageMode.FixedRegion; first.AiImageRegion = "inspect";
+ scopeBox.SelectedIndex = 0;
descriptions.Pending = new(TaskCreationOptions.RunContinuationsAsynchronously);
model.OptimizeStepsCommand.Execute(); Until(() => model.IsAgentBusy);
@@ -210,11 +228,13 @@ internal static class OptimizeStepsChecks
private sealed class Descriptions : ISopDescriptionClient
{
public int Calls;
+ public string? InvalidDescription;
public List Images { get; } = [];
public TaskCompletionSource>? Pending;
public Task> RewriteAsync(string name, string description, byte[] jpeg, SopAgentConnection connection, CancellationToken token)
{
Calls++; Images.Add(jpeg);
+ if (description == InvalidDescription) throw new FormatException("候选无效");
return Pending?.Task.WaitAsync(token) ?? Task.FromResult>(Enumerable.Range(1, 9).Select(i => description + "改写" + i).ToArray());
}
}