diff --git a/PLCSharp.Mcp/ProjectGateway.cs b/PLCSharp.Mcp/ProjectGateway.cs index c782e16..72b3902 100644 --- a/PLCSharp.Mcp/ProjectGateway.cs +++ b/PLCSharp.Mcp/ProjectGateway.cs @@ -21,15 +21,11 @@ internal sealed class ProjectGateway(string root, bool allowWrite) private string Dispatch(string operation, JsonObject arguments) { if (operation == "apply" && !allowWrite) throw new InvalidOperationException("Start MCP with --allow-write to save."); - // Do not hold the cross-process project lock while a person reads the dialog. - bool approved = false; - if (operation == "apply" && changes.PendingScript(Guid.Parse((string)arguments["draftId"])) is { } script) - approved = PLCSharp.VVMs.Workflows.ScriptReviewWindow.ConfirmOffline(script, root); - return ProjectPipe.Call(root, new() { ["operation"] = operation, ["arguments"] = arguments }, () => + return ProjectPipe.Call(root, new() { ["operation"] = operation == "apply" ? "applyAgentConfirmed" : operation, ["arguments"] = arguments }, () => { using var project = ProjectDirectory.Open(root); if (operation is "previewBatch" or "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewObjectEdit" or "previewObjectRename" or "previewDeviceRename" or "previewUndo" or "apply" or "status") - return changes.Execute(project, operation, arguments, allowWrite, change => (change.Review == null && change.Rename == null && change.Edit == null && change.Batch == null) || approved); + return changes.Execute(project, operation, arguments, allowWrite, _ => ProjectChanges.AgentApproval(arguments)); return ProjectInspection.Query(project, operation, arguments); }).ToJsonString(); } diff --git a/PLCSharp.Mcp/ProjectTools.cs b/PLCSharp.Mcp/ProjectTools.cs index dc7c0af..e0b4b8f 100644 --- a/PLCSharp.Mcp/ProjectTools.cs +++ b/PLCSharp.Mcp/ProjectTools.cs @@ -36,7 +36,7 @@ internal sealed class ProjectTools(ProjectGateway gateway) [McpServerTool(Name = "preview_undo"), Description("Preview reversal of an entire saved batch, object edit or rename from this session, without a dialog. Apply the new draft ID to confirm undo.")] public string PreviewUndo(string draftId) => gateway.Call("previewUndo", new() { ["draftId"] = draftId }); - [McpServerTool(Name = "preview_workflow_script"), Description("Preview replacement C# source for a workflow ID. Returns a line diff, Roslyn diagnostics, entry-point validation and draft ID. No code runs. Apply a valid draft with apply_changes; a local WPF confirmation is required.")] + [McpServerTool(Name = "preview_workflow_script"), Description("Preview replacement C# source for a workflow ID. Returns a line diff, Roslyn diagnostics, entry-point validation and draft ID. No code runs. Apply a valid draft with apply_changes; confirm the displayed draft in the Agent before saving.")] public string PreviewWorkflowScript(string id, string code) => gateway.Call("previewScript", new() { ["id"] = id, ["code"] = code }); @@ -44,8 +44,8 @@ internal sealed class ProjectTools(ProjectGateway gateway) public string PreviewChanges(string kind, string id, string comment) => gateway.Call("preview", new() { ["kind"] = kind, ["id"] = id, ["comment"] = comment }); - [McpServerTool(Name = "apply_changes"), Description("Save an existing preview using its draft ID. Requires write-enabled launch. An open editor requests user confirmation.")] - public string ApplyChanges(string draftId) => gateway.Call("apply", new() { ["draftId"] = draftId }); + [McpServerTool(Name = "apply_changes"), Description("Save an existing preview using its draft ID. Present this exact draft, impact and compile results to the user in the Agent first. Only pass confirmed=true after user approval of this draft. Pass false to reject. The editor never prompts. Requires --allow-write.")] + public string ApplyChanges(string draftId, bool confirmed) => gateway.Call("apply", new() { ["draftId"] = draftId, ["confirmed"] = confirmed }); [McpServerTool(Name = "get_change_status", ReadOnly = true), Description("Inspect a pending, rejected or saved draft.")] public string GetChangeStatus(string draftId) => gateway.Call("status", new() { ["draftId"] = draftId }); diff --git a/PLCSharpWpf/Models/BatchSummary.cs b/PLCSharpWpf/Models/BatchSummary.cs new file mode 100644 index 0000000..2bbe7f8 --- /dev/null +++ b/PLCSharpWpf/Models/BatchSummary.cs @@ -0,0 +1,58 @@ +namespace PLCSharp.Models; + +public sealed partial record ProjectBatch +{ + public string Summary => Describe(); + + private string Describe() + { + bool undo = UndoOf.HasValue; + var lines = new List(); + var refs = new HashSet(); + var manual = new HashSet(); + foreach (var step in undo ? Steps.AsEnumerable().Reverse() : Steps) + { + if (step.Edit is { } edit) + { + string action = (edit.Action, undo) switch { ("create", false) or ("delete", true) => "新增", + ("delete", false) or ("create", true) => "删除", _ => "修改" }; + var fields = new List(); + if (edit.Action == "update") + foreach (var (key, value) in edit.After) + { + if (System.Text.Json.Nodes.JsonNode.DeepEquals(edit.Before[key], value)) continue; + string from = (undo ? value : edit.Before[key])?.ToString() ?? "(空)"; + string to = (undo ? edit.Before[key] : value)?.ToString() ?? "(空)"; + string label = key switch { "Comment" => "备注", "Code" => "脚本", "ControlName" => "绑定控件", _ => key }; + fields.Add(from.Length + to.Length <= 90 ? $"{label}由「{from}」改为「{to}」" : $"{label}有修改"); + } + lines.Add($"{action}{KindName(edit.Kind)}「{step.Name}」" + (fields.Count == 0 ? "" : $",{string.Join(",", fields)}")); + foreach (var child in edit.OwnedRows) lines.Add($" 一并{(undo ? "恢复" : "删除")}{KindName(child.Kind)}「{child.Name}」"); + foreach (var hit in edit.WorkflowReferences) refs.Add($"工作流「{hit["Name"]}」第 {hit["line"]} 行引用「{step.Name}」。"); + foreach (var link in edit.ConfigReferences) refs.Add($"{KindName((string)link["table"])}的 {link["field"]} 引用「{step.Name}」。"); + foreach (var hit in edit.ManualReferences) manual.Add($"「{hit["Name"]}」第 {hit["line"]} 行 · {hit["expression"]}"); + } + else if (step.Rename is { } rename) + { + lines.Add($"{KindName(rename.Kind)}「{(undo ? rename.NewName : rename.OldName)}」改名为「{(undo ? rename.OldName : rename.NewName)}」"); + foreach (var flow in rename.Scripts) refs.Add($"工作流「{flow.Name}」同步更新。"); + foreach (var hit in rename.ManualReferences) manual.Add($"「{hit["Name"]}」第 {hit["line"]} 行 · {hit["expression"]}"); + foreach (var hit in rename.PointReferences.Concat(rename.MatrixReferences).Concat(rename.CylinderReferences)) + refs.Add($"{KindName(hit.Table)}的 {hit.Field} 同步更新。"); + foreach (var hit in rename.VisionReferences) refs.Add($"视觉功能的 {hit.Key} 同步更新。"); + } + } + if (refs.Count > 0) { lines.Add("\n受影响的工作流和配置"); lines.AddRange(refs); } + if (manual.Count > 0) { lines.Add("\n需要人工核对的引用"); lines.AddRange(manual); } + lines.Add(Workflows.Count == 0 ? "没有需要编译的工作流。" : + $"工作流编译结果(未运行):{string.Join("、", Workflows.Select(f => $"{f.Name}({(f.Compiled ? "通过" : "失败")})"))}"); + return string.Join("\n", lines); + } + + private static string KindName(string kind) => kind switch { "VisionLocalVariables" => "视觉局部变量", "ControlMeasurements" => "控件测量项", + "InterpolationSegments" => "插补段", "InterpolationPoints" => "插补段内点", "Recipes" => "配方", "SystemVariables" => "系统变量", "CustomControls" => "主页控件", + "Matrices" => "轴矩阵", "RobotMatrices" => "机器人矩阵", "InterpolationGroups" => "插补组", "Cameras" => "相机", "ImageDatas" => "视觉图像数据", "LocalImageDatas" => "本地图像数据", "Cylinders" => "气缸", "Robots" => "机器人", "Connects" => "通信连接", + "DI" => "数字输入", "DQ" => "数字输出", "Axes" => "运动轴", "VisionFunctions" => "视觉功能", "Workflows" => "工作流", + "AxisPoints" or "RobotPoints" => "点位", "Controllers" => "运动控制器", "CanvasConfigs" => "主页画布", "Variables" => "配方变量", _ => kind }; + +} diff --git a/PLCSharpWpf/Models/GlobalModel.Project.cs b/PLCSharpWpf/Models/GlobalModel.Project.cs index 671cbde..0e9c2ab 100644 --- a/PLCSharpWpf/Models/GlobalModel.Project.cs +++ b/PLCSharpWpf/Models/GlobalModel.Project.cs @@ -31,6 +31,7 @@ public partial class GlobalModel { if (!AllowAiAccess) throw new InvalidOperationException("请在机种配方页面启用 AI 访问。"); string operation = (string)request["operation"]; + if (operation == "applyAgentConfirmed") operation = "apply"; var args = request["arguments"].AsObject(); if (operation is "previewBatch" or "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewObjectEdit" or "previewObjectRename" or "previewDeviceRename" or "previewUndo" or "apply" or "status") { @@ -39,17 +40,12 @@ public partial class GlobalModel Action updateEditorView = null; var resultChange = aiChanges.Execute(Project, operation, args, true, change => { - bool accepted = change.Review != null || change.Rename != null || change.Edit != null || change.Batch != null - ? PLCSharp.VVMs.Workflows.ScriptReviewWindow.Confirm(change, Project.Root, Application.Current.MainWindow) - : MessageBox.Show($"{change.Path}\n{change.Kind} / {change.Name}\n\n原备注:{change.Before}\n新备注:{change.After}", - "应用 AI 修改", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes; - if (accepted && (ModeState.State.Execute || WorkflowsModel.IsBusy)) - throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。"); - if (accepted && change.Rename is { Kind: "Variables" } rename && CurrentRecipe.ID == rename.RecipeId && + if (!ProjectChanges.AgentApproval(args)) return false; + if (change.Rename is { Kind: "Variables" } rename && CurrentRecipe.ID == rename.RecipeId && (!VariablesModel.Variables.Any(v => v.ID == rename.VariableId && v.Name == rename.OldName) || VariablesModel.Variables.Any(v => v.ID != rename.VariableId && (v.Name == rename.NewName || v.Name == rename.OldName)))) throw new InvalidOperationException("编辑器变量列表存在更改,请先保存并重新预览。"); - if (accepted && change.Rename is { Kind: "VisionFunctions" } vision && CurrentRecipe.ID == vision.RecipeId) + if (change.Rename is { Kind: "VisionFunctions" } vision && CurrentRecipe.ID == vision.RecipeId) { var functions = VisionsModel.VisionFunctions; var target = functions.SingleOrDefault(v => v.ID == vision.ObjectId); @@ -58,7 +54,7 @@ public partial class GlobalModel throw new ProjectConflictException("编辑器视觉功能列表有更改,请先保存并重新预览。"); updateEditorView = () => target.SetReviewedName(vision.NewName); } - if (accepted && change.Rename is { IsPoint: true } point && CurrentRecipe.ID == point.RecipeId) + if (change.Rename is { IsPoint: true } point && CurrentRecipe.ID == point.RecipeId) { if (point.Kind == "AxisPoints") updateEditorView = Project.PreparePointView(point, ControllersModel.AxisPoints, ControllersModel.Matrices); @@ -70,11 +66,11 @@ public partial class GlobalModel updateEditorView = Project.PreparePointView(point, robot.Points, robot.RobotMatrices); } } - if (accepted && change.Rename is { Kind: "Axes" } axis) + if (change.Rename is { Kind: "Axes" } axis) updateEditorView = Project.PrepareAxisView(axis, ControllersModel, CurrentRecipe.ID); - if (accepted && change.Rename is { IsIo: true } io) + if (change.Rename is { IsIo: true } io) updateEditorView = Project.PrepareIoView(io, ControllersModel, CylindersModel); - if (accepted && change.Rename is { Nested: not null } member && CurrentRecipe.ID == member.RecipeId) + if (change.Rename is { Nested: not null } member && CurrentRecipe.ID == member.RecipeId) { object owner = member.Kind switch { @@ -84,7 +80,7 @@ public partial class GlobalModel }; updateEditorView = ProjectDirectory.PrepareNestedView(member, owner); } - if (accepted && change.Rename is { IsMatrixOrGroup: true } matrix && CurrentRecipe.ID == matrix.RecipeId) + if (change.Rename is { IsMatrixOrGroup: true } matrix && CurrentRecipe.ID == matrix.RecipeId) { IEnumerable objects = matrix.Kind switch { @@ -94,18 +90,18 @@ public partial class GlobalModel }; if (objects != null) updateEditorView = Project.PreparePointView(matrix, objects, []); } - if (accepted && change.Rename is { IsVisionAsset: true } asset) + if (change.Rename is { IsVisionAsset: true } asset) updateEditorView = Project.PrepareAssetView(asset, VisionsModel, CurrentRecipe.ID, CustomControls, VariablesModel.SystemVariables); - if (accepted && change.Rename is { IsDevice: true } device) + if (change.Rename is { IsDevice: true } device) updateEditorView = PrepareDeviceView(device); - if (accepted && change.Batch != null) + if (change.Batch != null) { var updates = change.Batch.Rows.OrderBy(row => row.Kind == "Recipes" ? 1 : 0) .Select(PrepareObjectView).Where(update => update != null).ToList(); updateEditorView = () => { foreach (var update in updates) update(); }; } - if (accepted && change.Edit != null) updateEditorView = PrepareObjectView(change.Edit); - return accepted; + if (change.Edit != null) updateEditorView = PrepareObjectView(change.Edit); + return true; }); if ((string)resultChange["Status"] == "saved") updateEditorView?.Invoke(); return resultChange; diff --git a/PLCSharpWpf/Models/ProjectBatch.cs b/PLCSharpWpf/Models/ProjectBatch.cs index 54c5c5b..b6a1684 100644 --- a/PLCSharpWpf/Models/ProjectBatch.cs +++ b/PLCSharpWpf/Models/ProjectBatch.cs @@ -9,7 +9,7 @@ using System.Text.Json.Serialization; namespace PLCSharp.Models; -public sealed record ProjectBatch(List Steps, List Workflows, string[] ChangedFiles, Guid? UndoOf = null) +public sealed partial record ProjectBatch(List Steps, List Workflows, string[] ChangedFiles, Guid? UndoOf = null) { public bool Compiled => Steps.All(s => s.Status == "pending") && Workflows.All(f => f.Compiled); [JsonIgnore] internal Dictionary From { get; init; } diff --git a/PLCSharpWpf/Models/ProjectChanges.cs b/PLCSharpWpf/Models/ProjectChanges.cs index cabcd8d..2ebced5 100644 --- a/PLCSharpWpf/Models/ProjectChanges.cs +++ b/PLCSharpWpf/Models/ProjectChanges.cs @@ -15,8 +15,9 @@ public sealed class ProjectChanges internal ProjectChange PendingOrInvalid(Guid id) => drafts[id]; - public ProjectChange PendingScript(Guid id) => - drafts.TryGetValue(id, out var draft) && (draft.Review != null || draft.Rename != null || draft.Edit != null || draft.Batch != null) && draft.Status == "pending" ? draft : null; + public static bool AgentApproval(JsonObject args) => + args["confirmed"] is JsonValue value && value.TryGetValue(out var confirmed) ? confirmed : + throw new ArgumentException("保存需要 Agent 提交当前草案的确认结果。"); private JsonNode Remember(ProjectChange change) { diff --git a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml deleted file mode 100644 index b837f7b..0000000 --- a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - -