diff --git a/PLCSharp.Mcp/ProjectGateway.cs b/PLCSharp.Mcp/ProjectGateway.cs index 820cff3..c782e16 100644 --- a/PLCSharp.Mcp/ProjectGateway.cs +++ b/PLCSharp.Mcp/ProjectGateway.cs @@ -28,8 +28,8 @@ internal sealed class ProjectGateway(string root, bool allowWrite) return ProjectPipe.Call(root, new() { ["operation"] = operation, ["arguments"] = arguments }, () => { using var project = ProjectDirectory.Open(root); - if (operation is "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) || approved); + 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 ProjectInspection.Query(project, operation, arguments); }).ToJsonString(); } diff --git a/PLCSharp.Mcp/ProjectTools.cs b/PLCSharp.Mcp/ProjectTools.cs index 5428f0b..7cddff4 100644 --- a/PLCSharp.Mcp/ProjectTools.cs +++ b/PLCSharp.Mcp/ProjectTools.cs @@ -7,6 +7,10 @@ namespace PLCSharp.Mcp; [McpServerToolType] internal sealed class ProjectTools(ProjectGateway gateway) { + [McpServerTool(Name = "preview_batch", ReadOnly = true), Description("Use one batch for all edits requested together, even across files. Preview only; no editor dialog or project writes. Pass ordered operations with action create/update/delete/rename, kind, id, properties or newName (and optional memberName/segmentName). To edit script source update Workflows with properties.Code. For dependencies give a create an alias, then use $alias as id or RecipeID/RobotID/FuncID. Returns references, diagnostics and one draft ID. Review once with apply_changes; preview_undo reverses the whole saved batch. For analysis only use read/preview tools and stop before apply_changes.")] + public string PreviewBatch(JsonArray operations) => + gateway.Call("previewBatch", new() { ["operations"] = operations.DeepClone() }); + [McpServerTool(Name = "preview_object_edit"), Description("Preview create, update or delete for Recipes, Workflows, Variables, SystemVariables, AxisPoints, RobotPoints, Matrices, RobotMatrices, InterpolationGroups, VisionFunctions, ImageDatas, LocalImageDatas, CanvasConfigs, CustomControls or hardware (Controllers, Axes, DI, DQ, Cylinders, Robots, Connects, Cameras). Use persisted JSON column names. Create generates an ID; pass RecipeID for scoped objects and RobotID for robot points/matrices and FuncID for local images. Workflow Code uses __WORKFLOW_ID__ for the generated class name suffix. Deletion previews list owned records and affected files. Update/delete require id. Objects in properties merge recursively, arrays replace. Review workflow/config references, dynamic references and compile results before apply_changes. Use preview_undo to reverse.")] public string PreviewObjectEdit(string action, string kind, string id = null, JsonObject properties = null) => gateway.Call("previewObjectEdit", new() { ["action"] = action, ["kind"] = kind, ["id"] = id, ["properties"] = properties?.DeepClone() }); @@ -45,7 +49,7 @@ internal sealed class ProjectTools(ProjectGateway gateway) [McpServerTool(Name = "preview_variable_rename"), Description("Preview renaming a recipe user variable by ID. Compile rewritten workflows, and report dynamic or uncertain references for review. Apply the returned draft ID after review.")] public string PreviewVariableRename(string id, string newName) => gateway.Call("previewRename", new() { ["id"] = id, ["newName"] = newName }); - [McpServerTool(Name = "preview_undo"), Description("Preview reversal of a saved variable, axis, vision function, point or workflow rename from this session. Apply the new draft ID to confirm undo.")] + [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.")] diff --git a/PLCSharpWpf/Models/GlobalModel.Project.cs b/PLCSharpWpf/Models/GlobalModel.Project.cs index b5d853b..671cbde 100644 --- a/PLCSharpWpf/Models/GlobalModel.Project.cs +++ b/PLCSharpWpf/Models/GlobalModel.Project.cs @@ -32,14 +32,14 @@ public partial class GlobalModel if (!AllowAiAccess) throw new InvalidOperationException("请在机种配方页面启用 AI 访问。"); string operation = (string)request["operation"]; var args = request["arguments"].AsObject(); - if (operation is "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") + 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") { if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy)) throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。"); Action updateEditorView = null; var resultChange = aiChanges.Execute(Project, operation, args, true, change => { - bool accepted = change.Review != null || change.Rename != null || change.Edit != null + 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; @@ -98,6 +98,12 @@ public partial class GlobalModel updateEditorView = Project.PrepareAssetView(asset, VisionsModel, CurrentRecipe.ID, CustomControls, VariablesModel.SystemVariables); if (accepted && change.Rename is { IsDevice: true } device) updateEditorView = PrepareDeviceView(device); + if (accepted && 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; }); diff --git a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs index 25d5352..17f5221 100644 --- a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs +++ b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs @@ -9,7 +9,8 @@ public partial class ScriptReviewWindow : Window private ScriptReviewWindow(ProjectChange change, string root) { InitializeComponent(); - if (change.Edit is { } edit) + if (change.Batch is { } batch) ShowBatch(batch); + else if (change.Edit is { } edit) { string action = edit.Action switch { "create" => "新增", "update" => "修改", _ => "删除" }; Title = $"确认{(edit.UndoOf.HasValue ? "撤销 · " : "")}{action}工程对象"; @@ -79,6 +80,63 @@ public partial class ScriptReviewWindow : Window Loaded += (_, _) => CancelChange.Focus(); } + private void ShowBatch(ProjectBatch batch) + { + bool undo = batch.UndoOf.HasValue; + Title = undo ? "确认整批撤销" : "确认整批保存"; + WorkflowTitle.Text = $"{(undo ? "撤销" : "保存")}这批 {batch.Steps.Count} 项修改"; + Location.Visibility = Visibility.Collapsed; + SaveChange.Content = undo ? "整批撤销" : "整批保存"; + var lines = new List(); + var refs = new HashSet(); + var manual = new HashSet(); + var details = new List(batch.ChangedFiles); + foreach (var step in undo ? batch.Steps.AsEnumerable().Reverse() : batch.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"]}"); + details.Add($"{step.Name}\n{(undo ? edit.After : edit.Before)} → {(undo ? edit.Before : edit.After)}"); + } + 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} 同步更新。"); + foreach (var flow in rename.Scripts) details.Add(flow.Review.Diff); + } + } + if (refs.Count > 0) { lines.Add("\n受影响的工作流和配置"); lines.AddRange(refs); } + if (manual.Count > 0) { lines.Add("\n需要人工核对的引用"); lines.AddRange(manual); } + CheckResult.Text = batch.Workflows.Count == 0 ? "本批没有需要编译的工作流。" : + $"工作流编译通过(未运行):{string.Join("、", batch.Workflows.Select(f=>f.Name))}"; + foreach (var f in batch.Workflows) + foreach (var diagnostic in f.Diagnostics) details.Add($"{f.Name} · {diagnostic.Code} · {diagnostic.Message}"); + ImpactSummary.Text = string.Join("\n", lines); + CodeDiff.Text = string.Join("\n", details); + DetailsToggle.Visibility = Visibility.Visible; + ToggleDetails(this, null); + } + private static string KindName(string kind) => kind switch { "VisionLocalVariables" => "视觉局部变量", "ControlMeasurements" => "控件测量项", "InterpolationSegments" => "插补段", "InterpolationPoints" => "插补段内点", "Recipes" => "配方", "SystemVariables" => "系统变量", "CustomControls" => "主页控件", "Matrices" => "轴矩阵", "RobotMatrices" => "机器人矩阵", "InterpolationGroups" => "插补组", "Cameras" => "相机", "ImageDatas" => "视觉图像数据", "LocalImageDatas" => "本地图像数据", "Cylinders" => "气缸", "Robots" => "机器人", "Connects" => "通信连接",