Apply reviewed workflow source only after explicit WPF approval
This commit is contained in:
parent
addac5ba77
commit
559eb230a6
@ -21,11 +21,15 @@ internal sealed class ProjectGateway(string root, bool allowWrite)
|
||||
private string Dispatch(string operation, JsonObject arguments)
|
||||
{
|
||||
if (operation == "apply" && !allowWrite) throw new InvalidOperationException("Start MCP with --allow-write to save.");
|
||||
// Do not hold the cross-process project lock while a person reads the dialog.
|
||||
bool approved = false;
|
||||
if (operation == "apply" && changes.PendingScript(Guid.Parse((string)arguments["draftId"])) is { } script)
|
||||
approved = PLCSharp.VVMs.Workflows.ScriptReviewWindow.ConfirmOffline(script, root);
|
||||
return ProjectPipe.Call(root, new() { ["operation"] = operation, ["arguments"] = arguments }, () =>
|
||||
{
|
||||
using var project = ProjectDirectory.Open(root);
|
||||
if (operation is "preview" or "apply" or "status")
|
||||
return changes.Execute(project, operation, arguments, allowWrite);
|
||||
if (operation is "preview" or "previewScript" or "apply" or "status")
|
||||
return changes.Execute(project, operation, arguments, allowWrite, change => change.Review == null || approved);
|
||||
return ProjectInspection.Query(project, operation, arguments);
|
||||
}).ToJsonString();
|
||||
}
|
||||
|
||||
@ -7,6 +7,10 @@ namespace PLCSharp.Mcp;
|
||||
[McpServerToolType]
|
||||
internal sealed class ProjectTools(ProjectGateway gateway)
|
||||
{
|
||||
[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 });
|
||||
|
||||
[McpServerTool(Name = "preview_changes"), Description("Preview a comment change to one recipe, variable or workflow. Returns a draft ID and before/after values. No file is written.")]
|
||||
public string PreviewChanges(string kind, string id, string comment) =>
|
||||
gateway.Call("preview", new() { ["kind"] = kind, ["id"] = id, ["comment"] = comment });
|
||||
|
||||
@ -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 "apply" or "status")
|
||||
if (operation is "preview" or "previewScript" or "apply" or "status")
|
||||
{
|
||||
if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy))
|
||||
throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。");
|
||||
return aiChanges.Execute(Project, operation, args, true, change =>
|
||||
return aiChanges.Execute(Project, operation, args, true, change => change.Review != 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);
|
||||
}
|
||||
|
||||
@ -7,15 +7,35 @@ 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);
|
||||
string Name, string Path, string Before, string After, string Revision, string Status, WorkflowScriptReview Review = 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;
|
||||
|
||||
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<ProjectChange, bool> confirm = null)
|
||||
{
|
||||
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"];
|
||||
@ -31,20 +51,25 @@ public sealed class ProjectChanges
|
||||
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");
|
||||
if (drafts.Count >= 256) drafts.Remove(drafts.Keys.First());
|
||||
drafts.Add(change.DraftId, change);
|
||||
return JsonSerializer.SerializeToNode(change);
|
||||
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 && confirm == null) throw new InvalidOperationException("脚本修改需要用户确认。");
|
||||
if (confirm != null && !confirm(draft)) draft = draft with { Status = "rejected" };
|
||||
else
|
||||
{
|
||||
try { project.ApplyComment(draft); }
|
||||
try
|
||||
{
|
||||
if (draft.Review == null) project.ApplyComment(draft);
|
||||
else project.ApplyScript(draft);
|
||||
}
|
||||
catch (ProjectConflictException)
|
||||
{
|
||||
drafts[draft.DraftId] = draft with { Status = "conflict" };
|
||||
@ -64,6 +89,28 @@ 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<string, string>(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)
|
||||
@ -85,19 +132,14 @@ public sealed partial class ProjectDirectory
|
||||
throw new ProjectConflictException("Save the pending editor change to this comment first.");
|
||||
target[field] = change.After;
|
||||
var json = Serialize(document);
|
||||
var files = new Dictionary<string, string>(baseline) { [change.Path] = json };
|
||||
|
||||
// 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));
|
||||
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.");
|
||||
}
|
||||
WriteReviewedFile(change, json);
|
||||
transaction?.Commit();
|
||||
if (isVariable)
|
||||
{
|
||||
|
||||
21
PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml
Normal file
21
PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml
Normal file
@ -0,0 +1,21 @@
|
||||
<Window x:Class="PLCSharp.VVMs.Workflows.ScriptReviewWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="确认工作流脚本修改" Width="820" Height="570" MinWidth="520" MinHeight="360"
|
||||
WindowStartupLocation="CenterScreen">
|
||||
<Grid Margin="16">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/><RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock x:Name="WorkflowTitle" FontWeight="Bold" FontSize="18"/>
|
||||
<TextBox x:Name="Location" Grid.Row="1" IsReadOnly="True" BorderThickness="0" TextWrapping="Wrap" Margin="0,6"/>
|
||||
<TextBox x:Name="CheckResult" Grid.Row="2" IsReadOnly="True" MaxHeight="100" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Margin="0,2,0,8"/>
|
||||
<TextBox x:Name="CodeDiff" Grid.Row="3" AutomationProperties.Name="代码差异" IsReadOnly="True" FontFamily="Consolas"
|
||||
VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Padding="8"/>
|
||||
<StackPanel Grid.Row="4" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,12,0,0">
|
||||
<Button x:Name="CancelChange" Content="取消" IsCancel="True" Width="84" Margin="0,0,8,0"/>
|
||||
<Button Content="确认保存" Click="Approve" Width="92"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Window>
|
||||
44
PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs
Normal file
44
PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs
Normal file
@ -0,0 +1,44 @@
|
||||
using PLCSharp.Models;
|
||||
using System.Threading;
|
||||
using System.Windows;
|
||||
|
||||
namespace PLCSharp.VVMs.Workflows;
|
||||
|
||||
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;
|
||||
Loaded += (_, _) => CancelChange.Focus();
|
||||
}
|
||||
|
||||
private void Approve(object sender, RoutedEventArgs e) => DialogResult = true;
|
||||
|
||||
public static bool Confirm(ProjectChange change, string root, Window owner)
|
||||
{
|
||||
var window = new ScriptReviewWindow(change, root);
|
||||
if (owner != null) { window.Owner = owner; window.WindowStartupLocation = WindowStartupLocation.CenterOwner; }
|
||||
return window.ShowDialog() == true;
|
||||
}
|
||||
|
||||
public static bool ConfirmOffline(ProjectChange change, string root)
|
||||
{
|
||||
if (!Environment.UserInteractive) throw new InvalidOperationException("脚本保存需要交互式 Windows 桌面。");
|
||||
var result = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
try { result.SetResult(Confirm(change, root, null)); }
|
||||
catch (Exception ex) { result.SetException(ex); }
|
||||
finally { System.Windows.Threading.Dispatcher.CurrentDispatcher.InvokeShutdown(); }
|
||||
}) { IsBackground = true };
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.Start();
|
||||
return result.Task.GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
|
||||
@ -326,6 +326,17 @@ namespace PLCSharp.VVMs.Workflows
|
||||
}
|
||||
}
|
||||
|
||||
internal void SaveReviewedCode(string before, string after, Action save)
|
||||
{
|
||||
lock (_executionGate)
|
||||
{
|
||||
if (IsRuning || _activeRun != null) throw new InvalidOperationException("请先停止工作流。");
|
||||
if ((Code ?? "") != before) throw new ProjectConflictException("编辑器内的脚本已更改,请重新预览。");
|
||||
save();
|
||||
Code = after;
|
||||
}
|
||||
}
|
||||
|
||||
private readonly object _executionGate = new();
|
||||
private TaskCompletionSource _activeRun;
|
||||
private CancellationTokenSource _scanCancellation;
|
||||
@ -408,4 +419,4 @@ namespace PLCSharp.VVMs.Workflows
|
||||
set { SetProperty(ref _Flow, value); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
54
Tests/PLCSharp.Tests/WorkflowScriptChangeTests.cs
Normal file
54
Tests/PLCSharp.Tests/WorkflowScriptChangeTests.cs
Normal file
@ -0,0 +1,54 @@
|
||||
using PLCSharp.Models;
|
||||
using PLCSharp.VVMs.Workflows;
|
||||
using System.IO;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace PLCSharp.Tests;
|
||||
|
||||
public class WorkflowScriptChangeTests
|
||||
{
|
||||
[Fact]
|
||||
public void SaveRequiresValidReviewedSourceApprovalAndAnUnchangedBase()
|
||||
{
|
||||
var folder = Directory.CreateTempSubdirectory();
|
||||
try
|
||||
{
|
||||
using var project = ProjectDirectory.New();
|
||||
var flow = new Workflow { Name = "测试", Code = "// before" };
|
||||
project.Flows(project.DefaultRecipeId).Add(flow);
|
||||
project.Save(folder.FullName);
|
||||
string path = Directory.GetFiles(folder.FullName, "*.cs", SearchOption.AllDirectories).Single();
|
||||
string valid = $"public class Extension_{flow.ID:N} {{ public void Run(PLCSharp.Models.GlobalModel m, PLCSharp.Core.Common.FlowModel f) {{ }} }}";
|
||||
var changes = new ProjectChanges();
|
||||
JsonNode Preview(string source) => changes.Execute(project, "previewScript",
|
||||
new() { ["id"] = flow.ID.ToString(), ["code"] = source }, false);
|
||||
JsonNode Apply(JsonNode draft, Func<ProjectChange, bool>? approve, bool write = true) =>
|
||||
changes.Execute(project, "apply", new() { ["draftId"] = (string?)draft["DraftId"] }, write, approve!);
|
||||
var invalid = Preview("bad source");
|
||||
Assert.Equal("invalid", (string?)invalid["Status"]);
|
||||
Assert.Throws<InvalidOperationException>(() => Apply(invalid, _ => throw new Exception("Unexpected confirmation")));
|
||||
var draft = Preview(valid);
|
||||
Assert.Throws<InvalidOperationException>(() => Apply(draft, _ => true, false));
|
||||
Assert.Throws<InvalidOperationException>(() => Apply(draft, null));
|
||||
Assert.Equal("rejected", (string?)Apply(draft, _ => false)["Status"]);
|
||||
Assert.Equal("// before", File.ReadAllText(path));
|
||||
var stale = Preview(valid);
|
||||
File.WriteAllText(path, "// external");
|
||||
Assert.ThrowsAny<IOException>(() => Apply(stale, _ => true));
|
||||
Assert.Equal("// external", File.ReadAllText(path));
|
||||
File.WriteAllText(path, "// before");
|
||||
var pending = Preview(valid);
|
||||
flow.Code = "// editor";
|
||||
Assert.ThrowsAny<IOException>(() => Apply(pending, _ => true));
|
||||
flow.Code = "// before";
|
||||
var final = Preview(valid);
|
||||
Assert.Equal("saved", (string?)Apply(final, _ => true)["Status"]);
|
||||
Assert.Equal("saved", (string?)Apply(final, _ => throw new Exception("Duplicate confirmation"))["Status"]);
|
||||
Assert.Equal(valid, File.ReadAllText(path));
|
||||
Assert.Equal(valid, flow.Code);
|
||||
Assert.False(flow.IsCompiled);
|
||||
}
|
||||
finally { folder.Delete(true); }
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user