Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) Auto-update
Egor Khindikaynend2e556e9bcbe
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 6115e7bf..0a869b78 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -220,3 +220,22 @@ The native engine is built by CMake + Ninja, separately from the managed app; thproject copies the resulting `libnota_engine.{dylib,so}` / `nota_engine.dll` plus`nota-scanworker` next to the managed binary for P/Invoke. See [`README.md`](README.md)for commands and [`BUILD.md`](BUILD.md) for details.++## Updates++The welcome screen asks GitHub for the latest published release (`IAppUpdater` →+`Infrastructure/Update/AppUpdater.cs`) and picks the asset `release.yml` builds for this OS+and architecture. **Update** downloads it into `<data>/updates/` and checks its size and the+sha256 `digest` GitHub reports for the asset. On macOS the `.dmg` is mounted and its+`Nota.app` copied out and version-checked. Nothing touches the installed app while Nota runs.+On exit (`desktop.Exit` in `App`) `RunPendingInstall` starts a small detached script. It+waits for the process to end, then puts the new build in place: it swaps the `.app` bundle+on macOS (rolling back on failure) or renames over the AppImage on Linux. On Windows it runs+the Inno Setup installer with `/SILENT`, and `/relaunch=1` makes the installer start Nota+again as the original user. **Restart now** quits through the normal close path, with the+relaunch flag set.++Only a packaged install in a writable location updates in place: an `.app` that isn't+translocated or running off the disk image, an Inno install folder, or `$APPIMAGE`. Dev+builds and everything else get the old **Download** button, which opens the release page.+`NOTA_UPDATE_API` points the check at another release JSON (a URL or a local file).diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d0dbb4f8..14dbf171 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -74,6 +74,12 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.- **Over MCP**, an AI can list the installed models, separate a clip into stems andtranscribe a clip into a MIDI track (`list_ai_models`, `separate_stems`,`convert_audio_to_midi`). Installing a model stays with you.+- **Updates install themselves.** When a new version is out, the banner on the start screen+ now has an **Update** button: Nota downloads the new version with a progress bar and+ checks it against the release's checksum. Then click **Restart now**, or **Later** to+ install it the next time you quit. Works with the macOS app, the Windows installer and+ the Linux AppImage. Copies that can't replace themselves (for example, one run straight+ from the disk image) still link to the release page.### Changed- **Faster saves of projects with audio:** a save now writes only new recordings anddiff --git a/FEATURES.md b/FEATURES.mdindex d80bdbb5..30dddc87 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -801,6 +801,11 @@ and user presets, automation, persistence and cloning.frame).- **What's New** — a window showing changelog entries newer than `LastSeenVersion`, onceafter the first launch on a new version.+- **Self-update** — the start screen's banner announces a newer GitHub release. **Update**+ downloads the build for this platform (with progress, checked against the release's+ sha256). **Restart now** installs it and relaunches, and **Later** installs it on quit.+ This covers the macOS .app, the Windows installer (run silently) and the Linux AppImage.+ Other copies fall back to a link to the release page.- **About** — the app and engine versions, the copyright notice, and a pointer to thethird-party attribution notices (`LICENSES/THIRD-PARTY-NOTICES.md`).- **Settings** — a larger window with a sidebar grouped into Devices, Plug-ins and Generaldiff --git a/scripts/nota.iss b/scripts/nota.issindex 66f31a8a..8e197f9b 100644--- a/scripts/nota.iss+++ b/scripts/nota.iss@@ -47,3 +47,12 @@ Name: "{commondesktop}\Nota"; Filename: "{app}\Nota.App.exe"; Tasks: desktopicon[Run]Filename: "{app}\Nota.App.exe"; Description: "Launch Nota"; Flags: nowait postinstall skipifsilent+; In-app update (AppUpdater): the installer runs /SILENT with /relaunch=1 after "Restart+; now": start Nota again, un-elevated, once the files are in place.+Filename: "{app}\Nota.App.exe"; Flags: nowait runasoriginaluser; Check: RelaunchAfterUpdate++[Code]+function RelaunchAfterUpdate: Boolean;+begin+ Result := WizardSilent and (ExpandConstant('{param:relaunch|0}') = '1');+end;diff --git a/src/managed/Nota.App/App.axaml.cs b/src/managed/Nota.App/App.axaml.csindex b495e4f5..6ba475fd 100644--- a/src/managed/Nota.App/App.axaml.cs+++ b/src/managed/Nota.App/App.axaml.cs@@ -42,6 +42,7 @@ public partial class App : Avalonia.Applicationservices.AddSingleton<ISampleAnalyzer, SampleAnalyzer>();services.AddSingleton<ISampleIndex, SampleLibraryIndex>();services.AddSingleton<IModelStore>(_ => new ModelStore());+ services.AddSingleton<IAppUpdater>(_ => new AppUpdater(AppInfo.Version));services.AddSingleton<IClipAi, ClipAi>();services.AddSingleton<IPresetLibrary, PresetLibrary>();services.AddSingleton<IProjectStore, ProjectStore>();@@ -95,6 +96,9 @@ public partial class App : Avalonia.Applicationif (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop){+ // A downloaded update installs once the app is gone (see AppUpdater).+ desktop.Exit += (_, _) => Services.GetRequiredService<IAppUpdater>().RunPendingInstall();+// Show the splash immediately, then defer the heavy engine spin-up to a// background dispatcher tick so the splash actually paints before the audio// backend loads (a synchronous VM resolve here would freeze the launch).diff --git a/src/managed/Nota.App/MainWindow.Welcome.cs b/src/managed/Nota.App/MainWindow.Welcome.csindex 2479272f..d92e9583 100644--- a/src/managed/Nota.App/MainWindow.Welcome.cs+++ b/src/managed/Nota.App/MainWindow.Welcome.cs@@ -50,11 +50,16 @@ public partial class MainWindowwin.Closed += (_, _) => { try { _recovery.ClearRecovery(); } catch { } };// Look for a newer release in the background; the banner appears if one turns up- // while the launcher is still open.- _ = UpdateChecker.CheckAsync().ContinueWith(t =>+ // while the launcher is still open. "Restart now" quits through the normal close path+ // (the installer runs on exit — see App's Exit hook) and relaunches the new version.+ var updater = App.Services.GetRequiredService<IAppUpdater>();+ _ = updater.CheckAsync().ContinueWith(t =>{- if (t.Result is { } update)- Avalonia.Threading.Dispatcher.UIThread.Post(() => { if (win.IsVisible) win.ShowUpdateAvailable(update); });+ if (t.Result is { } release)+ Avalonia.Threading.Dispatcher.UIThread.Post(() =>+ {+ if (win.IsVisible) win.ShowUpdateAvailable(release, updater, restart: () => { win.Close(); Close(); });+ });}, TaskScheduler.Default);await win.ShowDialog(this);diff --git a/src/managed/Nota.App/UpdateChecker.cs b/src/managed/Nota.App/UpdateChecker.csdeleted file mode 100644index 49d73d8e..00000000--- a/src/managed/Nota.App/UpdateChecker.cs+++ /dev/null@@ -1,61 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.-//-// New-version check for the welcome screen. Asks the GitHub API for the latest-// published release (drafts and pre-releases are excluded by that endpoint) and-// compares its tag against the running version. Best-effort: any network / parse-// failure just means "no update known" — the launcher never waits on or errors-// because of it.--using System;-using System.Net.Http;-using System.Text.Json;-using System.Threading;-using System.Threading.Tasks;--namespace Nota.App;--/// <summary>A release newer than the running app: its version and the page to download it from.</summary>-public sealed record AvailableUpdate(string Version, string Url);--public static class UpdateChecker-{- public const string ReleasesPage = "https://github.com/nota-daw/nota/releases";- private const string LatestApi = "https://api.github.com/repos/nota-daw/nota/releases/latest";-- /// <summary>The latest GitHub release if it's newer than <see cref="AppInfo.Version"/>, else null.</summary>- public static async Task<AvailableUpdate?> CheckAsync(CancellationToken ct = default)- {- try- {- using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(8) };- // GitHub's API rejects requests without a User-Agent.- http.DefaultRequestHeaders.UserAgent.ParseAdd($"Nota/{AppInfo.Version}");- http.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github+json");-- using var resp = await http.GetAsync(LatestApi, ct).ConfigureAwait(false);- if (!resp.IsSuccessStatusCode) return null;- await using var s = await resp.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);- using var doc = await JsonDocument.ParseAsync(s, cancellationToken: ct).ConfigureAwait(false);-- var root = doc.RootElement;- var tag = root.TryGetProperty("tag_name", out var t) ? t.GetString() : null;- var url = root.TryGetProperty("html_url", out var u) ? u.GetString() : null;- return NewerThanRunning(tag, url);- }- catch- {- return null;- }- }-- /// <summary>Compare a release tag ("v1.2.3" or "1.2.3") against the running version.</summary>- public static AvailableUpdate? NewerThanRunning(string? tag, string? url, string? running = null)- {- var latest = tag?.Trim().TrimStart('v', 'V');- if (!SemVer.TryParse(latest, out var lv)) return null;- if (!SemVer.TryParse(running ?? AppInfo.Version, out var cv)) return null;- if (lv.CompareTo(cv) <= 0) return null;- return new AvailableUpdate(latest!, string.IsNullOrWhiteSpace(url) ? ReleasesPage : url!);- }-}diff --git a/src/managed/Nota.App/WelcomeWindow.cs b/src/managed/Nota.App/WelcomeWindow.csindex c31c0ab4..de435f6e 100644--- a/src/managed/Nota.App/WelcomeWindow.cs+++ b/src/managed/Nota.App/WelcomeWindow.cs@@ -5,12 +5,15 @@// drawn in nota-design/Nota Start.html. Brand header, New / Open actions, a list of// recent projects (click selects, double-click / Return opens, ↑ ↓ move), and shortcuts to// Settings and What's New, plus banners for crash recovery and a newer release on-// GitHub. New / Open / a recent project close the launcher and hand+// GitHub (which downloads and installs it in place — see IAppUpdater). New / Open / a recent project close the launcher and hand// off to the main window; Settings and What's New open as child dialogs so the user// stays on the launcher.using System;using System.Collections.Generic;+using System.Linq;+using System.Threading;+using System.Threading.Tasks;using Avalonia;using Avalonia.Controls;using Avalonia.Layout;@@ -303,18 +306,121 @@ public sealed class WelcomeWindow : NotaWindowprivate readonly StackPanel _banners;- /// <summary>Show a "new version available" banner with a Download button that opens- /// the release page in the browser. Called once the background update check resolves.</summary>- public void ShowUpdateAvailable(AvailableUpdate update)+ /// <summary>Show the "new version available" banner. When this install can update itself+ /// it downloads in place (progress in the banner), then offers Restart now / Later — Later+ /// installs on quit. Otherwise Download opens the release page. Called once the background+ /// update check resolves.</summary>+ public void ShowUpdateAvailable(AppRelease release, IAppUpdater updater, Action restart){- Border banner = null!;- banner = Banner(- "A new version of Nota is available",- $"Nota {update.Version} is out — you have {AppInfo.Version}.",- actionLabel: "Download",- onAction: () => _ = Launcher.LaunchUriAsync(new Uri(update.Url)),- onDismiss: () => _banners.Children.Remove(banner));- _banners.Children.Add(banner);+ new UpdateBanner(release, updater, restart, _banners).Attach();+ }++ // The update banner's states: offer → downloading → ready (or failed → try again).+ private sealed class UpdateBanner+ {+ private readonly AppRelease _release;+ private readonly IAppUpdater _updater;+ private readonly Action _restart;+ private readonly StackPanel _host;+ private readonly Border _card;+ private CancellationTokenSource? _cts;++ public UpdateBanner(AppRelease release, IAppUpdater updater, Action restart, StackPanel host)+ {+ _release = release;+ _updater = updater;+ _restart = restart;+ _host = host;+ _card = BannerCard();+ }++ public void Attach()+ {+ if (_updater.PendingVersion == _release.Version) ShowReady();+ else ShowOffer();+ _host.Children.Add(_card);+ }++ private bool CanUpdate => _release.Asset is not null && _updater.CanInstallInPlace;++ private void ShowOffer()+ {+ var openPage = () => { _ = Launcher(_card)?.LaunchUriAsync(new Uri(_release.PageUrl)); };+ _card.Child = CanUpdate+ ? BannerContent("A new version of Nota is available",+ $"Nota {_release.Version} is out — you have {AppInfo.Version}.",+ progress: null,+ ("Update", true, () => _ = DownloadAsync()),+ ("Release notes", false, openPage),+ ("Dismiss", false, Remove))+ : BannerContent("A new version of Nota is available",+ $"Nota {_release.Version} is out — you have {AppInfo.Version}.",+ progress: null,+ ("Download", true, openPage),+ ("Dismiss", false, Remove));+ }++ private async Task DownloadAsync()+ {+ _cts = new CancellationTokenSource();+ var bar = new ProgressBar+ {+ Minimum = 0, Maximum = 1, Height = 4, Margin = new Thickness(0, 6, 0, 0),+ Foreground = NotaPalette.Accent, Background = NotaPalette.BorderDefault,+ };+ var size = _release.Asset!.Size / 1048576.0;+ var content = BannerContent($"Downloading Nota {_release.Version}…",+ $"0.0 / {NotaNum.Unit(size, "0.0", "MB")}", bar,+ ("Cancel", false, () => _cts?.Cancel()));+ _card.Child = content;+ var message = (TextBlock)((StackPanel)content.Children[0]).Children[1]; // BannerContent's message line++ var progress = new Progress<StoreProgress>(p =>+ {+ if (p.Fraction < 0)+ {+ bar.IsIndeterminate = true;+ message.Text = p.Message;+ return;+ }+ bar.Value = p.Fraction;+ message.Text = $"{(p.Fraction * size).ToString("0.0", NotaNum.Culture)} / {NotaNum.Unit(size, "0.0", "MB")}"+ + $" · {NotaNum.Unit(p.Fraction * 100, "0", "%")}";+ });+ try+ {+ await _updater.DownloadAsync(_release, progress, _cts.Token);+ ShowReady();+ }+ catch (OperationCanceledException) { ShowOffer(); }+ catch (Exception e) { ShowFailed(e is StoreException ? e.Message : $"Couldn't download the update: {e.Message}"); }+ finally { _cts.Dispose(); _cts = null; }+ }++ private void ShowReady()+ {+ _card.Child = BannerContent($"Nota {_release.Version} is ready to install",+ "Restart Nota to finish updating — or it installs the next time you quit.",+ progress: null,+ ("Restart now", true, () => { _updater.RelaunchAfterInstall = true; _restart(); }),+ ("Later", false, Remove));+ }++ private void ShowFailed(string error)+ {+ _card.Child = BannerContent("The update didn't download", error,+ progress: null,+ ("Try again", true, () => _ = DownloadAsync()),+ ("Dismiss", false, Remove));+ }++ private void Remove()+ {+ _cts?.Cancel();+ _host.Children.Remove(_card);+ }++ private static Avalonia.Platform.Storage.ILauncher? Launcher(Visual v) => TopLevel.GetTopLevel(v)?.Launcher;}// Offer to restore a crashed session.@@ -325,6 +431,28 @@ public sealed class WelcomeWindow : NotaWindow// prompt, not an error.private static Border Banner(string title, string message, string actionLabel,Action onAction, Action onDismiss)+ {+ var card = BannerCard();+ card.Child = BannerContent(title, message, progress: null,+ (actionLabel, true, onAction), ("Dismiss", false, onDismiss));+ return card;+ }++ private static Border BannerCard() => new()+ {+ Background = NotaPalette.AccentSubtle,+ BorderBrush = NotaPalette.Accent,+ BorderThickness = new Thickness(1),+ CornerRadius = NotaRadius.Panel,+ Padding = new Thickness(14, 12),+ Margin = new Thickness(28, 16, 28, 0),+ };++ // Title + message (+ an optional progress bar) on the left, buttons on the right. The+ // first "main" button is a plain button (not solid brass: "New project" is this window's+ // primary action); the rest are ghosts.+ private static Grid BannerContent(string title, string message, Control? progress,+ params (string Label, bool Main, Action OnClick)[] actions){var text = new StackPanel { Spacing = 2, VerticalAlignment = VerticalAlignment.Center };text.Children.Add(new TextBlock@@ -341,42 +469,25 @@ public sealed class WelcomeWindow : NotaWindowForeground = NotaPalette.TextSecondary,TextWrapping = TextWrapping.Wrap,});- Grid.SetColumn(text, 0);-- var recover = new Button- {- Content = actionLabel, // not solid brass: "New project" is this window's primary action- VerticalAlignment = VerticalAlignment.Center,- Margin = new Thickness(12, 0, 0, 0),- };- recover.Click += (_, _) => onAction();- Grid.SetColumn(recover, 1);+ if (progress is not null) text.Children.Add(progress);- var dismiss = new Button- {- Content = "Dismiss",- Classes = { "ghost" },- VerticalAlignment = VerticalAlignment.Center,- Margin = new Thickness(6, 0, 0, 0),- };- dismiss.Click += (_, _) => onDismiss();- Grid.SetColumn(dismiss, 2);-- var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto") };+ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*" + string.Concat(Enumerable.Repeat(",Auto", actions.Length))) };grid.Children.Add(text);- grid.Children.Add(recover);- grid.Children.Add(dismiss);-- return new Border+ for (int i = 0; i < actions.Length; i++){- Background = NotaPalette.AccentSubtle,- BorderBrush = NotaPalette.Accent,- BorderThickness = new Thickness(1),- CornerRadius = NotaRadius.Panel,- Padding = new Thickness(14, 12),- Margin = new Thickness(28, 16, 28, 0),- Child = grid,- };+ var (label, main, onClick) = actions[i];+ var button = new Button+ {+ Content = label,+ VerticalAlignment = VerticalAlignment.Center,+ Margin = new Thickness(i == 0 ? 12 : 6, 0, 0, 0),+ };+ if (!main) button.Classes.Add("ghost");+ button.Click += (_, _) => onClick();+ Grid.SetColumn(button, i + 1);+ grid.Children.Add(button);+ }+ return grid;}// One line of the recent list: name left, modified date right in mono. The selecteddiff --git a/src/managed/Nota.Application/Ports/IAppUpdater.cs b/src/managed/Nota.Application/Ports/IAppUpdater.csnew file mode 100644index 00000000..9baa0ff7--- /dev/null+++ b/src/managed/Nota.Application/Ports/IAppUpdater.cs@@ -0,0 +1,43 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++namespace Nota.Application;++/// <summary>A published release newer than the running app. <paramref name="Asset"/> is the build+/// for this OS + architecture, or null when the release ships none.</summary>+public sealed record AppRelease(string Version, string PageUrl, AppReleaseAsset? Asset);++/// <summary>One downloadable release file. <paramref name="Sha256"/> is null when the release+/// host didn't publish a digest — the size is still checked.</summary>+public sealed record AppReleaseAsset(string Name, string Url, long Size, string? Sha256);++/// <summary>Self-update: find a newer release, download and verify its build for this platform,+/// and swap it in when the app quits. The swap runs in a small detached helper that waits for+/// this process to exit, replaces the installed app (the .app bundle on macOS, the AppImage on+/// Linux; the Inno Setup installer runs silently on Windows) and optionally relaunches it.</summary>+public interface IAppUpdater+{+ /// <summary>The latest published release if it's newer than the running version, else null.+ /// Best-effort: network / parse failures return null.</summary>+ Task<AppRelease?> CheckAsync(CancellationToken ct = default);++ /// <summary>True when this install can be replaced in place (a packaged app in a writable+ /// location). Otherwise the user downloads the release by hand.</summary>+ bool CanInstallInPlace { get; }++ /// <summary>Downloads <paramref name="release"/>'s asset, verifies it and prepares it for+ /// install; afterwards <see cref="PendingVersion"/> is set and the update is applied on exit.+ /// Throws <see cref="StoreException"/> with a user-facing message on failure.</summary>+ Task DownloadAsync(AppRelease release, IProgress<StoreProgress>? progress = null, CancellationToken ct = default);++ /// <summary>The version a downloaded update will install on exit, or null.</summary>+ string? PendingVersion { get; }++ /// <summary>Start the new version once the update is installed (Restart now), rather than+ /// just installing it on quit.</summary>+ bool RelaunchAfterInstall { get; set; }++ /// <summary>Hands a pending update to the install helper. Called once, as the app exits;+ /// a no-op when nothing is pending.</summary>+ void RunPendingInstall();+}diff --git a/src/managed/Nota.Infrastructure/Update/AppUpdater.cs b/src/managed/Nota.Infrastructure/Update/AppUpdater.csnew file mode 100644index 00000000..264add21--- /dev/null+++ b/src/managed/Nota.Infrastructure/Update/AppUpdater.cs@@ -0,0 +1,435 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Self-update from GitHub releases. The check asks the API for the latest published release+// (drafts and pre-releases are excluded by that endpoint) and picks the asset the release+// workflow builds for this OS + arch. The download is verified against the asset's size and+// the sha256 digest GitHub reports for it, then prepared under <data>/updates:+// macOS — the .dmg is mounted and its Nota.app copied out (ditto), version-checked;+// Windows — the Inno Setup installer is kept as is;+// Linux — the AppImage is kept as is.+// Nothing touches the installed app while Nota runs. On exit, RunPendingInstall writes a tiny+// helper script and starts it detached: it waits for this process to end, swaps the new+// build in (or runs the installer silently) and relaunches when asked.+//+// NOTA_UPDATE_API overrides the release endpoint (a URL or a local JSON file, for testing);+// asset URLs may be local paths as well.++using System.Diagnostics;+using System.Runtime.InteropServices;+using System.Security.Cryptography;+using System.Text.Json;+using System.Text.RegularExpressions;+using Nota.Application;++namespace Nota.Infrastructure;++public sealed partial class AppUpdater : IAppUpdater+{+ public const string ReleasesPage = "https://github.com/nota-daw/nota/releases";+ private const string LatestApi = "https://api.github.com/repos/nota-daw/nota/releases/latest";++ /// <summary>How the prepared build gets installed.</summary>+ public enum InstallKind { MacBundle, WindowsInstaller, AppImage }++ private sealed record Pending(InstallKind Kind, string Staged, string Target, string Version);++ private readonly string _running;+ private readonly string _api;+ private readonly string _updatesDir;+ private readonly HttpClient _http;+ private readonly OSPlatform _os;+ private readonly Architecture _arch;+ private readonly string? _target;+ private Pending? _pending;++ public AppUpdater(string runningVersion) : this(runningVersion,+ Environment.GetEnvironmentVariable("NOTA_UPDATE_API") is { Length: > 0 } api ? api : LatestApi,+ NotaPaths.SubDir("updates"), CurrentOs(), RuntimeInformation.OSArchitecture,+ Environment.ProcessPath, Environment.GetEnvironmentVariable("APPIMAGE"))+ { }++ /// <summary>Test seam: every platform input explicit.</summary>+ public AppUpdater(string runningVersion, string api, string updatesDir, OSPlatform os, Architecture arch,+ string? processPath, string? appImage, HttpMessageHandler? handler = null)+ {+ _running = runningVersion;+ _api = api;+ _updatesDir = updatesDir;+ _os = os;+ _arch = arch;+ _target = InstallTarget(os, processPath, appImage);+ _http = handler is null ? new HttpClient() : new HttpClient(handler);+ _http.Timeout = Timeout.InfiniteTimeSpan; // big download; each request has its own token+ // GitHub's API rejects requests without a User-Agent.+ _http.DefaultRequestHeaders.UserAgent.ParseAdd($"Nota/{runningVersion}");+ }++ /// <summary>The installed app this process would replace, or null when it can't.</summary>+ public string? Target => _target;++ public bool CanInstallInPlace => _target is not null && (_os == OSPlatform.Windows || IsWritable(Path.GetDirectoryName(_target)!));++ public string? PendingVersion => _pending?.Version;++ public bool RelaunchAfterInstall { get; set; }++ // ---- check ------------------------------------------------------------------------------++ public async Task<AppRelease?> CheckAsync(CancellationToken ct = default)+ {+ if (_pending is null) CleanUpdatesDir();+ try+ {+ string json;+ if (RegistryClient.IsLocal(_api, out var local))+ json = await File.ReadAllTextAsync(local, ct).ConfigureAwait(false);+ else+ {+ using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);+ cts.CancelAfter(TimeSpan.FromSeconds(8));+ using var req = new HttpRequestMessage(HttpMethod.Get, _api);+ req.Headers.Accept.ParseAdd("application/vnd.github+json");+ using var resp = await _http.SendAsync(req, cts.Token).ConfigureAwait(false);+ if (!resp.IsSuccessStatusCode) return null;+ json = await resp.Content.ReadAsStringAsync(cts.Token).ConfigureAwait(false);+ }+ return ParseRelease(json, _running, _os, _arch);+ }+ catch+ {+ return null;+ }+ }++ /// <summary>A GitHub "release" JSON → the release if it's newer than <paramref name="running"/>,+ /// with the asset for <paramref name="os"/> + <paramref name="arch"/> (if it ships one).</summary>+ public static AppRelease? ParseRelease(string json, string running, OSPlatform os, Architecture arch)+ {+ using var doc = JsonDocument.Parse(json);+ var root = doc.RootElement;+ var tag = root.TryGetProperty("tag_name", out var t) ? t.GetString() : null;+ var latest = tag?.Trim().TrimStart('v', 'V');+ if (!IsNewer(latest, running)) return null;+ var page = root.TryGetProperty("html_url", out var u) && u.GetString() is { Length: > 0 } url ? url : ReleasesPage;++ var assets = new List<AppReleaseAsset>();+ if (root.TryGetProperty("assets", out var arr) && arr.ValueKind == JsonValueKind.Array)+ foreach (var a in arr.EnumerateArray())+ {+ var name = a.TryGetProperty("name", out var n) ? n.GetString() : null;+ var dl = a.TryGetProperty("browser_download_url", out var d) ? d.GetString() : null;+ var size = a.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0;+ string? sha = null;+ if (a.TryGetProperty("digest", out var dg) && dg.GetString() is { } digest+ && digest.StartsWith("sha256:", StringComparison.OrdinalIgnoreCase))+ sha = digest[7..].ToLowerInvariant();+ if (name is { Length: > 0 } && dl is { Length: > 0 } && size > 0)+ assets.Add(new AppReleaseAsset(name, dl, size, sha));+ }+ return new AppRelease(latest!, page, PickAsset(assets, os, arch));+ }++ /// <summary>True when <paramref name="latest"/> is a higher MAJOR.MINOR.PATCH than <paramref name="running"/>.</summary>+ public static bool IsNewer(string? latest, string? running)+ => TryParseVersion(latest, out var l) && TryParseVersion(running, out var r) && l > r;++ private static bool TryParseVersion(string? s, out Version v)+ {+ v = new Version();+ if (string.IsNullOrWhiteSpace(s)) return false;+ var core = s.Trim().TrimStart('v', 'V').Split('-', '+')[0];+ var parts = core.Split('.');+ if (parts.Length != 3) return false;+ if (!int.TryParse(parts[0], out var a) || !int.TryParse(parts[1], out var b) || !int.TryParse(parts[2], out var c)) return false;+ v = new Version(a, b, c);+ return true;+ }++ /// <summary>The asset the release workflow names for this platform (see release.yml):+ /// Nota-X-arm64.dmg / Nota-X-x86_64.dmg, Nota-Setup-X-x64.exe / -arm64.exe,+ /// Nota-X-x86_64.AppImage / Nota-X-aarch64.AppImage.</summary>+ public static AppReleaseAsset? PickAsset(IEnumerable<AppReleaseAsset> assets, OSPlatform os, Architecture arch)+ {+ bool arm = arch == Architecture.Arm64;+ Func<string, bool>? match = null;+ if (os == OSPlatform.OSX)+ match = n => n.EndsWith(arm ? "-arm64.dmg" : "-x86_64.dmg", StringComparison.OrdinalIgnoreCase);+ else if (os == OSPlatform.Windows)+ match = n => n.StartsWith("Nota-Setup-", StringComparison.OrdinalIgnoreCase)+ && n.EndsWith(arm ? "-arm64.exe" : "-x64.exe", StringComparison.OrdinalIgnoreCase);+ else if (os == OSPlatform.Linux)+ match = n => n.EndsWith(arm ? "-aarch64.AppImage" : "-x86_64.AppImage", StringComparison.OrdinalIgnoreCase);+ return match is null ? null : assets.FirstOrDefault(a => match(a.Name));+ }++ /// <summary>What an in-place update replaces: the .app bundle the process runs from (not a+ /// translocated or disk-image copy), the folder of an Inno Setup install, or the AppImage.+ /// Null for dev builds and anything else.</summary>+ public static string? InstallTarget(OSPlatform os, string? processPath, string? appImage)+ {+ if (os == OSPlatform.Linux)+ return appImage is { Length: > 0 } && File.Exists(appImage) ? appImage : null;+ if (string.IsNullOrEmpty(processPath)) return null;+ if (os == OSPlatform.OSX)+ {+ const string marker = ".app/Contents/MacOS/";+ int i = processPath.IndexOf(marker, StringComparison.Ordinal);+ if (i < 0) return null;+ var bundle = processPath[..(i + 4)];+ if (bundle.Contains("/AppTranslocation/", StringComparison.Ordinal)+ || bundle.StartsWith("/Volumes/", StringComparison.Ordinal)) return null;+ return Directory.Exists(bundle) ? bundle : null;+ }+ if (os == OSPlatform.Windows)+ {+ var dir = Path.GetDirectoryName(processPath);+ return dir is not null && File.Exists(Path.Combine(dir, "unins000.exe")) ? dir : null;+ }+ return null;+ }++ // ---- download + prepare -----------------------------------------------------------------++ public async Task DownloadAsync(AppRelease release, IProgress<StoreProgress>? progress = null, CancellationToken ct = default)+ {+ var asset = release.Asset ?? throw new StoreException($"Nota {release.Version} has no download for this computer.");+ if (!CanInstallInPlace) throw new StoreException("This copy of Nota can't update itself — download the new version from the release page.");+ _pending = null;+ CleanUpdatesDir();+ Directory.CreateDirectory(_updatesDir);++ var file = Path.Combine(_updatesDir, Path.GetFileName(asset.Name));+ await DownloadVerifiedAsync(asset, file, $"Downloading Nota {release.Version}…", progress, ct).ConfigureAwait(false);++ switch (_os == OSPlatform.OSX ? InstallKind.MacBundle : _os == OSPlatform.Windows ? InstallKind.WindowsInstaller : InstallKind.AppImage)+ {+ case InstallKind.MacBundle:+ progress?.Report(new StoreProgress(-1, "Preparing the update…"));+ var staged = Path.Combine(_updatesDir, $"Nota-{release.Version}.app");+ await Task.Run(() => StageMacBundle(file, staged, release.Version), ct).ConfigureAwait(false);+ TryDelete(file);+ _pending = new Pending(InstallKind.MacBundle, staged, _target!, release.Version);+ break;+ case InstallKind.WindowsInstaller:+ _pending = new Pending(InstallKind.WindowsInstaller, file, _target!, release.Version);+ break;+ default:+ _pending = new Pending(InstallKind.AppImage, file, _target!, release.Version);+ break;+ }+ }++ private async Task DownloadVerifiedAsync(AppReleaseAsset asset, string file, string label,+ IProgress<StoreProgress>? progress, CancellationToken ct)+ {+ progress?.Report(new StoreProgress(0, label));+ using var sha = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);+ long total = 0;+ try+ {+ Stream src;+ HttpResponseMessage? resp = null;+ if (RegistryClient.IsLocal(asset.Url, out var localPath)) src = File.OpenRead(localPath);+ else+ {+ resp = await _http.GetAsync(asset.Url, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);+ resp.EnsureSuccessStatusCode();+ src = await resp.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);+ }+ using (resp)+ await using (src)+ await using (var dst = File.Create(file))+ {+ var buf = new byte[1 << 16];+ int n;+ while ((n = await src.ReadAsync(buf, ct).ConfigureAwait(false)) > 0)+ {+ total += n;+ if (total > asset.Size) throw new StoreException("The update download is larger than expected — not installing it.");+ sha.AppendData(buf, 0, n);+ await dst.WriteAsync(buf.AsMemory(0, n), ct).ConfigureAwait(false);+ progress?.Report(new StoreProgress((double)total / asset.Size, label));+ }+ }+ }+ catch (HttpRequestException e)+ {+ TryDelete(file);+ throw new StoreException($"Couldn't download the update: {e.Message}", e);+ }+ catch+ {+ TryDelete(file);+ throw;+ }++ var digest = Convert.ToHexStringLower(sha.GetHashAndReset());+ if (total != asset.Size || asset.Sha256 is not null && digest != asset.Sha256)+ {+ TryDelete(file);+ throw new StoreException("The update download is damaged (checksum mismatch) — not installing it.");+ }+ }++ // Mount the disk image, copy its .app out and check it's the version we asked for.+ private void StageMacBundle(string dmg, string staged, string version)+ {+ // A fresh mount point each time, so a mount left behind by a crash can't get in the way.+ var mount = Directory.CreateTempSubdirectory("nota-update-").FullName;+ RunTool("hdiutil", "attach", "-nobrowse", "-readonly", "-noautoopen", "-mountpoint", mount, dmg);+ try+ {+ var app = Directory.EnumerateDirectories(mount, "*.app").FirstOrDefault()+ ?? throw new StoreException("The update disk image doesn't contain Nota.app.");+ RunTool("ditto", app, staged);+ }+ finally+ {+ try { RunTool("hdiutil", "detach", mount, "-force"); Directory.Delete(mount); } catch { /* best-effort */ }+ }+ var plist = Path.Combine(staged, "Contents", "Info.plist");+ var m = File.Exists(plist) ? BundleVersion().Match(File.ReadAllText(plist)) : Match.Empty;+ if (!m.Success || m.Groups[1].Value.Trim() != version)+ throw new StoreException("The downloaded Nota.app isn't the expected version — not installing it.");+ }++ [GeneratedRegex(@"<key>CFBundleShortVersionString</key>\s*<string>([^<]*)</string>")]+ private static partial Regex BundleVersion();++ private static void RunTool(string exe, params string[] args)+ {+ var psi = new ProcessStartInfo(exe) { UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true };+ foreach (var a in args) psi.ArgumentList.Add(a);+ using var p = Process.Start(psi) ?? throw new StoreException($"Couldn't start {exe}.");+ var err = p.StandardError.ReadToEndAsync();+ _ = p.StandardOutput.ReadToEndAsync();+ if (!p.WaitForExit(TimeSpan.FromMinutes(2))) { try { p.Kill(); } catch { } throw new StoreException($"{exe} timed out."); }+ if (p.ExitCode != 0) throw new StoreException($"Couldn't prepare the update ({exe}: {err.Result.Trim()}).");+ }++ // ---- install on exit --------------------------------------------------------------------++ public void RunPendingInstall()+ {+ if (_pending is not { } p) return;+ _pending = null;+ try+ {+ var pid = Environment.ProcessId.ToString();+ var relaunch = RelaunchAfterInstall ? "1" : "0";+ ProcessStartInfo psi;+ if (p.Kind == InstallKind.WindowsInstaller)+ {+ var script = Path.Combine(_updatesDir, "install.ps1");+ File.WriteAllText(script, WindowsScript);+ psi = new ProcessStartInfo("powershell.exe") { UseShellExecute = false, CreateNoWindow = true };+ foreach (var a in new[] { "-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-File", script, pid, p.Staged, relaunch })+ psi.ArgumentList.Add(a);+ }+ else+ {+ var script = Path.Combine(_updatesDir, "install.sh");+ File.WriteAllText(script, p.Kind == InstallKind.MacBundle ? MacScript : LinuxScript);+ psi = new ProcessStartInfo("/bin/sh") { UseShellExecute = false };+ foreach (var a in new[] { script, pid, p.Staged, p.Target, relaunch })+ psi.ArgumentList.Add(a);+ }+ Process.Start(psi)?.Dispose();+ }+ catch { /* the app is quitting either way; the next launch offers the update again */ }+ }++ // Shared prologue: wait (up to two minutes) for the app to exit; give up if it never does.+ private const string WaitForExit = """+ pid="$1"; staged="$2"; target="$3"; relaunch="$4"+ n=0+ while kill -0 "$pid" 2>/dev/null; do+ n=$((n+1)); [ "$n" -gt 600 ] && exit 1+ sleep 0.2+ done++ """;++ // Move the old bundle aside, move the new one in, roll back if that fails.+ public const string MacScript = "#!/bin/sh\n" + WaitForExit + """+ old="$target.updating-old"+ rm -rf "$old"+ if mv "$target" "$old"; then+ if mv "$staged" "$target"; then+ rm -rf "$old"+ else+ mv "$old" "$target"+ exit 1+ fi+ else+ exit 1+ fi+ xattr -dr com.apple.quarantine "$target" 2>/dev/null+ [ "$relaunch" = 1 ] && open "$target"+ exit 0++ """;++ // Copy next to the AppImage (same filesystem), then rename over it atomically.+ public const string LinuxScript = "#!/bin/sh\n" + WaitForExit + """+ tmp="$target.updating"+ if cp "$staged" "$tmp" && chmod 755 "$tmp" && mv -f "$tmp" "$target"; then+ rm -f "$staged"+ else+ rm -f "$tmp"+ exit 1+ fi+ [ "$relaunch" = 1 ] && nohup "$target" >/dev/null 2>&1 &+ exit 0++ """;++ // Run the installer silently (it asks for elevation itself); /relaunch=1 makes it start+ // Nota again as the original user (see scripts/nota.iss).+ public const string WindowsScript = """+ $p = [int]$args[0]; $installer = $args[1]; $relaunch = $args[2]+ try { Wait-Process -Id $p -Timeout 120 -ErrorAction SilentlyContinue } catch {}+ if (Get-Process -Id $p -ErrorAction SilentlyContinue) { exit 1 }+ $a = @('/SILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/SP-')+ if ($relaunch -eq '1') { $a += '/relaunch=1' }+ Start-Process -FilePath $installer -ArgumentList $a -Wait+ Remove-Item -LiteralPath $installer -ErrorAction SilentlyContinue++ """;++ // ---- helpers ----------------------------------------------------------------------------++ private static OSPlatform CurrentOs()+ => OperatingSystem.IsMacOS() ? OSPlatform.OSX : OperatingSystem.IsWindows() ? OSPlatform.Windows : OSPlatform.Linux;++ private static bool IsWritable(string dir)+ {+ try+ {+ var probe = Path.Combine(dir, $".nota-write-test-{Guid.NewGuid():N}");+ File.WriteAllText(probe, "");+ File.Delete(probe);+ return true;+ }+ catch { return false; }+ }++ // Leftovers from an earlier update (an installed .app copy, an interrupted download).+ private void CleanUpdatesDir()+ {+ try+ {+ if (!Directory.Exists(_updatesDir)) return;+ foreach (var d in Directory.EnumerateDirectories(_updatesDir))+ try { Directory.Delete(d, recursive: true); } catch { }+ foreach (var f in Directory.EnumerateFiles(_updatesDir)) TryDelete(f);+ }+ catch { /* best-effort */ }+ }++ private static void TryDelete(string file)+ {+ try { File.Delete(file); } catch { }+ }+}diff --git a/tests/Nota.SmokeTest/AppUpdaterTests.cs b/tests/Nota.SmokeTest/AppUpdaterTests.csnew file mode 100644index 00000000..6843efc6--- /dev/null+++ b/tests/Nota.SmokeTest/AppUpdaterTests.cs@@ -0,0 +1,254 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Self-update (IAppUpdater): version compare, picking this platform's asset from a GitHub+// release, what counts as an updatable install, download + checksum against a local release+// JSON, and the install helpers themselves — the Linux AppImage swap and the macOS bundle swap+// run for real on fake installs (plus, on macOS, staging Nota.app out of a real .dmg).+// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --updater`.++using System.Diagnostics;+using System.Runtime.InteropServices;+using System.Security.Cryptography;+using System.Text.Json;+using Nota.Application;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class AppUpdaterTests+{+ private static readonly string[] AssetNames =+ [+ "Nota-1.3.0-arm64.dmg", "Nota-1.3.0-x86_64.dmg",+ "Nota-Setup-1.3.0-x64.exe", "Nota-Setup-1.3.0-arm64.exe",+ "Nota-1.3.0-x86_64.AppImage", "Nota-1.3.0-aarch64.AppImage",+ ];++ public static IEnumerable<(bool Ok, string Label)> Run()+ {+ // ---- versions -------------------------------------------------------------------+ yield return (AppUpdater.IsNewer("v1.3.0", "1.2.9") && AppUpdater.IsNewer("1.10.0", "1.9.9"),+ "a higher tag (with or without the v) is newer; components compare numerically");+ yield return (!AppUpdater.IsNewer("1.2.0", "1.2.0") && !AppUpdater.IsNewer("1.1.9", "1.2.0"),+ "the same or an older release is not an update");+ yield return (!AppUpdater.IsNewer("nightly", "1.2.0") && !AppUpdater.IsNewer("1.3", "1.2.0"),+ "unparsable tags are ignored");++ // ---- assets ---------------------------------------------------------------------+ var assets = AssetNames.Select(n => new AppReleaseAsset(n, "https://x/" + n, 1, null)).ToList();+ string? Pick(OSPlatform os, Architecture a) => AppUpdater.PickAsset(assets, os, a)?.Name;+ yield return (Pick(OSPlatform.OSX, Architecture.Arm64) == "Nota-1.3.0-arm64.dmg"+ && Pick(OSPlatform.OSX, Architecture.X64) == "Nota-1.3.0-x86_64.dmg",+ "macOS takes the .dmg for its architecture");+ yield return (Pick(OSPlatform.Windows, Architecture.X64) == "Nota-Setup-1.3.0-x64.exe"+ && Pick(OSPlatform.Windows, Architecture.Arm64) == "Nota-Setup-1.3.0-arm64.exe",+ "Windows takes the installer for its architecture");+ yield return (Pick(OSPlatform.Linux, Architecture.X64) == "Nota-1.3.0-x86_64.AppImage"+ && Pick(OSPlatform.Linux, Architecture.Arm64) == "Nota-1.3.0-aarch64.AppImage",+ "Linux takes the AppImage for its architecture");++ var json = ReleaseJson("v1.3.0", [("Nota-1.3.0-arm64.dmg", "https://x/a.dmg", 42, "sha256:ABCDEF")]);+ var rel = AppUpdater.ParseRelease(json, "1.2.0", OSPlatform.OSX, Architecture.Arm64);+ yield return (rel is { Version: "1.3.0", PageUrl: "https://github.com/nota-daw/nota/releases/tag/v1.3.0",+ Asset: { Size: 42, Sha256: "abcdef", Url: "https://x/a.dmg" } },+ "a release parses to its version, page, and this platform's asset with its digest");+ yield return (AppUpdater.ParseRelease(json, "1.3.0", OSPlatform.OSX, Architecture.Arm64) is null,+ "…and is no update for a client already on it");+ yield return (AppUpdater.ParseRelease(json, "1.2.0", OSPlatform.Linux, Architecture.X64) is { Asset: null },+ "a release without this platform's build still reports the version (manual download)");++ var tmp = Directory.CreateTempSubdirectory("nota-updater-test-").FullName;+ try+ {+ foreach (var r in Targets(tmp)) yield return r;+ foreach (var r in LinuxFlow(tmp)) yield return r;+ if (!OperatingSystem.IsWindows())+ foreach (var r in MacSwap(tmp)) yield return r;+ if (OperatingSystem.IsMacOS())+ foreach (var r in MacFlow(tmp)) yield return r;+ }+ finally+ {+ try { Directory.Delete(tmp, recursive: true); } catch { }+ }+ }++ // ---- what is updatable ---------------------------------------------------------------+ private static IEnumerable<(bool, string)> Targets(string tmp)+ {+ var bundle = Path.Combine(tmp, "Apps", "Nota.app");+ Directory.CreateDirectory(Path.Combine(bundle, "Contents", "MacOS"));+ var exe = Path.Combine(bundle, "Contents", "MacOS", "Nota.App");+ yield return (AppUpdater.InstallTarget(OSPlatform.OSX, exe, null) == bundle,+ "macOS: the .app bundle the process runs from is the target");+ yield return (AppUpdater.InstallTarget(OSPlatform.OSX, "/private/var/folders/x/AppTranslocation/ABC/d/Nota.app/Contents/MacOS/Nota.App", null) is null+ && AppUpdater.InstallTarget(OSPlatform.OSX, "/Volumes/Nota/Nota.app/Contents/MacOS/Nota.App", null) is null,+ "…but not a translocated copy or one running off the disk image");+ yield return (AppUpdater.InstallTarget(OSPlatform.OSX, Path.Combine(tmp, "bin", "Nota.App"), null) is null,+ "…nor a dev build outside a bundle");++ var win = Path.Combine(tmp, "Program Files", "Nota");+ Directory.CreateDirectory(win);+ var winExe = Path.Combine(win, "Nota.App.exe");+ yield return (AppUpdater.InstallTarget(OSPlatform.Windows, winExe, null) is null,+ "Windows: a folder without the Inno uninstaller isn't an installed copy");+ File.WriteAllText(Path.Combine(win, "unins000.exe"), "");+ yield return (AppUpdater.InstallTarget(OSPlatform.Windows, winExe, null) == win,+ "…with it, the install folder is the target");++ var appImage = Path.Combine(tmp, "Nota.AppImage");+ File.WriteAllText(appImage, "");+ yield return (AppUpdater.InstallTarget(OSPlatform.Linux, "/tmp/.mount_x/usr/bin/Nota.App", appImage) == appImage+ && AppUpdater.InstallTarget(OSPlatform.Linux, "/usr/bin/Nota.App", null) is null,+ "Linux: only an AppImage ($APPIMAGE) updates itself");+ }++ // ---- download + verify, then the AppImage swap ------------------------------------------+ private static IEnumerable<(bool, string)> LinuxFlow(string tmp)+ {+ var dir = Path.Combine(tmp, "linux");+ Directory.CreateDirectory(dir);+ var installed = Path.Combine(dir, "Nota.AppImage");+ File.WriteAllText(installed, "old build");+ var newBuild = Path.Combine(dir, "Nota-1.3.0-x86_64.AppImage");+ File.WriteAllText(newBuild, "new build 1.3.0");+ var bytes = File.ReadAllBytes(newBuild);+ var sha = Convert.ToHexStringLower(SHA256.HashData(bytes));++ var api = Path.Combine(dir, "latest.json");+ File.WriteAllText(api, ReleaseJson("v1.3.0", [(Path.GetFileName(newBuild), newBuild, bytes.Length, "sha256:" + sha)]));+ var updates = Path.Combine(dir, "updates");+ var updater = new AppUpdater("1.2.0", api, updates, OSPlatform.Linux, Architecture.X64, "/tmp/.mount/usr/bin/Nota.App", installed);++ yield return (updater.CanInstallInPlace, "an AppImage in a writable folder can update in place");+ var release = updater.CheckAsync().GetAwaiter().GetResult();+ yield return (release is { Version: "1.3.0", Asset: not null }, "the check finds 1.3.0 and its AppImage");+ if (release is null) yield break;++ var fractions = new List<double>();+ updater.DownloadAsync(release, new SyncProgress(p => fractions.Add(p.Fraction))).GetAwaiter().GetResult();+ yield return (updater.PendingVersion == "1.3.0" && fractions.Count > 0 && fractions[^1] == 1.0,+ "the download reports progress to 100% and leaves 1.3.0 pending");+ yield return (File.ReadAllText(installed) == "old build", "…without touching the running install");++ var bad = release with { Asset = release.Asset! with { Sha256 = new string('0', 64) } };+ var err = Throws(() => updater.DownloadAsync(bad));+ yield return (err is StoreException && updater.PendingVersion is null+ && !Directory.EnumerateFiles(updates, "*.AppImage").Any(),+ "a checksum mismatch is refused, deleted, and nothing stays pending");+ var tooBig = release with { Asset = release.Asset! with { Size = bytes.Length - 1, Sha256 = null } };+ yield return (Throws(() => updater.DownloadAsync(tooBig)) is StoreException,+ "…as is a download larger than the release says");++ if (OperatingSystem.IsWindows()) yield break;+ updater.DownloadAsync(release).GetAwaiter().GetResult();+ var staged = Directory.EnumerateFiles(updates, "*.AppImage").Single();+ var code = RunScript(AppUpdater.LinuxScript, updates, staged, installed);+ yield return (code == 0 && File.ReadAllText(installed) == "new build 1.3.0" && !File.Exists(staged),+ "the install helper swaps the new AppImage in once the app has exited");+ yield return ((File.GetUnixFileMode(installed) & UnixFileMode.UserExecute) != 0,+ "…and leaves it executable");+ }++ // ---- the macOS bundle swap (plain shell, runs on any Unix) ------------------------------+ private static IEnumerable<(bool, string)> MacSwap(string tmp)+ {+ var dir = Path.Combine(tmp, "macswap");+ var target = Path.Combine(dir, "Applications", "Nota.app");+ var staged = Path.Combine(dir, "updates", "Nota-1.3.0.app");+ Directory.CreateDirectory(target);+ Directory.CreateDirectory(staged);+ File.WriteAllText(Path.Combine(target, "version"), "old");+ File.WriteAllText(Path.Combine(staged, "version"), "new");+ var code = RunScript(AppUpdater.MacScript, Path.GetDirectoryName(staged)!, staged, target);+ yield return (code == 0 && File.ReadAllText(Path.Combine(target, "version")) == "new"+ && !Directory.Exists(staged) && !Directory.Exists(target + ".updating-old"),+ "the macOS helper replaces the bundle and removes the old copy");++ var missing = Path.Combine(dir, "updates", "gone.app");+ code = RunScript(AppUpdater.MacScript, Path.GetDirectoryName(staged)!, missing, target);+ yield return (code != 0 && File.ReadAllText(Path.Combine(target, "version")) == "new",+ "…and rolls back, keeping the installed app, when the new bundle can't be moved in");+ }++ // ---- macOS: stage Nota.app out of a real disk image ---------------------------------------+ private static IEnumerable<(bool, string)> MacFlow(string tmp)+ {+ var dir = Path.Combine(tmp, "mac");+ var installed = Path.Combine(dir, "Applications", "Nota.app");+ Directory.CreateDirectory(Path.Combine(installed, "Contents", "MacOS"));+ var src = Path.Combine(dir, "dmgsrc");+ Directory.CreateDirectory(Path.Combine(src, "Nota.app", "Contents", "MacOS"));+ File.WriteAllText(Path.Combine(src, "Nota.app", "Contents", "Info.plist"), """+ <?xml version="1.0" encoding="UTF-8"?>+ <plist version="1.0"><dict>+ <key>CFBundleShortVersionString</key> <string>1.3.0</string>+ </dict></plist>+ """);+ File.WriteAllText(Path.Combine(src, "Nota.app", "Contents", "MacOS", "Nota.App"), "new binary");+ var dmg = Path.Combine(dir, "Nota-1.3.0-arm64.dmg");+ var made = Process.Start(new ProcessStartInfo("hdiutil", ["create", "-quiet", "-volname", "Nota", "-srcfolder", src, "-format", "UDZO", dmg])+ { RedirectStandardOutput = true, RedirectStandardError = true })!;+ made.WaitForExit();+ yield return (made.ExitCode == 0 && File.Exists(dmg), "(setup) built a test disk image");+ if (made.ExitCode != 0) yield break;++ var bytes = File.ReadAllBytes(dmg);+ var api = Path.Combine(dir, "latest.json");+ File.WriteAllText(api, ReleaseJson("v1.3.0", [+ ("Nota-1.3.0-arm64.dmg", dmg, bytes.Length, "sha256:" + Convert.ToHexStringLower(SHA256.HashData(bytes))),+ ("Nota-1.3.0-x86_64.dmg", dmg, bytes.Length, null)]));+ var updates = Path.Combine(dir, "updates");+ var updater = new AppUpdater("1.2.0", api, updates, OSPlatform.OSX, Architecture.Arm64, Path.Combine(installed, "Contents", "MacOS", "Nota.App"), null);+ var release = updater.CheckAsync().GetAwaiter().GetResult();+ yield return (updater.CanInstallInPlace && release is { Asset: not null }, "macOS: a bundle in a writable folder can update in place");+ if (release is null) yield break;++ updater.DownloadAsync(release).GetAwaiter().GetResult();+ var staged = Path.Combine(updates, "Nota-1.3.0.app");+ yield return (updater.PendingVersion == "1.3.0"+ && File.ReadAllText(Path.Combine(staged, "Contents", "MacOS", "Nota.App")) == "new binary"+ && !Directory.EnumerateFiles(updates, "*.dmg").Any(),+ "the .dmg is mounted, its Nota.app copied out and the image deleted");++ var wrong = new AppUpdater("1.2.0", api, updates, OSPlatform.OSX, Architecture.Arm64, Path.Combine(installed, "Contents", "MacOS", "Nota.App"), null);+ yield return (Throws(() => wrong.DownloadAsync(release with { Version = "1.4.0" })) is StoreException,+ "a bundle whose version isn't the release's is refused");+ }++ // ---- helpers ---------------------------------------------------------------------------++ private static string ReleaseJson(string tag, IEnumerable<(string Name, string Url, long Size, string? Digest)> assets)+ => JsonSerializer.Serialize(new+ {+ tag_name = tag,+ html_url = "https://github.com/nota-daw/nota/releases/tag/" + tag,+ assets = assets.Select(a => new { name = a.Name, browser_download_url = a.Url, size = a.Size, digest = a.Digest }),+ });++ // Run an install helper against an already-dead pid, as if the app had just quit.+ private static int RunScript(string script, string dir, string staged, string target)+ {+ Directory.CreateDirectory(dir);+ var path = Path.Combine(dir, "test-install.sh");+ File.WriteAllText(path, script);+ using var gone = Process.Start(new ProcessStartInfo("/bin/sh", ["-c", "exit 0"]))!;+ gone.WaitForExit();+ using var p = Process.Start(new ProcessStartInfo("/bin/sh", [path, gone.Id.ToString(), staged, target, "0"])+ { RedirectStandardError = true })!;+ p.WaitForExit(30_000);+ return p.ExitCode;+ }++ private static Exception? Throws(Func<Task> f)+ {+ try { f().GetAwaiter().GetResult(); return null; }+ catch (Exception e) { return e; }+ }++ private sealed class SyncProgress(Action<StoreProgress> on) : IProgress<StoreProgress>+ {+ public void Report(StoreProgress value) => on(value);+ }+}diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 25f884fb..28a10428 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -125,6 +125,14 @@ if (args.Length >= 1 && args[0] == "--smart-samples")Console.WriteLine(failures == 0 ? "SMART SAMPLES PASSED" : $"SMART SAMPLES FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Self-update alone: `--updater`.+if (args.Length >= 1 && args[0] == "--updater")+{+ Console.WriteLine("-- self-update --");+ foreach (var (ok, label) in AppUpdaterTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "UPDATER PASSED" : $"UPDATER FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// AI models store alone: `--models`.if (args.Length >= 1 && args[0] == "--models"){@@ -13668,5 +13676,9 @@ foreach (var (ok, label) in SmartSampleTests.Run()) Check(ok, label);Console.WriteLine("-- ai models: store --");foreach (var (ok, label) in ModelStoreTests.Run()) Check(ok, label);+// --- self-update: release parsing, download + verify, install helpers ---+Console.WriteLine("-- self-update --");+foreach (var (ok, label) in AppUpdaterTests.Run()) Check(ok, label);+Console.WriteLine(failures == 0 ? "SMOKE TEST PASSED" : $"SMOKE TEST FAILED ({failures})");return failures == 0 ? 0 : 1;