From 058ba4fcaed3c1b33987f7adf7ebfc146a479657 Mon Sep 17 00:00:00 2001 From: wanglei Date: Sat, 5 Dec 2026 21:34:17 +0800 Subject: [PATCH] Apply variable renames and guarded inverse drafts across project files --- PLCSharp.Mcp/ProjectGateway.cs | 4 +- PLCSharp.Mcp/ProjectTools.cs | 6 ++ PLCSharpWpf/Models/GlobalModel.Project.cs | 4 +- PLCSharpWpf/Models/ProjectChanges.cs | 33 +++++++- PLCSharpWpf/Models/VariableRename.cs | 75 +++++++++++++++++++ PLCSharpWpf/VVMs/GlobalVariables/Variable.cs | 3 +- .../VVMs/Workflows/ScriptReviewWindow.xaml.cs | 23 ++++-- .../PLCSharp.Tests/VariableRenameUndoTests.cs | 49 ++++++++++++ 8 files changed, 183 insertions(+), 14 deletions(-) create mode 100644 Tests/PLCSharp.Tests/VariableRenameUndoTests.cs diff --git a/PLCSharp.Mcp/ProjectGateway.cs b/PLCSharp.Mcp/ProjectGateway.cs index a645108..036d663 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 "apply" or "status") - return changes.Execute(project, operation, arguments, allowWrite, change => change.Review == null || approved); + if (operation is "preview" or "previewScript" or "previewRename" or "previewUndo" or "apply" or "status") + return changes.Execute(project, operation, arguments, allowWrite, change => (change.Review == null && change.Rename == null) || approved); return ProjectInspection.Query(project, operation, arguments); }).ToJsonString(); } diff --git a/PLCSharp.Mcp/ProjectTools.cs b/PLCSharp.Mcp/ProjectTools.cs index 6605245..424d794 100644 --- a/PLCSharp.Mcp/ProjectTools.cs +++ b/PLCSharp.Mcp/ProjectTools.cs @@ -7,6 +7,12 @@ namespace PLCSharp.Mcp; [McpServerToolType] 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 rename from this session. 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.")] public string PreviewWorkflowScript(string id, string code) => gateway.Call("previewScript", new() { ["id"] = id, ["code"] = code }); diff --git a/PLCSharpWpf/Models/GlobalModel.Project.cs b/PLCSharpWpf/Models/GlobalModel.Project.cs index 15caaf1..ec1dbc0 100644 --- a/PLCSharpWpf/Models/GlobalModel.Project.cs +++ b/PLCSharpWpf/Models/GlobalModel.Project.cs @@ -32,11 +32,11 @@ 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 "apply" or "status") + if (operation is "preview" or "previewScript" or "previewRename" or "previewUndo" or "apply" or "status") { if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy)) throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。"); - return aiChanges.Execute(Project, operation, args, true, change => change.Review != null + return aiChanges.Execute(Project, operation, args, true, change => (change.Review != null || change.Rename != 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 a509503..8fc37d6 100644 --- a/PLCSharpWpf/Models/ProjectChanges.cs +++ b/PLCSharpWpf/Models/ProjectChanges.cs @@ -7,14 +7,14 @@ 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, WorkflowScriptReview Review = null); + string Name, string Path, string Before, string After, string Revision, string Status, WorkflowScriptReview Review = null, VariableRename Rename = 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; + drafts.TryGetValue(id, out var draft) && (draft.Review != null || draft.Rename != null) && draft.Status == "pending" ? draft : null; private JsonNode Remember(ProjectChange change) { @@ -26,6 +26,22 @@ public sealed class ProjectChanges public JsonNode Execute(ProjectDirectory project, string operation, JsonObject args, bool allowWrite, Func confirm = null) { + if (operation is "previewRename" or "previewUndo") + { + VariableRename plan; + if (operation == "previewRename") + plan = project.PlanRename(Guid.Parse((string)args["id"]), (string)args["newName"]); + else + { + if (!drafts.TryGetValue(Guid.Parse((string)args["draftId"]), out var saved) || saved.ProjectId != project.Id || + saved.Status != "saved" || saved.Rename == null || saved.Rename.UndoOf.HasValue) + throw new ArgumentException("需要当前会话中已保存且尚未撤销的变量重命名 ID。"); + plan = project.PlanUndo(saved.DraftId, saved.Rename); + } + return Remember(new(Guid.NewGuid(), project.Id, "Variables", plan.VariableId, plan.RecipeId, plan.OldName, + ProjectDirectory.VariablesPath, plan.OldName, plan.NewName, project.Revision(ProjectDirectory.VariablesPath), + plan.Compiled ? "pending" : "invalid", Rename: plan)); + } if (operation == "previewScript") { var id = Guid.Parse((string)args["id"]); @@ -61,13 +77,22 @@ public sealed class ProjectChanges 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 ((draft.Review != null || draft.Rename != null) && confirm == null) throw new InvalidOperationException("脚本修改需要用户确认。"); if (confirm != null && !confirm(draft)) draft = draft with { Status = "rejected" }; else { try { - if (draft.Review == null) project.ApplyComment(draft); + if (draft.Rename != null) + { + if (draft.Rename.UndoOf is Guid source && + (!drafts.TryGetValue(source, out var original) || original.Status != "saved")) + throw new ProjectConflictException("原重命名已撤销或会话已过期。"); + project.ApplyRename(draft.Rename); + if (draft.Rename.UndoOf is Guid previous && drafts.TryGetValue(previous, out var saved)) + drafts[previous] = saved with { Status = "undone" }; + } + else if (draft.Review == null) project.ApplyComment(draft); else project.ApplyScript(draft); } catch (ProjectConflictException) diff --git a/PLCSharpWpf/Models/VariableRename.cs b/PLCSharpWpf/Models/VariableRename.cs index e400e23..acebebd 100644 --- a/PLCSharpWpf/Models/VariableRename.cs +++ b/PLCSharpWpf/Models/VariableRename.cs @@ -1,4 +1,6 @@ using Microsoft.CodeAnalysis.CSharp; +using Microsoft.EntityFrameworkCore; +using System.IO; using Microsoft.CodeAnalysis.Text; using System.Security.Cryptography; using System.Text; @@ -15,6 +17,8 @@ public sealed record VariableRename(Guid VariableId, Guid RecipeId, string OldNa public bool Compiled => Scripts.All(s => s.Review.Compiled) && ScanDiagnostics.Count == 0; [JsonIgnore] internal string Scope { get; init; } [JsonIgnore] internal string OriginalVariables { get; init; } + [JsonIgnore] internal string SavedScope { get; set; } + [JsonIgnore] internal string SavedVariables { get; set; } public Guid? UndoOf { get; init; } } @@ -60,5 +64,76 @@ public sealed partial class ProjectDirectory return new(id, variable.RecipeID, variable.Name, newName, edits, manual, analysis["diagnostics"].AsArray()) { Scope = RenameScope(variable.RecipeID), OriginalVariables = baseline[VariablesPath] }; } + internal VariableRename PlanUndo(Guid operationId, VariableRename saved) + { + if (saved.SavedScope != RenameScope(saved.RecipeId) || saved.SavedVariables != baseline[VariablesPath]) + throw new ProjectConflictException("保存后配方脚本或变量文件已改变,无法安全撤销。"); + CheckVariableName(saved.RecipeId, saved.VariableId, saved.NewName, saved.OldName); + var inverse = saved.Scripts.Select(s => s with { Before = s.After, After = s.Before, + Review = WorkflowScriptReview.Create(s.Id, s.After, s.Before) }).ToList(); + return new(saved.VariableId, saved.RecipeId, saved.NewName, saved.OldName, inverse, + saved.ManualReferences, new JsonArray()) { UndoOf = operationId, Scope = saved.SavedScope, + OriginalVariables = saved.SavedVariables, SavedVariables = saved.OriginalVariables }; + } + + internal void ApplyRename(VariableRename plan) + { + lock (Data.Sync) + { + CheckVariableName(plan.RecipeId, plan.VariableId, plan.OldName, plan.NewName); + if (RenameScope(plan.RecipeId) != plan.Scope || baseline[VariablesPath] != plan.OriginalVariables) + throw new ProjectConflictException("变量或工作流已经改变,请重新预览。"); + var files = new Dictionary(baseline); + var variables = JsonNode.Parse(files[VariablesPath]); + var row = variables["Variables"].AsArray().Single(v => Guid.Parse((string)v["ID"]) == plan.VariableId); + if ((string)row["Name"] != plan.OldName) + throw new ProjectConflictException("变量名有未保存的编辑,请先保存或还原。"); + row["Name"] = plan.NewName; + files[VariablesPath] = plan.UndoOf.HasValue ? plan.SavedVariables : Serialize(variables); + var recipePath = RecipePath(plan.RecipeId); + var flows = Flows(plan.RecipeId); + var persisted = JsonNode.Parse(files[recipePath])["workflows"].AsArray().Select(w => Guid.Parse((string)w["id"])); + if (!persisted.ToHashSet().SetEquals(flows.Select(w => w.ID))) + throw new ProjectConflictException("请先保存工作流列表。"); + var scope = new List { VariablesPath, recipePath, "project.json" }; + foreach (var flow in flows) scope.Add(ScriptPath(plan.RecipeId, flow.ID)); + foreach (var script in plan.Scripts) + { + if (files[script.Path] != script.Before) + throw new ProjectConflictException($"工作流 {script.Name} 存在未保存编辑。"); + files[script.Path] = script.After; + } + + // Hold each affected workflow's execution gate through the single multi-file commit. + void Commit(int index) + { + if (index < plan.Scripts.Count) + { + var script = plan.Scripts[index]; + flows.Single(w => w.ID == script.Id).SaveReviewedCode(script.Before, script.After, () => Commit(index + 1)); + return; + } + using var transaction = Data.Database.BeginTransaction(); + if (Data.Variables.Where(v => v.ID == plan.VariableId && v.Name == plan.OldName) + .ExecuteUpdate(s => s.SetProperty(v => v.Name, plan.NewName)) != 1) + throw new ProjectConflictException("变量已发生变化。"); + try { WriteFiles(Root, files, scope.ToArray()); } + catch (IOException) when (scope.Any(path => !File.Exists(ProjectFile(Root, path)) || + File.ReadAllText(ProjectFile(Root, path)) != baseline[path])) + { + throw new ProjectConflictException("工程文件已从外部修改,请重新打开并预览。"); + } + transaction.Commit(); + configuration[VariablesPath] = files[VariablesPath]; + var variable = Data.Variables.Local.Single(v => v.ID == plan.VariableId); + variable.Name = plan.NewName; + Data.Entry(variable).Property(v => v.Name).OriginalValue = plan.NewName; + } + Commit(0); + plan.SavedScope = RenameScope(plan.RecipeId); + plan.SavedVariables = files[VariablesPath]; + } + } + } diff --git a/PLCSharpWpf/VVMs/GlobalVariables/Variable.cs b/PLCSharpWpf/VVMs/GlobalVariables/Variable.cs index 910af23..fbc6f36 100644 --- a/PLCSharpWpf/VVMs/GlobalVariables/Variable.cs +++ b/PLCSharpWpf/VVMs/GlobalVariables/Variable.cs @@ -30,7 +30,8 @@ namespace PLCSharp.VVMs.GlobalVariables /// /// 变量名 /// - public string Name { get; set; } + public string Name { get => _name; set => SetProperty(ref _name, value); } + private string _name; /// /// 备注 diff --git a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs index 0ce3d0d..d4ae4f7 100644 --- a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs +++ b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs @@ -9,11 +9,24 @@ public partial class ScriptReviewWindow : Window private ScriptReviewWindow(ProjectChange change, string root) { InitializeComponent(); - WorkflowTitle.Text = $"工作流 · {change.Name}"; - Location.Text = System.IO.Path.Combine(root, change.Path); - CheckResult.Text = string.Join("\n", new[] { "编译通过(仅检查,未运行)" }.Concat( - change.Review.Diagnostics.Select(d => $"{d.Code} ({d.Line},{d.Column}) {d.Message}"))); - CodeDiff.Text = change.Review.Diff; + if (change.Rename is { } rename) + { + Title = rename.UndoOf.HasValue ? "确认撤销变量重命名" : "确认变量重命名"; + WorkflowTitle.Text = $"{rename.OldName} → {rename.NewName}"; + Location.Text = System.IO.Path.Combine(root, change.Path); + CheckResult.Text = $"已通过编译的工作流:{rename.Scripts.Count},需人工核对的引用:{rename.ManualReferences.Count}"; + CodeDiff.Text = string.Join("\n", rename.ManualReferences.Select(h => + $"待核对 [{h["confidence"]}] {h["path"]}:{h["line"]} {h["expression"]}") + .Concat(rename.Scripts.Select(s => $"\n{s.Path} · {s.Name}\n{s.Review.Diff}"))); + } + else + { + WorkflowTitle.Text = $"工作流 · {change.Name}"; + Location.Text = System.IO.Path.Combine(root, change.Path); + CheckResult.Text = string.Join("\n", new[] { "编译通过(仅检查,未运行)" }.Concat( + change.Review.Diagnostics.Select(d => $"{d.Code} ({d.Line},{d.Column}) {d.Message}"))); + CodeDiff.Text = change.Review.Diff; + } Loaded += (_, _) => CancelChange.Focus(); } diff --git a/Tests/PLCSharp.Tests/VariableRenameUndoTests.cs b/Tests/PLCSharp.Tests/VariableRenameUndoTests.cs new file mode 100644 index 0000000..90071bb --- /dev/null +++ b/Tests/PLCSharp.Tests/VariableRenameUndoTests.cs @@ -0,0 +1,49 @@ +using PLCSharp.Models; +using PLCSharp.VVMs.GlobalVariables; +using PLCSharp.VVMs.Workflows; +using System.IO; +using System.Text.Json.Nodes; + +namespace PLCSharp.Tests; + +public class VariableRenameUndoTests +{ + [Fact] + public void UndoRestoresExactInputsAndRejectsConcurrentFileEdits() + { + var root = Directory.CreateTempSubdirectory(); + try + { + using var p = ProjectDirectory.New(); + var v = new Variable { RecipeID = p.DefaultRecipeId, Name = "A" }; + p.Data.Add(v); + for (int i = 0; i < 2; i++) + { + var flow = new Workflow { Name = $"Step{i}" }; + flow.Code = $"public class Extension_{flow.ID:N} {{ public void Run(PLCSharp.Models.GlobalModel m, PLCSharp.Core.Common.FlowModel f) {{ m.GetVariable(\"A\"); }} }}"; + p.Flows(v.RecipeID).Add(flow); + } + p.Save(root.FullName); + var original = Directory.GetFiles(root.FullName, "*", SearchOption.AllDirectories).ToDictionary(f => f, File.ReadAllBytes); + var changes = new ProjectChanges(); + JsonNode Preview() => changes.Execute(p, "previewRename", new() { ["id"] = v.ID.ToString(), ["newName"] = "B" }, false); + JsonNode Apply(JsonNode draft) => changes.Execute(p, "apply", new() { ["draftId"] = (string?)draft["DraftId"] }, true, _ => true); + var saved = Apply(Preview()); + Assert.Equal("saved", (string?)saved["Status"]); + Assert.Equal("B", v.Name); + Assert.Equal(3, original.Count(kv => !kv.Value.SequenceEqual(File.ReadAllBytes(kv.Key)))); + var undo = changes.Execute(p, "previewUndo", new() { ["draftId"] = (string?)saved["DraftId"] }, false); + Assert.Equal("saved", (string?)Apply(undo)["Status"]); + Assert.Equal("A", v.Name); + Assert.All(original, kv => Assert.Equal(kv.Value, File.ReadAllBytes(kv.Key))); + var stale = Preview(); + var script = original.Keys.First(f => f.EndsWith(".cs")); + File.AppendAllText(script, "// external"); + Assert.ThrowsAny(() => Apply(stale)); + Assert.Equal("A", v.Name); + Assert.All(original.Where(kv => kv.Key != script), kv => Assert.Equal(kv.Value, File.ReadAllBytes(kv.Key))); + } + finally { root.Delete(true); } + } +} +