Apply variable renames and guarded inverse drafts across project files

This commit is contained in:
wanglei 2026-12-05 21:34:17 +08:00
parent 49fe9d599a
commit 058ba4fcae
8 changed files with 183 additions and 14 deletions

View File

@ -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();
}

View File

@ -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 });

View File

@ -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);

View File

@ -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<Guid, ProjectChange> 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<ProjectChange, bool> 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)

View File

@ -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<string, string>(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<string> { 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];
}
}
}

View File

@ -30,7 +30,8 @@ namespace PLCSharp.VVMs.GlobalVariables
/// <summary>
/// 变量名
/// </summary>
public string Name { get; set; }
public string Name { get => _name; set => SetProperty(ref _name, value); }
private string _name;
/// <summary>
/// 备注

View File

@ -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();
}

View File

@ -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<IOException>(() => 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); }
}
}