Open-source Xbox-inspired desktop launcher for Xodus on Linux
TypeScript
Reserve runtime mutations through discovery and settings persistence
domsvobodaa03bbc6b0951
diff --git a/src/main/index.ts b/src/main/index.tsindex 0fa1ff2..be45489 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -36,7 +36,7 @@ import { run, spawnTracked } from './process.js';import { inspectGameDirectory, StateStore } from './store.js';import { inspectStartupLibrary } from './startup-library.js';import { hasIncompleteUpdate, INCOMPLETE_UPDATE_MESSAGE } from './installation-state.js';-import { RuntimeManager } from './runtime.js';+import { RuntimeManager, type RuntimeSettingsReservation } from './runtime.js';import { prepareProtonRunner, syncPrefixUserLocale, syncUnrealCultureGameIni } from './proton.js';import { layoutOfWine } from './proton-layout.js';import { accountCacheKey } from './offline-identity.js';@@ -482,7 +482,8 @@ function requireBackend(command: keyof typeof backend.current.capabilities): strreturn status.binaryPath;}-function ensureIdle(mode?: 'install' | 'launch' | 'remove'): void {+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.');@@ -496,7 +497,7 @@ function ensureIdle(mode?: 'install' | 'launch' | 'remove'): void {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) throw new Error('Xodus Runtime is being installed.');+ if ((runtime.current.updating || runtime.busy) && !ownRuntimeReservation) throw new Error('Xodus Runtime is being installed.');}async function syncManagedWinePath(): Promise<void> {@@ -728,8 +729,8 @@ function requestAuth(command: 'login' | 'logout', player = false): Promise<void>}/** Reserve the auth job before any asynchronous preparation or credential mutation. */-function requestSavedAccount(action: 'use' | 'forget' | 'enable', name: unknown): Promise<void> {- ensureIdle();+function requestSavedAccount(action: 'use' | 'forget' | 'enable', name: unknown, ownRuntimeReservation?: RuntimeSettingsReservation): Promise<void> {+ ensureIdle(undefined, ownRuntimeReservation);const binary = backend.current.binaryPath;if (typeof name !== 'string' || !binary || !backend.current.capabilities.savedAccounts) return Promise.reject(Error('Saved accounts are not available.'));if (action === 'forget' && authState.stored === null) return Promise.reject(Error('Refresh account status before forgetting a saved Store account.'));@@ -1822,29 +1823,38 @@ function registerIpc(): void {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('runtime-refresh', async () => { const value = await runtime.refresh(); await syncManagedWinePath(); await refreshAccount(false); emitSnapshot(); return value; });+ ipcMain.handle('runtime-refresh', async () => {+ ensureIdle();+ return runtime.refreshSelection(emitSnapshot, async () => {+ await syncManagedWinePath();+ await refreshAccount(false);+ });+ });ipcMain.handle('runtime-check-update', async () => { const value = await runtime.check(); emitSnapshot(); return value; });ipcMain.handle('runtime-check-nexus', async () => { const value = await runtime.checkNexus(); emitSnapshot(); return value; });ipcMain.handle('runtime-install', async () => {ensureIdle();- const winePath = await runtime.install(emitSnapshot);- await store.setSettings({ winePath });- await refreshAccount(false);- emitSnapshot();+ await runtime.install(emitSnapshot, async winePath => {+ await store.setSettings({ winePath });+ await refreshAccount(false);+ emitSnapshot();+ });});ipcMain.handle('runtime-install-nexus', async () => {ensureIdle();- const winePath = await runtime.installNexus(emitSnapshot);- await store.setSettings({ winePath });- await refreshAccount(false);- emitSnapshot();+ await runtime.installNexus(emitSnapshot, async winePath => {+ await store.setSettings({ winePath });+ await refreshAccount(false);+ emitSnapshot();+ });});ipcMain.handle('runtime-rollback-preview', async () => {ensureIdle();- const winePath = await runtime.rollbackCloudSavePreview(emitSnapshot);- await store.setSettings({ winePath });- await refreshAccount(false);- emitSnapshot();+ await runtime.rollbackCloudSavePreview(emitSnapshot, async winePath => {+ await store.setSettings({ winePath });+ await refreshAccount(false);+ emitSnapshot();+ });});ipcMain.handle('account-refresh', () => refreshAccount());const socialClient=(event:Electron.IpcMainInvokeEvent)=>{@@ -2231,39 +2241,51 @@ function registerIpc(): void {if (patch.closeToTray !== undefined) {if(typeof patch.closeToTray !== 'boolean')throw Error('Invalid close-to-tray setting.');allowed.closeToTray=patch.closeToTray;}if (typeof patch.firstRunCompleted === 'boolean') allowed.firstRunCompleted = patch.firstRunCompleted;const previous = store.settings;- if (allowed.multiAccountEnabled === true && (previous.multiAccountEnabled !== true || savedAccountsEnabled !== true)) await requestSavedAccount('enable', '');- const settings = await store.setSettings(allowed);- if(patch.closeToTray!==undefined){- if(!launcherTray.configure(settings.closeToTray===true)){- await store.setSettings({closeToTray:previous.closeToTray===true});emitSnapshot();- throw Error('The system tray is unavailable. Use a desktop session with a system tray.');+ const componentKeys = ['market', 'winePath', 'externalXodusRoot', 'runtimeRoot'] as const;+ // Do not reapply unchanged component values after an unrelated async action.+ for (const key of componentKeys) if (allowed[key] === previous[key]) delete allowed[key];+ const componentChange = componentKeys.some(key => allowed[key] !== undefined);+ const reservation = componentChange ? runtime.reserveSettingsChange() : undefined;+ try {+ if (allowed.multiAccountEnabled === true && (previous.multiAccountEnabled !== true || savedAccountsEnabled !== true)) await requestSavedAccount('enable', '', reservation);+ const settings = await store.setSettings(allowed);+ if (reservation) {+ // Settings have committed; keep component roots coherent even if a+ // later independent tray/overlay/bandwidth side effect fails.+ backend.setExternalRoot(settings.externalXodusRoot);+ reservation.setRoot(settings.runtimeRoot);}- if(!settings.closeToTray&&mainWindow&&!mainWindow.isVisible())await showLauncher();- if(Object.keys(patch).every(key=>key==='closeToTray')){emitSnapshot();return settings;}- }- if(Object.keys(xboxOverlayPatch(patch)).length){- await overlayShortcut?.configure(settings);gameGuide?.publish('overlay',xboxOverlaySettings(settings));- if(!xboxOverlaySettings(settings).overlayEnabled)gameGuide?.reset();- if(Object.keys(patch).every(key=>['overlayEnabled','overlayShortcut','overlaySide'].includes(key))){emitSnapshot();return settings;}- }- if (patch.downloadLimitMiB !== undefined) {- try { await downloadLimitControls.apply(settings.downloadLimitMiB ?? 0); }- catch { emitSnapshot(); throw Error('The speed limit was saved, but could not be sent to the active download. Retry the installation to apply it.'); }+ if(patch.closeToTray!==undefined){+ if(!launcherTray.configure(settings.closeToTray===true)){+ await store.setSettings({closeToTray:previous.closeToTray===true});emitSnapshot();+ throw Error('The system tray is unavailable. Use a desktop session with a system tray.');+ }+ if(!settings.closeToTray&&mainWindow&&!mainWindow.isVisible())await showLauncher();+ if(Object.keys(patch).every(key=>key==='closeToTray')){emitSnapshot();return settings;}+ }+ if(Object.keys(xboxOverlayPatch(patch)).length){+ await overlayShortcut?.configure(settings);gameGuide?.publish('overlay',xboxOverlaySettings(settings));+ if(!xboxOverlaySettings(settings).overlayEnabled)gameGuide?.reset();+ if(Object.keys(patch).every(key=>['overlayEnabled','overlayShortcut','overlaySide'].includes(key))){emitSnapshot();return settings;}+ }+ if (patch.downloadLimitMiB !== undefined) {+ try { await downloadLimitControls.apply(settings.downloadLimitMiB ?? 0); }+ catch { emitSnapshot(); throw Error('The speed limit was saved, but could not be sent to the active download. Retry the installation to apply it.'); }+ }+ // A bandwidth-only change must not restart authentication or refresh devices.+ if (isBandwidthOnlyPatch(patch)) { emitSnapshot(); return settings; }+ if (isShaderCacheOnlyPatch(patch)) { emitSnapshot(); return settings; }+ // Cosmetic/storage preferences do not change the selected components or+ // account scope, including a full unchanged Settings form saved by the UI.+ if (!componentChange) { emitSnapshot(); return settings; }+ await backend.refresh();+ await refreshAccount(false);+ await runtime.refresh();+ emitSnapshot();+ return settings;+ } finally {+ if (reservation) { reservation.release(); emitSnapshot(); }}- // A bandwidth-only change must not restart authentication or refresh devices.- if (isBandwidthOnlyPatch(patch)) { emitSnapshot(); return settings; }- if (isShaderCacheOnlyPatch(patch)) { emitSnapshot(); return settings; }- // Cosmetic/storage preferences do not change the selected components or- // account scope, including a full unchanged Settings form saved by the UI.- if ((['market', 'winePath', 'externalXodusRoot', 'runtimeRoot'] as const)- .every(key => settings[key] === previous[key])) { emitSnapshot(); return settings; }- backend.setExternalRoot(settings.externalXodusRoot);- runtime.setRoot(settings.runtimeRoot);- await backend.refresh();- await refreshAccount(false);- await runtime.refresh();- emitSnapshot();- return settings;});ipcMain.handle('choose-directory', async (_event, defaultPath?: string) => {const result = await dialog.showOpenDialog(mainWindow!, { properties: ['openDirectory', 'createDirectory'], defaultPath });@@ -2568,8 +2590,8 @@ app.whenReady().then(async () => {}}await store.patchGames(inspectedGames);- runtime = new RuntimeManager(store.settings.runtimeRoot, emitLog, () => downloadCancellations.size > 0 || operations.size > 0 || installQueue.size > 0 || preparingInstall || backend?.current.updating === true);- backend = new BackendManager(app.getPath('userData'), store.settings.externalXodusRoot, emitLog, () => keyringSupport.busy || downloadCancellations.size > 0 || operations.size > 0 || installQueue.size > 0 || preparingInstall || runtime?.current.updating === true);+ runtime = new RuntimeManager(store.settings.runtimeRoot, emitLog, () => preparingLaunch || finalizingGame || downloadCancellations.size > 0 || operations.size > 0 || installQueue.size > 0 || preparingInstall || backend?.current.updating === true);+ 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);await backend.refresh();await runtime.refresh();if (!demoMode) {diff --git a/src/main/runtime-reservation.test.ts b/src/main/runtime-reservation.test.tsnew file mode 100644index 0000000..299af35--- /dev/null+++ b/src/main/runtime-reservation.test.ts@@ -0,0 +1,119 @@+import {afterEach,describe,it,expect,vi} from 'vitest';+import {promises as fs,readFileSync} from 'node:fs';+import path from 'node:path';import os from 'node:os';import {createHash} from 'node:crypto';+import {createContext,runInContext} from 'node:vm';import ts from 'typescript';+import {RuntimeManager,type RuntimeSettingsReservation} from './runtime.js';+import * as processModule from './process.js';+import {selectedWinePath} from './xodus-service.js';+function deferred<T=void>(){let resolve!:(value:T)=>void;const promise=new Promise<T>(yes=>{resolve=yes;});return{promise,resolve};}+const roots:string[]=[],releases:(()=>void)[]=[],jobs:Promise<unknown>[]=[];const realRun=processModule.run;+afterEach(async()=>{for(const release of releases.splice(0))release();await Promise.allSettled(jobs.splice(0));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};+}+describe('runtime mutation reservations',()=>{+ it.each(['install','installNexus','rollbackCloudSavePreview'] as const)('reserves %s before discovery and releases rejection without changing old data',async method=>{+ const f=await fixture(),gate=deferred();releases.push(()=>gate.resolve());+ if(method==='install')vi.spyOn(f.manager,'check').mockImplementation(async()=>{await gate.promise;throw Error('held discovery failed');});+ else if(method==='installNexus')vi.spyOn(f.manager,'checkNexus').mockImplementation(async()=>{await gate.promise;throw Error('held discovery failed');});+ else vi.spyOn(f.manager as any,'readPointer').mockImplementation(async()=>{await gate.promise;return null;});+ const job=f.manager[method](()=>{});jobs.push(job);expect(f.manager.busy).toBe(true);expect(f.manager.current.updating).toBe(true);+ await expect(f.manager.installNexus(()=>{})).rejects.toThrow('active');expect(()=>f.manager.setRoot(path.join(f.root,'other'))).toThrow('active');expect(()=>f.manager.reserveSettingsChange()).toThrow('active');+ expect(await fs.readFile(path.join(f.runtimeRoot,'current.json'),'utf8')).toBe(f.oldPointer);await f.preserved();await f.noStaging();gate.resolve();await expect(job).rejects.toThrow();expect(f.manager.busy).toBe(false);expect(f.manager.current.updating).toBe(false);await f.preserved();+ });+ it.each(['install','installNexus','rollbackCloudSavePreview'] as const)('holds %s through post-activation persistence and retains old prefix/runtime',async method=>{+ const f=await fixture(),gate=deferred(),entered=deferred();releases.push(()=>gate.resolve());+ if(method==='install')(f.manager as any).latestArtifact={runId:123,commit:'a'.repeat(40),name:f.archive,checksumName:f.checksum};+ if(method==='rollbackCloudSavePreview'){+ const name='proton-xodus-base',wine=path.join(f.runtimeRoot,'releases',name,'files/bin/wine');await fs.mkdir(path.dirname(wine),{recursive:true});await fs.writeFile(wine,'inert base',{mode:0o755});await fs.writeFile(path.join(f.runtimeRoot,'current.json'),JSON.stringify({name:name+'-xgamesave-pr28-3fd4ae1091',winePath:f.oldWine,commit:'preview',installedAt:'before'}));+ }+ const job=f.manager[method](()=>{},async()=>{entered.resolve();await gate.promise;});jobs.push(job);await entered.promise;expect(f.manager.busy).toBe(true);expect(f.manager.current.installed).toBe(true);+ expect(()=>context(f.manager,f.runtimeRoot).ctx.ensureIdle('launch')).toThrow('Runtime');+ await expect(f.manager.installNexus(()=>{})).rejects.toThrow('active');expect(()=>f.manager.reserveSettingsChange()).toThrow('active');expect(()=>f.manager.setRoot(path.join(f.root,'other'))).toThrow('active');await f.preserved();gate.resolve();await job;expect(f.manager.busy).toBe(false);await f.preserved();await f.noStaging();+ });+ it('releases after callback failure without claiming pointer rollback',async()=>{+ const f=await fixture();await expect(f.manager.installNexus(()=>{},async()=>{throw Error('settings callback failed');})).rejects.toThrow('settings callback failed');expect(f.manager.busy).toBe(false);expect(f.manager.current.installed).toBe(true);expect(f.manager.current.name).toBe('nexus-runtime-fixture');expect(JSON.parse(await fs.readFile(path.join(f.runtimeRoot,'current.json'),'utf8')).name).toBe('nexus-runtime-fixture');await f.preserved();await f.noStaging();+ });+ it('releases when status notification throws before staging',async()=>{+ const f=await fixture();await expect(f.manager.installNexus(()=>{throw Error('status fixture failed');})).rejects.toThrow('status fixture failed');expect(f.manager.busy).toBe(false);expect(f.manager.current.updating).toBe(false);expect(await fs.readFile(path.join(f.runtimeRoot,'current.json'),'utf8')).toBe(f.oldPointer);await f.preserved();await f.noStaging();+ });+ it('validates exact live settings ownership and stale release cannot clear another mutation',async()=>{+ const f=await fixture(),other=new RuntimeManager(path.join(f.root,'other'),()=>{},()=>false);const token=f.manager.reserveSettingsChange();expect(f.manager.current.updating).toBe(true);+ expect(()=>other.assertSettingsReservation(token)).toThrow('active');expect(()=>f.manager.assertSettingsReservation({setRoot(){},release(){}})).toThrow('active');token.setRoot(f.runtimeRoot);token.release();expect(()=>token.setRoot(f.runtimeRoot)).toThrow('active');+ const next=f.manager.reserveSettingsChange();token.release();expect(f.manager.busy).toBe(true);f.manager.assertSettingsReservation(next);next.release();expect(f.manager.busy).toBe(false);+ });+ it('holds refreshSelection through a settings save and clears busy on rejection',async()=>{+ const f=await fixture(),gate=deferred(),entered=deferred();releases.push(()=>gate.resolve());const job=f.manager.refreshSelection(()=>{},async()=>{entered.resolve();await gate.promise;throw Error('held selection save failed');});jobs.push(job);await entered.promise;+ await expect(f.manager.installNexus(()=>{})).rejects.toThrow('active');expect(()=>f.manager.setRoot(path.join(f.root,'other'))).toThrow('active');gate.resolve();await expect(job).rejects.toThrow('held selection save failed');expect(f.manager.busy).toBe(false);expect(f.manager.current.updating).toBe(false);await f.preserved();+ });+});++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 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')!};+}+it('actual Settings reserves a held save, prevents install, then binds the committed root',async()=>{+ const f=await fixture(),{ctx,store,handler}=context(f.manager,f.runtimeRoot),gate=deferred(),entered=deferred(),newRoot=path.join(f.root,'new-runtime');releases.push(()=>gate.resolve());+ store.setSettings.mockImplementation(async(patch:any)=>{store.settings={...store.settings,...patch};entered.resolve();await gate.promise;return store.settings;});vi.spyOn(f.manager,'refresh').mockImplementation(async()=>f.manager.current);+ ctx.requestSavedAccount=vi.fn(async(_action:string,_name:string,token:RuntimeSettingsReservation)=>{expect(token).toBeDefined();ctx.ensureIdle(undefined,token);});+ const job=handler({}, {runtimeRoot:newRoot,multiAccountEnabled:true});jobs.push(job);await entered.promise;expect(f.manager.busy).toBe(true);await expect(f.manager.installNexus(()=>{})).rejects.toThrow('active');gate.resolve();await job;expect(f.manager.current.runtimeRoot).toBe(newRoot);expect(store.settings.runtimeRoot).toBe(newRoot);expect(f.manager.busy).toBe(false);await f.preserved();expect(ctx.refreshAccount).toHaveBeenCalled();+});+it('blocked or invalid actual Settings changes leave settings and old paths untouched',async()=>{+ const f=await fixture(),{store,handler}=context(f.manager,f.runtimeRoot),old={...store.settings},token=f.manager.reserveSettingsChange();await expect(handler({}, {runtimeRoot:path.join(f.root,'blocked')})).rejects.toThrow();expect(store.setSettings).not.toHaveBeenCalled();expect(store.settings).toEqual(old);token.release();+ const reserve=vi.spyOn(f.manager,'reserveSettingsChange');+ await expect(handler({}, {runtimeRoot:path.join(f.root,'invalid'),interfaceLanguage:'invalid'})).rejects.toThrow('Invalid interface language');expect(reserve).not.toHaveBeenCalled();expect(f.manager.busy).toBe(false);expect(store.settings).toEqual(old);await f.preserved();+});+it('committed roots remain coherent when a later tray side effect fails',async()=>{+ const f=await fixture(),{ctx,store,handler}=context(f.manager,f.runtimeRoot),newRoot=path.join(f.root,'committed-runtime');ctx.launcherTray.configure=()=>false;+ await expect(handler({}, {runtimeRoot:newRoot,closeToTray:true})).rejects.toThrow('system tray');expect(store.settings.runtimeRoot).toBe(newRoot);expect(f.manager.current.runtimeRoot).toBe(newRoot);expect(f.manager.busy).toBe(false);await f.preserved();+});+it('own runtime exception never bypasses other activity guards or accepts foreign/expired tokens',async()=>{+ const f=await fixture(),{ctx}=context(f.manager,f.runtimeRoot),token=f.manager.reserveSettingsChange(),other=new RuntimeManager(path.join(f.root,'other'),()=>{},()=>false),foreign=other.reserveSettingsChange();+ expect(()=>ctx.ensureIdle(undefined,token)).not.toThrow();ctx.preparingLaunch=true;expect(()=>ctx.ensureIdle(undefined,token)).toThrow('launch');ctx.preparingLaunch=false;ctx.finalizingGame=true;expect(()=>ctx.ensureIdle(undefined,token)).toThrow('cleanup');ctx.finalizingGame=false;+ expect(()=>ctx.ensureIdle(undefined,foreign)).toThrow('active');token.release();expect(()=>ctx.ensureIdle(undefined,token)).toThrow('active');foreign.release();+});+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();+});++it('actual runtime-refresh holds selection/save through account refresh and publishes idle status',async()=>{+ const f=await fixture(),{ctx,store,handlers,handler}=context(f.manager,f.runtimeRoot),gate=deferred(),entered=deferred();releases.push(()=>gate.resolve());+ const nextWine=path.join(f.runtimeRoot,'releases/next/files/bin/wine');await fs.mkdir(path.dirname(nextWine),{recursive:true});await fs.writeFile(nextWine,'inert next',{mode:0o755});await fs.writeFile(path.join(f.runtimeRoot,'current.json'),JSON.stringify({name:'next',winePath:nextWine,commit:'next',installedAt:'after'}));store.settings.winePath=f.oldWine;+ store.setSettings.mockImplementation(async(patch:any)=>{store.settings={...store.settings,...patch};entered.resolve();await gate.promise;return store.settings;});ctx.selectedWinePath=selectedWinePath;+ const begin=source.indexOf('async function syncManagedWinePath()'),end=source.indexOf('\nconst accountRefresh',begin),ipc=source.indexOf(" ipcMain.handle('runtime-refresh', async");+ runInContext(ts.transpileModule(source.slice(begin,end)+'\n'+source.slice(ipc,source.indexOf(" ipcMain.handle('runtime-check-update'",ipc)),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText,ctx);+ const job=handlers.get('runtime-refresh')!({});jobs.push(job);await entered.promise;expect(f.manager.busy).toBe(true);await expect(f.manager.installNexus(()=>{})).rejects.toThrow('active');await expect(handler({}, {runtimeRoot:path.join(f.root,'blocked')})).rejects.toThrow();expect(store.setSettings).toHaveBeenCalledTimes(1);+ gate.resolve();const status=await job;expect(status.updating).toBe(false);expect(f.manager.busy).toBe(false);expect(store.settings.winePath).toBe(nextWine);expect(store.settings.runtimeRoot).toBe(f.runtimeRoot);expect(ctx.refreshAccount).toHaveBeenCalled();await f.preserved();+});+it('unchanged full-form component values do not overwrite a newer selection after account enable',async()=>{+ const f=await fixture(),{ctx,store,handler}=context(f.manager,f.runtimeRoot),gate=deferred(),entered=deferred();releases.push(()=>gate.resolve());const form={...store.settings,multiAccountEnabled:true};ctx.requestSavedAccount=vi.fn(async()=>{entered.resolve();await gate.promise;});+ const job=handler({},form);jobs.push(job);await entered.promise;expect(f.manager.busy).toBe(false);+ const wine=await f.manager.installNexus(()=>{},async winePath=>{await store.setSettings({winePath});});gate.resolve();await job;expect(store.settings.winePath).toBe(wine);expect(store.settings.multiAccountEnabled).toBe(true);expect(f.manager.busy).toBe(false);await f.preserved();+});+it('captures an artifact before a later release check can replace mutable cached fields',async()=>{+ const f=await fixture(),gate=deferred(),entered=deferred();releases.push(()=>gate.resolve());const original=(f.fetcher as any).getMockImplementation();+ (f.fetcher as any).mockImplementation(async(input:URL|RequestInfo)=>{if(String(input).endsWith('/'+f.archive)){entered.resolve();await gate.promise;}return original(input);});+ const job=f.manager.installNexus(()=>{});jobs.push(job);await entered.promise;Object.assign((f.manager as any).nexusArtifact,{name:'changed.tar.xz',checksumName:'changed.sha512sum',version:'changed'});gate.resolve();await job;expect(f.manager.current.name).toBe('nexus-runtime-fixture');expect(f.manager.current.commit).toBe('runtime-fixture');await f.preserved();+});diff --git a/src/main/runtime.ts b/src/main/runtime.tsindex 51ec8b1..5d4f861 100644--- a/src/main/runtime.ts+++ b/src/main/runtime.ts@@ -55,7 +55,12 @@ export function previewBaseRelease(name: string): string | null {return match?.[1] ?? null;}+export interface RuntimeSettingsReservation { setRoot(root: string): void; release(): void; }+type AfterInstall = (winePath: string) => Promise<void>;+export class RuntimeManager {+ private mutation?: symbol;+ private settingsReservation?: RuntimeSettingsReservation;private status: RuntimeStatus;private emitLog: (scope: string, line: string) => void;private isOperationActive: () => boolean;@@ -80,16 +85,44 @@ export class RuntimeManager {}get current(): RuntimeStatus { return structuredClone(this.status); }- setRoot(root: string): void { this.status.runtimeRoot = root; }+ get busy(): boolean { return this.mutation !== undefined; }+ setRoot(root: string): void {+ if (this.busy) throw new Error('The runtime cannot be changed while a Xodus operation is active.');+ this.status.runtimeRoot = root;+ }+ private reserveMutation() {+ if (this.busy || this.isOperationActive()) throw new Error('The runtime cannot be changed while a Xodus operation is active.');+ const owner = Symbol('runtime mutation'), root = this.status.runtimeRoot;+ this.mutation = owner;+ this.status.updating = true;+ return { owner, root, release: () => {+ if (this.mutation !== owner) return;+ this.settingsReservation = undefined;+ this.mutation = undefined;+ this.status.updating = false;+ } };+ }+ assertSettingsReservation(reservation: RuntimeSettingsReservation): void {+ if (!this.busy || this.settingsReservation !== reservation) throw new Error('The runtime cannot be changed while a Xodus operation is active.');+ }+ reserveSettingsChange(): RuntimeSettingsReservation {+ const lease = this.reserveMutation();+ const reservation: RuntimeSettingsReservation = Object.freeze({+ setRoot: (root: string) => { this.assertSettingsReservation(reservation); this.status.runtimeRoot = root; },+ release: lease.release,+ });+ this.settingsReservation = reservation;+ return reservation;+ }private async commandOk(command: string, args: string[]): Promise<boolean> {try { return (await run(command, args, { maxOutput: 30_000 })).code === 0; } catch { return false; }}- private pointerFile(): string { return path.join(this.status.runtimeRoot, 'current.json'); }+ private pointerFile(root = this.status.runtimeRoot): string { return path.join(root, 'current.json'); }- private async readPointer(): Promise<RuntimePointer | null> {- try { return JSON.parse(await fs.readFile(this.pointerFile(), 'utf8')) as RuntimePointer; } catch { return null; }+ private async readPointer(root = this.status.runtimeRoot): Promise<RuntimePointer | null> {+ try { return JSON.parse(await fs.readFile(this.pointerFile(root), 'utf8')) as RuntimePointer; } catch { return null; }}private async validateWine(winePath: string, failureMessage?: string): Promise<boolean> {@@ -136,6 +169,19 @@ export class RuntimeManager {return this.current;}+ async refreshSelection(onStatus: () => void, afterRefresh: () => Promise<void>): Promise<RuntimeStatus> {+ const lease = this.reserveMutation();+ try {+ onStatus();+ await this.refresh();+ await afterRefresh();+ } finally {+ lease.release();+ onStatus();+ }+ return this.current;+ }+private async discoverArtifact(): Promise<ArtifactInfo> {if (this.hostArch !== 'x64') throw new Error('The upstream runtime snapshot supports x86_64 only. Install the native Nexus runtime instead.');const remote = await run('git', ['ls-remote', REPOSITORY_URL, `refs/heads/${BRANCH}`], { maxOutput: 30_000 });@@ -197,19 +243,20 @@ export class RuntimeManager {onStatus();}- async install(onStatus: () => void): Promise<string> {- if (this.isOperationActive()) throw new Error('The runtime cannot be changed while a Xodus operation is active.');- if (!this.latestArtifact) await this.check();- const artifact = this.latestArtifact;- if (!artifact) throw new Error(this.status.error ?? 'The current snapshot is unavailable.');- if (!this.status.prerequisites.tar || !this.status.prerequisites.sha512sum) throw new Error('tar or sha512sum is missing.');-- this.status.updating = true;- this.status.error = undefined;- onStatus();- const staging = path.join(this.status.runtimeRoot, `.staging-${randomUUID()}`);- const downloads = path.join(staging, 'downloads');+ async install(onStatus: () => void, afterInstall?: AfterInstall): Promise<string> {+ const lease = this.reserveMutation();+ let staging: string | undefined;try {+ onStatus();+ if (!this.latestArtifact) await this.check();+ const artifact = this.latestArtifact && { ...this.latestArtifact };+ if (!artifact) throw new Error(this.status.error ?? 'The current snapshot is unavailable.');+ if (!this.status.prerequisites.tar || !this.status.prerequisites.sha512sum) throw new Error('tar or sha512sum is missing.');++ this.status.error = undefined;+ onStatus();+ staging = path.join(lease.root, `.staging-${randomUUID()}`);+ const downloads = path.join(staging, 'downloads');await fs.mkdir(downloads, { recursive: true });this.setPhase('Downloading the official x86_64 snapshot from GitHub Actions…', onStatus);let result = await run('gh', ['run', 'download', String(artifact.runId), '--repo', REPOSITORY, '--name', artifact.name, '--dir', downloads], {@@ -225,23 +272,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.');- return await this.activateArchive(downloads, artifact.name, artifact.commit, onStatus, canonicalSnapshotName(artifact.commit));+ const wine = await this.activateArchive(downloads, artifact.name, artifact.commit, onStatus, canonicalSnapshotName(artifact.commit), lease.root);+ await afterInstall?.(wine);+ return wine;} catch (error) {this.status.error = (error as Error).message;throw error;} finally {- this.status.updating = false;- await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined);+ if (staging) await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined);+ lease.release();onStatus();}}-// 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): Promise<string> {- const staging = path.join(this.status.runtimeRoot, `.staging-${randomUUID()}`);+ private async activateArchive(downloads: string, archiveName: string, commit: string, onStatus: () => void, releaseName: string, root: string): Promise<string> {+ const staging = path.join(root, `.staging-${randomUUID()}`);const extracted = path.join(staging, 'extracted');const archivePath = path.join(downloads, archiveName);try {@@ -267,7 +315,7 @@ export class RuntimeManager {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.');- const releases = path.join(this.status.runtimeRoot, 'releases');+ const releases = path.join(root, 'releases');const releaseRoot = path.join(releases, releaseName);await fs.mkdir(releases, { recursive: true });try {@@ -278,10 +326,10 @@ export class RuntimeManager {const winePath = path.join(releaseRoot, path.relative(candidateRoot, candidateWine));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(this.status.runtimeRoot, { recursive: true });- const pointerTmp = `${this.pointerFile()}.tmp`;+ 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());+ 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;@@ -359,19 +407,20 @@ export class RuntimeManager {await pipeline(Readable.fromWeb(response.body as import('node:stream/web').ReadableStream), createWriteStream(target));}- async installNexus(onStatus: () => void): Promise<string> {- if (this.isOperationActive()) throw new Error('The runtime cannot be changed while a Xodus operation is active.');- if (!this.nexusArtifact) await this.checkNexus();- const artifact = this.nexusArtifact;- if (!artifact) throw new Error(this.status.nexusError ?? 'No Nexus runtime is available.');- if (!this.status.prerequisites.tar || !this.status.prerequisites.sha512sum) throw new Error('tar or sha512sum is missing.');-- this.status.updating = true;- this.status.error = undefined;- onStatus();- const staging = path.join(this.status.runtimeRoot, `.staging-${randomUUID()}`);- const downloads = path.join(staging, 'downloads');+ async installNexus(onStatus: () => void, afterInstall?: AfterInstall): Promise<string> {+ const lease = this.reserveMutation();+ let staging: string | undefined;try {+ onStatus();+ if (!this.nexusArtifact) await this.checkNexus();+ const artifact = this.nexusArtifact && { ...this.nexusArtifact };+ if (!artifact) throw new Error(this.status.nexusError ?? 'No Nexus runtime is available.');+ if (!this.status.prerequisites.tar || !this.status.prerequisites.sha512sum) throw new Error('tar or sha512sum is missing.');++ this.status.error = undefined;+ onStatus();+ staging = path.join(lease.root, `.staging-${randomUUID()}`);+ const downloads = path.join(staging, 'downloads');await fs.mkdir(downloads, { recursive: true });this.setPhase(`Downloading the Nexus runtime ${artifact.version}…`, onStatus);await this.downloadFile(artifact.url, path.join(downloads, artifact.name));@@ -382,36 +431,38 @@ 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.');- return await this.activateArchive(downloads, artifact.name, artifact.version, onStatus, nexusReleaseName(artifact.name));+ const wine = await this.activateArchive(downloads, artifact.name, artifact.version, onStatus, nexusReleaseName(artifact.name), lease.root);+ await afterInstall?.(wine);+ return wine;} catch (error) {this.status.error = (error as Error).message;throw error;} finally {- this.status.updating = false;- await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined);+ if (staging) await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined);+ lease.release();onStatus();}}-- async rollbackCloudSavePreview(onStatus: () => void): Promise<string> {- if (this.isOperationActive()) throw new Error('The runtime cannot be changed while a Xodus operation is active.');- const current = await this.readPointer();- const baseName = current ? previewBaseRelease(current.name) : null;- if (!current || !baseName) throw new Error('No cloud-save preview is active.');- const winePath = await runtimeLoader(path.join(this.status.runtimeRoot, 'releases', baseName), this.hostArch);- await this.validateWine(winePath, 'The previous runtime is missing or failed validation. The preview remains active.');- this.status.updating = true;- onStatus();+ async rollbackCloudSavePreview(onStatus: () => void, afterInstall?: AfterInstall): Promise<string> {+ const lease = this.reserveMutation();try {+ onStatus();+ const current = await this.readPointer(lease.root);+ const baseName = current ? previewBaseRelease(current.name) : null;+ if (!current || !baseName) throw new Error('No cloud-save preview is active.');+ const winePath = await runtimeLoader(path.join(lease.root, 'releases', baseName), this.hostArch);+ 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()}.tmp-${randomUUID()}`;+ 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());+ 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);return winePath;} finally {- this.status.updating = false;+ lease.release();onStatus();}}