Open-source Xbox-inspired desktop launcher for Xodus on Linux
TypeScript
fix(runtime): report committed activation and follow-up failures accurately
domsvobodae3b56c0e6d72
diff --git a/src/main/index.ts b/src/main/index.tsindex be45489..ced6900 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1834,26 +1834,23 @@ function registerIpc(): void {ipcMain.handle('runtime-check-nexus', async () => { const value = await runtime.checkNexus(); emitSnapshot(); return value; });ipcMain.handle('runtime-install', async () => {ensureIdle();- await runtime.install(emitSnapshot, async winePath => {- await store.setSettings({ winePath });- await refreshAccount(false);- emitSnapshot();+ await runtime.install(emitSnapshot, {+ persistSelection: async winePath => { await store.setSettings({ winePath }); },+ refreshAccount: async () => { await refreshAccount(false); emitSnapshot(); },});});ipcMain.handle('runtime-install-nexus', async () => {ensureIdle();- await runtime.installNexus(emitSnapshot, async winePath => {- await store.setSettings({ winePath });- await refreshAccount(false);- emitSnapshot();+ await runtime.installNexus(emitSnapshot, {+ persistSelection: async winePath => { await store.setSettings({ winePath }); },+ refreshAccount: async () => { await refreshAccount(false); emitSnapshot(); },});});ipcMain.handle('runtime-rollback-preview', async () => {ensureIdle();- await runtime.rollbackCloudSavePreview(emitSnapshot, async winePath => {- await store.setSettings({ winePath });- await refreshAccount(false);- emitSnapshot();+ await runtime.rollbackCloudSavePreview(emitSnapshot, {+ persistSelection: async winePath => { await store.setSettings({ winePath }); },+ refreshAccount: async () => { await refreshAccount(false); emitSnapshot(); },});});ipcMain.handle('account-refresh', () => refreshAccount());diff --git a/src/main/runtime-pointer-activation.test.ts b/src/main/runtime-pointer-activation.test.tsnew file mode 100644index 0000000..d4094bd--- /dev/null+++ b/src/main/runtime-pointer-activation.test.ts@@ -0,0 +1,70 @@+import {afterEach,it,expect,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 {RuntimeManager} from './runtime';+import * as processModule from './process';+import * as pointerModule from './runtime-pointer-commit';+import type {PointerCommitIO} from './runtime-pointer-commit';+const realCommit=pointerModule.commitRuntimePointer,realRun=processModule.run,roots:string[]=[];+afterEach(async()=>{vi.restoreAllMocks();await Promise.all(roots.splice(0).map(root=>fs.rm(root,{recursive:true,force:true})));});+async function fixture(){+ const root=await fs.mkdtemp(path.join(process.env.TMPDIR??os.tmpdir(),'runtime-lease-'));roots.push(root);const runtimeRoot=path.join(root,'runtimes'),oldWine=path.join(runtimeRoot,'releases/previous/files/bin/wine'),save=path.join(root,'compatdata/game/pfx/drive_c/users/synthetic/save.dat'),link=path.join(path.dirname(save),'runtime-link');+ await fs.mkdir(path.dirname(oldWine),{recursive:true});await fs.writeFile(oldWine,'synthetic old loader',{mode:0o755});await fs.mkdir(path.dirname(save),{recursive:true});await fs.writeFile(save,'unchanged synthetic progress');await fs.symlink(oldWine,link);+ const oldPointer=JSON.stringify({name:'previous',winePath:oldWine,commit:'previous',installedAt:'before'});await fs.writeFile(path.join(runtimeRoot,'current.json'),oldPointer);+ const archive='nexus-runtime-fixture-x86_64.tar.xz',checksum=archive.replace('.tar.xz','.sha512sum'),payload=path.join(root,'payload/nexus-runtime-fixture'),wine=path.join(payload,'files/bin/wine');await fs.mkdir(path.dirname(wine),{recursive:true});await fs.writeFile(wine,'inert synthetic loader; never executed',{mode:0o755});+ const archiveFile=path.join(root,archive);expect((await realRun('tar',['-cJf',archiveFile,'-C',path.dirname(payload),path.basename(payload)])).code).toBe(0);const bytes=await fs.readFile(archiveFile),sum=Buffer.from(createHash('sha512').update(bytes).digest('hex')+' '+archive+'\n');+ const fetcher=vi.fn(async(input:URL|RequestInfo)=>{const url=String(input);if(url.includes('/releases?'))return new Response(JSON.stringify([{tag_name:'runtime-fixture',published_at:'2026-11-03T00:00:00Z',assets:[archive,checksum].map(name=>({name,browser_download_url:'https://example.invalid/'+name}))}]));if(url.endsWith('/'+archive))return new Response(bytes);if(url.endsWith('/'+checksum))return new Response(sum);throw Error('Unexpected closed fixture request: '+url);}) as unknown as typeof fetch;+ vi.spyOn(processModule,'run').mockImplementation(async(command,args,options)=>{+ if(path.basename(command)==='wine')return{code:0,output:'wine synthetic'};+ if(command==='gh'){+ if(args[0]==='run'){const name=args[args.indexOf('--name')+1],dir=args[args.indexOf('--dir')+1];await fs.writeFile(path.join(dir,name),name===archive?bytes:sum);}+ return{code:0,output:'synthetic gh'};+ }+ if(command==='tar'||command==='sha512sum')return realRun(command,args,options);+ throw Error('External command forbidden in closed fixture: '+command);+ });+ const manager=new RuntimeManager(runtimeRoot,()=>{},()=>false,fetcher,'x64');await manager.refresh();+ const preserved=async()=>{expect(await fs.readFile(oldWine,'utf8')).toBe('synthetic old loader');expect(await fs.readFile(save,'utf8')).toBe('unchanged synthetic progress');expect(await fs.readlink(link)).toBe(oldWine);};+ const noStaging=async()=>expect((await fs.readdir(runtimeRoot)).filter(x=>x.startsWith('.staging-'))).toEqual([]);+ return{root,runtimeRoot,oldWine,oldPointer,manager,fetcher,preserved,noStaging,archive,checksum};+}++function faultIO(root:string,fault:string):PointerCommitIO {+ return {open:async(file,flags,mode)=>{const handle=await fs.open(file,flags,mode),directory=file===root;return {+ writeFile:async data=>{if(fault==='write')throw Error('injected write failure');await handle.writeFile(data);},+ sync:async()=>{if(fault===(directory?'dir sync':'file sync'))throw Error('injected '+fault+' failure');await handle.sync();},+ close:async()=>{await handle.close();if(fault==='file close'&&!directory)throw Error('injected close failure');}};},+ rename:async(from,to)=>{if(fault==='rename')throw Error('injected rename failure');await fs.rename(from,to);},unlink:fs.unlink};+}+it.each(['write','file sync','file close','rename'])('actual activation preserves prior active pointer/status and all old data on %s failure',async fault=>{+ const f=await fixture();vi.spyOn(pointerModule,'commitRuntimePointer').mockImplementation((root,pointer)=>realCommit(root,pointer,faultIO(root,fault)));+ const callbacks={persistSelection:vi.fn(async()=>{}),refreshAccount:vi.fn(async()=>{})};+ await expect(f.manager.installNexus(()=>{},callbacks)).rejects.toThrow('not activated');+ expect(await fs.readFile(path.join(f.runtimeRoot,'current.json'),'utf8')).toBe(f.oldPointer);expect(f.manager.current.name).toBe('previous');expect(f.manager.current.winePath).toBe(f.oldWine);expect(f.manager.busy).toBe(false);expect(callbacks.persistSelection).not.toHaveBeenCalled();+ expect((await fs.stat(path.join(f.runtimeRoot,'releases/nexus-runtime-fixture'))).isDirectory()).toBe(true);await f.preserved();await f.noStaging();+});+it.each(['dir sync','settings-before','settings-after','account','dir sync+settings'])('actual committed activation reports %s truthfully without reverting pointer or deleting old data',async fault=>{+ const f=await fixture();const sync=fault.startsWith('dir sync');vi.spyOn(pointerModule,'commitRuntimePointer').mockImplementation((root,pointer)=>realCommit(root,pointer,faultIO(root,sync?'dir sync':'')));+ let selected=f.oldWine;const callbacks={persistSelection:vi.fn(async(wine:string)=>{+ expect(f.manager.busy).toBe(true);await expect(f.manager.installNexus(()=>{})).rejects.toThrow('active');+ if(fault==='settings-before')throw Error('settings unavailable');selected=wine;+ if(fault==='settings-after'||fault==='dir sync+settings')throw Error('settings may have committed');+ }),refreshAccount:vi.fn(async()=>{expect(f.manager.busy).toBe(true);if(fault==='account')throw Error('account unavailable');})};+ const job=f.manager.installNexus(()=>{},callbacks);await expect(job).rejects.toThrow('runtime was activated');+ const current=JSON.parse(await fs.readFile(path.join(f.runtimeRoot,'current.json'),'utf8'));expect(current.name).toBe('nexus-runtime-fixture');expect(f.manager.current.name).toBe(current.name);expect(f.manager.current.winePath).toBe(current.winePath);expect(f.manager.current.phase).toContain('needs attention');expect(f.manager.busy).toBe(false);+ expect(callbacks.persistSelection).toHaveBeenCalledOnce();+ if(fault.includes('settings')){expect(callbacks.refreshAccount).not.toHaveBeenCalled();expect(f.manager.current.error).toContain('failed or could not be confirmed');}else expect(callbacks.refreshAccount).toHaveBeenCalledOnce();+ if(sync)expect(f.manager.current.error).toContain('directory sync');+ if(fault==='account')expect(f.manager.current.error).toContain('selection was saved, but refreshing account');+ expect(selected).toBe(fault==='settings-before'?f.oldWine:current.winePath);await f.preserved();await f.noStaging();expect((await fs.stat(path.join(f.runtimeRoot,'releases/previous'))).isDirectory()).toBe(true);+});+it('does not mask a committed durability failure with a later status notification failure',async()=>{+ const f=await fixture();vi.spyOn(pointerModule,'commitRuntimePointer').mockImplementation((root,pointer)=>realCommit(root,pointer,faultIO(root,'dir sync')));+ await expect(f.manager.installNexus(()=>{if(!f.manager.busy)throw Error('status failure');})).rejects.toThrow(/directory sync.*Status notification failed: status failure/);expect(f.manager.busy).toBe(false);await f.preserved();+});++it('reports successful activation and selection truthfully if only the final status notification fails',async()=>{+ const f=await fixture(),callbacks={persistSelection:vi.fn(async()=>{}),refreshAccount:vi.fn(async()=>{})};+ await expect(f.manager.installNexus(()=>{if(!f.manager.busy)throw Error('final notification failed');},callbacks)).rejects.toThrow('runtime was activated, but updating its status failed');+ expect(callbacks.persistSelection).toHaveBeenCalledOnce();expect(callbacks.refreshAccount).toHaveBeenCalledOnce();expect(JSON.parse(await fs.readFile(path.join(f.runtimeRoot,'current.json'),'utf8')).name).toBe('nexus-runtime-fixture');expect(f.manager.current.phase).toContain('needs attention');expect(f.manager.busy).toBe(false);await f.preserved();+});diff --git a/src/main/runtime.ts b/src/main/runtime.tsindex 64ab23f..e6a7cc4 100644--- a/src/main/runtime.ts+++ b/src/main/runtime.ts@@ -1,3 +1,4 @@+import {commitRuntimePointer,type PointerCommitResult} from './runtime-pointer-commit.js';import {installedRuntimeFamilies} from './runtime-families.js';import {runtimeWineFailure} from './runtime-prerequisites.js';import { constants, createWriteStream, promises as fs } from 'node:fs';@@ -57,7 +58,11 @@ export function previewBaseRelease(name: string): string | null {}export interface RuntimeSettingsReservation { setRoot(root: string): void; release(): void; }-type AfterInstall = (winePath: string) => Promise<void>;+type AfterInstall = ((winePath: string) => Promise<void>) | {+ persistSelection(winePath:string):Promise<void>;+ refreshAccount?():Promise<void>;+};+interface Activation {winePath:string;pointer:PointerCommitResult;}export class RuntimeManager {private mutation?: symbol;@@ -172,13 +177,14 @@ export class RuntimeManager {async refreshSelection(onStatus: () => void, afterRefresh: () => Promise<void>): Promise<RuntimeStatus> {const lease = this.reserveMutation();+ let operationError:unknown;try {onStatus();await this.refresh();await afterRefresh();- } finally {+ } catch(error){operationError=error;throw error;} finally {lease.release();- onStatus();+ this.notifyCompletion(onStatus,operationError);}return this.current;}@@ -247,6 +253,7 @@ export class RuntimeManager {async install(onStatus: () => void, afterInstall?: AfterInstall): Promise<string> {const lease = this.reserveMutation();let staging: string | undefined;+ let operationError:unknown;try {onStatus();if (!this.latestArtifact) await this.check();@@ -273,23 +280,24 @@ export class RuntimeManager {result = await run('sha512sum', ['-c', artifact.checksumName], { cwd: downloads, maxOutput: 100_000 });if (result.code !== 0) throw new Error('Snapshot SHA-512 verification failed.');- const wine = await this.activateArchive(downloads, artifact.name, artifact.commit, onStatus, canonicalSnapshotName(artifact.commit), lease.root);- await afterInstall?.(wine);- return wine;+ const activation = await this.activateArchive(downloads, artifact.name, artifact.commit, onStatus, canonicalSnapshotName(artifact.commit), lease.root);+ await this.completeActivation(activation,afterInstall);+ return activation.winePath;} catch (error) {+ operationError=error;this.status.error = (error as Error).message;throw error;} finally {if (staging) await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined);lease.release();- onStatus();+ this.notifyCompletion(onStatus,operationError,true);}}// Shared tail of both install paths: verify the archive structure, extract,// validate Wine and atomically switch the active runtime pointer. The// release directory uses the simple canonical name (releaseName); what the// archive calls its top-level folder is only provenance, kept in current.json.- private async activateArchive(downloads: string, archiveName: string, commit: string, onStatus: () => void, releaseName: string, root: string): Promise<string> {+ private async activateArchive(downloads: string, archiveName: string, commit: string, onStatus: () => void, releaseName: string, root: string): Promise<Activation> {const staging = path.join(root, `.staging-${randomUUID()}`);const extracted = path.join(staging, 'extracted');const archivePath = path.join(downloads, archiveName);@@ -336,17 +344,45 @@ export class RuntimeManager {if (!await this.validateWine(winePath)) throw new Error('The activated runtime is not executable.');const pointer: RuntimePointer = { name: releaseName, winePath, commit, installedAt: new Date().toISOString() };await fs.mkdir(root, { recursive: true });- const pointerTmp = `${this.pointerFile(root)}.tmp`;- await fs.writeFile(pointerTmp, JSON.stringify(pointer, null, 2), { mode: 0o600 });- await fs.rename(pointerTmp, this.pointerFile(root));- Object.assign(this.status, { installed: true, name: releaseName, winePath, commit, phase: 'Runtime is ready.', error: undefined });- this.emitLog('runtime', `Active Wine: ${winePath}`);- return winePath;+ 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};} finally {await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined);}}+ private notifyCompletion(onStatus:()=>void,prior:unknown,activated=false):void {+ try{onStatus();}catch(error){+ if(prior)throw new AggregateError([prior,error],(prior as Error).message+' Status notification failed: '+(error as Error).message);+ if(activated){+ this.status.phase='Runtime activated; finishing setup needs attention.';+ this.status.error='The runtime was activated, but updating its status failed: '+(error as Error).message;+ throw new Error(this.status.error,{cause:error});+ }+ throw error;+ }+ }+ private async completeActivation(activation:Activation,afterInstall?:AfterInstall):Promise<void> {+ const errors=[...activation.pointer.errors];+ if(typeof afterInstall==='function') {+ try{await afterInstall(activation.winePath);}catch(error){errors.push(new Error('Finishing launcher setup failed: '+(error as Error).message,{cause:error}));}+ } else if(afterInstall) {+ let saved=false;+ try{await afterInstall.persistSelection(activation.winePath);saved=true;}+ catch(error){errors.push(new Error('Saving the selected runtime failed or could not be confirmed: '+(error as Error).message,{cause:error}));}+ if(saved&&afterInstall.refreshAccount)try{await afterInstall.refreshAccount();}+ catch(error){errors.push(new Error('The runtime selection was saved, but refreshing account status failed: '+(error as Error).message,{cause:error}));}+ }+ if(errors.length) {+ this.status.phase='Runtime activated; finishing setup needs attention.';+ this.status.error='The runtime was activated. '+errors.map(error=>error.message).join(' ');+ throw new AggregateError(errors,this.status.error);+ }+ this.status.phase='Runtime is ready.';this.status.error=undefined;+ }+// Only published releases are installable here, never unapproved CI artifacts.// The complete fork has its own release repository. Keep the existing release// source as a fallback until a complete new runtime is explicitly published.@@ -419,6 +455,7 @@ export class RuntimeManager {async installNexus(onStatus: () => void, afterInstall?: AfterInstall): Promise<string> {const lease = this.reserveMutation();let staging: string | undefined;+ let operationError:unknown;try {onStatus();if (!this.nexusArtifact) await this.checkNexus();@@ -440,20 +477,22 @@ export class RuntimeManager {const result = await run('sha512sum', ['-c', artifact.checksumName], { cwd: downloads, maxOutput: 100_000 });if (result.code !== 0) throw new Error('Nexus runtime SHA-512 verification failed.');- const wine = await this.activateArchive(downloads, artifact.name, artifact.version, onStatus, nexusReleaseName(artifact.name), lease.root);- await afterInstall?.(wine);- return wine;+ const activation = await this.activateArchive(downloads, artifact.name, artifact.version, onStatus, nexusReleaseName(artifact.name), lease.root);+ await this.completeActivation(activation,afterInstall);+ return activation.winePath;} catch (error) {+ operationError=error;this.status.error = (error as Error).message;throw error;} finally {if (staging) await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined);lease.release();- onStatus();+ this.notifyCompletion(onStatus,operationError,true);}}async rollbackCloudSavePreview(onStatus: () => void, afterInstall?: AfterInstall): Promise<string> {const lease = this.reserveMutation();+ let operationError:unknown;try {onStatus();const current = await this.readPointer(lease.root);@@ -463,16 +502,14 @@ export class RuntimeManager {await this.validateWine(winePath, 'The previous runtime is missing or failed validation. The preview remains active.');onStatus();const pointer: RuntimePointer = { ...current, name: baseName, winePath, installedAt: new Date().toISOString() };- const temporary = `${this.pointerFile(lease.root)}.tmp-${randomUUID()}`;- await fs.writeFile(temporary, JSON.stringify(pointer, null, 2), { mode: 0o600 });- await fs.rename(temporary, this.pointerFile(lease.root));- Object.assign(this.status, { name: baseName, winePath, phase: 'Previous runtime restored.', error: undefined });- this.emitLog('runtime', `Restored Wine: ${winePath}`);- await afterInstall?.(winePath);+ const pointerResult=await commitRuntimePointer(lease.root,pointer);+ Object.assign(this.status, { installed:true,name:baseName,winePath,commit:pointer.commit,phase:'Previous runtime restored; finishing setup.',error:undefined });+ try{this.emitLog('runtime', `Restored Wine: ${winePath}`);}catch(error){pointerResult.errors.push(new Error('Runtime activation log failed: '+(error as Error).message,{cause:error}));}+ await this.completeActivation({winePath,pointer:pointerResult},afterInstall);return winePath;- } finally {+ } catch(error){operationError=error;this.status.error=(error as Error).message;throw error;} finally {lease.release();- onStatus();+ this.notifyCompletion(onStatus,operationError,true);}}}