merge: bring feat/full-installer into SK-local

Integrates the aelrynth snapshot port (main), the full installer, the
tmds.dbus advisory fix and all launcher/engine work into SK-local.

Conflict resolutions:
- Logging: keep SK-local's level-based logging (EngineLogLevel, ShouldLog,
  engine.json LoggingLevel) and adopt full-installer's tagged WRN/ERR,
  LastIssue and per-PID logs; the Desktop rolling log is superseded.
- Launcher: keep the inject-all-sessions toggle and Logging level combo
  alongside the new stagger/crash-relaunch/stuck-client options; the
  LoggingLevel is now written through EngineJsonStore.SetString.
- PluginManager: keep SK-local's basename/canonical-path de-duplication,
  drop the default-directory scan (opt-in via PluginPaths).
- Injector, installer, CI workflow, BUILD.md: take full-installer.
- Solution: add DesktopLog + Loader, drop the stale Plugins/RynthAi stub.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
BlankenshipG 2026-10-04 16:16:24 -04:00
commit 36ffa94252
256 changed files with 62130 additions and 3382 deletions

View file

@ -23,6 +23,45 @@ internal sealed class AcClientLaunchSettingsService
UpdateIntroVideoState(gameDirectory, skipIntroVideos, log);
}
/// <summary>
/// Copies a per-account UserPreferences.ini stash over the live file in
/// My Documents\Asheron's Call, then re-applies the ComputeUniquePort flag.
/// If <paramref name="stashPath"/> is empty or missing, no swap is performed
/// and the live file is left as-is.
/// </summary>
public bool SwapUserPreferences(string? stashPath, bool allowMultipleClients, Action<string>? log = null)
{
if (string.IsNullOrWhiteSpace(stashPath))
return false;
if (!File.Exists(stashPath))
{
log?.Invoke($"User prefs swap skipped: stash file not found at {stashPath}.");
return false;
}
string documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string prefsDirectory = Path.Combine(documentsDirectory, "Asheron's Call");
string prefsPath = Path.Combine(prefsDirectory, UserPreferencesFileName);
try
{
Directory.CreateDirectory(prefsDirectory);
File.Copy(stashPath, prefsPath, overwrite: true);
}
catch (Exception ex)
{
log?.Invoke($"User prefs swap failed copying {stashPath}: {ex.Message}");
return false;
}
// Re-apply the ComputeUniquePort flag — the stash may have it set to
// the wrong value (e.g. user set it up before enabling multi-client).
UpdateUserPreferences(allowMultipleClients, log: null);
log?.Invoke($"User prefs swap: applied stash {Path.GetFileName(stashPath)}.");
return true;
}
private static void UpdateUserPreferences(bool allowMultipleClients, Action<string>? log)
{
string documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

View file

@ -19,8 +19,52 @@ internal sealed class AppSettings
public bool WatchForAcStart { get; set; } = true;
public bool InjectAllRunningClients { get; set; } = true;
public string LoggingLevel { get; set; } = "Info";
public int LaunchStaggerMs { get; set; } = 250;
public int CrashRelaunchLimitInWindow { get; set; } = 3;
public int CrashRelaunchWindowMinutes { get; set; } = 5;
public bool OverrideWindowTitle { get; set; } = true;
/// When true (default), the launcher installs RynthSuite plugin updates as soon as a
/// check finds them. Safe mid-session: running clients keep the version they started
/// with; the new one loads on the next AC start. Core updates always ask first.
public bool AutoUpdatePlugins { get; set; } = true;
/// When true, the launcher kills any RynthCore-mode acclient.exe it
/// launched that hasn't reached IsLoggedIn within
/// <see cref="StuckClientTimeoutSeconds"/>. Catches stuck char-select,
/// patcher hangs, and "you have been disconnected" failure screens at
/// the front of the launch flow. Off by default — destructive.
/// Decal-mode clients are skipped (no engine = no IsLoggedIn signal).
public bool KillStuckClients { get; set; }
public int StuckClientTimeoutSeconds { get; set; } = 60;
/// When true (default), the launcher kills+relaunches a RynthCore-mode
/// client whose per-PID heartbeat shows the WEDGE signature: login=1 and
/// fps=0 sustained for <see cref="WedgeRestartSeconds"/> while the engine
/// heartbeat keeps flowing (AC main thread dead, process alive — the AV
/// class). Containment for the residual corruption AVs: an overnight soak
/// loses ~2 minutes to a wedge instead of the rest of the night.
/// Minimized windows are exempt (some drivers stop presenting). Relaunch
/// rides the existing crash-relaunch machinery (counts toward the
/// circuit breaker) and needs AutoLaunch for the relaunch half.
public bool AutoRestartWedgedClients { get; set; } = true;
public int WedgeRestartSeconds { get; set; } = 90;
public List<string> EnabledPluginIds { get; set; } = [];
public List<string> PluginDllPaths { get; set; } = [];
/// User-added plugin DLL paths whose checkboxes are currently unchecked.
/// The path stays in <see cref="PluginDllPaths"/> (so the row remains in
/// the UI), but is filtered out when syncing PluginPaths into engine.json.
/// Case-insensitive set semantics; comparisons must use OrdinalIgnoreCase.
public List<string> DisabledPluginDllPaths { get; set; } = [];
/// <summary>
/// Last installer plugin hand-off (registry <c>Software\Rynth\PendingPluginRegistration</c>)
/// the launcher applied. Lets an all-users install, whose HKLM value the launcher cannot
/// delete, register its plugins once without re-adding a plugin the user later removed.
/// </summary>
public string? AppliedInstallerPluginRegistration { get; set; }
public List<LaunchServerProfile> ServerProfiles { get; set; } = [];
public List<LaunchAccountProfile> AccountProfiles { get; set; } = [];

View file

@ -20,16 +20,52 @@ internal static class AppSettingsStore
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
private static string SettingsPath => Path.Combine(SettingsDirectory, "appsettings.json");
private static string BackupPath => SettingsPath + ".bak";
/// <summary>
/// Set when the last Load() hit a corrupt/unreadable file (quarantined it,
/// possibly recovered from the .bak). Null when the load was clean. The
/// launcher surfaces this after startup — this store is shared source and
/// must not depend on launcher-only logging.
/// </summary>
public static string? LastLoadDiagnostic { get; private set; }
public static AppSettings Load()
{
LastLoadDiagnostic = null;
if (!File.Exists(SettingsPath))
return new AppSettings();
if (TryLoadFrom(SettingsPath, out AppSettings? settings))
return settings!;
// The primary file is corrupt (truncated write, disk issue). This file
// holds every server/account profile — NEVER silently reset to defaults.
// Quarantine the bad file for post-mortem, then try the backup the
// atomic Save() keeps.
string quarantine = SettingsPath + ".corrupt-" + DateTime.Now.ToString("yyyyMMdd-HHmmss");
try { File.Move(SettingsPath, quarantine); }
catch { quarantine = "(quarantine move failed)"; }
if (File.Exists(BackupPath) && TryLoadFrom(BackupPath, out AppSettings? backup))
{
try { File.Copy(BackupPath, SettingsPath, overwrite: true); } catch { }
LastLoadDiagnostic = $"appsettings.json was corrupt — recovered from .bak (bad file kept at {quarantine}).";
return backup!;
}
LastLoadDiagnostic = $"appsettings.json was corrupt and no usable .bak exists — starting with defaults (bad file kept at {quarantine}).";
return new AppSettings();
}
private static bool TryLoadFrom(string path, out AppSettings? settings)
{
settings = null;
try
{
if (!File.Exists(SettingsPath))
return new AppSettings();
string json = File.ReadAllText(SettingsPath);
AppSettings settings = JsonSerializer.Deserialize<AppSettings>(json, JsonOptions) ?? new AppSettings();
string json = File.ReadAllText(path);
AppSettings loaded = JsonSerializer.Deserialize<AppSettings>(json, JsonOptions) ?? new AppSettings();
using JsonDocument document = JsonDocument.Parse(json);
JsonElement root = document.RootElement;
@ -37,20 +73,30 @@ internal static class AppSettingsStore
root.TryGetProperty("AutoRelaunch", out JsonElement legacyAutoRelaunch) &&
legacyAutoRelaunch.ValueKind is JsonValueKind.True or JsonValueKind.False)
{
settings.AutoLaunch = legacyAutoRelaunch.GetBoolean();
loaded.AutoLaunch = legacyAutoRelaunch.GetBoolean();
}
return settings;
settings = loaded;
return true;
}
catch
{
return new AppSettings();
return false;
}
}
public static void Save(AppSettings settings)
{
// Atomic write: serialize to a temp file, then swap it in. A crash or
// power cut mid-write can no longer truncate the live file (which holds
// every server/account profile and is rewritten constantly); the swap
// also maintains a .bak Load() can recover from.
Directory.CreateDirectory(SettingsDirectory);
File.WriteAllText(SettingsPath, JsonSerializer.Serialize(settings, JsonOptions));
string tmp = SettingsPath + ".tmp";
File.WriteAllText(tmp, JsonSerializer.Serialize(settings, JsonOptions));
if (File.Exists(SettingsPath))
File.Replace(tmp, SettingsPath, BackupPath);
else
File.Move(tmp, SettingsPath);
}
}

View file

@ -0,0 +1,46 @@
using System.Diagnostics;
using System.IO;
namespace RynthCore.App;
/// <summary>
/// Human-readable build versions, for the launcher and the in-game UI.
///
/// Release builds are stamped with the release number (Build-Installer.ps1 and
/// Publish-Update.ps1 pass -p:Version=yyyy.m.d.n), and the .NET SDK appends the git
/// commit to the product version: "2026.9.26.3+8ca322f…". Anything built without a
/// version (Deploy-RynthCore.ps1, an IDE build) reads "1.0.0+8ca322f…" — a dev build.
/// NativeAOT DLLs carry the same Windows version resource, so plugins need no code.
/// </summary>
internal static class BuildVersion
{
/// <summary>"2026.9.26.3 (8ca322f)" for a release, "dev (8ca322f)" otherwise.</summary>
public static string Format(string? productVersion)
{
if (string.IsNullOrWhiteSpace(productVersion)) return "unknown";
string version = productVersion.Trim();
string commit = "";
int plus = version.IndexOf('+');
if (plus >= 0)
{
commit = version[(plus + 1)..];
version = version[..plus];
}
if (commit.Length > 7) commit = commit[..7];
if (version is "1.0.0" or "1.0.0.0") version = "dev";
return commit.Length > 0 ? $"{version} ({commit})" : version;
}
/// <summary>A DLL's or EXE's version resource, formatted; "" if it has none or can't be read.</summary>
public static string OfFile(string path)
{
try
{
return File.Exists(path) ? Format(FileVersionInfo.GetVersionInfo(path).ProductVersion) : "";
}
catch
{
return "";
}
}
}

View file

@ -10,6 +10,28 @@ namespace RynthCore.App;
internal static class CharacterCacheStore
{
/// Strict reader — only returns characters from the server-scoped file
/// for this (account, server) pair. Will NOT fall through to the
/// account-only file. Use this when correctness across accounts/servers
/// matters more than tolerance for missing data (e.g. UI dropdowns where
/// stale legacy files would leak the wrong account's characters).
public static List<string> ReadStrict(string accountName, string serverName)
{
try
{
if (string.IsNullOrWhiteSpace(accountName) || string.IsNullOrWhiteSpace(serverName))
return [];
string safeAccount = SanitizeFileName(accountName);
string safeServer = SanitizeFileName(serverName);
return ReadCharacterFile(GetServerScopedPath(safeServer, safeAccount));
}
catch
{
return [];
}
}
public static List<string> Read(string accountName, string serverName = "")
{
try
@ -63,12 +85,17 @@ internal static class CharacterCacheStore
return;
List<string> characters = Read(accountName, serverName);
if (!characters.Contains(characterName, StringComparer.OrdinalIgnoreCase))
if (!characters.Any(existing => IsSameCharacter(existing, characterName)))
characters.Add(characterName);
Write(accountName, serverName, characters);
}
// The client shows admin names with a leading '+' ('+Buffi'); a launch-context
// name may lack it. Treat both as one character so the list holds no duplicate.
private static bool IsSameCharacter(string a, string b) =>
string.Equals(a.Trim().TrimStart('+'), b.Trim().TrimStart('+'), StringComparison.OrdinalIgnoreCase);
public static void DeleteForAccount(string accountName)
{
if (string.IsNullOrWhiteSpace(accountName))

View file

@ -0,0 +1,73 @@
using System;
using System.IO;
using Microsoft.Win32;
namespace RynthCore.App;
/// <summary>
/// Locates a local Decal install via the same registry probe ThwargLauncher
/// uses. Decal records its agent directory at HKLM\SOFTWARE\Decal\Agent (the
/// launcher is x86, so we transparently see the Wow6432Node redirect on 64-bit
/// Windows). Inject.dll lives directly in that directory and exports
/// DecalStartup, which is the entry point the suspended-launch injector calls.
/// </summary>
internal static class DecalLocator
{
private const string AgentSubKey = @"SOFTWARE\Decal\Agent";
private const string AgentPathValue = "AgentPath";
private const string PortalPathValue = "PortalPath";
private const string InjectDllName = "Inject.dll";
private const string AcClientName = "acclient.exe";
/// <summary>Returns the absolute path to Decal's Inject.dll, or null if
/// Decal is not registered or the file cannot be found beside its agent
/// directory.</summary>
public static string? TryGetInjectDllPath()
{
try
{
using RegistryKey? key = Registry.LocalMachine.OpenSubKey(AgentSubKey);
if (key == null)
return null;
string? agentPath = key.GetValue(AgentPathValue) as string;
if (string.IsNullOrWhiteSpace(agentPath))
return null;
string injectPath = Path.Combine(agentPath, InjectDllName);
return File.Exists(injectPath) ? injectPath : null;
}
catch
{
return null;
}
}
/// <summary>Returns the AC client install Decal expects, derived from its
/// PortalPath registry value (e.g. C:\Turbine\Asheron's Call). Used when an
/// account is set to Decal mode and the launcher's global AcClientPath
/// points elsewhere (e.g. the RynthCore-private duplicate). Returns null if
/// not registered or the file is missing.</summary>
public static string? TryGetDecalAcClientPath()
{
try
{
using RegistryKey? key = Registry.LocalMachine.OpenSubKey(AgentSubKey);
if (key == null)
return null;
string? portalPath = key.GetValue(PortalPathValue) as string;
if (string.IsNullOrWhiteSpace(portalPath))
return null;
string acPath = Path.Combine(portalPath, AcClientName);
return File.Exists(acPath) ? acPath : null;
}
catch
{
return null;
}
}
public static bool IsInstalled() => TryGetInjectDllPath() != null;
}

View file

@ -0,0 +1,17 @@
namespace RynthCore.App;
/// <summary>
/// Per-account choice of which modding stack to inject when launching the AC
/// client. Selected from the launcher's per-row Injection Method dropdown.
/// </summary>
internal enum InjectionMode
{
/// <summary>RynthCore.Loader.dll → RynthCore.Engine.dll injected via the
/// in-process injector. The native RynthCore stack.</summary>
RynthCore = 0,
/// <summary>Decal's Inject.dll injected with its DecalStartup export. The
/// account runs against Decal + UBService + VTank or whatever Decal plugins
/// the user has registered.</summary>
Decal = 1,
}

View file

@ -1,9 +1,15 @@
using System;
using System.Collections.Generic;
namespace RynthCore.App;
internal sealed class LaunchAccountProfile
{
/// Sentinel stored in CharacterName when the user has explicitly opted out of auto-login.
/// At launch time, ResolveTargetCharacterForLaunch translates this to an empty string so
/// the engine's CharacterCapture sees a blank TargetCharacter and skips auto-login entirely.
public const string NoneOption = "(None — no auto-login)";
public string Id { get; set; } = Guid.NewGuid().ToString("N");
public string AccountName { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
@ -11,11 +17,39 @@ internal sealed class LaunchAccountProfile
public string Alias { get; set; } = string.Empty;
public string ServerId { get; set; } = string.Empty;
// Saved AC client window placement, restored on next launch and updated
// when the user moves/resizes the window. Null until first save.
public int? WindowX { get; set; }
public int? WindowY { get; set; }
public int? WindowWidth { get; set; }
public int? WindowHeight { get; set; }
/// Optional path to a per-account stash of UserPreferences.ini. If set, the
/// launcher copies this file over My Documents\Asheron's Call\UserPreferences.ini
/// before launching this account. Empty/missing path = no swap, AC reads
/// whatever happens to be in place.
public string UserPrefsPath { get; set; } = string.Empty;
/// Which modding stack to inject when this account is launched. Defaults to
/// RynthCore. Decal mode launches AC with Decal's Inject.dll instead and
/// does not load the RynthCore engine into the process.
public InjectionMode InjectionMode { get; set; } = InjectionMode.RynthCore;
/// Per-character chat commands to dispatch after login completes. Key is
/// the character name (case-insensitive on lookup). Each list entry is one
/// command line — "/say hi", "/fellow create xyz", etc. — sent in order
/// with a small gap between commands. Empty/missing key = no commands.
public Dictionary<string, List<string>> OnLoginCommandsByCharacter { get; set; } = new(StringComparer.OrdinalIgnoreCase);
/// Milliseconds to wait after the engine observes login-complete before
/// dispatching the first OnLogin command. Matches Thwargle's default.
public int OnLoginWaitMs { get; set; } = 3000;
public string DisplayName
{
get
{
string launchLabel = !string.IsNullOrWhiteSpace(CharacterName)
string launchLabel = !string.IsNullOrWhiteSpace(CharacterName) && CharacterName != NoneOption
? CharacterName
: Alias;
@ -34,7 +68,15 @@ internal sealed class LaunchAccountProfile
Password = Password,
CharacterName = CharacterName,
Alias = Alias,
ServerId = ServerId
ServerId = ServerId,
WindowX = WindowX,
WindowY = WindowY,
WindowWidth = WindowWidth,
WindowHeight = WindowHeight,
UserPrefsPath = UserPrefsPath,
InjectionMode = InjectionMode,
OnLoginCommandsByCharacter = new Dictionary<string, List<string>>(OnLoginCommandsByCharacter, StringComparer.OrdinalIgnoreCase),
OnLoginWaitMs = OnLoginWaitMs,
};
}
@ -46,6 +88,14 @@ internal sealed class LaunchAccountProfile
CharacterName = source.CharacterName;
Alias = source.Alias;
ServerId = source.ServerId;
WindowX = source.WindowX;
WindowY = source.WindowY;
WindowWidth = source.WindowWidth;
WindowHeight = source.WindowHeight;
UserPrefsPath = source.UserPrefsPath;
InjectionMode = source.InjectionMode;
OnLoginCommandsByCharacter = new Dictionary<string, List<string>>(source.OnLoginCommandsByCharacter, StringComparer.OrdinalIgnoreCase);
OnLoginWaitMs = source.OnLoginWaitMs;
}
public override string ToString()

View file

@ -14,6 +14,16 @@ internal sealed class LaunchContextRecord
public string TargetCharacter { get; set; } = string.Empty;
public bool SkipLoginLogos { get; set; }
public DateTime CreatedAtUtc { get; set; } = DateTime.UtcNow;
/// Chat commands the engine should dispatch after login-complete fires
/// for this PID. Resolved by the launcher from
/// LaunchAccountProfile.OnLoginCommandsByCharacter at launch time. Null /
/// empty = nothing to dispatch.
public List<string>? OnLoginCommands { get; set; }
/// Milliseconds to wait after login-complete before sending the first
/// command. 0 (or omitted) = use the engine's default.
public int OnLoginWaitMs { get; set; }
}
internal static class LaunchContextStore
@ -25,7 +35,9 @@ internal static class LaunchContextStore
string accountName,
string serverName,
string targetCharacter,
bool skipLoginLogos)
bool skipLoginLogos,
List<string>? onLoginCommands = null,
int onLoginWaitMs = 0)
{
return new LaunchContextRecord
{
@ -33,7 +45,9 @@ internal static class LaunchContextStore
ServerName = serverName ?? string.Empty,
TargetCharacter = targetCharacter ?? string.Empty,
SkipLoginLogos = skipLoginLogos,
CreatedAtUtc = DateTime.UtcNow
CreatedAtUtc = DateTime.UtcNow,
OnLoginCommands = onLoginCommands,
OnLoginWaitMs = onLoginWaitMs
};
}
@ -56,7 +70,9 @@ internal static class LaunchContextStore
ServerName = context.ServerName,
TargetCharacter = context.TargetCharacter,
SkipLoginLogos = context.SkipLoginLogos,
CreatedAtUtc = DateTime.UtcNow
CreatedAtUtc = DateTime.UtcNow,
OnLoginCommands = context.OnLoginCommands,
OnLoginWaitMs = context.OnLoginWaitMs
};
File.WriteAllText(GetProcessPath(processId), JsonSerializer.Serialize(processContext));

View file

@ -0,0 +1,128 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace RynthCore.Install;
/// <summary>
/// Resolves where RynthCore and RynthSuite are installed. The installer lets the user pick
/// both folders and records them under <c>Software\Rynth</c> (HKCU for a per-user install,
/// HKLM for an all-users install), so nothing may assume <c>C:\Games\...</c> any more.
/// <para>
/// Resolution order per folder: environment override (<c>RYNTHCORE_DIR</c> /
/// <c>RYNTHSUITE_DIR</c>, for dev setups) → HKCU → HKLM (32-bit view, where the 32-bit
/// installer writes) → the historical default under <c>C:\Games</c>. Results are cached
/// for the life of the process.
/// </para>
/// Linked into every RynthCore project (Engine, Loader, Injector, launcher, StatusAgent);
/// RynthSuite keeps an identical copy in <c>Shared/RynthInstallPaths.cs</c> — change both together.
/// Registry access is a direct RegGetValueW P/Invoke so it works under NativeAOT and trimming
/// without pulling in Microsoft.Win32.Registry.
/// </summary>
internal static class RynthInstallPaths
{
/// <summary>Default RynthCore folder (pre-2026.10.4.2 installs always used this).</summary>
public const string DefaultCoreDir = @"C:\Games\RynthCore";
/// <summary>Default RynthSuite folder (pre-2026.10.4.2 installs always used this).</summary>
public const string DefaultSuiteDir = @"C:\Games\RynthSuite";
/// <summary>Registry key (under HKCU or HKLM) written by the installer.</summary>
public const string RegistryKey = @"Software\Rynth";
private static string? _coreDir;
private static string? _suiteDir;
/// <summary>RynthCore install folder (launcher, <c>Runtime\</c>, <c>Logs\</c>, <c>Tools\</c>).</summary>
public static string CoreDir => _coreDir ??= Resolve("RYNTHCORE_DIR", "CoreDir", DefaultCoreDir);
/// <summary>RynthSuite folder (plugins and their data, e.g. <c>RynthAi\</c>).</summary>
public static string SuiteDir => _suiteDir ??= Resolve("RYNTHSUITE_DIR", "SuiteDir", DefaultSuiteDir);
/// <summary>Unified RynthCore log folder (<c>&lt;CoreDir&gt;\Logs</c>).</summary>
public static string CoreLogsDir => Path.Combine(CoreDir, "Logs");
/// <summary>RynthAi plugin home and data root (<c>&lt;SuiteDir&gt;\RynthAi</c>).</summary>
public static string RynthAiDir => Path.Combine(SuiteDir, "RynthAi");
/// <summary>Reads a string value from <c>Software\Rynth</c> (HKCU first, then HKLM 32-bit view); null when absent.</summary>
public static string? ReadSetting(string valueName)
=> ReadRegistryString(HKEY_CURRENT_USER, valueName, 0)
?? ReadRegistryString(HKEY_LOCAL_MACHINE, valueName, RRF_SUBKEY_WOW6432KEY);
/// <summary>Deletes a value from HKCU <c>Software\Rynth</c> (used for one-shot installer hand-offs). Best effort.</summary>
public static void DeleteUserSetting(string valueName)
{
try { RegDeleteKeyValueW(HKEY_CURRENT_USER, RegistryKey, valueName); } catch { }
}
private static string Resolve(string envVar, string valueName, string fallback)
{
string? fromEnv = null;
try { fromEnv = Environment.GetEnvironmentVariable(envVar); } catch { }
foreach (string? candidate in new[] { fromEnv, ReadSetting(valueName) })
{
string? normalized = Normalize(candidate);
if (normalized != null) return normalized;
}
return fallback;
}
/// <summary>Accepts only absolute paths; trims whitespace, quotes and trailing separators.</summary>
private static string? Normalize(string? path)
{
if (string.IsNullOrWhiteSpace(path)) return null;
string p = path.Trim().Trim('"').TrimEnd('\\', '/');
if (p.Length == 2 && p[1] == ':') p += "\\"; // keep "D:" as the drive root "D:\"
try
{
if (!Path.IsPathFullyQualified(p)) return null;
string full = Path.GetFullPath(p);
return full.Length > 3 ? full.TrimEnd('\\') : full; // "D:\" stays a root
}
catch
{
return null;
}
}
// ── Win32 registry (advapi32) ───────────────────────────────────────────
private static readonly IntPtr HKEY_CURRENT_USER = new(unchecked((int)0x80000001));
private static readonly IntPtr HKEY_LOCAL_MACHINE = new(unchecked((int)0x80000002));
private const uint RRF_RT_REG_SZ = 0x00000002;
private const uint RRF_RT_REG_EXPAND_SZ = 0x00000004;
private const uint RRF_SUBKEY_WOW6432KEY = 0x00020000;
private const int ERROR_SUCCESS = 0;
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern int RegGetValueW(IntPtr hkey, string lpSubKey, string lpValue, uint dwFlags,
IntPtr pdwType, char[]? pvData, ref uint pcbData);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern int RegDeleteKeyValueW(IntPtr hkey, string lpSubKey, string lpValueName);
private static string? ReadRegistryString(IntPtr root, string valueName, uint viewFlags)
{
try
{
uint flags = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | viewFlags;
uint bytes = 0;
if (RegGetValueW(root, RegistryKey, valueName, flags, IntPtr.Zero, null, ref bytes) != ERROR_SUCCESS || bytes < 2)
return null;
var buffer = new char[(bytes + 1) / 2];
if (RegGetValueW(root, RegistryKey, valueName, flags, IntPtr.Zero, buffer, ref bytes) != ERROR_SUCCESS)
return null;
int len = Array.IndexOf(buffer, '\0');
return new string(buffer, 0, len >= 0 ? len : buffer.Length);
}
catch
{
// Missing advapi32 entry point or access denied — fall back to the defaults.
return null;
}
}
}

