using Microsoft.EntityFrameworkCore; using System.Security.Cryptography; using System.Text; using System.Text.Json; 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, ProjectRename Rename = null, ObjectEdit Edit = null); public sealed class ProjectChanges { private readonly Dictionary drafts = new(); public ProjectChange PendingScript(Guid id) => drafts.TryGetValue(id, out var draft) && (draft.Review != null || draft.Rename != null || draft.Edit != null) && draft.Status == "pending" ? draft : null; private JsonNode Remember(ProjectChange change) { if (drafts.Count >= 256) drafts.Remove(drafts.Keys.First()); drafts.Add(change.DraftId, change); return JsonSerializer.SerializeToNode(change); } public JsonNode Execute(ProjectDirectory project, string operation, JsonObject args, bool allowWrite, Func confirm = null) { ObjectEdit edit = null; if (operation == "previewObjectEdit") edit = project.PlanObjectEdit((string)args["action"], (string)args["kind"], args["id"] == null ? null : Guid.Parse((string)args["id"]), args["properties"]?.AsObject()); if (operation == "previewUndo" && drafts.TryGetValue(Guid.Parse((string)args["draftId"]), out var previousEdit) && previousEdit.Edit != null) { if (previousEdit.ProjectId != project.Id || previousEdit.Status != "saved" || previousEdit.Edit.UndoOf.HasValue) throw new ProjectConflictException("需要当前工程中已保存且尚未撤销的对象修改。"); edit = project.UndoObject(previousEdit.DraftId, previousEdit.Edit); } if (edit != null) { var row = edit.After ?? edit.Before; return Remember(new(Guid.NewGuid(), project.Id, edit.Kind, edit.Id, Guid.TryParse((string)row["RecipeID"], out var recipe) ? recipe : Guid.Empty, (string)row["Name"] ?? edit.Kind, edit.Path, null, null, project.Revision(edit.Path), edit.Compiled ? "pending" : "invalid", Edit: edit)); } if (operation is "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewObjectRename" or "previewDeviceRename" or "previewUndo") { ProjectRename plan; if (operation == "previewObjectRename") plan = project.PlanObjectRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"], (string)args["memberName"], (string)args["segmentName"]); else if (operation == "previewVisionAssetRename") plan = project.PlanVisionAssetRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"]); else if (operation == "previewDeviceRename") plan = project.PlanDeviceRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"]); else if (operation == "previewIoRename") plan = project.PlanIoRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"]); else if (operation == "previewAxisRename") plan = project.PlanAxisRename(Guid.Parse((string)args["id"]), (string)args["newName"]); else if (operation == "previewVisionRename") plan = project.PlanVisionRename(Guid.Parse((string)args["id"]), (string)args["newName"]); else 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"]); 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, 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") { var id = Guid.Parse((string)args["id"]); var target = ProjectInspection.Query(project, "get", new() { ["kind"] = "Workflows", ["id"] = id.ToString() }); var recipe = Guid.Parse((string)target["RecipeID"]); string path = $"recipes/{recipe:D}/workflows/{id:D}.cs", before = (string)target["Code"] ?? "", after = (string)args["code"]; var review = WorkflowScriptReview.Create(id, before, after); return Remember(new(Guid.NewGuid(), project.Id, "Workflows", id, recipe, (string)target["Name"], path, before, after, project.Revision(path), review.Compiled ? "pending" : "invalid", review)); } if (operation == "preview") { string kind = (string)args["kind"], after = (string)args["comment"]; if (after == null || after.Length > 8192) throw new ArgumentException("Expected a comment of at most 8192 characters."); if (kind is not ("Recipes" or "Variables" or "SystemVariables" or "Workflows")) throw new ArgumentException("Unsupported comment target."); var id = Guid.Parse((string)args["id"]); lock (project.Data.Sync) { var target = ProjectInspection.Query(project, "get", args); var recipeId = kind == "Recipes" ? id : Guid.Parse((string)target["RecipeID"]); string path = kind is "Variables" or "SystemVariables" ? "configuration/variables.json" : $"recipes/{recipeId:D}/recipe.json"; string before = (string)target["Comment"]; var change = new ProjectChange(Guid.NewGuid(), project.Id, kind, id, recipeId, (string)target["Name"], path, before, after, project.Revision(path), "pending"); return Remember(change); } } if (!drafts.TryGetValue(Guid.Parse((string)args["draftId"]), out var draft) || draft.ProjectId != project.Id) throw new ArgumentException("Unknown or expired draft."); if (operation == "apply" && draft.Status == "invalid") throw new InvalidOperationException("脚本编译检查未通过,请修正后重新预览。"); 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 || draft.Rename != null || draft.Edit != null) && confirm == null) throw new InvalidOperationException("脚本修改需要用户确认。"); if (confirm != null && !confirm(draft)) draft = draft with { Status = "rejected" }; else { try { if (draft.Edit != null) { if (draft.Edit.UndoOf is Guid source && (!drafts.TryGetValue(source, out var orig) || orig.Status != "saved")) throw new ProjectConflictException("原操作已经撤销。"); project.ApplyObjectEdit(draft.Edit); if (draft.Edit.UndoOf is Guid previous) drafts[previous] = drafts[previous] with { Status = "undone" }; } else 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) { drafts[draft.DraftId] = draft with { Status = "conflict" }; throw; } draft = draft with { Status = "saved" }; } drafts[draft.DraftId] = draft; } return JsonSerializer.SerializeToNode(draft); } } internal sealed class ProjectConflictException(string message) : System.IO.IOException(message); public sealed partial class ProjectDirectory { internal string Revision(string path) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(baseline[path]))); private void WriteReviewedFile(ProjectChange change, string contents) { var files = new Dictionary(baseline) { [change.Path] = contents }; try { WriteFiles(Root, files, [change.Path]); } catch (System.IO.IOException) when (!System.IO.File.Exists(ProjectFile(Root, change.Path)) || System.IO.File.ReadAllText(ProjectFile(Root, change.Path)) != baseline[change.Path]) { throw new ProjectConflictException("The file changed outside the editor. Reopen the project and preview again."); } } internal void ApplyScript(ProjectChange change) { lock (Data.Sync) { if (Revision(change.Path) != change.Revision || baseline[change.Path] != change.Before) throw new ProjectConflictException("脚本存在未保存编辑或预览已过期,请先核对当前版本。"); var workflow = Flows(change.RecipeId).Single(w => w.ID == change.ObjectId); workflow.SaveReviewedCode(change.Before, change.After, () => WriteReviewedFile(change, change.After)); } } internal void ApplyComment(ProjectChange change) { lock (Data.Sync) { var id = change.ObjectId; var current = ProjectInspection.Query(this, "get", new() { ["kind"] = change.Kind, ["id"] = id.ToString() }); if (Revision(change.Path) != change.Revision || (string)current["Comment"] != change.Before) throw new ProjectConflictException("The target changed after preview. Create a new preview."); var document = JsonNode.Parse(baseline[change.Path]); var isVariable = change.Kind is "Variables" or "SystemVariables"; JsonNode target = change.Kind switch { "Recipes" => document, "Workflows" => document["workflows"].AsArray().Single(w => Guid.Parse((string)w["id"]) == id), _ => document[change.Kind].AsArray().Single(v => Guid.Parse((string)v["ID"]) == id) }; var field = isVariable ? "Comment" : "comment"; if ((string)target[field] != change.Before) throw new ProjectConflictException("Save the pending editor change to this comment first."); target[field] = change.After; var json = Serialize(document); // Change only the approved column in the private working database. Other tracked drafts stay pending. using var transaction = isVariable ? Data.Database.BeginTransaction() : null; if (change.Kind == "Variables") Data.Variables.Where(v => v.ID == id).ExecuteUpdate(s => s.SetProperty(v => v.Comment, change.After)); if (change.Kind == "SystemVariables") Data.SystemVariables.Where(v => v.ID == id).ExecuteUpdate(s => s.SetProperty(v => v.Comment, change.After)); WriteReviewedFile(change, json); transaction?.Commit(); if (isVariable) { configuration[change.Path] = json; object entity = change.Kind == "Variables" ? Data.Variables.Local.First(v => v.ID == id) : Data.SystemVariables.Local.First(v => v.ID == id); var property = Data.Entry(entity).Property(field); if (entity is PLCSharp.VVMs.GlobalVariables.Variable variable) variable.Comment = change.After; else ((PLCSharp.VVMs.GlobalVariables.SystemVariable)entity).Comment = change.After; property.OriginalValue = change.After; } else if (change.Kind == "Recipes") Recipes.Single(r => r.ID == id).Comment = change.After; else Flows(change.RecipeId).Single(w => w.ID == id).Comment = change.After; } } }