Review, apply and undo point names with their scoped matrix and script references

This commit is contained in:
wanglei 2026-12-05 21:49:35 +08:00
parent 779932f7a2
commit c4f406e975
8 changed files with 245 additions and 16 deletions

View File

@ -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 "previewWorkflowRename" or "previewUndo" or "apply" or "status")
if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" 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,13 +7,17 @@ namespace PLCSharp.Mcp;
[McpServerToolType]
internal sealed class ProjectTools(ProjectGateway gateway)
{
[McpServerTool(Name = "preview_point_rename"), Description("Preview renaming an AxisPoints or RobotPoints ID, including bound workflow and matrix references. Review uncertain and dynamic hits before applying.")]
public string PreviewPointRename(string kind, string id, string newName) =>
gateway.Call("previewPointRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName });
[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 or workflow rename from this session. Apply the new draft ID to confirm undo.")]
[McpServerTool(Name = "preview_undo"), Description("Preview reversal of a saved variable, point 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.")]

View File

@ -32,11 +32,12 @@ 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 "previewWorkflowRename" or "previewUndo" or "apply" or "status")
if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" 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 =>
Action updatePointView = null;
var resultChange = 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)
@ -48,8 +49,22 @@ public partial class GlobalModel
(!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("编辑器变量列表存在更改,请先保存并重新预览。");
if (accepted && change.Rename is { IsPoint: true } point && CurrentRecipe.ID == point.RecipeId)
{
if (point.Kind == "AxisPoints")
updatePointView = Project.PreparePointView(point, ControllersModel.AxisPoints, ControllersModel.Matrices);
else
{
var owner = Project.Data.RobotPoints.Single(p => p.ID == point.ObjectId).RobotID;
var robot = RobotModel.Robots.SingleOrDefault(r => r.ID == owner);
if (robot != null)
updatePointView = Project.PreparePointView(point, robot.Points, robot.RobotMatrices);
}
}
return accepted;
});
if ((string)resultChange["Status"] == "saved") updatePointView?.Invoke();
return resultChange;
}
var result = ProjectInspection.Query(Project, operation, args);
if (operation == "summary")

View File

