RynthCore as of 2026-10-04 (internal 843c801): RynthNav auto-travel and the navigation map, plugin API v75 (server and titles), launcher with Available plugins, download progress and the update on the front page, opt-in usage statistics, NPC names, radar colours, title-bar text size, FPS limiter, client action unlocks, release 2026.10.4.6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-10-04 18:34:27 -04:00
commit a24ed6df7c
322 changed files with 83009 additions and 7504 deletions

View file

@ -0,0 +1,128 @@
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using RynthCore.App;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Small code-built dialogs for the Decal bridge: the "Check Decal bridge" report (with
/// Repair / Copy) and the yes/no before the one administrator step.
/// </summary>
internal static class DecalBridgeDialog
{
private static readonly IBrush Back = new SolidColorBrush(Color.Parse("#132028"));
private static readonly IBrush Text = new SolidColorBrush(Color.Parse("#EAF0F4"));
private static readonly IBrush Muted = new SolidColorBrush(Color.Parse("#9AA8B3"));
private static readonly IBrush Accent = new SolidColorBrush(Color.Parse("#26C1A6"));
/// <summary>Yes/no. True = the person pressed <paramref name="yes"/>.</summary>
public static async Task<bool> AskAsync(Window owner, string title, string message, string yes, string no)
{
var dialog = NewWindow(title, 560);
var yesButton = new Button { Content = yes, IsDefault = true };
var noButton = new Button { Content = no, IsCancel = true };
yesButton.Click += (_, _) => dialog.Close(true);
noButton.Click += (_, _) => dialog.Close(false);
dialog.Content = Layout(title,
new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap, Foreground = Text },
yesButton, noButton);
bool? result = await dialog.ShowDialog<bool?>(owner);
return result == true;
}
/// <summary>
/// Shows the check's report. With <paramref name="offerRepair"/>, a Repair button; returns
/// true when the person pressed it.
/// </summary>
public static async Task<bool> ShowReportAsync(Window owner, DecalBridgeCheck.Result check, bool offerRepair)
{
string title = check.Blocking ? "Decal bridge check: it would NOT load" : "Decal bridge check: OK";
string report = check.ToReport();
var dialog = NewWindow(title, 760);
var body = new TextBox
{
Text = report,
IsReadOnly = true,
TextWrapping = TextWrapping.Wrap,
FontFamily = new FontFamily("Consolas, Cascadia Mono, monospace"),
FontSize = 12,
MaxHeight = 420,
Foreground = Text,
Background = new SolidColorBrush(Color.Parse("#0F161D")),
};
var copy = new Button { Content = "Copy report" };
copy.Click += async (_, _) =>
{
try
{
var clipboard = TopLevel.GetTopLevel(dialog)?.Clipboard;
if (clipboard != null) await clipboard.SetTextAsync(report);
copy.Content = "Copied";
}
catch { copy.Content = "Copy failed"; }
};
var close = new Button { Content = "Close", IsCancel = true };
close.Click += (_, _) => dialog.Close(false);
Control[] buttons;
if (offerRepair)
{
var repair = new Button { Content = check.NeedsMachineWideRegistration ? "Repair (asks for administrator)" : "Repair", IsDefault = true };
repair.Click += (_, _) => dialog.Close(true);
buttons = new Control[] { repair, copy, close };
}
else
{
buttons = new Control[] { copy, close };
}
string hint = check.Blocking
? "A Decal + RynthCore client started now would run without the bridge: no RynthCore overlay, then a crash. " +
(offerRepair ? "Repair registers the bridge where Decal reads on this PC and checks again." : "Fix the FAIL lines, then check again.")
: "A Decal + RynthCore client started now will load the bridge.";
dialog.Content = Layout(title,
new StackPanel
{
Spacing = 8,
Children =
{
new TextBlock { Text = hint, TextWrapping = TextWrapping.Wrap, Foreground = Muted },
body,
},
},
buttons);
bool? result = await dialog.ShowDialog<bool?>(owner);
return result == true;
}
private static Window NewWindow(string title, double width) => new()
{
Title = title,
Width = width,
SizeToContent = SizeToContent.Height,
CanResize = false,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Background = Back,
};
private static Control Layout(string title, Control body, params Control[] buttons)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right };
foreach (Control b in buttons) row.Children.Add(b);
return new StackPanel
{
Margin = new Thickness(18),
Spacing = 12,
Children =
{
new TextBlock { Text = title, FontSize = 16, FontWeight = FontWeight.SemiBold, Foreground = Accent },
body,
row,
},
};
}
}

View file

@ -0,0 +1,146 @@
using System;
using System.Diagnostics;
using System.Globalization;
namespace RynthCore.App.Avalonia;
/// <summary>The step a launcher download is on.</summary>
public enum DownloadStage
{
/// <summary>Bytes arriving: Done/Total are bytes, against the signed size from the feed.</summary>
Downloading,
/// <summary>The download finished and matched the signed size and SHA-256.</summary>
Verified,
/// <summary>Unpacking an archive: Done/Total are files.</summary>
Unpacking,
/// <summary>Putting the files in place (no measurable progress).</summary>
Installing,
}
/// <summary>
/// One progress report for the launcher's download area. <see cref="What"/> names the download
/// ("RynthNav map", "RynthOracle", "RynthCore 2026.10.5.1"). Reports come from the updater at a
/// few a second at most (<see cref="DownloadMeter"/>); the first, the last and every stage change
/// always come through.
/// </summary>
public sealed record DownloadProgress(string What, DownloadStage Stage, long Done, long Total,
double BytesPerSecond = 0, TimeSpan? Remaining = null, TimeSpan Elapsed = default)
{
/// <summary>0..100, or null when the step has no measurable progress.</summary>
public double? Percent => Total > 0 ? Math.Clamp(Done * 100.0 / Total, 0, 100) : null;
/// <summary>The line under the progress bar.</summary>
public string Detail => Stage switch
{
DownloadStage.Downloading => FormatDownloading(),
DownloadStage.Verified => $"{FormatMb(Total)} downloaded and verified against the signed feed.",
DownloadStage.Unpacking => Total > 0
? $"Unpacking {Done.ToString("N0", CultureInfo.InvariantCulture)} of {Total.ToString("N0", CultureInfo.InvariantCulture)} files…"
: "Unpacking…",
_ => "Installing…",
};
/// <summary>The activity-log line when a download is done: "RynthNav map: 539 MB in 2m10s, verified".</summary>
public string Summary => $"{What}: {FormatMb(Total)} in {FormatDuration(Elapsed)}, verified";
private string FormatDownloading()
{
string s = $"{FormatMb(Done, withUnit: false)} of {FormatMb(Total)}";
if (BytesPerSecond > 0) s += $" · {FormatMb((long)BytesPerSecond)}/s";
if (Remaining is { } r) s += $" · about {FormatDuration(r)} left";
return s;
}
/// <summary>"539 MB", "12.4 MB", "0.3 MB" (one decimal under 100 MB).</summary>
public static string FormatMb(long bytes, bool withUnit = true)
{
double mb = bytes / (1024.0 * 1024.0);
string n = mb >= 100 ? mb.ToString("N0", CultureInfo.InvariantCulture) : mb.ToString("0.0", CultureInfo.InvariantCulture);
return withUnit ? n + " MB" : n;
}
/// <summary>"8s", "2m10s", "1h05m".</summary>
public static string FormatDuration(TimeSpan t)
{
if (t < TimeSpan.Zero) t = TimeSpan.Zero;
if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h{t.Minutes:00}m";
if (t.TotalMinutes >= 1) return $"{(int)t.TotalMinutes}m{t.Seconds:00}s";
return $"{Math.Max(0, (int)Math.Round(t.TotalSeconds))}s";
}
}
/// <summary>
/// Measures one download: speed over the last few seconds, time left, and throttling so the UI
/// gets a handful of reports a second rather than one per 80 KB read. The clock is injectable
/// for tests.
/// </summary>
public sealed class DownloadMeter
{
public static readonly TimeSpan ReportEvery = TimeSpan.FromMilliseconds(250);
private static readonly TimeSpan SpeedWindow = TimeSpan.FromSeconds(4);
private readonly string _what;
private readonly long _total;
private readonly IProgress<DownloadProgress>? _progress;
private readonly Func<TimeSpan> _clock;
private readonly TimeSpan _start;
private TimeSpan _lastReport = TimeSpan.MinValue;
// A ring of (time, bytes) samples for the speed over the last few seconds.
private readonly (TimeSpan T, long Bytes)[] _samples = new (TimeSpan, long)[32];
private int _sampleCount, _sampleHead;
public DownloadMeter(string what, long total, IProgress<DownloadProgress>? progress, Func<TimeSpan>? clock = null)
{
_what = what;
_total = total;
_progress = progress;
if (clock == null)
{
var sw = Stopwatch.StartNew();
clock = () => sw.Elapsed;
}
_clock = clock;
_start = _clock();
AddSample(_start, 0);
}
public TimeSpan Elapsed => _clock() - _start;
/// <summary>Called after each read; reports at most every <see cref="ReportEvery"/>, and always at the end.</summary>
public void Report(long done)
{
if (_progress == null) return;
TimeSpan now = _clock();
bool last = done >= _total;
if (!last && _lastReport != TimeSpan.MinValue && now - _lastReport < ReportEvery) return;
_lastReport = now;
AddSample(now, done);
double speed = Speed(now, done);
TimeSpan? remaining = speed > 0 && !last ? TimeSpan.FromSeconds((_total - done) / speed) : last ? TimeSpan.Zero : null;
_progress.Report(new DownloadProgress(_what, DownloadStage.Downloading, done, _total, speed, remaining, now - _start));
}
/// <summary>The download matched the signed size and hash.</summary>
public void Verified() =>
_progress?.Report(new DownloadProgress(_what, DownloadStage.Verified, _total, _total, 0, TimeSpan.Zero, Elapsed));
private void AddSample(TimeSpan t, long bytes)
{
_samples[_sampleHead] = (t, bytes);
_sampleHead = (_sampleHead + 1) % _samples.Length;
if (_sampleCount < _samples.Length) _sampleCount++;
}
private double Speed(TimeSpan now, long done)
{
// The oldest sample still inside the window (or the oldest kept) is the baseline.
(TimeSpan T, long Bytes) baseline = (now, done);
for (int i = 0; i < _sampleCount; i++)
{
var s = _samples[(_sampleHead - _sampleCount + i + _samples.Length) % _samples.Length];
if (now - s.T <= SpeedWindow || i == _sampleCount - 1) { baseline = s; break; }
}
double secs = (now - baseline.T).TotalSeconds;
return secs > 0.05 ? (done - baseline.Bytes) / secs : 0;
}
}

View file

