返回提交历史
Modified
README.md
+2
-1
Added
XFEToolBox.Client.Core/Tools/ToolchainManager.cs
+320
-0
Modified
XFEToolBox.Client.Installer/README.md
+1
-1
Added
XFEToolBox.Client.Wpf.Test/ToolchainIntegrationTests.cs
+143
-0
Added
XFEToolBox.Client.Wpf.Test/ToolchainManagerTests.cs
+239
-0
Modified
XFEToolBox/Utilities/ToolProjectRunService.cs
+65
-16
Modified
XFEToolBox/Views/Pages/ToolBoxPage.xaml.cs
+15
-1
Modified
XFEToolBox/Views/Windows/ToolCodeEditorWindow.xaml.cs
+14
-2
Modified
docs/tool-packages.md
+6
-2
Added
tests/FormatConverter.Validation/FormatConverter.Validation.csproj
+4
-0
Added
tests/FormatConverter.Validation/Program.cs
+208
-0
Added
tests/FormatConverter.Validation/README.md
+48
-0
Modified
tests/NetworkDoctor.Validation/Program.cs
+1
-1
Modified
tests/ProgramDebugger.Validation/Program.cs
+2
-2
Modified
tests/TextReplacer.Validation/Program.cs
+1
-1
XFEstudio/XFEToolBox
支持私有 .NET 10 SDK 自动下载与隔离运行
新增 ToolchainManager,首次运行自动下载并缓存适配架构的 .NET 10 SDK/WPF,支持 SHA-512 校验、解压、异常恢复与损坏修复。所有工具编译/运行流程统一切换为私有 SDK,完全隔离于系统 .NET,支持进度回调与取消。前端集成进度显示,提升用户体验。文档更新,说明无需预装 .NET,环境自动准备。新增多场景单元与集成测试,确保隔离运行与缓存机制可靠。相关代码重构,兼容原有流程。
4e0cd17
代码差异
15 个文件
+1069
-27
@@ -17,7 +17,8 @@ XFEToolBox 是一个基于 .NET 10 与 WPF 的 Windows 桌面工具箱。项目
17
17
## 环境要求
18
18
19
19
- Windows 10 1809(Build 17763)或更高版本,用于运行 WPF 客户端。
20
- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0)。
20
- 使用自包含发布版无需安装 .NET;首次打开或编译工具时,应用会自动从 Microsoft 下载编译与运行组件到用户私有目录,之后复用缓存。首次准备组件及获取新的 NuGet 依赖需要联网。
21
- 从源码开发或构建本仓库需要 [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0)。
21
22
- Microsoft Edge WebView2 Runtime,用于 Code Studio 编辑器和 Markdown 预览。
22
23
- 可选:支持 .NET 10 与 WPF 的 Visual Studio。
23
24
@@ -0,0 +1,320 @@
1
using System.Diagnostics;
2
using System.IO.Compression;
3
using System.Net.Http;
4
using System.Runtime.InteropServices;
5
using System.Security.Cryptography;
6
using System.Text.Json;
7
8
namespace XFEToolBox.Client.Core.Tools;
9
10
public sealed record ToolPreparationProgress(string Message, double? Percentage = null);
11
12
public sealed record ToolchainInstallation(string Root, string SdkVersion, string RuntimeVersion, string RuntimeIdentifier)
13
{
14
public string DotNetPath => Path.Combine(Root, "dotnet.exe");
15
}
16
17
/// <summary>Downloads a portable Windows SDK, including the WPF runtime, without changing the system installation.</summary>
18
public sealed class ToolchainManager
19
{
20
private const long MaximumDownloadBytes = 1024L * 1024 * 1024;
21
private const long MaximumExpandedBytes = 4L * 1024 * 1024 * 1024;
22
private const string MetadataUrl = "https://builds.dotnet.microsoft.com/dotnet/release-metadata/10.0/releases.json";
23
private static readonly HttpClient SharedClient = new() { Timeout = Timeout.InfiniteTimeSpan };
24
public static ToolchainManager Default { get; } = new(
25
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XFEToolBox", "Toolchains"),
26
GetRuntimeIdentifier(), SharedClient);
27
28
private readonly HttpClient _client;
29
private readonly string _runtimeIdentifier;
30
31
public string CacheRoot { get; }
32
33
public ToolchainManager(string cacheRoot, string runtimeIdentifier, HttpClient client)
34
{
35
if (runtimeIdentifier is not ("win-x64" or "win-arm64" or "win-x86"))
36
throw new PlatformNotSupportedException("工具运行组件不支持当前处理器架构。");
37
CacheRoot = Path.Combine(Path.GetFullPath(cacheRoot), "net10", runtimeIdentifier);
38
_runtimeIdentifier = runtimeIdentifier;
39
_client = client;
40
}
41
42
public async Task<ToolchainInstallation> EnsureInstalledAsync(
43
IProgress<ToolPreparationProgress>? progress = null, CancellationToken cancellationToken = default)
44
{
45
cancellationToken.ThrowIfCancellationRequested();
46
Directory.CreateDirectory(CacheRoot);
47
if (FindInstallation() is { } existing)
48
return existing;
49
50
progress?.Report(new("正在准备工具运行组件,首次使用需要下载…"));
51
// File sharing also serializes downloads from separate toolbox processes.
52
await using var installationLock = await AcquireLockAsync(cancellationToken).ConfigureAwait(false);
53
if (FindInstallation() is { } installedByAnotherProcess)
54
return installedByAnotherProcess;
55
56
var stagingRoot = Path.Combine(CacheRoot, ".staging-" + Guid.NewGuid().ToString("N"));
57
Directory.CreateDirectory(stagingRoot);
58
try
59
{
60
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
61
timeout.CancelAfter(TimeSpan.FromMinutes(30));
62
var token = timeout.Token;
63
var release = await GetReleaseAsync(token).ConfigureAwait(false);
64
var archivePath = Path.Combine(stagingRoot, "sdk.zip");
65
await DownloadAsync(release, archivePath, progress, token).ConfigureAwait(false);
66
var sdkRoot = Path.Combine(stagingRoot, "sdk");
67
progress?.Report(new("正在解压工具运行组件…"));
68
await Task.Run(() => ExtractAsync(archivePath, sdkRoot, token), token).ConfigureAwait(false);
69
var installation = new ToolchainInstallation(sdkRoot, release.SdkVersion, release.RuntimeVersion, _runtimeIdentifier);
70
if (!IsComplete(installation))
71
throw new InvalidDataException("下载的工具运行组件不完整,请重试。");
72
73
await File.WriteAllTextAsync(Path.Combine(sdkRoot, "toolchain.json"),
74
JsonSerializer.Serialize(new CachedToolchain(release.SdkVersion, release.RuntimeVersion, _runtimeIdentifier)), token).ConfigureAwait(false);
75
token.ThrowIfCancellationRequested();
76
var destination = Path.Combine(CacheRoot, $"sdk-{release.SdkVersion}-{Guid.NewGuid():N}");
77
Directory.Move(sdkRoot, destination);
78
progress?.Report(new("工具运行组件已就绪", 100));
79
return installation with { Root = destination };
80
}
81
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
82
{
83
throw new IOException("下载工具运行组件超时,请检查网络后重试。");
84
}
85
catch (HttpRequestException exception)
86
{
87
throw new IOException("无法下载工具运行组件,请检查网络后重试。" + exception.Message, exception);
88
}
89
finally
90
{
91
TryDeleteDirectory(stagingRoot);
92
}
93
}
94
95
public string CreateRunDirectory()
96
{
97
// The apphost embeds a relative path to the private runtime, so both must be on the same volume.
98
var directory = Path.Combine(CacheRoot, "runs", Guid.NewGuid().ToString("N"));
99
Directory.CreateDirectory(directory);
100
return directory;
101
}
102
103
public void ConfigureBuildEnvironment(ProcessStartInfo startInfo, ToolchainInstallation installation)
104
{
105
foreach (var key in startInfo.Environment.Keys.Where(key =>
106
key.StartsWith("DOTNET_ROOT", StringComparison.OrdinalIgnoreCase)
107
|| key.StartsWith("DOTNET_MSBUILD_SDK_RESOLVER_", StringComparison.OrdinalIgnoreCase)
108
|| key.StartsWith("MSBUILD", StringComparison.OrdinalIgnoreCase)).ToArray())
109
startInfo.Environment.Remove(key);
110
startInfo.Environment["DOTNET_ROOT"] = installation.Root;
111
startInfo.Environment["DOTNET_HOST_PATH"] = installation.DotNetPath;
112
startInfo.Environment["PATH"] = installation.Root + Path.PathSeparator + startInfo.Environment["PATH"];
113
startInfo.Environment["DOTNET_MULTILEVEL_LOOKUP"] = "0";
114
startInfo.Environment["DOTNET_CLI_HOME"] = Path.Combine(CacheRoot, "cli-home");
115
startInfo.Environment["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1";
116
startInfo.Environment["DOTNET_SKIP_FIRST_TIME_EXPERIENCE"] = "1";
117
startInfo.Environment["DOTNET_ADD_GLOBAL_TOOLS_TO_PATH"] = "false";
118
startInfo.Environment["DOTNET_CLI_WORKLOAD_UPDATE_NOTIFY_DISABLE"] = "true";
119
startInfo.Environment["MSBUILDDISABLENODEREUSE"] = "1";
120
startInfo.Environment["NUGET_PACKAGES"] = Path.Combine(CacheRoot, "nuget", "packages");
121
startInfo.Environment["NUGET_HTTP_CACHE_PATH"] = Path.Combine(CacheRoot, "nuget", "http-cache");
122
}
123
124
private ToolchainInstallation? FindInstallation()
125
{
126
foreach (var root in Directory.EnumerateDirectories(CacheRoot, "sdk-*"))
127
{
128
try
129
{
130
var manifest = JsonSerializer.Deserialize<CachedToolchain>(File.ReadAllText(Path.Combine(root, "toolchain.json")));
131
if (manifest is null || manifest.RuntimeIdentifier != _runtimeIdentifier)
132
continue;
133
var installation = new ToolchainInstallation(root, manifest.SdkVersion, manifest.RuntimeVersion, manifest.RuntimeIdentifier);
134
if (IsComplete(installation))
135
return installation;
136
}
137
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException)
138
{
139
// An interrupted or incomplete installation is never used for compilation.
140
}
141
}
142
return null;
143
}
144
145
private static bool IsComplete(ToolchainInstallation installation)
146
{
147
if (!IsStableVersion(installation.SdkVersion) || !IsStableVersion(installation.RuntimeVersion))
148
return false;
149
string[] requiredFiles =
150
[
151
"dotnet.exe",
152
$"sdk/{installation.SdkVersion}/MSBuild.dll",
153
$"sdk/{installation.SdkVersion}/Roslyn/bincore/csc.dll",
154
$"sdk/{installation.SdkVersion}/Sdks/Microsoft.NET.Sdk/targets/Microsoft.NET.Sdk.targets",
155
$"sdk/{installation.SdkVersion}/Sdks/Microsoft.NET.Sdk.WindowsDesktop/targets/Microsoft.NET.Sdk.WindowsDesktop.targets",
156
$"host/fxr/{installation.RuntimeVersion}/hostfxr.dll",
157
$"shared/Microsoft.NETCore.App/{installation.RuntimeVersion}/coreclr.dll",
158
$"shared/Microsoft.WindowsDesktop.App/{installation.RuntimeVersion}/PresentationFramework.dll",
159
$"packs/Microsoft.NETCore.App.Ref/{installation.RuntimeVersion}/ref/net10.0/System.Runtime.dll",
160
$"packs/Microsoft.WindowsDesktop.App.Ref/{installation.RuntimeVersion}/ref/net10.0/PresentationFramework.dll"
161
];
162
return requiredFiles.All(file => new FileInfo(Path.Combine(installation.Root, file)) is { Exists: true, Length: > 0 });
163
}
164
165
private async Task<FileStream> AcquireLockAsync(CancellationToken cancellationToken)
166
{
167
while (true)
168
{
169
cancellationToken.ThrowIfCancellationRequested();
170
try
171
{
172
return new FileStream(Path.Combine(CacheRoot, "install.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
173
}
174
catch (IOException exception) when ((exception.HResult & 0xffff) is 32 or 33)
175
{
176
await Task.Delay(300, cancellationToken).ConfigureAwait(false);
177
}
178
}
179
}
180
181
private async Task<SdkRelease> GetReleaseAsync(CancellationToken cancellationToken)
182
{
183
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
184
timeout.CancelAfter(TimeSpan.FromSeconds(60));
185
using var response = await _client.GetAsync(MetadataUrl, HttpCompletionOption.ResponseHeadersRead, timeout.Token).ConfigureAwait(false);
186
response.EnsureSuccessStatusCode();
187
await using var stream = await response.Content.ReadAsStreamAsync(timeout.Token).ConfigureAwait(false);
188
using var metadata = new MemoryStream();
189
await CopyBoundedAsync(stream, metadata, 8 * 1024 * 1024, timeout.Token).ConfigureAwait(false);
190
using var document = JsonDocument.Parse(metadata.ToArray());
191
var latest = document.RootElement.GetProperty("latest-sdk").GetString();
192
foreach (var release in document.RootElement.GetProperty("releases").EnumerateArray())
193
{
194
foreach (var sdk in release.GetProperty("sdks").EnumerateArray())
195
{
196
var version = sdk.GetProperty("version").GetString();
197
var runtime = sdk.GetProperty("runtime-version").GetString();
198
if (version != latest || !IsStableVersion(version) || !IsStableVersion(runtime))
199
continue;
200
foreach (var file in sdk.GetProperty("files").EnumerateArray())
201
{
202
if (file.GetProperty("rid").GetString() != _runtimeIdentifier
203
|| !file.GetProperty("name").GetString()!.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
204
continue;
205
var url = new Uri(file.GetProperty("url").GetString()!);
206
var hash = file.GetProperty("hash").GetString()!;
207
if (url.Scheme != Uri.UriSchemeHttps
208
|| url.Host is not ("builds.dotnet.microsoft.com" or "download.visualstudio.microsoft.com" or "dotnetcli.azureedge.net")
209
|| !url.AbsolutePath.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)
210
|| hash.Length != 128 || !hash.All(Uri.IsHexDigit))
211
throw new InvalidDataException("工具运行组件下载地址或校验信息无效。");
212
return new SdkRelease(version!, runtime!, url, hash);
213
}
214
}
215
}
216
throw new InvalidDataException("未找到适合当前设备的 .NET 10 工具运行组件,请稍后重试。");
217
}
218
219
private async Task DownloadAsync(SdkRelease release, string path, IProgress<ToolPreparationProgress>? progress, CancellationToken token)
220
{
221
using var response = await _client.GetAsync(release.Url, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false);
222
response.EnsureSuccessStatusCode();
223
var total = response.Content.Headers.ContentLength;
224
if (total > MaximumDownloadBytes)
225
throw new InvalidDataException("工具运行组件下载大小超过限制。");
226
await using var input = await response.Content.ReadAsStreamAsync(token).ConfigureAwait(false);
227
await using var output = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, FileOptions.Asynchronous);
228
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA512);
229
var buffer = new byte[81920];
230
long received = 0;
231
var clock = Stopwatch.StartNew();
232
progress?.Report(new("正在下载工具运行组件…", total > 0 ? 0 : null));
233
while (await input.ReadAsync(buffer, token).ConfigureAwait(false) is var count && count > 0)
234
{
235
received += count;
236
if (received > MaximumDownloadBytes)
237
throw new InvalidDataException("工具运行组件下载大小超过限制。");
238
hash.AppendData(buffer, 0, count);
239
await output.WriteAsync(buffer.AsMemory(0, count), token).ConfigureAwait(false);
240
if (clock.ElapsedMilliseconds < 200)
241
continue;
242
clock.Restart();
243
var size = total > 0 ? $"{received / 1048576d:0.0} / {total / 1048576d:0.0} MB" : $"{received / 1048576d:0.0} MB";
244
progress?.Report(new($"正在下载工具运行组件 · {size}", total > 0 ? received * 100d / total.Value : null));
245
}
246
if ((total is not null && received != total.Value)
247
|| !CryptographicOperations.FixedTimeEquals(hash.GetHashAndReset(), Convert.FromHexString(release.Sha512)))
248
throw new InvalidDataException("工具运行组件校验失败,请重试下载。");
249
}
250
251
private static async Task ExtractAsync(string archivePath, string destination, CancellationToken token)
252
{
253
Directory.CreateDirectory(destination);
254
using var archive = ZipFile.OpenRead(archivePath);
255
if (archive.Entries.Count > 50000)
256
throw new InvalidDataException("工具运行组件文件数量超过限制。");
257
long expanded = 0;
258
foreach (var entry in archive.Entries)
259
{
260
token.ThrowIfCancellationRequested();
261
var relative = entry.FullName.Replace('\\', '/');
262
var segments = relative.TrimEnd('/').Split('/');
263
if (segments.Any(segment => string.IsNullOrWhiteSpace(segment) || segment is "." or ".."
264
|| segment.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0
265
|| segment.EndsWith('.') || segment.EndsWith(' '))
266
|| ((entry.ExternalAttributes >> 16) & 0xf000) == 0xa000
267
|| (entry.ExternalAttributes & (int)FileAttributes.ReparsePoint) != 0)
268
throw new InvalidDataException("工具运行组件包含不安全的文件路径。");
269
var path = Path.GetFullPath(Path.Combine(destination, Path.Combine(segments)));
270
if (!path.StartsWith(destination + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
271
throw new InvalidDataException("工具运行组件包含越界路径。");
272
expanded = checked(expanded + entry.Length);
273
if (expanded > MaximumExpandedBytes)
274
throw new InvalidDataException("工具运行组件解压大小超过限制。");
275
if (relative.EndsWith('/'))
276
{
277
Directory.CreateDirectory(path);
278
continue;
279
}
280
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
281
await using var source = entry.Open();
282
await using var target = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, FileOptions.Asynchronous);
283
await CopyBoundedAsync(source, target, entry.Length, token).ConfigureAwait(false);
284
}
285
}
286
287
private static async Task CopyBoundedAsync(Stream source, Stream destination, long limit, CancellationToken token)
288
{
289
var buffer = new byte[81920];
290
long copied = 0;
291
while (await source.ReadAsync(buffer, token).ConfigureAwait(false) is var count && count > 0)
292
{
293
copied += count;
294
if (copied > limit)
295
throw new InvalidDataException("工具运行组件数据大小超过限制。");
296
await destination.WriteAsync(buffer.AsMemory(0, count), token).ConfigureAwait(false);
297
}
298
}
299
300
private static bool IsStableVersion(string? value) => Version.TryParse(value, out var version)
301
&& version.Major == 10 && version.Minor == 0 && version.Build >= 0 && version.Revision == -1
302
&& value == version.ToString();
303
304
private static string GetRuntimeIdentifier() => RuntimeInformation.ProcessArchitecture switch
305
{
306
Architecture.Arm64 => "win-arm64",
307
Architecture.X86 => "win-x86",
308
_ => "win-x64"
309
};
310
311
private static void TryDeleteDirectory(string path)
312
{
313
try { if (Directory.Exists(path)) Directory.Delete(path, recursive: true); }
314
catch (IOException) { }
315
catch (UnauthorizedAccessException) { }
316
}
317
318
private sealed record SdkRelease(string SdkVersion, string RuntimeVersion, Uri Url, string Sha512);
319
private sealed record CachedToolchain(string SdkVersion, string RuntimeVersion, string RuntimeIdentifier);
320
}
@@ -26,7 +26,7 @@
26
26
27
27
## 推荐发布流程
28
28
29
1. 发布 XFEToolBox 客户端,仅将软件文件压缩为 `Source.zip`,打包时排除旧的 `Installer.exe` 和临时 `InstallPackage.zip`。
29
1. 以自包含方式发布 XFEToolBox 客户端(如 `dotnet publish XFEToolBox/XFEToolBox.Client.csproj -c Release -r win-x64 --self-contained true`),仅将软件文件压缩为 `Source.zip`,打包时排除旧的 `Installer.exe` 和临时 `InstallPackage.zip`。工具编译所需的私有组件会在首次使用时自动下载,不要把用户目录中的 `Toolchains` 缓存放入安装包。
30
30
2. 将 `Source.zip` 放入 `XFEToolBox.Client.Installer/Resources/Resource`,然后发布安装器:
31
31
32
32
```powershell
@@ -0,0 +1,143 @@
1
using System.Diagnostics;
2
using System.IO;
3
using System.IO.Compression;
4
using System.Security.Cryptography;
5
using System.Text.Json;
6
using XFEToolBox.Client.Core.Tools;
7
using XFEToolBox.Client.Utilities;
8
using XFEToolBox.Core.Tools;
9
10
namespace XFEToolBox.Client.Wpf.Test;
11
12
[NonParallel]
13
public static class ToolchainIntegrationTests
14
{
15
// Explicit: first run downloads the real SDK and NuGet packages. The WPF fixture stays invisible.
16
[Test]
17
[Explicit]
18
public static async Task BuildsAndRunsWpfWithoutSystemDotNet()
19
{
20
using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(20));
21
var progress = new InlineProgress();
22
var installation = await ToolchainManager.Default.EnsureInstalledAsync(progress, timeout.Token);
23
var root = Path.Combine(ToolchainManager.Default.CacheRoot, "smoke-" + Guid.NewGuid().ToString("N"));
24
var workspace = Path.Combine(root, "workspace");
25
Directory.CreateDirectory(Path.Combine(workspace, "Code"));
26
var marker = Path.Combine(root, "runtime.txt");
27
var environment = new Dictionary<string, string?>
28
{
29
["PATH"] = Environment.GetFolderPath(Environment.SpecialFolder.System),
30
["DOTNET_ROOT"] = Path.Combine(root, "missing-dotnet"),
31
["DOTNET_ROOT_X64"] = Path.Combine(root, "missing-dotnet"),
32
["DOTNET_ROOT_X86"] = Path.Combine(root, "missing-dotnet"),
33
["DOTNET_ROOT_ARM64"] = Path.Combine(root, "missing-dotnet"),
34
["DOTNET_ROOT(x86)"] = Path.Combine(root, "missing-dotnet"),
35
["DOTNET_MULTILEVEL_LOOKUP"] = "0",
36
["MSBuildSDKsPath"] = Path.Combine(root, "missing-sdk")
37
};
38
var originalEnvironment = environment.Keys.ToDictionary(key => key, Environment.GetEnvironmentVariable);
39
try
40
{
41
var manifest = new ToolPackageManifest
42
{
43
Id = "xfestudio.private-toolchain-smoke", Name = "Private runtime smoke", Version = "1.0.0",
44
Description = "Invisible WPF compilation fixture", Author = "XFEstudio",
45
Entry = new ToolEntryManifest { ViewXaml = "Code/Main.xaml", ViewCodeBehind = "Code/Main.xaml.cs", ViewClass = "PrivateRuntimeSmoke.Main" }
46
};
47
await File.WriteAllTextAsync(Path.Combine(workspace, "manifest.json"),
48
JsonSerializer.Serialize(manifest, new JsonSerializerOptions(JsonSerializerDefaults.Web)), timeout.Token);
49
await File.WriteAllTextAsync(Path.Combine(workspace, "Code/Main.xaml"), """
50
<Window x:Class="PrivateRuntimeSmoke.Main" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
51
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Opacity="0" ShowInTaskbar="False" ShowActivated="False">
52
<TextBlock Text="{Binding Value}" />
53
</Window>
54
""", timeout.Token);
55
await File.WriteAllTextAsync(Path.Combine(workspace, "Code/Main.xaml.cs"), $$"""
56
using System.IO;
57
using System.Windows;
58
using System.Windows.Threading;
59
using CommunityToolkit.Mvvm.ComponentModel;
60
namespace PrivateRuntimeSmoke;
61
public partial class Model : ObservableObject
62
{
63
[ObservableProperty] private string value = "source-generator-ok";
64
}
65
public partial class Main : Window
66
{
67
public Main()
68
{
69
InitializeComponent();
70
var model = new Model();
71
DataContext = model;
72
Loaded += (_, _) =>
73
{
74
File.WriteAllLines({{JsonSerializer.Serialize(marker)}}, new[]
75
{
76
typeof(object).Assembly.Location, typeof(Window).Assembly.Location, model.Value
77
});
78
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
79
timer.Tick += (_, _) => { timer.Stop(); Application.Current.Shutdown(); };
80
timer.Start();
81
};
82
}
83
}
84
""", timeout.Token);
85
86
foreach (var (key, value) in environment) Environment.SetEnvironmentVariable(key, value);
87
var build = await ToolProjectRunService.BuildAsync(workspace, manifest, timeout.Token, progress);
88
Ensure(build.Success, build.Message);
89
Console.WriteLine("PASS Code Studio build with unavailable system dotnet");
90
var preview = await ToolProjectRunService.BuildAndRunAsync(workspace, manifest, timeout.Token, progress);
91
await VerifyRuntimeAsync(preview, marker, installation, timeout.Token);
92
93
File.Delete(marker);
94
var package = Path.Combine(root, "smoke.xfetool");
95
ZipFile.CreateFromDirectory(workspace, package);
96
var sha256 = Convert.ToHexString(SHA256.HashData(await File.ReadAllBytesAsync(package, timeout.Token)));
97
var opened = await ToolProjectRunService.BuildPackageAndRunAsync(package, manifest.Id, manifest.Version, sha256,
98
cancellationToken: timeout.Token, progress: progress);
99
await VerifyRuntimeAsync(opened, marker, installation, timeout.Token);
100
Console.WriteLine("PASS Code Studio preview and downloaded package: WPF, XAML, source generator, private CLR and WPF runtime");
101
}
102
finally
103
{
104
foreach (var (key, value) in originalEnvironment) Environment.SetEnvironmentVariable(key, value);
105
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
106
}
107
}
108
109
private static async Task VerifyRuntimeAsync(ToolRunResult result, string marker, ToolchainInstallation installation, CancellationToken token)
110
{
111
Ensure(result.Success && result.ProcessId is not null, result.Message);
112
using var process = Process.GetProcessById(result.ProcessId!.Value);
113
var runtimeRoot = Path.GetDirectoryName(Path.GetDirectoryName(process.MainModule!.FileName))!;
114
try
115
{
116
await process.WaitForExitAsync(token).WaitAsync(TimeSpan.FromSeconds(30), token);
117
Ensure(process.ExitCode == 0, "工具运行失败。");
118
var lines = await File.ReadAllLinesAsync(marker, token);
119
Ensure(lines.Length == 3 && lines.Take(2).All(line => line.StartsWith(installation.Root + Path.DirectorySeparatorChar,
120
StringComparison.OrdinalIgnoreCase)), "工具没有加载私有运行时:" + string.Join("; ", lines));
121
Ensure(lines[2] == "source-generator-ok", "NuGet 源生成器没有正常工作。");
122
Console.WriteLine(string.Join(Environment.NewLine, lines));
123
// The host also waits for a possible elevated replacement before removing the build directory.
124
for (var attempt = 0; attempt < 100 && Directory.Exists(runtimeRoot); attempt++)
125
await Task.Delay(100, token);
126
Ensure(!Directory.Exists(runtimeRoot), "工具退出后未清理生成目录。");
127
}
128
finally
129
{
130
if (!process.HasExited) { process.Kill(entireProcessTree: true); await process.WaitForExitAsync(CancellationToken.None); }
131
}
132
}
133
134
private static void Ensure(bool condition, string message)
135
{
136
if (!condition) throw new InvalidOperationException(message);
137
}
138
139
private sealed class InlineProgress : IProgress<ToolPreparationProgress>
140
{
141
public void Report(ToolPreparationProgress value) => Console.WriteLine(value.Message);
142
}
143
}
@@ -0,0 +1,239 @@
1
using System.Diagnostics;
2
using System.IO;
3
using System.IO.Compression;
4
using System.Net;
5
using System.Net.Http;
6
using System.Security.Cryptography;
7
using System.Text.Json;
8
using System.Xml.Linq;
9
using XFEToolBox.Client.Core.Tools;
10
using XFEToolBox.Client.Utilities;
11
12
namespace XFEToolBox.Client.Wpf.Test;
13
14
public static class ToolchainManagerTests
15
{
16
[TestCase("win-x64")]
17
[TestCase("win-arm64")]
18
[TestCase("win-x86")]
19
public static async Task FirstUseSelectsArchitectureAndReusesCacheOffline(string rid)
20
{
21
using var fixture = new Fixture(rid);
22
var installation = await fixture.Manager.EnsureInstalledAsync();
23
Ensure(installation.RuntimeIdentifier == rid && File.Exists(installation.DotNetPath), "没有安装正确架构的私有 SDK。");
24
Ensure(fixture.Server.Requests == 2, "首次安装应只请求元数据和一个 ZIP。");
25
fixture.Server.Offline = true;
26
var cached = await fixture.NewManager().EnsureInstalledAsync();
27
Ensure(cached.Root == installation.Root && fixture.Server.Requests == 2, "已缓存的组件仍依赖网络。");
28
Ensure(!Directory.EnumerateDirectories(fixture.Manager.CacheRoot, ".staging-*").Any(), "安装完成后遗留下载文件。");
29
}
30
31
[Test]
32
public static async Task ConcurrentInstancesDownloadOnlyOnce()
33
{
34
using var fixture = new Fixture();
35
fixture.Server.BlockDownload = true;
36
var first = fixture.Manager.EnsureInstalledAsync();
37
await fixture.Server.DownloadStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
38
var second = fixture.NewManager().EnsureInstalledAsync();
39
Ensure(!second.IsCompleted, "第二个实例未等待安装锁。");
40
fixture.Server.ReleaseDownload.TrySetResult();
41
var installed = await Task.WhenAll(first, second).WaitAsync(TimeSpan.FromSeconds(10));
42
Ensure(installed[0].Root == installed[1].Root && fixture.Server.Requests == 2, "并发打开重复下载了 SDK。");
43
}
44
45
[Test]
46
public static async Task CancelledDownloadReleasesLockAndCanRetry()
47
{
48
using var fixture = new Fixture();
49
fixture.Server.BlockDownload = true;
50
using var cancellation = new CancellationTokenSource();
51
var first = fixture.Manager.EnsureInstalledAsync(cancellationToken: cancellation.Token);
52
await fixture.Server.DownloadStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
53
cancellation.Cancel();
54
await ThrowsAsync<OperationCanceledException>(() => first);
55
Ensure(!Directory.EnumerateDirectories(fixture.Manager.CacheRoot, "sdk-*").Any(), "取消后发布了不完整组件。");
56
Ensure(!Directory.EnumerateDirectories(fixture.Manager.CacheRoot, ".staging-*").Any(), "取消后未清理临时文件。");
57
fixture.Server.BlockDownload = false;
58
await fixture.NewManager().EnsureInstalledAsync().WaitAsync(TimeSpan.FromSeconds(10));
59
}
60
61
[Test]
62
public static async Task HashMismatchIsRejectedBeforeExtractionAndCanRetry()
63
{
64
using var fixture = new Fixture();
65
fixture.Server.WrongHash = true;
66
await ThrowsAsync<InvalidDataException>(() => fixture.Manager.EnsureInstalledAsync());
67
Ensure(!Directory.EnumerateDirectories(fixture.Manager.CacheRoot, "sdk-*").Any(), "哈希不匹配的下载被启用。");
68
fixture.Server.WrongHash = false;
69
await fixture.Manager.EnsureInstalledAsync();
70
}
71
72
[TestCase("../escaped.dll")]
73
[TestCase("/absolute.dll")]
74
[TestCase("C:/outside.dll")]
75
[TestCase("sdk/file.dll:payload")]
76
public static async Task ArchiveCannotEscapeItsStagingDirectory(string entry)
77
{
78
using var fixture = new Fixture(archive: CreateArchive(extraEntry: entry));
79
await ThrowsAsync<InvalidDataException>(() => fixture.Manager.EnsureInstalledAsync());
80
Ensure(!Directory.EnumerateDirectories(fixture.Manager.CacheRoot, "sdk-*").Any(), "不安全的 ZIP 被启用。");
81
Ensure(!File.Exists(Path.Combine(fixture.Manager.CacheRoot, "escaped.dll")), "ZIP 越界写入文件。");
82
}
83
84
[Test]
85
public static async Task SymbolicLinksAreRejected()
86
{
87
using var fixture = new Fixture(archive: CreateArchive(extraEntry: "link", symbolicLink: true));
88
await ThrowsAsync<InvalidDataException>(() => fixture.Manager.EnsureInstalledAsync());
89
}
90
91
[Test]
92
public static async Task IncompleteWpfRuntimeIsNotCached()
93
{
94
using var fixture = new Fixture(archive: CreateArchive(includeWpf: false));
95
await ThrowsAsync<InvalidDataException>(() => fixture.Manager.EnsureInstalledAsync());
96
Ensure(!Directory.EnumerateDirectories(fixture.Manager.CacheRoot, "sdk-*").Any(), "缺少 WPF 的 SDK 被缓存。");
97
}
98
99
[Test]
100
public static async Task DamagedCacheIsReplacedWithoutUsingIt()
101
{
102
using var fixture = new Fixture();
103
var first = await fixture.Manager.EnsureInstalledAsync();
104
File.Delete(Path.Combine(first.Root, "shared/Microsoft.WindowsDesktop.App/10.0.1/PresentationFramework.dll"));
105
var repaired = await fixture.NewManager().EnsureInstalledAsync();
106
Ensure(repaired.Root != first.Root && fixture.Server.Requests == 4, "损坏的缓存没有重新下载。");
107
}
108
109
[Test]
110
public static async Task GeneratedLauncherAndBuildUseThePrivateSdk()
111
{
112
using var fixture = new Fixture();
113
var installed = await fixture.Manager.EnsureInstalledAsync();
114
var runRoot = fixture.Manager.CreateRunDirectory();
115
var outputRoot = Path.Combine(runRoot, "output");
116
var project = XDocument.Parse(ToolProjectRunService.CreateProjectFile(runRoot, "Test", "XFEToolBox", [], installed, outputRoot));
117
Ensure(project.Descendants("AppHostDotNetSearch").Single().Value == "AppRelative", "启动器仍会寻找全局运行时。");
118
var relativeRoot = project.Descendants("AppHostRelativeDotNet").Single().Value;
119
Ensure(Path.GetFullPath(Path.Combine(outputRoot, relativeRoot)) == installed.Root, "启动器私有运行时路径错误。");
120
Ensure(project.Descendants("SelfContained").Single().Value == "false", "每个工具重复携带了运行时。");
121
var start = new ProcessStartInfo(installed.DotNetPath);
122
start.Environment["MSBuildSDKsPath"] = "invalid-sdk";
123
start.Environment["DOTNET_ROOT_X64"] = "invalid-runtime";
124
start.Environment["DOTNET_HOST_PATH"] = "invalid-host";
125
start.Environment["DOTNET_MSBUILD_SDK_RESOLVER_SDKS_DIR"] = "invalid-resolver";
126
fixture.Manager.ConfigureBuildEnvironment(start, installed);
127
Ensure(!start.Environment.ContainsKey("MSBuildSDKsPath") && !start.Environment.ContainsKey("DOTNET_ROOT_X64"), "构建环境继承了系统 SDK 覆盖配置。");
128
Ensure(start.Environment["DOTNET_ROOT"] == installed.Root, "构建没有绑定私有运行时。");
129
Ensure(start.Environment["DOTNET_HOST_PATH"] == installed.DotNetPath
130
&& !start.Environment.ContainsKey("DOTNET_MSBUILD_SDK_RESOLVER_SDKS_DIR")
131
&& start.Environment["PATH"]!.StartsWith(installed.Root + Path.PathSeparator), "构建中的子工具仍可能调用系统 dotnet。");
132
Ensure(start.Environment["NUGET_PACKAGES"]!.StartsWith(fixture.Manager.CacheRoot), "NuGet 没有使用私有缓存。");
133
}
134
135
private static byte[] CreateArchive(bool includeWpf = true, string? extraEntry = null, bool symbolicLink = false)
136
{
137
string[] files =
138
[
139
"dotnet.exe", "sdk/10.0.101/MSBuild.dll", "sdk/10.0.101/Roslyn/bincore/csc.dll",
140
"sdk/10.0.101/Sdks/Microsoft.NET.Sdk/targets/Microsoft.NET.Sdk.targets",
141
"sdk/10.0.101/Sdks/Microsoft.NET.Sdk.WindowsDesktop/targets/Microsoft.NET.Sdk.WindowsDesktop.targets",
142
"host/fxr/10.0.1/hostfxr.dll", "shared/Microsoft.NETCore.App/10.0.1/coreclr.dll",
143
"shared/Microsoft.WindowsDesktop.App/10.0.1/PresentationFramework.dll",
144
"packs/Microsoft.NETCore.App.Ref/10.0.1/ref/net10.0/System.Runtime.dll",
145
"packs/Microsoft.WindowsDesktop.App.Ref/10.0.1/ref/net10.0/PresentationFramework.dll"
146
];
147
using var stream = new MemoryStream();
148
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
149
{
150
foreach (var file in files.Where(file => includeWpf || !file.StartsWith("shared/Microsoft.WindowsDesktop.App")))
151
{
152
using var entry = archive.CreateEntry(file).Open();
153
entry.Write([1, 2, 3]);
154
}
155
if (extraEntry is not null)
156
{
157
var entry = archive.CreateEntry(extraEntry);
158
if (symbolicLink)
159
entry.ExternalAttributes = unchecked((int)0xa1ff0000);
160
using var output = entry.Open();
161
output.Write([1]);
162
}
163
}
164
return stream.ToArray();
165
}
166
167
private sealed class Fixture : IDisposable
168
{
169
private readonly string _root = Path.Combine(Path.GetTempPath(), "XFEToolBox.Toolchain.Tests", Guid.NewGuid().ToString("N"));
170
private readonly string _rid;
171
private readonly HttpClient _client;
172
public FakeServer Server { get; }
173
public ToolchainManager Manager { get; }
174
175
public Fixture(string rid = "win-x64", byte[]? archive = null)
176
{
177
_rid = rid;
178
Server = new FakeServer(archive ?? CreateArchive(), rid);
179
_client = new HttpClient(Server);
180
Manager = NewManager();
181
}
182
public ToolchainManager NewManager() => new(_root, _rid, _client);
183
public void Dispose()
184
{
185
_client.Dispose();
186
if (Directory.Exists(_root)) Directory.Delete(_root, recursive: true);
187
}
188
}
189
190
private sealed class FakeServer(byte[] archive, string rid) : HttpMessageHandler
191
{
192
public int Requests;
193
public bool Offline;
194
public bool WrongHash;
195
public bool BlockDownload;
196
public TaskCompletionSource DownloadStarted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
197
public TaskCompletionSource ReleaseDownload { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
198
199
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
200
{
201
if (Offline) throw new HttpRequestException("Offline test");
202
Interlocked.Increment(ref Requests);
203
if (request.RequestUri!.AbsolutePath.EndsWith("releases.json"))
204
{
205
var hash = WrongHash ? new string('0', 128) : Convert.ToHexString(SHA512.HashData(archive));
206
var metadata = new Dictionary<string, object>
207
{
208
["latest-sdk"] = "10.0.101",
209
["releases"] = new[] { new { sdks = new[] { new Dictionary<string, object>
210
{
211
["version"] = "10.0.101", ["runtime-version"] = "10.0.1",
212
["files"] = new[]
213
{
214
new { rid = "linux-x64", name = "sdk.zip", url = "https://builds.dotnet.microsoft.com/wrong.zip", hash },
215
new { rid, name = "sdk.zip", url = "https://builds.dotnet.microsoft.com/sdk.zip", hash }
216
}
217
} } } }
218
};
219
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonSerializer.Serialize(metadata)) };
220
}
221
Ensure(request.RequestUri.AbsolutePath == "/sdk.zip", "下载了错误架构的 SDK。");
222
DownloadStarted.TrySetResult();
223
if (BlockDownload) await ReleaseDownload.Task.WaitAsync(cancellationToken);
224
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(archive) };
225
}
226
}
227
228
private static void Ensure(bool condition, string message)
229
{
230
if (!condition) throw new InvalidOperationException(message);
231
}
232
233
private static async Task ThrowsAsync<T>(Func<Task> action) where T : Exception
234
{
235
try { await action(); }
236
catch (T) { return; }
237
throw new InvalidOperationException($"Expected {typeof(T).Name}.");
238
}
239
}
@@ -6,6 +6,7 @@ using System.Security;
6
6
using System.Security.Cryptography;
7
7
using System.Text;
8
8
using System.Text.Json;
9
using XFEToolBox.Client.Core.Tools;
9
10
using XFEToolBox.Core.Model;
10
11
using XFEToolBox.Core.Tools;
11
12
using XFEToolBox.WpfCore.Controls;
@@ -23,7 +24,8 @@ internal static class ToolProjectRunService
23
24
public static async Task<ToolRunResult> BuildAsync(
24
25
string workspaceRoot,
25
26
ToolPackageManifest manifest,
26
CancellationToken cancellationToken = default)
27
CancellationToken cancellationToken = default,
28
IProgress<ToolPreparationProgress>? progress = null)
27
29
{
28
30
return await BuildAndRunCoreAsync(
29
31
workspaceRoot,
@@ -32,13 +34,15 @@ internal static class ToolProjectRunService
32
34
temporaryWorkspaceRoot: null,
33
35
launchAfterBuild: false,
34
36
runAsAdministrator: false,
35
cancellationToken);
37
cancellationToken,
38
progress);
36
39
}
37
40
38
41
public static async Task<ToolRunResult> BuildAndRunAsync(
39
42
string workspaceRoot,
40
43
ToolPackageManifest manifest,
41
CancellationToken cancellationToken = default)
44
CancellationToken cancellationToken = default,
45
IProgress<ToolPreparationProgress>? progress = null)
42
46
{
43
47
return await BuildAndRunCoreAsync(
44
48
workspaceRoot,
@@ -47,7 +51,8 @@ internal static class ToolProjectRunService
47
51
temporaryWorkspaceRoot: null,
48
52
launchAfterBuild: true,
49
53
runAsAdministrator: false,
50
cancellationToken);
54
cancellationToken,
55
progress);
51
56
}
52
57
53
58
public static async Task<ToolRunResult> BuildPackageAndRunAsync(
@@ -56,7 +61,8 @@ internal static class ToolProjectRunService
56
61
string expectedVersion,
57
62
string expectedSha256,
58
63
bool runAsAdministrator = false,
59
CancellationToken cancellationToken = default)
64
CancellationToken cancellationToken = default,
65
IProgress<ToolPreparationProgress>? progress = null)
60
66
{
61
67
var packageWorkspaceRoot = Path.Combine(
62
68
Path.GetTempPath(),
@@ -81,7 +87,8 @@ internal static class ToolProjectRunService
81
87
packageWorkspaceRoot,
82
88
launchAfterBuild: true,
83
89
runAsAdministrator,
84
cancellationToken);
90
cancellationToken,
91
progress);
85
92
}
86
93
catch (OperationCanceledException)
87
94
{
@@ -102,14 +109,23 @@ internal static class ToolProjectRunService
102
109
string? temporaryWorkspaceRoot,
103
110
bool launchAfterBuild,
104
111
bool runAsAdministrator,
105
CancellationToken cancellationToken)
112
CancellationToken cancellationToken,
113
IProgress<ToolPreparationProgress>? progress)
106
114
{
107
var runtimeRoot = Path.Combine(Path.GetTempPath(), "XFEToolBox", "CodeStudioRuns", Guid.NewGuid().ToString("N"));
115
var toolchainManager = ToolchainManager.Default;
116
var runtimeRoot = toolchainManager.CreateRunDirectory();
108
117
var outputRoot = Path.Combine(runtimeRoot, "output");
109
118
Directory.CreateDirectory(runtimeRoot);
110
119
111
120
try
112
121
{
122
var toolchain = await toolchainManager.EnsureInstalledAsync(progress, cancellationToken);
123
progress?.Report(new("正在编译工具,首次编译需要获取依赖…"));
124
await File.WriteAllTextAsync(Path.Combine(runtimeRoot, "global.json"),
125
JsonSerializer.Serialize(new
126
{
127
sdk = new { version = toolchain.SdkVersion, rollForward = "disable", allowPrerelease = false }
128
}), cancellationToken);
113
129
var assemblyName = $"XFEToolRuntime_{Guid.NewGuid():N}";
114
130
var hostAssemblyName = typeof(ToolProjectRunService).Assembly.GetName().Name
115
131
?? throw new InvalidOperationException("无法确定宿主程序集名称。");
@@ -128,7 +144,7 @@ internal static class ToolProjectRunService
128
144
var toolIconPath = ResolveToolIconPath(preparedWorkspaceRoot, manifest.Icon);
129
145
await File.WriteAllTextAsync(
130
146
projectPath,
131
CreateProjectFile(preparedWorkspaceRoot, assemblyName, hostAssemblyName, manifest.NuGetPackages),
147
CreateProjectFile(preparedWorkspaceRoot, assemblyName, hostAssemblyName, manifest.NuGetPackages, toolchain, outputRoot),
132
148
new UTF8Encoding(false),
133
149
cancellationToken);
134
150
await File.WriteAllTextAsync(
@@ -137,7 +153,7 @@ internal static class ToolProjectRunService
137
153
new UTF8Encoding(false),
138
154
cancellationToken);
139
155
140
var buildInfo = new ProcessStartInfo("dotnet")
156
var buildInfo = new ProcessStartInfo(toolchain.DotNetPath)
141
157
{
142
158
WorkingDirectory = runtimeRoot,
143
159
UseShellExecute = false,
@@ -145,19 +161,35 @@ internal static class ToolProjectRunService
145
161
RedirectStandardOutput = true,
146
162
RedirectStandardError = true
147
163
};
148
buildInfo.ArgumentList.Add("build");
164
// AppHostDotNetSearch is embedded by publish, not by build.
165
buildInfo.ArgumentList.Add("publish");
149
166
buildInfo.ArgumentList.Add(projectPath);
150
167
buildInfo.ArgumentList.Add("--nologo");
168
buildInfo.ArgumentList.Add("--configuration");
169
buildInfo.ArgumentList.Add("Release");
170
buildInfo.ArgumentList.Add("--disable-build-servers");
151
171
buildInfo.ArgumentList.Add("--output");
152
172
buildInfo.ArgumentList.Add(outputRoot);
153
173
buildInfo.ArgumentList.Add("--property:UseSharedCompilation=false");
154
174
buildInfo.ArgumentList.Add("--property:RestoreIgnoreFailedSources=true");
175
toolchainManager.ConfigureBuildEnvironment(buildInfo, toolchain);
155
176
156
177
using var buildProcess = Process.Start(buildInfo)
157
?? throw new InvalidOperationException("无法启动 .NET SDK。请确认已安装 .NET 10 SDK。");
158
var standardOutputTask = buildProcess.StandardOutput.ReadToEndAsync(cancellationToken);
159
var standardErrorTask = buildProcess.StandardError.ReadToEndAsync(cancellationToken);
160
await buildProcess.WaitForExitAsync(cancellationToken);
178
?? throw new InvalidOperationException("无法启动工具编译组件,请重试。");
179
var standardOutputTask = buildProcess.StandardOutput.ReadToEndAsync();
180
var standardErrorTask = buildProcess.StandardError.ReadToEndAsync();
181
try
182
{
183
await buildProcess.WaitForExitAsync(cancellationToken);
184
}
185
catch (OperationCanceledException)
186
{
187
try { buildProcess.Kill(entireProcessTree: true); }
188
catch (InvalidOperationException) when (buildProcess.HasExited) { }
189
await buildProcess.WaitForExitAsync();
190
await Task.WhenAll(standardOutputTask, standardErrorTask);
191
throw;
192
}
161
193
var buildOutput = (await standardOutputTask) + Environment.NewLine + (await standardErrorTask);
162
194
if (buildProcess.ExitCode != 0)
163
195
{
@@ -187,6 +219,7 @@ internal static class ToolProjectRunService
187
219
runtimeExecutable,
188
220
workspaceRoot,
189
221
requiresElevatedProcess);
222
progress?.Report(new("正在打开工具…"));
190
223
var runtimeProcess = Process.Start(runInfo)
191
224
?? throw new InvalidOperationException("工具运行进程启动失败。");
192
225
var runtimeStandardOutputTask = runInfo.RedirectStandardOutput
@@ -260,7 +293,9 @@ internal static class ToolProjectRunService
260
293
string workspaceRoot,
261
294
string assemblyName,
262
295
string hostAssemblyName,
263
IReadOnlyCollection<ToolNuGetPackageReference>? nugetPackages)
296
IReadOnlyCollection<ToolNuGetPackageReference>? nugetPackages,
297
ToolchainInstallation? toolchain = null,
298
string? outputRoot = null)
264
299
{
265
300
var root = EscapeXml(Path.GetFullPath(workspaceRoot).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
266
301
var coreAssembly = EscapeXml(typeof(ToolPackageManifest).Assembly.Location);
@@ -292,6 +327,19 @@ internal static class ToolProjectRunService
292
327
packageReferences
293
328
.OrderBy(package => package.Key, StringComparer.OrdinalIgnoreCase)
294
329
.Select(package => $" <PackageReference Include=\"{EscapeXml(package.Key)}\" Version=\"{EscapeXml(package.Value)}\" />"));
330
var runtimeProperties = string.Empty;
331
if (toolchain is not null)
332
{
333
var relativeDotNet = Path.GetRelativePath(outputRoot ?? throw new ArgumentNullException(nameof(outputRoot)), toolchain.Root);
334
if (Path.IsPathRooted(relativeDotNet))
335
throw new InvalidOperationException("工具运行目录与运行组件必须位于同一磁盘。");
336
// Embedded in the native launcher: also works when UAC replaces the process environment.
337
runtimeProperties = $"""
338
<RuntimeIdentifier>{EscapeXml(toolchain.RuntimeIdentifier)}</RuntimeIdentifier>
339
<AppHostDotNetSearch>AppRelative</AppHostDotNetSearch>
340
<AppHostRelativeDotNet>{EscapeXml(relativeDotNet)}</AppHostRelativeDotNet>
341
""";
342
}
295
343
return $$"""
296
344
<Project Sdk="Microsoft.NET.Sdk">
297
345
<PropertyGroup>
@@ -300,6 +348,7 @@ internal static class ToolProjectRunService
300
348
<UseWPF>true</UseWPF>
301
349
<UseAppHost>true</UseAppHost>
302
350
<SelfContained>false</SelfContained>
351
{{runtimeProperties}}
303
352
<Nullable>enable</Nullable>
304
353
<ImplicitUsings>enable</ImplicitUsings>
305
354
<AssemblyName>{{assemblyName}}</AssemblyName>
@@ -8,6 +8,7 @@ using System.Windows.Controls;
8
8
using System.Windows.Input;
9
9
using System.Windows.Media;
10
10
using System.Windows.Media.Imaging;
11
using XFEToolBox.Client.Core.Tools;
11
12
using XFEToolBox.Client.Model;
12
13
using XFEToolBox.Client.Models;
13
14
using XFEToolBox.Client.Utilities;
@@ -490,13 +491,26 @@ public partial class ToolBoxPage : Page
490
491
StatusText.Text = runAsAdministrator
491
492
? $"正在准备 {card.Name},随后将向 Windows 请求管理员权限…"
492
493
: $"正在编译并打开 {card.Name}…";
494
var preparationProgress = new Progress<ToolPreparationProgress>(item =>
495
{
496
if (card.IsEnabled || cancellationToken.IsCancellationRequested)
497
return;
498
card.IsDownloading = true;
499
card.IsDownloadIndeterminate = item.Percentage is null;
500
card.DownloadProgress = item.Percentage ?? 0;
501
card.DownloadProgressText = item.Message;
502
card.CacheState = item.Percentage is { } percentage ? $"准备 {percentage:0}%" : "正在准备…";
503
StatusText.Text = $"{card.Name} · {item.Message}";
504
activity.Report(item.Percentage, StatusText.Text);
505
});
493
506
var runResult = await ToolProjectRunService.BuildPackageAndRunAsync(
494
507
cachePath,
495
508
card.Id,
496
509
package.Version,
497
510
package.Sha256,
498
511
runAsAdministrator,
499
cancellationToken);
512
cancellationToken,
513
preparationProgress);
500
514
if (!runResult.Success)
501
515
throw new InvalidOperationException(runResult.Message);
502
516
@@ -22,6 +22,7 @@ using Ganss.Xss;
22
22
using Markdig;
23
23
using Microsoft.Web.WebView2.Core;
24
24
using Microsoft.Win32;
25
using XFEToolBox.Client.Core.Tools;
25
26
using XFEToolBox.Client.Model;
26
27
using XFEToolBox.Client.Utilities;
27
28
using XFEToolBox.WpfCore.Windowing;
@@ -1149,7 +1150,8 @@ public partial class ToolCodeEditorWindow : Window
1149
1150
SetHostStatus("正在保存并编译工具…");
1150
1151
activity.Report(null, "正在保存并编译工具…");
1151
1152
var manifest = await SaveAndReadManifestAsync();
1152
var result = await ToolProjectRunService.BuildAndRunAsync(_workspaceRoot, manifest, activity.CancellationToken);
1153
var progress = CreateToolPreparationProgress(activity);
1154
var result = await ToolProjectRunService.BuildAndRunAsync(_workspaceRoot, manifest, activity.CancellationToken, progress);
1153
1155
if (!result.Success)
1154
1156
{
1155
1157
SetHostStatus("工具编译失败");
@@ -1179,6 +1181,15 @@ public partial class ToolCodeEditorWindow : Window
1179
1181
}
1180
1182
}
1181
1183
1184
private IProgress<ToolPreparationProgress> CreateToolPreparationProgress(ActivityHandle activity) =>
1185
new Progress<ToolPreparationProgress>(item =>
1186
{
1187
if (RunButton.IsEnabled || activity.CancellationToken.IsCancellationRequested)
1188
return;
1189
SetHostStatus(item.Message);
1190
activity.Report(item.Percentage, item.Message);
1191
});
1192
1182
1193
private async void BuildProjectButton_Click(object sender, RoutedEventArgs e)
1183
1194
{
1184
1195
if (!_editorReady)
@@ -1195,7 +1206,8 @@ public partial class ToolCodeEditorWindow : Window
1195
1206
SetHostStatus("正在保存并生成工具工程…");
1196
1207
activity.Report(null, "正在保存并生成工具工程…");
1197
1208
var manifest = await SaveAndReadManifestAsync();
1198
var result = await ToolProjectRunService.BuildAsync(_workspaceRoot, manifest, activity.CancellationToken);
1209
var progress = CreateToolPreparationProgress(activity);
1210
var result = await ToolProjectRunService.BuildAsync(_workspaceRoot, manifest, activity.CancellationToken, progress);
1199
1211
if (!result.Success)
1200
1212
{
1201
1213
SetHostStatus("工具生成失败");
@@ -27,7 +27,11 @@
27
27
28
28
`.xfetool` 是扩展名固定的 ZIP 源码包,当前 `packageFormatVersion` 为 `1`。服务端使用 `XFEExtension.NetCore.ServerInteractive` 保存、校验和分发工具包,但不会在服务器上编译或执行其中的代码。
29
29
30
客户端在下载后校验服务端返回的 SHA-256,再把包解压到临时目录、生成独立的 WPF 运行工程并调用 `dotnet` 编译。工具最终在单独进程和窗口中运行,但仍拥有当前桌面用户的系统权限,因此发布前必须审核源码。
30
客户端在下载后校验服务端返回的 SHA-256,再把包解压到临时目录、生成独立的 WPF 运行工程并调用应用私有的 `dotnet` 编译。使用自包含发布版不需要用户安装 .NET:首次打开工具或在 Code Studio 中生成、预览时,应用会从 Microsoft 官方发布元数据选择对应进程架构的 .NET 10 SDK ZIP(包含 WPF 运行时),校验 SHA-512 后解压到 `%LOCALAPPDATA%\XFEToolBox\Toolchains\net10\<架构>`,后续直接复用完整缓存。下载支持进度显示与取消,失败后可重试,不修改系统 PATH 或系统 .NET 安装。
31
32
生成的工具通过原生启动器中的相对路径使用同一份私有运行时,普通启动和管理员启动都不依赖系统安装的 .NET。工具最终在单独进程和窗口中运行,但仍拥有当前桌面用户(或经 UAC 授权的管理员)的系统权限,因此发布前必须审核源码。首次准备组件与获取尚未缓存的 NuGet 依赖需要联网;安装包无需预先携带这份 SDK 缓存。
33
34
私有组件的单元测试可用 `--tests --filter ToolchainManagerTests` 运行。真实下载和 WPF 编译启动验证是显式测试:`dotnet run --project XFEToolBox.Client.Wpf.Test -c Release -p:EmbedInstallationPackage=false -- --tests --filter ToolchainIntegrationTests --explicit --no-parallel --report none`。它会屏蔽测试进程的系统 .NET 环境设置,验证 Code Studio 生成、预览和工具包打开,并检查实际加载的 CLR 与 WPF 程序集来自私有组件目录。
31
35
32
36
每个工具拥有独立进程、独立 WPF `Application`、独立宿主窗口和按工具 ID 隔离的数据目录。独立进程可以隔离崩溃和静态状态,但不是安全沙箱:工具仍能访问当前 Windows 用户有权访问的文件、网络、剪贴板、注册表和进程。
33
37
@@ -170,7 +174,7 @@ Code Studio 可视化设计器提供的通用权限名称为:`FileSystem`、`N
170
174
171
175
### `nugetPackages`
172
176
173
每个项目可以在 Code Studio 的 `manifest.json · 可视化配置` →“NuGet 包”中独立添加、更新或移除包。运行和生成验证时,工具箱会把这些引用写入该工具自己的临时 `.csproj`,再使用标准 `dotnet restore/build` 流程解析依赖;发布到 `.xfetool` 后,包引用仍保存在清单中。
177
每个项目可以在 Code Studio 的 `manifest.json · 可视化配置` →“NuGet 包”中独立添加、更新或移除包。运行和生成验证时,工具箱会把这些引用写入该工具自己的临时 `.csproj`,再使用私有 SDK 的 `dotnet publish`(包含 restore)解析依赖,NuGet 包也缓存在应用私有目录;发布到 `.xfetool` 后,包引用仍保存在清单中。
174
178
175
179
包 ID 仅允许字母、数字、点、短横线和下划线,长度不超过 100;`version` 必须固定为 `1.2.3`、`1.2.3-beta.1` 这类精确版本,不接受 `*`、`[1.0,2.0)` 等浮动版本或范围。项目显式引用 `CommunityToolkit.Mvvm` 时可以覆盖工具箱内置的默认版本。NuGet 包可能携带构建目标并在还原/编译阶段运行,因此只应添加可信来源的包。
176
180
@@ -0,0 +1,4 @@
1
<Project Sdk="Microsoft.NET.Sdk">
2
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0-windows10.0.17763.0</TargetFramework><UseWPF>true</UseWPF><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings><EnableDefaultCompileItems>false</EnableDefaultCompileItems><EnableDefaultPageItems>false</EnableDefaultPageItems><StartupObject>FormatConverter.Validation.Program</StartupObject><ToolWorkspace>$(LOCALAPPDATA)\XFEToolBox\CrossVersion\EditorWorkspaces\FormatConverter</ToolWorkspace></PropertyGroup>
3
<ItemGroup><Compile Include="Program.cs"/><Compile Include="$(ToolWorkspace)\Code\**\*.cs" Link="Tool\%(RecursiveDir)%(Filename)%(Extension)"/><Page Include="$(ToolWorkspace)\Code\**\*.xaml" Link="Tool\%(RecursiveDir)%(Filename)%(Extension)"/><ProjectReference Include="..\..\XFEToolBox\XFEToolBox.Client.csproj"/><PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2"/><PackageReference Include="Magick.NET-Q16-AnyCPU" Version="14.17.1"/></ItemGroup>
4
</Project>
@@ -0,0 +1,48 @@
1
# FormatConverter validation
2
3
Runs the actual FormatConverter source, Magick.NET native codecs, FFmpeg/FFprobe, and a real WPF view with the toolbox theme. No user media is modified or used. Input fixtures are generated in a per-run test-artifacts directory.
4
5
## Latest verified result
6
7
2026-09-13: **135 checks passed**, exit code 0, using `--check-package --register`. Both the workspace and the extracted package compiled successfully through the toolbox production builder; all package file bytes matched the workspace.
8
9
Artifacts: `bin/Debug/net10.0-windows10.0.17763.0/test-artifacts/run-20260913-025643/`.
10
11
Package: `xfestudio.format-converter-1.0.0.xfetool` (39,022 bytes).
12
13
SHA-256: `DA15E9C1061A582DB8B61041CE2C5CD55B42B0ED6753D2A1145D09137026DD46`.
14
15
## Run
16
17
Prerequisites: Windows, .NET 10 SDK, NuGet access/cache, the tool workspace at `%LOCALAPPDATA%\XFEToolBox\CrossVersion\EditorWorkspaces\FormatConverter`, and a working FFmpeg/FFprobe pair discoverable by `EngineSetup` (PATH, previously configured environment, or VideoStudio tool runtime).
18
19
```powershell
20
dotnet run --project tests/FormatConverter.Validation/FormatConverter.Validation.csproj
21
```
22
23
Optional switches:
24
25
- `--skip-host`: codec/guard/WPF checks only, without the toolbox production compilation step.
26
- `--check-package`: also extract the version-matching `.xfetool` from the workspace sibling `Packages` directory using the production package loader, byte-compare against the workspace, and compile the extracted package.
27
- `--register`: remember the project in the toolbox's editor project list. Omit this for a read-only registration check.
28
29
Results and rendered WPF screenshots are saved under `bin/Debug/net10.0-windows10.0.17763.0/test-artifacts/run-<timestamp>/`. The test process exits nonzero on any failed assertion; `results.json` records successful assertions and overall status. A deterministic code-drawn icon is emitted to the tool's `Assets/icon.png` before production compilation.
30
31
## Coverage
32
33
- Encode/decode every advertised image writer (35 with Magick.NET 14.17.1 on the tested machine), including ICO's seven sizes and DDS DXT5 header. Reverse conversions for ICO/DDS/JPEG/WebP/TIFF/TGA/AVIF/PSD, animated frame preservation and rejection of unintended frame loss.
34
- All available 12 audio and 12 video/GIF output presets: actual conversion, FFprobe stream checks and complete FFmpeg decode to a null sink. Video-to-audio and resize presets.
35
- Self-generated MP3 and FLAC NCM containers, including cover padding and payloads exceeding the streaming buffer size: bit-exact extraction, extraction without FFmpeg, real WAV transcode, invalid/truncated header rejection.
36
- Cancellation of a running FFmpeg process, timeout, active conversion cancellation without partial publication, same-name output safety, unchanged source hash and temporary directory cleanup.
37
- Corrupt images, SVG rasterization/external-reference rejection, executable/playlist extension exclusion and renamed concat demuxer rejection.
38
- Real ZIP extraction, traversal rejection, HTTP download via controlled fixture transport, matching and mismatching SHA-256.
39
- Real ViewModel conversion command, UI dispatcher heartbeat, batch continuation after a bad file, safe close during active work, audio/NCM tab, WPF error-level binding tracing, full/minimum-size page rendering.
40
- Production toolbox build, and optionally package extraction/byte identity/extracted-project compilation.
41
42
## Tested scope and limits
43
44
The local run uses Magick.NET-Q16-AnyCPU 14.17.1 and the existing Gyan FFmpeg 9.0.1 Essentials installation. No network download or modification of that existing FFmpeg installation is performed by these tests.
45
46
NCM fixtures are synthetic protocol samples, not user-provided service downloads. This does not prove compatibility with every NCM variant. No exhaustive fuzzing, every input codec variant, HEIC input sample, large real-world project, full HDR precision preservation, or manual click/drag/file-picker test is claimed. WPF is instantiated/rendered and its actual command is invoked programmatically; package compilation is distinct from a full manually operated runtime session.
47
48
The installer tests exercise stream download/checksum/extraction with a mock HTTP transport; they do not assert live Gyan availability or a complete live download installation. The one-click configuration code additionally verifies downloaded executables before remembering them.
@@ -230,7 +230,7 @@ internal static class Program
230
230
{
231
231
var assembly=typeof(XFEToolBox.Client.Models.LauncherItem).Assembly;var service=assembly.GetType("XFEToolBox.Client.Utilities.ToolProjectRunService",true)!;
232
232
var manifest=JsonSerializer.Deserialize<ToolPackageManifest>(File.ReadAllText(Path.Combine(Workspace,"manifest.json")),new JsonSerializerOptions(JsonSerializerDefaults.Web))!;
233
async Task Build(string root){var task=(Task)service.GetMethod("BuildAsync",BindingFlags.Public|BindingFlags.Static)!.Invoke(null,[root,manifest,CancellationToken.None])!;await task.WaitAsync(TimeSpan.FromMinutes(3));var result=task.GetType().GetProperty("Result")!.GetValue(task)!;Assert((bool)result.GetType().GetProperty("Success")!.GetValue(result)!,"production host compilation: "+result.GetType().GetProperty("Message")!.GetValue(result));}
233
async Task Build(string root){var task=(Task)service.GetMethod("BuildAsync",BindingFlags.Public|BindingFlags.Static)!.Invoke(null,[root,manifest,CancellationToken.None,null])!;await task.WaitAsync(TimeSpan.FromMinutes(3));var result=task.GetType().GetProperty("Result")!.GetValue(task)!;Assert((bool)result.GetType().GetProperty("Success")!.GetValue(result)!,"production host compilation: "+result.GetType().GetProperty("Message")!.GetValue(result));}
234
234
await Build(Workspace);
235
235
if(args.Contains("--check-package")){string package=Path.Combine(Path.GetDirectoryName(Workspace)!,"Packages",$"{manifest.Id}-{manifest.Version}.xfetool"),extracted=Path.Combine(Artifacts,"package-"+Guid.NewGuid().ToString("N"));await (Task<ToolPackageManifest>)service.GetMethod("ExtractAndValidatePackageAsync",BindingFlags.NonPublic|BindingFlags.Static)!.Invoke(null,[package,extracted,manifest.Id,manifest.Version,CancellationToken.None])!;var files=Directory.GetFiles(extracted,"*",SearchOption.AllDirectories);Assert(files.Length==Directory.GetFiles(Workspace,"*",SearchOption.AllDirectories).Length&&files.All(f=>File.ReadAllBytes(f).SequenceEqual(File.ReadAllBytes(Path.Combine(Workspace,Path.GetRelativePath(extracted,f))))),"package matches tested sources");await Build(extracted);}
236
236
if(args.Contains("--register"))await (Task)assembly.GetType("XFEToolBox.Client.Utilities.ToolProjectWorkspaceService",true)!.GetMethod("RememberProjectAsync",BindingFlags.Public|BindingFlags.Static)!.Invoke(null,[Workspace])!;