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

XFEWorkflow

【WinUI】XFE基于windows的工作流

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

XFEstudio/XFEWorkflow

添加支持输出联动和管理员启动的 PowerShell 与 CMD 节点

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

代码差异

11 个文件 +463 -5
Modified README.md +2 -0
@@ -1,5 +1,7 @@
1 1 # XFEWorkflow
2 2
3 命令行节点提供 **PowerShell 脚本**(Windows PowerShell 5.1)和 **CMD 命令**,支持多行脚本、工作目录、环境变量、最长执行时间与管理员启动。管理员模式由 Windows 显示 UAC,取消后不会执行命令。`stdout`、`stderr`、`exitCode`、`succeeded` 可以连到后续节点;`result` 提供完整结果。默认保留非零退出码供条件节点判断,也可开启“非零退出码报错”。每个输出流最多保留 256 Ki 字符,超出后继续排空并设置 `truncated`;停止或超时会终止所属命令及子进程。
4
3 5 基于 .NET 10、WinUI 3 和 XFEExtension 的本地自动化工作台。提供节点画布、C# 节点、纯 C# 工作流、独立 Runner、插件管理和在线插件 Space。
4 6
5 7 ## 启动
Added XFEWorkflow/XFEWorkflow.Infrastructure/Execution/CommandProcessHost.cs +140 -0
@@ -0,0 +1,140 @@
1 using System.Collections.Concurrent;
2 using System.ComponentModel;
3 using System.Diagnostics;
4 using System.IO.Pipes;
5 using System.Text;
6 using System.Text.Json.Nodes;
7 using XFEWorkflow.Abstractions;
8 using XFEWorkflow.Infrastructure.Communication;
9
10 namespace XFEWorkflow.Infrastructure.Execution;
11
12 /// <summary>Runs a shell in an owned helper, including UAC elevation, without using temporary output files.</summary>
13 public sealed class CommandProcessHost(string runnerPath) : IAsyncDisposable
14 {
15 private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, Session>> owners = [];
16 public async Task<JsonObject> ExecuteAsync(string owner, JsonObject input, CancellationToken ct)
17 {
18 if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException("命令行节点需要 Windows");
19 var name = "XFEWorkflow-Command-" + Guid.NewGuid().ToString("N");
20 var elevated = input.Boolean("administrator");
21 await using var pipe = new NamedPipeServerStream(name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
22 var session = new Session(pipe); var sessions = owners.GetOrAdd(owner, _ => []); sessions[name] = session;
23 using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, session.Stop.Token);
24 try
25 {
26 var start = new ProcessStartInfo(runnerPath) { UseShellExecute = elevated, CreateNoWindow = !elevated, WindowStyle = ProcessWindowStyle.Hidden };
27 start.ArgumentList.Add("--command-host"); start.ArgumentList.Add(name);
28 if (elevated) start.Verb = "runas";
29 // UAC can outlive cancellation. The helper has a bounded connect timeout and cannot run a command without this pipe.
30 var launch = Task.Run(() => Process.Start(start) ?? throw new IOException("无法启动命令执行进程"));
31 try { session.Process = await launch.WaitAsync(linked.Token); }
32 catch (OperationCanceledException) { _ = launch.ContinueWith(t => { if (t.Status == TaskStatus.RanToCompletion) t.Result.Dispose(); }, TaskScheduler.Default); throw; }
33 catch (Win32Exception ex) when (ex.NativeErrorCode == 1223) { throw new OperationCanceledException("已取消管理员启动,命令未执行", ex); }
34 using var deadline = CancellationTokenSource.CreateLinkedTokenSource(linked.Token); deadline.CancelAfter(TimeSpan.FromSeconds(20));
35 await pipe.WaitForConnectionAsync(deadline.Token);
36 session.Peer = new RpcPeer(pipe); session.Peer.Start();
37 return await session.Peer.RequestAsync<JsonObject>("run", input, linked.Token) ?? throw new IOException("命令执行未返回结果");
38 }
39 finally { await session.DisposeAsync(); sessions.TryRemove(name, out _); }
40 }
41 public async Task ReleaseAsync(string owner)
42 { if (owners.TryRemove(owner, out var sessions)) foreach (var session in sessions.Values) { try { await session.Stop.CancelAsync(); } catch (ObjectDisposedException) { } } }
43 public async ValueTask DisposeAsync()
44 { foreach (var owner in owners.Keys) await ReleaseAsync(owner); }
45
46 private sealed class Session(NamedPipeServerStream pipe) : IAsyncDisposable
47 {
48 public CancellationTokenSource Stop { get; } = new();
49 public Process? Process { get; set; }
50 public RpcPeer? Peer { get; set; }
51 public async ValueTask DisposeAsync()
52 {
53 if (Peer is not null)
54 {
55 try { await Peer.RequestAsync<JsonObject>("cancel").WaitAsync(TimeSpan.FromSeconds(1)); } catch (Exception) { }
56 await Peer.DisposeAsync();
57 }
58 else await pipe.DisposeAsync();
59 if (Process is { } process)
60 {
61 try { await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(5)); }
62 catch (TimeoutException) { try { process.Kill(true); } catch (Win32Exception) { /* Elevated helper cancels its own child after pipe closure. */ } }
63 finally { process.Dispose(); }
64 }
65 Stop.Dispose();
66 }
67 }
68 }
69
70 public static class CommandProcessWorker
71 {
72 public static async Task<int> RunAsync(string pipeName)
73 {
74 if (!pipeName.StartsWith("XFEWorkflow-Command-", StringComparison.Ordinal)) return 2;
75 using var lifetime = new CancellationTokenSource();
76 await using var pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
77 try { await pipe.ConnectAsync(5000, lifetime.Token); } catch (Exception) { return 3; }
78 await using var peer = new RpcPeer(pipe); var started = 0; Task<JsonObject>? command = null;
79 peer.RequestReceived = async (method, value, ct) =>
80 {
81 if (method == "cancel") { await lifetime.CancelAsync(); return new JsonObject { ["cancelled"] = true }; }
82 if (method != "run" || Interlocked.Exchange(ref started, 1) != 0) throw new InvalidOperationException("命令执行进程只接受一次任务");
83 command = ExecuteAsync(value?.AsObject() ?? [], lifetime.Token); return await command;
84 };
85 peer.Start(); await peer.Completion; await lifetime.CancelAsync();
86 if (command is not null) { try { await command; } catch (Exception) { } }
87 return 0;
88 }
89 public static async Task<JsonObject> ExecuteAsync(JsonObject input, CancellationToken ct)
90 {
91 if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException("命令行节点需要 Windows");
92 var shell = input.String("shell"); if (shell is not ("powershell" or "cmd")) throw new ArgumentException("请选择 PowerShell 或 CMD");
93 var script = input.String("script"); if (string.IsNullOrWhiteSpace(script) || script.Length > 256 * 1024) throw new ArgumentException("命令不能为空且不能超过 256 Ki 字符");
94 var directory = input.String("workingDirectory"); if (directory.Length == 0) directory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
95 directory = Path.GetFullPath(directory); if (!Directory.Exists(directory)) throw new DirectoryNotFoundException("工作目录不存在:" + directory);
96 var executable = shell == "cmd" ? Path.Combine(Environment.SystemDirectory, "cmd.exe") : Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe");
97 var start = new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden,
98 WorkingDirectory = directory, RedirectStandardOutput = true, RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8 };
99 if (input["environment"] is JsonObject environment) foreach (var pair in environment) start.Environment[pair.Key] = pair.Value.Text();
100 string? scriptFile = null;
101 try
102 {
103 if (shell == "powershell")
104 {
105 start.ArgumentList.Add("-NoLogo"); start.ArgumentList.Add("-NoProfile"); start.ArgumentList.Add("-NonInteractive"); start.ArgumentList.Add("-EncodedCommand");
106 start.ArgumentList.Add(Convert.ToBase64String(Encoding.Unicode.GetBytes("[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); $OutputEncoding = [Console]::OutputEncoding;\n" + script)));
107 }
108 else
109 {
110 var temporary = Path.Combine(Path.GetTempPath(), "XFEWorkflow-Commands", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(temporary);
111 scriptFile = Path.Combine(temporary, "command.cmd"); await File.WriteAllTextAsync(scriptFile, "@echo off\r\nchcp 65001 >nul\r\n" + script.ReplaceLineEndings("\r\n"), new UTF8Encoding(false), ct);
112 start.ArgumentList.Add("/D"); start.ArgumentList.Add("/C"); start.ArgumentList.Add(scriptFile);
113 }
114 using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
115 var seconds = input.Integer("timeoutSeconds", 300); if (seconds is < 1 or > 86400) throw new ArgumentException("命令超时必须为 1 到 86400 秒"); timeout.CancelAfter(TimeSpan.FromSeconds(seconds));
116 using var process = Process.Start(start) ?? throw new IOException("无法启动命令行");
117 var stdout = ReadAsync(process.StandardOutput); var stderr = ReadAsync(process.StandardError);
118 try { await process.WaitForExitAsync(timeout.Token); }
119 catch (OperationCanceledException)
120 {
121 if (!process.HasExited) process.Kill(true); await process.WaitForExitAsync(); await Task.WhenAll(stdout, stderr);
122 if (ct.IsCancellationRequested) throw;
123 throw new TimeoutException("命令执行超时,已终止进程及其子进程");
124 }
125 var streams = await Task.WhenAll(stdout, stderr);
126 var result = new JsonObject { ["stdout"] = streams[0].Text, ["stderr"] = streams[1].Text, ["exitCode"] = process.ExitCode,
127 ["succeeded"] = process.ExitCode == 0, ["truncated"] = streams.Any(x => x.Truncated), ["processId"] = process.Id,
128 ["administrator"] = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator) };
129 if (input.Boolean("failOnNonZero") && process.ExitCode != 0) throw new InvalidOperationException($"命令退出码 {process.ExitCode}:{streams[1].Text}");
130 return result;
131 }
132 finally { if (scriptFile is not null) { File.Delete(scriptFile); try { Directory.Delete(Path.GetDirectoryName(scriptFile)!); } catch (IOException) { } } }
133 }
134 private static async Task<(string Text, bool Truncated)> ReadAsync(StreamReader reader)
135 {
136 const int limit = 256 * 1024; var text = new StringBuilder(); var buffer = new char[8192]; var truncated = false;
137 while (await reader.ReadAsync(buffer) is var read && read > 0) { var keep = Math.Min(read, limit - text.Length); text.Append(buffer, 0, keep); truncated |= keep < read; }
138 return (text.ToString(), truncated);
139 }
140 }
Added XFEWorkflow/XFEWorkflow.Plugins.Standard/Manifests/xfe.command.json +249 -0
@@ -0,0 +1,249 @@
1 {
2 "schemaVersion": 1,
3 "sdkMajorVersion": 1,
4 "id": "xfe.command",
5 "name": "命令行",
6 "version": "1.0.0",
7 "author": "XFEstudio",
8 "description": "命令行 官方能力",
9 "assembly": "XFEWorkflow.Plugins.Standard.dll",
10 "entryType": "XFEWorkflow.Plugins.Standard.CommandPlugin",
11 "supportedRids": [],
12 "permissions": [
13 "process",
14 "filesystem"
15 ],
16 "dependencies": [],
17 "capabilities": [
18 {
19 "id": "xfe.command.powershell",
20 "name": "PowerShell 脚本",
21 "category": "命令行",
22 "description": "Windows PowerShell 5.1;支持多行脚本、UTF-8 输出、取消和管理员启动。",
23 "inputs": [
24 {
25 "name": "script",
26 "label": "命令脚本",
27 "type": "String",
28 "required": true,
29 "secret": false
30 },
31 {
32 "name": "workingDirectory",
33 "label": "工作目录(空为用户目录)",
34 "type": "String",
35 "required": false,
36 "secret": false
37 },
38 {
39 "name": "administrator",
40 "label": "以管理员身份启动(UAC)",
41 "type": "Boolean",
42 "required": false,
43 "secret": false,
44 "defaultValue": false
45 },
46 {
47 "name": "timeoutSeconds",
48 "label": "最长执行秒数",
49 "type": "Number",
50 "required": false,
51 "secret": false,
52 "defaultValue": 300
53 },
54 {
55 "name": "environment",
56 "label": "环境变量",
57 "type": "Object",
58 "required": false,
59 "secret": false
60 },
61 {
62 "name": "failOnNonZero",
63 "label": "非零退出码报错",
64 "type": "Boolean",
65 "required": false,
66 "secret": false,
67 "defaultValue": false
68 }
69 ],
70 "outputs": [
71 {
72 "name": "stdout",
73 "label": "标准输出",
74 "type": "String",
75 "required": false,
76 "secret": false
77 },
78 {
79 "name": "stderr",
80 "label": "错误输出",
81 "type": "String",
82 "required": false,
83 "secret": false
84 },
85 {
86 "name": "exitCode",
87 "label": "退出码",
88 "type": "Number",
89 "required": false,
90 "secret": false
91 },
92 {
93 "name": "succeeded",
94 "label": "成功",
95 "type": "Boolean",
96 "required": false,
97 "secret": false
98 },
99 {
100 "name": "truncated",
101 "label": "输出已截断",
102 "type": "Boolean",
103 "required": false,
104 "secret": false
105 },
106 {
107 "name": "processId",
108 "label": "进程 ID",
109 "type": "Number",
110 "required": false,
111 "secret": false
112 },
113 {
114 "name": "administrator",
115 "label": "实际管理员权限",
116 "type": "Boolean",
117 "required": false,
118 "secret": false
119 },
120 {
121 "name": "result",
122 "label": "完整结果",
123 "type": "Object",
124 "required": false,
125 "secret": false
126 }
127 ],
128 "executionOutputs": [
129 "next"
130 ],
131 "pluginId": "xfe.command"
132 },
133 {
134 "id": "xfe.command.cmd",
135 "name": "CMD 命令",
136 "category": "命令行",
137 "description": "Windows CMD;支持多行批处理、UTF-8 输出、取消和管理员启动。",
138 "inputs": [
139 {
140 "name": "script",
141 "label": "命令脚本",
142 "type": "String",
143 "required": true,
144 "secret": false
145 },
146 {
147 "name": "workingDirectory",
148 "label": "工作目录(空为用户目录)",
149 "type": "String",
150 "required": false,
151 "secret": false
152 },
153 {
154 "name": "administrator",
155 "label": "以管理员身份启动(UAC)",
156 "type": "Boolean",
157 "required": false,
158 "secret": false,
159 "defaultValue": false
160 },
161 {
162 "name": "timeoutSeconds",
163 "label": "最长执行秒数",
164 "type": "Number",
165 "required": false,
166 "secret": false,
167 "defaultValue": 300
168 },
169 {
170 "name": "environment",
171 "label": "环境变量",
172 "type": "Object",
173 "required": false,
174 "secret": false
175 },
176 {
177 "name": "failOnNonZero",
178 "label": "非零退出码报错",
179 "type": "Boolean",
180 "required": false,
181 "secret": false,
182 "defaultValue": false
183 }
184 ],
185 "outputs": [
186 {
187 "name": "stdout",
188 "label": "标准输出",
189 "type": "String",
190 "required": false,
191 "secret": false
192 },
193 {
194 "name": "stderr",
195 "label": "错误输出",
196 "type": "String",
197 "required": false,
198 "secret": false
199 },
200 {
201 "name": "exitCode",
202 "label": "退出码",
203 "type": "Number",
204 "required": false,
205 "secret": false
206 },
207 {
208 "name": "succeeded",
209 "label": "成功",
210 "type": "Boolean",
211 "required": false,
212 "secret": false
213 },
214 {
215 "name": "truncated",
216 "label": "输出已截断",
217 "type": "Boolean",
218 "required": false,
219 "secret": false
220 },
221 {
222 "name": "processId",
223 "label": "进程 ID",
224 "type": "Number",
225 "required": false,
226 "secret": false
227 },
228 {
229 "name": "administrator",
230 "label": "实际管理员权限",
231 "type": "Boolean",
232 "required": false,
233 "secret": false
234 },
235 {
236 "name": "result",
237 "label": "完整结果",
238 "type": "Object",
239 "required": false,
240 "secret": false
241 }
242 ],
243 "executionOutputs": [
244 "next"
245 ],
246 "pluginId": "xfe.command"
247 }
248 ]
249 }
Modified XFEWorkflow/XFEWorkflow.Plugins.Standard/StandardPlugins.cs +6 -0
@@ -31,6 +31,7 @@ public sealed class AiPlugin() : StandardPlugin("xfe.ai");
31 31 public sealed class WeComPlugin() : StandardPlugin("xfe.wecom");
32 32 public sealed class BrowserPlugin() : StandardPlugin("xfe.browser");
33 33 public sealed class TimerPlugin() : StandardPlugin("xfe.timer");
34 public sealed class CommandPlugin() : StandardPlugin("xfe.command");
34 35
35 36 public sealed class TimerTrigger : IWorkflowTrigger
36 37 {
@@ -50,6 +51,11 @@ public sealed class StandardAction(string capabilityId) : IWorkflowAction
50 51 {
51 52 if (capabilityId.StartsWith("xfe.browser.", StringComparison.Ordinal))
52 53 return await context.InvokeHostAsync("browser." + capabilityId["xfe.browser.".Length..], input, ct);
54 if (capabilityId is "xfe.command.powershell" or "xfe.command.cmd")
55 {
56 var command = WorkflowJson.Copy(input); command["shell"] = capabilityId["xfe.command.".Length..];
57 var result = await context.InvokeHostAsync("command.run", command, ct); result["result"] = result.DeepClone(); return result;
58 }
53 59 switch (capabilityId)
54 60 {
55 61 case "xfe.http.request":
Modified XFEWorkflow/XFEWorkflow.Runner/Program.cs +3 -0
@@ -7,6 +7,9 @@ using XFEWorkflow.Infrastructure.Communication;
7 7 using XFEWorkflow.Infrastructure.Compilation;
8 8 using XFEWorkflow.Infrastructure.Plugins;
9 9 using XFEWorkflow.Infrastructure.Storage;
10 using XFEWorkflow.Infrastructure.Execution;
11
12 if (args.Length == 2 && args[0] == "--command-host") return await CommandProcessWorker.RunAsync(args[1]);
10 13
11 14 if (args.Length != 2 || args[0] != "--pipe") { Console.Error.WriteLine("Runner 由 XFEWorkflow 启动。"); return 2; }
12 15 using var lifetime = new CancellationTokenSource();
Added XFEWorkflow/XFEWorkflow.Test/CommandTests.cs +47 -0
@@ -0,0 +1,47 @@
1 using System.Text.Json.Nodes;
2 using XFEExtension.NetCore.XUnit.Assertions;
3 using XFEExtension.NetCore.XUnit.Attributes;
4 using XFEWorkflow.Abstractions;
5 using XFEWorkflow.Core.Runtime;
6 using XFEWorkflow.Infrastructure.Compilation;
7 using XFEWorkflow.Infrastructure.Execution;
8
9 namespace XFEWorkflow.Test;
10
11 [TestFixture]
12 public class CommandTests
13 {
14 [Test]
15 public async Task PowerShellOutputsChineseErrorsAndExitCodeThroughOwnedHelper()
16 {
17 await using var host = new CommandProcessHost(TestSupport.FindOutput("XFEWorkflow.Runner", "XFEWorkflow.Runner.exe"));
18 var result = await host.ExecuteAsync("fixture", new() { ["shell"] = "powershell", ["script"] = "Write-Output '中文输出'; [Console]::Error.WriteLine('错误信息'); exit 7" }, default);
19 Assert.Contains("中文输出", result.String("stdout")); Assert.Contains("错误信息", result.String("stderr"));
20 Assert.Equal(7, result.Integer("exitCode")); Assert.False(result.Boolean("succeeded"));
21 }
22 [Test]
23 public async Task CmdUsesEnvironmentAndWorkingDirectoryAndCanBindOutputToFollowingNode()
24 {
25 await using var workspace = new TestWorkspace(); var directory = Path.Combine(workspace.Paths.Temp, "中文 空格"); Directory.CreateDirectory(directory);
26 var registry = TestSupport.Standard(); using var compiler = new CodeCompiler();
27 var node = new NodeDefinition { CapabilityId = "xfe.command.cmd", Parameters = new() { ["script"] = "echo %XFE_FIXTURE%\r\ncd", ["workingDirectory"] = directory, ["environment"] = new JsonObject { ["XFE_FIXTURE"] = "联动成功" } } };
28 var flow = TestSupport.Graph(node); flow.Graph.Edges.Add(new() { Kind = PortKind.Data, FromNode = node.Id, FromPort = "stdout", ToNode = flow.Graph.Nodes[^1].Id, ToPort = "result" });
29 var context = TestSupport.Context(registry, host: async (_, input, ct) => await CommandProcessWorker.ExecuteAsync(input, ct));
30 var result = await new WorkflowEngine(compiler, CoreCapabilities.Catalog(registry.Descriptors.Values)).ExecuteAsync(flow, context, default);
31 Assert.Contains("联动成功", result.String("result")); Assert.Contains(directory, result.String("result"));
32 }
33 [Test]
34 public async Task TimeoutCancellationAndNonZeroFailureAreReported()
35 {
36 await Assert.ThrowsAsync<TimeoutException>(() => CommandProcessWorker.ExecuteAsync(new() { ["shell"] = "powershell", ["script"] = "Start-Sleep -Seconds 20", ["timeoutSeconds"] = 1 }, default));
37 using var stop = new CancellationTokenSource(1000);
38 await Assert.ThrowsAsync<OperationCanceledException>(() => CommandProcessWorker.ExecuteAsync(new() { ["shell"] = "cmd", ["script"] = "ping -n 25 127.0.0.1 >nul" }, stop.Token));
39 await Assert.ThrowsAsync<InvalidOperationException>(() => CommandProcessWorker.ExecuteAsync(new() { ["shell"] = "cmd", ["script"] = "exit /b 4", ["failOnNonZero"] = true }, default));
40 }
41 [Test]
42 public async Task ExcessOutputIsDrainedAndBounded()
43 {
44 var result = await CommandProcessWorker.ExecuteAsync(new() { ["shell"] = "powershell", ["script"] = "[Console]::Write(('x' * 300000)); [Console]::Error.Write(('e' * 300000))" }, default);
45 Assert.True(result.Boolean("truncated")); Assert.Equal(256 * 1024, result.String("stdout").Length); Assert.Equal(256 * 1024, result.String("stderr").Length); Assert.Equal(0, result.Integer("exitCode"));
46 }
47 }
Modified XFEWorkflow/XFEWorkflow.Test/TestSupport.cs +3 -3
@@ -37,11 +37,11 @@ internal static class TestSupport
37 37 }).ToList();
38 38 return candidates.OrderByDescending(x => x.Replace('\\', '/').Contains("/" + configuration + "/", StringComparison.OrdinalIgnoreCase)).ThenByDescending(File.GetLastWriteTimeUtc).First();
39 39 }
40 public static WorkflowExecutionContext Context(CapabilityRegistry? registry = null, JsonObject? inputs = null, List<RunEvent>? events = null, string? entryNodeId = null) => new()
40 public static WorkflowExecutionContext Context(CapabilityRegistry? registry = null, JsonObject? inputs = null, List<RunEvent>? events = null, string? entryNodeId = null, Func<string, JsonObject, CancellationToken, ValueTask<JsonObject>>? host = null) => new()
41 41 {
42 42 RunId = Guid.NewGuid().ToString("N"), Inputs = inputs ?? [], Capabilities = registry ?? new(), EntryNodeId = entryNodeId,
43 43 Subworkflow = (_, _, _) => throw new NotSupportedException(), Secret = (_, _) => ValueTask.FromResult("mock-managed-secret"),
44 Host = (_, _, _) => throw new NotSupportedException(),
44 Host = host ?? ((_, _, _) => throw new NotSupportedException()),
45 45 Report = ev => { if (events is not null) lock (events) events.Add(ev); return ValueTask.CompletedTask; }
46 46 };
47 47 public static WorkflowDefinition Graph(params NodeDefinition[] nodes)
@@ -53,7 +53,7 @@ internal static class TestSupport
53 53 public static CapabilityRegistry Standard()
54 54 {
55 55 var registry = new CapabilityRegistry();
56 foreach (var plugin in new IWorkflowPlugin[] { new HttpPlugin(), new FilePlugin(), new AiPlugin(), new WeComPlugin(), new BrowserPlugin(), new TimerPlugin() }) plugin.Register(registry);
56 foreach (var plugin in new IWorkflowPlugin[] { new HttpPlugin(), new FilePlugin(), new AiPlugin(), new WeComPlugin(), new BrowserPlugin(), new TimerPlugin(), new CommandPlugin() }) plugin.Register(registry);
57 57 return registry;
58 58 }
59 59 public static string Package(string directory, PluginManifest? manifest = null, params (string Path, string Text)[] extra)
Modified XFEWorkflow/XFEWorkflow/Services/AppServices.cs +5 -1
@@ -30,6 +30,7 @@ public sealed class AppServices : IWorkflowApplicationService, IAsyncDisposable
30 30 public WorkflowLogService Logs { get; }
31 31 public DesktopInputService Desktop { get; } = new();
32 32 public ScreenToolsService ScreenTools { get; } = new();
33 public CommandProcessHost Commands { get; }
33 34 public BrowserHost? Browser { get; private set; }
34 35 public Task Ready { get; private set; } = Task.CompletedTask;
35 36 private bool initialized;
@@ -38,6 +39,7 @@ public sealed class AppServices : IWorkflowApplicationService, IAsyncDisposable
38 39 Paths = new(Utilities.AppPath.WorkspaceDirectory);
39 40 State = new(Paths); Credentials = new(State); Workflows = new(Paths); Plugins = new(Paths, State);
40 41 Runs = new(Paths, Plugins, Credentials, Redactor, Path.Combine(AppContext.BaseDirectory, "Runner", "XFEWorkflow.Runner.exe"));
42 Commands = new(Path.Combine(AppContext.BaseDirectory, "Runner", "XFEWorkflow.Runner.exe"));
41 43 Scheduler = new(Workflows, Runs); Space = new(State, Credentials);
42 44 Logs = new(Paths, Runs, Redactor);
43 45 Runs.RunChanged += Logs.Observe;
@@ -49,9 +51,10 @@ public sealed class AppServices : IWorkflowApplicationService, IAsyncDisposable
49 51 if (method.StartsWith("browser.", StringComparison.Ordinal)) return await (Browser ?? throw new InvalidOperationException("浏览器服务尚未启动")).InvokeAsync(id, method, input, ct);
50 52 if (method == "desktop.input") return await Desktop.ExecuteAsync(id, input, ct);
51 53 if (method.StartsWith("screen.", StringComparison.Ordinal)) return await ScreenTools.InvokeAsync(method, input, ct);
54 if (method == "command.run") return await Commands.ExecuteAsync(id, input, ct);
52 55 throw new NotSupportedException(method);
53 56 };
54 Runs.ReleaseHost = async id => { await Desktop.ReleaseAsync(id); if (Browser is not null) await Browser.ReleaseAsync(id); };
57 Runs.ReleaseHost = async id => { await Desktop.ReleaseAsync(id); await Commands.ReleaseAsync(id); if (Browser is not null) await Browser.ReleaseAsync(id); };
55 58 ServiceManager.RegisterService<IWorkflowApplicationService>(() => this);
56 59 }
57 60 public void Start(BrowserHost browser) { Browser = browser; browser.Paths = Paths; Ready = InitializeAsync(); }
@@ -75,6 +78,7 @@ public sealed class AppServices : IWorkflowApplicationService, IAsyncDisposable
75 78 initialized = false;
76 79 if (MainPage.Current?.ViewModel.SelectedWorkflow is { } workflow) await Workflows.SaveAsync(workflow);
77 80 await Scheduler.DisposeAsync(); ScreenTools.CancelSelection(); Desktop.EmergencyStop(); await Runs.DisposeAsync();
81 await Commands.DisposeAsync();
78 82 if (Browser is not null) await Browser.DisposeAsync();
79 83 Desktop.Dispose(); await State.DisposeAsync();
80 84 }
Modified XFEWorkflow/XFEWorkflow/ViewModels/MainPageViewModel.cs +1 -0
@@ -32,6 +32,7 @@ public sealed class PaletteItem(CapabilityDescriptor descriptor, string pluginNa
32 32 _ when Descriptor.PluginId.Contains("file", StringComparison.OrdinalIgnoreCase) => Symbol.Folder,
33 33 _ when Descriptor.PluginId.Contains("ai", StringComparison.OrdinalIgnoreCase) => Symbol.Favorite,
34 34 _ when Descriptor.PluginId.Contains("wecom", StringComparison.OrdinalIgnoreCase) => Symbol.Message,
35 _ when Descriptor.PluginId == "xfe.command" => (Symbol)0xE756,
35 36 _ when Descriptor.PluginId.Contains("desktop", StringComparison.OrdinalIgnoreCase) => Symbol.AllApps,
36 37 _ when Descriptor.PluginId == "xfe.vision" && Descriptor.Category == "屏幕区域" => Symbol.Camera,
37 38 _ when Descriptor.PluginId == "xfe.vision" && Descriptor.Category == "文字识别" => Symbol.Document,
Modified XFEWorkflow/XFEWorkflow/Views/MainPage.xaml.cs +1 -1
@@ -272,7 +272,7 @@ public sealed partial class MainPage : Page
272 272 private void AddText(string label, string initial, Action<string> apply)
273 273 {
274 274 PropertyPanel.Children.Add(new TextBlock { Text = label, FontSize = 12, Opacity = .75 });
275 var box = new TextBox { AcceptsReturn = label.Contains("提示词") || label.Contains("内容") || label.Contains("消息") || initial.Contains('\n') || initial.Contains('\r'), Text = initial, TextWrapping = TextWrapping.Wrap, MaxHeight = 130 };
275 var box = new TextBox { AcceptsReturn = label.Contains("提示词") || label.Contains("内容") || label.Contains("消息") || label.Contains("脚本") || initial.Contains('\n') || initial.Contains('\r'), Text = initial, TextWrapping = TextWrapping.Wrap, MaxHeight = 130 };
276 276 box.LostFocus += (_, _) => { if (box.Text == initial) return; try { CanvasEditor.Checkpoint(); apply(box.Text); initial = box.Text; CanvasEditor.Commit(); } catch (Exception ex) { ViewModel.Status = ex.Message; } };
277 277 PropertyPanel.Children.Add(box);
278 278 }
Modified tools/Generate-BundledManifests.ps1 +6 -0
@@ -23,6 +23,12 @@ Plugin 'xfe.file' '文件' 'FilePlugin' @('filesystem') @(
23 23 (Action 'xfe.file.write' '写入文本' @((Port 'path' '路径' 'String' $true), (Port 'text' '内容' 'Any' $true), (Port 'append' '追加' 'Boolean' $false $false)) @((Port 'path' '路径'))),
24 24 (Action 'xfe.file.list' '列出文件' @((Port 'path' '目录' 'String' $true), (Port 'pattern' '匹配模式' 'String' $false '*'), (Port 'recursive' '包含子目录' 'Boolean' $false $false)) @((Port 'files' '文件' 'Array')))
25 25 )
26 $commandInputs = @((Port 'script' '命令脚本' 'String' $true), (Port 'workingDirectory' '工作目录(空为用户目录)'), (Port 'administrator' '以管理员身份启动(UAC)' 'Boolean' $false $false), (Port 'timeoutSeconds' '最长执行秒数' 'Number' $false 300), (Port 'environment' '环境变量' 'Object'), (Port 'failOnNonZero' '非零退出码报错' 'Boolean' $false $false))
27 $commandOutputs = @((Port 'stdout' '标准输出'), (Port 'stderr' '错误输出'), (Port 'exitCode' '退出码' 'Number'), (Port 'succeeded' '成功' 'Boolean'), (Port 'truncated' '输出已截断' 'Boolean'), (Port 'processId' '进程 ID' 'Number'), (Port 'administrator' '实际管理员权限' 'Boolean'), (Port 'result' '完整结果' 'Object'))
28 Plugin 'xfe.command' '命令行' 'CommandPlugin' @('process', 'filesystem') @(
29 (Action 'xfe.command.powershell' 'PowerShell 脚本' $commandInputs $commandOutputs 'Windows PowerShell 5.1;支持多行脚本、UTF-8 输出、取消和管理员启动。'),
30 (Action 'xfe.command.cmd' 'CMD 命令' $commandInputs $commandOutputs 'Windows CMD;支持多行批处理、UTF-8 输出、取消和管理员启动。')
31 )
26 32 Plugin 'xfe.ai' 'AI' 'AiPlugin' @('network', 'credentials') @(
27 33 (Action 'xfe.ai.chat' 'AI 对话' @((Port 'endpoint' '兼容接口地址' 'String' $false 'https://api.openai.com/v1/'), (Port 'model' '模型' 'String' $true), (Port 'credential' 'API Key 凭据引用'), (Port 'apiKey' '临时 API Key' 'String' $false $null $true), (Port 'system' '系统提示词'), (Port 'prompt' '提示词' 'Any'), (Port 'messages' '消息数组' 'Array'), (Port 'temperature' '采样温度' 'Number')) @((Port 'text' '回复'), (Port 'response' '完整响应' 'Object')))
28 34 )