@ -0,0 +1,128 @@
using Microsoft.EntityFrameworkCore;
using PLCSharp.VVMs.MotionController;
using PLCSharp.VVMs.Robots;
using System.Text.Json.Nodes;
namespace PLCSharp.Models;
public sealed record PointField(string Table, Guid Id, string Field)
{
internal JsonNode Row(JsonNode document) => document[Table].AsArray()
.Single(row => Guid.Parse((string)row["ID"]) == Id);
internal Type EntityType => Table switch
{
"AxisPoints" => typeof(AxisPoint), "RobotPoints" => typeof(RobotPoint),
"Matrices" => typeof(Matrix), "RobotMatrices" => typeof(RobotMatrix),
_ => throw new ArgumentException("未知点位配置表。")
};
}
public sealed partial class ProjectDirectory
{
private static readonly string[] MatrixPointFields = ["StartName", "XEndName", "YEndName"];
internal ProjectRename PlanPointRename(string kind, Guid id, string newName)
{
if (kind is not ("AxisPoints" or "RobotPoints")) throw new ArgumentException("请选择 AxisPoints 或 RobotPoints。");
var document = JsonNode.Parse(baseline[ConfigPath("points")]);
var row = new PointField(kind, id, "Name").Row(document);
var recipe = Guid.Parse((string)row["RecipeID"]);
var oldName = (string)row["Name"];
if (string.IsNullOrWhiteSpace(newName)) throw new ArgumentException("请输入新点位名称。");
var plan = PlanReferences(kind, id, recipe, oldName, newName) with
{
MatrixReferences = MatrixLinks(kind, document, row, oldName),
RobotScope = kind == "RobotPoints" ? baseline[ConfigPath("hardware")] : null
};
ValidatePoint(plan, oldName, newName);
return plan;
}
private static List<PointField> MatrixLinks(string kind, JsonNode document, JsonNode point, string name)
{
var table = kind == "AxisPoints" ? "Matrices" : "RobotMatrices";
return (from matrix in document[table].AsArray()
where SamePointScope(point, matrix)
from field in MatrixPointFields
where (string)matrix[field] == name
select new PointField(table, Guid.Parse((string)matrix["ID"]), field)).ToList();
}
private static bool SamePointScope(JsonNode a, JsonNode b) =>
Guid.Parse((string)a["RecipeID"]) == Guid.Parse((string)b["RecipeID"]) &&
string.Equals((string)a["RobotID"], (string)b["RobotID"], StringComparison.OrdinalIgnoreCase);
private void ValidatePoint(ProjectRename plan, string before, string after)
{
if (string.IsNullOrWhiteSpace(before) || string.IsNullOrWhiteSpace(after) || after != after.Trim() || before == after)
throw new ArgumentException("请输入不同的新点位名称,首尾不能有空白。");
if (plan.RobotScope != null && baseline[ConfigPath("hardware")] != plan.RobotScope)
throw new ProjectConflictException("机器人配置已改变,请重新预览。");
var doc = JsonNode.Parse(baseline[plan.MetadataPath]);
var target = new PointField(plan.Kind, plan.ObjectId, "Name").Row(doc);
var points = doc[plan.Kind].AsArray().Where(p => SamePointScope(target, p)).ToList();
if ((string)target["Name"] != before || points.Count(p => (string)p["Name"] == before) != 1 ||
points.Any(p => (string)p["Name"] == after) || MatrixLinks(plan.Kind, doc, target, after).Count != 0 ||
!MatrixLinks(plan.Kind, doc, target, before).ToHashSet().SetEquals(plan.MatrixReferences))
throw new ProjectConflictException("点位名称或矩阵引用有冲突,请重新核对。");
}
private static IEnumerable<PointField> PointFields(ProjectRename plan) =>
plan.MatrixReferences.Prepend(new(plan.Kind, plan.ObjectId, "Name"));
private void WritePointFields(ProjectRename plan)
{
foreach (var f in PointFields(plan))
{
var entry = Data.Entry(Data.Find(f.EntityType, f.Id) ?? throw new ProjectConflictException("点位配置已删除。"));
if ((string)entry.Property(f.Field).CurrentValue != plan.OldName)
throw new ProjectConflictException("点位配置存在未保存的修改。");
// Table and column names come solely from the fixed project schema above.
string sql = $"UPDATE \"{f.Table}\" SET \"{f.Field}\" = {{0}} WHERE ID = {{1}} AND \"{f.Field}\" = {{2}}";
if (Data.Database.ExecuteSqlRaw(sql, plan.NewName, f.Id, plan.OldName) != 1)
throw new ProjectConflictException("点位或矩阵已改变,请重新预览。");
}
}
private void AcceptPointFields(ProjectRename plan)
{
foreach (var f in PointFields(plan))
{
var property = Data.Entry(Data.Find(f.EntityType, f.Id)).Property(f.Field);
property.CurrentValue = property.OriginalValue = plan.NewName;
}
}
// The editor displays detached copies. Validate displayed names and matrix links before writing,
// then update only the reviewed fields to preserve other UI edits.
internal Action PreparePointView(ProjectRename plan, IEnumerable<object> points, IEnumerable<object> matrices)
{
var live = points.Concat(matrices).Select(e => Data.Entry(e)).ToDictionary(
e => (e.Metadata.ClrType, (Guid)e.Property("ID").CurrentValue));
var point = new PointField(plan.Kind, plan.ObjectId, "Name");
var edits = PointFields(plan).ToList();
foreach (var (key, entry) in live)
{
if (key.Item1 == point.EntityType)
{
var name = (string)entry.Property("Name").CurrentValue;
if (key.Item2 != plan.ObjectId && (name == plan.NewName || name == plan.OldName))
throw new ProjectConflictException("编辑器点位列表存在重名,请先保存。");
continue;
}
foreach (string field in MatrixPointFields)
{
var value = (string)entry.Property(field).CurrentValue;
if (value == plan.NewName || (value == plan.OldName && !edits.Any(f => f.Id == key.Item2 && f.Field == field)))
throw new ProjectConflictException("编辑器矩阵引用存在更改,请先保存。");
}
}
var properties = edits.Select(f =>
{
if (!live.TryGetValue((f.EntityType, f.Id), out var entry) || (string)entry.Property(f.Field).CurrentValue != plan.OldName)
throw new ProjectConflictException("编辑器点位或矩阵引用已改变,请先保存。");
return entry.Property(f.Field);
}).ToList();
return () => properties.ForEach(p => p.CurrentValue = plan.NewName);
}
}

