Move draft approval to the Agent and return combined impact without WPF prompts

This commit is contained in:
wanglei 2026-12-05 23:56:10 +08:00
parent 1fb7464a08
commit 850b4da16b
9 changed files with 91 additions and 246 deletions

View File

@ -21,15 +21,11 @@ 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 }, () =>
return ProjectPipe.Call(root, new() { ["operation"] = operation == "apply" ? "applyAgentConfirmed" : operation, ["arguments"] = arguments }, () =>
{
using var project = ProjectDirectory.Open(root);
if (operation is "previewBatch" or "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewObjectEdit" or "previewObjectRename" or "previewDeviceRename" or "previewUndo" or "apply" or "status")
return changes.Execute(project, operation, arguments, allowWrite, change => (change.Review == null && change.Rename == null && change.Edit == null && change.Batch == null) || approved);
return changes.Execute(project, operation, arguments, allowWrite, _ => ProjectChanges.AgentApproval(arguments));
return ProjectInspection.Query(project, operation, arguments);
}).ToJsonString();
}

View File

@ -36,7 +36,7 @@ internal sealed class ProjectTools(ProjectGateway gateway)
[McpServerTool(Name = "preview_undo"), Description("Preview reversal of an entire saved batch, object edit or rename from this session, without a dialog. 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.")]
[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; confirm the displayed draft in the Agent before saving.")]
public string PreviewWorkflowScript(string id, string code) =>
gateway.Call("previewScript", new() { ["id"] = id, ["code"] = code });
@ -44,8 +44,8 @@ internal sealed class ProjectTools(ProjectGateway gateway)
public string PreviewChanges(string kind, string id, string comment) =>
gateway.Call("preview", new() { ["kind"] = kind, ["id"] = id, ["comment"] = comment });
[McpServerTool(Name = "apply_changes"), Description("Save an existing preview using its draft ID. Requires write-enabled launch. An open editor requests user confirmation.")]
public string ApplyChanges(string draftId) => gateway.Call("apply", new() { ["draftId"] = draftId });
[McpServerTool(Name = "apply_changes"), Description("Save an existing preview using its draft ID. Present this exact draft, impact and compile results to the user in the Agent first. Only pass confirmed=true after user approval of this draft. Pass false to reject. The editor never prompts. Requires --allow-write.")]
public string ApplyChanges(string draftId, bool confirmed) => gateway.Call("apply", new() { ["draftId"] = draftId, ["confirmed"] = confirmed });
[McpServerTool(Name = "get_change_status", ReadOnly = true), Description("Inspect a pending, rejected or saved draft.")]
public string GetChangeStatus(string draftId) => gateway.Call("status", new() { ["draftId"] = draftId });

View File

@ -0,0 +1,58 @@
namespace PLCSharp.Models;
public sealed partial record ProjectBatch
{
public string Summary => Describe();
private string Describe()
{
bool undo = UndoOf.HasValue;
var lines = new List<string>();
var refs = new HashSet<string>();
var manual = new HashSet<string>();
foreach (var step in undo ? Steps.AsEnumerable().Reverse() : Steps)
{
if (step.Edit is { } edit)
{
string action = (edit.Action, undo) switch { ("create", false) or ("delete", true) => "新增",
("delete", false) or ("create", true) => "删除", _ => "修改" };
var fields = new List<string>();
if (edit.Action == "update")
foreach (var (key, value) in edit.After)
{
if (System.Text.Json.Nodes.JsonNode.DeepEquals(edit.Before[key], value)) continue;
string from = (undo ? value : edit.Before[key])?.ToString() ?? "(空)";
string to = (undo ? edit.Before[key] : value)?.ToString() ?? "(空)";
string label = key switch { "Comment" => "备注", "Code" => "脚本", "ControlName" => "绑定控件", _ => key };
fields.Add(from.Length + to.Length <= 90 ? $"{label}由「{from}」改为「{to}」" : $"{label}有修改");
}
lines.Add($"{action}{KindName(edit.Kind)}「{step.Name}」" + (fields.Count == 0 ? "" : $",{string.Join(",", fields)}"));
foreach (var child in edit.OwnedRows) lines.Add($" 一并{(undo ? "恢复" : "删除")}{KindName(child.Kind)}「{child.Name}」");
foreach (var hit in edit.WorkflowReferences) refs.Add($"工作流「{hit["Name"]}」第 {hit["line"]} 行引用「{step.Name}」。");
foreach (var link in edit.ConfigReferences) refs.Add($"{KindName((string)link["table"])}的 {link["field"]} 引用「{step.Name}」。");
foreach (var hit in edit.ManualReferences) manual.Add($"「{hit["Name"]}」第 {hit["line"]} 行 · {hit["expression"]}");
}
else if (step.Rename is { } rename)
{
lines.Add($"{KindName(rename.Kind)}「{(undo ? rename.NewName : rename.OldName)}」改名为「{(undo ? rename.OldName : rename.NewName)}」");
foreach (var flow in rename.Scripts) refs.Add($"工作流「{flow.Name}」同步更新。");
foreach (var hit in rename.ManualReferences) manual.Add($"「{hit["Name"]}」第 {hit["line"]} 行 · {hit["expression"]}");
foreach (var hit in rename.PointReferences.Concat(rename.MatrixReferences).Concat(rename.CylinderReferences))
refs.Add($"{KindName(hit.Table)}的 {hit.Field} 同步更新。");
foreach (var hit in rename.VisionReferences) refs.Add($"视觉功能的 {hit.Key} 同步更新。");
}
}
if (refs.Count > 0) { lines.Add("\n受影响的工作流和配置"); lines.AddRange(refs); }
if (manual.Count > 0) { lines.Add("\n需要人工核对的引用"); lines.AddRange(manual); }
lines.Add(Workflows.Count == 0 ? "没有需要编译的工作流。" :
$"工作流编译结果(未运行):{string.Join("、", Workflows.Select(f => $"{f.Name}({(f.Compiled ? "通过" : "失败")})"))}");
return string.Join("\n", lines);
}
private static string KindName(string kind) => kind switch { "VisionLocalVariables" => "视觉局部变量", "ControlMeasurements" => "控件测量项",
"InterpolationSegments" => "插补段", "InterpolationPoints" => "插补段内点", "Recipes" => "配方", "SystemVariables" => "系统变量", "CustomControls" => "主页控件",
"Matrices" => "轴矩阵", "RobotMatrices" => "机器人矩阵", "InterpolationGroups" => "插补组", "Cameras" => "相机", "ImageDatas" => "视觉图像数据", "LocalImageDatas" => "本地图像数据", "Cylinders" => "气缸", "Robots" => "机器人", "Connects" => "通信连接",
"DI" => "数字输入", "DQ" => "数字输出", "Axes" => "运动轴", "VisionFunctions" => "视觉功能", "Workflows" => "工作流",
"AxisPoints" or "RobotPoints" => "点位", "Controllers" => "运动控制器", "CanvasConfigs" => "主页画布", "Variables" => "配方变量", _ => kind };
}

View File

@ -31,6 +31,7 @@ public partial class GlobalModel
{
if (!AllowAiAccess) throw new InvalidOperationException("请在机种配方页面启用 AI 访问。");
string operation = (string)request["operation"];
if (operation == "applyAgentConfirmed") operation = "apply";
var args = request["arguments"].AsObject();
if (operation is "previewBatch" or "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewObjectEdit" or "previewObjectRename" or "previewDeviceRename" or "previewUndo" or "apply" or "status")
{
@ -39,17 +40,12 @@ public partial class GlobalModel
Action updateEditorView = null;
var resultChange = aiChanges.Execute(Project, operation, args, true, change =>
{
bool accepted = change.Review != null || change.Rename != null || change.Edit != null || change.Batch != 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;
if (accepted && (ModeState.State.Execute || WorkflowsModel.IsBusy))
throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。");
if (accepted && change.Rename is { Kind: "Variables" } rename && CurrentRecipe.ID == rename.RecipeId &&
if (!ProjectChanges.AgentApproval(args)) return false;
if (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("编辑器变量列表存在更改,请先保存并重新预览。");
if (accepted && change.Rename is { Kind: "VisionFunctions" } vision && CurrentRecipe.ID == vision.RecipeId)
if (change.Rename is { Kind: "VisionFunctions" } vision && CurrentRecipe.ID == vision.RecipeId)
{
var functions = VisionsModel.VisionFunctions;
var target = functions.SingleOrDefault(v => v.ID == vision.ObjectId);
@ -58,7 +54,7 @@ public partial class GlobalModel
throw new ProjectConflictException("编辑器视觉功能列表有更改,请先保存并重新预览。");
updateEditorView = () => target.SetReviewedName(vision.NewName);
}
if (accepted && change.Rename is { IsPoint: true } point && CurrentRecipe.ID == point.RecipeId)
if (change.Rename is { IsPoint: true } point && CurrentRecipe.ID == point.RecipeId)
{
if (point.Kind == "AxisPoints")
updateEditorView = Project.PreparePointView(point, ControllersModel.AxisPoints, ControllersModel.Matrices);
@ -70,11 +66,11 @@ public partial class GlobalModel
updateEditorView = Project.PreparePointView(point, robot.Points, robot.RobotMatrices);
}
}
if (accepted && change.Rename is { Kind: "Axes" } axis)
if (change.Rename is { Kind: "Axes" } axis)
updateEditorView = Project.PrepareAxisView(axis, ControllersModel, CurrentRecipe.ID);
if (accepted && change.Rename is { IsIo: true } io)
if (change.Rename is { IsIo: true } io)
updateEditorView = Project.PrepareIoView(io, ControllersModel, CylindersModel);
if (accepted && change.Rename is { Nested: not null } member && CurrentRecipe.ID == member.RecipeId)
if (change.Rename is { Nested: not null } member && CurrentRecipe.ID == member.RecipeId)
{
object owner = member.Kind switch
{
@ -84,7 +80,7 @@ public partial class GlobalModel
};
updateEditorView = ProjectDirectory.PrepareNestedView(member, owner);
}
if (accepted && change.Rename is { IsMatrixOrGroup: true } matrix && CurrentRecipe.ID == matrix.RecipeId)
if (change.Rename is { IsMatrixOrGroup: true } matrix && CurrentRecipe.ID == matrix.RecipeId)
{
IEnumerable<object> objects = matrix.Kind switch
{
@ -94,18 +90,18 @@ public partial class GlobalModel
};
if (objects != null) updateEditorView = Project.PreparePointView(matrix, objects, []);
}
if (accepted && change.Rename is { IsVisionAsset: true } asset)
if (change.Rename is { IsVisionAsset: true } asset)
updateEditorView = Project.PrepareAssetView(asset, VisionsModel, CurrentRecipe.ID, CustomControls, VariablesModel.SystemVariables);
if (accepted && change.Rename is { IsDevice: true } device)
if (change.Rename is { IsDevice: true } device)
updateEditorView = PrepareDeviceView(device);
if (accepted && change.Batch != null)
if (change.Batch != null)
{
var updates = change.Batch.Rows.OrderBy(row => row.Kind == "Recipes" ? 1 : 0)
.Select(PrepareObjectView).Where(update => update != null).ToList();
updateEditorView = () => { foreach (var update in updates) update(); };
}
if (accepted && change.Edit != null) updateEditorView = PrepareObjectView(change.Edit);
return accepted;
if (change.Edit != null) updateEditorView = PrepareObjectView(change.Edit);
return true;
});
if ((string)resultChange["Status"] == "saved") updateEditorView?.Invoke();
return resultChange;

View File

@ -9,7 +9,7 @@ using System.Text.Json.Serialization;
namespace PLCSharp.Models;
public sealed record ProjectBatch(List<ProjectChange> Steps, List<CheckedFlow> Workflows, string[] ChangedFiles, Guid? UndoOf = null)
public sealed partial 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; }

View File

@ -15,8 +15,9 @@ public sealed class ProjectChanges
internal ProjectChange PendingOrInvalid(Guid id) => drafts[id];
public ProjectChange PendingScript(Guid id) =>
drafts.TryGetValue(id, out var draft) && (draft.Review != null || draft.Rename != null || draft.Edit != null || draft.Batch != null) && draft.Status == "pending" ? draft : null;
public static bool AgentApproval(JsonObject args) =>
args["confirmed"] is JsonValue value && value.TryGetValue<bool>(out var confirmed) ? confirmed :
throw new ArgumentException("保存需要 Agent 提交当前草案的确认结果。");
private JsonNode Remember(ProjectChange change)
{

View File

@ -1,27 +0,0 @@
<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"/>
<DockPanel Grid.Row="3">
<CheckBox x:Name="DetailsToggle" DockPanel.Dock="Top" Visibility="Collapsed" Content="查看字段差异、引用位置和文件路径" Margin="0,4,0,8" Checked="ToggleDetails" Unchecked="ToggleDetails"/>
<ScrollViewer x:Name="SummaryPanel" Visibility="Collapsed" VerticalScrollBarVisibility="Auto">
<TextBlock x:Name="ImpactSummary" TextWrapping="Wrap" FontSize="15" LineHeight="25"/>
</ScrollViewer>
<TextBox x:Name="CodeDiff" Grid.Row="3" AutomationProperties.Name="代码差异" IsReadOnly="True" FontFamily="Consolas"
VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Padding="8"/>
</DockPanel>
<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 x:Name="SaveChange" Content="确认保存" Click="Approve" Width="92"/>
</StackPanel>
</Grid>
</Window>

View File

@ -1,177 +0,0 @@
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();
if (change.Batch is { } batch) ShowBatch(batch);
else if (change.Edit is { } edit)
{
string action = edit.Action switch { "create" => "新增", "update" => "修改", _ => "删除" };
Title = $"确认{(edit.UndoOf.HasValue ? "撤销 · " : "")}{action}工程对象";
WorkflowTitle.Text = $"{action}{KindName(edit.Kind)}「{change.Name}」";
SaveChange.Content = edit.UndoOf.HasValue ? "确认撤销" : $"确认{action}";
Location.Text = System.IO.Path.Combine(root, edit.Path);
CheckResult.Text = $"已编译工作流 {edit.Workflows.Count},工作流引用 {edit.WorkflowReferences.Count},配置引用 {edit.ConfigReferences.Count},待核对 {edit.ManualReferences.Count}";
var lines = new List<string>();
foreach (var hit in edit.WorkflowReferences) lines.Add($"工作流 {hit["Name"]} · {hit["path"]}:{hit["line"]} {hit["expression"]}");
foreach (var link in edit.ConfigReferences) lines.Add($"配置 {link["path"]} · {link["table"]}/{link["id"]} · {link["field"]}");
foreach (var hit in edit.ManualReferences) lines.Add($"待核对 [{hit["confidence"]}] {hit["path"]}:{hit["line"]} {hit["expression"]}");
if (edit.Action == "delete" && lines.Count > 0) lines.Add("确认删除将保留上列引用,请核对删除后的影响。");
foreach (var owned in edit.OwnedRows) lines.Add($"{(owned.Restore ? "恢复" : "随对象删除")} {owned.Kind} · {owned.Name} · {owned.Id}");
foreach (var path in edit.ChangedFiles) lines.Add($"文件 {path}");
foreach (var key in (edit.Before ?? edit.After).Select(k => k.Key))
if (!System.Text.Json.Nodes.JsonNode.DeepEquals(edit.Before?[key], edit.After?[key]))
lines.Add($"{key}:{edit.Before?[key]} → {edit.After?[key]}");
CodeDiff.Text = string.Join("\n", lines);
Location.Visibility = Visibility.Collapsed;
DetailsToggle.Visibility = Visibility.Visible;
ToggleDetails(this, null);
CheckResult.Text = edit.Workflows.Count == 0 ? "本次未发现需要编译的工作流。" : $"{edit.Workflows.Count} 个相关工作流通过编译,尚未运行。";
var summary = new List<string>();
if (edit.UndoOf.HasValue) summary.Add($"这将撤销之前的操作,{WorkflowTitle.Text}。");
if (edit.Action == "update")
foreach (var field in edit.After.Where(p => !System.Text.Json.Nodes.JsonNode.DeepEquals(edit.Before[p.Key], p.Value)))
{
var label = field.Key switch { "Comment" => "备注", "Code" => "工作流脚本", "ControlName" => "绑定控件", "AutomaticExecution" => "自动运行", "CycleDelayTime" => "循环间隔", _ => field.Key };
string Brief(System.Text.Json.Nodes.JsonNode value) => value == null ? "(空)" : value.ToString();
var from = Brief(edit.Before[field.Key]);
var to = Brief(field.Value);
summary.Add(from.Length + to.Length < 100 ? $"{label}由「{from}」改为「{to}」。" : $"{label}已修改,完整内容可在字段差异中查看。");
}
foreach (var owned in edit.OwnedRows) summary.Add($"{(owned.Restore ? "一并恢复" : "一并删除")}{KindName(owned.Kind)}「{owned.Name}」。");
foreach (var hit in edit.WorkflowReferences) summary.Add($"工作流「{hit["Name"]}」第 {hit["line"]} 行引用此对象。");
foreach (var reference in edit.ConfigReferences) summary.Add($"{KindName((string)reference["table"])}配置中的 {reference["field"]} 引用了此对象。");
if (edit.Action == "delete" && edit.WorkflowReferences.Count > 0)
summary.Add("删除后,保留的工作流按原名称查找时可能找不到对象。");
foreach (var hit in edit.ManualReferences)
summary.Add($"需核对工作流「{hit["Name"]}」第 {hit["line"]} 行。目标名称取决于运行时的值。");
if (summary.Count == 0) summary.Add("未发现关联的配置或工作流。");
ImpactSummary.Text = string.Join("\n", summary);
}
else if (change.Rename is { } rename)
{
var subject = KindName(rename.Kind);
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.PointReferences.Select(p => $"configuration/points.json · {p.Table}/{p.Id} · {p.Field}:{rename.OldName} → {rename.NewName}")
.Concat(rename.CylinderReferences.Select(p => $"configuration/hardware.json · {p.Table}/{p.Id} · {p.Field}:{rename.OldName} → {rename.NewName}"))
.Concat(rename.VisionReferences.Select(e => $"configuration/vision.json · {e.FunctionId} · {(e.Index < 0 ? "功能" : $"步骤 {e.Index + 1}")} · {e.Key}:{rename.OldName} → {rename.NewName}"))
.Concat(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
{
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 ShowBatch(ProjectBatch batch)
{
bool undo = batch.UndoOf.HasValue;
Title = undo ? "确认整批撤销" : "确认整批保存";
WorkflowTitle.Text = $"{(undo ? "撤销" : "保存")}这批 {batch.Steps.Count} 项修改";
Location.Visibility = Visibility.Collapsed;
SaveChange.Content = undo ? "整批撤销" : "整批保存";
var lines = new List<string>();
var refs = new HashSet<string>();
var manual = new HashSet<string>();
var details = new List<string>(batch.ChangedFiles);
foreach (var step in undo ? batch.Steps.AsEnumerable().Reverse() : batch.Steps)
{
if (step.Edit is { } edit)
{
string action = (edit.Action, undo) switch { ("create", false) or ("delete", true) => "新增",
("delete", false) or ("create", true) => "删除", _ => "修改" };
var fields = new List<string>();
if (edit.Action == "update")
foreach (var (key, value) in edit.After)
{
if (System.Text.Json.Nodes.JsonNode.DeepEquals(edit.Before[key], value)) continue;
string from = (undo ? value : edit.Before[key])?.ToString() ?? "(空)";
string to = (undo ? edit.Before[key] : value)?.ToString() ?? "(空)";
string label = key switch { "Comment" => "备注", "Code" => "脚本", "ControlName" => "绑定控件", _ => key };
fields.Add(from.Length + to.Length <= 90 ? $"{label}由「{from}」改为「{to}」" : $"{label}有修改");
}
lines.Add($"{action}{KindName(edit.Kind)}「{step.Name}」" + (fields.Count == 0 ? "" : $",{string.Join(",", fields)}"));
foreach (var child in edit.OwnedRows) lines.Add($" 一并{(undo ? "恢复" : "删除")}{KindName(child.Kind)}「{child.Name}」");
foreach (var hit in edit.WorkflowReferences) refs.Add($"工作流「{hit["Name"]}」第 {hit["line"]} 行引用「{step.Name}」。");
foreach (var link in edit.ConfigReferences) refs.Add($"{KindName((string)link["table"])}的 {link["field"]} 引用「{step.Name}」。");
foreach (var hit in edit.ManualReferences) manual.Add($"「{hit["Name"]}」第 {hit["line"]} 行 · {hit["expression"]}");
details.Add($"{step.Name}\n{(undo ? edit.After : edit.Before)} → {(undo ? edit.Before : edit.After)}");
}
else if (step.Rename is { } rename)
{
lines.Add($"{KindName(rename.Kind)}「{(undo ? rename.NewName : rename.OldName)}」改名为「{(undo ? rename.OldName : rename.NewName)}」");
foreach (var flow in rename.Scripts) refs.Add($"工作流「{flow.Name}」同步更新。");
foreach (var hit in rename.ManualReferences) manual.Add($"「{hit["Name"]}」第 {hit["line"]} 行 · {hit["expression"]}");
foreach (var hit in rename.PointReferences.Concat(rename.MatrixReferences).Concat(rename.CylinderReferences))
refs.Add($"{KindName(hit.Table)}的 {hit.Field} 同步更新。");
foreach (var hit in rename.VisionReferences) refs.Add($"视觉功能的 {hit.Key} 同步更新。");
foreach (var flow in rename.Scripts) details.Add(flow.Review.Diff);
}
}
if (refs.Count > 0) { lines.Add("\n受影响的工作流和配置"); lines.AddRange(refs); }
if (manual.Count > 0) { lines.Add("\n需要人工核对的引用"); lines.AddRange(manual); }
CheckResult.Text = batch.Workflows.Count == 0 ? "本批没有需要编译的工作流。" :
$"工作流编译通过(未运行):{string.Join("、", batch.Workflows.Select(f=>f.Name))}";
foreach (var f in batch.Workflows)
foreach (var diagnostic in f.Diagnostics) details.Add($"{f.Name} · {diagnostic.Code} · {diagnostic.Message}");
ImpactSummary.Text = string.Join("\n", lines);
CodeDiff.Text = string.Join("\n", details);
DetailsToggle.Visibility = Visibility.Visible;
ToggleDetails(this, null);
}
private static string KindName(string kind) => kind switch { "VisionLocalVariables" => "视觉局部变量", "ControlMeasurements" => "控件测量项",
"InterpolationSegments" => "插补段", "InterpolationPoints" => "插补段内点", "Recipes" => "配方", "SystemVariables" => "系统变量", "CustomControls" => "主页控件",
"Matrices" => "轴矩阵", "RobotMatrices" => "机器人矩阵", "InterpolationGroups" => "插补组", "Cameras" => "相机", "ImageDatas" => "视觉图像数据", "LocalImageDatas" => "本地图像数据", "Cylinders" => "气缸", "Robots" => "机器人", "Connects" => "通信连接",
"DI" => "数字输入", "DQ" => "数字输出", "Axes" => "运动轴", "VisionFunctions" => "视觉功能", "Workflows" => "工作流",
"AxisPoints" or "RobotPoints" => "点位", "Controllers" => "运动控制器", "CanvasConfigs" => "主页画布", "Variables" => "配方变量", _ => kind };
private void ToggleDetails(object sender, RoutedEventArgs e)
{
bool details = DetailsToggle.IsChecked == true;
CodeDiff.Visibility = details ? Visibility.Visible : Visibility.Collapsed;
SummaryPanel.Visibility = details ? Visibility.Collapsed : Visibility.Visible;
}
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();
}
}

View File

@ -1,4 +1,4 @@
# PLCSharp PLC风格的上位机
# PLCSharp PLC风格的上位机
- 用户可以通过灵活配置硬件、界面、视觉工具、运动控制、编写工艺流程脚本完成项目开发。
@ -43,9 +43,15 @@
让 AI 先调用 `get_object` 读取工作流,再把该工作流的 ID 和完整 C# 源码传给 `preview_workflow_script`。返回值包含逐行差异、编译诊断和草案 ID。Roslyn 在内存中编译并校验 `Extension_<工作流ID的32位十六进制>` 的同步入口 `public void Run(GlobalModel, FlowModel)`。有编译错误的草案不能保存。
客户端以 `--allow-write` 启动后,可调用 `apply_changes` 请求保存。编辑器已打开时由编辑器显示 WPF 弹窗;离线时由本机 MCP 服务显示相同的弹窗,需要交互式 Windows 桌面。点击「确认保存」只写入预览中的脚本;点击「取消」或关闭窗口会拒绝草案。文件或编辑器文本变化后需要重新预览。运行新脚本仍使用原有的工作流编译和运行入口。
### 在 Agent 中确认整批修改
交互验收可运行 `python Tests/mcp_script_dialog_smoke.py <MCP可执行文件> <可移植验收样例目录>`,依次在两个弹窗中取消和确认。测试使用样例副本,验证错误诊断、编译结果、实际写入文件和重开后的变量引用。
同一句请求中的修改使用一次 `preview_batch(operations)`。Agent 展示返回的 `Batch.Summary`、动态引用和编译结果,按需展示各项差异。查询和预览均不会打开确认窗口或改动工程文件。
用户确认当前草案后,Agent 调用 `apply_changes(draftId, confirmed=true)`。用户拒绝时交回 `confirmed=false`,缺少确认参数的请求会被拒绝。保存仍需以 `--allow-write` 启动 MCP。WPF 编辑器和离线服务都直接处理 Agent 的确认结果。开发 Agent 客户端时,应将用户的确认动作绑定到所展示的草案 ID,重新预览后重新确认。
整批撤销使用已保存的草案 ID 调用 `preview_undo`,展示逆向变更后对撤销草案调用同一个保存工具。工程发生冲突时需要重新预览。撤销记录随编辑器或离线服务会话保存,最多缓存 256 个草案。
AI 可以在流程中按名称引用硬件、配方和点位;这些现有名称由人工维护。
### 跨对象重命名与撤销
@ -53,15 +59,7 @@
调用 `preview_workflow_rename(id, newName)` 可重命名配方中的工作流,并更新同一配方脚本中能确定的 `GetTask` 常量参数和直接查询 `WorkflowsModel.Workflows` 时的名称相等比较。请逐项检查 `ManualReferences` 中的运行时表达式。工作流 ID 和脚本文件路径保持稳定。
调用 `preview_point_rename(kind, id, newName)` 可重命名轴点位(`AxisPoints`)或机器人点位(`RobotPoints`)。预览会列出同一配方的脚本差异,以及矩阵的起点、X 端点、Y 端点引用(`MatrixReferences`)。轴点位支持直接查询 `ControllersModel.AxisPoints` 时的名称相等比较。机器人点位按所属机器人匹配,支持通过常量名称直接选择唯一机器人后的 `RunPoint`、`Jog` 和 `Points` 查询。运行时名称和无法判定所属机器人的调用会列入 `ManualReferences`,供人工核对。
调用 `preview_vision_function_rename(id, newName)` 可重命名配方中的视觉功能。预览包括同一配方内 `GetVisionFunction` 的常量名称参数,以及直接查询 `VisionsModel.VisionFunctions` 时的名称相等比较。请核对 `ManualReferences` 中的动态或不确定引用。确认后一起保存 `configuration/vision.json` 和受影响的脚本。
调用 `preview_axis_rename(id, newName)` 可按硬件 ID 重命名工程运动轴。预览扫描所有配方的脚本,识别直接查询轴集合时的轴名相等比较,并将动态或不确定的匹配列入 `ManualReferences`。点位的 X、Y、Z、U 轴名及插补组的 X、Y 轴名列在 `PointReferences`。确认后一起保存硬件配置、点位配置和受影响的脚本。
调用 `preview_device_rename(kind, id, newName)` 可按 ID 重命名气缸(`Cylinders`)、机器人(`Robots`)或通信连接(`Connects`)。工具检查所有配方脚本,识别设备集合上的名称相等比较、`GetRobot`、`GetConnect` 和通信数据写入方法中可确定的连接名参数。预览返回代码差异、编译结果和 `ManualReferences`。机器人点位和矩阵通过 `RobotID` 关联。连续保存多项修改时,可按保存的相反顺序逐项撤销。
核对后将草案 ID 交给 `apply_changes`,在 WPF 弹窗确认后一起保存名称和受影响的脚本。要撤销,把**已保存的重命名草案 ID** 传给 `preview_undo`,再对返回的**撤销草案 ID** 调用 `apply_changes` 并确认。变量 ID 始终保留。撤销记录保存在处理本次请求的编辑器或离线 MCP 服务会话中,沿用最近 256 个草案的缓存;关闭会话后记录失效。名称所在的 JSON 文件或该配方的脚本发生冲突时会停止写入。
视觉功能、图像数据和流程变量等允许改名的对象也可以用批次中的 `rename` 操作。每一步的差异和动态引用会随整批草案返回。
## 界面展示