Open-source Xbox-inspired desktop launcher for Xodus on Linux
TypeScript
fix(backend): improve component update diagnostics and recovery
Nexus Maintainera31def7a5a9c
diff --git a/scripts/BACKEND.md b/scripts/BACKEND.mdindex d1fa273..ebb2f54 100644--- a/scripts/BACKEND.md+++ b/scripts/BACKEND.md@@ -81,6 +81,16 @@ failure record carries `committed`, so a failure before `current.json`publication is distinguishable from an activation that needs attention. Theserecords never contain messages, paths, URLs, tokens, accounts or child output.+Component update orchestration (`Update all components`) uses operation+`component-update` in the same private log. Only failures are recorded:+`plan-blocked` (the check was requested while another update batch holds the+launcher), `plan-discovery` (a component's read-only release discovery failed;+`component` is `backend`, `runtime` or `launcher`, and `status` is present only+when the failure carried an HTTP status) and `apply-blocked` (the update start+was rejected by the activity gate or another running batch). These records never+contain messages, paths, URLs, tokens or accounts, and they never replace the+installer's own `update` failure, start or exit records.+## Package selection`resolve-package PRODUCT --json --market US` reads public Store metadata withoutdiff --git a/src/main/backend-diagnostics.ts b/src/main/backend-diagnostics.tsindex b99e243..0de9264 100644--- a/src/main/backend-diagnostics.ts+++ b/src/main/backend-diagnostics.ts@@ -9,7 +9,7 @@ import { transferDiagnostic, transferStages } from '../shared/transfer-failure.jimport { keyringSteps, keyringFailures, keyringBusErrors, type KeyringDiagnostic } from './keyring-diagnostic.js';import { backendPrerequisiteFailure } from './backend-prerequisites.js';-const operations = new Set(['keyring', 'account', 'profile', 'achievements', 'library', 'login', 'logout', 'streaming', 'download', 'license', 'run', 'resolve-package', 'service', 'probe', 'social', 'update']);+const operations = new Set(['keyring', 'account', 'profile', 'achievements', 'library', 'login', 'logout', 'streaming', 'download', 'license', 'run', 'resolve-package', 'service', 'probe', 'social', 'update', 'component-update']);// Fixed installer phases and failure codes. They are never derived from// messages, paths, URLs or child output.const updateStages = new Set([@@ -19,6 +19,10 @@ const updateStages = new Set(['update-file-mismatch', 'update-binary', 'update-permission', 'update-validate','update-commit', 'update-discovery', 'update-check-failed', 'update-cleanup', 'update-notify',]);+// Fixed component-update orchestration failures. They describe the plan/apply+// entry, never an installer step, and never carry free-form text.+const componentUpdateStages = new Set(['plan-blocked', 'plan-discovery', 'apply-blocked']);+const componentUpdateComponents = new Set(['backend', 'runtime', 'launcher']);const socialHttpStages = new Set(['friends-http','conversation-http','send-http','chat-policy-http','chat-device-http','chat-context-http','chat-xsts-http','chat-privacy-http']);const socialStages = new Set([...socialHttpStages,'conversation-response','friends-response',@@ -38,6 +42,7 @@ const stages = new Set([...contentLicenseStages,...transferStages,...updateStages,+ ...componentUpdateStages,'keyring-unavailable', 'keyring-invalid-data', 'keyring-missing-data', 'keyring-write-verification', 'credential-io', 'device-authentication','stored-account', 'account-changed', 'stored-device', 'device-token', 'stored-user', 'user-token', 'http-client','store-ticket', 'store-ticket-refused', 'store-ticket-type', 'store-ticket-format', 'market', 'account-check',@@ -51,7 +56,7 @@ const stages = new Set([type Event = 'start' | 'exit' | 'spawn-error' | 'diagnostic' | 'validation' | 'failure';type Context = { launcher?: string; backend?: string; source?: string };type SocialReceiptDiagnostic = {hasMessageId:boolean;hasConversationId:boolean;nudge:'absent'|'false'|'true'|'invalid';hasError:boolean};-type RecordData = { operation: string; event: Event; stage?: string; status?: number; skipped?: number; code?: number; serviceCode?: string; signal?: string; elapsedMs?: number; committed?: boolean; keyring?: KeyringDiagnostic; socialReceipt?:SocialReceiptDiagnostic };+type RecordData = { operation: string; event: Event; stage?: string; component?: 'backend' | 'runtime' | 'launcher'; status?: number; skipped?: number; code?: number; serviceCode?: string; signal?: string; elapsedMs?: number; committed?: boolean; keyring?: KeyringDiagnostic; socialReceipt?:SocialReceiptDiagnostic };const version = (value?: string) => value && /^\d{1,4}\.\d{1,4}\.\d{1,4}$/.test(value) ? value : 'unknown';/** Allowlisted metadata only. Never persists child output, argv, auth frames or identifiers. */@@ -94,7 +99,10 @@ export class BackendDiagnostics {}record(data: RecordData): void {if (!operations.has(data.operation) || !['start', 'exit', 'spawn-error', 'diagnostic', 'validation', 'failure'].includes(data.event)- || (data.event === 'failure' && data.operation !== 'update') || this.pending >= 256) return;+ || (data.event === 'failure' && data.operation !== 'update' && data.operation !== 'component-update') || this.pending >= 256) return;+ // Orchestration visibility is failure-only; it never duplicates a component+ // operation's own start, progress or exit records.+ if (data.operation === 'component-update' && data.event !== 'failure') return;let context: Context;try { context = this.context(); } catch { context = {}; }const entry: Record<string, unknown> = {@@ -102,13 +110,20 @@ export class BackendDiagnostics {launcher: version(context.launcher), backend: version(context.backend),source: ['managed', 'external'].includes(context.source ?? '') ? context.source : 'unknown',};- // Installer stages are a separate fixed vocabulary and never mix with- // backend child-process stages for other operations.+ // Installer and orchestration stages are separate fixed vocabularies and+ // never mix with backend child-process stages for other operations.if (data.stage && updateStages.has(data.stage) && data.operation !== 'update') return;- const stageAllowed = Boolean(data.stage && stages.has(data.stage) && (data.operation === 'update') === updateStages.has(data.stage!));- // An installer record without a fixed stage carries no useful information.- if (data.operation === 'update' && ['diagnostic', 'failure'].includes(data.event) && !stageAllowed) return;+ if (data.stage && componentUpdateStages.has(data.stage) && data.operation !== 'component-update') return;+ const stageAllowed = Boolean(data.stage && stages.has(data.stage) && (data.operation === 'update') === updateStages.has(data.stage!)+ && (data.operation === 'component-update') === componentUpdateStages.has(data.stage!));+ // A record without its fixed stage carries no useful information.+ if (['update', 'component-update'].includes(data.operation) && ['diagnostic', 'failure'].includes(data.event) && !stageAllowed) return;+ const componentAllowed = data.component !== undefined && componentUpdateComponents.has(data.component);+ // A discovery failure must name the component it belongs to, or it could be+ // mistaken for a different component's install.+ if (data.operation === 'component-update' && data.stage === 'plan-discovery' && !componentAllowed) return;if (data.stage && stageAllowed) entry.stage = data.stage;+ if (data.operation === 'component-update' && componentAllowed) entry.component = data.component;if (Number.isInteger(data.status) && data.status! >= 100 && data.status! <= 599) entry.status = data.status;if (Number.isInteger(data.skipped) && data.skipped! >= 0 && data.skipped! <= 200_000) entry.skipped = data.skipped;if (Number.isInteger(data.code) && data.code! >= -1 && data.code! <= 255) entry.code = data.code;diff --git a/src/main/backend-recovery-matrix.test.ts b/src/main/backend-recovery-matrix.test.tsnew file mode 100644index 0000000..6f0076e--- /dev/null+++ b/src/main/backend-recovery-matrix.test.ts@@ -0,0 +1,334 @@+import { createHash } from 'node:crypto';+import { promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { readFileSync } from 'node:fs';+import { runInNewContext } from 'node:vm';+import ts from 'typescript';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { BackendManager } from './backend.js';+import { BackendDiagnostics, setBackendDiagnostics } from './backend-diagnostics.js';+import { backendLock, backendPackageName, backendRecipeSha256, compareVersions, minimumBackendVersion, validateBackendManifest } from './backend-package.js';+import { BACKEND_ARCH_SUFFIX, ELF_MACHINE, currentArch } from './arch.js';+import { run } from './process.js';+import { ComponentUpdates, type PreparedComponentUpdate } from './component-updates.js';+import { ComponentUpdateAdmission } from './component-update-admission.js';+import { assertActivityCompatible } from './install-queue.js';++// The synthetic backend binary is never executed; only help/capability parsing+// and install validation are exercised. Real tar/filesystem code is used.+vi.mock('./process.js', async importOriginal => {+ const actual = await importOriginal<typeof import('./process.js')>();+ const help = 'xodus-cli 0.1.0\n account Account\n login Login\n logout Logout\n download Download\n streaming Streaming\n run Run\n resolve-package Resolve packages\n\nOptions:\n --external-webview-stdio External UI\n';+ return { ...actual, run: vi.fn(async (cmd: string, args: string[], options: object) => {+ if (cmd.endsWith('/xodus-cli')) {+ const bytes = await fs.readFile(cmd).catch(() => Buffer.alloc(64));+ if (bytes[63] === 7) return { code: 127, output: '/private/path/xodus-cli: error while loading shared libraries: libdbus-1.so.3: cannot open shared object file: No such file or directory\n' };+ if (args[0] === 'streaming') return { code: 0, output: '--selected-content-id\n--json\n' };+ if (args[0] === 'run') return { code: 0, output: '--materialize-chain\n' };+ if (args[0] === 'resolve-package') return { code: 0, output: '--json\n' };+ if (args[0] === '--help') return { code: 0, output: help };+ return { code: 0, output: '' };+ }+ if (cmd.endsWith('/xodus-service')) throw new Error('Service must never start in installer tests');+ if (['git', 'cargo', 'rustc', 'protoc'].includes(cmd)) return { code: 1, output: 'Build tool intentionally absent' };+ if (cmd === 'ps') return { code: 0, output: '' };+ return actual.run(cmd, args, options);+ }) };+});++const source = readFileSync(new URL('./index.ts', import.meta.url), 'utf8');+const ast = ts.createSourceFile('index.ts', source, ts.ScriptTarget.ES2022, true);+const names = new Set(['ensureIdle', 'ensureActivityIdle']);+const functions = ast.statements.filter(node => ts.isFunctionDeclaration(node) && node.name && names.has(node.name.text))+ .map(node => node.getText(ast)).join('\n');+const register = ast.statements.find(node => ts.isFunctionDeclaration(node) && node.name?.text === 'registerIpc') as ts.FunctionDeclaration;+const handlerSource = register.body!.statements.filter(node => ts.isExpressionStatement(node) && ts.isCallExpression(node.expression)+ && node.expression.expression.getText(ast) === 'ipcMain.handle' && ts.isStringLiteral(node.expression.arguments[0])+ && node.expression.arguments[0].text === 'backend-update').map(node => node.getText(ast)).join('\n');++const arch = currentArch();+const version = backendLock.version;+const sha = (data: Buffer, algorithm = 'sha256') => createHash(algorithm).update(data).digest('hex');+const elf = (marker = 0) => {+ const bytes = Buffer.alloc(64);+ bytes.set([0x7f, 0x45, 0x4c, 0x46, 2, 1]);+ bytes.writeUInt16LE(ELF_MACHINE[arch], 18);+ bytes[63] = marker;+ return bytes;+};++let root: string;+let managed: string;+let log: BackendDiagnostics;+beforeEach(async () => {+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'nexus-backend-recovery-matrix-'));+ managed = path.join(root, 'xodus-backends');+ await fs.mkdir(managed, { recursive: true });+ log = new BackendDiagnostics(root);+ setBackendDiagnostics(log);+});+afterEach(async () => {+ setBackendDiagnostics(undefined);+ await log.read().catch(() => {});+ await fs.rm(root, { recursive: true, force: true });+});++async function records(): Promise<Array<Record<string, unknown>>> {+ const { content } = await log.read();+ return content.trim().split('\n').filter(line => line.startsWith('{')).map(line => JSON.parse(line));+}++interface ReleaseFixture {+ manifest: Record<string, unknown>;+ bytes: Buffer;+ packageName: string;+ archive: string;+ tag: string;+ repository: 'domsvoboda/nexus-backend' | 'domsvoboda/xodus-nexus';+}++/** A tiny synthetic release whose bytes never leave this fixture. */+async function releaseFixture(releaseVersion = version, legacy = false): Promise<ReleaseFixture> {+ const name = backendPackageName(releaseVersion, arch);+ const archive = `${name}.tar.xz`;+ const build = path.join(root, 'build', `${releaseVersion}-${legacy ? 'legacy' : 'modern'}`);+ const bundle = path.join(build, name);+ await fs.mkdir(bundle, { recursive: true });+ for (const file of ['xodus-cli', 'xodus-service', 'LICENSE'])+ await fs.writeFile(path.join(bundle, file), file === 'LICENSE' ? Buffer.from('synthetic license fixture') : elf(), { mode: file === 'LICENSE' ? 0o644 : 0o755 });+ const files: Record<string, string> = {};+ for (const file of ['xodus-cli', 'xodus-service', 'LICENSE']) files[file] = sha(await fs.readFile(path.join(bundle, file)));+ expect((await run('tar', ['-cJf', path.join(build, archive), '-C', build, name])).code).toBe(0);+ const bytes = await fs.readFile(path.join(build, archive));+ const common = { authUi: 'electron', version: releaseVersion, commit: backendLock.commit, recipeSha256: backendRecipeSha256,+ compatibility: backendLock.compatibility, platform: 'linux', arch, archive, archiveSha512: sha(bytes, 'sha512'), files };+ // Schema 1 is the published legacy layout; schema 2 is the current one.+ const manifest = legacy ? { schema: 1, ...common } : { schema: 2, sourceRepository: 'domsvoboda/nexus-backend', ...common };+ return { manifest, bytes, packageName: name, archive, tag: `backend-v${releaseVersion}`,+ repository: legacy ? 'domsvoboda/xodus-nexus' : 'domsvoboda/nexus-backend' };+}++function fetcherFor(fixture: ReleaseFixture) {+ const requests: string[] = [];+ const url = (asset: string) => `https://github.com/${fixture.repository}/releases/download/${fixture.tag}/${asset}`;+ const assets = [fixture.archive, `${fixture.packageName}.manifest.json`, `${fixture.packageName}.sha512sum`,+ `${fixture.packageName}-source.tar.xz`, `${fixture.packageName}-source.sha512sum`];+ const release = () => new Response(JSON.stringify([{ tag_name: fixture.tag,+ assets: assets.map(asset => ({ name: asset, browser_download_url: url(asset) })) }]));+ const fetcher = vi.fn(async (input: URL | RequestInfo) => {+ const target = String(input); requests.push(target);+ if (target.includes('/repos/domsvoboda/nexus-backend/releases?'))+ return fixture.repository === 'domsvoboda/nexus-backend' ? release() : new Response('[]');+ if (target.includes('/repos/domsvoboda/xodus-nexus/releases?'))+ return fixture.repository === 'domsvoboda/xodus-nexus' ? release() : new Response('[]');+ if (target.includes('/releases?')) return new Response('[]');+ if (target.endsWith('.manifest.json')) return new Response(JSON.stringify(fixture.manifest));+ if (target.endsWith('.sha512sum')) return new Response(`${fixture.manifest.archiveSha512} ${fixture.archive}\n`);+ if (target.endsWith(fixture.archive)) return new Response(fixture.bytes);+ return new Response('synthetic source fixture bytes');+ });+ return { fetcher: fetcher as unknown as typeof fetch, requests };+}++function manager(fetcher: typeof fetch) { return new BackendManager(root, '', () => {}, () => false, fetcher); }++async function seedInstalled(installedVersion: string, options: { unusable?: boolean } = {}) {+ const directory = path.join(managed, 'releases', installedVersion.replace(/\./g, '-'));+ await fs.mkdir(directory, { recursive: true });+ const cli = path.join(directory, 'xodus-cli');+ await fs.writeFile(cli, elf(options.unusable ? 7 : 0), { mode: 0o755 });+ await fs.writeFile(path.join(directory, 'xodus-service'), elf(), { mode: 0o755 });+ await fs.writeFile(path.join(directory, 'LICENSE'), 'synthetic old license', { mode: 0o644 });+ const pointer = { commit: backendLock.commit, binaryPath: cli, builtAt: new Date().toISOString(),+ linuxRunPatch: backendLock.compatibility, recipeSha256: backendRecipeSha256, version: installedVersion, delivery: 'release' };+ const bytes = JSON.stringify(pointer, null, 2);+ await fs.writeFile(path.join(managed, 'current.json'), bytes);+ return { directory, pointer: bytes };+}++type Files = Record<string, string>;+async function gameFixtures(): Promise<Files> {+ const files = {+ game: path.join(root, 'games', 'Synthetic Game', 'content.bin'),+ save: path.join(root, 'prefixes', 'synthetic', 'drive_c', 'save', 'slot1.sav'),+ ini: path.join(root, 'prefixes', 'synthetic', 'drive_c', 'settings.ini'),+ };+ for (const file of Object.values(files)) await fs.mkdir(path.dirname(file), { recursive: true });+ await fs.writeFile(files.game, 'synthetic-game-bytes');+ await fs.writeFile(files.save, 'synthetic-save-bytes');+ await fs.writeFile(files.ini, 'synthetic=1\n');+ return files;+}+async function bytesOf(files: Files): Promise<Record<string, Buffer>> {+ return Object.fromEntries(await Promise.all(Object.entries(files).map(async ([key, file]) => [key, await fs.readFile(file)])));+}+async function expectBytes(files: Files, before: Record<string, Buffer>): Promise<void> {+ for (const [key, file] of Object.entries(files)) expect((await fs.readFile(file)).equals(before[key]), key).toBe(true);+}++async function componentPlan(backend: BackendManager, fetcher: typeof fetch) {+ const prepared: PreparedComponentUpdate[] = [await backend.prepareComponentUpdate(() => {})];+ const admission = new ComponentUpdateAdmission(() => {});+ const updates = new ComponentUpdates(admission, async () => prepared, () => {}, () => false);+ return { updates, prepared, admission };+}++/** The actual registerIpc backend-update statement in its production gates. */+function backendUpdateHandler(backend: BackendManager) {+ const handlers = new Map<string, Function>();+ const ctx: any = {+ ipcMain: { handle: (name: string, handler: Function) => handlers.set(name, handler) },+ backend, emitSnapshot: vi.fn(), refreshAccount: vi.fn(async () => {}),+ runtime: { busy: false, current: { updating: false }, assertSettingsReservation: vi.fn() },+ componentUpdateAdmission: new ComponentUpdateAdmission(() => ctx.ensureActivityIdle()),+ offlinePermissionChanging: false, keyringSupport: { busy: false }, authState: { running: false }, authJob: undefined,+ shutdownStarted: false, downloadCancellations: new Set(), preparingInstall: false, preparingContent: false,+ preparingLaunch: false, finalizingGame: false, launcherUpdater: { busy: false }, checkingGameUpdates: false,+ gameRemovalInProgress: false, gameOperation: undefined, operations: new Map(), store: { downloads: [] },+ installQueue: { size: 0 }, assertActivityCompatible,+ backendDiagnostic: (record: unknown) => log.record(record as never),+ };+ runInNewContext(ts.transpileModule(functions + '\n' + handlerSource, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText, ctx);+ return { handlers, ctx };+}++describe('backend recovery matrix with the actual update preparation path', () => {+ it.each([+ ['0.2.13', 'installed below the launcher minimum'],+ ['0.2.14', 'installed at the launcher minimum'],+ ])('prepares and applies recovery from %s (%s) without a capability admission cycle', async installedVersion => {+ const files = await gameFixtures(), before = await bytesOf(files);+ const seeded = await seedInstalled(installedVersion);+ const release = await releaseFixture(), { fetcher } = fetcherFor(release);+ const backend = manager(fetcher);+ expect(await backend.refresh()).toMatchObject({ available: true, version: installedVersion, source: 'managed' });+ expect(await backend.checkUpdate()).toMatchObject({ releaseAvailable: true, updateAvailable: true, blockReason: undefined });+ const { updates, prepared } = await componentPlan(backend, fetcher);+ expect(prepared[0].item).toMatchObject({ id: 'backend', component: 'backend', state: 'ready', currentVersion: installedVersion, targetVersion: version });++ const plan = await updates.plan();+ const result = await updates.apply(plan.id);+ expect(result.items[0]).toMatchObject({ id: 'backend', outcome: 'updated', committed: true });+ expect(backend.current).toMatchObject({ available: true, version, source: 'managed', updateAvailable: false });+ expect(JSON.parse(await fs.readFile(path.join(managed, 'current.json'), 'utf8')).version).toBe(version);+ expect((await fs.stat(seeded.directory)).isDirectory()).toBe(true);+ expect((await records()).filter(row => row.operation === 'component-update')).toEqual([]);+ await expectBytes(files, before);+ });++ it('recovers from an installed below-minimum backend through the actual backend-update IPC handler', async () => {+ const files = await gameFixtures(), before = await bytesOf(files);+ const seeded = await seedInstalled('0.2.13');+ const release = await releaseFixture(), { fetcher } = fetcherFor(release);+ const backend = manager(fetcher);+ expect(await backend.refresh()).toMatchObject({ available: true, version: '0.2.13' });+ expect(await backend.checkUpdate()).toMatchObject({ releaseAvailable: true, updateAvailable: true });+ const { handlers, ctx } = backendUpdateHandler(backend);++ await handlers.get('backend-update')!();++ expect(backend.current).toMatchObject({ available: true, version, source: 'managed' });+ expect(ctx.refreshAccount).toHaveBeenCalledOnce();+ expect(JSON.parse(await fs.readFile(path.join(managed, 'current.json'), 'utf8')).version).toBe(version);+ expect(seeded.pointer).not.toBe(await fs.readFile(path.join(managed, 'current.json'), 'utf8'));+ expect((await fs.stat(seeded.directory)).isDirectory()).toBe(true);+ expect((await records()).filter(row => row.operation === 'component-update')).toEqual([]);+ await expectBytes(files, before);+ });++ it('offers and performs a direct install when the backend is missing, and does not auto-install it in a component plan', async () => {+ const files = await gameFixtures(), before = await bytesOf(files);+ const release = await releaseFixture(), { fetcher } = fetcherFor(release);+ const backend = manager(fetcher);+ expect(await backend.refresh()).toMatchObject({ available: false, source: 'none' });+ expect(await backend.checkUpdate()).toMatchObject({ releaseAvailable: true, updateAvailable: true });+ // Update all deliberately skips an absent backend instead of guessing an+ // install destination; the Settings Install action remains available.+ const { prepared, updates } = await componentPlan(backend, fetcher);+ expect(prepared[0].item).toMatchObject({ state: 'skipped' });+ const plan = await updates.plan();+ const result = await updates.apply(plan.id);+ expect(result.items[0].outcome).toBe('skipped');+ expect(backend.current.available).toBe(false);+ await expect(fs.readFile(path.join(managed, 'current.json'))).rejects.toThrow();++ const { handlers } = backendUpdateHandler(backend);+ await handlers.get('backend-update')!();+ expect(backend.current).toMatchObject({ available: true, version });+ await expectBytes(files, before);+ });++ it('recovers an unusable installed backend through the actual IPC handler and keeps the old release', async () => {+ const files = await gameFixtures(), before = await bytesOf(files);+ const seeded = await seedInstalled('0.2.14', { unusable: true });+ const release = await releaseFixture(), { fetcher } = fetcherFor(release);+ const backend = manager(fetcher);+ const broken = await backend.refresh();+ expect(broken.available).toBe(false);+ expect(broken.blockReason).toContain('D-Bus runtime library is missing');+ expect(await backend.checkUpdate()).toMatchObject({ releaseAvailable: true, updateAvailable: true });+ // The component plan must not claim it can repair an unusable managed backend.+ const { prepared } = await componentPlan(backend, fetcher);+ expect(prepared[0].item.state).toBe('skipped');+ expect(prepared[0].item.reason).toContain('Only an installed managed backend release');++ const { handlers } = backendUpdateHandler(backend);+ await handlers.get('backend-update')!();+ expect(backend.current).toMatchObject({ available: true, version, source: 'managed' });+ expect((await fs.stat(seeded.directory)).isDirectory()).toBe(true);+ await expectBytes(files, before);+ });++ it('reports a current backend as unchanged and never downloads or replaces it', async () => {+ const files = await gameFixtures(), before = await bytesOf(files);+ const seeded = await seedInstalled(version);+ const release = await releaseFixture(), { fetcher, requests } = fetcherFor(release);+ const backend = manager(fetcher);+ expect(await backend.refresh()).toMatchObject({ available: true, version });+ expect(await backend.checkUpdate()).toMatchObject({ releaseAvailable: true, updateAvailable: false });+ const { prepared, updates } = await componentPlan(backend, fetcher);+ expect(prepared[0].item.state).toBe('unchanged');+ const plan = await updates.plan();+ const result = await updates.apply(plan.id);+ expect(result.items[0].outcome).toBe('unchanged');+ expect(await fs.readFile(path.join(managed, 'current.json'), 'utf8')).toBe(seeded.pointer);+ expect(requests.some(url => url.endsWith(release.archive))).toBe(false);+ expect((await records()).filter(row => row.operation === 'update')).toEqual([]);+ await expectBytes(files, before);+ });++ it('installs the published minimum version 0.2.14 legacy release from the legacy repository', async () => {+ const files = await gameFixtures(), before = await bytesOf(files);+ await seedInstalled('0.2.13');+ const release = await releaseFixture('0.2.14', true);+ const { fetcher, requests } = fetcherFor(release);+ const backend = manager(fetcher);+ expect(await backend.refresh()).toMatchObject({ available: true, version: '0.2.13' });+ expect(await backend.checkUpdate()).toMatchObject({ releaseAvailable: true, updateAvailable: true });+ const { prepared, updates } = await componentPlan(backend, fetcher);+ expect(prepared[0].item).toMatchObject({ state: 'ready', currentVersion: '0.2.13', targetVersion: '0.2.14' });+ const plan = await updates.plan();+ const result = await updates.apply(plan.id);+ expect(result.items[0]).toMatchObject({ outcome: 'updated', committed: true });+ expect(JSON.parse(await fs.readFile(path.join(managed, 'current.json'), 'utf8')).version).toBe('0.2.14');+ expect(requests.some(target => target.endsWith('/xodus-nexus-backend-0.2.14-linux-x86_64.tar.xz'))).toBe(true);+ await expectBytes(files, before);+ });++ it('accepts the published 0.2.14 legacy manifest as a valid recovery target and keeps 0.2.13 below the minimum', () => {+ // Exact public fields of xodus-nexus-backend-0.2.14-linux-x86_64.manifest.json.+ const published = { schema: 1, version: '0.2.14', commit: '53ea781dcd073e31d7ea68e894134e9c959bff04',+ recipeSha256: 'd2d57ba9ffd973778bb253d64e4d6be8d780ed8434474dab367bf35cf3c9563c', compatibility: 'linux-run-v25',+ authUi: 'electron', platform: 'linux', arch: 'x64', archive: 'xodus-nexus-backend-0.2.14-linux-x86_64.tar.xz',+ archiveSha512: '7b5d8ddfb99245a4e7ed1023a324cb1ed56ddcb35bf0903564ad5a0b26493425bfc133a172973350c59331b012b639f218665a946738161d6a8cd7a1d0f71a21',+ files: { 'xodus-cli': '3938cb1c6f109f4249953270fa241178856e791240376fe96f94fd807fe3c026',+ 'xodus-service': '36f299bace488371e1ca6915dee61d69d199e66aa66307561323e1c5ec6dfb50',+ LICENSE: '3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986' } };+ expect(compareVersions('0.2.14', minimumBackendVersion)).toBe(0);+ expect(compareVersions('0.2.13', minimumBackendVersion)).toBeLessThan(0);+ expect(backendPackageName('0.2.14', 'x64')).toBe('xodus-nexus-backend-0.2.14-linux-x86_64');+ expect(validateBackendManifest(structuredClone(published), 'x64', 'domsvoboda/xodus-nexus')).toMatchObject({ schema: 1, version: '0.2.14', arch: 'x64' });+ expect(() => validateBackendManifest(structuredClone(published), 'x64', 'domsvoboda/nexus-backend')).toThrow('not a valid compatible release');+ });+});diff --git a/src/main/component-update-diagnostics.test.ts b/src/main/component-update-diagnostics.test.tsnew file mode 100644index 0000000..910e94f--- /dev/null+++ b/src/main/component-update-diagnostics.test.ts@@ -0,0 +1,266 @@+import { readFileSync, promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { runInNewContext } from 'node:vm';+import ts from 'typescript';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { BackendManager } from './backend.js';+import { BackendDiagnostics, setBackendDiagnostics } from './backend-diagnostics.js';+import { backendHttpStatus } from './backend-releases.js';+import { backendLock, backendRecipeSha256 } from './backend-package.js';+import { ELF_MACHINE, currentArch } from './arch.js';+import { ComponentUpdates, type PreparedComponentUpdate } from './component-updates.js';+import { ComponentUpdateAdmission } from './component-update-admission.js';++// Real tar/filesystem code is not needed here, but backend refresh and update+// discovery must never execute a real backend, account or network request.+vi.mock('./process.js', async importOriginal => {+ const actual = await importOriginal<typeof import('./process.js')>();+ const help = 'xodus-cli 0.1.0\n account Account\n login Login\n logout Logout\n download Download\n streaming Streaming\n run Run\n resolve-package Resolve packages\n\nOptions:\n --external-webview-stdio External UI\n';+ return { ...actual, run: vi.fn(async (cmd: string, args: string[], options: object) => {+ if (cmd.endsWith('/xodus-cli')) {+ if (args[0] === 'streaming') return { code: 0, output: '--selected-content-id\n--json\n' };+ if (args[0] === 'run') return { code: 0, output: '--materialize-chain\n' };+ if (args[0] === '--help') return { code: 0, output: help };+ return { code: 0, output: '' };+ }+ if (['git', 'cargo', 'rustc', 'protoc'].includes(cmd)) return { code: 1, output: 'Build tool intentionally absent' };+ if (cmd === 'ps') return { code: 0, output: '' };+ return actual.run(cmd, args, options);+ }) };+});++const source = readFileSync(new URL('./index.ts', import.meta.url), 'utf8');+const ast = ts.createSourceFile('index.ts', source, ts.ScriptTarget.ES2022, true);+const names = new Set(['discoverComponent', 'prepareComponentUpdates']);+const functions = ast.statements.filter(node => ts.isFunctionDeclaration(node) && node.name && names.has(node.name.text))+ .map(node => node.getText(ast)).join('\n');+const register = ast.statements.find(node => ts.isFunctionDeclaration(node) && node.name?.text === 'registerIpc') as ts.FunctionDeclaration;+const routes = new Set(['component-updates-plan', 'component-updates-apply']);+const handlerSource = register.body!.statements.filter(node => ts.isExpressionStatement(node) && ts.isCallExpression(node.expression)+ && node.expression.expression.getText(ast) === 'ipcMain.handle' && ts.isStringLiteral(node.expression.arguments[0])+ && routes.has(node.expression.arguments[0].text)).map(node => node.getText(ast)).join('\n');++const elf = () => {+ const bytes = Buffer.alloc(64);+ bytes.set([0x7f, 0x45, 0x4c, 0x46, 2, 1]);+ bytes.writeUInt16LE(ELF_MACHINE[currentArch()], 18);+ return bytes;+};++let root: string;+let managed: string;+let log: BackendDiagnostics;+beforeEach(async () => {+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'nexus-component-update-diagnostics-'));+ managed = path.join(root, 'xodus-backends');+ await fs.mkdir(managed, { recursive: true });+ log = new BackendDiagnostics(root);+ setBackendDiagnostics(log);+});+afterEach(async () => {+ setBackendDiagnostics(undefined);+ await log.read().catch(() => {});+ await fs.rm(root, { recursive: true, force: true });+});++async function records(): Promise<Array<Record<string, unknown>>> {+ const { content } = await log.read();+ return content.trim().split('\n').filter(line => line.startsWith('{')).map(line => JSON.parse(line));+}+async function componentRecords(): Promise<Array<Record<string, unknown>>> {+ return (await records()).filter(row => row.operation === 'component-update');+}+async function updateRecords(): Promise<Array<Record<string, unknown>>> {+ return (await records()).filter(row => row.operation === 'update');+}++async function seedManagedBackend() {+ const directory = path.join(managed, 'releases', 'old');+ await fs.mkdir(directory, { recursive: true });+ for (const file of ['xodus-cli', 'xodus-service', 'LICENSE'])+ await fs.writeFile(path.join(directory, file), elf(), { mode: file === 'LICENSE' ? 0o644 : 0o755 });+ const pointer = { commit: backendLock.commit, binaryPath: path.join(directory, 'xodus-cli'), builtAt: new Date().toISOString(),+ linuxRunPatch: backendLock.compatibility, recipeSha256: backendRecipeSha256, version: backendLock.version, delivery: 'release' };+ const bytes = JSON.stringify(pointer, null, 2);+ await fs.writeFile(path.join(managed, 'current.json'), bytes);+ return { pointer: bytes, directory };+}++function manager(fetcher: typeof fetch) {+ return new BackendManager(root, '', () => {}, () => false, fetcher);+}++function forbidden(): typeof fetch {+ return vi.fn(async () => new Response('synthetic forbidden response', { status: 403 })) as unknown as typeof fetch;+}++type Files = Record<string, string>;+async function gameFixtures(): Promise<Files> {+ const files = {+ game: path.join(root, 'games', 'Synthetic Game', 'content.bin'),+ save: path.join(root, 'prefixes', 'synthetic', 'drive_c', 'save', 'slot1.sav'),+ ini: path.join(root, 'prefixes', 'synthetic', 'drive_c', 'settings.ini'),+ };+ for (const file of Object.values(files)) await fs.mkdir(path.dirname(file), { recursive: true });+ await fs.writeFile(files.game, 'synthetic-game-bytes');+ await fs.writeFile(files.save, 'synthetic-save-bytes');+ await fs.writeFile(files.ini, 'synthetic=1\n');+ return files;+}+async function bytesOf(files: Files): Promise<Record<string, Buffer>> {+ return Object.fromEntries(await Promise.all(Object.entries(files).map(async ([key, file]) => [key, await fs.readFile(file)])));+}+async function expectBytes(files: Files, before: Record<string, Buffer>): Promise<void> {+ for (const [key, file] of Object.entries(files)) expect((await fs.readFile(file)).equals(before[key]), key).toBe(true);+}++function readyEntry(id: string, component: 'backend' | 'runtime' | 'launcher' = 'backend'): PreparedComponentUpdate {+ return { item: { id, component, label: id, state: 'ready' }, isCurrent: vi.fn(async () => true), apply: vi.fn(async () => ({ committed: true })) };+}++/** The actual registerIpc plan/apply statements plus the actual discovery seam. */+function harness(options: { backend?: unknown; prepareManaged?: () => Promise<unknown>; prepareLauncher?: () => Promise<unknown>; discover?: () => Promise<PreparedComponentUpdate[]> }) {+ const handlers = new Map<string, Function>();+ const ctx: any = {+ ipcMain: { handle: (name: string, handler: Function) => handlers.set(name, handler) },+ backend: options.backend ?? {},+ runtime: { current: { updating: false } },+ launcherUpdater: { prepareComponentUpdate: options.prepareLauncher ?? vi.fn(async () => readyEntry('launcher', 'launcher')) },+ store: { settings: { winePath: '' }, setSettings: vi.fn(async () => {}) },+ emitSnapshot: vi.fn(), refreshAccount: vi.fn(async () => {}),+ prepareManagedComponentUpdates: options.prepareManaged ?? vi.fn(async () => [readyEntry('runtime-standard', 'runtime')]),+ prepareLegacyComponentUpdate: vi.fn(async () => readyEntry('runtime-legacy', 'runtime')),+ backendDiagnostic: (record: unknown) => log.record(record as never),+ backendHttpStatus,+ };+ runInNewContext(ts.transpileModule(functions + '\n' + handlerSource, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText, ctx);+ const admission = new ComponentUpdateAdmission(() => {});+ const updates = new ComponentUpdates(admission, options.discover ?? (() => ctx.prepareComponentUpdates()), () => {}, () => false);+ ctx.componentUpdates = updates;+ return { ctx, handlers, admission, updates };+}++describe('component update orchestration diagnostics', () => {+ it('records one backend plan discovery failure through the actual plan IPC entry, before any install', async () => {+ const files = await gameFixtures(), before = await bytesOf(files);+ const seeded = await seedManagedBackend();+ const backend = manager(forbidden());+ await backend.refresh();+ expect(backend.current).toMatchObject({ available: true, source: 'managed' });+ const { ctx, handlers, admission, updates } = harness({ backend });++ await expect(handlers.get('component-updates-plan')!()).rejects.toThrow('HTTP 403');++ const component = await componentRecords();+ expect(component).toHaveLength(1);+ expect(component[0]).toMatchObject({ operation: 'component-update', event: 'failure', stage: 'plan-discovery', component: 'backend', status: 403 });+ expect(component[0].committed).toBeUndefined();+ expect(await updateRecords()).toEqual([]);+ expect(ctx.prepareManagedComponentUpdates).not.toHaveBeenCalled();+ expect(ctx.launcherUpdater.prepareComponentUpdate).not.toHaveBeenCalled();+ expect(admission.busy).toBe(false);+ expect(updates.current).toEqual({ running: false });+ expect(await fs.readFile(path.join(managed, 'current.json'), 'utf8')).toBe(seeded.pointer);+ expect((await fs.readdir(managed)).filter(name => name.startsWith('.download-'))).toEqual([]);+ await expectBytes(files, before);+ });++ it('records a later component discovery failure without a plan, side effects or retained reservation', async () => {+ const files = await gameFixtures(), before = await bytesOf(files);+ const backendEntry = readyEntry('backend');+ const backendApply = backendEntry.apply;+ const { ctx, handlers, admission, updates } = harness({+ backend: { prepareComponentUpdate: vi.fn(async () => backendEntry) },+ prepareManaged: vi.fn(async () => { throw Error('synthetic runtime discovery failure'); }),+ });++ await expect(handlers.get('component-updates-plan')!()).rejects.toThrow('synthetic runtime discovery failure');++ const component = await componentRecords();+ expect(component).toEqual([expect.objectContaining({ stage: 'plan-discovery', component: 'runtime' })]);+ expect(component[0].status).toBeUndefined();+ expect(backendApply).not.toHaveBeenCalled();+ expect(ctx.launcherUpdater.prepareComponentUpdate).not.toHaveBeenCalled();+ expect(admission.busy).toBe(false);+ expect(updates.current).toEqual({ running: false });+ expect(await updateRecords()).toEqual([]);+ await expectBytes(files, before);+ });++ it('records plan admission rejection once and never touches the other reservation', async () => {+ const discover = vi.fn(async () => [readyEntry('backend')]);+ const { handlers, admission } = harness({ discover });+ const owner = admission.reserve();+ await expect(handlers.get('component-updates-plan')!()).rejects.toThrow('Component updates are in progress.');+ expect(await componentRecords()).toEqual([expect.objectContaining({ stage: 'plan-blocked' })]);+ expect(discover).not.toHaveBeenCalled();+ expect(admission.busy).toBe(true);+ admission.release(owner);+ expect(admission.busy).toBe(false);+ expect(await updateRecords()).toEqual([]);+ });++ it('records apply admission rejection once and keeps the running batch reservation', async () => {+ const entry = readyEntry('backend');+ const { handlers, admission, updates } = harness({ discover: vi.fn(async () => [entry]) });+ const plan = await updates.plan();+ const owner = admission.reserve();+ await expect(handlers.get('component-updates-apply')!({}, plan.id)).rejects.toThrow('Component updates are in progress.');+ expect(await componentRecords()).toEqual([expect.objectContaining({ stage: 'apply-blocked' })]);+ expect(entry.apply).not.toHaveBeenCalled();+ expect(admission.busy).toBe(true);+ admission.release(owner);+ expect(admission.busy).toBe(false);+ expect(await updateRecords()).toEqual([]);+ });++ it('does not duplicate the installer failure, start or exit for a failing backend component', async () => {+ const files = await gameFixtures(), before = await bytesOf(files);+ await seedManagedBackend();+ const backend = manager(forbidden());+ const entry = readyEntry('backend');+ entry.apply = vi.fn(async () => { await backend.update(() => {}); return { committed: true }; });+ const admission = new ComponentUpdateAdmission(() => {});+ const updates = new ComponentUpdates(admission, async () => [entry], () => {}, () => false);++ const plan = await updates.plan();+ const result = await updates.apply(plan.id);++ expect(result.items[0]).toMatchObject({ id: 'backend', outcome: 'failed-before-commit', committed: false });+ expect(await componentRecords()).toEqual([]);+ const update = await updateRecords();+ expect(update.filter(row => row.event === 'start')).toHaveLength(1);+ expect(update.filter(row => row.event === 'failure')).toEqual([expect.objectContaining({ stage: 'update-discovery', committed: false })]);+ expect(update.filter(row => row.event === 'exit')).toEqual([expect.objectContaining({ code: -1 })]);+ expect(admission.busy).toBe(false);+ await expectBytes(files, before);+ });++ it('rejects free-form, unclassified and cross-operation orchestration records', async () => {+ log.record({ operation: 'component-update', event: 'failure', stage: 'plan-discovery', component: 'backend',+ message: 'EACCES /home/synthetic/secret https://example.test/?token=secret-token', path: '/home/synthetic/secret', url: 'https://example.test' } as never);+ log.record({ operation: 'component-update', event: 'failure', stage: 'plan-discovery' } as never);+ log.record({ operation: 'component-update', event: 'failure', stage: 'plan-discovery', component: 'account' } as never);+ log.record({ operation: 'component-update', event: 'failure', stage: 'plan-private', component: 'backend' } as never);+ log.record({ operation: 'component-update', event: 'start', stage: 'plan-blocked' } as never);+ log.record({ operation: 'component-update', event: 'failure', stage: 'plan-blocked' });+ log.record({ operation: 'component-update', event: 'failure', stage: 'apply-blocked', committed: false } as never);+ log.record({ operation: 'component-update', event: 'failure', stage: 'plan-discovery', component: 'runtime', status: 999 } as never);+ log.record({ operation: 'login', event: 'failure', stage: 'plan-discovery', component: 'backend' } as never);+ log.record({ operation: 'component-update', event: 'failure', stage: 'plan-discovery', component: 'launcher', status: 403 });+ const { content } = await log.read();+ const rows = content.trim().split('\n').map(line => JSON.parse(line));+ expect(rows).toHaveLength(5);+ expect(rows[0]).toMatchObject({ stage: 'plan-discovery', component: 'backend' });+ expect(Object.keys(rows[0]).sort()).toEqual(['at', 'backend', 'component', 'event', 'launcher', 'operation', 'source', 'stage']);+ expect(rows[1]).toMatchObject({ stage: 'plan-blocked' });+ expect(rows[1].component).toBeUndefined();+ expect(rows[2]).toMatchObject({ stage: 'apply-blocked' });+ expect(rows[2].committed).toBeUndefined();+ expect(rows[3]).toMatchObject({ stage: 'plan-discovery', component: 'runtime' });+ expect(rows[3].status).toBeUndefined();+ expect(rows[4]).toMatchObject({ stage: 'plan-discovery', component: 'launcher', status: 403 });+ expect(content).not.toMatch(/secret-token|EACCES|home\/synthetic|example\.test|plan-private|"operation":"login"/);+ });+});diff --git a/src/main/component-updates.ts b/src/main/component-updates.tsindex 5a31d61..7afe34f 100644--- a/src/main/component-updates.ts+++ b/src/main/component-updates.ts@@ -1,6 +1,7 @@import { randomUUID } from 'node:crypto';import type { ComponentUpdateBatchResult, ComponentUpdateItemResult, ComponentUpdatePlan, ComponentUpdatePlanItem, ComponentUpdatesStatus } from '../shared/types.js';import { ComponentUpdateAdmission, type ComponentUpdateOwner } from './component-update-admission.js';+import { backendDiagnostic } from './backend-diagnostics.js';export interface PreparedComponentUpdate {readonly item: ComponentUpdatePlanItem;/** Compare installed identity and context, never silently substitute latest. */@@ -29,12 +30,32 @@ export class ComponentUpdates {return { running: this.state.running };return structuredClone(this.state);}+ /** A rejected plan entry is an orchestration blocker, never an install. */+ private assertPlanAllowed(): void {+ try {+ this.admission.assertAllowed();+ }+ catch (error) {+ backendDiagnostic({ operation: 'component-update', event: 'failure', stage: 'plan-blocked' });+ throw error;+ }+ }+ /** A rejected apply entry keeps another operation's reservation untouched. */+ private reserveForApply(): ComponentUpdateOwner {+ try {+ return this.admission.reserve();+ }+ catch (error) {+ backendDiagnostic({ operation: 'component-update', event: 'failure', stage: 'apply-blocked' });+ throw error;+ }+ }async plan(): Promise<ComponentUpdatePlan> {- this.admission.assertAllowed();+ this.assertPlanAllowed();const generation = ++this.generation;const context = this.currentContext();const prepared = await this.discover();- this.admission.assertAllowed();+ this.assertPlanAllowed();if (context !== this.currentContext())throw Error('The component update context changed. Check again.');if (generation !== this.generation)@@ -56,7 +77,7 @@ export class ComponentUpdates {}async apply(planId: string, retryItemId?: string): Promise<ComponentUpdateBatchResult> {// Synchronous reservation closes the first-await window for all child operations.- const owner = this.admission.reserve();+ const owner = this.reserveForApply();try {if (!this.state.plan || typeof planId !== 'string' || planId !== this.state.plan.id)throw Error('The component update plan is stale. Check again.');diff --git a/src/main/index.ts b/src/main/index.tsindex 604f64d..b8b3546 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -35,6 +35,7 @@ import {XboxGuideParty} from './xbox-guide-party.js';import {XboxOverlayShortcut,ensureOverlayDesktopEntry} from './xbox-overlay-shortcut.js';import {xboxOverlaySettings,xboxOverlayPatch} from '../shared/xbox-overlay-settings.js';import { BackendManager } from './backend.js';+import { backendHttpStatus } from './backend-releases.js';import { run, spawnTracked } from './process.js';import { inspectGameDirectory, StateStore } from './store.js';import { inspectStartupLibrary } from './startup-library.js';@@ -534,8 +535,18 @@ function componentActivityRunning(): boolean {store.downloads.some(task => task.status === 'queued' || task.status === 'running');}+async function discoverComponent<T>(component: 'backend' | 'runtime' | 'launcher', prepare: () => Promise<T>): Promise<T> {+ try { return await prepare(); }+ catch (error) {+ // Read-only plan discovery failed before any installer entry point. Record+ // the phase and component once, then let the original error reach the UI.+ backendDiagnostic({ operation: 'component-update', event: 'failure', stage: 'plan-discovery', component, status: backendHttpStatus(error) });+ throw error;+ }+}+async function prepareComponentUpdates(): Promise<PreparedComponentUpdate[]> {- const backendPlan = await backend.prepareComponentUpdate(emitSnapshot);+ const backendPlan = await discoverComponent('backend', () => backend.prepareComponentUpdate(emitSnapshot));const backendApply = backendPlan.apply, backendReconcile = backendPlan.reconcile;backendPlan.apply = async (owner) => {const result = await backendApply(owner);@@ -550,9 +561,10 @@ async function prepareComponentUpdates(): Promise<PreparedComponentUpdate[]> {};if (backendReconcile)backendPlan.reconcile = async (owner) => { const result = await backendReconcile(owner); await refreshAccount(false); emitSnapshot(); return result; };- return [backendPlan, ...await prepareManagedComponentUpdates(runtime, emitSnapshot),- await prepareLegacyComponentUpdate(runtime, { configuredWine: () => store.settings.winePath, persistSelection: async (winePath) => { await store.setSettings({ winePath }); }, refreshAccount: async () => { await refreshAccount(false); } }, emitSnapshot),- await launcherUpdater.prepareComponentUpdate()];+ return [backendPlan,+ ...await discoverComponent('runtime', () => prepareManagedComponentUpdates(runtime, emitSnapshot)),+ await discoverComponent('runtime', () => prepareLegacyComponentUpdate(runtime, { configuredWine: () => store.settings.winePath, persistSelection: async (winePath) => { await store.setSettings({ winePath }); }, refreshAccount: async () => { await refreshAccount(false); } }, emitSnapshot)),+ await discoverComponent('launcher', () => launcherUpdater.prepareComponentUpdate())];}async function syncManagedWinePath(): Promise<void> {