diff --git a/PLCSharpWpf/Models/GlobalModel.Project.cs b/PLCSharpWpf/Models/GlobalModel.Project.cs index ec1dbc0..c6fe784 100644 --- a/PLCSharpWpf/Models/GlobalModel.Project.cs +++ b/PLCSharpWpf/Models/GlobalModel.Project.cs @@ -36,10 +36,20 @@ public partial class GlobalModel { if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy)) throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。"); - 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); + return aiChanges.Execute(Project, operation, args, true, change => + { + bool accepted = 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; + if (accepted && (ModeState.State.Execute || WorkflowsModel.IsBusy)) + throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。"); + if (accepted && change.Rename is { } 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("编辑器变量列表存在更改,请先保存并重新预览。"); + return accepted; + }); } var result = ProjectInspection.Query(Project, operation, args); if (operation == "summary") diff --git a/PLCSharpWpf/Models/ProjectDirectory.cs b/PLCSharpWpf/Models/ProjectDirectory.cs index 212e098..d3d8fd0 100644 --- a/PLCSharpWpf/Models/ProjectDirectory.cs +++ b/PLCSharpWpf/Models/ProjectDirectory.cs @@ -210,7 +210,7 @@ public sealed partial class ProjectDirectory : IDisposable WriteFiles(root, Files()); } - private void WriteFiles(string root, Dictionary files, string[] scope = null) + private void WriteFiles(string root, Dictionary files, string[] scope = null, Action finalize = null) { Directory.CreateDirectory(root); // Serialize writers and detect edits made after this instance opened the project. @@ -262,6 +262,7 @@ public sealed partial class ProjectDirectory : IDisposable installed.Add(target); } } + finalize?.Invoke(); } catch { diff --git a/PLCSharpWpf/Models/VariableRename.cs b/PLCSharpWpf/Models/VariableRename.cs index acebebd..3a13a3c 100644 --- a/PLCSharpWpf/Models/VariableRename.cs +++ b/PLCSharpWpf/Models/VariableRename.cs @@ -96,7 +96,13 @@ public sealed partial class ProjectDirectory 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 flow in flows) + { + var path = ScriptPath(plan.RecipeId, flow.ID); + if (files[path] != (flow.Code ?? "")) + throw new ProjectConflictException($"工作流 {flow.Name} 有未保存的编辑,请保存后重新预览。"); + scope.Add(path); + } foreach (var script in plan.Scripts) { if (files[script.Path] != script.Before) @@ -105,31 +111,24 @@ public sealed partial class ProjectDirectory } // Hold each affected workflow's execution gate through the single multi-file commit. - void Commit(int index) + var updates = plan.Scripts.Select(s => (Flow: flows.Single(w => w.ID == s.Id), s.Before, s.After)).ToArray(); + PLCSharp.VVMs.Workflows.Workflow.SaveReviewedBatch(updates, () => { - 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()); } + try { WriteFiles(Root, files, scope.ToArray(), transaction.Commit); } 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/Workflows/Workflow.cs b/PLCSharpWpf/VVMs/Workflows/Workflow.cs index a7b983d..70dffd5 100644 --- a/PLCSharpWpf/VVMs/Workflows/Workflow.cs +++ b/PLCSharpWpf/VVMs/Workflows/Workflow.cs @@ -326,14 +326,28 @@ namespace PLCSharp.VVMs.Workflows } } - internal void SaveReviewedCode(string before, string after, Action save) + internal void SaveReviewedCode(string before, string after, Action save) => + SaveReviewedBatch([(this, before, after)], save); + + internal static void SaveReviewedBatch((Workflow Flow, string Before, string After)[] edits, Action save) { - lock (_executionGate) + var ordered = edits.OrderBy(e => e.Flow.ID).ToArray(); + var locked = 0; + try { - if (IsRuning || _activeRun != null) throw new InvalidOperationException("请先停止工作流。"); - if ((Code ?? "") != before) throw new ProjectConflictException("编辑器内的脚本已更改,请重新预览。"); + foreach (var (flow, before, _) in ordered) + { + Monitor.Enter(flow._executionGate); + locked++; + if (flow.IsRuning || flow._activeRun != null) throw new InvalidOperationException("请先停止工作流。"); + if ((flow.Code ?? "") != before) throw new ProjectConflictException("编辑器内的脚本已更改,请重新预览。"); + } save(); - Code = after; + foreach (var (flow, _, after) in ordered) flow.Code = after; + } + finally + { + while (locked > 0) Monitor.Exit(ordered[--locked].Flow._executionGate); } } diff --git a/README.md b/README.md index 2aeb283..725d171 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,12 @@ 交互验收可运行 `python Tests/mcp_script_dialog_smoke.py <可移植验收样例目录>`,依次在两个弹窗中取消和确认。测试使用样例副本,验证错误诊断、编译结果、实际写入文件和重开后的变量引用。 +### 跨对象重命名与撤销 + +调用 `preview_variable_rename(id, newName)` 可重命名一个配方用户变量。预览返回受影响工作流的代码差异、编译诊断和 `ManualReferences` 核对清单,包含脚本路径、行列和原表达式。自动替换覆盖同一配方中能够绑定的 `GetVariable` 常量参数,以及直接查询变量集合时的名称相等比较。动态名称和不确定的匹配保留原文。 + +核对后将草案 ID 交给 `apply_changes`,在 WPF 弹窗确认后一起保存变量与脚本。要撤销,把**已保存的重命名草案 ID** 传给 `preview_undo`,再对返回的**撤销草案 ID** 调用 `apply_changes` 并确认。变量 ID 始终保留。撤销记录保存在处理本次请求的编辑器或离线 MCP 服务会话中,沿用最近 256 个草案的缓存;关闭会话后记录失效。变量文件或该配方的脚本发生冲突时会停止写入。 + ## 界面展示 ![界面 1](images/screenshot-1.png) diff --git a/Tests/mcp_rename_editor_smoke.py b/Tests/mcp_rename_editor_smoke.py new file mode 100644 index 0000000..5e55cf8 --- /dev/null +++ b/Tests/mcp_rename_editor_smoke.py @@ -0,0 +1,66 @@ +"""Prepare a portable sample copy, open it in PLCSharp and enable AI access, then run verify.""" +import argparse +import json +from pathlib import Path +import shutil + +from mcp_smoke import Client + + +def prepare(sample, directory): + shutil.copytree(sample, directory) + script, = directory.rglob("*.cs") + source = ( + "using PLCSharp.Models;\nusing PLCSharp.Core.Common;\n" + f"public class Extension_{script.stem.replace('-', '')} {{\n" + " public void Run(GlobalModel model, FlowModel flow) {\n" + ' _ = model.GetVariable("计数");\n' + ' _ = model.GetVariable(flow.Step.ToString());\n' + " }\n}\n" + ) + script.write_bytes(source.encode("utf-8")) + + +def verify(exe, directory): + before = {p: p.read_bytes() for p in directory.rglob("*") if p.is_file()} + client = Client(exe, directory, "--allow-write") + try: + summary = client.call("get_project_summary") + assert summary["source"] == "editor" + recipe = summary["DefaultRecipeId"] + var, = client.call("list_objects", kind="Variables", recipeId=recipe)["items"] + draft = client.call("preview_variable_rename", id=var["id"], newName="完成计数") + plan = draft["Rename"] + script, = plan["Scripts"] + manual, = plan["ManualReferences"] + assert draft["Status"] == "pending" and script["Review"]["Compiled"] + assert manual["confidence"] == "dynamic" and manual["line"] == 6 + assert 'GetVariable("完成计数")' in script["After"] and manual["expression"] in script["After"] + print(json.dumps({"source": summary["source"], "dynamic": manual, "compiled": True}, ensure_ascii=False), flush=True) + assert all(p.read_bytes() == old for p, old in before.items()) + saved = client.call("apply_changes", draftId=draft["DraftId"]) + assert saved["Status"] == "saved" + assert client.call("get_object", kind="Variables", id=var["id"])["Name"] == "完成计数" + assert client.call("get_object", kind="Workflows", id=script["Id"])["Code"] == script["After"] + assert {p for p, old in before.items() if p.read_bytes() != old} == { + directory / "configuration/variables.json", directory / script["Path"]} + undo = client.call("preview_undo", draftId=draft["DraftId"]) + assert undo["Rename"]["Compiled"] and undo["Rename"]["UndoOf"] == draft["DraftId"] + assert client.call("apply_changes", draftId=undo["DraftId"])["Status"] == "saved" + assert client.call("get_change_status", draftId=draft["DraftId"])["Status"] == "undone" + assert client.call("get_object", kind="Variables", id=var["id"])["Name"] == "计数" + assert client.call("get_object", kind="Workflows", id=script["Id"])["Code"] == script["Before"] + assert before == {p: p.read_bytes() for p in directory.rglob("*") if p.is_file()} + print("PASS: live editor rename, confirmation, undo and byte-for-byte restore.") + finally: + client.close() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=["prepare", "verify"]) + parser.add_argument("source", type=Path, help="Sample directory for prepare, MCP executable for verify") + parser.add_argument("project", type=Path) + args = parser.parse_args() + (prepare if args.mode == "prepare" else verify)(args.source, args.project) +