XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
返回提交历史

XFEstudio/XFEWorkflow

完善嵌套节点封装、同插件方法组合和运行时依赖回溯

c777d15
XFE工作室室长 <mail@xfegzs.com>
提交于

代码差异

6 个文件 +126 -52
Modified XFEWorkflow/XFEWorkflow.Core/Runtime/NodeEncapsulation.cs +36 -8
@@ -15,11 +15,15 @@ public sealed class NodeEncapsulation
15 15 selection = ids.ToHashSet(); var chosen = graph.Nodes.Where(x => selection.Contains(x.Id)).ToArray();
16 16 if (chosen.Length == 0 || chosen.Any(x => x.CapabilityId is "core.start" or "core.end" || WorkflowTriggerNodes.IsTrigger(x)))
17 17 throw new ArgumentException("请选择动作节点进行封装,开始、结束和触发节点保留在原工作流中");
18 var variableWrites = chosen.Where(x => x.CapabilityId == "core.set").Select(x => x.Parameters.String("name")).ToHashSet();
18 var allNodes = Descendants(graph.Nodes).ToDictionary(x => x.Id);
19 var inside = Descendants(chosen).Select(x => x.Id).ToHashSet();
20 var variableWrites = Descendants(chosen).Where(x => x.CapabilityId == "core.set").Select(x => x.Parameters.String("name"))
21 .Concat(Descendants(chosen).Where(x => x.CapabilityId == "core.foreach").SelectMany(x => new[] { x.Parameters.String("itemName", "item"), "index" }))
22 .Concat(Descendants(chosen).Where(x => x.CapabilityId == "core.try").Select(_ => "error")).ToHashSet();
19 23 bool UsesVariable(JsonNode? value, Func<string, bool> predicate) => value is JsonObject obj
20 24 ? (obj.Count == 1 && obj["$var"] is { } v && predicate(v.Text().Split('.')[0])) || obj.Any(x => UsesVariable(x.Value, predicate))
21 25 : value is JsonArray array && array.Any(x => UsesVariable(x, predicate));
22 if (chosen.Any(x => UsesVariable(x.Parameters, name => !variableWrites.Contains(name))) || graph.Nodes.Where(x => !selection.Contains(x.Id)).Any(x => UsesVariable(x.Parameters, variableWrites.Contains)))
26 if (Descendants(chosen).Any(x => UsesVariable(x.Parameters, name => !variableWrites.Contains(name))) || allNodes.Values.Where(x => !inside.Contains(x.Id)).Any(x => UsesVariable(x.Parameters, variableWrites.Contains)))
23 27 throw new ArgumentException("选区与外部共享了变量,请先改成数据端口或参数 / 返回值再封装,以保留变量作用域");
24 28 var incoming = graph.Edges.Where(x => x.Kind == PortKind.Execution && !selection.Contains(x.FromNode) && selection.Contains(x.ToNode)).Select(x => x.ToNode).Distinct().ToArray();
25 29 var roots = chosen.Where(x => !graph.Edges.Any(e => e.Kind == PortKind.Execution && e.ToNode == x.Id && selection.Contains(e.FromNode))).Select(x => x.Id).ToArray();
@@ -34,23 +38,36 @@ public sealed class NodeEncapsulation
34 38 if (tails.Length != 1 || catalog[tails[0].CapabilityId].ExecutionOutputs.Count != 1) throw new ArgumentException("请先将执行分支汇合,再封装节点");
35 39 exit = (tails[0].Id, catalog[tails[0].CapabilityId].ExecutionOutputs[0]);
36 40 }
41 foreach (var node in chosen)
42 foreach (var port in GraphValidator.ExecutionOutputs(node, catalog[node.CapabilityId]))
43 if (!graph.Edges.Any(e => e.Kind == PortKind.Execution && e.FromNode == node.Id && e.FromPort == port) && (node.Id, port) != exit.Value)
44 throw new ArgumentException("选区包含提前结束的分支,请将所有执行分支汇合后再封装");
37 45 Method = new() { Name = name, Graph = WorkflowJson.Clone(new GraphDefinition { Nodes = chosen.ToList(), Edges = graph.Edges.Where(x => selection.Contains(x.FromNode) && selection.Contains(x.ToNode)).ToList() }) };
38 46 string Add((string Node, string Port) source, bool output)
39 47 {
40 48 var map = output ? outputs : inputs; if (map.TryGetValue(source, out var known)) return known;
41 49 var key = (output ? "out" : "arg") + (map.Count + 1); map[source] = key;
42 var node = graph.Nodes.Single(x => x.Id == source.Node);
50 if (source.Node.Length == 0)
51 { Method.Inputs.Add(new() { Name = key, Label = "工作流输入 · " + (source.Port.Length == 0 ? "全部" : source.Port), Type = source.Port.Length == 0 ? WorkflowValueType.Object : WorkflowValueType.Any }); return key; }
52 var node = allNodes[source.Node];
43 53 var port = catalog[node.CapabilityId].Outputs.FirstOrDefault(x => x.Name == source.Port);
44 54 (output ? Method.Outputs : Method.Inputs).Add(new() { Name = key, Label = (node.Name.Length > 0 ? node.Name : catalog[node.CapabilityId].Name) + " · " + (port?.Label ?? source.Port), Type = port?.Type ?? WorkflowValueType.Any }); return key;
45 55 }
56 foreach (var node in Descendants(Method.Graph.Nodes))
57 {
58 RewriteInputs(node.Parameters, path =>
59 { var parts = path.Split('.', 2); return Add(("", parts[0]), false) + (parts.Length == 2 ? "." + parts[1] : ""); });
60 Rewrite(node.Parameters, (source, port, suffix) => !inside.Contains(source) ? new JsonObject { ["$input"] = Add((source, port), false) + suffix }
61 : allNodes[source].CapabilityId == "core.start" && port == "inputs" ? new JsonObject { ["$input"] = Add(("", suffix.TrimStart('.')), false) } : null);
62 }
46 63 foreach (var edge in graph.Edges.Where(x => x.Kind == PortKind.Data && !selection.Contains(x.FromNode) && selection.Contains(x.ToNode)))
47 64 Method.Graph.Nodes.Single(x => x.Id == edge.ToNode).Parameters[edge.ToPort] = new JsonObject { ["$input"] = Add((edge.FromNode, edge.FromPort), false) };
48 65 foreach (var edge in graph.Edges.Where(x => x.Kind == PortKind.Data && selection.Contains(x.FromNode) && !selection.Contains(x.ToNode))) Add((edge.FromNode, edge.FromPort), true);
49 foreach (var node in Method.Graph.Nodes) Rewrite(node.Parameters, (source, port, suffix) => !selection.Contains(source) ? new JsonObject { ["$input"] = Add((source, port), false) + suffix } : null);
50 foreach (var node in graph.Nodes.Where(x => !selection.Contains(x.Id))) Scan(node.Parameters, (source, port, _) => { if (selection.Contains(source)) Add((source, port), true); });
66 foreach (var node in allNodes.Values.Where(x => !inside.Contains(x.Id))) Scan(node.Parameters, (source, port, _) => { if (inside.Contains(source)) Add((source, port), true); });
51 67 var start = new NodeDefinition { CapabilityId = "core.start", Name = "参数", X = chosen.Min(x => x.X) - 320, Y = chosen.Min(x => x.Y) };
52 68 var end = new NodeDefinition { CapabilityId = "core.end", Name = "返回值", X = chosen.Max(x => x.X) + 320, Y = chosen.Max(x => x.Y) };
53 foreach (var pair in outputs) end.Parameters[pair.Value] = new JsonObject { ["$node"] = pair.Key.Node + "." + pair.Key.Port };
69 foreach (var pair in outputs) end.Parameters[pair.Value] = allNodes[pair.Key.Node].CapabilityId == "core.start" && pair.Key.Port == "inputs"
70 ? new JsonObject { ["$input"] = Add(("", ""), false) } : new JsonObject { ["$node"] = pair.Key.Node + "." + pair.Key.Port };
54 71 if (outputs.Count == 0) end.Parameters["result"] = new JsonObject();
55 72 Method.Graph.Nodes.Add(start); Method.Graph.Nodes.Add(end); Method.Graph.Edges.Add(new() { FromNode = start.Id, ToNode = entry });
56 73 Method.Graph.Edges.Add(new() { FromNode = exit.Value.Node, FromPort = exit.Value.Port, ToNode = end.Id });
@@ -59,7 +76,7 @@ public sealed class NodeEncapsulation
59 76 {
60 77 var result = WorkflowJson.Clone(original); var chosen = result.Nodes.Where(x => selection.Contains(x.Id)).ToArray();
61 78 var replacement = new NodeDefinition { CapabilityId = capability, Name = Method.Name, X = chosen.Min(x => x.X), Y = chosen.Min(x => x.Y) };
62 foreach (var pair in inputs) replacement.Parameters[pair.Value] = new JsonObject { ["$node"] = pair.Key.Node + "." + pair.Key.Port };
79 foreach (var pair in inputs) replacement.Parameters[pair.Value] = pair.Key.Node.Length == 0 ? new JsonObject { ["$input"] = pair.Key.Port } : new JsonObject { ["$node"] = pair.Key.Node + "." + pair.Key.Port };
63 80 result.Edges.RemoveAll(x => selection.Contains(x.FromNode) && selection.Contains(x.ToNode));
64 81 foreach (var edge in result.Edges)
65 82 {
@@ -67,10 +84,21 @@ public sealed class NodeEncapsulation
67 84 if (selection.Contains(edge.FromNode)) { var node = edge.FromNode; edge.FromNode = replacement.Id; edge.FromPort = edge.Kind == PortKind.Execution ? "next" : outputs[(node, edge.FromPort)]; }
68 85 }
69 86 result.Nodes.RemoveAll(x => selection.Contains(x.Id));
70 foreach (var node in result.Nodes) Rewrite(node.Parameters, (source, port, suffix) => selection.Contains(source) ? new JsonObject { ["$node"] = replacement.Id + "." + outputs[(source, port)] + suffix } : null);
87 var removed = Descendants(chosen).Select(x => x.Id).ToHashSet();
88 foreach (var node in Descendants(result.Nodes)) Rewrite(node.Parameters, (source, port, suffix) => removed.Contains(source) ? new JsonObject { ["$node"] = replacement.Id + "." + outputs[(source, port)] + suffix } : null);
71 89 result.Nodes.Add(replacement); return result;
72 90 }
73 91 private static void Scan(JsonNode? value, Action<string, string, string> action) => Rewrite(value, (node, port, suffix) => { action(node, port, suffix); return null; });
92 private static IEnumerable<NodeDefinition> Descendants(IEnumerable<NodeDefinition> nodes) => nodes.SelectMany(x => new[] { x }.Concat(Descendants(x.Children.Values.SelectMany(g => g.Nodes))));
93 private static void RewriteInputs(JsonNode? value, Func<string, string> replace)
94 {
95 if (value is JsonObject obj)
96 {
97 if (obj.Count == 1 && obj["$input"] is JsonValue input) obj["$input"] = replace(input.GetValue<string>());
98 else foreach (var child in obj.ToArray()) RewriteInputs(child.Value, replace);
99 }
100 else if (value is JsonArray array) foreach (var child in array) RewriteInputs(child, replace);
101 }
74 102 private static void Rewrite(JsonNode? value, Func<string, string, string, JsonObject?> replace)
75 103 {
76 104 if (value is JsonObject obj)
Modified XFEWorkflow/XFEWorkflow.Infrastructure/Plugins/GraphPluginBuilder.cs +23 -11
@@ -32,26 +32,37 @@ public sealed class GraphPluginBuilder(PluginManager plugins)
32 32 throw new ArgumentException("一个插件需要 1 到 128 个方法,方法 ID 不能重复");
33 33 var manifest = new PluginManifest { Id = project.Id, Name = project.Name, Version = project.Version, Author = project.Author, Description = project.Description,
34 34 SdkMinimumVersion = "1.3.0", Assembly = "XFEWorkflow.GeneratedPlugin.dll", EntryType = "XFEWorkflow.Generated.Plugin" };
35 var required = new Dictionary<string, InstalledPlugin>();
36 35 foreach (var method in project.Methods)
37 36 {
38 37 WorkspacePaths.RequireId(method.Id);
38 manifest.Capabilities.Add(new() { Id = project.Id + "." + method.Id, PluginId = project.Id, Name = method.Name, Category = method.Category,
39 Description = method.Workflow.Description, Inputs = WorkflowJson.Clone(method.Workflow.Inputs), Outputs = WorkflowJson.Clone(method.Workflow.Outputs.Count > 0 ? method.Workflow.Outputs : [new PortDefinition { Name = "result", Label = "返回值", Type = WorkflowValueType.Any }]) });
40 }
41 var dependencyFlow = new WorkflowDefinition();
42 foreach (var method in project.Methods)
43 {
39 44 var workflow = method.Workflow;
40 45 if (WorkflowTriggerNodes.Enumerate(workflow).Any() || workflow.Triggers.Count > 0) throw new ArgumentException("方法不能包含自动触发节点;请保留触发器,在其后封装动作");
41 var errors = GraphValidator.Validate(workflow, plugins.Catalog(workflow));
46 var nodes = Nodes(workflow.Graph).ToArray();
47 if (nodes.Any(x => x.CapabilityId == "core.subworkflow")) throw new ArgumentException("子工作流 ID 属于本机工作区,请先将子工作流封装为插件节点,再引用该节点制作可分享的插件");
48 var catalog = plugins.Catalog(workflow).Where(x => x.Value.PluginId != project.Id).ToDictionary(x => x.Key, x => x.Value);
49 foreach (var capability in manifest.Capabilities) catalog[capability.Id] = capability;
50 var errors = GraphValidator.Validate(workflow, catalog);
42 51 if (errors.Any(x => x.IsError)) throw new ArgumentException(string.Join("\n", errors.Select(x => x.Message)));
43 foreach (var dependency in plugins.Resolve(workflow))
52 var used = nodes.Where(x => !x.CapabilityId.StartsWith("core.", StringComparison.Ordinal) && !x.CapabilityId.StartsWith(project.Id + ".", StringComparison.Ordinal)).ToArray();
53 dependencyFlow.Graph.Nodes.AddRange(used);
54 var hasCode = workflow.Kind == WorkflowKind.CSharp || nodes.Any(x => x.CapabilityId == "core.csharp");
55 var ids = used.Select(x => catalog[x.CapabilityId].PluginId).ToHashSet();
56 foreach (var locked in workflow.PluginVersions.Where(x => x.Key != project.Id && (hasCode || ids.Contains(x.Key))))
44 57 {
45 if (dependency.Manifest.Id == project.Id) throw new ArgumentException("插件方法不能依赖自身");
46 if (required.TryGetValue(dependency.Manifest.Id, out var previous) && previous.Manifest.Version != dependency.Manifest.Version)
47 throw new ArgumentException("不同方法的依赖版本冲突:" + dependency.Manifest.Id);
48 required[dependency.Manifest.Id] = dependency;
58 if (dependencyFlow.PluginVersions.TryGetValue(locked.Key, out var previous) && previous != locked.Value) throw new ArgumentException("不同方法的依赖版本冲突:" + locked.Key);
59 dependencyFlow.PluginVersions[locked.Key] = locked.Value;
49 60 }
50 manifest.Capabilities.Add(new() { Id = project.Id + "." + method.Id, PluginId = project.Id, Name = method.Name, Category = method.Category,
51 Description = workflow.Description, Inputs = WorkflowJson.Clone(workflow.Inputs), Outputs = WorkflowJson.Clone(workflow.Outputs.Count > 0 ? workflow.Outputs : [new PortDefinition { Name = "result", Label = "返回值", Type = WorkflowValueType.Any }]) });
61 workflow.PluginVersions.Remove(project.Id);
52 62 }
53 manifest.Dependencies = required.Values.OrderBy(x => x.Manifest.Id).Select(x => new PluginDependency { Id = x.Manifest.Id, MinimumVersion = x.Manifest.Version, ExactVersion = x.Manifest.Version }).ToList();
54 manifest.Permissions = required.Values.SelectMany(x => x.Manifest.Permissions).Distinct().Order().ToList();
63 var required = plugins.Resolve(dependencyFlow);
64 manifest.Dependencies = required.OrderBy(x => x.Manifest.Id).Select(x => new PluginDependency { Id = x.Manifest.Id, MinimumVersion = x.Manifest.Version, ExactVersion = x.Manifest.Version }).ToList();
65 manifest.Permissions = required.SelectMany(x => x.Manifest.Permissions).Distinct().Order().ToList();
55 66 PluginPackage.Validate(manifest); return manifest;
56 67 }
57 68 public async Task<PluginManifest> BuildAsync(GraphPluginProject project, string destination, CancellationToken ct = default)
@@ -86,4 +97,5 @@ public sealed class GraphPluginBuilder(PluginManager plugins)
86 97 finally { Directory.Delete(folder, true); }
87 98 }
88 99 private static string Literal(string value) => JsonSerializer.Serialize(value);
100 private static IEnumerable<NodeDefinition> Nodes(GraphDefinition graph) => graph.Nodes.Concat(graph.Nodes.SelectMany(x => x.Children.Values).SelectMany(Nodes));
89 101 }
Modified XFEWorkflow/XFEWorkflow.Infrastructure/Plugins/PluginManager.cs +15 -32
@@ -106,45 +106,28 @@ public sealed class PluginManager(WorkspacePaths paths, ClientState state)
106 106 public List<InstalledPlugin> Resolve(WorkflowDefinition workflow)
107 107 {
108 108 var available = Installed.Where(x => x.Enabled && !x.PendingRemoval).ToList();
109 var resolved = new Dictionary<string, InstalledPlugin>();
110 void Add(string id, string? version = null)
111 {
112 if (workflow.PluginVersions.TryGetValue(id, out var locked)) version = locked;
113 if (resolved.TryGetValue(id, out var existing))
114 {
115 if (version is not null && version != existing.Manifest.Version) throw new InvalidOperationException("插件版本冲突:" + id);
116 return;
117 }
118 var plugin = available.Where(x => x.Manifest.Id == id && (version is null || x.Manifest.Version == version))
119 .MaxBy(x => SemanticVersion.Parse(x.Manifest.Version))
120 ?? throw new InvalidOperationException($"缺少或已禁用插件:{id} {version}");
121 var rid = System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier;
122 if (plugin.Manifest.SupportedRids.Count > 0 && !plugin.Manifest.SupportedRids.Contains(rid))
123 throw new PlatformNotSupportedException($"插件 {id} 不支持 {rid}");
124 resolved.Add(id, plugin);
125 foreach (var dependency in plugin.Manifest.Dependencies)
126 {
127 if (!resolved.ContainsKey(dependency.Id) && !workflow.PluginVersions.ContainsKey(dependency.Id))
128 {
129 var candidate = available.Where(x => x.Manifest.Id == dependency.Id && InRange(x.Manifest.Version, dependency))
130 .MaxBy(x => SemanticVersion.Parse(x.Manifest.Version)) ?? throw new InvalidOperationException("缺少插件依赖:" + dependency.Id);
131 Add(dependency.Id, candidate.Manifest.Version);
132 }
133 else Add(dependency.Id);
134 if (!InRange(resolved[dependency.Id].Manifest.Version, dependency)) throw new InvalidOperationException("依赖版本不兼容:" + dependency.Id);
135 }
136 }
137 foreach (var locked in workflow.PluginVersions) Add(locked.Key, locked.Value);
109 var requiredCapabilities = new Dictionary<string, HashSet<string>>();
138 110 foreach (var capability in UsedCapabilities(workflow.Graph).Concat(WorkflowTriggerNodes.Enumerate(workflow).Where(x => x.Kind == TriggerKind.Plugin).Select(x => x.CapabilityId)).Concat(workflow.Triggers.Where(x => x.Kind == TriggerKind.Plugin).Select(x => x.CapabilityId)))
139 111 {
140 112 if (capability.StartsWith("core.", StringComparison.Ordinal)) continue;
141 113 var id = available.FirstOrDefault(x => x.Manifest.Capabilities.Any(c => c.Id == capability))?.Manifest.Id
142 114 ?? throw new InvalidOperationException("找不到节点能力:" + capability);
143 Add(id);
115 if (!requiredCapabilities.TryGetValue(id, out var required)) requiredCapabilities[id] = required = [];
116 required.Add(capability);
144 117 }
145 return resolved.Values.ToList();
118 var roots = workflow.PluginVersions.Keys.Concat(requiredCapabilities.Keys).Distinct().ToArray();
119 if (roots.Length == 0) return [];
120 var root = new PluginManifest { Id = "$workflow", Version = "1.0.0", Dependencies = roots.Select(id => new PluginDependency
121 { Id = id, MinimumVersion = "0.0.0", ExactVersion = workflow.PluginVersions.GetValueOrDefault(id) }).ToList() };
122 var rid = System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier;
123 // This resolver receives only completed in-memory tasks, so it never blocks
124 // on the UI synchronization context. Installation and execution use one solver.
125 var solution = PluginDependencyResolver.ResolveAsync(root, (id, _) => Task.FromResult(available
126 .Where(x => x.Manifest.Id == id && (x.Manifest.SupportedRids.Count == 0 || x.Manifest.SupportedRids.Contains(rid))
127 && (!requiredCapabilities.TryGetValue(id, out var capabilities) || capabilities.All(capability => x.Manifest.Capabilities.Any(c => c.Id == capability))))
128 .Select(x => x.Manifest).ToList())).GetAwaiter().GetResult();
129 return solution.Where(x => x.Id != root.Id).Select(x => available.Single(p => p.Manifest.Id == x.Id && p.Manifest.Version == x.Version)).ToList();
146 130 }
147 private static bool InRange(string version, PluginDependency dependency) => dependency.Accepts(version);
148 131 private static IEnumerable<string> UsedCapabilities(GraphDefinition graph) =>
149 132 graph.Nodes.Select(x => x.CapabilityId).Concat(graph.Nodes.SelectMany(x => x.Children.Values).SelectMany(UsedCapabilities));
150 133 public async Task<IAsyncDisposable> AcquireAsync(IEnumerable<InstalledPlugin> plugins, CancellationToken ct = default)
Modified XFEWorkflow/XFEWorkflow.Test/GraphPluginTests.cs +43 -0
@@ -67,4 +67,47 @@ public class GraphPluginTests
67 67 b.Dependencies = [new PluginDependency { Id = "user.root" }];
68 68 await Assert.ThrowsAsync<InvalidOperationException>(() => PluginDependencyResolver.ResolveAsync(root, (id, _) => Task.FromResult(versions.Where(x => x.Id == id).ToList())));
69 69 }
70 [Test]
71 public async Task NestedSelectionPreservesWorkflowInputsExternalNodesAndLoopVariables()
72 {
73 await using var workspace = new TestWorkspace(); var plugins = new PluginManager(workspace.Paths, workspace.State);
74 var source = new NodeDefinition { CapabilityId = "core.set", Parameters = new() { ["name"] = "source", ["value"] = "外部" } };
75 var body = TestSupport.Graph(); var bodyEnd = body.Graph.Nodes[^1];
76 bodyEnd.Parameters["result"] = new JsonObject { ["source"] = new JsonObject { ["$node"] = source.Id + ".value" }, ["note"] = new JsonObject { ["$input"] = "note" }, ["item"] = new JsonObject { ["$var"] = "item" } };
77 var loop = new NodeDefinition { CapabilityId = "core.foreach", Parameters = new() { ["items"] = new JsonArray(1, 2) }, Children = new() { ["body"] = body.Graph } };
78 var flow = TestSupport.Graph(source, loop); flow.Graph.Nodes[^1].Parameters["result"] = new JsonObject { ["$node"] = bodyEnd.Id + ".result" };
79 var selection = new NodeEncapsulation(flow.Graph, [loop.Id], plugins.Catalog(), "嵌套方法");
80 var project = new GraphPluginProject { Id = "user.nested", Name = "嵌套流程", Methods = [new() { Workflow = selection.Method }] };
81 var package = Path.Combine(workspace.Paths.Temp, "nested.xfeplugin"); await new GraphPluginBuilder(plugins).BuildAsync(project, package); await plugins.InstallAsync(package);
82 flow.Graph = selection.Replace(flow.Graph, "user.nested.run");
83 await using var coordinator = new RunCoordinator(workspace.Paths, plugins, new(workspace.State), new(), TestSupport.FindOutput("XFEWorkflow.Runner", "XFEWorkflow.Runner.exe"));
84 var run = await coordinator.RunAsync(flow, inputs: new() { ["note"] = "输入" }); Assert.Equal(RunStatus.Succeeded, run.Status, run.Error);
85 Assert.Equal("外部", run.Outputs["result"]!["source"]!.GetValue<string>()); Assert.Equal("输入", run.Outputs["result"]!["note"]!.GetValue<string>()); Assert.Equal(2, run.Outputs["result"]!["item"]!.GetValue<int>());
86 var branch = new NodeDefinition { CapabilityId = "core.if", Parameters = new() { ["left"] = true } }; var unsafeFlow = TestSupport.Graph(branch); unsafeFlow.Graph.Edges.Single(x => x.FromNode == branch.Id).FromPort = "true";
87 Assert.Throws<ArgumentException>(() => new NodeEncapsulation(unsafeFlow.Graph, [branch.Id], plugins.Catalog(), "不能改变提前结束语义"));
88 }
89 [Test]
90 public async Task MethodsWithinOnePluginComposeWithoutSelfDependencyOrUnusedGraphLocks()
91 {
92 await using var workspace = new TestWorkspace(); var plugins = new PluginManager(workspace.Paths, workspace.State);
93 var first = TestSupport.Graph(); first.Outputs = [new() { Name = "text", Type = WorkflowValueType.String }]; first.Graph.Nodes[^1].Parameters["text"] = "方法返回值";
94 first.PluginVersions["unused.plugin"] = "9.0.0";
95 var call = new NodeDefinition { CapabilityId = "user.methods.first" }; var second = TestSupport.Graph(call); second.Outputs = WorkflowJson.Clone(first.Outputs);
96 second.Graph.Nodes[^1].Parameters["text"] = new JsonObject { ["$node"] = call.Id + ".text" };
97 var project = new GraphPluginProject { Id = "user.methods", Name = "组合方法", Methods = [new() { Id = "first", Workflow = first }, new() { Id = "second", Workflow = second }] };
98 var package = Path.Combine(workspace.Paths.Temp, "methods.xfeplugin"); var manifest = await new GraphPluginBuilder(plugins).BuildAsync(project, package); Assert.Equal(0, manifest.Dependencies.Count); await plugins.InstallAsync(package);
99 var node = new NodeDefinition { CapabilityId = "user.methods.second" }; var flow = TestSupport.Graph(node); flow.Graph.Nodes[^1].Parameters["result"] = new JsonObject { ["$node"] = node.Id + ".text" };
100 await using var coordinator = new RunCoordinator(workspace.Paths, plugins, new(workspace.State), new(), TestSupport.FindOutput("XFEWorkflow.Runner", "XFEWorkflow.Runner.exe"));
101 var run = await coordinator.RunAsync(flow); Assert.Equal(RunStatus.Succeeded, run.Status, run.Error); Assert.Equal("方法返回值", run.Outputs.String("result"));
102 }
103 [Test]
104 public async Task RuntimeDependencyResolutionBacktracksAndHonorsExplicitLocks()
105 {
106 await using var workspace = new TestWorkspace(); var plugins = new PluginManager(workspace.Paths, workspace.State);
107 InstalledPlugin P(string id, string version, params PluginDependency[] dependencies) => new() { Manifest = new() { Id = id, Name = id, Version = version, Assembly = "fixture.dll", EntryType = "Fixture", Dependencies = dependencies.ToList(), Capabilities = [new() { Id = id + ".run", PluginId = id }] } };
108 workspace.State.Store.Update(p => p.InstancePlugins = [P("user.a", "2.0.0", new PluginDependency { Id = "user.shared", MinimumVersion = "2.0.0" }), P("user.a", "1.0.0", new PluginDependency { Id = "user.shared", MaximumVersionExclusive = "2.0.0" }), P("user.b", "1.0.0", new PluginDependency { Id = "user.shared", MaximumVersionExclusive = "2.0.0" }), P("user.shared", "2.0.0"), P("user.shared", "1.0.0")]);
109 var flow = TestSupport.Graph(new NodeDefinition { CapabilityId = "user.a.run" }, new NodeDefinition { CapabilityId = "user.b.run" }); var resolved = plugins.Resolve(flow);
110 Assert.Equal("1.0.0", resolved.Single(x => x.Manifest.Id == "user.a").Manifest.Version); Assert.Equal("1.0.0", resolved.Single(x => x.Manifest.Id == "user.shared").Manifest.Version);
111 flow.PluginVersions["user.a"] = "2.0.0"; Assert.Throws<InvalidOperationException>(() => plugins.Resolve(flow));
112 }
70 113 }
Modified XFEWorkflow/XFEWorkflow/ViewModels/MainPageViewModel.cs +5 -1
@@ -140,7 +140,11 @@ public partial class MainPageViewModel : ViewModelBase
140 140 }
141 141 private void LockPlugins(WorkflowDefinition workflow)
142 142 {
143 foreach (var plugin in services.Plugins.Installed.Where(x => x.Enabled && !x.PendingRemoval).GroupBy(x => x.Manifest.Id).Select(x => x.MaxBy(p => SemanticVersion.Parse(p.Manifest.Version))!)) workflow.PluginVersions.TryAdd(plugin.Manifest.Id, plugin.Manifest.Version);
143 IEnumerable<NodeDefinition> Nodes(GraphDefinition graph) => graph.Nodes.Concat(graph.Nodes.SelectMany(x => x.Children.Values).SelectMany(Nodes));
144 var nodes = Nodes(workflow.Graph).ToArray(); var code = string.Join("\n", nodes.Select(x => x.Code).Prepend(workflow.Kind == WorkflowKind.CSharp ? workflow.Code : ""));
145 foreach (var plugin in services.Plugins.Installed.Where(x => x.Enabled && !x.PendingRemoval).GroupBy(x => x.Manifest.Id).Select(x => x.MaxBy(p => SemanticVersion.Parse(p.Manifest.Version))!))
146 if (nodes.Any(x => plugin.Manifest.Capabilities.Any(c => c.Id == x.CapabilityId)) || code.Contains(plugin.Manifest.Id, StringComparison.Ordinal) || code.Contains("XfePlugins." + Infrastructure.Compilation.PluginMethodBindings.Identifier(plugin.Manifest.Id) + ".", StringComparison.Ordinal))
147 workflow.PluginVersions.TryAdd(plugin.Manifest.Id, plugin.Manifest.Version);
144 148 }
145 149 private static bool HasCode(GraphDefinition graph) => graph.Nodes.Any(x => x.CapabilityId == "core.csharp" || x.Children.Values.Any(HasCode));
146 150 public async Task SaveAsync()
Modified docs/graph-plugin-authoring.md +4 -0
@@ -2,6 +2,8 @@
2 2
3 3 在编辑器中框选一段动作节点,选择“保存为节点 / 制作插件”。封装保留一个执行入口和出口,自动将跨选区的数据连线、`$node` 引用转成参数和返回值,安装成功后将选区替换成单个节点,可撤销。分支先汇合;开始、结束与触发器留在外层。
4 4
5 嵌套循环和结构化子图也会扫描跨边界引用,保留工作流输入与循环变量。存在提前结束的分支时需先汇合,避免封装后改变外层执行路径。选区与外部共享的变量请先改成参数或返回值。引用本机子工作流的固定 ID 不能直接分享,请先将该子工作流封装为插件节点,再引用该节点。
6
5 7 不选择节点时,可将整个工作流封装为方法。在工作流设置中定义 `inputs` 与 `outputs`:输入名称会出现在开始节点的数据输出,返回值名称出现在结束节点的数据输入。多个返回值分别接到结束节点,也可用参数中的 `$node` 绑定。每次调用隔离输入、变量与内部节点结果,取消沿调用链传播。
6 8
7 9 插件 ID 相同可以继续添加方法,方法 ID 相同更新该方法的草稿。源工程保存在工作区 `PluginProjects/<插件ID>/project.json`,生成包中也包含可编辑的 `project.json`。已经安装或发布的版本不可覆盖,请提高版本号。插件中心可导出 `.xfeplugin`,在“我的发布”中提交到 Space。
@@ -20,6 +22,8 @@ var result = await context.InvokeAsync("user.demo.run", new JsonObject { ["name"
20 22
21 23 打包锁定引用插件的具体版本,并汇总权限。依赖实现 DLL 不会嵌入包或相互引用;各插件继续由独立加载上下文加载,共享 SDK。纯 C# 的动态能力 ID 无法静态推断,请在工作流设置中声明所需插件版本。
22 24
25 同一插件中的方法可以互相调用,引用的方法必须包含在本次插件工程中,无需声明自身为依赖。纯图形方法会清理无关的旧版本锁定;代码节点保留显式声明的依赖。编辑器只自动锁定图形引用及能从代码识别到的插件,不会因为切换到 C# 而锁定全部已安装插件。运行时和安装时使用相同的全局依赖解析,支持多个已安装版本之间的回溯,同时严格遵守显式版本锁定。
26
23 27 Space 下载及客户端本地导入都会先解析完整依赖链、检查版本约束与循环引用,再下载、验证哈希和清单,最后按依赖顺序安装。已有版本复用,停用的所需版本会启用;依赖冲突或缺失会阻止安装。解析支持共享依赖的版本回溯,不会仅取各插件的最新版本。
24 28
25 29 自动验证:XFE XUnit 覆盖图形方法参数、多个返回值、C# 元组解构、独立 Runner、选区边界引用、版本锁定、依赖回溯及循环拒绝;ServerInteractive 实际协议测试覆盖下载时自动安装依赖。