Snapshot for release 2026.10.21.3 (internal 04b831a)

This commit is contained in:
Tom Bohar 2026-10-21 21:03:43 -04:00
commit c4efe5821d
46 changed files with 2657 additions and 213 deletions

View file

@ -6,7 +6,9 @@
.DESCRIPTION
One command per release:
1. Refuses if the signing key isn't set up or isn't trusted by the launcher being shipped,
if either repo has uncommitted changes, or if -Version isn't newer than the live feed.
if either repo has uncommitted changes, or if -Version isn't newer than the live feed;
with -SkipNavData, also if the last published RynthNav map can't be found or isn't on
the server as signed (a feed without it gives new RynthNav players no map).
2. Builds the installer (Build-Installer.ps1 -Version; it includes the Decal bridge, so the
build machine needs Decal installed) and the RynthSuite plugins into
installer\Releases\<release>\ — never into the live C:\Games folders.
@ -46,7 +48,12 @@ param(
# portals.tsv and locations.json from this folder. Only re-uploaded when the set changes
# (its id is a hash of every file); otherwise the live feed's entry is carried over.
[string]$NavDataDir = "C:\Games\RynthCore\NavData",
[switch]$SkipNavData, # leave navdata out of this feed (launchers then keep what they have)
# Build and upload no new RynthNav archive: the feed carries the last published navdata entry
# instead (see "RynthNav's map with -SkipNavData" below). It never ships a feed without the map.
[switch]$SkipNavData,
# With -SkipNavData: an earlier update.json (signed) or update.payload.json whose navdata entry to
# carry, for when neither the live feed nor any kept release manifest has one.
[string]$NavDataFrom = "",
[switch]$NativeAotPlugins, # the old NativeAOT plugin builds (each reload keeps a copy of every one)
# The World Map's optional sizes (RynthNav.Baker --map-world): worldmap-hd.rmap, worldmap-ultra.rmap and worldmap-p32.rmap from this
# folder are offered by the launcher as separate downloads ("mappacks" in the feed). Each is uploaded once under
@ -120,6 +127,23 @@ if (-not $AllowDirty) {
Write-Host " RynthCore $(git -C $RepoRoot rev-parse --short HEAD), RynthSuite $(git -C $RynthSuiteRoot rev-parse --short HEAD), RynthServers $(git -C $RynthServersRoot rev-parse --short HEAD)"
}
# The plugins build against the RynthCore beside RynthSuite (its SDK and build targets), not
# necessarily this checkout. Those targets must derive minEngineApi for release builds
# (RynthPluginSharedSdk, see the plugin build below): with older ones every managed plugin's
# manifest would keep its csproj's stale minimum (66), and launchers would offer it to cores that
# can't even load managed plugins.
$managedPluginApi = 0
if (-not $NativeAotPlugins) {
$sdkTargets = Join-Path (Split-Path $RynthSuiteRoot -Parent) "RynthCore\src\RynthCore.PluginSdk\build\RynthCore.PluginSdk.targets"
$targetsText = if (Test-Path $sdkTargets) { Get-Content $sdkTargets -Raw } else { "" }
$floor = [regex]::Match($targetsText, '<RynthCoreManagedPluginApi>(\d+)</RynthCoreManagedPluginApi>')
if (-not $floor.Success -or $targetsText -notmatch "'\`$\(RynthPluginSharedSdk\)' == 'true'") {
throw "The plugins' SDK build targets ($sdkTargets) don't derive minEngineApi for release builds (RynthPluginSharedSdk). Update the RynthCore checkout beside RynthSuite to one with this script's SDK."
}
$managedPluginApi = [int]$floor.Groups[1].Value
Write-Host " plugin SDK targets: minEngineApi derived per plugin (managed plugins need API $managedPluginApi+)"
}
$liveManifest = $null
try {
$live = Invoke-RestMethod "$BaseUrl/update.json" -TimeoutSec 20
@ -131,6 +155,121 @@ try {
Write-Host " no live feed yet — this is the first release"
}
# ── RynthNav's map with -SkipNavData ─────────────────────────────────────────
# -SkipNavData means "build and upload no new archive", never "ship without the map": the feed
# carries the last published "navdata" entry, the way map packs are carried. It used to drop the
# entry, so every feed from 2026.10.18.1 on had none and a player who added RynthNav got no tiles,
# route graph or World Map (structural audit 2026-10-21, #6). The entry comes from, in order:
# -NavDataFrom, the live feed, then each earlier release's own signed manifest
# (releases/<n>/update.json, kept from 2026.10.19.1 on; releases.json names them, newest first).
# The first one found is used once its archive is checked on the server (size and SHA-256, the
# same ssh + sha256sum check as the uploads); a missing or changed archive, or no entry anywhere,
# stops the release here, before anything is built.
# A manifest's navdata object as the feed writes it (ConvertFrom-Json: whole numbers forced back to
# integers, see the [long] note at the navdata step), or $null when it isn't a usable entry. The
# URL must be inside the feed folder, as the launcher requires (RynthUpdater.CheckUrl).
function ConvertTo-NavDataEntry($nd) {
if (-not $nd) { return $null }
try {
$e = [ordered]@{
id = ([string]$nd.id).ToLowerInvariant()
release = [long]$nd.release
url = [string]$nd.url
size = [long]$nd.size
sha256 = ([string]$nd.sha256).ToLowerInvariant()
files = [long]$nd.files
bytes = [long]$nd.bytes
}
} catch { return $null }
if ($e.id -notmatch '^[0-9a-f]{16,64}$' -or $e.sha256 -notmatch '^[0-9a-f]{64}$' -or $e.size -le 0 -or $e.files -le 0 -or
-not $e.url.StartsWith("$BaseUrl/", [StringComparison]::Ordinal) -or $e.url.Contains("..")) { return $null }
return $e
}
# The manifest in a signed update.json (only when a key the launcher trusts signed it) or in a plain
# update.payload.json (a local release folder's); $null when it can't be read.
function Read-ManifestFile([string]$path) {
try {
$doc = Get-Content $path -Raw | ConvertFrom-Json
if ($doc.payload -and $doc.signatures) {
if (-not (Test-Envelope $path $trusted)) { Write-Warning "$path is not signed by a key the launcher trusts - ignored."; return $null }
return [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($doc.payload)) | ConvertFrom-Json
}
return $doc
} catch { Write-Warning "Can't read ${path}: $($_.Exception.Message)"; return $null }
}
# @{ Entry; From } for the last published navdata entry (see above), or $null.
function Find-PublishedNavData {
if ($NavDataFrom) {
if (-not (Test-Path $NavDataFrom)) { throw "-NavDataFrom: no file at $NavDataFrom" }
$m = Read-ManifestFile $NavDataFrom
$e = if ($m) { ConvertTo-NavDataEntry $m.navdata } else { $null }
if ($null -eq $e) { throw "-NavDataFrom: $NavDataFrom has no usable navdata entry (or isn't signed by a trusted key)." }
return @{ Entry = $e; From = $NavDataFrom }
}
if ($liveManifest) {
$e = ConvertTo-NavDataEntry $liveManifest.navdata
if ($null -ne $e) { return @{ Entry = $e; From = "the live feed (release $($liveManifest.release))" } }
}
$history = @()
try { $history = @((Invoke-RestMethod "$BaseUrl/releases.json" -TimeoutSec 20).releases) }
catch { Write-Warning "releases.json: $($_.Exception.Message)" }
$looked = 0
foreach ($h in $history) {
$v = ([string]$h.version).Split('.')
if ($v.Count -ne 4 -or ($v | Where-Object { $_ -notmatch '^\d+$' })) { continue }
$n = [int]$v[0] * 1000000 + [int]$v[1] * 10000 + [int]$v[2] * 100 + [int]$v[3]
if ($n -ge $release -or $n -lt 2026101901) { continue } # 2026101901: the first release whose manifest is kept
if (++$looked -gt 20) { break }
$tmp = New-TemporaryFile
try {
try { Invoke-WebRequest "$BaseUrl/releases/$n/update.json" -OutFile $tmp -UseBasicParsing -TimeoutSec 20 | Out-Null }
catch { continue }
$m = Read-ManifestFile $tmp
if ($m -and [long]$m.release -eq $n) {
$e = ConvertTo-NavDataEntry $m.navdata
if ($null -ne $e) { return @{ Entry = $e; From = "release $n's signed manifest" } }
}
} finally { Remove-Item $tmp -ErrorAction SilentlyContinue }
}
return $null
}
# The archive an entry names must be on the server exactly as signed: the launcher refuses a download
# whose size or SHA-256 differs, so a feed pointing at a gone or changed file gives players no map.
function Assert-RemoteNavData($e, [string]$from) {
$relPath = $e.url.Substring($BaseUrl.Length + 1)
if ($relPath -notmatch '^[A-Za-z0-9._/-]+$') { throw "RynthNav's map entry from $from has an unexpected URL: $($e.url)" }
$remoteFile = "$RemoteDir/$relPath"
$out = @(ssh $SshHost "stat -c %s '$remoteFile' && sha256sum '$remoteFile'")
if ($LASTEXITCODE -ne 0 -or $out.Count -lt 2) {
throw "RynthNav's map from $from ($remoteFile) is not on the server (or ssh failed) - not publishing a feed without the map. " +
"Leave out -SkipNavData and pass -NavDataDir a complete, finished NavData folder to publish a new archive."
}
$size = [long]("$($out[0])".Trim())
$sum = ("$($out[1])".Trim() -split '\s+')[0].ToLowerInvariant()
if ($size -ne $e.size -or $sum -ne $e.sha256) {
throw "RynthNav's map on the server ($remoteFile) is not the one $from signed (size $size vs $($e.size), sha256 $sum vs $($e.sha256)) - not publishing."
}
Write-Host (" RynthNav map: release {0}'s archive ({1:N0} MB, id {2}) is on the server as signed; from {3}" -f $e.release, ($e.size / 1MB), $e.id, $from)
}
if ($NavDataFrom -and -not $SkipNavData) { throw "-NavDataFrom goes with -SkipNavData (without it the archive is built from -NavDataDir)." }
$carriedNavData = $null
if ($SkipNavData) {
$found = Find-PublishedNavData
if (-not $found) {
throw "-SkipNavData, but neither the live feed nor any kept release manifest has RynthNav's map (navdata), and a feed without it " +
"gives players who add RynthNav no tiles, route graph or World Map - not publishing. Either leave out -SkipNavData and pass " +
"-NavDataDir a complete, finished NavData folder (not one being re-baked) to publish a new archive, or pass -NavDataFrom an " +
"earlier update.json / update.payload.json that has the entry."
}
Assert-RemoteNavData $found.Entry $found.From
$carriedNavData = $found.Entry
}
# ── 2. Build ─────────────────────────────────────────────────────────────────
$rel = Join-Path $ScriptDir "Releases\$release"
if (Test-Path $rel) { Remove-Item $rel -Recurse -Force }
@ -140,8 +279,15 @@ New-Item -ItemType Directory -Force "$rel\plugins", "$rel\build" | Out-Null
# unloaded, so every reload kept a copy of each one - 220-450 MB of address space per reload,
# 2026-10-19). Each managed plugin still ships as one DLL in the feed: their common dependencies
# (RynthCore.PluginSdk, PluginCore, ImGui.NET, MoonSharp, ...) go into the installer's
# Runtime\PluginShared, where the engine (API 88) finds them. The plugins declare minEngineApi 88,
# so an older engine refuses them instead of failing to load them. -NativeAotPlugins: the old builds.
# Runtime\PluginShared, where the engine (API 88) finds them. -NativeAotPlugins: the old builds.
# minEngineApi: -p:RynthPluginSharedSdk=true tells the SDK's build targets that these plugins bind
# the PluginShared SDK, which reaches players only with this release's core. Each plugin's manifest
# then says its own declared minimum when that is 88 or more (a checked claim), else this SDK's API
# (_RynthPluginEffectiveMinEngineApi in RynthCore.PluginSdk.targets explains why). The feed copies
# each plugin's minEngineApi from the manifest embedded in its DLL (below), which is also what the
# engine checks at load and what the launcher's EngineBlocker holds updates by. This used to force
# -p:RynthPluginMinEngineApi=88 on every plugin, a constant that offered plugins calling v89 SDK
# members to API-88 cores (structural audit 2026-10-21, F5 / #7).
$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision", "RynthLua", "RynthOracle", "RynthInventory", "RynthSort", "RynthNet"
# Server plugins (the RynthServers repository since 2026-10-21; ServerPack is SilentKelpie's): one per
# game server, each loaded by the engine only for its own server. They go in the feed only, so the
@ -152,7 +298,7 @@ $serverPlugins = "RynthAChard", "RynthAelrynth", "RynthColdeve", "RynthConquest"
"RynthReefcull", "RynthSundering", "RynthThistlecrown", "RynthThreads"
$managedArgs = if ($NativeAotPlugins) { @() } else {
@("-p:PublishAot=false", "-p:NativeLib=", "-p:SelfContained=false", "-p:RuntimeIdentifier=win-x86",
"-p:GenerateRuntimeConfigurationFiles=false", "-p:RynthPluginMinEngineApi=88")
"-p:GenerateRuntimeConfigurationFiles=false", "-p:RynthPluginSharedSdk=true")
}
function Build-Plugin([string]$name, [string]$label, [string]$root = $RynthSuiteRoot, [string[]]$extra = @()) {
Step "Building $name$label"
@ -266,13 +412,14 @@ Compress-Archive -Path "$zipRoot\*" -DestinationPath "$rel\RynthSuite-Plugins.zi
# RynthNav's data for the launchers (RynthUpdater.NavData.cs): one archive, flat, only the file
# names RynthNav reads. Its id is a hash over every file's name and SHA-256, so an unchanged
# set reuses the live entry (and the archive already on the server) instead of re-uploading.
$navData = $null
# -SkipNavData: the entry found and checked in step 1 (never none).
$navData = $carriedNavData
$navZip = $null
if (-not $SkipNavData) {
Step "RynthNav data (tiles, route graph, portals, Atlas, Town Network, World Map) from $NavDataDir"
$navFiles = @(Get-ChildItem $NavDataDir -File | Where-Object { $_.Name -match '^(nav_[0-9A-Fa-f]{4}\.tile|portals\.tsv|locations\.json|navgraph\.bin|townnet\.json|worldmap\.rmap|worldmap\.vec)$' } | Sort-Object Name)
$tileCount = @($navFiles | Where-Object { $_.Extension -eq ".tile" }).Count
if ($tileCount -eq 0) { throw "$NavDataDir has no tiles. Pass -NavDataDir, or -SkipNavData to publish without them." }
if ($tileCount -eq 0) { throw "$NavDataDir has no tiles. Pass -NavDataDir, or -SkipNavData to carry the last published map." }
# The long-range route graph (RynthNav.Baker --graph) must come from these very tiles: the
# plugin ignores a graph whose tiles don't match (long gotos then walk the straight line).
# The World Map's picture (RynthNav.Baker --map --map-tiles from the dats; the terrain doesn't change between releases).
@ -304,6 +451,7 @@ if (-not $SkipNavData) {
bytes = [long]$navData.bytes
}
Write-Host " unchanged ($($navFiles.Count) files, id $navId): the live archive from release $($navData.release) stays"
Assert-RemoteNavData $navData "the live feed"
} else {
$navZip = "$rel\RynthNav-NavData.zip"
Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem
@ -408,8 +556,12 @@ $plugins = foreach ($dll in Get-ChildItem "$rel\plugins\*.dll" | Sort-Object Nam
if ($pm) {
if ($pm.name -ne $pluginName) { throw "$($dll.Name): its manifest says '$($pm.name)', the feed would say '$pluginName'." }
if ($pm.version -and $pm.version -ne $Version) { throw "$($dll.Name): its manifest is version $($pm.version), not $Version (stale build?)." }
# The plugin's own minimum, as its build wrote it into the DLL (see the plugin build above).
$min = [int]$pm.minEngineApi
if ($min -gt $engineApi) { throw "$($dll.Name) needs engine API $min but this release's engine is $engineApi - it would never load." }
if ($managedPluginApi -gt 0 -and $min -lt $managedPluginApi) {
throw "$($dll.Name): its manifest says engine API $min, but a managed plugin needs $managedPluginApi just to load - launchers would offer it to cores that can't run it (stale SDK targets beside RynthSuite?)."
}
if ($min -gt 0) { $entry.minEngineApi = $min }
Write-Host " $pluginName $($pm.version): engine API $min+"
} else {
@ -437,7 +589,9 @@ $manifest = [ordered]@{
}
plugins = @($plugins)
}
if ($navData) { $manifest.navdata = $navData }
# Every feed carries RynthNav's map (built above, unchanged from the live feed, or carried by -SkipNavData).
if (-not $navData) { throw "No RynthNav map (navdata) for this feed - not publishing a feed without it." }
$manifest.navdata = $navData
if ($mapPacks.Count -gt 0) { $manifest.mappacks = @($mapPacks) }
Set-Content "$rel\update.payload.json" ($manifest | ConvertTo-Json -Depth 5) -Encoding utf8NoBOM
& (Join-Path $ScriptDir "Sign-Update.ps1") -PayloadPath "$rel\update.payload.json" -OutPath "$rel\update.json" -KeyDir $KeyDir
@ -467,6 +621,10 @@ scp -q "$rel\RynthCore-Setup.exe" "${SshHost}:$remoteRel/RynthCore-Setup.exe"
if ($LASTEXITCODE -ne 0) { throw "scp of the installer failed" }
scp -q (Get-ChildItem "$rel\plugins\*.dll").FullName "${SshHost}:$remoteRel/plugins/"
if ($LASTEXITCODE -ne 0) { throw "scp of the plugins failed" }
# The release's own signed manifest stays beside its files: the launcher's Roll back
# (RynthUpdater.Rollback.cs) verifies it to go back to this release later.
scp -q "$rel\update.json" "${SshHost}:$remoteRel/update.json"
if ($LASTEXITCODE -ne 0) { throw "scp of the release's update.json failed" }
$navSum = ""
if ($navZip) {
scp -q $navZip "${SshHost}:$remoteRel/RynthNav-NavData.zip"
@ -491,8 +649,9 @@ foreach ($up in $mapPackUploads) {
Write-Host " $($up.Remote): uploaded and hash-checked"
}
$remoteSums = ssh $SshHost "cd '$remoteRel' && sha256sum RynthCore-Setup.exe plugins/*.dll$navSum"
$expect = @{ "RynthCore-Setup.exe" = $manifest.core.sha256 }
$remoteSums = ssh $SshHost "cd '$remoteRel' && sha256sum RynthCore-Setup.exe update.json plugins/*.dll$navSum"
$expect = @{ "RynthCore-Setup.exe" = $manifest.core.sha256
"update.json" = (Get-FileHash "$rel\update.json" -Algorithm SHA256).Hash.ToLowerInvariant() }
if ($navZip) { $expect["RynthNav-NavData.zip"] = $navData.sha256 }
foreach ($pl in $plugins) { $expect["plugins/$($pl.file)"] = $pl.sha256 }
foreach ($line in $remoteSums) {
@ -500,6 +659,9 @@ foreach ($line in $remoteSums) {
if ($expect[$name.TrimStart('*')] -ne $sum) { throw "Hash mismatch on the server for $name — feed NOT published" }
}
Write-Host " $($expect.Count) files uploaded and hash-checked"
# A carried RynthNav archive (not uploaded by this release) is checked once more just before the
# feed that points at it goes live.
if (-not $navZip) { Assert-RemoteNavData $navData "this feed" }
Step "Replacing the website downloads"
scp -q "$rel\RynthCore-Setup.exe" "${SshHost}:$RemoteDir/.RynthCore-Setup.exe.new"

View file

@ -7,6 +7,10 @@
WindowStartupLocation="CenterOwner"
Title="Account Profile"
Background="#132028">
<Window.Resources>
<!-- The "show password" eye (the same one in FirstLoginDialog.axaml). -->
<StreamGeometry x:Key="EyeIcon">F0 M8,3 C4.4,3 1.6,5.3 0.5,8 C1.6,10.7 4.4,13 8,13 C11.6,13 14.4,10.7 15.5,8 C14.4,5.3 11.6,3 8,3 Z M8,4.3 C5.3,4.3 3,5.9 2,8 C3,10.1 5.3,11.7 8,11.7 C10.7,11.7 13,10.1 14,8 C13,5.9 10.7,4.3 8,4.3 Z M8,5.5 A2.5,2.5 0 1 1 8,10.5 A2.5,2.5 0 1 1 8,5.5 Z</StreamGeometry>
</Window.Resources>
<Grid RowDefinitions="*,Auto" Margin="18">
<StackPanel Spacing="12">
<TextBlock Text="Server" Foreground="#EAF0F4" />
@ -14,10 +18,22 @@
<TextBlock Text="Account" Foreground="#EAF0F4" />
<TextBox x:Name="AccountBox" />
<TextBlock Text="Password" Foreground="#EAF0F4" />
<TextBox x:Name="PasswordBox"
PasswordChar="*"
RevealPassword="False"
Watermark="Leave blank to keep the saved password hidden" />
<!-- The eye shows the password; with the box empty, the saved one (SavedPasswordReveal). -->
<Grid ColumnDefinitions="*,Auto">
<TextBox x:Name="PasswordBox"
Grid.Column="0"
Margin="0,0,6,0"
PasswordChar="*"
RevealPassword="False"
Watermark="Leave blank to keep the saved password" />
<ToggleButton x:Name="ShowPasswordToggle"
Grid.Column="1"
VerticalAlignment="Stretch"
ToolTip.Tip="Show password"
AutomationProperties.Name="Show password">
<PathIcon Data="{StaticResource EyeIcon}" Width="16" Height="16" />
</ToggleButton>
</Grid>
<CheckBox x:Name="ClearPasswordCheckBox"
Content="Clear saved password"
Foreground="#EAF0F4" />

View file

@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Platform.Storage;
using RynthCore.App;
@ -13,6 +14,8 @@ internal partial class AccountProfileDialog : Window
private readonly LaunchAccountProfile _profile;
private readonly List<LaunchServerProfile> _servers;
private readonly Func<string, string, List<string>> _knownCharactersFor;
// The eye beside the password box; it keeps no copy of the password.
private readonly SavedPasswordReveal _passwordReveal;
private List<string> _knownCharacters = [];
// Set once the player picks in "Log in as"; until then the saved choice is kept as it is
@ -27,6 +30,7 @@ internal partial class AccountProfileDialog : Window
_profile = profile;
_servers = servers;
_knownCharactersFor = knownCharactersFor;
_passwordReveal = SavedPasswordReveal.For(profile);
InitializeComponent();
ServerComboBox.ItemsSource = _servers.Select(s => s.DisplayName).ToList();
@ -41,7 +45,7 @@ internal partial class AccountProfileDialog : Window
? "Password needs re-entering: the saved one can't be read on this Windows user (settings copied from another user or PC?). Type it again to launch this account."
: !profile.HasSavedPassword
? "No password is saved for this profile yet. The game client won't start without one; you'll be asked for it on the first launch."
: "A password is saved for this profile, encrypted for this Windows user. It stays hidden unless you replace or clear it.";
: "A password is saved for this profile, encrypted for this Windows user. The eye shows it; type a new one to replace it.";
ServerComboBox.SelectionChanged += (_, _) => RefreshLoginAs();
AccountBox.TextChanged += (_, _) => RefreshLoginAs();
@ -52,12 +56,34 @@ internal partial class AccountProfileDialog : Window
};
RefreshLoginAs();
ShowPasswordToggle.IsCheckedChanged += (_, _) => OnShowPasswordChanged();
// The plain text lives only in the box, and only while the dialog is open.
Closed += (_, _) =>
{
PasswordBox.Text = string.Empty;
_passwordReveal.Reset();
};
SaveButton.Click += (_, _) => SaveAndClose();
CancelButton.Click += (_, _) => Close(false);
BrowseUserPrefsButton.Click += async (_, _) => await BrowseUserPrefsAsync();
SnapshotUserPrefsButton.Click += (_, _) => SnapshotLiveUserPrefs();
}
/// <summary>
/// The eye: on shows what's typed, or the saved password (decrypted now) when the box is empty;
/// off hides it and empties the box again if it still holds the saved password unchanged.
/// </summary>
private void OnShowPasswordChanged()
{
bool show = ShowPasswordToggle.IsChecked == true;
PasswordBox.Text = show ? _passwordReveal.EyeOn(PasswordBox.Text) : _passwordReveal.EyeOff(PasswordBox.Text);
PasswordBox.RevealPassword = show;
string tip = show ? SavedPasswordReveal.HideTip : SavedPasswordReveal.ShowTip;
ToolTip.SetTip(ShowPasswordToggle, tip);
AutomationProperties.SetName(ShowPasswordToggle, tip);
}
/// <summary>Lists the characters known for the account on the chosen server in "Log in as".</summary>
private void RefreshLoginAs()
{
@ -181,12 +207,14 @@ internal partial class AccountProfileDialog : Window
{
_profile.ClearPassword();
}
else if (!string.IsNullOrEmpty(PasswordBox.Text))
else if (_passwordReveal.PasswordToSave(PasswordBox.Text) is string newPassword)
{
// Encrypted at once (DPAPI, this Windows user); the plain text isn't kept on the profile.
_profile.SetPassword(PasswordBox.Text);
// A blank box, or the saved password the eye showed left unchanged, keeps the saved one.
_profile.SetPassword(newPassword);
}
PasswordBox.Text = string.Empty;
_passwordReveal.Reset();
_profile.Alias = AliasBox.Text?.Trim() ?? string.Empty;
_profile.UserPrefsPath = UserPrefsPathBox.Text?.Trim() ?? string.Empty;

View file

@ -7,7 +7,7 @@ namespace RynthCore.App.Avalonia;
/// <summary>
/// Read-modify-write access to %APPDATA%\RynthCore\engine.json. The launcher
/// owns a few engine-side flags (DComp overlay toggle, plugin paths, etc.)
/// owns a few engine-side flags (plugin paths, etc.)
/// but the engine has its own flags that the launcher should never overwrite
/// (EnableImGuiShell, EnableImGuiBackend, EngineHookCount, ...). This helper
/// preserves every field it doesn't touch so those don't get clobbered when

View file

@ -7,6 +7,10 @@
WindowStartupLocation="CenterOwner"
Title="First Login"
Background="#132028">
<Window.Resources>
<!-- The same eye as the account editor's (AccountProfileDialog.axaml). -->
<StreamGeometry x:Key="EyeIcon">F0 M8,3 C4.4,3 1.6,5.3 0.5,8 C1.6,10.7 4.4,13 8,13 C11.6,13 14.4,10.7 15.5,8 C14.4,5.3 11.6,3 8,3 Z M8,4.3 C5.3,4.3 3,5.9 2,8 C3,10.1 5.3,11.7 8,11.7 C10.7,11.7 13,10.1 14,8 C13,5.9 10.7,4.3 8,4.3 Z M8,5.5 A2.5,2.5 0 1 1 8,10.5 A2.5,2.5 0 1 1 8,5.5 Z</StreamGeometry>
</Window.Resources>
<Grid RowDefinitions="*,Auto" Margin="18">
<StackPanel Spacing="10">
<TextBlock x:Name="HeaderText" Foreground="#EAF0F4" FontSize="16" FontWeight="SemiBold" TextWrapping="Wrap" />
@ -22,9 +26,22 @@
<StackPanel x:Name="PasswordPanel" Spacing="10">
<TextBlock Text="Password" Foreground="#EAF0F4" />
<TextBox x:Name="PasswordBox" PasswordChar="*" RevealPassword="False" />
<!-- The eyes only reveal what's typed (nothing is saved yet to show). -->
<Grid ColumnDefinitions="*,Auto">
<TextBox x:Name="PasswordBox" Grid.Column="0" Margin="0,0,6,0" PasswordChar="*" RevealPassword="False" />
<ToggleButton x:Name="ShowPasswordToggle" Grid.Column="1" VerticalAlignment="Stretch"
ToolTip.Tip="Show password" AutomationProperties.Name="Show password">
<PathIcon Data="{StaticResource EyeIcon}" Width="16" Height="16" />
</ToggleButton>
</Grid>
<TextBlock Text="Confirm password" Foreground="#EAF0F4" />
<TextBox x:Name="ConfirmBox" PasswordChar="*" RevealPassword="False" />
<Grid ColumnDefinitions="*,Auto">
<TextBox x:Name="ConfirmBox" Grid.Column="0" Margin="0,0,6,0" PasswordChar="*" RevealPassword="False" />
<ToggleButton x:Name="ShowConfirmToggle" Grid.Column="1" VerticalAlignment="Stretch"
ToolTip.Tip="Show password" AutomationProperties.Name="Show password">
<PathIcon Data="{StaticResource EyeIcon}" Width="16" Height="16" />
</ToggleButton>
</Grid>
</StackPanel>
<TextBlock Text="The password is saved encrypted for this Windows user, like the other accounts."
Foreground="#9AA8B3" TextWrapping="Wrap" />

View file

@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using RynthCore.App;
namespace RynthCore.App.Avalonia;
@ -53,12 +55,31 @@ internal partial class FirstLoginDialog : Window
AccountBox.TextChanged += (_, _) => OnAccountChanged();
ReuseSavedPasswordCheckBox.IsCheckedChanged += (_, _) => UpdatePasswordPanel();
ShowPasswordToggle.IsCheckedChanged += (_, _) => Reveal(PasswordBox, ShowPasswordToggle);
ShowConfirmToggle.IsCheckedChanged += (_, _) => Reveal(ConfirmBox, ShowConfirmToggle);
// The plain text lives only in the boxes, and only while the dialog is open.
Closed += (_, _) =>
{
PasswordBox.Text = string.Empty;
ConfirmBox.Text = string.Empty;
};
LoginButton.Click += (_, _) => LogInAndClose();
CancelButton.Click += (_, _) => Close(false);
OnAccountChanged();
}
/// <summary>An eye: shows or hides what's typed in its box (nothing saved to fill in here).</summary>
private static void Reveal(TextBox box, ToggleButton eye)
{
bool show = eye.IsChecked == true;
box.RevealPassword = show;
string tip = show ? SavedPasswordReveal.HideTip : SavedPasswordReveal.ShowTip;
ToolTip.SetTip(eye, tip);
AutomationProperties.SetName(eye, tip);
}
/// <summary>Re-reads the account's characters and whether another profile's password can be reused.</summary>
private void OnAccountChanged()
{

View file

@ -110,8 +110,9 @@
<Grid Grid.Row="1" ColumnDefinitions="3*,Auto,2*">
<TabControl x:Name="MainTabs" Grid.Column="0" Margin="14,0,0,0" Padding="0">
<TabItem Header="Launcher">
<!-- Named so we can reset Offset on tab select; * rows inside this scroll
must not be used (they claim infinite height and clip Updates/Launch Targets). -->
<!-- Named so the tab keeps the player's scroll position (MainWindow.KeepLauncherScroll);
* rows inside this scroll must not be used (they claim infinite height and clip
Updates/Launch Targets). -->
<ScrollViewer x:Name="LauncherScroll"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled">
@ -130,6 +131,8 @@
<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" />
<Button x:Name="RollbackButton" Content="Roll back…" Margin="8,0,0,6" IsVisible="False"
ToolTip.Tip="Go back to an earlier RynthCore release if this one broke something. Updates then wait for a newer release." />
</WrapPanel>
</Grid>
<StackPanel x:Name="UpdateCardWhatsNewPanel" Spacing="2" IsVisible="False" />
@ -383,9 +386,9 @@
<TextBox x:Name="EnginePathTextBox" Watermark="C:\Games\RynthCore\Runtime\RynthCore.Engine.dll" />
<TextBlock Text="Extra Launch Arguments" Foreground="#EAF0F4" />
<TextBox x:Name="LaunchArgumentsTextBox"
Watermark="Optional arguments appended by the host"
AcceptsReturn="True"
MinHeight="64"
Watermark="Optional arguments added after each account's login"
ToolTip.Tip="Added to the end of every launch's command line, after the account, password and server the profiles set. It can't contain -a, -v, -h, -p or -rodat: set those in the account and server profiles. One line."
AcceptsReturn="False"
TextWrapping="Wrap" />
<Button x:Name="SavePathsButton"
Content="Save Runtime Paths"
@ -458,9 +461,6 @@
<TextBlock Text="These flags are read by RynthCore.Engine on each AC client launch. They write to %APPDATA%\RynthCore\engine.json — other engine flags in that file are preserved untouched."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<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)." />

View file

@ -106,6 +106,8 @@ internal partial class MainWindow : Window
private readonly Dictionary<string, DateTime> _autoLaunchAttemptTimesUtc = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DateTime> _autoLaunchServerDownNoticeTimesUtc = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DateTime> _autoLaunchNeedsPasswordNoticeTimesUtc = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DateTime> _autoLaunchNoServerNoticeTimesUtc = new(StringComparer.OrdinalIgnoreCase);
private DateTime _extraArgumentsNoticeUtc = DateTime.MinValue;
private readonly Dictionary<string, ServerAvailabilityState> _serverStatuses = new(StringComparer.OrdinalIgnoreCase);
private readonly List<PluginDefinition> _plugins =
[
@ -165,36 +167,80 @@ internal partial class MainWindow : Window
_updateTimer.Tick += async (_, _) => await CheckForUpdatesAsync();
_updateTimer.Start();
_ = CheckForUpdatesAsync();
// Keep Updates + Launch Targets reachable: a bad * row under this scroll used to
// leave Offset stuck with those cards clipped above the viewport.
MainTabs.SelectionChanged += (_, _) =>
{
if (MainTabs.SelectedIndex == 0)
ResetLauncherScrollToTop();
};
WireLauncherScroll();
Opened += async (_, _) =>
{
ResetLauncherScrollToTop();
await AskAboutUsageStatsOnceAsync();
await CleanUpDecalBridgeIfUnusedAsync(atStartup: true);
await CheckFolderAccessAtStartupAsync(); // MainWindow.FolderAccess.cs: can the game client save?
};
}
/// <summary>
/// Scroll the Launcher tab back to the top so Updates and Launch Targets stay reachable.
/// </summary>
private void ResetLauncherScrollToTop()
// ── The Launcher tab keeps the player's scroll position ───────────────────
// Player report R-20261021-183803-97c0: scrolled down, the tab jumped back to the top. It was
// reset on every SelectionChanged that reached the tab control, and that event bubbles: every
// ComboBox and ListBox inside the tabs raised it there too, and the launch targets' character
// dropdowns are refilled every 2 s (RefreshLaunchTargetCharacterSelections), the server list
// every 15 s, the lists whenever a profile changes. Now only the tab control's own selection
// counts, and selecting the tab puts the player back where they were.
// The reset worked around an earlier layout bug (a * row in the profile cards under this
// scroll left Updates and Launch Targets clipped above the viewport). That is fixed in the
// layout itself (all-Auto rows, MaxHeight on the lists, MainWindow.axaml), the ScrollViewer
// clamps a restored offset to the content's current height, and the Plugins tab's update
// button still opens this tab at the top, where the update card is.
private global::Avalonia.Vector _launcherScrollOffset;
private bool _launcherScrollRestorePending;
private void WireLauncherScroll()
{
try { LauncherScroll.Offset = new global::Avalonia.Vector(0, 0); }
catch { /* designer / pre-init */ }
// ScrollChanged bubbles too (the Launch Targets list and the profile lists scroll inside).
LauncherScroll.ScrollChanged += (_, e) =>
{
if (ReferenceEquals(e.Source, LauncherScroll) && MainTabs.SelectedIndex == 0 && !_launcherScrollRestorePending)
_launcherScrollOffset = LauncherScroll.Offset;
};
MainTabs.SelectionChanged += (_, e) =>
{
if (ReferenceEquals(e.Source, MainTabs) && MainTabs.SelectedIndex == 0)
KeepLauncherScroll();
};
}
/// <summary>
/// Puts the Launcher tab back where the player had it once layout has run: called when the tab
/// is selected again and before its content is refilled (lists, launch targets, update card).
/// Runs before input, so it never undoes the player's own scrolling.
/// </summary>
private void KeepLauncherScroll()
{
if (_launcherScrollRestorePending)
return;
_launcherScrollRestorePending = true;
Dispatcher.UIThread.Post(() =>
{
_launcherScrollRestorePending = false;
try
{
if (MainTabs.SelectedIndex == 0 && LauncherScroll.Offset != _launcherScrollOffset)
LauncherScroll.Offset = _launcherScrollOffset; // clamped to the content by the ScrollViewer
}
catch { /* window closing */ }
}, DispatcherPriority.Loaded);
}
/// <summary>The Plugins tab's "show the update card": the Launcher tab, at the top.</summary>
private void ShowLauncherTabAtTop()
{
_launcherScrollOffset = default;
MainTabs.SelectedIndex = 0;
KeepLauncherScroll(); // also when the tab was already showing
}
private void WireEvents()
{
AddServerButton.Click += async (_, _) => await AddServerAsync();
EditServerButton.Click += async (_, _) => await EditServerAsync();
DeleteServerButton.Click += (_, _) => DeleteServer();
DeleteServerButton.Click += async (_, _) => await DeleteServerAsync();
AddAccountButton.Click += async (_, _) => await AddAccountAsync();
EditAccountButton.Click += async (_, _) => await EditAccountAsync();
@ -217,10 +263,11 @@ internal partial class MainWindow : Window
FixFolderPermissionsButton.Click += async (_, _) => await FixFolderPermissionsAsync();
AddPluginDllButton.Click += async (_, _) => await AddPluginDllAsync();
CheckUpdatesButton.Click += async (_, _) => await CheckForUpdatesAsync();
RollbackButton.Click += async (_, _) => await RollBackAsync();
UpdateCardActionButton.Click += async (_, _) => await OnUpdateCardActionAsync();
CancelDownloadButton.Click += (_, _) => CancelDownload();
UpdateCardNewPluginsButton.Click += (_, _) => ShowAvailablePlugins();
ShowUpdateCardButton.Click += (_, _) => MainTabs.SelectedIndex = 0;
ShowUpdateCardButton.Click += (_, _) => ShowLauncherTabAtTop();
AutoUpdatePluginsCheckBox.IsChecked = _settings.AutoUpdatePlugins;
AutoUpdatePluginsCheckBox.IsCheckedChanged += (_, _) =>
{
@ -336,6 +383,12 @@ internal partial class MainWindow : Window
? _settings.EnginePath
: _injector.TryResolveEnginePath(null) ?? string.Empty;
LaunchArgumentsTextBox.Text = _settings.LaunchArguments;
// A whole-line override saved by an older launcher (with -a/-v/-h) would now ride along
// on every account: launches refuse it, so say so up front.
if (AcLaunchArgumentBuilder.ExtraArgumentsProblem(_settings.LaunchArguments, out _) is string extraProblem)
{
try { AppendActivity($"Runtime > Extra Launch Arguments: {extraProblem} Launches are blocked until it is fixed."); } catch { }
}
AllowMultipleClientsCheckBox.IsChecked = _settings.AllowMultipleClients;
SkipIntroVideosCheckBox.IsChecked = _settings.SkipIntroVideos;
@ -355,8 +408,9 @@ internal partial class MainWindow : Window
// Engine flags live in %APPDATA%\RynthCore\engine.json, not the
// launcher's own settings. The engine reads them on init; the launcher
// just provides a UI window into the same file.
EnableDcompOverlayCheckBox.IsChecked = EngineJsonStore.GetBool("EnableDcompOverlay") ?? false;
EnableDcompOverlayCheckBox.IsCheckedChanged += OnEnableDcompOverlayChanged;
// (No "Use DComp overlay" box any more: the DComp overlay is an Avalonia app, and the
// shipped CoreCLR engine runs without Avalonia (EngineSettings.EnableAvaloniaOverlay is
// always false there), so EnableDcompOverlay changed nothing. A saved key is left alone.)
// The engine treats a missing key as true.
EnableImGuiBackendCheckBox.IsChecked = EngineJsonStore.GetBool("EnableImGuiBackend") ?? true;
EnableImGuiBackendCheckBox.IsCheckedChanged += OnEnableImGuiBackendChanged;
@ -376,20 +430,6 @@ internal partial class MainWindow : Window
}
}
private void OnEnableDcompOverlayChanged(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
{
bool value = EnableDcompOverlayCheckBox.IsChecked == true;
try
{
EngineJsonStore.SetBool("EnableDcompOverlay", value);
AppendActivity($"Engine setting saved: EnableDcompOverlay={value}. Takes effect on next AC client launch.");
}
catch (Exception ex)
{
AppendActivity($"Failed to save EnableDcompOverlay to engine.json: {ex.Message}");
}
}
private void BuildPluginLoadout()
{
PluginLoadoutPanel.Children.Clear();
@ -674,6 +714,7 @@ internal partial class MainWindow : Window
private void RefreshLists()
{
KeepLauncherScroll();
_suppressPrimarySelectionChanged = true;
try
{
@ -693,9 +734,19 @@ internal partial class MainWindow : Window
private void RefreshSummary()
{
LaunchServerProfile? server = GetSelectedServer();
LaunchAccountProfile? account = GetSelectedAccount();
// The preview shows what a launch does: the account on its own server, not on the one
// selected in the server list (the launch never uses that one for it).
LaunchServerProfile? server = account != null ? ResolveServerForAccount(account) : null;
int checkedTargets = _settings.CheckedLaunchAccountProfileIds?.Count ?? 0;
if (account != null && server == null)
{
string noServer = $"{account.DisplayName}: {AccountServerRules.NoServerMessage(account, _settings.ServerProfiles.Count > 0)}";
SummaryText.Text = noServer;
LaunchProfileStatusText.Text = noServer;
LaunchPreviewText.Text = noServer;
return;
}
if (server == null || account == null)
{
SummaryText.Text = checkedTargets == 0
@ -774,13 +825,24 @@ internal partial class MainWindow : Window
await RefreshServerStatusesAsync();
}
private void DeleteServer()
private async Task DeleteServerAsync()
{
int index = ServerProfilesList.SelectedIndex;
if (index < 0 || index >= _settings.ServerProfiles.Count)
return;
string removedServerId = _settings.ServerProfiles[index].Id;
// Refused while accounts log on to it: they are never moved to another server (their
// passwords belong to this one). AccountServerRules says why refusing beats clearing.
LaunchServerProfile toRemove = _settings.ServerProfiles[index];
if (AccountServerRules.DeleteBlocker(toRemove, _settings.AccountProfiles) is string blocker)
{
AppendActivity($"Server not deleted: {toRemove.DisplayName} still has " +
$"{AccountServerRules.AccountsOn(toRemove, _settings.AccountProfiles).Count} account(s). Move or delete them first.");
await DecalBridgeDialog.InfoAsync(this, "Server still in use", blocker);
return;
}
string removedServerId = toRemove.Id;
bool removedSelected = string.Equals(removedServerId, _settings.SelectedServerProfileId, StringComparison.OrdinalIgnoreCase);
_settings.ServerProfiles.RemoveAt(index);
if (removedSelected)
@ -790,7 +852,7 @@ internal partial class MainWindow : Window
RefreshLists();
ServerProfilesList.SelectedIndex = Math.Min(index, _settings.ServerProfiles.Count - 1);
RefreshSummary();
AppendActivity($"Server removed: {index + 1}");
AppendActivity($"Server removed: {toRemove.DisplayName}");
}
private async System.Threading.Tasks.Task AddAccountAsync()
@ -973,6 +1035,7 @@ internal partial class MainWindow : Window
private void RefreshLaunchTargets()
{
KeepLauncherScroll();
LaunchTargetsPanel.Children.Clear();
_launchTargetStatusTexts.Clear();
_launchTargetChecks.Clear();
@ -986,13 +1049,10 @@ internal partial class MainWindow : Window
{
LaunchAccountProfile account = _settings.AccountProfiles[accountIndex];
// Try to find the associated server, or fallback to the first one if not set or invalid
LaunchServerProfile? server = _settings.ServerProfiles.FirstOrDefault(s => s.Id == account.ServerId);
if (server == null && _settings.ServerProfiles.Count > 0)
{
server = _settings.ServerProfiles.FirstOrDefault();
account.ServerId = server?.Id ?? string.Empty;
}
// The account's own server only. An account whose server is missing used to be bound
// to the first server here (and saved), which sent its password to that server on
// the next launch; now it shows "No Server" and can't launch (AccountServerRules).
LaunchServerProfile? server = ResolveServerForAccount(account);
var container = new Grid
{
@ -1118,7 +1178,7 @@ internal partial class MainWindow : Window
button.Click += async (_, _) =>
{
LaunchServerProfile? server = _settings.ServerProfiles.FirstOrDefault(s => s.Id == account.ServerId);
LaunchServerProfile? server = ResolveServerForAccount(account);
var dialog = new LoginCommandsDialog(account, server);
await dialog.ShowDialog(this);
if (dialog.ChangesSaved)
@ -1524,11 +1584,15 @@ internal partial class MainWindow : Window
return;
}
// Ensure the account is associated with the currently selected server if it doesn't have one
// An account that never had a server (added before any server existed) takes the one
// selected beside it, at the player's click and said in Activity. An account that names
// a server, even a deleted one, is never changed here (AccountServerRules).
LaunchServerProfile? selectedServer = GetSelectedServer();
if (selectedServer != null && string.IsNullOrEmpty(account.ServerId))
if (selectedServer != null && string.IsNullOrWhiteSpace(account.ServerId))
{
account.ServerId = selectedServer.Id;
SaveSettings();
AppendActivity($"{account.DisplayName} had no server; it now logs on to {selectedServer.DisplayName}.");
}
_settings.CheckedLaunchAccountProfileIds ??= [];
@ -1553,7 +1617,11 @@ internal partial class MainWindow : Window
SaveSettings();
RefreshSummary();
if (appendActivity)
{
AppendActivity("Runtime paths saved.");
if (AcLaunchArgumentBuilder.ExtraArgumentsProblem(_settings.LaunchArguments, out _) is string extraProblem)
AppendActivity($"Launches are blocked until this is fixed: {extraProblem}");
}
}
private void SaveLaunchBehavior(bool appendActivity = true)
@ -1661,10 +1729,17 @@ internal partial class MainWindow : Window
return;
}
string overrideArguments = isAutomaticLaunch ? string.Empty : LaunchArgumentsTextBox.Text?.Trim() ?? string.Empty;
if (!string.IsNullOrWhiteSpace(overrideArguments) && accountsToLaunch.Count > 1)
// Extra Launch Arguments go after each account's own arguments, for manual and automatic
// launches alike. They used to replace the whole line instead (and only manually, one
// account at a time); ExtraArgumentsProblem refuses what an old override would carry.
if (AcLaunchArgumentBuilder.ExtraArgumentsProblem(LaunchArgumentsTextBox.Text, out string extraArguments) is string extraProblem)
{
AppendActivity("Launch blocked: manual launch arguments can only be used with one account at a time.");
DateTime nowUtc = DateTime.UtcNow;
if (!isAutomaticLaunch || nowUtc - _extraArgumentsNoticeUtc >= AutoLaunchNeedsPasswordLogCooldown)
{
_extraArgumentsNoticeUtc = nowUtc;
AppendActivity($"Launch blocked: {extraProblem}");
}
return;
}
@ -1710,26 +1785,23 @@ internal partial class MainWindow : Window
// No usable password: the client would refuse to start ("You can only run the game from
// the launcher program") and exit within seconds. A manual launch asks for it (and the
// account) in the First Login dialog; an automatic one skips the account.
if (string.IsNullOrWhiteSpace(overrideArguments))
var ready = new List<LaunchAccountProfile>(accountsToLaunch.Count);
foreach (LaunchAccountProfile account in accountsToLaunch)
{
var ready = new List<LaunchAccountProfile>(accountsToLaunch.Count);
foreach (LaunchAccountProfile account in accountsToLaunch)
{
if (!AcLaunchArgumentBuilder.NeedsPassword(account))
ready.Add(account);
else if (isAutomaticLaunch)
AppendActivity($"Auto launch skipped for {account.DisplayName}: {AcLaunchArgumentBuilder.MissingPasswordMessage(account.AccountName)}");
else if (await PromptFirstLoginAsync(account))
ready.Add(account);
else
AppendActivity($"Launch cancelled for {account.DisplayName}: no password entered.");
}
if (ready.Count == 0)
return;
accountsToLaunch = ready;
if (!AcLaunchArgumentBuilder.NeedsPassword(account))
ready.Add(account);
else if (isAutomaticLaunch)
AppendActivity($"Auto launch skipped for {account.DisplayName}: {AcLaunchArgumentBuilder.MissingPasswordMessage(account.AccountName)}");
else if (await PromptFirstLoginAsync(account))
ready.Add(account);
else
AppendActivity($"Launch cancelled for {account.DisplayName}: no password entered.");
}
if (ready.Count == 0)
return;
accountsToLaunch = ready;
SaveRuntimePaths(appendActivity: !isAutomaticLaunch);
SaveLaunchBehavior(appendActivity: !isAutomaticLaunch);
@ -1771,7 +1843,7 @@ internal partial class MainWindow : Window
{
if (!TryGetLaunchArgumentsForAccount(
account,
allowArgumentOverride: !isAutomaticLaunch,
extraArguments,
out string launchArguments,
out string launchSummary,
out string error))
@ -2100,7 +2172,7 @@ internal partial class MainWindow : Window
LaunchServerProfile? server = ResolveServerForAccount(account);
if (server == null)
{
AppendActivity($"Launch blocked for {account.DisplayName}: add a server profile first.");
AppendActivity($"Launch blocked for {account.DisplayName}: {AccountServerRules.NoServerMessage(account, _settings.ServerProfiles.Count > 0)}");
return false;
}
@ -2163,38 +2235,27 @@ internal partial class MainWindow : Window
SessionStateStore.WriteForProcess(processId, record);
}
/// <param name="extraArguments">Extra Launch Arguments, already checked by
/// <see cref="AcLaunchArgumentBuilder.ExtraArgumentsProblem"/>; appended after the account's own.</param>
private bool TryGetLaunchArgumentsForAccount(
LaunchAccountProfile account,
bool allowArgumentOverride,
string extraArguments,
out string arguments,
out string launchSummary,
out string error)
{
string overrideArguments = allowArgumentOverride
? LaunchArgumentsTextBox.Text?.Trim() ?? string.Empty
: string.Empty;
if (!string.IsNullOrWhiteSpace(overrideArguments))
{
arguments = overrideArguments;
launchSummary = string.IsNullOrWhiteSpace(account.DisplayName)
? "Manual argument override"
: $"Manual argument override / {account.DisplayName}";
error = string.Empty;
return true;
}
LaunchServerProfile? server = ResolveServerForAccount(account);
if (server == null)
{
arguments = string.Empty;
launchSummary = string.Empty;
error = "Select a server profile, or enter manual launch arguments.";
error = AccountServerRules.NoServerMessage(account, _settings.ServerProfiles.Count > 0);
return false;
}
try
{
arguments = _launchArgumentBuilder.BuildArguments(server, account);
arguments = AcLaunchArgumentBuilder.WithExtraArguments(_launchArgumentBuilder.BuildArguments(server, account), extraArguments);
launchSummary = _launchArgumentBuilder.Describe(server, account);
error = string.Empty;
return true;
@ -2208,18 +2269,12 @@ internal partial class MainWindow : Window
}
}
private LaunchServerProfile? ResolveServerForAccount(LaunchAccountProfile account)
{
if (!string.IsNullOrWhiteSpace(account.ServerId))
{
LaunchServerProfile? savedServer = _settings.ServerProfiles.FirstOrDefault(server =>
string.Equals(server.Id, account.ServerId, StringComparison.OrdinalIgnoreCase));
if (savedServer != null)
return savedServer;
}
return GetSelectedServer() ?? _settings.ServerProfiles.FirstOrDefault();
}
/// <summary>
/// The server profile the account names, or null. No fallback to the selected or first
/// server: that would send this account's password to a server it doesn't belong to.
/// </summary>
private LaunchServerProfile? ResolveServerForAccount(LaunchAccountProfile account) =>
AccountServerRules.ServerFor(account, _settings.ServerProfiles);
private List<LaunchAccountProfile> GetCheckedLaunchAccounts()
{
@ -2514,7 +2569,10 @@ internal partial class MainWindow : Window
_updateChecking = false;
AnnounceNewPlugins(_updateCheck);
BuildAvailablePlugins();
if (_settings.AutoUpdatePlugins && (_updateCheck.PluginsToUpdate.Any() || _updateCheck.Companions.Count > 0
if (_updateCheck.HoldEnded)
EndRollbackHold($"RynthCore {_updateCheck.Manifest.Version} is out: updates are back on after the rollback.");
// After Roll back, the release the player left isn't installed again by itself (RynthUpdater.Rollback.cs).
if (_settings.AutoUpdatePlugins && !_updateCheck.Held && (_updateCheck.PluginsToUpdate.Any() || _updateCheck.Companions.Count > 0
|| (_updateCheck.NavDataUpdateAvailable && !_navDataCancelledThisSession)))
await ApplyPluginUpdatesAsync(automatic: true);
SendUsageReportIfDue(); // opt-in only, at most once a day, never awaited
@ -2686,7 +2744,7 @@ internal partial class MainWindow : Window
{
switch (_updateCard?.Kind)
{
case UpdateCardKind.CoreUpdate: await InstallCoreUpdateAsync(); break;
case UpdateCardKind.CoreUpdate or UpdateCardKind.Held: await InstallCoreUpdateAsync(); break;
case UpdateCardKind.PluginUpdates: await UpdatePluginsAsync(); break;
}
}
@ -2704,6 +2762,7 @@ internal partial class MainWindow : Window
/// <summary>Redraws the front page's update card, the Plugins tab's status line and the header.</summary>
private void RefreshUpdateCard()
{
KeepLauncherScroll();
RefreshMapPacksCard();
RynthUpdater.CheckResult? c = _updateCheck;
bool coreUpdate = c?.CoreUpdateAvailable == true;
@ -2725,23 +2784,26 @@ internal partial class MainWindow : Window
ClientsRunning = coreUpdate && _download == null ? RynthCoreClientsRunning() : 0,
Download = _download,
CanCancel = _downloadCts is { IsCancellationRequested: false },
HeldFromVersion = c is { Held: true } ? FormatRelease(c.HoldThrough) : "",
});
_updateCard = card;
UpdateCardTitle.Text = card.Title;
UpdateCardTitle.Foreground = Brush.Parse(card.Kind switch
{
UpdateCardKind.CoreUpdate or UpdateCardKind.PluginUpdates => "#F2C14E",
UpdateCardKind.CoreUpdate or UpdateCardKind.PluginUpdates or UpdateCardKind.Held => "#F2C14E",
UpdateCardKind.Error => "#E57373",
_ => "#26C1A6",
});
UpdateCardBorder.BorderBrush = Brush.Parse(card.Kind is UpdateCardKind.CoreUpdate or UpdateCardKind.PluginUpdates ? "#F2C14E" : "#243742");
UpdateCardBorder.BorderBrush = Brush.Parse(card.Kind is UpdateCardKind.CoreUpdate or UpdateCardKind.PluginUpdates or UpdateCardKind.Held ? "#F2C14E" : "#243742");
UpdateCardDetail.Text = card.Detail;
UpdateCardDetail.IsVisible = card.Detail.Length > 0;
UpdateCardActionButton.IsVisible = card.ActionButton != null;
UpdateCardActionButton.Content = card.ActionButton ?? "";
UpdateCardActionButton.IsEnabled = !_updateBusy;
CheckUpdatesButton.IsVisible = card.ShowCheckButton;
RollbackButton.IsVisible = card.ShowCheckButton && _updater.IsConfigured && _updater.InstalledCoreRelease > 0;
RollbackButton.IsEnabled = !_updateBusy;
UpdateCardWhatsNewPanel.Children.Clear();
if (card.WhatsNew.Count > 0)
@ -2874,6 +2936,7 @@ internal partial class MainWindow : Window
RefreshUpdateCard();
try
{
if (_updateCheck.HoldThrough > 0) EndRollbackHold(null); // updating by hand ends a rollback's hold
await ApplyPluginUpdatesAsync(automatic: false);
}
catch (Exception ex)
@ -2950,6 +3013,88 @@ internal partial class MainWindow : Window
BuildPluginLoadout();
}
/// <summary>
/// Roll back (RynthUpdater.Rollback.cs): with every game client closed, picks an earlier release,
/// downloads and verifies it, puts its plugins in place, holds updates, then runs its installer (the
/// launcher restarts as that release).
/// </summary>
private async Task RollBackAsync()
{
if (_updateBusy) return;
int running = RynthCoreClientsRunning();
if (running > 0)
{
AppendActivity($"Close your {running} game client(s) running RynthCore or its Decal bridge first: going back replaces files they have open.");
return;
}
_updateBusy = true;
RefreshUpdateCard();
try
{
IReadOnlyList<RynthUpdater.RollbackTarget> targets = await _updater.ListRollbackTargetsAsync();
if (targets.Count == 0)
{
AppendActivity($"There's no earlier release to go back to (going back works to releases from {FormatRelease(RynthUpdater.FirstRollbackRelease)} on).");
return;
}
var dialog = new RollbackDialog(targets, FormatRelease(_updater.InstalledCoreRelease));
RynthUpdater.RollbackTarget? chosen = await dialog.ShowDialog<RynthUpdater.RollbackTarget?>(this);
if (chosen == null) return;
RynthUpdater.RollbackPlan plan = await RunDownloadAsync((progress, ct) =>
_updater.PrepareRollbackAsync(chosen, _pluginDllPaths.ToList(), progress, ct));
if (RynthCoreClientsRunning() > 0)
{
AppendActivity("A RynthCore client started meanwhile. Close it, then press Roll back again. Nothing was changed.");
return;
}
List<string> plugins = _updater.ApplyRollbackPlugins(plan);
// The rolled-back launcher may be older than the hold: it would update the plugins straight back.
bool turnOff = _settings.AutoUpdatePlugins;
_updater.StartHold(plan.LeavingRelease, turnOff);
if (turnOff)
{
_settings.AutoUpdatePlugins = false;
AutoUpdatePluginsCheckBox.IsChecked = false;
SaveSettings();
}
AppendActivity($"Going back to RynthCore {plan.Manifest.Version}" +
(plugins.Count > 0 ? $" (plugins: {string.Join(", ", plugins)})" : "") +
$"; the launcher restarts when it's done. Updates are on hold until a release newer than {FormatRelease(plan.LeavingRelease)} comes out.");
RynthUpdater.RunInstaller(plan.InstallerPath);
(Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.Shutdown();
}
catch (OperationCanceledException)
{
AppendActivity("Going back cancelled. Nothing was changed.");
}
catch (Exception ex)
{
AppendActivity($"Going back failed: {ex.Message}");
}
finally
{
_updateBusy = false;
RefreshUpdateCard();
}
}
/// <summary>Ends a rollback's hold and turns automatic plugin updates back on if the rollback turned them off.</summary>
private void EndRollbackHold(string? message)
{
bool restore = _updater.HoldTurnedOffAutoUpdate;
_updater.EndHold();
if (restore && !_settings.AutoUpdatePlugins)
{
_settings.AutoUpdatePlugins = true;
AutoUpdatePluginsCheckBox.IsChecked = true;
SaveSettings();
}
if (message != null) AppendActivity(message);
}
private async Task InstallCoreUpdateAsync()
{
if (_updateBusy || _updateCheck is not { CoreUpdateAvailable: true } c) return;
@ -2971,6 +3116,7 @@ internal partial class MainWindow : Window
AppendActivity("A RynthCore client started meanwhile. Close it, then press Update RynthCore again.");
return;
}
if (c.HoldThrough > 0) EndRollbackHold(null); // going forward by hand ends a rollback's hold
AppendActivity($"Installing RynthCore {c.Manifest.Core.Version}; the launcher restarts when it's done.");
RynthUpdater.RunInstaller(installer);
(Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.Shutdown();
@ -3918,8 +4064,14 @@ internal partial class MainWindow : Window
{
try
{
// Never decrypts: a saved password shows as the mask.
return _launchArgumentBuilder.BuildMaskedArguments(server, account);
// Never decrypts: a saved password shows as the mask. Extra Launch Arguments follow,
// as they do at launch.
string masked = _launchArgumentBuilder.BuildMaskedArguments(server, account);
if (AcLaunchArgumentBuilder.NeedsPassword(account))
return masked; // the message saying why, not a command line
return AcLaunchArgumentBuilder.ExtraArgumentsProblem(LaunchArgumentsTextBox.Text, out string extra) is string problem
? problem
: AcLaunchArgumentBuilder.WithExtraArguments(masked, extra);
}
catch (Exception ex)
{
@ -4710,6 +4862,13 @@ internal partial class MainWindow : Window
if (HasTrackedPresence(account, server, activeContexts, activeSessions))
continue;
// No server profile (deleted, or never picked): never launched on another server.
if (server == null)
{
MaybeLogAutoLaunchNoServer(account, nowUtc);
continue;
}
if (IsServerKnownDown(server))
{
MaybeLogAutoLaunchServerDown(account, server, nowUtc);
@ -4787,6 +4946,18 @@ internal partial class MainWindow : Window
AppendActivity($"Auto launch waiting for {account.DisplayName}: {AcLaunchArgumentBuilder.MissingPasswordMessage(account.AccountName)}");
}
private void MaybeLogAutoLaunchNoServer(LaunchAccountProfile account, DateTime nowUtc)
{
if (_autoLaunchNoServerNoticeTimesUtc.TryGetValue(account.Id, out DateTime lastNoticeUtc) &&
nowUtc - lastNoticeUtc < AutoLaunchNeedsPasswordLogCooldown)
{
return;
}
_autoLaunchNoServerNoticeTimesUtc[account.Id] = nowUtc;
AppendActivity($"Auto launch skipped for {account.DisplayName}: {AccountServerRules.NoServerMessage(account, _settings.ServerProfiles.Count > 0)}");
}
private bool IsServerKnownDown(LaunchServerProfile? server)
{
if (server == null)
@ -4960,16 +5131,23 @@ internal partial class MainWindow : Window
// "(None)" at the top — selecting it opts out of auto-login for this account
detectedCharacters.Insert(0, LaunchAccountProfile.NoneOption);
string? wanted = account.CharacterName == LaunchAccountProfile.NoneOption
? LaunchAccountProfile.NoneOption
: !string.IsNullOrWhiteSpace(account.CharacterName) && detectedCharacters.Contains(account.CharacterName)
? account.CharacterName
: null;
// This runs every 2 s: refill a dropdown only when its list or choice changed, so the
// Launcher tab isn't refilled (and its selection events raised) for nothing.
if (dropdown.ItemsSource is IEnumerable<string> shown && shown.SequenceEqual(detectedCharacters)
&& Equals(dropdown.SelectedItem as string, wanted))
continue;
KeepLauncherScroll();
_suppressLaunchTargetCharacterSelectionChanged = true;
try
{
dropdown.ItemsSource = detectedCharacters;
if (account.CharacterName == LaunchAccountProfile.NoneOption)
dropdown.SelectedItem = LaunchAccountProfile.NoneOption;
else
dropdown.SelectedItem = !string.IsNullOrWhiteSpace(account.CharacterName) && detectedCharacters.Contains(account.CharacterName)
? account.CharacterName
: null;
dropdown.SelectedItem = wanted;
}
finally
{
@ -5078,6 +5256,7 @@ internal partial class MainWindow : Window
private void RefreshServerProfileDisplay()
{
KeepLauncherScroll();
int selectedIndex = ServerProfilesList.SelectedIndex;
_suppressPrimarySelectionChanged = true;
try

View file

@ -0,0 +1,26 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="RynthCore.App.Avalonia.RollbackDialog"
Width="600"
SizeToContent="Height"
CanResize="False"
WindowStartupLocation="CenterOwner"
Title="Roll back"
Background="#132028">
<Grid RowDefinitions="*,Auto" Margin="18">
<StackPanel Spacing="10">
<TextBlock x:Name="HeaderText" Foreground="#EAF0F4" FontSize="16" FontWeight="SemiBold" TextWrapping="Wrap" />
<TextBlock Foreground="#9AA8B3" TextWrapping="Wrap"
Text="Pick the release to go back to. Your settings, profiles and accounts stay as they are." />
<ScrollViewer MaxHeight="380" VerticalScrollBarVisibility="Auto">
<StackPanel x:Name="ReleasesPanel" Spacing="10" />
</ScrollViewer>
<TextBlock x:Name="HoldText" Foreground="#9AA8B3" TextWrapping="Wrap" />
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8" Margin="0,16,0,0">
<Button x:Name="CancelButton" Content="Cancel" />
<Button x:Name="RollbackButton" Content="Go back" IsEnabled="False"
Background="#26C1A6" Foreground="#0B1218" FontWeight="SemiBold" />
</StackPanel>
</Grid>
</Window>

View file

@ -0,0 +1,60 @@
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Media;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Roll back's choice (RynthUpdater.Rollback.cs): the earlier releases whose signed manifests verified,
/// newest first, each with its date and first changes. Closes with the chosen target, or null.
/// </summary>
internal partial class RollbackDialog : Window
{
private const int ChangesShown = 3;
private RynthUpdater.RollbackTarget? _chosen;
public RollbackDialog() : this(new List<RynthUpdater.RollbackTarget>(), "") { } // the XAML previewer
public RollbackDialog(IReadOnlyList<RynthUpdater.RollbackTarget> targets, string installedVersion)
{
InitializeComponent();
HeaderText.Text = $"Go back from RynthCore {installedVersion}";
HoldText.Text = "Every game client must be closed. The launcher installs that release and restarts; " +
"updates then wait until a release newer than this one comes out, or until you press Update RynthCore.";
foreach (RynthUpdater.RollbackTarget t in targets)
{
var choice = new RadioButton { GroupName = "release", Tag = t };
var body = new StackPanel { Spacing = 2 };
body.Children.Add(new TextBlock
{
Text = $"RynthCore {t.Version} · {t.Manifest.PublishedUtc.ToLocalTime():MMM d}",
Foreground = Brush.Parse("#EAF0F4"), FontWeight = FontWeight.SemiBold,
});
IReadOnlyList<string> lines = t.Manifest.Changes.Count > 0
? t.Manifest.Changes.Take(ChangesShown).ToList()
: (t.Manifest.Notes.Length > 0 ? new[] { t.Manifest.Notes } : new string[0]);
foreach (string line in lines)
body.Children.Add(new TextBlock
{
Text = "• " + (line.Length > 160 ? line[..159].TrimEnd() + "…" : line),
Foreground = Brush.Parse("#C5D0D8"), TextWrapping = TextWrapping.Wrap,
});
if (t.Manifest.Changes.Count > ChangesShown)
body.Children.Add(new TextBlock { Text = $"…and {t.Manifest.Changes.Count - ChangesShown} more.", Foreground = Brush.Parse("#9AA8B3") });
choice.Content = body;
choice.IsCheckedChanged += (_, _) =>
{
if (choice.IsChecked != true) return;
_chosen = (RynthUpdater.RollbackTarget)choice.Tag!;
RollbackButton.Content = $"Go back to {_chosen.Version}";
RollbackButton.IsEnabled = true;
};
ReleasesPanel.Children.Add(choice);
}
CancelButton.Click += (_, _) => Close(null);
RollbackButton.Click += (_, _) => Close(_chosen);
}
}

View file

@ -46,6 +46,7 @@
<Compile Include="..\RynthCore.App\KnownServerCatalog.cs" Link="Shared\KnownServerCatalog.cs" />
<Compile Include="..\RynthCore.App\LaunchAccountProfile.cs" Link="Shared\LaunchAccountProfile.cs" />
<Compile Include="..\RynthCore.App\AccountPasswordProtection.cs" Link="Shared\AccountPasswordProtection.cs" />
<Compile Include="..\RynthCore.App\SavedPasswordReveal.cs" Link="Shared\SavedPasswordReveal.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" />
@ -55,6 +56,7 @@
<Compile Include="..\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="Shared\AcLaunchArgumentBuilder.cs" />
<Compile Include="..\RynthCore.App\AcClientCommandLine.cs" Link="Shared\AcClientCommandLine.cs" />
<Compile Include="..\RynthCore.App\FirstLoginRules.cs" Link="Shared\FirstLoginRules.cs" />
<Compile Include="..\RynthCore.App\AccountServerRules.cs" Link="Shared\AccountServerRules.cs" />
<Compile Include="..\RynthCore.App\CrashDumpWriterRule.cs" Link="Shared\CrashDumpWriterRule.cs" />
<Compile Include="..\RynthCore.App\AcClientLaunchSettingsService.cs" Link="Shared\AcClientLaunchSettingsService.cs" />
<Compile Include="..\RynthCore.App\UserPrefsSwapRecovery.cs" Link="Shared\UserPrefsSwapRecovery.cs" />

View file

@ -0,0 +1,198 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Roll back: go back to an earlier release when a new one broke something (2026-10-21).
///
/// Every release keeps its own signed manifest beside its files on the server
/// (releases/&lt;release&gt;/update.json; Publish-Update.ps1 uploads it, and did by hand for 2026.10.19.1
/// on). Which releases exist comes from releases.json (unsigned; only used to find candidates); each
/// candidate is offered only once its own manifest verifies, and everything a rollback downloads is
/// checked against that manifest's signed sizes and hashes, exactly like an update. Only releases older
/// than the installed one, and not older than <see cref="FirstRollbackRelease"/>.
///
/// A rollback puts back that release's build of every plugin the player has (the files it ships; other
/// plugins are left alone), then runs that release's installer (the core: engine, launcher, RynthAi),
/// with every game client closed, like a core update. Afterwards updates are held
/// (<see cref="StartHold"/>): no automatic plugin updates while the feed offers nothing newer than the
/// release left behind, so the launcher doesn't put it straight back. The hold ends by itself when a
/// newer release comes out, or when the player updates by hand.
///
/// A launcher from before this feature (the rolled-back one may be) knows nothing of the hold, so a
/// rollback also turns "Update plugins automatically" off, and a later launcher turns it back on when
/// the hold ends (<see cref="HoldTurnedOffAutoUpdate"/>).
/// </summary>
internal sealed partial class RynthUpdater
{
/// <summary>The oldest release whose signed manifest is kept on the server (2026.10.19.1).</summary>
public const int FirstRollbackRelease = 2026101901;
/// <summary>How many earlier releases Roll back offers.</summary>
public const int RollbackChoices = 5;
private const long MaxReleasesListBytes = 4L << 20;
/// <summary>Tests lower it; the launcher uses <see cref="FirstRollbackRelease"/>.</summary>
internal int RollbackFloor { get; set; } = FirstRollbackRelease;
/// <summary>An earlier release Roll back can install, from its own verified manifest.</summary>
public sealed record RollbackTarget(Manifest Manifest)
{
public int Release => Manifest.Release;
public string Version => Manifest.Version;
}
/// <summary>What a prepared rollback installs: the verified installer and the player's plugins, staged.</summary>
public sealed record RollbackPlan(Manifest Manifest, int LeavingRelease, string InstallerPath,
IReadOnlyList<(PluginEntry Entry, string Path, string Staged)> Plugins);
/// <summary>"2026.10.21.2" → 2026102102 (Publish-Update.ps1's numbering); 0 when it isn't a release version.</summary>
public static int ReleaseOf(string? version)
{
string[] p = (version ?? "").Trim().Split('.');
if (p.Length != 4) return 0;
if (!int.TryParse(p[0], out int y) || !int.TryParse(p[1], out int m) || !int.TryParse(p[2], out int d) || !int.TryParse(p[3], out int n))
return 0;
if (y < 2000 || y > 2999 || m < 1 || m > 12 || d < 1 || d > 31 || n < 0 || n > 99) return 0;
return y * 1000000 + m * 10000 + d * 100 + n;
}
/// <summary>
/// The earlier releases Roll back offers, newest first: up to <paramref name="max"/>, older than the
/// installed release, not older than <see cref="RollbackFloor"/>, each with a manifest that verifies.
/// A release whose manifest is missing or doesn't verify is skipped.
/// </summary>
public async Task<IReadOnlyList<RollbackTarget>> ListRollbackTargetsAsync(int max = RollbackChoices, CancellationToken ct = default)
{
if (!IsConfigured)
throw new InvalidOperationException("updates are not set up in this build (no signing key)");
int installed = InstalledCoreRelease;
if (installed <= 0)
throw new InvalidOperationException("this RynthCore wasn't installed from a release, so there's nothing to go back from");
byte[] list = await DownloadBytesAsync(_allowedPrefix + "releases.json", MaxReleasesListBytes, ct);
var candidates = new List<int>();
using (JsonDocument doc = JsonDocument.Parse(list))
{
foreach (JsonElement r in doc.RootElement.GetProperty("releases").EnumerateArray())
{
int release = r.TryGetProperty("version", out JsonElement v) ? ReleaseOf(v.GetString()) : 0;
if (release > 0 && release < installed && release >= RollbackFloor && !candidates.Contains(release))
candidates.Add(release);
}
}
var targets = new List<RollbackTarget>();
foreach (int release in candidates.OrderByDescending(r => r))
{
if (targets.Count >= max) break;
try { targets.Add(new RollbackTarget(await LoadReleaseManifestAsync(release, ct))); }
catch (OperationCanceledException) { throw; }
catch { /* no signed manifest kept for it, or it doesn't verify: not offered */ }
}
return targets;
}
/// <summary>
/// <paramref name="release"/>'s own signed manifest (releases/&lt;release&gt;/update.json). Throws unless a
/// trusted key signed it, it is that release (not another one served under its name) and it is
/// older than the installed release.
/// </summary>
public async Task<Manifest> LoadReleaseManifestAsync(int release, CancellationToken ct = default)
{
byte[] envelope = await DownloadBytesAsync($"{_allowedPrefix}releases/{release}/update.json", MaxFeedBytes, ct);
Manifest m = ParseManifest(VerifyEnvelope(envelope, _trustedKeys));
if (m.Release != release || m.Core.Release != release)
throw new InvalidDataException($"releases/{release} holds the manifest of release {m.Release}");
if (m.Release >= InstalledCoreRelease)
throw new InvalidDataException($"{m.Version} isn't older than the installed release");
return m;
}
/// <summary>
/// Downloads and verifies everything <paramref name="target"/> installs: its installer, and its build of
/// each plugin in <paramref name="pluginPaths"/> that it ships (staged, not installed yet). Nothing is
/// changed if any download fails.
/// </summary>
public async Task<RollbackPlan> PrepareRollbackAsync(RollbackTarget target, IEnumerable<string> pluginPaths,
IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
Manifest m = target.Manifest;
int leaving = InstalledCoreRelease;
string installer = await DownloadInstallerAsync(m.Core, progress, ct);
string stage = Path.Combine(UpdatesDir, $"rollback-{m.Release}");
Directory.CreateDirectory(stage);
var byFile = m.Plugins.ToDictionary(p => p.File, StringComparer.OrdinalIgnoreCase);
var staged = new Dictionary<PluginEntry, string>();
var plugins = new List<(PluginEntry, string, string)>();
foreach (string path in pluginPaths.Distinct(StringComparer.OrdinalIgnoreCase))
{
if (!File.Exists(path) || !byFile.TryGetValue(Path.GetFileName(path), out PluginEntry? e)) continue;
if (!staged.TryGetValue(e, out string? file))
{
file = Path.Combine(stage, e.File);
bool have = File.Exists(file) && new FileInfo(file).Length == e.Size &&
string.Equals(Sha256File(file), e.Sha256, StringComparison.OrdinalIgnoreCase);
if (!have)
{
string part = file + ".part";
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, part, ct, $"{e.Name} {m.Version}", progress);
File.Move(part, file, overwrite: true);
}
staged[e] = file;
}
plugins.Add((e, path, file));
}
return new RollbackPlan(m, leaving, installer, plugins);
}
/// <summary>
/// Puts the staged plugins in place (the replaced file kept as .previous, as an update does) and
/// returns what changed. Stamped with the release's time, so a later check doesn't take them for a
/// local build. Call with every game client closed, before running the installer.
/// </summary>
public List<string> ApplyRollbackPlugins(RollbackPlan plan)
{
var done = new List<string>();
foreach (var (entry, path, file) in plan.Plugins)
{
string fresh = path + ".new";
File.Copy(file, fresh, overwrite: true);
File.SetLastWriteTimeUtc(fresh, plan.Manifest.PublishedUtc);
File.Copy(path, path + ".previous", overwrite: true);
File.Move(fresh, path, overwrite: true);
done.Add($"{entry.Name} → {plan.Manifest.Version}");
}
return done;
}
// ── The hold ───────────────────────────────────────────────────────────────
/// <summary>The release the player rolled back from (0: no hold).</summary>
public int HeldThroughRelease => ReadStateInt("holdThrough");
/// <summary>True when the rollback turned "Update plugins automatically" off (turned back on when the hold ends).</summary>
public bool HoldTurnedOffAutoUpdate => ReadStateBool("holdTurnedOffAutoUpdate");
/// <summary>Holds updates through <paramref name="leavingRelease"/> (the release rolled back from).</summary>
public void StartHold(int leavingRelease, bool turnedOffAutoUpdate) => WriteState(s =>
{
s["holdThrough"] = leavingRelease;
s["holdTurnedOffAutoUpdate"] = turnedOffAutoUpdate;
});
/// <summary>Ends a rollback's hold (a newer release is out, or the player updated by hand).</summary>
public void EndHold() => WriteState(s =>
{
s.Remove("holdThrough");
s.Remove("holdTurnedOffAutoUpdate");
});
}

View file

@ -95,6 +95,15 @@ internal sealed partial class RynthUpdater
public bool NavDataUpdateAvailable => NavData is { State: NavDataState.NeedsUpdate };
/// <summary>The optional World Map sizes: what the feed offers and what is installed. Not part of "Update plugins": the player chooses.</summary>
public IReadOnlyList<MapPackStatus> MapPacks { get; init; } = Array.Empty<MapPackStatus>();
/// <summary>
/// The release the player went back from with Roll back (0: none; RynthUpdater.Rollback.cs). While
/// the feed offers nothing newer and the player hasn't updated past it, updates are held.
/// </summary>
public int HoldThrough { get; init; }
/// <summary>Held after a rollback: no automatic plugin updates; the card says so.</summary>
public bool Held => HoldThrough > 0 && Manifest.Release <= HoldThrough && InstalledCoreRelease < HoldThrough;
/// <summary>A rollback's hold is over: a newer release is out, or the player updated past it by hand.</summary>
public bool HoldEnded => HoldThrough > 0 && !Held;
}
/// <summary>
@ -153,6 +162,10 @@ internal sealed partial class RynthUpdater
return coreBringsIt ? $"needs RynthCore {core.Version}" : $"needs a newer RynthCore (API {e.MinEngineApi})";
}
/// <summary>Where installers (and a rollback's plugins) are downloaded: %LOCALAPPDATA%\RynthCore\updates. Tests set it.</summary>
internal string UpdatesDir { get; set; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "updates");
/// <summary>False until the signing keys exist: with no trusted key nothing can verify.</summary>
public bool IsConfigured => _trustedKeys.Count > 0;
@ -220,6 +233,7 @@ internal sealed partial class RynthUpdater
MapPacks = CheckMapPacks(manifest),
Available = available,
NewlyAnnounced = available.Where(a => fresh.Contains(a.Entry.Name)).ToList(),
HoldThrough = HeldThroughRelease,
};
}
@ -317,11 +331,13 @@ internal sealed partial class RynthUpdater
// ── Core ──────────────────────────────────────────────────────────────────
/// <summary>Downloads (or reuses) the release installer, verified, and returns its path.</summary>
public async Task<string> DownloadInstallerAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
public Task<string> DownloadInstallerAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default) =>
DownloadInstallerAsync(check.Manifest.Core, progress, ct);
/// <summary>Downloads (or reuses) <paramref name="core"/>'s installer, verified, and returns its path.</summary>
public async Task<string> DownloadInstallerAsync(InstallerEntry core, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
InstallerEntry core = check.Manifest.Core;
string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"RynthCore", "updates", core.Release.ToString());
string dir = Path.Combine(UpdatesDir, core.Release.ToString());
Directory.CreateDirectory(dir);
string path = Path.Combine(dir, "RynthCore-Setup.exe");
if (File.Exists(path) && new FileInfo(path).Length == core.Size &&
@ -522,24 +538,45 @@ internal sealed partial class RynthUpdater
catch { }
}
private int ReadHighestRelease()
private int ReadHighestRelease() => ReadStateInt("highestRelease");
private void WriteHighestRelease(int release) => WriteState(s => s["highestRelease"] = release);
// update-state.json holds several values (the replay guard's highest release, a rollback's hold):
// each write changes its own keys and keeps the rest.
private System.Text.Json.Nodes.JsonObject ReadState()
{
try
{
if (!File.Exists(StatePath)) return 0;
using var doc = JsonDocument.Parse(File.ReadAllText(StatePath));
return doc.RootElement.TryGetProperty("highestRelease", out JsonElement v) ? v.GetInt32() : 0;
if (File.Exists(StatePath) && System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(StatePath)) is System.Text.Json.Nodes.JsonObject o)
return o;
}
catch { }
return new System.Text.Json.Nodes.JsonObject();
}
private int ReadStateInt(string key)
{
try { return ReadState()[key]?.GetValue<int>() ?? 0; }
catch { return 0; }
}
private void WriteHighestRelease(int release)
private bool ReadStateBool(string key)
{
try { return ReadState()[key]?.GetValue<bool>() ?? false; }
catch { return false; }
}
private void WriteState(Action<System.Text.Json.Nodes.JsonObject> change)
{
try
{
System.Text.Json.Nodes.JsonObject state = ReadState();
change(state);
Directory.CreateDirectory(_stateDir);
string tmp = StatePath + ".tmp";
File.WriteAllText(tmp, $"{{\"highestRelease\": {release}}}", Encoding.UTF8);
File.WriteAllText(tmp, state.ToJsonString(), Encoding.UTF8);
File.Move(tmp, StatePath, overwrite: true);
}
catch { }

View file

@ -6,7 +6,7 @@ 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 }
public enum UpdateCardKind { NotConfigured, NotChecked, Checking, Error, UpToDate, CoreUpdate, PluginUpdates, Downloading, Held }
/// <summary>Everything the card needs to know, gathered by the window (no UI types, so tests can build it).</summary>
public sealed record UpdateCardInput
@ -32,6 +32,8 @@ public sealed record UpdateCardInput
public int ClientsRunning { get; init; }
/// <summary>The download in progress, if any.</summary>
public DownloadProgress? Download { get; init; }
/// <summary>After Roll back: the version the player went back from, while updates are held (else "").</summary>
public string HeldFromVersion { get; init; } = "";
public bool CanCancel { get; init; }
}
@ -53,7 +55,7 @@ public sealed record UpdateCard(
/// <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.
/// (bar, MB, speed, time left, step), errors, a line about new plugins, and the hold after a Roll back.
/// </summary>
public static class UpdateCardModel
{
@ -105,6 +107,18 @@ public static class UpdateCardModel
string checkedLine = i.LastChecked is { } lc ? $"Last checked {FormatWhen(lc)}." : "";
IReadOnlyList<string> whatsNew = WhatsNew(i.Changes, i.Notes);
if (i.HeldFromVersion.Length > 0)
{
// Roll back: the launcher doesn't push the release the player left straight back.
var detail = new List<string> { $"You went back from {i.HeldFromVersion}. Updates are on hold until a newer release comes out." };
if (i.CoreUpdateAvailable)
detail.Add($"{UpdateCoreButton} goes forward to {i.AvailableVersion} now.");
if (checkedLine.Length > 0) detail.Add(checkedLine);
return new UpdateCard(UpdateCardKind.Held, $"RynthCore {installed} - rolled back", string.Join(" ", detail),
Array.Empty<string>(), true, i.CoreUpdateAvailable ? UpdateCoreButton : null, false, null, false, newLine,
$"RynthCore {installed} - rolled back from {i.HeldFromVersion}; updates on hold.");
}
if (i.CoreUpdateAvailable)
{
var detail = new List<string> { $"You have {installed}. The update installs once every game client is closed." };

View file

@ -128,6 +128,59 @@ internal sealed class AcLaunchArgumentBuilder
return null;
}
/// <summary>
/// The switches the launcher writes itself from the account and its server profile (ACE and
/// GDLE lines above). Extra Launch Arguments may not repeat them.
/// </summary>
public static readonly IReadOnlyList<string> LoginSwitches = ["-a", "-v", "-h", "-p", "-rodat"];
/// <summary>
/// Checks the Runtime tab's "Extra Launch Arguments" and gives them as one line
/// (<paramref name="normalized"/>) to put after each account's own arguments with
/// <see cref="WithExtraArguments"/>. Null = fine (an empty box is fine); else why the launch
/// can't go ahead, and <paramref name="normalized"/> is empty.
///
/// The box used to replace the whole command line, account, password and host included (and
/// only for one manual launch at a time), though it was labelled "appended". It now appends,
/// for every launch. So it may not carry the login switches (<see cref="LoginSwitches"/>): a
/// saved old override would otherwise ride along on every account and could log each of them
/// in as the override's account, or send their passwords to the override's host. Line breaks
/// and tabs become spaces (the client splits on spaces only), and a quote left open is refused
/// (the client would then drop the whole line, login included).
/// </summary>
public static string? ExtraArgumentsProblem(string? extra, out string normalized)
{
normalized = string.Empty;
string line = (extra ?? string.Empty).Replace("\r\n", " ").Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' ').Trim();
if (line.Length == 0)
return null;
List<string>? args = AcClientCommandLine.Split(line);
if (args == null)
return "Extra Launch Arguments have a quote mark left open; the client would ignore its whole command line, login included. Close or remove the quote.";
foreach (string arg in args)
{
foreach (string loginSwitch in LoginSwitches)
{
if (string.Equals(arg, loginSwitch, StringComparison.OrdinalIgnoreCase))
return $"Extra Launch Arguments can't contain {loginSwitch}: the account and its server profile set " +
$"{string.Join(", ", LoginSwitches)} themselves. Remove it (an old whole-line override goes in the account and server profiles now).";
}
}
normalized = line;
return null;
}
/// <summary>
/// <paramref name="accountArguments"/> (from <see cref="BuildArguments"/> or
/// <see cref="BuildMaskedArguments"/>) followed by extra arguments already checked by
/// <see cref="ExtraArgumentsProblem"/>.
/// </summary>
public static string WithExtraArguments(string accountArguments, string normalizedExtra) =>
string.IsNullOrWhiteSpace(normalizedExtra) ? accountArguments : accountArguments + " " + normalizedExtra;
/// <summary>One argument by acclient's own rules (AcClientCommandLine), not the C runtime's.</summary>
private static string Quote(string value) => AcClientCommandLine.Token(value);
}

View file

@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace RynthCore.App;
/// <summary>
/// Which server an account logs on to, and when a server profile may be deleted. Pure: no UI,
/// no files.
///
/// An account's name and password belong to one server, so an account only ever resolves to the
/// server profile it names (<see cref="LaunchAccountProfile.ServerId"/>). There is no fallback to
/// the selected or the first server: that fallback re-pointed every account of a deleted server
/// at another one and saved it, so the next launch (or an automatic relaunch within seconds) sent
/// one server's account name and password to a different server's operator, with nothing on
/// screen (structural audit 2026-10-21, F2). An account whose server profile is missing has no
/// server until the player picks one in its editor, and it doesn't launch.
///
/// Deleting a server that accounts still use is refused, with the accounts named, rather than
/// leaving them with no server. Refusing changes nothing behind the player's back: they move each
/// account to its new server (or delete it) and then delete the server. The other choice, clearing
/// the accounts' server, would quietly stop checked accounts from auto-launching (overnight
/// multi-boxing) with only a line in Activity. The no-server rule above stays as the backstop for
/// accounts whose server went some other way (settings copied from another PC, a second
/// launcher, a hand edit).
/// </summary>
internal static class AccountServerRules
{
/// <summary>
/// The server profile <paramref name="account"/> names, or null when it names none or one
/// that isn't in <paramref name="servers"/>. Never another server.
/// </summary>
public static LaunchServerProfile? ServerFor(LaunchAccountProfile account, IEnumerable<LaunchServerProfile> servers)
{
ArgumentNullException.ThrowIfNull(account);
string id = account.ServerId?.Trim() ?? string.Empty;
if (id.Length == 0 || servers == null)
return null;
return servers.FirstOrDefault(s => s != null && string.Equals(s.Id, id, StringComparison.OrdinalIgnoreCase));
}
/// <summary>The accounts that log on to <paramref name="server"/>.</summary>
public static List<LaunchAccountProfile> AccountsOn(LaunchServerProfile server, IEnumerable<LaunchAccountProfile> accounts)
{
ArgumentNullException.ThrowIfNull(server);
if (accounts == null || string.IsNullOrWhiteSpace(server.Id))
return [];
return accounts
.Where(a => a != null && string.Equals(a.ServerId?.Trim(), server.Id.Trim(), StringComparison.OrdinalIgnoreCase))
.ToList();
}
/// <summary>
/// Why <paramref name="server"/> can't be deleted (it names the accounts that use it), or null
/// when no account uses it.
/// </summary>
public static string? DeleteBlocker(LaunchServerProfile server, IEnumerable<LaunchAccountProfile> accounts)
{
List<LaunchAccountProfile> users = AccountsOn(server, accounts);
if (users.Count == 0)
return null;
const int MaxNamed = 8;
IEnumerable<string> names = users.Take(MaxNamed).Select(a => " - " + a.DisplayName);
string more = users.Count > MaxNamed ? $"\n ...and {users.Count - MaxNamed} more" : string.Empty;
return $"{server.DisplayName} can't be deleted while {users.Count} account(s) log on to it:\n" +
string.Join("\n", names) + more + "\n\n" +
"Their names and passwords belong to that server, so they are never moved to another one for you. " +
"Edit each account and pick its server (or delete the account), then delete the server.";
}
/// <summary>Why <paramref name="account"/> can't launch: it has no server profile.</summary>
public static string NoServerMessage(LaunchAccountProfile account, bool anyServerProfiles)
{
ArgumentNullException.ThrowIfNull(account);
return anyServerProfiles
? $"account '{account.AccountName}' has no server (its server profile was deleted or never set). " +
"Edit the account and pick the server it logs on to; it isn't sent to another server in the meantime."
: $"account '{account.AccountName}' has no server. Add a server profile, then edit the account and pick it.";
}
}

View file

@ -0,0 +1,85 @@
using System;
namespace RynthCore.App;
/// <summary>
/// The "show password" eye beside the account editor's password box. Pure: no UI.
///
/// The box starts empty ("leave blank to keep the saved password"). Turning the eye on with the
/// box empty fills it with the saved password, decrypted at that moment, so the player can read
/// it; with something typed, the eye only reveals what was typed. Turning the eye off empties the
/// box again when it still holds the saved password it was filled with, so blank = keep holds,
/// and saving it unchanged keeps the saved password as it is (nothing re-encrypted). A saved
/// password that can't be read on this Windows user (needs re-entering) is never filled in.
///
/// Keeps no copy of the password: only whether the box was filled; the box's text is compared
/// with a fresh decrypt. Never log what these return.
/// </summary>
internal sealed class SavedPasswordReveal
{
public const string ShowTip = "Show password";
public const string HideTip = "Hide password";
// The saved password decrypted now; null when none is saved or it can't be read here.
private readonly Func<string?> _readSaved;
public SavedPasswordReveal(Func<string?> readSaved)
{
_readSaved = readSaved ?? throw new ArgumentNullException(nameof(readSaved));
}
/// <summary>For an account profile (the editor's draft): its saved password, if readable.</summary>
public static SavedPasswordReveal For(LaunchAccountProfile profile)
{
ArgumentNullException.ThrowIfNull(profile);
return new SavedPasswordReveal(() =>
profile.HasSavedPassword && !profile.PasswordNeedsReentry
&& profile.TryGetPasswordForLaunch(out string saved, out _) && saved.Length > 0
? saved
: null);
}
/// <summary>True while the box holds the saved password the eye filled in.</summary>
public bool FilledFromSaved { get; private set; }
/// <summary>The eye turned on: the box's text, or the saved password when the box is empty.</summary>
public string EyeOn(string? boxText)
{
if (string.IsNullOrEmpty(boxText) && _readSaved() is string saved)
{
FilledFromSaved = true;
return saved;
}
FilledFromSaved = false;
return boxText ?? string.Empty;
}
/// <summary>
/// The eye turned off: the box's new text. Empty again when it still holds the saved password
/// it was filled with; anything the player typed or changed stays.
/// </summary>
public string EyeOff(string? boxText)
{
string text = boxText ?? string.Empty;
bool unchanged = HoldsSaved(text);
FilledFromSaved = false;
return unchanged ? string.Empty : text;
}
/// <summary>
/// What Save does with the box: null = keep the saved password as it is (the box is blank, or
/// holds the saved password the eye showed, unchanged); otherwise the new password to save.
/// </summary>
public string? PasswordToSave(string? boxText)
{
if (string.IsNullOrEmpty(boxText) || HoldsSaved(boxText))
return null;
return boxText;
}
/// <summary>Forgets the fill (the dialog closes).</summary>
public void Reset() => FilledFromSaved = false;
private bool HoldsSaved(string text) =>
FilledFromSaved && text.Length > 0 && _readSaved() is string saved && string.Equals(saved, text, StringComparison.Ordinal);
}

View file

@ -5,13 +5,17 @@
//
// Order matters. Each phase is wrapped so a failure does not abort the rest:
//
// 0. TickPump.StopAndJoin — the plugin pump stops (and its frame in flight
// finishes) before any plugin is shut down: no Tick alongside a Shutdown.
// 1. EndSceneHook.Uninstall — chains into EngineFrameController.Shutdown which
// tears down PluginManager (RynthPluginShutdown + FreeLibrary plugins),
// OverlayTextureRenderer, DX9Backend, and destroys the ImGui context.
// 2. Drain — sleep so any in-flight EndScene call has returned through the
// trampoline before we tear down anything else.
// 3. AvaloniaOverlay.Stop — Dispatcher shutdown, join STA thread.
// 4. PluginManager.ShutdownAll — defensive (no-op if step 1 already ran).
// 4. PluginManager.ShutdownAll — defensive (no-op if step 1 already ran; it
// tries again if step 1 left the plugins alone because the pump was
// still inside a frame).
// 5. MH_DisableHook(ALL) + MH_Uninitialize — safety net for Compatibility/*
// hooks that aren't in the ImGui chain.
//
@ -140,6 +144,17 @@ internal static class EngineLifecycle
// plugin-mutating UI command while the plugins are shutting down.
Step("UiDataHub.Disarm", () => UI.Data.UiDataHub.Disarm());
// Stop the plugin pump (and wait for a frame in flight) BEFORE anything below can
// shut a plugin down: EndSceneHook.Uninstall runs PluginManager.ShutdownAll (through
// EngineFrameController.Shutdown), and a pump still running would call a plugin's Tick
// and events on its own thread while that plugin's Shutdown frees what they use on
// this one (audit 2026-10-21, 01 #1). It used to stop further down, after the plugins
// were already gone; only the WM_CLOSE path (Win32Backend) stopped it first. Every
// shutdown comes through here: the loader's hot reload, ExitProcess and
// RtlExitUserProcess, WM_CLOSE, the bar's Sd button. If a frame is still running when
// the wait ends, ShutdownAll leaves the plugins alone (PluginShutdownGate).
Step("TickPump.StopAndJoin", () => EntryPoint.StopTickPumpAndJoin());
// AC's UI-pass hook draws the world overlays mid-frame from the same render-side
// state EndSceneHook.Uninstall tears down: stop it first (its 80 ms drain covers both).
Step("AcUiPassHook.Uninstall", () => AcUiPassHook.Uninstall());
@ -166,17 +181,14 @@ internal static class EngineLifecycle
Step("Win32Backend.Shutdown (input subclass)", () => ImGuiBackend.Win32Backend.Shutdown());
Step("HotkeyService.Shutdown", () => Hotkeys.HotkeyService.Shutdown());
// Stop the dispatch-file watcher and the auto-ID drain timer before the
// tick pump and plugins go away — both otherwise keep firing in the old
// generation's (intentionally still-mapped) module across hot-reloads.
// Stop the dispatch-file watcher and the auto-ID drain timer — both
// otherwise keep firing in the old generation's (intentionally
// still-mapped) module across hot-reloads.
Step("ChatFileDispatcher.Stop", () => Compatibility.ChatFileDispatcher.Stop());
Step("LogSettings.StopWatcher", () => LogSettings.StopWatcher());
Step("AutoIdService.Stop", () => Compatibility.AutoIdService.Stop());
// Stop the headless tick pump BEFORE plugin shutdown / FreeLibrary.
// Otherwise the pump's TickAll/ProcessPendingActions can be mid-call
// into a plugin whose code pages we're about to unmap → AV.
Step("TickPump.StopAndJoin", () => EntryPoint.StopTickPumpAndJoin());
// (The plugin pump stopped at the top, before the plugins were shut down.)
// spike/decal-bridge: after the pump (its only reader) has stopped.
Step("DecalBridgeHost.Shutdown", () => Compatibility.DecalBridgeHost.Shutdown());

View file

@ -1312,7 +1312,11 @@ public static class EntryPoint
{
try
{
if (!EngineThreads.Sleep(DecalCoexistencePluginInitDelay))
// In short steps that watch the pump's stop flag: a teardown in these seconds
// (a reload right after login) then finds this thread gone at once rather than
// after the delay, and plugins are never initialised for a dying generation
// (StopTickPumpAndJoin, PluginShutdownGate).
if (!SleepUnlessPumpStopRequested(DecalCoexistencePluginInitDelay))
return;
// Reseed the qualities pointer from the live player object
@ -1601,10 +1605,13 @@ public static class EntryPoint
internal static bool StopTickPumpAndJoin(int timeoutMs = 2000)
{
Compatibility.GameTickHooks.HeadlessPrefetch = false; // no more prefetch work once teardown starts
// Before the null check: a pump that starts after this (a login bootstrap racing the
// teardown) leaves its loop at once instead of ticking a generation being torn down.
Interlocked.Exchange(ref _tickPumpStopRequested, 1);
if (_tickPumpThread == null)
return true;
Interlocked.Exchange(ref _tickPumpStopRequested, 1);
if (_tickPumpThread == Thread.CurrentThread)
return Volatile.Read(ref _tickPumpExited) != 0; // never wait for itself
long deadline = Environment.TickCount64 + timeoutMs;
while (Volatile.Read(ref _tickPumpExited) == 0 && Environment.TickCount64 < deadline)
@ -1612,10 +1619,31 @@ public static class EntryPoint
bool exited = Volatile.Read(ref _tickPumpExited) != 0;
if (!exited)
RynthLog.Plugin($"DecalCoexistence: tick pump did NOT exit within {timeoutMs}ms.");
RynthLog.Plugin($"Plugin tick pump did NOT exit within {timeoutMs}ms{DescribePumpInside()}.");
return exited;
}
private static string DescribePumpInside()
{
try { string? inside = Plugins.PluginManager.DescribePumpDispatch(); return inside != null ? " (" + inside + ")" : ""; }
catch { return ""; }
}
/// <summary>
/// For PluginManager.ShutdownAll: stops the plugin pump if it is still running, waits up
/// to <paramref name="timeoutMs"/> for its frame in flight, and says whether the plugins
/// may be shut down now (PluginShutdownGate). At once when the pump already stopped (every
/// EngineLifecycle.Shutdown stops it first) or never started.
/// </summary>
internal static Plugins.PluginShutdownGate.Verdict StopTickPumpForPluginShutdown(int timeoutMs)
{
Thread? pump = _tickPumpThread;
bool onPump = pump != null && pump == Thread.CurrentThread;
if (pump != null && !onPump && Volatile.Read(ref _tickPumpExited) == 0)
StopTickPumpAndJoin(timeoutMs);
return Plugins.PluginShutdownGate.Decide(pump != null, Volatile.Read(ref _tickPumpExited) != 0, onPump);
}
/// <summary>
/// Non-blocking request for the headless plugin pump (NormalPluginPump /
/// DecalCoexistence) to stop. Sets the same flag as <see cref="StopTickPumpAndJoin"/>
@ -1630,6 +1658,22 @@ public static class EntryPoint
Interlocked.Exchange(ref _tickPumpStopRequested, 1);
}
/// <summary>
/// Sleeps <paramref name="total"/> in steps of at most 100 ms. False (stop now) as soon as
/// the pump's stop is requested or the engine's threads are stopped.
/// </summary>
private static bool SleepUnlessPumpStopRequested(TimeSpan total)
{
long end = Environment.TickCount64 + (long)total.TotalMilliseconds;
while (Volatile.Read(ref _tickPumpStopRequested) == 0)
{
long left = end - Environment.TickCount64;
if (left <= 0) return true;
if (!EngineThreads.Sleep((int)Math.Min(left, 100))) return false;
}
return false;
}
private static Thread? _initThread;
private static int _initAbortLogged;

View file

@ -9,7 +9,11 @@
// asked for a button (WindowFlags.BarButton: RynthSort, Oracle, ...; tooltip =
// its title; the set is rebuilt as plugins come and go), one per window a plugin
// draws that asked for one (its manifest's "windows" with "bar", UI/Sections/
// PluginWindows.cs), reload (RL) and pop out.
// PluginWindows.cs; an engine panel such a window has taken over loses its own
// button), reload (RL) and pop out.
// A button whose window is open, docked or popped out, draws highlighted in the
// theme's accent (RynthTheme.BarButtonOpen*); the ILT and Scripts buttons while
// any window in their menu is (UI/BarOpenState.cs; one IsOpen lookup a key).
// Dragging the grip moves the bar; the position is the shared bar= row in
// panel_state.txt. Right-click the grip for the bar's menu: its size, its rows
// and "Report a problem" (panel buttons have no menu). Pop out moves the ImGui
@ -65,8 +69,12 @@ internal static class ImGuiBar
// Window: a plugin's script window with a bar button of its own (WindowFlags.BarButton);
// the button toggles it through ScriptWindowRegistry, like the Scripts menu does.
// OpenKey: the panel whose open state lights the button (BarOpenState.KeyFor).
private sealed record ButtonInfo(string Title, string Id, string Icon, bool Letter, string Tooltip,
ScriptWindow? Window = null);
string OpenKey, ScriptWindow? Window = null);
// The open check every highlight uses (one set lookup a key), as one delegate: no allocation a frame.
private static readonly Func<string, bool> IsOpenCheck = ImGuiPanelHost.IsOpen;
// Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button.
// Item Count has no icon of its own since 2026-10-18: Inventory's Count button, /rc itemcount, the Character menu.
@ -147,6 +155,9 @@ internal static class ImGuiBar
private static ScriptBarItem[]? _builtScriptButtons;
private static int _builtImGuiOnlyMask;
private static int _builtPluginWindows = -1;
// The Scripts menu's panel keys (its button lights while any is open), rebuilt with the snapshot.
private static ScriptBarItem[]? _scriptKeysFor;
private static string[] _scriptKeys = Array.Empty<string>();
private static string _tooltip = "";
private static bool _placed;
private static Vector2 _pos, _persistedPos;
@ -457,12 +468,15 @@ internal static class ImGuiBar
PushBarButtonStyle(s);
ImFontPtr letterFont = ImGuiFonts.Get(UiFont.UiBold11);
// A button whose window is open (docked or popped out) draws in the theme's accent
// (BarOpenState); a menu button (ILT, Scripts) while any window it lists is open.
foreach (ButtonInfo b in _buttons!)
{
NextSlot(ref slot, perRow, iconsX, s, iconFont, popped);
if (IconButton(b.Id, b.Letter ? letterFont : iconFont, b.Icon, square, RynthTheme.BarText))
bool open = BarOpenState.IsOpen(b.OpenKey, IsOpenCheck);
if (IconButton(b.Id, b.Letter ? letterFont : iconFont, b.Icon, square, RynthTheme.BarText, open))
{
if (b.Window != null) ScriptWindowRegistry.PlayerSetVisible(b.Window, !ImGuiPanelHost.IsOpen(b.Window.PanelKey));
if (b.Window != null) ScriptWindowRegistry.PlayerSetVisible(b.Window, !open);
else PanelRouter.Toggle(b.Title);
}
SafeImGui.SetItemTooltip(b.Tooltip);
@ -474,7 +488,8 @@ internal static class ImGuiBar
{
NextSlot(ref slot, perRow, iconsX, s, iconFont, popped);
string? only = iltCount == 1 ? FirstIltPanel() : null;
if (IconButton("##ilt", iconFont, PhosphorIcons.Leaf, square, RynthTheme.BarText))
bool open = BarOpenState.AnyOpen(IltPanels, IsOpenCheck);
if (IconButton("##ilt", iconFont, PhosphorIcons.Leaf, square, RynthTheme.BarText, open))
{
if (only != null) PanelRouter.Toggle(only);
else ImGuiNET.ImGui.OpenPopup("##ilt_menu");
@ -488,7 +503,8 @@ internal static class ImGuiBar
if (scripts.Length > 0)
{
NextSlot(ref slot, perRow, iconsX, s, iconFont, popped);
if (IconButton("##scripts", iconFont, PhosphorIcons.AppWindow, square, RynthTheme.BarText))
bool open = BarOpenState.AnyOpen(ScriptKeys(scripts), IsOpenCheck);
if (IconButton("##scripts", iconFont, PhosphorIcons.AppWindow, square, RynthTheme.BarText, open))
ImGuiNET.ImGui.OpenPopup("##scripts_menu");
ImGuiNET.ImGui.SetItemTooltip("Script windows");
}
@ -610,11 +626,32 @@ internal static class ImGuiBar
}
}
/// <summary>A square bar button (the bar's button style) with an icon, or a letter, centred on it.</summary>
private static bool IconButton(string id, ImFontPtr font, string icon, Vector2 size, uint color)
/// <summary>The Scripts menu's panel keys, rebuilt only when its snapshot changes (a new array then). AC thread.</summary>
private static string[] ScriptKeys(ScriptBarItem[] items)
{
if (ReferenceEquals(items, _scriptKeysFor)) return _scriptKeys;
var keys = new string[items.Length];
for (int i = 0; i < items.Length; i++) keys[i] = items[i].PanelKey;
_scriptKeys = keys;
_scriptKeysFor = items;
return keys;
}
/// <summary>
/// A square bar button (the bar's button style) with an icon, or a letter, centred on it.
/// <paramref name="open"/>: its window is open, so it draws in the theme's accent.
/// </summary>
private static bool IconButton(string id, ImFontPtr font, string icon, Vector2 size, uint color, bool open = false)
{
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos();
if (open)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, RynthTheme.BarButtonOpen);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, RynthTheme.BarButtonOpenHover);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, RynthTheme.BarButtonOpenBorder);
}
bool clicked = ImGuiNET.ImGui.Button(id, size);
if (open) ImGuiNET.ImGui.PopStyleColor(3);
PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), font, icon, at, size, color);
return clicked;
}
@ -761,17 +798,19 @@ internal static class ImGuiBar
_builtImGuiOnlyMask = mask;
_builtPluginWindows = pluginWindows;
var list = new List<ButtonInfo>();
// An engine panel a plugin window has taken over ("takeOver") has no engine button: the
// window's own (below) stands in when it asks for one.
foreach (var (title, _) in OverlayHost.GetPanels())
if (!LauncherOnly.Contains(title))
if (!LauncherOnly.Contains(title) && !UI.Sections.PluginWindows.TakesOver(title))
{
string icon = IconFor(title, out bool letter);
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title));
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title, BarOpenState.KeyFor(title, null)));
}
foreach (string title in ImGuiOnlyBarPanels)
if (ImGuiOnlyWanted(title) && !LauncherOnly.Contains(title))
if (ImGuiOnlyWanted(title) && !LauncherOnly.Contains(title) && !UI.Sections.PluginWindows.TakesOver(title))
{
string icon = IconFor(title, out bool letter);
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title));
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title, BarOpenState.KeyFor(title, null)));
}
// Windows plugins draw (their manifests' "windows" with "bar", docs/PLUGIN_WINDOWS.md): the
// icon they name (a Phosphor glyph), else the title's letter; the button toggles the panel.
@ -779,7 +818,8 @@ internal static class ImGuiBar
{
bool letter = false;
string icon = w.Icon.Length > 0 ? w.Icon : IconFor(w.Title, out letter);
list.Add(new ButtonInfo(w.Title, "##bar_pw_" + w.Plugin + "_" + w.Id, icon, letter, w.Title));
list.Add(new ButtonInfo(w.Title, "##bar_pw_" + w.Plugin + "_" + w.Id, icon, letter, w.Title,
BarOpenState.KeyFor(w.Title, null)));
}
// Plugin script windows that asked for a button (RynthSort, Oracle, ...): after the
// engine's own. Only while the plugin is loaded and has submitted the window.
@ -789,7 +829,7 @@ internal static class ImGuiBar
string title = w.Title.Length > 0 ? w.Title : w.Key;
string icon = IconFor(title, out bool letter);
string id = "##bar_sw" + w.Hash.ToString("X8");
list.Add(new ButtonInfo(title, id, icon, letter, title, Window: w));
list.Add(new ButtonInfo(title, id, icon, letter, title, BarOpenState.KeyFor(title, w.PanelKey), Window: w));
}
_buttons = list.ToArray();
_tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar size and rows. Ctrl+wheel over the bar: size.";

