From 559eb230a693b5460612a92bd12f9af8db6b9780 Mon Sep 17 00:00:00 2001 From: wanglei Date: Sat, 5 Dec 2026 21:26:51 +0800 Subject: [PATCH] Apply reviewed workflow source only after explicit WPF approval --- PLCSharp.Mcp/ProjectGateway.cs | 8 ++- PLCSharp.Mcp/ProjectTools.cs | 4 ++ PLCSharpWpf/Models/GlobalModel.Project.cs | 5 +- PLCSharpWpf/Models/ProjectChanges.cs | 66 +++++++++++++++---- .../VVMs/Workflows/ScriptReviewWindow.xaml | 21 ++++++ .../VVMs/Workflows/ScriptReviewWindow.xaml.cs | 44 +++++++++++++ PLCSharpWpf/VVMs/Workflows/Workflow.cs | 13 +++- .../WorkflowScriptChangeTests.cs | 54 +++++++++++++++ 8 files changed, 198 insertions(+), 17 deletions(-) create mode 100644 PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml create mode 100644 PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs create mode 100644 Tests/PLCSharp.Tests/WorkflowScriptChangeTests.cs diff --git a/PLCSharp.Mcp/ProjectGateway.cs b/PLCSharp.Mcp/ProjectGateway.cs index e7e4b50..a645108 100644 --- a/PLCSharp.Mcp/ProjectGateway.cs +++ b/PLCSharp.Mcp/ProjectGateway.cs @@ -21,11 +21,15 @@ 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 }, () => { using var project = ProjectDirectory.Open(root); - if (operation is "preview" or "apply" or "status") - return changes.Execute(project, operation, arguments, allowWrite); + if (operation is "preview" or "previewScript" or "apply" or "status") + return changes.Execute(project, operation, arguments, allowWrite, change => change.Review == null || approved); return ProjectInspection.Query(project, operation, arguments); }).ToJsonString(); } diff --git a/PLCSharp.Mcp/ProjectTools.cs b/PLCSharp.Mcp/ProjectTools.cs index aac1e90..6605245 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_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.")] + public string PreviewWorkflowScript(string id, string code) => + gateway.Call("previewScript", new() { ["id"] = id, ["code"] = code }); + [McpServerTool(Name = "preview_changes"), Description("Preview a comment change to one recipe, variable or workflow. Returns a draft ID and before/after values. No file is written.")] public string PreviewChanges(string kind, string id, string comment) => gateway.Call("preview", new() { ["kind"] = kind, ["id"] = id, ["comment"] = comment }); diff --git a/PLCSharpWpf/Models/GlobalModel.Project.cs b/PLCSharpWpf/Models/GlobalModel.Project.cs index dfcfa91..15caaf1 100644 --- a/PLCSharpWpf/Models/GlobalModel.Project.cs +++ b/PLCSharpWpf/Models/GlobalModel.Project.cs @@ -32,11 +32,12 @@ 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 "apply" or "status") + if (operation is "preview" or "previewScript" or "apply" or "status") { if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy)) throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。"); - return aiChanges.Execute(Project, operation, args, true, change => + return aiChanges.Execute(Project, operation, args, true, change => change.Review != 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); } diff --git a/PLCSharpWpf/Models/ProjectChanges.cs b/PLCSharpWpf/Models/ProjectChanges.cs index 650d8f0..a509503 100644 --- a/PLCSharpWpf/Models/ProjectChanges.cs +++ b/PLCSharpWpf/Models/ProjectChanges.cs @@ -7,15 +7,35 @@ using System.Text.Json.Nodes; namespace PLCSharp.Models; public sealed record ProjectChange(Guid DraftId, Guid ProjectId, string Kind, Guid ObjectId, Guid RecipeId, - string Name, string Path, string Before, string After, string Revision, string Status); + string Name, string Path, string Before, string After, string Revision, string Status, WorkflowScriptReview Review = null); public sealed class ProjectChanges { private readonly Dictionary drafts = new(); + public ProjectChange PendingScript(Guid id) => + drafts.TryGetValue(id, out var draft) && draft.Review != null && draft.Status == "pending" ? draft : null; + + private JsonNode Remember(ProjectChange change) + { + if (drafts.Count >= 256) drafts.Remove(drafts.Keys.First()); + drafts.Add(change.DraftId, change); + return JsonSerializer.SerializeToNode(change); + } + public JsonNode Execute(ProjectDirectory project, string operation, JsonObject args, bool allowWrite, Func confirm = null) { + if (operation == "previewScript") + { + var id = Guid.Parse((string)args["id"]); + var target = ProjectInspection.Query(project, "get", new() { ["kind"] = "Workflows", ["id"] = id.ToString() }); + var recipe = Guid.Parse((string)target["RecipeID"]); + string path = $"recipes/{recipe:D}/workflows/{id:D}.cs", before = (string)target["Code"] ?? "", after = (string)args["code"]; + var review = WorkflowScriptReview.Create(id, before, after); + return Remember(new(Guid.NewGuid(), project.Id, "Workflows", id, recipe, (string)target["Name"], path, + before, after, project.Revision(path), review.Compiled ? "pending" : "invalid", review)); + } if (operation == "preview") { string kind = (string)args["kind"], after = (string)args["comment"]; @@ -31,20 +51,25 @@ public sealed class ProjectChanges string before = (string)target["Comment"]; var change = new ProjectChange(Guid.NewGuid(), project.Id, kind, id, recipeId, (string)target["Name"], path, before, after, project.Revision(path), "pending"); - if (drafts.Count >= 256) drafts.Remove(drafts.Keys.First()); - drafts.Add(change.DraftId, change); - return JsonSerializer.SerializeToNode(change); + return Remember(change); } } if (!drafts.TryGetValue(Guid.Parse((string)args["draftId"]), out var draft) || draft.ProjectId != project.Id) throw new ArgumentException("Unknown or expired draft."); + if (operation == "apply" && draft.Status == "invalid") + throw new InvalidOperationException("脚本编译检查未通过,请修正后重新预览。"); if (operation == "apply" && draft.Status == "pending") { if (!allowWrite) throw new InvalidOperationException("Start the MCP server with --allow-write to apply a preview."); + if (draft.Review != null && confirm == null) throw new InvalidOperationException("脚本修改需要用户确认。"); if (confirm != null && !confirm(draft)) draft = draft with { Status = "rejected" }; else { - try { project.ApplyComment(draft); } + try + { + if (draft.Review == null) project.ApplyComment(draft); + else project.ApplyScript(draft); + } catch (ProjectConflictException) { drafts[draft.DraftId] = draft with { Status = "conflict" }; @@ -64,6 +89,28 @@ public sealed partial class ProjectDirectory { internal string Revision(string path) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(baseline[path]))); + private void WriteReviewedFile(ProjectChange change, string contents) + { + var files = new Dictionary(baseline) { [change.Path] = contents }; + try { WriteFiles(Root, files, [change.Path]); } + catch (System.IO.IOException) when (!System.IO.File.Exists(ProjectFile(Root, change.Path)) || + System.IO.File.ReadAllText(ProjectFile(Root, change.Path)) != baseline[change.Path]) + { + throw new ProjectConflictException("The file changed outside the editor. Reopen the project and preview again."); + } + } + + internal void ApplyScript(ProjectChange change) + { + lock (Data.Sync) + { + if (Revision(change.Path) != change.Revision || baseline[change.Path] != change.Before) + throw new ProjectConflictException("脚本存在未保存编辑或预览已过期,请先核对当前版本。"); + var workflow = Flows(change.RecipeId).Single(w => w.ID == change.ObjectId); + workflow.SaveReviewedCode(change.Before, change.After, () => WriteReviewedFile(change, change.After)); + } + } + internal void ApplyComment(ProjectChange change) { lock (Data.Sync) @@ -85,19 +132,14 @@ public sealed partial class ProjectDirectory throw new ProjectConflictException("Save the pending editor change to this comment first."); target[field] = change.After; var json = Serialize(document); - var files = new Dictionary(baseline) { [change.Path] = json }; + // Change only the approved column in the private working database. Other tracked drafts stay pending. using var transaction = isVariable ? Data.Database.BeginTransaction() : null; if (change.Kind == "Variables") Data.Variables.Where(v => v.ID == id).ExecuteUpdate(s => s.SetProperty(v => v.Comment, change.After)); if (change.Kind == "SystemVariables") Data.SystemVariables.Where(v => v.ID == id).ExecuteUpdate(s => s.SetProperty(v => v.Comment, change.After)); - try { WriteFiles(Root, files, [change.Path]); } - catch (System.IO.IOException) when (!System.IO.File.Exists(ProjectFile(Root, change.Path)) || - System.IO.File.ReadAllText(ProjectFile(Root, change.Path)) != baseline[change.Path]) - { - throw new ProjectConflictException("The file changed outside the editor. Reopen the project and preview again."); - } + WriteReviewedFile(change, json); transaction?.Commit(); if (isVariable) { diff --git a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml new file mode 100644 index 0000000..0dfe6df --- /dev/null +++ b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml @@ -0,0 +1,21 @@ + + + + + + + + + + + +