View File

@ -26,10 +26,12 @@ 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 "previewWorkflowRename" or "previewUndo")
if (operation is "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewUndo")
{
ProjectRename plan;
if (operation == "previewWorkflowRename")
if (operation == "previewPointRename")
plan = project.PlanPointRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"]);
else 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"]);

View File

@ -16,7 +16,16 @@ public sealed record ProjectRename(Guid ObjectId, Guid RecipeId, string OldName,
{
public string Kind { get; init; } = "Variables";
public Guid? VariableId => Kind == "Variables" ? ObjectId : null;
public string MetadataPath => Kind == "Workflows" ? $"recipes/{RecipeId:D}/recipe.json" : ProjectDirectory.VariablesPath;
public bool IsPoint => Kind is "AxisPoints" or "RobotPoints";
public string MetadataPath => PathFor(Kind, RecipeId);
internal static string PathFor(string kind, Guid recipe) => kind switch
{
"AxisPoints" or "RobotPoints" => "configuration/points.json",
"Workflows" => $"recipes/{recipe:D}/recipe.json",
_ => ProjectDirectory.VariablesPath
};
public List<PointField> MatrixReferences { get; init; } = [];
[JsonIgnore] internal string RobotScope { get; init; }
public bool Compiled => Scripts.All(s => s.Review.Compiled) && ScanDiagnostics.Count == 0;
[JsonIgnore] internal string Scope { get; init; }
[JsonIgnore] internal string OriginalMetadata { get; init; }
@ -87,7 +96,7 @@ public sealed partial class ProjectDirectory
WorkflowScriptReview.Create(flow.ID, flow.Code, next)));
}
return new(id, recipeId, oldName, newName, edits, manual, analysis["diagnostics"].AsArray())
{ Kind = kind, Scope = RenameScope(recipeId), OriginalMetadata = baseline[kind == "Workflows" ? RecipePath(recipeId) : VariablesPath] };
{ Kind = kind, Scope = RenameScope(recipeId), OriginalMetadata = baseline[ProjectRename.PathFor(kind, recipeId)] };
}
internal ProjectRename PlanUndo(Guid operationId, ProjectRename saved)
{
@ -97,13 +106,14 @@ public sealed partial class ProjectDirectory
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()) { Kind = saved.Kind, UndoOf = operationId, Scope = saved.SavedScope,
saved.ManualReferences, new JsonArray()) { Kind = saved.Kind, MatrixReferences = saved.MatrixReferences, RobotScope = saved.RobotScope, 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 if (plan.IsPoint) ValidatePoint(plan, before, after);
else CheckVariableName(plan.RecipeId, plan.ObjectId, before, after);
}
@ -118,7 +128,7 @@ public sealed partial class ProjectDirectory
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 rows = metadata[workflowRename ? "workflows" : plan.Kind].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)
@ -129,9 +139,12 @@ public sealed partial class ProjectDirectory
if (flows.Count != persisted.Count || flows.Any(w => !persisted.TryGetValue(w.ID, out var name) || w.Name != name))
throw new ProjectConflictException("请先保存工作流列表。");
row[field] = plan.NewName;
foreach (var reference in plan.MatrixReferences)
reference.Row(metadata)[reference.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);
if (!workflowRename) scope.Add(plan.MetadataPath);
if (plan.Kind == "RobotPoints") scope.Add(ConfigPath("hardware"));
foreach (var flow in flows)
{
var path = ScriptPath(plan.RecipeId, flow.ID);
@ -154,7 +167,8 @@ public sealed partial class ProjectDirectory
PLCSharp.VVMs.Workflows.Workflow.SaveReviewedBatch(updates, () =>
{
using var transaction = workflowRename ? null : Data.Database.BeginTransaction();
if (!workflowRename && Data.Variables.Where(v => v.ID == plan.ObjectId && v.Name == plan.OldName)
if (plan.IsPoint) WritePointFields(plan);
if (plan.Kind == "Variables" && 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 == null ? null : transaction.Commit); }
@ -168,7 +182,12 @@ public sealed partial class ProjectDirectory
targetFlow.SetReviewedName(plan.NewName);
return;
}
configuration[VariablesPath] = files[VariablesPath];
configuration[plan.MetadataPath] = files[plan.MetadataPath];
if (plan.IsPoint)
{
AcceptPointFields(plan);
return;
}
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;

View File

@ -11,13 +11,14 @@ public partial class ScriptReviewWindow : Window
InitializeComponent();
if (change.Rename is { } rename)
{
var subject = rename.Kind == "Workflows" ? "工作流" : "变量";
var subject = rename.IsPoint ? "点位" : 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}";
CodeDiff.Text = string.Join("\n", rename.ManualReferences.Select(h =>
$"待核对 [{h["confidence"]}] {h["path"]}:{h["line"]} {h["expression"]}")
CodeDiff.Text = string.Join("\n", rename.MatrixReferences.Select(m => $"{m.Table}/{m.Id} · {m.Field}:{rename.OldName} → {rename.NewName}")
.Concat(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

View File

@ -0,0 +1,60 @@
using PLCSharp.Models;
using PLCSharp.VVMs.Robots;
using PLCSharp.VVMs.Workflows;
using System.IO;
namespace PLCSharp.Tests;
public class PointRenameTests
{
[Fact]
public void RobotReferencesAndMatrixEditsStayWithinTheOwningRobot()
{
var root = Directory.CreateTempSubdirectory();
try
{
using var p = ProjectDirectory.New();
var a = new Robot { Name = "A" };
var b = new Robot { Name = "B" };
var target = new RobotPoint { Name = "P1", RobotID = a.ID, RecipeID = p.DefaultRecipeId };
var other = new RobotPoint { Name = "P1", RobotID = b.ID, RecipeID = p.DefaultRecipeId };
var matrix = new RobotMatrix { RobotID = a.ID, RecipeID = p.DefaultRecipeId, XEndName = "P1" };
p.Data.AddRange(a, b, target, other, matrix);
p.Data.Save();
var caller = new Workflow { Name = "Caller", RecipeID = p.DefaultRecipeId };
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) {
model.GetRobot("A").RunPoint("P1");
model.GetRobot("B").RunPoint("P1");
model.GetRobot("A").Jog(cmd: "X+", dist: 10, pointName: "P1");
model.GetRobot("A").RunPoint(flow.Step.ToString());
model.GetRobot(flow.Step.ToString()).RunPoint("P1");
_ = model.GetRobot("A").Points.FirstOrDefault(p => p.Name == "P1");
}
}
""";
p.Flows(p.DefaultRecipeId).Add(caller);
p.Save(root.FullName);
var preview = p.PlanPointRename("RobotPoints", target.ID, "Pick");
Assert.True(preview.Compiled);
var output = Assert.Single(preview.Scripts).After;
Assert.Contains("GetRobot(\"A\").RunPoint(\"Pick\")", output);
Assert.Contains("GetRobot(\"B\").RunPoint(\"P1\")", output);
Assert.Contains("pointName: \"Pick\"", output);
Assert.Contains("p.Name == \"Pick\"", output);
Assert.Equal(new[] { "dynamic", "possible" }, preview.ManualReferences.Select(h => (string?)h!["confidence"]));
p.ApplyRename(preview);
Assert.Equal("Pick", target.Name);
Assert.Equal("Pick", matrix.XEndName);
Assert.Equal("P1", other.Name);
p.ApplyRename(p.PlanUndo(Guid.NewGuid(), preview));
Assert.Equal("P1", matrix.XEndName);
Assert.Equal("P1", target.Name);
}
finally { root.Delete(true); }
}
}