View file

@ -9,12 +9,16 @@
// and close; 16 px resize grip, all Phosphor icons), placement restore/persistence shared
// with the Avalonia face through PanelStateStore, and per-panel error isolation.
//
// A plugin window can take an engine panel's place (TakeOver, the manifest's
// "takeOver"): same key, so the saved place, open state and commands carry
// over; the engine's face is kept and comes back on ReleaseTakeOver.
//
// Threads:
// Register engine init.
// RegisterDynamic / Unregister / RequestSize / RequestPos
// RegisterDynamic / Unregister / RequestSize / RequestPos / TakeOver / ReleaseTakeOver
// any thread (script windows, from the plugin pump thread);
// DrawOrder is copy-on-write, removal finishes in DrawAll;
// requests are applied in DrawPanel.
// requests are applied in DrawPanel, face swaps in DrawAll.
// Open / Close any thread (router: game thread / Avalonia UI thread).
// Applied on AC's render thread at the next DrawAll.
// DrawAll AC's render thread, inside the ImGui frame.
@ -146,8 +150,17 @@ internal static class ImGuiPanelHost
public volatile bool HasRequest; // RequestedSize or RequestedPos is set
public int Failures;
public string? Error;
/// <summary>True while a plugin window has this engine panel's place (TakeOver).</summary>
public bool TakenOver;
/// <summary>The engine's own face, kept from the first TakeOver for ReleaseTakeOver.</summary>
public FaceSet? EngineOwn;
/// <summary>A face change waiting for the render thread (ApplyFaceChanges).</summary>
public FaceSet? NextFace;
}
/// <summary>What draws a panel: its spec, its face's factory and its header text.</summary>
private sealed record FaceSet(PanelSpec Spec, Func<IImGuiPanel> Factory, string DisplayTitle);
private static readonly object Sync = new();
private static readonly Dictionary<string, Entry> Entries = new(StringComparer.OrdinalIgnoreCase);
// Copy-on-write under Sync: DrawAll iterates the list it read without holding the lock,
@ -264,6 +277,109 @@ internal static class ImGuiPanelHost
lock (Sync) return Entries.ContainsKey(title);
}
// ── Plugin windows taking over an engine panel (docs/PLUGIN_WINDOWS.md, "takeOver") ──
/// <summary>True when <paramref name="key"/> is an engine panel (Register), taken over or not. Any thread.</summary>
public static bool IsEnginePanel(string key)
{
lock (Sync) return Entries.TryGetValue(key, out Entry? e) && !e.Dynamic;
}
/// <summary>True while a plugin window draws in the engine panel <paramref name="key"/>'s place. Any thread.</summary>
public static bool IsTakenOver(string key)
{
lock (Sync) return Entries.TryGetValue(key, out Entry? e) && e.TakenOver;
}
/// <summary>
/// A plugin window takes the engine panel <paramref name="key"/>'s place: the panel keeps its
/// key (its saved place and size, open state, hotkeys, /rc command and router entry) and is
/// drawn with <paramref name="spec"/> and <paramref name="factory"/>'s face from the next
/// frame; one open now closes and opens again as the new face, where it was (popped out
/// stays popped out). The engine's own face is kept for <see cref="ReleaseTakeOver"/>. Also
/// updates a window already in place. False when <paramref name="key"/> isn't an engine
/// panel. Any thread; applied on AC's render thread.
/// </summary>
public static bool TakeOver(string key, string displayTitle, PanelSpec spec, Func<IImGuiPanel> factory)
{
lock (Sync)
{
if (!Entries.TryGetValue(key, out Entry? e) || e.Dynamic) return false;
// The first takeover finds the engine's face in place; later ones may find a plugin's.
e.EngineOwn ??= new FaceSet(e.Spec, e.Factory, e.DisplayTitle);
e.TakenOver = true;
e.NextFace = new FaceSet(spec, factory, displayTitle);
}
_faceChangePending = true;
return true;
}
/// <summary>
/// The plugin window that took over <paramref name="key"/> went (plugin unloaded, window
/// dropped): the engine's own face comes back in its place, open if the window was open.
/// Any thread; applied on AC's render thread.
/// </summary>
public static void ReleaseTakeOver(string key)
{
lock (Sync)
{
if (!Entries.TryGetValue(key, out Entry? e) || !e.TakenOver || e.EngineOwn == null) return;
e.TakenOver = false;
e.NextFace = e.EngineOwn;
}
_faceChangePending = true;
}
private static volatile bool _faceChangePending;
/// <summary>
/// Swaps in the faces TakeOver / ReleaseTakeOver asked for. A panel shown now closes as its
/// old face and opens as the new one (placement saved and read back as usual), and embedded
/// copies of it are dropped so their hosts draw the new face. AC thread, before the requests.
/// </summary>
private static void ApplyFaceChanges(float placeScale)
{
if (!_faceChangePending) return;
_faceChangePending = false;
List<Entry>? changed = null;
lock (Sync)
foreach (Entry e in DrawOrder)
{
if (e.NextFace is not FaceSet next) continue;
e.NextFace = null;
bool sameFace = e.Factory == next.Factory;
e.Spec = next.Spec;
e.Factory = next.Factory;
e.DisplayTitle = next.DisplayTitle;
if (!sameFace) (changed ??= new List<Entry>()).Add(e);
}
if (changed == null) return;
foreach (Entry e in changed)
{
RynthLog.UI($"ImGuiPanelHost: {e.Title} is drawn by {(e.TakenOver ? "a plugin's window" : "the engine's face again")}.");
DropEmbeddedCopies(e.Title);
if (!e.Shown) continue; // the next open uses the new face
Apply(e.Title, RequestKind.Close, placeScale);
Apply(e.Title, RequestKind.Open, placeScale);
}
}
/// <summary>Hides and drops the embedded copies of <paramref name="title"/> (another face takes its place). AC thread.</summary>
private static void DropEmbeddedCopies(string title)
{
List<string>? gone = null;
foreach (var kv in EmbeddedFaces)
if (kv.Value.Title.Equals(title, StringComparison.OrdinalIgnoreCase)) (gone ??= new List<string>()).Add(kv.Key);
if (gone == null) return;
foreach (string key in gone)
{
EmbeddedFace face = EmbeddedFaces[key];
EmbeddedFaces.Remove(key);
try { face.Instance.OnHidden(); }
catch (Exception ex) { RynthLog.UI($"ImGuiPanelHost: embedded {face.Title}.OnHidden threw {ex.GetType().Name}: {ex.Message}"); }
}
}
public static PanelFace CodeDefault(string title)
{
lock (Sync) return Entries.TryGetValue(title, out Entry? e) ? e.Spec.CodeDefault : PanelFace.Avalonia;
@ -455,6 +571,7 @@ internal static class ImGuiPanelHost
{
_frameScale = uiScale;
float placeScale = PlacementScale();
ApplyFaceChanges(placeScale); // plugin windows taking over (or giving back) engine panels
while (Requests.TryDequeue(out var req))
Apply(req.Title, req.Kind, placeScale);
RemoveUnregistered();

View file

@ -0,0 +1,149 @@
// ============================================================================
// RynthCore.Engine - ImGui/ImGuiStackGuard.cs
// Puts ImGui's stacks back after plugin drawing code (audit 2026-10-21, 02 F4).
// A plugin window's body (PluginWindowFace) is the plugin's own ImGui code; one
// unbalanced PushStyleColor, a BeginChild left open, or an exception between a
// Begin and its End used to carry over into every panel drawn after it that
// frame (soft asserts, so it showed as garbage or a later native fault).
//
// Take() records the stack depths with ImGui's own ErrorRecoveryStoreState
// (exported by our cimgui build); Check() compares a fresh record with it;
// RecoverTo() hands a record back to ErrorRecoveryTryToRecoverState, which ends
// what was left open (windows and child windows, tables, tab bars, tree nodes,
// groups, IDs, disabled blocks, colours, item flags, style vars, fonts, focus
// scopes) down to that record. ImGui's own error report (assert, tooltip, debug
// log) is switched off around that call: the caller logs once instead, and a
// broken plugin can't put an error tooltip on the screen every frame.
//
// Rule from ImGui: a record to recover to must be taken where the current
// window's ID stack is at its base (the start of a window or child body), since
// the recovery pops that window's IDs down to its first.
//
// The record is opaque here (ImGuiStackState reads it for the log). Its size is
// checked on first use; on a mismatch, or with a cimgui.dll without the exports,
// Available is false and callers do as before. AC's render thread, inside an
// ImGui frame and window (StoreState reads the current window).
// ============================================================================
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ImGuiStackGuard
{
/// <summary>Room for one record (ImGui 1.91.6 writes 22 bytes).</summary>
private const int RecordCapacity = 64;
/// <summary>One stack record. Zeroed before ImGui writes it, so two records compare byte for byte.</summary>
[StructLayout(LayoutKind.Sequential, Size = RecordCapacity)]
internal struct Mark
{
private fixed byte _bytes[RecordCapacity];
}
/// <summary>A record's fields (ImGuiStackState.Names), read in place: no allocation.</summary>
private static ReadOnlySpan<short> FieldsOf(in Mark m) =>
MemoryMarshal.Cast<byte, short>(MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(in m), 1)))
[..ImGuiStackState.Fields];
private static delegate* unmanaged[Cdecl]<void*, void> _store;
private static delegate* unmanaged[Cdecl]<void*, void> _recover;
private static int _state; // 0 = not resolved, 1 = available, -1 = off
/// <summary>True when the exports exist and the record size checked out. Render thread, inside a window.</summary>
public static bool Available
{
get
{
if (_state == 0) Resolve();
return _state > 0;
}
}
private static void Resolve()
{
_state = -1;
IntPtr module = EntryPoint.ImGuiNativeHandle;
if (module == IntPtr.Zero
|| !NativeLibrary.TryGetExport(module, "igErrorRecoveryStoreState", out IntPtr store)
|| !NativeLibrary.TryGetExport(module, "igErrorRecoveryTryToRecoverState", out IntPtr recover))
{
RynthLog.UI("ImGuiStackGuard: this cimgui.dll has no igErrorRecovery* exports; plugin drawing isn't checked for unbalanced stacks.");
return;
}
_store = (delegate* unmanaged[Cdecl]<void*, void>)store;
_recover = (delegate* unmanaged[Cdecl]<void*, void>)recover;
const byte fill = 0xCC;
byte* probe = stackalloc byte[RecordCapacity];
new Span<byte>(probe, RecordCapacity).Fill(fill);
_store(probe);
if (!ImGuiStackState.WroteExpectedSize(new ReadOnlySpan<byte>(probe, RecordCapacity), fill))
{
RynthLog.UI($"ImGuiStackGuard: ImGui's stack record isn't the {ImGuiStackState.RecordBytes} bytes this engine expects; plugin drawing isn't checked.");
return;
}
_state = 1;
}
/// <summary>The stack depths now. Only when <see cref="Available"/>.</summary>
public static Mark Take()
{
Mark m = default;
_store(&m);
return m;
}
/// <summary>The stack depths now against <paramref name="before"/>; <paramref name="now"/> for the log.</summary>
public static StackCheck Check(in Mark before, out Mark now)
{
now = Take();
return ImGuiStackState.Compare(FieldsOf(before), FieldsOf(now));
}
/// <summary>True when the record was taken with the window's ID stack at its base: one a recovery may go back to.</summary>
public static bool AtWindowBase(in Mark mark) => ImGuiStackState.IdsAtBase(FieldsOf(mark));
/// <summary>What changed between two records, for the log ("colours +2, windows +1").</summary>
public static string Describe(in Mark before, in Mark after) => ImGuiStackState.Describe(FieldsOf(before), FieldsOf(after));
/// <summary>
/// Ends and pops everything above <paramref name="mark"/> (taken where the window's ID stack
/// was at its base). Windows or pops below the mark can't be put back. When windows below it
/// were ended (ImGui's recovery then does nothing), only the colours, style vars and fonts
/// above it are popped, which are the context's and safe from any window.
/// </summary>
public static void RecoverTo(in Mark mark)
{
Mark now = Take();
if (!ImGuiStackState.CanRecover(FieldsOf(mark), FieldsOf(now)))
{
(int colours, int vars, int fonts) = ImGuiStackState.GlobalPops(FieldsOf(mark), FieldsOf(now));
if (colours > 0) ImGuiNET.ImGui.PopStyleColor(colours);
if (vars > 0) ImGuiNET.ImGui.PopStyleVar(vars);
for (int i = 0; i < fonts; i++) ImGuiNET.ImGui.PopFont();
return;
}
ImGuiNET.ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
bool assert = io.ConfigErrorRecoveryEnableAssert, tooltip = io.ConfigErrorRecoveryEnableTooltip;
bool debugLog = io.ConfigErrorRecoveryEnableDebugLog, recovery = io.ConfigErrorRecovery;
io.ConfigErrorRecoveryEnableAssert = false;
io.ConfigErrorRecoveryEnableTooltip = false;
io.ConfigErrorRecoveryEnableDebugLog = false;
io.ConfigErrorRecovery = true;
try
{
fixed (Mark* m = &Unsafe.AsRef(in mark)) _recover(m);
}
finally
{
io.ConfigErrorRecoveryEnableAssert = assert;
io.ConfigErrorRecoveryEnableTooltip = tooltip;
io.ConfigErrorRecoveryEnableDebugLog = debugLog;
io.ConfigErrorRecovery = recovery;
}
}
}