@ -108,10 +108,39 @@
</Border>
<Grid Grid.Row="1" ColumnDefinitions="3*,Auto,2*">
<TabControl Grid.Column="0" Margin="14,0,0,0" Padding="0">
<TabControl x:Name="MainTabs" Grid.Column="0" Margin="14,0,0,0" Padding="0">
<TabItem Header="Launcher">
<ScrollViewer>
<StackPanel Spacing="12" Margin="6">
<!-- Updates: the card is built by UpdateCardModel (MainWindow.RefreshUpdateCard). -->
<Border x:Name="UpdateCardBorder" Background="#132028" CornerRadius="16" Padding="18"
BorderBrush="#243742" BorderThickness="1">
<StackPanel Spacing="8">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Grid.Column="0" Spacing="4" VerticalAlignment="Center">
<TextBlock x:Name="UpdateCardTitle" Text="Updates" FontSize="16" FontWeight="SemiBold"
Foreground="#26C1A6" TextWrapping="Wrap" />
<TextBlock x:Name="UpdateCardDetail" Text="Not checked yet." TextWrapping="Wrap" Foreground="#9AA8B3" />
</StackPanel>
<WrapPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Top" Margin="12,0,0,0">
<Button x:Name="UpdateCardActionButton" IsVisible="False" Margin="0,0,8,6"
Background="#26C1A6" Foreground="#0B1218" FontWeight="SemiBold" />
<Button x:Name="CheckUpdatesButton" Content="Check for updates" Margin="0,0,0,6" />
</WrapPanel>
</Grid>
<StackPanel x:Name="UpdateCardWhatsNewPanel" Spacing="2" IsVisible="False" />
<Grid x:Name="DownloadArea" ColumnDefinitions="*,Auto" IsVisible="False">
<ProgressBar x:Name="DownloadProgressBar" Grid.Column="0" Minimum="0" Maximum="100"
Height="10" MinHeight="10" VerticalAlignment="Center"
Foreground="#26C1A6" Background="#0F161D" />
<Button x:Name="CancelDownloadButton" Grid.Column="1" Content="Cancel" Margin="10,0,0,0"
ToolTip.Tip="Stops the download. Nothing half-installed is left behind: the partial file is deleted and what you have stays as it is." />
</Grid>
<Button x:Name="UpdateCardNewPluginsButton" IsVisible="False" HorizontalAlignment="Left"
Background="Transparent" BorderThickness="0" Padding="0" Foreground="#F2C14E" />
</StackPanel>
</Border>
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Launch Targets" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
@ -234,36 +263,58 @@
</ScrollViewer>
</TabItem>
<TabItem Header="Plugins">
<ScrollViewer>
<TabItem x:Name="PluginsTab" Header="Plugins">
<ScrollViewer x:Name="PluginsScroll">
<StackPanel Spacing="12" Margin="6">
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Updates" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
<!-- Compact: the update card with its buttons is on the Launcher tab. -->
<TextBlock x:Name="UpdateStatusText"
Text="Not checked yet."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<WrapPanel Orientation="Horizontal">
<Button x:Name="CheckUpdatesButton" Content="Check for updates" Margin="0,0,8,6" />
<Button x:Name="UpdatePluginsButton" Content="Update plugins" IsVisible="False" Margin="0,0,8,6" />
<Button x:Name="InstallCoreUpdateButton" Content="Install RynthCore update" IsVisible="False" Margin="0,0,8,6" />
</WrapPanel>
<ProgressBar x:Name="PluginsTabProgressBar" Minimum="0" Maximum="100" Height="6" MinHeight="6"
IsVisible="False" Foreground="#26C1A6" Background="#0F161D" />
<Button x:Name="ShowUpdateCardButton" Content="Updates on the Launcher tab" HorizontalAlignment="Left"
Background="Transparent" BorderThickness="0" Padding="0" Foreground="#26C1A6" />
<CheckBox x:Name="AutoUpdatePluginsCheckBox"
Content="Update plugins automatically (a running bot keeps its version until AC restarts)"
Foreground="#EAF0F4" />
</StackPanel>
</Border>
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Usage statistics" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
<CheckBox x:Name="UsageStatsCheckBox"
Content="Help improve RynthCore: send an anonymous usage report once a day"
Foreground="#EAF0F4" />
<TextBlock x:Name="UsageStatsWhatText" TextWrapping="Wrap" Foreground="#9AA8B3" />
<TextBlock x:Name="UsageStatsNeverText" TextWrapping="Wrap" Foreground="#9AA8B3" />
<TextBlock x:Name="UsageStatsStopText" TextWrapping="Wrap" Foreground="#9AA8B3" />
<Button x:Name="ShowUsageReportButton" Content="Show what is sent" HorizontalAlignment="Left" />
</StackPanel>
</Border>
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Plugins" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
<TextBlock Text="Manage the runtime modules loaded into RynthCore. Add plugins by browsing for their DLL file."
<TextBlock Text="The plugins RynthCore loads. Untick one to skip it; the X takes it out of the list (its files stay on disk). RynthSuite plugins you don't have are under Available plugins below; Add Plugin is for any other plugin DLL."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<StackPanel x:Name="PluginLoadoutPanel" Spacing="10" />
<Button x:Name="AddPluginDllButton" Content="Add Plugin" HorizontalAlignment="Left" />
</StackPanel>
</Border>
<Border x:Name="AvailablePluginsBorder" Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Available plugins" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
<TextBlock x:Name="AvailablePluginsHint"
Text="Plugins you can add appear here after the first update check."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<StackPanel x:Name="AvailablePluginsPanel" Spacing="10" />
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
</TabItem>
@ -352,6 +403,9 @@
<CheckBox x:Name="EnableDcompOverlayCheckBox"
Content="Use DComp overlay (experimental, GPU-rendered)"
ToolTip.Tip="When ON, the engine starts the new DirectComposition overlay instead of the production AvaloniaOverlay. Mutually exclusive — Avalonia is single-app-per-process. Toggle takes effect on next AC client launch (a hot reload won't switch overlays)." />
<CheckBox x:Name="EnableImGuiBackendCheckBox"
Content="ImGui panels (preview)"
ToolTip.Tip="When ON, the engine runs its in-client ImGui layer, which docked panels move to as their ImGui versions are finished (choose per panel with /rc ui). Popped-out panels stay Avalonia windows. Costs nothing while no ImGui panel is open. Takes effect on next AC client launch or engine reload (RL)." />
</StackPanel>
</Border>
@ -366,6 +420,8 @@
<Button x:Name="RefreshSessionsButton" Content="Refresh Sessions" Margin="0,0,8,8" />
<Button x:Name="ResetOverlayBarButton" Content="Reset Overlay Bar" Margin="0,0,8,8"
ToolTip.Tip="Drags the in-game RynthCore overlay bar back to the top-left corner. Use this if the bar was moved off-screen and can no longer be reached. Applies to every running RynthCore client." />
<Button x:Name="CheckDecalBridgeButton" Content="Check Decal bridge" Margin="0,0,8,8"
ToolTip.Tip="For Decal + RynthCore (experimental): checks whether a client started now will load the RynthCore Decal bridge - where Decal reads its plugin list on this PC, whether the bridge is listed and enabled there, Decal's version and its .NET part. Changes nothing unless you press Repair." />
</WrapPanel>
<TextBlock Text="Manual inject targets the first detected acclient.exe session. Reset Overlay Bar signals all running RynthCore clients via the dispatch file."
TextWrapping="Wrap"

File diff suppressed because it is too large Load diff

View file

