Check workflow analysis inputs and verify complete sample restoration
This commit is contained in:
parent
ace61e0171
commit
e5151ae9b7
@ -12,9 +12,9 @@ namespace PLCSharp.Models;
|
||||
public sealed record ProjectBatch(List<ProjectChange> Steps, List<CheckedFlow> Workflows, string[] ChangedFiles, Guid? UndoOf = null)
|
||||
{
|
||||
public bool Compiled => Steps.All(s => s.Status == "pending") && Workflows.All(f => f.Compiled);
|
||||
[JsonIgnore] internal Dictionary<string,string> From { get; init; }
|
||||
[JsonIgnore] internal Dictionary<string,string> To { get; init; }
|
||||
[JsonIgnore] internal Dictionary<string,byte[]> OriginalBytes { get; init; }
|
||||
[JsonIgnore] internal Dictionary<string, string> From { get; init; }
|
||||
[JsonIgnore] internal Dictionary<string, string> To { get; init; }
|
||||
[JsonIgnore] internal Dictionary<string, byte[]> OriginalBytes { get; init; }
|
||||
[JsonIgnore] internal List<ObjectEdit> Rows { get; init; }
|
||||
}
|
||||
|
||||
@ -23,6 +23,7 @@ public sealed partial class ProjectDirectory
|
||||
internal ProjectBatch PlanBatch(JsonArray operations)
|
||||
{
|
||||
if (operations == null || operations.Count == 0) throw new ArgumentException("批次不能为空。");
|
||||
CheckBatchScripts();
|
||||
var temp = Directory.CreateTempSubdirectory("plcsharp-preview-");
|
||||
try
|
||||
{
|
||||
@ -46,13 +47,13 @@ public sealed partial class ProjectDirectory
|
||||
obj[key] = aliases.TryGetValue(s[1..], out var id) ? id.ToString() : throw new ArgumentException($"未知批次对象 {s}");
|
||||
}
|
||||
Resolve(args, "id");
|
||||
foreach (string field in new[]{"RecipeID","RobotID","FuncID"}) Resolve(args["properties"]?.AsObject(), field);
|
||||
foreach (string field in new[] { "RecipeID", "RobotID", "FuncID" }) Resolve(args["properties"]?.AsObject(), field);
|
||||
var operation = (string)args["action"] == "rename" ? "previewObjectRename" : "previewObjectEdit";
|
||||
var result = preview.Execute(stage, operation, args, false);
|
||||
var draft = preview.PendingOrInvalid(Guid.Parse((string)result["DraftId"]));
|
||||
steps.Add(draft);
|
||||
if (draft.Status == "invalid") break;
|
||||
if ((string)args["alias"] is string alias && !aliases.TryAdd(alias,draft.ObjectId)) throw new ArgumentException("批次别名重复。");
|
||||
if ((string)args["alias"] is string alias && !aliases.TryAdd(alias, draft.ObjectId)) throw new ArgumentException("批次别名重复。");
|
||||
if (draft.Edit != null) stage.ApplyObjectEdit(draft.Edit);
|
||||
else stage.ApplyRename(draft.Rename);
|
||||
}
|
||||
@ -63,36 +64,41 @@ public sealed partial class ProjectDirectory
|
||||
{
|
||||
var old = before.GetValueOrDefault(key);
|
||||
var next = after.GetValueOrDefault(key);
|
||||
if (JsonNode.DeepEquals(old,next)) continue;
|
||||
rows.Add(new(old == null ? "create" : next == null ? "delete" : "update",key.Kind,key.Id,"",old,next,[],[],[],[]));
|
||||
if (JsonNode.DeepEquals(old, next)) continue;
|
||||
rows.Add(new(old == null ? "create" : next == null ? "delete" : "update", key.Kind, key.Id, "", old, next, [], [], [], []));
|
||||
}
|
||||
var flows = steps.SelectMany(s => s.Edit?.Workflows ?? s.Rename.Scripts.Select(f => new CheckedFlow(f.Id,f.Name,f.Path,f.Review.Compiled,f.Review.Diagnostics)).ToList())
|
||||
.GroupBy(f=>f.Id).Select(g=>g.Last()).ToList();
|
||||
var flows = steps.SelectMany(s => s.Edit?.Workflows ?? s.Rename.Scripts.Select(f => new CheckedFlow(f.Id, f.Name, f.Path, f.Review.Compiled, f.Review.Diagnostics)).ToList())
|
||||
.GroupBy(f => f.Id).Select(g => g.Last()).ToList();
|
||||
foreach (var flow in flows.ToArray())
|
||||
{
|
||||
if (after.GetValueOrDefault(("Workflows",flow.Id)) is not { } row) continue;
|
||||
if (after.GetValueOrDefault(("Workflows", flow.Id)) is not { } row) continue;
|
||||
var check = WorkflowScriptReview.Create(flow.Id, (string)row["Code"], (string)row["Code"]);
|
||||
flows[flows.IndexOf(flow)] = flow with { Compiled = check.Compiled, Diagnostics = check.Diagnostics };
|
||||
}
|
||||
return new(steps,flows,paths) { From = new(baseline), To = new(stage.baseline), Rows = rows,
|
||||
OriginalBytes = paths.Where(baseline.ContainsKey).ToDictionary(p=>p,p=>File.ReadAllBytes(ProjectFile(Root,p))) };
|
||||
return new(steps, flows, paths)
|
||||
{
|
||||
From = new(baseline),
|
||||
To = new(stage.baseline),
|
||||
Rows = rows,
|
||||
OriginalBytes = paths.Where(baseline.ContainsKey).ToDictionary(p => p, p => File.ReadAllBytes(ProjectFile(Root, p)))
|
||||
};
|
||||
}
|
||||
finally { temp.Delete(true); }
|
||||
}
|
||||
|
||||
private Dictionary<(string Kind, Guid Id),JsonObject> BatchRows()
|
||||
private Dictionary<(string Kind, Guid Id), JsonObject> BatchRows()
|
||||
{
|
||||
var rows = new Dictionary<(string,Guid),JsonObject>();
|
||||
var rows = new Dictionary<(string, Guid), JsonObject>();
|
||||
foreach (var recipe in Recipes)
|
||||
{
|
||||
rows.Add(("Recipes",recipe.ID),RecipeRow(recipe));
|
||||
foreach (var flow in Flows(recipe.ID)) rows.Add(("Workflows",flow.ID),FlowRow(flow));
|
||||
rows.Add(("Recipes", recipe.ID), RecipeRow(recipe));
|
||||
foreach (var flow in Flows(recipe.ID)) rows.Add(("Workflows", flow.ID), FlowRow(flow));
|
||||
}
|
||||
foreach (var (group,tables) in ProjectConfiguration.Groups)
|
||||
foreach (var (group, tables) in ProjectConfiguration.Groups)
|
||||
{
|
||||
var doc = JsonNode.Parse(configuration[ConfigPath(group)]);
|
||||
foreach (var table in tables)
|
||||
foreach (var row in doc[table].AsArray()) rows.Add((table,Guid.Parse((string)row["ID"])),row.AsObject());
|
||||
foreach (var row in doc[table].AsArray()) rows.Add((table, Guid.Parse((string)row["ID"])), row.AsObject());
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
@ -107,22 +113,41 @@ public sealed partial class ProjectDirectory
|
||||
var review = WorkflowScriptReview.Create(flow.Id, batch.To.GetValueOrDefault(flow.Path), code);
|
||||
restoredFlows.Add(flow with { Compiled = review.Compiled, Diagnostics = review.Diagnostics });
|
||||
}
|
||||
return batch with { From = batch.To, To = batch.From, UndoOf = id, Workflows = restoredFlows,
|
||||
Rows = batch.Rows.AsEnumerable().Reverse().Select(e=>e with { Before=e.After, After=e.Before,
|
||||
Action=e.Action=="update"?"update":e.Action=="create"?"delete":"create" }).ToList() };
|
||||
return batch with
|
||||
{
|
||||
From = batch.To,
|
||||
To = batch.From,
|
||||
UndoOf = id,
|
||||
Workflows = restoredFlows,
|
||||
Rows = batch.Rows.AsEnumerable().Reverse().Select(e => e with
|
||||
{
|
||||
Before = e.After,
|
||||
After = e.Before,
|
||||
Action = e.Action == "update" ? "update" : e.Action == "create" ? "delete" : "create"
|
||||
}).ToList()
|
||||
};
|
||||
}
|
||||
|
||||
private void CheckBatchState(Dictionary<string,string> expected)
|
||||
private void CheckBatchState(Dictionary<string, string> expected)
|
||||
{
|
||||
if (!baseline.OrderBy(p=>p.Key).SequenceEqual(expected.OrderBy(p=>p.Key)))
|
||||
if (!baseline.OrderBy(p => p.Key).SequenceEqual(expected.OrderBy(p => p.Key)))
|
||||
throw new ProjectConflictException("工程已经改变,请重新预览整批操作。");
|
||||
}
|
||||
|
||||
private void CheckBatchScripts()
|
||||
{
|
||||
foreach (var recipe in Recipes)
|
||||
foreach (var flow in Flows(recipe.ID))
|
||||
if (!baseline.TryGetValue(ScriptPath(recipe.ID, flow.ID), out var saved) || saved != (flow.Code ?? ""))
|
||||
throw new ProjectConflictException($"工作流「{flow.Name}」有未保存脚本,请保存后重新分析引用。");
|
||||
}
|
||||
|
||||
internal void ApplyBatch(ProjectBatch batch)
|
||||
{
|
||||
lock (Data.Sync)
|
||||
{
|
||||
CheckBatchState(batch.From);
|
||||
CheckBatchScripts();
|
||||
var previousManifest = JsonSerializer.Deserialize<Manifest>(batch.From["project.json"], Json);
|
||||
if (!Recipes.Select(r => r.ID).SequenceEqual(previousManifest.Recipes) || DefaultRecipeId != previousManifest.DefaultRecipeId)
|
||||
throw new ProjectConflictException("配方列表有未保存修改。");
|
||||
@ -133,15 +158,15 @@ public sealed partial class ProjectDirectory
|
||||
throw new ProjectConflictException("工作流列表有未保存修改。");
|
||||
}
|
||||
var current = BatchRows();
|
||||
var configRows = batch.Rows.Where(r=>r.Kind is not ("Workflows" or "Recipes")).ToList();
|
||||
var touched = configRows.Select(r=>(r.Kind,r.Id)).ToHashSet();
|
||||
var tracked = Data.ChangeTracker.Entries().Where(e=>e.Metadata.FindProperty("ID")?.ClrType==typeof(Guid) &&
|
||||
touched.Contains((e.Metadata.GetTableName(),(Guid)e.Property("ID").CurrentValue))).ToArray();
|
||||
if (tracked.Any(e=>e.State!=EntityState.Unchanged) || batch.Rows.Any(r=>!JsonNode.DeepEquals(current.GetValueOrDefault((r.Kind,r.Id)),r.Before)))
|
||||
var configRows = batch.Rows.Where(r => r.Kind is not ("Workflows" or "Recipes")).ToList();
|
||||
var touched = configRows.Select(r => (r.Kind, r.Id)).ToHashSet();
|
||||
var tracked = Data.ChangeTracker.Entries().Where(e => e.Metadata.FindProperty("ID")?.ClrType == typeof(Guid) &&
|
||||
touched.Contains((e.Metadata.GetTableName(), (Guid)e.Property("ID").CurrentValue))).ToArray();
|
||||
if (tracked.Any(e => e.State != EntityState.Unchanged) || batch.Rows.Any(r => !JsonNode.DeepEquals(current.GetValueOrDefault((r.Kind, r.Id)), r.Before)))
|
||||
throw new ProjectConflictException("批次涉及的对象有未保存修改。");
|
||||
var flowRows = batch.Rows.Where(r=>r.Kind=="Workflows").ToList();
|
||||
var gates = flowRows.Where(r=>r.Before!=null).Select(r=>(Flows(Guid.Parse((string)r.Before["RecipeID"])).Single(f=>f.ID==r.Id),
|
||||
(string)r.Before["Code"], (string)(r.After??r.Before)["Code"])).ToArray();
|
||||
var flowRows = batch.Rows.Where(r => r.Kind == "Workflows").ToList();
|
||||
var gates = flowRows.Where(r => r.Before != null).Select(r => (Flows(Guid.Parse((string)r.Before["RecipeID"])).Single(f => f.ID == r.Id),
|
||||
(string)r.Before["Code"], (string)(r.After ?? r.Before)["Code"])).ToArray();
|
||||
Workflow.SaveReviewedBatch(gates, () =>
|
||||
{
|
||||
using var tx = Data.Database.BeginTransaction();
|
||||
@ -149,51 +174,55 @@ public sealed partial class ProjectDirectory
|
||||
{
|
||||
if (row.After == null)
|
||||
{
|
||||
if (Data.Database.ExecuteSqlRaw($"DELETE FROM \"{row.Kind}\" WHERE ID = {{0}}",row.Id)!=1)
|
||||
if (Data.Database.ExecuteSqlRaw($"DELETE FROM \"{row.Kind}\" WHERE ID = {{0}}", row.Id) != 1)
|
||||
throw new ProjectConflictException("配置记录已改变。");
|
||||
}
|
||||
else ProjectConfiguration.Restore(Data,[row.Kind],new(){[row.Kind]=new JsonArray(row.After.DeepClone())},row.Before!=null);
|
||||
else ProjectConfiguration.Restore(Data, [row.Kind], new() { [row.Kind] = new JsonArray(row.After.DeepClone()) }, row.Before != null);
|
||||
}
|
||||
var expectedBytes = batch.UndoOf.HasValue ? batch.ChangedFiles.Where(batch.From.ContainsKey)
|
||||
.ToDictionary(p=>p,p=>Encoding.UTF8.GetBytes(batch.From[p])) : batch.OriginalBytes;
|
||||
WriteFiles(Root,new(batch.To),batch.From.Keys.Union(batch.To.Keys).ToArray(),tx.Commit,
|
||||
.ToDictionary(p => p, p => Encoding.UTF8.GetBytes(batch.From[p])) : batch.OriginalBytes;
|
||||
WriteFiles(Root, new(batch.To), batch.From.Keys.Union(batch.To.Keys).ToArray(), tx.Commit,
|
||||
batch.UndoOf.HasValue ? batch.OriginalBytes : null, expectedBytes);
|
||||
foreach (var entry in tracked) entry.Reload();
|
||||
foreach (string path in configuration.Keys.ToList()) configuration[path]=baseline[path];
|
||||
var manifest=JsonSerializer.Deserialize<Manifest>(baseline["project.json"],Json);
|
||||
DefaultRecipeId=manifest.DefaultRecipeId;
|
||||
foreach (string path in configuration.Keys.ToList()) configuration[path] = baseline[path];
|
||||
var manifest = JsonSerializer.Deserialize<Manifest>(baseline["project.json"], Json);
|
||||
DefaultRecipeId = manifest.DefaultRecipeId;
|
||||
foreach (var row in flowRows)
|
||||
{
|
||||
var collection=Flows(Guid.Parse((string)(row.After??row.Before)["RecipeID"]));
|
||||
var flow=collection.SingleOrDefault(f=>f.ID==row.Id);
|
||||
if (row.After==null) { flow.Stop(); collection.Remove(flow); continue; }
|
||||
var a=row.After;
|
||||
bool add=flow==null;
|
||||
flow??=new Workflow { ID=row.Id, RecipeID=Guid.Parse((string)a["RecipeID"]) };
|
||||
flow.Name=(string)a["Name"]; flow.Comment=(string)a["Comment"]; flow.Code=(string)a["Code"];
|
||||
flow.CycleDelayTime=(double)a["CycleDelayTime"]; flow.AutomaticExecution=(bool)a["AutomaticExecution"]; flow.Prompt="";
|
||||
var collection = Flows(Guid.Parse((string)(row.After ?? row.Before)["RecipeID"]));
|
||||
var flow = collection.SingleOrDefault(f => f.ID == row.Id);
|
||||
if (row.After == null) { flow.Stop(); collection.Remove(flow); continue; }
|
||||
var definition = row.After;
|
||||
bool add = flow == null;
|
||||
flow ??= new Workflow { ID = row.Id, RecipeID = Guid.Parse((string)definition["RecipeID"]) };
|
||||
flow.Name = (string)definition["Name"];
|
||||
flow.Comment = (string)definition["Comment"];
|
||||
flow.Code = (string)definition["Code"];
|
||||
flow.CycleDelayTime = (double)definition["CycleDelayTime"];
|
||||
flow.AutomaticExecution = (bool)definition["AutomaticExecution"];
|
||||
flow.Prompt = "";
|
||||
if (add) collection.Add(flow);
|
||||
}
|
||||
foreach (var row in batch.Rows.Where(r=>r.Kind=="Recipes"))
|
||||
foreach (var row in batch.Rows.Where(r => r.Kind == "Recipes"))
|
||||
{
|
||||
var recipe=Recipes.SingleOrDefault(r=>r.ID==row.Id);
|
||||
if(row.After==null) { Recipes.Remove(recipe); workflows.Remove(row.Id); continue; }
|
||||
bool add=recipe==null;
|
||||
recipe??=new Recipe { ID=row.Id };
|
||||
recipe.Name=(string)row.After["Name"]; recipe.Comment=(string)row.After["Comment"]; recipe.Prompt="";
|
||||
if(add) Recipes.Add(recipe);
|
||||
var recipe = Recipes.SingleOrDefault(r => r.ID == row.Id);
|
||||
if (row.After == null) { Recipes.Remove(recipe); workflows.Remove(row.Id); continue; }
|
||||
bool add = recipe == null;
|
||||
recipe ??= new Recipe { ID = row.Id };
|
||||
recipe.Name = (string)row.After["Name"]; recipe.Comment = (string)row.After["Comment"]; recipe.Prompt = "";
|
||||
if (add) Recipes.Add(recipe);
|
||||
}
|
||||
for(int i=0;i<manifest.Recipes.Length;i++)
|
||||
for (int i = 0; i < manifest.Recipes.Length; i++)
|
||||
{
|
||||
var rid=manifest.Recipes[i];
|
||||
var index=Recipes.IndexOf(Recipes.Single(r=>r.ID==rid));
|
||||
if(index!=i) Recipes.Move(index,i);
|
||||
var list=Flows(rid);
|
||||
var order=JsonSerializer.Deserialize<RecipeFile>(baseline[RecipePath(rid)],Json).Workflows;
|
||||
for(int j=0;j<order.Length;j++)
|
||||
var rid = manifest.Recipes[i];
|
||||
var index = Recipes.IndexOf(Recipes.Single(r => r.ID == rid));
|
||||
if (index != i) Recipes.Move(index, i);
|
||||
var list = Flows(rid);
|
||||
var order = JsonSerializer.Deserialize<RecipeFile>(baseline[RecipePath(rid)], Json).Workflows;
|
||||
for (int j = 0; j < order.Length; j++)
|
||||
{
|
||||
int at=list.IndexOf(list.Single(f=>f.ID==order[j].Id));
|
||||
if(at!=j) list.Move(at,j);
|
||||
int at = list.IndexOf(list.Single(f => f.ID == order[j].Id));
|
||||
if (at != j) list.Move(at, j);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
63
Tests/mcp_batch_smoke.py
Normal file
63
Tests/mcp_batch_smoke.py
Normal file
@ -0,0 +1,63 @@
|
||||
"""Review three changes in a single live editor dialog, then undo with one confirmation."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
from mcp_smoke import Client
|
||||
|
||||
|
||||
def verify(exe, root, offline=False):
|
||||
def snapshot():
|
||||
return {p.relative_to(root): p.read_bytes() for p in root.rglob("*") if p.is_file()}
|
||||
|
||||
initial = snapshot()
|
||||
client = Client(exe, root, "--allow-write")
|
||||
try:
|
||||
summary = client.call("get_project_summary")
|
||||
if offline:
|
||||
assert summary.get("source") != "editor"
|
||||
recipe = summary["DefaultRecipeId"]
|
||||
else:
|
||||
assert summary["source"] == "editor"
|
||||
recipe = summary["currentRecipeId"]
|
||||
|
||||
def named(kind, name):
|
||||
return next(x["id"] for x in client.call("list_objects", kind=kind, recipeId=recipe)["items"] if x["name"] == name)
|
||||
|
||||
vision = named("VisionFunctions", "检查")
|
||||
workflow = named("Workflows", "调度")
|
||||
control = named("CustomControls", "显示")
|
||||
refs = client.call("find_references", kind="VisionFunctions", id=vision)
|
||||
assert refs["hits"]
|
||||
script = client.call("get_object", kind="Workflows", id=workflow)["Code"]
|
||||
marker = "批次验收"
|
||||
operations = [
|
||||
{"action": "update", "kind": "VisionFunctions", "id": vision, "properties": {"Comment": marker}},
|
||||
{"action": "update", "kind": "CustomControls", "id": control, "properties": {"Comment": marker}},
|
||||
{"action": "update", "kind": "Workflows", "id": workflow, "properties": {"Code": script + "\n// " + marker + "\n"}},
|
||||
]
|
||||
draft = client.call("preview_batch", operations=operations)
|
||||
batch = draft["Batch"]
|
||||
assert draft["Status"] == "pending" and batch["Compiled"] and batch["Workflows"]
|
||||
assert len(batch["Steps"]) == 3 and any(s["Edit"]["ManualReferences"] for s in batch["Steps"])
|
||||
assert initial == snapshot()
|
||||
print("ANALYZED", len(refs["hits"]), "references;", len(batch["Workflows"]), "compiled workflows", flush=True)
|
||||
assert client.call("apply_changes", draftId=draft["DraftId"])["Status"] == "saved"
|
||||
saved = snapshot()
|
||||
assert {p for p in initial if initial[p] != saved[p]} == set(map(Path, batch["ChangedFiles"]))
|
||||
for op in operations:
|
||||
row = client.call("get_object", kind=op["kind"], id=op["id"])
|
||||
assert all(row[k] == v for k, v in op["properties"].items())
|
||||
undo = client.call("preview_undo", draftId=draft["DraftId"])
|
||||
assert undo["Batch"]["UndoOf"] == draft["DraftId"] and saved == snapshot()
|
||||
print("SAVED", batch["ChangedFiles"], flush=True)
|
||||
assert client.call("apply_changes", draftId=undo["DraftId"])["Status"] == "saved"
|
||||
assert client.call("get_change_status", draftId=draft["DraftId"])["Status"] == "undone"
|
||||
assert snapshot() == initial
|
||||
print("PASS", len(initial), "files;", sum(map(len, initial.values())), "bytes")
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
verify(Path(sys.argv[1]), Path(sys.argv[2]), offline="--offline" in sys.argv[3:])
|
||||
|
||||
Loading…
Reference in New Issue
Block a user