View file

@ -0,0 +1,121 @@
// ============================================================================
// RynthCore.Engine - ImGui/ImGuiStackState.cs
// What a plugin's draw left on ImGui's stacks, from two of Dear ImGui's own
// stack records (ImGuiErrorRecoveryState, taken by ImGuiStackGuard before and
// after the call). Pure: no ImGui calls, so tools/SectionsTests compiles it.
//
// The record is ImGui 1.91.6's ImGuiErrorRecoveryState: 11 shorts in the order
// of Names below (imgui_internal.h; ImGuiSelfTest pins the version). Checked
// against our cimgui.dll in a 32-bit probe on 2026-10-21: 22 bytes written,
// and ImGuiStackGuard re-checks the size before its first use.
// ============================================================================
using System;
using System.Text;
namespace RynthCore.Engine.ImGuiBackend;
/// <summary>How a plugin's draw left ImGui's stacks.</summary>
internal enum StackCheck
{
/// <summary>As it found them.</summary>
Balanced,
/// <summary>It left things open (pushes, a child window, a group...): ImGui can unwind them.</summary>
LeftOpen,
/// <summary>It ended or popped something it didn't begin (the host's window, colours): can't be put back.</summary>
ClosedTooMuch,
}
internal static class ImGuiStackState
{
/// <summary>Shorts in ImGuiErrorRecoveryState (1.91.6).</summary>
public const int Fields = 11;
/// <summary>Bytes ImGui writes for one record.</summary>
public const int RecordBytes = Fields * sizeof(short);
/// <summary>Index of the window stack's depth (Begin / BeginChild).</summary>
public const int WindowStack = 0;
/// <summary>What each field counts, in the record's order.</summary>
public static readonly string[] Names =
{
"windows", "IDs", "tree nodes", "colours", "style vars", "fonts",
"focus scopes", "groups", "item flags", "popups", "disabled",
};
/// <summary>
/// Fields that count the current window's own stacks (its IDs, its tree depth): they compare
/// only at the same window depth. The rest belong to the context.
/// </summary>
public static bool PerWindow(int field) => field is 1 or 2;
/// <summary>The draw's effect: <paramref name="after"/> against <paramref name="before"/>.</summary>
public static StackCheck Compare(ReadOnlySpan<short> before, ReadOnlySpan<short> after)
{
if (after[WindowStack] < before[WindowStack]) return StackCheck.ClosedTooMuch;
bool sameWindow = after[WindowStack] == before[WindowStack];
bool changed = !sameWindow;
for (int i = 0; i < Fields; i++)
{
if (i == WindowStack || (!sameWindow && PerWindow(i))) continue;
if (after[i] < before[i]) return StackCheck.ClosedTooMuch;
if (after[i] != before[i]) changed = true;
}
return changed ? StackCheck.LeftOpen : StackCheck.Balanced;
}
/// <summary>
/// The window's ID stack holds only the window's own ID: a record taken here is one ImGui's
/// recovery can go back to (it pops a window's IDs down to that one).
/// </summary>
public static bool IdsAtBase(ReadOnlySpan<short> record) => record[1] == 1;
/// <summary>Indexes of the context-wide stacks a pop works on from any window.</summary>
public const int Colours = 3, StyleVars = 4, Fonts = 5;
/// <summary>
/// ImGui's recovery can unwind to <paramref name="mark"/> only from the same window depth or
/// deeper; when the draw ended windows below the mark (the host's own), it does nothing.
/// </summary>
public static bool CanRecover(ReadOnlySpan<short> mark, ReadOnlySpan<short> now) => now[WindowStack] >= mark[WindowStack];
/// <summary>
/// When <see cref="CanRecover"/> is false: the colours, style vars and fonts to pop to get back
/// to <paramref name="mark"/> (those stacks belong to the context, not a window). 0 where none.
/// </summary>
public static (int Colours, int StyleVars, int Fonts) GlobalPops(ReadOnlySpan<short> mark, ReadOnlySpan<short> now) =>
(Math.Max(0, now[Colours] - mark[Colours]), Math.Max(0, now[StyleVars] - mark[StyleVars]), Math.Max(0, now[Fonts] - mark[Fonts]));
/// <summary>
/// "windows +1, colours +2, style vars +1": the fields that changed, with the change (a
/// window's own IDs and tree depth only when the window depth is the same).
/// </summary>
public static string Describe(ReadOnlySpan<short> before, ReadOnlySpan<short> after)
{
var sb = new StringBuilder();
bool sameWindow = after[WindowStack] == before[WindowStack];
for (int i = 0; i < Fields; i++)
{
int d = after[i] - before[i];
if (d == 0 || (!sameWindow && PerWindow(i))) continue;
if (sb.Length > 0) sb.Append(", ");
sb.Append(Names[i]).Append(' ').Append(d > 0 ? "+" : "").Append(d);
}
return sb.Length > 0 ? sb.ToString() : "nothing";
}
/// <summary>
/// The size check on first use: <paramref name="record"/> was filled with
/// <paramref name="fill"/> and then written by ImGui. True when exactly the first
/// <see cref="RecordBytes"/> bytes were written (the layout this file expects).
/// </summary>
public static bool WroteExpectedSize(ReadOnlySpan<byte> record, byte fill)
{
int written = 0;
for (int i = 0; i < record.Length; i++)
if (record[i] != fill) written = i + 1;
// A short that happens to equal fill|fill is a value no stack reaches (0xCCCC = -13108).
return written == RecordBytes;
}
}

