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) Sample packs in Downloads: registry store, shared Plug-ins | Sample Packs page with sticky toolbar
Egor Khindikaynen9104d951efce
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 527eefd7..eab27208 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,6 +31,14 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.that erases the open project's history, and other projects' on their next save. Over MCP,an AI can list versions, save one with a note before an experiment, switch back, and name,note or star versions.+- **Sample packs:** **Settings → Downloads** now has a **Sample Packs** side next to+ Plug-ins. It installs free sample packs — drum kits, a TR-808, sampled basses, guitars,+ pianos, horns and more — into a **Downloaded** folder in your Samples folder, so they show+ up in the browser's Files tab. Every pack is licensed for any music, commercial releases+ included; each downloads from its author's own page and is checked against the registry's+ checksum before it's unpacked. Only the samples and their docs are installed, and Nota+ checks there is room for a pack before downloading it. On both sides the filters and+ search stay at the top while the list scrolls.### Changed- **Faster saves of projects with audio:** a save now writes only new recordings and@@ -38,6 +46,10 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.stored once. Background autosave no longer rewrites the project's audio either. Olderprojects are converted on their next save.+### Fixed+- **Big sample libraries in the Files tab:** the browser listed only the first 2,000 files of+ the Samples folder; it now lists up to 100,000, and searching them stays fast.+## [0.42.2] — 2026-09-30### Highlightsdiff --git a/src/managed/Nota.App/App.axaml.cs b/src/managed/Nota.App/App.axaml.csindex f3c74677..5b6b6a22 100644--- a/src/managed/Nota.App/App.axaml.cs+++ b/src/managed/Nota.App/App.axaml.cs@@ -38,6 +38,7 @@ public partial class App : Avalonia.Applicationservices.AddSingleton<ISettingsService, SettingsService>();services.AddSingleton<IPluginCatalog, PluginCatalog>();services.AddSingleton<IPluginStore, PluginStore>();+ services.AddSingleton<ISampleStore, SampleStore>();services.AddSingleton<IPresetLibrary, PresetLibrary>();services.AddSingleton<IProjectStore, ProjectStore>();services.AddSingleton<IProjectHistory>(_ => new ProjectHistory(AppInfo.Version));diff --git a/src/managed/Nota.App/BrowserView.cs b/src/managed/Nota.App/BrowserView.csindex 9ab76571..07a33158 100644--- a/src/managed/Nota.App/BrowserView.cs+++ b/src/managed/Nota.App/BrowserView.cs@@ -570,9 +570,9 @@ public sealed class BrowserView : UserControl0 => ("No instruments yet", "Nota's built-in synths plus your VST/AU plug-ins. Scan your plug-ins in Settings → Plug-ins to add more."),1 => ("No audio effects yet", "Nota's built-in effects plus your VST/AU plug-ins. Scan your plug-ins in Settings → Plug-ins to add more."),2 => ("No MIDI effects yet", "Arpeggiator, chord, scale and more — they process notes before an instrument; drop one to the left of an instrument in a track."),- 3 => ("No samples yet", "Add audio files to your Samples folder (Settings → Folders), then browse them here as a folder tree. You can also drag files in from Finder."),+ 3 => ("No samples yet", "Add audio files to your Samples folder (Settings → Library) or install free packs from Settings → Downloads → Sample Packs, then browse them here as a folder tree. You can also drag files in from Finder."),4 => ("No presets yet", "Right-click a device header and choose Save preset; it appears here grouped by category and device."),- _ => ("No projects yet", "Save a project (⌘S) into your Projects folder (Settings → Folders) and it shows up here."),+ _ => ("No projects yet", "Save a project (⌘S) into your Projects folder (Settings → Library) and it shows up here."),};}diff --git a/src/managed/Nota.App/MainWindow.Browser.cs b/src/managed/Nota.App/MainWindow.Browser.csindex 0ef204c0..aae3f90c 100644--- a/src/managed/Nota.App/MainWindow.Browser.cs+++ b/src/managed/Nota.App/MainWindow.Browser.cs@@ -241,7 +241,7 @@ public partial class MainWindowcatch (Exception ex) { _vm.StatusText = $"Reveal failed: {ex.Message}"; }}- private static void RevealInFileManager(string path)+ internal static void RevealInFileManager(string path){if (OperatingSystem.IsMacOS()) Process.Start("open", new[] { "-R", path });else if (OperatingSystem.IsWindows()) Process.Start("explorer.exe", $"/select,\"{path}\"");diff --git a/src/managed/Nota.App/MainWindow.MissingPlugins.cs b/src/managed/Nota.App/MainWindow.MissingPlugins.csindex f4d4e5d1..844a29b9 100644--- a/src/managed/Nota.App/MainWindow.MissingPlugins.cs+++ b/src/managed/Nota.App/MainWindow.MissingPlugins.cs@@ -22,7 +22,7 @@ public partial class MainWindowif (_vm is null || missing.Count == 0) return;var store = App.Services.GetRequiredService<IPluginStore>();try { await store.FetchAsync(); }- catch (PluginStoreException) { return; }+ catch (StoreException) { return; }var offers = missing.Select(store.FindProvider).OfType<StorePlugin>().Where(p => p.Asset is not null).DistinctBy(p => p.Id)@@ -50,7 +50,7 @@ public partial class MainWindowawait store.InstallAsync(p, new Progress<StoreProgress>(r =>prog.Report(r.Fraction < 0 ? ProgressReport.Indeterminate(r.Message) : ProgressReport.At(r.Fraction, r.Message))));}- catch (PluginStoreException e) { error ??= e.Message; }+ catch (StoreException e) { error ??= e.Message; }}prog.Report(ProgressReport.Indeterminate("Scanning plugins…"));await PluginScan.RescanAsync(_vm);diff --git a/src/managed/Nota.App/PreferencesWindow.Downloads.cs b/src/managed/Nota.App/PreferencesWindow.Downloads.csnew file mode 100644index 00000000..fd297732--- /dev/null+++ b/src/managed/Nota.App/PreferencesWindow.Downloads.cs@@ -0,0 +1,90 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Preferences → Downloads: one page for both registries, Plug-ins and Sample Packs, picked+// with a switch beside the title (PreferencesWindow.Store.cs / .Samples.cs build each half).+// The title, switch and intro scroll away; the filter / search / Refresh toolbar sticks to the+// top of the pane. It lives in an overlay above the ScrollViewer, held level with a spacer in+// the scrolled content until the spacer passes the top edge, and gets a hairline underneath+// once rows slide below it.++using System;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Primitives;+using Avalonia.Layout;+using Avalonia.Media;++namespace Nota.App;++public sealed partial class PreferencesWindow+{+ private const int DownloadsIndex = 4;+ private static readonly string[] DownloadSources = { "Plug-ins", "Sample Packs" };+ private int _downloadSource; // 0 = plug-ins, 1 = sample packs; kept for the window's life++ private Control DownloadsPane(Control header)+ {+ var (toolbar, body) = _downloadSource == 0 ? StoreParts() : PackParts();+ var intro = Caption(_downloadSource == 0 ? StoreIntro : PacksIntro, muted: true);+ intro.MaxWidth = 600;+ intro.HorizontalAlignment = HorizontalAlignment.Left;+ intro.Margin = new Thickness(0, 0, 0, 4);++ // Title row: the page header left, the registry switch right.+ var strip = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2 };+ var segs = new ToggleButton[DownloadSources.Length];+ for (int i = 0; i < DownloadSources.Length; i++)+ {+ int idx = i;+ segs[i] = new ToggleButton { Classes = { "seg" }, FontSize = 12, IsChecked = i == _downloadSource, Content = DownloadSources[i] };+ segs[i].Click += (_, _) =>+ {+ segs[idx].IsChecked = idx == _downloadSource; // a toggle never clears itself+ if (idx == _downloadSource) return;+ _downloadSource = idx;+ Select(DownloadsIndex);+ };+ strip.Children.Add(segs[i]);+ }+ header.Margin = new Thickness(0);+ var titleRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Margin = new Thickness(0, 0, 0, 16) };+ titleRow.Children.Add(header);+ var sw = new Border { Classes = { "segmented" }, Child = strip, VerticalAlignment = VerticalAlignment.Bottom };+ Grid.SetColumn(sw, 1);+ titleRow.Children.Add(sw);++ // The toolbar sits in the overlay; the spacer keeps its place in the flow.+ var spacer = new Border();+ var pinned = new Border+ {+ Background = Ground, BorderBrush = Brushes.Transparent, BorderThickness = new Thickness(0, 0, 0, 1),+ Padding = new Thickness(32, 10, 32 - ScrollBarWidth, 10), Margin = new Thickness(0, 0, ScrollBarWidth, 0),+ VerticalAlignment = VerticalAlignment.Top, Child = toolbar,+ RenderTransform = new TranslateTransform(),+ };+ var content = new StackPanel { Children = { titleRow, intro, spacer, body } };+ var scroll = new ScrollViewer+ {+ Content = new Border { Padding = new Thickness(32, 26, 32, 40), Child = content },+ };++ void Place()+ {+ spacer.Height = pinned.Bounds.Height;+ // The spacer's top in the viewport: its place in the content (under the 26 px top+ // padding) less how far the content has scrolled.+ double top = spacer.Bounds.Y + 26 - scroll.Offset.Y;+ ((TranslateTransform)pinned.RenderTransform!).Y = Math.Max(0, top);+ pinned.BorderBrush = top < 0 ? Hairline : Brushes.Transparent;+ }+ scroll.ScrollChanged += (_, _) => Place();+ pinned.SizeChanged += (_, _) => Place();+ content.LayoutUpdated += (_, _) => Place();++ return new Panel { Children = { scroll, pinned } };+ }++ // ScrollBar:vertical width in NotaTheme.axaml: the overlay stops short of it.+ private const double ScrollBarWidth = 9;+}diff --git a/src/managed/Nota.App/PreferencesWindow.Samples.cs b/src/managed/Nota.App/PreferencesWindow.Samples.csnew file mode 100644index 00000000..d9fde784--- /dev/null+++ b/src/managed/Nota.App/PreferencesWindow.Samples.cs@@ -0,0 +1,384 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Preferences → Downloads → Sample Packs: browse the Nota sample registry and install /+// update / remove free sample packs (ISampleStore) into the Samples folder. Built like Get Plug-ins+// (PreferencesWindow.Store.cs) and sharing its job state: one download at a time across both+// stores, shown in the same dock. A pack's busy key is "pack:<id>" so it can't collide with a+// plugin id. After every change the browser's Files tab is rescanned.++using System;+using System.Collections.Generic;+using System.Linq;+using System.Threading;+using System.Threading.Tasks;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Primitives;+using Avalonia.Controls.Templates;+using Avalonia.Layout;+using Avalonia.Media;+using Microsoft.Extensions.DependencyInjection;+using Nota.Application;++namespace Nota.App;++public sealed partial class PreferencesWindow+{+ private static readonly string[] PackFilters = { "All", "One-shots", "Instruments", "Installed" };++ private readonly ISampleStore _samples = App.Services.GetRequiredService<ISampleStore>();+ private IReadOnlyList<StorePack>? _packs;+ private int _packFilter;+ private string _packSearch = "";+ private string? _packMessage; // registry loading / error, shown under the toolbar+ private Task? _packLoad;+ private bool _packLoading;+ private ContentControl? _packList; // null while another pane is showing+ private ItemsControl? _packItems;+ private TextBlock[]? _packCounts;+ private TextBlock? _packStatus;+ private Button? _packRefresh;+ private ProgressBar? _packLoadBar;++ private sealed record PackEntry(StorePack Pack, InstalledStorePack? Installed, bool First);++ private static string PackKey(string id) => "pack:" + id;++ private const string PacksIntro = "Free sample packs from the Nota sample registry, licensed for any music, commercial releases included. Each pack downloads from where its author publishes it, is checked against the registry's checksum and unpacked into your Samples folder.";++ // The Sample Packs half of Downloads (PreferencesWindow.Downloads.cs).+ private (Control Toolbar, Control Body) PackParts()+ {+ var strip = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2 };+ var segs = new List<ToggleButton>();+ _packCounts = new TextBlock[PackFilters.Length];+ for (int i = 0; i < PackFilters.Length; i++)+ {+ int idx = i;+ var count = new TextBlock { FontSize = 9, FontFamily = NotaFonts.MonoFamily, VerticalAlignment = VerticalAlignment.Center };+ _packCounts[i] = count;+ var b = new ToggleButton+ {+ Classes = { "seg" }, FontSize = 12, IsChecked = i == _packFilter,+ Content = new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 6,+ Children = { new TextBlock { Text = PackFilters[i], VerticalAlignment = VerticalAlignment.Center }, count },+ },+ };+ b.Click += (_, _) =>+ {+ for (int k = 0; k < segs.Count; k++) segs[k].IsChecked = k == idx;+ _packFilter = idx;+ RenderPackList();+ };+ segs.Add(b);+ strip.Children.Add(b);+ }+ var search = new TextBox { PlaceholderText = "Search", Text = _packSearch, Classes = { "search" }, FontSize = 12 };+ search.TextChanged += (_, _) => { _packSearch = search.Text ?? ""; RenderPackList(); };+ var refresh = new Button { Content = "Refresh", Classes = { "ghost" }, Height = 30, FontSize = 12, Padding = new Thickness(12, 0), Foreground = TextSecondary };+ ToolTip.SetTip(refresh, "Reload the registry");+ refresh.Click += (_, _) => { if (!_packLoading) _packLoad = LoadPacksAsync(refresh: true); };+ _packRefresh = refresh;++ var toolbar = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 10 };+ toolbar.Children.Add(new Border { Classes = { "segmented" }, Child = strip });+ var searchField = SearchField(search, double.PositiveInfinity);+ searchField.MinWidth = 140;+ Grid.SetColumn(searchField, 1); toolbar.Children.Add(searchField);+ Grid.SetColumn(refresh, 2); toolbar.Children.Add(refresh);++ var list = _packList = new ContentControl();+ _packStatus = Caption("");+ _packLoadBar = new ProgressBar { IsIndeterminate = true, Height = 3, MinWidth = 0, IsVisible = false };+ _packItems = PackItems();++ var body = new StackPanel+ {+ Spacing = 14,+ Children =+ {+ _packStatus,+ new StackPanel { Spacing = 6, Children = { _packLoadBar, _packList } },+ Caption($"Installed to {_samples.InstallDir}"),+ },+ };+ body.DetachedFromVisualTree += (_, _) =>+ {+ if (_packList != list) return;+ _packList = null; _packItems = null; _packStatus = null; _packCounts = null; _packRefresh = null; _packLoadBar = null;+ };+ if (_packs is null && _packLoad is not { IsCompleted: false }) _packLoad = LoadPacksAsync(refresh: false);+ RenderPackList();+ return (toolbar, body);+ }++ private async Task LoadPacksAsync(bool refresh)+ {+ _packLoading = true;+ _packMessage = null;+ RenderPackList();+ try+ {+ _packs = await _samples.FetchAsync(refresh);+ }+ catch (StoreException e)+ {+ _packMessage = e.Message;+ }+ finally { _packLoading = false; }+ RenderPackList();+ }++ private ItemsControl PackItems() => new()+ {+ ItemsPanel = new FuncTemplate<Panel?>(() => new VirtualizingStackPanel()),+ Margin = new Thickness(0, 0, 0, -1),+ DataTemplates =+ {+ new FuncDataTemplate<PackEntry>((e, _) => e is null ? new Panel() : new Border+ {+ Background = RowBg, BorderBrush = Hairline, BorderThickness = new Thickness(0, e.First ? 0 : 1, 0, 0),+ Child = PackRow(e.Pack, e.Installed),+ }),+ },+ };++ private void RenderPackList()+ {+ if (_packList is null || _packItems is null) return;+ if (_packStatus is not null)+ {+ _packStatus.Text = _packMessage ?? "";+ _packStatus.IsVisible = _packStatus.Text.Length > 0;+ }+ if (_packRefresh is not null)+ {+ _packRefresh.IsEnabled = !_packLoading;+ _packRefresh.Content = _packLoading && _packs is not null ? "Refreshing…" : "Refresh";+ }+ if (_packLoadBar is not null) _packLoadBar.IsVisible = _packLoading && _packs is not null;+ if (_packs is null)+ {+ _packList.Content = _packLoading ? PackLoadingBlock() : null;+ UpdatePackCounts(null);+ return;+ }++ var installed = _samples.Installed.ToDictionary(i => i.Id);+ UpdatePackCounts(installed);+ var q = _packSearch.Trim();+ var shown = _packs.Where(p => MatchesPackFilter(p, _packFilter, installed))+ .Where(p => q.Length == 0+ || p.Name.Contains(q, StringComparison.OrdinalIgnoreCase)+ || p.Author.Contains(q, StringComparison.OrdinalIgnoreCase)+ || p.Description.Contains(q, StringComparison.OrdinalIgnoreCase)+ || p.Tags.Any(t => t.Contains(q, StringComparison.OrdinalIgnoreCase)))+ .ToList();++ if (shown.Count == 0)+ {+ var empty = new TextBlock+ {+ Text = _packFilter == 3 && q.Length == 0 ? "No sample packs installed from the registry yet." : "Nothing matches.",+ FontSize = 12, Foreground = TextTertiary, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(28),+ };+ _packList.Content = Table(new List<Control> { empty });+ return;+ }++ _packItems.ItemsSource = shown.Select((p, i) => new PackEntry(p, installed.GetValueOrDefault(p.Id), First: i == 0)).ToList();+ if (_packList.Content is not Border { Tag: "pack-table" })+ _packList.Content = new Border+ {+ Tag = "pack-table", BorderBrush = Divider, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel,+ ClipToBounds = true, Child = _packItems,+ };+ }++ private Control PackLoadingBlock() => Table(new List<Control>+ {+ new StackPanel+ {+ Spacing = 10, Margin = new Thickness(28, 36), HorizontalAlignment = HorizontalAlignment.Center,+ Children =+ {+ new ProgressBar { IsIndeterminate = true, Width = 180, Height = 4, MinWidth = 0 },+ new TextBlock { Text = "Loading the sample registry…", FontSize = 12, Foreground = TextTertiary, HorizontalAlignment = HorizontalAlignment.Center },+ },+ },+ });++ private static bool MatchesPackFilter(StorePack p, int filter, IReadOnlyDictionary<string, InstalledStorePack> installed) => filter switch+ {+ 1 => p.Kind is "one-shots" or "loops" or "mixed",+ 2 => p.Kind is "multisample",+ 3 => installed.ContainsKey(p.Id),+ _ => true,+ };++ private void UpdatePackCounts(IReadOnlyDictionary<string, InstalledStorePack>? installed)+ {+ if (_packCounts is null) return;+ for (int i = 0; i < _packCounts.Length; i++)+ {+ _packCounts[i].Text = _packs is null || installed is null ? "" : _packs.Count(p => MatchesPackFilter(p, i, installed)).ToString();+ _packCounts[i].Foreground = i == _packFilter ? NotaPalette.AccentEdge : TextDisabled;+ }+ }++ private static string PackKindLabel(string kind) => kind switch+ {+ "one-shots" => "ONE-SHOTS",+ "loops" => "LOOPS",+ "multisample" => "INSTRUMENT",+ "mixed" => "MIXED",+ _ => kind.ToUpperInvariant(),+ };++ private static string Megabytes(long bytes)+ => bytes >= 1L << 30 ? NotaNum.Unit(bytes / (double)(1L << 30), "0.0", "GB") : NotaNum.Unit(bytes / 1048576.0, "0.0", "MB");++ private Control PackRow(StorePack p, InstalledStorePack? inst)+ {+ var text = new StackPanel+ {+ Spacing = 4,+ Children =+ {+ new WrapPanel+ {+ Children =+ {+ new TextBlock { Text = p.Name, FontSize = 13, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary, Margin = new Thickness(0, 0, 8, 0), VerticalAlignment = VerticalAlignment.Center },+ new TextBlock { Text = PackKindLabel(p.Kind), FontSize = 9, LetterSpacing = 0.7, FontFamily = NotaFonts.MonoFamily, Foreground = TextMuted, VerticalAlignment = VerticalAlignment.Center },+ },+ },+ new TextBlock { Text = $"{p.Author} · {p.Version} · {p.License}", FontSize = 10, FontFamily = NotaFonts.MonoFamily, Foreground = TextTertiary },+ new TextBlock { Text = p.Description, FontSize = 12, LineHeight = 18, Foreground = TextSecondary, TextWrapping = TextWrapping.Wrap },+ },+ };+ if (p.Attribution is { Length: > 0 } credit)+ text.Children.Add(new TextBlock { Text = $"Credit: {credit}", FontSize = 11, LineHeight = 16, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap });+ if (p.Notes is { Length: > 0 } notes)+ text.Children.Add(new TextBlock { Text = notes, FontSize = 11, LineHeight = 16, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap });++ var actions = new StackPanel { Spacing = 8, MinWidth = 96, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top };+ bool busy = _storeBusyId is not null;+ if (_storeBusyId == PackKey(p.Id))+ {+ actions.Children.Add(StoreButton(inst is null ? "Installing…" : "Working…", enabled: false, () => { }));+ }+ else if (inst is null)+ {+ actions.Children.Add(StoreButton("Install", enabled: !busy, () => InstallPack(p)));+ }+ else+ {+ if (inst.Version != p.Version)+ actions.Children.Add(StoreButton($"Update to {p.Version}", enabled: !busy, () => InstallPack(p)));+ else+ actions.Children.Add(new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 6, Height = 26, HorizontalAlignment = HorizontalAlignment.Right,+ Children = { Dot(Brass), new TextBlock { Text = "Installed", FontSize = 11, FontWeight = FontWeight.Medium, Foreground = Brass, VerticalAlignment = VerticalAlignment.Center } },+ });+ var show = StoreLink("Show", null, () => { try { MainWindow.RevealInFileManager(inst.Path); } catch { /* no file manager */ } });+ ToolTip.SetTip(show, "Show the pack's folder");+ actions.Children.Add(show);+ actions.Children.Add(StoreLink("Remove", null, busy ? null : () => RemovePack(p, inst)));+ }+ actions.Children.Add(new TextBlock+ {+ Text = inst is null ? $"{Megabytes(p.Asset.Size)} · {p.Asset.Files} samples" : $"{inst.Files} samples",+ FontSize = 10, FontFamily = NotaFonts.MonoFamily, Foreground = TextTertiary, HorizontalAlignment = HorizontalAlignment.Right,+ });+ if (inst is null)+ ToolTip.SetTip(actions.Children[^1], $"{Megabytes(p.Asset.Size)} download · {p.Asset.Files} samples · {Megabytes(p.Asset.UnpackedSize)} on disk · {string.Join(", ", p.Asset.Formats)}");+ var source = StoreLink("Source", GlyphKind.PopOut, () => _ = Launcher.LaunchUriAsync(new Uri(p.Source)));+ ToolTip.SetTip(source, "Open the pack's page");+ actions.Children.Add(source);++ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 16, Margin = new Thickness(16, 14, 14, 14) };+ grid.Children.Add(text);+ Grid.SetColumn(actions, 1);+ grid.Children.Add(actions);+ return grid;+ }++ private async void InstallPack(StorePack p)+ {+ if (_storeBusyId is not null) return;+ _storeBusyId = PackKey(p.Id);+ _storeBusySize = p.Asset.Size;+ _storeProgress = new StoreProgress(0, $"Downloading {p.Name}…");+ SetStoreResult(null, sticky: true);+ _storeCts ??= new CancellationTokenSource();+ var job = _storeJobCts = CancellationTokenSource.CreateLinkedTokenSource(_storeCts.Token);+ RenderStoreLists();+ var progress = new Progress<StoreProgress>(r =>+ {+ if (job.IsCancellationRequested) return;+ // Only the download has a known byte count; the copy stage's fraction is of the unpacked size.+ if (!r.Message.StartsWith("Downloading", StringComparison.Ordinal)) _storeBusySize = 0;+ _storeProgress = r;+ UpdateDock();+ });+ try+ {+ await _samples.InstallAsync(p, progress, job.Token);+ _main?.Browser.RebuildSamples();+ SetStoreResult($"{p.Name} is installed — find it under Downloaded in the browser's Files tab.", sticky: false);+ }+ catch (OperationCanceledException)+ {+ if (_storeCts is { IsCancellationRequested: false }) SetStoreResult($"Installing {p.Name} was cancelled.", sticky: false);+ }+ catch (StoreException e) { SetStoreResult(e.Message, sticky: true); }+ catch (Exception e)+ {+ App.Services.GetRequiredService<ILogSink>().Error($"Installing pack {p.Id} failed", e);+ SetStoreResult($"Installing {p.Name} failed: {e.Message}", sticky: true);+ }+ finally+ {+ _storeBusyId = null;+ _storeJobCts = null;+ job.Dispose();+ }+ RenderStoreLists();+ }++ private async void RemovePack(StorePack p, InstalledStorePack inst)+ {+ if (_storeBusyId is not null) return;+ var ok = await new ConfirmWindow("Remove sample pack",+ $"Remove {p.Name}? Its folder ({inst.Path}) is deleted.",+ "Remove", "Cancel").ShowDialog<bool>(this);+ if (!ok) return;+ _storeBusyId = PackKey(p.Id);+ _storeBusySize = 0;+ _storeProgress = new StoreProgress(-1, $"Removing {p.Name}…");+ SetStoreResult(null, sticky: true);+ RenderStoreLists();+ try+ {+ await Task.Run(() => _samples.Uninstall(p.Id));+ _main?.Browser.RebuildSamples();+ SetStoreResult($"{p.Name} was removed.", sticky: false);+ }+ catch (StoreException e) { SetStoreResult(e.Message, sticky: true); }+ finally { _storeBusyId = null; }+ RenderStoreLists();+ }++ // Both lists, since a job in one disables the Install buttons of the other.+ private void RenderStoreLists()+ {+ RenderStoreList();+ RenderPackList();+ UpdateDock(); // RenderStoreList only reaches the dock while the Downloads pane is showing+ }+}diff --git a/src/managed/Nota.App/PreferencesWindow.Store.cs b/src/managed/Nota.App/PreferencesWindow.Store.csindex 9f00ec53..becee0b6 100644--- a/src/managed/Nota.App/PreferencesWindow.Store.cs+++ b/src/managed/Nota.App/PreferencesWindow.Store.cs@@ -1,12 +1,13 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Preferences → Get Plug-ins: browse the Nota plugin registry and install / update /+// Preferences → Downloads → Plug-ins: browse the Nota plugin registry and install / update /// remove open-source VST3 plugins (IPluginStore). One install at a time; it keeps// running when the user switches panes and is cancelled when the window closes. Its// progress and outcome show in a dock at the bottom of the window (visible from every-// pane), which also cancels it. After every change the catalog is rescanned so the-// browser lists the new plugins.+// pane), which also cancels it; Sample Packs (PreferencesWindow.Samples.cs) shares that+// job state and dock. After every change the catalog is rescanned so the browser lists the+// new plugins.//// The list is virtualized (only the rows in view exist), so filtering and searching the// whole registry stays instant. Plugins without a build for this computer sink to the end,@@ -67,12 +68,12 @@ public sealed partial class PreferencesWindowprivate Button _dockCancel = null!;private Control _dockClose = null!;- private Control StorePane()- {- var intro = Caption("Open-source VST3 plugins from the Nota plugin registry. Each one downloads from the project's own GitHub release, is checked against the registry's checksum and unpacked — installers never run.", muted: true);- intro.MaxWidth = 600;- intro.HorizontalAlignment = HorizontalAlignment.Left;+ private const string StoreIntro = "Open-source VST3 plugins from the Nota plugin registry. Each one downloads from the project's own GitHub release, is checked against the registry's checksum and unpacked — installers never run.";+ // The Plug-ins half of Downloads (PreferencesWindow.Downloads.cs): its toolbar pins to the+ // top while the body scrolls.+ private (Control Toolbar, Control Body) StoreParts()+ {// Filter segments carry a mono count; RenderStoreList keeps the counts current.var strip = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2 };var segs = new List<ToggleButton>();@@ -114,9 +115,9 @@ public sealed partial class PreferencesWindowGrid.SetColumn(searchField, 1); toolbar.Children.Add(searchField);Grid.SetColumn(refresh, 2); toolbar.Children.Add(refresh);+ var list = _storeList = new ContentControl();_storeStatus = Caption("");_storeLoadBar = new ProgressBar { IsIndeterminate = true, Height = 3, MinWidth = 0, IsVisible = false };- _storeList = new ContentControl();_storeItems = StoreItems();var body = new StackPanel@@ -124,16 +125,21 @@ public sealed partial class PreferencesWindowSpacing = 14,Children ={- intro, toolbar,_storeStatus,new StackPanel { Spacing = 6, Children = { _storeLoadBar, _storeList } },Caption($"Installed to {_store.PluginsDir}"),},};- body.DetachedFromVisualTree += (_, _) => { _storeList = null; _storeItems = null; _storeStatus = null; _storeCounts = null; _storeRefresh = null; _storeLoadBar = null; };+ // Only forget the controls if they are still these: switching to Sample Packs and back+ // builds the new ones before the old body leaves the tree.+ body.DetachedFromVisualTree += (_, _) =>+ {+ if (_storeList != list) return;+ _storeList = null; _storeItems = null; _storeStatus = null; _storeCounts = null; _storeRefresh = null; _storeLoadBar = null;+ };EnsureStoreLoading();RenderStoreList();- return body;+ return (toolbar, body);}// The registry index is cached on disk, so the window starts this on open: the sidebar's@@ -152,7 +158,7 @@ public sealed partial class PreferencesWindow{_storePlugins = await _store.FetchAsync(refresh);}- catch (PluginStoreException e)+ catch (StoreException e){_storeMessage = e.Message;}@@ -540,7 +546,7 @@ public sealed partial class PreferencesWindowSetStoreResult(null, sticky: true);_storeCts ??= new CancellationTokenSource();var job = _storeJobCts = CancellationTokenSource.CreateLinkedTokenSource(_storeCts.Token);- RenderStoreList();+ RenderStoreLists();// A report queued before Cancel must not overwrite "Cancelling…".var progress = new Progress<StoreProgress>(r => { if (job.IsCancellationRequested) return; _storeProgress = r; UpdateDock(); });try@@ -556,7 +562,7 @@ public sealed partial class PreferencesWindow// Window closing: nothing to show. Otherwise the user pressed Cancel.if (_storeCts is { IsCancellationRequested: false }) SetStoreResult($"Installing {p.Name} was cancelled.", sticky: false);}- catch (PluginStoreException e) { SetStoreResult(e.Message, sticky: true); }+ catch (StoreException e) { SetStoreResult(e.Message, sticky: true); }catch (Exception e){App.Services.GetRequiredService<ILogSink>().Error($"Installing {p.Id} failed", e);@@ -568,7 +574,7 @@ public sealed partial class PreferencesWindow_storeJobCts = null;job.Dispose();}- RenderStoreList();+ RenderStoreLists();}private async void RemoveFromStore(StorePlugin p)@@ -582,16 +588,16 @@ public sealed partial class PreferencesWindow_storeBusySize = 0;_storeProgress = new StoreProgress(-1, $"Removing {p.Name}…");SetStoreResult(null, sticky: true);- RenderStoreList();+ RenderStoreLists();try{_store.Uninstall(p.Id);await RescanAfterStoreChange();SetStoreResult($"{p.Name} was removed.", sticky: false);}- catch (PluginStoreException e) { SetStoreResult(e.Message, sticky: true); }+ catch (StoreException e) { SetStoreResult(e.Message, sticky: true); }finally { _storeBusyId = null; }- RenderStoreList();+ RenderStoreLists();}private async Task<bool> RescanAfterStoreChange()diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex 6a4377e1..06bf57d4 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -2,12 +2,13 @@// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//// Settings (nota-design/Nota Settings.html): 880×640 with a 188px sidebar grouped as-// Devices (Audio / MIDI / Gamepads), Plug-ins (Plug-ins / Downloads) and General (Library /-// Appearance / Shortcuts), and a content pane per section under a title + subtitle header.-// Audio device / sample-rate / buffer are persisted natively (audio.json) and applied by-// restarting the backend (MainWindowViewModel.ApplyAudioSettings); scan folders go through-// the catalog. Test: a 440 Hz sine through the master (toggle; stopped when the pane or-// window goes away) and a 5 s CPU check sampling the live DSP load + dropout count.+// Devices (Audio / MIDI / Gamepads), Plug-ins (Plug-ins / Downloads: plug-ins + sample packs)+// and General (Library / Appearance / Shortcuts), and a content pane per section under a+// title + subtitle header. Audio device / sample-rate / buffer are persisted natively (audio.json)+// and applied by restarting the backend (MainWindowViewModel.ApplyAudioSettings); scan+// folders go through the catalog. Test: a 440 Hz sine through the master (toggle; stopped+// when the pane or window goes away) and a 5 s CPU check sampling the live DSP load ++// dropout count.using System;using System.Collections.Generic;@@ -67,7 +68,7 @@ public sealed partial class PreferencesWindow : NotaWindow("PLUG-INS", new[]{new Page("Plug-ins", "Where Nota looks for VST3", "M9 3 V7 M15 3 V7 M6 7 H18 V11 A6 6 0 0 1 6 11 Z M12 17 V21"),- new Page("Downloads", "Nota plugin registry", "M12 4 V15 M7 10 L12 15 L17 10 M5 19 H19"),+ new Page("Downloads", "Plug-ins and sample packs", "M12 4 V15 M7 10 L12 15 L17 10 M5 19 H19"),}),("GENERAL", new[]{@@ -218,6 +219,8 @@ public sealed partial class PreferencesWindow : NotaWindowheader.Children.Add(new TextBlock { Text = page.Title, FontSize = 17, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Bottom });header.Children.Add(new TextBlock { Text = page.Subtitle, FontSize = 11, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(0, 0, 0, 2) });+ if (index == DownloadsIndex) { _content.Content = DownloadsPane(header); return; }+// Padding lives inside the scrolled content: a ScrollViewer's own Padding isn't part of// its extent, so the last rows of a long pane (Shortcuts) couldn't be scrolled into view._content.Content = new ScrollViewer@@ -233,7 +236,7 @@ public sealed partial class PreferencesWindow : NotaWindow// The Downloads item carries the number of registry plugins not installed yet.private void UpdateDownloadsBadge(int count){- var badge = _navItems[4].Badge;+ var badge = _navItems[DownloadsIndex].Badge;badge.Text = count.ToString();badge.IsVisible = count > 0;}@@ -244,7 +247,6 @@ public sealed partial class PreferencesWindow : NotaWindow1 => MidiPane(),2 => GamepadsPane(),3 => PluginsPane(),- 4 => StorePane(),5 => LibraryPane(),6 => AppearancePane(),_ => ShortcutsPane(),diff --git a/src/managed/Nota.Application/Ports/IPluginStore.cs b/src/managed/Nota.Application/Ports/IPluginStore.csindex d1372651..0e55a3fa 100644--- a/src/managed/Nota.Application/Ports/IPluginStore.cs+++ b/src/managed/Nota.Application/Ports/IPluginStore.cs@@ -61,7 +61,7 @@ public interface IPluginStoreIReadOnlyList<InstalledStorePlugin> Installed { get; }/// <summary>Downloads, verifies (size + sha256) and unpacks the plugin's asset, replacing any- /// installed version. Throws <see cref="PluginStoreException"/> with a user-facing message.</summary>+ /// installed version. Throws <see cref="StoreException"/> with a user-facing message.</summary>Task InstallAsync(StorePlugin plugin, IProgress<StoreProgress>? progress = null, CancellationToken ct = default);/// <summary>Removes an installed plugin's files. No-op when it isn't installed.</summary>@@ -72,4 +72,7 @@ public interface IPluginStoreStorePlugin? FindProvider(string pluginIdentifier);}-public sealed class PluginStoreException(string message, Exception? inner = null) : Exception(message, inner);+/// <summary>A registry store failure (plugins or sample packs) with a user-facing message.</summary>+public class StoreException(string message, Exception? inner = null) : Exception(message, inner);++public sealed class PluginStoreException(string message, Exception? inner = null) : StoreException(message, inner);diff --git a/src/managed/Nota.Application/Ports/ISampleStore.cs b/src/managed/Nota.Application/Ports/ISampleStore.csnew file mode 100644index 00000000..cb4c9bf4--- /dev/null+++ b/src/managed/Nota.Application/Ports/ISampleStore.cs@@ -0,0 +1,64 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++namespace Nota.Application;++/// <summary>A sample pack listed in the Nota sample registry (github.com/nota-daw/nota-samples-registry).</summary>+public sealed record StorePack(+ string Id,+ string Name,+ string Author,+ string Description,+ string Kind, // one-shots | loops | multisample | mixed+ string License, // SPDX id (CC0-1.0, CC-BY-4.0, …)+ string Source, // the page where the author publishes the pack+ IReadOnlyList<string> Tags,+ string Version, // newest registry version+ StorePackAsset Asset)+{+ /// <summary>Credit line the license asks for (CC-BY); null for CC0.</summary>+ public string? Attribution { get; init; }++ /// <summary>Optional caveat from the registry.</summary>+ public string? Notes { get; init; }++ public string? Homepage { get; init; }+}++/// <summary>The pack's archive and what installing it puts on disk.</summary>+public sealed record StorePackAsset(+ string Url,+ string Sha256,+ long Size, // download bytes+ string Archive, // zip | tar+ string? Root, // folder inside the archive to install; null = all of it+ int Files, // audio files installed+ long UnpackedSize, // bytes installed (audio + docs)+ IReadOnlyList<string> Formats); // audio extensions, e.g. wav, flac++/// <summary>A registry pack installed into the Samples folder.</summary>+public sealed record InstalledStorePack(string Id, string Version, string Sha256, string Path, int Files, DateTimeOffset InstalledAt);++/// <summary>Browse and install free sample packs from the Nota sample registry. A pack installs+/// into its own folder under <see cref="InstallDir"/> (inside the Samples folder, so the browser's+/// Files tab lists it); only audio and docs are copied out of the archive.</summary>+public interface ISampleStore+{+ /// <summary>Where new packs go: "Downloaded" inside the current Samples folder.</summary>+ string InstallDir { get; }++ /// <summary>The registry's packs (newest version each). Served from the on-disk cache unless+ /// <paramref name="refresh"/> is set or the cache is older than a day; falls back to the cache+ /// when offline. Throws only when there is neither network nor cache.</summary>+ Task<IReadOnlyList<StorePack>> FetchAsync(bool refresh = false, CancellationToken ct = default);++ /// <summary>Packs installed from the registry whose folders still exist.</summary>+ IReadOnlyList<InstalledStorePack> Installed { get; }++ /// <summary>Checks free space, downloads, verifies (size + sha256) and unpacks the pack, replacing+ /// any installed version. Throws <see cref="StoreException"/> with a user-facing message.</summary>+ Task InstallAsync(StorePack pack, IProgress<StoreProgress>? progress = null, CancellationToken ct = default);++ /// <summary>Removes an installed pack's folder. No-op when it isn't installed.</summary>+ void Uninstall(string id);+}diff --git a/src/managed/Nota.Infrastructure/PluginStore/ArchiveUnpacker.cs b/src/managed/Nota.Infrastructure/PluginStore/ArchiveUnpacker.csindex 70d5d5b7..99bf6207 100644--- a/src/managed/Nota.Infrastructure/PluginStore/ArchiveUnpacker.cs+++ b/src/managed/Nota.Infrastructure/PluginStore/ArchiveUnpacker.cs@@ -1,9 +1,10 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Expands a downloaded plugin release asset. Only ever *unpacks*: installer scripts-// never run (a .pkg is expanded with `pkgutil --expand-full`, which extracts payloads-// without executing anything). Mirrors unpack() in the registry's scripts/registry.py.+// Expands a downloaded registry asset (a plugin release or a sample pack). Only ever+// *unpacks*: installer scripts never run (a .pkg is expanded with `pkgutil --expand-full`,+// which extracts payloads without executing anything). Mirrors unpack() in the+// registries' scripts/registry.py.// zip -> ditto on macOS (keeps bundle symlinks + permissions), else managed// tar -> the system tar (bsdtar on macOS/Windows, GNU tar on Linux: gz/xz/bz2)// dmg -> hdiutil attach (read-only, hidden) + copy + detach (macOS)@@ -57,13 +58,13 @@ public static class ArchiveUnpackerUnpackDeb(archive, dest, ct);break;default:- throw new PluginStoreException($"Unsupported archive type \"{kind}\".");+ throw new StoreException($"Unsupported archive type \"{kind}\".");}}private static void RequireMac(string kind){- if (!OperatingSystem.IsMacOS()) throw new PluginStoreException($"A .{kind} archive can only be unpacked on macOS.");+ if (!OperatingSystem.IsMacOS()) throw new StoreException($"A .{kind} archive can only be unpacked on macOS.");}// Refuses entries that would land outside the destination (absolute, drive-rooted or@@ -77,7 +78,7 @@ public static class ArchiveUnpacker{var rel = e.FullName.Replace('\\', '/');if (rel.StartsWith('/') || rel.Contains(':') || rel.Split('/').Contains(".."))- throw new PluginStoreException($"The archive contains an unsafe path: {e.FullName}");+ throw new StoreException($"The archive contains an unsafe path: {e.FullName}");backslashes |= e.FullName.Contains('\\');}return backslashes;@@ -93,7 +94,7 @@ public static class ArchiveUnpackervar rel = e.FullName.Replace('\\', '/');var target = Path.GetFullPath(Path.Combine(dest, rel));if (!target.StartsWith(root, StringComparison.Ordinal) && target + Path.DirectorySeparatorChar != root)- throw new PluginStoreException($"The archive contains an unsafe path: {e.FullName}");+ throw new StoreException($"The archive contains an unsafe path: {e.FullName}");if (rel.EndsWith('/')) { Directory.CreateDirectory(target); continue; }Directory.CreateDirectory(Path.GetDirectoryName(target)!);e.ExtractToFile(target, overwrite: true);@@ -125,7 +126,7 @@ public static class ArchiveUnpackerusing var f = File.OpenRead(archive);var magic = new byte[8];if (f.Read(magic) != 8 || System.Text.Encoding.ASCII.GetString(magic) != "!<arch>\n")- throw new PluginStoreException("The .deb archive is damaged.");+ throw new StoreException("The .deb archive is damaged.");var header = new byte[60];while (f.Read(header) == 60){@@ -145,7 +146,7 @@ public static class ArchiveUnpacker}f.Seek(size + (size & 1), SeekOrigin.Current);}- throw new PluginStoreException("The .deb archive has no data.");+ throw new StoreException("The .deb archive has no data.");}private static void CopyExactly(Stream from, Stream to, long count)@@ -154,7 +155,7 @@ public static class ArchiveUnpackerwhile (count > 0){int n = from.Read(buf, 0, (int)Math.Min(buf.Length, count));- if (n <= 0) throw new PluginStoreException("The .deb archive is truncated.");+ if (n <= 0) throw new StoreException("The .deb archive is truncated.");to.Write(buf, 0, n);count -= n;}@@ -198,8 +199,8 @@ public static class ArchiveUnpackerforeach (var a in args) psi.ArgumentList.Add(a);Process p;- try { p = Process.Start(psi) ?? throw new PluginStoreException($"Couldn't start {exe}."); }- catch (System.ComponentModel.Win32Exception e) { throw new PluginStoreException($"Unpacking needs \"{exe}\", which wasn't found.", e); }+ try { p = Process.Start(psi) ?? throw new StoreException($"Couldn't start {exe}."); }+ catch (System.ComponentModel.Win32Exception e) { throw new StoreException($"Unpacking needs \"{exe}\", which wasn't found.", e); }using (p){if (stdin is not null) { p.StandardInput.Write(stdin); p.StandardInput.Close(); }@@ -208,7 +209,7 @@ public static class ArchiveUnpackertry { p.WaitForExitAsync(ct).GetAwaiter().GetResult(); }catch (OperationCanceledException) { try { p.Kill(entireProcessTree: true); } catch { } throw; }if (p.ExitCode != 0)- throw new PluginStoreException($"{exe} failed ({p.ExitCode}): {stderr.GetAwaiter().GetResult().Trim()}");+ throw new StoreException($"{exe} failed ({p.ExitCode}): {stderr.GetAwaiter().GetResult().Trim()}");}}}diff --git a/src/managed/Nota.Infrastructure/PluginStore/PluginStore.cs b/src/managed/Nota.Infrastructure/PluginStore/PluginStore.csindex c3dfa80a..7c4fa054 100644--- a/src/managed/Nota.Infrastructure/PluginStore/PluginStore.cs+++ b/src/managed/Nota.Infrastructure/PluginStore/PluginStore.cs@@ -4,7 +4,7 @@// Get Plug-ins: installs open-source VST3 plugins listed in the Nota plugin registry// (github.com/nota-daw/nota-plugins-registry). The registry is one static index.json on// GitHub Pages; assets download straight from each plugin's GitHub release and must match-// the size + sha256 pinned in the index before anything is unpacked.+// the size + sha256 pinned in the index before anything is unpacked (RegistryClient).//// Layout under <data>/plugins:// VST3/<id>/<Bundle>.vst3 installed bundles, one folder per plugin (the scan path)@@ -14,7 +14,6 @@// swaps that folder in — a failed install never leaves a half-copied plugin behind.// NOTA_PLUGIN_REGISTRY overrides the index URL (or points at a local index.json).-using System.Security.Cryptography;using System.Text.Json;namespace Nota.Infrastructure;@@ -22,13 +21,11 @@ namespace Nota.Infrastructure;public sealed class PluginStore : IPluginStore{public const string DefaultIndexUrl = "https://nota-daw.github.io/nota-plugins-registry/index.json";- private static readonly TimeSpan CacheFreshFor = TimeSpan.FromHours(24);private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) { WriteIndented = true };private readonly string _root;- private readonly string _indexSource;private readonly IReadOnlyList<string> _platformKeys;- private readonly HttpClient _http;+ private readonly RegistryClient _registry;private readonly object _gate = new();private IReadOnlyList<StorePlugin> _plugins = [];private List<InstalledStorePlugin> _installed;@@ -42,11 +39,9 @@ public sealed class PluginStore : IPluginStore{_root = root;var env = Environment.GetEnvironmentVariable("NOTA_PLUGIN_REGISTRY");- _indexSource = indexSource ?? (string.IsNullOrEmpty(env) ? DefaultIndexUrl : env);_platformKeys = platformKeys ?? RegistryIndex.PlatformKeys();- _http = handler is null ? new HttpClient() : new HttpClient(handler);- _http.Timeout = Timeout.InfiniteTimeSpan; // big assets; each request carries its own token- _http.DefaultRequestHeaders.UserAgent.ParseAdd("Nota-PluginStore");+ _registry = new RegistryClient(indexSource ?? (string.IsNullOrEmpty(env) ? DefaultIndexUrl : env),+ Path.Combine(root, "registry-index.json"), "plugin registry", "Nota-PluginStore", handler);PluginsDir = Path.Combine(root, "VST3");Directory.CreateDirectory(PluginsDir);_installed = LoadInstalled();@@ -54,7 +49,6 @@ public sealed class PluginStore : IPluginStorepublic string PluginsDir { get; }- private string CachePath => Path.Combine(_root, "registry-index.json");private string InstalledPath => Path.Combine(_root, "installed.json");public IReadOnlyList<InstalledStorePlugin> Installed@@ -66,33 +60,7 @@ public sealed class PluginStore : IPluginStorepublic async Task<IReadOnlyList<StorePlugin>> FetchAsync(bool refresh = false, CancellationToken ct = default){- string json;- if (IsLocal(_indexSource, out var localPath))- {- json = await File.ReadAllTextAsync(localPath, ct).ConfigureAwait(false);- }- else if (!refresh && File.Exists(CachePath) && DateTime.UtcNow - File.GetLastWriteTimeUtc(CachePath) < CacheFreshFor)- {- json = await File.ReadAllTextAsync(CachePath, ct).ConfigureAwait(false);- }- else- {- try- {- using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);- cts.CancelAfter(TimeSpan.FromSeconds(15));- json = await _http.GetStringAsync(_indexSource, cts.Token).ConfigureAwait(false);- RegistryIndex.Parse(json, _platformKeys); // don't cache something unparseable- WriteAtomic(CachePath, json);- }- catch (Exception e) when (e is HttpRequestException or TaskCanceledException && !ct.IsCancellationRequested- || e is JsonException)- {- if (!File.Exists(CachePath))- throw new PluginStoreException("Couldn't reach the plugin registry. Check your internet connection.", e);- json = await File.ReadAllTextAsync(CachePath, ct).ConfigureAwait(false);- }- }+ var json = await _registry.FetchIndexAsync(refresh, j => RegistryIndex.Parse(j, _platformKeys), ct).ConfigureAwait(false);IReadOnlyList<StorePlugin> plugins;try { plugins = RegistryIndex.Parse(json, _platformKeys); }@@ -116,8 +84,8 @@ public sealed class PluginStore : IPluginStorevar work = Directory.CreateTempSubdirectory("nota-plugin-").FullName;try{- var file = Path.Combine(work, "asset" + ExtensionOf(asset));- await DownloadAsync(plugin, asset, file, progress, ct).ConfigureAwait(false);+ var file = Path.Combine(work, "asset" + RegistryClient.ExtensionOf(asset.Url, asset.Archive));+ await _registry.DownloadAsync(asset.Url, asset.Size, asset.Sha256, file, plugin.Name, progress, ct).ConfigureAwait(false);progress?.Report(new StoreProgress(-1, $"Unpacking {plugin.Name}…"));var bundleRoot = await Task.Run(() => Expand(asset, file, work, ct), ct).ConfigureAwait(false);@@ -157,63 +125,18 @@ public sealed class PluginStore : IPluginStoreprivate string PluginDir(string id){- // Registry ids are [a-z0-9-]; refuse anything that could walk out of PluginsDir.- if (id.Length == 0 || !id.All(c => c is >= 'a' and <= 'z' or >= '0' and <= '9' or '-'))+ if (!RegistryClient.IsValidId(id))throw new PluginStoreException($"Invalid plugin id \"{id}\".");return Path.Combine(PluginsDir, id);}- private async Task DownloadAsync(StorePlugin plugin, StoreAsset asset, string file, IProgress<StoreProgress>? progress, CancellationToken ct)- {- string label = $"Downloading {plugin.Name}…";- progress?.Report(new StoreProgress(0, label));- using var sha = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);- long total = 0;- try- {- Stream src;- HttpResponseMessage? resp = null;- if (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 PluginStoreException($"The download of {plugin.Name} is larger than the registry says — 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)- {- throw new PluginStoreException($"Couldn't download {plugin.Name}: {e.Message}", e);- }-- var digest = Convert.ToHexStringLower(sha.GetHashAndReset());- if (total != asset.Size || digest != asset.Sha256)- throw new PluginStoreException($"The download of {plugin.Name} doesn't match the registry's checksum — not installing it.");- }-private static string Expand(StoreAsset asset, string file, string work, CancellationToken ct){var outer = Path.Combine(work, "outer");ArchiveUnpacker.Unpack(file, asset.Archive, outer, ct);if (asset.Inner is not { } inner) return outer;- var nested = Resolve(outer, inner);+ var nested = RegistryClient.Resolve(outer, inner);var kind = ArchiveUnpacker.KindOf(inner) ?? throw new PluginStoreException("Unknown nested archive type.");if (!File.Exists(nested) && !Directory.Exists(nested))throw new PluginStoreException($"The download doesn't contain {inner}.");@@ -235,7 +158,7 @@ public sealed class PluginStore : IPluginStoreforeach (var rel in asset.Bundles){ct.ThrowIfCancellationRequested();- var src = Resolve(bundleRoot, rel);+ var src = RegistryClient.Resolve(bundleRoot, rel);if (!Directory.Exists(src) && !File.Exists(src))throw new PluginStoreException($"The download doesn't contain {rel}.");var name = Path.GetFileName(src);@@ -253,31 +176,6 @@ public sealed class PluginStore : IPluginStore}}- /// <summary>A manifest-relative path ("a/b.vst3") under root; refuses paths that escape it.</summary>- private static string Resolve(string root, string rel)- {- var full = Path.GetFullPath(Path.Combine(root, rel.Replace('/', Path.DirectorySeparatorChar)));- var prefix = Path.GetFullPath(root) + Path.DirectorySeparatorChar;- if (!full.StartsWith(prefix, StringComparison.Ordinal))- throw new PluginStoreException($"Unsafe path in the registry entry: {rel}");- return full;- }-- private static string ExtensionOf(StoreAsset asset)- {- var name = asset.Url[(asset.Url.LastIndexOf('/') + 1)..].ToLowerInvariant();- foreach (var ext in new[] { ".tar.gz", ".tar.xz", ".tar.bz2", ".tgz", ".txz", ".tar", ".zip", ".dmg", ".pkg", ".deb" })- if (name.EndsWith(ext)) return ext;- return "." + asset.Archive;- }-- private static bool IsLocal(string source, out string path)- {- if (source.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) { path = new Uri(source).LocalPath; return true; }- path = source;- return !source.Contains("://");- }-// ---- installed.json ---------------------------------------------------------------private sealed record InstalledFile(List<InstalledStorePlugin> Plugins);@@ -297,12 +195,5 @@ public sealed class PluginStore : IPluginStore}}- private void SaveInstalled() => WriteAtomic(InstalledPath, JsonSerializer.Serialize(new InstalledFile(_installed), Json));-- private static void WriteAtomic(string path, string text)- {- var tmp = path + ".tmp";- File.WriteAllText(tmp, text);- File.Move(tmp, path, overwrite: true);- }+ private void SaveInstalled() => RegistryClient.WriteAtomic(InstalledPath, JsonSerializer.Serialize(new InstalledFile(_installed), Json));}diff --git a/src/managed/Nota.Infrastructure/Registry/RegistryClient.cs b/src/managed/Nota.Infrastructure/Registry/RegistryClient.csnew file mode 100644index 00000000..b0ee8ee4--- /dev/null+++ b/src/managed/Nota.Infrastructure/Registry/RegistryClient.cs@@ -0,0 +1,144 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// What the plugin and sample stores share: one static index.json per registry (on GitHub+// Pages), cached on disk for a day and used as the offline fallback, and downloads that must+// match the size + sha256 pinned in that index before anything is unpacked. Sources may be+// URLs or local paths (tests, and the NOTA_*_REGISTRY overrides).++using System.Security.Cryptography;+using System.Text.Json;++namespace Nota.Infrastructure;++internal sealed class RegistryClient+{+ private static readonly TimeSpan CacheFreshFor = TimeSpan.FromHours(24);++ private readonly string _indexSource;+ private readonly string _cachePath;+ private readonly string _what; // "plugin registry" / "sample registry", for messages++ public RegistryClient(string indexSource, string cachePath, string what, string userAgent, HttpMessageHandler? handler)+ {+ _indexSource = indexSource;+ _cachePath = cachePath;+ _what = what;+ Http = handler is null ? new HttpClient() : new HttpClient(handler);+ Http.Timeout = Timeout.InfiniteTimeSpan; // big assets; each request carries its own token+ Http.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent);+ }++ public HttpClient Http { get; }++ /// <summary>The index JSON: the cache while it's fresh (unless <paramref name="refresh"/>),+ /// else the network, falling back to the cache when offline. <paramref name="validate"/>+ /// parses a download before it replaces the cache.</summary>+ public async Task<string> FetchIndexAsync(bool refresh, Action<string> validate, CancellationToken ct)+ {+ if (IsLocal(_indexSource, out var localPath))+ return await File.ReadAllTextAsync(localPath, ct).ConfigureAwait(false);+ if (!refresh && File.Exists(_cachePath) && DateTime.UtcNow - File.GetLastWriteTimeUtc(_cachePath) < CacheFreshFor)+ return await File.ReadAllTextAsync(_cachePath, ct).ConfigureAwait(false);+ try+ {+ using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);+ cts.CancelAfter(TimeSpan.FromSeconds(15));+ var json = await Http.GetStringAsync(_indexSource, cts.Token).ConfigureAwait(false);+ validate(json); // don't cache something unparseable+ WriteAtomic(_cachePath, json);+ return json;+ }+ catch (Exception e) when (e is HttpRequestException or TaskCanceledException && !ct.IsCancellationRequested+ || e is JsonException)+ {+ if (!File.Exists(_cachePath))+ throw new StoreException($"Couldn't reach the {_what}. Check your internet connection.", e);+ return await File.ReadAllTextAsync(_cachePath, ct).ConfigureAwait(false);+ }+ }++ /// <summary>Downloads <paramref name="url"/> to <paramref name="file"/>, reporting progress, and+ /// refuses it unless it is exactly <paramref name="size"/> bytes with the given sha256.</summary>+ public async Task DownloadAsync(string url, long size, string sha256, string file, string name,+ IProgress<StoreProgress>? progress, CancellationToken ct)+ {+ string label = $"Downloading {name}…";+ progress?.Report(new StoreProgress(0, label));+ using var sha = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);+ long total = 0;+ try+ {+ Stream src;+ HttpResponseMessage? resp = null;+ if (IsLocal(url, out var localPath)) src = File.OpenRead(localPath);+ else+ {+ resp = await Http.GetAsync(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 > size)+ throw new StoreException($"The download of {name} is larger than the registry says — not installing it.");+ sha.AppendData(buf, 0, n);+ await dst.WriteAsync(buf.AsMemory(0, n), ct).ConfigureAwait(false);+ progress?.Report(new StoreProgress((double)total / size, label));+ }+ }+ }+ catch (HttpRequestException e)+ {+ throw new StoreException($"Couldn't download {name}: {e.Message}", e);+ }++ var digest = Convert.ToHexStringLower(sha.GetHashAndReset());+ if (total != size || digest != sha256)+ throw new StoreException($"The download of {name} doesn't match the registry's checksum — not installing it.");+ }++ /// <summary>A manifest-relative path ("a/b.vst3") under root; refuses paths that escape it.</summary>+ public static string Resolve(string root, string rel)+ {+ var full = Path.GetFullPath(Path.Combine(root, rel.Replace('/', Path.DirectorySeparatorChar)));+ var prefix = Path.GetFullPath(root) + Path.DirectorySeparatorChar;+ if (!full.StartsWith(prefix, StringComparison.Ordinal))+ throw new StoreException($"Unsafe path in the registry entry: {rel}");+ return full;+ }++ /// <summary>The download's file extension (".tar.gz", ".zip", …), for the unpackers.</summary>+ public static string ExtensionOf(string url, string archive)+ {+ var name = url[(url.LastIndexOf('/') + 1)..].ToLowerInvariant();+ foreach (var ext in new[] { ".tar.gz", ".tar.xz", ".tar.bz2", ".tgz", ".txz", ".tar", ".zip", ".dmg", ".pkg", ".deb" })+ if (name.EndsWith(ext)) return ext;+ return "." + archive;+ }++ /// <summary>Registry ids are [a-z0-9-]; anything else could walk out of a store folder.</summary>+ public static bool IsValidId(string id)+ => id.Length > 0 && id.All(c => c is >= 'a' and <= 'z' or >= '0' and <= '9' or '-');++ public static bool IsLocal(string source, out string path)+ {+ if (source.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) { path = new Uri(source).LocalPath; return true; }+ path = source;+ return !source.Contains("://");+ }++ public static void WriteAtomic(string path, string text)+ {+ var tmp = path + ".tmp";+ File.WriteAllText(tmp, text);+ File.Move(tmp, path, overwrite: true);+ }+}diff --git a/src/managed/Nota.Infrastructure/SampleStore/SampleIndex.cs b/src/managed/Nota.Infrastructure/SampleStore/SampleIndex.csnew file mode 100644index 00000000..389727cd--- /dev/null+++ b/src/managed/Nota.Infrastructure/SampleStore/SampleIndex.cs@@ -0,0 +1,106 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Parses the sample registry's index.json (github.com/nota-daw/nota-samples-registry — its+// README documents the manifest), and holds the rules for which files of a pack get installed.+// Those mirror AUDIO / EXTRAS / JUNK_* in the registry's scripts/registry.py, so the+// manifest's files / unpackedSize match what Nota puts on disk.++using System.Text.Json;++namespace Nota.Infrastructure;++public static class SampleIndex+{+ /// <summary>Highest index schema this build understands.</summary>+ public const int SupportedSchema = 1;++ /// <summary>Audio the engine decodes (AudioFile.cpp picks the decoder by extension); these+ /// count as the pack's samples. Other audio (aiff, ogg) is skipped like any other file.</summary>+ public static readonly IReadOnlySet<string> AudioExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)+ { "wav", "flac", "mp3" };++ /// <summary>Docs and mappings installed alongside the samples ("" = no extension: LICENSE,+ /// README). Anything else in an archive (synth presets, Kontakt files, DAW projects) is skipped.</summary>+ public static readonly IReadOnlySet<string> ExtraExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)+ { "txt", "md", "pdf", "rtf", "html", "htm", "sfz", "mid", "midi", "png", "jpg", "jpeg", "json", "xml", "csv", "nfo", "" };++ private static readonly HashSet<string> JunkFiles = new(StringComparer.OrdinalIgnoreCase) { ".DS_Store", "Thumbs.db", "desktop.ini" };++ public static string ExtensionOf(string name)+ {+ var trimmed = name.TrimStart('.');+ int dot = trimmed.LastIndexOf('.');+ return dot < 0 ? "" : trimmed[(dot + 1)..].ToLowerInvariant();+ }++ public static bool IsJunkDir(string name) => name == "__MACOSX";++ public static bool IsJunkFile(string name) => JunkFiles.Contains(name) || name.StartsWith("._", StringComparison.Ordinal);++ /// <summary>Whether a file of a pack gets installed.</summary>+ public static bool IsInstalled(string name)+ {+ if (IsJunkFile(name)) return false;+ var ext = ExtensionOf(name);+ return AudioExtensions.Contains(ext) || ExtraExtensions.Contains(ext);+ }++ public static IReadOnlyList<StorePack> Parse(string json)+ {+ using var doc = JsonDocument.Parse(json);+ var root = doc.RootElement;+ int schema = root.TryGetProperty("schema", out var s) && s.TryGetInt32(out var n) ? n : 0;+ if (schema is < 1 or > SupportedSchema)+ throw new StoreException("The sample registry needs a newer version of Nota.");++ var list = new List<StorePack>();+ foreach (var p in root.GetProperty("packs").EnumerateArray())+ {+ try { list.Add(ParsePack(p)); }+ catch (Exception e) when (e is KeyNotFoundException or InvalidOperationException or FormatException)+ {+ // One malformed entry must not hide the rest of the registry.+ }+ }+ return list;+ }++ private static StorePack ParsePack(JsonElement p)+ {+ var latest = p.GetProperty("versions")[0];+ var a = latest.GetProperty("asset");+ string url = a.GetProperty("url").GetString()!;+ var archive = Str(a, "archive") ?? ArchiveUnpacker.KindOf(url);+ if (archive is not ("zip" or "tar")) throw new FormatException("archive type");+ var asset = new StorePackAsset(+ url,+ a.GetProperty("sha256").GetString()!.ToLowerInvariant(),+ a.GetProperty("size").GetInt64(),+ archive,+ Str(a, "root"),+ a.GetProperty("files").GetInt32(),+ a.GetProperty("unpackedSize").GetInt64(),+ a.TryGetProperty("formats", out var f) ? f.EnumerateArray().Select(x => x.GetString()!).ToList() : []);++ return new StorePack(+ Id: p.GetProperty("id").GetString()!,+ Name: p.GetProperty("name").GetString()!,+ Author: p.GetProperty("author").GetString()!,+ Description: p.GetProperty("description").GetString()!,+ Kind: p.GetProperty("kind").GetString()!,+ License: p.GetProperty("license").GetString()!,+ Source: p.GetProperty("source").GetString()!,+ Tags: p.TryGetProperty("tags", out var t) ? t.EnumerateArray().Select(x => x.GetString()!).ToList() : [],+ Version: latest.GetProperty("version").GetString()!,+ Asset: asset)+ {+ Attribution = Str(p, "attribution"),+ Notes = Str(p, "notes"),+ Homepage = Str(p, "homepage"),+ };+ }++ private static string? Str(JsonElement e, string name)+ => e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;+}diff --git a/src/managed/Nota.Infrastructure/SampleStore/SampleStore.cs b/src/managed/Nota.Infrastructure/SampleStore/SampleStore.csnew file mode 100644index 00000000..4dc3dbeb--- /dev/null+++ b/src/managed/Nota.Infrastructure/SampleStore/SampleStore.cs@@ -0,0 +1,262 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Get Samples: installs free sample packs listed in the Nota sample registry+// (github.com/nota-daw/nota-samples-registry) into the user's Samples folder, so the browser's+// Files tab lists them. Packs download straight from where their authors publish them and must+// match the size + sha256 pinned in the index before anything is unpacked (RegistryClient).+//+// Layout:+// <Samples>/Downloaded/<Pack Name>/ one folder per pack: its audio + docs, nothing else+// .nota-pack marker with the pack id; Uninstall only deletes a+// folder that carries the matching marker+// <data>/sample-store/+// registry-index.json last fetched index (offline fallback, 24 h freshness)+// installed.json what was installed where+// An install checks free space first, unpacks into a temp dir, copies the pack's audio and+// docs into Downloaded/.staging-<id> (same volume as the final folder), then swaps that in —+// a failed or cancelled install never leaves a half-copied pack behind.+// NOTA_SAMPLE_REGISTRY overrides the index URL (or points at a local index.json).++using System.Text.Json;++namespace Nota.Infrastructure;++public sealed class SampleStore : ISampleStore+{+ public const string DefaultIndexUrl = "https://nota-daw.github.io/nota-samples-registry/index.json";+ public const string MarkerFile = ".nota-pack";+ private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) { WriteIndented = true };++ private readonly string _root;+ private readonly Func<string> _samplesFolder;+ private readonly RegistryClient _registry;+ private readonly object _gate = new();+ private List<InstalledStorePack> _installed;++ public SampleStore(ISettingsService settings) : this(NotaPaths.SubDir("sample-store"), settings.ResolvedSamplesFolder) { }++ /// <param name="root">Store bookkeeping folder (tests pass a temp dir).</param>+ /// <param name="samplesFolder">The current Samples folder; read on every install, since the user can change it.</param>+ /// <param name="indexSource">Index URL or local path; defaults to NOTA_SAMPLE_REGISTRY, then the public registry.</param>+ public SampleStore(string root, Func<string> samplesFolder, string? indexSource = null, HttpMessageHandler? handler = null)+ {+ _root = root;+ _samplesFolder = samplesFolder;+ Directory.CreateDirectory(root);+ var env = Environment.GetEnvironmentVariable("NOTA_SAMPLE_REGISTRY");+ _registry = new RegistryClient(indexSource ?? (string.IsNullOrEmpty(env) ? DefaultIndexUrl : env),+ Path.Combine(root, "registry-index.json"), "sample registry", "Nota-SampleStore", handler);+ _installed = LoadInstalled();+ }++ public string InstallDir => Path.Combine(_samplesFolder(), "Downloaded");++ private string InstalledPath => Path.Combine(_root, "installed.json");++ public IReadOnlyList<InstalledStorePack> Installed+ {+ get+ {+ lock (_gate)+ {+ // A pack folder the user deleted or moved by hand is no longer installed.+ if (_installed.RemoveAll(i => !IsOurFolder(i.Path, i.Id)) > 0) SaveInstalled();+ return _installed.ToList();+ }+ }+ }++ public async Task<IReadOnlyList<StorePack>> FetchAsync(bool refresh = false, CancellationToken ct = default)+ {+ var json = await _registry.FetchIndexAsync(refresh, j => SampleIndex.Parse(j), ct).ConfigureAwait(false);+ try { return SampleIndex.Parse(json); }+ catch (JsonException e) { throw new StoreException("The sample registry index is damaged.", e); }+ }++ // ---- install / uninstall ----------------------------------------------------------++ public async Task InstallAsync(StorePack pack, IProgress<StoreProgress>? progress = null, CancellationToken ct = default)+ {+ if (!RegistryClient.IsValidId(pack.Id)) throw new StoreException($"Invalid pack id \"{pack.Id}\".");+ var asset = pack.Asset;+ var installDir = InstallDir;+ Directory.CreateDirectory(installDir);+ var work = Directory.CreateTempSubdirectory("nota-pack-").FullName;+ try+ {+ CheckFreeSpace(pack, installDir, work);++ var file = Path.Combine(work, "pack" + RegistryClient.ExtensionOf(asset.Url, asset.Archive));+ await _registry.DownloadAsync(asset.Url, asset.Size, asset.Sha256, file, pack.Name, progress, ct).ConfigureAwait(false);++ progress?.Report(new StoreProgress(-1, $"Unpacking {pack.Name}…"));+ var unpacked = Path.Combine(work, "x");+ await Task.Run(() => ArchiveUnpacker.Unpack(file, asset.Archive, unpacked, ct), ct).ConfigureAwait(false);+ try { File.Delete(file); } catch { /* temp; frees space for big packs */ }+ var packRoot = asset.Root is { } r ? RegistryClient.Resolve(unpacked, r) : unpacked;+ if (!Directory.Exists(packRoot)) throw new StoreException($"The download of {pack.Name} doesn't contain {asset.Root}.");++ var path = await Task.Run(() => Place(pack, packRoot, installDir, progress, ct), ct).ConfigureAwait(false);+ lock (_gate)+ {+ _installed.RemoveAll(i => i.Id == pack.Id);+ _installed.Add(new InstalledStorePack(pack.Id, pack.Version, asset.Sha256, path.Path, path.Files, DateTimeOffset.UtcNow));+ SaveInstalled();+ }+ }+ finally+ {+ try { Directory.Delete(work, recursive: true); } catch { /* temp; best-effort */ }+ }+ }++ public void Uninstall(string id)+ {+ if (!RegistryClient.IsValidId(id)) throw new StoreException($"Invalid pack id \"{id}\".");+ InstalledStorePack? inst;+ lock (_gate) inst = _installed.FirstOrDefault(i => i.Id == id);+ if (inst is null) return;+ try+ {+ if (IsOurFolder(inst.Path, id)) Directory.Delete(inst.Path, recursive: true);+ }+ catch (Exception e) when (e is IOException or UnauthorizedAccessException)+ {+ throw new StoreException("Couldn't remove the pack's files — close anything using them and try again.", e);+ }+ lock (_gate)+ {+ if (_installed.RemoveAll(i => i.Id == id) > 0) SaveInstalled();+ }+ }++ // Unpacking needs the archive plus its contents in temp; the pack's own folder needs its+ // unpacked size. Both checked before the download, with 5% headroom.+ private static void CheckFreeSpace(StorePack pack, string installDir, string work)+ {+ long need = pack.Asset.UnpackedSize + pack.Asset.UnpackedSize / 20;+ long needTemp = pack.Asset.Size + need;+ if (FreeBytes(installDir) is { } free && free < need)+ throw new StoreException($"{pack.Name} needs {Mb(need)} of free space in your Samples folder, which has {Mb(free)}.");+ if (FreeBytes(work) is { } freeTemp && freeTemp < needTemp)+ throw new StoreException($"Unpacking {pack.Name} needs {Mb(needTemp)} of free space on the system drive, which has {Mb(freeTemp)}.");+ }++ // Free space on the volume holding path: the drive whose root is the longest prefix of it+ // (on macOS/Linux every mount point is a "drive"). Null when it can't be told.+ private static long? FreeBytes(string path)+ {+ try+ {+ var full = Path.GetFullPath(path);+ var drive = DriveInfo.GetDrives()+ .Where(d => d.IsReady && full.StartsWith(d.RootDirectory.FullName, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))+ .MaxBy(d => d.RootDirectory.FullName.Length);+ return drive?.AvailableFreeSpace;+ }+ catch (Exception e) when (e is IOException or UnauthorizedAccessException or ArgumentException)+ {+ return null;+ }+ }++ private static string Mb(long bytes) => bytes >= 1L << 30 ? $"{bytes / (double)(1L << 30):0.0} GB" : $"{bytes / (double)(1 << 20):0} MB";++ // Copies the pack's audio + docs into Downloaded/.staging-<id>, then swaps it in for the+ // installed folder (same name on an update) or a new one named after the pack.+ private (string Path, int Files) Place(StorePack pack, string packRoot, string installDir, IProgress<StoreProgress>? progress, CancellationToken ct)+ {+ var staging = Path.Combine(installDir, ".staging-" + pack.Id);+ if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);+ Directory.CreateDirectory(staging);+ try+ {+ string label = $"Installing {pack.Name}…";+ long copied = 0, total = Math.Max(1, pack.Asset.UnpackedSize);+ int files = 0;+ progress?.Report(new StoreProgress(0, label));+ CopyPack(new DirectoryInfo(packRoot), staging, ref files, ref copied, () => progress?.Report(new StoreProgress(Math.Min(1, (double)copied / total), label)), ct);+ if (files == 0) throw new StoreException($"The download of {pack.Name} contains no samples Nota can use.");+ File.WriteAllText(Path.Combine(staging, MarkerFile), pack.Id);++ InstalledStorePack? previous;+ lock (_gate) previous = _installed.FirstOrDefault(i => i.Id == pack.Id);+ string final = previous is not null && IsOurFolder(previous.Path, pack.Id) ? previous.Path : FreeFolder(installDir, pack);+ if (Directory.Exists(final)) Directory.Delete(final, recursive: true);+ Directory.Move(staging, final);+ return (final, files);+ }+ catch+ {+ try { Directory.Delete(staging, recursive: true); } catch { /* best-effort */ }+ throw;+ }+ }++ private static void CopyPack(DirectoryInfo src, string dest, ref int files, ref long copied, Action report, CancellationToken ct)+ {+ foreach (var entry in src.EnumerateFileSystemInfos())+ {+ ct.ThrowIfCancellationRequested();+ if (entry.LinkTarget is not null) continue; // a link could point anywhere on disk+ if (entry is DirectoryInfo d)+ {+ if (SampleIndex.IsJunkDir(d.Name)) continue;+ var sub = Path.Combine(dest, d.Name);+ Directory.CreateDirectory(sub);+ CopyPack(d, sub, ref files, ref copied, report, ct);+ if (!Directory.EnumerateFileSystemEntries(sub).Any()) Directory.Delete(sub); // e.g. a presets-only folder+ }+ else if (entry is FileInfo f && SampleIndex.IsInstalled(f.Name))+ {+ f.CopyTo(Path.Combine(dest, f.Name), overwrite: true);+ copied += f.Length;+ if (SampleIndex.AudioExtensions.Contains(SampleIndex.ExtensionOf(f.Name))) files++;+ report();+ }+ }+ }++ // "<Pack Name>", or "<Pack Name> (2)" … when the user already has a folder by that name.+ private static string FreeFolder(string installDir, StorePack pack)+ {+ var name = string.Concat(pack.Name.Select(c => Path.GetInvalidFileNameChars().Contains(c) || c is '/' or '\\' or ':' ? '-' : c)).Trim().TrimEnd('.');+ if (name.Length == 0 || name.StartsWith('.')) name = pack.Id;+ var path = Path.Combine(installDir, name);+ for (int n = 2; Directory.Exists(path) || File.Exists(path); n++) path = Path.Combine(installDir, $"{name} ({n})");+ return path;+ }++ private static bool IsOurFolder(string path, string id)+ {+ try+ {+ var marker = Path.Combine(path, MarkerFile);+ return File.Exists(marker) && File.ReadAllText(marker).Trim() == id;+ }+ catch (Exception e) when (e is IOException or UnauthorizedAccessException)+ {+ return false;+ }+ }++ // ---- installed.json ---------------------------------------------------------------++ private sealed record InstalledFile(List<InstalledStorePack> Packs);++ private List<InstalledStorePack> LoadInstalled()+ {+ try+ {+ if (!File.Exists(InstalledPath)) return [];+ return JsonSerializer.Deserialize<InstalledFile>(File.ReadAllText(InstalledPath), Json)?.Packs ?? [];+ }+ catch (Exception e) when (e is JsonException or IOException)+ {+ return [];+ }+ }++ private void SaveInstalled() => RegistryClient.WriteAtomic(InstalledPath, JsonSerializer.Serialize(new InstalledFile(_installed), Json));+}diff --git a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.csindex 1da585ea..52ccaac6 100644--- a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs+++ b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs@@ -78,7 +78,9 @@ public sealed class BrowserItempublic sealed partial class BrowserViewModel : ObservableObject{- private const int MaxSamples = 2000;+ // A safety cap on the Files scan, not a browsing limit: installed sample packs alone run to+ // tens of thousands of files (the tree builds in ~150 ms for 45k).+ private const int MaxSamples = 100_000;private static readonly string[] SampleExts = { ".wav", ".flac", ".mp3" };private readonly IPluginCatalog _catalog;@@ -122,9 +124,9 @@ public sealed partial class BrowserViewModel : ObservableObjectpublic ObservableCollection<BrowserItem> Instruments { get; } = new();public ObservableCollection<BrowserItem> Effects { get; } = new();public ObservableCollection<BrowserItem> MidiEffects { get; } = new();- public ObservableCollection<BrowserItem> Samples { get; } = new();+ public BulkObservableCollection<BrowserItem> Samples { get; } = new();public ObservableCollection<BrowserItem> Projects { get; } = new();- public ObservableCollection<BrowserItem> Presets { get; } = new();+ public BulkObservableCollection<BrowserItem> Presets { get; } = new();public BrowserViewModel(IPluginCatalog catalog, IPresetLibrary presets, IFactoryPresets factory,ISettingsService? settings = null, IBrowserLibrary? library = null,@@ -649,16 +651,17 @@ public sealed partial class BrowserViewModel : ObservableObject// Shared folder-tree flatten (Files + Presets): both are Folder parents with non-folder// leaves, so the same expand/query logic applies.- private void RebuildTreeVisible(List<BrowserItem> roots, ObservableCollection<BrowserItem> dst, string q)+ private void RebuildTreeVisible(List<BrowserItem> roots, BulkObservableCollection<BrowserItem> dst, string q){- dst.Clear();- foreach (var node in roots) FlattenTree(node, q, ancestorMatched: false, dst);+ var rows = new List<BrowserItem>();+ foreach (var node in roots) FlattenTree(node, q, ancestorMatched: false, rows);+ dst.ReplaceAll(rows);}// Adds `node` (and, for folders, its visible descendants) to `dst`. Returns whether the// node ended up visible. With a query, folders auto-expand and survive only if the folder// name or some descendant matches; a folder-name hit reveals its whole subtree.- private bool FlattenTree(BrowserItem node, string q, bool ancestorMatched, ObservableCollection<BrowserItem> dst)+ private bool FlattenTree(BrowserItem node, string q, bool ancestorMatched, List<BrowserItem> dst){if (node.Kind != BrowserItemKind.Folder){diff --git a/src/managed/Nota.Presentation/ViewModels/BulkObservableCollection.cs b/src/managed/Nota.Presentation/ViewModels/BulkObservableCollection.csnew file mode 100644index 00000000..064e428c--- /dev/null+++ b/src/managed/Nota.Presentation/ViewModels/BulkObservableCollection.cs@@ -0,0 +1,23 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System.Collections.ObjectModel;+using System.Collections.Specialized;+using System.ComponentModel;++namespace Nota.Presentation;++/// <summary>An ObservableCollection whose whole contents can be swapped with one Reset+/// notification — a search over a big sample library would otherwise raise one Add per row.</summary>+public sealed class BulkObservableCollection<T> : ObservableCollection<T>+{+ public void ReplaceAll(IEnumerable<T> items)+ {+ CheckReentrancy();+ Items.Clear();+ foreach (var item in items) Items.Add(item);+ OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count)));+ OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));+ OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));+ }+}diff --git a/tests/Nota.SmokeTest/PluginStoreTests.cs b/tests/Nota.SmokeTest/PluginStoreTests.csindex 1df27105..0766d8f1 100644--- a/tests/Nota.SmokeTest/PluginStoreTests.cs+++ b/tests/Nota.SmokeTest/PluginStoreTests.cs@@ -195,7 +195,7 @@ internal static class PluginStoreTestsvar sw = System.Diagnostics.Stopwatch.StartNew();string? err = null;try { store.InstallAsync(p).GetAwaiter().GetResult(); }- catch (PluginStoreException e) { err = e.Message; }+ catch (StoreException e) { err = e.Message; }yield return (err is null, $"{id} {p.Version} ({p.Asset.Platform}, {p.Asset.Archive}{(p.Asset.Inner is null ? "" : " → pkg")}) installs in {sw.Elapsed.TotalSeconds:0.0} s {err}");if (err is not null || !File.Exists(worker)) continue;foreach (var bundle in Directory.GetFileSystemEntries(Path.Combine(store.PluginsDir, id)))@@ -263,26 +263,26 @@ internal static class PluginStoreTests// ---- helpers ----------------------------------------------------------------------------- private sealed class SyncProgress(Action<StoreProgress> report) : IProgress<StoreProgress>+ internal sealed class SyncProgress(Action<StoreProgress> report) : IProgress<StoreProgress>{public void Report(StoreProgress value) => report(value);}- private static bool Throws(Action a)+ internal static bool Throws(Action a){try { a(); return false; }- catch (PluginStoreException) { return true; }+ catch (StoreException) { return true; }}- private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));+ internal static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));- private static void Entry(ZipArchive z, string name, string text)+ internal static void Entry(ZipArchive z, string name, string text){using var s = z.CreateEntry(name).Open();s.Write(Encoding.UTF8.GetBytes(text));}- private static void WriteTarGz(string path, params (string Name, string Text)[] files)+ internal static void WriteTarGz(string path, params (string Name, string Text)[] files){using var fs = File.Create(path);using var gz = new GZipStream(fs, CompressionLevel.Fastest);diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 96c234b0..beb8c1d1 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -108,6 +108,14 @@ if (args.Length >= 1 && args[0] == "--store")Console.WriteLine(failures == 0 ? "STORE PASSED" : $"STORE FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Get Samples alone: `--samples`.+if (args.Length >= 1 && args[0] == "--samples")+{+ Console.WriteLine("-- get samples: sample registry store --");+ foreach (var (ok, label) in SampleStoreTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "SAMPLES PASSED" : $"SAMPLES FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}if (args.Length >= 3 && args[0] == "--store-catalog"){Console.WriteLine("-- get plug-ins: catalog identifiers --");@@ -13614,5 +13622,9 @@ foreach (var (ok, label) in HistoryTests.RunMcp()) Check(ok, label);Console.WriteLine("-- get plug-ins: registry store --");foreach (var (ok, label) in PluginStoreTests.Run()) Check(ok, label);+// --- get samples: sample registry index, pack install/uninstall from local archives ---+Console.WriteLine("-- get samples: sample registry store --");+foreach (var (ok, label) in SampleStoreTests.Run()) Check(ok, label);+Console.WriteLine(failures == 0 ? "SMOKE TEST PASSED" : $"SMOKE TEST FAILED ({failures})");return failures == 0 ? 0 : 1;diff --git a/tests/Nota.SmokeTest/SampleStoreTests.cs b/tests/Nota.SmokeTest/SampleStoreTests.csnew file mode 100644index 00000000..565d74df--- /dev/null+++ b/tests/Nota.SmokeTest/SampleStoreTests.cs@@ -0,0 +1,182 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Get Samples (ISampleStore): sample registry index parsing, which files of a pack get+// installed, and install / update / uninstall end to end against a local index with generated+// zip / tar.gz packs — checksum, path-escape, free-space and folder-name collisions included.+// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --samples`.++using System.IO.Compression;+using System.Text.Json;+using Nota.Application;+using Nota.Infrastructure;+using static Nota.SmokeTest.PluginStoreTests;++namespace Nota.SmokeTest;++internal static class SampleStoreTests+{+ public static IEnumerable<(bool Ok, string Label)> Run()+ {+ // ---- which files install ----------------------------------------------------------+ yield return (SampleIndex.IsInstalled("Kick 01.WAV") && SampleIndex.IsInstalled("pad.flac") && SampleIndex.IsInstalled("Piano.sfz")+ && SampleIndex.IsInstalled("LICENSE") && SampleIndex.IsInstalled("readme.txt"),+ "samples, mappings and docs install");+ yield return (!SampleIndex.IsInstalled("patch.xiz") && !SampleIndex.IsInstalled("Kit.nki") && !SampleIndex.IsInstalled("setup.exe")+ && !SampleIndex.IsInstalled(".DS_Store") && !SampleIndex.IsInstalled("._kick.wav"),+ "…presets, instruments for other samplers, programs and archive cruft don't");+ yield return (!SampleIndex.IsInstalled("pad.aiff") && !SampleIndex.IsInstalled("loop.ogg"),+ "…nor audio the engine can't decode yet");++ // ---- index parsing ----------------------------------------------------------------+ var json = IndexJson(Pack("drums", "Drums", "https://github.com/a/b/releases/download/v1/drums.tar.gz", new string('A', 64), 10,+ root: "Drums-1.0", files: 3, unpacked: 30, license: "CC-BY-4.0", attribution: "Drums by A"));+ var parsed = SampleIndex.Parse(json).Single();+ yield return (parsed.Asset is { Archive: "tar", Root: "Drums-1.0", Files: 3, UnpackedSize: 30, Size: 10 } a+ && a.Sha256 == new string('a', 64) && a.Formats.SequenceEqual(["wav"]),+ "the index yields the pack's archive (type from the URL), root and contents");+ yield return (parsed is { License: "CC-BY-4.0", Attribution: "Drums by A", Kind: "one-shots", Version: "1.0" },+ "…with its license and attribution");+ yield return (SampleIndex.Parse(json.Replace("\"packs\": [", "\"packs\": [{\"id\": \"half\"},")).Count == 1,+ "a malformed entry is skipped, not fatal");+ yield return (SampleIndex.Parse(json.Replace("drums.tar.gz", "drums.dmg")).Count == 0,+ "a pack in an archive type Nota doesn't unpack for samples is skipped");+ yield return (Throws(() => SampleIndex.Parse(json.Replace("\"schema\": 1", "\"schema\": 99"))),+ "a newer index schema asks for a newer Nota");++ // ---- install / update / uninstall end to end ----------------------------------------+ var tmp = Directory.CreateTempSubdirectory("nota-samples-test-").FullName;+ try+ {+ foreach (var r in InstallFlow(tmp)) yield return r;+ }+ finally+ {+ try { Directory.Delete(tmp, recursive: true); } catch { }+ }+ }++ private static IEnumerable<(bool, string)> InstallFlow(string tmp)+ {+ var assets = Path.Combine(tmp, "assets");+ Directory.CreateDirectory(assets);++ // A zip wrapped in one folder, with presets to skip and macOS cruft.+ var zip = Path.Combine(assets, "kit.zip");+ using (var z = System.IO.Compression.ZipFile.Open(zip, ZipArchiveMode.Create))+ {+ Entry(z, "Kit-1.0/Drums/kick.wav", "kick");+ Entry(z, "Kit-1.0/Drums/snare.flac", "snare");+ Entry(z, "Kit-1.0/Kit.sfz", "<region>");+ Entry(z, "Kit-1.0/README.txt", "hi");+ Entry(z, "Kit-1.0/Presets/Kit.nki", "kontakt");+ Entry(z, "Kit-1.0/.DS_Store", "x");+ Entry(z, "__MACOSX/Kit-1.0/._kick.wav", "x");+ }+ var zip2 = Path.Combine(assets, "kit2.zip");+ using (var z = System.IO.Compression.ZipFile.Open(zip2, ZipArchiveMode.Create))+ Entry(z, "Kit-2.0/Drums/clap.wav", "clap");+ var tgz = Path.Combine(assets, "loops.tar.gz");+ WriteTarGz(tgz, ("loop 120.mp3", "loop"), ("loop 120.ogg", "not loadable"), ("LICENSE", "CC0"));+ var noAudio = Path.Combine(assets, "presets.zip");+ using (var z = System.IO.Compression.ZipFile.Open(noAudio, ZipArchiveMode.Create))+ Entry(z, "patches/lead.xiz", "x");++ var index = Path.Combine(tmp, "index.json");+ string Packs(string kitZip, string kitVersion, string kitRoot) => IndexJson(+ Pack("kit", "Test Kit", kitZip, Sha(kitZip), new FileInfo(kitZip).Length, root: kitRoot, files: 2, unpacked: 20, version: kitVersion),+ Pack("loops", "Other Pack", tgz, Sha(tgz), new FileInfo(tgz).Length, root: null, files: 1, unpacked: 7, kind: "loops"),+ Pack("bad-sum", "Bad Sum", zip, new string('0', 64), new FileInfo(zip).Length, root: "Kit-1.0", files: 2, unpacked: 20),+ Pack("escape", "Escape", zip, Sha(zip), new FileInfo(zip).Length, root: "../..", files: 2, unpacked: 20),+ Pack("huge", "Huge", zip, Sha(zip), new FileInfo(zip).Length, root: "Kit-1.0", files: 2, unpacked: 1L << 60),+ Pack("no-audio", "No Audio", noAudio, Sha(noAudio), new FileInfo(noAudio).Length, root: null, files: 1, unpacked: 1));+ File.WriteAllText(index, Packs(zip, "1.0", "Kit-1.0"));++ var samples = Path.Combine(tmp, "My Samples");+ var root = Path.Combine(tmp, "store");+ var store = new SampleStore(root, () => samples, index);+ StorePack P(string id) => store.FetchAsync().GetAwaiter().GetResult().Single(p => p.Id == id);+ yield return (store.FetchAsync().GetAwaiter().GetResult().Count == 6, "a local index lists its packs");+ yield return (store.InstallDir == Path.Combine(samples, "Downloaded"), "packs install under Downloaded in the Samples folder");++ var reports = new List<StoreProgress>();+ store.InstallAsync(P("kit"), new SyncProgress(reports.Add)).GetAwaiter().GetResult();+ var kit = Path.Combine(samples, "Downloaded", "Test Kit");+ yield return (File.Exists(Path.Combine(kit, "Drums", "kick.wav")) && File.Exists(Path.Combine(kit, "Drums", "snare.flac")),+ "a zip installs into a folder named after the pack, its wrapper folder dropped");+ yield return (File.Exists(Path.Combine(kit, "Kit.sfz")) && File.Exists(Path.Combine(kit, "README.txt")),+ "…mappings and docs come along");+ yield return (!Directory.Exists(Path.Combine(kit, "Presets")) && !File.Exists(Path.Combine(kit, ".DS_Store")) && !Directory.Exists(Path.Combine(samples, "Downloaded", "__MACOSX")),+ "…presets and archive cruft don't, and a folder left empty isn't created");+ yield return (reports.Any(r => r.Message.StartsWith("Downloading") && r.Fraction >= 0.99)+ && reports.Any(r => r.Message.StartsWith("Unpacking")) && reports.Any(r => r.Message.StartsWith("Installing")),+ "install reports the download, unpack and copy stages");+ yield return (store.Installed.SingleOrDefault(i => i.Id == "kit") is { Version: "1.0", Files: 2 } inst && inst.Path == kit,+ "the install is recorded with its version, folder and sample count");+ yield return (new SampleStore(root, () => samples, index).Installed.Any(i => i.Id == "kit"),+ "…and survives a restart (installed.json)");+ yield return (!Directory.EnumerateDirectories(store.InstallDir, ".staging-*").Any(), "no staging folder is left behind");++ // The user already has a folder named like the next pack: it gets a numbered sibling.+ var mine = Path.Combine(samples, "Downloaded", "Other Pack");+ Directory.CreateDirectory(mine);+ File.WriteAllText(Path.Combine(mine, "mine.wav"), "mine");+ store.InstallAsync(P("loops")).GetAwaiter().GetResult();+ var other = Path.Combine(samples, "Downloaded", "Other Pack (2)");+ yield return (File.Exists(Path.Combine(other, "loop 120.mp3")) && File.Exists(Path.Combine(mine, "mine.wav")),+ "a tar.gz installs beside a same-named user folder without touching it");+ yield return (!File.Exists(Path.Combine(other, "loop 120.ogg")) && File.Exists(Path.Combine(other, "LICENSE")),+ "…skipping audio the engine can't load, keeping the license");++ // Update: a new version replaces the pack's files in the same folder.+ File.WriteAllText(index, Packs(zip2, "2.0", "Kit-2.0"));+ store.InstallAsync(P("kit")).GetAwaiter().GetResult();+ yield return (File.Exists(Path.Combine(kit, "Drums", "clap.wav")) && !File.Exists(Path.Combine(kit, "Drums", "kick.wav"))+ && store.Installed.Single(i => i.Id == "kit").Version == "2.0",+ "an update replaces the pack's files in place");++ yield return (Throws(() => store.InstallAsync(P("bad-sum")).GetAwaiter().GetResult()) && !Directory.Exists(Path.Combine(samples, "Downloaded", "Bad Sum")),+ "a checksum mismatch is refused, nothing installed");+ yield return (Throws(() => store.InstallAsync(P("escape")).GetAwaiter().GetResult()) && !Directory.Exists(Path.Combine(samples, "Downloaded", "Escape")),+ "a root that climbs out of the archive is refused");+ yield return (Throws(() => store.InstallAsync(P("huge")).GetAwaiter().GetResult()), "a pack bigger than the free space is refused up front");+ yield return (Throws(() => store.InstallAsync(P("no-audio")).GetAwaiter().GetResult()) && !Directory.Exists(Path.Combine(samples, "Downloaded", "No Audio")),+ "an archive with no usable samples installs nothing");+ yield return (!Directory.EnumerateDirectories(store.InstallDir, ".staging-*").Any(), "…and failed installs leave no staging folder");++ store.Uninstall("kit");+ yield return (!Directory.Exists(kit) && store.Installed.All(i => i.Id != "kit"), "uninstall removes the pack's folder");+ yield return (Throws(() => store.Uninstall("../x")), "uninstall refuses ids that aren't registry ids");++ // A pack folder whose marker is gone (the user replaced it) is forgotten, never deleted.+ var loops = store.Installed.Single(i => i.Id == "loops").Path;+ File.Delete(Path.Combine(loops, SampleStore.MarkerFile));+ store.Uninstall("loops");+ yield return (Directory.Exists(loops) && store.Installed.All(i => i.Id != "loops"),+ "a folder without its pack marker is dropped from the list but not deleted");++ var offline = new SampleStore(Path.Combine(tmp, "store2"), () => samples, "https://127.0.0.1:1/index.json");+ yield return (Throws(() => offline.FetchAsync().GetAwaiter().GetResult()), "offline with no cache is a clear error");+ }++ private static string IndexJson(params string[] packs)+ => $"{{\n\"schema\": 1,\n\"generated\": \"2026-01-01T00:00:00Z\",\n\"packs\": [{string.Join(",", packs)}]\n}}";++ private static string Pack(string id, string name, string url, string sha, long size, string? root, int files, long unpacked,+ string version = "1.0", string kind = "one-shots", string license = "CC0-1.0", string? attribution = null)+ {+ var asset = new Dictionary<string, object?>+ {+ ["url"] = url, ["sha256"] = sha, ["size"] = size, ["files"] = files, ["unpackedSize"] = unpacked, ["formats"] = new[] { "wav" },+ };+ if (root is not null) asset["root"] = root;+ var pack = new Dictionary<string, object?>+ {+ ["id"] = id, ["name"] = name, ["author"] = "Test", ["description"] = "A test pack.", ["source"] = "https://example.com",+ ["license"] = license, ["kind"] = kind, ["tags"] = new[] { "test" },+ ["versions"] = new[] { new Dictionary<string, object?> { ["version"] = version, ["asset"] = asset } },+ };+ if (attribution is not null) pack["attribution"] = attribution;+ return JsonSerializer.Serialize(pack);+ }+}