@ -7,7 +7,67 @@ namespace RynthCore.App.Avalonia;
internal static class Program
{
[STAThread]
public static void Main(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
public static int Main(string[] args)
{
// The uninstaller removes the Decal bridge registration (docs/DECAL_BRIDGE_PLAN.md):
// no window, just the per-user registry entries this launcher added.
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-unregister", StringComparison.OrdinalIgnoreCase)))
{
bool ok = RynthCore.App.DecalBridgeRegistration.Unregister(out string report);
LauncherDiag.Info($"DECALBRIDGE: unregister (command line): {report}");
// A machine-wide entry (added with administrator rights when AC runs elevated on this
// PC) goes too: the uninstaller removes the DLL it points at. Ask for the rights only
// when there is one.
if (RynthCore.App.DecalBridgeRegistration.MachineEntryIsOurs())
{
var outcome = RynthCore.App.DecalBridgeRegistration.UnregisterMachineWide(out string mReport);
if (outcome == RynthCore.App.DecalBridgeRegistration.Outcome.NeedsAdmin && Environment.ProcessPath is string self)
outcome = RynthCore.App.DecalBridgeRegistration.RunElevated(self, "--decal-bridge-unregister-machine", out mReport);
LauncherDiag.Info($"DECALBRIDGE: unregister machine-wide (command line): {mReport}");
ok &= outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered;
}
return ok ? 0 : 1;
}
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-unregister-machine", StringComparison.OrdinalIgnoreCase)))
{
var outcome = RynthCore.App.DecalBridgeRegistration.UnregisterMachineWide(out string report);
LauncherDiag.Info($"DECALBRIDGE: unregister machine-wide (elevated step): {report}");
return outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered ? 0 : 1;
}
// The launcher's elevated step for "AC reads Decal's filter list for all users"
// (MainWindow.EnsureDecalBridgeAsync): --decal-bridge-register-machine "<bridge folder>".
int rm = Array.FindIndex(args, a => string.Equals(a, "--decal-bridge-register-machine", StringComparison.OrdinalIgnoreCase));
if (rm >= 0)
{
string dir = rm + 1 < args.Length ? args[rm + 1] : RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory;
var outcome = RynthCore.App.DecalBridgeRegistration.RegisterMachineWide(dir, out string report);
LauncherDiag.Info($"DECALBRIDGE: register machine-wide (elevated step): {report}");
return outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered ? 0 : 1;
}
// The installer's per-user half (installer\RynthCore.iss, as the installing user, every
// install and update): our entry into an EXISTING per-user copy of Decal's filter list.
int iu = Array.FindIndex(args, a => string.Equals(a, "--decal-bridge-install-user", StringComparison.OrdinalIgnoreCase));
if (iu >= 0)
{
string dir = iu + 1 < args.Length ? args[iu + 1] : RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory;
bool ok = RynthCore.App.DecalBridgeRegistration.InstallPerUser(dir, out string report);
LauncherDiag.Info($"DECALBRIDGE: install per-user (installer): {report}");
return ok ? 0 : 1;
}
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-status", StringComparison.OrdinalIgnoreCase)))
{
LauncherDiag.Info($"DECALBRIDGE: status (command line): {RynthCore.App.DecalBridgeRegistration.GetStatus()}");
return 0;
}
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-check", StringComparison.OrdinalIgnoreCase)))
{
var check = RynthCore.App.RealDecalCheckHost.Check(RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory,
RynthCore.App.DecalLocator.TryGetDecalAcClientPath(), EngineJsonStore.Path);
LauncherDiag.Info($"DECALBRIDGE: check (command line):{Environment.NewLine}{check.ToReport()}");
return check.Blocking ? 1 : 0;
}
return BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()

View file

@ -32,6 +32,9 @@
<Compile Include="..\RynthCore.App\LaunchAccountProfile.cs" Link="Shared\LaunchAccountProfile.cs" />
<Compile Include="..\RynthCore.App\InjectionMode.cs" Link="Shared\InjectionMode.cs" />
<Compile Include="..\RynthCore.App\DecalLocator.cs" Link="Shared\DecalLocator.cs" />
<Compile Include="..\RynthCore.App\DecalBridgeRegistration.cs" Link="Shared\DecalBridgeRegistration.cs" />
<Compile Include="..\RynthCore.App\DecalBridgeCheck.cs" Link="Shared\DecalBridgeCheck.cs" />
<Compile Include="..\RynthCore.App\RealDecalCheckHost.cs" Link="Shared\RealDecalCheckHost.cs" />
<Compile Include="..\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="Shared\AcLaunchArgumentBuilder.cs" />
<Compile Include="..\RynthCore.App\AcClientLaunchSettingsService.cs" Link="Shared\AcClientLaunchSettingsService.cs" />
<Compile Include="..\RynthCore.App\AcClientLoginAutomationService.cs" Link="Shared\AcClientLoginAutomationService.cs" />
@ -41,6 +44,7 @@
<Compile Include="..\RynthCore.App\BuildVersion.cs" Link="Shared\BuildVersion.cs" />
<Compile Include="..\RynthCore.App\AppSettings.cs" Link="Shared\AppSettings.cs" />
<Compile Include="..\RynthCore.App\AppSettingsStore.cs" Link="Shared\AppSettingsStore.cs" />
<Compile Include="..\RynthCore.App\DecalAccountModes.cs" Link="Shared\DecalAccountModes.cs" />
<Compile Include="..\RynthCore.App\PluginDefinition.cs" Link="Shared\PluginDefinition.cs" />
<Compile Include="..\RynthCore.Injector\EngineInjectionService.cs" Link="Shared\EngineInjectionService.cs" />
<Compile Include="..\RynthCore.Injector\InjectionResult.cs" Link="Shared\InjectionResult.cs" />

View file

@ -0,0 +1,301 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.App.Avalonia;
/// <summary>
/// "Available plugins": every plugin in the signed feed that isn't in the player's plugin list,
/// for the player to install or not.
///
/// Install downloads the feed's file (verified against the signed size and SHA-256, like every
/// update) into C:\Games\RynthSuite\&lt;Name&gt;\&lt;File&gt; - the folder beside RynthAi's, or the
/// default - and the caller adds it to the plugin list. Only plugins named in the signed manifest
/// can be installed, from the URLs it carries; nothing else.
///
/// Removing a plugin from the list never deletes its files; a feed plugin that leaves the list is
/// simply available again.
///
/// "New": a plugin the launcher sees in the feed for the first time is marked New for a month and
/// said once in the activity log. The first time this runs (no update-seen-plugins.json yet),
/// what the feed already had counts as old except <see cref="RecentlyAdded"/>, which a player
/// who never got them should hear about.
/// </summary>
internal sealed partial class RynthUpdater
{
public const string DefaultSuiteDir = @"C:\Games\RynthSuite";
private const string RynthAiFile = "RynthCore.Plugin.RynthAi.dll";
private const int MaxDescriptionLength = 160;
private const int MaxChanges = 20;
private static readonly TimeSpan NewBadgeFor = TimeSpan.FromDays(30);
private static readonly Regex SafeFolderName = new(@"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", RegexOptions.CultureInvariant);
/// <summary>A feed plugin the player can install: where it would go, what it is, and whether it's new.</summary>
public sealed record AvailablePlugin(PluginEntry Entry, string Path, string Description, string Version, bool IsNew);
/// <summary>What <see cref="InstallPluginAsync"/> did: Downloaded is false when a good copy was already there.</summary>
public sealed record PluginInstall(PluginEntry Entry, string Path, string Description, bool Downloaded);
/// <summary>
/// Plugins new in the feed before this list existed (2026.10.3.4). 2026.10.4.3 installed them
/// beside RynthAi automatically; from this launcher on they are offered, not forced.
/// </summary>
private static readonly string[] RecentlyAdded = { "RynthOracle", "RynthInventory" };
/// <summary>One line per plugin for feeds that carry no "description" (every feed before 2026.10.5).</summary>
private static readonly Dictionary<string, string> BuiltInDescriptions = new(StringComparer.OrdinalIgnoreCase)
{
["RynthAi"] = "The bot: combat, buffs, looting, navigation routes and metas.",
["RynthChat"] = "A chat window that sorts messages into tabs.",
["RynthTracker"] = "Kills, experience and luminance per hour for each session.",
["RynthNav"] = "Walks you to coordinates and towns, with route planning and the Atlas. Downloads its map (about 540 MB).",
["RynthVision"] = "Shows unclimbable slopes, impassable water and your radar range in the world.",
["RynthLua"] = "Lua scripting for metas and your own scripts.",
["RynthOracle"] = "Quests, character, titles and leaderboards.",
["RynthInventory"] = "Search every character's items.",
};
/// <summary>The feed's description, else the launcher's own line, else "".</summary>
public static string DescribePlugin(PluginEntry e) =>
e.Description.Length > 0 ? e.Description
: BuiltInDescriptions.TryGetValue(e.Name, out string? d) ? d : "";
private string? _suiteDirOverride;
/// <summary>Tests: the folder to use when no plugin in the list shows where RynthSuite lives.</summary>
internal void SetDefaultSuiteDir(string dir) => _suiteDirOverride = dir;
/// <summary>Tests: the clock for the New badge.</summary>
internal Func<DateTime> UtcNow { get; set; } = () => DateTime.UtcNow;
/// <summary>
/// Where RynthSuite plugins go: beside RynthAi (C:\Games\RynthSuite\RynthAi\x.dll -> C:\Games\RynthSuite),
/// else beside any feed plugin that sits in a folder named after it, else the default.
/// </summary>
public string SuiteDir(Manifest manifest, IEnumerable<string> pluginPaths)
{
List<string> paths = pluginPaths.ToList();
string? FromPlugin(string path)
{
string? folder = Path.GetDirectoryName(path);
string? suite = Path.GetDirectoryName(folder);
return string.IsNullOrEmpty(folder) || string.IsNullOrEmpty(suite) ? null : suite;
}
string? ai = paths.FirstOrDefault(p => string.Equals(Path.GetFileName(p), RynthAiFile, StringComparison.OrdinalIgnoreCase));
if (ai != null && FromPlugin(ai) is { } s1) return s1;
foreach (string p in paths)
{
PluginEntry? e = manifest.Plugins.FirstOrDefault(x => string.Equals(x.File, Path.GetFileName(p), StringComparison.OrdinalIgnoreCase));
if (e != null && string.Equals(Path.GetFileName(Path.GetDirectoryName(p)), e.Name, StringComparison.OrdinalIgnoreCase)
&& FromPlugin(p) is { } s2)
return s2;
}
return _suiteDirOverride ?? DefaultSuiteDir;
}
/// <summary>C:\Games\RynthSuite\&lt;Name&gt;\&lt;File&gt;; null for a name that isn't a plain folder name.</summary>
private static string? TargetPath(PluginEntry e, string suiteDir) =>
SafeFolderName.IsMatch(e.Name) && e.Name != "." && e.Name != ".." ? Path.Combine(suiteDir, e.Name, e.File) : null;
/// <summary>
/// Every feed plugin whose file isn't in <paramref name="pluginPaths"/> (by file name, like the
/// updates), except companions about to be installed anyway.
/// </summary>
public List<AvailablePlugin> GetAvailable(Manifest manifest, IEnumerable<string> pluginPaths, IEnumerable<CompanionInstall>? pending = null)
{
List<string> paths = pluginPaths.ToList();
var listed = new HashSet<string>(paths.Select(Path.GetFileName).OfType<string>(), StringComparer.OrdinalIgnoreCase);
var skip = new HashSet<string>((pending ?? Array.Empty<CompanionInstall>()).Select(c => c.Entry.File), StringComparer.OrdinalIgnoreCase);
string suite = SuiteDir(manifest, paths);
Dictionary<string, DateTime> seen = ReadSeenPlugins(out _);
DateTime now = UtcNow();
var result = new List<AvailablePlugin>();
foreach (PluginEntry e in manifest.Plugins)
{
if (listed.Contains(e.File) || skip.Contains(e.File)) continue;
if (TargetPath(e, suite) is not { } target) continue;
bool isNew = seen.TryGetValue(e.Name, out DateTime first) && now - first < NewBadgeFor;
result.Add(new AvailablePlugin(e, target, DescribePlugin(e), manifest.Version, isNew));
}
// New ones first, then by name.
return result.OrderByDescending(a => a.IsNew).ThenBy(a => a.Entry.Name, StringComparer.OrdinalIgnoreCase).ToList();
}
/// <summary>The Available list for a check, against the plugin list as it is now.</summary>
public List<AvailablePlugin> GetAvailable(CheckResult check, IEnumerable<string> pluginPaths) =>
GetAvailable(check.Manifest, pluginPaths, check.Companions);
/// <summary>
/// Installs one plugin from the signed feed for the caller to add to the plugin list. A file
/// already at the target is kept when it is the release build or newer (someone's own build);
/// an older one is replaced and kept beside it as .previous. Throws, with nothing changed,
/// when the download doesn't match the signed size and hash or is cancelled.
/// </summary>
public async Task<PluginInstall> InstallPluginAsync(CheckResult check, string name, IEnumerable<string> pluginPaths,
IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
List<string> paths = pluginPaths.ToList();
PluginEntry e = check.Manifest.Plugins.FirstOrDefault(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))
?? throw new InvalidOperationException($"{name} is not in the update feed");
if (paths.Any(p => string.Equals(Path.GetFileName(p), e.File, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"{e.Name} is already in your plugin list");
string target = TargetPath(e, SuiteDir(check.Manifest, paths))
?? throw new InvalidDataException($"bad plugin name '{e.Name}' in the feed");
if (File.Exists(target))
{
bool same = string.Equals(Sha256File(target), e.Sha256, StringComparison.OrdinalIgnoreCase);
bool localBuild = File.GetLastWriteTimeUtc(target) > check.Manifest.PublishedUtc.AddMinutes(1);
if (same || localBuild)
return new PluginInstall(e, target, DescribePlugin(e), Downloaded: false);
}
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
string temp = Path.Combine(Path.GetTempPath(), $"rynth-{Guid.NewGuid():N}.dll");
try
{
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, temp, ct, e.Name, progress);
progress?.Report(new DownloadProgress(e.Name, DownloadStage.Installing, 0, 0));
// Stamp the release time so a later check never mistakes it for a local build.
File.SetLastWriteTimeUtc(temp, check.Manifest.PublishedUtc);
if (File.Exists(target)) File.Copy(target, target + ".previous", overwrite: true);
File.Move(temp, target, overwrite: true);
}
finally
{
try { File.Delete(temp); } catch { }
}
return new PluginInstall(e, target, DescribePlugin(e), Downloaded: true);
}
// ── Manifest fields (optional, backward-compatible) ───────────────────────
/// <summary>The plugin entry's optional "description": one line, plain text, at most 160 characters.</summary>
private static string ReadDescription(JsonElement p)
{
if (!p.TryGetProperty("description", out JsonElement d) || d.ValueKind != JsonValueKind.String) return "";
return OneLine(d.GetString(), MaxDescriptionLength);
}
/// <summary>The manifest's optional "changes": up to 20 lines.</summary>
private static IReadOnlyList<string> ReadChanges(JsonElement r)
{
if (!r.TryGetProperty("changes", out JsonElement c) || c.ValueKind != JsonValueKind.Array) return Array.Empty<string>();
var list = new List<string>();
foreach (JsonElement e in c.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.String) continue;
string line = OneLine(e.GetString(), 300);
if (line.Length > 0) list.Add(line);
if (list.Count >= MaxChanges) break;
}
return list;
}
private static string OneLine(string? s, int max)
{
if (string.IsNullOrWhiteSpace(s)) return "";
var sb = new StringBuilder(Math.Min(s.Length, max + 1));
bool space = false;
foreach (char ch in s)
{
if (char.IsWhiteSpace(ch) || char.IsControl(ch)) { space = sb.Length > 0; continue; }
if (space) { sb.Append(' '); space = false; }
sb.Append(ch);
if (sb.Length > max) break;
}
string line = sb.ToString();
return line.Length > max ? line[..(max - 1)].TrimEnd() + "…" : line;
}
// ── Seen plugins (the New badge) ──────────────────────────────────────────
private string SeenPath => Path.Combine(_stateDir, "update-seen-plugins.json");
private Dictionary<string, DateTime> ReadSeenPlugins(out bool existed)
{
var map = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
existed = false;
try
{
if (!File.Exists(SeenPath)) return map;
using var doc = JsonDocument.Parse(File.ReadAllText(SeenPath));
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
if (p.Value.ValueKind == JsonValueKind.String && DateTime.TryParse(p.Value.GetString(), null,
System.Globalization.DateTimeStyles.AdjustToUniversal | System.Globalization.DateTimeStyles.AssumeUniversal, out DateTime t))
map[p.Name] = t;
existed = true;
}
catch { map.Clear(); existed = false; }
return map;
}
/// <summary>Records the feed's plugins as seen; returns the ones seen for the first time that count as new.</summary>
private HashSet<string> RecordSeenPlugins(Manifest manifest)
{
var fresh = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, DateTime> seen = ReadSeenPlugins(out bool existed);
HashSet<string> offered = ReadOfferedCompanions();
DateTime now = UtcNow();
bool changed = !existed;
foreach (PluginEntry e in manifest.Plugins)
{
if (seen.ContainsKey(e.Name)) continue;
// First run of this list: only the recent additions are news, and not to a player who
// already had them offered (2026.10.4.3 installed them; removing one keeps it removed).
bool isNew = existed || (RecentlyAdded.Contains(e.Name, StringComparer.OrdinalIgnoreCase) && !offered.Contains(e.Name));
seen[e.Name] = isNew ? now : DateTime.UnixEpoch;
if (isNew) fresh.Add(e.Name);
changed = true;
}
if (changed)
{
try
{
Directory.CreateDirectory(_stateDir);
string tmp = SeenPath + ".tmp";
var ordered = seen.OrderBy(kv => kv.Key, StringComparer.OrdinalIgnoreCase)
.ToDictionary(kv => kv.Key, kv => kv.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"));
File.WriteAllText(tmp, JsonSerializer.Serialize(ordered, new JsonSerializerOptions { WriteIndented = true }), Encoding.UTF8);
File.Move(tmp, SeenPath, overwrite: true);
}
catch { }
}
return fresh;
}
}
/// <summary>Edits to the launcher's plugin list (kept apart from the window so tests can run them).</summary>
internal static class PluginListEdits
{
/// <summary>Adds <paramref name="path"/> once; false when it was already listed.</summary>
public static bool Add(IList<string> paths, string path)
{
if (paths.Any(p => string.Equals(p, path, StringComparison.OrdinalIgnoreCase))) return false;
paths.Add(path);
return true;
}
/// <summary>
/// Takes <paramref name="path"/> out of the list, and out of the disabled list so adding it back
/// later starts it enabled. Never touches the file.
/// </summary>
public static bool Remove(IList<string> paths, IList<string>? disabled, string path)
{
bool removed = RemoveAll(paths, path) > 0;
if (disabled != null) RemoveAll(disabled, path);
return removed;
}
private static int RemoveAll(IList<string> list, string path)
{
int n = 0;
for (int i = list.Count - 1; i >= 0; i--)
if (string.Equals(list[i], path, StringComparison.OrdinalIgnoreCase)) { list.RemoveAt(i); n++; }
return n;
}
}

View file

@ -0,0 +1,298 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.App.Avalonia;
/// <summary>
/// RynthNav's data folder (C:\Games\RynthCore\NavData by default): the navmesh tiles, portals.tsv
/// and locations.json, shipped as one archive.
///
/// Feed: an optional "navdata" object in the signed manifest —
/// {"id": hash of the tile set, "release": n, "url", "size", "sha256", "files": file count,
/// "bytes": unpacked size}.
/// The signature covers it exactly like the plugins; the archive is checked against the signed
/// size and SHA-256 before it is opened, and only plain file names RynthNav reads
/// (nav_XXXX.tile, portals.tsv, locations.json, navgraph.bin: the long-range route graph,
/// townnet.json: the Town Network's portals and the walks inside) are
/// accepted from it.
///
/// Install: only when RynthNav is in the plugin list and the folder's navdata.id differs from the
/// feed's id. The archive is unpacked beside the folder (NavData.new), the player's own files there
/// (atlas.txt, recalls.txt, anything else not shipped) are copied across, then the folders swap:
/// the old one is kept as NavData.previous (one generation). Old tiles never mix with new ones —
/// tiles from different bakes don't link. A folder with a navdata.local file in it is never touched
/// (someone baking their own tiles). Running clients keep the tiles they already loaded; new ones
/// load as they move (a relog picks up everything).
/// </summary>
internal sealed partial class RynthUpdater
{
public const string NavDataDefaultDir = @"C:\Games\RynthCore\NavData";
public const string NavDataIdFile = "navdata.id";
public const string NavDataLocalMarker = "navdata.local";
private const string RynthNavFile = "RynthCore.Plugin.RynthNav.dll";
private const long MaxNavDataBytes = 3L << 30; // the archive
private const long MaxNavDataEntryBytes = 32L << 20; // one file in it
private static readonly Regex ShippedName = new(@"^(nav_[0-9A-Fa-f]{4}\.tile|portals\.tsv|locations\.json|navgraph\.bin|townnet\.json)$", RegexOptions.CultureInvariant);
private static readonly Regex IdPattern = new(@"^[0-9a-f]{16,64}$", RegexOptions.CultureInvariant);
public sealed record NavDataEntry(string Id, int Release, string Url, long Size, string Sha256, int Files, long Bytes);
public enum NavDataState { UpToDate, NeedsUpdate, LocalTiles }
public sealed record NavDataStatus(NavDataEntry Entry, string Dir, string InstalledId, NavDataState State);
/// <summary>True for a file name the archive may carry (and that an update replaces).</summary>
public static bool IsShippedNavFile(string name) => ShippedName.IsMatch(name);
/// <summary>
/// A whole number written either way: 1383002945 or 1383002945.0. PowerShell's ConvertTo-Json writes
/// a double with ".0", and GetInt64 refused it - which failed the whole update check for every
/// launcher on 2026.10.3.1/2 ("One of the identified items was in an invalid format").
/// </summary>
private static long WholeNumber(JsonElement e)
{
if (e.TryGetInt64(out long l)) return l;
double d = e.GetDouble();
if (d < 0 || d > long.MaxValue || d != Math.Floor(d)) throw new InvalidDataException($"not a whole number: {e.GetRawText()}");
return (long)d;
}
/// <summary>A navdata entry that can't be read leaves the tiles out of this check; the core and plugins still update.</summary>
private NavDataEntry? TryParseNavData(JsonElement nd)
{
try { return ParseNavData(nd); }
catch (Exception ex) when (ex is InvalidDataException or FormatException or InvalidOperationException or KeyNotFoundException)
{
System.Diagnostics.Debug.WriteLine($"RynthUpdater: navdata entry unreadable ({ex.Message}); tiles skipped this check.");
return null;
}
}
private NavDataEntry ParseNavData(JsonElement nd)
{
string id = (nd.GetProperty("id").GetString() ?? "").ToLowerInvariant();
if (!IdPattern.IsMatch(id)) throw new InvalidDataException($"bad navdata id '{id}'");
int files = (int)WholeNumber(nd.GetProperty("files"));
if (files <= 0) throw new InvalidDataException("navdata lists no files");
return new NavDataEntry(id, (int)WholeNumber(nd.GetProperty("release")), CheckUrl(nd.GetProperty("url").GetString()),
WholeNumber(nd.GetProperty("size")), nd.GetProperty("sha256").GetString() ?? "", files,
nd.TryGetProperty("bytes", out JsonElement b) ? WholeNumber(b) : 0);
}
/// <summary>
/// Where RynthNav reads its data: "navDataDir" in %APPDATA%\RynthCore\rynthnav.json (the same
/// file the plugin reads; see the plugin's NavDataConfig), else the default.
/// </summary>
public string NavDataDir
{
get
{
try
{
string settings = Path.Combine(_stateDir, "rynthnav.json");
if (File.Exists(settings))
{
using var doc = JsonDocument.Parse(File.ReadAllText(settings),
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
if (doc.RootElement.ValueKind == JsonValueKind.Object)
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
if (p.Name.Equals("navDataDir", StringComparison.OrdinalIgnoreCase) && p.Value.ValueKind == JsonValueKind.String
&& p.Value.GetString() is { } dir && Path.IsPathFullyQualified(dir.Trim()))
return dir.Trim().TrimEnd('\\', '/');
}
}
catch { }
return _navDataDirOverride ?? NavDataDefaultDir;
}
}
private string? _navDataDirOverride;
/// <summary>Where the archive is downloaded to; null = %LOCALAPPDATA%\RynthCore\updates (tests set their own).</summary>
internal string? NavDataCacheDir { get; set; }
/// <summary>Tests: the folder to use when rynthnav.json doesn't name one.</summary>
internal void SetDefaultNavDataDir(string dir) => _navDataDirOverride = dir;
private NavDataStatus? CheckNavData(Manifest manifest, IEnumerable<string> pluginPaths)
{
if (manifest.NavData is not { } e) return null;
bool hasNav = pluginPaths.Any(p => string.Equals(Path.GetFileName(p), RynthNavFile, StringComparison.OrdinalIgnoreCase) && File.Exists(p));
if (!hasNav) return null;
string dir = NavDataDir;
string installed = "";
try { if (File.Exists(Path.Combine(dir, NavDataIdFile))) installed = File.ReadAllText(Path.Combine(dir, NavDataIdFile)).Trim().ToLowerInvariant(); }
catch { }
NavDataState state = File.Exists(Path.Combine(dir, NavDataLocalMarker)) ? NavDataState.LocalTiles
: installed == e.Id ? NavDataState.UpToDate : NavDataState.NeedsUpdate;
return new NavDataStatus(e, dir, installed, state);
}
/// <summary>
/// Downloads, verifies and installs the feed's RynthNav data (see the class notes). Returns a
/// line for the activity log. Throws on anything wrong, leaving the installed folder as it was.
/// </summary>
public const string NavDataDisplayName = "RynthNav map";
/// <summary>
/// Cancel is safe at any point before the folder swap: the partial download is deleted, an
/// unpacked staging folder is removed, and the installed tiles stay as they were. A fully
/// downloaded, verified archive stays in the cache and is reused by the next try. The swap
/// itself (two folder renames) doesn't stop half way.
/// </summary>
public async Task<string> UpdateNavDataAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
if (check.NavData is not { State: NavDataState.NeedsUpdate } st) return "";
NavDataEntry e = st.Entry;
string dir = st.Dir.TrimEnd('\\', '/');
string parent = Path.GetDirectoryName(dir) ?? throw new InvalidOperationException($"bad NavData folder {dir}");
Directory.CreateDirectory(parent);
// Room for the archive, the unpacked copy and the old folder kept as .previous.
long need = e.Size + Math.Max(e.Bytes, e.Size * 3) + (64L << 20);
long free = new DriveInfo(Path.GetPathRoot(Path.GetFullPath(dir))!).AvailableFreeSpace;
if (free < need)
throw new IOException($"not enough disk space for the navmesh tiles: {need >> 20} MB needed, {free >> 20} MB free on {Path.GetPathRoot(dir)}");
string cache = NavDataCacheDir ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "updates");
Directory.CreateDirectory(cache);
string zip = Path.Combine(cache, $"navdata-{e.Id}.zip");
if (!(File.Exists(zip) && new FileInfo(zip).Length == e.Size && string.Equals(Sha256File(zip), e.Sha256, StringComparison.OrdinalIgnoreCase)))
{
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxNavDataBytes, zip + ".part", ct, NavDataDisplayName, progress);
File.Move(zip + ".part", zip, overwrite: true);
}
// Unpacking tens of thousands of files takes a while: off the caller's (UI) thread.
await Task.Run(() =>
{
progress?.Report(new DownloadProgress(NavDataDisplayName, DownloadStage.Unpacking, 0, e.Files));
string staging = dir + ".new";
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
Directory.CreateDirectory(staging);
try
{
int count = ExtractNavData(zip, staging, ct,
n => progress?.Report(new DownloadProgress(NavDataDisplayName, DownloadStage.Unpacking, n, e.Files)));
if (count != e.Files) throw new InvalidDataException($"the tile archive has {count} files, the feed says {e.Files}");
// The player's own files (atlas.txt, recalls.txt, …) and anything else not shipped come along.
if (Directory.Exists(dir)) CopyUnshipped(dir, staging);
File.WriteAllText(Path.Combine(staging, NavDataIdFile), e.Id);
// Last chance to cancel: from here the swap runs to the end.
ct.ThrowIfCancellationRequested();
progress?.Report(new DownloadProgress(NavDataDisplayName, DownloadStage.Installing, 0, 0));
SwapNavData(dir, staging);
}
catch
{
try { if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true); } catch { }
throw;
}
}, ct);
try { File.Delete(zip); } catch { }
return $"RynthNav navmesh tiles updated: {e.Files} files into {dir} (the old ones are in {Path.GetFileName(dir)}.previous). Running clients load the new tiles as they move; a relog picks up all of them.";
}
/// <summary>Unpacks only plain, known file names; returns how many files were written.</summary>
internal static int ExtractNavData(string zipPath, string dest, CancellationToken ct = default, Action<int>? unpacked = null)
{
int n = 0;
var sinceReport = System.Diagnostics.Stopwatch.StartNew();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
using ZipArchive za = ZipFile.OpenRead(zipPath);
foreach (ZipArchiveEntry z in za.Entries)
{
ct.ThrowIfCancellationRequested();
if (z.FullName.EndsWith('/') && z.Length == 0) continue; // a folder entry
string name = z.FullName;
if (name != z.Name || !IsShippedNavFile(name))
throw new InvalidDataException($"unexpected file in the tile archive: '{name}'");
if (!seen.Add(name)) throw new InvalidDataException($"'{name}' is in the tile archive twice");
if (z.Length > MaxNavDataEntryBytes) throw new InvalidDataException($"'{name}' is too large ({z.Length} bytes)");
string target = Path.Combine(dest, name);
using (Stream src = z.Open())
using (var f = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
byte[] buf = new byte[81920];
long total = 0; int r;
while ((r = src.Read(buf, 0, buf.Length)) > 0)
{
total += r;
if (total > MaxNavDataEntryBytes) throw new InvalidDataException($"'{name}' unpacks larger than it says");
f.Write(buf, 0, r);
}
}
n++;
if (unpacked != null && sinceReport.Elapsed >= DownloadMeter.ReportEvery)
{
unpacked(n);
sinceReport.Restart();
}
}
unpacked?.Invoke(n);
return n;
}
private static void CopyUnshipped(string from, string to)
{
foreach (string f in Directory.GetFiles(from))
{
string name = Path.GetFileName(f);
if (IsShippedNavFile(name) || name.Equals(NavDataIdFile, StringComparison.OrdinalIgnoreCase)) continue;
string target = Path.Combine(to, name);
if (!File.Exists(target)) File.Copy(f, target);
}
foreach (string d in Directory.GetDirectories(from))
{
string target = Path.Combine(to, Path.GetFileName(d));
Directory.CreateDirectory(target);
CopyTree(d, target);
}
}
private static void CopyTree(string from, string to)
{
foreach (string f in Directory.GetFiles(from)) File.Copy(f, Path.Combine(to, Path.GetFileName(f)), overwrite: false);
foreach (string d in Directory.GetDirectories(from))
{
string t = Path.Combine(to, Path.GetFileName(d));
Directory.CreateDirectory(t);
CopyTree(d, t);
}
}
// dir -> dir.previous, staging -> dir. A client reading a tile at that moment holds it open for
// a few milliseconds, so each move is retried; if the second fails the first is undone.
private static void SwapNavData(string dir, string staging)
{
string previous = dir + ".previous";
bool hadOld = Directory.Exists(dir);
if (hadOld)
{
if (Directory.Exists(previous)) Directory.Delete(previous, recursive: true);
Retry(() => Directory.Move(dir, previous));
}
try { Retry(() => Directory.Move(staging, dir)); }
catch
{
if (hadOld && !Directory.Exists(dir)) { try { Directory.Move(previous, dir); } catch { } }
throw;
}
}
private static void Retry(Action a)
{
for (int i = 0; ; i++)
{
try { a(); return; }
catch (IOException) when (i < 9) { Thread.Sleep(500); }
catch (UnauthorizedAccessException) when (i < 9) { Thread.Sleep(500); }
}
}
}