View file

@ -4,9 +4,13 @@
// the panel host draws the window, this face hands the body to the plugin's
// RynthPluginRenderEmbed(surface, width, height) in the default UI font, under
// an ID scope of its own. Popped out, PluginManager.RenderEmbed adds ":popout"
// to the surface name. An export that throws is switched off (PluginManager
// logs it); the body then says so and asks again every 5 s, so a reloaded
// plugin draws again without the window being reopened.
// to the surface name. An export that throws (or returns -2, "failed") is
// switched off (PluginManager logs it); the body then says so and asks again
// every 5 s, so a reloaded plugin draws again without the window being reopened.
// After every call ImGui's stacks are checked against what they were before it
// (ImGuiStackGuard): whatever the plugin left open (colours, style vars, fonts,
// IDs, groups, child windows, tables...) is ended and popped there, so the
// panels drawn after it start clean; logged once per window, then counted.
// docs/PLUGIN_WINDOWS.md. AC's render thread.
// ============================================================================
@ -44,13 +48,31 @@ internal sealed class PluginWindowFace : IImGuiPanel
int result = PluginManager.EmbedFailed;
if (_failedAtMs < 0 || now - _failedAtMs >= RetryMs)
{
// Two stack records: the body's base (where a recovery goes back to: the panel host
// calls Draw right after its BeginChild, the ID stack at its base) and the depth the
// plugin gets, which it must leave as it found.
bool guarded = ImGuiStackGuard.Available;
ImGuiStackGuard.Mark bodyBase = guarded ? ImGuiStackGuard.Take() : default;
guarded = guarded && ImGuiStackGuard.AtWindowBase(bodyBase); // drawn anywhere else: as before
ImGuiNET.ImGui.PushID(_idScope);
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
ImGuiStackGuard.Mark given = guarded ? ImGuiStackGuard.Take() : default;
try { result = PluginManager.RenderEmbed(_plugin, _surface, avail, out _); }
finally
{
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.PopID();
ImGuiStackGuard.Mark after = default;
StackCheck check = guarded ? ImGuiStackGuard.Check(given, out after) : StackCheck.Balanced;
if (check == StackCheck.Balanced)
{
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.PopID();
}
else
{
// Ends and pops what the plugin left, with this face's ID scope and font.
ImGuiStackGuard.RecoverTo(bodyBase);
NoteUnbalanced(check, ImGuiStackGuard.Describe(given, after));
}
}
if (result == PluginManager.EmbedFailed) _failedAtMs = now;
else if (result == PluginManager.EmbedDrawn) _failedAtMs = -1;
@ -66,4 +88,22 @@ internal sealed class PluginWindowFace : IImGuiPanel
_ => $"Waiting for {_plugin}…",
}, Mute);
}
// Unbalanced draws by plugin + surface: logged the first time, then every RepeatEvery-th.
private static readonly System.Collections.Generic.Dictionary<string, int> Unbalanced = new(StringComparer.Ordinal);
private const int RepeatEvery = 1000;
private void NoteUnbalanced(StackCheck check, string what)
{
string key = _plugin + "/" + _title;
Unbalanced.TryGetValue(key, out int n);
Unbalanced[key] = ++n;
if (n != 1 && n % RepeatEvery != 0) return;
string again = n == 1 ? "" : $" ({n} times so far)";
RynthLog.Warn(check == StackCheck.ClosedTooMuch
? $"PluginWindows: {_plugin} drawing '{_title}' ended or popped what it didn't open ({what}){again}. " +
"What it left open was put back; what it took can't be, so the window may draw wrongly."
: $"PluginWindows: {_plugin} drawing '{_title}' left ImGui's stacks unbalanced ({what}){again}. " +
"Put back after its draw; the panels after it draw as normal.");
}
}

View file

@ -211,6 +211,11 @@ internal static class RynthTheme
public static uint BarBackground => WithAlpha(_t.BarBg, 0xE6);
public const float BarRounding = 4f;
public static uint BarButton => _t.FrameBg;
// A button whose window is open (docked or popped out, BarOpenState): the accent fill
// (Chat's active tab), halfway to the accent under the mouse, and an accent border.
public static uint BarButtonOpen => _t.AccentFill;
public static uint BarButtonOpenHover => _t.WindowBorder;
public static uint BarButtonOpenBorder => _t.Accent;
public static readonly uint BarText = Argb(0xFFFFFFFF);
public static readonly uint RcLabel = Argb(0xFF90EE90); // LightGreen
public static readonly uint ReloadLabel = Argb(0xFFF0E68C); // Khaki

View file

@ -21,7 +21,12 @@
// "miniremote") into the engine's current ImGui
// window on AC's render thread, inside a
// width x height child; reports the size it wants.
// 1 = drawn, 0 = not ready / unknown surface.
// 1 = drawn, 0 = not ready / unknown surface,
// -2 = failed (it caught its own exception): its
// surfaces go off for the session, as for a throw
// (engines before 2026-10-21 read -2 as 0). Leave
// ImGui's stacks as found; the engine puts back
// what a plugin window leaves open, and logs it.
// void RynthPluginOnServerMessage(uint opcode, byte* data, int length)
// — v78, reassembled server messages the plugin
// asked for with SetServerMessageInterestFn

View file

@ -1336,8 +1336,8 @@ internal static partial class PluginManager
/// Render thread only. Returns <see cref="EmbedDrawn"/>, <see cref="EmbedNotReady"/> (the
/// plugin isn't ready: before login, no ImGui context, or too old to draw in a pop-out),
/// <see cref="EmbedNoPlugin"/> (not loaded, or too old to have the export) or
/// <see cref="EmbedFailed"/> (it threw: the export is switched off for this session; the
/// plugin keeps running).
/// <see cref="EmbedFailed"/> (it threw, or returned -2 to say it caught its own exception:
/// the export is switched off for this session; the plugin keeps running).
/// </summary>
internal static unsafe int RenderEmbed(string pluginName, ReadOnlySpan<byte> surfaceUtf8, System.Numerics.Vector2 size, out System.Numerics.Vector2 want)
{
@ -1380,6 +1380,15 @@ internal static partial class PluginManager
fixed (byte* s = surfaceUtf8)
r = ((delegate* unmanaged[Cdecl]<byte*, float, float, float*, float*, int>)fn)(s, size.X, size.Y, &w, &h);
want = new System.Numerics.Vector2(float.IsFinite(w) ? MathF.Max(0, w) : 0, float.IsFinite(h) ? MathF.Max(0, h) : 0);
if (r == EmbedFailed)
{
// The plugin caught its own exception and says so (an exception can't leave a
// managed plugin's [UnmanagedCallersOnly] export, so plugins catch everything; with
// 0 the window would say "Waiting..." for ever): the same as a throw.
p.RenderEmbedPtr = IntPtr.Zero;
RynthLog.Error($"PluginManager: {p.DisplayName} RenderEmbed reported a failure (-2) - embedded surfaces off for this session (plugin keeps running).");
return EmbedFailed;
}
return r == 1 ? EmbedDrawn : EmbedNotReady;
}
catch (Exception ex)
@ -1436,6 +1445,17 @@ internal static partial class PluginManager
public static void ShutdownAll()
{
// A plugin's Shutdown never runs alongside its Tick on the pump thread (audit
// 2026-10-21, 01 #1). EngineLifecycle.Shutdown stops the pump before anything reaches
// here, so this returns at once; a frame still running gets ShutdownWaitMs more, and
// if it outlasts that the plugins are left alone. Nothing below changes then: the
// teardown's defensive ShutdownAll asks again after its other steps.
PluginShutdownGate.Verdict gate = EntryPoint.StopTickPumpForPluginShutdown(PluginShutdownGate.ShutdownWaitMs);
if (!PluginShutdownGate.MayShutDownPlugins(gate))
{
RynthLog.Error(PluginShutdownGate.DescribeRefusal(_plugins.Count, DescribePumpDispatch()));
return;
}
RynthLog.Plugin($"PluginManager: Shutting down {_plugins.Count} plugin(s)...");
UiLifecycleHooks.UiInitialized -= OnUIInitializedObserved;
LoginLifecycleHooks.LoginComplete -= OnLoginCompleteObserved;

View file

@ -1,7 +1,7 @@
// ============================================================================
// RynthCore.Engine - Plugins/PumpGuards.cs
//
// Two small pieces for PluginManager.TickAll and the plugin pump thread.
// Small pieces for PluginManager.TickAll, the plugin pump thread and plugin shutdown.
//
// StepFaultLog: TickAll's own steps (the main-thread freeze check, the delayed
// self-identify, the Nav3D frame clear/commit, dropping failed plugins' script
@ -17,6 +17,9 @@
// the dump, the hang watchdog reports, and this line names the plugin
// (2026-10-13 06:00: RynthAi's tick jumped to address 0).
//
// PluginShutdownGate: plugins are shut down only once the pump has stopped (or
// never ran), so no plugin's Shutdown runs alongside its Tick (audit 2026-10-21).
//
// Pure: no engine state. Compiled into tools\EngineRobustnessTests.
// ============================================================================
@ -82,3 +85,47 @@ internal static class PumpDispatchInfo
return $"inside {plugin} {export ?? "call"} for {ms} ms";
}
}
/// <summary>
/// Whether PluginManager.ShutdownAll may call the plugins' Shutdown now: never while the
/// plugin pump may still be inside a frame on its own thread, or a plugin's Tick and events
/// would run alongside its Shutdown, which frees their threads, textures and handles (a
/// native fault there can't be caught: audit 2026-10-21, 01 #1). EngineLifecycle.Shutdown
/// stops the pump before anything shuts a plugin down; this checks that the stop finished.
/// </summary>
internal static class PluginShutdownGate
{
/// <summary>How long ShutdownAll waits for the pump on top of EngineLifecycle's own join.</summary>
public const int ShutdownWaitMs = 5000;
internal enum Verdict
{
/// <summary>No pump was started in this generation (plugins off, or before login).</summary>
NoPump,
/// <summary>The pump has left its loop: nothing ticks the plugins any more.</summary>
PumpStopped,
/// <summary>Called on the pump thread itself: no frame of it can run alongside.</summary>
OnPumpThread,
/// <summary>The pump is still running (a frame outlasted the wait): leave the plugins alone.</summary>
PumpStillRunning,
}
/// <summary>
/// <paramref name="pumpStarted"/>: a pump thread was started; <paramref name="pumpExited"/>:
/// it has left its loop (after the stop and the wait); <paramref name="onPumpThread"/>: the
/// caller is that thread.
/// </summary>
public static Verdict Decide(bool pumpStarted, bool pumpExited, bool onPumpThread) =>
!pumpStarted ? Verdict.NoPump
: pumpExited ? Verdict.PumpStopped
: onPumpThread ? Verdict.OnPumpThread
: Verdict.PumpStillRunning;
public static bool MayShutDownPlugins(Verdict verdict) => verdict != Verdict.PumpStillRunning;
/// <summary>The log line when ShutdownAll leaves the plugins alone.</summary>
public static string DescribeRefusal(int plugins, string? pumpInside) =>
$"PluginManager: the plugin pump is still running ({pumpInside ?? "no plugin call named"}) - " +
$"{plugins} plugin(s) NOT shut down now, so no Shutdown runs alongside a Tick. " +
"The engine's teardown tries once more after its other steps.";
}

View file

@ -0,0 +1,42 @@
// ============================================================================
// RynthCore.Engine - UI/BarOpenState.cs
// Which toolbar buttons (ImGuiBar) draw as open: a button is highlighted in
// the theme's accent while a window it stands for is open, docked or popped
// out (a popped-out panel stays open in ImGuiPanelHost).
//
// What a button stands for: an engine panel's or a plugin window's button its
// title (a plugin window that took over an engine panel has that panel's
// title), a plugin script window's button that window's panel key ("script:
// ...", not its title); a button that opens a menu of several (ILT, Scripts)
// every window it lists, open while any of them is.
//
// Pure (no ImGui, no engine state): the caller passes the open check
// (ImGuiPanelHost.IsOpen, one set lookup a key). Tests: tools/BarLayoutTests.
// Any thread.
// ============================================================================
using System;
namespace RynthCore.Engine.UI;
internal static class BarOpenState
{
/// <summary>
/// The window a one-window button stands for: a script window's panel key when it is one,
/// else the title (engine panels, ImGui-only panels, plugin windows).
/// </summary>
public static string KeyFor(string title, string? scriptPanelKey) =>
string.IsNullOrEmpty(scriptPanelKey) ? title : scriptPanelKey;
/// <summary>A one-window button is open while its window is (an empty key never is).</summary>
public static bool IsOpen(string key, Func<string, bool> isOpen) =>
!string.IsNullOrEmpty(key) && isOpen(key);
/// <summary>A button for several windows (ILT, Scripts) is open while any of them is; none listed = closed.</summary>
public static bool AnyOpen(ReadOnlySpan<string> keys, Func<string, bool> isOpen)
{
foreach (string key in keys)
if (IsOpen(key, isOpen)) return true;
return false;
}
}

View file

@ -9,12 +9,20 @@
// registers a dynamic panel for each window the manifests ask for (a window
// with "server" only while that server is active) and unregisters the rest.
// The panel key is the window's title, so its saved place, hotkeys and /rc
// commands use the name players see; a title an engine panel has is refused.
// commands use the name players see. A title an engine panel has is refused,
// unless the window declares "takeOver": then it takes that panel's place
// (ImGuiPanelHost.TakeOver: same key, so the saved place and size, open state,
// hotkeys and commands carry over) and the engine's face steps aside, not drawn
// and without its bar button (TakesOver), until the window goes (the plugin
// unloads or stops declaring it): then the engine's face comes back where the
// window was, open if it was open. So a screen can move out of the engine with
// the plugin shipping first and the engine face deleted a release later.
// A window seen for the first time this session opens if it was open when the
// game last closed (Remember Open Windows); one that went with a plugin reload
// opens again when the plugin comes back.
//
// WindowPlan.cs is the pure part (which windows, which are refused and why).
// WindowPlan.cs is the pure part (which windows, which are refused and why,
// which take over an engine panel).
// ============================================================================
using System;
@ -27,13 +35,14 @@ namespace RynthCore.Engine.UI.Sections;
internal static class PluginWindows
{
private sealed record Hosted(SectionWindowDecl Decl, string Signature);
private sealed record Hosted(SectionWindowDecl Decl, string Signature, bool TakesOver);
private static readonly Dictionary<string, Hosted> Live = new(StringComparer.OrdinalIgnoreCase); // render thread
private static readonly HashSet<string> SeenThisSession = new(StringComparer.OrdinalIgnoreCase); // render thread
private static readonly HashSet<string> ReopenWhenBack = new(StringComparer.OrdinalIgnoreCase); // render thread
private static readonly HashSet<string> RefusalsLogged = new(StringComparer.Ordinal); // render thread
private static volatile SectionWindowDecl[] _barWindows = Array.Empty<SectionWindowDecl>();
private static volatile string[] _takenOver = Array.Empty<string>();
private static int _version;
/// <summary>Hosted windows that asked for a bar button, in manifest order. Any thread.</summary>
@ -45,12 +54,23 @@ internal static class PluginWindows
/// <summary>True when <paramref name="title"/> is a plugin window hosted now. Render thread.</summary>
public static bool IsHosted(string title) => Live.ContainsKey(title);
/// <summary>
/// True while a plugin window has taken the place of the engine panel <paramref name="title"/>:
/// the engine's own bar button for it is left out (the window has its own when it asks). Any thread.
/// </summary>
public static bool TakesOver(string title)
{
foreach (string t in _takenOver)
if (t.Equals(title, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
/// <summary>After a SectionRegistry rebuild: register, update and drop the windows' panels. Render thread.</summary>
public static void Sync(IReadOnlyList<SectionManifest> manifests, IReadOnlyList<ServerState> servers)
{
var refused = new List<string>();
Dictionary<string, SectionWindowDecl> want = WindowPlan.Build(manifests, servers,
title => ImGuiPanelHost.HasFace(title) && !Live.ContainsKey(title), refused);
var takeOvers = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, SectionWindowDecl> want = WindowPlan.Build(manifests, servers, Use, refused, takeOvers);
foreach (string r in refused)
if (RefusalsLogged.Add(r)) RynthLog.UI("PluginWindows: " + r + " - not shown.");
@ -60,8 +80,18 @@ internal static class PluginWindows
if (!want.ContainsKey(title)) gone.Add(title);
foreach (string title in gone)
{
if (ImGuiPanelHost.IsOpen(title)) ReopenWhenBack.Add(title);
ImGuiPanelHost.Unregister(title);
Hosted was = Live[title];
if (was.TakesOver)
{
// The engine's face comes back in the window's place (open if it was open).
ImGuiPanelHost.ReleaseTakeOver(title);
RynthLog.UI($"PluginWindows: {was.Decl.Plugin}'s window '{title}' went - the engine's panel is back.");
}
else
{
if (ImGuiPanelHost.IsOpen(title)) ReopenWhenBack.Add(title);
ImGuiPanelHost.Unregister(title);
}
Live.Remove(title);
changed = true;
}
@ -71,9 +101,19 @@ internal static class PluginWindows
string sig = WindowPlan.Signature(w);
if (Live.TryGetValue(title, out Hosted? h) && h.Signature == sig) continue;
SectionWindowDecl decl = w;
ImGuiPanelHost.RegisterDynamic(title, title, Spec(decl), () => new PluginWindowFace(decl.Plugin, decl.Surface, decl.Title));
Func<IImGuiPanel> face = () => new PluginWindowFace(decl.Plugin, decl.Surface, decl.Title);
if (takeOvers.Contains(title))
{
// An engine panel's place: its key, saved place and open state stay; nothing to reopen.
if (!ImGuiPanelHost.TakeOver(title, title, Spec(decl), face)) continue;
if (h == null) RynthLog.UI($"PluginWindows: {decl.Plugin}'s window '{title}' takes the engine panel's place.");
Live[title] = new Hosted(decl, sig, TakesOver: true);
changed = true;
continue;
}
ImGuiPanelHost.RegisterDynamic(title, title, Spec(decl), face);
bool first = h == null;
Live[title] = new Hosted(decl, sig);
Live[title] = new Hosted(decl, sig, TakesOver: false);
changed = true;
if (!first) continue;
bool reopen = ReopenWhenBack.Remove(title);
@ -86,12 +126,26 @@ internal static class PluginWindows
if (!changed) return;
var bar = new List<SectionWindowDecl>();
var taken = new List<string>();
foreach (Hosted h in Live.Values)
{
if (h.Decl.Bar) bar.Add(h.Decl);
if (h.TakesOver) taken.Add(h.Decl.Title);
}
_barWindows = bar.ToArray();
_takenOver = taken.ToArray();
System.Threading.Interlocked.Increment(ref _version);
}
/// <summary>
/// What already uses <paramref name="title"/>: an engine panel (taken over by a window here or
/// not), this sync's own hosted window (free), or another panel such as a script window.
/// </summary>
private static TitleUse Use(string title) =>
ImGuiPanelHost.IsEnginePanel(title) ? TitleUse.EnginePanel
: ImGuiPanelHost.HasFace(title) && !Live.ContainsKey(title) ? TitleUse.Other
: TitleUse.Free;
private static PanelSpec Spec(SectionWindowDecl w) => new(
new Vector2(w.Width, w.Height), new Vector2(w.MinWidth, w.MinHeight),
EdgeToEdge: w.EdgeToEdge, GripInBody: w.EdgeToEdge);

View file

@ -20,7 +20,7 @@
// "windows": [
// { "id": "characters", "title": "Characters", "surface": "window:characters",
// "icon": "\uE68E", "width": 420, "height": 260, "minWidth": 280, "minHeight": 140,
// "bar": true, "edgeToEdge": true, "server": "" } ]
// "bar": true, "edgeToEdge": true, "server": "", "takeOver": false } ]
// }
// servers servers the plugin knows. A built-in id (ilt, aelrynth) keeps the
// engine's own detection; a new id is detected from its lists.
@ -34,7 +34,11 @@
// hosts as panels: header, pop-out, resize, remembered place, a bar
// button when "bar" (the icon: a Phosphor glyph, else the title's
// letter); the body is "surface" through RynthPluginRenderEmbed.
// "title" is the panel key (unique; an engine panel's is refused).
// "title" is the panel key (unique). An engine panel's title is refused,
// unless "takeOver": true (2026-10-21): the window then draws in that
// panel's place (same key: its saved place, open state and commands)
// and the engine's face comes back when the plugin goes. Engines
// before that ignore the key and keep their face (the title refused).
// "server" set: only while that server is active. docs/PLUGIN_WINDOWS.md.
//
// Everything from a plugin is checked here: ids are short lower-case words,
@ -93,7 +97,9 @@ internal sealed record SectionWindowDecl(
float MinHeight,
bool Bar,
bool EdgeToEdge,
string Server)
string Server,
// Takes the place of the engine panel with this title while hosted ("takeOver": true).
bool TakeOver = false)
{
/// <summary>For every world, not one server.</summary>
public bool IsUniversal => Server.Length == 0;
@ -210,7 +216,8 @@ internal static class SectionManifestParser
float minWidth = Math.Min(WindowSize(Size(e, "minWidth"), MinWindowSize), width);
float minHeight = Math.Min(WindowSize(Size(e, "minHeight"), MinWindowSize), height);
windows.Add(new SectionWindowDecl(plugin, id, title, surface, Icon(Str(e, "icon")),
width, height, minWidth, minHeight, Bool(e, "bar", false), Bool(e, "edgeToEdge", false), server));
width, height, minWidth, minHeight, Bool(e, "bar", false), Bool(e, "edgeToEdge", false), server,
Bool(e, "takeOver", false)));
}
return new SectionManifest(plugin, servers.ToArray(), sections.ToArray(), contributions.ToArray())

View file

@ -9,29 +9,49 @@ using System.Collections.Generic;
namespace RynthCore.Engine.UI.Sections;
/// <summary>What already uses a window's title (its panel key).</summary>
internal enum TitleUse
{
/// <summary>Nothing, or this window's own panel (hosted already).</summary>
Free,
/// <summary>An engine panel: a window that declares "takeOver" draws in its place; any other is refused.</summary>
EnginePanel,
/// <summary>Another panel that isn't the engine's (a script window): refused.</summary>
Other,
}
/// <summary>Which plugin windows to host, from the manifests and the servers. Pure.</summary>
internal static class WindowPlan
{
/// <summary>
/// The windows to host, keyed by title, and the ones left out with the reason. A server
/// window counts only while its server is active; the first plugin to claim a title keeps it;
/// <paramref name="isEnginePanel"/> titles are refused.
/// window counts only while its server is active; the first plugin to claim a title keeps it.
/// A title an engine panel has (<paramref name="titleUse"/>) is hosted only when the window
/// declares "takeOver": it then goes in <paramref name="takeOvers"/>, and the engine's face
/// for that title steps aside while the window is hosted. Other used titles are refused.
/// </summary>
public static Dictionary<string, SectionWindowDecl> Build(IReadOnlyList<SectionManifest> manifests,
IReadOnlyList<ServerState> servers, Func<string, bool> isEnginePanel, List<string> refused)
IReadOnlyList<ServerState> servers, Func<string, TitleUse> titleUse, List<string> refused, ISet<string> takeOvers)
{
var want = new Dictionary<string, SectionWindowDecl>(StringComparer.OrdinalIgnoreCase);
foreach (SectionManifest m in manifests)
foreach (SectionWindowDecl w in m.Windows)
{
if (!w.IsUniversal && !ServerActive(servers, w.Server)) continue;
if (isEnginePanel(w.Title)) { refused.Add($"{w.Plugin}'s window '{w.Title}': an engine panel has that title"); continue; }
TitleUse use = titleUse(w.Title);
if (use == TitleUse.Other) { refused.Add($"{w.Plugin}'s window '{w.Title}': another panel has that title"); continue; }
if (use == TitleUse.EnginePanel && !w.TakeOver)
{
refused.Add($"{w.Plugin}'s window '{w.Title}': an engine panel has that title (\"takeOver\": true takes its place)");
continue;
}
if (want.TryGetValue(w.Title, out SectionWindowDecl? first))
{
refused.Add($"{w.Plugin}'s window '{w.Title}': {first.Plugin} has a window with that title");
continue;
}
want[w.Title] = w;
if (use == TitleUse.EnginePanel) takeOvers.Add(w.Title);
}
return want;
}
@ -45,5 +65,5 @@ internal static class WindowPlan
/// <summary>What a hosted window's panel depends on: a change re-registers it.</summary>
public static string Signature(SectionWindowDecl w) =>
string.Join("|", w.Plugin, w.Surface, w.Icon, w.Width, w.Height, w.MinWidth, w.MinHeight, w.Bar, w.EdgeToEdge);
string.Join("|", w.Plugin, w.Surface, w.Icon, w.Width, w.Height, w.MinWidth, w.MinHeight, w.Bar, w.EdgeToEdge, w.TakeOver);
}

View file

@ -7,7 +7,7 @@
1. writes obj\...\rynth-plugin.json from the csproj:
name RynthPluginName (default: AssemblyName without "RynthCore.Plugin.")
version Version (Publish-Update.ps1 passes -p:Version=yyyy.m.d.n)
minEngineApi RynthPluginMinEngineApi
minEngineApi RynthPluginMinEngineApi (raised in release builds; see _RynthPluginEffectiveMinEngineApi)
maxEngineApi RynthPluginMaxEngineApi (optional; leave unset - the table is append-only)
dependencies @(RynthPluginDependency) Include = plugin name, metadata MinVersion, Optional="true"
author RynthPluginAuthor (default: Authors, then Company)
@ -37,9 +37,41 @@
<PropertyGroup>
<!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. -->
<RynthCoreSdkApiVersion>89</RynthCoreSdkApiVersion>
<!-- The first engine API that loads managed plugins and gives them Runtime\PluginShared (2026.10.19.1). -->
<RynthCoreManagedPluginApi>88</RynthCoreManagedPluginApi>
<_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn>
</PropertyGroup>
<!--
The minEngineApi that goes into the manifest (and the [assembly: RynthPluginManifest] runtime
check): _RynthPluginEffectiveMinEngineApi.
Normally the plugin's own RynthPluginMinEngineApi, as it is.
RynthPluginSharedSdk=true (Publish-Update.ps1's release builds): the plugin ships alone in the
feed and runs against the RynthCore.PluginSdk.dll in Runtime\PluginShared, which reaches a
player only with the core installer of the same release. Its Has* checks guard against an
engine without a function, not against an older PluginShared without an SDK member it calls
(that fails the method, or the load). So:
* a declared minimum at or above RynthCoreManagedPluginApi (88) is the plugin's own checked
claim and is used as it is;
* a lower one (the "66: every newer call is behind its Has* check" of NativeAOT days, when each
plugin carried its own SDK) can't hold for a plugin that needs 88 just to load, so the build
uses RynthCoreSdkApiVersion, the API of the SDK it was compiled against: it may call anything
this SDK has, and the launcher then holds the plugin until the player's core has that API.
A plugin checked against an older PluginShared declares that API (88 or more) to keep running on
older cores. Release builds used to force -p:RynthPluginMinEngineApi=88 on every plugin instead,
so a plugin calling a v89 SDK member was offered to API-88 cores (structural audit 2026-10-21).
-->
<PropertyGroup Condition="'$(_RynthPluginManifestOn)' == 'true'">
<_RynthPluginEffectiveMinEngineApi>$(RynthPluginMinEngineApi.Trim())</_RynthPluginEffectiveMinEngineApi>
<_RynthPluginMinIsNumber>$([System.Text.RegularExpressions.Regex]::IsMatch('$(RynthPluginMinEngineApi.Trim())', '^[0-9]{1,9}$'))</_RynthPluginMinIsNumber>
</PropertyGroup>
<PropertyGroup Condition="'$(_RynthPluginManifestOn)' == 'true' and '$(RynthPluginSharedSdk)' == 'true' and '$(_RynthPluginMinIsNumber)' == 'True'">
<_RynthPluginMinRaised Condition="$(RynthPluginMinEngineApi.Trim()) &lt; $(RynthCoreManagedPluginApi)">true</_RynthPluginMinRaised>
<_RynthPluginEffectiveMinEngineApi Condition="'$(_RynthPluginMinRaised)' == 'true'">$(RynthCoreSdkApiVersion)</_RynthPluginEffectiveMinEngineApi>
</PropertyGroup>
<PropertyGroup Condition="'$(_RynthPluginManifestOn)' == 'true'">
<RynthPluginName Condition="'$(RynthPluginName)' == ''">$([System.Text.RegularExpressions.Regex]::Replace('$(AssemblyName)', '^RynthCore\.Plugin\.', ''))</RynthPluginName>
<RynthPluginAuthor Condition="'$(RynthPluginAuthor)' == '' and '$(Authors)' != '' and '$(Authors)' != '$(AssemblyName)'">$(Authors)</RynthPluginAuthor>
@ -56,7 +88,7 @@
plugin's own check matches its manifest without any code in the plugin. -->
<ItemGroup Condition="'$(_RynthPluginManifestOn)' == 'true'">
<AssemblyAttribute Include="RynthCore.PluginSdk.RynthPluginManifestAttribute">
<_Parameter1>$(RynthPluginMinEngineApi)</_Parameter1>
<_Parameter1>$(_RynthPluginEffectiveMinEngineApi)</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
@ -283,7 +315,9 @@ public class RynthEmbedPluginManifest : Task
<!-- 1 + 2: the JSON and RynthPluginInfo, before compiling (RynthPluginInfo is compiled in). -->
<Target Name="RynthGeneratePluginManifest" BeforeTargets="CoreCompile" Condition="'$(_RynthPluginManifestOn)' == 'true'">
<RynthWritePluginManifest Name="$(RynthPluginName)" Version="$(Version)" MinEngineApi="$(RynthPluginMinEngineApi)"
<Message Importance="high" Condition="'$(_RynthPluginMinRaised)' == 'true'"
Text="$(RynthPluginName): RynthPluginMinEngineApi $(RynthPluginMinEngineApi) is below the managed-plugin API $(RynthCoreManagedPluginApi); this shared-SDK build declares $(_RynthPluginEffectiveMinEngineApi), the API of the SDK it was built with. Declare a checked minimum (at least $(RynthCoreManagedPluginApi)) to run on older cores." />
<RynthWritePluginManifest Name="$(RynthPluginName)" Version="$(Version)" MinEngineApi="$(_RynthPluginEffectiveMinEngineApi)"
MaxEngineApi="$(RynthPluginMaxEngineApi)" SdkApiVersion="$(RynthCoreSdkApiVersion)"
Author="$(RynthPluginAuthor)" Description="$(RynthPluginDescription)"
Homepage="$(RynthPluginHomepage)" License="$(RynthPluginLicense)"

View file

@ -5,7 +5,9 @@
icons per row = ceil(icons / rows) capped at the limit, the clamps (rows 1-6, limit 0 or
2-30), the grip menu's icons-per-row steps (no limit above 30), the Settings picker index
maps, and the barlayout= row of panel_state.txt (a missing or bad row gives 1 row, no limit).
No files, no ImGui. Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
The open highlight (src\RynthCore.Engine\UI\BarOpenState.cs, compiled in): the window each
button stands for (a script window by its panel key, not its title) and a menu button (ILT,
Scripts) lit while any window it lists is open. No files, no ImGui. Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
@ -18,6 +20,7 @@
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\BarLayout.cs" Link="Engine\BarLayout.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\BarOpenState.cs" Link="Engine\BarOpenState.cs" />
</ItemGroup>
</Project>

View file

@ -22,6 +22,7 @@ internal static class Program
StepMaxPerRow();
PickerIndexes();
ParseAndFormat();
OpenState();
Console.WriteLine();
Console.WriteLine(_fails == 0 ? $"PASS ({_asserts} checks)" : $"FAIL ({_fails} of {_asserts} checks failed)");
return _fails == 0 ? 0 : 1;
@ -111,4 +112,43 @@ internal static class Program
Check(!BarLayout.TryParse("two,8", out r, out m) && r == 1 && m == 0, "not a number: defaults");
Check(!BarLayout.TryParse("2,8,1", out r, out m) && r == 1 && m == 0, "three values: defaults");
}
private static void OpenState()
{
Console.WriteLine("OpenState");
// What ImGuiPanelHost would say: these panels open (case-insensitive, like its set).
// A popped-out panel is in the set too (pop out never closes it).
var openSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Chat", "Mini Remote", "script:rynthsort", "Guardian" };
Func<string, bool> isOpen = openSet.Contains;
// Which window a one-window button stands for.
Eq(BarOpenState.KeyFor("Chat", null), "Chat", "an engine panel: its title");
Eq(BarOpenState.KeyFor("Mini Remote", ""), "Mini Remote", "an empty panel key reads as none");
Eq(BarOpenState.KeyFor("RynthSort", "script:rynthsort"), "script:rynthsort", "a script window: its panel key, not its title");
// One-window buttons.
Check(BarOpenState.IsOpen(BarOpenState.KeyFor("Chat", null), isOpen), "an open panel's button is lit");
Check(BarOpenState.IsOpen(BarOpenState.KeyFor("Mini Remote", null), isOpen), "the remote open: its button is lit");
Check(!BarOpenState.IsOpen(BarOpenState.KeyFor("Radar", null), isOpen), "a closed panel's button is not");
Check(BarOpenState.IsOpen(BarOpenState.KeyFor("RynthSort", "script:rynthsort"), isOpen), "an open script window's button is lit");
Check(!BarOpenState.IsOpen(BarOpenState.KeyFor("Oracle", "script:oracle"), isOpen), "a closed script window's button is not");
Check(!BarOpenState.IsOpen("", isOpen), "an empty key is never open");
Check(BarOpenState.IsOpen("chat", isOpen), "the open check's case rules apply (the host's set ignores case)");
// Menu buttons: lit while any window they list is open.
Check(BarOpenState.AnyOpen(new[] { "Bounties", "Guardian" }, isOpen), "ILT: Guardian open lights the ILT button");
Check(!BarOpenState.AnyOpen(new[] { "Bounties" }, isOpen), "ILT: only Bounties, closed");
Check(BarOpenState.AnyOpen(new[] { "script:lua/a", "script:rynthsort" }, isOpen), "Scripts: one window open is enough");
Check(!BarOpenState.AnyOpen(new[] { "script:lua/a", "script:lua/b" }, isOpen), "Scripts: none open");
Check(!BarOpenState.AnyOpen(Array.Empty<string>(), isOpen), "a menu with nothing listed is not lit");
// The open check is asked once a key, and the search stops at the first open one.
int asked = 0;
Func<string, bool> counting = k => { asked++; return openSet.Contains(k); };
BarOpenState.AnyOpen(new[] { "Guardian", "Bounties", "Radar" }, counting);
Eq(asked, 1, "stops at the first open window");
asked = 0;
BarOpenState.AnyOpen(new[] { "Radar", "", "Bounties" }, counting);
Eq(asked, 2, "every key asked once when none is open; an empty key not at all");
}
}

View file

@ -22,7 +22,9 @@
IdRequester.cs the engine-send marker that tags every engine 0xC8
DumpBudget.cs the full OOM dump needs free space and a cap on dumps across clients
PumpGuards.cs TickAll's own steps are caught (logged once, then counted); the hang
report names the plugin call the pump is inside
report names the plugin call the pump is inside; PluginShutdownGate:
plugins are shut down only once the pump stopped (plus source scans
of EngineLifecycle's step order and ShutdownAll's gate)
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>

View file

@ -50,6 +50,7 @@ internal static partial class Program
RunAutoIdDrainTests();
RunPumpGuardTests();
RunShutdownOrderTests();
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
return _failed == 0 ? 0 : 1;

View file

@ -0,0 +1,114 @@
using System.Text.RegularExpressions;
using RynthCore.Engine.Plugins;
namespace EngineRobustnessTests;
/// <summary>
/// Plugins are shut down only once the plugin pump has stopped (audit 2026-10-21, 01 #1):
/// PluginShutdownGate's verdicts (Plugins/PumpGuards.cs), and source scans that
/// EngineLifecycle.Shutdown stops the pump before any step that shuts a plugin down, and that
/// PluginManager.ShutdownAll asks the gate before it calls a plugin.
/// </summary>
internal static partial class Program
{
private static void RunShutdownOrderTests()
{
ShutdownGateVerdicts();
ShutdownGateRefusalLine();
LifecycleStopsPumpBeforePlugins();
ShutdownAllAsksTheGateFirst();
}
private static void ShutdownGateVerdicts()
{
_case = "shutdown gate";
Check(PluginShutdownGate.Decide(pumpStarted: false, pumpExited: false, onPumpThread: false) == PluginShutdownGate.Verdict.NoPump,
"no pump started: plugins may be shut down");
Check(PluginShutdownGate.Decide(true, true, false) == PluginShutdownGate.Verdict.PumpStopped, "pump left its loop: stopped");
Check(PluginShutdownGate.Decide(true, false, true) == PluginShutdownGate.Verdict.OnPumpThread, "on the pump thread itself");
Check(PluginShutdownGate.Decide(true, false, false) == PluginShutdownGate.Verdict.PumpStillRunning,
"pump still running on another thread");
Check(PluginShutdownGate.MayShutDownPlugins(PluginShutdownGate.Verdict.NoPump), "NoPump allows");
Check(PluginShutdownGate.MayShutDownPlugins(PluginShutdownGate.Verdict.PumpStopped), "PumpStopped allows");
Check(PluginShutdownGate.MayShutDownPlugins(PluginShutdownGate.Verdict.OnPumpThread), "OnPumpThread allows (no frame alongside)");
Check(!PluginShutdownGate.MayShutDownPlugins(PluginShutdownGate.Verdict.PumpStillRunning),
"a pump still in a frame refuses: no Shutdown alongside a Tick");
int wait = PluginShutdownGate.ShutdownWaitMs;
Check(wait >= 1000 && wait <= 10000, $"the extra wait is bounded (1-10 s), got {wait} ms");
}
private static void ShutdownGateRefusalLine()
{
_case = "shutdown gate line";
string line = PluginShutdownGate.DescribeRefusal(3, "inside RynthAi Tick for 4200 ms");
Check(line.Contains("inside RynthAi Tick for 4200 ms"), "names what the pump is inside");
Check(line.Contains("3 plugin(s) NOT shut down"), "says how many plugins were left alone");
Check(PluginShutdownGate.DescribeRefusal(1, null).Contains("no plugin call named"), "no dispatch: says so");
}
/// <summary>
/// The pump stops (TickPump.StopAndJoin) once, after the queues are disarmed and before
/// every step that can shut a plugin down or tear down what its tick reads.
/// </summary>
private static void LifecycleStopsPumpBeforePlugins()
{
_case = "shutdown order";
string? engine = FindRepoDir(Path.Combine("src", "RynthCore.Engine"));
Check(engine != null, "found src\\RynthCore.Engine by walking up");
if (engine == null) return;
string src = File.ReadAllText(Path.Combine(engine, "EngineLifecycle.cs"));
int start = src.IndexOf("public static void Shutdown()", StringComparison.Ordinal);
Check(start >= 0, "EngineLifecycle.Shutdown found");
if (start < 0) return;
var steps = new List<string>();
foreach (Match m in Regex.Matches(src[start..], "Step\\(\"([^\"]+)\""))
steps.Add(m.Groups[1].Value);
int pump = steps.IndexOf("TickPump.StopAndJoin");
Check(pump >= 0, "the pump is stopped");
Check(steps.FindAll(s => s == "TickPump.StopAndJoin").Count == 1, "exactly once");
foreach (string before in new[] { "AcMainThreadQueue.Disarm", "UiDataHub.Disarm" })
{
int at = steps.IndexOf(before);
Check(at >= 0 && at < pump, $"{before} still comes first");
}
foreach (string after in new[] { "AcUiPassHook.Uninstall", "VideoPatch.Uninstall", "EndSceneHook.Uninstall",
"DecalBridgeHost.Shutdown", "PluginManager.ShutdownAll (defensive)",
"EngineThreads.StopAndJoinAll", "ManagedPlugins.UnloadRetired" })
{
int at = steps.IndexOf(after);
Check(at > pump, $"the pump stops before {after} (pump at {pump}, {after} at {at})");
}
}
/// <summary>ShutdownAll asks PluginShutdownGate (through EntryPoint) before UnloadAllPlugins, and returns on a refusal.</summary>
private static void ShutdownAllAsksTheGateFirst()
{
_case = "ShutdownAll gate";
string? plugins = FindRepoDir(Path.Combine("src", "RynthCore.Engine", "Plugins"));
Check(plugins != null, "found src\\RynthCore.Engine\\Plugins by walking up");
if (plugins == null) return;
string src = File.ReadAllText(Path.Combine(plugins, "PluginManager.cs")).Replace("\r\n", "\n");
int start = src.IndexOf("public static void ShutdownAll()", StringComparison.Ordinal);
Check(start >= 0, "ShutdownAll found");
if (start < 0) return;
int end = src.IndexOf("\n }\n", start, StringComparison.Ordinal);
string body = end > start ? src[start..end] : src[start..];
int gate = body.IndexOf("EntryPoint.StopTickPumpForPluginShutdown(", StringComparison.Ordinal);
int refuse = body.IndexOf("PluginShutdownGate.MayShutDownPlugins(gate)", StringComparison.Ordinal);
int unload = body.IndexOf("UnloadAllPlugins();", StringComparison.Ordinal);
Check(gate >= 0 && refuse > gate, "asks the gate");
Check(unload > refuse, "before any plugin is called (UnloadAllPlugins)");
int ret = refuse < 0 ? -1 : body.IndexOf("return;", refuse, StringComparison.Ordinal);
Check(ret > refuse && ret < unload, "returns without calling the plugins on a refusal");
string? engine = Path.GetDirectoryName(plugins);
string entry = File.ReadAllText(Path.Combine(engine!, "EntryPoint.cs")).Replace("\r\n", "\n");
int stop = entry.IndexOf("internal static bool StopTickPumpAndJoin(", StringComparison.Ordinal);
Check(stop >= 0, "StopTickPumpAndJoin found");
if (stop < 0) return;
int flag = entry.IndexOf("Interlocked.Exchange(ref _tickPumpStopRequested, 1);", stop, StringComparison.Ordinal);
int nullCheck = entry.IndexOf("if (_tickPumpThread == null)", stop, StringComparison.Ordinal);
Check(flag > stop && flag < nullCheck, "the stop flag is set before the no-pump early return (a late pump exits at once)");
}
}

View file

@ -28,11 +28,13 @@
<Compile Include="..\..\src\RynthCore.App\InjectionMode.cs" Link="App\InjectionMode.cs" />
<Compile Include="..\..\src\RynthCore.App\LaunchAccountProfile.cs" Link="App\LaunchAccountProfile.cs" />
<Compile Include="..\..\src\RynthCore.App\AccountPasswordProtection.cs" Link="App\AccountPasswordProtection.cs" />
<Compile Include="..\..\src\RynthCore.App\SavedPasswordReveal.cs" Link="App\SavedPasswordReveal.cs" />
<Compile Include="..\..\src\RynthCore.App\LaunchServerProfile.cs" Link="App\LaunchServerProfile.cs" />
<Compile Include="..\..\src\RynthCore.App\KnownServerCatalog.cs" Link="App\KnownServerCatalog.cs" />
<Compile Include="..\..\src\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="App\AcLaunchArgumentBuilder.cs" />
<Compile Include="..\..\src\RynthCore.App\AcClientCommandLine.cs" Link="App\AcClientCommandLine.cs" />
<Compile Include="..\..\src\RynthCore.App\FirstLoginRules.cs" Link="App\FirstLoginRules.cs" />
<Compile Include="..\..\src\RynthCore.App\AccountServerRules.cs" Link="App\AccountServerRules.cs" />
<Compile Include="..\..\src\RynthCore.App\UserPrefsSwapRecovery.cs" Link="App\UserPrefsSwapRecovery.cs" />
<Compile Include="..\..\src\RynthCore.App\CrashDumpWriterRule.cs" Link="App\CrashDumpWriterRule.cs" />
</ItemGroup>

View file

