534 lines
34 KiB
C#
534 lines
34 KiB
C#
// 编辑器的 Agent 部分:组织视频分析、聊天、草稿应用及显式回测,管理请求取消和界面状态。
|
||
|
||
using System.Collections.ObjectModel;
|
||
using System.IO;
|
||
using System.Net.Http;
|
||
using System.Text.Json;
|
||
using OpenCvSharp;
|
||
using Prism.Commands;
|
||
using Prism.Mvvm;
|
||
using SopHelper.Engine.Sop;
|
||
using SopHelper.Engine.SopAgent;
|
||
using SopHelper.Presentation;
|
||
using SopHelper.Presentation.Imaging;
|
||
using SopHelper.SopVideo;
|
||
|
||
namespace SopHelper.VVMs.RecipeEditor;
|
||
|
||
public partial class RecipeEditorViewModel
|
||
{
|
||
private static readonly HttpClient AgentHttp = new() { Timeout = Timeout.InfiniteTimeSpan, MaxResponseContentBufferSize = 1024 * 1024 };
|
||
public ISopVideoDraftClient AgentClient { get; set; } = new SopVideoAgentClient(AgentHttp);
|
||
private CancellationTokenSource? _agentCancellation;
|
||
private object? _agentPromptSession;
|
||
private Task? _agentTask;
|
||
private SopVideoSample? _agentSample;
|
||
private bool _isAgentBusy, _draftApplied, _isApplyingAgentDraft;
|
||
public Func<Task<AgentRecipeApplyChoice>>? ChooseAgentApplyAsync { get; set; }
|
||
public Func<string, Task>? ShowAgentApplyCompletedAsync { get; set; }
|
||
private bool _agentSettingsLoaded;
|
||
// 只允许同步读取配置期间绕过角色校验,未打开编辑器本身不授予写权限。
|
||
private bool _loadingAgentSettings;
|
||
/// <summary>工艺师可使用助手,模型连接及推理参数只允许管理员修改。</summary>
|
||
public bool CanChangeAgentModels => SopHelper.Models.UserAccess.Current.IsAdministrator && AgentIsIdle;
|
||
public bool AgentUseForSequence { get => false; set { /* 旧配置兼容:禁止Agent参与判定。 */ } }
|
||
private bool? _agentSequenceEnableThinking;
|
||
private bool? _agentEnableThinking;
|
||
public bool? AgentEnableThinking { get => _agentEnableThinking; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentEnableThinking, value)) SaveAgentSettings(); } }
|
||
public bool? AgentSequenceEnableThinking { get => _agentSequenceEnableThinking; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentSequenceEnableThinking, value)) SaveAgentSettings(); } }
|
||
private string _agentEndpoint = "", _agentModel = "", _agentApiKey = "", _agentVideoPath = "", _agentInstructions = "";
|
||
private string _agentStatus = "", _agentSummary = "";
|
||
private int _agentMaxFrames = 3;
|
||
private int _agentContextLength = 131702, _agentMaxTokens = 8192, _agentTimeoutSeconds = 300;
|
||
private double _agentTemperature = .2, _agentTopP = .9;
|
||
private CancellationTokenSource? _modelDiscoveryCancellation;
|
||
private bool _agentClosed;
|
||
private readonly List<SopAgentChatTurn> _agentConversation = [];
|
||
private readonly List<StepNode> _agentAppliedNodes = [];
|
||
private string _agentChatInput = "";
|
||
public ObservableCollection<AgentChatLine> AgentChatMessages { get; } = [];
|
||
public string AgentChatInput
|
||
{
|
||
get => _agentChatInput;
|
||
set { if (SetProperty(ref _agentChatInput, value)) SendAgentChatCommand?.RaiseCanExecuteChanged(); }
|
||
}
|
||
public string AgentApplyLabel => _agentAppliedNodes.Count == 0 ? "添加到配方" : "更新配方";
|
||
public ObservableCollection<string> AgentModels { get; } = [];
|
||
public int AgentContextLength { get => _agentContextLength; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentContextLength, value)) SaveAgentSettings(); } }
|
||
public int AgentMaxTokens { get => _agentMaxTokens; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentMaxTokens, value)) SaveAgentSettings(); } }
|
||
public int AgentTimeoutSeconds { get => _agentTimeoutSeconds; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentTimeoutSeconds, value)) SaveAgentSettings(); } }
|
||
public double AgentTemperature { get => _agentTemperature; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentTemperature, value)) SaveAgentSettings(); } }
|
||
public double AgentTopP { get => _agentTopP; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentTopP, value)) SaveAgentSettings(); } }
|
||
public ObservableCollection<AgentDraftRow> AgentDraftSteps { get; } = [];
|
||
public string AgentEndpoint { get => _agentEndpoint; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentEndpoint, value)) { SaveAgentSettings(); ScheduleModelDiscovery(); } } }
|
||
public string AgentModel { get => _agentModel; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentModel, value)) SaveAgentSettings(); } }
|
||
public string AgentApiKey { get => _agentApiKey; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentApiKey, value)) { SaveAgentSettings(); ScheduleModelDiscovery(); } } }
|
||
public string AgentInstructions { get => _agentInstructions; set => SetProperty(ref _agentInstructions, value); }
|
||
public int AgentMaxFrames { get => _agentMaxFrames; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentMaxFrames, value)) SaveAgentSettings(); } }
|
||
public string AgentVideoPath
|
||
{
|
||
get => _agentVideoPath;
|
||
set { if (SetProperty(ref _agentVideoPath, value) && !IsAgentBusy) ClearAgentDraft(); }
|
||
}
|
||
public string AgentStatus { get => _agentStatus; private set => SetProperty(ref _agentStatus, value); }
|
||
public string AgentSummary { get => _agentSummary; private set => SetProperty(ref _agentSummary, value); }
|
||
public bool AgentIsIdle => !IsAgentBusy;
|
||
public bool AgentCanEditDraft => !IsAgentBusy && !_draftApplied;
|
||
public bool IsAgentBusy
|
||
{
|
||
get => _isAgentBusy;
|
||
private set
|
||
{
|
||
if (!SetProperty(ref _isAgentBusy, value)) return;
|
||
RaisePropertyChanged(nameof(AgentIsIdle));
|
||
RaisePropertyChanged(nameof(CanChangeAgentModels));
|
||
RaisePropertyChanged(nameof(AgentCanEditDraft));
|
||
OptimizeStepsCommand.RaiseCanExecuteChanged();
|
||
GenerateStepsCommand.RaiseCanExecuteChanged(); CancelAgentCommand.RaiseCanExecuteChanged();
|
||
ApplyAgentDraftCommand.RaiseCanExecuteChanged(); BrowseAgentVideoCommand.RaiseCanExecuteChanged();
|
||
SaveCommand.RaiseCanExecuteChanged();
|
||
SendAgentChatCommand.RaiseCanExecuteChanged();
|
||
ClearAgentChatCommand.RaiseCanExecuteChanged();
|
||
}
|
||
}
|
||
public DelegateCommand GenerateStepsCommand { get; private set; } = null!;
|
||
public DelegateCommand CancelAgentCommand { get; private set; } = null!;
|
||
public DelegateCommand ApplyAgentDraftCommand { get; private set; } = null!;
|
||
public DelegateCommand BrowseAgentVideoCommand { get; private set; } = null!;
|
||
public DelegateCommand FetchAgentModelsCommand { get; private set; } = null!;
|
||
public DelegateCommand SendAgentChatCommand { get; private set; } = null!;
|
||
public DelegateCommand ClearAgentChatCommand { get; private set; } = null!;
|
||
private string AgentSettingsPath => Path.Combine(DesktopPlatform.WorkspaceRoot, "workspace", "sop-agent.json");
|
||
|
||
private void InitializeAgentCommands()
|
||
{
|
||
OptimizeStepsCommand = new DelegateCommand(() => _agentTask = OptimizeStepsAsync(), CanStartAgentStepTask);
|
||
GenerateStepsCommand = new DelegateCommand(() => _agentTask = AnalyzeVideoAsync(), CanStartAgentStepTask);
|
||
SendAgentChatCommand = new DelegateCommand(() => _agentTask = AnalyzeVideoAsync(AgentChatInput.Trim()),
|
||
() => !IsAgentBusy && !IsCapturing && !string.IsNullOrWhiteSpace(AgentChatInput));
|
||
ClearAgentChatCommand = new DelegateCommand(ClearAgentConversation, () => !IsAgentBusy);
|
||
FetchAgentModelsCommand = new DelegateCommand(() => ScheduleModelDiscovery(immediate: true));
|
||
CancelAgentCommand = new DelegateCommand(() => _agentCancellation?.Cancel(), () => IsAgentBusy);
|
||
ApplyAgentDraftCommand = new DelegateCommand(async () => await ApplyAgentDraftAsync(), CanApplyAgentDraft);
|
||
BrowseAgentVideoCommand = new DelegateCommand(async () =>
|
||
{
|
||
var dialog = new OpenFileDialog { Title = "选择标准 SOP 视频", Filter = "视频|*.avi;*.mp4;*.mov;*.mkv;*.webm|所有文件|*.*" };
|
||
if (await dialog.ShowDialogAsync() == true) AgentVideoPath = dialog.FileName;
|
||
}, () => !IsAgentBusy);
|
||
}
|
||
|
||
private void LoadAgentSettings()
|
||
{
|
||
_agentSettingsLoaded = false;
|
||
_loadingAgentSettings = true;
|
||
try
|
||
{
|
||
if (File.Exists(AgentSettingsPath))
|
||
{
|
||
using var document = JsonDocument.Parse(File.ReadAllText(AgentSettingsPath));
|
||
AgentEndpoint = document.RootElement.GetProperty("endpoint").GetString() ?? "";
|
||
AgentModel = document.RootElement.GetProperty("model").GetString() ?? "";
|
||
AgentApiKey = document.RootElement.TryGetProperty("apiKey", out var key) ? key.GetString() ?? "" : "";
|
||
var root = document.RootElement;
|
||
if (root.TryGetProperty("useForSequence", out var sequence)) AgentUseForSequence = sequence.GetBoolean();
|
||
if (root.TryGetProperty("sequenceEnableThinking", out var thinking)) AgentSequenceEnableThinking = thinking.ValueKind == JsonValueKind.Null ? null : thinking.GetBoolean();
|
||
if (root.TryGetProperty("enableThinking", out var agentThinking)) AgentEnableThinking = agentThinking.ValueKind == JsonValueKind.Null ? null : agentThinking.GetBoolean();
|
||
if (root.TryGetProperty("maxFrames", out var frames)) AgentMaxFrames = frames.GetInt32();
|
||
if (root.TryGetProperty("contextLength", out var context)) AgentContextLength = context.GetInt32();
|
||
if (root.TryGetProperty("maxTokens", out var output)) AgentMaxTokens = output.GetInt32();
|
||
if (root.TryGetProperty("temperature", out var temperature)) AgentTemperature = temperature.GetDouble();
|
||
if (root.TryGetProperty("topP", out var topP)) AgentTopP = topP.GetDouble();
|
||
if (root.TryGetProperty("timeoutSeconds", out var timeout)) AgentTimeoutSeconds = timeout.GetInt32();
|
||
}
|
||
}
|
||
catch (Exception) { AgentStatus = "模型连接设置无法读取,请重新填写地址和模型名。"; }
|
||
AgentEndpoint = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_ENDPOINT") ?? AgentEndpoint;
|
||
AgentModel = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_MODEL") ?? AgentModel;
|
||
AgentApiKey = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_API_KEY") ?? AgentApiKey;
|
||
_loadingAgentSettings = false;
|
||
_agentSettingsLoaded = true;
|
||
UpdateAgentDefaultVideo();
|
||
ScheduleModelDiscovery();
|
||
}
|
||
|
||
private void SaveAgentSettings()
|
||
{
|
||
if (!_agentSettingsLoaded || !SopHelper.Models.UserAccess.Current.IsAdministrator) return;
|
||
var temporary = AgentSettingsPath + "." + Guid.NewGuid().ToString("N") + ".tmp";
|
||
try
|
||
{
|
||
Directory.CreateDirectory(Path.GetDirectoryName(AgentSettingsPath)!);
|
||
var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write };
|
||
if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
|
||
using (var stream = new FileStream(temporary, options))
|
||
JsonSerializer.Serialize(stream, new { endpoint = AgentEndpoint, model = AgentModel, apiKey = AgentApiKey,
|
||
useForSequence = AgentUseForSequence, sequenceEnableThinking = AgentSequenceEnableThinking, enableThinking = AgentEnableThinking,
|
||
maxFrames = AgentMaxFrames, contextLength = AgentContextLength, maxTokens = AgentMaxTokens,
|
||
temperature = AgentTemperature, topP = AgentTopP, timeoutSeconds = AgentTimeoutSeconds });
|
||
File.Move(temporary, AgentSettingsPath, overwrite: true);
|
||
}
|
||
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
|
||
{ AgentStatus = "模型设置保存失败。"; }
|
||
finally
|
||
{
|
||
try { File.Delete(temporary); }
|
||
catch (Exception error) when (error is IOException or UnauthorizedAccessException) { }
|
||
}
|
||
}
|
||
|
||
/// <summary>取消过时的模型发现请求,并按立即执行或延迟方式安排新请求。</summary>
|
||
private void ScheduleModelDiscovery(bool immediate = false)
|
||
{
|
||
if (!_agentSettingsLoaded || _agentClosed) return;
|
||
_modelDiscoveryCancellation?.Cancel();
|
||
_modelDiscoveryCancellation = null;
|
||
AgentModels.Clear();
|
||
if (!Uri.TryCreate(AgentEndpoint.Trim(), UriKind.Absolute, out var endpoint) || endpoint.Scheme is not ("http" or "https")) return;
|
||
var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(15));
|
||
_modelDiscoveryCancellation = cancellation;
|
||
_ = DiscoverModelsAsync(AgentEndpoint.Trim(), AgentApiKey.Trim(), cancellation, immediate);
|
||
}
|
||
|
||
/// <summary>读取配置端点的模型列表;取消或配置变化后不应用旧查询结果。</summary>
|
||
private async Task DiscoverModelsAsync(string endpoint, string key, CancellationTokenSource cancellation, bool immediate)
|
||
{
|
||
try
|
||
{
|
||
if (!immediate) await Task.Delay(600, cancellation.Token);
|
||
var models = await new SopVideoDraftClient(AgentHttp).GetModelsAsync(endpoint, key, cancellation.Token);
|
||
cancellation.Token.ThrowIfCancellationRequested();
|
||
foreach (var model in models) AgentModels.Add(model);
|
||
if (SopHelper.Models.UserAccess.Current.IsAdministrator && string.IsNullOrWhiteSpace(AgentModel) && models.Count > 0) AgentModel = models[0];
|
||
if (!IsAgentBusy) AgentStatus = models.Count == 0 ? "没有可用模型。" : $"已获取 {models.Count} 个模型。";
|
||
}
|
||
catch (OperationCanceledException) { ReportDiscoveryError("获取模型超时。"); }
|
||
catch (HttpRequestException error)
|
||
{
|
||
ReportDiscoveryError(error.StatusCode switch
|
||
{
|
||
System.Net.HttpStatusCode.Unauthorized => "获取模型失败:401,请填写正确的密钥。",
|
||
System.Net.HttpStatusCode.Forbidden => "获取模型失败:403,密钥无访问权限。",
|
||
System.Net.HttpStatusCode.NotFound => "获取模型失败:404,请检查接口地址。",
|
||
{ } status => $"获取模型失败:HTTP {(int)status}。",
|
||
_ => "无法连接模型服务。"
|
||
});
|
||
}
|
||
catch (Exception) { ReportDiscoveryError("模型列表响应格式无效。"); }
|
||
finally
|
||
{
|
||
if (ReferenceEquals(_modelDiscoveryCancellation, cancellation)) _modelDiscoveryCancellation = null;
|
||
cancellation.Dispose();
|
||
}
|
||
|
||
void ReportDiscoveryError(string message)
|
||
{
|
||
if (ReferenceEquals(_modelDiscoveryCancellation, cancellation) && !_agentClosed && !IsAgentBusy)
|
||
AgentStatus = message;
|
||
}
|
||
}
|
||
private void UpdateAgentDefaultVideo()
|
||
{
|
||
if (string.IsNullOrWhiteSpace(AgentVideoPath) && SopRecording is not null) AgentVideoPath = SopRecording.StandardVideoPath;
|
||
}
|
||
|
||
/// <summary>以当前配方和视频构造 Agent 请求,维护聊天及草稿状态,并支持取消。</summary>
|
||
private async Task AnalyzeVideoAsync(string? userMessage = null)
|
||
{
|
||
if (IsAgentBusy || IsCapturing || _agentClosed || (userMessage is null && IsTestingStep)) return;
|
||
if (SopRecording?.IsRecording == true) { AgentStatus = "请先停止并保存 SOP 录像,再开始分析。"; return; }
|
||
if (!File.Exists(AgentVideoPath)) { AgentStatus = "请先录制标准 SOP 视频,或选择已有视频。"; return; }
|
||
if (!Uri.TryCreate(AgentEndpoint.Trim(), UriKind.Absolute, out var endpoint) || endpoint.Scheme is not ("http" or "https")
|
||
|| string.IsNullOrWhiteSpace(AgentModel)) { AgentStatus = "请先设置完整的视觉模型接口地址和模型名。"; return; }
|
||
if (AgentMaxFrames is < 2 or > 60 || AgentInstructions.Length > 4000) { AgentStatus = "最大抽帧数须为 2–60,补充要求须小于 4000 字。"; return; }
|
||
if (userMessage is { Length: > 4000 }) { AgentStatus = "消息须小于 4000 字。"; return; }
|
||
var path = AgentVideoPath; var maxFrames = AgentMaxFrames;
|
||
var connection = new SopAgentConnection(endpoint.ToString(), AgentModel.Trim(), AgentApiKey.Trim(),
|
||
AgentContextLength, AgentMaxTokens, AgentTemperature, AgentTopP, AgentTimeoutSeconds, AgentEnableThinking);
|
||
try { SopVideoDraftClient.ValidateSettings(connection); }
|
||
catch (ArgumentException error) { AgentStatus = error.Message; return; }
|
||
var regionDefinitions = Recipe.ToConfig().Sop.Regions;
|
||
var regions = regionDefinitions.Keys.ToArray();
|
||
var recipeName = Recipe.Name; var instructions = AgentInstructions;
|
||
_agentCancellation = new CancellationTokenSource();
|
||
var token = _agentCancellation.Token;
|
||
IsAgentBusy = true;
|
||
if (userMessage is null) ResetAgentStepTaskHistory();
|
||
AgentStatus = "正在读取标准 SOP 视频…";
|
||
var activeAnalysis = _agentCancellation;
|
||
SopAgentRunLog? runLog = null;
|
||
var promptSession = _agentPromptSession = new object();
|
||
var promptLog = new Progress<SopAgentPrompt>(prompt =>
|
||
{
|
||
if (_agentClosed || !ReferenceEquals(_agentPromptSession, promptSession)) return;
|
||
AgentChatMessages.Add(new("发送给 Agent 的提示词", prompt.Text, true,
|
||
(prompt.Round == 0 ? "历史摘要请求" : $"第 {prompt.Round} 轮") + $" · 估算输入 {prompt.EstimatedTokens:N0} / 上下文 {prompt.ContextLength:N0} tokens"
|
||
+ (string.IsNullOrWhiteSpace(prompt.Compression) ? "" : "\n" + prompt.Compression)));
|
||
});
|
||
var progress = new Progress<string>(value => { if (IsAgentBusy && ReferenceEquals(_agentCancellation, activeAnalysis)) AgentStatus = value; });
|
||
try
|
||
{
|
||
runLog = new SopAgentRunLog(DesktopPlatform.WorkspaceRoot, connection.ApiKey);
|
||
runLog.Write(new("session_start", 0, JsonSerializer.Serialize(new
|
||
{
|
||
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
|
||
})));
|
||
AgentChatMessages.Add(new("分析日志", "本次分析过程自动保存:" + runLog.Path));
|
||
var sample = await Task.Run(() => SopVideoSampler.ReadInfo(path, token), token);
|
||
runLog.Write(new("video_info", 0, JsonSerializer.Serialize(sample)));
|
||
var djevTimeoutMs = (SopHelper.Models.RuntimeSettingsStore.Current.Read() ?? new()).DjevTimeoutMs;
|
||
SopVideoDraft? draft;
|
||
string reply;
|
||
if (userMessage is not null)
|
||
{
|
||
if (_agentSample is not null && (sample.Path != _agentSample.Path || sample.SourceLength != _agentSample.SourceLength
|
||
|| sample.SourceModifiedUtc != _agentSample.SourceModifiedUtc)) throw new InvalidDataException("视频已变化,请重新生成步骤");
|
||
sample = sample with { Frames = _agentSample?.Frames ?? [] };
|
||
AgentChatInput = "";
|
||
AgentChatMessages.Add(new("我", userMessage));
|
||
var result = await AgentClient.ChatAsync(new(recipeName, instructions, sample, regions, maxFrames, progress,
|
||
userMessage, _agentConversation.ToArray(), CreateAgentDraftSnapshot(), regionDefinitions,
|
||
CreateAgentImageScopes(), PromptSent: promptLog, Trace: runLog.Write,
|
||
SequenceAvailable: false, DjevTimeoutMs: djevTimeoutMs), connection, token).WaitAsync(token);
|
||
token.ThrowIfCancellationRequested();
|
||
draft = result.Draft; reply = result.Reply;
|
||
sample = sample with { Frames = result.ObservedFrames };
|
||
if (draft is not null) SopVideoDraftClient.Validate(draft, sample, regions, regionDefinitions);
|
||
_agentConversation.Add(new("user", userMessage));
|
||
_agentConversation.Add(new("assistant", reply));
|
||
}
|
||
else
|
||
{
|
||
draft = await AgentClient.AnalyzeAsync(new(recipeName, instructions, sample, regions, maxFrames, progress,
|
||
RegionDefinitions: regionDefinitions, PromptSent: promptLog, Trace: runLog.Write,
|
||
SequenceAvailable: false, DjevTimeoutMs: djevTimeoutMs), connection, token).WaitAsync(token);
|
||
sample = sample with { Frames = draft.ObservedFrames };
|
||
reply = string.IsNullOrWhiteSpace(draft.Summary) ? $"已生成 {draft.Steps.Count} 步。" : draft.Summary;
|
||
}
|
||
token.ThrowIfCancellationRequested();
|
||
if (draft is not null)
|
||
{
|
||
SopVideoDraftClient.Validate(draft, sample, regions, regionDefinitions);
|
||
token.ThrowIfCancellationRequested();
|
||
ClearAgentDraft(clearConversation: false, forgetApplied: userMessage is null);
|
||
_agentRegionAdjustments.AddRange(draft.RegionAdjustments);
|
||
RaisePropertyChanged(nameof(AgentRegionAdjustmentsSummary));
|
||
for (var i = 0; i < draft.Steps.Count; i++)
|
||
{
|
||
var step = draft.Steps[i];
|
||
var row = new AgentDraftRow(step, sample.Frames[step.EvidenceFrame]);
|
||
AgentDraftSteps.Add(row);
|
||
}
|
||
AgentSummary = draft.Summary + (draft.Warnings.Count == 0 ? "" : "\n需核对:" + string.Join(";", draft.Warnings));
|
||
AgentStatus = $"已更新 {draft.Steps.Count} 步草稿,可编辑或添加到配方。";
|
||
}
|
||
else AgentStatus = "";
|
||
_agentSample = sample;
|
||
if (userMessage is null) _agentConversation.Add(new("assistant", reply));
|
||
AgentChatMessages.Add(new("Agent", reply));
|
||
}
|
||
catch (OperationCanceledException error)
|
||
{
|
||
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) { }
|
||
}
|
||
catch (Exception error) { ReportAgentFailure(error, connection, runLog); }
|
||
finally
|
||
{
|
||
try { runLog?.Write(new("session_end", 0, AgentStatus)); }
|
||
catch (Exception logError) when (logError is IOException or UnauthorizedAccessException)
|
||
{ AgentChatMessages.Add(new("错误详情", "分析日志写入失败:" + logError.Message)); }
|
||
finally
|
||
{
|
||
try { runLog?.Dispose(); }
|
||
finally { _agentCancellation.Dispose(); _agentCancellation = null; IsAgentBusy = false; }
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>将当前草稿转换为编辑节点,协调录像工具和预览,供用户继续编辑与保存。</summary>
|
||
private async Task ApplyAgentDraftAsync()
|
||
{
|
||
if (!CanApplyAgentDraft() || _agentSample is null) return;
|
||
_isApplyingAgentDraft = true;
|
||
ApplyAgentDraftCommand.RaiseCanExecuteChanged();
|
||
try
|
||
{
|
||
var draft = new SopVideoDraft { Steps = AgentDraftSteps.Select(row => row.Step).ToList(), RegionAdjustments = [.. _agentRegionAdjustments] };
|
||
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(CreateAgentDraftTemplate(), draft);
|
||
var currentVideo = new FileInfo(_agentSample.Path);
|
||
if (!currentVideo.Exists || _agentSample.SourceLength > 0 && (currentVideo.Length != _agentSample.SourceLength || currentVideo.LastWriteTimeUtc != _agentSample.SourceModifiedUtc))
|
||
{ AgentStatus = "标准视频已变化,请重新生成。"; return; }
|
||
var choice = ChooseAgentApplyAsync is { } choose ? await choose() : AgentRecipeApplyChoice.Cancel;
|
||
if (choice == AgentRecipeApplyChoice.Cancel || _agentClosed || IsAgentBusy || _draftApplied || _agentSample is null) return;
|
||
foreach (var adjusted in _agentRegionAdjustments)
|
||
{
|
||
var source = resolved.Sop.Regions[adjusted.Key];
|
||
var region = Recipe.Regions.FirstOrDefault(r => r.Key.Equals(adjusted.Key, StringComparison.OrdinalIgnoreCase)) ?? Recipe.AddRegion(adjusted.Key);
|
||
region.X1 = source.X1; region.Y1 = source.Y1; region.X2 = source.X2; region.Y2 = source.Y2;
|
||
region.Name = source.Name; region.Description = source.Description; region.Color = source.Color;
|
||
}
|
||
var existing = choice == AgentRecipeApplyChoice.Overwrite
|
||
? _agentAppliedNodes.Where(Recipe.Steps.Contains).ToArray() : Array.Empty<StepNode>();
|
||
var previousSteps = Recipe.Steps.ToArray();
|
||
var applied = new List<StepNode>();
|
||
for (var i = 0; i < AgentDraftSteps.Count; i++)
|
||
{
|
||
var step = AgentDraftSteps[i].Step; var node = i < existing.Length ? existing[i] : Recipe.AddStep();
|
||
applied.Add(node);
|
||
node.Name = step.Name; node.Description = step.Description;
|
||
node.StandardDurationMs = Math.Max(1, (int)Math.Round((step.EndSeconds - step.StartSeconds) * 1000));
|
||
node.Detection = ConditionNode.From(resolved.Sop.Steps[i].Detection!);
|
||
node.AiConfirmation = resolved.Sop.Steps[i].AiConfirmation;
|
||
// 直接复用草稿参考画面的整图 JPEG 和视频时间,供步骤按送检规则裁剪。
|
||
var frame = _agentSample.Frames[step.EvidenceFrame];
|
||
node.KeyFrameBase64 = Convert.ToBase64String(frame.Jpeg);
|
||
node.KeyFrameSeconds = frame.Seconds;
|
||
}
|
||
if (choice == AgentRecipeApplyChoice.Overwrite)
|
||
{
|
||
foreach (var removed in previousSteps.Where(node => !applied.Contains(node))) Recipe.RemoveStep(removed);
|
||
}
|
||
_agentAppliedNodes.Clear(); _agentAppliedNodes.AddRange(applied);
|
||
RaisePropertyChanged(nameof(AgentApplyLabel));
|
||
_draftApplied = true;
|
||
RaisePropertyChanged(nameof(AgentCanEditDraft));
|
||
ApplyAgentDraftCommand.RaiseCanExecuteChanged();
|
||
RefreshWarnings();
|
||
AgentStatus = choice == AgentRecipeApplyChoice.Overwrite
|
||
? $"配方更新完成,已覆盖为 {AgentDraftSteps.Count} 步。请点击“保存”写入配方文件。"
|
||
: $"配方更新完成,已追加 {AgentDraftSteps.Count} 步,当前共 {Recipe.Steps.Count} 步。请点击“保存”写入配方文件。";
|
||
if (ShowAgentApplyCompletedAsync is { } completed) await completed(AgentStatus);
|
||
}
|
||
finally
|
||
{
|
||
_isApplyingAgentDraft = false;
|
||
ApplyAgentDraftCommand.RaiseCanExecuteChanged();
|
||
}
|
||
}
|
||
|
||
/// <summary>把当前可编辑步骤固定为草稿快照,避免聊天沿用较早版本覆盖用户手动修改。</summary>
|
||
private SopVideoDraft? CreateAgentDraftSnapshot()
|
||
{
|
||
if (AgentDraftSteps.Count == 0) return null;
|
||
var draft = JsonSerializer.Deserialize<SopVideoDraft>(JsonSerializer.Serialize(new SopVideoDraft
|
||
{ Summary = AgentSummary, Steps = AgentDraftSteps.Select(row => row.Step).ToList(), RegionAdjustments = [.. _agentRegionAdjustments] }))!;
|
||
if (_draftApplied)
|
||
for (var i = 0; i < Math.Min(draft.Steps.Count, _agentAppliedNodes.Count); i++)
|
||
{
|
||
var node = _agentAppliedNodes[i]; var step = draft.Steps[i];
|
||
step.Name = node.Name; step.Description = node.Description;
|
||
step.Method = node.Detection?.Method ?? step.Method;
|
||
step.Region = node.Detection?.Region ?? ""; step.FromRegion = node.Detection?.FromRegion ?? "";
|
||
step.ToRegion = node.Detection?.ToRegion ?? ""; step.Hand = node.Detection?.Hand ?? "any";
|
||
step.StableFrames = node.Detection?.StableFrames; step.Tolerance = node.Detection?.Tolerance;
|
||
step.ImageMode = node.AiImageMode; step.ImageRegion = node.AiImageRegion;
|
||
step.Inspection = new() { EvidenceMode = node.AiEvidenceMode, CheckWindowMs = node.AiCheckWindowMs > 0 ? node.AiCheckWindowMs : null,
|
||
ObservationMinMs = node.AiObservationMinMs,
|
||
ObservationMaxMs = node.AiObservationMaxMs, ObservationMaxFrames = node.AiObservationMaxFrames,
|
||
ObservationRequestMaxFrames = node.AiObservationRequestMaxFrames };
|
||
}
|
||
return draft;
|
||
}
|
||
|
||
/// <summary>整理每步的实际送检范围与检查参数,作为 Agent 可使用的图像上下文。</summary>
|
||
private IReadOnlyList<SopAgentImageScope> CreateAgentImageScopes()
|
||
{
|
||
if (CreateAgentDraftSnapshot() is not { } draft) return [];
|
||
var resolved = SopDraftConfigBuilder.Build(CreateAgentDraftTemplate(), draft);
|
||
var timeoutMs = (SopHelper.Models.RuntimeSettingsStore.Current.Read() ?? new()).DjevTimeoutMs;
|
||
return resolved.Sop.Steps.Select((step, index) =>
|
||
{
|
||
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.ObservationMaxMs, ai.ObservationMaxFrames, ai.ObservationRequestMaxFrames, timeoutMs);
|
||
}).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 && !_isApplyingAgentDraft && !_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;
|
||
}
|
||
|
||
/// <summary>等待单步测试结束后再启动,避免旧测试把结果追加到清空后的日志。</summary>
|
||
private bool CanStartAgentStepTask() => !IsAgentBusy && !IsTestingStep && !IsCapturing && !_agentClosed;
|
||
|
||
/// <summary>新任务通过校验后清空旧对话、界面判定日志及优化报告,后续聊天使用本次上下文。</summary>
|
||
private void ResetAgentStepTaskHistory()
|
||
{
|
||
ClearAgentConversation();
|
||
StepDecisionLog = "";
|
||
ClearOptimizationReports();
|
||
}
|
||
|
||
/// <summary>清空对话上下文和显示记录,使已排队的旧提示词回调失效。</summary>
|
||
private void ClearAgentConversation() { _agentPromptSession = null; _agentConversation.Clear(); AgentChatMessages.Clear(); }
|
||
|
||
private void ClearAgentDraft(bool clearConversation = true, bool forgetApplied = true)
|
||
{
|
||
foreach (var row in AgentDraftSteps) row.Dispose();
|
||
_agentRegionAdjustments.Clear();
|
||
RaisePropertyChanged(nameof(AgentRegionAdjustmentsSummary));
|
||
AgentDraftSteps.Clear(); _agentSample = null; _draftApplied = false; AgentSummary = "";
|
||
if (clearConversation) ClearAgentConversation();
|
||
if (forgetApplied) _agentAppliedNodes.Clear();
|
||
RaisePropertyChanged(nameof(AgentApplyLabel));
|
||
RaisePropertyChanged(nameof(AgentCanEditDraft));
|
||
ApplyAgentDraftCommand?.RaiseCanExecuteChanged();
|
||
}
|
||
}
|
||
|
||
public enum AgentRecipeApplyChoice { Cancel, Overwrite, Append }
|
||
|
||
public sealed record AgentChatLine(string Speaker, string Text, bool IsPrompt = false, string Summary = "")
|
||
{
|
||
public bool IsRegular => !IsPrompt;
|
||
}
|
||
|
||
public sealed class AgentDraftRow : BindableBase, IDisposable
|
||
{
|
||
public SopDraftStep Step { get; }
|
||
public string Name { get => Step.Name; set { Step.Name = value; RaisePropertyChanged(); } }
|
||
public string Description { get => Step.Description; set { Step.Description = value; RaisePropertyChanged(); } }
|
||
public bool IsHandMove => Step.Method == ConditionMethod.HandMove;
|
||
public string RegionLabel => IsHandMove ? "终点区域" : "触发区域";
|
||
public string FromRegion { get => Step.FromRegion; set { Step.FromRegion = value; RaisePropertyChanged(); } }
|
||
public string Region
|
||
{
|
||
get => Step.Method == ConditionMethod.HandMove ? Step.ToRegion : Step.Region;
|
||
set { if (Step.Method == ConditionMethod.HandMove) Step.ToRegion = value; else Step.Region = value; RaisePropertyChanged(); RaisePropertyChanged(nameof(Note)); }
|
||
}
|
||
public string Timeline => $"{TimeSpan.FromSeconds(Step.StartSeconds):mm\\:ss\\.f} – {TimeSpan.FromSeconds(Step.EndSeconds):mm\\:ss\\.f}";
|
||
public string EvidenceLabel { get; }
|
||
public string Note => Step.Note + $" 触发:{Step.Method}/{Step.Hand};稳定 {Step.StableFrames?.ToString() ?? "沿用"} 帧;送检:{Step.ImageRegion ?? Region}"
|
||
+ $";判定:{Step.Inspection?.EvidenceMode ?? "沿用/单帧"};检查窗口:{Step.Inspection?.CheckWindowMs?.ToString() ?? "默认"}ms"
|
||
+ (string.IsNullOrWhiteSpace(Region) ? " 触发区域未设置。" : "");
|
||
public BitmapSource EvidenceImage { get; }
|
||
public AgentDraftRow(SopDraftStep step, SopVideoFrame frame)
|
||
{
|
||
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()));
|
||
}
|
||
public void Dispose() => EvidenceImage.Dispose();
|
||
}
|