Open-source Xbox-inspired desktop launcher for Xodus on Linux
TypeScript
feat: apply coherent component plans with lifecycle admission and legacy updates
domsvoboda651994d202f7
diff --git a/src/main/backend-update-outcomes.test.ts b/src/main/backend-update-outcomes.test.tsindex 0395d85..5b37909 100644--- a/src/main/backend-update-outcomes.test.ts+++ b/src/main/backend-update-outcomes.test.ts@@ -1,3 +1,5 @@+import {createHash} from 'node:crypto';+import os from 'node:os';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { promises as fs } from 'node:fs';import path from 'node:path';@@ -9,7 +11,7 @@ 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);let root: string;-beforeEach(async () => { vi.resetAllMocks(); root = await fs.mkdtemp('/mnt/data/XodusNexus-work/builds/backend-update-outcomes-'); await fs.mkdir(path.join(root, 'xodus-backends')); vi.mocked(discoverBackend).mockResolvedValue(artifact()); vi.mocked(installBackend).mockResolvedValue(path.join(root, 'selected/xodus-cli')); });+beforeEach(async () => { vi.resetAllMocks(); root = await fs.mkdtemp(path.join(os.tmpdir(),'backend-update-outcomes-')); await fs.mkdir(path.join(root, 'xodus-backends')); vi.mocked(discoverBackend).mockResolvedValue(artifact()); vi.mocked(installBackend).mockResolvedValue(path.join(root, 'selected/xodus-cli')); });afterEach(async () => { await fs.rm(root, { recursive: true, force: true }); });function manager() { const result = new BackendManager(root, '', () => {}, () => false); vi.spyOn(result, 'externalDownloadRunning').mockResolvedValue(false); return result; }function refreshSelected(m: BackendManager) { return vi.spyOn(m, 'refresh').mockImplementation(async () => { expect(m.current.available).toBe(false); expect(m.current.capabilities.login).toBe(false); Object.assign((m as unknown as { status: object }).status, { available: true }); return m.current; }); }@@ -72,6 +74,21 @@ describe('backend mutation boundaries', () => {await fs.writeFile(pointer,'changed');expect(await prepared.isCurrent()).toBe(false);await expect(prepared.apply({identity:Symbol()})).rejects.toMatchObject({committed:false});expect(installBackend).not.toHaveBeenCalled();});+ it('preserves newer discovery completed before a frozen plan begins applying',async()=>{+ const m=manager();await fs.writeFile(path.join(root,'xodus-backends/current.json'),JSON.stringify({binaryPath:'/old',delivery:'release',version:'1.0.0'}));Object.assign((m as unknown as {status:object}).status,{available:true,source:'managed',binaryPath:'/old'});+ vi.mocked(discoverBackend).mockResolvedValueOnce(artifact('99.0.0')).mockResolvedValueOnce(artifact('100.0.0'));+ const prepared=await m.prepareComponentUpdate(()=>{});await m.checkUpdate();refreshSelected(m);await prepared.apply({identity:Symbol()});expect(m.current.version).toBe('99.0.0');expect(m.current.releaseVersion).toBe('100.0.0');expect(m.current.updateAvailable).toBe(true);+ });+ it.each(['binary','service','recipe','delivery'])('rejects changed %s during committed backend reconciliation',async change=>{+ const m=manager(),pointer=path.join(root,'xodus-backends/current.json'),directory=path.join(root,'xodus-backends/releases/verified');await fs.mkdir(directory,{recursive:true});+ const files:Record<string,string>={};for(const name of ['xodus-cli','xodus-service','LICENSE']){const bytes=Buffer.from('verified-'+name);await fs.writeFile(path.join(directory,name),bytes);files[name]=createHash('sha256').update(bytes).digest('hex');}+ const selected=artifact();selected.manifest.files=files as typeof selected.manifest.files;vi.mocked(discoverBackend).mockResolvedValue(selected);vi.mocked(installBackend).mockResolvedValue(path.join(directory,'xodus-cli'));+ await fs.writeFile(pointer,JSON.stringify({binaryPath:'/old',delivery:'release',version:'1.0.0'}));Object.assign((m as unknown as {status:object}).status,{available:true,source:'managed',binaryPath:'/old'});+ vi.spyOn(m,'refresh').mockImplementation(async()=>{Object.assign((m as unknown as {status:object}).status,{available:true});return m.current;});+ let calls=0;const prepared=await m.prepareComponentUpdate(()=>{if(++calls===2)throw Error('notify after commit');});await expect(prepared.apply({identity:Symbol()})).rejects.toMatchObject({committed:true});await expect(prepared.reconcile!({identity:Symbol()})).resolves.toEqual({});+ if(change==='binary'||change==='service')await fs.writeFile(path.join(directory,change==='binary'?'xodus-cli':'xodus-service'),'corrupted');else{const actual=JSON.parse(await fs.readFile(pointer,'utf8'));if(change==='recipe')actual.recipeSha256='changed';else actual.delivery='local';await fs.writeFile(pointer,JSON.stringify(actual));}+ await expect(prepared.reconcile!({identity:Symbol()})).rejects.toMatchObject({retryable:false});expect(installBackend).toHaveBeenCalledOnce();+ });it('keeps operation target A while concurrent discovery records newer B', async () => {const m = manager(), entered = deferred<void>(), release = deferred<void>(); refreshSelected(m);vi.mocked(discoverBackend).mockResolvedValueOnce(artifact('99.0.0')).mockResolvedValueOnce(artifact('100.0.0'));diff --git a/src/main/backend.ts b/src/main/backend.tsindex cc877ce..3c79e65 100644--- a/src/main/backend.ts+++ b/src/main/backend.ts@@ -18,7 +18,7 @@ const EMPTY_CAPABILITIES: BackendCapabilities = {interface ManagedPointer { commit: string; binaryPath: string; builtAt: string; linuxRunPatch?: string; recipeSha256?: string; version?: string; delivery?: 'release' | 'local' }type BackendMutation = 'update' | 'rebuild';-export type BackendMutationTarget = Readonly<Pick<ManagedPointer, 'commit' | 'binaryPath' | 'version' | 'delivery'>>;+export type BackendMutationTarget = Readonly<Pick<ManagedPointer, 'commit' | 'binaryPath' | 'version' | 'delivery' | 'linuxRunPatch' | 'recipeSha256'>>;/** Publication of current.json is a commit boundary, not a durability claim. */export class BackendMutationError extends Error {readonly target?: BackendMutationTarget;@@ -233,13 +233,13 @@ export class BackendManager {item: { ...item, targetVersion: artifact.manifest.version, state: newer ? 'ready' : 'unchanged', reason: undefined },isCurrent: same,apply: async () => {- try { await this.performUpdate(onStatus, artifact, same); target = { commit: this.status.commit!, binaryPath: this.status.binaryPath!, version: this.status.version, delivery: this.status.delivery }; }+ try { await this.performUpdate(onStatus, artifact, same); target = { commit: this.status.commit!, binaryPath: this.status.binaryPath!, version: this.status.version, delivery: this.status.delivery, linuxRunPatch: this.status.linuxRunPatch, recipeSha256: this.status.recipeSha256 }; }catch (error) { if (error instanceof BackendMutationError && error.committed) target = error.target; throw error; }return { committed: true };},reconcile: async () => {const pointer = await this.readPointer();- if (!target || pointer?.binaryPath !== target.binaryPath || pointer.commit !== target.commit || pointer.version !== target.version) throw Error('The activated backend changed. Check again.');+ if (!target || !pointer || (['binaryPath','commit','version','delivery','linuxRunPatch','recipeSha256'] as const).some(key=>pointer[key]!==target![key]) || !await this.matchesPreparedPayload(target,artifact)) throw Object.assign(Error('The activated backend changed. Check again.'), {retryable:false});const refreshed = await this.refresh();if (!refreshed.available || refreshed.source !== 'managed' || refreshed.binaryPath !== target.binaryPath) throw Error('The activated backend is not available.');onStatus(); return {};@@ -247,6 +247,44 @@ export class BackendManager {};}+ private async matchesPreparedPayload(target: BackendMutationTarget, artifact: BackendArtifact): Promise<boolean> {+ try {+ const directory = path.dirname(target.binaryPath), relative = path.relative(this.managedRoot, directory);+ if (relative.startsWith('..') || path.isAbsolute(relative))+ return false;+ let parent = this.managedRoot;+ for (const part of ['', ...relative.split(path.sep)]) {+ parent = path.join(parent, part);+ if (!(await fs.lstat(parent)).isDirectory())+ return false;+ }+ for (const [name, expected] of Object.entries(artifact.manifest.files)) {+ const filename = path.join(directory, name), before = await fs.lstat(filename);+ if (!before.isFile())+ return false;+ const file = await fs.open(filename, constants.O_RDONLY | constants.O_NOFOLLOW);+ try {+ const opened = await file.stat();+ if (opened.dev !== before.dev || opened.ino !== before.ino)+ return false;+ const digest = createHash('sha256');+ for await (const bytes of file.createReadStream({ autoClose: false }))+ digest.update(bytes);+ const after = await file.stat(), named = await fs.lstat(filename);+ if (digest.digest('hex') !== expected || before.dev !== after.dev || before.ino !== after.ino || before.mode !== after.mode || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || named.dev !== before.dev || named.ino !== before.ino || named.ctimeMs !== before.ctimeMs)+ return false;+ }+ finally {+ await file.close();+ }+ }+ return true;+ }+ catch {+ return false;+ }+ }+async update(onStatus: () => void): Promise<void> { return this.performUpdate(onStatus); }private async performUpdate(onStatus: () => void, selected?: BackendArtifact, expectedCurrent?: () => Promise<boolean>): Promise<void> {@@ -267,7 +305,7 @@ export class BackendManager {// release checks, which may replace the manager's discovery cache.if (expectedCurrent && !await expectedCurrent()) throw Error('The installed backend changed. Check again.');const artifact = selected ?? await discoverBackend(this.fetcher);- this.artifact = artifact;+ if (!selected) this.artifact = artifact;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) {@@ -283,7 +321,7 @@ export class BackendManager {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 };+ target = { commit: pointer.commit, binaryPath, version: pointer.version, delivery: pointer.delivery, linuxRunPatch: pointer.linuxRunPatch, recipeSha256: pointer.recipeSha256 };const temporary = `${this.pointerFile}.${randomUUID()}.tmp`;try {await fs.writeFile(temporary, JSON.stringify(pointer, null, 2));@@ -304,7 +342,8 @@ export class BackendManager {}reconciled = true;// A concurrent read-only check may have discovered a newer release.- const latest = this.artifact?.manifest;+ const cached = this.artifact?.manifest;+ 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.' });} catch (error) {@@ -388,7 +427,7 @@ export class BackendManager {await fs.writeFile(path.join(releaseDir, 'metadata.json'), JSON.stringify({ commit, builtAt: new Date().toISOString(), capabilities, linuxRunPatch: LINUX_RUN_PATCH }, null, 2));const pointer: ManagedPointer = { commit, binaryPath: managedCli, builtAt: new Date().toISOString(), linuxRunPatch: LINUX_RUN_PATCH,recipeSha256: backendRecipeSha256, version: backendLock.version, delivery: 'local' };- targetIdentity = { commit, binaryPath: managedCli, version: pointer.version, delivery: pointer.delivery };+ targetIdentity = { commit, binaryPath: managedCli, version: pointer.version, delivery: pointer.delivery, linuxRunPatch: pointer.linuxRunPatch, recipeSha256: pointer.recipeSha256 };const pointerTmp = `${this.pointerFile}.${randomUUID()}.tmp`;try {await fs.writeFile(pointerTmp, JSON.stringify(pointer, null, 2));diff --git a/src/main/catalog-install-ipc.test.ts b/src/main/catalog-install-ipc.test.tsindex 9db0fdd..0441949 100644--- a/src/main/catalog-install-ipc.test.ts+++ b/src/main/catalog-install-ipc.test.ts@@ -20,7 +20,7 @@ function fixture(){let granted=true;const plan=vi.fn(async()=>({choices:[{supported:true,contentId:'content',kind:'Game',productId:id}]}));const run=vi.fn(async()=>{}),prepare=vi.fn(async()=>{});- const context:any={path,assertStoreOfferAccess,authState:{stored:true,running:false,username:'store'},backend:{current:{binaryPath:'/backend',capabilities:{library:true,packageSelection:true,streamingControls:true}},externalDownloadRunning:async()=>false},+ const context:any={componentUpdateAdmission:{assertAllowed:vi.fn()},path,assertStoreOfferAccess,authState:{stored:true,running:false,username:'store'},backend:{current:{binaryPath:'/backend',capabilities:{library:true,packageSelection:true,streamingControls:true}},externalDownloadRunning:async()=>false},store:{settings:{market:'US',runtimeRoot:'/synthetic/runtime'},games:[],downloads,addDownload:async(task:any)=>{downloads.push(task);},updateDownload:async()=>{},removeDownload:async()=>{}},currentMarket:()=> 'US',accountLibrary:{select:vi.fn(),storeAccess:async()=>({account:'store',backend:'/backend',market:'US',configuredMarket:'US',checkedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+60_000).toISOString(),accessByProductId:granted?{[id]:'owned'}:{}})},stopGameUpdateCheck:async()=>{},ensureIdle:()=>{},prepareSystemWallet:async()=>{},preparingInstall:false,gameOperation:undefined,requireBackend:()=>'/backend',safeProductId:(value:string)=>value,diff --git a/src/main/component-update-admission.ts b/src/main/component-update-admission.tsindex e7e66d1..faa4846 100644--- a/src/main/component-update-admission.ts+++ b/src/main/component-update-admission.ts@@ -1,26 +1,30 @@/** Process-local ownership only. No renderer-supplied value can acquire ownership. */-export interface ComponentUpdateOwner { readonly identity: symbol }+export interface ComponentUpdateOwner {+ readonly identity: symbol;+}export class ComponentUpdateAdmission {- private owner?: ComponentUpdateOwner;- constructor(private readonly assertActivityIdle: () => void) {}- get busy(): boolean { return this.owner !== undefined; }- assertAllowed(owner?: ComponentUpdateOwner): void {- if (this.owner && owner !== this.owner) throw Error('Component updates are in progress.');- if (owner && owner !== this.owner) throw Error('The component update reservation has expired.');- }- reserve(): ComponentUpdateOwner {- this.assertAllowed();- this.assertActivityIdle();- const owner = Object.freeze({ identity: Symbol('component-update') });- this.owner = owner;- return owner;- }- assertActivity(owner: ComponentUpdateOwner): void {- this.assertAllowed(owner);- this.assertActivityIdle();- }- release(owner: ComponentUpdateOwner): void {- this.assertAllowed(owner);- this.owner = undefined;- }+ private owner?: ComponentUpdateOwner;+ constructor(private readonly assertActivityIdle: () => void) { }+ get busy(): boolean { return this.owner !== undefined; }+ assertAllowed(owner?: ComponentUpdateOwner): void {+ if (this.owner && owner !== this.owner)+ throw Error('Component updates are in progress.');+ if (owner && owner !== this.owner)+ throw Error('The component update reservation has expired.');+ }+ reserve(): ComponentUpdateOwner {+ this.assertAllowed();+ this.assertActivityIdle();+ const owner = Object.freeze({ identity: Symbol('component-update') });+ this.owner = owner;+ return owner;+ }+ assertActivity(owner: ComponentUpdateOwner): void {+ this.assertAllowed(owner);+ this.assertActivityIdle();+ }+ release(owner: ComponentUpdateOwner): void {+ this.assertAllowed(owner);+ this.owner = undefined;+ }}diff --git a/src/main/component-update-runtime.test.ts b/src/main/component-update-runtime.test.tsnew file mode 100644index 0000000..8506315--- /dev/null+++ b/src/main/component-update-runtime.test.ts@@ -0,0 +1,36 @@+import os from 'node:os';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { promises as fs } from 'node:fs';+import path from 'node:path';+import type { RuntimeManager } from './runtime.js';+import { prepareManagedComponentUpdates } from './component-update-runtime.js';+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(),'component-runtime-'));roots.push(root);+ const pointer=path.join(root,'variants/nexus/current.json');await fs.mkdir(path.dirname(pointer),{recursive:true});await fs.writeFile(pointer,'old');+ const installed={id:'nexus',label:'Nexus',buildId:'A',sourceCommit:'old-source',manifestSha256:'old-manifest'};+ const state:any={runtimeRoot:root,managedFamilies:[{id:'nexus',installed,channel:'stable',version:'old'}]};+ const target={tag:'new',commit:'new-source',candidateSha256:'captured-sha',prerelease:false};+ const runtime:any={get current(){return structuredClone(state);},refreshFamilies:vi.fn(async()=>state.managedFamilies.map((row:any)=>row.installed)),checkManagedRuntimeUpdate:vi.fn(async()=>({updateAvailable:true,available:{candidateSha256:'captured-sha'}})),managedTarget:vi.fn(()=>target),installPreparedManagedRuntime:vi.fn(async()=>({success:true,committed:true,buildId:'B',durability:'confirmed'}))};+ return {root,pointer,state,target,runtime:runtime as RuntimeManager,raw:runtime};+}+describe('managed component adapter',()=>{+ it('never installs an absent optional family or assigns an unknown release channel',async()=>{+ const f=await fixture();f.state.managedFamilies[0].channel=undefined;const entries=await prepareManagedComponentUpdates(f.runtime,()=>{});expect(entries.map(e=>e.item.state)).toEqual(['skipped','skipped']);expect(f.raw.checkManagedRuntimeUpdate).not.toHaveBeenCalled();expect(f.raw.installPreparedManagedRuntime).not.toHaveBeenCalled();+ });+ it('captures exact installed selection and candidate, never global settings or optional installation',async()=>{+ const f=await fixture(),entries=await prepareManagedComponentUpdates(f.runtime,()=>{});expect(entries[0].item.state).toBe('ready');expect(entries[1].item.state).toBe('skipped');expect(await entries[0].isCurrent()).toBe(true);+ const result=await entries[0].apply({identity:Symbol()});expect(result.committed).toBe(true);expect(f.raw.installPreparedManagedRuntime).toHaveBeenCalledWith('nexus',f.target,{allowCachyos:false,allowPrerelease:false},expect.any(Function));+ });+ it('rejects changed pointer bytes or root before child installation',async()=>{+ const f=await fixture(),entries=await prepareManagedComponentUpdates(f.runtime,()=>{});await fs.writeFile(f.pointer,'replacement');expect(await entries[0].isCurrent()).toBe(false);await expect(entries[0].apply({identity:Symbol()})).rejects.toThrow('changed');expect(f.raw.installPreparedManagedRuntime).not.toHaveBeenCalled();+ });+ it('keeps unknown durability committed attention manual, never reinstallation retry',async()=>{+ const f=await fixture();f.raw.installPreparedManagedRuntime.mockResolvedValue({success:false,committed:true,buildId:'B',durability:'unknown',error:'directory sync'});const entries=await prepareManagedComponentUpdates(f.runtime,()=>{});+ await expect(entries[0].apply({identity:Symbol()})).rejects.toMatchObject({committed:true,retryable:false});expect(f.raw.installPreparedManagedRuntime).toHaveBeenCalledOnce();+ });+ it('clearly defers prerequisites against installed versions rather than pretending scheduled updates are installed',async()=>{+ const f=await fixture();f.raw.checkManagedRuntimeUpdate.mockResolvedValue({error:'Backend 99 required'});const entries=await prepareManagedComponentUpdates(f.runtime,()=>{});expect(entries[0].item.state).toBe('deferred');expect(entries[0].item.reason).toContain('Check again after updating');expect(f.raw.installPreparedManagedRuntime).not.toHaveBeenCalled();+ });+});diff --git a/src/main/component-update-runtime.ts b/src/main/component-update-runtime.tsnew file mode 100644index 0000000..3d4c01a--- /dev/null+++ b/src/main/component-update-runtime.ts@@ -0,0 +1,99 @@+import { promises as fs } from 'node:fs';+import path from 'node:path';+import { runtimeFamilies, runtimeFamilyLabels } from '../shared/runtime-selection.js';+import type { RuntimeManager } from './runtime.js';+import type { PreparedComponentUpdate } from './component-updates.js';+/** Read only discovery; absent families and unknown channels never become installers. */+export async function prepareManagedComponentUpdates(runtime: RuntimeManager, onStatus: () => void): Promise<PreparedComponentUpdate[]> {+ const root = runtime.current.runtimeRoot;+ await runtime.refreshFamilies();+ const entries: PreparedComponentUpdate[] = [];+ for (const family of runtimeFamilies) {+ const installed = runtime.current.managedFamilies?.find(row => row.id === family);+ const item = { id: 'runtime-' + family, component: 'runtime' as const, label: runtimeFamilyLabels[family], currentVersion: installed?.version,+ state: 'skipped' as 'ready' | 'unchanged' | 'skipped' | 'deferred', reason: installed?.installed ? 'The installed release channel could not be verified.' : 'This optional runtime family is not installed.' };+ if (!installed?.installed || !installed.channel) {+ entries.push({ item, isCurrent: async () => false, apply: async () => { throw Error(item.reason); } });+ continue;+ }+ const pointerFile = path.join(root, 'variants', family, 'current.json');+ const before = await fs.readFile(pointerFile);+ const policy = { allowCachyos: family === 'nexus-cachyos', allowPrerelease: installed.channel === 'prerelease' };+ const checked = await runtime.checkManagedRuntimeUpdate(family, installed.channel, onStatus), target = runtime.managedTarget(family);+ if (checked.error || !target) {+ entries.push({ item: { ...item, state: 'deferred', reason: (checked.error ?? 'No verified runtime release is available.') + ' Check again after updating or restarting the required component.' }, isCurrent: async () => false, apply: async () => { throw Error('No runtime target.'); } });+ continue;+ }+ if (checked.available?.candidateSha256 !== target.candidateSha256) {+ entries.push({ item: { ...item, state: 'deferred', reason: 'Runtime release selection changed while checking. Check again.' }, isCurrent: async () => false, apply: async () => { throw Error('Runtime release selection changed.'); } });+ continue;+ }+ if (target.prerelease !== (installed.channel === 'prerelease')) {+ entries.push({ item: { ...item, state: 'skipped', reason: 'The proposed release uses a different channel. Choose it explicitly in runtime settings.' }, isCurrent: async () => false, apply: async () => { throw Error('Runtime release channel changed.'); } });+ continue;+ }+ let activatedBuild: string | undefined, durability: string | undefined;+ const same = async () => {+ if (runtime.current.runtimeRoot !== root)+ return false;+ try {+ await runtime.refreshFamilies();+ const current = runtime.current.managedFamilies?.find(row => row.id === family)?.installed;+ return (await fs.readFile(pointerFile)).equals(before) && current?.buildId === installed.installed!.buildId && current.manifestSha256 === installed.installed!.manifestSha256 && current.sourceCommit === installed.installed!.sourceCommit;+ }+ catch {+ return false;+ }+ };+ entries.push({ item: { ...item, state: checked.updateAvailable ? 'ready' : 'unchanged', targetVersion: target.tag, reason: undefined },+ isCurrent: same,+ apply: async () => {+ if (!await same())+ throw Error('The installed runtime changed. Check again.');+ const result = await runtime.installPreparedManagedRuntime(family, target, policy, onStatus);+ activatedBuild = result.buildId;+ durability = result.durability;+ if (!result.success)+ throw Object.assign(Error(result.error ?? 'Runtime installation failed.'), { committed: result.committed, retryable: result.committed && result.durability !== 'confirmed' ? false : undefined });+ return { committed: result.committed };+ },+ reconcile: async () => {+ if (runtime.current.runtimeRoot !== root || !activatedBuild)+ throw Object.assign(Error('Runtime activation context changed. Check again.'), { retryable: false });+ await runtime.refreshFamilies();+ const current = runtime.current.managedFamilies?.find(row => row.id === family)?.installed;+ const pointer = JSON.parse(await fs.readFile(pointerFile, 'utf8'));+ if (current?.buildId !== activatedBuild || current.sourceCommit !== target.commit || pointer.candidateSha256 !== target.candidateSha256)+ throw Object.assign(Error('The activated runtime changed. Check again.'), { retryable: false });+ if (durability !== 'confirmed')+ throw Object.assign(Error('The runtime is selected, but its saved selection still needs manual confirmation.'), { retryable: false });+ onStatus();+ return {};+ },+ });+ }+ return entries;+}+/** Update the existing global Standard selection within its recorded channel,+ * preserving prefix roots and per-game family settings. */+export async function prepareLegacyComponentUpdate(runtime: RuntimeManager, callbacks: import('./runtime.js').LegacyRuntimeUpdateCallbacks, onStatus: () => void): Promise<PreparedComponentUpdate> {+ const prepared = await runtime.prepareLegacyManagedUpdate(callbacks.configuredWine());+ const target = prepared.target;+ const item = { id: 'runtime-legacy', component: 'runtime' as const, label: 'Managed Standard runtime', currentVersion: prepared.currentVersion, targetVersion: target?.version, state: prepared.state, reason: prepared.skipReason };+ if (!target)+ return { item, isCurrent: async () => false, apply: async () => { throw Error('No supported Standard runtime update was selected.'); } };+ const same = async () => {+ if (runtime.current.runtimeRoot !== target.root || callbacks.configuredWine() !== target.installed.configuredWine)+ return false;+ const { legacyManagedState } = await import('./legacy-runtime-state.js');+ return (await legacyManagedState(target.root, callbacks.configuredWine()))?.identity === target.installed.identity;+ };+ return { item, isCurrent: same, apply: async () => {+ if (!await same())+ throw Error('The selected Standard runtime changed. Check again.');+ const result = await runtime.applyLegacyManagedUpdate(target, callbacks, onStatus);+ if (!result.success)+ throw Object.assign(Error(result.error ?? 'Updating the Standard runtime failed.'), { committed: result.committed, retryable: result.committed ? false : undefined });+ return { committed: result.committed };+ } };+}diff --git a/src/main/component-updates-ipc.test.ts b/src/main/component-updates-ipc.test.tsnew file mode 100644index 0000000..62a820c--- /dev/null+++ b/src/main/component-updates-ipc.test.ts@@ -0,0 +1,50 @@+import { readFileSync } from 'node:fs';+import { runInNewContext } from 'node:vm';+import ts from 'typescript';+import { describe, expect, it, vi } from 'vitest';+import { ComponentUpdateAdmission } from './component-update-admission.js';+import { assertActivityCompatible } from './install-queue.js';+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','componentActivityRunning','prepareFirstRunBackend']);+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-rebuild','runtime-family-install','install-launcher-update','rollback-launcher-update','restart-launcher']);+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 activityExpressions:string[]=[];let contextExpression='';+function collect(node:ts.Node):void{if(ts.isNewExpression(node)){const name=node.expression.getText(ast);if(name==='RuntimeManager')activityExpressions.push(node.arguments![2].getText(ast));if(name==='BackendManager')activityExpressions.push(node.arguments![3].getText(ast));if(name==='ComponentUpdates')contextExpression=node.arguments![4].getText(ast);}ts.forEachChild(node,collect);}collect(ast);+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)}};+ 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);+ return {ctx,handlers,activity,gate:ctx.componentUpdateAdmission as ComponentUpdateAdmission};+}+describe('actual main component admission',()=>{+ it.each(['backend-update','backend-rebuild','runtime-family-install','install-launcher-update','rollback-launcher-update','restart-launcher'])('blocks %s while a batch holds ownership',async name=>{+ const {ctx,handlers,gate}=fixture(),owner=gate.reserve();await expect(Promise.resolve().then(()=>handlers.get(name)!({},'nexus','sha',{}))).rejects.toThrow('Component updates');+ expect(ctx.backend.update).not.toHaveBeenCalled();expect(ctx.runtime.installManagedRuntime).not.toHaveBeenCalled();expect(ctx.launcherUpdater.install).not.toHaveBeenCalled();expect(ctx.app.relaunch).not.toHaveBeenCalled();gate.release(owner);+ });+ it.each(['preparingLaunch','finalizingGame','preparingInstall','preparingContent','offlinePermissionChanging','shutdownStarted'])('rejects batch and both manager activity callbacks for %s',flag=>{+ const {ctx,gate,activity}=fixture();ctx[flag]=true;expect(()=>gate.reserve()).toThrow();expect(ctx.componentActivityRunning()).toBe(true);expect(activity).toHaveLength(2);for(const callback of activity)expect(callback()).toBe(true);+ });+ it('rejects wallet/auth/launcher reservations but accepts completed or failed game operations',()=>{+ const {ctx,gate}=fixture();ctx.keyringSupport.busy=true;expect(()=>gate.reserve()).toThrow();ctx.keyringSupport.busy=false;ctx.authJob={};expect(()=>gate.reserve()).toThrow();ctx.authJob=undefined;ctx.launcherUpdater.busy=true;expect(()=>gate.reserve()).toThrow();ctx.launcherUpdater.busy=false;+ for(const status of ['complete','failed']){ctx.gameOperation={status};expect(ctx.componentActivityRunning()).toBe(false);const owner=gate.reserve();gate.release(owner);}+ for(const status of ['preparing','running','stopping']){ctx.gameOperation={status};expect(ctx.componentActivityRunning()).toBe(true);expect(()=>gate.reserve()).toThrow();}+ });+ it('binds actual status context to Store, player and stored state but not its own backend update',()=>{+ const {ctx}=fixture();ctx.store.settings.runtimeRoot='/root';ctx.store.settings.market='US';ctx.authState.username='store';ctx.authState.player='player';ctx.authState.stored=true;+ const context=runInNewContext('('+contextExpression+')',ctx) as ()=>string,before=context();ctx.backend.current.version='new';expect(context()).toBe(before);+ ctx.authState.player='other';expect(context()).not.toBe(before);ctx.authState.player='player';ctx.authState.stored=false;expect(context()).not.toBe(before);+ });+ it('allows a verified pending launcher restart despite an unrelated failed backend result',async()=>{+ const {ctx,handlers}=fixture();ctx.componentUpdates={current:{result:{items:[{id:'backend',outcome:'failed-before-commit'}]}}};await handlers.get('restart-launcher')!({});expect(ctx.launcherUpdater.assertRestartReady).toHaveBeenCalledOnce();expect(ctx.app.relaunch).toHaveBeenCalledOnce();+ });+ it('rechecks batch admission after first-run backend discovery finishes',async()=>{+ const {ctx,gate}=fixture();let release!:()=>void;ctx.backend.checkUpdate.mockImplementation(()=>new Promise<void>(r=>release=r));const pending=ctx.prepareFirstRunBackend();const owner=gate.reserve();release();await pending;expect(ctx.backend.update).not.toHaveBeenCalled();gate.release(owner);+ });+});diff --git a/src/main/component-updates.test.ts b/src/main/component-updates.test.tsindex a9df4de..da823d4 100644--- a/src/main/component-updates.test.ts+++ b/src/main/component-updates.test.ts@@ -25,6 +25,10 @@ describe('component update coordinator', () => {it('retries committed attention by reconciliation only, never reinstallation', async () => {const e=entry('a');e.apply=vi.fn(async()=>{throw Object.assign(Error('account refresh'),{committed:true});});e.reconcile=vi.fn(async()=>({})); const {updates}=fixture([e]);const plan=await updates.plan(),first=await updates.apply(plan.id);expect(first.items[0]).toMatchObject({outcome:'committed-needs-attention',retryable:true});const retry=await updates.apply(plan.id,'a');expect(retry.items[0].outcome).toBe('updated');expect(e.apply).toHaveBeenCalledOnce();expect(e.reconcile).toHaveBeenCalledOnce();});+ it('does not offer endless retry for a committed activation requiring manual repair', async () => {+ const e=entry('a');e.apply=vi.fn(async()=>{throw Object.assign(Error('backup restore failed'),{committed:true,retryable:false});});e.reconcile=vi.fn(async()=>({}));+ const {updates}=fixture([e]);const plan=await updates.plan(),result=await updates.apply(plan.id);expect(result.items[0]).toMatchObject({committed:true,retryable:false,outcome:'committed-needs-attention'});await expect(updates.apply(plan.id,'a')).rejects.toThrow('cannot');expect(e.reconcile).not.toHaveBeenCalled();+ });it('rechecks activity before child apply and retains the prior committed outcome', async () => {const a=entry('a'),b=entry('b');const {updates,idle}=fixture([a,b]);a.apply=vi.fn(async()=>{idle.mockImplementation(()=>{throw Error('closing');});return {committed:true};});const plan=await updates.plan(),r=await updates.apply(plan.id);expect(r.items[0].committed).toBe(true);expect(r.items[1].outcome).toBe('failed-before-commit');expect(b.apply).not.toHaveBeenCalled();});diff --git a/src/main/component-updates.ts b/src/main/component-updates.tsindex 4aae72e..5a31d61 100644--- a/src/main/component-updates.ts+++ b/src/main/component-updates.ts@@ -2,108 +2,133 @@ 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';export interface PreparedComponentUpdate {- readonly item: ComponentUpdatePlanItem;- /** Compare installed identity and context, never silently substitute latest. */- isCurrent(): Promise<boolean>;- apply(owner: ComponentUpdateOwner): Promise<{ committed: boolean; restartRequired?: boolean }>;- /** Postcommit retry must only reconcile existing activation, not install again. */- reconcile?(owner: ComponentUpdateOwner): Promise<{ restartRequired?: boolean }>;+ readonly item: ComponentUpdatePlanItem;+ /** Compare installed identity and context, never silently substitute latest. */+ isCurrent(): Promise<boolean>;+ apply(owner: ComponentUpdateOwner): Promise<{+ committed: boolean;+ restartRequired?: boolean;+ }>;+ /** Postcommit retry must only reconcile existing activation, not install again. */+ reconcile?(owner: ComponentUpdateOwner): Promise<{+ restartRequired?: boolean;+ }>;+}+export interface ComponentUpdateFailure extends Error {+ committed?: boolean;+ retryable?: boolean;}-export interface ComponentUpdateFailure extends Error { committed?: boolean }export class ComponentUpdates {- private prepared: PreparedComponentUpdate[] = [];- private state: ComponentUpdatesStatus = { running: false };- private generation = 0;- private context?: string;- constructor(private readonly admission: ComponentUpdateAdmission,- private readonly discover: () => Promise<PreparedComponentUpdate[]>,- private readonly changed: () => void,- private readonly restartPending: () => boolean,- private readonly currentContext: () => string = () => '') {}- get current(): ComponentUpdatesStatus {- if (this.context !== undefined && this.context !== this.currentContext()) return { running: this.state.running };- return structuredClone(this.state);- }- async plan(): Promise<ComponentUpdatePlan> {- this.admission.assertAllowed();- const generation = ++this.generation;- const context = this.currentContext();- const prepared = await this.discover();- this.admission.assertAllowed();- if (context !== this.currentContext()) throw Error('The component update context changed. Check again.');- if (generation !== this.generation) throw Error('A newer component update check replaced this plan.');- const ids = new Set<string>();- for (const entry of prepared) {- if (!entry.item.id || ids.has(entry.item.id)) throw Error('Duplicate component update identity.');- ids.add(entry.item.id);+ private prepared: PreparedComponentUpdate[] = [];+ private state: ComponentUpdatesStatus = { running: false };+ private generation = 0;+ private context?: string;+ constructor(private readonly admission: ComponentUpdateAdmission, private readonly discover: () => Promise<PreparedComponentUpdate[]>, private readonly changed: () => void, private readonly restartPending: () => boolean, private readonly currentContext: () => string = () => '') { }+ get current(): ComponentUpdatesStatus {+ if (this.context !== undefined && this.context !== this.currentContext())+ return { running: this.state.running };+ return structuredClone(this.state);}- // Launcher last, stable order within the runtime family set.- const rank = { backend: 0, runtime: 1, launcher: 2 };- this.prepared = [...prepared].sort((a, b) => rank[a.item.component] - rank[b.item.component]);- const plan: ComponentUpdatePlan = { id: randomUUID(), createdAt: new Date().toISOString(), items: this.prepared.map(row => structuredClone(row.item)) };- this.context = context;- this.state = { running: false, plan };- this.changed();- return structuredClone(plan);- }- async apply(planId: string, retryItemId?: string): Promise<ComponentUpdateBatchResult> {- // Synchronous reservation closes the first-await window for all child operations.- const owner = this.admission.reserve();- try {- if (!this.state.plan || typeof planId !== 'string' || planId !== this.state.plan.id) throw Error('The component update plan is stale. Check again.');- if (this.context !== this.currentContext()) throw Error('The component update context changed. Check again.');- const previous = this.state.result;- if (retryItemId !== undefined && (!previous || !previous.items.some(row => row.id === retryItemId && row.retryable))) throw Error('This component cannot be retried.');- if (retryItemId === undefined && previous) throw Error('This plan was already executed. Retry an eligible component or check again.');- const results: ComponentUpdateItemResult[] = retryItemId ? structuredClone(previous!.items) : [];- this.state.running = true;- this.changed();- let stopped = false;- for (const entry of this.prepared) {- if (retryItemId && entry.item.id !== retryItemId) continue;- let result: ComponentUpdateItemResult;- const old = previous?.items.find(row => row.id === entry.item.id);- if (stopped) result = { id: entry.item.id, outcome: 'not-run', committed: false, retryable: false, message: 'An earlier component needs attention.' };- else if (entry.item.state !== 'ready') result = { id: entry.item.id, outcome: entry.item.state, committed: false, retryable: false, message: entry.item.reason };- else {- this.state.phase = entry.item.label;- this.changed();- try {- this.admission.assertActivity(owner);- if (this.context !== this.currentContext()) throw Error('The component update context changed. Check again.');- // A committed retry compares the captured target in its reconcile adapter.- if (old?.committed) {- if (!entry.reconcile) throw Object.assign(Error('Activation needs manual reconciliation.'), { committed: true });- await entry.reconcile(owner);- result = { id: entry.item.id, outcome: 'updated', committed: true, retryable: false };- } else if (!await entry.isCurrent()) {- result = { id: entry.item.id, outcome: 'stale', committed: false, retryable: false, message: 'The installed component or update context changed. Check again.' };- stopped = true;- } else {- this.admission.assertActivity(owner);- if (this.context !== this.currentContext()) throw Error('The component update context changed. Check again.');- const applied = await entry.apply(owner);- result = { id: entry.item.id, outcome: 'updated', committed: applied.committed, retryable: false };- }- } catch (error) {- const committed = old?.committed === true || (error as ComponentUpdateFailure)?.committed === true;- result = { id: entry.item.id, outcome: committed ? 'committed-needs-attention' : 'failed-before-commit', committed,- retryable: committed ? Boolean(entry.reconcile) : true, message: error instanceof Error ? error.message : String(error) };- stopped = true;- }+ async plan(): Promise<ComponentUpdatePlan> {+ this.admission.assertAllowed();+ const generation = ++this.generation;+ const context = this.currentContext();+ const prepared = await this.discover();+ this.admission.assertAllowed();+ if (context !== this.currentContext())+ throw Error('The component update context changed. Check again.');+ if (generation !== this.generation)+ throw Error('A newer component update check replaced this plan.');+ const ids = new Set<string>();+ for (const entry of prepared) {+ if (!entry.item.id || ids.has(entry.item.id))+ throw Error('Duplicate component update identity.');+ ids.add(entry.item.id);}- const index = results.findIndex(row => row.id === result.id);- if (index < 0) results.push(result); else results[index] = result;- this.state.result = { planId, items: structuredClone(results), restartRequired: this.restartPending() };+ // Launcher last, stable order within the runtime family set.+ const rank = { backend: 0, runtime: 1, launcher: 2 };+ this.prepared = [...prepared].sort((a, b) => rank[a.item.component] - rank[b.item.component]);+ const plan: ComponentUpdatePlan = { id: randomUUID(), createdAt: new Date().toISOString(), items: this.prepared.map(row => structuredClone(row.item)) };+ this.context = context;+ this.state = { running: false, plan };this.changed();- }- this.state.result = { planId, items: results, restartRequired: this.restartPending() };- return structuredClone(this.state.result);- } finally {- this.state.running = false;- this.state.phase = undefined;- this.admission.release(owner);- this.changed();+ return structuredClone(plan);+ }+ async apply(planId: string, retryItemId?: string): Promise<ComponentUpdateBatchResult> {+ // Synchronous reservation closes the first-await window for all child operations.+ const owner = this.admission.reserve();+ try {+ if (!this.state.plan || typeof planId !== 'string' || planId !== this.state.plan.id)+ throw Error('The component update plan is stale. Check again.');+ if (this.context !== this.currentContext())+ throw Error('The component update context changed. Check again.');+ const previous = this.state.result;+ if (retryItemId !== undefined && (!previous || !previous.items.some(row => row.id === retryItemId && row.retryable)))+ throw Error('This component cannot be retried.');+ if (retryItemId === undefined && previous)+ throw Error('This plan was already executed. Retry an eligible component or check again.');+ const results: ComponentUpdateItemResult[] = retryItemId ? structuredClone(previous!.items) : [];+ this.state.running = true;+ this.changed();+ let stopped = false;+ for (const entry of this.prepared) {+ if (retryItemId && entry.item.id !== retryItemId)+ continue;+ let result: ComponentUpdateItemResult;+ const old = previous?.items.find(row => row.id === entry.item.id);+ if (stopped)+ result = { id: entry.item.id, outcome: 'not-run', committed: false, retryable: false, message: 'An earlier component needs attention.' };+ else if (entry.item.state !== 'ready')+ result = { id: entry.item.id, outcome: entry.item.state, committed: false, retryable: false, message: entry.item.reason };+ else {+ this.state.phase = entry.item.label;+ this.changed();+ try {+ this.admission.assertActivity(owner);+ if (this.context !== this.currentContext())+ throw Error('The component update context changed. Check again.');+ // A committed retry compares the captured target in its reconcile adapter.+ if (old?.committed) {+ if (!entry.reconcile)+ throw Object.assign(Error('Activation needs manual reconciliation.'), { committed: true });+ await entry.reconcile(owner);+ result = { id: entry.item.id, outcome: 'updated', committed: true, retryable: false };+ }+ else if (!await entry.isCurrent()) {+ result = { id: entry.item.id, outcome: 'stale', committed: false, retryable: false, message: 'The installed component or update context changed. Check again.' };+ stopped = true;+ }+ else {+ this.admission.assertActivity(owner);+ if (this.context !== this.currentContext())+ throw Error('The component update context changed. Check again.');+ const applied = await entry.apply(owner);+ result = { id: entry.item.id, outcome: 'updated', committed: applied.committed, retryable: false };+ }+ }+ catch (error) {+ const committed = old?.committed === true || (error as ComponentUpdateFailure)?.committed === true;+ result = { id: entry.item.id, outcome: committed ? 'committed-needs-attention' : 'failed-before-commit', committed,+ retryable: (error as ComponentUpdateFailure)?.retryable !== false && (committed ? Boolean(entry.reconcile) : true), message: error instanceof Error ? error.message : String(error) };+ stopped = true;+ }+ }+ const index = results.findIndex(row => row.id === result.id);+ if (index < 0)+ results.push(result);+ else+ results[index] = result;+ this.state.result = { planId, items: structuredClone(results), restartRequired: this.restartPending() };+ this.changed();+ }+ this.state.result = { planId, items: results, restartRequired: this.restartPending() };+ return structuredClone(this.state.result);+ }+ finally {+ this.state.running = false;+ this.state.phase = undefined;+ this.admission.release(owner);+ this.changed();+ }}- }}diff --git a/src/main/index.ts b/src/main/index.tsindex b636f36..ff8aca4 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,3 +1,6 @@+import { ComponentUpdateAdmission, type ComponentUpdateOwner } from './component-update-admission.js';+import { ComponentUpdates, type PreparedComponentUpdate } from './component-updates.js';+import { prepareManagedComponentUpdates, prepareLegacyComponentUpdate } from './component-update-runtime.js';import {gameRuntimeReadiness} from './game-runtime-readiness.js';import {approvedRuntimeSettings,type RuntimeSettingsRequest} from './runtime-settings.js';import {gameRuntimeSelection} from '../shared/runtime-selection.js';@@ -256,6 +259,8 @@ const keyringSupport = new KeyringSupport(process.env, undefined, process.platfo});const demoArtwork = new Map<string, DemoArtwork>();let launcherUpdater: LauncherUpdater;+let componentUpdates: ComponentUpdates | undefined;+const componentUpdateAdmission = new ComponentUpdateAdmission(() => ensureActivityIdle());const gameUpdates: Record<string, GameUpdate> = {};let checkingGameUpdates = false;let gameUpdateController: AbortController | undefined;@@ -373,6 +378,7 @@ function snapshot(): AppSnapshot {settings: structuredClone(store.settings),auth: structuredClone({ ...authState, gamertag: accountProfile?.value?.gamertag, avatarDataUrl: accountProfile?.value?.avatarDataUrl, saved: savedAccounts, savedAccountsEnabled, licenseAvatarDataUrl: authState.player ? licenseProfile?.value?.avatarDataUrl : undefined, subscription: (authState.player ? licenseProfile : accountProfile)?.value?.subscription }),launcherUpdate: structuredClone(launcherUpdater.state),+ componentUpdates: componentUpdates?.current,gameUpdates: structuredClone(gameUpdates),overlayShortcut:overlayShortcut?.current,downloadProgressSupported: Boolean(backend.current.capabilities.streamingProgressJson),@@ -482,22 +488,69 @@ function requireBackend(command: keyof typeof backend.current.capabilities): strreturn status.binaryPath;}-function ensureIdle(mode?: 'install' | 'launch' | 'remove', ownRuntimeReservation?: RuntimeSettingsReservation): void {- if (ownRuntimeReservation) runtime.assertSettingsReservation(ownRuntimeReservation);- if (offlinePermissionChanging) throw Error('Wait for the offline-permission change to finish.');- if (keyringSupport.busy) throw Error('Wait for the wallet operation to finish.');- if (authState.running || authJob) throw Error('A sign-in operation is already in progress.');- if (shutdownStarted) throw Error('The launcher is closing.');- if (downloadCancellations.size) throw Error('A download is being cancelled. Wait for its cleanup to finish.');- if (preparingInstall || preparingContent) throw new Error('An installation is being prepared.');- if (preparingLaunch) throw new Error('A game launch is already being prepared.');- if (finalizingGame) throw new Error('The previous game is still finishing cleanup.');- if (launcherUpdater?.state.updating) throw new Error('The launcher is being updated.');- if (checkingGameUpdates) throw new Error('A game update check is in progress.');- if (gameRemovalInProgress) throw new Error('A game is being removed. Wait for it to finish.');- assertActivityCompatible(operations.keys(), store.downloads, gameOperation, installQueue.size, mode);- if (backend.current.updating) throw new Error('The backend is being updated.');- if ((runtime.current.updating || runtime.busy) && !ownRuntimeReservation) throw new Error('Xodus Runtime is being installed.');+function ensureIdle(mode?: 'install' | 'launch' | 'remove', ownRuntimeReservation?: RuntimeSettingsReservation, owner?: ComponentUpdateOwner): void {+ componentUpdateAdmission.assertAllowed(owner);+ ensureActivityIdle(mode, ownRuntimeReservation);+}++function ensureActivityIdle(mode?: 'install' | 'launch' | 'remove', ownRuntimeReservation?: RuntimeSettingsReservation): void {+ if (ownRuntimeReservation)+ runtime.assertSettingsReservation(ownRuntimeReservation);+ if (offlinePermissionChanging)+ throw Error('Wait for the offline-permission change to finish.');+ if (keyringSupport.busy)+ throw Error('Wait for the wallet operation to finish.');+ if (authState.running || authJob)+ throw Error('A sign-in operation is already in progress.');+ if (shutdownStarted)+ throw Error('The launcher is closing.');+ if (downloadCancellations.size)+ throw Error('A download is being cancelled. Wait for its cleanup to finish.');+ if (preparingInstall || preparingContent)+ throw new Error('An installation is being prepared.');+ if (preparingLaunch)+ throw new Error('A game launch is already being prepared.');+ if (finalizingGame)+ throw new Error('The previous game is still finishing cleanup.');+ if (launcherUpdater?.busy)+ throw new Error('The launcher is being updated.');+ if (checkingGameUpdates)+ throw new Error('A game update check is in progress.');+ if (gameRemovalInProgress)+ throw new Error('A game is being removed. Wait for it to finish.');+ assertActivityCompatible(operations.keys(), store.downloads, gameOperation, installQueue.size, mode);+ if (backend.current.updating)+ throw new Error('The backend is being updated.');+ if ((runtime.current.updating || runtime.busy) && !ownRuntimeReservation)+ throw new Error('Xodus Runtime is being installed.');+}++function componentActivityRunning(): boolean {+ return offlinePermissionChanging || keyringSupport.busy || authState.running || Boolean(authJob) || shutdownStarted ||+ downloadCancellations.size > 0 || preparingInstall || preparingContent || preparingLaunch || finalizingGame ||+ checkingGameUpdates || gameRemovalInProgress || operations.size > 0 || installQueue.size > 0 || Boolean(gameOperation && ['preparing', 'running', 'stopping'].includes(gameOperation.status)) ||+ store.downloads.some(task => task.status === 'queued' || task.status === 'running');+}++async function prepareComponentUpdates(): Promise<PreparedComponentUpdate[]> {+ const backendPlan = await backend.prepareComponentUpdate(emitSnapshot);+ const backendApply = backendPlan.apply, backendReconcile = backendPlan.reconcile;+ backendPlan.apply = async (owner) => {+ const result = await backendApply(owner);+ try {+ await refreshAccount(false);+ emitSnapshot();+ }+ catch (error) {+ throw Object.assign(new Error('Backend activated, but refreshing the account failed.', { cause: error }), { committed: result.committed });+ }+ return result;+ };+ 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()];}async function syncManagedWinePath(): Promise<void> {@@ -1067,6 +1120,7 @@ function cancellableDownload(id: string): DownloadTask {}function cancelDownload(id: string, mode: 'keep' | 'delete-files' = 'keep'): Promise<void> {+ componentUpdateAdmission.assertAllowed();if (mode !== 'keep' && mode !== 'delete-files') return Promise.reject(Error('Invalid cancellation option.'));if (downloadCancellations.has(id)) return Promise.reject(Error('This download is already being cancelled.'));if (shutdownStarted || preparingInstall || preparingContent || gameRemovalInProgress) return Promise.reject(Error('Wait for the current operation to finish.'));@@ -1657,6 +1711,10 @@ async function loadDemoCovers(): Promise<void> {// the live Microsoft Store catalog so demo screenshots show real data.function registerDemoIpc(catalogMarket: () => string): void {ipcMain.handle('get-snapshot', () => snapshot());+ ipcMain.handle('component-updates-status', () => ({running:false}));+ ipcMain.handle('component-updates-plan', () => {throw Error('Component updates are unavailable in demo mode.');});+ ipcMain.handle('component-updates-apply', () => {throw Error('Component updates are unavailable in demo mode.');});+ ipcMain.handle('component-updates-retry', () => {throw Error('Component updates are unavailable in demo mode.');});ipcMain.handle('backend-refresh', () => snapshot().backend);ipcMain.handle('backend-check-update', () => snapshot().backend);ipcMain.handle('backend-update', () => {});@@ -1823,8 +1881,12 @@ function registerIpc(): void {ipcMain.handle('get-snapshot', () => snapshot());ipcMain.handle('backend-refresh', async () => { const value = await backend.refresh(); await refreshAccount(false); emitSnapshot(); return value; });ipcMain.handle('backend-check-update', async () => { const value = await backend.checkUpdate(); emitSnapshot(); return value; });- ipcMain.handle('backend-update', async () => { await backend.update(emitSnapshot); await refreshAccount(); });- ipcMain.handle('backend-rebuild', async () => { await backend.rebuild(emitSnapshot); await refreshAccount(); });+ ipcMain.handle('component-updates-status', () => componentUpdates!.current);+ 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-rebuild', async () => { ensureIdle(); await backend.rebuild(emitSnapshot); await refreshAccount(); });ipcMain.handle('runtime-refresh', async () => {ensureIdle();return runtime.refreshSelection(emitSnapshot, async () => {@@ -1893,8 +1955,11 @@ function registerIpc(): void {ipcMain.handle('check-launcher-update', async () => { await checkLauncherUpdate(); emitSnapshot(); return snapshot().launcherUpdate; });ipcMain.handle('install-launcher-update', async () => { ensureIdle(); if (authState.running) throw new Error('Wait for sign-in to finish.'); await launcherUpdater.install(); });ipcMain.handle('rollback-launcher-update', async () => { ensureIdle(); await launcherUpdater.rollback(); });- ipcMain.handle('restart-launcher', () => {+ ipcMain.handle('restart-launcher', async () => {ensureIdle();+ const owner=componentUpdateAdmission.reserve();+ try {+ await launcherUpdater.assertRestartReady();if (!launcherUpdater.state.restartRequired || !launcherUpdater.targetPath) throw new Error('No launcher restart is pending.');// AppImage sets these again for the new mount. Do not reuse the old mount.for (const key of ['APPIMAGE', 'APPDIR', 'ARGV0', 'OWD']) delete process.env[key];@@ -1904,6 +1969,7 @@ function registerIpc(): void {else process.env[key] = externalEnvironment[key];}app.relaunch({ execPath: launcherUpdater.targetPath, args: [] }); app.quit();+ } finally {componentUpdateAdmission.release(owner);}});ipcMain.handle('stop-game-update-check', () => stopGameUpdateCheck());ipcMain.handle('check-game-updates', (_event, id?: string) => {@@ -2005,12 +2071,14 @@ function registerIpc(): void {});ipcMain.handle('cancel-download', async (_event, id: string, mode?: 'keep' | 'delete-files') => cancelDownload(id, mode));ipcMain.handle('pause-download', (_event, id: string) => {+ componentUpdateAdmission.assertAllowed();if (downloadCancellations.has(id)) throw Error('This download is being cancelled.');const control = downloadControls.get(id);if (!control) throw new Error('Pause requires a backend with download controls. Update the Nexus backend in Settings.');return control(true);});ipcMain.handle('resume-download', (_event, id: string) => {+ componentUpdateAdmission.assertAllowed();if (downloadCancellations.has(id)) throw Error('This download is being cancelled.');const control = downloadControls.get(id);if (!control) {@@ -2036,8 +2104,8 @@ function registerIpc(): void {}return control(false);});- ipcMain.handle('remove-download', async (_event, id: string) => { if (downloadCancellations.size) throw Error('Wait for cancellation cleanup.'); await store.removeDownload(id); emitSnapshot(); });- ipcMain.handle('clear-finished-downloads', async () => { if (downloadCancellations.size) throw Error('Wait for cancellation cleanup.'); await store.clearFinishedDownloads(); emitSnapshot(); });+ ipcMain.handle('remove-download', async (_event, id: string) => { componentUpdateAdmission.assertAllowed(); if (downloadCancellations.size) throw Error('Wait for cancellation cleanup.'); await store.removeDownload(id); emitSnapshot(); });+ ipcMain.handle('clear-finished-downloads', async () => { componentUpdateAdmission.assertAllowed(); if (downloadCancellations.size) throw Error('Wait for cancellation cleanup.'); await store.clearFinishedDownloads(); emitSnapshot(); });ipcMain.handle('import-game', (_event, input?: string) => importGame(input));ipcMain.handle('game-locales', async (_event, id: string) => {const game = store.games.find((entry) => entry.id === id);@@ -2356,6 +2424,7 @@ async function prepareFirstRunBackend(): Promise<void> {backend.current.updating || !backend.current.releaseAvailable || !backend.current.updateAvailable) return;try {// Uses the same checksum-verified managed installer and activity guards as Settings.+ ensureIdle();await backend.update(emitSnapshot);if (!shutdownStarted && mainWindow?.isVisible()) void refreshInitialAccount().catch(() => {});} catch { /* Keep the installer error visible for an explicit retry in the wizard. */ }@@ -2591,10 +2660,11 @@ app.whenReady().then(async () => {}}await store.patchGames(inspectedGames);- runtime = new RuntimeManager(store.settings.runtimeRoot, emitLog, () => preparingLaunch || finalizingGame || downloadCancellations.size > 0 || operations.size > 0 || installQueue.size > 0 || preparingInstall || backend?.current.updating === true, fetch, process.arch, () => ({launcher:app.getVersion(),backend:backend?.current.version??'0.0.0'}), emitSnapshot);- backend = new BackendManager(app.getPath('userData'), store.settings.externalXodusRoot, emitLog, () => keyringSupport.busy || downloadCancellations.size > 0 || operations.size > 0 || installQueue.size > 0 || preparingInstall || runtime?.busy === true);+ runtime = new RuntimeManager(store.settings.runtimeRoot, emitLog, () => componentActivityRunning() || backend?.current.updating === true || launcherUpdater?.busy === true, fetch, process.arch, () => ({launcher:app.getVersion(),backend:backend?.current.version??'0.0.0'}), emitSnapshot);+ backend = new BackendManager(app.getPath('userData'), store.settings.externalXodusRoot, emitLog, () => componentActivityRunning() || runtime?.busy === true || launcherUpdater?.busy === true);await backend.refresh();await runtime.refresh();+ componentUpdates = new ComponentUpdates(componentUpdateAdmission,prepareComponentUpdates,emitSnapshot,()=>launcherUpdater.state.restartRequired===true,()=>JSON.stringify([store.settings.runtimeRoot,authState.username??null,authState.player??null,authState.stored??null,store.settings.market]));if (!demoMode) {// Reachability of Microsoft's sign-in hosts, kept current for the header// and consulted before a launch so offline play starts without waitingdiff --git a/src/main/launcher-update.test.ts b/src/main/launcher-update.test.tsindex 25932fb..3ff2f48 100644--- a/src/main/launcher-update.test.ts+++ b/src/main/launcher-update.test.ts@@ -3,6 +3,7 @@ import { promises as fs } from 'node:fs';import os from 'node:os';import path from 'node:path';import { createHash } from 'node:crypto';+import { ComponentUpdateAdmission } from './component-update-admission.js';import { LauncherUpdater, launcherCandidate } from './launcher-update.js';import { APPIMAGE_ARCH_SUFFIX, ELF_MACHINE, currentArch, type NexusArch } from './arch.js';const roots: string[] = [];@@ -50,7 +51,7 @@ describe('AppImage updater', () => {const {root,target,updater}=await fixture();const write=fs.writeFile,rename=fs.rename;vi.spyOn(fs,'writeFile').mockImplementation(async(p,data,options)=>{if(String(p).includes('launcher-update.json.'))throw Error('journal failed');return write(p,data,options);});vi.spyOn(fs,'rename').mockImplementation(async(a,b)=>{if(String(a).includes('.nexus-backup-'))throw Error('restore failed');return rename(a,b);});- await expect(updater.install()).rejects.toMatchObject({committed:true});expect(await fs.readFile(target)).toEqual(image(2));expect(updater.state.updating).toBe(false);+ await expect(updater.install()).rejects.toMatchObject({committed:true,retryable:false});expect(await fs.readFile(target)).toEqual(image(2));expect(updater.state.updating).toBe(false);const backups=(await fs.readdir(root)).filter(name=>name.includes('.nexus-backup-'));expect(backups).toHaveLength(1);expect(await fs.readFile(path.join(root,backups[0]))).toEqual(image(1));});it('does not remove a consumed journal temporary path after publication', async () => {@@ -59,7 +60,25 @@ describe('AppImage updater', () => {it('rejects concurrent installation before awaited image validation', async () => {const {updater}=await fixture();let release!:()=>void;const hold=new Promise<void>(r=>release=r);const internal=updater as unknown as {writableImage():Promise<string>};const original=internal.writableImage.bind(updater);vi.spyOn(internal,'writableImage').mockImplementation(async()=>{await hold;return original();});- const pending=updater.install();await expect(updater.install()).rejects.toThrow('pending');release();await pending;+ const pending=updater.install();const admission=new ComponentUpdateAdmission(()=>{if(updater.busy)throw Error('launcher busy');});expect(()=>admission.reserve()).toThrow('busy');await expect(updater.install()).rejects.toThrow('pending');await expect(updater.rollback()).rejects.toThrow('pending');release();await pending;+ });+ it('reserves rollback before awaited image validation and excludes installation', async () => {+ const {updater}=await fixture();await updater.install();let release!:()=>void;const hold=new Promise<void>(r=>release=r);+ const internal=updater as unknown as {writableImage():Promise<string>};const original=internal.writableImage.bind(updater);vi.spyOn(internal,'writableImage').mockImplementation(async()=>{await hold;return original();});+ const pending=updater.rollback();const admission=new ComponentUpdateAdmission(()=>{if(updater.busy)throw Error('launcher busy');});expect(()=>admission.reserve()).toThrow('busy');await expect(updater.rollback()).rejects.toThrow('pending');await expect(updater.install()).rejects.toThrow('pending');release();await pending;+ });+ it.each(['changed','deleted'])('rejects %s activated bytes during targeted reconciliation',async change=>{+ const {root,target,fetcher}=await fixture();let updater!:LauncherUpdater;+ updater=new LauncherUpdater('0.2.2',target,root,()=>{if(updater.state.restartRequired)throw Error('notify after commit');},fetcher);await updater.initialize();const plan=await updater.prepareComponentUpdate();+ await expect(plan.apply({identity:Symbol()})).rejects.toMatchObject({committed:true});+ if(change==='changed')await fs.writeFile(target,image(7));else await fs.rm(target);+ await expect(plan.reconcile!({identity:Symbol()})).rejects.toMatchObject({retryable:false});+ });+ it('rejects a checksum changed after plan approval without replacing installed bytes',async()=>{+ const {root,target,fetcher}=await fixture();let tamper=false;+ const guarded=(async(input:URL|RequestInfo,options?:RequestInit)=>tamper&&String(input).endsWith('.sha512sum')?new Response('0'.repeat(128)+' '+release().assets[0].name+'\n'):fetcher(input,options)) as typeof fetch;+ const updater=new LauncherUpdater('0.2.2',target,root,()=>{},guarded);await updater.initialize();const plan=await updater.prepareComponentUpdate();tamper=true;+ await expect(plan.apply({identity:Symbol()})).rejects.toMatchObject({committed:false});expect(await fs.readFile(target)).toEqual(image(1));expect(updater.busy).toBe(false);});it('rejects a changed installed image from an approved component plan', async () => {const {updater,target}=await fixture();const plan=await updater.prepareComponentUpdate();expect(plan.item.state).toBe('ready');await fs.writeFile(target,image(7));expect(await plan.isCurrent()).toBe(false);await expect(plan.apply({identity:Symbol()})).rejects.toThrow('changed');expect(await fs.readFile(target)).toEqual(image(7));diff --git a/src/main/launcher-update.ts b/src/main/launcher-update.tsindex 775cb2e..9cfaf88 100644--- a/src/main/launcher-update.ts+++ b/src/main/launcher-update.ts@@ -1,4 +1,4 @@-import { constants, promises as fs } from 'node:fs';+import { constants, createReadStream, promises as fs } from 'node:fs';import { createHash, randomUUID } from 'node:crypto';import path from 'node:path';import type { PreparedComponentUpdate } from './component-updates.js';@@ -44,6 +44,8 @@ export class LauncherUpdater {private checking?: Promise<void>;private controller?: AbortController;private mutationReserved = false;+ private activated?: {target:string;version:string;sha512:string;size:number};+ get busy(): boolean { return this.mutationReserved || this.state.updating === true; }cancel(): void { this.controller?.abort(); }constructor(private version: string, private image: string | undefined, private userData: string,private changed: () => void, private fetcher: typeof fetch = fetch, private arch: NexusArch = currentArch()) {@@ -88,33 +90,115 @@ export class LauncherUpdater {} catch (error) { this.state.error = (error as Error).message; }finally { this.state.checking = false; this.state.checkedAt = new Date().toISOString(); this.changed(); }}+ private async checksum(candidate: LauncherCandidate, signal: AbortSignal): Promise<string> {+ const response = await this.fetcher(candidate.checksum.browser_download_url, { signal });+ if (!response.ok || !response.body || candidate.checksum.size > 4096)+ throw Error('Could not download the launcher checksum.');+ const reader = response.body.getReader();+ const chunks: Uint8Array[] = [];+ let size = 0;+ try {+ for (;;) {+ const value = await reader.read();+ if (value.done)+ break;+ size += value.value.length;+ if (size > 4096)+ throw Error('Launcher checksum exceeds its size limit.');+ chunks.push(value.value);+ }+ }+ finally {+ await reader.cancel();+ }+ const match = Buffer.concat(chunks).toString('utf8').trim().match(/^([a-f0-9]{128}) ([A-Za-z0-9._-]+)$/i);+ if (!match || match[2] !== candidate.image.name)+ throw Error('Invalid launcher checksum file.');+ return match[1].toLowerCase();+ }+ private async imageDigest(file: string): Promise<{+ sha512: string;+ size: number;+ }> {+ const before = await fs.stat(file);+ if (!before.isFile() || before.size > 1024 ** 3)+ throw Error('Invalid pending launcher image.');+ const hash = createHash('sha512');+ let size = 0;+ for await (const chunk of createReadStream(file)) {+ size += chunk.length;+ if (size > before.size)+ throw Error('Pending launcher image changed.');+ hash.update(chunk);+ }+ const after = await fs.stat(file);+ if (size !== before.size || before.dev !== after.dev || before.ino !== after.ino || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs)+ throw Error('Pending launcher image changed.');+ return { sha512: hash.digest('hex'), size };+ }+ private async activatedImageMatches(target: string, version: string): Promise<boolean> {+ const expected = this.activated;+ if (!expected || expected.target !== target || expected.version !== version)+ return false;+ try {+ if (await this.writableImage() !== target)+ return false;+ const actual = await this.imageDigest(target);+ return actual.sha512 === expected.sha512 && actual.size === expected.size;+ }+ catch {+ return false;+ }+ }+ async assertRestartReady(): Promise<void> {+ if (this.busy)+ throw Error('A launcher update is still running.');+ if (!this.state.restartRequired || !this.targetPath || !this.activated || !await this.activatedImageMatches(this.targetPath, this.activated.version))+ throw Error('The pending launcher image could not be verified. Check its update before restarting.');+ }async prepareComponentUpdate(): Promise<PreparedComponentUpdate> {- const item = { id: 'launcher', component: 'launcher' as const, label: 'Launcher', currentVersion: this.version,- state: 'skipped' as 'ready' | 'skipped' | 'unchanged' | 'deferred', reason: 'An installed writable AppImage is required.' };- if (this.state.restartRequired) return { item: { ...item, state: 'deferred', reason: 'Restart to use the installed launcher update.' }, isCurrent: async () => false, apply: async () => { throw Error('Restart required.'); } };- let target: string;- try { target = await this.writableImage(); } catch { return { item, isCurrent: async () => false, apply: async () => { throw Error(item.reason); } }; }- const before = await fs.stat(target);- await this.check();- if (this.state.error) throw Error(this.state.error);- const candidate = this.candidate ? structuredClone(this.candidate) : undefined;- const same = async () => {- try { const current = await fs.stat(target); return !this.state.restartRequired && await this.writableImage() === target && current.ino === before.ino && current.dev === before.dev && current.size === before.size && current.mtimeMs === before.mtimeMs && current.ctimeMs === before.ctimeMs; } catch { return false; }- };- return { item: { ...item, state: candidate ? 'ready' : 'unchanged', targetVersion: candidate?.version, reason: undefined },- isCurrent: same,- apply: async () => { if (!candidate) throw Error('No launcher update was selected.'); await this.install(candidate, same); return { committed: true, restartRequired: true }; },- reconcile: async () => { if (!candidate || !this.state.restartRequired || this.journal?.version !== candidate.version || this.targetPath !== target) throw Error('Launcher update needs manual reconciliation.'); return { restartRequired: true }; },- };+ const item = { id: 'launcher', component: 'launcher' as const, label: 'Launcher', currentVersion: this.version,+ state: 'skipped' as 'ready' | 'skipped' | 'unchanged' | 'deferred', reason: 'An installed writable AppImage is required.' };+ if (this.state.restartRequired)+ return { item: { ...item, state: 'deferred', reason: 'Restart to use the installed launcher update.' }, isCurrent: async () => false, apply: async () => { throw Error('Restart required.'); } };+ let target: string;+ try {+ target = await this.writableImage();+ }+ catch {+ return { item, isCurrent: async () => false, apply: async () => { throw Error(item.reason); } };+ }+ const before = await fs.stat(target);+ await this.check();+ if (this.state.error)+ throw Error(this.state.error);+ const candidate = this.candidate ? structuredClone(this.candidate) : undefined;+ const checksum = candidate ? await this.checksum(candidate, AbortSignal.timeout(15000)) : undefined;+ const same = async () => {+ try {+ const current = await fs.stat(target);+ return !this.state.restartRequired && await this.writableImage() === target && current.ino === before.ino && current.dev === before.dev && current.size === before.size && current.mtimeMs === before.mtimeMs && current.ctimeMs === before.ctimeMs;+ }+ catch {+ return false;+ }+ };+ return { item: { ...item, state: candidate ? 'ready' : 'unchanged', targetVersion: candidate?.version, reason: undefined },+ isCurrent: same,+ apply: async () => { if (!candidate)+ throw Error('No launcher update was selected.'); await this.install(candidate, same, checksum); return { committed: true, restartRequired: true }; },+ reconcile: async () => { if (!candidate || !this.state.restartRequired || this.journal?.version !== candidate.version || this.targetPath !== target || !await this.activatedImageMatches(target, candidate.version))+ throw Object.assign(Error('Launcher update needs manual reconciliation.'), { retryable: false }); return { restartRequired: true }; },+ };}- async install(selected?: LauncherCandidate, expectedCurrent?: () => Promise<boolean>): Promise<void> {+ async install(selected?: LauncherCandidate, expectedCurrent?: () => Promise<boolean>, expectedChecksum?: string): Promise<void> {if (this.mutationReserved) throw Error('A launcher update is already pending.');this.mutationReserved = true;- try { await this.performInstall(selected, expectedCurrent); }+ try { await this.performInstall(selected, expectedCurrent, expectedChecksum); }finally { this.mutationReserved = false; }}- private async performInstall(selected?: LauncherCandidate, expectedCurrent?: () => Promise<boolean>): Promise<void> {+ private async performInstall(selected?: LauncherCandidate, expectedCurrent?: () => Promise<boolean>, expectedChecksum?: string): Promise<void> {if (this.state.updating || this.state.restartRequired) throw new Error('A launcher update is already pending.');const candidate = selected ?? this.candidate;if (!candidate) throw new Error('Check for a newer launcher release first.');@@ -133,25 +217,22 @@ export class LauncherUpdater {catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error; }await fs.rm(lockPath); lock = await fs.open(lockPath, 'wx', 0o600);}- let activationCommitted = false;+ let activationCommitted = false, rollbackFailed = false;try {await lock.writeFile(String(process.pid)); await lock.close();const before = await fs.stat(target);const temporary = `${target}.nexus-update-${randomUUID()}`;const backup = `${target}.nexus-backup-${randomUUID()}`;const previousJournal = this.journal;- let replaced = false, backedUp = false, rollbackFailed = false;+ let replaced = false, backedUp = false;let failure: unknown;let failed = false;this.controller = new AbortController();this.state.updating = true; this.state.error = undefined; this.state.progress = 0; this.state.phase = 'Downloading launcher update…';try {this.changed();- const checksumResponse = await this.fetcher(candidate.checksum.browser_download_url, { signal: AbortSignal.any([this.controller.signal, AbortSignal.timeout(15_000)]) });- if (!checksumResponse.ok || candidate.checksum.size > 4096) throw new Error('Could not download the launcher checksum.');- const checksum = (await checksumResponse.text()).trim();- const match = checksum.match(/^([a-f0-9]{128}) ([A-Za-z0-9._-]+)$/i);- if (!match || match[2] !== candidate.image.name) throw new Error('Invalid launcher checksum file.');+ const checksum = await this.checksum(candidate,AbortSignal.any([this.controller.signal,AbortSignal.timeout(15_000)]));+ if(expectedChecksum!==undefined&&checksum!==expectedChecksum)throw Error('The reviewed launcher checksum changed. Check again.');const response = await this.fetcher(candidate.image.browser_download_url, { signal: AbortSignal.any([this.controller.signal, AbortSignal.timeout(600_000)]) });if (!response.ok || !response.body) throw new Error('Could not download the launcher AppImage.');const handle = await fs.open(temporary, 'wx', 0o700);@@ -166,7 +247,7 @@ export class LauncherUpdater {}await handle.sync();} finally { await handle.close(); }- if (bytes !== candidate.image.size || hash.digest('hex') !== match[1].toLowerCase()) throw new Error('Launcher SHA-512 verification failed. Your current launcher was kept.');+ if (bytes !== candidate.image.size || hash.digest('hex') !== checksum) throw new Error('Launcher SHA-512 verification failed. Your current launcher was kept.');if (!isLinuxElf64(header, this.arch) || header.subarray(8, 11).toString('hex') !== '414902') throw new Error(`The update is not a ${APPIMAGE_ARCH_SUFFIX[this.arch]} AppImage.`);const now = await fs.stat(target);this.controller.signal.throwIfAborted();@@ -183,6 +264,7 @@ export class LauncherUpdater {try { await fs.writeFile(journalTemp, JSON.stringify(j), { flag: 'wx', mode: 0o600 }); await fs.rename(journalTemp, journalFile); journalPublished = true; }finally { if (!journalPublished) await fs.rm(journalTemp, { force: true }); }this.journal = j; this.targetPath = target;+ this.activated={target,version:candidate.version,sha512:checksum,size:candidate.image.size};this.state.restartRequired = true; this.state.canRollback = true; this.state.phase = 'Update installed. Restart to use it.';if (previousJournal?.backup) await fs.rm(previousJournal.backup, { force: true }).catch(() => {});} catch (error) {@@ -192,7 +274,7 @@ export class LauncherUpdater {catch (rollbackError) { rollbackFailed = true; failure = new AggregateError([error, rollbackError], 'The launcher was replaced but restoring its backup failed.'); }}this.state.error = failure instanceof Error ? failure.message : String(failure);- throw Object.assign(new Error(this.state.error, { cause: failure }), { committed: activationCommitted });+ throw Object.assign(new Error(this.state.error, { cause: failure }), { committed: activationCommitted, retryable: rollbackFailed ? false : undefined });} finally {let finishingFailure: unknown, finishingFailed = false;try {@@ -203,22 +285,45 @@ export class LauncherUpdater {try { this.changed(); } catch (error) { finishingFailure = finishingFailed ? new AggregateError([finishingFailure,error], 'Launcher cleanup and notification failed.') : error; finishingFailed = true; }if (finishingFailed) {const cause = failed ? new AggregateError([failure,finishingFailure], 'Launcher update needs attention.') : finishingFailure;- throw Object.assign(new Error(cause instanceof Error ? cause.message : String(cause), { cause }), { committed: activationCommitted });+ throw Object.assign(new Error(cause instanceof Error ? cause.message : String(cause), { cause }), { committed: activationCommitted, retryable: rollbackFailed ? false : undefined });}}} finally {await lock.close().catch(() => undefined);- try { await fs.rm(lockPath, { force: true }); } catch (error) { throw Object.assign(new Error('Launcher update lock cleanup failed.', { cause: error }), { committed: activationCommitted }); }+ try { await fs.rm(lockPath, { force: true }); } catch (error) { throw Object.assign(new Error('Launcher update lock cleanup failed.', { cause: error }), { committed: activationCommitted, retryable: rollbackFailed ? false : undefined }); }}}async rollback(): Promise<void> {- if (this.state.updating || !this.journal) throw new Error('No launcher backup is available.');- if (await this.writableImage() !== this.journal.target) throw new Error('The launcher location has changed.');- const stat = await fs.lstat(this.journal.backup);- if (!stat.isFile() || stat.uid !== process.getuid?.()) throw new Error('The launcher backup is unsafe.');- await fs.rename(this.journal.backup, this.journal.target);- await fs.rm(path.join(this.userData, 'launcher-update.json'), { force: true });- this.state.canRollback = false; this.state.restartRequired = true; this.state.phase = 'Previous launcher restored. Restart to use it.';- this.journal = undefined; this.changed();+ if (this.mutationReserved) throw Error('A launcher update is already pending.');+ this.mutationReserved = true;+ try { await this.performRollback(); }+ finally { this.mutationReserved = false; }+ }+ private async performRollback(): Promise<void> {+ if (this.state.updating || !this.journal)+ throw new Error('No launcher backup is available.');+ const journal = this.journal;+ if (await this.writableImage() !== journal.target)+ throw new Error('The launcher location has changed.');+ const stat = await fs.lstat(journal.backup);+ if (!stat.isFile() || stat.uid !== process.getuid?.())+ throw new Error('The launcher backup is unsafe.');+ const digest = await this.imageDigest(journal.backup);+ let committed = false;+ try {+ await fs.rename(journal.backup, journal.target);+ committed = true;+ this.activated = { target: journal.target, version: journal.previousVersion, ...digest };+ this.targetPath = journal.target;+ this.state.canRollback = false;+ this.state.restartRequired = true;+ this.state.phase = 'Previous launcher restored. Restart to use it.';+ this.journal = undefined;+ await fs.rm(path.join(this.userData, 'launcher-update.json'), { force: true });+ this.changed();+ }+ catch (error) {+ throw Object.assign(new Error(error instanceof Error ? error.message : String(error), { cause: error }), { committed });+ }}}diff --git a/src/main/legacy-runtime-state.ts b/src/main/legacy-runtime-state.tsindex b89e945..f032ed5 100644--- a/src/main/legacy-runtime-state.ts+++ b/src/main/legacy-runtime-state.ts@@ -1,31 +1,75 @@-import {constants,promises as fs} from 'node:fs';-import {createHash} from 'node:crypto';+import { constants, promises as fs } from 'node:fs';+import { createHash } from 'node:crypto';import path from 'node:path';-export interface LegacyManagedState {root:string;configuredWine:string;name:string;winePath:string;sourceCommit:string;pointerSha256:string;identity:string;candidateSha256?:string;releaseTag:string;channel?:'stable'|'prerelease';}-const hash=(bytes:Buffer|string)=>createHash('sha256').update(bytes).digest('hex');+export interface LegacyManagedState {+ root: string;+ configuredWine: string;+ name: string;+ winePath: string;+ sourceCommit: string;+ pointerSha256: string;+ identity: string;+ candidateSha256?: string;+ releaseTag: string;+ channel?: 'stable' | 'prerelease';+}+const hash = (bytes: Buffer | string) => createHash('sha256').update(bytes).digest('hex');/** Recognize the existing global Standard installer layout, never a custom* Wine, preview, family variant or arbitrary directory supplied by a caller. */-export async function legacyManagedState(root:string,configuredWine:string):Promise<Readonly<LegacyManagedState>|undefined>{- try{- if(typeof configuredWine!=='string')return;- const current=path.join(root,'current.json'),stamp=await fs.lstat(current);- if(!stamp.isFile()||stamp.size>65536)return;- const bytes=await fs.readFile(current),pointer=JSON.parse(bytes.toString('utf8'));- if(typeof pointer.name!=='string'||!/^nexus-runtime-[0-9][A-Za-z0-9._-]*-g[a-f0-9]{8,40}$/.test(pointer.name)||pointer.name.includes('..'))return;- const hint=pointer.name.match(/-g([a-f0-9]{8,40})$/)![1];- if(typeof pointer.commit!=='string'||!/^runtime-[A-Za-z0-9._-]+-g[a-f0-9]{8,40}$/.test(pointer.commit)||pointer.commit.match(/-g([a-f0-9]{8,40})$/)?.[1]!==hint)return;- const expected=path.join(root,'releases',pointer.name,'files/bin/wine');if(pointer.winePath!==expected)return;- if(configuredWine&&configuredWine!==expected)return;- for(const directory of [root,path.join(root,'releases'),path.join(root,'releases',pointer.name),path.dirname(path.dirname(expected)),path.dirname(expected)])if(!(await fs.lstat(directory)).isDirectory())return;- const metadataFile=path.join(root,'releases',pointer.name,'XODUS_NEXUS_PATCH.json'),metadataStat=await fs.lstat(metadataFile);if(!metadataStat.isFile()||metadataStat.size>2*1024*1024)return;- const metadataBytes=await fs.readFile(metadataFile),metadata=JSON.parse(metadataBytes.toString('utf8')),source=metadata.sourceGraph?.proton;- if(metadata.schema!==1||typeof source!=='string'||!/^[a-f0-9]{40}$/.test(source)||!source.startsWith(hint)||typeof metadata.sourceLockSha256!=='string'||!/^[a-f0-9]{64}$/.test(metadata.sourceLockSha256)||metadata.variant?.family==='nexus-cachyos')return;- if(pointer.sourceRepository!==undefined&&pointer.sourceRepository!=='domsvoboda/nexus-runtime')return;- if(pointer.prerelease!==undefined&&typeof pointer.prerelease!=='boolean')return;- const before=await fs.lstat(expected);if(!before.isFile())return;await fs.access(expected,constants.X_OK);- const file=await fs.open(expected,constants.O_RDONLY|constants.O_NOFOLLOW);const digest=createHash('sha256');try{const opened=await file.stat();if(opened.ino!==before.ino||opened.dev!==before.dev)return;for await(const chunk of file.createReadStream({autoClose:false}))digest.update(chunk);}finally{await file.close();}- const after=await fs.lstat(expected);if(before.ino!==after.ino||before.size!==after.size||before.mtimeMs!==after.mtimeMs||before.ctimeMs!==after.ctimeMs||!(await fs.readFile(current)).equals(bytes))return;- const identity=hash(JSON.stringify([await fs.realpath(root),hash(bytes),hash(metadataBytes),before.dev,before.ino,before.size,before.mtimeMs,before.ctimeMs,digest.digest('hex')]));- return Object.freeze({root,configuredWine,name:pointer.name,winePath:expected,sourceCommit:source,pointerSha256:hash(bytes),identity,releaseTag:pointer.commit,channel:pointer.sourceRepository==='domsvoboda/nexus-runtime'&&typeof pointer.prerelease==='boolean'&&typeof pointer.candidateSha256==='string'&&/^[a-f0-9]{64}$/.test(pointer.candidateSha256)?(pointer.prerelease?'prerelease':'stable'):undefined,candidateSha256:typeof pointer.candidateSha256==='string'&&/^[a-f0-9]{64}$/.test(pointer.candidateSha256)?pointer.candidateSha256:undefined});- }catch{return;}+export async function legacyManagedState(root: string, configuredWine: string): Promise<Readonly<LegacyManagedState> | undefined> {+ try {+ if (typeof configuredWine !== 'string')+ return;+ const current = path.join(root, 'current.json'), stamp = await fs.lstat(current);+ if (!stamp.isFile() || stamp.size > 65536)+ return;+ const bytes = await fs.readFile(current), pointer = JSON.parse(bytes.toString('utf8'));+ if (typeof pointer.name !== 'string' || !/^nexus-runtime-[0-9][A-Za-z0-9._-]*-g[a-f0-9]{8,40}$/.test(pointer.name) || pointer.name.includes('..'))+ return;+ const hint = pointer.name.match(/-g([a-f0-9]{8,40})$/)![1];+ if (typeof pointer.commit !== 'string' || !/^runtime-[A-Za-z0-9._-]+-g[a-f0-9]{8,40}$/.test(pointer.commit) || pointer.commit.match(/-g([a-f0-9]{8,40})$/)?.[1] !== hint)+ return;+ const expected = path.join(root, 'releases', pointer.name, 'files/bin/wine');+ if (pointer.winePath !== expected)+ return;+ if (configuredWine && configuredWine !== expected)+ return;+ for (const directory of [root, path.join(root, 'releases'), path.join(root, 'releases', pointer.name), path.dirname(path.dirname(expected)), path.dirname(expected)])+ if (!(await fs.lstat(directory)).isDirectory())+ return;+ const metadataFile = path.join(root, 'releases', pointer.name, 'XODUS_NEXUS_PATCH.json'), metadataStat = await fs.lstat(metadataFile);+ if (!metadataStat.isFile() || metadataStat.size > 2 * 1024 * 1024)+ return;+ const metadataBytes = await fs.readFile(metadataFile), metadata = JSON.parse(metadataBytes.toString('utf8')), source = metadata.sourceGraph?.proton;+ if (metadata.schema !== 1 || typeof source !== 'string' || !/^[a-f0-9]{40}$/.test(source) || !source.startsWith(hint) || typeof metadata.sourceLockSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(metadata.sourceLockSha256) || metadata.variant?.family === 'nexus-cachyos')+ return;+ if (pointer.sourceRepository !== undefined && pointer.sourceRepository !== 'domsvoboda/nexus-runtime')+ return;+ if (pointer.prerelease !== undefined && typeof pointer.prerelease !== 'boolean')+ return;+ const before = await fs.lstat(expected);+ if (!before.isFile())+ return;+ await fs.access(expected, constants.X_OK);+ const file = await fs.open(expected, constants.O_RDONLY | constants.O_NOFOLLOW);+ const digest = createHash('sha256');+ try {+ const opened = await file.stat();+ if (opened.ino !== before.ino || opened.dev !== before.dev)+ return;+ for await (const chunk of file.createReadStream({ autoClose: false }))+ digest.update(chunk);+ }+ finally {+ await file.close();+ }+ const after = await fs.lstat(expected);+ if (before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || !(await fs.readFile(current)).equals(bytes))+ return;+ const identity = hash(JSON.stringify([await fs.realpath(root), hash(bytes), hash(metadataBytes), before.dev, before.ino, before.size, before.mtimeMs, before.ctimeMs, digest.digest('hex')]));+ return Object.freeze({ root, configuredWine, name: pointer.name, winePath: expected, sourceCommit: source, pointerSha256: hash(bytes), identity, releaseTag: pointer.commit, channel: pointer.sourceRepository === 'domsvoboda/nexus-runtime' && typeof pointer.prerelease === 'boolean' && typeof pointer.candidateSha256 === 'string' && /^[a-f0-9]{64}$/.test(pointer.candidateSha256) ? (pointer.prerelease ? 'prerelease' : 'stable') : undefined, candidateSha256: typeof pointer.candidateSha256 === 'string' && /^[a-f0-9]{64}$/.test(pointer.candidateSha256) ? pointer.candidateSha256 : undefined });+ }+ catch {+ return;+ }}diff --git a/src/main/legacy-runtime-update.test.ts b/src/main/legacy-runtime-update.test.tsindex 395e0c9..462ec63 100644--- a/src/main/legacy-runtime-update.test.ts+++ b/src/main/legacy-runtime-update.test.ts@@ -1,3 +1,4 @@+import {prepareLegacyComponentUpdate} from './component-update-runtime.js';import {afterEach,expect,it,vi} from 'vitest';import {promises as fs} from 'node:fs';import path from 'node:path';import os from 'node:os';import {createHash} from 'node:crypto';import {execFile} from 'node:child_process';import {promisify} from 'node:util';import {RuntimeManager} from './runtime';import * as processModule from './process';@@ -103,3 +104,22 @@ it('requires genuine fixed-repository installed-tag channel evidence for an oldit('supports an ordinary old managed install through an installed tag reference when release target is a branch',async()=>{const f=await fixture(),original=vi.mocked(f.fetcher).getMockImplementation()!;f.old.release.target_commitish='main';vi.mocked(f.fetcher).mockImplementation(async(input,init)=>String(input).includes('/git/ref/tags/')?new Response(JSON.stringify({object:{type:'commit',sha:f.old.commit}})):original(input,init));expect((await f.manager.prepareLegacyManagedUpdate(f.callbacks.configuredWine())).target?.channel).toBe('stable');await f.preserved();});++it.each(['before','after'] as const)('releases the legacy lease and reports %s notification failure truthfully',async phase=>{+ const f=await fixture(),{target}=await f.manager.prepareLegacyManagedUpdate(f.callbacks.configuredWine());let calls=0;+ const result=await f.manager.applyLegacyManagedUpdate(target,f.callbacks,()=>{calls++;if(phase==='before'||calls===2)throw Error('notification fixture');});+ expect(result.success).toBe(false);expect(result.committed).toBe(phase==='after');expect(f.manager.busy).toBe(false);+ const pointer=await fs.readFile(f.pointerFile,'utf8');if(phase==='before')expect(pointer).toBe(f.oldPointer);else expect(JSON.parse(pointer).candidateSha256).toBe(target!.candidateSha256);await f.preserved();+});+it('reports staging cleanup failure after activation without claiming the old runtime stayed active',async()=>{+ const f=await fixture(),{target}=await f.manager.prepareLegacyManagedUpdate(f.callbacks.configuredWine()),original=fs.rm;let injected=false;+ vi.spyOn(fs,'rm').mockImplementation(async(file,options)=>{if(!injected&&String(file).startsWith(path.join(f.runtimeRoot,'.staging-'))){injected=true;throw Error('staging fixture');}return original(file,options);});+ const result=await f.manager.applyLegacyManagedUpdate(target,f.callbacks);expect(result.success).toBe(false);expect(result.committed).toBe(true);expect(result.error).toContain('staging');expect(f.manager.busy).toBe(false);expect(JSON.parse(await fs.readFile(f.pointerFile,'utf8')).candidateSha256).toBe(target!.candidateSha256);await f.preserved();+});++it('executes the Update all legacy adapter with the exact target and preserves existing progress',async()=>{+ const f=await fixture(),entry=await prepareLegacyComponentUpdate(f.manager,f.callbacks,()=>{});expect(entry.item.state).toBe('ready');expect(await entry.isCurrent()).toBe(true);expect((await entry.apply({identity:Symbol()})).committed).toBe(true);expect(f.callbacks.persistSelection).toHaveBeenCalledOnce();await f.preserved();+});+it('keeps legacy postcommit failures manual instead of redownloading on targeted retry',async()=>{+ const f=await fixture(),entry=await prepareLegacyComponentUpdate(f.manager,f.callbacks,()=>{});f.callbacks.persistSelection.mockRejectedValue(Error('settings fault'));await expect(entry.apply({identity:Symbol()})).rejects.toMatchObject({committed:true,retryable:false});expect(entry.reconcile).toBeUndefined();await f.preserved();+});diff --git a/src/main/managed-runtime.test.ts b/src/main/managed-runtime.test.tsindex c78001d..b5953a6 100644--- a/src/main/managed-runtime.test.ts+++ b/src/main/managed-runtime.test.ts@@ -344,3 +344,18 @@ it('checks updates within the recorded prerelease channel even when a stable relvi.mocked(f.fetcher).mockImplementation(async(input,init)=>String(input).includes('/releases?')?new Response(JSON.stringify([stable.release,f.remote.release])):original(input,init));const checked=await f.manager.checkManagedRuntimeUpdate('nexus-cachyos','prerelease');expect(checked.available?.sourceCommit).toBe(f.remote.commit);await expect(f.manager.checkManagedRuntimeUpdate('nexus-cachyos','stable')).rejects.toThrow('channel changed');await f.preserved();});++it('does not fall back past a newest candidate with an unknown channel flag',async()=>{+ const f=await fixture();await f.install();f.setRemote(await payload(f.root,'b'));const malformed=await payload(f.root,'c');delete (malformed.release as {prerelease?:boolean}).prerelease;malformed.release.published_at='2026-11-05T00:00:00Z';const original=vi.mocked(f.fetcher).getMockImplementation()!;+ vi.mocked(f.fetcher).mockImplementation(async(input,init)=>String(input).includes('/releases?')?new Response(JSON.stringify([malformed.release,f.remote.release])):original(input,init));+ const checked=await f.manager.checkManagedRuntimeUpdate('nexus-cachyos','prerelease');expect(checked.available).toBeUndefined();expect(checked.error).toContain('prerelease');await f.preserved();+});++it('installs an exact issued target after a later check selects another release, never the replacement',async()=>{+ const f=await fixture();await f.install();f.setRemote(await payload(f.root,'b'));await f.manager.checkManagedRuntimeUpdate('nexus-cachyos','prerelease');const prepared=f.manager.managedTarget('nexus-cachyos')!;+ const selectedCommit=prepared.commit,old=f.remote;f.setRemote(await payload(f.root,'c'));await f.manager.checkManagedRuntime('nexus-cachyos',policy);expect(f.manager.managedTarget('nexus-cachyos')!.commit).not.toBe(selectedCommit);+ const latest=f.remote,original=vi.mocked(f.fetcher).getMockImplementation()!;+ vi.mocked(f.fetcher).mockImplementation(async(input,init)=>{const name=String(input).split('/').pop()!;const bytes=old.assets.get(name);return bytes?new Response(bytes):original(input,init);});+ const forged=await f.manager.installPreparedManagedRuntime('nexus-cachyos',{...prepared},policy);expect(forged.committed).toBe(false);expect(forged.success).toBe(false);+ const result=await f.manager.installPreparedManagedRuntime('nexus-cachyos',prepared,policy);expect(result.success).toBe(true);expect(f.manager.current.managedFamilies!.find(row=>row.id==='nexus-cachyos')!.installed!.sourceCommit).toBe(selectedCommit);expect(latest.commit).not.toBe(selectedCommit);await f.preserved();+});diff --git a/src/main/managed-runtime.ts b/src/main/managed-runtime.tsindex d34c7c8..4e8f9e3 100644--- a/src/main/managed-runtime.ts+++ b/src/main/managed-runtime.ts@@ -182,7 +182,7 @@ export class ManagedRuntimeManager {// Legacy releases without candidate metadata are not managed-family targets.// Select newest in the chosen channel first, then validate it exactly. Never// fall back past a malformed newest trusted-format candidate.- const candidates = json.filter(item => object(item) && item.draft !== true && (item.prerelease !== true || policy.allowPrerelease) && (channel===undefined||item.prerelease===(channel==='prerelease')) && typeof item.tag_name === 'string' && item.tag_name.startsWith(id === 'nexus' ? 'runtime-' : 'runtime-cachyos-') && Array.isArray(item.assets) && item.assets.some(asset => object(asset) && asset.name === 'candidate.json'));+ const candidates = json.filter(item => object(item) && item.draft !== true && (item.prerelease !== true || policy.allowPrerelease) && (channel===undefined||typeof item.prerelease!=='boolean'||item.prerelease===(channel==='prerelease')) && typeof item.tag_name === 'string' && item.tag_name.startsWith(id === 'nexus' ? 'runtime-' : 'runtime-cachyos-') && Array.isArray(item.assets) && item.assets.some(asset => object(asset) && asset.name === 'candidate.json'));for (const item of candidates)if (typeof item.published_at !== 'string' || !Number.isFinite(Date.parse(item.published_at)))throw Error('Invalid managed runtime publication date');@@ -225,12 +225,15 @@ export class ManagedRuntimeManager {}return structuredClone(state);}- async checkInstalledUpdate(selection:unknown,channel:unknown):Promise<ManagedFamilyStatus>{- const id=familyId(selection);if(channel!=='stable'&&channel!=='prerelease')throw Error('Unknown installed runtime channel');- const installed=await this.installed(id,this.context.root());- if(!installed.provenance||installed.provenance.prerelease!==(channel==='prerelease'))throw Error('Installed runtime channel changed or is not recorded');- return this.check(id,{allowCachyos:id==='nexus-cachyos',allowPrerelease:channel==='prerelease'},channel);- }+ async checkInstalledUpdate(selection: unknown, channel: unknown): Promise<ManagedFamilyStatus> {+ const id = familyId(selection);+ if (channel !== 'stable' && channel !== 'prerelease')+ throw Error('Unknown installed runtime channel');+ const installed = await this.installed(id, this.context.root());+ if (!installed.provenance || installed.provenance.prerelease !== (channel === 'prerelease'))+ throw Error('Installed runtime channel changed or is not recorded');+ return this.check(id, { allowCachyos: id === 'nexus-cachyos', allowPrerelease: channel === 'prerelease' }, channel);+ }/** A frozen internal target is provided for later component coordinators. */target(selection: unknown): Readonly<VerifiedManagedFamilyRelease> | undefined {return this.targets.get(familyId(selection))?.release;@@ -311,33 +314,53 @@ export class ManagedRuntimeManager {throw error;}}- async legacyInstalledChannel(tag:string,name:string,sourceCommit:string):Promise<'stable'|'prerelease'|undefined>{- if(!/^runtime-[A-Za-z0-9._-]+-g[a-f0-9]{8,40}$/.test(tag)||tag.includes('..')||!/^nexus-runtime-[0-9][A-Za-z0-9._-]*-g[a-f0-9]{8,40}$/.test(name))return;- for(const repository of ['domsvoboda/nexus-runtime','domsvoboda/xodus-nexus','domsvoboda/nexus-launcher']){- let metadata:unknown;try{metadata=JSON.parse((await this.bytes(`https://api.github.com/repos/${repository}/releases/tags/${tag}`,2*1024*1024)).toString('utf8'));}catch(error){if((error as {status?:number}).status===404)continue;throw error;}- if(!object(metadata)||metadata.tag_name!==tag||metadata.draft!==false||typeof metadata.prerelease!=='boolean'||!Array.isArray(metadata.assets)||metadata.assets.length>100||typeof metadata.published_at!=='string'||!Number.isFinite(Date.parse(metadata.published_at)))continue;- const assets=metadata.assets;- const binary=name+'-x86_64.tar.xz',checksum=name+'-x86_64.sha512sum';- if(![binary,checksum].every(name=>{const found=assets.filter(item=>object(item)&&item.name===name);return found.length===1&&object(found[0])&&found[0].browser_download_url===`https://github.com/${repository}/releases/download/${tag}/${name}`&&typeof found[0].size==='number'&&Number.isSafeInteger(found[0].size)&&found[0].size>0&&found[0].size<=(name===binary?8*1024**3:65536);} ))continue;- let commit=metadata.target_commitish;- if(typeof commit!=='string'||!/^[a-f0-9]{40}$/.test(commit)){- const ref=JSON.parse((await this.bytes(`https://api.github.com/repos/${repository}/git/ref/tags/${tag}`,65536)).toString('utf8'));- let objectRef:unknown=object(ref)?ref.object:undefined;- for(let depth=0;depth<4&&object(objectRef)&&objectRef.type==='tag'&&typeof objectRef.sha==='string'&&/^[a-f0-9]{40}$/.test(objectRef.sha);depth++){- const annotation=JSON.parse((await this.bytes(`https://api.github.com/repos/${repository}/git/tags/${objectRef.sha}`,65536)).toString('utf8'));objectRef=object(annotation)?annotation.object:undefined;- }- commit=object(objectRef)&&objectRef.type==='commit'?objectRef.sha:undefined;- }- if(commit===sourceCommit)return metadata.prerelease?'prerelease':'stable';- }- return;- }- async downloadPreparedRelease(value:unknown,root:string,file:string,policy:ManagedRuntimeOptions):Promise<VerifiedManagedFamilyRelease>{- if(!object(value))throw Error('Unknown prepared runtime release');const target=this.issuedTargets.get(value as unknown as VerifiedManagedFamilyRelease);- if(!target||target.root!==root||this.context.root()!==root)throw Error('Runtime release preparation changed');- const versions=this.context.versions();const release=verifyManagedFamilyCandidate(target.bytes,parseManagedFamilyRelease(target.release.family,target.input,{...options(policy),arch:this.context.arch??process.arch,launcherVersion:versions.launcher,backendVersion:versions.backend}));- await this.archive({...target,release},file);return release;- }+ async legacyInstalledChannel(tag: string, name: string, sourceCommit: string): Promise<'stable' | 'prerelease' | undefined> {+ if (!/^runtime-[A-Za-z0-9._-]+-g[a-f0-9]{8,40}$/.test(tag) || tag.includes('..') || !/^nexus-runtime-[0-9][A-Za-z0-9._-]*-g[a-f0-9]{8,40}$/.test(name))+ return;+ for (const repository of ['domsvoboda/nexus-runtime', 'domsvoboda/xodus-nexus', 'domsvoboda/nexus-launcher']) {+ let metadata: unknown;+ try {+ metadata = JSON.parse((await this.bytes(`https://api.github.com/repos/${repository}/releases/tags/${tag}`, 2 * 1024 * 1024)).toString('utf8'));+ }+ catch (error) {+ if ((error as {+ status?: number;+ }).status === 404)+ continue;+ throw error;+ }+ if (!object(metadata) || metadata.tag_name !== tag || metadata.draft !== false || typeof metadata.prerelease !== 'boolean' || !Array.isArray(metadata.assets) || metadata.assets.length > 100 || typeof metadata.published_at !== 'string' || !Number.isFinite(Date.parse(metadata.published_at)))+ continue;+ const assets = metadata.assets;+ const binary = name + '-x86_64.tar.xz', checksum = name + '-x86_64.sha512sum';+ if (![binary, checksum].every(name => { const found = assets.filter(item => object(item) && item.name === name); return found.length === 1 && object(found[0]) && found[0].browser_download_url === `https://github.com/${repository}/releases/download/${tag}/${name}` && typeof found[0].size === 'number' && Number.isSafeInteger(found[0].size) && found[0].size > 0 && found[0].size <= (name === binary ? 8 * 1024 ** 3 : 65536); }))+ continue;+ let commit = metadata.target_commitish;+ if (typeof commit !== 'string' || !/^[a-f0-9]{40}$/.test(commit)) {+ const ref = JSON.parse((await this.bytes(`https://api.github.com/repos/${repository}/git/ref/tags/${tag}`, 65536)).toString('utf8'));+ let objectRef: unknown = object(ref) ? ref.object : undefined;+ for (let depth = 0; depth < 4 && object(objectRef) && objectRef.type === 'tag' && typeof objectRef.sha === 'string' && /^[a-f0-9]{40}$/.test(objectRef.sha); depth++) {+ const annotation = JSON.parse((await this.bytes(`https://api.github.com/repos/${repository}/git/tags/${objectRef.sha}`, 65536)).toString('utf8'));+ objectRef = object(annotation) ? annotation.object : undefined;+ }+ commit = object(objectRef) && objectRef.type === 'commit' ? objectRef.sha : undefined;+ }+ if (commit === sourceCommit)+ return metadata.prerelease ? 'prerelease' : 'stable';+ }+ return;+ }+ async downloadPreparedRelease(value: unknown, root: string, file: string, policy: ManagedRuntimeOptions): Promise<VerifiedManagedFamilyRelease> {+ if (!object(value))+ throw Error('Unknown prepared runtime release');+ const target = this.issuedTargets.get(value as unknown as VerifiedManagedFamilyRelease);+ if (!target || target.root !== root || this.context.root() !== root)+ throw Error('Runtime release preparation changed');+ const versions = this.context.versions();+ const release = verifyManagedFamilyCandidate(target.bytes, parseManagedFamilyRelease(target.release.family, target.input, { ...options(policy), arch: this.context.arch ?? process.arch, launcherVersion: versions.launcher, backendVersion: versions.backend }));+ await this.archive({ ...target, release }, file);+ return release;+ }private async archive(target: Target, file: string): Promise<void> {const asset = target.release.assets.binary, record = target.release.files.find(item => item.name === asset.name)!;const checksumAsset = target.release.assets.checksum, checksumRecord = target.release.files.find(item => item.name === checksumAsset.name)!, sum = await this.bytes(checksumAsset.url, 65536, checksumAsset.size);@@ -367,7 +390,7 @@ export class ManagedRuntimeManager {if (bytes !== asset.size || h256.digest('hex') !== record.sha256 || h512.digest('hex') !== line[1])throw Error('Runtime archive checksum mismatch');}- async install(selection: unknown, expected: unknown, value: unknown): Promise<ManagedFamilyInstallResult> {+ async install(selection: unknown, expected: unknown, value: unknown, prepared?:Readonly<VerifiedManagedFamilyRelease>): Promise<ManagedFamilyInstallResult> {const id = familyId(selection), state = this.states.get(id)!, lease = this.context.reserve();let staging: string | undefined, committed = false, buildId: string | undefined, durability: ManagedFamilyInstallResult['durability'] = 'not-committed';this.selectionEpoch++;@@ -387,8 +410,8 @@ export class ManagedRuntimeManager {};};try {- const selected = this.targets.get(id);- if (!selected || selected.root !== lease.root || typeof expected !== 'string' || selected.release.candidateSha256 !== expected)+ const selected = prepared ? this.issuedTargets.get(prepared) : this.targets.get(id);+ if (!selected || selected.release.family !== id || selected.root !== lease.root || typeof expected !== 'string' || selected.release.candidateSha256 !== expected)throw Error('Check this runtime release again before installing');const policy = await this.policy(id, lease.root, value), versions = this.context.versions();const release = verifyManagedFamilyCandidate(selected.bytes, parseManagedFamilyRelease(id, selected.input, {diff --git a/src/main/offline-actions-ipc.test.ts b/src/main/offline-actions-ipc.test.tsindex 0ec0fda..074d961 100644--- a/src/main/offline-actions-ipc.test.ts+++ b/src/main/offline-actions-ipc.test.ts@@ -6,7 +6,7 @@ import {expect,it,vi} from 'vitest';const source=readFileSync(new URL('./index.ts',import.meta.url),'utf8');const parsed=ts.createSourceFile('index.ts',source,ts.ScriptTarget.Latest,true);-const names=new Set(['requireBackend','ensureIdle','offlineDataRoot','assertOfflineScope']);+const names=new Set(['requireBackend','ensureIdle','ensureActivityIdle','offlineDataRoot','assertOfflineScope']);const functions=parsed.statements.filter(node=>ts.isFunctionDeclaration(node)&&node.name&&names.has(node.name.text)).map(node=>node.getText(parsed)).join('\n');const start=source.indexOf(" ipcMain.handle('offline-permissions'",source.indexOf('function registerIpc():'));const routes=source.slice(start,source.indexOf(" ipcMain.handle('catalog-search'",start));@@ -18,7 +18,7 @@ function fixture(){const store={settings:{runtimeRoot:'/fixture/data/runtimes'},downloads:[]};const status={enabled:true,requestSuccess:true};const read=vi.fn(async()=>status),change=vi.fn(async()=>status),settle=vi.fn(async(value:unknown)=>value),wallet=vi.fn(async()=>{});- const context:any={path,ipcMain:{handle:(name:string,fn:Function)=>handlers.set(name,fn)},authState,backend,store,+ const context:any={componentUpdateAdmission:{assertAllowed:vi.fn()},path,ipcMain:{handle:(name:string,fn:Function)=>handlers.set(name,fn)},authState,backend,store,authJob:undefined,shutdownStarted:false,keyringSupport:{busy:false},downloadCancellations:new Set(),preparingInstall:false,preparingContent:false,preparingLaunch:false,finalizingGame:false,launcherUpdater:{state:{updating:false}},checkingGameUpdates:false,gameRemovalInProgress:false,assertActivityCompatible:vi.fn(),operations:new Map(),gameOperation:undefined,installQueue:{size:0},runtime:{current:{updating:false}},accountRefresh:{invalidate:vi.fn()},prepareSystemWallet:wallet,offlineLaunchSupported:async()=>true,offlineLicenseCache:async()=>'/fixture/cache',backendRunner:(binary:string)=>binary,readOfflinePermissions:read,changeOfflinePermissions:change,settleOfflinePermissions:settle};@@ -63,7 +63,7 @@ it('cache recovery keeps its original data root across asynchronous filesystem cconst helper=parsed.statements.filter(node=>ts.isFunctionDeclaration(node)&&node.name&&['offlineDataRoot','offlineLicenseCache'].includes(node.name.text)).map(node=>node.getText(parsed)).join('\n');const check=deferred<boolean>(),store={settings:{runtimeRoot:'/original/runtimes'}};const revoke=vi.fn(async()=>{}),ready=vi.fn(async()=>{});- const context:any={path,store,backend:{current:{capabilities:{licenseCache:true}}},offlineAccessRevoked:()=>check.promise,revokeOfflineAccess:revoke,assertOfflineAccessReady:ready,licenseCacheDirectory:(root:string)=>path.join(root,'license-cache')};+ const context:any={componentUpdateAdmission:{assertAllowed:vi.fn()},path,store,backend:{current:{capabilities:{licenseCache:true}}},offlineAccessRevoked:()=>check.promise,revokeOfflineAccess:revoke,assertOfflineAccessReady:ready,licenseCacheDirectory:(root:string)=>path.join(root,'license-cache')};runInNewContext(ts.transpileModule(helper+'\nglobalThis.recover=offlineLicenseCache;',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText,context);const pending=context.recover();store.settings.runtimeRoot='/different/runtimes';check.resolve(true);await expect(pending).resolves.toBe('/original/license-cache');diff --git a/src/main/runtime-reservation.test.ts b/src/main/runtime-reservation.test.tsindex 299af35..0b69aca 100644--- a/src/main/runtime-reservation.test.ts+++ b/src/main/runtime-reservation.test.ts@@ -69,7 +69,7 @@ describe('runtime mutation reservations',()=>{const source=readFileSync(new URL('./index.ts',import.meta.url),'utf8');function context(manager:RuntimeManager,root:string){const store:any={settings:{market:'US',winePath:'custom-wine',externalXodusRoot:'',runtimeRoot:root,multiAccountEnabled:false},downloads:[],setSettings:vi.fn(async(patch:any)=>{store.settings={...store.settings,...patch};return store.settings;})};- const handlers=new Map<string,Function>();const ctx:any={runtime:manager,store,ipcMain:{handle:(name:string,fn:Function)=>handlers.set(name,fn)},path,offlinePermissionChanging:false,keyringSupport:{busy:false},authState:{running:false},authJob:undefined,shutdownStarted:false,downloadCancellations:new Set(),preparingInstall:false,preparingContent:false,preparingLaunch:false,finalizingGame:false,launcherUpdater:{state:{updating:false}},checkingGameUpdates:false,gameRemovalInProgress:false,operations:new Map(),gameOperation:undefined,installQueue:{size:0},assertActivityCompatible:vi.fn(),backend:{current:{updating:false,capabilities:{}},setExternalRoot:vi.fn(),refresh:vi.fn(async()=>{})},emitSnapshot:vi.fn(),refreshAccount:vi.fn(async()=>{}),savedAccountsEnabled:false,requestSavedAccount:vi.fn(async()=>{}),xboxOverlayPatch:()=>({}),interfaceLanguagePreference:(s:string)=>s==='invalid'?'system':s,downloadLimitKiB:()=>{},downloadLimitArgs:()=>{},shaderCacheLimits:()=>{},isBandwidthOnlyPatch:()=>false,isShaderCacheOnlyPatch:()=>false,launcherTray:{configure:()=>true},mainWindow:undefined,downloadLimitControls:{apply:vi.fn(async()=>{})}};+ const handlers=new Map<string,Function>();const ctx:any={componentUpdateAdmission:{assertAllowed:vi.fn()},runtime:manager,store,ipcMain:{handle:(name:string,fn:Function)=>handlers.set(name,fn)},path,offlinePermissionChanging:false,keyringSupport:{busy:false},authState:{running:false},authJob:undefined,shutdownStarted:false,downloadCancellations:new Set(),preparingInstall:false,preparingContent:false,preparingLaunch:false,finalizingGame:false,launcherUpdater:{state:{updating:false}},checkingGameUpdates:false,gameRemovalInProgress:false,operations:new Map(),gameOperation:undefined,installQueue:{size:0},assertActivityCompatible:vi.fn(),backend:{current:{updating:false,capabilities:{}},setExternalRoot:vi.fn(),refresh:vi.fn(async()=>{})},emitSnapshot:vi.fn(),refreshAccount:vi.fn(async()=>{}),savedAccountsEnabled:false,requestSavedAccount:vi.fn(async()=>{}),xboxOverlayPatch:()=>({}),interfaceLanguagePreference:(s:string)=>s==='invalid'?'system':s,downloadLimitKiB:()=>{},downloadLimitArgs:()=>{},shaderCacheLimits:()=>{},isBandwidthOnlyPatch:()=>false,isShaderCacheOnlyPatch:()=>false,launcherTray:{configure:()=>true},mainWindow:undefined,downloadLimitControls:{apply:vi.fn(async()=>{})}};const begin=source.indexOf('function ensureIdle('),end=source.indexOf('\nasync function syncManagedWinePath()',begin),settings=source.lastIndexOf(" ipcMain.handle('update-settings'");const code=source.slice(begin,end)+'\n'+source.slice(settings,source.indexOf(" ipcMain.handle('choose-directory'",settings));runInContext(ts.transpileModule(code,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText,createContext(ctx));return{ctx,store,handlers,handler:handlers.get('update-settings')!};}@@ -95,7 +95,7 @@ it('own runtime exception never bypasses other activity guards or accepts foreig});it.each(['preparingLaunch','finalizingGame'])('actual runtime admission rejects %s before discovery',async flag=>{const f=await fixture(),ast=ts.createSourceFile('index.ts',source,ts.ScriptTarget.ES2022,true);let expression='';function visit(node:ts.Node){if(ts.isNewExpression(node)&&node.expression.getText(ast)==='RuntimeManager')expression=node.arguments![2].getText(ast);ts.forEachChild(node,visit);}visit(ast);expect(expression).toBeTruthy();- const ctx:any={preparingLaunch:false,finalizingGame:false,downloadCancellations:new Set(),operations:new Map(),installQueue:{size:0},preparingInstall:false,backend:{current:{updating:false}}};ctx[flag]=true;const active=runInContext('('+expression+')',createContext(ctx));const manager=new RuntimeManager(f.runtimeRoot,()=>{},active,f.fetcher,'x64');await expect(manager.installNexus(()=>{})).rejects.toThrow('active');expect(f.fetcher).not.toHaveBeenCalled();await f.preserved();+ const ctx:any={offlinePermissionChanging:false,keyringSupport:{busy:false},authState:{running:false},authJob:undefined,shutdownStarted:false,preparingContent:false,checkingGameUpdates:false,gameRemovalInProgress:false,gameOperation:undefined,store:{downloads:[]},launcherUpdater:{state:{updating:false}},preparingLaunch:false,finalizingGame:false,downloadCancellations:new Set(),operations:new Map(),installQueue:{size:0},preparingInstall:false,backend:{current:{updating:false}}};ctx[flag]=true;const activity=ast.statements.find(node=>ts.isFunctionDeclaration(node)&&node.name?.text==='componentActivityRunning')!;const active=runInContext(ts.transpileModule(activity.getText(ast)+'\n('+expression+')',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText,createContext(ctx));const manager=new RuntimeManager(f.runtimeRoot,()=>{},active,f.fetcher,'x64');await expect(manager.installNexus(()=>{})).rejects.toThrow('active');expect(f.fetcher).not.toHaveBeenCalled();await f.preserved();});it('actual runtime-refresh holds selection/save through account refresh and publishes idle status',async()=>{diff --git a/src/main/runtime.ts b/src/main/runtime.tsindex 1cbe30a..0599ebb 100644--- a/src/main/runtime.ts+++ b/src/main/runtime.ts@@ -67,8 +67,19 @@ type AfterInstall = ((winePath: string) => Promise<void>) | {persistSelection(winePath:string):Promise<void>;refreshAccount?():Promise<void>;};-export interface LegacyRuntimeUpdateTarget {readonly kind:'legacy-standard';readonly root:string;readonly installed:Readonly<LegacyManagedState>;readonly version:string;readonly candidateSha256:string;readonly channel:'stable'|'prerelease';}-export interface LegacyRuntimeUpdateCallbacks {configuredWine():string;persistSelection(wine:string):Promise<void>;refreshAccount?():Promise<void>;}+export interface LegacyRuntimeUpdateTarget {+ readonly kind: 'legacy-standard';+ readonly root: string;+ readonly installed: Readonly<LegacyManagedState>;+ readonly version: string;+ readonly candidateSha256: string;+ readonly channel: 'stable' | 'prerelease';+}+export interface LegacyRuntimeUpdateCallbacks {+ configuredWine(): string;+ persistSelection(wine: string): Promise<void>;+ refreshAccount?(): Promise<void>;+}interface Activation {winePath:string;pointer:PointerCommitResult;}export class RuntimeManager {@@ -104,7 +115,23 @@ export class RuntimeManager {checkManagedRuntime(family:unknown,options:unknown,onStatus:()=>void=()=>{}) {return this.managedCheck(family,options,onStatus);}private async managedCheck(family:unknown,options:unknown,onStatus:()=>void) {try{onStatus();return await this.managed.check(family,options);}finally{onStatus();}}async installManagedRuntime(family:unknown,expected:unknown,options:unknown,onStatus:()=>void=()=>{}) {const result=await this.managed.install(family,expected,options);try{await this.refreshFamilies();onStatus();}catch(error){return {...result,success:false,error:[result.error,'Updating runtime status failed: '+(error as Error).message].filter(Boolean).join(' ')};}return result;}- async checkManagedRuntimeUpdate(family:unknown,channel:unknown,onStatus:()=>void=()=>{}) {try{return await this.managed.checkInstalledUpdate(family,channel);}finally{onStatus();}}+ async installPreparedManagedRuntime(family: unknown, target: Readonly<VerifiedManagedFamilyRelease>, options: unknown, onStatus: () => void = () => { }) {+ const result = await this.managed.install(family, target.candidateSha256, options, target);+ try {+ await this.refreshFamilies();+ onStatus();+ }+ catch (error) {+ return { ...result, success: false, error: [result.error, 'Updating runtime status failed: ' + (error instanceof Error ? error.message : String(error))].filter(Boolean).join(' ') };+ }+ return result;+ }+ async checkManagedRuntimeUpdate(family: unknown, channel: unknown, onStatus: () => void = () => { }) { try {+ return await this.managed.checkInstalledUpdate(family, channel);+ }+ finally {+ onStatus();+ } }managedTarget(family:unknown){return this.managed.target(family);}get busy(): boolean { return this.mutation !== undefined; }setRoot(root: string): void {@@ -344,62 +371,150 @@ export class RuntimeManager {}}- private async activateVerifiedPayload(candidateRoot:string,candidateWine:string,commit:string,onStatus:()=>void,releaseName:string,root:string,precommit?:()=>Promise<void>,releaseIdentity?:{sourceRepository:string;candidateSha256:string;prerelease:boolean}):Promise<Activation>{+ private async activateVerifiedPayload(candidateRoot: string, candidateWine: string, commit: string, onStatus: () => void, releaseName: string, root: string, precommit?: () => Promise<void>, releaseIdentity?: {+ sourceRepository: string;+ candidateSha256: string;+ prerelease: boolean;+ }): Promise<Activation> {await this.validateWine(candidateWine, 'The downloaded Wine failed --version validation.');- if (this.isOperationActive()) throw new Error('Another operation started during installation; the runtime was not activated.');-+ if (this.isOperationActive())+ throw new Error('Another operation started during installation; the runtime was not activated.');const releases = path.join(root, 'releases');const releaseRoot = path.join(releases, releaseName);await fs.mkdir(releases, { recursive: true });let existing = true;- try { await fs.lstat(releaseRoot); }+ try {+ await fs.lstat(releaseRoot);+ }catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;- existing = false;+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT')+ throw error;+ existing = false;}if (existing) {- if (!await runtimePayloadMatches(candidateRoot, releaseRoot)) {- throw new Error('The existing runtime folder does not match the verified download. It was left unchanged.');- }- } else {- await fs.rename(candidateRoot, releaseRoot);+ if (!await runtimePayloadMatches(candidateRoot, releaseRoot)) {+ throw new Error('The existing runtime folder does not match the verified download. It was left unchanged.');+ }+ }+ else {+ await fs.rename(candidateRoot, releaseRoot);}const winePath = path.join(releaseRoot, path.relative(candidateRoot, candidateWine));- if (!await this.validateWine(winePath)) throw new Error('The activated runtime is not executable.');+ if (!await this.validateWine(winePath))+ throw new Error('The activated runtime is not executable.');await precommit?.();- const pointer: RuntimePointer = { name: releaseName, winePath, commit, installedAt: new Date().toISOString(),...releaseIdentity };+ const pointer: RuntimePointer = { name: releaseName, winePath, commit, installedAt: new Date().toISOString(), ...releaseIdentity };await fs.mkdir(root, { recursive: true });- const pointerResult=await commitRuntimePointer(root,pointer);+ const pointerResult = await commitRuntimePointer(root, pointer);Object.assign(this.status, { installed: true, name: releaseName, winePath, commit, phase: 'Runtime activated; finishing setup.', error: undefined });- try{this.emitLog('runtime', `Active Wine: ${winePath}`);}catch(error){pointerResult.errors.push(new Error('Runtime activation log failed: '+(error as Error).message,{cause:error}));}- return {winePath,pointer:pointerResult};+ try {+ this.emitLog('runtime', `Active Wine: ${winePath}`);+ }+ catch (error) {+ pointerResult.errors.push(new Error('Runtime activation log failed: ' + (error as Error).message, { cause: error }));+ }+ return { winePath, pointer: pointerResult };}- async prepareLegacyManagedUpdate(configuredWine:string):Promise<{target?:Readonly<LegacyRuntimeUpdateTarget>;skipReason?:string}>{- const root=this.status.runtimeRoot,installed=await legacyManagedState(root,configuredWine);- if(!installed)return{skipReason:'The default runtime is custom, unavailable or not a supported managed Standard installation.'};- const channel=installed.channel??await this.managed.legacyInstalledChannel(installed.releaseTag,installed.name,installed.sourceCommit);- if(!channel)return{skipReason:'The installed Standard runtime release channel could not be verified.'};- const checked=await this.managed.check('nexus',{allowCachyos:false,allowPrerelease:channel==='prerelease'},channel);const release=this.managed.target('nexus');- if(!release||checked.error)return{skipReason:checked.error??'No trusted Standard runtime update is available.'};- if(root!==this.status.runtimeRoot||(await legacyManagedState(root,configuredWine))?.identity!==installed.identity)return{skipReason:'The installed Standard runtime changed while checking.'};- if(installed.candidateSha256===release.candidateSha256)return{skipReason:'The managed Standard runtime is already current.'};- const target=Object.freeze({kind:'legacy-standard' as const,root,installed,version:release.tag,candidateSha256:release.candidateSha256,channel});this.legacyTargets.set(target,release);return{target};+ async prepareLegacyManagedUpdate(configuredWine: string): Promise<{+ target?: Readonly<LegacyRuntimeUpdateTarget>;+ skipReason?: string;+ state: 'ready' | 'unchanged' | 'skipped' | 'deferred';+ currentVersion?: string;+ }> {+ const root = this.status.runtimeRoot, installed = await legacyManagedState(root, configuredWine);+ if (!installed)+ return { state: 'skipped', skipReason: 'The default runtime is custom, unavailable or not a supported managed Standard installation.' };+ const currentVersion = installed.releaseTag;+ const channel = installed.channel ?? await this.managed.legacyInstalledChannel(installed.releaseTag, installed.name, installed.sourceCommit);+ if (!channel)+ return { state: 'skipped', currentVersion, skipReason: 'The installed Standard runtime release channel could not be verified.' };+ const checked = await this.managed.check('nexus', { allowCachyos: false, allowPrerelease: channel === 'prerelease' }, channel);+ const release = this.managed.target('nexus');+ if (!release || checked.error)+ return { state: 'deferred', currentVersion, skipReason: checked.error ?? 'No trusted Standard runtime update is available.' };+ if (checked.available?.candidateSha256 !== release.candidateSha256 || release.prerelease !== (channel === 'prerelease'))+ return { state: 'deferred', currentVersion, skipReason: 'Runtime release selection changed while checking. Check again.' };+ if (root !== this.status.runtimeRoot || (await legacyManagedState(root, configuredWine))?.identity !== installed.identity)+ return { state: 'deferred', currentVersion, skipReason: 'The installed Standard runtime changed while checking.' };+ if (installed.candidateSha256 === release.candidateSha256)+ return { state: 'unchanged', currentVersion, skipReason: 'The managed Standard runtime is already current.' };+ const target = Object.freeze({ kind: 'legacy-standard' as const, root, installed, version: release.tag, candidateSha256: release.candidateSha256, channel });+ this.legacyTargets.set(target, release);+ return { target, state: 'ready', currentVersion };}- async applyLegacyManagedUpdate(value:unknown,callbacks:LegacyRuntimeUpdateCallbacks,onStatus:()=>void=()=>{}):Promise<{success:boolean;committed:boolean;durability:'confirmed'|'unknown'|'not-committed';error?:string}>{- if(!value||typeof value!=='object'||!this.legacyTargets.has(value as LegacyRuntimeUpdateTarget))throw Error('Unknown prepared Standard runtime update');- const target=value as LegacyRuntimeUpdateTarget,release=this.legacyTargets.get(target)!,lease=this.reserveMutation();let staging:string|undefined,activation:Activation|undefined,operationError:unknown;- let outcome:{success:boolean;committed:boolean;durability:'confirmed'|'unknown'|'not-committed';error?:string}={success:false,committed:false,durability:'not-committed'};- try{- const unchanged=async()=>{if(this.status.runtimeRoot!==target.root||lease.root!==target.root||(await legacyManagedState(target.root,callbacks.configuredWine()))?.identity!==target.installed.identity||callbacks.configuredWine()!==target.installed.configuredWine)throw Error('The selected Standard runtime changed; check updates again.');};await unchanged();- staging=path.join(lease.root,'.staging-'+randomUUID());await fs.mkdir(staging,{mode:0o700});const archive=path.join(staging,release.assets.binary.name);- await this.managed.downloadPreparedRelease(release,lease.root,archive,{allowCachyos:false,allowPrerelease:target.channel==='prerelease'});const extracted=path.join(staging,'payload');await fs.mkdir(extracted,{mode:0o700});const name=nexusReleaseName(release.assets.binary.name),payload=await materializeRuntimeArchive(archive,extracted,name);- const file=path.join(payload,'XODUS_NEXUS_PATCH.json'),stat=await fs.lstat(file);if(!stat.isFile()||stat.size>2*1024*1024)throw Error('Missing bounded runtime source metadata');const metadata=JSON.parse(await fs.readFile(file,'utf8'));- if(metadata.schema!==1||!isDeepStrictEqual(metadata.sourceGraph,release.sourceGraph)||metadata.requiresBackendVersion!==release.requiresBackendVersion||metadata.requiresLauncherVersion!==release.requiresLauncherVersion||typeof metadata.sourceLockSha256!=='string'||!/^[a-f0-9]{64}$/.test(metadata.sourceLockSha256))throw Error('Standard runtime payload does not match its verified release identity');- const wine=await runtimeLoader(payload,this.hostArch,false);await unchanged();activation=await this.activateVerifiedPayload(payload,wine,release.tag,onStatus,name,lease.root,unchanged,{sourceRepository:release.repository,candidateSha256:release.candidateSha256,prerelease:target.channel==='prerelease'});- await this.completeActivation(activation,{persistSelection:callbacks.persistSelection,refreshAccount:callbacks.refreshAccount});outcome={success:true,committed:true,durability:activation.pointer.durability};- }catch(error){operationError=error;this.status.error=(error as Error).message;if(!activation)this.status.phase='Active runtime selection was not changed.';outcome={success:false,committed:Boolean(activation),durability:activation?.pointer.durability??'not-committed',error:this.status.error};}- finally{if(staging)await fs.rm(staging,{recursive:true,force:true}).catch(()=>{});lease.release();try{this.notifyCompletion(onStatus,operationError,Boolean(activation));}catch(error){this.status.error=(error as Error).message;outcome={...outcome,success:false,error:this.status.error};}}- return outcome;++ async applyLegacyManagedUpdate(value: unknown, callbacks: LegacyRuntimeUpdateCallbacks, onStatus: () => void = () => { }): Promise<{+ success: boolean;+ committed: boolean;+ durability: 'confirmed' | 'unknown' | 'not-committed';+ error?: string;+ }> {+ if (!value || typeof value !== 'object' || !this.legacyTargets.has(value as LegacyRuntimeUpdateTarget))+ throw Error('Unknown prepared Standard runtime update');+ const target = value as LegacyRuntimeUpdateTarget, release = this.legacyTargets.get(target)!;+ const lease = this.reserveMutation();+ let staging: string | undefined, activation: Activation | undefined, operationError: Error | undefined;+ let outcome: {+ success: boolean;+ committed: boolean;+ durability: 'confirmed' | 'unknown' | 'not-committed';+ error?: string;+ } = { success: false, committed: false, durability: 'not-committed' };+ const fail = (error: unknown) => {+ const next = error instanceof Error ? error : new Error(String(error), { cause: error });+ operationError = operationError ? new AggregateError([operationError, next], operationError.message + ' ' + next.message) : next;+ this.status.error = operationError.message;+ this.status.phase = activation ? 'Runtime activated; finishing setup needs attention.' : 'Active runtime selection was not changed.';+ outcome = { success: false, committed: Boolean(activation), durability: activation?.pointer.durability ?? 'not-committed', error: this.status.error };+ };+ try {+ this.status.phase = 'Checking the selected Standard runtime update.';+ onStatus();+ const unchanged = async () => {+ const configured = callbacks.configuredWine();+ if (this.status.runtimeRoot !== target.root || lease.root !== target.root || configured !== target.installed.configuredWine || (await legacyManagedState(target.root, configured))?.identity !== target.installed.identity)+ throw Error('The selected Standard runtime changed; check updates again.');+ };+ await unchanged();+ staging = path.join(lease.root, '.staging-' + randomUUID());+ await fs.mkdir(staging, { mode: 0o700 });+ const archive = path.join(staging, release.assets.binary.name);+ await this.managed.downloadPreparedRelease(release, lease.root, archive, { allowCachyos: false, allowPrerelease: target.channel === 'prerelease' });+ const extracted = path.join(staging, 'payload');+ await fs.mkdir(extracted, { mode: 0o700 });+ const name = nexusReleaseName(release.assets.binary.name), payload = await materializeRuntimeArchive(archive, extracted, name);+ const file = path.join(payload, 'XODUS_NEXUS_PATCH.json'), stat = await fs.lstat(file);+ if (!stat.isFile() || stat.size > 2 * 1024 * 1024)+ throw Error('Missing bounded runtime source metadata');+ const metadata = JSON.parse(await fs.readFile(file, 'utf8'));+ if (metadata.schema !== 1 || !isDeepStrictEqual(metadata.sourceGraph, release.sourceGraph) || metadata.requiresBackendVersion !== release.requiresBackendVersion || metadata.requiresLauncherVersion !== release.requiresLauncherVersion || typeof metadata.sourceLockSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(metadata.sourceLockSha256))+ throw Error('Standard runtime payload does not match its verified release identity');+ const wine = await runtimeLoader(payload, this.hostArch, false);+ await unchanged();+ activation = await this.activateVerifiedPayload(payload, wine, release.tag, onStatus, name, lease.root, unchanged, { sourceRepository: release.repository, candidateSha256: release.candidateSha256, prerelease: target.channel === 'prerelease' });+ await this.completeActivation(activation, { persistSelection: callbacks.persistSelection, refreshAccount: callbacks.refreshAccount });+ outcome = { success: true, committed: true, durability: activation.pointer.durability };+ }+ catch (error) {+ fail(error);+ }+ finally {+ if (staging)+ try {+ await fs.rm(staging, { recursive: true, force: true });+ }+ catch (error) {+ fail(new Error('Cleaning runtime staging failed.', { cause: error }));+ }+ lease.release();+ try {+ onStatus();+ }+ catch (error) {+ fail(new Error('Updating runtime status failed.', { cause: error }));+ }+ }+ return outcome;}private notifyCompletion(onStatus:()=>void,prior:unknown,activated=false):void {try{onStatus();}catch(error){diff --git a/src/shared/types.ts b/src/shared/types.tsindex 1c4cc6e..16c035f 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -73,6 +73,7 @@ export interface BackendStatus {prerequisites: { git: boolean; cargo: boolean; rustc: boolean; protoc: boolean };blockReason?: string;linuxRunPatch?: string;+ recipeSha256?: string;version?: string;delivery?: 'release' | 'local';releaseAvailable?: boolean;