View file

@ -19,6 +19,10 @@ internal sealed class SessionStateRecord
public DateTime? LoginCompletedAtUtc { get; set; }
public DateTime LastUpdatedAtUtc { get; set; } = DateTime.UtcNow;
public bool IsLoggedIn { get; set; }
/// Set by the engine when LogoutLifecycleHooks observes a logout (clean
/// or server-driven disconnect). Stays set across the post-login reaper
/// window so the launcher can detect "stuck on disconnect/char-select".
public DateTime? LogoutAtUtc { get; set; }
}
internal static class SessionStateStore
@ -32,7 +36,9 @@ internal static class SessionStateStore
record.ProcessId = processId;
record.LastUpdatedAtUtc = DateTime.UtcNow;
File.WriteAllText(GetProcessPath(processId), BuildSessionJson(record), Encoding.UTF8);
// Explicit no-BOM UTF-8 — Encoding.UTF8 emits a BOM under NativeAOT which
// breaks JsonDocument.Parse on the launcher side.
File.WriteAllText(GetProcessPath(processId), BuildSessionJson(record), new System.Text.UTF8Encoding(false));
}
public static SessionStateRecord? TryReadForProcess(int processId)
@ -43,7 +49,15 @@ internal static class SessionStateStore
try
{
using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(path));
byte[] bytes = File.ReadAllBytes(path);
// Strip UTF-8 BOM if present — the engine writes with Encoding.UTF8
// which emits a BOM (EF BB BF) under NativeAOT, and JsonDocument.Parse
// on a byte span rejects the BOM as an invalid JSON start character.
ReadOnlyMemory<byte> content = bytes;
if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)
content = new ReadOnlyMemory<byte>(bytes, 3, bytes.Length - 3);
using JsonDocument document = JsonDocument.Parse(content);
JsonElement root = document.RootElement;
var record = new SessionStateRecord
@ -56,7 +70,8 @@ internal static class SessionStateStore
LaunchStartedAtUtc = GetDateTime(root, "LaunchStartedAtUtc") ?? DateTime.UtcNow,
LoginCompletedAtUtc = GetDateTime(root, "LoginCompletedAtUtc"),
LastUpdatedAtUtc = GetDateTime(root, "LastUpdatedAtUtc") ?? DateTime.UtcNow,
IsLoggedIn = GetBoolean(root, "IsLoggedIn")
IsLoggedIn = GetBoolean(root, "IsLoggedIn"),
LogoutAtUtc = GetDateTime(root, "LogoutAtUtc")
};
if (record.ProcessId == 0)
@ -138,6 +153,10 @@ internal static class SessionStateStore
writer.WriteNull("LoginCompletedAtUtc");
writer.WriteString("LastUpdatedAtUtc", record.LastUpdatedAtUtc.ToString("O", CultureInfo.InvariantCulture));
writer.WriteBoolean("IsLoggedIn", record.IsLoggedIn);
if (record.LogoutAtUtc.HasValue)
writer.WriteString("LogoutAtUtc", record.LogoutAtUtc.Value.ToString("O", CultureInfo.InvariantCulture));
else
writer.WriteNull("LogoutAtUtc");
writer.WriteEndObject();
}