@ -373,6 +373,48 @@ internal static class Program
Check(FirstLoginRules.Problem("", "pw", "pw", false, AcEmulatorKind.Ace) != null, "a name is required");
});
// Deleting a server profile re-pointed its accounts at the first remaining server, so the
// next launch sent one server's password to another (audit 2026-10-21 F2).
Scenario("server profiles: an account logs on only to its own server", root, () =>
{
var conquest = new LaunchServerProfile { Id = "conq", Name = "Conquest", Host = "conquest.example", Port = 9000 };
var ilt = new LaunchServerProfile { Id = "ilt", Name = "Infinite Leaftide", Host = "ilt.example", Port = 9000 };
var servers = new List<LaunchServerProfile> { conquest, ilt };
var onConquest = new LaunchAccountProfile { Id = "a", AccountName = "SK", ServerId = "conq" };
var onConquest2 = new LaunchAccountProfile { Id = "b", AccountName = "Buffi", Alias = "Buffer", ServerId = "CONQ" };
var onIlt = new LaunchAccountProfile { Id = "c", AccountName = "SK", ServerId = "ilt" };
var never = new LaunchAccountProfile { Id = "d", AccountName = "New" };
var dangling = new LaunchAccountProfile { Id = "e", AccountName = "Old", ServerId = "deleted-elsewhere" };
var accounts = new List<LaunchAccountProfile> { onConquest, onConquest2, onIlt, never, dangling };
Check(AccountServerRules.ServerFor(onConquest, servers) == conquest, "its own server");
Check(AccountServerRules.ServerFor(onConquest2, servers) == conquest, "the id is matched ignoring case");
Check(AccountServerRules.ServerFor(onIlt, servers) == ilt, "the same name on another server: that server");
Check(AccountServerRules.ServerFor(never, servers) == null, "no server set: none (not the first or the selected one)");
Check(AccountServerRules.ServerFor(dangling, servers) == null, "a server that is gone: none, never another server");
Check(AccountServerRules.ServerFor(dangling, new List<LaunchServerProfile> { ilt }) == null, "not even when only one server is left");
Check(AccountServerRules.ServerFor(onConquest, new List<LaunchServerProfile>()) == null, "no servers at all: none");
Check(AccountServerRules.AccountsOn(conquest, accounts).Select(a => a.Id).SequenceEqual(new[] { "a", "b" }), "Conquest's accounts: a and b");
string? blocker = AccountServerRules.DeleteBlocker(conquest, accounts);
Check(blocker != null && blocker.Contains("2 account(s)") && blocker.Contains("SK") && blocker.Contains("Buffer (Buffi)"),
"deleting a server with accounts is refused, naming them: " + blocker);
Check(blocker != null && !blocker.Contains("Old") && !blocker.Contains("New"), "only that server's accounts are named");
var unused = new LaunchServerProfile { Id = "spare", Name = "Spare", Host = "h", Port = 1 };
Check(AccountServerRules.DeleteBlocker(unused, accounts) == null, "a server no account uses can be deleted");
// The refusal leaves every account as it was (nothing re-pointed).
Check(accounts.Select(a => a.ServerId).SequenceEqual(new[] { "conq", "CONQ", "ilt", "", "deleted-elsewhere" }), "no account was changed");
var many = Enumerable.Range(1, 12).Select(i => new LaunchAccountProfile { AccountName = "Acc" + i, ServerId = "ilt" }).ToList();
string? manyBlocker = AccountServerRules.DeleteBlocker(ilt, many);
Check(manyBlocker != null && manyBlocker.Contains("12 account(s)") && manyBlocker.Contains("4 more") && !manyBlocker.Contains("Acc9"),
"a long list names 8 and counts the rest");
Check(AccountServerRules.NoServerMessage(dangling, anyServerProfiles: true).Contains("pick the server"), "no-server launch message says what to do");
Check(AccountServerRules.NoServerMessage(never, anyServerProfiles: false).Contains("Add a server profile"), "with no servers at all: add one");
});
// A saved UserPreferences.ini whose display mode the PC can't use made every launch
// fail with "Could not initialize Direct3D"; a quick exit must undo that swap.
Scenario("prefs swap: did the swap change the live file", root, () =>
@ -464,6 +506,8 @@ internal static class Program
}
ClientCommandLineChecks();
ExtraLaunchArgumentChecks();
PasswordEyeChecks();
Console.WriteLine(_failed == 0
? $"PASS: {_checks} checks"
@ -492,6 +536,10 @@ internal static class Program
// exactly as ThwargLauncher writes it.
string special = "Aa1!@#$%^&*()_+-=[]{}|\\:;'<>,.?/~`" + "Zz9\\\\end\\";
Check(AcClientCommandLine.Token(special) == special, "no space, no quote: the password as it is");
// The saved form (DPAPI over UTF-8, base64) gives every one of these characters back.
foreach (string pw in new[] { special, "Aa1!@#$%^&*(_+-=[]{}|\\:;'<>,.?/~`*Zz9" + new string('(', 3) + "**", "€£§°´¨ü x" })
Check(AccountPasswordProtection.TryUnprotect(AccountPasswordProtection.Protect(pw), out string back) && back == pw,
"saved and read back unchanged: " + pw.Length + " characters");
Check(ReadsBack(special, special), "and the client reads it back");
// Quote marks: the client drops them whatever the launcher does; with them left out the rest
@ -531,6 +579,117 @@ internal static class Program
Check(ours > 3500 && thwargSame > 100, $"random passwords: {ours} read back, {thwargSame} the same as ThwargLauncher's");
}
// ── Extra Launch Arguments ───────────────────────────────────────────────
// Labelled "appended", the box replaced the whole command line (account, password and host);
// it now appends to every launch, so it may not carry the login switches (audit 2026-10-21 F10).
private static void ExtraLaunchArgumentChecks()
{
Console.WriteLine("-- extra launch arguments");
var account = new LaunchAccountProfile { AccountName = "SK" };
account.SetPassword("pw x");
string built = new AcLaunchArgumentBuilder().BuildArguments(Server(AcEmulatorKind.Ace), account);
Check(AcLaunchArgumentBuilder.ExtraArgumentsProblem(null, out string none) == null && none == "", "none: fine, nothing added");
Check(AcLaunchArgumentBuilder.ExtraArgumentsProblem(" \r\n\t ", out string blank) == null && blank == "", "only blanks: fine, nothing added");
Check(AcLaunchArgumentBuilder.WithExtraArguments(built, "") == built, "nothing added: the account's line unchanged");
Check(AcLaunchArgumentBuilder.ExtraArgumentsProblem("-nointro\r\n-w \"My Window\"", out string extra) == null && extra == "-nointro -w \"My Window\"",
"line breaks become spaces: " + extra);
string line = AcLaunchArgumentBuilder.WithExtraArguments(built, extra);
List<string>? args = AcClientCommandLine.Split(line);
Check(line.StartsWith(built + " ", StringComparison.Ordinal), "appended after the account's own arguments, not instead of them");
Check(args != null && ArgAfter(args, "-a") == "SK" && ArgAfter(args, "-v") == "pw x" && ArgAfter(args, "-h") == "127.0.0.1:9000",
"the client still reads this account, its password and its server");
Check(args != null && args.Contains("-nointro") && ArgAfter(args, "-w") == "My Window", "and the extra arguments");
// An old whole-line override saved in the box: refused rather than appended to every account.
foreach (string sw in new[] { "-a", "-v", "-h", "-p", "-rodat", "-A", "-RODAT" })
{
string? problem = AcLaunchArgumentBuilder.ExtraArgumentsProblem($"-nointro {sw} other", out string n);
Check(problem != null && n == "" && problem.Contains(sw, StringComparison.OrdinalIgnoreCase), $"{sw} refused: {problem}");
}
Check(AcLaunchArgumentBuilder.ExtraArgumentsProblem("-a acct -v secret -h other.example:9000", out _) is string old && !old.Contains("secret"),
"a saved old override is refused, and the message doesn't repeat its password");
Check(AcLaunchArgumentBuilder.ExtraArgumentsProblem("-host -apple \"-a b\"", out string lookalike) == null && lookalike.Length > 0,
"switches that only start like a login switch, or a quoted value with one inside, are fine");
Check(AcLaunchArgumentBuilder.ExtraArgumentsProblem("-w \"open", out _)?.Contains("quote") == true,
"a quote left open is refused (the client would drop the whole line, login included)");
}
// ── The "show password" eye ──────────────────────────────────────────────
// Player request (2026-10-21): the account editor's box starts empty ("leave blank to keep the
// saved password") and the saved password was never shown. SavedPasswordReveal: the eye fills an
// empty box with the saved password and empties it again if unchanged; saving it unchanged keeps
// the saved one as it is.
private static void PasswordEyeChecks()
{
Console.WriteLine("-- the show-password eye");
const string Saved = "s3cret pw ü\\\"";
var account = new LaunchAccountProfile { AccountName = "A" };
account.SetPassword(Saved);
string blob = account.PasswordProtected;
var eye = SavedPasswordReveal.For(account);
Check(eye.EyeOn("") == Saved && eye.FilledFromSaved, "eye on, box empty: the saved password, decrypted now");
Check(eye.PasswordToSave(Saved) == null, "saved while shown and unchanged: the saved password is kept");
Check(eye.EyeOff(Saved) == "" && !eye.FilledFromSaved, "eye off, unchanged: the box is empty again (blank = keep)");
Check(eye.PasswordToSave("") == null && eye.PasswordToSave(null) == null, "blank box: kept");
ApplySave(account, eye, "");
Check(account.PasswordProtected == blob, "Save with a blank box: the blob is the same");
Check(eye.EyeOn("") == Saved, "fill, then Save while it's shown");
ApplySave(account, eye, Saved);
Check(account.PasswordProtected == blob, "Save with the shown password unchanged: nothing re-encrypted, the blob is the same");
Check(account.TryGetPasswordForLaunch(out string still, out _) && still == Saved, "and it still decrypts to the saved password");
Check(eye.EyeOn("") == Saved, "fill again");
Check(eye.EyeOff(Saved + "x") == Saved + "x" && eye.PasswordToSave(Saved + "x") == Saved + "x", "edited: stays in the box and is saved as the new password");
Check(eye.EyeOn("") == Saved && eye.EyeOff("") == "", "filled, then emptied by the player: stays empty");
Check(eye.EyeOn("") == Saved && eye.PasswordToSave("other") == "other", "filled, replaced while shown: the new one is saved");
eye.EyeOff("other");
Check(eye.EyeOn("typed") == "typed" && !eye.FilledFromSaved, "eye on with something typed: only reveals it");
Check(eye.EyeOff("typed") == "typed" && eye.PasswordToSave("typed") == "typed", "eye off: what was typed stays and is saved");
Check(eye.EyeOn(Saved) == Saved && eye.EyeOff(Saved) == Saved, "the saved password typed by hand is not taken for the eye's fill");
eye.EyeOn("");
eye.Reset();
Check(!eye.FilledFromSaved && eye.PasswordToSave(Saved) == Saved, "after Reset the fill is forgotten (at most re-encrypts the same text)");
ApplySave(account, eye, "new pw");
Check(account.TryGetPasswordForLaunch(out string got, out _) && got == "new pw", "a new password typed: saved");
var none = new LaunchAccountProfile { AccountName = "B" };
var noneEye = SavedPasswordReveal.For(none);
Check(noneEye.EyeOn("") == "" && !noneEye.FilledFromSaved, "no saved password: nothing to fill");
Check(noneEye.EyeOn("x") == "x", "no saved password: reveals what's typed");
// Settings copied from another Windows user or PC: the blob doesn't decrypt here.
var copied = new LaunchAccountProfile { AccountName = "C", PasswordProtected = Convert.ToBase64String(new byte[64]) };
var copiedEye = SavedPasswordReveal.For(copied);
Check(copiedEye.EyeOn("") == "" && !copiedEye.FilledFromSaved, "unreadable saved password: nothing filled in");
Check(copied.PasswordNeedsReentry, "and the profile says it needs re-entering");
Check(copiedEye.EyeOn("") == "" && copiedEye.EyeOn("retyped") == "retyped", "needs re-entering: the eye only reveals what's typed");
Check(copiedEye.PasswordToSave("retyped") == "retyped", "the retyped password is saved");
var legacy = new LaunchAccountProfile { AccountName = "D", LegacyPlainPassword = "legacy pw" };
Check(SavedPasswordReveal.For(legacy).EyeOn("") == "legacy pw", "a not-yet-migrated plain password is shown too");
// The eye keeps no copy of the password: no string field, only the "filled" flag.
Check(typeof(SavedPasswordReveal).GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)
.All(f => f.FieldType != typeof(string)), "SavedPasswordReveal holds no string");
Check(SavedPasswordReveal.ShowTip.Length < 20 && SavedPasswordReveal.HideTip.Length < 20, "short tooltips");
}
/// <summary>The account editor's Save for the password box (AccountProfileDialog.SaveAndClose).</summary>
private static void ApplySave(LaunchAccountProfile profile, SavedPasswordReveal eye, string? boxText)
{
if (eye.PasswordToSave(boxText) is string newPassword)
profile.SetPassword(newPassword);
eye.Reset();
}
/// <summary>The launcher's ACE line for <paramref name="password"/>, read back by acclient's rules.</summary>
private static bool ReadsBack(string password, string expected)
{

View file

@ -23,6 +23,7 @@
<Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.MapPacks.cs" Link="Linked\RynthUpdater.MapPacks.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.NavData.cs" Link="Linked\RynthUpdater.NavData.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.Available.cs" Link="Linked\RynthUpdater.Available.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.Rollback.cs" Link="Linked\RynthUpdater.Rollback.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\PluginNames.cs" Link="Linked\PluginNames.cs" />
<Compile Include="..\..\src\RynthCore.App\KnownServerCatalog.cs" Link="Linked\KnownServerCatalog.cs" />
<Compile Include="..\..\src\RynthCore.App\LaunchServerProfile.cs" Link="Linked\LaunchServerProfile.cs" />

View file

@ -8,7 +8,7 @@ using RynthCore.App.Avalonia;
// Tests for the launcher's Available plugins list, plugin installs (verified, with progress and
// Cancel), Remove, old feeds without descriptions, the download meter, and the front page's
// update card. A throwaway signing key signs feeds served by a local HttpListener.
internal static class Program
internal static partial class Program
{
private static int _fails, _asserts;
private static void Check(bool cond, string msg)
@ -61,6 +61,7 @@ internal static class Program
await Run(nameof(TooNewUpdateIsHeldBack), TooNewUpdateIsHeldBack);
await Run(nameof(TooNewCompanionWaits), TooNewCompanionWaits);
await Run(nameof(MinEngineApiAtOrBelowInstalledIsFine), MinEngineApiAtOrBelowInstalledIsFine);
await RollbackTests();
}
finally
{
@ -275,7 +276,7 @@ internal static class Program
var f = Setup("olddesc", descriptions: false, extraPlugins: new[] { "RynthSomethingElse" });
var c = await f.Upd.CheckAsync(new[] { f.RynthAiPath });
Check(c.Manifest.Plugins.All(p => p.Description == ""), "an old feed parses with no descriptions");
Check(c.Available.Single(a => a.Entry.Name == "RynthOracle").Description == "Quests, character, titles and leaderboards.",
Check(c.Available.Single(a => a.Entry.Name == "RynthOracle").Description == "Quests, character and titles.",
"a missing description falls back to the launcher's table");
Check(c.Available.Single(a => a.Entry.Name == "RynthNav").Description.Contains("540 MB"), "RynthNav's says how big its map is");
Check(c.Available.Single(a => a.Entry.Name == "RynthSomethingElse").Description == "", "a plugin the table doesn't know: no description, still listed");

View file

@ -0,0 +1,255 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using RynthCore.App.Avalonia;
// Roll back (RynthUpdater.Rollback.cs): the earlier releases offered, their own signed manifests, what a
// rollback downloads and puts in place, and the hold afterwards.
internal static partial class Program
{
private const int RbInstalled = 2026100501; // the feed's release (WriteFeed), installed here
private static async Task RollbackTests()
{
await Run(nameof(RollbackReleaseNumbers), RollbackReleaseNumbers);
await Run(nameof(RollbackOffersVerifiedEarlierReleases), RollbackOffersVerifiedEarlierReleases);
await Run(nameof(RollbackRefusesForeignOrForwardManifests), RollbackRefusesForeignOrForwardManifests);
await Run(nameof(RollbackPreparesThenApplies), RollbackPreparesThenApplies);
await Run(nameof(RollbackFailedDownloadChangesNothing), RollbackFailedDownloadChangesNothing);
await Run(nameof(RollbackHoldsUntilANewerRelease), RollbackHoldsUntilANewerRelease);
await Run(nameof(RollbackHoldEndsWhenUpdatedByHand), RollbackHoldEndsWhenUpdatedByHand);
await Run(nameof(RollbackCardWhileHeld), RollbackCardWhileHeld);
}
private static Feed RollbackSetup(string tag)
{
Feed f = Setup(tag);
File.WriteAllText(Path.Combine(f.Dir, "app", "release.txt"), RbInstalled.ToString());
f.Upd.UpdatesDir = Path.Combine(f.Dir, "updates");
f.Upd.RollbackFloor = 2026100101;
return f;
}
private static string VersionOf(int release) =>
$"{release / 1000000}.{release / 10000 % 100}.{release / 100 % 100}.{release % 100}";
private static byte[] Envelope(Dictionary<string, object?> manifest, ECDsa? key = null)
{
key ??= Key;
byte[] payload = JsonSerializer.SerializeToUtf8Bytes(manifest);
byte[] sig = key.SignData(payload, HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
return Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new
{
payload = Convert.ToBase64String(payload),
signatures = new[] { new { key = RynthUpdater.KeyId(key.ExportSubjectPublicKeyInfo()), sig = Convert.ToBase64String(sig) } },
}));
}
/// <summary>
/// An earlier release's own signed manifest at releases/&lt;release&gt;/update.json, its installer and its
/// plugins (RynthAi, RynthChat, RynthNav as "v1"). <paramref name="claim"/>: the release written inside
/// (another one than its folder, for the test that refuses it).
/// </summary>
private static DateTime ServeRelease(string tag, int release, int? claim = null, ECDsa? key = null, string? tamper = null)
{
int inside = claim ?? release;
DateTime published = new(release / 1000000, release / 10000 % 100, release / 100 % 100, 12, 0, 0, DateTimeKind.Utc);
var plugins = new List<Dictionary<string, object>>();
foreach (string name in new[] { "RynthAi", "RynthChat", "RynthNav" })
{
byte[] body = Body(name, "v1-" + release);
string rel = $"{tag}/releases/{release}/plugins/{FileOf(name)}";
lock (Served) Served[rel] = name == tamper ? Encoding.UTF8.GetBytes("tampered " + name) : body;
plugins.Add(new Dictionary<string, object>
{
["name"] = name, ["file"] = FileOf(name), ["url"] = _base + rel, ["size"] = body.Length, ["sha256"] = Sha(body),
});
}
byte[] setup = Encoding.UTF8.GetBytes("installer " + release);
lock (Served) Served[$"{tag}/releases/{release}/RynthCore-Setup.exe"] = setup;
var manifest = new Dictionary<string, object?>
{
["schema"] = 1, ["release"] = inside, ["version"] = VersionOf(inside),
["published"] = published.ToString("yyyy-MM-ddTHH:mm:ssZ"), ["notes"] = "Notes " + inside,
["changes"] = new[] { $"Change one of {inside}.", "Change two.", "Change three.", "Change four." },
["core"] = new Dictionary<string, object>
{
["release"] = inside, ["version"] = VersionOf(inside),
["url"] = _base + $"{tag}/releases/{release}/RynthCore-Setup.exe", ["size"] = setup.Length, ["sha256"] = Sha(setup),
},
["plugins"] = plugins,
};
lock (Served) Served[$"{tag}/releases/{release}/update.json"] = Envelope(manifest, key);
return published;
}
private static void ServeReleasesList(string tag, params int[] releases)
{
var list = releases.Select(r => new { version = VersionOf(r), date = "x", changes = new[] { "c" } }).ToArray();
lock (Served) Served[$"{tag}/releases.json"] = JsonSerializer.SerializeToUtf8Bytes(new { releases = list });
}
/// <summary>The current feed, as a release of its own (WriteFeed's is fixed at <see cref="RbInstalled"/>).</summary>
private static void ServeFeed(string tag, int release)
{
var plugins = new List<Dictionary<string, object>>();
foreach (string name in FeedPlugins)
{
byte[] body = Body(name, "v3-" + release);
string rel = $"{tag}/releases/{release}/plugins/{FileOf(name)}";
lock (Served) Served[rel] = body;
plugins.Add(new Dictionary<string, object> { ["name"] = name, ["file"] = FileOf(name), ["url"] = _base + rel, ["size"] = body.Length, ["sha256"] = Sha(body) });
}
var manifest = new Dictionary<string, object?>
{
["schema"] = 1, ["release"] = release, ["version"] = VersionOf(release),
["published"] = Published.AddDays(1).ToString("yyyy-MM-ddTHH:mm:ssZ"), ["notes"] = "n",
["core"] = new Dictionary<string, object> { ["release"] = release, ["version"] = VersionOf(release), ["url"] = _base + $"{tag}/x.exe", ["size"] = 1, ["sha256"] = "00" },
["plugins"] = plugins,
};
lock (Served) Served[$"{tag}/update.json"] = Envelope(manifest);
}
private static Task RollbackReleaseNumbers()
{
Check(RynthUpdater.ReleaseOf("2026.10.21.2") == 2026102102, "2026.10.21.2 → 2026102102");
Check(RynthUpdater.ReleaseOf("2026.9.26.3") == 2026092603, "a one-digit month and day");
Check(RynthUpdater.ReleaseOf("2026.10.5.20") == 2026100520, "a two-digit release of the day");
Check(RynthUpdater.ReleaseOf("0.0.0") == 0 && RynthUpdater.ReleaseOf("2026.13.1.1") == 0 && RynthUpdater.ReleaseOf(null) == 0,
"not a release: 0");
Check(RynthUpdater.FirstRollbackRelease == 2026101901, "the launcher goes back to 2026.10.19.1 at the oldest");
return Task.CompletedTask;
}
private static async Task RollbackOffersVerifiedEarlierReleases()
{
Feed f = RollbackSetup("rb-list");
ServeRelease("rb-list", 2026100402);
ServeRelease("rb-list", 2026100301, claim: 2026100302); // holds another release's manifest
ServeRelease("rb-list", 2026100201);
ServeRelease("rb-list", 2026100105, key: ECDsa.Create(ECCurve.NamedCurves.nistP256)); // signed by a stranger
ServeRelease("rb-list", 2026093001); // below the floor
// 2026.10.4.1 is listed but has no manifest kept.
ServeReleasesList("rb-list", RbInstalled, 2026100402, 2026100401, 2026100301, 2026100201, 2026100105, 2026093001);
var targets = await f.Upd.ListRollbackTargetsAsync();
Check(string.Join(",", targets.Select(t => t.Version)) == "2026.10.4.2,2026.10.2.1",
"offered: older, verified, its own release, not below the floor: " + string.Join(",", targets.Select(t => t.Version)));
Check(targets[0].Manifest.Changes.Count == 4 && targets[0].Manifest.Changes[0] == "Change one of 2026100402.",
"the changes shown come from the signed manifest");
Check((await f.Upd.ListRollbackTargetsAsync(max: 1)).Count == 1, "at most max");
}
private static async Task RollbackRefusesForeignOrForwardManifests()
{
Feed f = RollbackSetup("rb-refuse");
ServeRelease("rb-refuse", 2026100301, claim: 2026100302);
ServeRelease("rb-refuse", 2026100601); // newer than installed
ServeRelease("rb-refuse", 2026100401, key: ECDsa.Create(ECCurve.NamedCurves.nistP256));
async Task<bool> Refused(int release)
{
try { await f.Upd.LoadReleaseManifestAsync(release); return false; }
catch (InvalidDataException) { return true; }
}
Check(await Refused(2026100301), "another release's manifest under its name: refused");
Check(await Refused(2026100601), "a release newer than the installed one: refused (that's an update, not a rollback)");
Check(await Refused(2026100401), "a manifest no trusted key signed: refused");
bool missing = false;
try { await f.Upd.LoadReleaseManifestAsync(2026100101); }
catch (HttpRequestException) { missing = true; }
Check(missing, "a release with nothing kept: the download fails (and ListRollbackTargets skips it)");
}
private static async Task RollbackPreparesThenApplies()
{
Feed f = RollbackSetup("rb-apply");
DateTime published = ServeRelease("rb-apply", 2026100402);
ServeReleasesList("rb-apply", RbInstalled, 2026100402);
string chat = Place(f, "RynthChat");
string mine = Path.Combine(f.Suite, "RynthMine", "RynthCore.Plugin.RynthMine.dll"); // not shipped by the release
Directory.CreateDirectory(Path.GetDirectoryName(mine)!);
File.WriteAllText(mine, "my own build");
var paths = new List<string> { f.RynthAiPath, chat, mine };
var target = (await f.Upd.ListRollbackTargetsAsync()).Single();
var plan = await f.Upd.PrepareRollbackAsync(target, paths);
Check(plan.LeavingRelease == RbInstalled && plan.Manifest.Release == 2026100402, "the plan: from the installed release to the chosen one");
Check(string.Join(",", plan.Plugins.Select(p => p.Entry.Name).OrderBy(n => n)) == "RynthAi,RynthChat",
"only the player's plugins the release ships (not RynthNav, not their own): " + string.Join(",", plan.Plugins.Select(p => p.Entry.Name)));
Check(File.Exists(plan.InstallerPath) && File.ReadAllText(plan.InstallerPath) == "installer 2026100402", "the release's installer, verified");
Check(File.ReadAllBytes(f.RynthAiPath).SequenceEqual(Body("RynthAi")), "prepared, nothing installed yet");
List<string> done = f.Upd.ApplyRollbackPlugins(plan);
Check(done.Count == 2 && done.All(d => d.EndsWith("→ 2026.10.4.2")), "two plugins put back: " + string.Join("; ", done));
Check(File.ReadAllBytes(f.RynthAiPath).SequenceEqual(Body("RynthAi", "v1-2026100402"))
&& File.ReadAllBytes(chat).SequenceEqual(Body("RynthChat", "v1-2026100402")), "RynthAi and RynthChat are the release's builds");
Check(File.ReadAllBytes(f.RynthAiPath + ".previous").SequenceEqual(Body("RynthAi")), "the replaced file kept as .previous");
Check(File.GetLastWriteTimeUtc(f.RynthAiPath) == published, "stamped with the release's time (not taken for a local build)");
Check(File.ReadAllText(mine) == "my own build", "a plugin the release doesn't ship is left alone");
}
private static async Task RollbackFailedDownloadChangesNothing()
{
Feed f = RollbackSetup("rb-fail");
ServeRelease("rb-fail", 2026100402, tamper: "RynthChat");
ServeReleasesList("rb-fail", RbInstalled, 2026100402);
string chat = Place(f, "RynthChat");
var target = (await f.Upd.ListRollbackTargetsAsync()).Single();
bool threw = false;
try { await f.Upd.PrepareRollbackAsync(target, new[] { f.RynthAiPath, chat }); }
catch (InvalidDataException) { threw = true; }
Check(threw, "a download that doesn't match the signed hash stops the rollback");
Check(File.ReadAllBytes(f.RynthAiPath).SequenceEqual(Body("RynthAi")) && File.ReadAllBytes(chat).SequenceEqual(Body("RynthChat")),
"and nothing installed is touched");
Check(f.Upd.HeldThroughRelease == 0, "and no hold started");
}
private static async Task RollbackHoldsUntilANewerRelease()
{
Feed f = RollbackSetup("rb-hold");
// Rolled back from 2026.10.5.1 to 2026.10.4.2: the installer wrote the older release.txt.
f.Upd.StartHold(RbInstalled, turnedOffAutoUpdate: true);
File.WriteAllText(Path.Combine(f.Dir, "app", "release.txt"), "2026100402");
var c = await f.Upd.CheckAsync(new[] { f.RynthAiPath });
Check(c.Held && !c.HoldEnded && c.HoldThrough == RbInstalled, "the feed still offers the release left behind: held");
Check(c.CoreUpdateAvailable, "going forward stays possible (by hand)");
Check(f.Upd.HeldThroughRelease == RbInstalled && f.Upd.HoldTurnedOffAutoUpdate, "the replay guard's write keeps the hold");
ServeFeed("rb-hold", 2026100601);
var c2 = await f.Upd.CheckAsync(new[] { f.RynthAiPath });
Check(!c2.Held && c2.HoldEnded, "a newer release than the one left behind: the hold is over");
f.Upd.EndHold();
Check(f.Upd.HeldThroughRelease == 0 && !f.Upd.HoldTurnedOffAutoUpdate, "EndHold clears both");
var c3 = await f.Upd.CheckAsync(new[] { f.RynthAiPath });
Check(!c3.Held && !c3.HoldEnded && c3.HoldThrough == 0, "no hold: nothing to say");
}
private static async Task RollbackHoldEndsWhenUpdatedByHand()
{
Feed f = RollbackSetup("rb-hand");
f.Upd.StartHold(RbInstalled, turnedOffAutoUpdate: false);
// release.txt still says 2026100501: the player went forward again by hand (or the rollback didn't install).
var c = await f.Upd.CheckAsync(new[] { f.RynthAiPath });
Check(!c.Held && c.HoldEnded, "installed release at or past the hold: it's over");
}
private static Task RollbackCardWhileHeld()
{
var card = UpdateCardModel.Build(new UpdateCardInput
{
HasCheck = true, InstalledVersion = "2026.10.4.2", CoreUpdateAvailable = true, AvailableVersion = "2026.10.5.1",
HeldFromVersion = "2026.10.5.1", PendingPluginUpdates = new[] { "RynthAi" },
});
Check(card.Kind == UpdateCardKind.Held && card.Title == "RynthCore 2026.10.4.2 - rolled back", "held: " + card.Title);
Check(card.Detail.Contains("went back from 2026.10.5.1") && card.Detail.Contains("on hold"), "says why: " + card.Detail);
Check(card.ActionButton == UpdateCardModel.UpdateCoreButton, "Update RynthCore still goes forward");
var normal = UpdateCardModel.Build(new UpdateCardInput
{
HasCheck = true, InstalledVersion = "2026.10.4.2", CoreUpdateAvailable = true, AvailableVersion = "2026.10.5.1",
});
Check(normal.Kind == UpdateCardKind.CoreUpdate, "without a hold: the usual update card");
return Task.CompletedTask;
}
}

View file

@ -576,6 +576,16 @@ internal static class Program
Match match = Regex.Match(File.ReadAllText(targets), @"<RynthCoreSdkApiVersion>(\d+)</RynthCoreSdkApiVersion>");
Check(match.Success, "targets declare RynthCoreSdkApiVersion");
Eq(match.Success ? uint.Parse(match.Groups[1].Value) : 0u, PluginContractVersion.Current, "RynthCoreSdkApiVersion in RynthCore.PluginSdk.targets");
// Release (shared-SDK) builds raise a minimum below the managed-plugin API to the SDK's API
// (Publish-Update.ps1 checks for this rule before building).
string targetsText = File.ReadAllText(targets);
Match managed = Regex.Match(targetsText, @"<RynthCoreManagedPluginApi>(\d+)</RynthCoreManagedPluginApi>");
Check(managed.Success && uint.Parse(managed.Groups[1].Value) == 88u, "targets: managed plugins need API 88 (RynthCoreManagedPluginApi)");
Check(targetsText.Contains("'$(RynthPluginSharedSdk)' == 'true'") &&
targetsText.Contains("MinEngineApi=\"$(_RynthPluginEffectiveMinEngineApi)\"") &&
targetsText.Contains("<_Parameter1>$(_RynthPluginEffectiveMinEngineApi)</_Parameter1>"),
"targets: the manifest and the runtime attribute both use the derived minimum");
}
// v79: the SDK's copies of the training structs must be the engine's, byte for byte.

View file

@ -1,4 +1,5 @@
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.ImGuiBackend;
using RynthCore.Engine.UI.Sections;
namespace SectionsTests;
@ -30,6 +31,8 @@ internal static class Program
StateJson();
ManifestWindows();
WindowPlanChoices();
WindowTakeOver();
StackCheckAfterPluginDraw();
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
@ -488,17 +491,130 @@ internal static class Program
var offIlt = new[] { new ServerState("ilt", "Infinite Leaftide", false, false, ServerForce.Auto, true, "") };
var onIlt = new[] { new ServerState("ilt", "Infinite Leaftide", true, true, ServerForce.Auto, true, "") };
var refused = new List<string>();
var plan = WindowPlan.Build(new[] { net, other }, offIlt, t => t == "Inventory", refused);
var takeOvers = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var plan = WindowPlan.Build(new[] { net, other }, offIlt, t => t == "Inventory" ? TitleUse.EnginePanel : TitleUse.Free, refused, takeOvers);
Check(plan.ContainsKey("Characters") && plan["Characters"].Plugin == "RynthNet", "the first plugin keeps a title");
Check(!plan.ContainsKey("Bank"), "a server's window waits for its server");
Check(!plan.ContainsKey("Inventory"), "an engine panel's title is refused");
Check(!plan.ContainsKey("Inventory"), "an engine panel's title is refused without takeOver");
Check(refused.Count == 2 && refused.Exists(r => r.Contains("Other") && r.Contains("RynthNet")) && refused.Exists(r => r.Contains("engine panel")),
"both refusals say why: " + string.Join(" | ", refused));
var on = WindowPlan.Build(new[] { net }, onIlt, _ => false, new List<string>());
Check(takeOvers.Count == 0, "nothing taken over");
var on = WindowPlan.Build(new[] { net }, onIlt, _ => TitleUse.Free, new List<string>(), new HashSet<string>());
Check(on.ContainsKey("Bank"), "and shows while its server is active");
Check(WindowPlan.Signature(net.Windows[0]) != WindowPlan.Signature(net.Windows[1]), "signatures differ per window");
}
// A plugin window that declares "takeOver" draws in an engine panel's place (same title, same key).
private const string TakeOverManifest = """
{ "windows": [
{ "id": "inv", "title": "Inventory", "surface": "window:inv", "bar": true, "takeOver": true },
{ "id": "chat", "title": "Chat", "surface": "window:chat", "takeOver": true },
{ "id": "lua", "title": "Lua", "surface": "window:lua", "takeOver": "yes" },
{ "id": "notes", "title": "Notes", "surface": "window:notes", "takeOver": true },
{ "id": "sort", "title": "RynthSort", "surface": "window:sort", "takeOver": true }
] }
""";
private static void WindowTakeOver()
{
Case("plugin windows: taking over an engine panel");
SectionManifest m = SectionManifestParser.Parse("RynthAi", TakeOverManifest, out string err);
Check(err.Length == 0 && m.Windows.Length == 5, "parses: " + err);
Check(m.Windows[0].TakeOver && m.Windows[1].TakeOver && m.Windows[3].TakeOver, "\"takeOver\": true read");
Check(!m.Windows[2].TakeOver, "not a boolean: off");
Check(!SectionManifestParser.Parse("RynthNet", WindowsManifest, out _).Windows[0].TakeOver, "absent: off (as before)");
Check(WindowPlan.Signature(m.Windows[0]) != WindowPlan.Signature(m.Windows[0] with { TakeOver = false }),
"takeOver is in the signature (a change re-registers)");
// Inventory, Chat and Lua are engine panels; RynthSort is a script window's key; Notes is free.
TitleUse Use(string t) => t switch
{
"Inventory" or "Chat" or "Lua" => TitleUse.EnginePanel,
"RynthSort" => TitleUse.Other,
_ => TitleUse.Free,
};
var refused = new List<string>();
var takeOvers = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var none = Array.Empty<ServerState>();
var plan = WindowPlan.Build(new[] { m }, none, Use, refused, takeOvers);
Check(plan.ContainsKey("Inventory") && plan.ContainsKey("Chat") && takeOvers.SetEquals(new[] { "Inventory", "Chat" }),
"declared takeovers of engine panels are hosted and marked: " + string.Join(", ", takeOvers));
Check(!plan.ContainsKey("Lua") && refused.Exists(r => r.Contains("'Lua'") && r.Contains("takeOver")),
"an engine panel's title without takeOver is still refused, and the line says how");
Check(plan.ContainsKey("Notes") && !takeOvers.Contains("Notes"), "takeOver on a free title: an ordinary window (the engine face is gone)");
Check(!plan.ContainsKey("RynthSort") && refused.Exists(r => r.Contains("RynthSort") && r.Contains("another panel")),
"never another panel's (a script window's) title, takeOver or not");
// Two plugins taking over the same panel: the first keeps it.
SectionManifest second = SectionManifestParser.Parse("RynthInventory",
"{\"windows\":[{\"id\":\"inv\",\"title\":\"inventory\",\"surface\":\"window:i\",\"takeOver\":true}]}", out _);
var refused2 = new List<string>();
var taken2 = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var plan2 = WindowPlan.Build(new[] { m, second }, none, Use, refused2, taken2);
Check(plan2["Inventory"].Plugin == "RynthAi" && refused2.Exists(r => r.Contains("RynthInventory") && r.Contains("RynthAi")),
"the first plugin to take a panel over keeps it (titles match without case)");
// The plugin goes: its manifest is gone, so the panel isn't in the plan (the engine's face comes back).
var after = WindowPlan.Build(Array.Empty<SectionManifest>(), none, Use, new List<string>(), taken2 = new HashSet<string>());
Check(after.Count == 0 && taken2.Count == 0, "no manifest: nothing hosted, nothing taken over");
}
// ImGui 1.91.6's ImGuiErrorRecoveryState, in field order: windows, IDs, tree nodes, colours,
// style vars, fonts, focus scopes, groups, item flags, popups, disabled. The base values are
// the ones a 32-bit probe of our cimgui.dll read inside a panel's body child (2026-10-21).
private static short[] Rec(params short[] f) => f;
private static void StackCheckAfterPluginDraw()
{
Case("plugin windows: ImGui stacks after a plugin's draw");
short[] given = Rec(3, 2, 0, 0, 0, 1, 3, 0, 1, 0, 0);
Check(ImGuiStackState.Fields == 11 && ImGuiStackState.RecordBytes == 22 && ImGuiStackState.Names.Length == 11,
"11 shorts, 22 bytes, a name each");
Check(ImGuiStackState.Compare(given, (short[])given.Clone()) == StackCheck.Balanced, "as found: balanced");
Check(ImGuiStackState.IdsAtBase(Rec(3, 1, 0, 0, 0, 0, 3, 0, 1, 0, 0)), "the body's start (one ID) is a base to recover to");
Check(!ImGuiStackState.IdsAtBase(given), "inside the face's PushID it isn't (the recovery would pop the caller's IDs)");
// Probe frame 1: two colours, a style var, two IDs, a font, a group, a disabled block, a tree node.
short[] leaked = Rec(3, 4, 1, 2, 1, 2, 3, 1, 1, 0, 1);
Check(ImGuiStackState.Compare(given, leaked) == StackCheck.LeftOpen, "pushes left open: ImGui unwinds them");
string what = ImGuiStackState.Describe(given, leaked);
Check(what == "IDs +2, tree nodes +1, colours +2, style vars +1, fonts +1, groups +1, disabled +1",
"the log says what was left: " + what);
Check(ImGuiStackState.CanRecover(given, leaked), "same window depth: recoverable");
// A child window left open (with a table inside): deeper, still recoverable.
short[] child = Rec(4, 1, 0, 1, 0, 1, 5, 0, 1, 0, 0);
Check(ImGuiStackState.Compare(given, child) == StackCheck.LeftOpen,
"a child window left open (its own IDs aren't compared with the body's)");
Check(ImGuiStackState.Describe(given, child) == "windows +1, colours +1, focus scopes +2",
"the log leaves out the other window's IDs: " + ImGuiStackState.Describe(given, child));
Check(ImGuiStackState.CanRecover(given, child), "a deeper window stack is recoverable");
short[] childPopped = Rec(4, 1, 0, -1, 0, 1, 5, 0, 1, 0, 0);
Check(ImGuiStackState.Compare(given, childPopped) == StackCheck.ClosedTooMuch, "a context stack below, even in a deeper window");
// The plugin ended the host's body child (one End too many) and left a colour and a font.
short[] ended = Rec(2, 1, 0, 1, 0, 2, 2, 0, 1, 0, 0);
Check(ImGuiStackState.Compare(given, ended) == StackCheck.ClosedTooMuch, "ended a window it didn't begin");
Check(!ImGuiStackState.CanRecover(given, ended), "ImGui's recovery can't go back up to the host's window");
Check(ImGuiStackState.GlobalPops(given, ended) == (1, 0, 1), "only the context's colours and fonts are popped by hand");
Check(ImGuiStackState.Describe(given, ended) == "windows -1, colours +1, fonts +1, focus scopes -1",
"negative changes are shown with their sign: " + ImGuiStackState.Describe(given, ended));
// Popped the host's colours: below the record, nothing to pop.
short[] overPopped = Rec(3, 2, 0, -2, 0, 1, 3, 0, 1, 0, 0);
Check(ImGuiStackState.Compare(given, overPopped) == StackCheck.ClosedTooMuch, "popped what it didn't push");
Check(ImGuiStackState.GlobalPops(given, overPopped) == (0, 0, 0), "never pops below the record");
Check(ImGuiStackState.Describe(given, given) == "nothing", "no change: nothing");
// The first-use size check (the record filled with 0xCC, then written by ImGui).
byte[] rec = Enumerable.Repeat((byte)0xCC, 64).ToArray();
for (int i = 0; i < 22; i++) rec[i] = (byte)(i % 2 == 0 ? 1 : 0);
Check(ImGuiStackState.WroteExpectedSize(rec, 0xCC), "22 bytes written: the layout expected");
rec[30] = 0;
Check(!ImGuiStackState.WroteExpectedSize(rec, 0xCC), "more written: a different layout, the guard stays off");
Check(!ImGuiStackState.WroteExpectedSize(Enumerable.Repeat((byte)0xCC, 64).ToArray(), 0xCC), "nothing written: off");
}
// ── Harness ────────────────────────────────────────────────────────
private static void Case(string name)

View file

@ -3,7 +3,9 @@
<!--
Offline checks for the Mini Remote's sections (src\RynthCore.Engine\UI\Sections, the pure
files compiled in): the per-character server overrides file, the plugin manifest parser and
its limits, and the section catalog (core sections, server-scoped contributions, ordering).
its limits, and the section catalog (core sections, server-scoped contributions, ordering);
plugin windows: which are hosted, which take over an engine panel, and the stack check after
a plugin's draw (ImGui\ImGuiStackState.cs).
IltDetect.cs (with AelrynthWire.cs, which it shares a parser with) supplies the matching a
plugin-declared server is detected with. Nothing native: no AC, no engine state.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
@ -24,6 +26,8 @@
<Compile Include="..\..\src\RynthCore.Engine\UI\Sections\SectionManifest.cs" Link="Engine\SectionManifest.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Sections\SectionCatalog.cs" Link="Engine\SectionCatalog.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Sections\WindowPlan.cs" Link="Engine\WindowPlan.cs" />
<!-- What a plugin window's draw left on ImGui's stacks (the record ImGuiStackGuard takes). -->
<Compile Include="..\..\src\RynthCore.Engine\ImGui\ImGuiStackState.cs" Link="Engine\ImGuiStackState.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\IltDetect.cs" Link="Engine\IltDetect.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AelrynthWire.cs" Link="Engine\AelrynthWire.cs" />
<!-- The Diagnostics server picker's plan and the plugin API v86 server-state JSON. -->