View file

@ -25,8 +25,12 @@ namespace RynthCore.App.Avalonia;
/// touches a running bot: the new version loads the next time AC starts, or on RL if the player
/// chooses — the updater never reloads anything. The core (engine, Loader, launcher) updates by
/// running the release's installer, and only while no RynthCore client is running.
///
/// RynthNav's data (navmesh tiles, portals.tsv, locations.json) is an optional signed archive in
/// the same manifest ("navdata"), installed only for players who have RynthNav in their plugin
/// list, and only when its id (a hash of the tile set) changes. See RynthUpdater.NavData.cs.
/// </summary>
internal sealed class RynthUpdater
internal sealed partial class RynthUpdater
{
public const string DefaultFeedUrl = "https://aelrynth.com/downloads/rynth/update.json";
@ -34,21 +38,60 @@ internal sealed class RynthUpdater
private const long MaxPluginBytes = 64L << 20;
private const long MaxInstallerBytes = 256L << 20;
public sealed record PluginEntry(string Name, string File, string Url, long Size, string Sha256);
/// <summary>
/// One plugin in the feed. <paramref name="Description"/> is the optional one-line "description"
/// (written since 2026.10.5); older feeds have none and the launcher's own table fills in
/// (<see cref="DescribePlugin"/>). Launchers before it ignore the field.
/// </summary>
public sealed record PluginEntry(string Name, string File, string Url, long Size, string Sha256, string Description = "");
public sealed record InstallerEntry(int Release, string Version, string Url, long Size, string Sha256);
public sealed record Manifest(int Release, string Version, DateTime PublishedUtc, string Notes,
InstallerEntry Core, IReadOnlyList<PluginEntry> Plugins);
InstallerEntry Core, IReadOnlyList<PluginEntry> Plugins, NavDataEntry? NavData = null)
{
/// <summary>
/// The release's changes, one line each: the optional "changes" array (written since 2026.10.5;
/// signed with the rest). Empty for older feeds, which only have <see cref="Notes"/>.
/// </summary>
public IReadOnlyList<string> Changes { get; init; } = Array.Empty<string>();
}
/// <summary>One installed copy of a plugin the feed knows.</summary>
public sealed record PluginStatus(PluginEntry Entry, string Path, PluginState State);
public enum PluginState { UpToDate, NeedsUpdate, LocalBuild }
/// <summary>A plugin split out of one the player has, to be installed beside it (see <see cref="Companions"/>).</summary>
public sealed record CompanionInstall(PluginEntry Entry, string Path, string Reason);
public sealed record CheckResult(Manifest Manifest, int InstalledCoreRelease, IReadOnlyList<PluginStatus> Plugins)
{
public bool CoreUpdateAvailable => Manifest.Core.Release > InstalledCoreRelease;
public IEnumerable<PluginStatus> PluginsToUpdate => Plugins.Where(p => p.State == PluginState.NeedsUpdate);
/// <summary>New plugins that came out of an installed one; installed with the plugin updates.</summary>
public IReadOnlyList<CompanionInstall> Companions { get; init; } = Array.Empty<CompanionInstall>();
/// <summary>Feed plugins not in the plugin list, for the player to install or not (see <see cref="GetAvailable"/>).</summary>
public IReadOnlyList<AvailablePlugin> Available { get; init; } = Array.Empty<AvailablePlugin>();
/// <summary>Available plugins this launcher sees in the feed for the first time: said once in the activity log.</summary>
public IReadOnlyList<AvailablePlugin> NewlyAnnounced { get; init; } = Array.Empty<AvailablePlugin>();
/// <summary>RynthNav's tiles: null when the feed has none or RynthNav isn't in the plugin list.</summary>
public NavDataStatus? NavData { get; init; }
public bool NavDataUpdateAvailable => NavData is { State: NavDataState.NeedsUpdate };
}
/// <summary>
/// Features that moved out of a plugin into their own. When the player has the parent and not the
/// child, the child is installed in a sibling folder and registered, once: a player who removes it
/// afterwards keeps it removed.
///
/// Only for a split, where the player's scripts stop working without the child. A plugin that is
/// simply new (RynthOracle, RynthInventory: 2026.10.4.3 auto-installed them this way) is offered
/// instead, under Available plugins with a "New" badge (<see cref="RecentlyAdded"/>); players who
/// already got them keep them.
/// </summary>
private static readonly (string ParentFile, string ChildName, string Reason)[] Companions =
{
("RynthCore.Plugin.RynthAi.dll", "RynthLua", "Lua scripting, which moved out of RynthAi"),
};
private static readonly HttpClient Http = CreateHttp();
private readonly string _feedUrl;
@ -124,7 +167,71 @@ internal sealed class RynthUpdater
statuses.Add(new PluginStatus(entry, path, state));
}
return new CheckResult(manifest, InstalledCoreRelease, statuses);
List<CompanionInstall> companions = FindCompanions(manifest, pluginPaths);
HashSet<string> fresh = RecordSeenPlugins(manifest); // before GetAvailable: it reads the New badges
List<AvailablePlugin> available = GetAvailable(manifest, pluginPaths, companions);
return new CheckResult(manifest, InstalledCoreRelease, statuses)
{
Companions = companions,
NavData = CheckNavData(manifest, pluginPaths),
Available = available,
NewlyAnnounced = available.Where(a => fresh.Contains(a.Entry.Name)).ToList(),
};
}
private List<CompanionInstall> FindCompanions(Manifest manifest, IEnumerable<string> pluginPaths)
{
var result = new List<CompanionInstall>();
List<string> paths = pluginPaths.ToList();
HashSet<string> offered = ReadOfferedCompanions();
foreach (var (parentFile, childName, reason) in Companions)
{
if (offered.Contains(childName)) continue;
string? parent = paths.FirstOrDefault(p =>
string.Equals(Path.GetFileName(p), parentFile, StringComparison.OrdinalIgnoreCase) && File.Exists(p));
PluginEntry? child = manifest.Plugins.FirstOrDefault(e => string.Equals(e.Name, childName, StringComparison.OrdinalIgnoreCase));
if (parent == null || child == null) continue;
if (paths.Any(p => string.Equals(Path.GetFileName(p), child.File, StringComparison.OrdinalIgnoreCase)))
{
MarkCompanionOffered(childName); // already there: nothing to do, ever
continue;
}
// C:\Games\RynthSuite\RynthAi\x.dll -> C:\Games\RynthSuite\RynthLua\<file>
string? suiteDir = Path.GetDirectoryName(Path.GetDirectoryName(parent));
if (string.IsNullOrEmpty(suiteDir)) continue;
result.Add(new CompanionInstall(child, Path.Combine(suiteDir, childName, child.File), reason));
}
return result;
}
/// <summary>
/// Installs <see cref="CheckResult.Companions"/> (verified like every plugin; an existing file at the
/// target is kept) and returns their paths for the caller to register in the plugin list.
/// </summary>
public async Task<List<CompanionInstall>> InstallCompanionsAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
var done = new List<CompanionInstall>();
foreach (CompanionInstall c in check.Companions)
{
if (!File.Exists(c.Path))
{
Directory.CreateDirectory(Path.GetDirectoryName(c.Path)!);
string temp = Path.Combine(Path.GetTempPath(), $"rynth-{Guid.NewGuid():N}.dll");
try
{
await DownloadVerifiedAsync(c.Entry.Url, c.Entry.Size, c.Entry.Sha256, MaxPluginBytes, temp, ct, c.Entry.Name, progress);
File.SetLastWriteTimeUtc(temp, check.Manifest.PublishedUtc);
File.Move(temp, c.Path, overwrite: false);
}
finally
{
try { File.Delete(temp); } catch { }
}
}
MarkCompanionOffered(c.Entry.Name);
done.Add(c);
}
return done;
}
// ── Plugins ───────────────────────────────────────────────────────────────
@ -133,7 +240,7 @@ internal sealed class RynthUpdater
/// Swaps each outdated plugin DLL for the verified release build. The previous file is kept
/// beside it as .previous. Running clients keep the version they started with.
/// </summary>
public async Task<List<string>> UpdatePluginsAsync(CheckResult check, CancellationToken ct = default)
public async Task<List<string>> UpdatePluginsAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
var done = new List<string>();
foreach (var group in check.PluginsToUpdate.GroupBy(p => p.Entry))
@ -142,7 +249,7 @@ internal sealed class RynthUpdater
string temp = Path.Combine(Path.GetTempPath(), $"rynth-{Guid.NewGuid():N}.dll");
try
{
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, temp, ct);
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, temp, ct, e.Name, progress);
foreach (PluginStatus p in group)
{
string staged = p.Path + ".new";
@ -165,7 +272,7 @@ internal sealed class RynthUpdater
// ── Core ──────────────────────────────────────────────────────────────────
/// <summary>Downloads (or reuses) the release installer, verified, and returns its path.</summary>
public async Task<string> DownloadInstallerAsync(CheckResult check, CancellationToken ct = default)
public async Task<string> DownloadInstallerAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
InstallerEntry core = check.Manifest.Core;
string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
@ -177,7 +284,7 @@ internal sealed class RynthUpdater
return path;
string temp = path + ".part";
await DownloadVerifiedAsync(core.Url, core.Size, core.Sha256, MaxInstallerBytes, temp, ct);
await DownloadVerifiedAsync(core.Url, core.Size, core.Sha256, MaxInstallerBytes, temp, ct, $"RynthCore {core.Version}", progress);
File.Move(temp, path, overwrite: true);
return path;
}
@ -238,12 +345,17 @@ internal sealed class RynthUpdater
if (file.Length == 0 || file != Path.GetFileName(file) || !file.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
throw new InvalidDataException($"bad plugin file name '{file}'");
plugins.Add(new PluginEntry(p.GetProperty("name").GetString() ?? file, file,
CheckUrl(p.GetProperty("url").GetString()), p.GetProperty("size").GetInt64(), p.GetProperty("sha256").GetString() ?? ""));
CheckUrl(p.GetProperty("url").GetString()), p.GetProperty("size").GetInt64(), p.GetProperty("sha256").GetString() ?? "",
ReadDescription(p)));
}
return new Manifest(r.GetProperty("release").GetInt32(), r.GetProperty("version").GetString() ?? "",
r.GetProperty("published").GetDateTime().ToUniversalTime(),
r.TryGetProperty("notes", out JsonElement n) ? n.GetString() ?? "" : "", core, plugins);
r.TryGetProperty("notes", out JsonElement n) ? n.GetString() ?? "" : "", core, plugins,
r.TryGetProperty("navdata", out JsonElement nd) && nd.ValueKind == JsonValueKind.Object ? TryParseNavData(nd) : null)
{
Changes = ReadChanges(r),
};
}
private string CheckUrl(string? url)
@ -271,31 +383,49 @@ internal sealed class RynthUpdater
return ms.ToArray();
}
private static async Task DownloadVerifiedAsync(string url, long size, string sha256, long max, string dest, CancellationToken ct)
/// <summary>
/// Downloads to <paramref name="dest"/> and checks it against the signed size and SHA-256. On any
/// failure (a wrong hash, a lost connection, Cancel) the partial file is deleted. Progress, when
/// asked for, goes to <paramref name="progress"/> a few times a second (<see cref="DownloadMeter"/>),
/// then one <see cref="DownloadStage.Verified"/> report once the hash matched.
/// </summary>
private static async Task DownloadVerifiedAsync(string url, long size, string sha256, long max, string dest, CancellationToken ct,
string? what = null, IProgress<DownloadProgress>? progress = null)
{
if (size <= 0 || size > max) throw new InvalidDataException($"{url}: size {size} out of range");
using var resp = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct);
resp.EnsureSuccessStatusCode();
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
long total = 0;
await using (var s = await resp.Content.ReadAsStreamAsync(ct))
await using (var f = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None))
var meter = new DownloadMeter(what ?? Path.GetFileName(url), size, progress);
try
{
byte[] buf = new byte[81920];
int n;
while ((n = await s.ReadAsync(buf, ct)) > 0)
using var resp = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct);
resp.EnsureSuccessStatusCode();
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
long total = 0;
meter.Report(0);
await using (var s = await resp.Content.ReadAsStreamAsync(ct))
await using (var f = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None))
{
total += n;
if (total > size) throw new InvalidDataException($"{url} is larger than the signed size");
hash.AppendData(buf, 0, n);
await f.WriteAsync(buf.AsMemory(0, n), ct);
byte[] buf = new byte[81920];
int n;
while ((n = await s.ReadAsync(buf, ct)) > 0)
{
ct.ThrowIfCancellationRequested();
total += n;
if (total > size) throw new InvalidDataException($"{url} is larger than the signed size");
hash.AppendData(buf, 0, n);
await f.WriteAsync(buf.AsMemory(0, n), ct);
meter.Report(total);
}
}
string got = Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant();
if (total != size || !string.Equals(got, sha256, StringComparison.OrdinalIgnoreCase))
throw new InvalidDataException($"{Path.GetFileName(url)} does not match the signed hash — not installed");
meter.Verified();
}
string got = Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant();
if (total != size || !string.Equals(got, sha256, StringComparison.OrdinalIgnoreCase))
catch
{
// The file stream is closed by now (its using block ended), so the delete can't be refused by it.
try { File.Delete(dest); } catch { }
throw new InvalidDataException($"{Path.GetFileName(url)} does not match the signed hash — not installed");
throw;
}
}
@ -315,6 +445,35 @@ internal sealed class RynthUpdater
// ── State ─────────────────────────────────────────────────────────────────
private string StatePath => Path.Combine(_stateDir, "update-state.json");
private string CompanionsPath => Path.Combine(_stateDir, "update-companions.json");
private HashSet<string> ReadOfferedCompanions()
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
try
{
if (!File.Exists(CompanionsPath)) return set;
using var doc = JsonDocument.Parse(File.ReadAllText(CompanionsPath));
foreach (JsonElement e in doc.RootElement.EnumerateArray())
if (e.GetString() is { Length: > 0 } s) set.Add(s);
}
catch { }
return set;
}
private void MarkCompanionOffered(string name)
{
try
{
HashSet<string> set = ReadOfferedCompanions();
if (!set.Add(name)) return;
Directory.CreateDirectory(_stateDir);
string tmp = CompanionsPath + ".tmp";
File.WriteAllText(tmp, "[" + string.Join(", ", set.OrderBy(s => s).Select(s => JsonSerializer.Serialize(s))) + "]", Encoding.UTF8);
File.Move(tmp, CompanionsPath, overwrite: true);
}
catch { }
}
private int ReadHighestRelease()
{

View file

@ -0,0 +1,153 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace RynthCore.App.Avalonia;
/// <summary>What the update card on the launcher's front page is showing.</summary>
public enum UpdateCardKind { NotConfigured, NotChecked, Checking, Error, UpToDate, CoreUpdate, PluginUpdates, Downloading }
/// <summary>Everything the card needs to know, gathered by the window (no UI types, so tests can build it).</summary>
public sealed record UpdateCardInput
{
public bool Configured { get; init; } = true;
public bool Checking { get; init; }
/// <summary>The last check's error; null when it worked.</summary>
public string? Error { get; init; }
/// <summary>When the last check succeeded (local time); null before the first.</summary>
public DateTime? LastChecked { get; init; }
/// <summary>True once a check has succeeded this session.</summary>
public bool HasCheck { get; init; }
public string InstalledVersion { get; init; } = "";
public bool CoreUpdateAvailable { get; init; }
public string AvailableVersion { get; init; } = "";
public string Notes { get; init; } = "";
public IReadOnlyList<string> Changes { get; init; } = Array.Empty<string>();
/// <summary>Plugin updates (and new companions, the RynthNav map) waiting to be installed.</summary>
public IReadOnlyList<string> PendingPluginUpdates { get; init; } = Array.Empty<string>();
/// <summary>Available plugins with the New badge.</summary>
public IReadOnlyList<string> NewPlugins { get; init; } = Array.Empty<string>();
/// <summary>Game clients running RynthCore (a RynthCore update waits for them to close).</summary>
public int ClientsRunning { get; init; }
/// <summary>The download in progress, if any.</summary>
public DownloadProgress? Download { get; init; }
public bool CanCancel { get; init; }
}
/// <summary>The card's text and which buttons show.</summary>
public sealed record UpdateCard(
UpdateCardKind Kind,
string Title,
string Detail,
IReadOnlyList<string> WhatsNew,
bool ShowCheckButton,
string? ActionButton,
bool ShowProgress,
double? ProgressPercent,
bool ShowCancel,
string? NewPluginsLine,
/// <summary>One line for the Plugins tab and the header.</summary>
string Compact);
/// <summary>
/// The front page's update card as a pure function of <see cref="UpdateCardInput"/>: up to date,
/// RynthCore update (installs once every game client is closed), plugin updates, downloading
/// (bar, MB, speed, time left, step), errors, and a line about new plugins.
/// </summary>
public static class UpdateCardModel
{
public const int MaxWhatsNew = 4;
public const string UpdateCoreButton = "Update RynthCore";
public const string UpdatePluginsButton = "Update plugins";
public static UpdateCard Build(UpdateCardInput i)
{
string? newLine = i.NewPlugins.Count > 0
? $"New plugins available: {string.Join(", ", i.NewPlugins)}. See Available plugins on the Plugins tab."
: null;
string installed = i.InstalledVersion.Length > 0 ? i.InstalledVersion : "unknown";
if (!i.Configured)
return new UpdateCard(UpdateCardKind.NotConfigured, "Updates", "Updates aren't set up in this build.",
Array.Empty<string>(), false, null, false, null, false, null, "Updates aren't set up in this build.");
if (i.Download is { } d)
{
string title = d.Stage switch
{
DownloadStage.Downloading => $"Downloading {d.What}",
DownloadStage.Verified => $"{d.What}: verified",
DownloadStage.Unpacking => $"Unpacking {d.What}",
_ => $"Installing {d.What}",
};
// Installing is the last step (files moving into place): it always runs to the end.
bool cancel = i.CanCancel && d.Stage != DownloadStage.Installing;
return new UpdateCard(UpdateCardKind.Downloading, title, d.Detail, Array.Empty<string>(), false, null,
true, d.Percent, cancel, newLine, $"{title}: {d.Detail}");
}
if (i.Checking)
return new UpdateCard(UpdateCardKind.Checking, "Checking for updates…", $"RynthCore {installed}",
Array.Empty<string>(), false, null, false, null, false, newLine, "Checking for updates…");
if (i.Error != null)
{
string when = i.LastChecked is { } t ? $" Last good check: {FormatWhen(t)}." : "";
return new UpdateCard(UpdateCardKind.Error, "Couldn't check for updates", i.Error.TrimEnd('.', ' ') + "." + when,
Array.Empty<string>(), true, null, false, null, false, newLine, $"Update check failed: {i.Error}");
}
if (!i.HasCheck)
return new UpdateCard(UpdateCardKind.NotChecked, $"RynthCore {installed}", "Not checked for updates yet.",
Array.Empty<string>(), true, null, false, null, false, newLine, "Not checked yet.");
string checkedLine = i.LastChecked is { } lc ? $"Last checked {FormatWhen(lc)}." : "";
IReadOnlyList<string> whatsNew = WhatsNew(i.Changes, i.Notes);
if (i.CoreUpdateAvailable)
{
var detail = new List<string> { $"You have {installed}. The update installs once every game client is closed." };
if (i.ClientsRunning > 0)
detail.Add($"Close your {i.ClientsRunning} game client{(i.ClientsRunning == 1 ? "" : "s")} running RynthCore first.");
if (i.PendingPluginUpdates.Count > 0)
detail.Add($"Plugin updates ready too: {string.Join(", ", i.PendingPluginUpdates)}.");
if (checkedLine.Length > 0) detail.Add(checkedLine);
return new UpdateCard(UpdateCardKind.CoreUpdate, $"RynthCore {i.AvailableVersion} is available", string.Join(" ", detail),
whatsNew, true, UpdateCoreButton, false, null, false, newLine, $"Update available: RynthCore {i.AvailableVersion}");
}
if (i.PendingPluginUpdates.Count > 0)
{
string detail = $"{string.Join(", ", i.PendingPluginUpdates)}. Running bots keep their version until AC restarts.";
if (checkedLine.Length > 0) detail += " " + checkedLine;
return new UpdateCard(UpdateCardKind.PluginUpdates, "Plugin updates ready", detail,
whatsNew, true, UpdatePluginsButton, false, null, false, newLine, $"Plugin updates ready: {string.Join(", ", i.PendingPluginUpdates)}");
}
return new UpdateCard(UpdateCardKind.UpToDate, $"RynthCore {installed} - up to date", checkedLine,
Array.Empty<string>(), true, null, false, null, false, newLine, $"RynthCore {installed} - up to date.");
}
/// <summary>A few of the release's changes; the notes when the feed has no list (feeds before 2026.10.5).</summary>
public static IReadOnlyList<string> WhatsNew(IReadOnlyList<string> changes, string notes)
{
if (changes.Count > 0)
{
var list = changes.Take(MaxWhatsNew).ToList();
if (changes.Count > MaxWhatsNew) list.Add($"…and {changes.Count - MaxWhatsNew} more.");
return list;
}
if (string.IsNullOrWhiteSpace(notes)) return Array.Empty<string>();
string n = notes.Trim();
return new[] { n.Length > 300 ? n[..299].TrimEnd() + "…" : n };
}
/// <summary>"at 14:05" today, else "Oct 3 at 14:05".</summary>
public static string FormatWhen(DateTime local, DateTime? now = null)
{
DateTime today = (now ?? DateTime.Now).Date;
string time = local.ToString("HH:mm", CultureInfo.InvariantCulture);
return local.Date == today ? $"at {time}" : $"{local.ToString("MMM d", CultureInfo.InvariantCulture)} at {time}";
}
}

View file

@ -0,0 +1,292 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Opt-in, anonymous usage statistics ("Help improve RynthCore"). OFF unless the player turns it on.
///
/// When on, at most one small report a day goes to aelrynth.com (never to a game server), sent
/// after a successful update check. The report holds exactly:
/// - a random install ID (a GUID made when the player opts in, stored only in usage-stats.json,
/// tied to nothing else);
/// - the RynthCore version;
/// - the enabled plugins the update feed ships (RynthSuite), with their versions; other plugins
/// only as a count, never by name (a private plugin's name could identify its author);
/// - how many crash_*.dmp files the engine wrote since the last report (a count only);
/// - the Windows major version ("10" or "11").
/// Never: character, account or server names, file paths, or anything else identifying.
///
/// Turning it off deletes usage-stats.json (and with it the install ID) and cancels a report in
/// flight. Every failure is silent, and nothing here ever delays or fails the update check.
/// </summary>
internal sealed class UsageStats
{
public const string DefaultEndpoint = "https://aelrynth.com/rynth/ping";
/// <summary>Where the engine writes crash/hang minidumps (RynthCore.Engine CrashDump / LogPaths).</summary>
public const string DefaultDumpDirectory = @"C:\Games\RynthCore\Logs\dumps";
public const int Schema = 1;
private const int MaxCrashes = 1000;
private const int MaxPlugins = 32;
public sealed record PluginInfo(string Name, string Version);
private static readonly HttpClient Http = CreateHttp();
private static readonly Regex ReleaseVersion = new(@"^\d{4}\.\d{1,2}\.\d{1,2}(\.\d{1,4})?$", RegexOptions.CultureInvariant);
private static readonly Regex SafeName = new(@"^[A-Za-z0-9 ._-]{1,40}$", RegexOptions.CultureInvariant);
private readonly string _endpoint;
private readonly string _stateDir;
private readonly string _dumpDir;
private CancellationTokenSource _cts = new();
private int _sending;
public UsageStats(string endpoint = DefaultEndpoint, string? stateDir = null, string dumpDir = DefaultDumpDirectory)
{
_endpoint = endpoint;
_stateDir = stateDir ?? Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
_dumpDir = dumpDir;
}
public string StatePath => Path.Combine(_stateDir, "usage-stats.json");
// ── Opt in / out ──────────────────────────────────────────────────────────
/// <summary>Called when the player turns statistics on: makes the install ID if there is none.</summary>
public void OptIn(DateTime utcNow)
{
if (ReadState() != null) return;
// Crashes count from the moment of opting in, never from before.
WriteState(new State(Guid.NewGuid().ToString("D"), "", utcNow));
}
/// <summary>Called when the player turns statistics off: cancels a report in flight and deletes the ID.</summary>
public void OptOut()
{
try { _cts.Cancel(); } catch { }
_cts = new CancellationTokenSource();
try { File.Delete(StatePath); } catch { }
try { File.Delete(StatePath + ".tmp"); } catch { }
}
/// <summary>The install ID, or null when the player hasn't opted in (or it was deleted).</summary>
public string? InstallId => ReadState()?.InstallId;
// ── Report ────────────────────────────────────────────────────────────────
/// <summary>
/// Sends today's report if one hasn't gone out yet (UTC day). <paramref name="stillEnabled"/> is
/// asked again right before sending, so turning it off mid-way stops it. Returns true only
/// when a report was accepted. Never throws.
/// </summary>
public async Task<bool> MaybeSendAsync(Func<bool> stillEnabled, string coreVersion,
IReadOnlyList<PluginInfo> plugins, int otherPlugins, DateTime utcNow)
{
if (Interlocked.Exchange(ref _sending, 1) == 1) return false;
try
{
if (!stillEnabled()) return false;
State? state = ReadState();
if (state == null)
{
OptIn(utcNow); // enabled but the file is gone (deleted by hand): start a new ID
state = ReadState();
if (state == null) return false;
}
string today = utcNow.ToString("yyyy-MM-dd");
if (state.LastPingDay == today) return false;
int crashes = CountCrashDumps(_dumpDir, state.CrashesSinceUtc, utcNow);
string json = BuildPayload(state.InstallId, coreVersion, plugins, otherPlugins, crashes, WindowsMajor());
CancellationToken ct = _cts.Token;
if (!stillEnabled() || ct.IsCancellationRequested) return false;
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var resp = await Http.PostAsync(_endpoint, content, ct).ConfigureAwait(false);
if (!resp.IsSuccessStatusCode) return false;
// Opted out while the request was out: the file is gone, keep it gone.
if (!stillEnabled() || ct.IsCancellationRequested || ReadState()?.InstallId != state.InstallId) return true;
WriteState(state with { LastPingDay = today, CrashesSinceUtc = utcNow });
return true;
}
catch
{
return false;
}
finally
{
Interlocked.Exchange(ref _sending, 0);
}
}
/// <summary>The report that would go out now (for "Show what is sent"); nothing is sent or saved.</summary>
public string Preview(string coreVersion, IReadOnlyList<PluginInfo> plugins, int otherPlugins, DateTime utcNow)
{
State? state = ReadState();
string id = state?.InstallId ?? "(a random ID, made when you turn this on)";
int crashes = state == null ? 0 : CountCrashDumps(_dumpDir, state.CrashesSinceUtc, utcNow);
return BuildPayload(id, coreVersion, plugins, otherPlugins, crashes, WindowsMajor());
}
/// <summary>The report body, exactly as sent. Public for the launcher's "Show what is sent" and the tests.</summary>
public static string BuildPayload(string installId, string coreVersion, IReadOnlyList<PluginInfo> plugins,
int otherPlugins, int crashes, string windows)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteNumber("schema", Schema);
w.WriteString("install", installId);
w.WriteString("version", ShortVersion(coreVersion));
w.WriteString("windows", windows);
w.WriteNumber("crashes", Math.Clamp(crashes, 0, MaxCrashes));
w.WriteStartArray("plugins");
foreach (PluginInfo p in plugins
.Where(p => SafeName.IsMatch(p.Name))
.GroupBy(p => p.Name, StringComparer.OrdinalIgnoreCase).Select(g => g.First())
.OrderBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
.Take(MaxPlugins))
{
w.WriteStartObject();
w.WriteString("name", p.Name);
w.WriteString("version", ShortVersion(p.Version));
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteNumber("otherPlugins", Math.Clamp(otherPlugins, 0, 100));
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
/// <summary>
/// The enabled plugins to report: those whose file name the update feed ships (by the feed's name
/// for them, with the DLL's own version), and a count of every other enabled plugin.
/// </summary>
public static (List<PluginInfo> Known, int Other) DescribePlugins(IEnumerable<string> enabledPaths,
IReadOnlyDictionary<string, string> feedNameByFile)
{
var known = new List<PluginInfo>();
int other = 0;
foreach (string path in enabledPaths.Distinct(StringComparer.OrdinalIgnoreCase))
{
string file = Path.GetFileName(path);
if (feedNameByFile.TryGetValue(file, out string? name) && File.Exists(path))
{
string version;
try { version = FileVersionInfo.GetVersionInfo(path).ProductVersion ?? ""; }
catch { version = ""; }
known.Add(new PluginInfo(name, version));
}
else
{
other++;
}
}
return (known, other);
}
/// <summary>"2026.10.2.1" for a release build, "dev" for an unversioned build, else "unknown". Drops the commit.</summary>
public static string ShortVersion(string? productVersion)
{
string v = (productVersion ?? "").Trim();
int plus = v.IndexOf('+');
if (plus >= 0) v = v[..plus];
int space = v.IndexOf(' ');
if (space >= 0) v = v[..space];
if (v is "1.0.0" or "1.0.0.0" or "dev") return "dev";
return ReleaseVersion.IsMatch(v) ? v : "unknown";
}
/// <summary>"11" (build 22000 and up), "10", or "other".</summary>
public static string WindowsMajor()
{
Version os = Environment.OSVersion.Version;
if (!OperatingSystem.IsWindows()) return "other";
if (os.Major == 10) return os.Build >= 22000 ? "11" : "10";
return "other";
}
/// <summary>crash_*.dmp files written after <paramref name="sinceUtc"/> (hang dumps are not crashes).</summary>
public static int CountCrashDumps(string dir, DateTime sinceUtc, DateTime utcNow)
{
try
{
if (!Directory.Exists(dir)) return 0;
int n = 0;
foreach (string f in Directory.EnumerateFiles(dir, "crash_*.dmp"))
{
DateTime t = File.GetLastWriteTimeUtc(f);
if (t > sinceUtc && t <= utcNow.AddMinutes(5)) n++;
if (n >= MaxCrashes) break;
}
return n;
}
catch { return 0; }
}
// ── State file ────────────────────────────────────────────────────────────
private sealed record State(string InstallId, string LastPingDay, DateTime CrashesSinceUtc);
private State? ReadState()
{
try
{
if (!File.Exists(StatePath)) return null;
using var doc = JsonDocument.Parse(File.ReadAllText(StatePath));
JsonElement r = doc.RootElement;
string id = r.GetProperty("installId").GetString() ?? "";
if (!Guid.TryParseExact(id, "D", out _)) return null;
string last = r.TryGetProperty("lastPingDay", out JsonElement l) ? l.GetString() ?? "" : "";
DateTime since = r.TryGetProperty("crashesSinceUtc", out JsonElement s) && s.TryGetDateTime(out DateTime d)
? d.ToUniversalTime() : DateTime.UtcNow;
return new State(id, last, since);
}
catch { return null; }
}
private void WriteState(State s)
{
try
{
Directory.CreateDirectory(_stateDir);
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteString("about", "RynthCore usage statistics (opt-in). Deleted when you turn them off.");
w.WriteString("installId", s.InstallId);
w.WriteString("lastPingDay", s.LastPingDay);
w.WriteString("crashesSinceUtc", DateTime.SpecifyKind(s.CrashesSinceUtc, DateTimeKind.Utc));
w.WriteEndObject();
}
string tmp = StatePath + ".tmp";
File.WriteAllBytes(tmp, ms.ToArray());
File.Move(tmp, StatePath, overwrite: true);
}
catch { }
}
private static HttpClient CreateHttp()
{
// Short: a slow stats server must never hold anything up (and nothing awaits this anyway).
var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
http.DefaultRequestHeaders.UserAgent.ParseAdd("RynthCore-Launcher");
return http;
}
}

View file

@ -0,0 +1,121 @@
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
namespace RynthCore.App.Avalonia;
/// <summary>
/// The one-time "Help improve RynthCore?" question and the "Show what is sent" window.
/// Plain words; "No thanks" is the safe answer (Escape and closing the window both mean no).
/// </summary>
internal static class UsageStatsDialog
{
private static readonly IBrush Back = new SolidColorBrush(Color.Parse("#132028"));
private static readonly IBrush Text = new SolidColorBrush(Color.Parse("#EAF0F4"));
private static readonly IBrush Muted = new SolidColorBrush(Color.Parse("#9AA8B3"));
private static readonly IBrush Accent = new SolidColorBrush(Color.Parse("#26C1A6"));
public const string WhatIsSent =
"Sent once a day, only if you turn it on: a random ID made just for this, the RynthCore version, " +
"which RynthSuite plugins you have enabled and their versions (other plugins only as a number), " +
"how many times RynthCore crashed since the last report (a number), and whether you run Windows 10 or 11.";
public const string NeverSent =
"Never sent: character, account or server names, file paths, or anything else about you or your game. " +
"It goes to aelrynth.com only, never to a game server.";
public const string HowToStop =
"Turning it off stops the reports at once and deletes the random ID from this PC.";
/// <summary>True when the player chose to turn statistics on.</summary>
public static async Task<bool> AskAsync(Window owner)
{
var dialog = NewWindow("Help improve RynthCore?", 560);
var on = new Button { Content = "Turn it on" };
var off = new Button { Content = "No thanks", IsCancel = true };
on.Click += (_, _) => dialog.Close(true);
off.Click += (_, _) => dialog.Close(false);
dialog.Content = Layout("Help improve RynthCore?",
new StackPanel
{
Spacing = 10,
Children =
{
Para("RynthCore can send a small anonymous report once a day, so we can see how many people use it, " +
"which versions and plugins are in use, and whether a new release crashes more than the last one.", Text),
Para(WhatIsSent, Muted),
Para(NeverSent, Muted),
Para("It stays off unless you turn it on. You can change your mind any time on the Plugins tab, " +
"under Usage statistics. " + HowToStop, Muted),
},
},
on, off);
bool? result = await dialog.ShowDialog<bool?>(owner);
return result == true;
}
/// <summary>Shows the report exactly as it would be sent now.</summary>
public static async Task ShowPayloadAsync(Window owner, string json, bool enabled)
{
var dialog = NewWindow("Usage statistics: what is sent", 620);
var body = new TextBox
{
Text = json,
IsReadOnly = true,
TextWrapping = TextWrapping.Wrap,
FontFamily = new FontFamily("Consolas, Cascadia Mono, monospace"),
FontSize = 12,
MaxHeight = 380,
Foreground = Text,
Background = new SolidColorBrush(Color.Parse("#0F161D")),
};
var close = new Button { Content = "Close", IsCancel = true, IsDefault = true };
close.Click += (_, _) => dialog.Close(null);
dialog.Content = Layout("Usage statistics: what is sent",
new StackPanel
{
Spacing = 8,
Children =
{
Para(enabled
? "This is today's report, exactly as it goes to aelrynth.com (at most once a day)."
: "Statistics are off, so nothing is sent. If you turned them on, this is what would go out.", Muted),
body,
},
},
close);
await dialog.ShowDialog<object?>(owner);
}
private static TextBlock Para(string text, IBrush brush) =>
new() { Text = text, TextWrapping = TextWrapping.Wrap, Foreground = brush };
private static Window NewWindow(string title, double width) => new()
{
Title = title,
Width = width,
SizeToContent = SizeToContent.Height,
CanResize = false,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Background = Back,
};
private static Control Layout(string title, Control body, params Control[] buttons)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right };
foreach (Control b in buttons) row.Children.Add(b);
return new StackPanel
{
Margin = new Thickness(18),
Spacing = 12,
Children =
{
new TextBlock { Text = title, FontSize = 16, FontWeight = FontWeight.SemiBold, Foreground = Accent },
body,
row,
},
};
}
}