Skip to content

Open-source Xbox-inspired desktop launcher for Xodus on Linux

TypeScript

[source-only] fix(backend): report fixed update stages in diagnostics

Nexus Maintainer59d73b256773
diff --git a/scripts/BACKEND.md b/scripts/BACKEND.md
index c8ce5de..d1fa273 100644
--- a/scripts/BACKEND.md
+++ b/scripts/BACKEND.md
@@ -62,6 +62,25 @@ offers an in-app viewer and Copy log. Arbitrary stdout, stderr, command
arguments and sign-in protocol messages are not saved. Logs remain local and
are never uploaded automatically.
+### Backend update diagnostics
+
+Launcher-side component updates use operation `update` in the same private
+`backend.log`. Progress stages are `update-download`, `update-verify`,
+`update-validate`, `update-activate`, `update-confirm` and `update-ready`.
+Failures use fixed codes: `update-blocked` (activity gate or an update already
+running), `update-discovery` (install release lookup), `update-check-failed`
+(standalone release check, with the HTTP status when available),
+`update-download-http` (with the HTTP status), `update-download-limit`,
+`update-checksum`, `update-archive`, `update-extract`, `update-file-mismatch`,
+`update-binary`, `update-permission`, `update-validate`, `update-commit`,
+`update-cleanup`, `update-confirm` and `update-notify`. A cleanup failure after
+another installer failure is recorded as the fixed `update-cleanup` diagnostic
+while the original failure and its reason are kept; a cleanup failure after an
+otherwise valid install fails the operation before activation. Each update
+failure record carries `committed`, so a failure before `current.json`
+publication is distinguishable from an activation that needs attention. These
+records never contain messages, paths, URLs, tokens, accounts or child output.
+
## Package selection
`resolve-package PRODUCT --json --market US` reads public Store metadata without
diff --git a/src/main/backend-diagnostics.test.ts b/src/main/backend-diagnostics.test.ts
index e93fcb0..33e9f84 100644
--- a/src/main/backend-diagnostics.test.ts
+++ b/src/main/backend-diagnostics.test.ts
@@ -264,6 +264,35 @@ it('does not break backend calls when logging fails and never captures stdout or
} finally { setBackendDiagnostics(undefined); await fs.rm(root, { recursive: true, force: true }); }
});
+it('records only fixed installer stages with commit state and never a raw reason', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'nexus-update-diagnostic-'));
+ try {
+ const log = new BackendDiagnostics(root);
+ log.record({ operation: 'update', event: 'start' });
+ log.record({ operation: 'update', event: 'diagnostic', stage: 'update-download' });
+ log.record({ operation: 'update', event: 'failure', stage: 'update-download-http', status: 503, committed: false });
+ log.record({ operation: 'update', event: 'failure', stage: 'update-confirm', committed: true });
+ log.record({ operation: 'update', event: 'exit', code: -1, elapsedMs: 1200 });
+ log.record({ operation: 'update', event: 'failure', stage: 'update-commit', committed: 'yes' as never });
+ log.record({ operation: 'login', event: 'failure', stage: 'update-checksum', committed: true });
+ log.record({ operation: 'update', event: 'diagnostic', stage: 'entitlements-http' });
+ log.record({ operation: 'login', event: 'diagnostic', stage: 'update-checksum' });
+ log.record({ operation: 'update', event: 'failure', stage: 'update-checksum', committed: false, message: 'EACCES /private/path' } as never);
+ log.record({ operation: 'update', event: 'failure', stage: 'private-secret' });
+ const { content } = await log.read();
+ const records = content.trim().split('\n').map(line => JSON.parse(line));
+ expect(records.map(row => row.event)).toEqual(['start', 'diagnostic', 'failure', 'failure', 'exit', 'failure', 'failure']);
+ expect(records[1]).toMatchObject({ stage: 'update-download' });
+ expect(records[2]).toMatchObject({ stage: 'update-download-http', status: 503, committed: false });
+ expect(records[3]).toMatchObject({ stage: 'update-confirm', committed: true });
+ expect(records[4]).toMatchObject({ code: -1, elapsedMs: 1200 });
+ expect(records[5].committed).toBeUndefined();
+ expect(records[6]).toMatchObject({ stage: 'update-checksum', committed: false });
+ expect(Object.keys(records[6]).sort()).toEqual(['at', 'backend', 'committed', 'event', 'launcher', 'operation', 'source', 'stage']);
+ expect(content).not.toMatch(/private-secret|EACCES|private\/path|entitlements-http|update-commit.*yes/);
+ } finally { await fs.rm(root, { recursive: true, force: true }); }
+});
+
it('observes actual tracked CLI calls without capturing license JSON or paths', async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'nexus-log-cli-'));
try {
diff --git a/src/main/backend-diagnostics.ts b/src/main/backend-diagnostics.ts
index 10be9fd..b99e243 100644
--- a/src/main/backend-diagnostics.ts
+++ b/src/main/backend-diagnostics.ts
@@ -9,7 +9,16 @@ import { transferDiagnostic, transferStages } from '../shared/transfer-failure.j
import { 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']);
+const operations = new Set(['keyring', 'account', 'profile', 'achievements', 'library', 'login', 'logout', 'streaming', 'download', 'license', 'run', 'resolve-package', 'service', 'probe', 'social', 'update']);
+// Fixed installer phases and failure codes. They are never derived from
+// messages, paths, URLs or child output.
+const updateStages = new Set([
+ 'update-download', 'update-verify', 'update-validate', 'update-activate', 'update-confirm', 'update-ready',
+ 'update-blocked', 'update-stale', 'update-platform', 'update-manifest', 'update-storage',
+ 'update-download-http', 'update-download-limit', 'update-checksum', 'update-archive', 'update-extract',
+ 'update-file-mismatch', 'update-binary', 'update-permission', 'update-validate',
+ 'update-commit', 'update-discovery', 'update-check-failed', 'update-cleanup', 'update-notify',
+]);
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',
@@ -28,6 +37,7 @@ const stages = new Set([
...sessionStages,
...contentLicenseStages,
...transferStages,
+ ...updateStages,
'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',
@@ -38,10 +48,10 @@ const stages = new Set([
'timeout', 'invalid-response', 'loader-library', 'loader-openssl', 'loader-dbus', 'loader-glibc', 'loader-compiler-runtime',
'panic', 'ready', 'protocol-error', 'cancelled', 'window-error', 'spawn-not-found', 'spawn-permission',
]);
-type Event = 'start' | 'exit' | 'spawn-error' | 'diagnostic' | 'validation';
+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; keyring?: KeyringDiagnostic; socialReceipt?:SocialReceiptDiagnostic };
+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 };
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. */
@@ -83,7 +93,8 @@ export class BackendDiagnostics {
} finally { await handle.close(); }
}
record(data: RecordData): void {
- if (!operations.has(data.operation) || !['start', 'exit', 'spawn-error', 'diagnostic', 'validation'].includes(data.event) || this.pending >= 256) return;
+ 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;
let context: Context;
try { context = this.context(); } catch { context = {}; }
const entry: Record<string, unknown> = {
@@ -91,7 +102,13 @@ export class BackendDiagnostics {
launcher: version(context.launcher), backend: version(context.backend),
source: ['managed', 'external'].includes(context.source ?? '') ? context.source : 'unknown',
};
- if (data.stage && stages.has(data.stage)) entry.stage = data.stage;
+ // Installer stages are a separate fixed vocabulary 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 && stageAllowed) entry.stage = data.stage;
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;
@@ -104,6 +121,9 @@ export class BackendDiagnostics {
entry.socialReceipt={hasMessageId:value.hasMessageId,hasConversationId:value.hasConversationId,nudge:value.nudge,hasError:value.hasError};
}
if (Number.isFinite(data.elapsedMs)) entry.elapsedMs = Math.max(0, Math.min(86_400_000, Math.round(data.elapsedMs!)));
+ // Precommit failures must stay distinguishable from committed activations
+ // that only need attention, and only on the update operation.
+ if (data.operation === 'update' && data.event === 'failure' && typeof data.committed === 'boolean') entry.committed = data.committed;
if (data.operation === 'keyring' && data.event === 'diagnostic' && data.keyring
&& keyringSteps.includes(data.keyring.step) && keyringFailures.includes(data.keyring.failure)) {
entry.keyringStep = data.keyring.step;
diff --git a/src/main/backend-releases.ts b/src/main/backend-releases.ts
index a590f39..0912837 100644
--- a/src/main/backend-releases.ts
+++ b/src/main/backend-releases.ts
@@ -7,12 +7,36 @@ import {
validateBackendManifest, validateBackendArchive, type BackendPackageManifest,
} from './backend-package.js';
import { BACKEND_ARCH_SUFFIX, currentArch, isLinuxElf64, nexusArch, type NexusArch } from './arch.js';
+import { backendDiagnostic } from './backend-diagnostics.js';
export interface BackendArtifact { repository: BackendRepository; tag: string; manifest: BackendPackageManifest; archiveUrl: string }
+/** Fixed installer failure codes. Never derived from messages or paths. */
+export type BackendInstallStage =
+ | 'update-blocked' | 'update-manifest' | 'update-storage' | 'update-download-http' | 'update-download-limit'
+ | 'update-checksum' | 'update-archive' | 'update-extract' | 'update-file-mismatch' | 'update-binary'
+ | 'update-permission' | 'update-validate' | 'update-activate' | 'update-cleanup';
+/** Fixed update operation stages, including the manager-owned boundaries. */
+export type BackendUpdateStage = BackendInstallStage
+ | 'update-platform' | 'update-stale' | 'update-discovery' | 'update-commit' | 'update-confirm' | 'update-notify';
+
+export class BackendInstallError extends Error {
+ readonly status?: number;
+ constructor(readonly stage: BackendUpdateStage, cause: unknown) {
+ const http = cause instanceof BackendHttpError ? cause.status : undefined;
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
+ this.name = 'BackendInstallError';
+ this.status = http;
+ }
+}
+
class BackendHttpError extends Error {
constructor(readonly status: number) { super(`Backend download failed (HTTP ${status}).`); }
}
+/** Discovery transport failures may carry a fixed HTTP status without a stage. */
+export function backendHttpStatus(error: unknown): number | undefined {
+ return error instanceof BackendHttpError ? error.status : undefined;
+}
async function bytes(url: string, fetcher: typeof fetch, limit: number): Promise<Buffer> {
const response = await fetcher(url, { signal: AbortSignal.timeout(60_000) });
@@ -85,38 +109,55 @@ export async function installBackend(
validate: (cli: string) => Promise<void>, assertIdle: () => Promise<void>,
phase: (message: string) => void, runner: typeof run = run,
): Promise<string> {
- if (process.platform !== 'linux' || !nexusArch()) throw new Error('The prebuilt backend supports x86_64 and arm64 Linux only.');
- await assertIdle();
- const manifest = validateBackendManifest(artifact.manifest, currentArch(), artifact.repository);
- backendAssetUrl(artifact.tag, manifest.archive, artifact.archiveUrl, artifact.repository);
- const staging = path.join(managedRoot, `.download-${randomUUID()}`);
- await fs.mkdir(staging, { recursive: true });
+ if (process.platform !== 'linux' || !nexusArch()) throw new BackendInstallError('update-platform', new Error('The prebuilt backend supports x86_64 and arm64 Linux only.'));
+ let stage: BackendInstallStage = 'update-blocked';
+ let staging: string | undefined;
+ let primary: BackendInstallError | undefined;
try {
+ await assertIdle();
+ stage = 'update-manifest';
+ const manifest = validateBackendManifest(artifact.manifest, currentArch(), artifact.repository);
+ backendAssetUrl(artifact.tag, manifest.archive, artifact.archiveUrl, artifact.repository);
+ const download = path.join(managedRoot, `.download-${randomUUID()}`);
+ stage = 'update-storage';
+ await fs.mkdir(download, { recursive: true });
+ staging = download;
phase('Downloading the Nexus backend…');
+ backendDiagnostic({ operation: 'update', event: 'diagnostic', stage: 'update-download' });
+ stage = 'update-download-http';
const archive = path.join(staging, manifest.archive);
const response = await fetcher(artifact.archiveUrl, { signal: AbortSignal.timeout(300_000) });
if (!response.ok || !response.body) throw new BackendHttpError(response.status);
const reader = response.body.getReader();
+ stage = 'update-storage';
const file = await fs.open(archive, 'wx');
const hash = createHash('sha512');
let size = 0;
try {
for (;;) {
+ // Transport reads and local writes fail independently; keep their fixed
+ // stages separate so a broken stream is never reported as storage.
+ stage = 'update-download-http';
const chunk = await reader.read();
if (chunk.done) break;
size += chunk.value.length;
- if (size > 256 * 1024 * 1024) throw new Error('Backend archive exceeds the download limit.');
+ if (size > 256 * 1024 * 1024) throw new BackendInstallError('update-download-limit', new Error('Backend archive exceeds the download limit.'));
hash.update(chunk.value);
+ stage = 'update-storage';
await file.writeFile(chunk.value);
}
} finally { await file.close(); await reader.cancel(); }
phase('Verifying the backend checksum and archive…');
+ backendDiagnostic({ operation: 'update', event: 'diagnostic', stage: 'update-verify' });
+ stage = 'update-checksum';
if (hash.digest('hex') !== manifest.archiveSha512) throw new Error('Backend SHA-512 verification failed.');
+ stage = 'update-archive';
const listing = await runner('tar', ['-tJf', archive], { maxOutput: 100_000 });
const verbose = await runner('tar', ['-tvJf', archive], { maxOutput: 100_000 });
if (listing.code !== 0 || verbose.code !== 0) throw new Error('The backend archive is invalid.');
const packageName = backendPackageName(manifest.version);
validateBackendArchive(listing.output.trimEnd().split('\n'), verbose.output.trimEnd().split('\n'), packageName);
+ stage = 'update-extract';
const extracted = path.join(staging, 'extracted');
await fs.mkdir(extracted);
const result = await runner('tar', ['-xJf', archive, '--no-same-owner', '--no-same-permissions', '-C', extracted]);
@@ -124,25 +165,33 @@ export async function installBackend(
const candidate = path.join(extracted, packageName);
const verifyFiles = async (root: string) => {
for (const [name, expected] of Object.entries(manifest.files)) {
+ stage = 'update-file-mismatch';
const target = path.join(root, name);
if (!(await fs.lstat(target)).isFile() || createHash('sha256').update(await fs.readFile(target)).digest('hex') !== expected) {
throw new Error(`Backend file verification failed: ${name}`);
}
}
for (const name of ['xodus-cli', 'xodus-service']) {
+ stage = 'update-binary';
const header = await fs.readFile(path.join(root, name));
if (!isLinuxElf64(header, currentArch())) {
throw new Error(`The backend binary is not a Linux ${BACKEND_ARCH_SUFFIX[currentArch()]} ELF executable.`);
}
+ stage = 'update-permission';
await fs.chmod(path.join(root, name), 0o755);
await fs.access(path.join(root, name), constants.X_OK);
}
// Never execute xodus-service --help: it starts keychain/device auth.
+ stage = 'update-validate';
+ backendDiagnostic({ operation: 'update', event: 'diagnostic', stage: 'update-validate' });
await validate(path.join(root, 'xodus-cli'));
};
phase('Checking backend commands and runtime libraries…');
await verifyFiles(candidate);
+ stage = 'update-blocked';
await assertIdle();
+ stage = 'update-activate';
+ backendDiagnostic({ operation: 'update', event: 'diagnostic', stage: 'update-activate' });
const release = path.join(managedRoot, 'releases', `${packageName}-${manifest.archiveSha512.slice(0, 16)}`);
await fs.mkdir(path.dirname(release), { recursive: true });
try { await fs.rename(candidate, release); }
@@ -150,7 +199,25 @@ export async function installBackend(
if (!['EEXIST', 'ENOTEMPTY'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error;
await verifyFiles(release);
}
+ stage = 'update-storage';
await fs.writeFile(path.join(release, 'metadata.json'), JSON.stringify(manifest, null, 2));
return path.join(release, 'xodus-cli');
- } finally { await fs.rm(staging, { recursive: true, force: true }); }
+ } catch (error) {
+ primary = error instanceof BackendInstallError ? error : new BackendInstallError(stage, error);
+ throw primary;
+ } finally {
+ if (staging) {
+ try { await fs.rm(staging, { recursive: true, force: true }); }
+ catch (cleanupError) {
+ // A cleanup failure is reported separately and must never replace the
+ // captured installer failure, its user-facing reason or its stage.
+ backendDiagnostic({ operation: 'update', event: 'diagnostic', stage: 'update-cleanup' });
+ if (!primary) {
+ throw new BackendInstallError('update-cleanup', new Error(
+ 'The backend update staging area could not be removed. Check available disk space and profile permissions, then retry.',
+ { cause: cleanupError }));
+ }
+ }
+ }
+ }
}
diff --git a/src/main/backend-update-diagnostics.test.ts b/src/main/backend-update-diagnostics.test.ts
new file mode 100644
index 0000000..cfb3cc9
--- /dev/null
+++ b/src/main/backend-update-diagnostics.test.ts
@@ -0,0 +1,376 @@
+import { createHash, randomBytes } from 'node:crypto';
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+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 } from './backend-package.js';
+import { BACKEND_ARCH_SUFFIX, ELF_MACHINE, currentArch } from './arch.js';
+import { run } from './process.js';
+
+// The installer must reach real tar/filesystem code, while the staged CLI is a
+// synthetic fixture that never executes a real backend or touches an account.
+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 arch = currentArch();
+const version = backendLock.version;
+const packageName = backendPackageName(version, arch);
+const archiveName = `${packageName}.tar.xz`;
+const assetUrl = (asset: string) => `https://github.com/domsvoboda/nexus-backend/releases/download/backend-v${version}/${asset}`;
+const sha = (data: Buffer, algorithm = 'sha256') => createHash(algorithm).update(data).digest('hex');
+const elf = () => {
+ const bytes = Buffer.alloc(64);
+ bytes.set([0x7f, 0x45, 0x4c, 0x46, 2, 1]);
+ bytes.writeUInt16LE(ELF_MACHINE[arch], 18);
+ return bytes;
+};
+
+let root: string;
+let managed: string;
+let log: BackendDiagnostics;
+beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'nexus-backend-update-diagnostics-'));
+ managed = path.join(root, 'xodus-backends');
+ await fs.mkdir(managed);
+ log = new BackendDiagnostics(root);
+ setBackendDiagnostics(log);
+});
+afterEach(async () => {
+ setBackendDiagnostics(undefined);
+ await log.read().catch(() => {});
+ for (const entry of await fs.readdir(managed).catch(() => [] as string[]))
+ if (entry.startsWith('.download-')) await fs.chmod(path.join(managed, entry), 0o700).catch(() => {});
+ await fs.rm(root, { recursive: true, force: true });
+});
+
+/** A tiny synthetic package whose bytes never leave this fixture. */
+async function packageFixture(options: { badDigest?: boolean } = {}) {
+ const build = path.join(root, 'build');
+ const bundle = path.join(build, packageName);
+ await fs.mkdir(bundle, { recursive: true });
+ await fs.writeFile(path.join(bundle, 'xodus-cli'), elf());
+ await fs.writeFile(path.join(bundle, 'xodus-service'), elf());
+ await fs.writeFile(path.join(bundle, 'LICENSE'), 'synthetic license fixture');
+ 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, archiveName), '-C', build, packageName])).code).toBe(0);
+ const bytes = await fs.readFile(path.join(build, archiveName));
+ const archiveSha512 = options.badDigest ? sha(randomBytes(32), 'sha512') : sha(bytes, 'sha512');
+ const manifest = {
+ schema: 2, sourceRepository: 'domsvoboda/nexus-backend', authUi: 'electron', version, commit: backendLock.commit,
+ recipeSha256: backendRecipeSha256, compatibility: backendLock.compatibility, platform: 'linux', arch,
+ archive: archiveName, archiveSha512, files,
+ };
+ return { manifest, bytes };
+}
+
+function fetcherFor(fixture: { manifest: Record<string, unknown>; bytes: Buffer }, options: { omitSource?: boolean; archive?: () => Response | Promise<Response> } = {}) {
+ const requests: string[] = [];
+ const assets = [archiveName, `${packageName}.manifest.json`, `${packageName}.sha512sum`, `${packageName}-source.tar.xz`,
+ ...(options.omitSource ? [] : [`${packageName}-source.sha512sum`])];
+ const fetcher = vi.fn(async (input: URL | RequestInfo) => {
+ const target = String(input); requests.push(target);
+ if (target.includes('/releases?')) return new Response(JSON.stringify([{ tag_name: `backend-v${version}`,
+ assets: assets.map(asset => ({ name: asset, browser_download_url: assetUrl(asset) })) }]));
+ if (target.endsWith('.manifest.json')) return new Response(JSON.stringify(fixture.manifest));
+ if (target.endsWith('.sha512sum')) return new Response(`${fixture.manifest.archiveSha512} ${archiveName}\n`);
+ if (target.endsWith(archiveName)) return options.archive ? options.archive() : new Response(fixture.bytes);
+ return new Response('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 restrictStaging() {
+ const staging = (await fs.readdir(managed)).find(entry => entry.startsWith('.download-'));
+ if (!staging) throw Error('synthetic staging directory missing');
+ await fs.chmod(path.join(managed, staging), 0o500);
+ return path.join(managed, staging);
+}
+
+async function gameSaveFixture() {
+ const save = path.join(root, 'prefix', 'drive_c', 'users', 'synthetic', 'save');
+ await fs.mkdir(save, { recursive: true });
+ const file = path.join(save, 'slot1.sav');
+ await fs.writeFile(file, 'synthetic-save-bytes');
+ return file;
+}
+
+async function seedWorkingBackend() {
+ 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: '0.0.1', delivery: 'release' };
+ const bytes = JSON.stringify(pointer, null, 2);
+ await fs.writeFile(path.join(managed, 'current.json'), bytes);
+ return { pointer: bytes, directory };
+}
+
+async function updateRecords(): Promise<Array<Record<string, unknown>>> {
+ const { content } = await log.read();
+ const lines = content.trim().split('\n').filter(line => line.startsWith('{'));
+ return lines.map(line => JSON.parse(line)).filter(row => row.operation === 'update');
+}
+
+describe('backend update diagnostics', () => {
+ it('records a successful install as fixed stages with no paths, URLs or child output', async () => {
+ const fixture = await packageFixture();
+ await manager(fetcherFor(fixture).fetcher).update(() => {});
+ const records = await updateRecords();
+ expect(records.filter(row => row.event === 'start')).toHaveLength(1);
+ expect(records.filter(row => row.event === 'diagnostic').map(row => row.stage)).toEqual(expect.arrayContaining(['update-download', 'update-verify', 'update-validate', 'update-activate', 'update-ready']));
+ expect(records.filter(row => row.event === 'failure')).toEqual([]);
+ expect(records.filter(row => row.event === 'exit')).toEqual([expect.objectContaining({ code: 0 })]);
+ const { content } = await log.read();
+ expect(content).not.toMatch(/https:|\.tar\.xz|xodus-backends|nexus-backend-update-diagnostics/);
+ });
+
+ it('records a failed release lookup with its fixed HTTP status and no response text', async () => {
+ const fetcher = vi.fn(async () => new Response('private rate-limit detail', { status: 403 })) as unknown as typeof fetch;
+ const selected = manager(fetcher);
+ await expect(selected.update(() => {})).rejects.toThrow('HTTP 403');
+ const records = await updateRecords();
+ expect(records.filter(row => row.event === 'failure')).toEqual([expect.objectContaining({ stage: 'update-discovery', status: 403, committed: false })]);
+ const { content } = await log.read();
+ expect(content).not.toMatch(/private rate-limit|api\.github/);
+ });
+
+ it('records a wrong archive digest as a precommit checksum failure and keeps the old backend usable', async () => {
+ const old = await seedWorkingBackend();
+ const fixture = await packageFixture({ badDigest: true });
+ const selected = manager(fetcherFor(fixture).fetcher);
+ await selected.refresh();
+ expect(selected.current.available).toBe(true);
+ await expect(selected.update(() => {})).rejects.toThrow('SHA-512 verification failed');
+ const records = await updateRecords();
+ expect(records.filter(row => row.event === 'failure')).toEqual([expect.objectContaining({ stage: 'update-checksum', committed: false })]);
+ expect(records.filter(row => row.event === 'exit')).toEqual([expect.objectContaining({ code: -1 })]);
+ expect(await fs.readFile(path.join(managed, 'current.json'), 'utf8')).toBe(old.pointer);
+ expect((await fs.stat(path.join(old.directory, 'xodus-cli'))).isFile()).toBe(true);
+ expect(selected.current.available).toBe(true);
+ expect(selected.current.phase).toContain('no new backend was activated');
+ expect((await fs.readdir(managed)).some(entry => entry.startsWith('.download-'))).toBe(false);
+ const { content } = await log.read();
+ expect(content).not.toMatch(/SHA-512 verification|https:|xodus-backends|nexus-backend-update-diagnostics/);
+ });
+
+ it('records a missing release asset as a discovery failure before any download', async () => {
+ const old = await seedWorkingBackend();
+ const fixture = await packageFixture();
+ const selected = manager(fetcherFor(fixture, { omitSource: true }).fetcher);
+ await selected.refresh();
+ await expect(selected.update(() => {})).rejects.toThrow('No compatible Nexus backend release');
+ const records = await updateRecords();
+ expect(records.filter(row => row.event === 'failure')).toEqual([expect.objectContaining({ stage: 'update-discovery', committed: false })]);
+ expect(await fs.readFile(path.join(managed, 'current.json'), 'utf8')).toBe(old.pointer);
+ expect(selected.current.available).toBe(true);
+ expect(selected.current.phase).toContain('no new backend was activated');
+ });
+
+ it('records a failed pointer publication as a precommit commit failure and keeps the verified release', async () => {
+ await fs.mkdir(path.join(managed, 'current.json'));
+ const fixture = await packageFixture();
+ const selected = manager(fetcherFor(fixture).fetcher);
+ await expect(selected.update(() => {})).rejects.toMatchObject({ committed: false });
+ const records = await updateRecords();
+ expect(records.filter(row => row.event === 'failure')).toEqual([expect.objectContaining({ stage: 'update-commit', committed: false })]);
+ const release = path.join(managed, 'releases', `${packageName}-${String(fixture.manifest.archiveSha512).slice(0, 16)}`);
+ expect((await fs.stat(path.join(release, 'xodus-cli'))).isFile()).toBe(true);
+ expect(selected.current.phase).toContain('no new backend was activated');
+ });
+
+ it('records an unusable managed path as a bounded storage failure without leaking the path', async () => {
+ await fs.rm(managed, { recursive: true, force: true });
+ await fs.writeFile(managed, 'not a directory');
+ const fixture = await packageFixture();
+ const selected = manager(fetcherFor(fixture).fetcher);
+ await expect(selected.update(() => {})).rejects.toMatchObject({ committed: false });
+ const records = await updateRecords();
+ expect(records.filter(row => row.event === 'failure')).toEqual([expect.objectContaining({ stage: 'update-storage', committed: false })]);
+ const { content } = await log.read();
+ expect(content).not.toContain(root);
+ expect(content).not.toMatch(/ENOTDIR|not a directory|xodus-backends/);
+ });
+
+ it.skipIf(process.getuid?.() === 0)('records a permission-denied profile path as update-storage without leaking it', async () => {
+ const denied = path.join(root, 'readonly-profile');
+ await fs.mkdir(denied);
+ await fs.chmod(denied, 0o500);
+ try {
+ const fixture = await packageFixture();
+ const restricted = new BackendManager(denied, '', () => {}, () => false, fetcherFor(fixture).fetcher);
+ await expect(restricted.update(() => {})).rejects.toMatchObject({ committed: false });
+ const records = await updateRecords();
+ expect(records.filter(row => row.event === 'failure')).toEqual([expect.objectContaining({ stage: 'update-storage', committed: false })]);
+ const { content } = await log.read();
+ expect(content).not.toMatch(/readonly-profile|EACCES|xodus-backends/);
+ } finally { await fs.chmod(denied, 0o700); }
+ });
+
+ it('records a broken transport read as update-download-http, not as local storage', async () => {
+ const fixture = await packageFixture();
+ const fetcher = fetcherFor(fixture, { archive: () => new Response(new ReadableStream({
+ start(controller) { controller.error(new Error('private socket reset')); },
+ })) }).fetcher;
+ const selected = manager(fetcher);
+ await expect(selected.update(() => {})).rejects.toMatchObject({ committed: false });
+ const failures = (await updateRecords()).filter(row => row.event === 'failure');
+ expect(failures).toEqual([expect.objectContaining({ stage: 'update-download-http', committed: false })]);
+ const { content } = await log.read();
+ expect(content).not.toMatch(/socket reset|update-storage/);
+ expect((await fs.readdir(managed)).some(entry => entry.startsWith('.download-'))).toBe(false);
+ });
+
+ it('records a local archive write failure as update-storage, not as transport', async () => {
+ const fixture = await packageFixture();
+ const fetcher = fetcherFor(fixture, { archive: async () => {
+ const staging = (await fs.readdir(managed)).find(entry => entry.startsWith('.download-'));
+ if (!staging) throw Error('synthetic staging directory missing');
+ await fs.mkdir(path.join(managed, staging, archiveName));
+ return new Response(fixture.bytes);
+ } }).fetcher;
+ const selected = manager(fetcher);
+ await expect(selected.update(() => {})).rejects.toMatchObject({ committed: false });
+ const failures = (await updateRecords()).filter(row => row.event === 'failure');
+ expect(failures).toEqual([expect.objectContaining({ stage: 'update-storage', committed: false })]);
+ const { content } = await log.read();
+ expect(content).not.toMatch(/EISDIR|update-download-http/);
+ expect((await fs.readdir(managed)).some(entry => entry.startsWith('.download-'))).toBe(false);
+ });
+
+ it('records a standalone release check failure with its own stage and truthful status', async () => {
+ const fetcher = vi.fn(async () => new Response('private rate-limit detail', { status: 403 })) as unknown as typeof fetch;
+ const selected = manager(fetcher);
+ const status = await selected.checkUpdate();
+ expect(status.releaseAvailable).toBe(false);
+ expect(status.updateAvailable).toBe(false);
+ expect(status.checking).toBe(false);
+ expect(status.blockReason).toContain('HTTP 403');
+ const failures = (await updateRecords()).filter(row => row.event === 'failure');
+ expect(failures).toEqual([expect.objectContaining({ stage: 'update-check-failed', committed: false, status: 403 })]);
+ expect((await log.read()).content).not.toMatch(/private rate-limit/);
+ expect(await fs.readdir(managed)).toEqual([]);
+ });
+
+ it('records a duplicate update attempt as update-blocked without releasing the running reservation', async () => {
+ const fixture = await packageFixture();
+ const selected = manager(fetcherFor(fixture).fetcher);
+ let release!: () => void;
+ const paused = new Promise<void>(resolve => { release = resolve; });
+ vi.spyOn(selected, 'externalDownloadRunning').mockReturnValue(paused.then(() => false));
+ const pending = selected.update(() => {}).catch(error => error);
+ expect(selected.current.updating).toBe(true);
+ await expect(selected.update(() => {})).rejects.toThrow('already running');
+ const failures = (await updateRecords()).filter(row => row.event === 'failure');
+ expect(failures).toEqual([expect.objectContaining({ stage: 'update-blocked', committed: false })]);
+ expect(selected.current.updating).toBe(true);
+ release();
+ expect(await pending).toBeUndefined();
+ });
+
+ it.skipIf(process.getuid?.() === 0)('keeps the checksum failure and user reason when staging cleanup also fails', async () => {
+ const old = await seedWorkingBackend();
+ const save = await gameSaveFixture();
+ const fixture = await packageFixture({ badDigest: true });
+ let pulls = 0;
+ const fetcher = fetcherFor(fixture, { archive: () => new Response(new ReadableStream({
+ async pull(controller) {
+ pulls++;
+ if (pulls === 1) { controller.enqueue(new Uint8Array(fixture.bytes)); return; }
+ // The download is complete; make the owned staging directory impossible
+ // to remove so the checksum failure and cleanup failure happen together.
+ if (pulls === 2) await restrictStaging();
+ controller.close();
+ },
+ })) }).fetcher;
+ const selected = manager(fetcher);
+ await selected.refresh();
+ expect(selected.current.available).toBe(true);
+ const error = await selected.update(() => {}).catch(value => value);
+ expect(error).toMatchObject({ committed: false });
+ expect(error.message).toContain('SHA-512 verification failed');
+ expect(selected.current.blockReason).toContain('SHA-512 verification failed');
+ expect(selected.current.phase).toContain('no new backend was activated');
+ const rows = await updateRecords();
+ expect(rows.filter(row => row.event === 'failure')).toEqual([expect.objectContaining({ stage: 'update-checksum', committed: false })]);
+ expect(rows.filter(row => row.event === 'diagnostic' && row.stage === 'update-cleanup')).toHaveLength(1);
+ expect(await fs.readFile(path.join(managed, 'current.json'), 'utf8')).toBe(old.pointer);
+ expect((await fs.stat(path.join(old.directory, 'xodus-cli'))).isFile()).toBe(true);
+ expect(await fs.readFile(save, 'utf8')).toBe('synthetic-save-bytes');
+ expect(selected.current.available).toBe(true);
+ const { content } = await log.read();
+ expect(content).not.toMatch(/EACCES|EPERM|nexus-backend-update-diagnostics|xodus-backends/);
+ });
+
+ it.skipIf(process.getuid?.() === 0)('fails an otherwise valid install as update-cleanup without activating it', async () => {
+ const old = await seedWorkingBackend();
+ const save = await gameSaveFixture();
+ const fixture = await packageFixture();
+ const selected = manager(fetcherFor(fixture).fetcher);
+ await selected.refresh();
+ const internals = selected as unknown as { validate(binary: string): Promise<Record<string, boolean>> };
+ vi.spyOn(internals, 'validate').mockImplementation(async () => {
+ await restrictStaging();
+ return { account: true, run: true, streaming: true, login: true, logout: true, download: true, externalAuth: true, packageSelection: true };
+ });
+ const error = await selected.update(() => {}).catch(value => value);
+ expect(error).toMatchObject({ committed: false });
+ expect(error.message).toContain('staging area could not be removed');
+ expect(selected.current.blockReason).toContain('staging area could not be removed');
+ expect(selected.current.phase).toContain('no new backend was activated');
+ const rows = await updateRecords();
+ expect(rows.filter(row => row.event === 'failure')).toEqual([expect.objectContaining({ stage: 'update-cleanup', committed: false })]);
+ expect(rows.filter(row => row.event === 'diagnostic' && row.stage === 'update-cleanup')).toHaveLength(1);
+ expect(await fs.readFile(path.join(managed, 'current.json'), 'utf8')).toBe(old.pointer);
+ expect((await fs.stat(path.join(old.directory, 'xodus-cli'))).isFile()).toBe(true);
+ const release = path.join(managed, 'releases', `${packageName}-${String(fixture.manifest.archiveSha512).slice(0, 16)}`);
+ expect((await fs.stat(path.join(release, 'xodus-cli'))).isFile()).toBe(true);
+ expect(await fs.readFile(save, 'utf8')).toBe('synthetic-save-bytes');
+ expect(selected.current.available).toBe(true);
+ const { content } = await log.read();
+ expect(content).not.toMatch(/EACCES|EPERM|nexus-backend-update-diagnostics|xodus-backends/);
+ });
+
+ it('records a committed activation that needs attention as committed:true', async () => {
+ const fixture = await packageFixture();
+ const selected = manager(fetcherFor(fixture).fetcher);
+ vi.spyOn(selected, 'refresh').mockRejectedValue(Error('synthetic probe failure'));
+ await expect(selected.update(() => {})).rejects.toMatchObject({ committed: true });
+ const records = await updateRecords();
+ expect(records.filter(row => row.event === 'failure')).toEqual([expect.objectContaining({ stage: 'update-confirm', committed: true })]);
+ expect(records.filter(row => row.event === 'exit')).toEqual([expect.objectContaining({ code: -1 })]);
+ const pointer = JSON.parse(await fs.readFile(path.join(managed, 'current.json'), 'utf8'));
+ expect((await fs.stat(path.join(pointer.binaryPath))).isFile()).toBe(true);
+ expect(selected.current.phase).toContain('needs attention');
+ const { content } = await log.read();
+ expect(content).not.toContain('synthetic probe failure');
+ });
+
+ it('never stores an unallowlisted stage or a raw reason for an update failure', async () => {
+ log.record({ operation: 'update', event: 'failure', stage: 'update-checksum', committed: false, message: 'EACCES ' + root } as never);
+ const records = await updateRecords();
+ expect(records).toEqual([expect.objectContaining({ event: 'failure', stage: 'update-checksum', committed: false })]);
+ const { content } = await log.read();
+ expect(content).not.toContain(root);
+ expect(content).not.toMatch(/EACCES/);
+ });
+});
diff --git a/src/main/backend-update-ipc.test.ts b/src/main/backend-update-ipc.test.ts
new file mode 100644
index 0000000..86a2677
--- /dev/null
+++ b/src/main/backend-update-ipc.test.ts
@@ -0,0 +1,94 @@
+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, expect, it, vi } from 'vitest';
+import { ComponentUpdateAdmission } from './component-update-admission.js';
+import { BackendDiagnostics } from './backend-diagnostics.js';
+import { assertActivityCompatible } from './install-queue.js';
+
+// The actual registerIpc handler statements are transpiled and executed, so the
+// production gate and its fixed diagnostic record are under test, not a copy.
+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 routes = new Set(['backend-update', 'backend-check-update']);
+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 roots: string[] = [];
+afterEach(async () => { for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true }); });
+
+async function fixture() {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'nexus-backend-update-ipc-'));
+ roots.push(root);
+ const log = new BackendDiagnostics(root);
+ const handlers = new Map<string, Function>();
+ const ctx: any = {
+ authState: { running: false }, authJob: undefined, offlinePermissionChanging: false, keyringSupport: { busy: false },
+ shutdownStarted: false, downloadCancellations: new Set(), preparingInstall: false, preparingContent: false,
+ preparingLaunch: false, finalizingGame: false, checkingGameUpdates: false, gameRemovalInProgress: false,
+ gameOperation: undefined, operations: new Map(), installQueue: { size: 0 }, store: { downloads: [] },
+ assertActivityCompatible,
+ backend: { current: { available: true, updating: false, releaseAvailable: true, updateAvailable: true },
+ update: vi.fn(async () => {}), checkUpdate: vi.fn(async () => ({ available: true })) },
+ runtime: { busy: false, current: { updating: false } }, launcherUpdater: { busy: false },
+ emitSnapshot: vi.fn(), refreshAccount: vi.fn(async () => {}),
+ backendDiagnostic: (record: unknown) => log.record(record as never),
+ ipcMain: { handle: (name: string, handler: Function) => handlers.set(name, handler) },
+ };
+ runInNewContext(ts.transpileModule(functions + '\n' + handlerSource, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText, ctx);
+ ctx.componentUpdateAdmission = new ComponentUpdateAdmission(() => ctx.ensureActivityIdle());
+ return { ctx, handlers, log };
+}
+
+async function records(log: BackendDiagnostics) {
+ const { content } = await log.read();
+ return content.trim().split('\n').filter(line => line.startsWith('{')).map(line => JSON.parse(line));
+}
+
+it('records update-blocked without touching the backend or releasing another reservation', async () => {
+ const { ctx, handlers, log } = await fixture();
+ const before = structuredClone(ctx.backend.current);
+ const owner = ctx.componentUpdateAdmission.reserve();
+ await expect(handlers.get('backend-update')!()).rejects.toThrow('Component updates');
+ expect(await records(log)).toEqual([expect.objectContaining({ operation: 'update', event: 'failure', stage: 'update-blocked', committed: false })]);
+ expect(ctx.backend.update).not.toHaveBeenCalled();
+ expect(ctx.backend.current).toEqual(before);
+ expect(ctx.componentUpdateAdmission.busy).toBe(true);
+ ctx.componentUpdateAdmission.release(owner);
+ expect(ctx.componentUpdateAdmission.busy).toBe(false);
+});
+
+it('records update-blocked for another active operation and leaves admission free', async () => {
+ const { ctx, handlers, log } = await fixture();
+ ctx.preparingLaunch = true;
+ const before = structuredClone(ctx.backend.current);
+ await expect(handlers.get('backend-update')!()).rejects.toThrow('game launch is already being prepared');
+ expect(await records(log)).toEqual([expect.objectContaining({ stage: 'update-blocked', committed: false })]);
+ expect(ctx.backend.update).not.toHaveBeenCalled();
+ expect(ctx.backend.current).toEqual(before);
+ expect(ctx.componentUpdateAdmission.busy).toBe(false);
+});
+
+it('does not duplicate start or exit records for a normal IPC update call', async () => {
+ const { ctx, handlers, log } = await fixture();
+ await handlers.get('backend-update')!();
+ expect(ctx.backend.update).toHaveBeenCalledTimes(1);
+ expect(ctx.refreshAccount).toHaveBeenCalledTimes(1);
+ expect(await records(log)).toEqual([]);
+});
+
+it('returns the truthful standalone check status and adds no install record', async () => {
+ const { ctx, handlers, log } = await fixture();
+ const status = { available: true, checking: false, releaseAvailable: false, updateAvailable: false, blockReason: 'Backend release check failed: Backend download failed (HTTP 403).' };
+ ctx.backend.checkUpdate.mockResolvedValueOnce(status);
+ expect(await handlers.get('backend-check-update')!()).toEqual(status);
+ expect(ctx.emitSnapshot).toHaveBeenCalledTimes(1);
+ expect(await records(log)).toEqual([]);
+});
diff --git a/src/main/backend-update-outcomes.test.ts b/src/main/backend-update-outcomes.test.ts
index 5b37909..94ec9c8 100644
--- a/src/main/backend-update-outcomes.test.ts
+++ b/src/main/backend-update-outcomes.test.ts
@@ -6,7 +6,10 @@ import path from 'node:path';
import { BackendManager, BackendMutationError } from './backend.js';
import { discoverBackend, installBackend, type BackendArtifact } from './backend-releases.js';
import { backendLock, backendRecipeSha256 } from './backend-package.js';
-vi.mock('./backend-releases.js', () => ({ discoverBackend: vi.fn(), installBackend: vi.fn() }));
+vi.mock('./backend-releases.js', async importOriginal => {
+ const actual = await importOriginal<typeof import('./backend-releases.js')>();
+ return { ...actual, discoverBackend: vi.fn(), installBackend: vi.fn() };
+});
vi.mock('./process.js', () => ({ run: vi.fn(async () => ({ code: 0, output: '' })) }));
const deferred = <T,>() => { let resolve!: (value: T) => void; const promise = new Promise<T>(r => { resolve = r; }); return { promise, resolve }; };
const artifact = (version = '99.0.0'): BackendArtifact => ({ repository: 'domsvoboda/nexus-backend', tag: `backend-v${version}`, archiveUrl: 'https://example.invalid/unused', manifest: { version, commit: backendLock.commit, compatibility: backendLock.compatibility, recipeSha256: backendRecipeSha256 } } as BackendArtifact);
diff --git a/src/main/backend.ts b/src/main/backend.ts
index 3c79e65..06a9466 100644
--- a/src/main/backend.ts
+++ b/src/main/backend.ts
@@ -5,7 +5,8 @@ import type { BackendCapabilities, BackendStatus } from '../shared/types.js';
import { parseBackendHelp } from '../shared/utils.js';
import { run } from './process.js';
import { backendLock, backendRecipeSha256, compareVersions } from './backend-package.js';
-import { discoverBackend, installBackend, type BackendArtifact } from './backend-releases.js';
+import { discoverBackend, installBackend, backendHttpStatus, type BackendArtifact, BackendInstallError, type BackendUpdateStage } from './backend-releases.js';
+import { backendDiagnostic } from './backend-diagnostics.js';
import type { PreparedComponentUpdate } from './component-updates.js';
import { BackendPrerequisiteError, backendPrerequisiteFailure } from './backend-prerequisites.js';
@@ -212,6 +213,10 @@ export class BackendManager {
const message = (error as Error).message;
this.status.blockReason = message.startsWith('No compatible Nexus backend release')
? message : `Backend release check failed: ${message}`;
+ // A read-only discovery failure is not an install attempt, so the fixed
+ // stage differs from install discovery and no state is mutated.
+ backendDiagnostic({ operation: 'update', event: 'failure', stage: 'update-check-failed', committed: false,
+ status: backendHttpStatus(error) });
} finally { this.status.checking = false; }
return this.current;
}
@@ -288,7 +293,10 @@ export class BackendManager {
async update(onStatus: () => void): Promise<void> { return this.performUpdate(onStatus); }
private async performUpdate(onStatus: () => void, selected?: BackendArtifact, expectedCurrent?: () => Promise<boolean>): Promise<void> {
- if (this.status.updating) throw new Error('A backend installation is already running.');
+ if (this.status.updating) {
+ backendDiagnostic({ operation: 'update', event: 'failure', stage: 'update-blocked', committed: false });
+ throw new Error('A backend installation is already running.');
+ }
// Reserve before the first awaited external activity check. Notification
// failures must also release this reservation.
this.status.updating = true;
@@ -298,14 +306,21 @@ export class BackendManager {
let failure: BackendMutationError | undefined;
let target: BackendMutationTarget | undefined;
let reconciled = false;
+ const started = performance.now();
+ // Fixed installer stages only. No messages, paths, URLs or child output.
+ let stage: BackendUpdateStage = 'update-blocked';
+ backendDiagnostic({ operation: 'update', event: 'start' });
try {
onStatus();
await this.assertUpdateAllowed();
// Keep this operation's verified target independent of later read-only
// release checks, which may replace the manager's discovery cache.
+ stage = 'update-stale';
if (expectedCurrent && !await expectedCurrent()) throw Error('The installed backend changed. Check again.');
+ stage = 'update-discovery';
const artifact = selected ?? await discoverBackend(this.fetcher);
if (!selected) this.artifact = artifact;
+ stage = 'update-storage';
const binaryPath = await installBackend(this.managedRoot, artifact, this.fetcher, async cli => {
const caps = await this.validate(cli);
if (!caps?.account || !caps.run || !caps.streaming || !caps.login || !caps.logout || !caps.download || !caps.externalAuth || !caps.packageSelection) {
@@ -316,13 +331,16 @@ export class BackendManager {
}, () => this.assertUpdateAllowed(), message => {
this.status.phase = message; this.emitLog('backend', message); onStatus();
});
+ stage = 'update-blocked';
await this.assertUpdateAllowed();
+ stage = 'update-stale';
if (expectedCurrent && !await expectedCurrent()) throw Error('The installed backend changed before activation. Check again.');
const manifest = artifact.manifest;
const pointer: ManagedPointer = { commit: manifest.commit, binaryPath, builtAt: new Date().toISOString(),
linuxRunPatch: manifest.compatibility, recipeSha256: manifest.recipeSha256, version: manifest.version, delivery: 'release' };
target = { commit: pointer.commit, binaryPath, version: pointer.version, delivery: pointer.delivery, linuxRunPatch: pointer.linuxRunPatch, recipeSha256: pointer.recipeSha256 };
const temporary = `${this.pointerFile}.${randomUUID()}.tmp`;
+ stage = 'update-commit';
try {
await fs.writeFile(temporary, JSON.stringify(pointer, null, 2));
await fs.rename(temporary, this.pointerFile);
@@ -336,6 +354,8 @@ export class BackendManager {
Object.assign(this.status, { available: false, capabilities: EMPTY_CAPABILITIES, source: 'managed', binaryPath, commit: manifest.commit,
linuxRunPatch: manifest.compatibility, recipeSha256: manifest.recipeSha256,
version: manifest.version, delivery: 'release', phase: 'Backend activated; checking availability.' });
+ stage = 'update-confirm';
+ backendDiagnostic({ operation: 'update', event: 'diagnostic', stage: 'update-confirm' });
const refreshed = await this.refresh();
if (!refreshed.available || refreshed.source !== 'managed' || refreshed.binaryPath !== binaryPath) {
throw new Error('The selected backend could not be confirmed after activation.');
@@ -346,14 +366,23 @@ export class BackendManager {
const latest = cached && compareVersions(cached.version, manifest.version) >= 0 ? cached : manifest;
Object.assign(this.status, { releaseAvailable: Boolean(latest), releaseVersion: latest?.version,
updateAvailable: Boolean(latest && compareVersions(manifest.version, latest.version) < 0), phase: 'Backend is ready.' });
+ backendDiagnostic({ operation: 'update', event: 'diagnostic', stage: 'update-ready' });
} catch (error) {
+ const failureStage = error instanceof BackendInstallError ? error.stage : stage;
+ backendDiagnostic({ operation: 'update', event: 'failure', stage: failureStage, committed,
+ status: error instanceof BackendInstallError ? error.status : backendHttpStatus(error) });
if (committed && !reconciled) Object.assign(this.status, { available: false, capabilities: EMPTY_CAPABILITIES,
source: 'managed', ...target });
failure = this.mutationFailure('update', error, committed, target);
throw failure;
} finally {
this.status.updating = false;
- this.notifyMutation('update', onStatus, committed, target, failure);
+ backendDiagnostic({ operation: 'update', event: 'exit', code: reconciled ? 0 : -1, elapsedMs: performance.now() - started });
+ try { this.notifyMutation('update', onStatus, committed, target, failure); }
+ catch (error) {
+ backendDiagnostic({ operation: 'update', event: 'failure', stage: 'update-notify', committed });
+ throw error;
+ }
}
}
diff --git a/src/main/component-updates-ipc.test.ts b/src/main/component-updates-ipc.test.ts
index 62a820c..2b088c2 100644
--- a/src/main/component-updates-ipc.test.ts
+++ b/src/main/component-updates-ipc.test.ts
@@ -17,7 +17,7 @@ function fixture(){
const handlers=new Map<string,Function>();
const ctx:any={componentUpdates:undefined,authState:{running:false},authJob:undefined,offlinePermissionChanging:false,keyringSupport:{busy:false},shutdownStarted:false,downloadCancellations:new Set(),preparingInstall:false,preparingContent:false,preparingLaunch:false,finalizingGame:false,checkingGameUpdates:false,gameRemovalInProgress:false,gameOperation:undefined,operations:new Map(),installQueue:{size:0},store:{settings:{firstRunCompleted:false},downloads:[]},assertActivityCompatible,
backend:{current:{available:false,updating:false,releaseAvailable:true,updateAvailable:true},update:vi.fn(async()=>{}),rebuild:vi.fn(async()=>{}),checkUpdate:vi.fn(async()=>{})},runtime:{busy:false,current:{updating:false},installManagedRuntime:vi.fn(async()=>{})},launcherUpdater:{busy:false,state:{restartRequired:true},targetPath:'/synthetic/AppImage',install:vi.fn(async()=>{}),rollback:vi.fn(async()=>{}),assertRestartReady:vi.fn(async()=>{})},
- emitSnapshot:vi.fn(),refreshAccount:vi.fn(async()=>{}),refreshInitialAccount:vi.fn(async()=>{}),mainWindow:{isVisible:()=>false},app:{relaunch:vi.fn(),quit:vi.fn()},externalLauncherEnvironment:()=>({}),process:{env:{}},ipcMain:{handle:(name:string,fn:Function)=>handlers.set(name,fn)}};
+ emitSnapshot:vi.fn(),refreshAccount:vi.fn(async()=>{}),refreshInitialAccount:vi.fn(async()=>{}),backendDiagnostic:vi.fn(),mainWindow:{isVisible:()=>false},app:{relaunch:vi.fn(),quit:vi.fn()},externalLauncherEnvironment:()=>({}),process:{env:{}},ipcMain:{handle:(name:string,fn:Function)=>handlers.set(name,fn)}};
runInNewContext(ts.transpileModule(functions+'\n'+handlerSource,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText,ctx);
ctx.componentUpdateAdmission=new ComponentUpdateAdmission(()=>ctx.ensureActivityIdle());
const activity=activityExpressions.map(expression=>runInNewContext('('+expression+')',ctx) as ()=>boolean);
diff --git a/src/main/index.ts b/src/main/index.ts
index bd2b54e..604f64d 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1898,7 +1898,13 @@ function registerIpc(): void {
ipcMain.handle('component-updates-plan', () => componentUpdates!.plan());
ipcMain.handle('component-updates-apply', (_event,id:unknown) => {if(typeof id!=='string'||id.length>80)throw Error('Invalid update plan.');return componentUpdates!.apply(id);});
ipcMain.handle('component-updates-retry', (_event,id:unknown,item:unknown) => {if(typeof id!=='string'||id.length>80||typeof item!=='string'||item.length>80)throw Error('Invalid update retry.');return componentUpdates!.apply(id,item);});
- ipcMain.handle('backend-update', async () => { ensureIdle(); await backend.update(emitSnapshot); await refreshAccount(); });
+ ipcMain.handle('backend-update', async () => {
+ // A rejected activity gate never enters BackendManager, so the attempt is
+ // recorded here as a fixed blocker instead of vanishing from diagnostics.
+ try { ensureIdle(); }
+ catch (error) { backendDiagnostic({ operation: 'update', event: 'failure', stage: 'update-blocked', committed: false }); throw error; }
+ await backend.update(emitSnapshot); await refreshAccount();
+ });
ipcMain.handle('backend-rebuild', async () => { ensureIdle(); await backend.rebuild(emitSnapshot); await refreshAccount(); });
ipcMain.handle('runtime-refresh', async () => {
ensureIdle();