using System.Text.Json;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;
using Windows.Foundation;
using XFEExtension.NetCore.WinUIHelper.Interface.Services;
using XFEExtension.NetCore.WinUIHelper.Utilities;
using XFEExtension.NetCore.WinUIHelper.Utilities.Helper;
using XFEWarframe.Player.Profiles.CrossVersionProfiles;
using XFEWarframe.Player.ViewModels;
using XFEWarframe.Player.Views;
using XFEWarframe.Player.Implements.Services;
using XFEWarframe.Client;
using XFEWarframe.Client.Runtime;
using Newtonsoft.Json.Linq;
using XFEWarframe.Desktop.Editing;
namespace XFEWarframe.Player.Utilities.Diagnostics;
// Opt-in isolated integration check; --verify-dialogs also exercises visible native modals without launching the game.
internal static partial class DesktopVerification
{
public static List<string> BindingErrors { get; } = [];
public static async Task RunAsync(string reportPath)
{
if (AppPath.Argument("verify-game-login") == "true") { await VerifyGameLoginAsync(reportPath); return; }
if (AppPath.Argument("verify-install-game") is string installGame) { await VerifyInstallerAsync(reportPath, installGame); return; }
if (AppPath.Argument("verify-ability-controls") == "true") { await AbilityEditorVerification.RunAsync(App.MainWindow, reportPath); return; }
if (AppPath.Argument("verify-readonly") == "true") { await VerifyReadOnlyInventoryAsync(reportPath); return; }
var checks = new List<string>();
string? error = null;
try
{
if (AppPath.Argument("profile-root") is null) throw new InvalidOperationException("UI verification requires an isolated --profile-root.");
if (!App.MainWindow.ExtendsContentIntoTitleBar || App.MainWindow.Content is not AppShellPage)
throw new InvalidOperationException("Native window shell was not initialized.");
checks.Add("native-titlebar-and-app-shell");
var bundledVersion = await Task.Run(() =>
{
var payload = ClientInstaller.FindPayload();
var manifest = JsonSerializer.Deserialize(File.ReadAllText(Path.Combine(payload, "payload.json")), ClientJson.Default.PayloadManifest)!;
var hash = Compatibility.Hash(Path.Combine(payload, ClientInstaller.BridgeFile));
if (manifest.Version != RuntimeControlServer.Version || !string.Equals(manifest.Sha256, hash, StringComparison.OrdinalIgnoreCase))
throw new InvalidDataException("The desktop application did not bundle the current native component with a matching checksum.");
return manifest.Version;
});
checks.Add($"bundled-native-component: {bundledVersion}, automatic discovery, current runtime version and matching SHA-256");
await App.Service.InitializeAsync();
var api = AppPath.Argument("verify-api") ?? throw new InvalidOperationException("Player verification requires an isolated --verify-api.");
if (!Uri.TryCreate(api, UriKind.Absolute, out var endpoint) || !endpoint.IsLoopback) throw new InvalidOperationException("UI verification only accepts a local test API.");
App.Service.State.ServerUrl = api;
var navigation = ServiceManager.GetGlobalService<INavigationViewService>()!;
foreach (var type in PageManager.PageDefinitions.Values.Where(x => x != typeof(AppShellPage)).ToArray())
{
navigation.NavigateTo(type);
var page = (Page)navigation.NavigationService.Frame!.Content;
var vm = (ViewModelBase)page.DataContext;
if (vm.LoadCommand.ExecutionTask is Task loading) await loading;
if (vm.LastError is not null) throw new InvalidOperationException(type.Name + ": " + vm.LastError);
if (vm.NavigationParameters.CurrentPage != page) throw new InvalidOperationException("Navigation parameter service lost its page.");
if (AppPath.Argument("verify-dialogs") != "true") foreach (var width in new[] { 1400d, 1024d, 800d })
{
page.Measure(new Size(width, 900));
page.Arrange(new Rect(0, 0, width, 900));
page.UpdateLayout();
}
if (AppPath.Argument("verify-dialogs") == "true") { await Task.Delay(80); page.UpdateLayout(); }
checks.Add(type.Name + ": navigation, view-model load, XAML layout");
if (type == typeof(SettingPage))
{
var languages = DialogVerification.Children<CommunityToolkit.WinUI.Controls.SettingsExpander>(page)
.Single(x => x.Items.OfType<CommunityToolkit.WinUI.Controls.SettingsCard>().Count(c => c.Content is ComboBox) == 2);
var grouped = languages.Items.OfType<CommunityToolkit.WinUI.Controls.SettingsCard>().ToArray();
var standalone = DialogVerification.Children<CommunityToolkit.WinUI.Controls.SettingsCard>(page)
.Count(x => !grouped.Contains(x) && x.Content is ComboBox or ToggleSwitch);
if (grouped.Length != 2 || standalone != 3 || grouped.Any(x => x.Content is not ComboBox))
throw new InvalidOperationException("Preferences must group language cards and retain direct theme and account settings.");
languages.IsExpanded = true; page.UpdateLayout();
languages.IsExpanded = false; page.UpdateLayout();
}
}
checks.Add("player-discovery-preferences-and-log-reading");
var email = "desktop-" + Guid.NewGuid().ToString("N") + "@example.invalid";
var password = Guid.NewGuid().ToString("N");
await App.Accounts.RegisterAsync(email, password, "Desktop" + Guid.NewGuid().ToString("N")[..10]);
if (App.Accounts.State.IsLoggedIn) throw new InvalidOperationException("Registration unexpectedly signed in the player.");
await App.Accounts.LoginAsync(email, password);
if (!SystemProfile.RememberAccount || !new AuthenticationViewModel().RememberAccount)
throw new InvalidOperationException("Remember account is not enabled by default.");
var credentialStore = new RememberedAccountStore();
var remembered = await credentialStore.ReadAsync(api);
if (remembered?.Email != email || remembered.Password != password)
throw new InvalidOperationException("Windows-protected account did not round-trip.");
if (await credentialStore.ReadAsync("http://localhost:1") is not null)
throw new InvalidOperationException("Remembered credentials crossed server origins.");
foreach (var file in Directory.GetFiles(Path.Combine(AppPath.DataDirectory, "Credentials"), "*.dat"))
if (System.Text.Encoding.UTF8.GetString(await File.ReadAllBytesAsync(file)).Contains(password, StringComparison.Ordinal))
throw new InvalidOperationException("Remembered credentials contain a plaintext password.");
var restored = new PlayerAccountService();
try
{
await restored.InitializeAsync();
if (!restored.State.IsLoggedIn || restored.State.Email != email)
throw new InvalidOperationException("A fresh account service could not restore the saved login.");
}
finally { restored.Stop(); }
checks.Add("remember-account-default-on-encrypted-and-restored-by-fresh-service");
await App.Accounts.SetRememberAccountAsync(false);
if (await credentialStore.ReadAsync(api) is not null || !App.Accounts.State.IsLoggedIn)
throw new InvalidOperationException("Disabling remember must clear saved credentials and retain this session.");
await App.Accounts.SetRememberAccountAsync(true);
if (await credentialStore.ReadAsync(api) is null)
throw new InvalidOperationException("Re-enabling remember did not save the active account.");
checks.Add("remember-account-toggle-clears-storage-without-ending-session");
await App.Accounts.GrantAsync("PremiumCredits", 25);
await App.Accounts.GrantAsync("RegularCredits", 3000);
await App.Accounts.GrantAsync("FusionPoints", 100);
await App.Accounts.RefreshAsync();
if (App.Accounts.State.Platinum != 25 || App.Accounts.State.Credits != 3000 || App.Accounts.State.Endo != 100)
throw new InvalidOperationException("Player wallet did not persist the grants.");
foreach (var pageType in new[] { typeof(AccountPage), typeof(InventoryPage), typeof(MainPage) })
{
navigation.NavigateTo(pageType);
var page = (Page)navigation.NavigationService.Frame!.Content;
var vm = (ViewModelBase)page.DataContext;
if (vm.LoadCommand.ExecutionTask is Task loading) await loading;
if (vm.LastError is not null) throw new InvalidOperationException(pageType.Name + ": " + vm.LastError);
if (AppPath.Argument("verify-dialogs") != "true") foreach (var width in new[] { 1400d, 1024d, 800d }) { page.Measure(new Size(width, 900)); page.Arrange(new Rect(0, 0, width, 900)); page.UpdateLayout(); }
}
await App.Accounts.GrantItemAsync("/Lotus/Types/Items/MiscItems/Ferrite", 3);
var owned = await App.Accounts.InventoryAsync("Ferrite", "", 0);
if (!owned.Items.Any(x => x.Type.EndsWith("/Ferrite", StringComparison.Ordinal) && x.Count == 3)) throw new InvalidOperationException("Player item grant was not saved.");
for (var attempt = 0; attempt < 30 && App.Accounts.State.Avatar is null; attempt++) await Task.Delay(100);
if (App.Accounts.State.Avatar is null) throw new InvalidOperationException("Game avatar did not load.");
var shell = (AppShellPage)App.MainWindow.Content;
var nav = (NavigationView)shell.FindName("NavigationView");
navigation.NavigateTo<AccountPage>();
var accountPage = (AccountPage)navigation.NavigationService.Frame!.Content;
if (accountPage.ViewModel.LoadCommand.ExecutionTask is Task accountLoad) await accountLoad;
if (nav.FooterMenuItems.Count != 2 || nav.SelectedItem != nav.FooterMenuItems[0]) throw new InvalidOperationException("Account navigation is not selected in the footer.");
var gameAvatar = App.Accounts.State.Avatar;
foreach (var open in new[] { true, false })
{
nav.PaneDisplayMode = NavigationViewPaneDisplayMode.LeftCompact;
nav.IsPaneOpen = open;
await Task.Delay(200);
VerifyAvatarLayout(shell, nav, accountPage, gameAvatar);
}
checks.Add("footer-avatar-image-layout-in-expanded-and-compact-navigation");
// Exercise a changed avatar after the shell's bindings have already initialized.
App.Accounts.State.Avatar = new WriteableBitmap(2, 2);
VerifyAvatarLayout(shell, nav, accountPage, App.Accounts.State.Avatar);
App.Accounts.State.Avatar = gameAvatar;
VerifyAvatarLayout(shell, nav, accountPage, gameAvatar);
nav.PaneDisplayMode = NavigationViewPaneDisplayMode.Auto;
checks.Add("footer-and-account-card-follow-avatar-changes");
App.Accounts.State.CurrencyGrantEnabled = false; App.Accounts.State.ItemGrantEnabled = false; App.Accounts.State.RegistrationEnabled = false;
if (App.Accounts.State.CurrencyVisibility != Visibility.Collapsed || App.Accounts.State.ItemVisibility != Visibility.Collapsed) throw new InvalidOperationException("Forbidden grant controls remain visible.");
var loginDialog = new Views.Dialogs.LoginDialog(); var registerDialog = new Views.Dialogs.RegisterDialog();
if (!string.IsNullOrEmpty(loginDialog.SecondaryButtonText) || !string.IsNullOrEmpty(registerDialog.PrimaryButtonText)) throw new InvalidOperationException("Disabled registration remains visible.");
await App.Accounts.InitializeAsync();
await App.Accounts.RefreshAsync();
if (App.Accounts.State.CurrencyVisibility != Visibility.Visible || App.Accounts.State.ItemVisibility != Visibility.Visible) throw new InvalidOperationException("Allowed grant controls are not restored.");
navigation.NavigateTo<ItemCatalogPage>();
var itemPage = (ItemCatalogPage)navigation.NavigationService.Frame!.Content;
if (itemPage.ViewModel.LoadCommand.ExecutionTask is Task catalogLoad) await catalogLoad;
if (itemPage.ViewModel.LastError is not null) throw new InvalidOperationException(itemPage.ViewModel.LastError);
if (AppPath.Argument("verify-dialogs") != "true") foreach (var width in new[] { 1400d, 1024d, 800d }) { itemPage.Measure(new Size(width, 900)); itemPage.Arrange(new Rect(0, 0, width, 900)); itemPage.UpdateLayout(); }
checks.Add("separate-registration-login-and-grants");
if (AppPath.Argument("verify-dialogs") == "true")
{
await SuggestionVerification.VerifyAsync((FrameworkElement)App.MainWindow.Content, new ItemCatalogPageViewModel().Suggestions);
checks.Add("native-AutoSuggestBox: nullable/invalid/ambiguous choices, exact paths, stale-response protection, context changes, failures, real catalog API");
}
await VerifyUnifiedInventoryAsync(navigation, checks);
if (AppPath.Argument("verify-dialogs") == "true") await VerifyQuestCreationAsync(navigation, checks);
await VerifyOverviewActionsAsync(navigation, checks);
checks.Add("game-avatar-and-footer-account-selection");
checks.Add("permission-controlled-visibility-and-auth-dialog-construction");
await VerifyEditorsAsync(navigation, checks);
await VerifyRuntimeAsync(navigation, checks);
await App.Accounts.LogoutAsync();
if (await credentialStore.ReadAsync(api) is not null) throw new InvalidOperationException("Logout retained saved credentials.");
var signedOut = new PlayerAccountService();
try
{
await signedOut.InitializeAsync();
if (signedOut.State.IsLoggedIn) throw new InvalidOperationException("Explicit logout was undone by automatic login.");
}
finally { signedOut.Stop(); }
checks.Add("logout-clears-remembered-account-and-prevents-auto-login");
if (App.Accounts.State.IsLoggedIn || App.Accounts.State.Platinum != 0) throw new InvalidOperationException("Logout retained account data.");
var accountItem = (NavigationViewItem)nav.FooterMenuItems[0];
if (accountItem.Icon is not FontIcon || accountItem.Content as string != UiText.Translate("登录账号"))
throw new InvalidOperationException("Logout did not restore the guest footer icon and label.");
checks.Add("footer-guest-icon-restored-after-logout");
SystemProfile.SaveProfile();
foreach (var file in Directory.GetFiles(AppPath.ProfilesDirectory, "*", SearchOption.AllDirectories))
if (File.ReadAllText(file).Contains(password, StringComparison.Ordinal)) throw new InvalidOperationException("A profile retained the test password.");
checks.Add("player-logout-clears-session-and-password-is-not-persisted");
var previous = SystemProfile.Theme;
foreach (var theme in new[] { ElementTheme.Light, ElementTheme.Dark, ElementTheme.Default })
AppThemeHelper.ChangeTheme(theme);
AppThemeHelper.ChangeTheme(previous);
SystemProfile.SaveProfile();
if (BindingErrors.Count > 0) throw new InvalidOperationException(string.Join("\n", BindingErrors));
checks.Add("theme-and-isolated-XFEProfile-save");
if (AppPath.Argument("verify-dialogs") == "true") checks.Add($"native-form-dialogs: {DialogVerification.CompletedCount} opens, button actions and detachments; shared button styling");
if (AppPath.Argument("verify-visible") == "true")
{
// Reuse only the generated account on the isolated loopback server.
// This leaves the real UI open for a separate, observed manual/automation pass.
await App.Accounts.LoginAsync(email, password);
navigation.NavigateTo<EditorPage>(InventoryNavigation.Route("Suits"));
}
}
catch (Exception ex) { error = ex.ToString(); AppPath.LogException(ex); }
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(reportPath))!);
await File.WriteAllTextAsync(reportPath, JsonSerializer.Serialize(new
{
application = "Player", passed = error is null, checks, error,
scope = AppPath.Argument("verify-dialogs") == "true"
? "Isolated real API, native WinUI modal open/save/cancel, persistence, navigation, bindings, styles and layout."
: "Hidden XAML construction, navigation, bindings and layout; not visual acceptance."
}, new JsonSerializerOptions { WriteIndented = true }));
}
private static async Task VerifyEditorsAsync(INavigationViewService navigation, List<string> checks)
{
await App.Accounts.GrantAsync("PrimeTokens", 12); await App.Accounts.GrantAsync("CrewShipFusionPoints", 9); await App.Accounts.GrantAsync("PrimeTokens", -2);
if (App.Accounts.State.RegalAya != 10 || App.Accounts.State.Dirac != 9) throw new InvalidOperationException("Additional currency balances did not update.");
const string type = "/Lotus/Upgrades/Mods/Rifle/WeaponDamageAmountMod";
await App.Accounts.GrantItemAsync(type, 1);
var language = SystemProfile.ItemLanguage;
try
{
SystemProfile.ItemLanguage = "en";
var found = await App.Accounts.CatalogAsync(type, "", 0);
if (!found.Items.Any(x => x.Type == type && x.Name == "Serration")) throw new InvalidOperationException("Localized path search failed across the HTTP transport.");
navigation.NavigateTo<EditorPage>(); var page = (EditorPage)navigation.NavigationService.Frame!.Content; var vm = page.ViewModel;
if (vm.LoadCommand.ExecutionTask is Task load) await load;
vm.Category = vm.Categories.First(x => x.Key == "RawUpgrades"); await vm.RefreshCommand.ExecuteAsync(null);
vm.SelectedItem = vm.Items.First(x => x.Name == "Serration"); await vm.OpenItemCommand.ExecuteAsync(null);
if (vm.LastError is not null || vm.Fields.Count == 0 || vm.ImportVisibility != Visibility.Visible || vm.ExportVisibility != Visibility.Visible)
throw new InvalidOperationException("Authorized editor form failed: " + vm.LastError);
if (AppPath.Argument("verify-dialogs") != "true") foreach (var width in new[] { 1400d, 1024d, 800d }) { page.Measure(new Size(width, 900)); page.Arrange(new Rect(0, 0, width, 900)); page.UpdateLayout(); }
var rankField = vm.Fields.First(x => x.Key == "rank"); rankField.Value = new JValue(7);
var view = await App.Accounts.ReadEditorAsync("RawUpgrades", "", type, 0);
await App.Accounts.SaveEditorAsync(new JObject { ["version"] = view["version"]!, ["category"] = "RawUpgrades", ["item"] = type, ["action"] = "mod.rank", ["values"] = new JObject { ["rank"] = 3 } });
await vm.CheckChangesAsync();
if (!vm.HasExternalChanges || vm.CanSave || !vm.HasChangeNotice || rankField.Value.Value<int>() != 7 || !ReferenceEquals(rankField, vm.Fields.First(x => x.Key == "rank")))
throw new InvalidOperationException("Concurrent inventory change discarded unsaved input or left saving enabled.");
await vm.RefreshCommand.ExecuteAsync(null);
if (vm.HasExternalChanges || vm.HasChangeNotice || vm.LastError is not null) throw new InvalidOperationException("Explicit refresh did not resolve the stale editor.");
// Recreate a raw MOD from another API caller and let the clean editor follow that change.
await App.Accounts.GrantItemAsync(type, 1); await vm.CheckChangesAsync();
if (!vm.Items.Any(x => x.Name == "Serration")) throw new InvalidOperationException("Clean editor failed to follow an external inventory change.");
checks.Add("editor-change-detection-preserves-unsaved-input-and-refreshes-clean-views");
var archive = await App.Accounts.ExportArchiveAsync();
var imported = await App.Accounts.ImportArchiveAsync(archive.Value<string>("version")!, new JObject { ["PrimeTokens"] = 14 });
if (string.IsNullOrEmpty(imported.Value<string>("backup"))) throw new InvalidOperationException("Archive import did not return its backup reference.");
await App.Accounts.RefreshAsync(); if (App.Accounts.State.RegalAya != 14) throw new InvalidOperationException("Archive currency was not applied.");
navigation.NavigateTo<RivenPage>(); var rivenPage = (RivenPage)navigation.NavigationService.Frame!.Content;
if (rivenPage.ViewModel.LoadCommand.ExecutionTask is Task rivenLoad) await rivenLoad;
if (rivenPage.ViewModel.LastError is not null || rivenPage.ViewModel.Families.Count != 7 || rivenPage.ViewModel.Rows.Count != 2)
throw new InvalidOperationException("Authorized riven page failed: " + rivenPage.ViewModel.LastError);
await RivenVerification.VerifyAsync(rivenPage, rivenPage.ViewModel.Rows, () => rivenPage.ViewModel.CalculateCommand.ExecuteAsync(null), () => rivenPage.ViewModel.Name, AppPath.Argument("verify-dialogs") == "true");
checks.Add("riven-instance-name-colored-stats-numeric-suggestions-and-live-preview");
if (AppPath.Argument("verify-dialogs") != "true") foreach (var width in new[] { 1400d, 1024d, 800d }) { rivenPage.Measure(new Size(width, 900)); rivenPage.Arrange(new Rect(0, 0, width, 900)); rivenPage.UpdateLayout(); }
checks.Add("authorized-editor-riven-localized-path-query-archive-and-five-currencies");
}
finally { SystemProfile.ItemLanguage = language; }
}
private static async Task VerifyReadOnlyInventoryAsync(string reportPath)
{
var checks = new List<string>(); string? error = null;
try
{
var api = AppPath.Argument("verify-api");
if (AppPath.Argument("profile-root") is null || !Uri.TryCreate(api, UriKind.Absolute, out var endpoint) || !endpoint.IsLoopback)
throw new InvalidOperationException("Read-only checks require an isolated local API and profile.");
await App.Service.InitializeAsync(); App.Service.State.ServerUrl = api!;
var email = Guid.NewGuid().ToString("N") + "@example.invalid"; var password = Guid.NewGuid().ToString("N");
await App.Accounts.RegisterAsync(email, password, "ReadOnly" + Guid.NewGuid().ToString("N")[..8]);
await App.Accounts.LoginAsync(email, password);
var state = App.Accounts.State;
if (state.EditingEnabled || state.ItemGrantEnabled || state.CurrencyGrantEnabled) throw new InvalidOperationException("Read-only fixture permissions are not restricted.");
var navigation = ServiceManager.GetGlobalService<INavigationViewService>()!;
foreach (var section in InventoryNavigation.All.Where(x => x.Key is not ("riven" or "catalog") && !InventoryNavigation.RequiresEditing(x.Key)))
{
navigation.NavigateTo<EditorPage>(InventoryNavigation.Route(section.Key));
var vm = ((EditorPage)navigation.NavigationService.Frame!.Content).ViewModel;
if (vm.LoadCommand.ExecutionTask is Task load) await load;
if (vm.QuestCreationVisibility != Visibility.Collapsed || vm.LastError is not null || vm.Category?.Key != section.Key || vm.CatalogToggleVisibility != Visibility.Collapsed || vm.ActionVisibility != Visibility.Collapsed || vm.BatchVisibility != Visibility.Collapsed || vm.ImportVisibility != Visibility.Collapsed || vm.ExportVisibility != Visibility.Collapsed)
throw new InvalidOperationException("Read-only category or visibility failed: " + section.Key + ": " + vm.LastError);
if (section.Key == "Ships" && !vm.Items.Any()) throw new InvalidOperationException("The read-only view lost the starter landing craft.");
await vm.ShowCatalogCommand.ExecuteAsync(null);
if (vm.IsCatalogMode) throw new InvalidOperationException("Read-only account entered item creation mode.");
}
var tree = (NavigationViewItem)((AppShellPage)App.MainWindow.Content).FindName("InventoryRoot");
void AssertHidden(IEnumerable<NavigationViewItem> nodes)
{
foreach (var node in nodes)
{
var key = (string)node.Tag;
if ((InventoryNavigation.RequiresEditing(key) || key is "catalog" or "riven") && node.Visibility != Visibility.Collapsed)
throw new InvalidOperationException("Unauthorized navigation remains visible: " + key);
AssertHidden(node.MenuItems.OfType<NavigationViewItem>());
}
}
AssertHidden(tree.MenuItems.OfType<NavigationViewItem>());
navigation.NavigateTo<InventoryPage>();
var overview = (InventoryPage)navigation.NavigationService.Frame!.Content;
if (overview.ViewModel.LoadCommand.ExecutionTask is Task overviewLoad) await overviewLoad;
overview.UpdateLayout();
var overviewActions = (OverviewActionsView)overview.FindName("OverviewActions");
for (var attempt = 0; attempt < 100 && !ReferenceEquals(overviewActions.Model, overview.ViewModel.OverviewActions); attempt++) await Task.Delay(10);
if (!ReferenceEquals(overviewActions.Model, overview.ViewModel.OverviewActions) || overview.ViewModel.OverviewActions.Actions.Count != 0 || overviewActions.Visibility != Visibility.Collapsed)
throw new InvalidOperationException("Unauthorized overview actions remain visible.");
await App.Accounts.LogoutAsync();
checks.Add("read-only-inventory: all 47 categories, starter landing craft, no grant/editor/archive controls or unauthorized navigation");
if (BindingErrors.Count > 0) throw new InvalidOperationException(string.Join("\n", BindingErrors));
}
catch (Exception ex) { error = ex.ToString(); AppPath.LogException(ex); }
await File.WriteAllTextAsync(reportPath, JsonSerializer.Serialize(new { application = "PlayerReadOnly", passed = error is null, checks, error, scope = "Isolated real API with all editor/item/currency grants disabled; native WinUI view models and bindings." }, new JsonSerializerOptions { WriteIndented = true }));
}
private static async Task VerifyOverviewActionsAsync(INavigationViewService navigation, List<string> checks)
{
navigation.NavigateTo<InventoryPage>();
var page = (InventoryPage)navigation.NavigationService.Frame!.Content;
if (page.ViewModel.LoadCommand.ExecutionTask is Task load) await load;
await OverviewActionsVerification.VerifyAsync((OverviewActionsView)page.FindName("OverviewActions"), page.ViewModel.OverviewActions,
async () => (JObject)(await App.Accounts.ExportArchiveAsync())["inventory"]!, AppPath.Argument("verify-dialogs") == "true");
await VerifyOverviewPermissionChangesAsync(page);
if (InventoryNavigation.All.Any(x => x.Key == "progress")) throw new InvalidOperationException("The old progress item-list navigation remains.");
checks.Add("overview-actions: 16 authorized buttons, grouped cards, native cancel and execute, syndicate suggestion, API readback, account-switch guard");
}
private static async Task VerifyOverviewPermissionChangesAsync(InventoryPage page)
{
var origin = new Uri(AppPath.Argument("verify-api")!);
if (!origin.IsLoopback) throw new InvalidOperationException("Permission verification requires an isolated loopback server.");
var config = JObject.Parse(await File.ReadAllTextAsync(Path.Combine(AppPath.Argument("root")!, "server.json")));
using var client = new System.Net.Http.HttpClient { BaseAddress = origin };
client.DefaultRequestHeaders.Authorization = new("Bearer", config.Value<string>("AdminToken")!);
async Task UpdateAsync(bool enabled)
{
var current = JObject.Parse(await client.GetStringAsync("control/v1/editor/permissions"));
using var response = await client.PostAsync("control/v1/editor/permissions", new System.Net.Http.StringContent(
new JObject { ["version"] = current["version"]!.DeepClone(), ["values"] = new JObject { ["unlock.intrinsics"] = enabled } }.ToString(), System.Text.Encoding.UTF8, "application/json"));
response.EnsureSuccessStatusCode();
await App.Accounts.RefreshAsync();
for (var i = 0; i < 250 && (page.ViewModel.OverviewActions.IsBusy || page.ViewModel.OverviewActions.Actions.Count != (enabled ? 16 : 15)); i++) await Task.Delay(20);
}
var model = page.ViewModel.OverviewActions;
var pending = await model.PrepareAsync("unlock.intrinsics") ?? throw new InvalidOperationException(model.Message);
var before = await App.Accounts.ExportArchiveAsync();
try
{
await UpdateAsync(false);
if (model.Actions.Count != 15 || ((OverviewActionsView)page.FindName("OverviewActions")).ActionButtons.Any(x => (string)x.Tag == "unlock.intrinsics"))
throw new InvalidOperationException("Revoking one permission did not remove its overview button.");
await model.ExecuteAsync(pending);
if (model.Message.Length == 0 || !JToken.DeepEquals(before["inventory"], (await App.Accounts.ExportArchiveAsync())["inventory"]))
throw new InvalidOperationException("Revoked prepared action modified the save.");
}
finally { await UpdateAsync(true); }
if (model.Actions.Count != 16) throw new InvalidOperationException("Restoring permission did not restore the overview button.");
}
private static async Task VerifyQuestCreationAsync(INavigationViewService navigation, List<string> checks)
{
navigation.NavigateTo<EditorPage>(InventoryNavigation.Route("QuestKeys"));
var page = (EditorPage)navigation.NavigationService.Frame!.Content;
var vm = page.ViewModel;
if (vm.LoadCommand.ExecutionTask is Task load) await load;
await QuestEditorVerification.VerifyAsync(page, (FormDialogButton)page.FindName("AddQuestButton"), (AutoSuggestBox)page.FindName("OwnedSearch"),
() => vm.QuestFields, () => vm.Items, () => vm.IsIdle, () => vm.LastError,
async () => (JObject)(await App.Accounts.ExportArchiveAsync())["inventory"]!);
checks.Add("missing-quest: native suggestion and add dialog, API persistence preserves progress; live name/path/no-match/clear list search");
}
private static async Task VerifyUnifiedInventoryAsync(INavigationViewService navigation, List<string> checks)
{
var shell = (AppShellPage)App.MainWindow.Content;
var tree = (NavigationViewItem)shell.FindName("InventoryRoot");
if (tree.MenuItems.Count != InventoryNavigation.Sections.Count + 1) throw new InvalidOperationException("Inventory tree is incomplete.");
var available = (await App.Accounts.ReadEditorAsync("Suits", "", null, 0))["categories"]!.Select(x => (string)x["key"]!).ToHashSet();
foreach (var section in InventoryNavigation.All.Where(x => available.Contains(x.Key)))
{
navigation.NavigateTo<EditorPage>(InventoryNavigation.Route(section.Key));
var page = (EditorPage)navigation.NavigationService.Frame!.Content;
var vm = page.ViewModel;
if (vm.LoadCommand.ExecutionTask is Task load) await load;
if (vm.LastError is not null || vm.Category?.Key != section.Key) throw new InvalidOperationException(section.Key + ": " + vm.LastError);
if (InventoryNavigation.RequiresEditing(section.Key) && vm.CatalogToggleVisibility != Visibility.Collapsed) throw new InvalidOperationException("An item grant was offered for a progress category.");
if (AppPath.Argument("verify-dialogs") != "true") { page.Measure(new Size(1024, 900)); page.Arrange(new Rect(0, 0, 1024, 900)); } page.UpdateLayout();
}
navigation.NavigateTo<EditorPage>(InventoryNavigation.Route("Suits"));
var editor = ((EditorPage)navigation.NavigationService.Frame!.Content).ViewModel;
if (editor.LoadCommand.ExecutionTask is Task loaded) await loaded;
await editor.ShowCatalogCommand.ExecuteAsync(null);
editor.Catalog.Query = "/Lotus/Powersuits/Excalibur/Excalibur"; await editor.Catalog.SearchCommand.ExecuteAsync(null);
editor.Catalog.SelectedItem = editor.Catalog.Items.First(x => x.Type == editor.Catalog.Query);
await editor.Catalog.GiveCommand.ExecuteAsync(null); await editor.ShowOwnedCommand.ExecuteAsync(null);
if (editor.LastError is not null || editor.IsCatalogMode || !editor.Items.Any()) throw new InvalidOperationException("Integrated player item creation failed: " + editor.LastError);
editor.SelectedItem = editor.Items.First(); await editor.OpenItemCommand.ExecuteAsync(null);
if (editor.Actions.Count == 0) throw new InvalidOperationException("The newly added Warframe cannot be edited.");
editor.Query = "Excalibur"; await editor.RefreshCommand.ExecuteAsync(null);
editor.SelectedItem = editor.Items.First(); var selectedKey = editor.SelectedItem.Key;
await VerifyInventoryPermissionRecoveryAsync((EditorPage)navigation.NavigationService.Frame.Content);
checks.Add("inventory-permission-recovery: editing to readonly and back via revision polling, visible explanation, same query and selected suit, no manual refresh");
editor.EditItemCommand.Execute(null);
if (navigation.NavigationService.Frame!.Content is not EquipmentPage details) throw new InvalidOperationException("Editing did not navigate to the dedicated page.");
if (details.ViewModel.LoadCommand.ExecutionTask is Task detailLoad) await detailLoad;
if (details.ViewModel.LastError is not null) throw new InvalidOperationException(details.ViewModel.LastError);
var liveInput = AppPath.Argument("verify-dialogs") == "true";
await EquipmentEditorVerification.VerifyAsync(details, (EquipmentEditorView)details.FindName("EditorView"), 2718, liveInput);
checks.Add(liveInput ? "ability-AutoSuggestBox: loaded input, name/path candidates, invalid input rejected, native query and save, API readback" : "ability-AutoSuggestBox: construction only; live input requires --verify-dialogs");
checks.Add(liveInput ? "multiple-abilities: four native suggestions, save/reload, independent configurations, restore original skills" : "multiple-abilities: four searchable slots constructed");
await EquipmentEditorVerification.VerifySynchronizationAsync(details.ViewModel.Editor,
async () => { await App.Accounts.GrantAsync("RegularCredits", 1); });
await VerifyEquipmentPermissionChangesAsync(details);
await EquipmentEditorVerification.VerifyExaltedAsync(details, (EquipmentEditorView)details.FindName("EditorView"),
async () => { foreach (var type in new[] { "/Lotus/Upgrades/Mods/Pistol/WeaponDamageAmountMod", "/Lotus/Upgrades/Mods/Warframe/AvatarHealthMaxMod", "/Lotus/Upgrades/Mods/Warframe/AvatarArmourMod",
"/Lotus/Upgrades/Mods/Pistol/WeaponFreezeDamageMod", "/Lotus/Upgrades/Mods/Pistol/WeaponToxinDamageMod", "/Lotus/Upgrades/Mods/Pistol/WeaponFireRateMod", "/Lotus/Upgrades/Mods/Pistol/WeaponCritChanceMod" })
await App.Accounts.GrantItemAsync(type, 1); },
async () => { var current = (EquipmentPage)navigation.NavigationService.Frame!.Content; if (current.ViewModel.LoadCommand.ExecutionTask is Task load) await load; return (current, (EquipmentEditorView)current.FindName("EditorView")); },
() => navigation.NavigationService.GoBack(), liveInput);
checks.Add("exalted-equipment: host-to-Glory shared card board, Warframe/Glory install/swap/uninstall, raw-to-instance conversion, C save, independent B, back retains host");
checks.Add("image-loading: native WinUI PNG decode, cache miss/hit, resource icon, stale request protection, no wrong-thread dependency-property reads");
checks.Add("mod-search: original descriptions, Viral includes Cold/Toxin, matching suggestions, AND keywords, cancelled stale request cannot replace results");
navigation.NavigationService.GoBack();
if (navigation.NavigationService.Frame.Content is not EditorPage returned) throw new InvalidOperationException("Native Back did not return to the inventory list.");
if (returned.ViewModel.ResumeListCommand.ExecutionTask is Task resumed) await resumed;
if (returned.ViewModel.Query != "Excalibur" || returned.ViewModel.SelectedItem?.Key != selectedKey) throw new InvalidOperationException("Back lost the inventory query or selected item.");
checks.Add("equipment-SelectorBar: dedicated page, native save/reset, cross-section drafts, API persistence, external conflict protection, back retains list context");
checks.Add("equipment-permission-changes: filtered sections, simultaneous inventory conflict preserves draft, revoke clears controls, restore reloads shared editor");
foreach (var type in new[] { EquipmentEditorVerification.FetchPetFixture, XFEWarframe.Mods.PetFetchMod.Type })
await App.Accounts.GrantItemAsync(type, 1);
navigation.NavigateTo<EditorPage>(InventoryNavigation.Route("KubrowPets"));
var pets = ((EditorPage)navigation.NavigationService.Frame.Content).ViewModel;
if (pets.LoadCommand.ExecutionTask is Task petLoad) await petLoad;
pets.SelectedItem = pets.Items.First(); pets.EditItemCommand.Execute(null);
if (navigation.NavigationService.Frame.Content is not EquipmentPage petDetails) throw new InvalidOperationException("Pet editing did not open the shared equipment page.");
if (petDetails.ViewModel.LoadCommand.ExecutionTask is Task petDetailLoad) await petDetailLoad;
await EquipmentEditorVerification.VerifyPetAsync(petDetails, (EquipmentEditorView)petDetails.FindName("EditorView"));
navigation.NavigationService.GoBack();
checks.Add("pet-fetch: shared ten-slot board at three widths, 300m keyword suggestions, full-rank owned card, install/move/uninstall/save, independent configs");
App.Accounts.State.ItemGrantEnabled = false;
if (editor.CatalogToggleVisibility != Visibility.Collapsed) throw new InvalidOperationException("Revoked item grant remains visible.");
await editor.ShowCatalogCommand.ExecuteAsync(null);
if (editor.IsCatalogMode) throw new InvalidOperationException("A hidden item grant can still be selected.");
await App.Accounts.RefreshAsync();
checks.Add($"unified-inventory: {available.Count} category routes, scoped item creation, owned equipment editing, permission visibility");
}
private static async Task VerifyEquipmentPermissionChangesAsync(EquipmentPage page)
{
// Administrative transport exists only inside this opt-in, isolated desktop test.
var origin = new Uri(AppPath.Argument("verify-api")!);
if (!origin.IsLoopback) throw new InvalidOperationException("Permission verification requires the isolated loopback server.");
var config = JObject.Parse(await File.ReadAllTextAsync(Path.Combine(AppPath.Argument("root")!, "server.json")));
using var client = new System.Net.Http.HttpClient { BaseAddress = origin };
client.DefaultRequestHeaders.Authorization = new("Bearer", config.Value<string>("AdminToken")!);
var before = JObject.Parse(await client.GetStringAsync("control/v1/editor/permissions"));
var saved = new JObject(before["fields"]!.Select(x => new JProperty(x.Value<string>("key")!, x.Value<bool>("value"))));
async Task UpdateAsync(JObject values)
{
var current = JObject.Parse(await client.GetStringAsync("control/v1/editor/permissions"));
using var response = await client.PostAsync("control/v1/editor/permissions", new System.Net.Http.StringContent(
new JObject { ["version"] = current["version"]!.DeepClone(), ["values"] = values }.ToString(), System.Text.Encoding.UTF8, "application/json"));
response.EnsureSuccessStatusCode();
}
var model = page.ViewModel.Editor;
try
{
var field = model.Actions.Single(x => x.Key == "experience").Fields.Single();
var draft = field.Value.Value<long>() + 321; field.Value = new JValue(draft);
var partial = new JObject(saved.Properties().Select(x => new JProperty(x.Name, x.Name == "experience")));
await UpdateAsync(partial); await App.Accounts.GrantAsync("RegularCredits", 1);
await PollEquipmentUntilAsync(model, () => model.Tabs.Count == (model.Related.Count > 0 ? 2 : 1) && model.Actions.All(x => x.Key is "experience" or "max"));
if (model.Actions.Any(x => x.Key is not ("experience" or "max")) || model.Tabs.Any(x => x.Key is not ("basic" or "exalted")) || !model.HasConflict ||
model.Actions.Single(x => x.Key == "experience").Fields.Single().Value.Value<long>() != draft)
throw new InvalidOperationException($"Partial permissions and a concurrent inventory change did not preserve an authorized draft safely. Actions={string.Join(',', model.Actions.Select(x => x.Key))}; tabs={model.Tabs.Count}; conflict={model.HasConflict}; busy={model.IsBusy}; expectedDraft={draft}; actualDraft={model.Actions.FirstOrDefault(x => x.Key == "experience")?.Fields.FirstOrDefault()?.Value}; message={model.Message}");
partial["experience"] = false; await UpdateAsync(partial);
await PollEquipmentUntilAsync(model, () => model.Tabs.Count == 0);
if (model.Tabs.Count != 0 || ((EquipmentEditorView)page.FindName("EditorView")).Selector.Items.Count != 0)
throw new InvalidOperationException("Revoked permissions left equipment controls visible.");
}
finally
{
await UpdateAsync(saved); await PollEquipmentUntilAsync(model, () => model.Tabs.Count >= 6);
}
if (model.HasMessage || model.Tabs.Count < 6) throw new InvalidOperationException("Restored permissions did not reload the shared equipment editor.");
}
private static async Task VerifyRuntimeAsync(INavigationViewService navigation, List<string> checks)
{
var game = Path.Combine(AppPath.DataDirectory, "RuntimeFixture"); var previous = App.Service.State.GameDirectory;
Directory.CreateDirectory(game); var logs = new RuntimeLogBuffer(); logs.Add("Isolated C# runtime integration fixture"); RuntimeSettings? applied = null;
await using var runtime = new RuntimeControlServer(game, new ClientConfiguration { BuildLabel = "fixture", ServerName = "UI verification" }, logs, value => applied = value, 0);
try
{
App.Service.State.GameDirectory = game;
navigation.NavigateTo<RuntimePage>(); var page = (RuntimePage)navigation.NavigationService.Frame!.Content; var vm = page.ViewModel;
if (vm.LoadCommand.ExecutionTask is Task load) await load;
if (vm.LastError is not null || !vm.IsConnected || vm.Logs.Count == 0) throw new InvalidOperationException("Runtime page did not connect: " + vm.LastError);
vm.ShowBranding = false; vm.LogRequests = true; await vm.SaveCommand.ExecuteAsync(null);
if (vm.LastError is not null || applied is null || !applied.DisableOverlay || !applied.ClientHttpLogging || !File.Exists(Path.Combine(game, "XFEWarframe", "runtime-settings.json")))
throw new InvalidOperationException("Runtime page did not apply and save settings: " + vm.LastError);
if (AppPath.Argument("verify-dialogs") != "true") foreach (var width in new[] { 1400d, 1024d, 800d }) { page.Measure(new Size(width, 900)); page.Arrange(new Rect(0, 0, width, 900)); page.UpdateLayout(); }
navigation.NavigateTo<SettingPage>(); if (vm.IsConnected) throw new InvalidOperationException("Runtime page retained its connection after navigation.");
checks.Add("runtime-page-real-loopback-status-logs-settings-save-and-disconnect-fixture-not-game");
}
finally { App.Service.State.GameDirectory = previous; }
}
private static void VerifyAvatarLayout(AppShellPage shell, NavigationView nav, AccountPage accountPage, ImageSource avatar)
{
if (AppPath.Argument("verify-dialogs") != "true") { shell.Measure(new Size(1400, 900)); shell.Arrange(new Rect(0, 0, 1400, 900)); }
shell.UpdateLayout();
var item = (NavigationViewItem)nav.FooterMenuItems[0];
var image = Descendants<Image>(item).FirstOrDefault(x => ReferenceEquals(x.Source, avatar));
if (image is null || image.ActualWidth <= 0 || image.ActualHeight <= 0 || image.Visibility != Visibility.Visible)
throw new InvalidOperationException($"Footer avatar has no visible image (pane open: {nav.IsPaneOpen}).");
var bounds = image.TransformToVisual(nav).TransformBounds(new Rect(0, 0, image.ActualWidth, image.ActualHeight));
const double tolerance = 0.1; // DPI transforms introduce fractional-pixel rounding.
if (Math.Abs(bounds.Width - 24) > tolerance || Math.Abs(bounds.Height - 24) > tolerance || bounds.X < -tolerance || bounds.Right > nav.ActualWidth + tolerance || bounds.Y < -tolerance || bounds.Bottom > nav.ActualHeight + tolerance)
throw new InvalidOperationException($"Footer avatar is clipped or outside the navigation pane: image={bounds}, navigation={nav.ActualWidth}x{nav.ActualHeight}, open={nav.IsPaneOpen}.");
if (!Descendants<PersonPicture>(accountPage).Any(x => ReferenceEquals(x.ProfilePicture, avatar)))
throw new InvalidOperationException("Footer avatar and account card use different images.");
}
private static IEnumerable<T> Descendants<T>(DependencyObject parent) where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T match) yield return match;
foreach (var descendant in Descendants<T>(child)) yield return descendant;
}
}
}
using System.Text.Json;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;
using Windows.Foundation;
using XFEExtension.NetCore.WinUIHelper.Interface.Services;
using XFEExtension.NetCore.WinUIHelper.Utilities;
using XFEExtension.NetCore.WinUIHelper.Utilities.Helper;
using XFEWarframe.Player.Profiles.CrossVersionProfiles;
using XFEWarframe.Player.ViewModels;
using XFEWarframe.Player.Views;
using XFEWarframe.Player.Implements.Services;
using XFEWarframe.Client;
using XFEWarframe.Client.Runtime;
using Newtonsoft.Json.Linq;
using XFEWarframe.Desktop.Editing;
namespace XFEWarframe.Player.Utilities.Diagnostics;
// Opt-in isolated integration check; --verify-dialogs also exercises visible native modals without launching the game.
internal static partial class DesktopVerification
{
public static List<string> BindingErrors { get; } = [];
public static async Task RunAsync(string reportPath)
{
if (AppPath.Argument("verify-game-login") == "true") { await VerifyGameLoginAsync(reportPath); return; }
if (AppPath.Argument("verify-install-game") is string installGame) { await VerifyInstallerAsync(reportPath, installGame); return; }
if (AppPath.Argument("verify-ability-controls") == "true") { await AbilityEditorVerification.RunAsync(App.MainWindow, reportPath); return; }
if (AppPath.Argument("verify-readonly") == "true") { await VerifyReadOnlyInventoryAsync(reportPath); return; }
var checks = new List<string>();
string? error = null;
try
{
if (AppPath.Argument("profile-root") is null) throw new InvalidOperationException("UI verification requires an isolated --profile-root.");
if (!App.MainWindow.ExtendsContentIntoTitleBar || App.MainWindow.Content is not AppShellPage)
throw new InvalidOperationException("Native window shell was not initialized.");
checks.Add("native-titlebar-and-app-shell");
var bundledVersion = await Task.Run(() =>
{
var payload = ClientInstaller.FindPayload();
var manifest = JsonSerializer.Deserialize(File.ReadAllText(Path.Combine(payload, "payload.json")), ClientJson.Default.PayloadManifest)!;
var hash = Compatibility.Hash(Path.Combine(payload, ClientInstaller.BridgeFile));
if (manifest.Version != RuntimeControlServer.Version || !string.Equals(manifest.Sha256, hash, StringComparison.OrdinalIgnoreCase))
throw new InvalidDataException("The desktop application did not bundle the current native component with a matching checksum.");
return manifest.Version;
});
checks.Add($"bundled-native-component: {bundledVersion}, automatic discovery, current runtime version and matching SHA-256");
await App.Service.InitializeAsync();
var api = AppPath.Argument("verify-api") ?? throw new InvalidOperationException("Player verification requires an isolated --verify-api.");
if (!Uri.TryCreate(api, UriKind.Absolute, out var endpoint) || !endpoint.IsLoopback) throw new InvalidOperationException("UI verification only accepts a local test API.");
App.Service.State.ServerUrl = api;
var navigation = ServiceManager.GetGlobalService<INavigationViewService>()!;
foreach (var type in PageManager.PageDefinitions.Values.Where(x => x != typeof(AppShellPage)).ToArray())
{
navigation.NavigateTo(type);
var page = (Page)navigation.NavigationService.Frame!.Content;
var vm = (ViewModelBase)page.DataContext;
if (vm.LoadCommand.ExecutionTask is Task loading) await loading;
if (vm.LastError is not null) throw new InvalidOperationException(type.Name + ": " + vm.LastError);
if (vm.NavigationParameters.CurrentPage != page) throw new InvalidOperationException("Navigation parameter service lost its page.");
if (AppPath.Argument("verify-dialogs") != "true") foreach (var width in new[] { 1400d, 1024d, 800d })
{
page.Measure(new Size(width, 900));
page.Arrange(new Rect(0, 0, width, 900));
page.UpdateLayout();
}
if (AppPath.Argument("verify-dialogs") == "true") { await Task.Delay(80); page.UpdateLayout(); }
checks.Add(type.Name + ": navigation, view-model load, XAML layout");
if (type == typeof(SettingPage))
{
var languages = DialogVerification.Children<CommunityToolkit.WinUI.Controls.SettingsExpander>(page)
.Single(x => x.Items.OfType<CommunityToolkit.WinUI.Controls.SettingsCard>().Count(c => c.Content is ComboBox) == 2);
var grouped = languages.Items.OfType<CommunityToolkit.WinUI.Controls.SettingsCard>().ToArray();
var standalone = DialogVerification.Children<CommunityToolkit.WinUI.Controls.SettingsCard>(page)
.Count(x => !grouped.Contains(x) && x.Content is ComboBox or ToggleSwitch);
if (grouped.Length != 2 || standalone != 3 || grouped.Any(x => x.Content is not ComboBox))
throw new InvalidOperationException("Preferences must group language cards and retain direct theme and account settings.");
languages.IsExpanded = true; page.UpdateLayout();
languages.IsExpanded = false; page.UpdateLayout();
}
}
checks.Add("player-discovery-preferences-and-log-reading");
var email = "desktop-" + Guid.NewGuid().ToString("N") + "@example.invalid";
var password = Guid.NewGuid().ToString("N");
await App.Accounts.RegisterAsync(email, password, "Desktop" + Guid.NewGuid().ToString("N")[..10]);
if (App.Accounts.State.IsLoggedIn) throw new InvalidOperationException("Registration unexpectedly signed in the player.");
await App.Accounts.LoginAsync(email, password);
if (!SystemProfile.RememberAccount || !new AuthenticationViewModel().RememberAccount)
throw new InvalidOperationException("Remember account is not enabled by default.");
var credentialStore = new RememberedAccountStore();
var remembered = await credentialStore.ReadAsync(api);
if (remembered?.Email != email || remembered.Password != password)
throw new InvalidOperationException("Windows-protected account did not round-trip.");
if (await credentialStore.ReadAsync("http://localhost:1") is not null)
throw new InvalidOperationException("Remembered credentials crossed server origins.");
foreach (var file in Directory.GetFiles(Path.Combine(AppPath.DataDirectory, "Credentials"), "*.dat"))
if (System.Text.Encoding.UTF8.GetString(await File.ReadAllBytesAsync(file)).Contains(password, StringComparison.Ordinal))
throw new InvalidOperationException("Remembered credentials contain a plaintext password.");
var restored = new PlayerAccountService();
try
{
await restored.InitializeAsync();
if (!restored.State.IsLoggedIn || restored.State.Email != email)
throw new InvalidOperationException("A fresh account service could not restore the saved login.");
}
finally { restored.Stop(); }
checks.Add("remember-account-default-on-encrypted-and-restored-by-fresh-service");
await App.Accounts.SetRememberAccountAsync(false);
if (await credentialStore.ReadAsync(api) is not null || !App.Accounts.State.IsLoggedIn)
throw new InvalidOperationException("Disabling remember must clear saved credentials and retain this session.");
await App.Accounts.SetRememberAccountAsync(true);
if (await credentialStore.ReadAsync(api) is null)
throw new InvalidOperationException("Re-enabling remember did not save the active account.");
checks.Add("remember-account-toggle-clears-storage-without-ending-session");
await App.Accounts.GrantAsync("PremiumCredits", 25);
await App.Accounts.GrantAsync("RegularCredits", 3000);
await App.Accounts.GrantAsync("FusionPoints", 100);
await App.Accounts.RefreshAsync();
if (App.Accounts.State.Platinum != 25 || App.Accounts.State.Credits != 3000 || App.Accounts.State.Endo != 100)
throw new InvalidOperationException("Player wallet did not persist the grants.");
foreach (var pageType in new[] { typeof(AccountPage), typeof(InventoryPage), typeof(MainPage) })
{
navigation.NavigateTo(pageType);
var page = (Page)navigation.NavigationService.Frame!.Content;
var vm = (ViewModelBase)page.DataContext;
if (vm.LoadCommand.ExecutionTask is Task loading) await loading;
if (vm.LastError is not null) throw new InvalidOperationException(pageType.Name + ": " + vm.LastError);
if (AppPath.Argument("verify-dialogs") != "true") foreach (var width in new[] { 1400d, 1024d, 800d }) { page.Measure(new Size(width, 900)); page.Arrange(new Rect(0, 0, width, 900)); page.UpdateLayout(); }
}
await App.Accounts.GrantItemAsync("/Lotus/Types/Items/MiscItems/Ferrite", 3);
var owned = await App.Accounts.InventoryAsync("Ferrite", "", 0);
if (!owned.Items.Any(x => x.Type.EndsWith("/Ferrite", StringComparison.Ordinal) && x.Count == 3)) throw new InvalidOperationException("Player item grant was not saved.");
for (var attempt = 0; attempt < 30 && App.Accounts.State.Avatar is null; attempt++) await Task.Delay(100);
if (App.Accounts.State.Avatar is null) throw new InvalidOperationException("Game avatar did not load.");
var shell = (AppShellPage)App.MainWindow.Content;
var nav = (NavigationView)shell.FindName("NavigationView");
navigation.NavigateTo<AccountPage>();
var accountPage = (AccountPage)navigation.NavigationService.Frame!.Content;
if (accountPage.ViewModel.LoadCommand.ExecutionTask is Task accountLoad) await accountLoad;
if (nav.FooterMenuItems.Count != 2 || nav.SelectedItem != nav.FooterMenuItems[0]) throw new InvalidOperationException("Account navigation is not selected in the footer.");
var gameAvatar = App.Accounts.State.Avatar;
foreach (var open in new[] { true, false })
{
nav.PaneDisplayMode = NavigationViewPaneDisplayMode.LeftCompact;
nav.IsPaneOpen = open;
await Task.Delay(200);
VerifyAvatarLayout(shell, nav, accountPage, gameAvatar);
}
checks.Add("footer-avatar-image-layout-in-expanded-and-compact-navigation");
// Exercise a changed avatar after the shell's bindings have already initialized.
App.Accounts.State.Avatar = new WriteableBitmap(2, 2);
VerifyAvatarLayout(shell, nav, accountPage, App.Accounts.State.Avatar);
App.Accounts.State.Avatar = gameAvatar;
VerifyAvatarLayout(shell, nav, accountPage, gameAvatar);
nav.PaneDisplayMode = NavigationViewPaneDisplayMode.Auto;
checks.Add("footer-and-account-card-follow-avatar-changes");
App.Accounts.State.CurrencyGrantEnabled = false; App.Accounts.State.ItemGrantEnabled = false; App.Accounts.State.RegistrationEnabled = false;
if (App.Accounts.State.CurrencyVisibility != Visibility.Collapsed || App.Accounts.State.ItemVisibility != Visibility.Collapsed) throw new InvalidOperationException("Forbidden grant controls remain visible.");
var loginDialog = new Views.Dialogs.LoginDialog(); var registerDialog = new Views.Dialogs.RegisterDialog();
if (!string.IsNullOrEmpty(loginDialog.SecondaryButtonText) || !string.IsNullOrEmpty(registerDialog.PrimaryButtonText)) throw new InvalidOperationException("Disabled registration remains visible.");
await App.Accounts.InitializeAsync();
await App.Accounts.RefreshAsync();
if (App.Accounts.State.CurrencyVisibility != Visibility.Visible || App.Accounts.State.ItemVisibility != Visibility.Visible) throw new InvalidOperationException("Allowed grant controls are not restored.");
navigation.NavigateTo<ItemCatalogPage>();
var itemPage = (ItemCatalogPage)navigation.NavigationService.Frame!.Content;
if (itemPage.ViewModel.LoadCommand.ExecutionTask is Task catalogLoad) await catalogLoad;
if (itemPage.ViewModel.LastError is not null) throw new InvalidOperationException(itemPage.ViewModel.LastError);
if (AppPath.Argument("verify-dialogs") != "true") foreach (var width in new[] { 1400d, 1024d, 800d }) { itemPage.Measure(new Size(width, 900)); itemPage.Arrange(new Rect(0, 0, width, 900)); itemPage.UpdateLayout(); }
checks.Add("separate-registration-login-and-grants");
if (AppPath.Argument("verify-dialogs") == "true")
{
await SuggestionVerification.VerifyAsync((FrameworkElement)App.MainWindow.Content, new ItemCatalogPageViewModel().Suggestions);
checks.Add("native-AutoSuggestBox: nullable/invalid/ambiguous choices, exact paths, stale-response protection, context changes, failures, real catalog API");
}
await VerifyUnifiedInventoryAsync(navigation, checks);
if (AppPath.Argument("verify-dialogs") == "true") await VerifyQuestCreationAsync(navigation, checks);
await VerifyOverviewActionsAsync(navigation, checks);
checks.Add("game-avatar-and-footer-account-selection");
checks.Add("permission-controlled-visibility-and-auth-dialog-construction");
await VerifyEditorsAsync(navigation, checks);
await VerifyRuntimeAsync(navigation, checks);
await App.Accounts.LogoutAsync();
if (await credentialStore.ReadAsync(api) is not null) throw new InvalidOperationException("Logout retained saved credentials.");
var signedOut = new PlayerAccountService();
try
{
await signedOut.InitializeAsync();
if (signedOut.State.IsLoggedIn) throw new InvalidOperationException("Explicit logout was undone by automatic login.");
}
finally { signedOut.Stop(); }
checks.Add("logout-clears-remembered-account-and-prevents-auto-login");
if (App.Accounts.State.IsLoggedIn || App.Accounts.State.Platinum != 0) throw new InvalidOperationException("Logout retained account data.");
var accountItem = (NavigationViewItem)nav.FooterMenuItems[0];
if (accountItem.Icon is not FontIcon || accountItem.Content as string != UiText.Translate("登录账号"))
throw new InvalidOperationException("Logout did not restore the guest footer icon and label.");
checks.Add("footer-guest-icon-restored-after-logout");
SystemProfile.SaveProfile();
foreach (var file in Directory.GetFiles(AppPath.ProfilesDirectory, "*", SearchOption.AllDirectories))
if (File.ReadAllText(file).Contains(password, StringComparison.Ordinal)) throw new InvalidOperationException("A profile retained the test password.");
checks.Add("player-logout-clears-session-and-password-is-not-persisted");
var previous = SystemProfile.Theme;
foreach (var theme in new[] { ElementTheme.Light, ElementTheme.Dark, ElementTheme.Default })
AppThemeHelper.ChangeTheme(theme);
AppThemeHelper.ChangeTheme(previous);
SystemProfile.SaveProfile();
if (BindingErrors.Count > 0) throw new InvalidOperationException(string.Join("\n", BindingErrors));
checks.Add("theme-and-isolated-XFEProfile-save");
if (AppPath.Argument("verify-dialogs") == "true") checks.Add($"native-form-dialogs: {DialogVerification.CompletedCount} opens, button actions and detachments; shared button styling");
if (AppPath.Argument("verify-visible") == "true")
{
// Reuse only the generated account on the isolated loopback server.
// This leaves the real UI open for a separate, observed manual/automation pass.
await App.Accounts.LoginAsync(email, password);
navigation.NavigateTo<EditorPage>(InventoryNavigation.Route("Suits"));
}
}
catch (Exception ex) { error = ex.ToString(); AppPath.LogException(ex); }
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(reportPath))!);
await File.WriteAllTextAsync(reportPath, JsonSerializer.Serialize(new
{
application = "Player", passed = error is null, checks, error,
scope = AppPath.Argument("verify-dialogs") == "true"
? "Isolated real API, native WinUI modal open/save/cancel, persistence, navigation, bindings, styles and layout."
: "Hidden XAML construction, navigation, bindings and layout; not visual acceptance."
}, new JsonSerializerOptions { WriteIndented = true }));
}
private static async Task VerifyEditorsAsync(INavigationViewService navigation, List<string> checks)
{
await App.Accounts.GrantAsync("PrimeTokens", 12); await App.Accounts.GrantAsync("CrewShipFusionPoints", 9); await App.Accounts.GrantAsync("PrimeTokens", -2);
if (App.Accounts.State.RegalAya != 10 || App.Accounts.State.Dirac != 9) throw new InvalidOperationException("Additional currency balances did not update.");
const string type = "/Lotus/Upgrades/Mods/Rifle/WeaponDamageAmountMod";
await App.Accounts.GrantItemAsync(type, 1);
var language = SystemProfile.ItemLanguage;
try
{
SystemProfile.ItemLanguage = "en";
var found = await App.Accounts.CatalogAsync(type, "", 0);
if (!found.Items.Any(x => x.Type == type && x.Name == "Serration")) throw new InvalidOperationException("Localized path search failed across the HTTP transport.");
navigation.NavigateTo<EditorPage>(); var page = (EditorPage)navigation.NavigationService.Frame!.Content; var vm = page.ViewModel;
if (vm.LoadCommand.ExecutionTask is Task load) await load;
vm.Category = vm.Categories.First(x => x.Key == "RawUpgrades"); await vm.RefreshCommand.ExecuteAsync(null);
vm.SelectedItem = vm.Items.First(x => x.Name == "Serration"); await vm.OpenItemCommand.ExecuteAsync(null);
if (vm.LastError is not null || vm.Fields.Count == 0 || vm.ImportVisibility != Visibility.Visible || vm.ExportVisibility != Visibility.Visible)
throw new InvalidOperationException("Authorized editor form failed: " + vm.LastError);
if (AppPath.Argument("verify-dialogs") != "true") foreach (var width in new[] { 1400d, 1024d, 800d }) { page.Measure(new Size(width, 900)); page.Arrange(new Rect(0, 0, width, 900)); page.UpdateLayout(); }
var rankField = vm.Fields.First(x => x.Key == "rank"); rankField.Value = new JValue(7);
var view = await App.Accounts.ReadEditorAsync("RawUpgrades", "", type, 0);
await App.Accounts.SaveEditorAsync(new JObject { ["version"] = view["version"]!, ["category"] = "RawUpgrades", ["item"] = type, ["action"] = "mod.rank", ["values"] = new JObject { ["rank"] = 3 } });
await vm.CheckChangesAsync();
if (!vm.HasExternalChanges || vm.CanSave || !vm.HasChangeNotice || rankField.Value.Value<int>() != 7 || !ReferenceEquals(rankField, vm.Fields.First(x => x.Key == "rank")))
throw new InvalidOperationException("Concurrent inventory change discarded unsaved input or left saving enabled.");
await vm.RefreshCommand.ExecuteAsync(null);
if (vm.HasExternalChanges || vm.HasChangeNotice || vm.LastError is not null) throw new InvalidOperationException("Explicit refresh did not resolve the stale editor.");
// Recreate a raw MOD from another API caller and let the clean editor follow that change.
await App.Accounts.GrantItemAsync(type, 1); await vm.CheckChangesAsync();
if (!vm.Items.Any(x => x.Name == "Serration")) throw new InvalidOperationException("Clean editor failed to follow an external inventory change.");
checks.Add("editor-change-detection-preserves-unsaved-input-and-refreshes-clean-views");
var archive = await App.Accounts.ExportArchiveAsync();
var imported = await App.Accounts.ImportArchiveAsync(archive.Value<string>("version")!, new JObject { ["PrimeTokens"] = 14 });
if (string.IsNullOrEmpty(imported.Value<string>("backup"))) throw new InvalidOperationException("Archive import did not return its backup reference.");
await App.Accounts.RefreshAsync(); if (App.Accounts.State.RegalAya != 14) throw new InvalidOperationException("Archive currency was not applied.");
navigation.NavigateTo<RivenPage>(); var rivenPage = (RivenPage)navigation.NavigationService.Frame!.Content;
if (rivenPage.ViewModel.LoadCommand.ExecutionTask is Task rivenLoad) await rivenLoad;
if (rivenPage.ViewModel.LastError is not null || rivenPage.ViewModel.Families.Count != 7 || rivenPage.ViewModel.Rows.Count != 2)
throw new InvalidOperationException("Authorized riven page failed: " + rivenPage.ViewModel.LastError);
await RivenVerification.VerifyAsync(rivenPage, rivenPage.ViewModel.Rows, () => rivenPage.ViewModel.CalculateCommand.ExecuteAsync(null), () => rivenPage.ViewModel.Name, AppPath.Argument("verify-dialogs") == "true");
checks.Add("riven-instance-name-colored-stats-numeric-suggestions-and-live-preview");
if (AppPath.Argument("verify-dialogs") != "true") foreach (var width in new[] { 1400d, 1024d, 800d }) { rivenPage.Measure(new Size(width, 900)); rivenPage.Arrange(new Rect(0, 0, width, 900)); rivenPage.UpdateLayout(); }
checks.Add("authorized-editor-riven-localized-path-query-archive-and-five-currencies");
}
finally { SystemProfile.ItemLanguage = language; }
}
private static async Task VerifyReadOnlyInventoryAsync(string reportPath)
{
var checks = new List<string>(); string? error = null;
try
{
var api = AppPath.Argument("verify-api");
if (AppPath.Argument("profile-root") is null || !Uri.TryCreate(api, UriKind.Absolute, out var endpoint) || !endpoint.IsLoopback)
throw new InvalidOperationException("Read-only checks require an isolated local API and profile.");
await App.Service.InitializeAsync(); App.Service.State.ServerUrl = api!;
var email = Guid.NewGuid().ToString("N") + "@example.invalid"; var password = Guid.NewGuid().ToString("N");
await App.Accounts.RegisterAsync(email, password, "ReadOnly" + Guid.NewGuid().ToString("N")[..8]);
await App.Accounts.LoginAsync(email, password);
var state = App.Accounts.State;
if (state.EditingEnabled || state.ItemGrantEnabled || state.CurrencyGrantEnabled) throw new InvalidOperationException("Read-only fixture permissions are not restricted.");
var navigation = ServiceManager.GetGlobalService<INavigationViewService>()!;
foreach (var section in InventoryNavigation.All.Where(x => x.Key is not ("riven" or "catalog") && !InventoryNavigation.RequiresEditing(x.Key)))
{
navigation.NavigateTo<EditorPage>(InventoryNavigation.Route(section.Key));
var vm = ((EditorPage)navigation.NavigationService.Frame!.Content).ViewModel;
if (vm.LoadCommand.ExecutionTask is Task load) await load;
if (vm.QuestCreationVisibility != Visibility.Collapsed || vm.LastError is not null || vm.Category?.Key != section.Key || vm.CatalogToggleVisibility != Visibility.Collapsed || vm.ActionVisibility != Visibility.Collapsed || vm.BatchVisibility != Visibility.Collapsed || vm.ImportVisibility != Visibility.Collapsed || vm.ExportVisibility != Visibility.Collapsed)
throw new InvalidOperationException("Read-only category or visibility failed: " + section.Key + ": " + vm.LastError);
if (section.Key == "Ships" && !vm.Items.Any()) throw new InvalidOperationException("The read-only view lost the starter landing craft.");
await vm.ShowCatalogCommand.ExecuteAsync(null);
if (vm.IsCatalogMode) throw new InvalidOperationException("Read-only account entered item creation mode.");
}
var tree = (NavigationViewItem)((AppShellPage)App.MainWindow.Content).FindName("InventoryRoot");
void AssertHidden(IEnumerable<NavigationViewItem> nodes)
{
foreach (var node in nodes)
{
var key = (string)node.Tag;
if ((InventoryNavigation.RequiresEditing(key) || key is "catalog" or "riven") && node.Visibility != Visibility.Collapsed)
throw new InvalidOperationException("Unauthorized navigation remains visible: " + key);
AssertHidden(node.MenuItems.OfType<NavigationViewItem>());
}
}
AssertHidden(tree.MenuItems.OfType<NavigationViewItem>());
navigation.NavigateTo<InventoryPage>();
var overview = (InventoryPage)navigation.NavigationService.Frame!.Content;
if (overview.ViewModel.LoadCommand.ExecutionTask is Task overviewLoad) await overviewLoad;
overview.UpdateLayout();
var overviewActions = (OverviewActionsView)overview.FindName("OverviewActions");
for (var attempt = 0; attempt < 100 && !ReferenceEquals(overviewActions.Model, overview.ViewModel.OverviewActions); attempt++) await Task.Delay(10);
if (!ReferenceEquals(overviewActions.Model, overview.ViewModel.OverviewActions) || overview.ViewModel.OverviewActions.Actions.Count != 0 || overviewActions.Visibility != Visibility.Collapsed)
throw new InvalidOperationException("Unauthorized overview actions remain visible.");
await App.Accounts.LogoutAsync();
checks.Add("read-only-inventory: all 47 categories, starter landing craft, no grant/editor/archive controls or unauthorized navigation");
if (BindingErrors.Count > 0) throw new InvalidOperationException(string.Join("\n", BindingErrors));
}
catch (Exception ex) { error = ex.ToString(); AppPath.LogException(ex); }
await File.WriteAllTextAsync(reportPath, JsonSerializer.Serialize(new { application = "PlayerReadOnly", passed = error is null, checks, error, scope = "Isolated real API with all editor/item/currency grants disabled; native WinUI view models and bindings." }, new JsonSerializerOptions { WriteIndented = true }));
}
private static async Task VerifyOverviewActionsAsync(INavigationViewService navigation, List<string> checks)
{
navigation.NavigateTo<InventoryPage>();
var page = (InventoryPage)navigation.NavigationService.Frame!.Content;
if (page.ViewModel.LoadCommand.ExecutionTask is Task load) await load;
await OverviewActionsVerification.VerifyAsync((OverviewActionsView)page.FindName("OverviewActions"), page.ViewModel.OverviewActions,
async () => (JObject)(await App.Accounts.ExportArchiveAsync())["inventory"]!, AppPath.Argument("verify-dialogs") == "true");
await VerifyOverviewPermissionChangesAsync(page);
if (InventoryNavigation.All.Any(x => x.Key == "progress")) throw new InvalidOperationException("The old progress item-list navigation remains.");
checks.Add("overview-actions: 16 authorized buttons, grouped cards, native cancel and execute, syndicate suggestion, API readback, account-switch guard");
}
private static async Task VerifyOverviewPermissionChangesAsync(InventoryPage page)
{
var origin = new Uri(AppPath.Argument("verify-api")!);
if (!origin.IsLoopback) throw new InvalidOperationException("Permission verification requires an isolated loopback server.");
var config = JObject.Parse(await File.ReadAllTextAsync(Path.Combine(AppPath.Argument("root")!, "server.json")));
using var client = new System.Net.Http.HttpClient { BaseAddress = origin };
client.DefaultRequestHeaders.Authorization = new("Bearer", config.Value<string>("AdminToken")!);
async Task UpdateAsync(bool enabled)
{
var current = JObject.Parse(await client.GetStringAsync("control/v1/editor/permissions"));
using var response = await client.PostAsync("control/v1/editor/permissions", new System.Net.Http.StringContent(
new JObject { ["version"] = current["version"]!.DeepClone(), ["values"] = new JObject { ["unlock.intrinsics"] = enabled } }.ToString(), System.Text.Encoding.UTF8, "application/json"));
response.EnsureSuccessStatusCode();
await App.Accounts.RefreshAsync();
for (var i = 0; i < 250 && (page.ViewModel.OverviewActions.IsBusy || page.ViewModel.OverviewActions.Actions.Count != (enabled ? 16 : 15)); i++) await Task.Delay(20);
}
var model = page.ViewModel.OverviewActions;
var pending = await model.PrepareAsync("unlock.intrinsics") ?? throw new InvalidOperationException(model.Message);
var before = await App.Accounts.ExportArchiveAsync();
try
{
await UpdateAsync(false);
if (model.Actions.Count != 15 || ((OverviewActionsView)page.FindName("OverviewActions")).ActionButtons.Any(x => (string)x.Tag == "unlock.intrinsics"))
throw new InvalidOperationException("Revoking one permission did not remove its overview button.");
await model.ExecuteAsync(pending);
if (model.Message.Length == 0 || !JToken.DeepEquals(before["inventory"], (await App.Accounts.ExportArchiveAsync())["inventory"]))
throw new InvalidOperationException("Revoked prepared action modified the save.");
}
finally { await UpdateAsync(true); }
if (model.Actions.Count != 16) throw new InvalidOperationException("Restoring permission did not restore the overview button.");
}
private static async Task VerifyQuestCreationAsync(INavigationViewService navigation, List<string> checks)
{
navigation.NavigateTo<EditorPage>(InventoryNavigation.Route("QuestKeys"));
var page = (EditorPage)navigation.NavigationService.Frame!.Content;
var vm = page.ViewModel;
if (vm.LoadCommand.ExecutionTask is Task load) await load;
await QuestEditorVerification.VerifyAsync(page, (FormDialogButton)page.FindName("AddQuestButton"), (AutoSuggestBox)page.FindName("OwnedSearch"),
() => vm.QuestFields, () => vm.Items, () => vm.IsIdle, () => vm.LastError,
async () => (JObject)(await App.Accounts.ExportArchiveAsync())["inventory"]!);
checks.Add("missing-quest: native suggestion and add dialog, API persistence preserves progress; live name/path/no-match/clear list search");
}
private static async Task VerifyUnifiedInventoryAsync(INavigationViewService navigation, List<string> checks)
{
var shell = (AppShellPage)App.MainWindow.Content;
var tree = (NavigationViewItem)shell.FindName("InventoryRoot");
if (tree.MenuItems.Count != InventoryNavigation.Sections.Count + 1) throw new InvalidOperationException("Inventory tree is incomplete.");
var available = (await App.Accounts.ReadEditorAsync("Suits", "", null, 0))["categories"]!.Select(x => (string)x["key"]!).ToHashSet();
foreach (var section in InventoryNavigation.All.Where(x => available.Contains(x.Key)))
{
navigation.NavigateTo<EditorPage>(InventoryNavigation.Route(section.Key));
var page = (EditorPage)navigation.NavigationService.Frame!.Content;
var vm = page.ViewModel;
if (vm.LoadCommand.ExecutionTask is Task load) await load;
if (vm.LastError is not null || vm.Category?.Key != section.Key) throw new InvalidOperationException(section.Key + ": " + vm.LastError);
if (InventoryNavigation.RequiresEditing(section.Key) && vm.CatalogToggleVisibility != Visibility.Collapsed) throw new InvalidOperationException("An item grant was offered for a progress category.");
if (AppPath.Argument("verify-dialogs") != "true") { page.Measure(new Size(1024, 900)); page.Arrange(new Rect(0, 0, 1024, 900)); } page.UpdateLayout();
}
navigation.NavigateTo<EditorPage>(InventoryNavigation.Route("Suits"));
var editor = ((EditorPage)navigation.NavigationService.Frame!.Content).ViewModel;
if (editor.LoadCommand.ExecutionTask is Task loaded) await loaded;
await editor.ShowCatalogCommand.ExecuteAsync(null);
editor.Catalog.Query = "/Lotus/Powersuits/Excalibur/Excalibur"; await editor.Catalog.SearchCommand.ExecuteAsync(null);
editor.Catalog.SelectedItem = editor.Catalog.Items.First(x => x.Type == editor.Catalog.Query);
await editor.Catalog.GiveCommand.ExecuteAsync(null); await editor.ShowOwnedCommand.ExecuteAsync(null);
if (editor.LastError is not null || editor.IsCatalogMode || !editor.Items.Any()) throw new InvalidOperationException("Integrated player item creation failed: " + editor.LastError);
editor.SelectedItem = editor.Items.First(); await editor.OpenItemCommand.ExecuteAsync(null);
if (editor.Actions.Count == 0) throw new InvalidOperationException("The newly added Warframe cannot be edited.");
editor.Query = "Excalibur"; await editor.RefreshCommand.ExecuteAsync(null);
editor.SelectedItem = editor.Items.First(); var selectedKey = editor.SelectedItem.Key;
await VerifyInventoryPermissionRecoveryAsync((EditorPage)navigation.NavigationService.Frame.Content);
checks.Add("inventory-permission-recovery: editing to readonly and back via revision polling, visible explanation, same query and selected suit, no manual refresh");
editor.EditItemCommand.Execute(null);
if (navigation.NavigationService.Frame!.Content is not EquipmentPage details) throw new InvalidOperationException("Editing did not navigate to the dedicated page.");
if (details.ViewModel.LoadCommand.ExecutionTask is Task detailLoad) await detailLoad;
if (details.ViewModel.LastError is not null) throw new InvalidOperationException(details.ViewModel.LastError);
var liveInput = AppPath.Argument("verify-dialogs") == "true";
await EquipmentEditorVerification.VerifyAsync(details, (EquipmentEditorView)details.FindName("EditorView"), 2718, liveInput);
checks.Add(liveInput ? "ability-AutoSuggestBox: loaded input, name/path candidates, invalid input rejected, native query and save, API readback" : "ability-AutoSuggestBox: construction only; live input requires --verify-dialogs");
checks.Add(liveInput ? "multiple-abilities: four native suggestions, save/reload, independent configurations, restore original skills" : "multiple-abilities: four searchable slots constructed");
await EquipmentEditorVerification.VerifySynchronizationAsync(details.ViewModel.Editor,
async () => { await App.Accounts.GrantAsync("RegularCredits", 1); });
await VerifyEquipmentPermissionChangesAsync(details);
await EquipmentEditorVerification.VerifyExaltedAsync(details, (EquipmentEditorView)details.FindName("EditorView"),
async () => { foreach (var type in new[] { "/Lotus/Upgrades/Mods/Pistol/WeaponDamageAmountMod", "/Lotus/Upgrades/Mods/Warframe/AvatarHealthMaxMod", "/Lotus/Upgrades/Mods/Warframe/AvatarArmourMod",
"/Lotus/Upgrades/Mods/Pistol/WeaponFreezeDamageMod", "/Lotus/Upgrades/Mods/Pistol/WeaponToxinDamageMod", "/Lotus/Upgrades/Mods/Pistol/WeaponFireRateMod", "/Lotus/Upgrades/Mods/Pistol/WeaponCritChanceMod" })
await App.Accounts.GrantItemAsync(type, 1); },
async () => { var current = (EquipmentPage)navigation.NavigationService.Frame!.Content; if (current.ViewModel.LoadCommand.ExecutionTask is Task load) await load; return (current, (EquipmentEditorView)current.FindName("EditorView")); },
() => navigation.NavigationService.GoBack(), liveInput);
checks.Add("exalted-equipment: host-to-Glory shared card board, Warframe/Glory install/swap/uninstall, raw-to-instance conversion, C save, independent B, back retains host");
checks.Add("image-loading: native WinUI PNG decode, cache miss/hit, resource icon, stale request protection, no wrong-thread dependency-property reads");
checks.Add("mod-search: original descriptions, Viral includes Cold/Toxin, matching suggestions, AND keywords, cancelled stale request cannot replace results");
navigation.NavigationService.GoBack();
if (navigation.NavigationService.Frame.Content is not EditorPage returned) throw new InvalidOperationException("Native Back did not return to the inventory list.");
if (returned.ViewModel.ResumeListCommand.ExecutionTask is Task resumed) await resumed;
if (returned.ViewModel.Query != "Excalibur" || returned.ViewModel.SelectedItem?.Key != selectedKey) throw new InvalidOperationException("Back lost the inventory query or selected item.");
checks.Add("equipment-SelectorBar: dedicated page, native save/reset, cross-section drafts, API persistence, external conflict protection, back retains list context");
checks.Add("equipment-permission-changes: filtered sections, simultaneous inventory conflict preserves draft, revoke clears controls, restore reloads shared editor");
foreach (var type in new[] { EquipmentEditorVerification.FetchPetFixture, XFEWarframe.Mods.PetFetchMod.Type })
await App.Accounts.GrantItemAsync(type, 1);
navigation.NavigateTo<EditorPage>(InventoryNavigation.Route("KubrowPets"));
var pets = ((EditorPage)navigation.NavigationService.Frame.Content).ViewModel;
if (pets.LoadCommand.ExecutionTask is Task petLoad) await petLoad;
pets.SelectedItem = pets.Items.First(); pets.EditItemCommand.Execute(null);
if (navigation.NavigationService.Frame.Content is not EquipmentPage petDetails) throw new InvalidOperationException("Pet editing did not open the shared equipment page.");
if (petDetails.ViewModel.LoadCommand.ExecutionTask is Task petDetailLoad) await petDetailLoad;
await EquipmentEditorVerification.VerifyPetAsync(petDetails, (EquipmentEditorView)petDetails.FindName("EditorView"));
navigation.NavigationService.GoBack();
checks.Add("pet-fetch: shared ten-slot board at three widths, 300m keyword suggestions, full-rank owned card, install/move/uninstall/save, independent configs");
App.Accounts.State.ItemGrantEnabled = false;
if (editor.CatalogToggleVisibility != Visibility.Collapsed) throw new InvalidOperationException("Revoked item grant remains visible.");
await editor.ShowCatalogCommand.ExecuteAsync(null);
if (editor.IsCatalogMode) throw new InvalidOperationException("A hidden item grant can still be selected.");
await App.Accounts.RefreshAsync();
checks.Add($"unified-inventory: {available.Count} category routes, scoped item creation, owned equipment editing, permission visibility");
}
private static async Task VerifyEquipmentPermissionChangesAsync(EquipmentPage page)
{
// Administrative transport exists only inside this opt-in, isolated desktop test.
var origin = new Uri(AppPath.Argument("verify-api")!);
if (!origin.IsLoopback) throw new InvalidOperationException("Permission verification requires the isolated loopback server.");
var config = JObject.Parse(await File.ReadAllTextAsync(Path.Combine(AppPath.Argument("root")!, "server.json")));
using var client = new System.Net.Http.HttpClient { BaseAddress = origin };
client.DefaultRequestHeaders.Authorization = new("Bearer", config.Value<string>("AdminToken")!);
var before = JObject.Parse(await client.GetStringAsync("control/v1/editor/permissions"));
var saved = new JObject(before["fields"]!.Select(x => new JProperty(x.Value<string>("key")!, x.Value<bool>("value"))));
async Task UpdateAsync(JObject values)
{
var current = JObject.Parse(await client.GetStringAsync("control/v1/editor/permissions"));
using var response = await client.PostAsync("control/v1/editor/permissions", new System.Net.Http.StringContent(
new JObject { ["version"] = current["version"]!.DeepClone(), ["values"] = values }.ToString(), System.Text.Encoding.UTF8, "application/json"));
response.EnsureSuccessStatusCode();
}
var model = page.ViewModel.Editor;
try
{
var field = model.Actions.Single(x => x.Key == "experience").Fields.Single();
var draft = field.Value.Value<long>() + 321; field.Value = new JValue(draft);
var partial = new JObject(saved.Properties().Select(x => new JProperty(x.Name, x.Name == "experience")));
await UpdateAsync(partial); await App.Accounts.GrantAsync("RegularCredits", 1);
await PollEquipmentUntilAsync(model, () => model.Tabs.Count == (model.Related.Count > 0 ? 2 : 1) && model.Actions.All(x => x.Key is "experience" or "max"));
if (model.Actions.Any(x => x.Key is not ("experience" or "max")) || model.Tabs.Any(x => x.Key is not ("basic" or "exalted")) || !model.HasConflict ||
model.Actions.Single(x => x.Key == "experience").Fields.Single().Value.Value<long>() != draft)
throw new InvalidOperationException($"Partial permissions and a concurrent inventory change did not preserve an authorized draft safely. Actions={string.Join(',', model.Actions.Select(x => x.Key))}; tabs={model.Tabs.Count}; conflict={model.HasConflict}; busy={model.IsBusy}; expectedDraft={draft}; actualDraft={model.Actions.FirstOrDefault(x => x.Key == "experience")?.Fields.FirstOrDefault()?.Value}; message={model.Message}");
partial["experience"] = false; await UpdateAsync(partial);
await PollEquipmentUntilAsync(model, () => model.Tabs.Count == 0);
if (model.Tabs.Count != 0 || ((EquipmentEditorView)page.FindName("EditorView")).Selector.Items.Count != 0)
throw new InvalidOperationException("Revoked permissions left equipment controls visible.");
}
finally
{
await UpdateAsync(saved); await PollEquipmentUntilAsync(model, () => model.Tabs.Count >= 6);
}
if (model.HasMessage || model.Tabs.Count < 6) throw new InvalidOperationException("Restored permissions did not reload the shared equipment editor.");
}
private static async Task VerifyRuntimeAsync(INavigationViewService navigation, List<string> checks)
{
var game = Path.Combine(AppPath.DataDirectory, "RuntimeFixture"); var previous = App.Service.State.GameDirectory;
Directory.CreateDirectory(game); var logs = new RuntimeLogBuffer(); logs.Add("Isolated C# runtime integration fixture"); RuntimeSettings? applied = null;
await using var runtime = new RuntimeControlServer(game, new ClientConfiguration { BuildLabel = "fixture", ServerName = "UI verification" }, logs, value => applied = value, 0);
try
{
App.Service.State.GameDirectory = game;
navigation.NavigateTo<RuntimePage>(); var page = (RuntimePage)navigation.NavigationService.Frame!.Content; var vm = page.ViewModel;
if (vm.LoadCommand.ExecutionTask is Task load) await load;
if (vm.LastError is not null || !vm.IsConnected || vm.Logs.Count == 0) throw new InvalidOperationException("Runtime page did not connect: " + vm.LastError);
vm.ShowBranding = false; vm.LogRequests = true; await vm.SaveCommand.ExecuteAsync(null);
if (vm.LastError is not null || applied is null || !applied.DisableOverlay || !applied.ClientHttpLogging || !File.Exists(Path.Combine(game, "XFEWarframe", "runtime-settings.json")))
throw new InvalidOperationException("Runtime page did not apply and save settings: " + vm.LastError);
if (AppPath.Argument("verify-dialogs") != "true") foreach (var width in new[] { 1400d, 1024d, 800d }) { page.Measure(new Size(width, 900)); page.Arrange(new Rect(0, 0, width, 900)); page.UpdateLayout(); }
navigation.NavigateTo<SettingPage>(); if (vm.IsConnected) throw new InvalidOperationException("Runtime page retained its connection after navigation.");
checks.Add("runtime-page-real-loopback-status-logs-settings-save-and-disconnect-fixture-not-game");
}
finally { App.Service.State.GameDirectory = previous; }
}
private static void VerifyAvatarLayout(AppShellPage shell, NavigationView nav, AccountPage accountPage, ImageSource avatar)
{
if (AppPath.Argument("verify-dialogs") != "true") { shell.Measure(new Size(1400, 900)); shell.Arrange(new Rect(0, 0, 1400, 900)); }
shell.UpdateLayout();
var item = (NavigationViewItem)nav.FooterMenuItems[0];
var image = Descendants<Image>(item).FirstOrDefault(x => ReferenceEquals(x.Source, avatar));
if (image is null || image.ActualWidth <= 0 || image.ActualHeight <= 0 || image.Visibility != Visibility.Visible)
throw new InvalidOperationException($"Footer avatar has no visible image (pane open: {nav.IsPaneOpen}).");
var bounds = image.TransformToVisual(nav).TransformBounds(new Rect(0, 0, image.ActualWidth, image.ActualHeight));
const double tolerance = 0.1; // DPI transforms introduce fractional-pixel rounding.
if (Math.Abs(bounds.Width - 24) > tolerance || Math.Abs(bounds.Height - 24) > tolerance || bounds.X < -tolerance || bounds.Right > nav.ActualWidth + tolerance || bounds.Y < -tolerance || bounds.Bottom > nav.ActualHeight + tolerance)
throw new InvalidOperationException($"Footer avatar is clipped or outside the navigation pane: image={bounds}, navigation={nav.ActualWidth}x{nav.ActualHeight}, open={nav.IsPaneOpen}.");
if (!Descendants<PersonPicture>(accountPage).Any(x => ReferenceEquals(x.ProfilePicture, avatar)))
throw new InvalidOperationException("Footer avatar and account card use different images.");
}
private static IEnumerable<T> Descendants<T>(DependencyObject parent) where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T match) yield return match;
foreach (var descendant in Descendants<T>(child)) yield return descendant;
}
}
}