diff --git a/desktop/App.xaml.cs b/desktop/App.xaml.cs
index 8497e80..ecaacbe 100644
--- a/desktop/App.xaml.cs
+++ b/desktop/App.xaml.cs
@@ -104,26 +104,20 @@ public partial class App : Application
AppLog.Write($"发现新版本 {info.Version}(当前 {current}):{info.DownloadUrl}");
- var notes = string.IsNullOrWhiteSpace(info.Notes) ? string.Empty : $"\n\n更新内容:{info.Notes}";
- var size = info.Size > 0 ? $"\n安装包大小:{info.Size / 1024.0 / 1024.0:0.0} MB" : string.Empty;
-
- var answer = MessageBox.Show(
- $"发现新版本 {info.Version}(当前 {current})。{notes}{size}\n\n现在下载安装包吗?",
- "软件更新",
- MessageBoxButton.YesNo,
- MessageBoxImage.Information);
-
- if (answer != MessageBoxResult.Yes) return;
-
- if (string.IsNullOrWhiteSpace(info.DownloadUrl))
+ // 软件内弹窗 + 进度条下载 + 自动安装(不跳浏览器)
+ AppLog.Write("准备显示更新窗口…");
+ var update = new UpdateWindow(info, current)
{
- AppLog.Write("更新信息里没有下载地址(version.json 的 downloadUrl)");
- return;
+ // 回归测试用:YUNCANG_AUTO_UPDATE=1 时不点按钮直接开始下载
+ AutoStart = Environment.GetEnvironmentVariable("YUNCANG_AUTO_UPDATE") == "1",
+ };
+ var result = update.ShowDialog();
+ AppLog.Write($"更新窗口返回:{result}");
+ if (result == true)
+ {
+ AppLog.Write("更新已开始安装,退出本程序以释放 exe");
+ ExitApplication();
}
-
- // 用默认浏览器打开下载(MSI 能直接下,也能交给用户自己跑)
- Process.Start(new ProcessStartInfo(info.DownloadUrl) { UseShellExecute = true });
- AppLog.Write($"已打开下载:{info.DownloadUrl}");
}
catch (Exception ex)
{
diff --git a/desktop/README.md b/desktop/README.md
index 55b2099..80057d9 100644
--- a/desktop/README.md
+++ b/desktop/README.md
@@ -150,10 +150,19 @@ cd desktop\installer
```
软件启动(登录后)→ GET {后端}/download/version.json?t=时间戳
- → version.json 里的 version 比当前程序集版本新
- → 弹窗「发现新版本 x.y.z」→ 用户点是 → 浏览器打开 downloadUrl 下载安装
+ → version.json 的 version 比当前程序集版本新
+ → 软件内弹窗:新版本号 / 更新说明 / 安装包大小
+ → 点「立即更新」→ **软件内下载(进度条)**→ MD5 校验
+ → 自动静默安装(msiexec /passive)→ 软件退出 → 装完自动重新打开
```
+- **不跳浏览器**:下载、进度、校验、安装都在软件里完成。
+- 下载落在 `%TEMP%\YuncangTraceUpdate\`,文件名取 downloadUrl 里的真实文件名。
+- 安装前会等 3 秒(让本进程先退出,否则 exe 被占用换不掉);perUser 安装不需要管理员。
+- **版本一致性防护**:若 `downloadUrl` 里的包版本(`YuncangTraceSetup-x.y.z.msi`)不比当前版本新,
+ 直接忽略 —— 防止 version.json 配错/漏传包导致「装完还是旧版 → 无限弹窗」。
+- 回归测试可用环境变量 `YUNCANG_AUTO_UPDATE=1` 让弹窗出现后自动开始下载(无需手点)。
+
`version.json` 长这样(脚本生成,**不用手写**):
```json
diff --git a/desktop/Services/UpdateChecker.cs b/desktop/Services/UpdateChecker.cs
index e37a59a..5fc96c9 100644
--- a/desktop/Services/UpdateChecker.cs
+++ b/desktop/Services/UpdateChecker.cs
@@ -1,6 +1,7 @@
using System;
using System.Net.Http;
using System.Text.Json;
+using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
@@ -35,6 +36,17 @@ public static class UpdateChecker
public static string VersionUrl(string serverBaseUrl)
=> serverBaseUrl.TrimEnd('/') + "/download/version.json";
+ ///
+ /// 从下载地址里解析安装包版本:`.../YuncangTraceSetup-1.0.3.msi` → 1.0.3;解析不到返回 null。
+ ///
+ public static Version? PackageVersionOf(string? downloadUrl)
+ {
+ if (string.IsNullOrWhiteSpace(downloadUrl)) return null;
+
+ var match = Regex.Match(downloadUrl, @"YuncangTraceSetup-(\d+(?:\.\d+){1,3})\.msi", RegexOptions.IgnoreCase);
+ return match.Success && Version.TryParse(match.Groups[1].Value, out var version) ? version : null;
+ }
+
///
/// 检查是否有更新。
///
@@ -66,9 +78,16 @@ public static class UpdateChecker
if (!Version.TryParse(text.Trim(), out var remote)) return null;
if (remote <= current) return null;
+ var downloadUrl = root.TryGetProperty("downloadUrl", out var d) ? d.GetString() : null;
+
+ // 防御:version.json 的 version 可能和下载包本身不一致(配错、或发版时漏传包)。
+ // 若包里的版本并不比当前新,提示了也装不上去 → 会无限弹窗,直接忽略。
+ var packageVersion = PackageVersionOf(downloadUrl);
+ if (packageVersion is not null && packageVersion <= current) return null;
+
return new UpdateInfo(
text.Trim(),
- root.TryGetProperty("downloadUrl", out var d) ? d.GetString() : null,
+ downloadUrl,
root.TryGetProperty("md5", out var m) ? m.GetString() : null,
root.TryGetProperty("size", out var s) && s.TryGetInt64(out var size) ? size : 0,
root.TryGetProperty("releaseNotes", out var n) ? n.GetString() : null);
diff --git a/desktop/UpdateWindow.xaml b/desktop/UpdateWindow.xaml
new file mode 100644
index 0000000..b26fa55
--- /dev/null
+++ b/desktop/UpdateWindow.xaml
@@ -0,0 +1,55 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/desktop/UpdateWindow.xaml.cs b/desktop/UpdateWindow.xaml.cs
new file mode 100644
index 0000000..cf55a9a
--- /dev/null
+++ b/desktop/UpdateWindow.xaml.cs
@@ -0,0 +1,217 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Net.Http;
+using System.Security.Cryptography;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using YuncangTrace.LocalService.Services;
+
+namespace YuncangTrace.LocalService;
+
+///
+/// 更新窗口:软件内下载(进度条)→ 校验 MD5 → 自动静默安装并退出。
+///
+/// 为什么不在浏览器里打开下载链接:
+/// 用户还要自己找文件、自己双击、自己处理"文件被占用";
+/// 这里直接下到临时目录、校验、`msiexec /passive` 安装,装完自动把新版拉起来。
+///
+public partial class UpdateWindow : Window
+{
+ private readonly UpdateInfo _info;
+ private bool _busy;
+
+ ///
+ /// 打开后自动开始下载(无 UI 自动化时用):由环境变量 YUNCANG_AUTO_UPDATE=1 开启,
+ /// 仅用于回归测试,正常使用不会走到。
+ ///
+ public bool AutoStart { get; set; }
+
+ public UpdateWindow(UpdateInfo info, Version current)
+ {
+ InitializeComponent();
+
+ _info = info;
+ TitleText.Text = $"发现新版本 {info.Version}";
+ SubText.Text = $"当前版本 {current} · 安装包 {FormatSize(info.Size)}";
+ NotesText.Text = string.IsNullOrWhiteSpace(info.Notes) ? "(本次更新没有提供说明)" : info.Notes;
+
+ Loaded += (_, _) =>
+ {
+ if (AutoStart) _ = StartUpdateAsync();
+ };
+ }
+
+ private void Later_Click(object sender, RoutedEventArgs e) => Close();
+
+ private void Update_Click(object sender, RoutedEventArgs e) => _ = StartUpdateAsync();
+
+ private async Task StartUpdateAsync()
+ {
+ if (_busy) return;
+
+ if (string.IsNullOrWhiteSpace(_info.DownloadUrl))
+ {
+ StatusText.Text = "更新信息里没有下载地址,请联系管理员。";
+ return;
+ }
+
+ _busy = true;
+ UpdateButton.IsEnabled = false;
+ LaterButton.IsEnabled = false;
+ Progress.Visibility = Visibility.Visible;
+ AppLog.Write($"开始下载更新包:{_info.DownloadUrl}");
+
+ try
+ {
+ StatusText.Text = "正在下载… 0%";
+
+ var progress = new Progress<(long received, long? total)>(p =>
+ {
+ if (p.total is > 0)
+ {
+ Progress.IsIndeterminate = false;
+ var percent = Math.Min(100.0, p.received * 100.0 / p.total.Value);
+ Progress.Value = percent;
+ StatusText.Text = $"正在下载… {percent:0}%({FormatSize(p.received)} / {FormatSize(p.total.Value)})";
+ }
+ else
+ {
+ // 服务端没给 Content-Length:退化成不确定进度
+ Progress.IsIndeterminate = true;
+ StatusText.Text = $"正在下载… {FormatSize(p.received)}";
+ }
+ });
+
+ var file = await DownloadAsync(_info.DownloadUrl!, progress, CancellationToken.None);
+ AppLog.Write($"更新包下载完成:{file}");
+
+ Progress.IsIndeterminate = false;
+ Progress.Value = 100;
+ StatusText.Text = "下载完成,正在校验安装包…";
+
+ var actual = await Task.Run(() => ComputeMd5(file));
+ if (!string.IsNullOrWhiteSpace(_info.Md5)
+ && !actual.Equals(_info.Md5.Trim(), StringComparison.OrdinalIgnoreCase))
+ {
+ TryDelete(file);
+ AppLog.Write($"安装包校验失败:实际 {actual},期望 {_info.Md5}");
+ StatusText.Text = "安装包校验失败(MD5 不一致),请稍后重试。";
+ ResetButtons();
+ return;
+ }
+
+ AppLog.Write("安装包校验通过,开始安装");
+ StatusText.Text = "正在安装,软件会短暂退出,安装完成后自动重新打开…";
+ LaunchInstaller(file);
+
+ // 通知 App:可以退出了(退出后才能替换正在运行的 exe)
+ DialogResult = true;
+ }
+ catch (Exception ex)
+ {
+ StatusText.Text = $"更新失败:{ex.Message}";
+ ResetButtons();
+ }
+ }
+
+ private void ResetButtons()
+ {
+ _busy = false;
+ UpdateButton.IsEnabled = true;
+ LaterButton.IsEnabled = true;
+ Progress.Visibility = Visibility.Collapsed;
+ Progress.IsIndeterminate = false;
+ Progress.Value = 0;
+ }
+
+ /// 下载到临时目录(流式,边下边报进度)
+ private async Task DownloadAsync(
+ string url,
+ IProgress<(long received, long? total)> progress,
+ CancellationToken cancellationToken)
+ {
+ var dir = Path.Combine(Path.GetTempPath(), "YuncangTraceUpdate");
+ Directory.CreateDirectory(dir);
+
+ // 文件名优先用下载地址里的真实文件名(避免 version.json 的 version 与包不一致时名字骗人)
+ var fileName = Path.GetFileName(new Uri(url).LocalPath);
+ if (string.IsNullOrWhiteSpace(fileName) || !fileName.EndsWith(".msi", StringComparison.OrdinalIgnoreCase))
+ {
+ fileName = $"YuncangTraceSetup-{_info.Version}.msi";
+ }
+
+ var file = Path.Combine(dir, fileName);
+
+ using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(15) };
+ using var response = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
+ .ConfigureAwait(false);
+ response.EnsureSuccessStatusCode();
+
+ var total = response.Content.Headers.ContentLength
+ ?? (_info.Size > 0 ? _info.Size : (long?)null);
+
+ await using var source = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ await using var target = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None);
+
+ var buffer = new byte[81920];
+ long received = 0;
+ int read;
+
+ while ((read = await source.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0)
+ {
+ await target.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false);
+ received += read;
+ progress.Report((received, total));
+ }
+
+ return file;
+ }
+
+ private static string ComputeMd5(string file)
+ {
+ using var md5 = MD5.Create();
+ using var stream = File.OpenRead(file);
+ return Convert.ToHexString(md5.ComputeHash(stream)).ToLowerInvariant();
+ }
+
+ private static void TryDelete(string file)
+ {
+ try { File.Delete(file); } catch { /* 忽略 */ }
+ }
+
+ ///
+ /// 启动安装:先等本进程退出(exe 被占用时 MSI 换不掉),再 /passive 安装,
+ /// 装完自动把新版拉起来。perUser 安装,不需要管理员权限。
+ ///
+ private static void LaunchInstaller(string msiPath)
+ {
+ var exe = Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
+ "Programs", "YuncangTrace", "YuncangTrace.LocalService.exe");
+
+ var command = $"/c timeout /t 3 /nobreak >nul & msiexec /i \"{msiPath}\" /passive /norestart";
+ if (File.Exists(exe))
+ {
+ command += $" & start \"\" \"{exe}\"";
+ }
+
+ AppLog.Write($"启动安装程序(软件退出后执行):{msiPath}");
+
+ Process.Start(new ProcessStartInfo("cmd.exe", command)
+ {
+ CreateNoWindow = true,
+ UseShellExecute = false,
+ WindowStyle = ProcessWindowStyle.Hidden,
+ });
+ }
+
+ private static string FormatSize(long bytes)
+ {
+ if (bytes <= 0) return "未知大小";
+ if (bytes >= 1024L * 1024 * 1024) return $"{bytes / 1024.0 / 1024 / 1024:0.0} GB";
+ if (bytes >= 1024 * 1024) return $"{bytes / 1024.0 / 1024:0.0} MB";
+ return $"{bytes / 1024.0:0} KB";
+ }
+}
diff --git a/desktop/installer/build.ps1 b/desktop/installer/build.ps1
index b8af6a4..2037ccd 100644
--- a/desktop/installer/build.ps1
+++ b/desktop/installer/build.ps1
@@ -50,6 +50,20 @@ param(
$ErrorActionPreference = 'Stop'
+# dotnet 可能装在用户目录(免管理员安装):wix 是 dotnet 全局工具(apphost),
+# **只认 DOTNET_ROOT / 默认安装路径,不认 PATH** —— 不设置会报「You must install .NET」。
+$dotnetRoot = Join-Path $env:LOCALAPPDATA 'Microsoft\dotnet'
+if (Test-Path (Join-Path $dotnetRoot 'dotnet.exe')) {
+ $env:DOTNET_ROOT = $dotnetRoot
+ if (($env:Path -split ';') -notcontains $dotnetRoot) {
+ $env:Path = "$dotnetRoot;$env:Path"
+ }
+ Write-Host "DOTNET_ROOT=$dotnetRoot"
+}
+if (-not (Get-Command dotnet -ErrorAction SilentlyContinue)) {
+ throw "找不到 dotnet。请先安装 .NET 8 SDK,或设置 DOTNET_ROOT。"
+}
+
$desktop = Split-Path -Parent $PSScriptRoot # desktop\
$project = Join-Path $desktop 'YuncangTrace.LocalService.csproj'
$publishDir = Join-Path $desktop 'publish'