From f4dee92233bbd82e35547eee3758dd33337287df Mon Sep 17 00:00:00 2001 From: wanglei Date: Sat, 5 Dec 2026 21:30:05 +0800 Subject: [PATCH] Track live script edits and verify cancel and save with real WPF dialogs --- .../VVMs/Workflows/CustomTextEditor.cs | 37 +++++------- README.md | 8 +++ Tests/mcp_script_dialog_smoke.py | 60 +++++++++++++++++++ 3 files changed, 83 insertions(+), 22 deletions(-) create mode 100644 Tests/mcp_script_dialog_smoke.py diff --git a/PLCSharpWpf/VVMs/Workflows/CustomTextEditor.cs b/PLCSharpWpf/VVMs/Workflows/CustomTextEditor.cs index cbba50e..890e0f6 100644 --- a/PLCSharpWpf/VVMs/Workflows/CustomTextEditor.cs +++ b/PLCSharpWpf/VVMs/Workflows/CustomTextEditor.cs @@ -20,10 +20,10 @@ namespace PLCSharp.VVMs.Workflows /// public class CustomTextEditor : RoslynCodeEditor { - private static Document _document; + private Document _document; private RoslynHost _host; - private string _pendingText; + /// /// 最小/最大字体大小 @@ -54,6 +54,11 @@ namespace PLCSharp.VVMs.Workflows TextArea.MouseWheel += TextArea_MouseWheel; ICSharpCode.AvalonEdit.Search.SearchPanel.Install(this); DataContextChanged += OnDataContextChanged; + TextChanged += (_, _) => + { + if (_document != null && Document != null && Text != Document.Text) + SetCurrentValue(TextProperty, Document.Text); + }; TextArea.Caret.PositionChanged += CaretOnPositionChanged; Loaded += (s, e) => SetValue(System.Windows.Controls.Control.FontSizeProperty, FontSize); } @@ -93,6 +98,7 @@ namespace PLCSharp.VVMs.Workflows { try { + _document = null; var workingDirectory = Directory.GetCurrentDirectory(); _host = new CustomRoslynHost(additionalAssemblies: @@ -114,13 +120,8 @@ namespace PLCSharp.VVMs.Workflows _document = _host.GetDocument(documentId); - // 如果有初始化前暂存的文本,现在应用 - if (_pendingText != null && Document != null) - { - Document.Text = _pendingText; - Text = _pendingText; - _pendingText = null; - } + if (Document != null && Document.Text != (Text ?? "")) + Document.Text = Text ?? ""; } // 原有的代码 catch (Exception) { @@ -247,14 +248,14 @@ namespace PLCSharp.VVMs.Workflows { try { - var textDocument = _document.WithText(SourceText.From(Document.Text)); + var original = Document.Text; + var textDocument = _document.WithText(SourceText.From(original)); var formatDoc = await Formatter.FormatAsync(textDocument); var text = await formatDoc.GetTextAsync(); - Document.Text = text.ToString(); - Text = Document.Text; + if (Document.Text == original) Document.Text = text.ToString(); } catch { @@ -271,7 +272,6 @@ namespace PLCSharp.VVMs.Workflows var offset = CaretOffset; Document.Insert(offset, str); CaretOffset = offset + str.Length; - Text = Document.Text; } // @@ -318,15 +318,8 @@ namespace PLCSharp.VVMs.Workflows var target = (CustomTextEditor)obj; var newValue = (args.NewValue ?? "").ToString(); - if (target.Document != null) - { + if (target.Document != null && target.Document.Text != newValue) target.Document.Text = newValue; - } - else - { - // Document 尚未初始化,暂存值,初始化后应用 - target._pendingText = newValue; - } } } @@ -363,4 +356,4 @@ namespace PLCSharp.VVMs.Workflows return []; } } -} \ No newline at end of file +} diff --git a/README.md b/README.md index cddacbd..2aeb283 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,14 @@ 例如,向 AI 提问:“找出默认配方中引用‘计数’的工作流,列出文件和行号,再预览将变量备注改为‘累计完成数量’。” 服务按对象 ID 和配方定位,使用 Roslyn 分析 `GetVariable`、`GetTask` 和对象名称相等比较。动态名称会标为待核对。首版支持修改配方、工作流、用户变量和系统变量的备注。应用草案时会核对预览版本。 +### 修改工作流脚本 + +让 AI 先调用 `get_object` 读取工作流,再把该工作流的 ID 和完整 C# 源码传给 `preview_workflow_script`。返回值包含逐行差异、编译诊断和草案 ID。Roslyn 在内存中编译并校验 `Extension_<工作流ID的32位十六进制>` 的同步入口 `public void Run(GlobalModel, FlowModel)`。有编译错误的草案不能保存。 + +客户端以 `--allow-write` 启动后,可调用 `apply_changes` 请求保存。编辑器已打开时由编辑器显示 WPF 弹窗;离线时由本机 MCP 服务显示相同的弹窗,需要交互式 Windows 桌面。点击「确认保存」只写入预览中的脚本;点击「取消」或关闭窗口会拒绝草案。文件或编辑器文本变化后需要重新预览。运行新脚本仍使用原有的工作流编译和运行入口。 + +交互验收可运行 `python Tests/mcp_script_dialog_smoke.py <可移植验收样例目录>`,依次在两个弹窗中取消和确认。测试使用样例副本,验证错误诊断、编译结果、实际写入文件和重开后的变量引用。 + ## 界面展示 ![界面 1](images/screenshot-1.png) diff --git a/Tests/mcp_script_dialog_smoke.py b/Tests/mcp_script_dialog_smoke.py new file mode 100644 index 0000000..bb9bce7 --- /dev/null +++ b/Tests/mcp_script_dialog_smoke.py @@ -0,0 +1,60 @@ +"""Interactive acceptance test. Click Cancel in the first WPF dialog and Confirm Save in the second.""" +from pathlib import Path +import shutil +import sys +import tempfile + +from mcp_smoke import Client + + +def verify(exe, sample): + with tempfile.TemporaryDirectory() as folder: + project = Path(folder) / "脚本验收副本" + shutil.copytree(sample, project) + client = Client(exe, project, "--allow-write") + try: + recipe = client.call("get_project_summary")["DefaultRecipeId"] + flow, = client.call("list_objects", kind="Workflows", recipeId=recipe)["items"] + flow_id = flow["id"] + script = next(project.rglob("*.cs")) + before = {p: p.read_bytes() for p in project.rglob("*") if p.is_file()} + source = (f'using PLCSharp.Models;\nusing PLCSharp.Core.Common;\n\n' + f'public class Extension_{flow_id.replace("-", "")}\n{{\n' + ' public void Run(GlobalModel model, FlowModel flow)\n {\n' + ' _ = model.GetVariable("计数");\n }\n}\n') + def preview(code): + return client.call("preview_workflow_script", id=flow_id, code=code) + + invalid = preview(source.replace("GetVariable", "MissingLookup")) + assert invalid["Status"] == "invalid" and not invalid["Review"]["Compiled"] + assert any(d["Code"] == "CS1061" and d["Line"] == 8 for d in invalid["Review"]["Diagnostics"]) + refused = client.request("tools/call", {"name": "apply_changes", "arguments": {"draftId": invalid["DraftId"]}}) + assert refused["isError"] + for expected in ("rejected", "saved"): + draft = preview(source) + assert draft["Review"]["Compiled"] and draft["Before"] == "// portability fixture" + assert '- // portability fixture' in draft["Review"]["Diff"] + assert all(p.read_bytes() == old for p, old in before.items()) + print(f'Awaiting WPF: {expected}', flush=True) + result = client.call("apply_changes", draftId=draft["DraftId"]) + print("WPF result:", result["Status"], flush=True) + assert result["Status"] == expected, (expected, result["Status"]) + assert client.call("get_change_status", draftId=draft["DraftId"])["Status"] == expected + assert [p for p, old in before.items() if p.read_bytes() != old] == [script] + assert script.read_bytes() == source.encode("utf-8") + finally: + client.close() + reopened = Client(exe, project) + try: + assert reopened.call("get_object", kind="Workflows", id=flow_id)["Code"] == source + variable, = reopened.call("list_objects", kind="Variables", recipeId=recipe)["items"] + hit, = reopened.call("find_references", kind="Variables", id=variable["id"])["hits"] + assert (hit["line"], hit["confidence"]) == (8, "confirmed") + finally: + reopened.close() + print("PASS: invalid code blocked, WPF rejected then saved, only .cs changed, reopened and resolved reference.") + + +if __name__ == "__main__": + verify(*sys.argv[1:]) +