Apply and undo reviewed workflow renames through MCP and WPF
This commit is contained in:
parent
2d4805a777
commit
ea414f488e
@ -28,7 +28,7 @@ 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 "previewRename" or "previewUndo" or "apply" or "status")
|
||||
if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" 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();
|
||||
|
||||
@ -7,10 +7,13 @@ namespace PLCSharp.Mcp;
|
||||
[McpServerToolType]
|
||||
internal sealed class ProjectTools(ProjectGateway gateway)
|
||||
{
|
||||
[McpServerTool(Name = "preview_workflow_rename"), Description("Preview renaming a workflow by ID in its recipe. Compile rewritten callers and list dynamic or uncertain references for review.")]
|
||||
public string PreviewWorkflowRename(string id, string newName) => gateway.Call("previewWorkflowRename", new() { ["id"] = id, ["newName"] = newName });
|
||||
|
||||
[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.")]
|
||||
[McpServerTool(Name = "preview_undo"), Description("Preview reversal of a saved variable or workflow 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.")]
|
||||
|
||||
@ -32,7 +32,7 @@ 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 "previewRename" or "previewUndo" or "apply" or "status")
|
||||
if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewUndo" or "apply" or "status")
|
||||
{
|
||||
if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy))
|
||||
throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。");
|
||||
@ -44,7 +44,7 @@ public partial class GlobalModel
|
||||
"应用 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 &&
|
||||
if (accepted && change.Rename is { Kind: "Variables" } 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("编辑器变量列表存在更改,请先保存并重新预览。");
|
||||
|
||||
@ -26,20 +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")
|
||||
if (operation is "previewRename" or "previewWorkflowRename" or "previewUndo")
|
||||
{
|
||||
ProjectRename plan;
|
||||
if (operation == "previewRename")
|
||||
if (operation == "previewWorkflowRename")
|
||||
plan = project.PlanWorkflowRename(Guid.Parse((string)args["id"]), (string)args["newName"]);
|
||||
else 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。");
|
||||
throw new ArgumentException("需要当前会话中已保存且尚未撤销的重命名 ID。");
|
||||
plan = project.PlanUndo(saved.DraftId, saved.Rename);
|
||||
}
|
||||
return Remember(new(Guid.NewGuid(), project.Id, "Variables", plan.ObjectId, plan.RecipeId, plan.OldName,
|
||||
ProjectDirectory.VariablesPath, plan.OldName, plan.NewName, project.Revision(ProjectDirectory.VariablesPath),
|
||||
return Remember(new(Guid.NewGuid(), project.Id, plan.Kind, plan.ObjectId, plan.RecipeId, plan.OldName,
|
||||
plan.MetadataPath, plan.OldName, plan.NewName, project.Revision(plan.MetadataPath),
|
||||
plan.Compiled ? "pending" : "invalid", Rename: plan));
|
||||
}
|
||||
if (operation == "previewScript")
|
||||
|
||||
@ -91,36 +91,47 @@ public sealed partial class ProjectDirectory
|
||||
}
|
||||
internal ProjectRename PlanUndo(Guid operationId, ProjectRename saved)
|
||||
{
|
||||
if (saved.SavedScope != RenameScope(saved.RecipeId) || saved.SavedMetadata != baseline[VariablesPath])
|
||||
throw new ProjectConflictException("保存后配方脚本或变量文件已改变,无法安全撤销。");
|
||||
CheckVariableName(saved.RecipeId, saved.ObjectId, saved.NewName, saved.OldName);
|
||||
if (saved.SavedScope != RenameScope(saved.RecipeId) || saved.SavedMetadata != baseline[saved.MetadataPath])
|
||||
throw new ProjectConflictException("保存后配方脚本或名称文件已改变,无法安全撤销。");
|
||||
CheckName(saved, 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.ObjectId, saved.RecipeId, saved.NewName, saved.OldName, inverse,
|
||||
saved.ManualReferences, new JsonArray()) { UndoOf = operationId, Scope = saved.SavedScope,
|
||||
saved.ManualReferences, new JsonArray()) { Kind = saved.Kind, UndoOf = operationId, Scope = saved.SavedScope,
|
||||
OriginalMetadata = saved.SavedMetadata, SavedMetadata = saved.OriginalMetadata };
|
||||
}
|
||||
|
||||
private void CheckName(ProjectRename plan, string before, string after)
|
||||
{
|
||||
if (plan.Kind == "Workflows") CheckWorkflowName(plan.RecipeId, plan.ObjectId, before, after);
|
||||
else CheckVariableName(plan.RecipeId, plan.ObjectId, before, after);
|
||||
}
|
||||
|
||||
internal void ApplyRename(ProjectRename plan)
|
||||
{
|
||||
lock (Data.Sync)
|
||||
{
|
||||
CheckVariableName(plan.RecipeId, plan.ObjectId, plan.OldName, plan.NewName);
|
||||
if (RenameScope(plan.RecipeId) != plan.Scope || baseline[VariablesPath] != plan.OriginalMetadata)
|
||||
CheckName(plan, plan.OldName, plan.NewName);
|
||||
if (RenameScope(plan.RecipeId) != plan.Scope || baseline[plan.MetadataPath] != plan.OriginalMetadata)
|
||||
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.ObjectId);
|
||||
if ((string)row["Name"] != plan.OldName)
|
||||
throw new ProjectConflictException("变量名有未保存的编辑,请先保存或还原。");
|
||||
row["Name"] = plan.NewName;
|
||||
files[VariablesPath] = plan.UndoOf.HasValue ? plan.SavedMetadata : Serialize(variables);
|
||||
bool workflowRename = plan.Kind == "Workflows";
|
||||
var recipePath = RecipePath(plan.RecipeId);
|
||||
var metadata = JsonNode.Parse(files[plan.MetadataPath]);
|
||||
var rows = metadata[workflowRename ? "workflows" : "Variables"].AsArray();
|
||||
var row = rows.Single(v => Guid.Parse((string)v[workflowRename ? "id" : "ID"]) == plan.ObjectId);
|
||||
var field = workflowRename ? "name" : "Name";
|
||||
if ((string)row[field] != plan.OldName)
|
||||
throw new ProjectConflictException("名称有未保存的编辑,请先保存或还原。");
|
||||
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)))
|
||||
var persisted = JsonNode.Parse(files[recipePath])["workflows"].AsArray()
|
||||
.ToDictionary(w => Guid.Parse((string)w["id"]), w => (string)w["name"]);
|
||||
if (flows.Count != persisted.Count || flows.Any(w => !persisted.TryGetValue(w.ID, out var name) || w.Name != name))
|
||||
throw new ProjectConflictException("请先保存工作流列表。");
|
||||
var scope = new List<string> { VariablesPath, recipePath, "project.json" };
|
||||
row[field] = plan.NewName;
|
||||
files[plan.MetadataPath] = plan.UndoOf.HasValue ? plan.SavedMetadata : Serialize(metadata);
|
||||
var scope = new List<string> { recipePath, "project.json" };
|
||||
if (!workflowRename) scope.Add(VariablesPath);
|
||||
foreach (var flow in flows)
|
||||
{
|
||||
var path = ScriptPath(plan.RecipeId, flow.ID);
|
||||
@ -137,25 +148,33 @@ public sealed partial class ProjectDirectory
|
||||
|
||||
// Hold each affected workflow's execution gate through the single multi-file commit.
|
||||
var updates = plan.Scripts.Select(s => (Flow: flows.Single(w => w.ID == s.Id), s.Before, s.After)).ToArray();
|
||||
var targetFlow = workflowRename ? flows.Single(w => w.ID == plan.ObjectId) : null;
|
||||
if (workflowRename && updates.All(edit => edit.Flow != targetFlow))
|
||||
updates = [.. updates, (targetFlow, targetFlow.Code ?? "", targetFlow.Code ?? "")];
|
||||
PLCSharp.VVMs.Workflows.Workflow.SaveReviewedBatch(updates, () =>
|
||||
{
|
||||
using var transaction = Data.Database.BeginTransaction();
|
||||
if (Data.Variables.Where(v => v.ID == plan.ObjectId && v.Name == plan.OldName)
|
||||
using var transaction = workflowRename ? null : Data.Database.BeginTransaction();
|
||||
if (!workflowRename && Data.Variables.Where(v => v.ID == plan.ObjectId && v.Name == plan.OldName)
|
||||
.ExecuteUpdate(s => s.SetProperty(v => v.Name, plan.NewName)) != 1)
|
||||
throw new ProjectConflictException("变量已发生变化。");
|
||||
try { WriteFiles(Root, files, scope.ToArray(), transaction.Commit); }
|
||||
try { WriteFiles(Root, files, scope.ToArray(), transaction == null ? null : transaction.Commit); }
|
||||
catch (IOException) when (scope.Any(path => !File.Exists(ProjectFile(Root, path)) ||
|
||||
File.ReadAllText(ProjectFile(Root, path)) != baseline[path]))
|
||||
{
|
||||
throw new ProjectConflictException("工程文件已从外部修改,请重新打开并预览。");
|
||||
}
|
||||
if (workflowRename)
|
||||
{
|
||||
targetFlow.SetReviewedName(plan.NewName);
|
||||
return;
|
||||
}
|
||||
configuration[VariablesPath] = files[VariablesPath];
|
||||
var variable = Data.Variables.Local.Single(v => v.ID == plan.ObjectId);
|
||||
variable.Name = plan.NewName;
|
||||
Data.Entry(variable).Property(v => v.Name).OriginalValue = plan.NewName;
|
||||
});
|
||||
plan.SavedScope = RenameScope(plan.RecipeId);
|
||||
plan.SavedMetadata = files[VariablesPath];
|
||||
plan.SavedMetadata = files[plan.MetadataPath];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -11,7 +11,8 @@ public partial class ScriptReviewWindow : Window
|
||||
InitializeComponent();
|
||||
if (change.Rename is { } rename)
|
||||
{
|
||||
Title = rename.UndoOf.HasValue ? "确认撤销变量重命名" : "确认变量重命名";
|
||||
var subject = rename.Kind == "Workflows" ? "工作流" : "变量";
|
||||
Title = $"确认{(rename.UndoOf.HasValue ? "撤销" : "")}{subject}重命名";
|
||||
WorkflowTitle.Text = $"{rename.OldName} → {rename.NewName}";
|
||||
Location.Text = System.IO.Path.Combine(root, change.Path);
|
||||
CheckResult.Text = $"已通过编译的工作流:{rename.Scripts.Count},需人工核对的引用:{rename.ManualReferences.Count}";
|
||||
|
||||
@ -45,6 +45,8 @@ namespace PLCSharp.VVMs.Workflows
|
||||
}
|
||||
}
|
||||
|
||||
internal void SetReviewedName(string value) => SetProperty(ref _Name, value, nameof(Name));
|
||||
|
||||
private string _Prompt;
|
||||
|
||||
/// <summary>
|
||||
@ -343,7 +345,8 @@ namespace PLCSharp.VVMs.Workflows
|
||||
if ((flow.Code ?? "") != before) throw new ProjectConflictException("编辑器内的脚本已更改,请重新预览。");
|
||||
}
|
||||
save();
|
||||
foreach (var (flow, _, after) in ordered) flow.Code = after;
|
||||
foreach (var (flow, before, after) in ordered)
|
||||
if (before != after) flow.Code = after;
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
65
Tests/PLCSharp.Tests/WorkflowRenameTests.cs
Normal file
65
Tests/PLCSharp.Tests/WorkflowRenameTests.cs
Normal file
@ -0,0 +1,65 @@
|
||||
using PLCSharp.Models;
|
||||
using PLCSharp.VVMs.Workflows;
|
||||
using System.IO;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace PLCSharp.Tests;
|
||||
|
||||
public class WorkflowRenameTests
|
||||
{
|
||||
[Fact]
|
||||
public void RenameRewritesCallersAndRestoresRecipeWithoutChangingIds()
|
||||
{
|
||||
var root = Directory.CreateTempSubdirectory();
|
||||
try
|
||||
{
|
||||
using var project = ProjectDirectory.New();
|
||||
var target = new Workflow { RecipeID = project.DefaultRecipeId, Name = "搬运" };
|
||||
var caller = new Workflow { RecipeID = target.RecipeID, Name = "调度" };
|
||||
caller.Code = $$"""
|
||||
using System.Linq;
|
||||
using PLCSharp.Models;
|
||||
using PLCSharp.Core.Common;
|
||||
public class Extension_{{caller.ID:N}} {
|
||||
public void Run(GlobalModel model, FlowModel flow) {
|
||||
const string label = "搬运";
|
||||
_ = model.GetTask(label);
|
||||
_ = model.WorkflowsModel.Workflows.FirstOrDefault(w => w.Name == "搬运");
|
||||
_ = model.GetTask(flow.Step.ToString());
|
||||
_ = model.GetVariable("搬运");
|
||||
}
|
||||
}
|
||||
""";
|
||||
project.Flows(target.RecipeID).Add(target);
|
||||
project.Flows(target.RecipeID).Add(caller);
|
||||
project.Save(root.FullName);
|
||||
var changes = new ProjectChanges();
|
||||
JsonNode Preview(string name) => changes.Execute(project, "previewWorkflowRename",
|
||||
new() { ["id"] = target.ID.ToString(), ["newName"] = name }, false);
|
||||
JsonNode Apply(JsonNode draft) => changes.Execute(project, "apply",
|
||||
new() { ["draftId"] = (string?)draft["DraftId"] }, true, _ => true);
|
||||
Assert.ThrowsAny<IOException>(() => Preview("调度"));
|
||||
var originalCode = caller.Code;
|
||||
var draft = Preview("送件");
|
||||
var plan = draft["Rename"]!;
|
||||
Assert.True((bool)plan["Compiled"]!);
|
||||
Assert.Equal("dynamic", (string?)Assert.Single(plan["ManualReferences"]!.AsArray())!["confidence"]);
|
||||
Assert.Equal(originalCode, caller.Code);
|
||||
var saved = Apply(draft);
|
||||
Assert.Contains("GetTask(\"送件\")", caller.Code);
|
||||
Assert.Contains("w.Name == \"送件\"", caller.Code);
|
||||
Assert.Contains("GetVariable(\"搬运\")", caller.Code);
|
||||
using (var reopened = ProjectDirectory.Open(root.FullName))
|
||||
Assert.Equal("送件", reopened.Flows(target.RecipeID).Single(w => w.ID == target.ID).Name);
|
||||
var undo = changes.Execute(project, "previewUndo", new() { ["draftId"] = (string?)saved["DraftId"] }, false);
|
||||
Apply(undo);
|
||||
Assert.Equal("搬运", target.Name);
|
||||
Assert.Equal(originalCode, caller.Code);
|
||||
var stale = Preview("送件");
|
||||
caller.Name = "送件";
|
||||
Assert.ThrowsAny<IOException>(() => Apply(stale));
|
||||
Assert.Equal("搬运", target.Name);
|
||||
}
|
||||
finally { root.Delete(true); }
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user